Changeset 1102


Ignore:
Timestamp:
05/10/18 16:04:51 (6 years ago)
Author:
davidb
Message:

Reworking of the code-base to separate logic from graphics. This version of Expeditee now supports a JFX graphics as an alternative to SWING

Location:
trunk
Files:
209 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/org/apollo/ApolloSystem.java

    r1040 r1102  
    11package org.apollo;
    22
    3 import java.awt.Image;
    4 import java.awt.Toolkit;
    5 import java.awt.event.WindowEvent;
    6 import java.awt.event.WindowListener;
    7 import java.net.URL;
    83import java.util.Collection;
    94import java.util.HashSet;
    105import java.util.Set;
    116
    12 import javax.swing.SwingUtilities;
    137import javax.swing.UIManager;
    148
     
    2923import org.apollo.widgets.FramePlayer;
    3024import org.expeditee.actions.Actions;
     25import org.expeditee.core.BlockingRunnable;
     26import org.expeditee.gio.EcosystemManager;
     27import org.expeditee.gio.EcosystemManager.Ecosystem;
     28import org.expeditee.gio.GraphicsManager;
     29import org.expeditee.gio.InputManager.WindowEventListener;
     30import org.expeditee.gio.InputManager.WindowEventType;
    3131import org.expeditee.gui.Browser;
    3232import org.expeditee.gui.Frame;
    3333import org.expeditee.gui.FrameIO;
    34 import org.expeditee.gui.FrameKeyboardActions;
    35 import org.expeditee.gui.FrameMouseActions;
    3634import org.expeditee.settings.UserSettings;
    37 import org.expeditee.importer.FrameDNDTransferHandler;
    3835import org.expeditee.items.Item;
    3936import org.expeditee.items.Text;
     
    4744public final class ApolloSystem {
    4845       
     46        private static final String APOLLO_ICON = "org/apollo/icons/mainicon.png";
     47       
    4948        // TODO: Create actual frames
    5049        public static final String SYSTEM_FRAMESET_NAME = "apollosystem";
    5150        public static final String HELP_TOP_FRAMENAME = SYSTEM_FRAMESET_NAME + 2;
    5251       
    53 //      TODO: How to get good results: collection (moteef) and querry
     52        // TODO: How to get good results: collection (moteef) and querry
    5453        // TODO: How to omit indexing on tracks
    5554        public static final String HELP_MELODYSEARCH_FRAMENAME = SYSTEM_FRAMESET_NAME + 3;
     
    5857        public static final String SETTINGS_NAME_TIMELINE_LMARGIN = "timelineleftmargin";
    5958       
    60 
    61 
    6259        public static boolean useQualityGraphics = true;
    63        
    64         private ApolloSystem() {
    65         }
    6660
    6761        private static boolean hasInitialized = false;
    6862       
     63        private ApolloSystem()
     64        {
     65        }
     66       
    6967        /**
    7068         * Initializes Apollo mod for expeditee - prepares all subsystems.
    7169         */
    72         public static void initialize() {
    73                
     70        public static void initialize()
     71        {
    7472                if (hasInitialized) return;
    7573
    7674                ApolloSystemLog.println("Initializing...");
    77                
    78                 SwingUtilities.invokeLater(new Runnable() {
    79                         public void run() {
    80                                
    81                                  try {
    82 
    83                                         URL url = ClassLoader.getSystemResource("org/apollo/icons/mainicon.png");
    84                                        
    85                                         if (url != null) {
    86                                                  Image img = Toolkit.getDefaultToolkit().getImage(url);
    87                                                  Browser._theBrowser.setIconImage(img);
    88                                         }
    89                                                
    90        
    91                                          
    92                                  } catch (Exception e) {
    93                                          e.printStackTrace();
    94                                  }
    95                                  
    96                                 // Ensure that resources are released before the application is closed.
    97                                 Browser._theBrowser.addWindowListener(new WindowListener() {
    98                
    99                                         public void windowActivated(WindowEvent e) {
    100                                         }
    101                
    102                                         public void windowClosed(WindowEvent e) {
    103                                         }
    104                
    105                                         public void windowClosing(WindowEvent e) {
    106                                                 ApolloSystem.shutdown();
    107                                         }
    108                
    109                                         public void windowDeactivated(WindowEvent e) {
    110                                         }
    111                
    112                                         public void windowDeiconified(WindowEvent e) {
    113                                         }
    114                
    115                                         public void windowIconified(WindowEvent e) {
    116                                         }
    117                
    118                                         public void windowOpened(WindowEvent e) {
    119                                         }
    120                                
    121                                 });
    122                                
    123                                 Browser._theBrowser.getContentPane().removeKeyListener(FrameKeyboardActions.getInstance());
    124                                 Browser._theBrowser.removeKeyListener(FrameKeyboardActions.getInstance());
    125                                
    126                                 Browser._theBrowser.getContentPane().addKeyListener(new AudioFrameKeyboardActions());
    127                                 Browser._theBrowser.addKeyListener(new AudioFrameKeyboardActions());
    128                                
    129                                 // Filter out some special mouse move cases
    130                                 AudioFrameMouseActions apolloMouseFilter = new AudioFrameMouseActions();
    131                                 Browser._theBrowser.getMouseEventRouter().removeExpediteeMouseMotionListener(
    132                                                 FrameMouseActions.getInstance());
    133                                 Browser._theBrowser.getMouseEventRouter().addExpediteeMouseMotionListener(apolloMouseFilter);
    134                                
    135                                 Browser._theBrowser.getMouseEventRouter().removeExpediteeMouseListener(
    136                                                 FrameMouseActions.getInstance());
    137                                 Browser._theBrowser.getMouseEventRouter().addExpediteeMouseListener(apolloMouseFilter);
     75
     76                // Ensure that resources are released before the application is closed.
     77                EcosystemManager.getInputManager().addWindowEventListener(new WindowEventListener() {
     78                        @Override
     79                        public void onWindowEvent(WindowEventType type)
     80                        {
     81                                if (type != WindowEventType.WINDOW_CLOSED) return;
     82                                ApolloSystem.shutdown();
    13883                        }
    13984                });
     85               
     86                EcosystemManager.getInputManager().registerGestureListener(ApolloGestureActions.getInstance());
     87                EcosystemManager.getInputManager().addInputEventToGestureTranslator(new ApolloKBMGestureTranslator());
    14088               
    14189                // Set title
     
    161109               
    162110                // Setup for importing audio
    163                 FrameDNDTransferHandler.getInstance().addCustomFileImporter(
    164                                 new SampledAudioFileImporter());
     111                EcosystemManager.getDragAndDropManager().addCustomFileImporter(new SampledAudioFileImporter());
    165112
    166113                ApolloSystemLog.println("  Loading actions and agents...");
     
    202149         * When invoked, the apollo setting frame is loaded and parsed... setting apollo-specific settings.
    203150         */
    204         public static void loadSettings() {
    205 
     151        public static void loadSettings()
     152        {
    206153                // Load apollo settings frame from the default profile
    207154                Frame profile = FrameIO.LoadProfile(UserSettings.DEFAULT_PROFILE_NAME);
     
    241188        }
    242189       
    243         private static Mutable.Integer stripNameValueStringInteger(String namevalue) {
     190        private static Mutable.Integer stripNameValueStringInteger(String namevalue)
     191        {
    244192                assert (namevalue != null);
    245193                int valueIndex = namevalue.indexOf(':') + 1;
     
    259207         * Releases all resources currently used by the SampledAudioManager.
    260208         */
    261         public static void shutdown() {
    262                
     209        public static void shutdown()
     210        {
    263211                ApolloSystemLog.println("Saving banks...");
    264212                SoundDesk.getInstance().saveMasterMix();
     
    280228         *              True if has initialized.
    281229         */
    282         public static boolean isInitialized() {
     230        public static boolean isInitialized()
     231        {
    283232                return hasInitialized;
    284233        }
     
    294243         * @param args
    295244         */
    296         public static void main(String[] args) {
    297                
    298                 try {
    299                 UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
    300             }
    301             catch (Exception e) {
    302                e.printStackTrace();
    303                return;
    304             }
     245        public static void main(String[] args)
     246        {
     247                if (Browser.ECOSYSTEM_TYPE == Ecosystem.Swing) {
     248                        try {
     249                        UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
     250                    } catch (Exception e) {
     251                       e.printStackTrace();
     252                       return;
     253                    }
     254                }
     255
     256                // Window icon must be set before initialisation
     257                GraphicsManager.setWindowIcon(APOLLO_ICON);
    305258               
    306259                // Run expeditee
     
    308261               
    309262                // Initialize apollo
    310                 SwingUtilities.invokeLater(new Runnable() {
    311                         public void run() {
     263                EcosystemManager.getMiscManager().runOnGIOThread(new BlockingRunnable() {
     264                        public void execute() {
    312265                                ApolloSystem.initialize();
    313266                        }
  • trunk/src/org/apollo/ApolloSystemApplet.java

    r489 r1102  
    33import java.io.File;
    44
    5 import java.awt.*;
    65import java.awt.event.ActionEvent;
    76import java.awt.event.ActionListener;
  • trunk/src/org/apollo/AudioFrameKeyboardActions.java

    r489 r1102  
    2525import org.expeditee.items.Item;
    2626import org.expeditee.items.Line;
    27 import org.expeditee.items.Permission;
    2827import org.expeditee.items.Text;
    2928import org.expeditee.items.Item.HighlightMode;
  • trunk/src/org/apollo/AudioFrameMouseActions.java

    r366 r1102  
    7373                        FrameMouseActions.MouseY = e.getY();
    7474                       
    75                 } else if (isSnapOn() &&
    76                                 !FreeItems.getInstance().isEmpty()) {
     75                } else if (isSnapOn() && !FreeItems.getInstance().isEmpty()) {
    7776                       
    7877                        // Couse movement of free items: Restraining left-most pixel in items
     
    222221                                       
    223222                                        if (firstInitTime == null) {
    224                                                 firstInitTime = Mutable.createMutableLong(it.value); // Important to crewate new instance
     223                                                firstInitTime = Mutable.createMutableLong(it.value); // Important to create new instance
    225224                                        } else if (it.value < firstInitTime.value) {
    226                                                 firstInitTime = Mutable.createMutableLong(it.value); // Important to crewate new instance
     225                                                firstInitTime = Mutable.createMutableLong(it.value); // Important to create new instance
    227226                                        }
    228227                                }
  • trunk/src/org/apollo/actions/ApolloActions.java

    r363 r1102  
    44import org.apollo.widgets.LinkedTrack;
    55import org.apollo.widgets.SampleRecorder;
    6 import org.expeditee.gui.DisplayIO;
     6import org.expeditee.gio.gesture.StandardGestureActions;
     7import org.expeditee.gui.DisplayController;
    78import org.expeditee.gui.Frame;
    8 import org.expeditee.gui.FrameMouseActions;
    99import org.expeditee.items.Text;
    1010
     
    1717public class ApolloActions {
    1818
    19         private ApolloActions() {} // Util construction
     19        /** Static-only class. */
     20        private ApolloActions()
     21        {
     22        }
    2023       
    21         /**
    22          * Attatches a new recorder to the cursor
    23          */
    24         public static void spawnRecorder() {
    25                
    26                 Frame target = DisplayIO.getCurrentFrame();
     24        /** Attaches a new recorder to the cursor. */
     25        public static void spawnRecorder()
     26        {
     27                Frame target = DisplayController.getCurrentFrame();
    2728                if (target  == null) return;
    2829
     
    3031                Text source = new Text(target.getNextItemID());
    3132                source.setParent(target);
    32                 source.setPosition(FrameMouseActions.MouseX, FrameMouseActions.MouseY);
     33                source.setPosition(DisplayController.getMousePosition());
    3334                SampleRecorder recWidget = new SampleRecorder(source, null);
    3435               
    3536                // Pick it up
    36                 FrameMouseActions.pickup(recWidget.getItems());
     37                StandardGestureActions.pickup(recWidget.getItems());
    3738        }
    3839       
     
    4243        public static void spawnLinkedTrack() {
    4344               
    44                 Frame target = DisplayIO.getCurrentFrame();
     45                Frame target = DisplayController.getCurrentFrame();
    4546                if (target  == null) return;
    4647
     
    4849                Text source = new Text(target.getNextItemID());
    4950                source.setParent(target);
    50                 source.setPosition(FrameMouseActions.MouseX, FrameMouseActions.MouseY);
     51                source.setPosition(DisplayController.getMousePosition());
    5152               
    5253                LinkedTrack ltWidget = new LinkedTrack(source, null);
    5354               
    5455                // Pick it up
    55                 FrameMouseActions.pickup(ltWidget.getItems());
     56                StandardGestureActions.pickup(ltWidget.getItems());
    5657        }
    5758       
     
    6465                // Create the launcher
    6566                FramePlaybackLauncher launcher = new FramePlaybackLauncher(null);
    66                 launcher.setPosition(FrameMouseActions.MouseX, FrameMouseActions.MouseY);
     67                launcher.setPosition(DisplayController.getMousePosition());
    6768
    6869                // Pick it up
    69                 FrameMouseActions.pickup(launcher);
     70                StandardGestureActions.pickup(launcher);
    7071        }
    7172       
  • trunk/src/org/apollo/agents/MelodySearch.java

    r903 r1102  
    11package org.apollo.agents;
    22
    3 import java.awt.Color;
    43import java.io.File;
    54import java.io.FileNotFoundException;
     
    109
    1110import javax.sound.sampled.AudioFormat;
    12 import javax.swing.SwingUtilities;
    1311
    1412import org.apollo.ApolloSystem;
     
    2624import org.apollo.widgets.TrackWidgetCommons;
    2725import org.expeditee.agents.SearchAgent;
     26import org.expeditee.core.Colour;
     27import org.expeditee.gui.DisplayController;
    2828import org.expeditee.gui.Frame;
    29 import org.expeditee.gui.FrameGraphics;
    3029import org.expeditee.gui.FrameIO;
    31 import org.expeditee.settings.UserSettings;
    3230import org.expeditee.settings.folders.FolderSettings;
    3331import org.expeditee.items.Item;
    3432import org.expeditee.items.ItemUtils;
    35 import org.expeditee.items.widgets.InteractiveWidget;
     33import org.expeditee.items.widgets.Widget;
    3634import org.expeditee.items.widgets.WidgetCorner;
    3735import org.expeditee.items.widgets.WidgetEdge;
     
    4240 * Uses meldex. Thanks David Bainbridge.
    4341 *
    44  * The agent runs a querry on the given track widget that launched it.
     42 * The agent runs a query on the given track widget that launched it.
    4543 * If the track launches it it does a full search for all tracks on the current frameset.
    4644 *
     
    9694         */
    9795        @Override
    98         public boolean initialise(Frame frame, Item item) {
     96        public boolean initialise(Frame frame, Item item)
     97        {
    9998                if (!super.initialise(frame, item)) return false;
    10099               
     
    104103                if (item != null) {
    105104                       
    106                         InteractiveWidget iw = null;
     105                        Widget iw = null;
    107106                       
    108107                        if (item instanceof WidgetCorner) {
     
    162161                               
    163162                                if (querryMelody == null) { // abort - failed to get audio
    164                                         SwingUtilities.invokeLater(new ExpediteeMessageBayFeedback(
    165                                                         "Melody search aborted: Failed to load tracks audio"));
     163                                        overwriteMessage("Melody search aborted: Failed to load tracks audio");
    166164                                        _results.addText("Melody search aborted: querry data not good enough to search with",
    167                                                         Color.RED, null, null, false);
     165                                                        Colour.RED, null, null, false);
    168166                                        _results.addText("Click here for help on melody searches",
    169                                                         new Color(0, 180, 0), ApolloSystem.HELP_MELODYSEARCH_FRAMENAME, null, false);
     167                                                        Colour.FromRGB255(0, 180, 0), ApolloSystem.HELP_MELODYSEARCH_FRAMENAME, null, false);
    170168                                       
    171169                                        _results.save();
     
    186184                               
    187185                                if (querryMelody == null) { // abort - failed to get audio
    188                                         SwingUtilities.invokeLater(new ExpediteeMessageBayFeedback(
    189                                                         "Melody search aborted: Failed to proccess querry data"));
    190                                         _results.addText("Melody search aborted: querry data not good enough to search with", Color.RED, null, null, false);
     186                                        overwriteMessage("Melody search aborted: Failed to proccess querry data");
     187                                        _results.addText("Melody search aborted: querry data not good enough to search with", Colour.RED, null, null, false);
    191188                                        _results.addText("Click here for help on melody searches",
    192                                                         new Color(0, 180, 0), ApolloSystem.HELP_MELODYSEARCH_FRAMENAME, null, false);
     189                                                        Colour.FromRGB255(0, 180, 0), ApolloSystem.HELP_MELODYSEARCH_FRAMENAME, null, false);
    193190                                        _results.save();
    194191                                        return null;
     
    240237                                        if(!results.isEmpty()) {
    241238                                                _results.addText(frameName + "(" + results.size() + ")", null, frameName, null, false);
    242                                                 FrameGraphics.requestRefresh(true);
     239                                                DisplayController.requestRefresh(true);
    243240                                        }
    244241                                       
     
    395392
    396393                                if (melodyScores.isEmpty() || melodyScores.get(0).getScore() > threshold) {
    397                                         _results.addText("No matches", Color.RED, null, null, false);
     394                                        _results.addText("No matches", Colour.RED, null, null, false);
    398395                                        _results.addText("Click here to find out how to improve your melody searches",
    399                                                         new Color(0, 180, 0), ApolloSystem.HELP_MELODYSEARCH_FRAMENAME, null, false);
     396                                                        Colour.FromRGB255(0, 180, 0), ApolloSystem.HELP_MELODYSEARCH_FRAMENAME, null, false);
    400397                                } else {
    401398                                       
     
    426423                       
    427424                        if (_stop) {
    428                                 _results.addText("Search cancelled", Color.RED, null, null, false);
     425                                _results.addText("Search cancelled", Colour.RED, null, null, false);
    429426                        }
    430427                       
     
    444441               
    445442        }
    446        
    447 
    448        
    449443       
    450444        /**
     
    470464
    471465        }
    472        
    473         /**
    474          * Safely outputs a message on the messagebay .. if ran on swing thread.
    475          * @author Brook Novak
    476          *
    477          */
    478         private class ExpediteeMessageBayFeedback implements Runnable {
    479                
    480                 String feedbackMessage;
    481                
    482                 public ExpediteeMessageBayFeedback(String feedbackMessage) {
    483                         assert(feedbackMessage != null);
    484                         this.feedbackMessage = feedbackMessage;
    485                 }
    486                
    487                
    488                 public void run() {
    489                         assert(feedbackMessage != null);
    490                         overwriteMessage(feedbackMessage);
    491                 }
    492         }
    493        
    494        
    495466}
  • trunk/src/org/apollo/agents/MelodySearchResult.java

    r315 r1102  
    11package org.apollo.agents;
    2 
    32
    43/**
  • trunk/src/org/apollo/audio/ApolloSubjectChangedEvent.java

    r367 r1102  
    99public final class ApolloSubjectChangedEvent {
    1010       
    11         private ApolloSubjectChangedEvent() {}
     11        private ApolloSubjectChangedEvent()
     12        {
     13        }
    1214
    1315        public static final int INPUT_MIXER = 1;
  • trunk/src/org/apollo/audio/AudioFormatNotSupportedException.java

    r315 r1102  
    66 * @author Brook Novak
    77 */
    8 public class AudioFormatNotSupportedException extends Exception {
     8public class AudioFormatNotSupportedException extends Exception
     9{
    910        protected static final long serialVersionUID = 0L;
    1011       
    11         public AudioFormatNotSupportedException() {
     12        public AudioFormatNotSupportedException()
     13        {
    1214                super();
    1315        }
    1416       
    15         public AudioFormatNotSupportedException(String message) {
     17        public AudioFormatNotSupportedException(String message)
     18        {
    1619                super(message);
    1720        }
    1821       
    19         public AudioFormatNotSupportedException(String message, Exception inner) {
     22        public AudioFormatNotSupportedException(String message, Exception inner)
     23        {
    2024                super(message, inner);
    2125        }
  • trunk/src/org/apollo/audio/Metronome.java

    r332 r1102  
    2020 *
    2121 */
    22 public class Metronome extends AbstractSubject {
     22public class Metronome extends AbstractSubject
     23{
    2324       
    2425        private Receiver receiver = null;
  • trunk/src/org/apollo/audio/RecordManager.java

    r332 r1102  
    1919 *
    2020 */
    21 public class RecordManager extends AbstractSubject  {
    22 
     21public class RecordManager extends AbstractSubject
     22{
    2323        private AudioCaptureThread captureThread = null;
    2424
  • trunk/src/org/apollo/audio/TrackSequence.java

    r365 r1102  
    1616 *
    1717 */
    18 public final class TrackSequence extends AbstractSubject implements Comparable {
     18public final class TrackSequence extends AbstractSubject implements Comparable<TrackSequence> {
    1919
    2020        /** FRIENDLY: ONLY TO BE ACCESSED BY AUDIO MIXER. */
     
    159159         * Order ascending by initiation frame
    160160         */
    161         public final int compareTo(Object o) {
    162                 TrackSequence other = (TrackSequence)o; // throws class cast exception
    163        
     161        public final int compareTo(TrackSequence other)
     162        {
    164163                int cmp = (new Long(initiationFrame)).compareTo(other.initiationFrame);
    165164
    166165                if (cmp == 0) {
    167                        
    168166                        return (new Integer(hashCode()).compareTo(other.hashCode()));
    169167                }
  • trunk/src/org/apollo/audio/structure/AudioStructureModel.java

    r903 r1102  
    33import java.io.FileNotFoundException;
    44import java.io.IOException;
    5 import java.lang.reflect.InvocationTargetException;
    65import java.util.HashMap;
    76import java.util.HashSet;
     
    1413
    1514import javax.sound.sampled.UnsupportedAudioFileException;
    16 import javax.swing.SwingUtilities;
    1715
    1816import org.apollo.audio.ApolloSubjectChangedEvent;
     
    2725import org.apollo.widgets.SampledTrack;
    2826import org.apollo.widgets.TrackWidgetCommons;
    29 import org.expeditee.gui.DisplayIO;
     27import org.expeditee.core.BlockingRunnable;
     28import org.expeditee.gio.EcosystemManager;
     29import org.expeditee.gui.DisplayController;
    3030import org.expeditee.gui.Frame;
    31 import org.expeditee.gui.FrameGraphics;
    3231import org.expeditee.gui.FrameIO;
    33 import org.expeditee.settings.UserSettings;
    3432import org.expeditee.io.Conversion;
    3533import org.expeditee.items.ItemUtils;
    36 import org.expeditee.items.widgets.InteractiveWidget;
     34import org.expeditee.items.widgets.Widget;
    3735import org.expeditee.settings.folders.FolderSettings;
    3836
    3937/**
    40  * A thread safe model of the heirarchical structure of a track graph...
     38 * A thread safe model of the hierarchical structure of a track graph...
    4139 * abstracted from Expeditee frames and audio widgets.
    4240 *
    43  * The track widgets notifty this model for keeping the structure consistent with
    44  * expeditees data.
     41 * The track widgets notify this model for keeping the structure consistent with
     42 * Expeditee's data.
    4543 *
    4644 *
     
    199197                NewGraphCommitor commit = new NewGraphCommitor(rootODFrame, newGraph);
    200198                try {
    201                         SwingUtilities.invokeAndWait(commit);
    202                 } catch (InvocationTargetException e) {
     199                        EcosystemManager.getMiscManager().runOnGIOThread(commit);
     200                } catch (Exception e) {
    203201                        e.printStackTrace();
    204202                        assert(false);
     
    264262               
    265263                try {
    266                         SwingUtilities.invokeAndWait(cacheFetch);
    267                 } catch (InvocationTargetException e) {
     264                        EcosystemManager.getMiscManager().runOnGIOThread(cacheFetch);
     265                } catch (Exception e) {
    268266                        e.printStackTrace();
    269267                        assert(false);
     
    562560         *
    563561         */
    564         private class ExpediteeCachedTrackInfoFetcher implements Runnable
     562        private class ExpediteeCachedTrackInfoFetcher extends BlockingRunnable
    565563        {
    566564                private String rootFrameName;
     
    578576                }
    579577               
    580                 public void run()
     578                public void execute()
    581579                {
    582580                        assert(rootFrameName != null);
     
    584582                        // Check if the current frame
    585583                        Frame rootFrame = null;
    586                         if (DisplayIO.getCurrentFrame() != null && DisplayIO.getCurrentFrame().getName() != null
    587                                         && DisplayIO.getCurrentFrame().getName().equals(rootFrameName)) {
    588                                 rootFrame = DisplayIO.getCurrentFrame();
     584                        if (DisplayController.getCurrentFrame() != null && DisplayController.getCurrentFrame().getName() != null
     585                                        && DisplayController.getCurrentFrame().getName().equals(rootFrameName)) {
     586                                rootFrame = DisplayController.getCurrentFrame();
    589587                        } else {
    590588                                // Check if in cache
     
    597595                                linkedTracks =  new HashMap<String, LinkedTrackModelData>();
    598596                               
    599                                 for (InteractiveWidget iw : rootFrame.getInteractiveWidgets()) {
     597                                for (Widget iw : rootFrame.getInteractiveWidgets()) {
    600598                                       
    601599                                        if (iw instanceof SampledTrack) {
     
    668666         *
    669667         */
    670         private class NewGraphCommitor implements Runnable
     668        private class NewGraphCommitor extends BlockingRunnable
    671669        {
    672670                private final OverdubbedFrame rootODFrame;
     
    687685                }
    688686               
    689                 public void run()
     687                public void execute()
    690688                {
    691689                       
     
    10831081                synchronized(sharedResourceLocker) { // IMPORTANT: Must wait for new graphs to be added to the shared resources
    10841082
    1085                         if (FrameGraphics.isXRayMode()) { // discard whole model
     1083                        if (DisplayController.isXRayMode()) { // discard whole model
    10861084
    10871085                                // Neccessary because if the user goes into xray then moves to a new frame
     
    14221420
    14231421       
    1424                         if (FrameGraphics.isXRayMode()) { // discard whole model
     1422                        if (DisplayController.isXRayMode()) { // discard whole model
    14251423
    14261424                                // Neccessary because if the user goes into xray then moves to a new frame
     
    16101608                                               
    16111609                                                try {
    1612                                                         SwingUtilities.invokeAndWait(new Runnable() {
     1610                                                        EcosystemManager.getMiscManager().runOnGIOThread(new BlockingRunnable() {
    16131611                                                               
    1614                                                                 public void run() { // on swing thread
     1612                                                                public void execute() { // on swing thread
    16151613
    16161614                                                                        synchronized(sharedResourceLocker) {
     
    16721670                                                                }
    16731671                                                        });
    1674                                                 } catch (InvocationTargetException e) {
     1672                                                } catch (Exception e) {
    16751673                                                        e.printStackTrace();
    16761674                                                        assert(false);
  • trunk/src/org/apollo/audio/util/MultiTrackPlaybackController.java

    r367 r1102  
    99
    1010import javax.sound.sampled.LineUnavailableException;
    11 import javax.swing.SwingUtilities;
    1211
    1312import org.apollo.audio.ApolloPlaybackMixer;
     
    3130import org.apollo.util.TrackModelHandler;
    3231import org.apollo.util.TrackModelLoadManager;
    33 import org.expeditee.gui.DisplayIO;
    34 import org.expeditee.gui.DisplayIOObserver;
    35 
     32import org.expeditee.core.BlockingRunnable;
     33import org.expeditee.gio.EcosystemManager;
     34import org.expeditee.gui.DisplayController;
     35import org.expeditee.gui.DisplayObserver;
    3636
    3737public class MultiTrackPlaybackController
    3838        extends AbstractSubject
    39         implements TrackModelHandler, Observer, DisplayIOObserver {
     39        implements TrackModelHandler, Observer, DisplayObserver {
    4040       
    4141        /** Can be a framename or virtual filename (e.g. from a linked track) */
     
    9191                // After a certain amount of frame changes since the last multi playback has occured
    9292                // the cached track models are freed to stop consuming all the memory.
    93                 DisplayIO.addDisplayIOObserver(this);
     93                DisplayController.addDisplayObserver(this);
    9494               
    9595                // For whenever a track sequence is created - must observe the created track sequences...
     
    295295         */
    296296        public void frameChanged() {
    297                 if (hasTrackCacheExpired() || isPlaying() || isLoading() || DisplayIO.getCurrentFrame() == null) return; // already expired - or is playing - so don't expire!
    298                
    299                 String currentFrameName = DisplayIO.getCurrentFrame().getName();
     297                if (hasTrackCacheExpired() || isPlaying() || isLoading() || DisplayController.getCurrentFrame() == null) return; // already expired - or is playing - so don't expire!
     298               
     299                String currentFrameName = DisplayController.getCurrentFrame().getName();
    300300               
    301301                // Free track group every so often..
     
    785785                        final int id1 = id;
    786786                        final Object state1 = state;
    787                         SwingUtilities.invokeLater(new Runnable() {
     787                        EcosystemManager.getMiscManager().runOnGIOThread(new Runnable() {
    788788                                public void run() {
    789789                                        synchronized(listeners1) {
     
    919919       
    920920                                try {
    921                                         SwingUtilities.invokeAndWait(absTrackGraphRetreiver);
     921                                        EcosystemManager.getMiscManager().runOnGIOThread(absTrackGraphRetreiver);
    922922                                } catch (Exception e) {
    923923                                        notifyListeners(loadListeners, MultitrackLoadListener.LOAD_FAILED_GENERIC, e, true);
     
    10951095
    10961096                        // Must commence on the swing thread
    1097                         SwingUtilities.invokeLater(new MultiTrackPlaybackCommencer());
     1097                        EcosystemManager.getMiscManager().runOnGIOThread(new MultiTrackPlaybackCommencer());
    10981098                }
    10991099               
     
    11541154                 * @author Brook Novak
    11551155                 */
    1156                 private class ABSTrackGraphRetreiver implements Runnable {
     1156                private class ABSTrackGraphRetreiver extends BlockingRunnable {
    11571157                       
    11581158                        private String masterMixID;
     
    11651165                        }
    11661166                       
    1167                         public void run() {
     1167                        public void execute() {
    11681168                                assert(rootODFrame != null);
    11691169                                assert(masterMixID != null);
  • trunk/src/org/apollo/audio/util/PlaybackClock.java

    r315 r1102  
    1010import org.apollo.mvc.SubjectChangedEvent;
    1111import org.apollo.util.AudioMath;
    12 import org.expeditee.gui.FrameGraphics;
     12import org.expeditee.gui.DisplayController;
    1313
    1414/**
     
    161161                                        // Do a repaint is something was listening
    162162                                        if (shouldRepaint) {
    163                                                 FrameGraphics.requestRefresh(true); // later - should not congest AWT queue
     163                                                DisplayController.requestRefresh(true); // later - should not congest AWT queue
    164164                                        }
    165165                                       
  • trunk/src/org/apollo/audio/util/Timeline.java

    r315 r1102  
    66 *
    77 * <ul>
    8  *              <li>The initation point: This is the smallest initiation time
    9  *                      <b>(not neccessarily zero)</b> in the frame - at its X pixel.
     8 *              <li>The initiation point: This is the smallest initiation time
     9 *                      <b>(not necessarily zero)</b> in the frame - at its X pixel.
    1010 *              <li>The end point: This is how long the frame runs for - and the
    1111 *                      x-pixel position of the last played track in the frame.
    1212 * </ul>
    1313 *
    14  * They are simple imutable objects thus are not kept consistant with model.
     14 * They are simple immutable objects thus are not kept consistent with model.
    1515 *
    1616 * @author Brook Novak
  • trunk/src/org/apollo/gui/ApolloColorIndexedModels.java

    r315 r1102  
    11package org.apollo.gui;
    22
    3 import java.awt.Color;
    4 import java.awt.image.IndexColorModel;
     3import org.expeditee.core.Colour;
    54
    65public class ApolloColorIndexedModels {
    76       
    8         public static final Color KEY_COLOR = new Color(123,58,123,0);
    9         private static final int KEY_INDEX = 0;
     7        public static final Colour KEY_COLOR = Colour.FromRGBA255(123,58,123,0);
     8        //private static final int KEY_INDEX = 0;
    109       
    1110        /** Color index model for the track graphs */
    12         public static final IndexColorModel graphIndexColorModel;
     11        //public static final IndexColorModel graphIndexColorModel;
    1312
     13        public static final Colour WAVEFORM_COLOR = Colour.fromRGB24BitPacked(0x1C5BA3);
     14        public static final Colour WAVEFORM_SELECTION_COLOR = Colour.YELLOW;
    1415       
    15         public static final Color WAVEFORM_COLOR = new Color(0x1C5BA3);
    16         public static final Color WAVEFORM_SELECTION_COLOR = Color.YELLOW;
     16        //private static final int WAVEFORM_INDEX = 1;
     17        //private static final int WAVEFORM_SELECTION_INDEX = 2;
    1718       
    18         private static final int WAVEFORM_INDEX = 1;
    19         private static final int WAVEFORM_SELECTION_INDEX = 2;
     19        //public static final IndexColorModel linkedTrackIndexColorModel;
    2020       
    21        
    22         public static final IndexColorModel linkedTrackIndexColorModel;
    23        
    24         public static final Color TRACK1_COLOR = new Color(0x1C5BA3);
    25         public static final Color TRACK2_COLOR = new Color(0x3280B7);
     21        public static final Colour TRACK1_COLOR = Colour.fromRGB24BitPacked(0x1C5BA3);
     22        public static final Colour TRACK2_COLOR = Colour.fromRGB24BitPacked(0x3280B7);
    2623       
    2724        public static final int TRACK1_INDEX = 1;
    2825        public static final int TRACK2_INDEX = 2;
    2926
    30         static { // Prepare the global color index model for the graphs
     27        /*static { // Prepare the global color index model for the graphs
    3128
    3229                // For waveform graphs:
     
    3532                byte[] blues = new byte[256];
    3633               
    37                 reds[KEY_INDEX] = (byte)KEY_COLOR.getRed();
    38                 greens[KEY_INDEX] = (byte)KEY_COLOR.getGreen();
    39                 blues[KEY_INDEX] = (byte)KEY_COLOR.getBlue();
     34                reds[KEY_INDEX] = (byte)KEY_COLOR.getRed255();
     35                greens[KEY_INDEX] = (byte)KEY_COLOR.getGreen255();
     36                blues[KEY_INDEX] = (byte)KEY_COLOR.getBlue255();
    4037               
    41                 reds[WAVEFORM_INDEX] = (byte)WAVEFORM_COLOR.getRed();
    42                 greens[WAVEFORM_INDEX] = (byte)WAVEFORM_COLOR.getGreen();
    43                 blues[WAVEFORM_INDEX] = (byte)WAVEFORM_COLOR.getBlue();
     38                reds[WAVEFORM_INDEX] = (byte)WAVEFORM_COLOR.getRed255();
     39                greens[WAVEFORM_INDEX] = (byte)WAVEFORM_COLOR.getGreen255();
     40                blues[WAVEFORM_INDEX] = (byte)WAVEFORM_COLOR.getBlue255();
    4441               
    45                 reds[WAVEFORM_SELECTION_INDEX] = (byte)WAVEFORM_SELECTION_COLOR.getRed();
    46                 greens[WAVEFORM_SELECTION_INDEX] = (byte)WAVEFORM_SELECTION_COLOR.getGreen();
    47                 blues[WAVEFORM_SELECTION_INDEX] = (byte)WAVEFORM_SELECTION_COLOR.getBlue();
     42                reds[WAVEFORM_SELECTION_INDEX] = (byte)WAVEFORM_SELECTION_COLOR.getRed255();
     43                greens[WAVEFORM_SELECTION_INDEX] = (byte)WAVEFORM_SELECTION_COLOR.getGreen255();
     44                blues[WAVEFORM_SELECTION_INDEX] = (byte)WAVEFORM_SELECTION_COLOR.getBlue255();
    4845               
    4946                graphIndexColorModel = new IndexColorModel(8, 256, reds, greens, blues, KEY_INDEX);
     
    5552                blues = new byte[256];
    5653               
    57                 reds[KEY_INDEX] = (byte)KEY_COLOR.getRed();
    58                 greens[KEY_INDEX] = (byte)KEY_COLOR.getGreen();
    59                 blues[KEY_INDEX] = (byte)KEY_COLOR.getBlue();
     54                reds[KEY_INDEX] = (byte)KEY_COLOR.getRed255();
     55                greens[KEY_INDEX] = (byte)KEY_COLOR.getGreen255();
     56                blues[KEY_INDEX] = (byte)KEY_COLOR.getBlue255();
    6057               
    61                 reds[TRACK1_INDEX] = (byte)TRACK1_COLOR.getRed();
    62                 greens[TRACK1_INDEX] = (byte)TRACK1_COLOR.getGreen();
    63                 blues[TRACK1_INDEX] = (byte)TRACK1_COLOR.getBlue();
     58                reds[TRACK1_INDEX] = (byte)TRACK1_COLOR.getRed255();
     59                greens[TRACK1_INDEX] = (byte)TRACK1_COLOR.getGreen255();
     60                blues[TRACK1_INDEX] = (byte)TRACK1_COLOR.getBlue255();
    6461               
    65                 reds[TRACK2_INDEX] = (byte)TRACK2_COLOR.getRed();
    66                 greens[TRACK2_INDEX] = (byte)TRACK2_COLOR.getGreen();
    67                 blues[TRACK2_INDEX] = (byte)TRACK2_COLOR.getBlue();
     62                reds[TRACK2_INDEX] = (byte)TRACK2_COLOR.getRed255();
     63                greens[TRACK2_INDEX] = (byte)TRACK2_COLOR.getGreen255();
     64                blues[TRACK2_INDEX] = (byte)TRACK2_COLOR.getBlue255();
    6865               
    6966                linkedTrackIndexColorModel = new IndexColorModel(8, 256, reds, greens, blues, KEY_INDEX);
    7067               
    71         }
    72        
    73        
    74        
    75        
     68        }*/
    7669}
  • trunk/src/org/apollo/gui/DualPeakTroughWaveFormRenderer.java

    r1007 r1102  
    3030         *                      If audioformat is not supported. See SampledAudioManager.isFormatSupportedForPlayback
    3131         */
    32         public DualPeakTroughWaveFormRenderer(AudioFormat audioFormat) {
     32        public DualPeakTroughWaveFormRenderer(AudioFormat audioFormat)
     33        {
    3334                if (audioFormat == null) throw new NullPointerException("audioFormat");
    3435               
    35                 if (!SampledAudioManager.getInstance().isFormatSupportedForPlayback(audioFormat))
    36                         throw new IllegalArgumentException();
     36                if (!SampledAudioManager.getInstance().isFormatSupportedForPlayback(audioFormat)) throw new IllegalArgumentException();
    3737
    3838                sampleSize = audioFormat.getSampleSizeInBits();
     
    7070         *              interleaves in rendering order)
    7171         */
    72         public float[] getSampleAmplitudes(byte[] audioBytes, int startFrame, int frameLength, int aggregationSize) {
     72        public float[] getSampleAmplitudes(byte[] audioBytes, int startFrame, int frameLength, int aggregationSize)
     73        {
    7374                assert(audioBytes != null);
    7475                assert(startFrame >= 0);
     
    7778                int aggregationCount = frameLength / aggregationSize;
    7879               
    79                 float[] amplitudes = (aggregationSize == 1) ?
    80                         new float[aggregationCount] :
    81                                 new float[aggregationCount * 2];
     80                float[] amplitudes = (aggregationSize == 1) ? new float[aggregationCount] : new float[aggregationCount * 2];
    8281               
    8382                if (sampleSize == 16) {
  • trunk/src/org/apollo/gui/EditableSampledTrackGraphView.java

    r355 r1102  
    11package org.apollo.gui;
    22
    3 import java.awt.Color;
    43import java.awt.Graphics;
    54import java.awt.Graphics2D;
    65import java.awt.Point;
    7 import java.awt.Rectangle;
    86import java.awt.event.KeyEvent;
    97import java.awt.event.KeyListener;
     
    2321import org.apollo.util.TrackNameCreator;
    2422import org.apollo.widgets.SampledTrack;
     23import org.expeditee.core.Colour;
     24import org.expeditee.core.bounds.AxisAlignedBoxBounds;
     25import org.expeditee.gio.gesture.StandardGestureActions;
     26import org.expeditee.gio.swing.SwingConversions;
     27import org.expeditee.gio.swing.SwingMiscManager;
    2528import org.expeditee.gui.Browser;
    26 import org.expeditee.gui.DisplayIO;
     29import org.expeditee.gui.DisplayController;
    2730import org.expeditee.gui.Frame;
    28 import org.expeditee.gui.FrameGraphics;
    29 import org.expeditee.gui.FrameMouseActions;
    3031import org.expeditee.gui.FreeItems;
    3132import org.expeditee.items.Item;
     
    5253        private boolean selectAllOnDoubleClick = false;
    5354
    54         public static final Color SELECTION_BACKING_COLOR_SELECT_ONLY = Color.BLACK;
    55         private static final Color SELECTION_BACKING_COLOR_SELECT_AND_COPY = Color.GREEN;
     55        public static final Colour SELECTION_BACKING_COLOR_SELECT_ONLY = Colour.BLACK;
     56        private static final Colour SELECTION_BACKING_COLOR_SELECT_AND_COPY = Colour.GREEN;
    5657
    5758        private static final int SELECTION_MODE_SELECT_ONLY = 1;
     
    215216                        }
    216217                       
    217                         FrameGraphics.refresh(true);
     218                        DisplayController.requestRefresh(true);
    218219                       
    219220                }
     
    289290                        assert(copiedAudioRegion != null);
    290291                       
    291                         Frame targetFrame = DisplayIO.getCurrentFrame();
     292                        Frame targetFrame = DisplayController.getCurrentFrame();
    292293                        if (targetFrame != null) {
    293294                               
     
    307308                                assert(Browser._theBrowser != null);
    308309                               
    309                                 // A workround for getting the widget into fre space centered on cursor
     310                                // A workaround for getting the widget into free space centred on cursor
    310311                                Point p = e.getLocationOnScreen();
    311                                 SwingUtilities.convertPointFromScreen(p, Browser._theBrowser.getContentPane());
     312                                SwingUtilities.convertPointFromScreen(p, SwingMiscManager.getIfUsingSwingGraphicsManager().getContentPane());
    312313                                twidget.setPosition(p.x - (twidget.getWidth() / 2), p.y - (twidget.getHeight() / 2));
    313314
    314315                                for (Item i : twidget.getItems()) {
    315                                         i.setOffset(new Point(
    316                                                         (i.getX() - DisplayIO.getMouseX()) + (twidget.getWidth() / 2),
    317                                                         (i.getY() - FrameMouseActions.getY()) + (twidget.getHeight() / 2)
    318                                                 ));
     316                                        i.setOffset(SwingConversions.fromSwingPoint(new Point(
     317                                                        (i.getX() - DisplayController.getMouseX()) + (twidget.getWidth() / 2),
     318                                                        (i.getY() - DisplayController.getMouseY()) + (twidget.getHeight() / 2)
     319                                                )));
    319320                                }
    320321                               
    321322                                // Put the new widget into free space
    322                                 FrameMouseActions.pickup(twidget.getItems());
     323                                StandardGestureActions.pickup(twidget.getItems());
    323324
    324325                        }
     
    399400       
    400401        @Override
    401         public void paint(Graphics g) {
     402        public void paint(Graphics g)
     403        {
    402404                super.paint(g);
    403405
     
    416418                        }
    417419                       
    418                         g.setColor(Color.RED);
    419                         g.drawLine(
    420                                         x,
    421                                         0,
    422                                         x,
    423                                         getHeight());
     420                        g.setColor(SwingConversions.toSwingColor(Colour.RED));
     421                        g.drawLine(x, 0, x, getHeight());
    424422                       
    425423                }
     
    432430        private void paintLock(Graphics g) {
    433431                if (isPlaying()) {
    434                         IconRepository.getIcon("lock.png").paintIcon(null,
     432                        /*IconRepository.getIcon("lock.png").paintIcon(null,
    435433                                        g,
    436434                                        getWidth() - LOCK_ICON_CORNER_OFFSET,
    437                                         LOCK_ICON_CORNER_OFFSET - 16);
     435                                        LOCK_ICON_CORNER_OFFSET - 16);*/
     436                       
     437                        g.drawImage(SwingMiscManager.getIfUsingSwingImageManager().getInternalImage(IconRepository.getIcon("lock.png")),
     438                                        getWidth() - LOCK_ICON_CORNER_OFFSET,
     439                                        LOCK_ICON_CORNER_OFFSET - 16,
     440                                        null);
    438441                }
    439442        }
     
    442445                Point exp = getExpediteePoint();
    443446                if (exp != null) {
    444                         FrameGraphics.invalidateArea(new Rectangle(
     447                        DisplayController.invalidateArea(new AxisAlignedBoxBounds(
    445448                                        exp.x + getWidth() - LOCK_ICON_CORNER_OFFSET,
    446449                                        exp.y + LOCK_ICON_CORNER_OFFSET  - 16,
     
    505508                       
    506509                        color =  (selectionMode == SELECTION_MODE_SELECT_ONLY) ?
    507                                         SELECTION_BACKING_COLOR_SELECT_ONLY : SELECTION_BACKING_COLOR_SELECT_AND_COPY;
     510                                                SwingConversions.toSwingColor(SELECTION_BACKING_COLOR_SELECT_ONLY) :
     511                                                SwingConversions.toSwingColor(SELECTION_BACKING_COLOR_SELECT_AND_COPY);
    508512                        super.paint(g);
    509513                }
  • trunk/src/org/apollo/gui/ExpandedTrackManager.java

    r315 r1102  
    22
    33import java.awt.Dimension;
     4import java.awt.Graphics2D;
    45import java.awt.GridBagConstraints;
    56import java.awt.GridBagLayout;
    6 import java.awt.Rectangle;
    77import java.awt.event.ActionEvent;
    88import java.awt.event.ActionListener;
    9 import java.awt.event.ComponentEvent;
    10 import java.awt.event.ComponentListener;
    119import java.util.LinkedList;
    1210
    1311import javax.swing.JButton;
    1412import javax.swing.JLabel;
    15 import javax.swing.SwingUtilities;
     13import javax.swing.JPanel;
    1614
    1715import org.apollo.audio.SampledTrackModel;
     
    2220import org.apollo.util.TrackModelHandler;
    2321import org.apollo.util.TrackModelLoadManager;
     22import org.expeditee.core.bounds.AxisAlignedBoxBounds;
     23import org.expeditee.gio.EcosystemManager;
     24import org.expeditee.gio.InputManager.WindowEventListener;
     25import org.expeditee.gio.InputManager.WindowEventType;
     26import org.expeditee.gio.swing.SwingConversions;
     27import org.expeditee.gio.swing.SwingMiscManager;
    2428import org.expeditee.gui.Browser;
    25 import org.expeditee.gui.FrameGraphics;
    26 import org.expeditee.gui.MessageBay;
     29import org.expeditee.gui.DisplayController;
    2730import org.expeditee.gui.Popup;
    2831import org.expeditee.gui.PopupManager;
     32import org.expeditee.gui.PopupManager.ExpandShrinkAnimator;
    2933
    3034/**
     
    4044       
    4145        /** All epxanded tracks ... either in all in view or all selected ... to be viewed */
    42         private LinkedList<ExpandedTrackPopup> expandedTracks = new LinkedList<ExpandedTrackPopup> (); // SHARED Model data
     46        private LinkedList<ExpandedTrackPopup> expandedTracks = new LinkedList<ExpandedTrackPopup>(); // SHARED Model data
    4347
    4448        private MultiTrackExpansionPopup trackSelectionPopup = new MultiTrackExpansionPopup();
    4549       
    4650        private static ExpandedTrackManager instance = new ExpandedTrackManager();
    47         private ExpandedTrackManager() {
    48                
     51       
     52        private ExpandedTrackManager()
     53        {
    4954                // Keep view centered to browser size
    50                 SwingUtilities.invokeLater(new Runnable() {
    51                         public void run() {
    52 
    53                                 // Keep expanded view centered to the browser window
    54                                 if (Browser._theBrowser != null) {
    55                                         Browser._theBrowser.addComponentListener(new ComponentListener() {
    56 
    57                                                 public void componentHidden(ComponentEvent e) {
    58                                                 }
    59 
    60                                                 public void componentMoved(ComponentEvent e) {
    61                                                 }
    62 
    63                                                 public void componentResized(ComponentEvent e) {
    64                                                        
    65                                                         if (PopupManager.getInstance().isShowing(trackSelectionPopup)) {
    66                                                                 // User currently selecting..
    67                                                                 trackSelectionPopup.setLocation(
    68                                                                                 (Browser._theBrowser.getWidth() / 2) - (trackSelectionPopup.getWidth() / 2), 0);
    69                                                                
    70                                                         } else { // expanded views might be showing
    71                                                                
    72                                                                 // Fails with Maximizing of window on some systems... swing
    73                                                                 // bug!! really anoying
    74                                                                 updateLayout();
    75        
    76                                                         }
    77        
    78                                                 }
    79 
    80                                                 public void componentShown(ComponentEvent e) {
    81                                                 }
    82                                                
    83                                         });
     55                EcosystemManager.getInputManager().addWindowEventListener(new WindowEventListener()
     56                {
     57                        @Override
     58                        public void onWindowEvent(WindowEventType type)
     59                        {
     60                                if (type != WindowEventType.WINDOW_RESIZED) return;
     61                                if (PopupManager.getInstance().isShowing(trackSelectionPopup)) {
     62                                        // User currently selecting..
     63                                        trackSelectionPopup.setLocation((EcosystemManager.getGraphicsManager().getWindowSize().getWidth() - trackSelectionPopup.getFullBounds().getWidth()) / 2, 0);
     64                                       
     65                                } else { // expanded views might be showing
     66                                       
     67                                        // Fails with maximising of window on some systems... swing
     68                                        // bug!! really annoying
     69                                        updateLayout();
     70
    8471                                }
    85                                
    86                         }
     72                        }
     73                       
    8774                });
    8875               
    89                 // Registewr for (indirectly) handling track models
     76                // Register for (indirectly) handling track models
    9077                TrackModelLoadManager.getInstance().addTrackModelHandler(this);
    9178
     79                PopupManager.getInstance().add(trackSelectionPopup);
    9280        }
    9381       
     
    162150         *              If trackModel or trackMix or trackSourceFrameName or localFilename is null.
    163151         */
    164         public boolean addTrackToSelection(
    165                         SampledTrackModel track,
    166                         String trackSourceFrameName,
    167                         Rectangle animationSource,
    168                         TrackMixSubject mix) {
    169                
     152        public boolean addTrackToSelection(SampledTrackModel track, String trackSourceFrameName, AxisAlignedBoxBounds animationSource, TrackMixSubject mix)
     153        {
    170154                assert(track != null);
    171155                assert(Browser._theBrowser != null);
     
    174158                synchronized(expandedTracks) {
    175159       
    176                         if (expandedTracks.size() < MAX_EXPANDED_TRACK_SIZE
    177                                         && !isTrackInExpansionSelection(track)) {
     160                        if (expandedTracks.size() < MAX_EXPANDED_TRACK_SIZE && !isTrackInExpansionSelection(track)) {
    178161                               
    179162                                ExpandedTrackPopup.giveToExpandedTrackManager(
     
    183166                                                0,
    184167                                                track.getFrameCount()); /** @see #receiveExpandedTrackPopup */
    185        
    186                                 Rectangle trackSelectionPopupBounds = null;
    187168                               
    188169                                // Ensure that the trackSelectionPopup is not already showing / animated to show
    189170                                if (!PopupManager.getInstance().isShowing(trackSelectionPopup)) {
    190171                                       
    191                                         trackSelectionPopupBounds = new Rectangle(
    192                                                         (Browser._theBrowser.getWidth() / 2 ) - (trackSelectionPopup.getWidth() / 2),
    193                                                         0,
    194                                                         trackSelectionPopup.getWidth(),
    195                                                         trackSelectionPopup.getHeight());
     172                                        trackSelectionPopup.setLocation((DisplayController.getFramePaintArea().getWidth() - trackSelectionPopup.getFullBounds().getWidth()) / 2, 0);
    196173                                       
    197174                                        // Creep from above
    198                                         PopupManager.getInstance().showPopup(
    199                                                         trackSelectionPopup,
    200                                                         trackSelectionPopupBounds.getLocation(),
    201                                                         null,
    202                                                         PopupManager.getInstance().new ExpandShrinkAnimator(
    203                                                                         trackSelectionPopupBounds,
    204                                                                         null));
    205                                        
    206                                 } else {
    207                                         trackSelectionPopup.repaint();
     175                                        trackSelectionPopup.show();
    208176                                }
    209177                               
    210178                                // Animate a fake popup expanding into the trackSelectionPopup from the given source if not null
    211179                                if (animationSource != null) {
    212                                        
    213                                         PopupManager.getInstance().doPureAnimation(PopupManager.getInstance().new ExpandShrinkAnimator(
    214                                                         animationSource, null),
    215                                                         (trackSelectionPopupBounds == null) ?
    216                                                                         trackSelectionPopup.getBounds() : trackSelectionPopupBounds);
     180                                        ((ExpandShrinkAnimator) trackSelectionPopup.getAnimator()).setInitialBounds(animationSource);
    217181                                }
    218182                               
     
    253217         *
    254218         */
    255         public void expandSingleTrack(
    256                         SampledTrackModel track,
    257                         Rectangle animationSource,
    258                         TrackMixSubject mix,
    259                         String trackSourceFrameName,
    260                         int frameStart,
    261                         int frameLength) {
     219        public void expandSingleTrack(SampledTrackModel track, AxisAlignedBoxBounds animationSource, TrackMixSubject mix, String trackSourceFrameName, int frameStart, int frameLength)
     220        {
    262221                assert(animationSource != null);
    263222                assert(track != null);
     
    265224                synchronized(expandedTracks) {
    266225                        // Hide all expandedTracks that are currently showing
    267                         while (!expandedTracks.isEmpty())
    268                                 PopupManager.getInstance().hidePopup(expandedTracks.getFirst());
     226                        for (ExpandedTrackPopup expandedTrack : expandedTracks) {
     227                                expandedTrack.hide();
     228                        }
    269229                }
    270230
     
    315275        }
    316276       
    317         private void cancelSelection() {
    318                
     277        private void cancelSelection()
     278        {
    319279                hideTrackSelectionPopup();
    320280               
    321281                // Remove from selection
    322                 LinkedList<? extends ExpandedTrackPopup> old = (LinkedList<? extends ExpandedTrackPopup>)expandedTracks.clone();
     282                LinkedList<? extends ExpandedTrackPopup> old = (LinkedList<? extends ExpandedTrackPopup>) expandedTracks.clone();
    323283               
    324284                synchronized(expandedTracks) {
     
    341301         *              A tracks ExpandedTrackPopup if one exists.
    342302         */
    343         private ExpandedTrackPopup getExpandedTrackPopup(SampledTrackModel track) {
     303        private ExpandedTrackPopup getExpandedTrackPopup(SampledTrackModel track)
     304        {
    344305                assert(track != null);
    345306               
     
    362323         *              True if the track is expanded - or is selected to be expanded..
    363324         */
    364         public boolean isTrackInExpansionSelection(SampledTrackModel track) {
     325        public boolean isTrackInExpansionSelection(SampledTrackModel track)
     326        {
    365327                assert(track != null);
    366328                return getExpandedTrackPopup(track) != null;
     
    371333         *                      True if at least 1 expanded track is showing - or is selected to show.
    372334         */
    373         public boolean doesExpandedTrackExist() {
     335        public boolean doesExpandedTrackExist()
     336        {
    374337                synchronized(expandedTracks) {
    375338                        return expandedTracks.size() > 0;
     
    377340        }
    378341       
    379         public boolean isAnyExpandedTrackVisible() {
     342        public boolean isAnyExpandedTrackVisible()
     343        {
    380344                for (ExpandedTrackPopup xtp : expandedTracks) {
    381345                        if (PopupManager.getInstance().isShowing(xtp)) return true;
     
    389353         *
    390354         */
    391         public void showSelection() {
     355        public void showSelection()
     356        {
    392357                expandTracks(null);
    393358        }
    394359       
    395360        /**
    396          * Returns immediatly if there are no tracks selected. Only expands if the popup is not already expanded.
     361         * Returns immediately if there are no tracks selected. Only expands if the popup is not already expanded.
    397362         *
    398363         * @param directAnimSource
     
    401366         *              a widget).
    402367         */
    403         private void expandTracks(Rectangle directAnimSource) {
    404 
     368        private void expandTracks(AxisAlignedBoxBounds directAnimSource)
     369        {
    405370                synchronized(expandedTracks) {
    406371                       
     
    418383                        for (ExpandedTrackPopup xtp : expandedTracks) {
    419384       
    420                                 // Note: returns immediatly if already showing
    421                                 PopupManager.getInstance().showPopup(
    422                                                 xtp,
    423                                                 xtp.getLocation(),
    424                                                 null,
    425                                                 PopupManager.getInstance().new ExpandShrinkAnimator(
    426                                                                 directAnimSource,
    427                                                                 null));
     385                                // Note: returns immediately if already showing
     386                                ((ExpandShrinkAnimator) xtp.getAnimator()).setInitialBounds(directAnimSource);
     387                                xtp.show();
    428388                       
    429389                        }
     
    435395        }
    436396       
    437         private void hideTrackSelectionPopup() {
    438                 PopupManager.getInstance().hidePopup(
    439                                 trackSelectionPopup, PopupManager.getInstance().new ExpandShrinkAnimator(
    440                                                 new Rectangle((Browser._theBrowser.getWidth() / 2 ) - (trackSelectionPopup.getWidth() / 2),
    441                                                                 0, trackSelectionPopup.getWidth(), trackSelectionPopup.getHeight()), null));
     397        private void hideTrackSelectionPopup()
     398        {
     399                trackSelectionPopup.hide();
    442400        }
    443401       
     
    446404         * current state of the window.
    447405         */
    448         private void updateLayout() {
    449                
    450                 synchronized(expandedTracks) {
    451                                
    452        
     406        private void updateLayout()
     407        {
     408                synchronized(expandedTracks) {
     409
    453410                        if (expandedTracks.isEmpty()) return;
    454411                       
     
    456413                        assert(Browser._theBrowser != null);
    457414               
    458                         int cpWidth = Browser._theBrowser.getContentPane().getWidth();
    459                         int cpHeight = Browser._theBrowser.getContentPane().getHeight();
    460                         if (!FrameGraphics.isAudienceMode()) { // if message bay is showing - the remove the height
    461                                
    462                                 cpHeight -= MessageBay.MESSAGE_BUFFER_HEIGHT;
     415                        int cpWidth = DisplayController.getFramePaintArea().getWidth();
     416                        int cpHeight = DisplayController.getFramePaintArea().getHeight();
     417                        if (!DisplayController.isAudienceMode()) { // if message bay is showing - the remove the height
     418                               
     419                                cpHeight -= DisplayController.getMessageBayPaintArea().getHeight();
    463420                               
    464421                        }
     
    504461         * Global Track model re-use .... can be called from any thread
    505462         */
    506         public SampledTrackModel getSharedSampledTrackModel(String localfilename) {
     463        public SampledTrackModel getSharedSampledTrackModel(String localfilename)
     464        {
    507465                synchronized(expandedTracks) {
    508466                        for (ExpandedTrackPopup xtp : expandedTracks) {
     
    521479         *
    522480         */
    523         private class MultiTrackExpansionPopup extends Popup implements ActionListener {
    524                
     481        private class MultiTrackExpansionPopup extends Popup implements ActionListener
     482        {
     483                private JPanel panel;
    525484                private JButton expandButton;
    526485                private JButton cancelButton;
     
    528487                private JLabel selected2;
    529488                private JLabel selectedMore;
    530 
    531                 private static final long serialVersionUID = 1L;
     489               
    532490                //private final Color BACK_COLOR = SampledTrackGraphViewPort.ZOOM_BACKING_COLOR_NORMAL;
    533491               
    534                 MultiTrackExpansionPopup() {
    535                         super(new GridBagLayout());
    536                         setSize(260, 80);
    537                         super.setAudoHide(false);
    538                        
    539                         expandButton = new JButton(IconRepository.getIcon("expand.png"));
     492                MultiTrackExpansionPopup()
     493                {
     494                        super(new ExpandShrinkAnimator());
     495                       
     496                        panel = new JPanel(new GridBagLayout());
     497                        panel.setSize(260, 80);
     498                       
     499                        expandButton = new JButton();
     500                        SwingMiscManager.setJButtonIcon(expandButton, IconRepository.getIcon("expand.png"));
    540501                        expandButton.addActionListener(this);
    541502                        expandButton.setPreferredSize(new Dimension(40, 40));
    542503                        expandButton.setToolTipText("Expand selection");
    543504                       
    544                         cancelButton = new JButton(IconRepository.getIcon("close.png"));
     505                        cancelButton = new JButton();
     506                        SwingMiscManager.setJButtonIcon(cancelButton, IconRepository.getIcon("close.png"));
    545507                        cancelButton.addActionListener(this);
    546508                        cancelButton.setPreferredSize(new Dimension(40, 40));
     
    563525                        c.gridy = 0;
    564526                        c.fill = GridBagConstraints.CENTER;
    565                         add(expandButton, c);
     527                        panel.add(expandButton, c);
    566528                       
    567529                        c = new GridBagConstraints();
     
    569531                        c.gridy = 0;
    570532                        c.fill = GridBagConstraints.CENTER;
    571                         add(cancelButton, c);
     533                        panel.add(cancelButton, c);
    572534                       
    573535                        c = new GridBagConstraints();
     
    576538                        c.gridwidth = 2;
    577539                        c.fill = GridBagConstraints.CENTER;
    578                         add(selected1, c);
     540                        panel.add(selected1, c);
    579541                       
    580542                        c = new GridBagConstraints();
     
    583545                        c.gridwidth = 2;
    584546                        c.fill = GridBagConstraints.CENTER;
    585                         add(selected2, c);
     547                        panel.add(selected2, c);
    586548                       
    587549                        c = new GridBagConstraints();
     
    591553                        c.gridheight = 2;
    592554                        c.fill = GridBagConstraints.CENTER;
    593                         add(selectedMore, c);
    594 
    595                 }
    596                
    597                 public void onTrackSelectionChanged() {
    598                        
     555                        panel.add(selectedMore, c);
     556                }
     557               
     558                public void setLocation(int x, int y)
     559                {
     560                        panel.setLocation(x, y);
     561                }
     562               
     563                public void onTrackSelectionChanged()
     564                {
    599565                        synchronized(expandedTracks) {
    600566                                       
     
    628594                }
    629595
    630                 public void actionPerformed(ActionEvent e) {
     596                public void actionPerformed(ActionEvent e)
     597                {
    631598                        if (e.getSource() == expandButton) {
    632599                                showSelection();
     
    635602                        }
    636603                }
    637                
    638                
    639 
    640         }
    641        
    642        
     604
     605                @Override
     606                protected void paintInternal()
     607                {
     608                        Graphics2D g = SwingMiscManager.getIfUsingSwingGraphicsManager().getCurrentSurface();
     609                       
     610                        panel.paint(g);
     611                }
     612
     613                @Override
     614                public AxisAlignedBoxBounds getFullBounds()
     615                {
     616                        return SwingConversions.fromSwingRectangle(panel.getBounds());
     617                }
     618
     619                @Override
     620                public void onHide()
     621                {
     622                }
     623
     624                @Override
     625                public void onShow()
     626                {
     627                }
     628        }
    643629}
  • trunk/src/org/apollo/gui/ExpandedTrackPopup.java

    r315 r1102  
    22
    33import java.awt.BorderLayout;
    4 import java.awt.Color;
    54import java.awt.Dimension;
    65import java.awt.Event;
    76import java.awt.Font;
    8 import java.awt.Graphics;
     7import java.awt.Graphics2D;
    98import java.awt.GridBagConstraints;
    109import java.awt.GridBagLayout;
    1110import java.awt.Insets;
    1211import java.awt.Point;
    13 import java.awt.Rectangle;
    1412import java.awt.event.ActionEvent;
    1513import java.awt.event.ActionListener;
    16 import java.awt.event.KeyEvent;
    17 import java.awt.event.KeyListener;
    18 import java.awt.event.MouseEvent;
    19 import java.awt.event.MouseListener;
    20 import java.awt.event.MouseMotionListener;
    2114
    2215import javax.sound.sampled.LineUnavailableException;
    23 import javax.swing.Icon;
    2416import javax.swing.JButton;
    2517import javax.swing.JPanel;
     
    4537import org.apollo.util.AudioMath;
    4638import org.apollo.widgets.TrackWidgetCommons;
     39import org.expeditee.core.Colour;
     40import org.expeditee.core.Image;
     41import org.expeditee.core.bounds.AxisAlignedBoxBounds;
     42import org.expeditee.gio.EcosystemManager;
     43import org.expeditee.gio.input.InputEvent;
     44import org.expeditee.gio.input.InputEventListener;
     45import org.expeditee.gio.swing.SwingConversions;
     46import org.expeditee.gio.swing.SwingMiscManager;
    4747import org.expeditee.gui.Browser;
    48 import org.expeditee.gui.FrameGraphics;
     48import org.expeditee.gui.DisplayController;
    4949import org.expeditee.gui.Popup;
    50 import org.expeditee.gui.PopupManager;
    51 
    52 public class ExpandedTrackPopup extends Popup implements ActionListener, Observer {
    53        
    54         private static final long serialVersionUID = 1L;
    55        
     50import org.expeditee.gui.PopupManager.ExpandShrinkAnimator;
     51
     52public class ExpandedTrackPopup extends Popup implements ActionListener, Observer
     53{
    5654        /** The observed subject. Can never be null */
    5755        private SampledTrackModel trackModel; // immutable
     
    6159        private TrackMixSubject trackMix; // immutable
    6260
     61        private JPanel panel;
    6362        private JButton playPauseButton;
    6463        private JButton stopButton;
     
    106105                        String trackSourceFrameName,
    107106                        int frameStart,
    108                         int frameLength) {
    109                 super(new BorderLayout());
     107                        int frameLength)
     108        {
     109                super(new ExpandShrinkAnimator());
    110110                super.setConsumeBackClick(true);
     111               
     112                panel = new JPanel(new BorderLayout());
    111113               
    112114                if (trackModel == null) throw new NullPointerException("trackModel");
     
    121123                playPauseButton = new JButton();
    122124                playPauseButton.addActionListener(this);
    123                 playPauseButton.setIcon(IconRepository.getIcon("play.png"));
     125                SwingMiscManager.setJButtonIcon(playPauseButton, IconRepository.getIcon("play.png"));
    124126                playPauseButton.setPreferredSize(new Dimension(BUTTON_SIZE, BUTTON_SIZE));
    125127                playPauseButton.setToolTipText("Play selection / Pause");
     
    128130                stopButton.setEnabled(false);
    129131                stopButton.addActionListener(this);
    130                 stopButton.setIcon(IconRepository.getIcon("stop.png"));
     132                SwingMiscManager.setJButtonIcon(stopButton, IconRepository.getIcon("stop.png"));
    131133                stopButton.setPreferredSize(new Dimension(BUTTON_SIZE, BUTTON_SIZE));
    132134                stopButton.setToolTipText("Stop playback");
     
    134136                rewindButton = new JButton();
    135137                rewindButton.addActionListener(this);
    136                 rewindButton.setIcon(IconRepository.getIcon("rewind.png"));
     138                SwingMiscManager.setJButtonIcon(rewindButton, IconRepository.getIcon("rewind.png"));
    137139                rewindButton.setPreferredSize(new Dimension(BUTTON_SIZE, BUTTON_SIZE));
    138140                rewindButton.setToolTipText("Rewind to start");
     
    140142                // Icon changes
    141143                muteButton = new JToggleButton();
    142                 muteButton.setSelectedIcon(IconRepository.getIcon("volmute.png"));
     144                SwingMiscManager.setJButtonIcon(muteButton, IconRepository.getIcon("volmute.png"));
    143145                muteButton.setPreferredSize(new Dimension(BUTTON_SIZE, BUTTON_SIZE));
    144146                muteButton.setToolTipText("Toggle mute");
     
    153155               
    154156                soloButton = new JToggleButton();
    155                 soloButton.setIcon(IconRepository.getIcon("solo.png"));
    156                 soloButton.setSelectedIcon(IconRepository.getIcon("soloon.png"));
     157                SwingMiscManager.setJButtonIcon(soloButton, IconRepository.getIcon("solo.png"));
     158                SwingMiscManager.setJButtonSelectedIcon(soloButton, IconRepository.getIcon("soloon.png"));
    157159                soloButton.setPreferredSize(new Dimension(BUTTON_SIZE, BUTTON_SIZE));
    158160                soloButton.setToolTipText("Toggle solo");
     
    170172                closeButton = new JButton();
    171173                closeButton.addActionListener(this);
    172                 closeButton.setIcon(IconRepository.getIcon("close.png"));
     174                SwingMiscManager.setJButtonIcon(closeButton, IconRepository.getIcon("close.png"));
    173175                closeButton.setPreferredSize(new Dimension(BUTTON_SIZE, BUTTON_SIZE));
    174176                closeButton.setToolTipText("Close");
     
    216218                nameLabelParent = new JPanel();
    217219               
    218                 nameLabelParent.addMouseListener(new MouseListener() {
    219 
    220                         public void mouseClicked(MouseEvent e) {
    221                                 if (nameLabel != null) {
    222                                         if (nameLabel.onMouseClicked(e)) {
    223                                                 e.consume();
    224                                                 return;
    225                                         }
    226                                 }
    227                         }
    228 
    229                         public void mouseEntered(MouseEvent e) {
    230                         }
    231 
    232                         public void mouseExited(MouseEvent e) {
    233                         }
    234 
    235                         public void mousePressed(MouseEvent e) {
    236                                 if (nameLabel != null) {
    237                                         if (nameLabel.onMousePressed(e)) {
    238                                                 e.consume();
    239                                         }
    240                                 }
    241                         }
    242 
    243                         public void mouseReleased(MouseEvent e) {
    244                                 if (nameLabel != null) {
    245                                         if (nameLabel.onMouseReleased(e)) {
    246                                                 e.consume();
    247                                         }
    248                                 }
    249                         }
    250                
    251                 });
    252                
    253                 nameLabelParent.addMouseMotionListener(new MouseMotionListener() {
    254 
    255                         public void mouseDragged(MouseEvent e) {
    256                                 if (nameLabel != null) {
    257                                         if (nameLabel.onMouseDragged(e)) {
    258                                                 e.consume();
    259                                         }
    260                                 }
    261                         }
    262 
    263                         public void mouseMoved(MouseEvent e) {
    264                                 if (nameLabel != null) {
    265                                         nameLabel.onMouseMoved(e, nameLabelParent);
    266                                 }
    267                         }
    268 
    269                 });
    270                
    271                 nameLabelParent.addKeyListener(new KeyListener() {
    272 
    273                         public void keyPressed(KeyEvent e) {
    274                                 if (nameLabel != null) {
    275                                         if (nameLabel.onKeyPressed(e, nameLabelParent)) {
    276                                                 e.consume();
    277                                         }
    278                                 }
    279                         }
    280 
    281                         public void keyReleased(KeyEvent e) {
    282                                 if (nameLabel != null) {
    283                                         if (nameLabel.onKeyReleased(e, nameLabelParent)) {
    284                                                 e.consume();
    285                                         }
    286                                 }
    287 
    288                         }
    289 
    290                         public void keyTyped(KeyEvent e) {
    291                         }
    292                        
    293                 });
    294                
    295                 nameLabel = new EmulatedTextItem(nameLabelParent, new Point(10, 25));
    296                 nameLabel.setFontStyle(Font.BOLD);
     220                nameLabel = new EmulatedTextItem(trackModel.getName(), SwingConversions.fromSwingPoint(new Point(10, 25)));
     221                nameLabel.setFontStyle(SwingConversions.fromSwingFontStyle(Font.BOLD));
    297222                nameLabel.setFontSize(16);
    298                 nameLabel.setBackgroundColor(Color.WHITE);     
    299                 nameLabel.setText(trackModel.getName());
     223                nameLabel.setBackgroundColor(Colour.WHITE);
     224                nameLabel.gainFocus();
    300225
    301226                nameLabel.addTextChangeListener(new TextChangeListener() { //  a little bit loopy!
     
    373298                toolBarPanel.add(closeButton, c);
    374299               
    375                 this.add(toolBarPanel, BorderLayout.NORTH);
    376                 this.add(splitPane, BorderLayout.CENTER);
     300                panel.add(toolBarPanel, BorderLayout.NORTH);
     301                panel.add(splitPane, BorderLayout.CENTER);
    377302               
    378303                // Observe track model
     
    430355                ExpandedTrackManager.getInstance().receiveExpandedTrackPopup(xtp);
    431356        }
    432 
     357       
    433358        @Override
    434         public void onShowing() {
    435 
    436         }
    437        
    438         @Override
    439         public void onShow() {
    440                
     359        public void onShow()
     360        {
    441361                if (splitPane.getHeight() < 140) {
    442362                        splitPane.setDividerLocation(splitPane.getHeight() - 30);
     
    456376                // Invalidate full frame for shading
    457377                if (Browser._theBrowser != null) {
    458                         FrameGraphics.refresh(false);
     378                        DisplayController.requestRefresh(false);
    459379                }
    460380        }
    461381
    462382        @Override
    463         public void onHide() {
     383        public void onHide()
     384        {
    464385                ExpandedTrackManager.getInstance().expandedTrackPopupHidden(this);
    465386                releaseMemory(); // get rid of buffer etc..
     
    470391                // Invalidate full frame for shading
    471392                if (Browser._theBrowser != null) {
    472                         FrameGraphics.refresh(false);
     393                        DisplayController.requestRefresh(false);
    473394                }
    474395        }
    475396       
    476        
    477 
    478 
    479397        @Override
    480         public void paint(Graphics g) {
    481                 super.paint(g);
    482                
    483                 g.translate(-getX(), -getY());
    484                 nameLabel.paint(g);
    485                 g.translate(getX(), getY());
    486                
    487         }
    488 
    489         public void actionPerformed(ActionEvent e) {
     398        public void paintInternal()
     399        {
     400                Graphics2D g = SwingMiscManager.getIfUsingSwingGraphicsManager().getCurrentSurface();
     401               
     402                panel.paint(g);
     403               
     404                g.translate(-getFullBounds().getMinX(), -getFullBounds().getMinY());
     405                nameLabel.paint();
     406                g.translate(getFullBounds().getMinX(), getFullBounds().getMinY());
     407        }
     408
     409        public void actionPerformed(ActionEvent e)
     410        {
    490411                if (trackModel == null) return;
    491412               
     
    587508                        // If there are more expanded tracks showing then the ExpandedTrackManager
    588509                        // will automatically re-layout the remaing views.
    589                         PopupManager.getInstance().hidePopup(this,
    590                                         PopupManager.getInstance().new ExpandShrinkAnimator(
    591                                         new Rectangle(0, getY(), 1, getHeight()),
    592                                                         Color.LIGHT_GRAY));
     510                        hide();
    593511                       
    594512                }
     
    660578                        stopButton.setEnabled(true);
    661579                        rewindButton.setEnabled(false);
    662                         playPauseButton.setIcon(IconRepository.getIcon("pause.png"));
     580                        SwingMiscManager.setJButtonIcon(playPauseButton, IconRepository.getIcon("pause.png"));
    663581
    664582                        setBorderThickness(TrackWidgetCommons.PLAYING_TRACK_EDGE_THICKNESS);
     
    670588                        rewindButton.setEnabled(true);
    671589                        stopButton.setEnabled(false);
    672                         playPauseButton.setIcon(IconRepository.getIcon("play.png"));
     590                        SwingMiscManager.setJButtonIcon(playPauseButton, IconRepository.getIcon("play.png"));
    673591                       
    674592                        // Note:
     
    810728               
    811729                // Get border color currently used
    812                 Color oldC = getBorderColor();
    813                
    814                 Color newC = TrackWidgetCommons.getBorderColor(
     730                Colour oldC = getBorderColor();
     731               
     732                Colour newC = TrackWidgetCommons.getBorderColor(
    815733                                SoundDesk.getInstance().isSolo(trackMix.getChannelID()),
    816734                                trackMix.isMuted());
     
    828746        private void updateButtonGUI() {
    829747               
    830                 Icon newIcon = null;
     748                Image newIcon = null;
    831749                if (volumeSlider.getValue() <= 25)
    832750                                newIcon = IconRepository.getIcon("vol25.png");
     
    838756                                newIcon = IconRepository.getIcon("vol100.png");
    839757               
    840                 muteButton.setIcon(newIcon);
     758                SwingMiscManager.setJButtonIcon(muteButton, newIcon);
    841759        }
    842760
     
    846764         *              Never null.
    847765         */
    848         public String getTrackSourceFrameName() {
     766        public String getTrackSourceFrameName()
     767        {
    849768                return trackSourceFrameName;
    850769        }
    851770       
     771        public void setBounds(int x, int y, int width, int height)
     772        {
     773                panel.setBounds(x, y, width, height);
     774        }
     775
     776        @Override
     777        public AxisAlignedBoxBounds getFullBounds()
     778        {
     779                return SwingConversions.fromSwingRectangle(panel.getBounds());
     780        }
     781       
    852782       
    853783}
  • trunk/src/org/apollo/gui/FastAlphaEffect.java

    r315 r1102  
    6060                        int x, int y,
    6161                        int width, int height,
    62                         int rgb) {
     62                        int rgb)
     63        {
    6364               
    64                 if (raster == null)
     65                if (raster == null) {
    6566                        throw new NullPointerException("raster");
    66                 else if (colorModel == null)
     67                } else if (colorModel == null) {
    6768                        throw new NullPointerException("raster");
     69                }
    6870               
    6971                int endcol = x + width;
  • trunk/src/org/apollo/gui/FrameLayoutDaemon.java

    r1061 r1102  
    11package org.apollo.gui;
    22
    3 import java.awt.Point;
    4 import java.awt.event.ComponentEvent;
    5 import java.awt.event.ComponentListener;
    6 import java.awt.event.MouseEvent;
    73import java.io.File;
    8 import java.lang.reflect.InvocationTargetException;
    94import java.util.Collection;
    105import java.util.HashMap;
    116import java.util.Map;
    12 
    13 import javax.swing.SwingUtilities;
    147
    158import org.apollo.audio.ApolloSubjectChangedEvent;
     
    3023import org.apollo.widgets.LinkedTrack;
    3124import org.apollo.widgets.SampledTrack;
    32 import org.expeditee.gui.Browser;
    33 import org.expeditee.gui.DisplayIO;
    34 import org.expeditee.gui.DisplayIOObserver;
     25import org.expeditee.core.Point;
     26import org.expeditee.gio.EcosystemManager;
     27import org.expeditee.gio.InputManager.WindowEventListener;
     28import org.expeditee.gio.InputManager.WindowEventType;
     29import org.expeditee.gio.gesture.StandardGestureActions;
     30import org.expeditee.gui.DisplayController;
     31import org.expeditee.gui.DisplayObserver;
    3532import org.expeditee.gui.Frame;
    36 import org.expeditee.gui.FrameMouseActions;
    3733import org.expeditee.gui.FreeItems;
    38 import org.expeditee.gui.MouseEventRouter;
    3934import org.expeditee.items.Item;
    4035import org.expeditee.items.ItemUtils;
    41 import org.expeditee.items.widgets.InteractiveWidget;
     36import org.expeditee.items.widgets.Widget;
    4237import org.expeditee.items.widgets.WidgetCorner;
    4338import org.expeditee.items.widgets.WidgetEdge;
     
    4641 * A daemon that lays out overdubbed frames.
    4742 *
    48  * It is a singletone. Also it is a subject which raises empty events whenever
     43 * It is a singleton. Also it is a subject which raises empty events whenever
    4944 * a new timeline is created.
    5045 *
     
    5247 *
    5348 */
    54 public class FrameLayoutDaemon extends AbstractSubject implements Observer, DisplayIOObserver {
     49public class FrameLayoutDaemon extends AbstractSubject implements Observer, DisplayObserver {
    5550       
    5651        /** The frame that should not be layout out at any point in time. */
     
    9893                daemon.start();
    9994                AudioStructureModel.getInstance().addObserver(this);
    100                 DisplayIO.addDisplayIOObserver(this);
    101                
    102                 // Listen for resize events
    103                 SwingUtilities.invokeLater(new Runnable() {
    104                         public void run() {
    105 
    106                                 // Keep expanded view centered to the browser window
    107                                 if (Browser._theBrowser != null) {
    108                                         Browser._theBrowser.addComponentListener(new ComponentListener() {
    109 
    110                                                 public void componentHidden(ComponentEvent e) {
    111                                                 }
    112 
    113                                                 public void componentMoved(ComponentEvent e) {
    114                                                 }
    115 
    116                                                 public void componentResized(ComponentEvent e) {
    117                                                         forceRecheck();
    118                                                 }
    119 
    120                                                 public void componentShown(ComponentEvent e) {
    121                                                 }
    122                                                
    123                                         });
    124                                 }
    125                                
     95                DisplayController.addDisplayObserver(this);
     96               
     97                EcosystemManager.getInputManager().addWindowEventListener(new WindowEventListener()
     98                {
     99                        @Override
     100                        public void onWindowEvent(WindowEventType type)
     101                        {
     102                                if (type == WindowEventType.WINDOW_RESIZED) forceRecheck();
    126103                        }
    127104                });
     
    321298                                // Note that accessing expeditee model in another thread --
    322299                                // Being real careful not to do anything unsafe
    323                                 Frame currentFrame = DisplayIO.getCurrentFrame();
     300                                Frame currentFrame = DisplayController.getCurrentFrame();
    324301                                if (currentFrame == null) continue;
    325302
     
    340317                               
    341318                                try {
    342                                         SwingUtilities.invokeAndWait(trackFormatter);
    343                                 } catch (InterruptedException e) {
     319                                        EcosystemManager.getMiscManager().runOnGIOThread(trackFormatter);
     320                                } catch (Throwable e) {
    344321                                        e.printStackTrace();
    345                                 } catch (InvocationTargetException e) {
    346                                         e.printStackTrace();
    347322                                }
    348323                               
     
    359334                                assert(toFormat != null);
    360335                               
    361                                 // To late?
    362                                 if (toFormat != DisplayIO.getCurrentFrame()) return;
     336                                // Too late?
     337                                if (toFormat != DisplayController.getCurrentFrame()) return;
    363338                               
    364339                                boolean supressSpatialLayout = suspendedFrame == toFormat;
     
    370345                                boolean hasRunningTime = false; // A flag set to true if there is actual audio to [lay
    371346                               
    372                                 Map<InteractiveWidget, AbstractTrackGraphNode> widgetsToFormat = new HashMap<InteractiveWidget, AbstractTrackGraphNode>();
    373        
    374                                 for (InteractiveWidget iw : toFormat.getInteractiveWidgets()) {
     347                                Map<Widget, AbstractTrackGraphNode> widgetsToFormat = new HashMap<Widget, AbstractTrackGraphNode>();
     348       
     349                                for (Widget iw : toFormat.getInteractiveWidgets()) {
    375350                                       
    376351                                        AbstractTrackGraphNode abinf = null;
     
    429404                               
    430405                                // Anything to format?
    431                                 if (!hasRunningTime ||
    432                                                 widgetsToFormat.isEmpty() ||
    433                                                 longestEndTime == firstInitiationTime) {
     406                                if (!hasRunningTime || widgetsToFormat.isEmpty() || longestEndTime == firstInitiationTime) {
    434407                                       
    435408                                        // NOTE: longestEndTime == firstInitiationTime indicates linked tracks
     
    450423                                        // Ensure that left most pixel is at a reasonable position
    451424                                        if (!supressSpatialLayout && (initiationXPixel < 0 ||
    452                                                         (initiationXPixel > Browser._theBrowser.getWidth() && Browser._theBrowser.getWidth() > leftMargin))) {
     425                                                        (initiationXPixel > DisplayController.getFramePaintArea().getWidth() && DisplayController.getFramePaintArea().getWidth() > leftMargin))) {
    453426                                                initiationXPixel = leftMargin;
    454427                                        } else if (!supressSpatialLayout && initiationXPixel > LAYOUT_MAX_INITIATION_PIXEL) {
     
    459432                                                timelineWidth = rightMostPixel - initiationXPixel;
    460433                                        } else {
    461                                                 timelineWidth = Browser._theBrowser.getWidth() - initiationXPixel - rightMargin;
     434                                                timelineWidth = DisplayController.getFramePaintArea().getWidth() - initiationXPixel - rightMargin;
    462435                                        }
    463436                                       
     
    483456                                if (!supressSpatialLayout) {
    484457                                       
    485                                         for (InteractiveWidget iw : widgetsToFormat.keySet()) {
     458                                        for (Widget iw : widgetsToFormat.keySet()) {
    486459                                               
    487460                                                AbstractTrackGraphNode atgi = widgetsToFormat.get(iw);
     
    545518                       
    546519                                Item i = FreeItems.getItemAttachedToCursor();
    547                                 InteractiveWidget freespaceTrackToFormat = null;
     520                                Widget freespaceTrackToFormat = null;
    548521                                if (i != null && i instanceof WidgetEdge) {
    549522                                        freespaceTrackToFormat = ((WidgetEdge)i).getWidgetSource();
     
    573546                                        if (width > 0) {
    574547                                               
    575                                                 if (width > (Browser._theBrowser.getWidth() - (2 * FREE_SPACE_MARGINS)))
    576                                                         width = Browser._theBrowser.getWidth() - (2 * FREE_SPACE_MARGINS);
     548                                                if (width > (DisplayController.getFramePaintArea().getWidth() - (2 * FREE_SPACE_MARGINS))) {
     549                                                        width = DisplayController.getFramePaintArea().getWidth() - (2 * FREE_SPACE_MARGINS);
     550                                                }
    577551
    578552                                                freespaceTrackToFormat.setSize(
     
    582556                                               
    583557                                                // Keep the floating track on the cursor
    584                                                 MouseEvent me = MouseEventRouter.getCurrentMouseEvent();
    585                                                 Point containerPoint = SwingUtilities.convertPoint(me.getComponent(), me.getPoint(), Browser._theBrowser.getContentPane());
    586                                                
     558                                                Point containerPoint = EcosystemManager.getInputManager().getCursorPosition();
     559                                               
     560                                                // If due to resize the track is not longer over the cursor then just center it.
    587561                                                if (!ItemUtils.expandRectangle(freespaceTrackToFormat.getBounds(), 20).contains(containerPoint)) {
    588                                                         // If due to resize the track is not longer over the cursor then just center it.
    589562                                                        int offsetX = width / 2;
    590563                                                        int offsetY = freespaceTrackToFormat.getHeight() / 2;
    591                                                         freespaceTrackToFormat.setPosition(
    592                                                                         containerPoint.x - offsetX,
    593                                                                         containerPoint.y - offsetY);
    594                                                         FrameMouseActions.resetOffset();
    595                
     564                                                        freespaceTrackToFormat.setPosition(containerPoint.x - offsetX, containerPoint.y - offsetY);
     565                                                        StandardGestureActions.resetOffset();
    596566                                                }
    597567                                               
     
    756726
    757727                // Look for all track widgets
    758                 for (InteractiveWidget iw : frame.getInteractiveWidgets()) {
     728                for (Widget iw : frame.getInteractiveWidgets()) {
    759729                       
    760730                        if (iw instanceof SampledTrack) {
     
    928898        public static long inferCurrentTotalMSTime() {
    929899               
    930                 Frame currentFrame = DisplayIO.getCurrentFrame();
     900                Frame currentFrame = DisplayController.getCurrentFrame();
    931901                String currentFrameName = (currentFrame != null) ? currentFrame.getName() : null;
    932902               
  • trunk/src/org/apollo/gui/FramePlaybackBarRenderer.java

    r372 r1102  
    11package org.apollo.gui;
    22
    3 import java.awt.BasicStroke;
    4 import java.awt.Color;
    5 import java.awt.Graphics2D;
    6 import java.awt.Rectangle;
    7 import java.awt.Stroke;
    83import java.util.LinkedList;
    94import java.util.List;
    10 
    11 import javax.swing.SwingUtilities;
    125
    136import org.apollo.audio.ApolloPlaybackMixer;
     
    2316import org.apollo.util.AudioMath;
    2417import org.apollo.widgets.FramePlayer;
     18import org.expeditee.core.Colour;
     19import org.expeditee.core.Stroke;
     20import org.expeditee.core.bounds.AxisAlignedBoxBounds;
     21import org.expeditee.gio.EcosystemManager;
     22import org.expeditee.gio.GraphicsManager;
    2523import org.expeditee.gui.Browser;
    26 import org.expeditee.gui.DisplayIO;
     24import org.expeditee.gui.DisplayController;
    2725import org.expeditee.gui.Frame;
    28 import org.expeditee.gui.FrameGraphics;
    2926
    3027/**
     
    5047       
    5148        private static final int BAR_STROKE_THICKNESS = 2;
    52         private static final Stroke BAR_STROKE = new BasicStroke(BAR_STROKE_THICKNESS);
    53         private static final Color BAR_COLOR = Color.DARK_GRAY;
     49        private static final Stroke BAR_STROKE = new Stroke(BAR_STROKE_THICKNESS);
     50        private static final Colour BAR_COLOR = Colour.DARK_GREY;
    5451       
    5552        private static FramePlaybackBarRenderer instance = new FramePlaybackBarRenderer();
     
    121118                        }
    122119                       
    123                         FrameGraphics.refresh(true);
     120                        DisplayController.requestRefresh(true);
    124121                       
    125122                       
     
    132129                        currentMSPosition = -1;
    133130                        pixelPositions.clear();
    134                         FrameGraphics.refresh(true);
     131                        DisplayController.requestRefresh(true);
    135132                       
    136133                        break;
     
    140137        }
    141138       
    142         private void invalidate() {
     139        private void invalidate()
     140        {
    143141                if (Browser._theBrowser == null) return;
    144142               
    145                 int height = Browser._theBrowser.getHeight();
     143                int height = EcosystemManager.getGraphicsManager().getWindowSize().getHeight();
    146144               
    147145                for (Integer n : pixelPositions) {
    148                         FrameGraphics.invalidateArea(new Rectangle(n - 1, 0, BAR_STROKE_THICKNESS + 2, height));
    149                 }
    150         }
    151        
    152         public void paint(Graphics2D g) {
     146                        DisplayController.invalidateArea(new AxisAlignedBoxBounds(n - 1, 0, BAR_STROKE_THICKNESS + 2, height));
     147                }
     148        }
     149       
     150        public void paint()
     151        {
    153152                if (Browser._theBrowser == null) return;
    154153               
    155                 Frame currentFrame = DisplayIO.getCurrentFrame();
     154                Frame currentFrame = DisplayController.getCurrentFrame();
    156155               
    157156                if (currentFrame == null || currentFrame.getName() == null || pixelPositionsParent == null ||
    158157                                !currentFrame.getName().equals(pixelPositionsParent)) return;
    159158               
    160                 int height = Browser._theBrowser.getHeight();
    161                
    162                 g.setColor(BAR_COLOR);
    163                 g.setStroke(BAR_STROKE);
     159                int height = EcosystemManager.getGraphicsManager().getWindowSize().getHeight();
     160               
     161                GraphicsManager gm = EcosystemManager.getGraphicsManager();
    164162               
    165163                for (Integer n : pixelPositions) {
    166                         g.drawLine(n, 0, n, height);
     164                        gm.drawLine(n, 0, n, height, BAR_COLOR, BAR_STROKE);
    167165                }
    168166        }
     
    193191                // Notes: the clock will queue a refresh for the frame after this
    194192                // event proccesses ...
    195                 SwingUtilities.invokeLater(updator);
     193                EcosystemManager.getMiscManager().runOnGIOThread(updator);
    196194        }
    197195       
     
    201199         * @author Brook Novak
    202200         */
    203         private class PlaybackFrameBarUpdator implements Runnable {
     201        private class PlaybackFrameBarUpdator implements Runnable
     202        {
    204203                public void run() {
    205204                       
    206205                        if (currentMSPosition == -1 || currentTimeline == null) return;
    207206                       
    208                         Frame currentFrame = DisplayIO.getCurrentFrame();
     207                        Frame currentFrame = DisplayController.getCurrentFrame();
    209208                       
    210209                        if (currentFrame == null || currentFrame.getName() == null) return;
  • trunk/src/org/apollo/gui/FrameRenderPasses.java

    r355 r1102  
    11package org.apollo.gui;
    22
    3 import java.awt.Color;
    4 import java.awt.FontMetrics;
    5 import java.awt.Graphics;
    6 import java.awt.Graphics2D;
    7 import java.awt.Rectangle;
    8 import java.awt.Stroke;
    9 import java.awt.geom.Area;
    10 import java.awt.geom.Rectangle2D;
    113import java.util.LinkedList;
    124
    13 import org.apollo.AudioFrameKeyboardActions;
    14 import org.apollo.AudioFrameMouseActions;
     5import org.apollo.ApolloGestureActions;
    156import org.apollo.audio.util.Timeline;
    167import org.apollo.items.FramePlaybackLauncher;
     
    1910import org.apollo.widgets.LinkedTrack;
    2011import org.apollo.widgets.SampledTrack;
     12import org.expeditee.core.Clip;
     13import org.expeditee.core.Colour;
     14import org.expeditee.core.Dimension;
     15import org.expeditee.core.Fill;
     16import org.expeditee.core.Point;
     17import org.expeditee.core.Stroke;
     18import org.expeditee.core.TextLayout;
     19import org.expeditee.core.bounds.AxisAlignedBoxBounds;
     20import org.expeditee.gio.EcosystemManager;
     21import org.expeditee.gio.GraphicsManager;
     22import org.expeditee.gio.gesture.StandardGestureActions;
     23import org.expeditee.gio.input.KBMInputEvent.Key;
     24import org.expeditee.gio.input.StandardInputEventListeners;
    2125import org.expeditee.gui.Browser;
    2226import org.expeditee.gui.FrameGraphics;
    23 import org.expeditee.gui.FrameMouseActions;
    2427import org.expeditee.gui.FreeItems;
    2528import org.expeditee.gui.FrameGraphics.FrameRenderPass;
    2629import org.expeditee.items.Item;
    27 import org.expeditee.items.widgets.InteractiveWidget;
     30import org.expeditee.items.widgets.Widget;
    2831import org.expeditee.items.widgets.WidgetCorner;
    2932import org.expeditee.items.widgets.WidgetEdge;
     
    3134/**
    3235 * All final effects rendered here - to give extra feedback to the user and simply to make
    33  * it more apealing.
     36 * it more appealing.
    3437 * @author Brook Novak
    3538 *
     
    3740public class FrameRenderPasses implements FrameRenderPass {
    3841       
    39         private static final Color SHADED_EXPANDED_BACKING_COLOR = new Color(80, 80, 80, 140);
    40         private static final Color Y_HELPER_LINES_COLOR = Color.DARK_GRAY;
     42        private static final Colour SHADED_EXPANDED_BACKING_COLOR = Colour.FromRGBA255(80, 80, 80, 140);
     43        private static final Colour Y_HELPER_LINES_COLOR = Colour.DARK_GREY;
    4144        private static final Stroke Y_HELPER_LINES_STROKE = OverdubbedFrameTimeAxis.TRACK_TIMELINE_STROKE;
    4245       
     
    4851        private boolean shouldDrawFullscreenHelpers = false;
    4952       
    50         private FrameRenderPasses() {
     53        private FrameRenderPasses()
     54        {
    5155                FrameGraphics.addFrameRenderPass(this);
    5256        }
    5357       
    54         public static FrameRenderPasses getInstance() {
     58        public static FrameRenderPasses getInstance()
     59        {
    5560                return instance;
    5661        }
    5762
    58         public void paintFinalPass(Graphics g) {
     63        public void paintFinalPass()
     64        {
    5965                if (Browser._theBrowser == null) return;
    60                 int frameHeight = Browser._theBrowser.getContentPane().getHeight();
     66               
     67                GraphicsManager gm = EcosystemManager.getGraphicsManager();
     68               
     69                int frameHeight = EcosystemManager.getGraphicsManager().getWindowSize().getHeight();
    6170                if (ExpandedTrackManager.getInstance().isAnyExpandedTrackVisible()
    6271                                && !FreeItems.getInstance().isEmpty()) {
     
    6776                        for (Item i : FreeItems.getInstance()) {
    6877                                if (i instanceof WidgetCorner) {
    69                                         InteractiveWidget iw = ((WidgetCorner)i).getWidgetSource();
     78                                        Widget iw = ((WidgetCorner)i).getWidgetSource();
    7079                                       
    7180                                        if (iw != null && iw instanceof SampledTrack) {
     
    8493                        if (toPaint != null) {
    8594                                for (SampledTrack trackWidget : toPaint) {
    86                                         if (g.getClip() == null
    87                                                         || g.getClip().intersects(trackWidget.getComponant().getBounds()))
    88                                         trackWidget.paintInFreeSpace(g, true);
    89                                        
     95                                        if (gm.peekClip() == null || gm.peekClip().isNotClipped() || (!gm.peekClip().isFullyClipped() && gm.peekClip().getBounds().intersects(trackWidget.getBounds()))) {
     96                                                trackWidget.paintInFreeSpace(true);
     97                                        }
    9098                                }
    9199                        }
     
    93101                }
    94102               
    95                 OverdubbedFrameTimeAxis.getInstance().paint(g);
     103                OverdubbedFrameTimeAxis.getInstance().paint();
    96104               
    97105                TimeAxis timeAxis = OverdubbedFrameTimeAxis.getInstance().getTimeAxis();       
    98106                Timeline lastTimeline = OverdubbedFrameTimeAxis.getInstance().getLastTimeline();
    99107               
    100                 FramePlaybackBarRenderer.getInstance().paint((Graphics2D)g);
     108                FramePlaybackBarRenderer.getInstance().paint();
    101109
    102110                if (timeHelperLinesToPaint != null && timeAxis != null && lastTimeline != null) {
    103111
    104                         Rectangle r = OverdubbedFrameTimeAxis.getInstance().getCurrentTimelineArea();
     112                        AxisAlignedBoxBounds r = OverdubbedFrameTimeAxis.getInstance().getCurrentTimelineArea();
    105113                       
    106114                        // Draw helper bar and text
    107115                        for (Integer x : timeHelperLinesToPaint) {
    108116                               
    109                                 ((Graphics2D)g).setStroke(OverdubbedFrameTimeAxis.TRACK_TIMELINE_STROKE);
    110                                 g.setColor(Color.RED);
    111                                
    112                                 if (shouldDrawFullscreenHelpers)
    113                                         g.drawLine(x, 0, x, frameHeight);
    114                                 else
    115                                         g.drawLine(x, r.y, x, r.y + r.height);
    116                                                                        
     117                                if (shouldDrawFullscreenHelpers) {
     118                                        gm.drawLine(new Point(x, 0), new Point(x, frameHeight), Colour.RED, OverdubbedFrameTimeAxis.TRACK_TIMELINE_STROKE);
     119                                } else {
     120                                        gm.drawLine(new Point(x, r.getMinY()), new Point(x, r.getMinY() + r.getHeight()), Colour.RED, OverdubbedFrameTimeAxis.TRACK_TIMELINE_STROKE);
     121                                }
     122                               
    117123                                long ms = lastTimeline.getMSTimeAtX(x) - lastTimeline.getFirstInitiationTime();
    118124
     
    120126                                if (ms < 0) label = "-" + label;
    121127                               
    122                                 FontMetrics fm   = g.getFontMetrics(SampledTrackGraphViewPort.TIME_HELPER_FONT);
    123                                 Rectangle2D rect = fm.getStringBounds(label, g);
     128                                //FontMetrics fm   = g.getFontMetrics(SampledTrackGraphViewPort.TIME_HELPER_FONT);
     129                                //Rectangle2D rect = fm.getStringBounds(label, g);
     130                                TextLayout layout = EcosystemManager.getTextLayoutManager().layoutStringSimple(label, SampledTrackGraphViewPort.TIME_HELPER_FONT);
     131                                AxisAlignedBoxBounds rect = layout.getPixelBounds(0, 0);
    124132                                int labelWidth  = (int)(rect.getWidth());
    125133                                int labelHeight  = (int)(rect.getHeight());
    126134                               
    127                                 int y = r.y + (r.height / 2) - ((labelHeight + 4) / 2);
    128                                
    129 
    130                                 g.setColor(SampledTrackGraphViewPort.TIME_HELPER_COLOR);
    131                                 g.fillRect(x + 2,  y, labelWidth + 3, labelHeight + 4);
    132        
    133                                 g.setColor(SampledTrackGraphViewPort.TIME_HELPER_BORDERCOLOR);
    134                                 ((Graphics2D)g).setStroke(SampledTrackGraphViewPort.ZOOM_BACKING_BORDER_STROKE);
    135                                 g.fillRect(x + 2,  y, labelWidth + 3, labelHeight + 4);
    136 
    137                                 g.setFont(SampledTrackGraphViewPort.TIME_HELPER_FONT);
    138                                 g.setColor(Color.BLACK);
    139                                 g.drawString(label, x + 4, y + labelHeight);
    140                                
    141                                
     135                                int y = r.getMinY() + (r.getHeight() / 2) - ((labelHeight + 4) / 2);
     136                               
     137                                gm.drawRectangle(new Point(x + 2,  y), new Dimension(labelWidth + 3, labelHeight + 4), 0.0, new Fill(SampledTrackGraphViewPort.TIME_HELPER_COLOR), SampledTrackGraphViewPort.TIME_HELPER_BORDERCOLOR, SampledTrackGraphViewPort.ZOOM_BACKING_BORDER_STROKE, null);
     138
     139                                gm.drawTextLayout(layout, new Point(x + 4, y + labelHeight), Colour.BLACK);
    142140                        }
    143141               
     
    146144//               Draw Y helper
    147145                if (yAxisTimelineHelperToPaint != null) {
    148 
    149                         ((Graphics2D)g).setStroke(Y_HELPER_LINES_STROKE);
    150                         g.setColor(Y_HELPER_LINES_COLOR);
    151 
    152                         g.drawLine(
    153                                         0,
    154                                         yAxisTimelineHelperToPaint.value,
    155                                         Browser._theBrowser.getContentPane().getWidth(),
    156                                         yAxisTimelineHelperToPaint.value);
    157                        
    158                 }
    159                
    160        
    161         }
    162 
    163         public void paintPreLayeredPanePass(Graphics g) {
     146                        gm.drawLine(0, yAxisTimelineHelperToPaint.value, EcosystemManager.getGraphicsManager().getWindowSize().getWidth(), yAxisTimelineHelperToPaint.value, Y_HELPER_LINES_COLOR, Y_HELPER_LINES_STROKE);
     147                }
     148               
     149       
     150        }
     151
     152        public void paintPreLayeredPanePass()
     153        {
    164154                if (Browser._theBrowser == null) return;
    165155               
    166156                if (ExpandedTrackManager.getInstance().isAnyExpandedTrackVisible()) {
    167                        
    168                         g.setColor(SHADED_EXPANDED_BACKING_COLOR);
    169                         g.fillRect(0, 0,
    170                                         Browser._theBrowser.getContentPane().getWidth(),
    171                                         Browser._theBrowser.getContentPane().getHeight());
    172                 }
    173                
    174         }
    175 
    176         public Area paintStarted(Area currentClip) {
     157                        Dimension windowSize = EcosystemManager.getGraphicsManager().getWindowSize();
     158                        EcosystemManager.getGraphicsManager().drawRectangle(Point.ORIGIN, windowSize, 0.0, new Fill(SHADED_EXPANDED_BACKING_COLOR), null, null, null);
     159                }
     160               
     161        }
     162
     163        public Clip paintStarted(Clip currentClip)
     164        {
    177165                if (Browser._theBrowser == null) return currentClip;
    178166
    179                 LinkedList<InteractiveWidget> seen = null;
     167                LinkedList<Widget> seen = null;
    180168               
    181169                //boolean idDirty = false;
     
    189177                timeHelperLinesToPaint = null;
    190178                yAxisTimelineHelperToPaint = null;
    191                 shouldDrawFullscreenHelpers = AudioFrameKeyboardActions.isControlDown() ||
    192                         (AudioFrameKeyboardActions.isShiftDown() && !FreeItems.getInstance().isEmpty());
     179                shouldDrawFullscreenHelpers = StandardInputEventListeners.kbmStateListener.isKeyDown(Key.CTRL) ||
     180                        (StandardInputEventListeners.kbmStateListener.isKeyDown(Key.SHIFT) && !FreeItems.getInstance().isEmpty());
    193181
    194182                // Get free tracks and paint line helpers
    195                 if (!FreeItems.getInstance().isEmpty() || FrameMouseActions.getlastHighlightedItem() != null) {
     183                if (!FreeItems.getInstance().isEmpty() || StandardGestureActions.getlastHighlightedItem() != null) {
    196184
    197185                        LinkedList<Item> possibles = new LinkedList<Item>(FreeItems.getInstance());
    198                         if (FreeItems.getInstance().isEmpty() &&
    199                                         FrameMouseActions.getlastHighlightedItem() != null)
    200                                 possibles.add(FrameMouseActions.getlastHighlightedItem());
     186                        if (FreeItems.getInstance().isEmpty() && StandardGestureActions.getlastHighlightedItem() != null) {
     187                                possibles.add(StandardGestureActions.getlastHighlightedItem());
     188                        }
    201189                       
    202190                        for (Item i : possibles) {
    203191                               
    204                                 InteractiveWidget iw = null;
     192                                Widget iw = null;
    205193                               
    206194                                if (i instanceof WidgetCorner) {
     
    216204                                               
    217205                                                if (seen == null) {
    218                                                         seen = new LinkedList<InteractiveWidget>();
     206                                                        seen = new LinkedList<Widget>();
    219207                                                } else if (seen.contains(iw)) {
    220208                                                        continue;
     
    235223                }
    236224               
    237                 if ((AudioFrameMouseActions.isYAxisRestictionOn() || AudioFrameMouseActions.isSnapOn())
     225                if ((ApolloGestureActions.isYAxisRestictionOn() || ApolloGestureActions.isSnapOn())
    238226                        && !FreeItems.getInstance().isEmpty()) {
    239227                       
     
    255243        }
    256244       
    257         private void invalidateHelperLines(Area currentClip) {
    258                 if (currentClip != null) {
    259                        
    260                         if (timeHelperLinesToPaint != null && !timeHelperLinesToPaint.isEmpty()) {
    261                                 currentClip.add(new Area(OverdubbedFrameTimeAxis.getInstance().getCurrentTimelineArea()));
    262                                 if (shouldDrawFullscreenHelpers) {
    263                                         int fsHeight = Browser._theBrowser.getContentPane().getHeight();
    264                                         for (Integer n : timeHelperLinesToPaint) {
    265                                                 currentClip.add(new Area(new Rectangle(n - 1, 0, 3, fsHeight)));
    266                                         }
    267                                 }
    268                         }
    269                        
    270                         if (yAxisTimelineHelperToPaint != null && shouldDrawFullscreenHelpers) {
    271 
    272                                 currentClip.add(new Area(new Rectangle(
    273                                                 0,
    274                                                 yAxisTimelineHelperToPaint.value - 1,
    275                                                 Browser._theBrowser.getContentPane().getWidth(),
    276                                                 3)));
    277                        
    278                         }
    279                 }
    280         }
    281        
    282        
    283        
    284 
     245        private void invalidateHelperLines(Clip currentClip)
     246        {
     247                if (currentClip == null) return;
     248               
     249                if (timeHelperLinesToPaint != null && !timeHelperLinesToPaint.isEmpty()) {
     250                        currentClip.includeBounds(OverdubbedFrameTimeAxis.getInstance().getCurrentTimelineArea().clone());
     251                        if (shouldDrawFullscreenHelpers) {
     252                                int fsHeight = EcosystemManager.getGraphicsManager().getWindowSize().getHeight();
     253                                for (Integer n : timeHelperLinesToPaint) {
     254                                        currentClip.includeBounds(new AxisAlignedBoxBounds(n - 1, 0, 3, fsHeight));
     255                                }
     256                        }
     257                }
     258               
     259                if (yAxisTimelineHelperToPaint != null && shouldDrawFullscreenHelpers) {
     260
     261                        currentClip.includeBounds(new AxisAlignedBoxBounds(
     262                                        0,
     263                                        yAxisTimelineHelperToPaint.value - 1,
     264                                        EcosystemManager.getGraphicsManager().getWindowSize().getWidth(),
     265                                        3));
     266               
     267                }
     268        }
    285269}
  • trunk/src/org/apollo/gui/OverdubbedFrameTimeAxis.java

    r1059 r1102  
    11package org.apollo.gui;
    2 
    3 import java.awt.BasicStroke;
    4 import java.awt.Color;
    5 import java.awt.Graphics;
    6 import java.awt.Graphics2D;
    7 import java.awt.Rectangle;
    8 import java.awt.Stroke;
    9 import java.awt.event.ComponentEvent;
    10 import java.awt.event.ComponentListener;
    11 
    12 import javax.swing.SwingUtilities;
    132
    143import org.apollo.audio.util.Timeline;
     
    165import org.apollo.mvc.Subject;
    176import org.apollo.mvc.SubjectChangedEvent;
     7import org.expeditee.core.Colour;
     8import org.expeditee.core.Dimension;
     9import org.expeditee.core.Fill;
     10import org.expeditee.core.Point;
     11import org.expeditee.core.Stroke;
     12import org.expeditee.core.bounds.AxisAlignedBoxBounds;
     13import org.expeditee.gio.EcosystemManager;
     14import org.expeditee.gio.GraphicsManager;
     15import org.expeditee.gio.InputManager.WindowEventListener;
     16import org.expeditee.gio.InputManager.WindowEventType;
    1817import org.expeditee.gui.Browser;
    19 import org.expeditee.gui.DisplayIO;
    20 import org.expeditee.gui.FrameGraphics;
    21 import org.expeditee.gui.MessageBay;
     18import org.expeditee.gui.DisplayController;
    2219
    2320/**
     
    3027
    3128        private TimeAxis timeAxis = null;
    32         private Rectangle lastInvalidated;
     29        private AxisAlignedBoxBounds lastInvalidated;
    3330        private Timeline lastTimeline = null;
    3431
     
    3633
    3734        private static final int GLOBAL_TIMELINE_HEIGHT = 30;
    38         private static final Color GLOBAL_TIMELINE_BACKCOLOR = new Color(220, 220, 220, 100);
    39         private static final Color GLOBAL_EMPTY_TIMELINE_BACKCOLOR = new Color(240, 240, 240, 100);
     35        private static final Colour GLOBAL_TIMELINE_BACKCOLOR = Colour.FromRGBA255(220, 220, 220, 100);
     36        private static final Colour GLOBAL_EMPTY_TIMELINE_BACKCOLOR = Colour.FromRGBA255(240, 240, 240, 100);
    4037       
    41         public static final Stroke TRACK_TIMELINE_STROKE = new BasicStroke(
    42                         1.0f, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_BEVEL, 0.0f, new float[] { 5.0f, 5.0f }, 0.0f);
     38        public static final Stroke TRACK_TIMELINE_STROKE = new Stroke(1.0f, Stroke.CAP.SQUARE, Stroke.JOIN.BEVEL, new float[] { 5.0f, 5.0f }, 0.0f);
    4339       
    44         private static final Stroke TIMELINE_BORDER_STROKE = new BasicStroke(1.0f);
     40        private static final Stroke TIMELINE_BORDER_STROKE = new Stroke(1.0f);
    4541                       
    4642        /**
     
    5450               
    5551                // Listen for resize events
    56                 SwingUtilities.invokeLater(new Runnable() {
    57                         public void run() {
    58 
    59                                 // Keep expanded view centered to the browser window
    60                                 if (Browser._theBrowser != null) {
    61                                         Browser._theBrowser.addComponentListener(new ComponentListener() {
    62 
    63                                                 public void componentHidden(ComponentEvent e) {
    64                                                 }
    65 
    66                                                 public void componentMoved(ComponentEvent e) {
    67                                                 }
    68 
    69                                                 public void componentResized(ComponentEvent e) {
    70                                                         updateAxis();
    71                                                 }
    72 
    73                                                 public void componentShown(ComponentEvent e) {
    74                                                 }
    75                                                
    76                                         });
    77                                 }
    78                                
     52                EcosystemManager.getInputManager().addWindowEventListener(new WindowEventListener()
     53                {
     54                        @Override
     55                        public void onWindowEvent(WindowEventType type)
     56                        {
     57                                if (type == WindowEventType.WINDOW_RESIZED) updateAxis();
    7958                        }
    8059                });
     
    11392                lastTimeline = FrameLayoutDaemon.getInstance().getLastComputedTimeline();
    11493                if (lastTimeline == null ||
    115                         FrameLayoutDaemon.getInstance().getTimelineOwner() != DisplayIO.getCurrentFrame()) {
     94                        FrameLayoutDaemon.getInstance().getTimelineOwner() != DisplayController.getCurrentFrame()) {
    11695                       
    11796                        // The frame layout daemon only lays out frames once - unless the user rearranges tracks
    11897                        // on a frame then the daemon we re-calc the timeline... thus a timeline must be infferred
    11998                       
    120                         lastTimeline = FrameLayoutDaemon.inferTimeline(DisplayIO.getCurrentFrame());
     99                        lastTimeline = FrameLayoutDaemon.inferTimeline(DisplayController.getCurrentFrame());
    121100                       
    122101                        if (lastTimeline == null) { // no widgets
    123102                                if (timeAxis != null && lastInvalidated != null) {
    124                                         FrameGraphics.invalidateArea(lastInvalidated); // old position
     103                                        DisplayController.invalidateArea(lastInvalidated); // old position
    125104                                }
    126105                               
     
    141120
    142121               
    143                 Rectangle newBounds = getCurrentTimelineArea();
     122                AxisAlignedBoxBounds newBounds = getCurrentTimelineArea();
    144123                if (lastInvalidated != null && !lastInvalidated.equals(newBounds)) {
    145                         FrameGraphics.invalidateArea(lastInvalidated); // old position
     124                        DisplayController.invalidateArea(lastInvalidated); // old position
    146125                }
    147126               
    148                 FrameGraphics.invalidateArea(newBounds);
     127                DisplayController.invalidateArea(newBounds);
    149128               
    150129                lastInvalidated = newBounds;
    151130               
    152                 FrameGraphics.refresh(true);
     131                DisplayController.requestRefresh(true);
    153132               
    154133        }
    155134
    156         public Rectangle getCurrentTimelineArea() {
     135        public AxisAlignedBoxBounds getCurrentTimelineArea()
     136        {
    157137                assert(Browser._theBrowser != null);
    158                 int y = Browser._theBrowser.getContentPane().getHeight() - GLOBAL_TIMELINE_HEIGHT;
    159                 if (!FrameGraphics.isAudienceMode()) {
    160                         y -= MessageBay.MESSAGE_BUFFER_HEIGHT;
     138                int y = EcosystemManager.getGraphicsManager().getWindowSize().getHeight() - GLOBAL_TIMELINE_HEIGHT;
     139                if (!DisplayController.isAudienceMode()) {
     140                        y -= DisplayController.getMessageBayPaintArea().getHeight();
    161141                }
    162142               
    163143                if (y < 0) y = 0;
    164144
    165                 return new Rectangle(0, y, Browser._theBrowser.getContentPane().getWidth(), GLOBAL_TIMELINE_HEIGHT);
     145                return new AxisAlignedBoxBounds(0, y, EcosystemManager.getGraphicsManager().getWindowSize().getWidth(), GLOBAL_TIMELINE_HEIGHT);
    166146        }
    167147       
    168148
    169         public void paint(Graphics g) {
     149        public void paint()
     150        {
    170151                if (Browser._theBrowser == null) return;
    171152
    172153                if (timeAxis != null && lastTimeline != null) {
    173154               
    174                         Rectangle r = getCurrentTimelineArea();
    175 
    176                         g.setColor(GLOBAL_EMPTY_TIMELINE_BACKCOLOR);
    177                         g.fillRect(0, r.y, Browser._theBrowser.getContentPane().getWidth(), r.height);
     155                        GraphicsManager gm = EcosystemManager.getGraphicsManager();
    178156                       
    179                         timeAxis.paint(g,
     157                        AxisAlignedBoxBounds r = getCurrentTimelineArea();
     158                        gm.drawRectangle(new Point(0, r.getMinY()), new Dimension(EcosystemManager.getGraphicsManager().getWindowSize().getWidth(), r.getHeight()), 0.0, new Fill(GLOBAL_EMPTY_TIMELINE_BACKCOLOR), null, null, null);
     159                       
     160                        timeAxis.paint(
    180161                                        lastTimeline.getInitiationXPixel(),
    181                                         r.y,
    182                                         r.height,
     162                                        r.getMinY(),
     163                                        r.getHeight(),
    183164                                        GLOBAL_TIMELINE_BACKCOLOR);
    184165                       
    185                        
    186                         g.setColor(Color.DARK_GRAY);
    187                        
    188                         ((Graphics2D)g).setStroke(TIMELINE_BORDER_STROKE);
    189                         g.drawLine(0, r.y, Browser._theBrowser.getContentPane().getWidth(), r.y);
     166                        gm.drawLine(new Point(0, r.getMinY()), new Point(EcosystemManager.getGraphicsManager().getWindowSize().getWidth(), r.getMinY()), Colour.DARK_GREY, TIMELINE_BORDER_STROKE);
    190167       
    191168                }
  • trunk/src/org/apollo/gui/PlaybackControlPopup.java

    r315 r1102  
    22
    33import java.awt.Dimension;
     4import java.awt.Graphics2D;
    45import java.awt.GridBagConstraints;
    56import java.awt.GridBagLayout;
     
    89import java.awt.event.ActionListener;
    910
    10 import javax.swing.Icon;
    1111import javax.swing.JButton;
     12import javax.swing.JPanel;
    1213import javax.swing.JSlider;
    1314import javax.swing.JToggleButton;
     
    1617
    1718import org.apollo.io.IconRepository;
     19import org.expeditee.core.Image;
     20import org.expeditee.core.bounds.AxisAlignedBoxBounds;
     21import org.expeditee.gio.swing.SwingConversions;
     22import org.expeditee.gio.swing.SwingMiscManager;
    1823import org.expeditee.gui.Popup;
     24import org.expeditee.gui.PopupManager.ExpandShrinkAnimator;
    1925
    2026/**
     
    2531 *
    2632 */
    27 public abstract class PlaybackControlPopup extends Popup implements ActionListener {
    28 
     33public abstract class PlaybackControlPopup extends Popup implements ActionListener
     34{
     35        public JPanel panel;
    2936        public JButton playPauseButton;
    3037        public JButton stopButton;
     
    3946        private static final int BUTTON_SIZE = 40;
    4047       
    41         protected PlaybackControlPopup() {
    42                 super(new GridBagLayout());
     48        protected PlaybackControlPopup()
     49        {
     50                super(new ExpandShrinkAnimator());
     51               
     52                panel = new JPanel(new GridBagLayout());
    4353               
    4454                playPauseButton = new JButton();
    4555                playPauseButton.setActionCommand("playpause");
    4656                playPauseButton.addActionListener(this);
    47                 playPauseButton.setIcon(IconRepository.getIcon("play.png"));
     57                SwingMiscManager.setJButtonIcon(playPauseButton, IconRepository.getIcon("play.png"));
    4858                playPauseButton.setPreferredSize(new Dimension(BUTTON_SIZE, BUTTON_SIZE));
    4959                playPauseButton.setToolTipText("Play selection / Pause");
     
    5363                stopButton.addActionListener(this);
    5464                stopButton.setActionCommand("stop");
    55                 stopButton.setIcon(IconRepository.getIcon("stop.png"));
     65                SwingMiscManager.setJButtonIcon(stopButton, IconRepository.getIcon("stop.png"));
    5666                stopButton.setPreferredSize(new Dimension(BUTTON_SIZE, BUTTON_SIZE));
    5767                stopButton.setToolTipText("Stop playback");
     
    6070                rewindButton.addActionListener(this);
    6171                rewindButton.setActionCommand("rewind");
    62                 rewindButton.setIcon(IconRepository.getIcon("rewind.png"));
     72                SwingMiscManager.setJButtonIcon(rewindButton, IconRepository.getIcon("rewind.png"));
    6373                rewindButton.setPreferredSize(new Dimension(BUTTON_SIZE, BUTTON_SIZE));
    6474                rewindButton.setToolTipText("Rewind to start");
     
    6676                // Icon changes
    6777                muteButton = new JToggleButton();
    68                 muteButton.setSelectedIcon(IconRepository.getIcon("volmute.png"));
     78                SwingMiscManager.setJButtonSelectedIcon(muteButton, IconRepository.getIcon("volmute.png"));
    6979                muteButton.setPreferredSize(new Dimension(BUTTON_SIZE, BUTTON_SIZE));
    7080                muteButton.setToolTipText("Toggle mute");
     
    7888               
    7989                soloButton = new JToggleButton();
    80                 soloButton.setIcon(IconRepository.getIcon("solo.png"));
    81                 soloButton.setSelectedIcon(IconRepository.getIcon("soloon.png"));
     90                SwingMiscManager.setJButtonIcon(soloButton, IconRepository.getIcon("solo.png"));
     91                SwingMiscManager.setJButtonSelectedIcon(soloButton, IconRepository.getIcon("soloon.png"));
    8292                soloButton.setPreferredSize(new Dimension(BUTTON_SIZE, BUTTON_SIZE));
    8393                soloButton.setToolTipText("Toggle solo");
     
    115125                c.gridy = 0;
    116126                c.fill = GridBagConstraints.BOTH;
    117                 add(playPauseButton, c);
     127                panel.add(playPauseButton, c);
    118128               
    119129                c = new GridBagConstraints();
     
    121131                c.gridy = 0;
    122132                c.fill = GridBagConstraints.BOTH;
    123                 add(stopButton, c);
     133                panel.add(stopButton, c);
    124134               
    125135                c = new GridBagConstraints();
     
    127137                c.gridy = 0;
    128138                c.fill = GridBagConstraints.BOTH;
    129                 add(rewindButton, c);
     139                panel.add(rewindButton, c);
    130140               
    131141                c = new GridBagConstraints();
     
    133143                c.gridy = 0;
    134144                c.fill = GridBagConstraints.BOTH;
    135                 add(soloButton, c);
     145                panel.add(soloButton, c);
    136146               
    137147                c = new GridBagConstraints();
     
    139149                c.gridy = 0;
    140150                c.fill = GridBagConstraints.BOTH;
    141                 add(muteButton, c);
     151                panel.add(muteButton, c);
    142152               
    143153                c = new GridBagConstraints();
     
    146156                c.fill = GridBagConstraints.BOTH;
    147157                c.insets = new Insets(0,VOLUME_SPACING,0,VOLUME_SPACING);
    148                 add(volumeSlider, c);
     158                panel.add(volumeSlider, c);
    149159               
    150160                c = new GridBagConstraints();
     
    152162                c.gridy = 0;
    153163                c.fill = GridBagConstraints.BOTH;
    154                 add(miscButton, c);
     164                panel.add(miscButton, c);
    155165               
    156166//
     
    201211//              this.setSize(BUTTON_SIZE * 4, BUTTON_SIZE * 2);
    202212               
    203                 this.setSize(BUTTON_SIZE * 8, BUTTON_SIZE);
    204                
    205                 this.doLayout();
     213                panel.setSize(BUTTON_SIZE * 8, BUTTON_SIZE);
     214               
     215                panel.doLayout();
    206216               
    207217        }
     
    213223        private void updateButtonGUI() {
    214224               
    215                 Icon newIcon = null;
     225                Image newIcon = null;
    216226                if (volumeSlider.getValue() <= 25)
    217227                                newIcon = IconRepository.getIcon("vol25.png");
     
    223233                                newIcon = IconRepository.getIcon("vol100.png");
    224234               
    225                 muteButton.setIcon(newIcon);
    226         }
    227 
    228 
     235                SwingMiscManager.setJButtonIcon(muteButton, newIcon);
     236        }
     237       
     238        @Override
     239        protected void paintInternal()
     240        {
     241                Graphics2D g = SwingMiscManager.getIfUsingSwingGraphicsManager().getCurrentSurface();
     242                AxisAlignedBoxBounds bounds = getBounds();
     243               
     244                g.translate(bounds.getMinX(), bounds.getMinY());
     245                panel.paint(g);
     246                g.translate(-bounds.getMinX(), -bounds.getMinY());
     247        }
     248
     249        @Override
     250        public AxisAlignedBoxBounds getFullBounds()
     251        {
     252                return SwingConversions.fromSwingRectangle(panel.getBounds());
     253        }
     254       
    229255        public abstract void actionPerformed(ActionEvent e);
    230256       
  • trunk/src/org/apollo/gui/SampledTrackGraphView.java

    r1007 r1102  
    11package org.apollo.gui;
    22
     3import java.awt.BasicStroke;
    34import java.awt.Color;
    45import java.awt.Event;
     
    1011import java.awt.Point;
    1112import java.awt.Rectangle;
    12 import java.awt.Stroke;
    1313import java.awt.event.ComponentEvent;
    1414import java.awt.event.ComponentListener;
    15 import java.awt.image.BufferedImage;
    1615import java.util.LinkedList;
    1716import java.util.List;
     
    3130import org.apollo.mvc.Subject;
    3231import org.apollo.mvc.SubjectChangedEvent;
     32import org.expeditee.core.Image;
     33import org.expeditee.core.bounds.AxisAlignedBoxBounds;
     34import org.expeditee.gio.swing.SwingConversions;
     35import org.expeditee.gio.swing.SwingMiscManager;
    3336import org.expeditee.gui.Browser;
    34 import org.expeditee.gui.FrameGraphics;
     37import org.expeditee.gui.DisplayController;
    3538
    3639/**
     
    5962
    6063        private WaveFormRenderProccessingUnit.WaveFormRenderTask renderTask = null;
    61         private BufferedImage backBuffer = null; // Shared resource
     64        private Image backBuffer = null; // Shared resource
    6265        private int bufferWidth = -1; // cached from backBuffer - so don't have to lock
    6366        private int bufferHeight = -1; // cached from backBuffer - so don't have to lock
     
    6770        private int timescaleFrameLength = 0; // in frames
    6871       
    69         private final Font RENDER_MESSAGE_FONT = new Font("Arial", Font.ITALIC | Font.BOLD, 14);
     72        private final Font RENDER_MESSAGE_FONT = new Font("Arial", Font.BOLD | Font.ITALIC, 14);
    7073       
    7174        private boolean alwaysFullViewOn = false;
     
    8083       
    8184        /** The stroke used for drawing graph bars. E.G: The selection Start bar. */
    82         public static final Stroke GRAPH_BAR_STROKE = Strokes.SOLID_1;
     85        public static final BasicStroke GRAPH_BAR_STROKE = SwingConversions.toSwingStroke(Strokes.SOLID_1);
    8386        public static final int GRAPH_BAR_NWIDTH = 1;
    8487       
     
    139142                                this,
    140143                                0, 0,
    141                                 Browser._theBrowser.getContentPane());
     144                                SwingMiscManager.getIfUsingSwingGraphicsManager().getContentPane());
    142145        }
    143146       
     
    339342                               
    340343                                if (x >= 0 && x <= viewWidth) { // is the playback position in view?
    341                                         FrameGraphics.invalidateArea(new Rectangle(
     344                                        DisplayController.invalidateArea(new AxisAlignedBoxBounds(
    342345                                                x + expediteePosition.x,
    343346                                                expediteePosition.y,
     
    356359                               
    357360                                if (x >= 0 && x <= viewWidth) { // is the playback position in view?
    358                                         FrameGraphics.invalidateArea(new Rectangle(
     361                                        DisplayController.invalidateArea(new AxisAlignedBoxBounds(
    359362                                                x + expediteePosition.x ,
    360363                                                expediteePosition.y,
     
    565568               
    566569                renderTask = null; // must be on swing thread because could be painting
    567                 if (backBuffer != null) backBuffer.flush();
     570                if (backBuffer != null) backBuffer.releaseImage();
    568571                backBuffer = null; // must be on swing thread because could be painting
    569572        }
     
    605608                               
    606609                                // Create new sized buffer
    607                                 backBuffer = new BufferedImage(
     610                                backBuffer = Image.createImage(width, height);
     611/*                              backBuffer = new BufferedImage(
    608612                                                width,
    609613                                                height,
    610614                                                BufferedImage.TYPE_BYTE_INDEXED,
    611                                                 ApolloColorIndexedModels.graphIndexColorModel);
     615                                                ApolloColorIndexedModels.graphIndexColorModel);*/
    612616                        }
    613617                }
     
    624628                                );
    625629               
    626                 // Wait for invalidation recomendation messages
     630                // Wait for invalidation recommendation messages
    627631                renderTask.addObserver(this);
    628632
     
    693697                                synchronized(backBuffer) {
    694698       
    695                                         g.drawImage(backBuffer,
     699                                        g.drawImage(SwingMiscManager.getIfUsingSwingImageManager().getInternalImage(backBuffer),
    696700                                                        0,
    697701                                                        0,
    698702                                                        getWidth(),
    699                                                         getHeight(), 
     703                                                        getHeight(),
    700704                                                        null);
    701705                                       
     
    709713                                // No need to synchronize waveformBuffer because there is no thread accessing it,
    710714                                // and a new render thread is always created on this thread.
    711                                 g.drawImage(backBuffer,
     715                                g.drawImage(SwingMiscManager.getIfUsingSwingImageManager().getInternalImage(backBuffer),
    712716                                                0,
    713717                                                0,
    714718                                                getWidth(),
    715                                                 getHeight(), 
     719                                                getHeight(),
    716720                                                null);
    717721                               
     
    919923         *
    920924         */
    921         public interface EffecientInvalidator {
     925        public interface EffecientInvalidator
     926        {
    922927                public void onGraphDirty(SampledTrackGraphView graph, Rectangle dirty);
    923928        }
    924929
    925         public Color getBackColor() {
     930        public Color getBackColor()
     931        {
    926932                return backColor;
    927933        }
     
    935941         *     
    936942         */
    937         public void setBackColor(Color backColor, Color highlights) {
     943        public void setBackColor(Color backColor, Color highlights)
     944        {
    938945                setBackColor(backColor, highlights, true);
    939946        }
     
    949956         *              Doesnt invalidate if the color has not changed.
    950957         */
    951         public void setBackColor(Color backColor, Color highlights, boolean invalidate) {
     958        public void setBackColor(Color backColor, Color highlights, boolean invalidate)
     959        {
    952960                if (backColor == null) throw new NullPointerException("backColor");
    953961                if (this.backColor != backColor || backColorHighlights != highlights) {
  • trunk/src/org/apollo/gui/SampledTrackGraphViewPort.java

    r356 r1102  
    11package org.apollo.gui;
    22
    3 import java.awt.Color;
    43import java.awt.Event;
    5 import java.awt.Font;
    6 import java.awt.FontMetrics;
    74import java.awt.Graphics;
    85import java.awt.Graphics2D;
    9 import java.awt.Stroke;
    106import java.awt.event.ComponentEvent;
    117import java.awt.event.ComponentListener;
     
    1713import java.awt.event.MouseWheelEvent;
    1814import java.awt.event.MouseWheelListener;
    19 import java.awt.geom.Rectangle2D;
    20 import java.awt.image.BufferedImage;
    2115import java.util.LinkedList;
    2216import java.util.List;
     
    2721import org.apollo.mvc.SubjectChangedEvent;
    2822import org.apollo.util.AudioMath;
    29 import org.expeditee.gui.Browser;
     23import org.expeditee.core.Colour;
     24import org.expeditee.core.Font;
     25import org.expeditee.core.Stroke;
     26import org.expeditee.core.TextLayout;
     27import org.expeditee.core.bounds.AxisAlignedBoxBounds;
     28import org.expeditee.gio.EcosystemManager;
     29import org.expeditee.gio.swing.SwingConversions;
     30import org.expeditee.gio.swing.SwingMiscManager;
    3031
    3132public class SampledTrackGraphViewPort extends SampledTrackGraphView
     
    4344        private static final int ZOOM_ADJUSTMENT_MODE_MODIFYZOOM = 3;
    4445       
    45         public static final Color ZOOM_BACKING_COLOR_NORMAL = new Color(251, 255, 168);
    46         private static final Color ZOOM_BACKING_COLOR_HIGHLIGHT = new Color(255, 255, 224);
    47         private static final Color ZOOM_BACKING_BORDER_COLOR = new Color(215, 219, 144);
     46        public static final Colour ZOOM_BACKING_COLOR_NORMAL = Colour.FromRGB255(251, 255, 168);
     47        private static final Colour ZOOM_BACKING_COLOR_HIGHLIGHT = Colour.FromRGB255(255, 255, 224);
     48        private static final Colour ZOOM_BACKING_BORDER_COLOR = Colour.FromRGB255(215, 219, 144);
    4849        public static final Stroke ZOOM_BACKING_BORDER_STROKE = Strokes.SOLID_1;
    4950       
    50         public static final Font TIME_HELPER_FONT = new Font("Arial", Font.PLAIN, 12);
    51         public static final Color TIME_HELPER_COLOR = new Color(132, 175, 201);
    52         public static final Color TIME_HELPER_BORDERCOLOR = new Color(111, 146, 168);
     51        public static final Font TIME_HELPER_FONT = new Font("Arial", Font.Style.PLAIN, 12);
     52        public static final Colour TIME_HELPER_COLOR = Colour.FromRGB255(132, 175, 201);
     53        public static final Colour TIME_HELPER_BORDERCOLOR = Colour.FromRGB255(111, 146, 168);
    5354       
    5455        // displays the current zoom or the new zoom-selection
     
    6768        private List<ZoomChangeListener> zoomChangeListeners = new LinkedList<ZoomChangeListener>();
    6869
    69         public SampledTrackGraphViewPort() {
     70        public SampledTrackGraphViewPort()
     71        {
    7072                super();
    7173               
    72                 setBackColor(new Color(250, 250, 250), new Color(230, 230, 230));
     74                setBackColor(SwingConversions.toSwingColor(Colour.FromRGB255(250, 250, 250)), SwingConversions.toSwingColor(Colour.FromRGB255(230, 230, 230)));
    7375                setAlwaysFullView(true);
    7476
     
    531533                void paint(Graphics g) {
    532534                       
    533                         color =  (zoomAdjustmentMode == ZOOM_ADJUSTMENT_MODE_NONE) ?
    534                                         ZOOM_BACKING_COLOR_NORMAL : ZOOM_BACKING_COLOR_HIGHLIGHT;
     535                        color = SwingConversions.toSwingColor((zoomAdjustmentMode == ZOOM_ADJUSTMENT_MODE_NONE) ? ZOOM_BACKING_COLOR_NORMAL : ZOOM_BACKING_COLOR_HIGHLIGHT);
    535536                        super.paint(g);
    536537                       
    537                         g.setColor(ZOOM_BACKING_BORDER_COLOR);
    538                         ((Graphics2D)g).setStroke(ZOOM_BACKING_BORDER_STROKE);
     538                        g.setColor(SwingConversions.toSwingColor(ZOOM_BACKING_BORDER_COLOR));
     539                        ((Graphics2D)g).setStroke(SwingConversions.toSwingStroke(ZOOM_BACKING_BORDER_STROKE));
    539540                        g.drawLine(left, 0, left, getHeight());
    540541                        g.drawLine(left + width, 0, left + width, getHeight());
     
    542543                }
    543544               
    544                 void postPaint(Graphics g) {
    545                         // Paint little helper labels when ajusting view port
    546                         if (startTimeHelpLabel != null && endTimeHelpLabel != null &&
    547                                         zoomAdjustmentMode != ZOOM_ADJUSTMENT_MODE_NONE) {
    548                                
    549                                 g.setColor(TIME_HELPER_COLOR);
     545                void postPaint(Graphics g)
     546                {
     547                        // Paint little helper labels when adjusting view port
     548                        if (startTimeHelpLabel != null && endTimeHelpLabel != null && zoomAdjustmentMode != ZOOM_ADJUSTMENT_MODE_NONE) {
     549                               
     550                                g.setColor(SwingConversions.toSwingColor(TIME_HELPER_COLOR));
    550551                                g.fillRect(labelStartX - 2, labelStartY - labelHeight + 2, labelWidth + 3, labelHeight);
    551552                                g.fillRect(labelEndX - 2, labelEndY  - labelHeight + 2, labelWidth + 3, labelHeight);
    552553                               
    553                                 g.setColor(TIME_HELPER_BORDERCOLOR);
    554                                 ((Graphics2D)g).setStroke(ZOOM_BACKING_BORDER_STROKE);
     554                                g.setColor(SwingConversions.toSwingColor(TIME_HELPER_BORDERCOLOR));
     555                                ((Graphics2D)g).setStroke(SwingConversions.toSwingStroke(ZOOM_BACKING_BORDER_STROKE));
    555556                                g.drawRect(labelStartX - 2, labelStartY - labelHeight + 2, labelWidth + 3, labelHeight);
    556557                                g.drawRect(labelEndX - 2, labelEndY  - labelHeight + 2, labelWidth + 3, labelHeight);
    557558
    558                                 g.setFont(TIME_HELPER_FONT);
    559                                 g.setColor(Color.BLACK);
     559                                g.setFont(SwingMiscManager.getIfUsingSwingFontManager().getInternalFont(TIME_HELPER_FONT));
     560                                g.setColor(SwingConversions.toSwingColor(Colour.BLACK));
    560561                                g.drawString(startTimeHelpLabel, labelStartX, labelStartY);
    561562                                g.drawString(endTimeHelpLabel, labelEndX, labelEndY);
     
    603604                               
    604605                                // Create a temp graphics for centered label positioning
    605                                 if (Browser._theBrowser != null && Browser._theBrowser.g != null) {
     606                                /*if (Browser._theBrowser != null && Browser._theBrowser.g != null) {
    606607                                        g = Browser._theBrowser.g.create();
    607608                                } else {
    608609                                        g = new BufferedImage(1,1,BufferedImage.TYPE_BYTE_INDEXED).getGraphics();
    609                                 }
     610                                }*/
    610611               
    611612                                // Position labels
    612                                 FontMetrics fm   = g.getFontMetrics(TIME_HELPER_FONT);
    613                                 Rectangle2D rect = fm.getStringBounds(startTimeHelpLabel, g);
     613                                //FontMetrics fm   = g.getFontMetrics(TIME_HELPER_FONT);
     614                                //Rectangle2D rect = fm.getStringBounds(startTimeHelpLabel, g);
     615                                TextLayout layout = EcosystemManager.getTextLayoutManager().layoutStringSimple(startTimeHelpLabel, TIME_HELPER_FONT);
     616                                AxisAlignedBoxBounds rect = layout.getPixelBounds(0, 0);
    614617                               
    615618                                labelWidth = (int)rect.getWidth();
  • trunk/src/org/apollo/gui/Strokes.java

    r356 r1102  
    11package org.apollo.gui;
    22
    3 import java.awt.BasicStroke;
    4 import java.awt.Stroke;
     3import org.expeditee.core.Stroke;
    54
    65public class Strokes {
     
    98        }
    109       
    11         public static final Stroke SOLID_1 = new BasicStroke(1.0f);
    12         public static final Stroke SOLID_2 = new BasicStroke(2.0f);
     10        public static final Stroke SOLID_1 = new Stroke(1.0f);
     11        public static final Stroke SOLID_2 = new Stroke(2.0f);
    1312       
    1413}
  • trunk/src/org/apollo/gui/TimeAxis.java

    r375 r1102  
    11package org.apollo.gui;
    22
    3 import java.awt.Color;
    4 import java.awt.Font;
    5 import java.awt.FontMetrics;
    6 import java.awt.GradientPaint;
    7 import java.awt.Graphics;
    8 import java.awt.Graphics2D;
    9 import java.awt.Stroke;
    10 import java.awt.geom.Rectangle2D;
    11 import java.awt.image.BufferedImage;
    123import java.util.LinkedList;
    134
    145import org.apollo.ApolloSystem;
    15 import org.expeditee.gui.Browser;
     6import org.expeditee.core.Colour;
     7import org.expeditee.core.Dimension;
     8import org.expeditee.core.Fill;
     9import org.expeditee.core.Font;
     10import org.expeditee.core.GradientFill;
     11import org.expeditee.core.Point;
     12import org.expeditee.core.Stroke;
     13import org.expeditee.core.TextLayout;
     14import org.expeditee.gio.EcosystemManager;
     15import org.expeditee.gio.GraphicsManager;
     16import org.expeditee.gio.swing.SwingConversions;
    1617
    1718/**
     
    2324public class TimeAxis {
    2425       
    25         private static final long serialVersionUID = 1L;
    26        
    27         public static final Font TIME_BAR_FONT = new Font("Arial", Font.PLAIN, 14);
     26        public static final Font TIME_BAR_FONT = new Font("Arial", Font.Style.PLAIN, 14);
    2827        private static final Stroke TICK_STROKE = Strokes.SOLID_1;
    2928       
    30         private static final Color MAJOR_TICK_COLOR = Color.BLACK;
    31         private static final Color MINOR_TICK_COLOR = new Color(0.4f, 0.4f, 0.4f);
     29        private static final Colour MAJOR_TICK_COLOR = Colour.BLACK;
     30        private static final Colour MINOR_TICK_COLOR = new Colour(0.4f, 0.4f, 0.4f);
    3231       
    3332        private static final int DESIRED_MAJOR_TICK_PIXEL_SPACING = 100;
     
    4342        private long totalTrackMSLength = 0;
    4443
    45         public TimeAxis() {
     44        public TimeAxis()
     45        {
    4646        }
    4747
     
    5151                        long timeLengthSamples,
    5252                        long totalTrackMSLength,
    53                         int width) {
     53                        int width)
     54        {
    5455
    5556                assert(width > 0);
     
    146147                LinkedList<Integer> majorTickLabelPositions = new LinkedList<Integer>();
    147148       
    148                 Graphics g = null;
    149                 try {
    150                
    151                        
    152                         // Create a temp graphics for centered label positioning
    153                         if (Browser._theBrowser != null && Browser._theBrowser.g != null) {
    154                                 g = Browser._theBrowser.g.create();
    155                         } else {
    156                                 g = new BufferedImage(1,1,BufferedImage.TYPE_BYTE_INDEXED).getGraphics();
    157                         }
    158                        
    159                         do {
    160        
    161                                 majorTickPositions.add(new Integer((int)currentTickX));
    162 
    163                                 String label = createSpecificTimeLabel((long)currentTickTime, timeAggregation);
    164                                
    165                                 majorTickLabels.add(label);
    166 
    167                                 // Center label
    168                                 FontMetrics fm   = g.getFontMetrics(TIME_BAR_FONT);
    169                                 Rectangle2D rect = fm.getStringBounds(label, g);
    170                                 int textWidth  = (int)(rect.getWidth());
    171                                
    172                                 majorTickLabelPositions.add(new Integer((int)currentTickX - (textWidth >> 1)));
    173 
    174                                 currentTickX += majorTickPixelSpacing;
    175                                 currentTickTime += timeAggregation;
    176        
    177                         } while (currentTickX < width);
    178 
    179                        
    180                 } finally {
    181                         if (g != null)
    182                                 g.dispose();
    183                 }
     149                do {
     150                        majorTickPositions.add(new Integer((int)currentTickX));
     151
     152                        String label = createSpecificTimeLabel((long)currentTickTime, timeAggregation);
     153                       
     154                        majorTickLabels.add(label);
     155
     156                        // Center label
     157                        int textWidth = EcosystemManager.getTextLayoutManager().layoutStringSimple(label, TIME_BAR_FONT).getPixelBounds(0, 0).getWidth();
     158                       
     159                        majorTickLabelPositions.add(new Integer((int)currentTickX - (textWidth >> 1)));
     160
     161                        currentTickX += majorTickPixelSpacing;
     162                        currentTickTime += timeAggregation;
     163                       
     164                } while (currentTickX < width);
    184165               
    185166                this.majorTickLabels = majorTickLabels.toArray(new String[0]);
     
    227208       
    228209       
    229         public String createSpecificTimeLabel(long atTime, double timeAggregation) {
    230 
     210        public String createSpecificTimeLabel(long atTime, double timeAggregation)
     211        {
    231212                Long min = null;
    232213                Long sec = null;
     
    261242        }
    262243       
    263         public static String createTimeLabel(Long min, Long sec, Long ms) {
    264                
     244        public static String createTimeLabel(Long min, Long sec, Long ms)
     245        {
    265246                if (min == null && sec == null && ms != null) {
    266247                        return ms + "ms";
     
    314295        }
    315296       
    316         public void paint(Graphics g, int x, int y, int height, Color backgroundColor) {
     297        public void paint(int x, int y, int height, Colour backgroundColor) {
    317298               
    318299                int majorTickHeight = height / 2;
     
    320301
    321302                // Draw backing
     303                Fill backingFill;
    322304                if (ApolloSystem.useQualityGraphics) {
    323                        
    324                         GradientPaint gp = new GradientPaint(
    325                                         x + (width / 2), y + (int)(height * 0.5), backgroundColor,
    326                                         x + (width / 2), y, SampledTrackGraphView.DEFAULT_BACKGROUND_HIGHTLIGHTS_COLOR);
    327                         ((Graphics2D)g).setPaint(gp);
    328                        
     305                        backingFill = new GradientFill(backgroundColor, new Point(x + (width / 2), y + (int)(height * 0.5)), SwingConversions.fromSwingColor(SampledTrackGraphView.DEFAULT_BACKGROUND_HIGHTLIGHTS_COLOR), new Point(x + (width / 2), y));
    329306                } else {
    330                         g.setColor(backgroundColor);
    331                 }
    332                
    333                 g.fillRect(x, y, width, height);
    334                
    335                 g.setFont(TIME_BAR_FONT);
     307                        backingFill = new Fill(backgroundColor);
     308                }
     309               
     310                GraphicsManager gm = EcosystemManager.getGraphicsManager();
     311               
     312                gm.drawRectangle(new Point(x, y), new Dimension(width, height), 0.0, backingFill, null, null, null);
    336313               
    337314                if (majorTickXPositions != null) {
    338 
    339                         ((Graphics2D)g).setStroke(TICK_STROKE);
    340                        
    341                         g.setColor(MAJOR_TICK_COLOR);
    342315                        // Draw Major ticks and labels
    343316                        for (int i = 0; i < majorTickLabels.length; i++) {
    344317                               
    345318                                // Label
    346                                 g.drawString(
     319                                gm.drawString(
    347320                                                majorTickLabels[i],
    348                                                 x + majorTickLabelXPositions[i],
    349                                                 y + height - 2);
     321                                                new Point(x + majorTickLabelXPositions[i], y + height - 2),
     322                                                TIME_BAR_FONT,
     323                                                MAJOR_TICK_COLOR);
    350324                               
    351325                                // Tick
    352                                 g.drawLine(
    353                                                 x + majorTickXPositions[i],
     326                                gm.drawLine(x + majorTickXPositions[i],
    354327                                                y,
    355328                                                x + majorTickXPositions[i],
    356                                                 y + majorTickHeight);
     329                                                y + majorTickHeight, MAJOR_TICK_COLOR, TICK_STROKE);
    357330                               
    358331                        }
    359                        
    360                         g.setColor(MINOR_TICK_COLOR);
    361332                       
    362333                        // Draw minor ticks
    363334                        if (minorTickXPositions != null) {
    364335                                for (int tx : minorTickXPositions) {
    365                                         g.drawLine(
     336                                        gm.drawLine(
    366337                                                        x + tx,
    367338                                                        y,
    368339                                                        x + tx,
    369                                                         y + minorTickHeight);
     340                                                        y + minorTickHeight, MINOR_TICK_COLOR, TICK_STROKE);
    370341                                }
    371342                        }
     
    373344                } else if (alternateLabel != null) {
    374345                       
    375                         g.setColor(Color.BLACK);
    376                        
    377                         FontMetrics fm   = g.getFontMetrics(TIME_BAR_FONT);
    378                         Rectangle2D rect = fm.getStringBounds(alternateLabel, g);
    379                         int textWidth  = (int)(rect.getWidth());
    380                        
    381                         g.drawString(
    382                                         alternateLabel,
    383                                         x + ((width >> 1) - (textWidth >> 1)),
    384                                         y + (height - 2));
    385 
    386                 }
    387                
    388         }
    389 
    390         public int getWidth() {
     346                        TextLayout layout = EcosystemManager.getTextLayoutManager().layoutStringSimple(alternateLabel, TIME_BAR_FONT);
     347
     348                        int textWidth  = layout.getPixelBounds(0, 0).getWidth();
     349                        gm.drawTextLayout(layout, new Point(x + ((width >> 1) - (textWidth >> 1)), y + (height - 2)), Colour.BLACK);
     350                       
     351                }
     352               
     353        }
     354
     355        public int getWidth()
     356        {
    391357                return width;
    392358        }
  • trunk/src/org/apollo/gui/TimeAxisPanel.java

    r315 r1102  
    1212
    1313import org.apollo.util.AudioMath;
     14import org.expeditee.gio.swing.SwingConversions;
    1415
    1516/**
     
    3031        private TimeAxis timeAxis = new TimeAxis();
    3132       
    32         public TimeAxisPanel(SampledTrackGraphView graph) {
     33        public TimeAxisPanel(SampledTrackGraphView graph)
     34        {
    3335                assert (graph != null);
    3436               
     
    3739               
    3840                // Auto-adjust scale when component resizes.
    39                 this.addComponentListener(new ComponentListener() {
    40 
    41                         public void componentHidden(ComponentEvent e) {
     41                this.addComponentListener(new ComponentListener()
     42                {
     43                        public void componentHidden(ComponentEvent e)
     44                        {
    4245                        }
    4346
    44                         public void componentMoved(ComponentEvent e) {
     47                        public void componentMoved(ComponentEvent e)
     48                        {
    4549                        }
    4650
    47                         public void componentResized(ComponentEvent e) {
     51                        public void componentResized(ComponentEvent e)
     52                        {
    4853                                updateAxis();
    4954                        }
    5055
    51                         public void componentShown(ComponentEvent e) {
     56                        public void componentShown(ComponentEvent e)
     57                        {
    5258                        }
    53                
    5459                });
    5560               
     
    5863       
    5964
    60         public void timelineChanged(Event e) {
     65        public void timelineChanged(Event e)
     66        {
    6167                 updateAxis();
    6268        }
    6369       
    6470
    65         private void updateAxis() {
    66                
     71        private void updateAxis()
     72        {
    6773                // Is track model even set yet?
    68                 if (observedSubject.getSampledTrackModel() == null ||
    69                                 getWidth() == 0) return;
     74                if (observedSubject.getSampledTrackModel() == null || getWidth() == 0) return;
    7075               
    7176                AudioFormat format = observedSubject.getSampledTrackModel().getFormat();
    7277               
    73                 long startTimeMS = AudioMath.framesToMilliseconds(
    74                                 observedSubject.getTimeScaleStart(), format);
     78                long startTimeMS = AudioMath.framesToMilliseconds(observedSubject.getTimeScaleStart(), format);
    7579               
    76                 long timeLengthMS = AudioMath.framesToMilliseconds(
    77                                 observedSubject.getTimeScaleLength(), format);
     80                long timeLengthMS = AudioMath.framesToMilliseconds(observedSubject.getTimeScaleLength(), format);
    7881               
    79                 long totalTrackMSLength = AudioMath.framesToMilliseconds(
    80                                 observedSubject.getSampledTrackModel().getFrameCount(), format);
     82                long totalTrackMSLength = AudioMath.framesToMilliseconds(observedSubject.getSampledTrackModel().getFrameCount(), format);
    8183               
    8284                timeAxis.setAxis(
     
    9294       
    9395        @Override
    94         public void paint(Graphics g) {
    95                 timeAxis.paint(g, 0, 0, getHeight(), getBackground());
     96        public void paint(Graphics g)
     97        {
     98                timeAxis.paint(0, 0, getHeight(), SwingConversions.fromSwingColor(getBackground()));
    9699        }
    97100
  • trunk/src/org/apollo/gui/TimelineChangeListener.java

    r315 r1102  
    33import java.awt.Event;
    44
    5 public interface TimelineChangeListener {
     5public interface TimelineChangeListener
     6{
    67        void timelineChanged(Event e);
    78}
  • trunk/src/org/apollo/gui/VolumeControlButton.java

    r343 r1102  
    11package org.apollo.gui;
    22
    3 import java.awt.Color;
    43import java.awt.Dimension;
    54import java.awt.GridBagConstraints;
    65import java.awt.GridBagLayout;
    76import java.awt.Insets;
    8 import java.awt.Point;
    97import java.awt.event.ActionEvent;
    108import java.awt.event.ActionListener;
     
    1210import java.util.List;
    1311
    14 import javax.swing.Icon;
    1512import javax.swing.JButton;
     13import javax.swing.JPanel;
    1614import javax.swing.JSlider;
    1715import javax.swing.event.ChangeEvent;
     
    1917
    2018import org.apollo.io.IconRepository;
     19import org.expeditee.core.Colour;
     20import org.expeditee.core.Image;
     21import org.expeditee.core.bounds.AxisAlignedBoxBounds;
     22import org.expeditee.gio.swing.SwingConversions;
     23import org.expeditee.gio.swing.SwingMiscManager;
    2124import org.expeditee.gui.Popup;
    2225import org.expeditee.gui.PopupManager;
     26import org.expeditee.gui.PopupManager.ExpandShrinkAnimator;
    2327
    2428/**
     
    4044        private String volumeTag;
    4145       
    42         private Color SELECTED_BACKCOLOR = Color.GRAY;
    43         private Color UNSELECTED_BACKCOLOR = null;
     46        private Colour SELECTED_BACKCOLOR = Colour.GRAY;
     47        private Colour UNSELECTED_BACKCOLOR = null;
    4448       
    4549        private static final int VOL_ADJUSTMENT = 10;
     
    5256         *              E.G. "Master Volume".
    5357         */
    54         public VolumeControlButton(String volumeTag) {
     58        public VolumeControlButton(String volumeTag)
     59        {
    5560                super();
    56                 UNSELECTED_BACKCOLOR = getBackground();
     61                UNSELECTED_BACKCOLOR = SwingConversions.fromSwingColor(getBackground());
    5762                vcPopup = new VolumeControlPopup();
    58                 vcPopup.setVisible(false);
     63                PopupManager.getInstance().add(vcPopup);
    5964                this.volumeTag = volumeTag;
    6065                toggleSelectionState(false);
     
    6873         * @param listener
    6974         */
    70         public void addVolumeChangeListener(ChangeListener listener) {
     75        public void addVolumeChangeListener(ChangeListener listener)
     76        {
    7177                assert(listener != null);
    7278                changeListeners.add(listener);
    7379        }
    7480       
    75         private void fireVolumeChanged() {
     81        private void fireVolumeChanged()
     82        {
    7683                for (ChangeListener a : changeListeners) {
    7784                        a.stateChanged(new ChangeEvent(this));
     
    7986        }
    8087
    81         private void toggleSelectionState(boolean selected) {
    82                 if (selected) setBackground(SELECTED_BACKCOLOR);
    83                 else setBackground(UNSELECTED_BACKCOLOR);
     88        private void toggleSelectionState(boolean selected)
     89        {
     90                if (selected) {
     91                        setBackground(SwingConversions.toSwingColor(SELECTED_BACKCOLOR));
     92                } else {
     93                        setBackground(SwingConversions.toSwingColor(UNSELECTED_BACKCOLOR));
     94                }
    8495        }
    8596       
     
    89100         */
    90101        @Override
    91         protected void fireActionPerformed(ActionEvent event) {
     102        protected void fireActionPerformed(ActionEvent event)
     103        {
    92104                super.fireActionPerformed(event);
    93105               
    94                 if (!vcPopup.isVisible()) { // show popup
    95                        
     106                if (!vcPopup.isShowing()) { // show popup
    96107                        vcPopup.showPopup();
    97 
    98108                } else { // hide popup
    99 
    100                         PopupManager.getInstance().hidePopup(vcPopup,
    101                                         PopupManager.getInstance().new ExpandShrinkAnimator(
    102                                                         VolumeControlButton.this.getBounds(),
    103                                                         Color.LIGHT_GRAY));
     109                        vcPopup.hide();
    104110                }
    105111        }
     
    133139         * @return
    134140         */
    135         public void setMuted(boolean mute) {
     141        public void setMuted(boolean mute)
     142        {
    136143                muted = mute;
    137144                updateButtonGUI();
     
    139146               
    140147
    141         private void updateButtonGUI() {
    142                
    143                 Icon newIcon;
     148        private void updateButtonGUI()
     149        {
     150                Image newIcon;
    144151                if(muted) 
    145152                                newIcon = IconRepository.getIcon("volmute.png");
     
    153160                                newIcon = IconRepository.getIcon("vol100.png");
    154161
    155                 if (newIcon != getIcon()) setIcon(newIcon);
     162                if (newIcon != getIcon()) SwingMiscManager.setJButtonIcon(this, newIcon);
    156163               
    157164                if (muted) {
    158                         if (volumeTag != null) setToolTipText(volumeTag + ": Muted");
    159                         else setToolTipText("Muted");
    160                 }
    161                 else {
    162                         if (volumeTag != null) setToolTipText(volumeTag + ": " + volumeValue + "%");
    163                         else setToolTipText(volumeValue + "%");
     165                        if (volumeTag != null) {
     166                                setToolTipText(volumeTag + ": Muted");
     167                        } else {
     168                                setToolTipText("Muted");
     169                        }
     170                } else {
     171                        if (volumeTag != null) {
     172                                setToolTipText(volumeTag + ": " + volumeValue + "%");
     173                        } else {
     174                                setToolTipText(volumeValue + "%");
     175                        }
    164176                }
    165177        }
     
    169181         * @return The volume value of the gui
    170182         */
    171         public int getVolumeValue() {
     183        public int getVolumeValue()
     184        {
    172185                return volumeValue;
    173186        }
     
    178191         * @return The mute value of the gui
    179192         */
    180         public boolean getMuteValue() {
     193        public boolean getMuteValue()
     194        {
    181195                return muted;
    182196        }
    183197
    184         private class VolumeControlPopup extends Popup {
    185                
    186                 private static final long serialVersionUID = 1L;
    187        
     198        private class VolumeControlPopup extends Popup
     199        {
     200                private JPanel panel;
    188201                private JSlider volumeSlider;
    189202                private JButton increaseButton;
     
    193206                 * Constructor.
    194207                 */
    195                 public VolumeControlPopup() {
    196                         super();
     208                public VolumeControlPopup()
     209                {
     210                        super(new ExpandShrinkAnimator());
     211                       
     212                        panel = new JPanel();
    197213
    198214                        volumeSlider = new JSlider(JSlider.VERTICAL);
     
    226242                }
    227243               
    228                 private void onIncrementVolume() {
     244                private void onIncrementVolume()
     245                {
    229246                        if (setVolumeValue(volumeValue + VOL_ADJUSTMENT)) {
    230247                                fireVolumeChanged();
     
    232249                }
    233250               
    234                 private void onDeincrementVolume() {
     251                private void onDeincrementVolume()
     252                {
    235253                        if (setVolumeValue(volumeValue - VOL_ADJUSTMENT)) {
    236254                                fireVolumeChanged();
     
    238256                }
    239257               
    240                 private void onVolumeSliderChanged() {
     258                private void onVolumeSliderChanged()
     259                {
    241260                        if (setVolumeValue(volumeSlider.getValue())) {
    242261                                fireVolumeChanged();
     
    244263                }
    245264               
    246                 private void updatePopupGUI() {
     265                private void updatePopupGUI()
     266                {
    247267                        volumeSlider.setValue(volumeValue);
    248268                        increaseButton.setEnabled(volumeValue < 100);
     
    250270                }
    251271               
    252                 private void prepLayout() {
    253                        
    254                         if (this.getComponents().length == 0) {
     272                private void prepLayout()
     273                {
     274                        if (panel.getComponents().length == 0) {
    255275                               
    256276                                final int INNER_SPACING = 0;
     
    286306                                c.insets = new Insets(OUTER_SPACING,OUTER_SPACING,INNER_SPACING,OUTER_SPACING);
    287307                                c.ipady = YPAD;
    288                                 this.add(increaseButton, c);
     308                                panel.add(increaseButton, c);
    289309                               
    290310                                c = new GridBagConstraints();
     
    294314                                c.insets = new Insets(INNER_SPACING,OUTER_SPACING,INNER_SPACING,OUTER_SPACING);
    295315                                c.ipady = YPAD;
    296                                 this.add(volumeSlider, c);
     316                                panel.add(volumeSlider, c);
    297317                               
    298318                                c = new GridBagConstraints();
     
    302322                                c.insets = new Insets(INNER_SPACING,OUTER_SPACING,OUTER_SPACING,OUTER_SPACING);
    303323                                c.ipady = YPAD;
    304                                 this.add(decreaseButton, c);
    305                                
    306                                 setSize(targetWidth, volumeSlider.getHeight() + (2 * buttonSizes.height)
    307                                                 + (2 * OUTER_SPACING));
    308                                 this.doLayout();
    309                         }
    310 
    311                 }
    312                
    313                 private void showPopup() {
     324                                panel.add(decreaseButton, c);
     325                               
     326                                setSize(targetWidth, volumeSlider.getHeight() + (2 * buttonSizes.height) + (2 * OUTER_SPACING));
     327                                panel.doLayout();
     328                        }
     329
     330                }
     331               
     332                private void showPopup()
     333                {
    314334                        prepLayout();
    315 
     335                        show();
     336                }
     337
     338                @Override
     339                public void onHide() {
     340                        // Toggle state = volume popup showing
     341                        toggleSelectionState(false);
     342                }
     343
     344                @Override
     345                public void onShow() {
     346                        // Toggle state = volume popup showing
     347                        toggleSelectionState(true);
     348                }
     349
     350                @Override
     351                public boolean shouldConsumeBackClick()
     352                {
     353                        return true;
     354                }
     355
     356                @Override
     357                protected void paintInternal()
     358                {
     359                        // TODO Auto-generated method stub
     360                       
     361                }
     362
     363                @Override
     364                public AxisAlignedBoxBounds getFullBounds()
     365                {
    316366                        // Determine where popup should show
    317367                        int x = VolumeControlButton.this.getX();
     
    321371                                y = VolumeControlButton.this.getY() + VolumeControlButton.this.getHeight() + 2;
    322372                        }
    323 
    324                         PopupManager.getInstance().showPopup(
    325                                         this,
    326                                         new Point(x, y),
    327                                         VolumeControlButton.this,
    328                                         PopupManager.getInstance().new ExpandShrinkAnimator(
    329                                                         VolumeControlButton.this.getBounds(),
    330                                                         Color.LIGHT_GRAY));
    331                 }
    332 
    333                 @Override
    334                 public void onHide() {
    335                         // Toggle state = volume popup showing
    336                         toggleSelectionState(false);
    337                 }
    338 
    339                 @Override
    340                 public void onShow() {
    341                         // Toggle state = volume popup showing
    342                         toggleSelectionState(true);
    343                 }
    344 
    345                 @Override
    346                 public boolean shouldConsumeBackClick() {
    347                         return true;
    348                 }
    349                
    350                
    351                
    352         }
    353 
     373                       
     374                        return new AxisAlignedBoxBounds(x, y, VolumeControlButton.this.getBounds().width, VolumeControlButton.this.getBounds().height);
     375                }
     376        }
    354377}
  • trunk/src/org/apollo/gui/WaveFormRenderProccessingUnit.java

    r355 r1102  
    22
    33import java.awt.Graphics2D;
    4 import java.awt.image.BufferedImage;
    54import java.util.LinkedList;
    65
     
    109import org.apollo.mvc.AbstractSubject;
    1110import org.apollo.mvc.SubjectChangedEvent;
     11import org.expeditee.core.Image;
     12import org.expeditee.gio.swing.SwingConversions;
     13import org.expeditee.gio.swing.SwingMiscManager;
    1214
    1315public class WaveFormRenderProccessingUnit {
     
    176178                                        bufferWidth = currentTask.imageBuffer.getWidth();
    177179                                       
    178                                         g = currentTask.imageBuffer.createGraphics();
    179        
    180                                         g.setStroke(Strokes.SOLID_1);
     180                                        g = SwingMiscManager.getIfUsingSwingImageManager().getImageGraphics(currentTask.imageBuffer);
     181       
     182                                        g.setStroke(SwingConversions.toSwingStroke(Strokes.SOLID_1));
    181183
    182184                                        // Clear the buffer with transparent pixels
    183                                         g.setBackground(ApolloColorIndexedModels.KEY_COLOR);
     185                                        g.setBackground(SwingConversions.toSwingColor(ApolloColorIndexedModels.KEY_COLOR));
    184186                                        g.clearRect(0, 0, bufferWidth, currentTask.imageBuffer.getHeight());
    185187                                       
     
    233235                                        synchronized(currentTask.imageBuffer) {
    234236                                               
    235                                                 g.setColor(ApolloColorIndexedModels.WAVEFORM_COLOR);
     237                                                g.setColor(SwingConversions.toSwingColor(ApolloColorIndexedModels.WAVEFORM_COLOR));
    236238                                               
    237239                                                if (aggregationSize == 1) {
     
    344346                private static final int STATE_STOPPED = 3;
    345347               
    346                 private BufferedImage imageBuffer; // nullified when stopped.
     348                private Image imageBuffer; // nullified when stopped.
    347349                private byte[] audioBytes; // nullified when stopped. - Arrays (not contents) are immutable so no need to worry about threading issues with indexes
    348350                private final int startFrame;
     
    352354               
    353355                public WaveFormRenderTask(
    354                                 BufferedImage imageBuffer,
     356                                Image imageBuffer,
    355357                                byte[] audioBytes,
    356358                                AudioFormat format,
  • trunk/src/org/apollo/gui/WaveFormRenderer.java

    r315 r1102  
    1313         *
    1414         * A single height is calculated for one or more frames, which is specified by the
    15          * aggregationSize. The way in which waveforms are rendered is implementation dependant.
     15         * aggregationSize. The way in which waveforms are rendered is implementation dependent.
    1616         *
    1717         * @param audioBytes
     
    2222         *
    2323         * @param frameLength
    24          *              The amount of frames to consider for rendering.
     24         *              The number of frames to consider for rendering.
    2525         *
    2626         * @param aggregationSize
    27          *              The amout of frames to aggregate.
     27         *              The amount of frames to aggregate.
    2828         *
    2929         * @return
  • trunk/src/org/apollo/gui/ZoomChangeListener.java

    r315 r1102  
    33import java.awt.Event;
    44
    5 public interface ZoomChangeListener {
     5public interface ZoomChangeListener
     6{
    67        void zoomChanged(Event e);
    78}
  • trunk/src/org/apollo/io/AudioIO.java

    r1007 r1102  
    167167                if (!sourceFormat.getEncoding().toString().startsWith("PCM")) {
    168168                       
    169                         AudioFormat.Encoding conversionEncoding =
    170                                 (sourceFormat.getSampleSizeInBits() == 8) ?
    171                                 AudioFormat.Encoding.PCM_UNSIGNED :
    172                                 AudioFormat.Encoding.PCM_SIGNED;
     169                        AudioFormat.Encoding conversionEncoding = (sourceFormat.getSampleSizeInBits() == 8) ? AudioFormat.Encoding.PCM_UNSIGNED : AudioFormat.Encoding.PCM_SIGNED;
    173170                       
    174171                        aisConverter = AudioSystem.getAudioInputStream(conversionEncoding, aisConverter);
  • trunk/src/org/apollo/io/IconRepository.java

    r759 r1102  
    11package org.apollo.io;
    22
    3 import java.awt.Color;
    4 import java.awt.Graphics2D;
    5 import java.awt.Image;
    6 import java.awt.image.BufferedImage;
    73import java.net.URL;
    84import java.util.HashMap;
    95
    10 import javax.swing.Icon;
    11 import javax.swing.ImageIcon;
    12 
    136import org.apollo.gui.Strokes;
     7import org.expeditee.core.Colour;
     8import org.expeditee.core.Image;
     9import org.expeditee.core.Line;
     10import org.expeditee.gio.EcosystemManager;
     11import org.expeditee.gio.GraphicsManager;
    1412
    1513/**
    16  * An icon provider. Only loads icons once and when they are requested (somple proxy approach).
     14 * An icon provider. Only loads icons once and when they are requested (simple proxy approach).
    1715 *
    1816 * @author Brook Novak
     
    2119public final class IconRepository {
    2220       
    23         private static HashMap<String, Icon> _loadedIcons = new HashMap<String, Icon>();
    24         private static Icon missingIcon = null;
     21        private static HashMap<String, Image> _loadedIcons = new HashMap<String, Image>();
     22       
     23        private static Image missingIcon = null;
    2524
    26         private IconRepository() {}
     25        private IconRepository()
     26        {
     27        }
    2728       
    28         private static Icon getMissingIcon() {
    29                
     29        private static Image getMissingIcon()
     30        {
    3031                if (missingIcon == null) {
    3132                       
    32                         Image image = new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
    33                         Graphics2D g = (Graphics2D)image.getGraphics();
     33                        Image image = EcosystemManager.getImageManager().createImage(16, 16, false);
    3434                       
    35                         g.setStroke(Strokes.SOLID_2);
     35                        GraphicsManager g = EcosystemManager.getGraphicsManager();
    3636                       
    37                         // White square with X
    38                         g.setColor(Color.WHITE);
    39                         g.fillRect(0, 0, 16, 16);
     37                        g.pushDrawingSurface(image);
    4038                       
    41                         g.setColor(Color.RED);
    42                         g.drawLine(0, 0, 16, 16);
    43                         g.drawLine(0, 16, 16, 0);
     39                        g.clear(Colour.WHITE);
     40
     41                        Line l1 = new Line(0, 0, 16, 16);
     42                        Line l2 = new Line(0, 16, 16, 0);
     43
     44                        g.drawLine(l1, Colour.RED, Strokes.SOLID_2);
     45                        g.drawLine(l2, Colour.RED, Strokes.SOLID_2);
    4446                       
    45                         missingIcon = new ImageIcon(image);
     47                        g.popDrawingSurface();
     48                       
     49                        missingIcon = image;
    4650                }
    4751                       
     
    5458         * @return
    5559         */
    56         public static Icon getIcon(String name) {
    57                 Icon icon = _loadedIcons.get(name);
     60        public static Image getIcon(String name)
     61        {
     62                Image icon = _loadedIcons.get(name);
    5863               
    5964                if (icon == null) {
    6065                        try {
    61                                 URL url;
     66                                URL url;
    6267                                ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    6368                                if (classLoader!=null) {
    6469                                    // Applet friendly
    6570                                    url = classLoader.getResource("org/apollo/assets/icons/" + name);
    66                                 }
    67                                 else {
     71                                } else {
    6872                                    url = ClassLoader.getSystemResource("org/apollo/assets/icons/" + name);
    6973                                }
    7074
    71                                 if (url != null) {
    72                                         icon = new ImageIcon(url);
    73                                 }
    74                                
     75                                if (url != null) icon = Image.getImage(url);
    7576                        } catch (Exception e) {
    7677                                e.printStackTrace();
  • trunk/src/org/apollo/io/SampledAudioFileImporter.java

    r318 r1102  
    11package org.apollo.io;
    22
    3 import java.awt.Point;
    43import java.io.File;
    54import java.io.IOException;
    65
    76import org.apollo.widgets.SampledTrack;
    8 import org.expeditee.gui.DisplayIO;
     7import org.expeditee.core.Point;
     8import org.expeditee.gui.DisplayController;
    99import org.expeditee.importer.FileImporter;
    1010import org.expeditee.items.Item;
     
    1818public class SampledAudioFileImporter implements FileImporter {
    1919
    20         public Item importFile(File f, Point location) throws IOException {
    21 
    22                 if (location == null || !AudioIO.canImportFile(f) ||
    23                                 DisplayIO.getCurrentFrame() == null) return null;
     20        public Item importFile(File f, Point location) throws IOException
     21        {
     22                if (location == null || !AudioIO.canImportFile(f) || DisplayController.getCurrentFrame() == null) return null;
    2423               
    2524                SampledTrack trackWidget = SampledTrack.createFromFile(
    2625                                f,
    27                                 DisplayIO.getCurrentFrame(),
     26                                DisplayController.getCurrentFrame(),
    2827                                location.x,
    2928                                location.y);
    3029               
    3130                // Add the sampled track widget to the current frame
    32                 DisplayIO.getCurrentFrame().addAllItems(trackWidget.getItems());
     31                DisplayController.getCurrentFrame().addAllItems(trackWidget.getItems());
    3332               
    3433                return trackWidget.getSource(); // Don't allow for other importers to deal with this file
  • trunk/src/org/apollo/items/EmulatedTextItem.java

    r489 r1102  
    11package org.apollo.items;
    22
    3 import java.awt.AWTException;
    4 import java.awt.Color;
    5 import java.awt.Component;
    6 import java.awt.Cursor;
    7 import java.awt.Font;
    8 import java.awt.Graphics;
    9 import java.awt.Graphics2D;
    10 import java.awt.IllegalComponentStateException;
    11 import java.awt.Point;
    12 import java.awt.Rectangle;
    13 import java.awt.Robot;
    14 import java.awt.Shape;
    153import java.awt.event.KeyEvent;
    164import java.awt.event.KeyListener;
     
    186import java.awt.event.MouseListener;
    197import java.awt.event.MouseMotionListener;
    20 import java.awt.geom.Area;
    21 import java.awt.geom.Point2D;
    228import java.util.LinkedList;
    239import java.util.List;
    2410
    25 import javax.swing.JComponent;
    26 import javax.swing.SwingUtilities;
    27 
    28 import org.expeditee.gui.Browser;
    29 import org.expeditee.gui.DisplayIO;
     11import org.expeditee.core.Clip;
     12import org.expeditee.core.Colour;
     13import org.expeditee.core.Cursor;
     14import org.expeditee.core.Font;
     15import org.expeditee.core.Point;
     16import org.expeditee.core.EnforcedClipStack.EnforcedClipKey;
     17import org.expeditee.core.bounds.AxisAlignedBoxBounds;
     18import org.expeditee.gio.EcosystemManager;
     19import org.expeditee.gio.GraphicsManager;
     20import org.expeditee.gio.gesture.StandardGestureActions;
     21import org.expeditee.gui.DisplayController;
    3022import org.expeditee.gui.Frame;
    31 import org.expeditee.gui.FrameGraphics;
    32 import org.expeditee.gui.FrameMouseActions;
    33 import org.expeditee.gui.MouseEventRouter;
    3423import org.expeditee.gui.Popup;
    3524import org.expeditee.gui.PopupManager;
     
    3827
    3928/**
    40  *
    4129 * Its a terrible hack - but it will do.
    4230 *
     
    4432 *
    4533 */
    46 public class EmulatedTextItem {
    47 
    48         private static final long serialVersionUID = 1L;
    49        
    50         private static Robot robot;
    51 
     34public class EmulatedTextItem
     35{
    5236        private List<TextChangeListener> textChangeListeners = new LinkedList<TextChangeListener>();
    5337       
    5438        private RestrictedTextItem emulatedSource;
    5539        private LabelEditPopup popup = null;
    56         private JComponent parentComponant = null;
    57         private Point masterOffset;
    58        
    59         private static final Font DEFAULT_FONT = new Font("Serif-Plain", Font.PLAIN, 12);
    60        
    61         static {
    62                 try {
    63                         robot = new Robot();
    64                 } catch (AWTException e) {
    65                         e.printStackTrace();
    66                 }
    67         }
     40       
     41        private static final Font DEFAULT_FONT = new Font("Serif-Plain", Font.Style.PLAIN, 12);
    6842       
    6943        /**
     
    7751         *              Must not be null.
    7852         */
    79         public EmulatedTextItem(JComponent parent, Point offset) {
    80                 assert(parent != null);
    81                 assert(offset != null);
    82                
    83                 parentComponant = parent;
    84                 masterOffset = offset;
     53        public EmulatedTextItem(String text, Point position)
     54        {
     55                assert(position != null);
     56               
    8557                emulatedSource = new RestrictedTextItem();
    86                 emulatedSource.setPosition(parent.getX() + offset.x, parent.getY() + offset.y);
     58                emulatedSource.setPosition(position);
    8759                emulatedSource.setFont(DEFAULT_FONT);
    88 
    89         }
    90        
    91        
    92         public void setFontStyle(int style) {
    93                 emulatedSource.setFont(emulatedSource.getFont().deriveFont(style));
    94         }
    95        
    96         public void setFontSize(float size) {
     60                emulatedSource.setText(text);
     61               
     62                popup = new LabelEditPopup();
     63                PopupManager.getInstance().add(popup);
     64        }
     65       
     66        @Override
     67        public void finalize()
     68        {
     69                PopupManager.getInstance().remove(popup);
     70        }
     71       
     72        public void setFontStyle(Font.Style style)
     73        {
     74                emulatedSource.setFont(emulatedSource.getFont().clone().setStyle(style));
     75        }
     76       
     77        public void setFontSize(float size)
     78        {
    9779                emulatedSource.setSize(size);
    9880        }
    9981       
     82        public void setPosition(Point position)
     83        {
     84                emulatedSource.setPosition(position);
     85        }
    10086       
    10187        /**
     
    10793         *              True if the event is over the emulated item.
    10894         */
    109         private boolean isOnEmulatedText(MouseEvent swingME) {
    110                 if (swingME == null) return false;
    111                 Point p = convertToExpediteeSpace(swingME.getLocationOnScreen());
     95        private boolean isOnEmulatedText()
     96        {
     97                Point p = EcosystemManager.getInputManager().getCursorPosition();
     98               
    11299                return isOnEmulatedText(p.x, p.y);
    113100        }
    114101       
    115         private boolean isOnEmulatedText(int expX, int expY) {
     102        private boolean isOnEmulatedText(int expX, int expY)
     103        {
    116104                return emulatedSource.contains(expX, expY);
    117         }
    118        
    119         private Point convertToExpediteeSpace(Point screenPos) {
    120                 assert(screenPos != null);
    121                
    122                 Point expPoint = new Point(0, 0);
    123                 SwingUtilities.convertPointToScreen(expPoint, Browser._theBrowser.getContentPane());
    124                
    125                 return new Point(screenPos.x - expPoint.x, screenPos.y - expPoint.y);
    126105        }
    127106       
     
    132111         * @param parent
    133112         */
    134         public boolean onMouseMoved(MouseEvent e, Component parent) {
    135 
    136                 if (isOnEmulatedText(e)) {
     113        public boolean onMouseMoved(MouseEvent e)
     114        {
     115                if (isOnEmulatedText()) {
    137116                       
    138117                        if (emulatedSource.getHighlightMode() != HighlightMode.Normal) {
    139118                                emulatedSource.setHighlightMode(HighlightMode.Normal);
     119                                emulatedSource.setHighlightColorToDefault();
    140120                                repaint();
    141121                        }
    142122                       
    143                         if (parent != popup &&
    144                                         (emulatedSource.getBoundsWidth() + masterOffset.x) > (parent.getWidth() - 10)) { // have some give to transition over widget edge
    145                                 if (popup == null) {
    146                                         popup = new LabelEditPopup();
    147                                 }
    148                                
    149                                 int x = (emulatedSource.getPolygon() == null) ? parent.getX() + masterOffset.x : emulatedSource.getPolygon().getBounds().x;
    150                                 int y = (emulatedSource.getPolygon() == null) ? parent.getY() + masterOffset.y : emulatedSource.getPolygon().getBounds().y;
    151                                 x -= 2;
    152                                 y -= 2;
    153 
    154                                 if (!PopupManager.getInstance().isShowing(popup)) {
    155                                         PopupManager.getInstance().showPopup(
    156                                                         popup,
    157                                                         new Point(x, y),
    158                                                         popup); 
    159                                 }
    160                                
    161                         }
    162                        
    163123                        return true;
    164                        
    165124                } else {
    166                        
    167125                        lostFocus();
    168 
    169126                }
    170127               
    171128                return false;
    172                
    173         }
    174        
    175         /**
    176          *
    177          * @param e
    178          *
    179          * @param parent
    180          */
    181         public boolean onKeyPressed(KeyEvent e, Component parent) {
    182 
    183                 MouseEvent currentME = MouseEventRouter.getCurrentMouseEvent();
    184                
    185                 if (currentME == null) return false;
    186                
    187                 Point p = convertToExpediteeSpace(currentME.getLocationOnScreen());
     129        }
     130       
     131        public boolean onKeyTyped(KeyEvent e)
     132        {
     133                Point p = EcosystemManager.getInputManager().getCursorPosition();
    188134
    189135                // If so and the event really comes from its parent ...
    190                 if (currentME.getComponent() == parent &&
    191                                 (isOnEmulatedText(p.x, p.y))) {
    192                        
    193                         int yOffset = (parent == popup) ? -6 : -6;
    194                        
    195                         Browser._theBrowser.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
     136                if (isOnEmulatedText(p.x, p.y)) {
     137                       
     138                        int yOffset = -6;
     139                       
     140                        EcosystemManager.getGraphicsManager().setCursor(new Cursor(Cursor.CursorType.TEXT));
    196141
    197142                        // If a alphanumeric text entry...
    198                         if (!e.isActionKey() &&
    199                                         (Character.isLetterOrDigit(e.getKeyChar()) ||
    200                                                         (e.getKeyChar() == KeyEvent.VK_BACK_SPACE && !emulatedSource.isEmpty()) ||
    201                                                         (e.getKeyChar() == KeyEvent.VK_DELETE && !emulatedSource.isEmpty()) ||
    202                                                         e.getKeyChar() == KeyEvent.VK_SPACE ||
    203                                                         e.getKeyChar() == KeyEvent.VK_UNDERSCORE) ||
    204                                                         e.getKeyChar() == KeyEvent.VK_AMPERSAND ||
    205                                                         e.getKeyChar() == KeyEvent.VK_OPEN_BRACKET ||
    206                                                         e.getKeyChar() == KeyEvent.VK_CLOSE_BRACKET ||
    207                                                         e.getKeyChar() == KeyEvent.VK_MINUS) {
    208 
    209 
    210                                 Rectangle[] oldArea = emulatedSource.getDrawingArea();
    211                                 int oldWidth = emulatedSource.getBoundsWidth();
    212                                
     143                        if (!e.isActionKey() &&
     144                                        Character.isLetterOrDigit(e.getKeyChar()) ||
     145                                        (e.getKeyChar() == Text.BACKSPACE_CHARACTER && !emulatedSource.isEmpty()) ||
     146                                        (e.getKeyChar() == Text.DELETE_CHARACTER && !emulatedSource.isEmpty()) ||
     147                                        e.getKeyChar() == ' ' ||
     148                                        e.getKeyChar() == '_' ||
     149                                        e.getKeyChar() == '&' ||
     150                                        e.getKeyChar() == '(' ||
     151                                        e.getKeyChar() == ')' ||
     152                                        e.getKeyChar() == '-'
     153                                )
     154                        {
    213155                                // Insert the text according to the current mouse position
    214                                 Point2D.Float newMouse = emulatedSource.insertChar(
    215                                                 e.getKeyChar(),
    216                                                 p.x,
    217                                                 p.y);
     156                                Point newMouse = emulatedSource.insertChar(e.getKeyChar(), p.x, p.y);
    218157                               
    219158                                List<String> lines = emulatedSource.getTextList();
     
    225164                                fireTextChanged();
    226165
    227                                 // Move "cursured mouse"
     166                                // Move "cursored mouse"
    228167                                if (newMouse != null) {
    229                                         Point bloc = Browser._theBrowser.getContentPane().getLocationOnScreen();
    230                                         robot.mouseMove(bloc.x + (int)newMouse.x, bloc.y + (int)newMouse.y + yOffset);
     168                                        EcosystemManager.getInputManager().setCursorPosition(new Point((int) newMouse.x, (int) newMouse.y + yOffset));
    231169                                }
    232                                
    233                                 // Invalidate emulated item if not in popup (popup will naturally handle invalidation)
    234                                 if (parent != popup) {
    235 
    236                                         if (oldWidth > emulatedSource.getBoundsWidth()) {
    237                                                 for (Rectangle r : oldArea)
    238                                                         FrameGraphics.invalidateArea(r);
    239                                         }
    240                                        
    241                                         repaint();
    242 
    243                                 }
    244                                
    245                         } else if (e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_RIGHT) {
    246                                
    247                                 Point2D.Float newMouse = emulatedSource.moveCursor(
    248                                                 (e.getKeyCode() == KeyEvent.VK_LEFT) ? Text.LEFT : Text.RIGHT,
    249                                                 (float)p.getX(), (float)p.getY(), false, false);
    250                                
    251                                 if (newMouse != null) {
    252                                         Point bloc = Browser._theBrowser.getContentPane().getLocationOnScreen();
    253                                         robot.mouseMove(bloc.x + (int)newMouse.x, bloc.y + (int)newMouse.y + yOffset);
    254                                 }
    255 
    256170                        }
    257171                       
     
    274188         * @param parent
    275189         */
    276         public boolean onKeyReleased(KeyEvent e, Component parent) {
    277                 return isOnEmulatedText(MouseEventRouter.getCurrentMouseEvent());
    278                
    279         }
    280        
    281        
    282         public boolean onMouseReleased(MouseEvent e) {
    283                
    284                 Point p = convertToExpediteeSpace(e.getLocationOnScreen());
     190        public boolean onKeyPressed(KeyEvent e)
     191        {
     192                Point p = EcosystemManager.getInputManager().getCursorPosition();
    285193
    286194                // If so and the event really comes from its parent ...
    287195                if (isOnEmulatedText(p.x, p.y)) {
    288196                       
     197                        int yOffset = -6;
     198                       
     199                        EcosystemManager.getGraphicsManager().setCursor(new Cursor(Cursor.CursorType.TEXT));
     200
     201                        // If a alphanumeric text entry...
     202                        if (e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_RIGHT) {
     203                               
     204                                Point newMouse = emulatedSource.moveCursor(
     205                                                (e.getKeyCode() == KeyEvent.VK_LEFT) ? Text.LEFT : Text.RIGHT,
     206                                                (float)p.getX(), (float)p.getY(), false, false);
     207                               
     208                                if (newMouse != null) {
     209                                        EcosystemManager.getInputManager().setCursorPosition(new Point((int) newMouse.x, (int) newMouse.y + yOffset));
     210                                }
     211
     212                        }
     213                       
     214                        if (emulatedSource.hasSelection()) {
     215                                emulatedSource.clearSelection();
     216                                repaint();
     217                        }
     218                       
     219                        return true;
     220                       
     221                }
     222               
     223                return false;
     224        }
     225       
     226        /**
     227         *
     228         * @param e
     229         *
     230         * @param parent
     231         */
     232        public boolean onKeyReleased(KeyEvent e)
     233        {
     234                return isOnEmulatedText();
     235        }
     236       
     237       
     238        public boolean onMouseReleased(MouseEvent e)
     239        {
     240                Point p = EcosystemManager.getInputManager().getCursorPosition();
     241
     242                // If so and the event really comes from its parent ...
     243                if (isOnEmulatedText(p.x, p.y)) {
    289244                       
    290245                        String toMoveIntoFreespace = null;
     
    292247                        if (e.getButton() == MouseEvent.BUTTON1) {
    293248                                // LINK
    294                         } else if (e.getButton() == MouseEvent.BUTTON2 &&
    295                                         emulatedSource.hasSelection() &&
    296                                         !emulatedSource.isEmpty() &&
    297                                         emulatedSource.selectionMouseButton == MouseEvent.BUTTON2) {
     249                        } else if (e.getButton() == MouseEvent.BUTTON2 && emulatedSource.hasSelection() && !emulatedSource.isEmpty()) {
    298250       
    299251                                invalidate();
     
    301253                                toMoveIntoFreespace = emulatedSource.cutSelectedText();
    302254                               
    303                         } else if (e.getButton() == MouseEvent.BUTTON3 &&
    304                                         emulatedSource.hasSelection() &&
    305                                         !emulatedSource.isEmpty() &&
    306                                         emulatedSource.selectionMouseButton == MouseEvent.BUTTON3) {
     255                        } else if (e.getButton() == MouseEvent.BUTTON3 && emulatedSource.hasSelection() && !emulatedSource.isEmpty()) {
    307256                                toMoveIntoFreespace = emulatedSource.copySelectedText();
    308257                               
     
    315264                        if (toMoveIntoFreespace != null) {
    316265                               
    317                                 Frame target = DisplayIO.getCurrentFrame();
     266                                Frame target = DisplayController.getCurrentFrame();
    318267                                if (target != null) {
    319268                                        Text selectionCopy = new Text(target.getNextItemID(), toMoveIntoFreespace);
    320269                                        selectionCopy.setPosition(p.x, p.y);
    321270                                        selectionCopy.setSize(emulatedSource.getSize());
    322                                         FrameMouseActions.pickup(selectionCopy);
     271                                        StandardGestureActions.pickup(selectionCopy);
    323272                                        lostFocus();
    324273                                }
     
    336285        }
    337286       
    338         public boolean onMousePressed(MouseEvent e) {
    339 
    340                 Point p = convertToExpediteeSpace(e.getLocationOnScreen());
     287        public boolean onMousePressed(MouseEvent e)
     288        {
     289                Point p = EcosystemManager.getInputManager().getCursorPosition();
    341290
    342291                // If so and the event really comes from its parent ...
     
    354303        }
    355304       
    356         public boolean onMouseClicked(MouseEvent e) {
    357                 return isOnEmulatedText(e);
    358         }
    359         public boolean onMouseDragged(MouseEvent e) {
    360 
    361                 Point p = convertToExpediteeSpace(e.getLocationOnScreen());
     305        public boolean onMouseClicked(MouseEvent e)
     306        {
     307                return isOnEmulatedText();
     308        }
     309       
     310        public boolean onMouseDragged(MouseEvent e)
     311        {
     312                Point p = EcosystemManager.getInputManager().getCursorPosition();
    362313
    363314                // If so and the event really comes from its parent ...
    364315                if (isOnEmulatedText(p.x, p.y)) {
    365316
    366                         Browser._theBrowser.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
     317                        EcosystemManager.getGraphicsManager().setCursor(new Cursor(Cursor.CursorType.TEXT));
    367318                       
    368319                        emulatedSource.setSelectionEnd(p.x, p.y);
     
    375326        }
    376327       
    377         public void addTextChangeListener(TextChangeListener listener) {
     328        public void addTextChangeListener(TextChangeListener listener)
     329        {
    378330                assert(listener != null);
    379                 if (!textChangeListeners.contains(listener))
    380                         textChangeListeners.add(listener);
    381         }
    382        
    383         public void lostFocus() {
    384                 Browser._theBrowser.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
     331                if (!textChangeListeners.contains(listener)) textChangeListeners.add(listener);
     332        }
     333       
     334        public void gainFocus()
     335        {
     336                if (popup != null && !PopupManager.getInstance().isShowing(popup)) {
     337                        popup.show();
     338                }
     339        }
     340       
     341        public void lostFocus()
     342        {
     343                EcosystemManager.getGraphicsManager().setCursor(new Cursor(Cursor.CursorType.DEFAULT));
    385344               
    386345                boolean dirty = false;
     
    392351                if (emulatedSource.getHighlightMode() != HighlightMode.None) {
    393352                        emulatedSource.setHighlightMode(HighlightMode.None);
     353                        emulatedSource.setHighlightColorToDefault();
    394354                        dirty = true;
    395355                }
    396356
    397                 if (popup != null &&
    398                                 PopupManager.getInstance().isShowing(popup)) {
    399                         PopupManager.getInstance().hidePopup(popup);
     357                if (popup != null && PopupManager.getInstance().isShowing(popup)) {
     358                        popup.hide();
    400359                }
    401360               
     
    410369         *              Null is allowed
    411370         */
    412         public void setText(String text) {
     371        public void setText(String text)
     372        {
    413373                if (text == null) text = "";
    414374               
     
    424384        }
    425385       
    426         public String getText() {
     386        public String getText()
     387        {
    427388                return emulatedSource.getText();
    428389        }
    429390       
    430         private void fireTextChanged() {
    431                
    432                 for (TextChangeListener listener : textChangeListeners)
     391        private void fireTextChanged()
     392        {
     393                for (TextChangeListener listener : textChangeListeners) {
    433394                        listener.onTextChanged(this, this.emulatedSource.getText());
    434                
    435         }
    436 
    437         public void setBackgroundColor(Color c) {
     395                }
     396        }
     397
     398        public void setBackgroundColor(Colour c)
     399        {
    438400                emulatedSource.setBackgroundColor(c);
    439401        }
    440402       
    441         private void repaint() {
    442 
     403        private void repaint()
     404        {
    443405                if (popup != null && PopupManager.getInstance().isShowing(popup)) {
    444406                        popup.invalidateAppearance();
    445                         FrameGraphics.refresh(true);
     407                        DisplayController.requestRefresh(true);
    446408                } else {
    447409                        invalidate();
    448                         FrameGraphics.refresh(true);
    449                 }
    450         }
    451        
    452         private void invalidate() {
    453                 for (Rectangle r : emulatedSource.getDrawingArea())
    454                         FrameGraphics.invalidateArea(r);
    455         }
    456 
    457         public void paint(Graphics g) {
    458                
    459                 if ((popup != null && PopupManager.getInstance().isShowing(popup)) ||
    460                                 !parentComponant.isShowing())
    461                         return;
    462                
    463                 Point pos;
    464                 try {
    465                 pos = this.convertToExpediteeSpace(parentComponant.getLocationOnScreen());
    466                 } catch (Exception e) {
    467                         e.printStackTrace();
    468                         return;
    469                 }
    470 
    471                 paint(  g,
    472                                 pos.x + masterOffset.x,
    473                                 pos.y + masterOffset.y,
    474                                 parentComponant.getWidth() - masterOffset.x);
    475         }
    476        
    477         private void paint(Graphics g, int parentX, int parentY, int maxWidth) {
    478 
    479                 if (Browser._theBrowser == null) return;
    480                
    481                 /*int xoffset = (emulatedSource.getLink() == null) ? 6 : 18;
    482                 int yoffset = emulatedSource.getBoundsHeight() - 3;
    483                 parentX += xoffset;
    484                 parentY += yoffset;*/
    485                
    486                 // Set the emulated position according to the parent position - the parent position
    487                 // can be from the popup or the actual parent componant
    488                 if (emulatedSource.getX() != parentX || emulatedSource.getY() != parentY)
    489                         emulatedSource.setPosition(parentX, parentY);
    490 
    491                 Shape saveClip = g.getClip();
    492                
    493                 if (maxWidth > 0) {
    494                        
    495                         Area clip = FrameGraphics.getCurrentClip();
    496 
    497                         Area tmpClip = (clip != null) ? clip :
    498                                 new Area(new Rectangle(0, 0,
    499                                                 Browser._theBrowser.getContentPane().getWidth(),
    500                                                 Browser._theBrowser.getContentPane().getHeight()));
    501                        
    502                 /*      tmpClip.intersect(new Area(new Rectangle(0, 0,
    503                                         parentX + maxWidth - xoffset, Browser._theBrowser.getContentPane().getHeight()
    504                         )));*/
    505                        
    506                         tmpClip.intersect(new Area(new Rectangle(0, 0,
    507                                         parentX + maxWidth, Browser._theBrowser.getContentPane().getHeight()
    508                         )));
    509        
    510                         // No intersection
    511                         if (!tmpClip.isEmpty())
    512                                 g.setClip(tmpClip);
    513                
    514                 }
    515                
    516                 emulatedSource.paint((Graphics2D)g);
    517                
    518                 // Restore
    519                 if (maxWidth > 0) {
    520                         g.setClip(saveClip);
    521                 }
    522                
    523                 // Restore emulated position for consuming mouse movements
    524                 try {
    525                 Point pos = this.convertToExpediteeSpace(parentComponant.getLocationOnScreen());
    526                 emulatedSource.setPosition(
    527                                 pos.x + masterOffset.x,
    528                                 pos.y + masterOffset.y);
    529                 } catch (IllegalComponentStateException ex) { // Cannot fix this .. this whole class needs revising
    530                         ex.printStackTrace();
    531                 }
     410                        DisplayController.requestRefresh(true);
     411                }
     412        }
     413       
     414        private void invalidate()
     415        {
     416                DisplayController.invalidateArea(emulatedSource.getDrawingArea());
     417        }
     418       
     419        public void paint()
     420        {
     421                GraphicsManager gm = EcosystemManager.getGraphicsManager();
     422
     423                EnforcedClipKey key = gm.pushClip(new Clip(emulatedSource.getDrawingArea()));
     424               
     425                emulatedSource.paint();
     426
     427                gm.popClip(key);
    532428        }
    533429       
     
    537433        }
    538434       
    539         private class LabelEditPopup extends Popup implements KeyListener, MouseListener, MouseMotionListener {
    540                
    541                 private static final long serialVersionUID = 1L;
    542                
    543                 LabelEditPopup() {
    544                         super.setAudoHide(true);
     435        private class LabelEditPopup extends Popup implements KeyListener, MouseListener, MouseMotionListener
     436        {
     437                LabelEditPopup()
     438                {
     439                        super(null); // No animation (instant show/hide)
    545440                        super.setConsumeBackClick(false);
    546441                        super.setBorderThickness(0);
    547                        
    548                         updateSize();
    549                        
    550                         addKeyListener(this);
    551                         addMouseListener(this);
    552                         addMouseMotionListener(this);
    553                 }
    554                
    555                 public void updateSize() {
    556                         setSize(emulatedSource.getBoundsWidth() + 4, emulatedSource.getBoundsHeight() + 4);
    557                 }
    558        
    559 
    560                 public void keyPressed(KeyEvent e) {
    561                         onKeyPressed(e, LabelEditPopup.this);
    562                         updateSize();
    563                 }
    564 
    565                 public void keyReleased(KeyEvent e) {
    566                 }
    567                
    568 
    569                 public void keyTyped(KeyEvent e) {
    570                 }
    571                
    572                
    573                 public void mouseClicked(MouseEvent e) {
    574                 }
    575 
    576                 public void mouseEntered(MouseEvent e) {
    577                 }
    578 
    579                 public void mouseExited(MouseEvent e) {
    580                 }
    581 
    582                 public void mousePressed(MouseEvent e) {
    583                         onMousePressed(e);
    584                 }
    585 
    586                 public void mouseReleased(MouseEvent e) {
    587                         onMouseReleased(e);
    588                         updateSize();
    589                 }
    590                
    591 
    592                 public void mouseDragged(MouseEvent e) {
    593                         onMouseDragged(e);
    594                 }
    595 
    596                 public void mouseMoved(MouseEvent e) {
    597 
    598                 }
    599 
    600                 @Override
    601                 public void onHide() {
    602                         super.onHide();
    603                 }
    604        
    605                 @Override
    606                 public void onShow() {
    607                         super.onShow();
    608                 }
    609                
    610                
    611 
    612                 @Override
    613                 public void paint(Graphics g) {
    614                        
    615                         EmulatedTextItem.this.paint(g, 7, 16, -1);
    616 
    617                 }
    618        
    619         }
    620        
    621         private class RestrictedTextItem extends Text {
    622                
    623                 private Color selectionColor = null;
    624                 private int selectionMouseButton = -1;
    625                
    626                 RestrictedTextItem() {
     442                }
     443
     444                @Override
     445                public void onHide()
     446                {
     447                }
     448       
     449                @Override
     450                public void onShow()
     451                {
     452                }
     453               
     454                @Override
     455                public void paintInternal()
     456                {
     457                        EmulatedTextItem.this.paint();
     458                }
     459
     460                @Override
     461                public AxisAlignedBoxBounds getFullBounds()
     462                {
     463                        return emulatedSource.getDrawingArea();
     464                }
     465
     466                @Override
     467                public void mouseDragged(MouseEvent e)
     468                {
     469                        boolean consume = onMouseDragged(e);
     470                        if (consume) e.consume();
     471                }
     472
     473                @Override
     474                public void mouseMoved(MouseEvent e)
     475                {
     476                        boolean consume = onMouseMoved(e);
     477                        if (consume) e.consume();
     478                }
     479
     480                @Override
     481                public void mouseClicked(MouseEvent e)
     482                {
     483                        boolean consume = onMouseClicked(e);
     484                        if (consume) e.consume();
     485                }
     486
     487                @Override
     488                public void mousePressed(MouseEvent e)
     489                {
     490                        boolean consume = onMousePressed(e);
     491                        if (consume) e.consume();
     492                }
     493
     494                @Override
     495                public void mouseReleased(MouseEvent e)
     496                {
     497                        boolean consume = onMouseReleased(e);
     498                        if (consume) e.consume();
     499                }
     500
     501                @Override
     502                public void mouseEntered(MouseEvent e)
     503                {
     504                        // Not required
     505                }
     506
     507                @Override
     508                public void mouseExited(MouseEvent e)
     509                {
     510                        // Not required
     511                }
     512
     513                @Override
     514                public void keyTyped(KeyEvent e)
     515                {
     516                        boolean consume = onKeyTyped(e);
     517                        if (consume) e.consume();
     518                }
     519
     520                @Override
     521                public void keyPressed(KeyEvent e)
     522                {
     523                        boolean consume = onKeyPressed(e);
     524                        if (consume) e.consume();
     525                }
     526
     527                @Override
     528                public void keyReleased(KeyEvent e)
     529                {
     530                        boolean consume = onKeyReleased(e);
     531                        if (consume) e.consume();
     532                }
     533       
     534        }
     535       
     536        private class RestrictedTextItem extends Text
     537        {
     538                private Colour selectionColor = null;
     539               
     540                RestrictedTextItem()
     541                {
    627542                        super(1);
    628543                }
    629544               
    630                 private void updateSelection(int mouseButton) {
    631                         selectionColor = super.getSelectionColor(mouseButton);
    632                         selectionMouseButton = mouseButton;
    633                 }
    634 
    635                 public void setSelectionStart(float mouseX, float mouseY, int mouseButton) {
     545                private void updateSelection()
     546                {
     547                        selectionColor = super.getSelectionColour();
     548                }
     549
     550                public void setSelectionStart(float mouseX, float mouseY, int mouseButton)
     551                {
    636552                        super.setSelectionStart(mouseX, mouseY);
    637                         updateSelection(mouseButton);
    638                 }
    639                
    640                
    641 
    642                 @Override
    643                 protected Color getSelectionColor(int mouseButton) {
    644                        
    645                         if (selectionColor != null)
     553                        updateSelection();
     554                }
     555               
     556                @Override
     557                public Colour getSelectionColour()
     558                {
     559                        if (selectionColor != null) {
    646560                                return selectionColor;
    647                        
    648                         else return super.getSelectionColor(mouseButton);
     561                        } else {
     562                                return super.getSelectionColour();
     563                        }
    649564
    650565                }
  • trunk/src/org/apollo/items/FramePlaybackLauncher.java

    r489 r1102  
    11package org.apollo.items;
    2 
    3 import java.awt.Color;
    4 import java.awt.GradientPaint;
    5 import java.awt.Graphics2D;
    6 import java.awt.Paint;
    7 import java.awt.Polygon;
    8 import java.awt.Stroke;
    92
    103import org.apollo.ApolloSystem;
     
    2417import org.apollo.util.ODFrameHeirarchyFetcher.ODFrameReceiver;
    2518import org.apollo.widgets.FramePlayer;
     19import org.expeditee.core.Colour;
     20import org.expeditee.core.Dimension;
     21import org.expeditee.core.Fill;
     22import org.expeditee.core.GradientFill;
     23import org.expeditee.core.Point;
     24import org.expeditee.core.Stroke;
     25import org.expeditee.core.bounds.AxisAlignedBoxBounds;
     26import org.expeditee.core.bounds.Bounds;
     27import org.expeditee.gio.EcosystemManager;
     28import org.expeditee.gio.GraphicsManager;
    2629import org.expeditee.gui.Browser;
    27 import org.expeditee.gui.DisplayIO;
     30import org.expeditee.gui.DisplayController;
    2831import org.expeditee.gui.Frame;
    2932import org.expeditee.gui.FrameIO;
     
    4346        private static int WIDTH = 80;
    4447        private static int HEIGHT = 80;
    45         private static Stroke BORDER_STOKE = Strokes.SOLID_1;
    46        
    47         private static final Color BASE_COLOR = new Color(60, 148, 255);
    48         private static final Color HIGHLIGHT_COLOR = new Color(253, 255, 201);
     48        private static Stroke BORDER_STROKE = Strokes.SOLID_1;
     49       
     50        private static final Colour BASE_COLOR = Colour.FromRGB255(60, 148, 255);
     51        private static final Colour HIGHLIGHT_COLOR = Colour.FromRGB255(253, 255, 201);
    4952       
    5053        private String frameToPlay = null;
     
    7477
    7578        @Override
    76         public void paint(Graphics2D g) {
     79        public void paint()
     80        {
    7781                if (Browser._theBrowser == null) return;
    7882               
    79                 Paint restore = g.getPaint();
    80                
     83                GraphicsManager g = EcosystemManager.getGraphicsManager();
     84               
     85                Fill fill = null;
    8186                if (ApolloSystem.useQualityGraphics) {
    82                         GradientPaint gp = new GradientPaint(
    83                                         _x + (WIDTH / 2), _y, HIGHLIGHT_COLOR,
    84                                         _x + (WIDTH / 2), _y + HEIGHT - (HEIGHT / 5), BASE_COLOR);
    85                         g.setPaint(gp);
     87                        Point fromPoint = new Point(_x + (WIDTH / 2), _y);
     88                        Point toPoint = new Point(_x + (WIDTH / 2), _y + HEIGHT - (HEIGHT / 5));
     89                        fill = new GradientFill(HIGHLIGHT_COLOR, fromPoint, BASE_COLOR, toPoint);
    8690                } else {
    87                         g.setColor(BASE_COLOR);
    88                 }
    89                
    90                 g.fillRect((int)_x, (int)_y, WIDTH, HEIGHT);
    91                
    92                 g.setPaint(restore);
    93                
    94                 g.setColor(Color.BLACK);
    95                 g.setStroke(BORDER_STOKE);
    96                 g.drawRect((int)_x, (int)_y, WIDTH, HEIGHT);
    97                
    98                 IconRepository.getIcon("frameplay.png").paintIcon(
    99                                 Browser._theBrowser.getContentPane(), g, getX() + 25, getY() + 25);
     91                        fill = new Fill(BASE_COLOR);
     92                }
     93
     94                Point topLeft = new Point((int)_x, (int)_y);
     95                Dimension size = new Dimension(WIDTH, HEIGHT);
     96                g.drawRectangle(topLeft, size, 0.0, fill, Colour.BLACK, BORDER_STROKE, null);
     97               
     98                /*IconRepository.getIcon("frameplay.png").paintIcon(
     99                                Browser._theBrowser.getContentPane(), g, getX() + 25, getY() + 25);*/
     100               
     101                g.drawImage(IconRepository.getIcon("frameplay.png"), new Point(getX() + 25, getY() + 25));
    100102               
    101103        }
     
    117119
    118120        @Override
    119         public void updatePolygon() {
    120                
    121                 _poly = new Polygon();
    122 
    123                 int x = (int)_x;
    124                 int y = (int)_y;
    125                
    126                 _poly.addPoint(x, y);
    127                 _poly.addPoint(x + WIDTH, y);
    128                 _poly.addPoint(x + WIDTH, y + HEIGHT);
    129                 _poly.addPoint(x, y + HEIGHT);
    130 
     121        public Bounds updateBounds()
     122        {
     123                return new AxisAlignedBoxBounds((int) _x, (int) _y, WIDTH, HEIGHT);
    131124        }
    132125
     
    148141        }
    149142       
    150         private void selfDestruct() {
    151                
     143        private void selfDestruct()
     144        {
    152145                Frame parent = getParent();
    153146                parent.removeItem(this);
    154147               
    155                 if (DisplayIO.getCurrentFrame() == null) return;
     148                if (DisplayController.getCurrentFrame() == null) return;
    156149               
    157150                Frame audioFrame = null;
    158151               
    159152                // Flag as null if frame to play is actually current frame
    160                 if (frameToPlay != null && frameToPlay.equals(DisplayIO.getCurrentFrame().getName()))
     153                if (frameToPlay != null && frameToPlay.equals(DisplayController.getCurrentFrame().getName()))
    161154                        frameToPlay = null;
    162155               
    163156                if (frameToPlay == null) {
    164                         audioFrame = DisplayIO.getCurrentFrame();
     157                        audioFrame = DisplayController.getCurrentFrame();
    165158                } else {
    166159                        audioFrame = FrameIO.LoadFrame(frameToPlay);
     
    199192                        } else {
    200193                                // Fetch the audio graph for the frame
    201                                 GraphReceiver receiver = new GraphReceiver(DisplayIO.getCurrentFrame());
     194                                GraphReceiver receiver = new GraphReceiver(DisplayController.getCurrentFrame());
    202195                                ODFrameHeirarchyFetcher.getInstance().doFetch(audioFrame.getName(), receiver);
    203196                                // The callback will later begin playback
     
    257250                                // Thus the start frame will be hence taken as a percentage of the whole frame
    258251                               
    259                                 float percent = _x / Browser._theBrowser.getContentPane().getWidth();
     252                                float percent = _x / EcosystemManager.getGraphicsManager().getWindowSize().getWidth();
    260253                                if (percent < 0) percent = 0;
    261254                                if (percent > 1) percent = 1;
  • trunk/src/org/apollo/items/RecordOverdubLauncher.java

    r489 r1102  
    11package org.apollo.items;
    2 
    3 import java.awt.Color;
    4 import java.awt.GradientPaint;
    5 import java.awt.Graphics2D;
    6 import java.awt.Paint;
    7 import java.awt.Polygon;
    8 import java.awt.Stroke;
    92
    103import org.apollo.ApolloSystem;
     
    125import org.apollo.io.IconRepository;
    136import org.apollo.widgets.SampleRecorder;
     7import org.expeditee.core.Colour;
     8import org.expeditee.core.Dimension;
     9import org.expeditee.core.Fill;
     10import org.expeditee.core.GradientFill;
     11import org.expeditee.core.Point;
     12import org.expeditee.core.Stroke;
     13import org.expeditee.core.bounds.AxisAlignedBoxBounds;
     14import org.expeditee.core.bounds.Bounds;
     15import org.expeditee.gio.EcosystemManager;
     16import org.expeditee.gio.GraphicsManager;
    1417import org.expeditee.gui.Browser;
    15 import org.expeditee.gui.DisplayIO;
     18import org.expeditee.gui.DisplayController;
    1619import org.expeditee.gui.Frame;
    1720import org.expeditee.items.Item;
     
    2326                private static int WIDTH = 80;
    2427                private static int HEIGHT = 80;
    25                 private static Stroke BORDER_STOKE = Strokes.SOLID_1;
     28                private static Stroke BORDER_STROKE = Strokes.SOLID_1;
    2629                private int countdown;
    2730               
    28                 private static final Color BASE_COLOR = new Color(255, 100, 100);
    29                 private static final Color HIGHLIGHT_COLOR = new Color(253, 255, 201);
     31                private static final Colour BASE_COLOR = Colour.FromRGB255(255, 100, 100);
     32                private static final Colour HIGHLIGHT_COLOR = Colour.FromRGB255(253, 255, 201);
    3033               
    3134                public RecordOverdubLauncher(int countdown) {
     
    4952
    5053                @Override
    51                 public void paint(Graphics2D g) {
     54                public void paint() {
    5255                        if (Browser._theBrowser == null) return;
    5356                       
    54                         Paint restore = g.getPaint();
     57                        GraphicsManager g = EcosystemManager.getGraphicsManager();
    5558                       
     59                        Fill fill = null;
    5660                        if (ApolloSystem.useQualityGraphics) {
    57                                 GradientPaint gp = new GradientPaint(
    58                                                 _x + (WIDTH / 2), _y, HIGHLIGHT_COLOR,
    59                                                 _x + (WIDTH / 2), _y + HEIGHT - (HEIGHT / 5), BASE_COLOR);
    60                                 g.setPaint(gp);
     61                                Point fromPoint = new Point(_x + (WIDTH / 2), _y);
     62                                Point toPoint = new Point(_x + (WIDTH / 2), _y + HEIGHT - (HEIGHT / 5));
     63                                fill = new GradientFill(HIGHLIGHT_COLOR, fromPoint, BASE_COLOR, toPoint);
    6164                        } else {
    62                                 g.setColor(BASE_COLOR);
     65                                fill = new Fill(BASE_COLOR);
    6366                        }
    6467                       
    65                         g.fillRect((int)_x, (int)_y, WIDTH, HEIGHT);
     68                        Point topLeft = new Point((int)_x, (int)_y);
     69                        Dimension size = new Dimension(WIDTH, HEIGHT);
     70                        g.drawRectangle(topLeft, size, 0.0, fill, Colour.BLACK, BORDER_STROKE, null);
    6671                       
    67                         g.setPaint(restore);
     72                        /*IconRepository.getIcon("recordplay.png").paintIcon(
     73                                        Browser._theBrowser.getContentPane(), g, getX() + 25, getY() + 25);*/
    6874                       
    69                         g.setColor(Color.BLACK);
    70                         g.setStroke(BORDER_STOKE);
    71                         g.drawRect((int)_x, (int)_y, WIDTH, HEIGHT);
    72                        
    73                         IconRepository.getIcon("recordplay.png").paintIcon(
    74                                         Browser._theBrowser.getContentPane(), g, getX() + 25, getY() + 25);
     75                        g.drawImage(IconRepository.getIcon("recordplay.png"), new Point(getX() + 25, getY() + 25));
    7576                       
    7677                }
     
    9293
    9394                @Override
    94                 public void updatePolygon() {
    95                        
    96                         _poly = new Polygon();
    97 
    98                         int x = (int)_x;
    99                         int y = (int)_y;
    100                        
    101                         _poly.addPoint(x, y);
    102                         _poly.addPoint(x + WIDTH, y);
    103                         _poly.addPoint(x + WIDTH, y + HEIGHT);
    104                         _poly.addPoint(x, y + HEIGHT);
    105 
     95                public Bounds updateBounds()
     96                {
     97                        return new AxisAlignedBoxBounds((int) _x, (int) _y, WIDTH, HEIGHT);
    10698                }
    10799
     
    128120                        parent.removeItem(this);
    129121                       
    130                         Frame currentFrame = DisplayIO.getCurrentFrame();
     122                        Frame currentFrame = DisplayController.getCurrentFrame();
    131123                       
    132124                        if (currentFrame != null) {
  • trunk/src/org/apollo/meldex/PitchTracker.java

    r315 r1102  
    33import java.util.ArrayList;
    44
    5 @SuppressWarnings("unchecked") // code in java 1.4
    65public class PitchTracker
    76{
     
    1413
    1514    // The pitch data
    16     ArrayList pitchData;
     15    ArrayList<PitchValue> pitchData;
    1716
    1817    // Our lovely Pitch Period Estimators
     
    2625
    2726
    28     public ArrayList process(byte[] rawData, int rawLength, int rawSampleRate)
     27    public ArrayList<PitchValue> process(byte[] rawData, int rawLength, int rawSampleRate)
    2928    {
    3029        // Save the sample rate of the loaded sample
     
    3231
    3332        // Allocate a new pitch data array to store our pitch values
    34         pitchData = new ArrayList();
     33        pitchData = new ArrayList<PitchValue>();
    3534
    3635        // Reset our 6 pitch period estimators
  • trunk/src/org/apollo/meldex/PitchValue.java

    r315 r1102  
    1111    public PitchValue(double per, int pos)
    1212    {
    13         period = per;
    14         position = pos;
     13                period = per;
     14                position = pos;
    1515    }
    1616}
  • trunk/src/org/apollo/meldex/RogTrack.java

    r315 r1102  
    11package org.apollo.meldex;
    2 
    32
    43import java.io.File;
    54import java.io.FileInputStream;
    65import java.io.FileOutputStream;
     6import java.io.IOException;
    77import java.util.ArrayList;
    8 import javax.swing.JOptionPane;
    9 
    10 @SuppressWarnings("unchecked") // code in java 1.4
     8
     9import org.expeditee.gio.EcosystemManager;
     10
    1111public class RogTrack
    1212{
     
    2020
    2121    // Data representing the track events
    22     ArrayList trackData = new ArrayList();
     22    ArrayList<RogTrackEvent> trackData = new ArrayList<RogTrackEvent>();
    2323
    2424
     
    217217        int track_len = trackData.size();
    218218
    219         ArrayList filtered_td = new ArrayList();
     219        ArrayList<RogTrackEvent> filtered_td = new ArrayList<RogTrackEvent>();
    220220
    221221        for (int i = 0; i < track_len; i++) {
     
    235235        }
    236236
    237         ArrayList me_list = new ArrayList();
     237        ArrayList<MelodyEvent> me_list = new ArrayList<MelodyEvent>();
    238238
    239239        for (int i = 0; i < filtered_track_len-1; i++) {
     
    283283    public boolean loadFromFile(File rogFile)
    284284    {
    285         try {
    286             // Open the file with a FileInputStream, ready for parsing
    287             FileInputStream fileIn = new FileInputStream(rogFile);
    288 
    289             // Get the number of bytes in the file
    290             int rogLength = fileIn.available();
    291 
    292             // Create a buffer to store the file, and read the file into it
    293             byte[] rogData = new byte[rogLength];
    294             fileIn.read(rogData, 0, rogLength);
    295 
    296             // Parse the .rog file
    297             parseFile(rogData, rogLength);
    298         }
    299         catch (Exception ex) {
    300             JOptionPane.showMessageDialog(null, "Exception occurred reading file.\n\n" + ex);
    301             return false;
    302         }
    303 
    304         // File loaded successfully
    305         return true;
     285        boolean success = true;
     286        FileInputStream fileIn = null;
     287                try {
     288                    // Open the file with a FileInputStream, ready for parsing
     289                    fileIn = new FileInputStream(rogFile);
     290       
     291                    // Get the number of bytes in the file
     292                    int rogLength = fileIn.available();
     293       
     294                    // Create a buffer to store the file, and read the file into it
     295                    byte[] rogData = new byte[rogLength];
     296                    fileIn.read(rogData, 0, rogLength);
     297       
     298                    // Parse the .rog file
     299                    parseFile(rogData, rogLength);
     300                } catch (Exception ex) {
     301                        EcosystemManager.getGraphicsManager().showDialog("Exception", "Exception occurred reading file.\n\n" + ex);
     302                        success = false;
     303                } finally {
     304                        if (fileIn != null) {
     305                                try {
     306                                        fileIn.close();
     307                                } catch (IOException e) {
     308                                        // If an IO exception occurs when closing the file, just sweep it under the rug
     309                                }
     310                        }
     311                }
     312       
     313                // File loaded successfully
     314                return success;
    306315    }
    307316
     
    406415            // Check that the noteName is valid
    407416            if (noteName < 'A' || noteName > 'G') {
    408                 JOptionPane.showMessageDialog(null, "Parsing error - check that the Rog file is valid.");
     417                EcosystemManager.getGraphicsManager().showDialog("Exception", "Parsing error - check that the Rog file is valid.");
    409418                return;
    410419            }
     
    497506        }
    498507        catch (Exception ex) {
    499             JOptionPane.showMessageDialog(null, "Exception occurred writing to file.\n\n" + ex);
     508            EcosystemManager.getGraphicsManager().showDialog("Exception", "Exception occurred writing to file.\n\n" + ex);
    500509            return false;
    501510        }
  • trunk/src/org/apollo/meldex/StandardisedMelody.java

    r315 r1102  
    9393
    9494            // Read the melody from the melody file
    95             return (StandardisedMelody) melodyFileStream.readObject();
     95            StandardisedMelody standardisedMelody = (StandardisedMelody) melodyFileStream.readObject();
     96           
     97            melodyFileStream.close();
     98           
     99            return standardisedMelody;
    96100
    97101    }
  • trunk/src/org/apollo/meldex/Transcriber.java

    r315 r1102  
    44import java.util.ArrayList;
    55
    6 @SuppressWarnings("unchecked") // code in java 1.4
    76public class Transcriber
    87{
     
    255254    {
    256255        // Pitch track the note
    257         ArrayList pitchData = pitchTracker.process(data, length, sampleRate);
     256        ArrayList<PitchValue> pitchData = pitchTracker.process(data, length, sampleRate);
    258257
    259258        // Average the pitch data
     
    265264
    266265
    267     private int averagePitchData(ArrayList pitchData)
     266    private int averagePitchData(ArrayList<PitchValue> pitchData)
    268267    {
    269268        // Loop through the pitch values...
    270269        int i = 0, k = 0;
    271270        while (i < (pitchData.size() - 1)) {
    272             int startPos = ((PitchValue) pitchData.get(i)).position;
    273             double period = ((PitchValue) pitchData.get(i)).period;
     271            int startPos = pitchData.get(i).position;
     272            double period = pitchData.get(i).period;
    274273            double averagePeriod = period;
    275             double runningPeriod = ((PitchValue) pitchData.get(i+1)).position - startPos;
     274            double runningPeriod = pitchData.get(i+1).position - startPos;
    276275            double numPeriods = runningPeriod / period;
    277276
     
    280279            while ((i+j) < (pitchData.size() - 1)) {
    281280                // Get the next pitch estimate
    282                 period = ((PitchValue) pitchData.get(i+j)).period;
    283                 int position = ((PitchValue) pitchData.get(i+j)).position;
     281                period = pitchData.get(i+j).period;
     282                int position = pitchData.get(i+j).position;
    284283
    285284                // Make sure that this period is covered by the average so far
     
    289288
    290289                // Stop if we have covered more than 20 msec
    291                 int nextPos = ((PitchValue) pitchData.get(i+j+1)).position;
     290                int nextPos = pitchData.get(i+j+1).position;
    292291                // if ((nextPos - startPos) >= 445) {  // !! PURE-ROG !!
    293292                if ((nextPos - startPos) >= (sampleRate * 0.02)) {
     
    315314
    316315
    317     private int calculateHistogram(ArrayList data, int length)
     316    private int calculateHistogram(ArrayList<PitchValue> data, int length)
    318317    {
    319318        // This probably shouldn't be a constant
     
    328327        // Calculate the histogram data
    329328        for (int i = 0; i < (length - 1); i++) {
    330             double period = ((PitchValue) data.get(i)).period;
    331             double position = ((PitchValue) data.get(i)).position;
    332             double periodLength = ((PitchValue) data.get(i+1)).position - position;
     329            double period = data.get(i).period;
     330            double position = data.get(i).position;
     331            double periodLength = data.get(i+1).position - position;
    333332
    334333            // We only need to do this if the pitch does not equal zero
  • trunk/src/org/apollo/meldex/WavSample.java

    r315 r1102  
    88import javax.sound.sampled.AudioInputStream;
    99import javax.sound.sampled.AudioSystem;
    10 import javax.swing.JOptionPane;
    11 
    12 @SuppressWarnings("unchecked") // code in java 1.4
     10
     11import org.expeditee.gio.EcosystemManager;
     12
    1313public class WavSample
    1414{
     
    6868        }
    6969        catch (Exception ex) {
    70             JOptionPane.showMessageDialog(null, "Exception occurred creating sample.\n\n" + ex);
     70            EcosystemManager.getGraphicsManager().showDialog("Exception", "Exception occurred creating sample.\n\n" + ex);
    7171            return false;
    7272        }
     
    9090            }
    9191            catch (Exception ex) {
    92                 JOptionPane.showMessageDialog(null, "Exception occurred reloading sample.\n\n" + ex);
     92            EcosystemManager.getGraphicsManager().showDialog("Exception", "Exception occurred reloading sample.\n\n" + ex);
    9393                return false;
    9494            }
     
    101101            }
    102102            catch (Exception ex) {
    103                 JOptionPane.showMessageDialog(null, "Exception occurred resetting audio stream.\n\n" + ex);
     103            EcosystemManager.getGraphicsManager().showDialog("Exception", "Exception occurred resetting audio stream.\n\n" + ex);
    104104                return false;
    105105            }
     
    172172        if (format.getSampleSizeInBits() == 8) {
    173173            if (format.getEncoding().equals(AudioFormat.Encoding.PCM_SIGNED)) {
    174                 JOptionPane.showMessageDialog(null, "Oops! Internal Error: Unexpected audio format (signed 8-bit).");
     174            EcosystemManager.getGraphicsManager().showDialog("Exception", "Oops! Internal Error: Unexpected audio format (signed 8-bit).");
    175175                return null;
    176176            }
     
    178178        if (format.getSampleSizeInBits() == 16) {
    179179            if (format.getEncoding().equals(AudioFormat.Encoding.PCM_UNSIGNED)) {
    180                 JOptionPane.showMessageDialog(null, "Oops! Internal Error: Unexpected audio format (unsigned 16-bit).");
     180            EcosystemManager.getGraphicsManager().showDialog("Exception", "Oops! Internal Error: Unexpected audio format (unsigned 16-bit).");
    181181                return null;
    182182            }
     
    188188
    189189        // Create a new list to store the standardised sample values
    190         ArrayList stdTemp = new ArrayList();
     190        ArrayList<Integer> stdTemp = new ArrayList<Integer>();
    191191
    192192        // Simply pick values from the sample at the frequency specified
     
    218218
    219219
    220     private static ArrayList toStandardEndian(AudioFormat format, ArrayList inData)
    221     {
    222         // Endian details do not apply to 8-bit samples, so no conversion needed
    223         if (format.getSampleSizeInBits() == 8) {
    224             return inData;
    225         }
    226 
    227         // Create a new list to store the results
    228         ArrayList outData = new ArrayList();
    229 
    230         // Simply convert each number in the sample to the endian form for the current system
    231         for (int i = 0; i < inData.size(); i += 2) {
    232 
    233             int MSB, LSB;
    234             if (format.isBigEndian()) {
    235                 MSB = ((Integer) inData.get(i)).intValue();    // First byte is MSB (high order)
    236                 LSB = ((Integer) inData.get(i+1)).intValue();  // Second byte is LSB (low order)
    237             }
    238             else {
    239                 LSB = ((Integer) inData.get(i)).intValue();    // First byte is LSB (low order)
    240                 MSB = ((Integer) inData.get(i+1)).intValue();  // Second byte is MSB (high order)
    241             }
    242 
    243             int val = (MSB << 8) + (LSB & 255);
    244             outData.add(new Integer(val));
    245         }
    246 
    247         return outData;
    248     }
    249 
    250 
    251     private static ArrayList toUnsignedValues(AudioFormat format, ArrayList inData)
     220    private static ArrayList<Integer> toStandardEndian(AudioFormat format, ArrayList<Integer> inData)
     221    {
     222                // Endian details do not apply to 8-bit samples, so no conversion needed
     223                if (format.getSampleSizeInBits() == 8) {
     224                    return inData;
     225                }
     226       
     227                // Create a new list to store the results
     228                ArrayList<Integer> outData = new ArrayList<Integer>();
     229       
     230                // Simply convert each number in the sample to the endian form for the current system
     231                for (int i = 0; i < inData.size(); i += 2) {
     232       
     233                    int MSB, LSB;
     234                    if (format.isBigEndian()) {
     235                        MSB = ((Integer) inData.get(i)).intValue();    // First byte is MSB (high order)
     236                        LSB = ((Integer) inData.get(i+1)).intValue();  // Second byte is LSB (low order)
     237                    }
     238                    else {
     239                        LSB = ((Integer) inData.get(i)).intValue();    // First byte is LSB (low order)
     240                        MSB = ((Integer) inData.get(i+1)).intValue();  // Second byte is MSB (high order)
     241                    }
     242       
     243                    int val = (MSB << 8) + (LSB & 255);
     244                    outData.add(new Integer(val));
     245                }
     246       
     247                return outData;
     248    }
     249
     250
     251    private static ArrayList<Integer> toUnsignedValues(AudioFormat format, ArrayList<Integer> inData)
    252252    {
    253253        // PCM_UNSIGNED samples are what we want, so no conversion needed
     
    257257
    258258        // Create a new list to store the results
    259         ArrayList outData = new ArrayList();
     259        ArrayList<Integer> outData = new ArrayList<Integer>();
    260260
    261261        // Simply convert each signed number in the sample to an unsigned value
     
    275275
    276276
    277     private static ArrayList to8bit(AudioFormat format, ArrayList inData)
     277    private static ArrayList<Integer> to8bit(AudioFormat format, ArrayList<Integer> inData)
    278278    {
    279279        // 8-bit data is what we want, so no conversion necessary
     
    283283
    284284        // Create a new list to store the results
    285         ArrayList outData = new ArrayList();
     285        ArrayList<Integer> outData = new ArrayList<Integer>();
    286286
    287287        // Simply reduce each value in the sample to an 8-bit value
     
    298298
    299299
    300     private static ArrayList toMono(AudioFormat format, ArrayList inData)
     300    private static ArrayList<Integer> toMono(AudioFormat format, ArrayList<Integer> inData)
    301301    {
    302302        // Mono-channel data is what we want, so no conversion necessary
     
    306306
    307307        // Create a new list to store the results
    308         ArrayList outData = new ArrayList();
     308        ArrayList<Integer> outData = new ArrayList<Integer>();
    309309
    310310        // Simply average all of the channels for each frame
     
    362362        try {
    363363            if (AudioSystem.write(audioData, AudioFileFormat.Type.WAVE, outFile) == -1) {
    364                 JOptionPane.showMessageDialog(null, "Problem occurred writing to file.");
     364            EcosystemManager.getGraphicsManager().showDialog("Exception", "Problem occurred writing to file.");
    365365                return false;
    366366            }
    367367        }
    368368        catch (Exception ex) {
    369             JOptionPane.showMessageDialog(null, "Exception occurred saving file.\n\n" + ex);
     369            EcosystemManager.getGraphicsManager().showDialog("Exception", "Exception occurred saving file.\n\n" + ex);
    370370            return false;
    371371        }
  • trunk/src/org/apollo/mvc/AbstractSubject.java

    r315 r1102  
    44import java.util.Set;
    55
    6 import javax.swing.SwingUtilities;
     6import org.expeditee.gio.EcosystemManager;
    77
    88/**
     
    6666        protected final void fireSubjectChangedLaterOnSwingThread(final SubjectChangedEvent event) {
    6767               
    68                 SwingUtilities.invokeLater(new Runnable() {
     68                EcosystemManager.getMiscManager().runOnGIOThread(new Runnable() {
    6969                        public void run() {
    7070                                fireSubjectChanged(event);
  • trunk/src/org/apollo/mvc/SwingEventQueue.java

    r315 r1102  
    44import java.util.Queue;
    55
    6 import javax.swing.SwingUtilities;
     6import org.expeditee.gio.EcosystemManager;
    77
    88/**
    99 * If your observer needs to reacts to events on the swing thread (i.e. interacting with swing
    1010 * objects somewhere in the event) and the observed subject raised events on other threads,
    11  * this class thunnels all events into the swing thread and ensures that they are raised in
     11 * this class tunnels all events into the swing thread and ensures that they are raised in
    1212 * the swing thread (thread safety!).
    1313 *
     
    2626        /**
    2727         * COnstructor.
    28          * @param target The SwingThreadedObserver instance to thunnel events to on the swing thread.
     28         * @param target The SwingThreadedObserver instance to tunnel events to on the swing thread.
    2929         */
    3030        public SwingEventQueue(SwingThreadedObserver target) {
     
    4444                        eventQueue.add(new QueudEvent(source, event));
    4545                }
    46                 SwingUtilities.invokeLater(eventProccessor);
     46                EcosystemManager.getMiscManager().runOnGIOThread(eventProccessor);
    4747        }
    4848
  • trunk/src/org/apollo/util/AudioPurger.java

    r903 r1102  
    1010import org.apollo.io.AudioPathManager;
    1111import org.apollo.widgets.SampledTrack;
    12 import org.expeditee.settings.UserSettings;
    1312import org.expeditee.settings.folders.FolderSettings;
    1413import org.expeditee.items.ItemUtils;
  • trunk/src/org/apollo/util/ExpediteeFileTextSearch.java

    r349 r1102  
    11package org.apollo.util;
    22
    3 import java.awt.Point;
    43import java.io.BufferedReader;
    54import java.io.FileNotFoundException;
     
    87import java.util.LinkedList;
    98import java.util.List;
     9
     10import org.expeditee.core.Point;
    1011
    1112/**
  • trunk/src/org/apollo/util/ODFrameHeirarchyFetcher.java

    r315 r1102  
    33import java.util.LinkedList;
    44import java.util.Queue;
    5 
    6 import javax.swing.SwingUtilities;
    75
    86import org.apollo.audio.structure.OverdubbedFrame;
    97import org.apollo.audio.structure.TrackGraphLoopException;
    108import org.apollo.audio.structure.AudioStructureModel;
     9import org.expeditee.gio.EcosystemManager;
    1110import org.expeditee.gui.FrameIO;
    1211
     
    139138                                }
    140139                               
    141                                 // Run result notiofaction for this request on swing thread
    142                                 SwingUtilities.invokeLater(request);
     140                                // Run result notification for this request on swing thread
     141                                EcosystemManager.getMiscManager().runOnGIOThread(request);
    143142                               
    144143                        }
  • trunk/src/org/apollo/util/PopupReaper.java

    r315 r1102  
    1313import javax.swing.SwingUtilities;
    1414
    15 import org.expeditee.gui.MouseEventRouter;
     15import org.expeditee.gio.swing.MouseEventRouter;
    1616import org.expeditee.gui.Popup;
    1717import org.expeditee.gui.PopupManager;
     
    1919
    2020/**
    21  * Yet another daemon .. whos job is to hide popups after their lifetimes have passed
     21 * Yet another daemon .. whose job is to hide popups after their lifetimes have passed
    2222 *
    2323 * @author Brook Novak
    2424 */
    2525
    26 public class PopupReaper {
    27        
     26public class PopupReaper
     27{
    2828        private Map<Popup, TemporaryPopup> tempPopups = new HashMap<Popup, TemporaryPopup>();// SHARED RESOURCE - the locker
    2929
     
    3131       
    3232        private static PopupReaper instance = new PopupReaper();
    33         private PopupReaper() {
    34         }
    35         public  static PopupReaper getInstance() {
     33       
     34        private PopupReaper()
     35        {
     36        }
     37       
     38        public  static PopupReaper getInstance()
     39        {
    3640                return instance;
    3741        }
     
    6266         *
    6367         */
    64         public void initPopupLifetime(Popup p, PopupAnimator hideAnimation, int lifetime) {
     68        public void initPopupLifetime(Popup p, PopupAnimator hideAnimation, int lifetime)
     69        {
    6570                if (p == null) throw new NullPointerException("p");
    6671                if (lifetime < 0) throw new IllegalArgumentException("lifetime < 0");
     
    8792                                reaper.interrupt();
    8893                        }
    89                        
    90 
    91                        
    92                 }
    93                
     94                }
    9495        }
    9596       
     
    115116         *
    116117         */
    117         public boolean revivePopup(Popup p, int lifetime) {
     118        public boolean revivePopup(Popup p, int lifetime)
     119        {
    118120                if (p == null) throw new NullPointerException("p");
    119121                if (lifetime < 0) throw new IllegalArgumentException("lifetime < 0");
     
    134136
    135137       
    136         private class ReapDaemon extends Thread {
    137                
    138                 ReapDaemon() {
     138        private class ReapDaemon extends Thread
     139        {
     140                ReapDaemon()
     141                {
    139142                        super("Popup Reaper");
    140143                        super.setPriority(Thread.MIN_PRIORITY);
     
    142145                }
    143146       
    144                 public void run() {
    145                        
     147                public void run()
     148                {
    146149                        while (true) {
    147150                       
     
    166169                 *              A Positive wait time, or a negative for nothing to to wait on.
    167170                 */
    168                 private long reap() {
    169 
     171                private long reap()
     172                {
    170173                        Collection<TemporaryPopup> snapshot;
    171174                       
     
    226229         *
    227230         */
    228         private class DoHide implements Runnable {
    229                
     231        private class DoHide implements Runnable
     232        {
    230233                private TemporaryPopup tempPopup;
    231234                public boolean didHide = false;
    232235               
    233                 public DoHide(TemporaryPopup tempPopup) {
     236                public DoHide(TemporaryPopup tempPopup)
     237                {
    234238                        this.tempPopup = tempPopup;
    235239                }
     
    244248                 *              True if screenPoint is over c.
    245249                 */
    246                 private boolean isPointInComponant(Component c, Point screenPoint) {
     250                private boolean isPointInComponant(Component c, Point screenPoint)
     251                {
    247252                        assert(c != null);
    248253                        assert(screenPoint != null);
     
    257262                }
    258263       
    259                 public void run() {
     264                public void run()
     265                {
    260266                        assert(tempPopup != null);
    261267                       
    262268                        MouseEvent me = MouseEventRouter.getCurrentMouseEvent();
    263269                        if (me != null) {
    264                                
    265                                 if (isPointInComponant(tempPopup.popup, me.getLocationOnScreen()))
    266                                         return;
     270                                if (isPointInComponant(tempPopup.popup, me.getLocationOnScreen())) return;
    267271                               
    268272                                Component invoker = PopupManager.getInstance().getInvoker(tempPopup.popup);
    269                                 if (invoker != null && isPointInComponant(invoker, me.getLocationOnScreen()))
    270                                         return;
    271                                
     273                               
     274                                if (invoker != null && isPointInComponant(invoker, me.getLocationOnScreen())) return;
    272275                        }
    273276
     
    289292         *
    290293         */
    291         private class TemporaryPopup implements Comparable {
    292 
     294        private class TemporaryPopup implements Comparable<TemporaryPopup>
     295        {
    293296                private Popup popup;
    294297                private PopupAnimator hideAnim;
     
    310313                 *
    311314                 */
    312                 public TemporaryPopup(Popup popup, PopupAnimator anim, int lifetime) {
     315                public TemporaryPopup(Popup popup, PopupAnimator anim, int lifetime)
     316                {
    313317                        assert(popup != null);
    314318                        assert(lifetime >= 0);
     
    320324                }
    321325
    322                 public void setNewLifetime(int lifetime) {
     326                public void setNewLifetime(int lifetime)
     327                {
    323328                        assert(lifetime >= 0);
    324329                        this.lifetime = lifetime;
     
    326331                }
    327332               
    328                 public void resetLifetime() {
     333                public void resetLifetime()
     334                {
    329335                        setNewLifetime(lifetime);
    330336                }
    331337               
    332                 public long getDelay() {
     338                public long getDelay()
     339                {
    333340                        return destructionTime - System.currentTimeMillis();
    334341                }
     
    337344                 * {@inheritDoc}
    338345                 */
    339                 public int compareTo(Object o) {
    340                        
    341                         long dt2 = ((TemporaryPopup)o).destructionTime;
    342                        
    343                         if (destructionTime < dt2)
    344                          return -1;
    345                        
    346                       if (destructionTime > dt2)
    347                          return 1;
     346                public int compareTo(TemporaryPopup o)
     347                {
     348                        long dt2 = o.destructionTime;
     349                       
     350                        if (destructionTime < dt2) return -1;
     351                       
     352                    if (destructionTime > dt2) return 1;
    348353                     
    349354                        return 0;
  • trunk/src/org/apollo/util/ProbeDaemon.java

    r372 r1102  
    77import org.apollo.audio.util.Timeline;
    88import org.apollo.gui.FrameLayoutDaemon;
    9 import org.expeditee.gui.DisplayIO;
     9import org.expeditee.gui.DisplayController;
    1010
    1111public class ProbeDaemon extends Thread {
     
    4646                        String timeline = "none";
    4747                        Timeline tl = FrameLayoutDaemon.getInstance().getLastComputedTimeline();
    48                         if (tl != null && DisplayIO.getCurrentFrame() == FrameLayoutDaemon.getInstance().getTimelineOwner()) {
     48                        if (tl != null && DisplayController.getCurrentFrame() == FrameLayoutDaemon.getInstance().getTimelineOwner()) {
    4949                                timeline = tl.toString();
    5050                        }
  • trunk/src/org/apollo/util/TextItemSearchResult.java

    r349 r1102  
    11package org.apollo.util;
    22
    3 import java.awt.Point;
    43import java.util.List;
     4
     5import org.expeditee.core.Point;
    56/**
    67 * Represents a single mutable search result.
  • trunk/src/org/apollo/util/TrackModelLoadManager.java

    r315 r1102  
    33import java.io.File;
    44import java.io.IOException;
    5 import java.lang.reflect.InvocationTargetException;
    65import java.util.HashSet;
    76import java.util.Set;
    87
    98import javax.sound.sampled.UnsupportedAudioFileException;
    10 import javax.swing.SwingUtilities;
    119
    1210import org.apollo.audio.SampledTrackModel;
     
    1412import org.apollo.io.LoadedAudioData;
    1513import org.apollo.mvc.Observer;
     14import org.expeditee.core.BlockingRunnable;
     15import org.expeditee.gio.EcosystemManager;
    1616import org.expeditee.items.widgets.HeavyDutyInteractiveWidget;
    1717import org.expeditee.items.widgets.WidgetCacheManager;
     
    124124                       
    125125                        try {
    126                                 SwingUtilities.invokeAndWait(locator);
    127                         } catch (InterruptedException e) {
    128                                 e.printStackTrace();
    129                         } catch (InvocationTargetException e) {
     126                                EcosystemManager.getMiscManager().runOnGIOThread(locator);
     127                        } catch (Exception e) {
    130128                                e.printStackTrace();
    131129                        }
     
    166164         * Look in expeditee memory - this should be quick - will hold up the user
    167165         */
    168         private class CachedTrackModelLocator implements Runnable
     166        private class CachedTrackModelLocator extends BlockingRunnable
    169167        {
    170168                private String localfileName;
     
    176174                }
    177175               
    178                 public void run() {
     176                public void execute() {
    179177               
    180178                        // Exploit knowledge that all SampledTrack are Cached HDW
  • trunk/src/org/apollo/widgets/AudioConfiguration.java

    r315 r1102  
    3131import org.expeditee.items.ItemParentStateChangedEvent;
    3232import org.expeditee.items.Text;
    33 import org.expeditee.items.widgets.InteractiveWidget;
    34 
    35 public class AudioConfiguration extends InteractiveWidget implements Observer {
     33import org.expeditee.items.widgets.SwingWidget;
     34
     35public class AudioConfiguration extends SwingWidget implements Observer {
    3636       
    3737        private static MixerItem[] inputMixerItems = null;
    3838
    39         private JComboBox inputMixureCombo;
     39        private JComboBox<MixerItem> inputMixureCombo;
    4040        private JSlider masterVolumeSlider;
    4141        private JCheckBox masterMuteCheckBox;
     
    4848                Font descFont = new Font("Arial", Font.PLAIN, 12);
    4949
    50                 inputMixureCombo = new JComboBox(getInputMixerItems());
     50                inputMixureCombo = new JComboBox<MixerItem>(getInputMixerItems());
    5151               
    5252                inputMixureCombo.addActionListener( new ActionListener() {
  • trunk/src/org/apollo/widgets/FramePlayer.java

    r372 r1102  
    11package org.apollo.widgets;
    22
    3 import java.awt.Color;
    43import java.awt.Dimension;
    54import java.awt.GridBagConstraints;
     
    2120import javax.swing.ComboBoxModel;
    2221import javax.swing.DefaultComboBoxModel;
    23 import javax.swing.Icon;
    2422import javax.swing.JButton;
    2523import javax.swing.JComboBox;
     
    4543import org.apollo.util.ApolloSystemLog;
    4644import org.apollo.util.AudioMath;
    47 import org.expeditee.gui.DisplayIO;
    48 import org.expeditee.gui.DisplayIOObserver;
    49 import org.expeditee.gui.FrameGraphics;
     45import org.expeditee.core.Colour;
     46import org.expeditee.core.Image;
     47import org.expeditee.gio.gesture.StandardGestureActions;
     48import org.expeditee.gio.swing.SwingMiscManager;
     49import org.expeditee.gui.DisplayController;
     50import org.expeditee.gui.DisplayObserver;
    5051import org.expeditee.gui.FrameIO;
    51 import org.expeditee.gui.FrameMouseActions;
    5252import org.expeditee.gui.MessageBay;
    5353import org.expeditee.items.ItemParentStateChangedEvent;
    5454import org.expeditee.items.Text;
    55 import org.expeditee.items.widgets.InteractiveWidget;
     55import org.expeditee.items.widgets.SwingWidget;
    5656
    5757/**
     
    6161 *
    6262 */
    63 public class FramePlayer extends InteractiveWidget
    64         implements Observer, MultitrackLoadListener, ActionListener, DisplayIOObserver {
     63public class FramePlayer extends SwingWidget
     64        implements Observer, MultitrackLoadListener, ActionListener, DisplayObserver {
    6565
    6666        private static final int BUTTON_SIZE = 40;
     
    7373        private JButton rewindButton;
    7474        private JButton playLauncherButton;
    75         private JComboBox frameSelection;
     75        private JComboBox<String> frameSelection;
    7676        private JToggleButton muteButton;
    7777        private JSlider volumeSlider;
     
    8686        public static String FRAME_PLAYERMASTER_CHANNEL_ID = "#$frameplayer#master$";
    8787       
    88         private static final Color LOADING_BORDER_COLOR = new Color(22, 205, 5);
     88        private static final Colour LOADING_BORDER_COLOR = Colour.FromRGB255(22, 205, 5);
    8989        //private static final Color FAILED_MESSAGE_COLOR = Color.RED;
    9090        //private static final Font MESSAGE_FONT = TrackWidgetCommons.FREESPACE_TRACKNAME_FONT;
     
    180180                playPauseButton = new JButton();
    181181                playPauseButton.addActionListener(this);
    182                 playPauseButton.setIcon(IconRepository.getIcon("play.png"));
     182                SwingMiscManager.setJButtonIcon(playPauseButton, IconRepository.getIcon("play.png"));
    183183                playPauseButton.setPreferredSize(new Dimension(BUTTON_SIZE, BUTTON_SIZE));
    184184                playPauseButton.setToolTipText("Play selection / Pause");
     
    187187                stopButton.setEnabled(false);
    188188                stopButton.addActionListener(this);
    189                 stopButton.setIcon(IconRepository.getIcon("stop.png"));
     189                SwingMiscManager.setJButtonIcon(stopButton, IconRepository.getIcon("stop.png"));
    190190                stopButton.setPreferredSize(new Dimension(BUTTON_SIZE, BUTTON_SIZE));
    191191                stopButton.setToolTipText("Stop playback");
     
    193193                rewindButton = new JButton();
    194194                rewindButton.addActionListener(this);
    195                 rewindButton.setIcon(IconRepository.getIcon("rewind.png"));
     195                SwingMiscManager.setJButtonIcon(rewindButton, IconRepository.getIcon("rewind.png"));
    196196                rewindButton.setPreferredSize(new Dimension(BUTTON_SIZE, BUTTON_SIZE));
    197197                rewindButton.setToolTipText("Rewind to start");
     
    199199                // Icon changes
    200200                muteButton = new JToggleButton();
    201                 muteButton.setSelectedIcon(IconRepository.getIcon("volmute.png"));
     201                SwingMiscManager.setJButtonIcon(muteButton, IconRepository.getIcon("volmute.png"));
    202202                muteButton.setPreferredSize(new Dimension(BUTTON_SIZE, BUTTON_SIZE));
    203203                muteButton.setToolTipText("Toggle mute");
     
    212212                playLauncherButton = new JButton();
    213213                playLauncherButton.addActionListener(this);
    214                 playLauncherButton.setIcon(IconRepository.getIcon("frameplay.png"));
     214                SwingMiscManager.setJButtonIcon(playLauncherButton, IconRepository.getIcon("frameplay.png"));
    215215                playLauncherButton.setPreferredSize(new Dimension(BUTTON_SIZE, BUTTON_SIZE));
    216216                playLauncherButton.setToolTipText("Play from a specific position");
     
    231231                volumeSlider.setPreferredSize(new Dimension((3 * BUTTON_SIZE) - (2 * VOLUME_SPACING), BUTTON_SIZE));
    232232
    233                 frameSelection = new JComboBox();
     233                frameSelection = new JComboBox<String>();
    234234                frameSelection.setEditable(true);
    235235                frameSelection.setPreferredSize(new Dimension(4 * BUTTON_SIZE, BUTTON_SIZE));
     
    304304                        stopButton.setEnabled(false);
    305305                        playPauseButton.setEnabled(true);
    306                         playPauseButton.setIcon(IconRepository.getIcon("play.png"));
     306                        SwingMiscManager.setJButtonIcon(playPauseButton, IconRepository.getIcon("play.png"));
    307307                        playLauncherButton.setEnabled(true);
    308308
     
    323323                        playLauncherButton.setEnabled(true);
    324324                        playPauseButton.setEnabled(true);
    325                         playPauseButton.setIcon(IconRepository.getIcon("pause.png"));
     325                        SwingMiscManager.setJButtonIcon(playPauseButton, IconRepository.getIcon("pause.png"));
    326326
    327327                        setWidgetEdgeThickness(TrackWidgetCommons.PLAYING_TRACK_EDGE_THICKNESS);
     
    336336               
    337337                invalidateSelf();
    338                 FrameGraphics.refresh(true);
     338                DisplayController.requestRefresh(true);
    339339        }
    340340       
     
    361361                        MultiTrackPlaybackController.getInstance().addObserver(this); // the core!
    362362                        masterMix.addObserver(this);
    363                         DisplayIO.addDisplayIOObserver(this);
     363                        DisplayController.addDisplayObserver(this);
    364364               
    365365                        // Evaluate the state of this add set the state accordingly
     
    405405                       
    406406                        // Remove observers
    407                         DisplayIO.removeDisplayIOObserver(this);
     407                        DisplayController.removeDisplayObserver(this);
    408408                        SoundDesk.getInstance().removeObserver(this);
    409409                        MultiTrackPlaybackController.getInstance().removeObserver(this);
     
    544544                if ((frameSelection.getSelectedItem() != null && frameSelection.getSelectedItem().equals(CURRENT_FRAME_SPECIFIER))
    545545                                || frameSelection.getSelectedItem() == null)
    546                         return DisplayIO.getCurrentFrame().getName();
     546                        return DisplayController.getCurrentFrame().getName();
    547547               
    548548                String frameSpecifier = (String)frameSelection.getSelectedItem();
    549549               
    550550                if (frameSpecifier.isEmpty()) {
    551                         return DisplayIO.getCurrentFrame().getName();
     551                        return DisplayController.getCurrentFrame().getName();
    552552                }
    553553               
     
    671671                       
    672672                        String target = getSelectedFrameName();
    673                         if (target == DisplayIO.getCurrentFrame().getName()) target = null;
     673                        if (target == DisplayController.getCurrentFrame().getName()) target = null;
    674674                       
    675675                        // Create the launcher
    676676                        FramePlaybackLauncher launcher = new FramePlaybackLauncher(target);
    677                         launcher.setPosition(FrameMouseActions.MouseX, FrameMouseActions.MouseY);
     677                        launcher.setPosition(DisplayController.getMousePosition());
    678678
    679679                        // Pick it up
    680                         FrameMouseActions.pickup(launcher);
     680                        StandardGestureActions.pickup(launcher);
    681681                }
    682682               
     
    687687               
    688688                // Get border color currently used
    689                 Color oldC = getSource().getBorderColor();
    690                 Color newC = null;
     689                Colour oldC = getSource().getBorderColor();
     690                Colour newC = null;
    691691               
    692692                if (this.state == PLAYBACK_LOADING) {
     
    714714        private void updateButtonGUI() {
    715715               
    716                 Icon newIcon = null;
     716                Image newIcon = null;
    717717                if (volumeSlider.getValue() <= 25)
    718718                                newIcon = IconRepository.getIcon("vol25.png");
     
    724724                                newIcon = IconRepository.getIcon("vol100.png");
    725725               
    726                 muteButton.setIcon(newIcon);
     726                SwingMiscManager.setJButtonIcon(muteButton, newIcon);
    727727        }
    728728       
     
    783783               
    784784                // Place last visited frames
    785                 List<String> history = DisplayIO.getUnmodifiableVisitedList();
     785                List<String> history = DisplayController.getUnmodifiableVisitedList();
    786786               
    787787                for (int i = history.size() - 1; i >= 0; i--) {
     
    802802                }
    803803               
    804             ComboBoxModel model = new DefaultComboBoxModel(orderedModelData.toArray());
     804            ComboBoxModel<String> model = new DefaultComboBoxModel<String>((String[]) orderedModelData.toArray());
    805805           
    806806            // Remove helper tags from model data
  • trunk/src/org/apollo/widgets/LinkedTrack.java

    r372 r1102  
    11package org.apollo.widgets;
    22
    3 import java.awt.Color;
    4 import java.awt.Font;
    53import java.awt.FontMetrics;
    64import java.awt.GradientPaint;
     
    86import java.awt.Graphics2D;
    97import java.awt.Paint;
    10 import java.awt.Point;
    118import java.awt.Rectangle;
    12 import java.awt.Shape;
    13 import java.awt.Stroke;
    149import java.awt.event.ActionEvent;
    1510import java.awt.event.ActionListener;
     
    1914import java.awt.event.MouseListener;
    2015import java.awt.event.MouseMotionListener;
    21 import java.awt.geom.Area;
    2216import java.awt.geom.Rectangle2D;
    2317import java.util.LinkedList;
     
    2923import javax.swing.SwingUtilities;
    3024
     25import org.apollo.ApolloGestureActions;
     26import org.apollo.ApolloKBMGestureTranslator;
    3127import org.apollo.ApolloSystem;
    32 import org.apollo.AudioFrameKeyboardActions;
    33 import org.apollo.AudioFrameMouseActions;
    3428import org.apollo.audio.ApolloSubjectChangedEvent;
    3529import org.apollo.audio.SampledAudioManager;
     
    6256import org.apollo.util.Mutable;
    6357import org.apollo.util.ODFrameHeirarchyFetcher;
    64 import org.apollo.util.PopupReaper;
    6558import org.apollo.util.StringEx;
    6659import org.apollo.util.ODFrameHeirarchyFetcher.ODFrameReceiver;
     60import org.expeditee.core.Clip;
     61import org.expeditee.core.Colour;
     62import org.expeditee.core.EnforcedClipStack.EnforcedClipKey;
     63import org.expeditee.core.Fill;
     64import org.expeditee.core.Font;
     65import org.expeditee.core.Line;
     66import org.expeditee.core.Point;
     67import org.expeditee.core.Stroke;
     68import org.expeditee.core.TextLayout;
     69import org.expeditee.core.bounds.AxisAlignedBoxBounds;
     70import org.expeditee.gio.EcosystemManager;
     71import org.expeditee.gio.GraphicsManager;
     72import org.expeditee.gio.TextLayoutManager;
     73import org.expeditee.gio.swing.MouseEventRouter;
     74import org.expeditee.gio.swing.SwingConversions;
     75import org.expeditee.gio.swing.SwingMiscManager;
    6776import org.expeditee.gui.Browser;
    68 import org.expeditee.gui.DisplayIO;
     77import org.expeditee.gui.DisplayController;
    6978import org.expeditee.gui.Frame;
    70 import org.expeditee.gui.FrameGraphics;
    7179import org.expeditee.gui.FrameUtils;
    7280import org.expeditee.gui.MessageBay;
    73 import org.expeditee.gui.MouseEventRouter;
    7481import org.expeditee.gui.PopupManager;
    7582import org.expeditee.items.Item;
    7683import org.expeditee.items.ItemParentStateChangedEvent;
    7784import org.expeditee.items.Text;
    78 import org.expeditee.items.widgets.InteractiveWidget;
    7985import org.expeditee.items.widgets.InteractiveWidgetInitialisationFailedException;
    8086import org.expeditee.items.widgets.InteractiveWidgetNotAvailableException;
    81 
    82 public class LinkedTrack extends InteractiveWidget implements ODFrameReceiver, Observer, MultitrackLoadListener, PlaybackClockListener {
     87import org.expeditee.items.widgets.SwingWidget;
     88import org.expeditee.items.widgets.Widget;
     89
     90public class LinkedTrack extends SwingWidget implements ODFrameReceiver, Observer, MultitrackLoadListener, PlaybackClockListener {
    8391       
    8492        private String virtualFilename; // immutable
     
    92100       
    93101        private PlaybackPopup playbackControlPopup = null;
    94 
    95102
    96103        // private SoundDeskPopup soundDeskPopup = null;
     
    116123        private String abortMessage = null;
    117124       
    118         private static final Color FAILED_MESSAGE_COLOR = Color.RED;
     125        private static final Colour FAILED_MESSAGE_COLOR = Colour.RED;
    119126        private static final Font MESSAGE_FONT = TrackWidgetCommons.FREESPACE_TRACKNAME_FONT;
    120         private static final Font HELPER_FONT = new Font("Arial", Font.BOLD, 12);
    121        
    122         private static final Color[] TRACK_COLOR_WHEEL = {
    123                                                         new Color(66, 145, 255),
    124                                                         new Color(255, 163, 33),
    125                                                         new Color(155, 227, 48),
     127        private static final Font HELPER_FONT = new Font("Arial", Font.Style.BOLD, 12);
     128       
     129        private static final Colour[] TRACK_COLOR_WHEEL = {
     130                                                        Colour.FromRGB255(66, 145, 255),
     131                                                        Colour.FromRGB255(255, 163, 33),
     132                                                        Colour.FromRGB255(155, 227, 48)
    126133                                                };
    127         private static final Color TRACK_LOAD_COLOR = Color.BLACK;
    128         private static final Color TRACK_FAIL_COLOR = Color.RED;
    129        
    130         private static final Color SELECTION_COLOR = new Color(0,0,0,100);
     134        private static final Colour TRACK_LOAD_COLOR = Colour.BLACK;
     135        private static final Colour TRACK_FAIL_COLOR = Colour.RED;
     136       
     137        private static final Colour SELECTION_COLOR = Colour.FromRGBA255(0,0,0,100);
    131138
    132139        private static final Stroke TRACK_BORDER = Strokes.SOLID_1;
    133140        private static final Stroke TRACK_SELECTED_BORDER = Strokes.SOLID_2;
    134         private static final Color TRACK_BORDER_COLOR = Color.BLACK;
    135         private static final Color TRACK_SELECTED_BORDER_COLOR = new Color(253, 255, 201);
     141        private static final Colour TRACK_BORDER_COLOR = Colour.BLACK;
     142        private static final Colour TRACK_SELECTED_BORDER_COLOR = Colour.FromRGB255(253, 255, 201);
    136143       
    137144       
     
    154161         * @param args
    155162         */
    156         public LinkedTrack(Text source, String[] args) {
     163        public LinkedTrack(Text source, String[] args)
     164        {
    157165                super(source, new JPanel(),
    158166                                100, -1,
     
    187195                playbackControlPopup = new PlaybackPopup();
    188196               
    189                 nameLabel = new EmulatedTextItem(_swingComponent, new Point(10, 20));
    190                 nameLabel.setBackgroundColor(Color.WHITE);     
     197                nameLabel = new EmulatedTextItem("", new Point(10, 20));
     198                nameLabel.setBackgroundColor(Colour.WHITE);     
    191199               
    192200                String metaName = getStrippedDataString(TrackWidgetCommons.META_NAME_TAG);
     
    210218                        public void keyPressed(KeyEvent e) {
    211219                                if ((state != PLAYING && state != STOPPED) || e.isControlDown()) return;
    212                                 if (nameLabel.onKeyPressed(e, _swingComponent)) {
    213                                         e.consume();
    214                                         return;
    215                                 }
    216220                        }
    217221
     
    219223                                if ((state != PLAYING && state != STOPPED)) return;
    220224                                else if (e.isControlDown()) {
    221                                         if (e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_RIGHT) {
    222                                                 AudioFrameKeyboardActions.adjustInitationTime(LinkedTrack.this, e.getKeyCode() == KeyEvent.VK_LEFT);
    223                                         } else if (e.getKeyCode() == KeyEvent.VK_UP || e.getKeyCode() == KeyEvent.VK_DOWN) {
    224                                                 AudioFrameKeyboardActions.adjustVerticlePosition(LinkedTrack.this, e.getKeyCode() == KeyEvent.VK_UP);
     225                                        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
     226                                                ApolloGestureActions.adjustInitiationTime(LinkedTrack.this, -ApolloKBMGestureTranslator.TRACK_WIDGET_TIMELINE_ADJUSTMENT);
     227                                        } else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
     228                                                ApolloGestureActions.adjustInitiationTime(LinkedTrack.this, ApolloKBMGestureTranslator.TRACK_WIDGET_TIMELINE_ADJUSTMENT);
     229                                        } else if (e.getKeyCode() == KeyEvent.VK_UP) {
     230                                                ApolloGestureActions.adjustVerticalPosition(LinkedTrack.this, -ApolloKBMGestureTranslator.TRACK_WIDGET_VERTICAL_ADJUSTMENT);
     231                                        } else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
     232                                                ApolloGestureActions.adjustVerticalPosition(LinkedTrack.this, ApolloKBMGestureTranslator.TRACK_WIDGET_VERTICAL_ADJUSTMENT);
    225233                                        }
    226                                 } else if (nameLabel.onKeyReleased(e, _swingComponent)) {
    227                                         e.consume();
    228                                         return;
    229234                                }
    230235                        }
     
    234239                       
    235240                });
    236                
    237241               
    238242                updateBorderColor();
     
    346350                        playbackControlPopup.stopButton.setEnabled(false);
    347351                        playbackControlPopup.playPauseButton.setEnabled(true);
    348                         playbackControlPopup.playPauseButton.setIcon(IconRepository.getIcon("play.png"));
     352                        SwingMiscManager.setJButtonIcon(playbackControlPopup.playPauseButton, IconRepository.getIcon("play.png"));
    349353               
    350354
     
    363367                        playbackControlPopup.rewindButton.setEnabled(false);
    364368                        playbackControlPopup.playPauseButton.setEnabled(true);
    365                         playbackControlPopup.playPauseButton.setIcon(IconRepository.getIcon("pause.png"));
     369                        SwingMiscManager.setJButtonIcon(playbackControlPopup.playPauseButton, IconRepository.getIcon("pause.png"));
    366370
    367371                        setWidgetEdgeThickness(TrackWidgetCommons.PLAYING_TRACK_EDGE_THICKNESS);
     
    408412               
    409413                invalidateSelf();
    410                 FrameGraphics.refresh(true);
     414                DisplayController.requestRefresh(true);
    411415        }
    412416       
     
    528532                        for (Track t : tracks) setTrackState(t, TRACKSTATE_READY);
    529533                        invalidateSelf();
    530                         FrameGraphics.refresh(true);
     534                        DisplayController.requestRefresh(true);
    531535                        break;
    532536                case MultitrackLoadListener.LOAD_FAILED_BAD_GRAPH:
     
    552556                        setTrackState((String) state, TRACKSTATE_READY);
    553557                        invalidateSelf();
    554                         FrameGraphics.refresh(true);
     558                        DisplayController.requestRefresh(true);
    555559                        break;
    556560
     
    611615         */
    612616        @Override
    613         public InteractiveWidget copy()
     617        public Widget copy()
    614618                throws InteractiveWidgetNotAvailableException, InteractiveWidgetInitialisationFailedException {
    615619               
     
    632636                source.setData(data);
    633637               
    634                 return InteractiveWidget.createWidget((Text)source);
     638                return Widget.createWidget((Text)source);
    635639
    636640        }
     
    640644         */
    641645        @Override
    642         protected void onParentStateChanged(int eventType) {
     646        protected void onParentStateChanged(int eventType)
     647        {
    643648                super.onParentStateChanged(eventType);
    644649               
     
    667672                                boolean inferInitTime = true;
    668673       
    669                                 if (AudioFrameMouseActions.isYAxisRestictionOn()) {
     674                                if (ApolloGestureActions.isYAxisRestictionOn()) {
    670675                                        Mutable.Long ms = getInitiationTimeFromMeta();
    671676                                        if (ms != null) {
     
    683688                               
    684689                                // Also must not set initiation time if the frame is simply being displayed
    685                                 inferInitTime &=
    686                                         (AudioFrameMouseActions.isMouseAnchoring() || AudioFrameMouseActions.isMouseStamping());
    687 
     690                                //inferInitTime &= (AudioFrameMouseActions.isMouseAnchoring() || AudioFrameMouseActions.isMouseStamping());
     691                                inferInitTime &= (eventType == ItemParentStateChangedEvent.EVENT_TYPE_ADDED);
     692                               
    688693                                if (inferInitTime) {
    689694                                        initTime = Mutable.createMutableLong(FrameLayoutDaemon.getInstance().getMSAtX(getX(), parent));
     
    731736                        if (MouseEventRouter.getCurrentMouseEvent() != null &&
    732737                                        MouseEventRouter.getCurrentMouseEvent().getButton() == MouseEvent.BUTTON2) {
    733                                 Frame suspended = DisplayIO.getCurrentFrame();
     738                                Frame suspended = DisplayController.getCurrentFrame();
    734739                                if (suspended != null) {
    735740                                        FrameLayoutDaemon.getInstance().suspendLayout(suspended, this);
     
    755760                                public void run() {
    756761                                        invalidateSelf();
    757                                         FrameGraphics.refresh(true);
     762                                        DisplayController.requestRefresh(true);
    758763                                }
    759764                        }); // NOTE TO REPEAT: Pick up a linked track and delete it directly from freespace
     
    946951         */
    947952        @Override
    948         public void paint(Graphics g) {
     953        public void paintSwingWidget(Graphics2D gm) {
    949954               
    950955                if (Browser._theBrowser == null) return;
    951956               
     957                GraphicsManager g = EcosystemManager.getGraphicsManager();
     958               
    952959                // Ensure that load bar or any text doesn't spill over widgets invalidation area
    953                 Area clip = FrameGraphics.getCurrentClip();
    954                
    955                 Shape clipBackUp = g.getClip();
    956                
    957                 Area tmpClip = (clip != null) ? clip :
    958                         new Area(new Rectangle(0, 0,
    959                                         Browser._theBrowser.getContentPane().getWidth(),
    960                                         Browser._theBrowser.getContentPane().getHeight()));
    961                
    962                 tmpClip.intersect(new Area(getBounds()));
    963 
    964                 if (tmpClip.isEmpty()) return;
    965 
    966                 g.setClip(tmpClip);
     960                EnforcedClipKey clipKey = g.pushClip(new Clip(getBounds()));
    967961               
    968962                // Paint backing
    969                 g.setColor(SampledTrackGraphView.DEFAULT_BACKGROUND_COLOR);
    970                 g.fillRect(getX(), getY(), getWidth(), getHeight());
     963                g.drawRectangle(getBounds(), 0.0, new Fill(SwingConversions.fromSwingColor(SampledTrackGraphView.DEFAULT_BACKGROUND_COLOR)), null, null, null);
    971964               
    972965                String centralizedMessage = null;
     966                Colour colour = null;
    973967
    974968                // Render according to the currently widget state
     
    978972
    979973                case FAILED_STATE:
     974                        centralizedMessage = failMessage;
     975                        assert(failMessage != null);
     976                        colour = FAILED_MESSAGE_COLOR;
     977                        break;
    980978                case EMPTY_STATE:
     979                        if (getLink() == null) {
     980                                centralizedMessage = "Click to create";
     981                        } else {
     982                                centralizedMessage = "Nothing to play";
     983                        }
     984                       
     985                        colour = Colour.DARK_GREY;
     986                        break;
    981987                case LOADING_TRACK_GRAPH:
    982                        
    983                         if (state == FAILED_STATE) {
    984                                 centralizedMessage = failMessage;
    985                                 assert(failMessage != null);
    986                                 g.setColor(FAILED_MESSAGE_COLOR);
    987                         } else if (state == LOADING_TRACK_GRAPH){
    988                                 centralizedMessage = "Loading...";
    989                                 g.setColor(Color.DARK_GRAY);
    990                         } else { // empty
    991                                 if (getLink() == null) {
    992                                         centralizedMessage = "Click to create";
    993                                 } else {
    994                                         centralizedMessage = "Nothing to play";
    995                                 }
    996                                
    997                                 g.setColor(Color.DARK_GRAY);
    998                         }
    999 
     988                        centralizedMessage = "Loading...";
     989                        colour = Colour.DARK_GREY;
    1000990                        break;
    1001991                       
     
    1008998
    1009999                        for (Track track : tracks) {
    1010                                 track.paintTrackArea((Graphics2D)g, x, y);
     1000                                track.paintTrackArea(x, y);
    10111001                                if (track.isSelected) {
    10121002                                        selected = track;
    10131003                                } else {
    1014                                         track.paintTrackBorder(g, x, y);
     1004                                        track.paintTrackBorder(x, y);
    10151005                                       
    10161006                                        if (track.area.height > 15) { // don't clutter up busy linked tracks
    1017                                                 drawTrackName(track, g, Color.DARK_GRAY);
     1007                                                drawTrackName(track, Colour.DARK_GREY);
    10181008                                        }
    10191009       
     
    10251015                        // the selected border is drawn last
    10261016                        if (selected != null) {
    1027                                 selected.paintTrackBorder(g, x, y);
    1028                                 drawTrackName(selected, g, Color.BLACK);
     1017                                selected.paintTrackBorder(x, y);
     1018                                drawTrackName(selected, Colour.BLACK);
    10291019                        }
    10301020
     
    10381028                               
    10391029                                centralizedMessage = "Loading dubs...";
    1040                                 g.setColor(Color.BLACK);
     1030                                colour = Colour.BLACK;
    10411031                               
    10421032                        } else {
     
    10451035                                int selLeftX = XatFrame(selectionStart);
    10461036                                if (selectionLength > 1) {
    1047                                         g.setColor(SELECTION_COLOR);
    1048                                         g.fillRect(     getX() + selLeftX,
    1049                                                                 getY(),
    1050                                                                 XatFrame(selectionStart + selectionLength) - selLeftX,
    1051                                                                 getHeight());
     1037                                        colour = SELECTION_COLOR;
     1038                                        AxisAlignedBoxBounds b = new AxisAlignedBoxBounds(      getX() + selLeftX,
     1039                                                        getY(),
     1040                                                        XatFrame(selectionStart + selectionLength) - selLeftX,
     1041                                                        getHeight());
     1042                                        g.drawRectangle(b, 0.0, new Fill(colour), null, null, null);
    10521043                                }
    1053                                
    1054                                 // Draw selection start bar
    1055                                 ((Graphics2D)g).setStroke(SampledTrackGraphView.GRAPH_BAR_STROKE);
    10561044                               
    10571045                                // Note that if the start line is near the edges of the panel it can be concealed - thus
     
    10631051                                        x = getWidth() - 1;
    10641052                                }
    1065                                
    1066                                 g.setColor(Color.RED);
    1067                                 g.drawLine(
     1053                                colour = Colour.RED;
     1054                                Line l = new Line(
    10681055                                                x,
    10691056                                                getY(),
    10701057                                                x,
    10711058                                                getY() + getHeight());
     1059                                g.drawLine(l, colour, SwingConversions.fromSwingStroke(SampledTrackGraphView.GRAPH_BAR_STROKE));
    10721060       
    10731061                               
     
    10761064                                       
    10771065                                        x = XatFrame(currentPlaybackFramePosition) + getX();
    1078                                        
    1079                                         ((Graphics2D)g).setStroke(SampledTrackGraphView.GRAPH_BAR_STROKE);
    1080                                         g.setColor(SampledTrackGraphView.PLAYBACK_BAR_COLOR);
    1081                                         g.drawLine(x, getY(), x, getY() + getHeight());
     1066                                        colour = SwingConversions.fromSwingColor(SampledTrackGraphView.PLAYBACK_BAR_COLOR);
     1067                                        Line l2 = new Line(x, getY(), x, getY() + getHeight());
     1068                                        g.drawLine(l2, colour, SwingConversions.fromSwingStroke(SampledTrackGraphView.GRAPH_BAR_STROKE));
    10821069                               
    10831070                                }
    10841071                       
    10851072                        }
    1086                        
    1087 
    10881073                       
    10891074                        break;
     
    10941079                if (centralizedMessage != null) {
    10951080
    1096                         FontMetrics fm   = g.getFontMetrics(MESSAGE_FONT);
    1097                         Rectangle2D rect = fm.getStringBounds(centralizedMessage, g);
     1081                        TextLayoutManager t = EcosystemManager.getTextLayoutManager();
     1082                       
     1083                        TextLayout layout = t.layoutString(centralizedMessage, MESSAGE_FONT, Point.ORIGIN, null, Integer.MAX_VALUE, 0, true, false).get(0);
     1084                       
     1085                        AxisAlignedBoxBounds layoutBounds = layout.getPixelBounds(0, 0);
    10981086
    10991087                        // Calc centered position
    1100                         int x = getX() + ((getWidth() / 2) - (int)(rect.getWidth() / 2));
    1101                         int y = getY() + ((getHeight() / 2) + (int)(rect.getHeight() / 2) - 4);
     1088                        int x = getX() + ((getWidth() / 2) - (int)(layoutBounds.getWidth() / 2));
     1089                        int y = getY() + ((getHeight() / 2) + (int)(layoutBounds.getHeight() / 2) - 4);
    11021090                       
    11031091                        // Draw text
    1104                         g.setFont(MESSAGE_FONT);
    1105                         g.drawString(centralizedMessage, x, y);
     1092                        g.drawTextLayout(layout, new Point(x, y), colour);
    11061093                       
    11071094                        // Draw add icon if waiting for a link
    11081095                        if (getLink() == null) {
    1109                                 IconRepository.getIcon("goto.png").paintIcon(null,
     1096                                /*IconRepository.getIcon("goto.png").paintIcon(null,
    11101097                                                g,
    11111098                                                x - 34,
    1112                                                 getY() + (getHeight() / 2) - 12);
     1099                                                getY() + (getHeight() / 2) - 12);*/
     1100                                g.drawImage(IconRepository.getIcon("goto.png"), new Point(x - 34, getY() + (getHeight() / 2) - 12));
    11131101                        }
    11141102                               
     
    11161104
    11171105                // Paint name label over everything
    1118                 if (state != NOT_INITIALIZED && state != FAILED_STATE && state != EMPTY_STATE)
    1119                         nameLabel.paint(g);
    1120                
    1121                 g.setClip(clipBackUp);
    1122                
    1123                 super.paintLink((Graphics2D)g);
    1124 
    1125         }
    1126        
    1127         private void drawTrackName(Track track, Graphics g, Color textColor) {
    1128 
     1106                if (state != NOT_INITIALIZED && state != FAILED_STATE && state != EMPTY_STATE) nameLabel.paint();
     1107               
     1108                g.popClip(clipKey);
     1109
     1110        }
     1111       
     1112        private void drawTrackName(Track track, Colour textColor)
     1113        {
     1114                Graphics2D g = SwingMiscManager.getIfUsingSwingGraphicsManager().getCurrentSurface();
     1115               
    11291116                // Draw helper message for user to give meaningful information of what they
    11301117                // are actually highlighting
     
    11331120                helperMessage = helperMessage + " (" + track.getParentFrameName() +  ")";
    11341121               
    1135                 FontMetrics fm   = g.getFontMetrics(HELPER_FONT);
     1122                FontMetrics fm   = g.getFontMetrics(SwingMiscManager.getIfUsingSwingFontManager().getInternalFont(HELPER_FONT));
    11361123                Rectangle2D rect = fm.getStringBounds(helperMessage, g);
    11371124
     
    11491136               
    11501137                // Draw text
    1151                 g.setColor(textColor);
    1152                 g.setFont(HELPER_FONT);
     1138                g.setColor(SwingConversions.toSwingColor(textColor));
     1139                g.setFont(SwingMiscManager.getIfUsingSwingFontManager().getInternalFont(HELPER_FONT));
    11531140                g.drawString(helperMessage, xoff, yoff);
    11541141
     
    11561143       
    11571144        @Override
    1158         protected void paintInFreeSpace(Graphics g) {
    1159 
    1160                 super.paintInFreeSpace(g);
    1161 
    1162                 Shape clipBackUp = g.getClip();
    1163                 Rectangle tmpClip = (clipBackUp != null) ? clipBackUp.getBounds() :
    1164                         new Rectangle(0, 0,
    1165                                         Browser._theBrowser.getContentPane().getWidth(),
    1166                                         Browser._theBrowser.getContentPane().getHeight());
    1167                        
    1168                 g.setClip(tmpClip.intersection(getBounds()));
     1145        protected void paintInFreeSpace()
     1146        {
     1147                super.paintInFreeSpace();
     1148               
     1149                // Draw the name of the track
     1150               
     1151                GraphicsManager g = EcosystemManager.getGraphicsManager();
     1152
     1153                // Ensure that load bar or any text doesn't spill over widgets invalidation area
     1154                EnforcedClipKey clipKey = g.pushClip(new Clip(getBounds()));
    11691155       
    11701156                // Draw the name
     
    11731159                        name = "Unnamed";
    11741160                }
    1175 
    1176                 g.setFont(TrackWidgetCommons.FREESPACE_TRACKNAME_FONT);
    1177                 g.setColor(TrackWidgetCommons.FREESPACE_TRACKNAME_TEXT_COLOR);
    1178                
    1179                 // Center track name
    1180                 FontMetrics fm   = g.getFontMetrics(TrackWidgetCommons.FREESPACE_TRACKNAME_FONT);
    1181                 Rectangle2D rect = fm.getStringBounds(name, g);
    1182                
    1183                 g.drawString(
    1184                                 name,
    1185                                 this.getX() + (int)((getWidth() - rect.getWidth()) / 2),
    1186                                 this.getY() + (int)((getHeight() - rect.getHeight()) / 2) + (int)rect.getHeight()
    1187                                 );
    1188                
    1189                 g.setClip(clipBackUp);
    1190        
    1191 
     1161               
     1162                List<TextLayout> layouts = EcosystemManager.getTextLayoutManager().layoutString(name, TrackWidgetCommons.FREESPACE_TRACKNAME_FONT, getBounds().getTopLeft(), null, getBounds().getWidth(), 0, true, false);
     1163
     1164                // Centre the track name
     1165                int lineYDelta = 0;
     1166                for (TextLayout layout : layouts) {
     1167                        AxisAlignedBoxBounds bounds = layout.getPixelBounds(getBounds().getMinX(), getBounds().getMinY() + lineYDelta);
     1168                        int centreXOffset = (getBounds().getWidth() - bounds.getWidth()) / 2;
     1169                        bounds.translate(centreXOffset, 0);
     1170                        g.drawTextLayout(layout, bounds.getTopLeft(), TrackWidgetCommons.FREESPACE_TRACKNAME_TEXT_COLOR);
     1171                        lineYDelta += bounds.getHeight();
     1172                }
     1173               
     1174                g.popClip(clipKey);
    11921175        }
    11931176
     
    12051188                                x = XatFrame(currentPlaybackFramePosition);
    12061189                               
    1207                                 FrameGraphics.invalidateArea(new Rectangle(
     1190                                DisplayController.invalidateArea(new AxisAlignedBoxBounds(
    12081191                                        x + offsetX,
    12091192                                        offsetY,
     
    12201203                                x = XatFrame(currentPlaybackFramePosition);
    12211204               
    1222                                 FrameGraphics.invalidateArea(new Rectangle(
     1205                                DisplayController.invalidateArea(new AxisAlignedBoxBounds(
    12231206                                                x + offsetX ,
    12241207                                                offsetY,
     
    14621445               
    14631446                // Get border color currently used
    1464                 Color oldC = getSource().getBorderColor();
    1465                
    1466                 Color newC = TrackWidgetCommons.getBorderColor(
     1447                Colour oldC = getSource().getBorderColor();
     1448               
     1449                Colour newC = TrackWidgetCommons.getBorderColor(
    14671450                                SoundDesk.getInstance().isSolo(masterMix.getChannelID()),
    14681451                                                masterMix.isMuted());
     
    15181501         *
    15191502         */
    1520         private class PlaybackPopup extends PlaybackControlPopup {
    1521 
    1522                 private static final long serialVersionUID = 1L;
    1523                
     1503        private class PlaybackPopup extends PlaybackControlPopup
     1504        {
    15241505                public PlaybackPopup() {
    15251506                        miscButton.setActionCommand("goto");
    1526                         miscButton.setIcon(IconRepository.getIcon("goto.png"));
     1507                        SwingMiscManager.setJButtonIcon(miscButton, IconRepository.getIcon("goto.png"));
    15271508                        miscButton.setToolTipText("Goto linked frame");
    15281509                }
    15291510
    15301511                @Override
    1531                 public void onHide() {
    1532                         super.onHide();
     1512                public void onHide()
     1513                {
    15331514                }
    15341515
    15351516                @Override
    1536                 public void onShow() {
    1537                         super.onShow();
     1517                public void onShow()
     1518                {
    15381519                        updateVolume((int)(100 * masterMix.getVolume()));
    15391520                        updateMute(masterMix.isMuted());
    15401521                        updateSolo(SoundDesk.getInstance().isSolo(masterMix.getChannelID()));
    15411522                }
    1542 
    1543                 public void actionPerformed(ActionEvent e) {
    1544                        
     1523               
     1524                public void actionPerformed(ActionEvent e)
     1525                {
    15451526                        if (e.getSource() == miscButton) {
    15461527                               
     
    16701651                                currentPlaybackFramePosition = -1;
    16711652                                setSelection(0, 0); // invalidates
    1672                                 FrameGraphics.refresh(true);
     1653                                DisplayController.requestRefresh(true);
    16731654                               
    16741655                        }
     
    16911672        }
    16921673       
    1693         private class MouseActions implements MouseListener, MouseMotionListener {
    1694 
    1695                 public void mouseClicked(MouseEvent e) {
     1674        private class MouseActions implements MouseListener, MouseMotionListener
     1675        {
     1676                public void mouseClicked(MouseEvent e)
     1677                {
    16961678                        assert(state != EMPTY_STATE);
    16971679                       
     
    17051687                }
    17061688
    1707 
    1708                 public void mouseEntered(MouseEvent e) {
     1689                public void mouseEntered(MouseEvent e)
     1690                {
    17091691                        assert(state != EMPTY_STATE);
    17101692                }
    17111693
    17121694
    1713                 public void mouseExited(MouseEvent e) {
     1695                public void mouseExited(MouseEvent e)
     1696                {
    17141697                        assert(state != EMPTY_STATE);
    1715                        
    1716                 }
    1717 
    1718 
    1719                 public void mousePressed(MouseEvent e) {
    1720                        
     1698                }
     1699
     1700
     1701                public void mousePressed(MouseEvent e)
     1702                {
    17211703                        assert(state != EMPTY_STATE);
    17221704                       
     
    17321714                        setSelection(frameAtX(selectionStartX), 1);
    17331715                       
    1734                         FrameGraphics.refresh(true);
    1735                 }
    1736 
    1737 
    1738                 public void mouseReleased(MouseEvent e) {
    1739                        
    1740 
     1716                        DisplayController.requestRefresh(true);
     1717                }
     1718
     1719
     1720                public void mouseReleased(MouseEvent e)
     1721                {
    17411722                        assert(state != EMPTY_STATE);
    1742                        
    17431723                       
    17441724                        // Was the release a simple click
     
    17651745                                return;
    17661746                        }
    1767 
    1768                        
    1769                 }
    1770                
    1771 
    1772                 public void mouseDragged(MouseEvent e) {
    1773                        
     1747                }
     1748               
     1749
     1750                public void mouseDragged(MouseEvent e)
     1751                {
    17741752                        assert(state != EMPTY_STATE);
    17751753                       
     
    18001778                        }
    18011779                       
    1802                         FrameGraphics.refresh(true);
    1803                 }
    1804 
    1805                 public void mouseMoved(MouseEvent e) {
     1780                        DisplayController.requestRefresh(true);
     1781                }
     1782
     1783                public void mouseMoved(MouseEvent e)
     1784                {
    18061785                        assert(state != EMPTY_STATE);
    18071786                       
    18081787                        if (state != PLAYING && state != STOPPED) return;
    18091788
    1810                         if (nameLabel.onMouseMoved(e, _swingComponent)) {
    1811                                 e.consume();
    1812                                 return;
     1789                        if (nameLabel != null) {
     1790                                nameLabel.gainFocus();
    18131791                        }
    18141792
     
    18221800                               
    18231801                                // Get rid of all popups
    1824                                 PopupManager.getInstance().hideAutohidePopups();
    1825                                
    1826                                 Rectangle animationSource = _swingComponent.getBounds();
     1802                                PopupManager.getInstance().hideAutoHidePopups();
     1803                               
     1804                                AxisAlignedBoxBounds animationSource = SwingConversions.fromSwingRectangle(_swingComponent.getBounds());
    18271805                               
    18281806                                // Determine where popup should show
    18291807                                int x = LinkedTrack.this.getX();
    1830                                 int y = LinkedTrack.this.getY() - playbackControlPopup.getHeight() - 2; // by default show above
     1808                                int y = LinkedTrack.this.getY() - playbackControlPopup.getFullBounds().getHeight() - 2; // by default show above
    18311809                               
    18321810                                // I get sick.dizzy from the popup expanding from the whole thing...
    1833                                 animationSource.height = 1;
    1834                                 animationSource.width = Math.min(animationSource.width, playbackControlPopup.getWidth());
     1811                                animationSource.getSize().height = 1;
     1812                                animationSource.getSize().width = Math.min(animationSource.getWidth(), playbackControlPopup.getFullBounds().getWidth());
    18351813                               
    18361814                                if (y < 0) {
    18371815                                        y = LinkedTrack.this.getY() + LinkedTrack.this.getHeight() + 2;
    1838                                         animationSource.y = y - 2;
     1816                                        animationSource.getTopLeft().y = y - 2;
    18391817                                }
    18401818
    18411819                                // Animate the popup
    1842                                 PopupManager.getInstance().showPopup(
    1843                                                 playbackControlPopup,
    1844                                                 new Point(x, y),
    1845                                                 _swingComponent,
    1846                                                 PopupManager.getInstance().new ExpandShrinkAnimator(
    1847                                                                 animationSource,
    1848                                                                 Color.LIGHT_GRAY));
    1849                                
    1850                                 PopupReaper.getInstance().initPopupLifetime(
    1851                                                 playbackControlPopup,
    1852                                                 PopupManager.getInstance().new ExpandShrinkAnimator(
    1853                                                                 animationSource,
    1854                                                                 Color.LIGHT_GRAY),
    1855                                                                 TrackWidgetCommons.POPUP_LIFETIME);
    1856                                
     1820                                playbackControlPopup.getAutoHideTime().setLifetime(TrackWidgetCommons.POPUP_LIFETIME);
     1821                                PopupManager.getInstance().add(playbackControlPopup);
     1822                                playbackControlPopup.show();
    18571823                        } else {
    1858                                 PopupReaper.getInstance().revivePopup(playbackControlPopup, TrackWidgetCommons.POPUP_LIFETIME);
     1824                                playbackControlPopup.show();
    18591825                        }
    18601826                       
     
    18781844                        if (shouldInvalidate) {
    18791845                                invalidateSelf();
    1880                                 FrameGraphics.refresh(true);
     1846                                DisplayController.requestRefresh(true);
    18811847                        }
    18821848                }
     
    18881854         * @author Brook Novak
    18891855         */
    1890         private class Track {
    1891                
     1856        private class Track
     1857        {
    18921858                private AbsoluteTrackNode absNode; // immutable. Never null
    18931859               
    18941860                private Rectangle area;
    18951861               
    1896                 private Color baseColor;
     1862                private Colour baseColor;
    18971863               
    18981864                boolean isSelected = false;
     
    19001866                private int state = TRACKSTATE_READY;
    19011867               
    1902                 Track(AbsoluteTrackNode absNode) {
     1868                Track(AbsoluteTrackNode absNode)
     1869                {
    19031870                        assert(absNode != null);
    19041871                        this.absNode = absNode;
    19051872                }
    19061873               
    1907                 public String getChannelID() {
     1874                public String getChannelID()
     1875                {
    19081876                        return absNode.getChannelID();
    19091877                }
     
    19291897                }
    19301898               
    1931                 public void paintTrackArea(Graphics2D g, int x, int y) {
     1899                public void paintTrackArea(int x, int y)
     1900                {
     1901                        Graphics2D g = SwingMiscManager.getIfUsingSwingGraphicsManager().getCurrentSurface();
    19321902                       
    19331903                        if (state == TRACKSTATE_LOADING && LinkedTrack.this.state == PLAYBACK_LOADING) {
    1934                                 g.setColor(TRACK_LOAD_COLOR);
     1904                                g.setColor(SwingConversions.toSwingColor(TRACK_LOAD_COLOR));
    19351905                        } else if (state == TRACKSTATE_FAILED) {
    1936                                 g.setColor(TRACK_FAIL_COLOR);
     1906                                g.setColor(SwingConversions.toSwingColor(TRACK_FAIL_COLOR));
    19371907                        } else {
    1938                                 g.setColor(baseColor);
     1908                                g.setColor(SwingConversions.toSwingColor(baseColor));
    19391909                        }
    19401910                       
     
    19431913
    19441914                                GradientPaint gp = new GradientPaint(
    1945                                                 (int) (area.x + x + (area.width / 2)), area.y + y + (int)(area.height * 0.8), baseColor,
    1946                                                 (int) (area.x + x + (area.width / 2)), area.y + y, TRACK_SELECTED_BORDER_COLOR);
     1915                                                (int) (area.x + x + (area.width / 2)), area.y + y + (int)(area.height * 0.8), SwingConversions.toSwingColor(baseColor),
     1916                                                (int) (area.x + x + (area.width / 2)), area.y + y, SwingConversions.toSwingColor(TRACK_SELECTED_BORDER_COLOR));
    19471917                                g.setPaint(gp);
    19481918                        }
    19491919                       
    1950                         // Draw a filled rect - represented a track in the heirarchy
     1920                        // Draw a filled rect - represented a track in the hierarchy
    19511921                        g.fillRect(area.x + x, area.y + y, area.width, area.height);
    19521922                       
     
    19571927                }
    19581928               
    1959                 public void paintTrackBorder(Graphics g, int x, int y) {
     1929                public void paintTrackBorder(int x, int y)
     1930                {
     1931                        Graphics g = SwingMiscManager.getIfUsingSwingGraphicsManager().getCurrentSurface();
    19601932                       
    19611933                        if (isSelected) {
    1962                                 g.setColor(TRACK_SELECTED_BORDER_COLOR);
    1963                                 ((Graphics2D)g).setStroke(TRACK_SELECTED_BORDER);
     1934                                g.setColor(SwingConversions.toSwingColor(TRACK_SELECTED_BORDER_COLOR));
     1935                                ((Graphics2D)g).setStroke(SwingConversions.toSwingStroke(TRACK_SELECTED_BORDER));
    19641936                        } else {
    1965                                 g.setColor(TRACK_BORDER_COLOR);
    1966                                 ((Graphics2D)g).setStroke(TRACK_BORDER); // todo muted colors etc...
     1937                                g.setColor(SwingConversions.toSwingColor(TRACK_BORDER_COLOR));
     1938                                ((Graphics2D)g).setStroke(SwingConversions.toSwingStroke(TRACK_BORDER)); // todo muted colors etc...
    19671939                        }
    19681940                       
     
    19721944        }
    19731945       
     1946        // TODO: Why not? cts16
    19741947        @Override
    19751948        public boolean isWidgetEdgeThicknessAdjustable() {
  • trunk/src/org/apollo/widgets/MasterVolume.java

    r315 r1102  
    1212import org.expeditee.items.ItemParentStateChangedEvent;
    1313import org.expeditee.items.Text;
    14 import org.expeditee.items.widgets.InteractiveWidget;
     14import org.expeditee.items.widgets.SwingWidget;
    1515
    1616/**
     
    2020 *
    2121 */
    22 public class MasterVolume extends InteractiveWidget implements Observer {
     22public class MasterVolume extends SwingWidget implements Observer {
    2323       
    2424        private VolumeControlButton vcButton;
  • trunk/src/org/apollo/widgets/MetronomePlayer.java

    r335 r1102  
    2121import org.apollo.mvc.Subject;
    2222import org.apollo.mvc.SubjectChangedEvent;
     23import org.expeditee.gio.swing.SwingMiscManager;
    2324import org.expeditee.items.ItemParentStateChangedEvent;
    2425import org.expeditee.items.Text;
    25 import org.expeditee.items.widgets.InteractiveWidget;
     26import org.expeditee.items.widgets.SwingWidget;
    2627
    2728/**
     
    3334 *
    3435 */
    35 public class MetronomePlayer extends InteractiveWidget implements Observer {
     36public class MetronomePlayer extends SwingWidget implements Observer {
    3637       
    3738        private JLabel tempoLabel;
    3839        private JSlider bpmSlider;
    3940        private JButton startStopButton;
    40         private JComboBox beatsPerMeasureCombo;
     41        private JComboBox<String> beatsPerMeasureCombo;
    4142        private JCheckBox enabledCheckbox;
    4243        private boolean interfaceIsUpdating = false;
     
    8485                });
    8586
    86                 beatsPerMeasureCombo = new JComboBox(new String[]{"1", "2", "3", "4", "5", "6", "7", "8"});
     87                beatsPerMeasureCombo = new JComboBox<String>(new String[]{"1", "2", "3", "4", "5", "6", "7", "8"});
    8788                beatsPerMeasureCombo.setPreferredSize(new Dimension(60, 25));
    8889                beatsPerMeasureCombo.setEditable(false);
     
    133134                       
    134135                        if (Metronome.getInstance().isPlaying()) {
    135                                 startStopButton.setIcon(IconRepository.getIcon("metrostop.png"));
     136                                SwingMiscManager.setJButtonIcon(startStopButton, IconRepository.getIcon("metrostop.png"));
    136137                                setWidgetEdgeThickness(TrackWidgetCommons.PLAYING_TRACK_EDGE_THICKNESS);
    137138       
    138139                        } else {
    139                                 startStopButton.setIcon(IconRepository.getIcon("metroplay.png"));
     140                                SwingMiscManager.setJButtonIcon(startStopButton, IconRepository.getIcon("metroplay.png"));
    140141                                setWidgetEdgeThickness(TrackWidgetCommons.STOPPED_TRACK_EDGE_THICKNESS);
    141142                        }
  • trunk/src/org/apollo/widgets/SampleRecorder.java

    r1057 r1102  
    11package org.apollo.widgets;
    22
    3 import java.awt.Color;
    43import java.awt.Dimension;
    54import java.awt.FontMetrics;
     
    4948import org.apollo.util.ApolloSystemLog;
    5049import org.apollo.util.TrackNameCreator;
    51 import org.expeditee.gui.DisplayIO;
     50import org.expeditee.core.Colour;
     51import org.expeditee.gio.gesture.StandardGestureActions;
     52import org.expeditee.gio.swing.SwingConversions;
     53import org.expeditee.gio.swing.SwingMiscManager;
     54import org.expeditee.gui.DisplayController;
    5255import org.expeditee.gui.Frame;
    53 import org.expeditee.gui.FrameGraphics;
    54 import org.expeditee.gui.FrameMouseActions;
    5556import org.expeditee.items.ItemParentStateChangedEvent;
    5657import org.expeditee.items.Text;
    57 import org.expeditee.items.widgets.InteractiveWidget;
     58import org.expeditee.items.widgets.SwingWidget;
    5859
    5960/**
     
    6364 *
    6465 */
    65 public class SampleRecorder extends InteractiveWidget
    66         implements ActionListener, Observer, MultitrackLoadListener {
     66public class SampleRecorder extends SwingWidget implements ActionListener, Observer, MultitrackLoadListener {
    6767       
    6868        private enum WidgetState {
     
    105105        private final static int MAX_COUNTDOWN_TIME = 60;
    106106       
    107         private static final Color GRAPH_BACKCOLOR = Color.BLACK;
    108         private static final Color GRAPH_WAVECOLOR = Color.GREEN;
     107        private static final Colour GRAPH_BACKCOLOR = Colour.BLACK;
     108        private static final Colour GRAPH_WAVECOLOR = Colour.GREEN;
    109109       
    110110        private final static int RENDER_POINTS_PER_SECOND = 20; // how many points to render each second
     
    112112        private final static String COUNTDOWN_META = "countdown=";
    113113       
    114         public SampleRecorder(Text source, String[] args) {
     114        public SampleRecorder(Text source, String[] args)
     115        {
    115116                this(source, args, false);
    116117        }
    117118       
    118         public SampleRecorder(Text source, String[] args, boolean isTemporary) {
     119        public SampleRecorder(Text source, String[] args, boolean isTemporary)
     120        {
    119121                super(source, new JPanel(new GridBagLayout()),
    120122                                AnimatedSampleGraph.GRAPH_WIDTH + (2 * HORO_SPACING),
     
    132134                // Create gui layout
    133135                recordButton = new JButton();
    134                 recordButton.setIcon(IconRepository.getIcon("record.png"));
     136                SwingMiscManager.setJButtonIcon(recordButton, IconRepository.getIcon("record.png"));
    135137                recordButton.addActionListener(this);
    136138                recordButton.setPreferredSize(new Dimension(AnimatedSampleGraph.GRAPH_WIDTH / 2, BUTTON_HEIGHT));
    137139               
    138140                recordSynchedButton = new JButton();
    139                 recordSynchedButton.setIcon(IconRepository.getIcon("recordplay.png"));
     141                SwingMiscManager.setJButtonIcon(recordSynchedButton, IconRepository.getIcon("recordplay.png"));
    140142                recordSynchedButton.addActionListener(this);
    141143                recordSynchedButton.setPreferredSize(new Dimension(AnimatedSampleGraph.GRAPH_WIDTH / 2, BUTTON_HEIGHT));
    142144
    143145                stopButton = new JButton();
    144                 stopButton.setIcon(IconRepository.getIcon("stop.png"));
     146                SwingMiscManager.setJButtonIcon(stopButton, IconRepository.getIcon("stop.png"));
    145147                stopButton.addActionListener(this);
    146148                stopButton.setPreferredSize(new Dimension(AnimatedSampleGraph.GRAPH_WIDTH, BUTTON_HEIGHT));
     
    303305       
    304306                                sampleGraph.alternateText = Integer.toString(countDown);
    305                                 sampleGraph.alternateTextColor = (countDown > 3) ? Color.WHITE : Color.RED;
     307                                sampleGraph.alternateTextColor = (countDown > 3) ? Colour.WHITE : Colour.RED;
    306308                                sampleGraph.invalidateGraph();
    307                                 FrameGraphics.refresh(true);
     309                                DisplayController.requestRefresh(true);
    308310                               
    309311                                countdownThread = new CountDownTimer(countDown);
     
    373375                                         Frame targetFrame = getParentFrame();
    374376                                         if (targetFrame == null) {
    375                                                  targetFrame = DisplayIO.getCurrentFrame();
     377                                                 targetFrame = DisplayController.getCurrentFrame();
    376378                                         }
    377379                                         
     
    398400                                         } else {
    399401                                                 
    400                                                  FrameMouseActions.pickup(trackWidget.getItems());
     402                                                 StandardGestureActions.pickup(trackWidget.getItems());
    401403                                                       
    402404                                                // Reset the state
     
    602604                        assert (state == WidgetState.Ready);
    603605                       
    604                         Frame target = DisplayIO.getCurrentFrame();
     606                        Frame target = DisplayController.getCurrentFrame();
    605607                        if (target  == null) return;
    606608
     
    608610                       
    609611                        RecordOverdubLauncher launcher = new RecordOverdubLauncher((Integer)countDownSpinner.getValue());
    610                         launcher.setPosition(FrameMouseActions.MouseX, FrameMouseActions.MouseY);
     612                        launcher.setPosition(DisplayController.getMousePosition());
    611613
    612614                        // Pick it up
    613                         FrameMouseActions.pickup(launcher);
     615                        StandardGestureActions.pickup(launcher);
    614616                       
    615617                }
     
    757759                        setState(WidgetState.LoadingPlayback, "Loading tracks...");
    758760                       
    759                         Frame currentFrame = DisplayIO.getCurrentFrame();
     761                        Frame currentFrame = DisplayController.getCurrentFrame();
    760762                        if (currentFrame == null || currentFrame.getName() == null) {
    761763                               
     
    843845               
    844846                private String alternateText = null;
    845                 private Color alternateTextColor = Color.WHITE;
     847                private Colour alternateTextColor = Colour.WHITE;
    846848
    847849                AnimatedSampleGraph() {
    848850                        imageBuffer = new BufferedImage(GRAPH_WIDTH, GRAPH_HEIGHT, BufferedImage.TYPE_INT_RGB);
    849851                        imageGraphics = (Graphics2D)imageBuffer.getGraphics();
    850                         imageGraphics.setColor(GRAPH_BACKCOLOR);
     852                        imageGraphics.setColor(SwingConversions.toSwingColor(GRAPH_BACKCOLOR));
    851853                        imageGraphics.fillRect(0, 0, GRAPH_WIDTH, GRAPH_HEIGHT);
    852854                        setPreferredSize(new Dimension(GRAPH_WIDTH, GRAPH_HEIGHT));
     
    857859                 */
    858860                public void clear() {
    859                         imageGraphics.setColor(GRAPH_BACKCOLOR);
     861                        imageGraphics.setColor(SwingConversions.toSwingColor(GRAPH_BACKCOLOR));
    860862                        imageGraphics.fillRect(0, 0, GRAPH_WIDTH, GRAPH_HEIGHT);
    861863                        invalidateGraph();
     
    867869                        if (alternateText != null) {
    868870                               
    869                                 g.setColor(Color.BLACK);
     871                                g.setColor(SwingConversions.toSwingColor(Colour.BLACK));
    870872                                g.fillRect(0, 0, getWidth(), getHeight());
    871873                               
    872                                 g.setFont(TrackWidgetCommons.FREESPACE_TRACKNAME_FONT);
    873                                 g.setColor(alternateTextColor);
     874                                g.setFont(SwingMiscManager.getIfUsingSwingFontManager().getInternalFont(TrackWidgetCommons.FREESPACE_TRACKNAME_FONT));
     875                                g.setColor(SwingConversions.toSwingColor(alternateTextColor));
    874876                               
    875877                                // Center track name
    876                                 FontMetrics fm   = g.getFontMetrics(TrackWidgetCommons.FREESPACE_TRACKNAME_FONT);
     878                                FontMetrics fm   = g.getFontMetrics(SwingMiscManager.getIfUsingSwingFontManager().getInternalFont(TrackWidgetCommons.FREESPACE_TRACKNAME_FONT));
    877879                                Rectangle2D rect = fm.getStringBounds(alternateText, g);
    878880                               
     
    907909                       
    908910                        // Render backcolor
    909                         imageGraphics.setColor(GRAPH_BACKCOLOR);
     911                        imageGraphics.setColor(SwingConversions.toSwingColor(GRAPH_BACKCOLOR));
    910912                        imageGraphics.fillRect(GRAPH_WIDTH - pixelWidth, 0, pixelWidth, GRAPH_HEIGHT);
    911913                       
    912914                        // Render wave forms from lastSampleHeight
    913                         imageGraphics.setColor(GRAPH_WAVECOLOR);
     915                        imageGraphics.setColor(SwingConversions.toSwingColor(GRAPH_WAVECOLOR));
    914916                        int currentPixelX = GRAPH_WIDTH - pixelWidth;
    915917
     
    933935                Rectangle dirty = this.getBounds();
    934936                dirty.translate(SampleRecorder.this.getX(), SampleRecorder.this.getY());
    935                 FrameGraphics.invalidateArea(dirty);
    936                 FrameGraphics.refresh(true);
     937                DisplayController.invalidateArea(SwingConversions.fromSwingRectangle(dirty));
     938                DisplayController.requestRefresh(true);
    937939               
    938940                }
     
    979981                                                        sampleGraph.alternateText = Integer.toString(currentCountdown);
    980982                                                        sampleGraph.alternateTextColor = (currentCountdown > 3) ?
    981                                                                                 Color.WHITE : Color.RED;
     983                                                                                Colour.WHITE : Colour.RED;
    982984                                                        sampleGraph.invalidateGraph();
    983                                                         FrameGraphics.refresh(true);
     985                                                        DisplayController.requestRefresh(true);
    984986                                                }
    985987                                        });
  • trunk/src/org/apollo/widgets/SampledTrack.java

    r1007 r1102  
    55import java.awt.Graphics;
    66import java.awt.Graphics2D;
    7 import java.awt.Point;
    87import java.awt.Rectangle;
    98import java.awt.Shape;
    10 import java.awt.Stroke;
    119import java.awt.event.ActionEvent;
    1210import java.awt.event.KeyEvent;
     
    2725import javax.swing.SwingUtilities;
    2826
    29 import org.apollo.AudioFrameKeyboardActions;
    30 import org.apollo.AudioFrameMouseActions;
     27import org.apollo.ApolloGestureActions;
     28import org.apollo.ApolloKBMGestureTranslator;
    3129import org.apollo.audio.ApolloPlaybackMixer;
    3230import org.apollo.audio.ApolloSubjectChangedEvent;
     
    5654import org.apollo.util.AudioMath;
    5755import org.apollo.util.Mutable;
    58 import org.apollo.util.PopupReaper;
    5956import org.apollo.util.TrackModelHandler;
    6057import org.apollo.util.TrackModelLoadManager;
    6158import org.apollo.util.TrackNameCreator;
    62 import org.expeditee.gui.Browser;
    63 import org.expeditee.gui.DisplayIO;
     59import org.expeditee.Util;
     60import org.expeditee.core.Colour;
     61import org.expeditee.core.Point;
     62import org.expeditee.core.Stroke;
     63import org.expeditee.core.bounds.AxisAlignedBoxBounds;
     64import org.expeditee.gio.gesture.StandardGestureActions;
     65import org.expeditee.gio.swing.MouseEventRouter;
     66import org.expeditee.gio.swing.SwingConversions;
     67import org.expeditee.gio.swing.SwingMiscManager;
     68import org.expeditee.gui.DisplayController;
    6469import org.expeditee.gui.Frame;
    65 import org.expeditee.gui.FrameGraphics;
    6670import org.expeditee.gui.FrameIO;
    67 import org.expeditee.gui.FrameMouseActions;
    68 import org.expeditee.gui.MouseEventRouter;
    6971import org.expeditee.gui.PopupManager;
    7072import org.expeditee.items.ItemParentStateChangedEvent;
     
    7274import org.expeditee.items.Text;
    7375import org.expeditee.items.widgets.HeavyDutyInteractiveWidget;
    74 import org.expeditee.items.widgets.InteractiveWidget;
    7576import org.expeditee.items.widgets.InteractiveWidgetInitialisationFailedException;
    7677import org.expeditee.items.widgets.InteractiveWidgetNotAvailableException;
     78import org.expeditee.items.widgets.Widget;
    7779
    7880/**
     
    8284 *
    8385 */
    84 public class SampledTrack extends HeavyDutyInteractiveWidget
    85         implements TrackModelHandler, EffecientInvalidator, Observer {
     86public class SampledTrack extends HeavyDutyInteractiveWidget implements TrackModelHandler, EffecientInvalidator, Observer {
    8687
    8788        /** The observered subject. Can be null */
     
    115116        private static final Stroke FREESPACE_OUTLINING = Strokes.SOLID_2;
    116117       
    117         private static final Color SEMI_TRANSPARENT_FREESPACE_BACKCOLOR = new Color(
     118        private static final Colour SEMI_TRANSPARENT_FREESPACE_BACKCOLOR = new Colour(
    118119                        FREESPACE_BACKCOLOR.getRed(), FREESPACE_BACKCOLOR.getGreen(),
    119                         FREESPACE_BACKCOLOR.getBlue(), 128);
     120                        FREESPACE_BACKCOLOR.getBlue(), Colour.FromComponent255(128));
    120121       
    121122       
     
    173174                initObservers();
    174175               
     176        }
     177       
     178        @Override
     179        public void onMoved()
     180        {
     181                if (nameLabel != null) nameLabel.setPosition(new Point(getX() + 10, getY() + 20));
    175182        }
    176183
     
    279286
    280287                                if (nameLabel != null) {
    281                                         nameLabel.onMouseMoved(e, fulltrackView);
     288                                        nameLabel.gainFocus();
    282289                                }
    283290                               
     
    291298                                       
    292299                                        // Get rid of all popups
    293                                         PopupManager.getInstance().hideAutohidePopups();
     300                                        PopupManager.getInstance().hideAutoHidePopups();
    294301                                       
    295302                                        Rectangle animationSource = _swingComponent.getBounds();
     
    297304                                        // Determine where popup should show
    298305                                        int x = SampledTrack.this.getX();
    299                                         int y = SampledTrack.this.getY() - playbackControlPopup.getHeight() - 2; // by default show above
     306                                        int y = SampledTrack.this.getY() - playbackControlPopup.getFullBounds().getHeight() - 2; // by default show above
    300307                                       
    301308                                        // I get sick.dizzy from the popup expanding from the whole thing...
    302309                                        animationSource.height = 1;
    303                                         animationSource.width = Math.min(animationSource.width, playbackControlPopup.getWidth());
     310                                        animationSource.width = Math.min(animationSource.width, playbackControlPopup.getFullBounds().getWidth());
    304311                                       
    305312                                        if (y < 0) {
     
    309316
    310317                                        // Animate the popup
    311                                         PopupManager.getInstance().showPopup(
    312                                                         playbackControlPopup,
    313                                                         new Point(x, y),
    314                                                         fulltrackView,
    315                                                         PopupManager.getInstance().new ExpandShrinkAnimator(
    316                                                                         animationSource,
    317                                                                         Color.LIGHT_GRAY));
    318                                        
    319                                         PopupReaper.getInstance().initPopupLifetime(
    320                                                         playbackControlPopup,
    321                                                         PopupManager.getInstance().new ExpandShrinkAnimator(
    322                                                                         animationSource,
    323                                                                         Color.LIGHT_GRAY),
    324                                                                         TrackWidgetCommons.POPUP_LIFETIME);
    325                                        
     318                                        playbackControlPopup.getAutoHideTime().setLifetime(TrackWidgetCommons.POPUP_LIFETIME);
     319                                        PopupManager.getInstance().add(playbackControlPopup);
     320                                        playbackControlPopup.show();
    326321                                } else {
    327                                         PopupReaper.getInstance().revivePopup(playbackControlPopup, TrackWidgetCommons.POPUP_LIFETIME);
     322                                        playbackControlPopup.show();
    328323                                }
    329324                               
     
    398393                fulltrackView.addKeyListener(new KeyListener() {
    399394
    400                         public void keyPressed(KeyEvent e) {
    401                                 if (!e.isControlDown() && nameLabel != null) {
    402                                         if (nameLabel.onKeyPressed(e, fulltrackView)) {
    403                                                 e.consume();
    404                                         }
    405                                 }
    406                         }
    407 
    408                         public void keyReleased(KeyEvent e) {
    409                                 if (!e.isControlDown() && nameLabel != null) {
    410                                         if (nameLabel.onKeyReleased(e, fulltrackView)) {
    411                                                 e.consume();
    412                                         }
    413                                 }
    414                                
     395                        public void keyPressed(KeyEvent e)
     396                        {
     397                        }
     398
     399                        public void keyReleased(KeyEvent e)
     400                        {
    415401                                // Toggle pitch-track indexing
    416402                                if (e.isControlDown() && e.getKeyCode() == KeyEvent.VK_I) {
    417403                                        setShouldOmitIndexAudio(!shouldOmitIndexAudio());
    418                                         FrameGraphics.refresh(true);
     404                                        DisplayController.requestRefresh(true);
    419405                                }
    420406                               
     
    429415                                else if (e.isControlDown() && e.getKeyCode() == KeyEvent.VK_L) {
    430416
    431                                         Frame current = DisplayIO.getCurrentFrame();
     417                                        Frame current = DisplayController.getCurrentFrame();
    432418                                       
    433419                                        if (current != null) {
     
    473459                                        }
    474460       
    475                                 } else if (e.isControlDown() &&
    476                                                 (e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_RIGHT)) {
    477                                         e.consume();
    478                                         AudioFrameKeyboardActions.adjustInitationTime(SampledTrack.this, e.getKeyCode() == KeyEvent.VK_LEFT);
    479                                 } else if (e.isControlDown() &&
    480                                                 (e.getKeyCode() == KeyEvent.VK_UP || e.getKeyCode() == KeyEvent.VK_DOWN)) {
    481                                         e.consume();
    482                                         AudioFrameKeyboardActions.adjustVerticlePosition(SampledTrack.this, e.getKeyCode() == KeyEvent.VK_UP);
     461                                } else if (e.isControlDown()) {
     462                                        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
     463                                                e.consume();
     464                                                ApolloGestureActions.adjustInitiationTime(SampledTrack.this, -ApolloKBMGestureTranslator.TRACK_WIDGET_TIMELINE_ADJUSTMENT);
     465                                        } else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
     466                                                e.consume();
     467                                                ApolloGestureActions.adjustInitiationTime(SampledTrack.this, ApolloKBMGestureTranslator.TRACK_WIDGET_TIMELINE_ADJUSTMENT);
     468                                        } else if (e.getKeyCode() == KeyEvent.VK_UP) {
     469                                                e.consume();
     470                                                ApolloGestureActions.adjustVerticalPosition(SampledTrack.this, -ApolloKBMGestureTranslator.TRACK_WIDGET_VERTICAL_ADJUSTMENT);
     471                                        } else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
     472                                                e.consume();
     473                                                ApolloGestureActions.adjustVerticalPosition(SampledTrack.this, ApolloKBMGestureTranslator.TRACK_WIDGET_VERTICAL_ADJUSTMENT);
     474                                        }
    483475                                }
    484476
     
    490482                });
    491483               
    492                
    493                
    494                 nameLabel = new EmulatedTextItem(_swingComponent, new Point(10, 20));
    495                 nameLabel.setBackgroundColor(Color.WHITE);     
     484                nameLabel = new EmulatedTextItem("", (new Point(10, 20)).add(getBounds().getTopLeft()));
     485                nameLabel.setBackgroundColor(Colour.WHITE);     
    496486               
    497487                String metaName = getStrippedDataString(TrackWidgetCommons.META_NAME_TAG);
     
    616606                Text source = new Text(
    617607                                targetFrame.getNextItemID(),
    618                                 ItemUtils.GetTag(ItemUtils.TAG_IWIDGET) + ":" + formatArgs(args));
     608                                ItemUtils.GetTag(ItemUtils.TAG_IWIDGET) + ":" + Util.formatArgs(args));
    619609               
    620610                source.setParent(targetFrame);
     
    685675       
    686676        @Override
    687         public InteractiveWidget copy()
     677        public Widget copy()
    688678                throws InteractiveWidgetNotAvailableException, InteractiveWidgetInitialisationFailedException {
    689679               
     
    11191109        }
    11201110
    1121         public void onGraphDirty(SampledTrackGraphView graph, Rectangle dirty) {
     1111        public void onGraphDirty(SampledTrackGraphView graph, Rectangle dirty)
     1112        {
    11221113        dirty.translate(getX(), getY() - 1);
    1123         FrameGraphics.invalidateArea(dirty);
    1124         FrameGraphics.refresh(true);
     1114        DisplayController.invalidateArea(SwingConversions.fromSwingRectangle(dirty));
     1115        DisplayController.requestRefresh(true);
    11251116        }
    11261117
     
    11311122
    11321123        @Override
    1133         protected void onSizeChanged() {
     1124        protected void onSizeChanged()
     1125        {
    11341126                super.onSizeChanged();
    11351127                // Keep meta as constant as possible for best reults
     
    12461238
    12471239        @Override
    1248         public void paintInFreeSpace(Graphics g) {
    1249                 paintInFreeSpace(g, false);
    1250         }
    1251        
    1252         public void paintInFreeSpace(Graphics g, boolean isAtFinalPass) {
     1240        public void paintInFreeSpace()
     1241        {
     1242                paintInFreeSpace(false);
     1243        }
     1244       
     1245        public void paintInFreeSpace(boolean isAtFinalPass)
     1246        {
     1247                Graphics g = SwingMiscManager.getIfUsingSwingGraphicsManager().getCurrentSurface();
    12531248
    12541249                if (isLoaded()) {
     
    12701265                                       
    12711266
    1272                                         Point containerPoint = SwingUtilities.convertPoint(me.getComponent(),
    1273                                                         new Point(0,0), Browser._theBrowser.getContentPane());
     1267                                        Point containerPoint = SwingConversions.fromSwingPoint(SwingUtilities.convertPoint(me.getComponent(),
     1268                                                        new java.awt.Point(0,0), SwingMiscManager.getIfUsingSwingGraphicsManager().getContentPane()));
    12741269                                       
    12751270                                        Shape clipBackUp = g.getClip();
    12761271                                        g.setClip(null);
    12771272                                       
    1278                                         g.setColor(Color.ORANGE);
     1273                                        g.setColor(SwingConversions.toSwingColor(Colour.ORANGE));
    12791274                                        ((Graphics2D)g).setStroke(EditableSampledTrackGraphView.GRAPH_BAR_STROKE);
    12801275                                        g.drawLine(
     
    12841279                                                        containerPoint.y + me.getComponent().getHeight());
    12851280                                       
    1286                                         FrameGraphics.invalidateArea(new Rectangle(
     1281                                        DisplayController.invalidateArea(new AxisAlignedBoxBounds(
    12871282                                                        containerPoint.x + me.getX(),
    12881283                                                        containerPoint.y,
     
    12931288                                        g.setClip(clipBackUp);
    12941289                                       
    1295                                         g.setColor(SEMI_TRANSPARENT_FREESPACE_BACKCOLOR);
     1290                                        g.setColor(SwingConversions.toSwingColor(SEMI_TRANSPARENT_FREESPACE_BACKCOLOR));
    12961291                                        g.fillRect(getX(), getY(), getWidth(), getHeight());
    12971292                                       
    12981293                                        if (isAtFinalPass) { // final pass does not draw the borders... so must manually draw them
    1299                                                 g.setColor(Color.BLACK);
    1300                                                 ((Graphics2D)g).setStroke(FREESPACE_OUTLINING);
     1294                                                g.setColor(SwingConversions.toSwingColor(Colour.BLACK));
     1295                                                ((Graphics2D)g).setStroke(SwingConversions.toSwingStroke(FREESPACE_OUTLINING));
    13011296                                                g.drawRect(getX(), getY(), getWidth(), getHeight());
    13021297                                        }
     
    13111306                }
    13121307               
    1313                 super.paintInFreeSpace(g);
     1308                super.paintInFreeSpace();
    13141309               
    13151310                if (isLoaded()) {
     
    13181313                        Rectangle tmpClip = (clipBackUp != null) ? clipBackUp.getBounds() :
    13191314                                new Rectangle(0, 0,
    1320                                                 Browser._theBrowser.getContentPane().getWidth(),
    1321                                                 Browser._theBrowser.getContentPane().getHeight());
    1322                                
    1323                         g.setClip(tmpClip.intersection(getBounds()));
     1315                                                SwingMiscManager.getIfUsingSwingGraphicsManager().getContentPane().getWidth(),
     1316                                                SwingMiscManager.getIfUsingSwingGraphicsManager().getContentPane().getHeight());
     1317                               
     1318                        g.setClip(tmpClip.intersection(SwingConversions.toSwingRectangle(getBounds())));
    13241319               
    13251320                        // Draw the name
     
    13271322                        if (name == null) name = "Unnamed";
    13281323
    1329                         g.setFont(TrackWidgetCommons.FREESPACE_TRACKNAME_FONT);
    1330                         g.setColor(TrackWidgetCommons.FREESPACE_TRACKNAME_TEXT_COLOR);
     1324                        g.setFont(SwingMiscManager.getIfUsingSwingFontManager().getInternalFont(TrackWidgetCommons.FREESPACE_TRACKNAME_FONT));
     1325                        g.setColor(SwingConversions.toSwingColor(TrackWidgetCommons.FREESPACE_TRACKNAME_TEXT_COLOR));
    13311326                       
    13321327                        // Center track name
    1333                         FontMetrics fm   = g.getFontMetrics(TrackWidgetCommons.FREESPACE_TRACKNAME_FONT);
     1328                        FontMetrics fm   = g.getFontMetrics(SwingMiscManager.getIfUsingSwingFontManager().getInternalFont(TrackWidgetCommons.FREESPACE_TRACKNAME_FONT));
    13341329                        Rectangle2D rect = fm.getStringBounds(name, g);
    13351330                       
     
    13491344
    13501345        @Override
    1351         public void paint(Graphics g) {
    1352                 super.paint(g);
     1346        public void paintHeavyDutyWidget(Graphics2D g)
     1347        {
     1348                super.paintHeavyDutyWidget(g);
    13531349               
    13541350                if (isLoaded() && nameLabel != null) {
    1355                         nameLabel.paint(g);
     1351                        nameLabel.paint();
    13561352                       
    13571353                        if (shouldOmitIndexAudio()) {
     
    13601356                                                -20 : 0;
    13611357                               
    1362                                 IconRepository.getIcon("omitindexed.png").paintIcon(
     1358                                /*IconRepository.getIcon("omitindexed.png").paintIcon(
    13631359                                                _swingComponent,
    13641360                                                g,
    13651361                                                getX() + getWidth() - EditableSampledTrackGraphView.LOCK_ICON_CORNER_OFFSET + shiftOffset,
    1366                                                 getY() + EditableSampledTrackGraphView.LOCK_ICON_CORNER_OFFSET - 16);
     1362                                                getY() + EditableSampledTrackGraphView.LOCK_ICON_CORNER_OFFSET - 16);*/
     1363                               
     1364                                g.drawImage(SwingMiscManager.getIfUsingSwingImageManager().getInternalImage(IconRepository.getIcon("omitindexed.png")),
     1365                                                getX() + getWidth() - EditableSampledTrackGraphView.LOCK_ICON_CORNER_OFFSET + shiftOffset,
     1366                                                getY() + EditableSampledTrackGraphView.LOCK_ICON_CORNER_OFFSET - 16, null);
    13671367                               
    13681368                        }
     
    14041404                                                boolean inferInitTime = true;
    14051405                                               
    1406                                                 if (AudioFrameMouseActions.isYAxisRestictionOn()) {
     1406                                                if (ApolloGestureActions.isYAxisRestictionOn()) {
    14071407                                                        Mutable.Long ms = getInitiationTimeFromMeta();
    14081408                                                        if (ms != null) {
     
    14171417                                                }
    14181418                                               
    1419                                                 inferInitTime &=
    1420                                                         (AudioFrameMouseActions.isMouseAnchoring() || AudioFrameMouseActions.isMouseStamping());
    1421 
     1419                                                // Also must not set initiation time if the frame is simply being displayed
     1420                                                //inferInitTime &= (AudioFrameMouseActions.isMouseAnchoring() || AudioFrameMouseActions.isMouseStamping());
     1421                                                inferInitTime &= (eventType == ItemParentStateChangedEvent.EVENT_TYPE_ADDED);
     1422                                               
    14221423                                                if (inferInitTime)
    14231424                                                        initTime = Mutable.createMutableLong(FrameLayoutDaemon.getInstance().getMSAtX(getX(), parent));
     
    14991500                                                MouseEventRouter.getCurrentMouseEvent().getButton() == MouseEvent.BUTTON2 &&
    15001501                                                MouseEventRouter.getCurrentMouseEvent() != lastInsertME) {
    1501                                         Frame suspended = DisplayIO.getCurrentFrame();
     1502                                        Frame suspended = DisplayController.getCurrentFrame();
    15021503                                        if (suspended != null) {
    15031504                                                FrameLayoutDaemon.getInstance().suspendLayout(suspended, this);
     
    16821683               
    16831684                // Get border color currently used
    1684                 Color oldC = getSource().getBorderColor();
    1685                
    1686                 Color newC = TrackWidgetCommons.getBorderColor(
     1685                Colour oldC = getSource().getBorderColor();
     1686               
     1687                Colour newC = TrackWidgetCommons.getBorderColor(
    16871688                                SoundDesk.getInstance().isSolo(trackMix.getChannelID()),
    16881689                                trackMix.isMuted());
     
    17721773                                // Build the new neighbouring widget
    17731774                                Frame target = getParentFrame();
    1774                                 if (target == null) target = DisplayIO.getCurrentFrame();
     1775                                if (target == null) target = DisplayController.getCurrentFrame();
    17751776                               
    17761777                                // Determine init time
     
    18111812                                                        trackMix);
    18121813                                       
    1813                                         FrameMouseActions.pickup(extractedTrack.getItems());
     1814                                        StandardGestureActions.pickup(extractedTrack.getItems());
    18141815                                       
    18151816                                }
     
    18401841                                                trackModel,
    18411842                                                pfname,
    1842                                                 _swingComponent.getBounds(),
     1843                                                SwingConversions.fromSwingRectangle(_swingComponent.getBounds()),
    18431844                                                trackMix);
    18441845
     
    18461847
    18471848                                // Get rid of all popups
    1848                                 PopupManager.getInstance().hideAutohidePopups();
     1849                                PopupManager.getInstance().hideAutoHidePopups();
    18491850                               
    18501851                                int start = trackModel.getSelectionStart();
     
    18591860                                ExpandedTrackManager.getInstance().expandSingleTrack(
    18601861                                                trackModel,
    1861                                                 _swingComponent.getBounds(),
     1862                                                SwingConversions.fromSwingRectangle(_swingComponent.getBounds()),
    18621863                                                trackMix,
    18631864                                                pfname,
     
    18821883         *
    18831884         */
    1884         private class PlaybackPopup extends PlaybackControlPopup implements Observer {
    1885 
    1886                 private static final long serialVersionUID = 1L;
    1887                
    1888                 public PlaybackPopup() {
     1885        private class PlaybackPopup extends PlaybackControlPopup implements Observer
     1886        {
     1887                public PlaybackPopup()
     1888                {
    18891889                        miscButton.setActionCommand("expand");
    1890                         miscButton.setIcon(IconRepository.getIcon("expand.png"));
     1890                        SwingMiscManager.setJButtonIcon(miscButton, IconRepository.getIcon("expand.png"));
    18911891                        miscButton.setToolTipText("Expand");
    1892 
    18931892                }
    18941893
    18951894                @Override
    1896                 public void onHide() {
    1897                         super.onHide();
    1898                        
     1895                public void onHide()
     1896                {
    18991897                        // Listen for volume or mute changed events
    19001898                        trackMix.removeObserver(this);
     
    19051903
    19061904                @Override
    1907                 public void onShow() {
    1908                         super.onShow();
     1905                public void onShow()
     1906                {
    19091907                        // Listen for volume or mute changed events
    19101908                        trackMix.addObserver(this);
     
    20162014                }
    20172015               
    2018                 public Subject getObservedSubject() {
     2016                public Subject getObservedSubject()
     2017                {
    20192018                        return null;
    20202019                }
    20212020
    2022                 public void setObservedSubject(Subject parent) {
     2021                public void setObservedSubject(Subject parent)
     2022                {
    20232023                }
    20242024
     
    20262026                 * Receives events from the track model OR from the observed track sequence.
    20272027                 */
    2028                 public void modelChanged(Subject source, SubjectChangedEvent event) {
    2029 
     2028                public void modelChanged(Subject source, SubjectChangedEvent event)
     2029                {
    20302030                        // Synch GUI with track state
    20312031                        switch (event.getID()) {
     
    20492049                                stopButton.setEnabled(true);
    20502050                                rewindButton.setEnabled(false);
    2051                                 playPauseButton.setIcon(IconRepository.getIcon("pause.png"));
     2051                                SwingMiscManager.setJButtonIcon(playPauseButton, IconRepository.getIcon("pause.png"));
    20522052                               
    20532053                                invalidateStateIcons();
     
    20632063                                rewindButton.setEnabled(true);
    20642064                                stopButton.setEnabled(false);
    2065                                 playPauseButton.setIcon(IconRepository.getIcon("play.png"));
     2065                                SwingMiscManager.setJButtonIcon(playPauseButton, IconRepository.getIcon("play.png"));
    20662066                               
    20672067                                // Note:
     
    21092109
    21102110                @Override
    2111                 protected void volumeChanged() {
     2111                protected void volumeChanged()
     2112                {
    21122113                        trackMix.setVolume(((float)volumeSlider.getValue()) / 100.0f);
    21132114                }
    21142115
    21152116                @Override
    2116                 protected void muteChanged() {
     2117                protected void muteChanged()
     2118                {
    21172119                        trackMix.setMuted(muteButton.isSelected());
    21182120                }
    21192121
    21202122                @Override
    2121                 protected void soloChanged() {
     2123                protected void soloChanged()
     2124                {
    21222125                        SoundDesk.getInstance().setSoloIDPrefix(soloButton.isSelected() ?
    21232126                                        trackMix.getChannelID() : null
    21242127                                        );
    21252128                }
    2126                
    21272129        }
    21282130
    21292131        @Override
    2130         public boolean isWidgetEdgeThicknessAdjustable() {
     2132        public boolean isWidgetEdgeThicknessAdjustable()
     2133        {
    21312134                return false;
    21322135        }
    2133        
    2134        
    2135        
    21362136}
  • trunk/src/org/apollo/widgets/SearchRecorder.java

    r355 r1102  
    3030import org.apollo.util.ApolloSystemLog;
    3131import org.expeditee.actions.Actions;
    32 import org.expeditee.gui.DisplayIO;
     32import org.expeditee.gio.swing.SwingMiscManager;
     33import org.expeditee.gui.DisplayController;
    3334import org.expeditee.gui.Frame;
    3435import org.expeditee.items.ItemParentStateChangedEvent;
    3536import org.expeditee.items.Text;
    36 import org.expeditee.items.widgets.InteractiveWidget;
    37 
    38 public class SearchRecorder extends InteractiveWidget
     37import org.expeditee.items.widgets.SwingWidget;
     38
     39public class SearchRecorder extends SwingWidget
    3940        implements ActionListener, Observer {
    4041       
     
    6869                // Create gui layout
    6970                recordButton = new JButton();
    70                 recordButton.setIcon(IconRepository.getIcon("searchmel.png"));
     71                SwingMiscManager.setJButtonIcon(recordButton, IconRepository.getIcon("searchmel.png"));
    7172                recordButton.setToolTipText("Search for audio from live recording");
    7273                recordButton.addActionListener(this);
     
    7475
    7576                commitButton = new JButton();
    76                 commitButton.setIcon(IconRepository.getIcon("commitquery.png"));
     77                SwingMiscManager.setJButtonIcon(commitButton, IconRepository.getIcon("commitquery.png"));
    7778                commitButton.addActionListener(this);
    7879                commitButton.setToolTipText("GO!");
     
    8283                cancelButton = new JButton();
    8384                cancelButton.setToolTipText("Cancel");
    84                 cancelButton.setIcon(IconRepository.getIcon("cancel.png"));
     85                SwingMiscManager.setJButtonIcon(cancelButton, IconRepository.getIcon("cancel.png"));
    8586                cancelButton.addActionListener(this);
    8687                cancelButton.setPreferredSize(new Dimension(BUTTON_SIZE, BUTTON_SIZE));
     
    384385                        if (hasExplicityStopped) {
    385386                               
    386                                 Frame sourceFrame = DisplayIO.getCurrentFrame();
     387                                Frame sourceFrame = DisplayController.getCurrentFrame();
    387388                               
    388389                                 if (sourceFrame != null &&
  • trunk/src/org/apollo/widgets/TrackWidgetCommons.java

    r315 r1102  
    11package org.apollo.widgets;
    22
    3 import java.awt.Color;
    4 import java.awt.Font;
     3import org.expeditee.core.Colour;
     4import org.expeditee.core.Font;
    55
    66public final class TrackWidgetCommons {
    7         private TrackWidgetCommons() {
     7       
     8        /** Static-only class. */
     9        private TrackWidgetCommons()
     10        {
    811        }
    912       
     
    1720        public static final int CACHE_DEPTH = 1;
    1821       
    19         public static final Color FREESPACE_TRACKNAME_TEXT_COLOR = Color.WHITE;
    20         public static final Font FREESPACE_TRACKNAME_FONT = new Font("Arial", Font.BOLD, 20);
     22        public static final Colour FREESPACE_TRACKNAME_TEXT_COLOR = Colour.WHITE;
     23        public static final Font FREESPACE_TRACKNAME_FONT = new Font("Arial", Font.Style.BOLD, 20);
    2124       
    2225        public static final int POPUP_LIFETIME = 1500;
    2326       
    24         public static final Color STANDARD_TRACK_EDGE_COLOR = Color.BLACK;
    25         public static final Color MUTED_TRACK_EDGE_COLOR = Color.GRAY;
    26         public static final Color SOLO_TRACK_EDGE_COLOR = Color.RED;
    27         public static final Color MUTED_SOLO_TRACK_EDGE_COLOR = new Color(255, 168, 168);
     27        public static final Colour STANDARD_TRACK_EDGE_COLOR = Colour.BLACK;
     28        public static final Colour MUTED_TRACK_EDGE_COLOR = Colour.GREY;
     29        public static final Colour SOLO_TRACK_EDGE_COLOR = Colour.RED;
     30        public static final Colour MUTED_SOLO_TRACK_EDGE_COLOR = Colour.FromRGB255(255, 168, 168);
    2831       
    2932        public static final float STOPPED_TRACK_EDGE_THICKNESS = 1.0f;
     
    3134       
    3235
    33         public static Color getBorderColor(boolean isSolo, boolean isMuted) {
     36        public static Colour getBorderColor(boolean isSolo, boolean isMuted) {
    3437               
    35                 Color newC = null;
     38                Colour newC = null;
    3639               
    3740                if (isSolo && isMuted) {
  • trunk/src/org/expeditee/actions/Actions.java

    r990 r1102  
    1919package org.expeditee.actions;
    2020
    21 import java.awt.GraphicsEnvironment;
    22 import java.io.Serializable;
    2321import java.lang.reflect.Constructor;
    2422import java.lang.reflect.Method;
     
    2624import java.rmi.UnexpectedException;
    2725import java.util.ArrayList;
    28 import java.util.Arrays;
    2926import java.util.Collection;
    3027import java.util.Comparator;
     
    3532
    3633import org.expeditee.agents.Agent;
    37 import org.expeditee.gui.DisplayIO;
     34import org.expeditee.gio.EcosystemManager;
     35import org.expeditee.gui.DisplayController;
    3836import org.expeditee.gui.Frame;
    39 import org.expeditee.gui.FrameGraphics;
    4037import org.expeditee.gui.FrameIO;
    4138import org.expeditee.gui.FrameUtils;
     
    217214         *         actions.
    218215         */
    219         public static Collection<String> Init() {
    220 
    221                 Collection<String> warnings = new LinkedList<String>();
     216        public static List<String> Init() {
     217
     218                List<String> warnings = new LinkedList<String>();
    222219                List<Class<?>> classes;
    223220
     
    436433                //      loose changes
    437434                if (firstCanditate.getDeclaringClass().getName().equals(NAVIGATIONS_CLASS)) {
    438                         FrameIO.SaveFrame(DisplayIO.getCurrentFrame());
     435                        FrameIO.SaveFrame(DisplayController.getCurrentFrame());
    439436                }
    440437                final List<Method> canditates = new LinkedList<Method>();
     
    825822                                        + nameWithCorrectCase + "'");
    826823                }
    827                 FrameGraphics.refresh(false);
     824                DisplayController.requestRefresh(false);
    828825        }
    829826
     
    10311028        private static void initFonts() {
    10321029                if (_Fonts.size() == 0) {
    1033                         String[] availableFonts = GraphicsEnvironment
    1034                                         .getLocalGraphicsEnvironment()
    1035                                         .getAvailableFontFamilyNames();
     1030                        String[] availableFonts = EcosystemManager.getFontManager().getRegisteredFontFamilies();
    10361031                        for (String s : availableFonts) {
    10371032                                _Fonts.put(s.toLowerCase(), s);
  • trunk/src/org/expeditee/actions/Debug.java

    r919 r1102  
    2121import java.util.List;
    2222
    23 import org.expeditee.gui.DisplayIO;
     23import org.expeditee.gui.DisplayController;
    2424import org.expeditee.items.Constraint;
    2525import org.expeditee.items.Item;
     
    3838         */
    3939        public static void ShowConstraints() {
    40                 List<Item> items = DisplayIO.getCurrentFrame().getItems();
     40                List<Item> items = DisplayController.getCurrentFrame().getItems();
    4141
    4242                for (Item i : items)
  • trunk/src/org/expeditee/actions/ExploratorySearchActions.java

    r919 r1102  
    1919package org.expeditee.actions;
    2020
     21import org.expeditee.core.Point;
     22import org.expeditee.gio.EcosystemManager;
     23import org.expeditee.gio.gesture.StandardGestureActions;
    2124import org.expeditee.gui.Browser;
    22 import org.expeditee.gui.DisplayIO;
     25import org.expeditee.gui.DisplayController;
    2326import org.expeditee.gui.Frame;
    2427import org.expeditee.gui.FrameIO;
    25 import org.expeditee.gui.FrameKeyboardActions;
    26 import org.expeditee.gui.FrameMouseActions;
    2728import org.expeditee.gui.FreeItems;
    2829import org.expeditee.items.Item;
     
    5960                        }
    6061                       
    61                         Text linkToBrowserSession = DisplayIO.getCurrentFrame().addText(FrameMouseActions.getX(), FrameMouseActions.getY(), " - Web Browser Session", null);
    62                         linkToBrowserSession.setParent(DisplayIO.getCurrentFrame());
    63                         FrameKeyboardActions.AddDate(linkToBrowserSession);
    64                         FrameMouseActions.pickup(linkToBrowserSession);
     62                        Text linkToBrowserSession = DisplayController.getCurrentFrame().addText(DisplayController.getMouseX(), DisplayController.getMouseY(), " - Web Browser Session", null);
     63                        linkToBrowserSession.setParent(DisplayController.getCurrentFrame());
     64                        Text.AddDate(linkToBrowserSession);
     65                        StandardGestureActions.pickup(linkToBrowserSession);
    6566                       
    6667                        // Create new frame
     
    7576                        // Add web browser active overlay and @old
    7677                        Text t = (Text) frame.addText(-150, 50, "@ao: 2", null, "overlayset2");
    77                         t.setAnchorRight(-100.0f);
    78                         t.setAnchorTop(50.0f);
     78                        t.setAnchorRight(-100);
     79                        t.setAnchorTop(50);
    7980                        t = (Text) frame.addText(-150, 50, "@old", null);
    8081                        t.setFamily("Roboto Condensed");
     
    8485                        t.setJustification(Justification.right);
    8586                        t.setLinkMark(false);
    86                         t.setAnchorLeft(9.0f);
    87                         t.setAnchorBottom(114.0f);
     87                        t.setAnchorLeft(9);
     88                        t.setAnchorBottom(114);
    8889                       
    8990                        Text wt;
     
    101102                                                + ("--anchorLeft " + (lm + ExploratorySearchSettings.BROWSER_HORZ_OFFSET) + " --anchorRight " + rm + " --anchorTop "
    102103                                                + (ExploratorySearchSettings.BROWSER_VERT_OFFSET + tm) + " --anchorBottom " + bm + " ")
    103                                                 + (Browser._theBrowser.getContentPane().getWidth() - ExploratorySearchSettings.BROWSER_HORZ_OFFSET - lm - rm) + " "
    104                                                 + (Browser._theBrowser.getContentPane().getHeight() - ExploratorySearchSettings.BROWSER_VERT_OFFSET - tm - bm) + " : " + url, null);
     104                                                + (EcosystemManager.getGraphicsManager().getWindowSize().getWidth() - ExploratorySearchSettings.BROWSER_HORZ_OFFSET - lm - rm) + " "
     105                                                + (EcosystemManager.getGraphicsManager().getWindowSize().getHeight() - ExploratorySearchSettings.BROWSER_VERT_OFFSET - tm - bm) + " : " + url, null);
    105106                        } else {
    106107                                wt = frame.addText(ExploratorySearchSettings.BROWSER_HORZ_OFFSET + lm, ExploratorySearchSettings.BROWSER_VERT_OFFSET + tm,
     
    122123                // Replace any text item on cursor with link to a new mindmap
    123124                FreeItems.getInstance().clear();
    124                 Text text = DisplayIO.getCurrentFrame().addText(FrameMouseActions.getX(), FrameMouseActions.getY(), " - Mindmap Session", null);
    125                 text.setParent(DisplayIO.getCurrentFrame());
    126                 FrameKeyboardActions.AddDate(text);
    127                 FrameMouseActions.pickup(text);
     125                Point cursorPos = DisplayController.getMousePosition();
     126                Text text = DisplayController.getCurrentFrame().addText(cursorPos.getX(), cursorPos.getY(), " - Mindmap Session", null);
     127                text.setParent(DisplayController.getCurrentFrame());
     128                Text.AddDate(text);
     129                StandardGestureActions.pickup(text);
    128130                Frame frame = FrameIO.CreateNewFrame(text);
    129131                text.setLink("" + frame.getNumber());
     
    132134                frame.removeAllItems(frame.getItems());
    133135                Text t = (Text) frame.addText(-150, 50, "@ao: 2", null, "overlayset3");
    134                 t.setAnchorLeft(-150.0f);
    135                 t.setAnchorTop(50.0f);
     136                t.setAnchorLeft(-150);
     137                t.setAnchorTop(50);
    136138                t = (Text) frame.addText(-150, 50, "@old", null);
    137139                t.setFamily("Roboto Condensed");
     
    141143                t.setJustification(Justification.right);
    142144                t.setLinkMark(false);
    143                 t.setAnchorLeft(9.0f);
    144                 t.setAnchorBottom(114.0f);
     145                t.setAnchorLeft(9);
     146                t.setAnchorBottom(114);
    145147               
    146148                FrameIO.SaveFrame(frame);
     
    168170                        }
    169171                       
    170                         Text linkToBrowserSession = DisplayIO.getCurrentFrame().addText(FrameMouseActions.getX(), FrameMouseActions.getY(), url, null);
    171                         linkToBrowserSession.setParent(DisplayIO.getCurrentFrame());
    172                         FrameMouseActions.pickup(linkToBrowserSession);
     172                        Point cursorPos = DisplayController.getMousePosition();
     173                        Text linkToBrowserSession = DisplayController.getCurrentFrame().addText(cursorPos.getX(), cursorPos.getY(), url, null);
     174                        linkToBrowserSession.setParent(DisplayController.getCurrentFrame());
     175                        StandardGestureActions.pickup(linkToBrowserSession);
    173176                       
    174177                        // Create new frame
     
    183186                        // Add web browser active overlay and @old
    184187                        Text t = (Text) frame.addText(-150, 50, "@ao: 2", null, "overlayset2");
    185                         t.setAnchorLeft(-150.0f);
    186                         t.setAnchorTop(50.0f);
     188                        t.setAnchorLeft(-150);
     189                        t.setAnchorTop(50);
    187190                        t = (Text) frame.addText(-150, 50, "@old", null);
    188191                        t.setFamily("Roboto Condensed");
     
    192195                        t.setJustification(Justification.right);
    193196                        t.setLinkMark(false);
    194                         t.setAnchorLeft(9.0f);
    195                         t.setAnchorBottom(114.0f);
     197                        t.setAnchorLeft(9);
     198                        t.setAnchorBottom(114);
    196199                       
    197200                        Text wt;
     
    209212                                                + ("--anchorLeft " + (lm + ExploratorySearchSettings.BROWSER_HORZ_OFFSET) + " --anchorRight " + rm + " --anchorTop "
    210213                                                + (ExploratorySearchSettings.BROWSER_VERT_OFFSET + tm) + " --anchorBottom " + bm + " ")
    211                                                 + (Browser._theBrowser.getContentPane().getWidth() - ExploratorySearchSettings.BROWSER_HORZ_OFFSET - lm - rm) + " "
    212                                                 + (Browser._theBrowser.getContentPane().getHeight() - ExploratorySearchSettings.BROWSER_VERT_OFFSET - tm - bm) + " : " + url, null);
     214                                                + (EcosystemManager.getGraphicsManager().getWindowSize().getWidth() - ExploratorySearchSettings.BROWSER_HORZ_OFFSET - lm - rm) + " "
     215                                                + (EcosystemManager.getGraphicsManager().getWindowSize().getHeight() - ExploratorySearchSettings.BROWSER_VERT_OFFSET - tm - bm) + " : " + url, null);
    213216                        } else {
    214217                                wt = frame.addText(ExploratorySearchSettings.BROWSER_HORZ_OFFSET + lm, ExploratorySearchSettings.BROWSER_VERT_OFFSET + tm,
  • trunk/src/org/expeditee/actions/GreenstoneActions.java

    r919 r1102  
    1919package org.expeditee.actions;
    2020
    21 import java.awt.Color;
    2221import java.lang.reflect.InvocationTargetException;
    2322import java.lang.reflect.Method;
     
    2524
    2625import org.expeditee.agents.SearchGreenstone;
     26import org.expeditee.core.Colour;
    2727import org.expeditee.greenstone.ResultDocument;
    2828import org.expeditee.gui.AttributeValuePair;
     
    134134                        }
    135135                }
    136                 MessageBay.displayMessage("Feedback complete", null, Color.green
     136                MessageBay.displayMessage("Feedback complete", null, Colour.GREEN
    137137                                .darker(), true, null);
    138138        }
  • trunk/src/org/expeditee/actions/Help.java

    r919 r1102  
    2525import java.util.List;
    2626
    27 import org.expeditee.gui.DisplayIO;
     27import org.expeditee.gio.EcosystemManager;
     28import org.expeditee.gui.DisplayController;
    2829import org.expeditee.gui.Frame;
    29 import org.expeditee.gui.FrameMouseActions;
    3030import org.expeditee.items.Item;
    3131import org.expeditee.items.Text;
     
    7777                });
    7878
    79                 Frame current = DisplayIO.getCurrentFrame();
    80                 float x = FrameMouseActions.MouseX;
    81                 float y = FrameMouseActions.MouseY;
     79                Frame current = DisplayController.getCurrentFrame();
     80                float x = DisplayController.getFloatMouseX();
     81                float y = DisplayController.getFloatMouseY();
    8282
    8383                // Do case sensitive comparison
  • trunk/src/org/expeditee/actions/IDE.java

    r919 r1102  
    1919package org.expeditee.actions;
    2020
    21 import java.awt.Color;
    22 import java.io.BufferedReader;
    2321import java.io.File;
    24 import java.io.InputStreamReader;
    2522
    2623import org.expeditee.agents.WriteTree;
    27 import org.expeditee.gui.DisplayIO;
     24import org.expeditee.core.Colour;
     25import org.expeditee.gui.DisplayController;
    2826import org.expeditee.gui.Frame;
    2927import org.expeditee.gui.FrameIO;
     
    3735                int exitVal = 0; // default's to status OK
    3836               
    39                 Frame source = DisplayIO.getCurrentFrame();
     37                Frame source = DisplayController.getCurrentFrame();
    4038                String title = source.getTitleItem().getText();
    4139                String[] tokens = title.split("\\s+");
     
    7270                                }
    7371                                else {
    74                                         MessageBay.displayMessage("Compiled " + fileName, Color.darkGray);
     72                                        MessageBay.displayMessage("Compiled " + fileName, Colour.DARK_GREY);
    7573                                }
    7674                        } catch (Exception e) {
     
    10199       
    102100        public static void RunClass() {
    103                 Frame source = DisplayIO.getCurrentFrame();
     101                Frame source = DisplayController.getCurrentFrame();
    104102                String className = getClassName(source);
    105103                try {
  • trunk/src/org/expeditee/actions/Javascript.java

    r919 r1102  
    1919package org.expeditee.actions;
    2020
    21 import java.awt.Color;
    2221import java.util.LinkedList;
    2322import java.util.List;
     
    2625import org.expeditee.agents.Agent;
    2726import org.expeditee.agents.DefaultAgent;
    28 import org.expeditee.gui.DisplayIO;
     27import org.expeditee.core.Colour;
     28import org.expeditee.gui.DisplayController;
    2929import org.expeditee.gui.Frame;
    30 import org.expeditee.gui.FrameGraphics;
    3130import org.expeditee.gui.FrameIO;
    3231import org.expeditee.gui.MessageBay;
     
    7574        private static int _stepPause = -1;
    7675
    77         private static Color _stepColor;
     76        private static Colour _stepColor;
    7877
    7978        private static boolean _nextStatement;
     
    9392        //Have changed parameters, so it takes an Item, not just a Text item.
    9493        private static void RunJavascriptFrame(Frame frame, Item current,
    95                         boolean acceptKeyboardInput, boolean step, int pause, Color color) {
     94                        boolean acceptKeyboardInput, boolean step, int pause, Colour color) {
    9695                try {
    9796                        if (current != null) {
     
    101100                                 */
    102101                                // DisplayIO.addToBack(current.getParent());
    103                                 DisplayIO.addToBack(DisplayIO.getCurrentFrame());
     102                                DisplayController.addToBack(DisplayController.getCurrentFrame());
    104103                        } else {
    105104                                /* TODO we should not have to pass an item just to run a frame! */
     
    108107                        }
    109108
    110                         _stepColor = color == null ? Color.green : color;
    111                         _stepColor = new Color(_stepColor.getRed(), _stepColor.getGreen(),
    112                                         _stepColor.getBlue(), 50);
     109                        _stepColor = color == null ? Colour.GREEN : color;
     110                        _stepColor = new Colour(_stepColor.getRed(), _stepColor.getGreen(),
     111                                        _stepColor.getBlue(), Colour.FromComponent255(50));
    113112                        _stepPause = pause;
    114113                        _step = step;
     
    168167                FrameUtils.DisplayFrame(item.getParent().getName(), true, true);
    169168                item.setHighlightMode(HighlightMode.Normal);
    170                 item.setHighlightColor(Color.CYAN);
     169                item.setHighlightColor(Colour.CYAN);
    171170                FrameIO.SaveFrame(item.getParent());
    172171        }
     
    192191
    193192                if (_step) {
    194                         if (child != DisplayIO.getCurrentFrame()) {
    195                                 DisplayIO.setCurrentFrame(child, true);
    196                         }
    197                         DisplayIO.addToBack(child);
     193                        if (child != DisplayController.getCurrentFrame()) {
     194                                DisplayController.setCurrentFrame(child, true);
     195                        }
     196                        DisplayController.addToBack(child);
    198197                }
    199198
     
    216215                        AgentStats.ItemExecuted();
    217216                        try {
    218                                 Color oldColor = item.getBackgroundColor();
     217                                Colour oldColor = item.getBackgroundColor();
    219218                                if (_step) {
    220219                                        pause(item);
     
    226225                                        } else {
    227226                                                item.setHighlightMode(Item.HighlightMode.None);
     227                                                item.setHighlightColorToDefault();
    228228                                        }
    229229                                }
     
    233233                                                        && lastItemStatus != Status.FalseIf) {
    234234                                                if (_step) {
    235                                                         DisplayIO.removeFromBack();
     235                                                        DisplayController.removeFromBack();
    236236                                                }
    237237                                                return lastItemStatus;
     
    257257
    258258                if (_step) {
    259                         DisplayIO.removeFromBack();
    260                         if (DisplayIO.getCurrentFrame() != current.getParent())
    261                                 DisplayIO.setCurrentFrame(current.getParent(), true);
     259                        DisplayController.removeFromBack();
     260                        if (DisplayController.getCurrentFrame() != current.getParent())
     261                                DisplayController.setCurrentFrame(current.getParent(), true);
    262262                }
    263263
     
    276276                        return;
    277277
    278                 Color oldColor = item.getBackgroundColor();
     278                Colour oldColor = item.getBackgroundColor();
    279279                item.setBackgroundColor(_stepColor);
    280280                item.setHighlightMode(Item.HighlightMode.None);
     281                item.setHighlightColorToDefault();
    281282
    282283                // Make sure we are on the frame with this item
    283284                Frame parent = item.getParentOrCurrentFrame();
    284                 if (!parent.equals(DisplayIO.getCurrentFrame())) {
    285                         DisplayIO.setCurrentFrame(parent, true);
    286                 }
    287 
    288                 FrameGraphics.Repaint();
     285                if (!parent.equals(DisplayController.getCurrentFrame())) {
     286                        DisplayController.setCurrentFrame(parent, true);
     287                }
     288
     289                DisplayController.requestRefresh(true);
    289290
    290291                int timeRemaining;
     
    297298                        if (_stop) {
    298299                                item.setBackgroundColor(oldColor);
    299                                 item.setHighlightMode(HighlightMode.Normal, _stepColor);
     300                                item.setHighlightModeAndColour(HighlightMode.Normal, _stepColor);
    300301                                throw new Exception("Program terminated");
    301302                        }
     
    388389                _programsRunning++;
    389390                AgentStats.reset();
    390                 MessageBay.displayMessage("Running Javascript Program ...", Color.BLUE);
     391                MessageBay.displayMessage("Running Javascript Program ...", Colour.BLUE);
    391392        }
    392393
  • trunk/src/org/expeditee/actions/Javascript2.java

    r1080 r1102  
    1919package org.expeditee.actions;
    2020
    21 import java.awt.Color;
    22 import java.util.Collection;
    23 import java.util.LinkedList;
    24 import java.util.List;
    25 
    26 import javax.script.Bindings;
    2721import javax.script.Invocable;
    28 import javax.script.ScriptContext;
    29 import javax.script.ScriptEngine;
    30 import javax.script.ScriptEngineManager;
    31 import javax.script.ScriptException;
    32 import javax.script.SimpleScriptContext;
    3322
    3423import org.expeditee.gui.Frame;
    35 import org.expeditee.gui.FrameIO;
    36 import org.expeditee.gui.FrameUtils;
    3724import org.expeditee.gui.MessageBay;
    38 import org.expeditee.io.flowlayout.XGroupItem;
    3925import org.expeditee.items.Item;
    40 import org.expeditee.items.ItemUtils;
    41 import org.expeditee.items.Text;
    4226
    4327/**
  • trunk/src/org/expeditee/actions/JfxBrowserActions.java

    r919 r1102  
    2222import java.io.InputStreamReader;
    2323import java.net.HttpURLConnection;
    24 import java.net.MalformedURLException;
    25 import java.net.URI;
    26 import java.net.URISyntaxException;
    2724import java.net.URL;
    2825import java.net.URLEncoder;
    2926import java.util.ArrayList;
    3027
    31 import org.expeditee.gui.Browser;
    32 import org.expeditee.gui.DisplayIO;
     28import org.expeditee.gio.EcosystemManager;
     29import org.expeditee.gio.gesture.StandardGestureActions;
     30import org.expeditee.gui.DisplayController;
    3331import org.expeditee.gui.Frame;
    34 import org.expeditee.gui.FrameGraphics;
    3532import org.expeditee.gui.FrameIO;
    36 import org.expeditee.gui.FrameMouseActions;
    3733import org.expeditee.gui.FrameUtils;
    3834import org.expeditee.gui.FreeItems;
     
    4238import org.expeditee.items.Picture;
    4339import org.expeditee.items.Text;
    44 import org.expeditee.items.widgets.InteractiveWidget;
     40import org.expeditee.items.widgets.Widget;
    4541import org.expeditee.items.widgets.JfxBrowser;
    46 import org.expeditee.settings.exploratorysearch.ExploratorySearchSettings;
    4742import org.expeditee.settings.network.NetworkSettings;
    4843import org.json.simple.JSONObject;
     
    8378                FreeItems.getInstance().clear();                                        // remove url text from cursor
    8479               
    85                 wt.setParent(DisplayIO.getCurrentFrame());                      // set parent of text source for InteractiveWidget.createWidget()
    86                 wt.setXY(FrameMouseActions.getX(), FrameMouseActions.getY());
     80                wt.setParent(DisplayController.getCurrentFrame());                      // set parent of text source for InteractiveWidget.createWidget()
     81                wt.setXY(DisplayController.getMouseX(), DisplayController.getMouseY());
    8782               
    8883                // create widget from text item
    89                 JfxBrowser browser = (JfxBrowser) InteractiveWidget.createWidget(wt);
     84                JfxBrowser browser = (JfxBrowser) Widget.createWidget(wt);
    9085                       
    91                 FrameMouseActions.pickup(browser.getItems());           // attach browser widget to mouse
     86                StandardGestureActions.pickup(browser.getItems());              // attach browser widget to mouse
    9287        }
    9388       
     
    109104                // If no text with url is passed to action create a new text item with http://www.waikato.ac.nz for a default url
    110105                if(!FreeItems.textOnlyAttachedToCursor()) {
    111                         text = DisplayIO.getCurrentFrame().addText(FrameMouseActions.getX(), FrameMouseActions.getY(),
     106                        text = DisplayController.getCurrentFrame().addText(DisplayController.getMouseX(), DisplayController.getMouseY(),
    112107                                        NetworkSettings.HomePage.get(), null);
    113                         text.setParent(DisplayIO.getCurrentFrame());    // set parent of text source for InteractiveWidget.createWidget()
    114                         FrameMouseActions.pickup(text);                                 // Attach new text link to cursor
     108                        text.setParent(DisplayController.getCurrentFrame());    // set parent of text source for InteractiveWidget.createWidget()
     109                        StandardGestureActions.pickup(text);                                    // Attach new text link to cursor
    115110                }
    116111               
     
    123118                Text wt = frame.addText(0, 0, "@iw: org.expeditee.items.widgets.JfxBrowser "
    124119                                + ("--anchorLeft 0 --anchorRight 0 --anchorTop 0 --anchorBottom 0 ")
    125                                 + Browser._theBrowser.getContentPane().getWidth() +  " " + Browser._theBrowser.getContentPane().getHeight()
     120                                + EcosystemManager.getGraphicsManager().getWindowSize().getWidth() +  " " + EcosystemManager.getGraphicsManager().getWindowSize().getHeight()
    126121                                + " : " + text.getText(), null);
    127122               
    128                 InteractiveWidget.createWidget(wt);
     123                Widget.createWidget(wt);
    129124               
    130125                FrameIO.SaveFrame(frame);                                                       // save frame to disk
     
    179174
    180175                // Create widget via text annotation
    181                 frame.addText(10, 10, "@iw: org.expeditee.items.widgets.JfxBrowser " + (int) (FrameGraphics.getMaxFrameSize().getWidth() * 0.9) + " "
    182                                 + (int) (FrameGraphics.getMaxFrameSize().getHeight() * 0.9) + " : " + url, null);
     176                frame.addText(10, 10, "@iw: org.expeditee.items.widgets.JfxBrowser " + (int) (DisplayController.getFramePaintArea().getWidth() * 0.9) + " "
     177                                + (int) (DisplayController.getFramePaintArea().getHeight() * 0.9) + " : " + url, null);
    183178
    184179                FrameIO.SaveFrame(frame);
     
    294289
    295290                                        if (!picSource.equals("")) {
    296                                                 pic = WebParser.getImageFromUrl(picSource, null, DisplayIO.getCurrentFrame(), 0, 0, 50, null, null,
     291                                                pic = WebParser.getImageFromUrl(picSource, null, DisplayController.getCurrentFrame(), 0, 0, 50, null, null,
    297292                                                                null, null, null, 0, 0);
    298293                                                items.add(pic);
     
    300295                                        }
    301296
    302                                         titleItem.setPosition(FrameMouseActions.getPosition());
     297                                        titleItem.setPosition(DisplayController.getMousePosition());
    303298                                        mainTextItem.setPosition(titleItem.getX(), titleItem.getY() + titleItem.getBoundsHeight());
    304299                                        sourceItem.setPosition(mainTextItem.getX(), mainTextItem.getY() + mainTextItem.getBoundsHeight());
     
    313308                                        items.add(sourceItem);
    314309                                        items.add(ddgLink);
    315                                         FrameMouseActions.pickup(items);
     310                                        StandardGestureActions.pickup(items);
    316311                                } catch (IOException e) {
    317312                                        MessageBay.displayMessage("Problem loading results");
  • trunk/src/org/expeditee/actions/Mail.java

    r919 r1102  
    1919package org.expeditee.actions;
    2020
    21 import java.awt.Color;
    2221import java.util.Collection;
    2322
     
    2524
    2625import org.expeditee.agents.mail.MailSession;
     26import org.expeditee.core.Colour;
     27import org.expeditee.gio.EcosystemManager;
     28import org.expeditee.gio.gesture.StandardGestureActions;
    2729import org.expeditee.gui.AttributeValuePair;
    28 import org.expeditee.gui.DisplayIO;
     30import org.expeditee.gui.DisplayController;
    2931import org.expeditee.gui.Frame;
    30 import org.expeditee.gui.FrameKeyboardActions;
    31 import org.expeditee.gui.FrameMouseActions;
    3232import org.expeditee.gui.MessageBay;
    3333import org.expeditee.items.Item;
     
    116116        public static Text getMailByID(int messageNo) {
    117117                Text mailItem = MailSession.getInstance().getMail(
    118                                 DisplayIO.getCurrentFrame(), FrameMouseActions.getPosition(),
     118                                DisplayController.getCurrentFrame(), DisplayController.getMousePosition(),
    119119                                messageNo - 1);
    120120                // MessageBay.displayMessage(mailItems.size() + " messages read",
     
    139139                        int noOfMessages) {
    140140                Collection<Text> mailItems = MailSession.getInstance().getMail(flag,
    141                                 isPresent, DisplayIO.getCurrentFrame(),
    142                                 FrameMouseActions.getPosition(), noOfMessages);
     141                                isPresent, DisplayController.getCurrentFrame(),
     142                                DisplayController.getMousePosition(), noOfMessages);
    143143                // MessageBay.displayMessage(mailItems.size() + " messages read",
    144144                // Color.green);
     
    187187
    188188                reply.setActions(null);
    189                 FrameMouseActions.tdfc(reply);
    190 
    191                 Frame replyFrame = DisplayIO.getCurrentFrame();
     189                StandardGestureActions.tdfc(reply);
     190
     191                Frame replyFrame = DisplayController.getCurrentFrame();
    192192                String titleText = frame.getTitle();
    193193                // Add Re on the end if it is not already there
     
    197197                }
    198198                replyFrame.setTitle(titleText);
    199                 FrameKeyboardActions.Drop(null, false);
     199                StandardGestureActions.Drop(null, false);
    200200
    201201                // Add a link to the original message
    202202                Text original = replyFrame.createNewText("@original");
    203                 original.setPosition(FrameMouseActions.getPosition());
     203                original.setPosition(DisplayController.getMousePosition());
    204204                original.setLink(frame.getName());
    205                 FrameKeyboardActions.Drop(original, false);
     205                StandardGestureActions.Drop(original, false);
    206206
    207207                Text to = replyFrame.createNewText("@to: " + fromAddress);
    208                 to.setPosition(FrameMouseActions.getPosition());
     208                to.setPosition(DisplayController.getMousePosition());
    209209                to.addAction("MailTree");
    210                 FrameKeyboardActions.Drop(to, false);
    211                 DisplayIO.setCursorPosition(FrameMouseActions.MouseX,
    212                                 FrameMouseActions.MouseY + 15);
     210                StandardGestureActions.Drop(to, false);
     211                DisplayController.setCursorPosition(DisplayController.getMouseX(), DisplayController.getMouseY() + 15);
    213212        }
    214213
     
    216215                if (FrameShare.getInstance().sendMessage(message, peerName)) {
    217216                        MessageBay.displayMessage("Sent message to " + peerName,
    218                                         Color.green.darker());
     217                                        Colour.GREEN.darker());
    219218                } else {
    220219                        MessageBay.errorMessage("Could not find " + peerName);
  • trunk/src/org/expeditee/actions/Misc.java

    r1079 r1102  
    1919package org.expeditee.actions;
    2020
    21 import java.awt.Color;
    22 import java.awt.Desktop;
    23 import java.awt.Image;
    24 import java.awt.image.BufferedImage;
    25 import java.awt.image.VolatileImage;
    2621import java.io.BufferedReader;
    2722import java.io.File;
     
    3126import java.io.InputStreamReader;
    3227import java.lang.reflect.Method;
    33 import java.net.URI;
    34 import java.net.URISyntaxException;
    3528import java.net.URL;
    3629import java.net.URLClassLoader;
     
    3932import java.util.LinkedList;
    4033import java.util.List;
    41 import java.util.Map;
    4234import java.util.Map.Entry;
    43 import java.util.Set;
    4435import java.util.jar.Attributes;
    4536import java.util.jar.JarFile;
    4637
    47 import javax.imageio.ImageIO;
    48 
     38import org.expeditee.core.Colour;
     39import org.expeditee.core.Image;
     40import org.expeditee.core.Point;
     41import org.expeditee.gio.EcosystemManager;
     42import org.expeditee.gio.gesture.StandardGestureActions;
    4943import org.expeditee.gui.AttributeUtils;
    50 import org.expeditee.gui.Browser;
    5144import org.expeditee.io.Conversion;
    52 import org.expeditee.gui.DisplayIO;
     45import org.expeditee.gui.DisplayController;
    5346import org.expeditee.io.ExpReader;
    5447import org.expeditee.gui.Frame;
    5548import org.expeditee.gui.FrameGraphics;
    5649import org.expeditee.gui.FrameIO;
    57 import org.expeditee.gui.FrameKeyboardActions;
    58 import org.expeditee.gui.FrameMouseActions;
    5950import org.expeditee.gui.FrameUtils;
    6051import org.expeditee.gui.FreeItems;
     
    6354import org.expeditee.gui.Reminders;
    6455import org.expeditee.gui.TimeKeeper;
    65 import org.expeditee.importer.FrameDNDTransferHandler;
    6656import org.expeditee.items.Item;
    6757import org.expeditee.items.ItemUtils;
     
    6959import org.expeditee.items.Text;
    7060import org.expeditee.items.XRayable;
    71 import org.expeditee.items.widgets.InteractiveWidget;
     61import org.expeditee.items.widgets.Widget;
    7262import org.expeditee.items.widgets.WidgetCorner;
    7363import org.expeditee.items.widgets.WidgetEdge;
     
    8373import org.nfunk.jep.ParseException;
    8474
    85 import com.lowagie.text.Font;
    86 
    8775
    8876
    8977/**
    90  * A list of miscellaneous Actions and Actions specific to Expeditee
     78 * A list of miscellaneous Actions specific to Expeditee
    9179 *
    9280 */
     
    9684         * Causes the system to beep
    9785         */
    98         public static void beep() {
    99                 java.awt.Toolkit.getDefaultToolkit().beep();
     86        public static void beep()
     87        {
     88                EcosystemManager.getMiscManager().beep();
    10089        }
    10190       
     
    161150         * Treats a string as a URL and attempts to open it
    162151         */
    163         public static void openURL(String siteURL){
    164                
    165                 try {
    166                         URL check = new URL(siteURL);                   
    167                         Desktop.getDesktop().browse(new URI(siteURL));
    168                        
    169                 } catch (IOException| URISyntaxException e) {
    170                
    171                         MessageBay.displayMessage("'" + siteURL + "' is not a valid URL");
    172                 }               
     152        public static void openURL(String siteURL)
     153        {
     154                boolean success = EcosystemManager.getMiscManager().browse(siteURL);
     155               
     156                if (!success) MessageBay.displayMessage("'" + siteURL + "' is not a valid URL");       
    173157        }
    174158        /**
     
    177161        public static void setRestorePoint()
    178162        {
    179                 Frame current = DisplayIO.getCurrentFrame();
     163                Frame current = DisplayController.getCurrentFrame();
    180164                current.change();
    181165                FrameIO.SaveFrameAsRestore(current, true, true);               
     
    185169         */
    186170        public static void display() {
    187                 FrameGraphics.refresh(false);
     171                DisplayController.requestRefresh(false);
    188172        }
    189173       
    190174        public static String getWindowSize() {
    191                 return Browser.getWindows()[0].getSize().toString();
     175                return EcosystemManager.getGraphicsManager().getWindowSize().toString();
    192176        }
    193177
     
    205189         */
    206190        public static void toggleAudienceMode() {
    207                 FrameGraphics.ToggleAudienceMode();
     191                DisplayController.ToggleAudienceMode();
    208192        }
    209193
     
    212196         */
    213197        public static void toggleTwinFramesMode() {
    214                 DisplayIO.ToggleTwinFrames();
     198                DisplayController.toggleTwinFrames();
    215199        }
    216200
     
    227211                        for (String action : actions) {
    228212                                if (!action.equalsIgnoreCase("runitem")) {
    229                                         Actions.PerformAction(DisplayIO.getCurrentFrame(), current,
     213                                        Actions.PerformAction(DisplayController.getCurrentFrame(), current,
    230214                                                        action);
    231215                                }
     
    249233                        String deletedFrameName = FrameIO.DeleteFrame(toDelete);
    250234                        if (deletedFrameName != null) {
    251                                 DisplayIO.Back();
     235                                DisplayController.Back();
    252236                                // Remove any links on the previous frame to the one being
    253237                                // deleted
    254                                 Frame current = DisplayIO.getCurrentFrame();
     238                                Frame current = DisplayController.getCurrentFrame();
    255239                                for (Item i : current.getItems())
    256240                                        if (i.getLink() != null
     
    312296                        // copy the item and switch
    313297                        item = item.copy();
    314                         item.setPosition(DisplayIO.getMouseX(), FrameMouseActions.getY());
     298                        item.setPosition(DisplayController.getMousePosition());
    315299                }
    316300                return item;
     
    327311                Collection<Item> copies = ItemUtils.CopyItems(items);
    328312                Item first = items.iterator().next();
    329                 float deltaX = DisplayIO.getMouseX() - first.getX();
    330                 float deltaY = FrameMouseActions.getY() - first.getY();
     313                float deltaX = DisplayController.getMouseX() - first.getX();
     314                float deltaY = DisplayController.getMouseY() - first.getY();
    331315                for (Item i : copies) {
    332316                        if (i.isVisible())
     
    334318                        i.setParent(null);
    335319                }
    336                 FrameMouseActions.pickup(copies);
    337                 FrameGraphics.Repaint();
     320                StandardGestureActions.pickup(copies);
     321                DisplayController.requestRefresh(true);
    338322        }
    339323       
     
    347331         *            The Color to give the Item.
    348332         */
    349         public static void SetItemBackgroundColor(Item toChange, Color toUse) {
     333        public static void SetItemBackgroundColor(Item toChange, Colour toUse) {
    350334                if (toChange == null)
    351335                        return;
    352336
    353337                toChange.setBackgroundColor(toUse);
    354                 FrameGraphics.Repaint();
     338                DisplayController.requestRefresh(true);
    355339        }
    356340
     
    364348         *            The Color to give the Item.
    365349         */
    366         public static void SetItemColor(Item toChange, Color toUse) {
     350        public static void SetItemColor(Item toChange, Colour toUse) {
    367351                if (toChange == null)
    368352                        return;
    369353
    370354                toChange.setColor(toUse);
    371                 FrameGraphics.Repaint();
     355                DisplayController.requestRefresh(true);
    372356        }
    373357
     
    428412        public static void attachStatsToCursor(String itemText) {
    429413                SessionStats.CreatedText();
    430                 Frame current = DisplayIO.getCurrentFrame();
     414                Frame current = DisplayController.getCurrentFrame();
    431415                Item text = current.getStatsTextItem(itemText);
    432                 FrameMouseActions.pickup(text);
    433                 FrameGraphics.Repaint();
     416                StandardGestureActions.pickup(text);
     417                DisplayController.requestRefresh(true);
    434418        }
    435419
    436420        public static void attachTextToCursor(String itemText) {
    437421                SessionStats.CreatedText();
    438                 Frame current = DisplayIO.getCurrentFrame();
     422                Frame current = DisplayController.getCurrentFrame();
    439423                Item text = current.getTextItem(itemText);
    440                 FrameMouseActions.pickup(text);
    441                 FrameGraphics.Repaint();
     424                StandardGestureActions.pickup(text);
     425                DisplayController.requestRefresh(true);
    442426        }
    443427       
     
    494478                }
    495479
    496                 for (Entry<String, java.awt.Font> entry: Text.FONT_WHEEL_ADDITIONAL_LOOKUP.entrySet()){
     480                for (Entry<String, org.expeditee.core.Font> entry: Text.FONT_WHEEL_ADDITIONAL_LOOKUP.entrySet()){
    497481                       
    498482                        String fontName = entry.getKey();
     
    585569         */
    586570        public static void jpegFrame() {
    587                 ImageFrame(DisplayIO.getCurrentFrame().getName(), "JPEG");
     571                ImageFrame(DisplayController.getCurrentFrame().getName(), "JPEG");
    588572        }
    589573
     
    610594        }
    611595
    612         public static String SaveImage(BufferedImage screen, String format,
     596        public static String SaveImage(Image screen, String format,
    613597                        String directory, String fileName) {
    614598                String suffix = "." + format.toLowerCase();
     
    633617
    634618                        // If the image is successfully written out return the fileName
    635                         if (ImageIO.write(screen, format, out))
     619                        if (screen.writeToDisk(format, out))
    636620                                return fileName;
    637621
     
    647631                Image oldBuffer = frame.getBuffer();
    648632                frame.setBuffer(null);
    649                 // Jpeg only works properly with volitile frames
     633                // Jpeg only works properly with volatile frames
    650634                // Png transparency only works with bufferedImage form
    651                 Image frameBuffer = FrameGraphics.getBuffer(frame, false, format
    652                                 .equalsIgnoreCase("jpeg"));
    653                 // Make sure overlay stuff doesnt disapear on the frame visible on the
     635                Image frameBuffer = FrameGraphics.getFrameImage(frame, null, null, false, format.equalsIgnoreCase("jpeg"));
     636                // Make sure overlay stuff doesnt disappear on the frame visible on the
    654637                // screen
    655638                frame.setBuffer(oldBuffer);
    656                 BufferedImage screen = null;
    657 
    658                 if (frameBuffer instanceof VolatileImage) {
    659                         // If its the current frame it will be a volitive image
    660                         screen = ((VolatileImage) frameBuffer).getSnapshot();
    661                 } else {
    662                         assert (frameBuffer instanceof BufferedImage);
    663                         screen = (BufferedImage) frameBuffer;
    664                 }
    665                 return SaveImage(screen, format, directory, frame.getExportFileName());
     639               
     640                return SaveImage(frameBuffer, format, directory, frame.getExportFileName());
    666641        }
    667642
     
    842817                current.setActions(null);
    843818
    844                 FrameGraphics.Repaint();
     819                DisplayController.requestRefresh(true);
    845820        }
    846821
     
    932907                                text.setFormula(formulaFullCase);
    933908                                if (text.isFloating()) {
    934                                         text.setPosition(FrameMouseActions.MouseX,
    935                                                         FrameMouseActions.MouseY);
    936                                         FrameMouseActions.resetOffset();
     909                                        Point cursorPos = EcosystemManager.getInputManager().getCursorPosition();
     910                                        text.setPosition(cursorPos.x, cursorPos.y);
     911                                        StandardGestureActions.resetOffset();
    937912                                } else {
    938913                                        text.getParentOrCurrentFrame().change();
     
    956931        public static void attachToCursor(Item item) {
    957932                item.setParent(null);
    958                 FrameMouseActions.pickup(item);
    959                 FrameGraphics.Repaint();
     933                StandardGestureActions.pickup(item);
     934                DisplayController.requestRefresh(true);
    960935        }
    961936
     
    965940                        i.invalidateAll();
    966941                }
    967                 FrameMouseActions.pickup(items);
     942                StandardGestureActions.pickup(items);
    968943                // TODO figure out why this isnt repainting stuff immediately
    969944                // All of text item doesnt repaint until the cursor is moved
    970                 FrameGraphics.requestRefresh(true);
     945                DisplayController.requestRefresh(true);
    971946        }
    972947
     
    980955                }
    981956                try {
    982                         FrameDNDTransferHandler.getInstance().importFileList(files,
    983                                         FrameMouseActions.getPosition());
     957                        EcosystemManager.getDragAndDropManager().importFileList(files, EcosystemManager.getInputManager().getCursorPosition());
    984958                } catch (Exception e) {
    985959                }
     
    990964                if (file.exists()) {
    991965                        try {
    992                                 FrameDNDTransferHandler.getInstance().importFile(file,
    993                                                 FrameMouseActions.getPosition());
     966                                EcosystemManager.getDragAndDropManager().importFile(file, EcosystemManager.getInputManager().getCursorPosition());
    994967                        } catch (Exception e) {
    995968                                e.printStackTrace();
     
    1021994                }
    1022995
    1023                 float curX = FrameMouseActions.MouseX;
    1024                 float curY = FrameMouseActions.MouseY;
     996                Point cursorPos = DisplayController.getMousePosition();
     997                float curX = cursorPos.x;
     998                float curY = cursorPos.y;
    1025999
    10261000                Collection<Item> newItems = new LinkedList<Item>();
    10271001                Item[] d = new Item[sides];
    10281002                // create dots
    1029                 Frame current = DisplayIO.getCurrentFrame();
     1003                Frame current = DisplayController.getCurrentFrame();
    10301004                for (int i = 0; i < d.length; i++) {
    10311005                        d[i] = current.createDot();
     
    10531027                }
    10541028
    1055                 Color newColor = item.getColor();
     1029                Colour newColor = item.getColor();
    10561030                if (newColor != null) {
    10571031                        d[0].setColor(item.getColor());
     
    10681042
    10691043                ItemUtils.EnclosedCheck(newItems);
    1070                 FrameGraphics.refresh(false);
     1044                DisplayController.requestRefresh(false);
    10711045
    10721046                return d[0];
     
    10771051        }
    10781052
    1079         public static void print(String file) {
    1080                 try {
    1081                         if (Browser._theBrowser.isMinimumVersion6()) {
    1082                                 if (Desktop.isDesktopSupported()) {
    1083                                         Desktop.getDesktop().print(new File(file));
    1084                                 }
    1085                         }
    1086                 } catch (Exception e) {
    1087                         MessageBay.errorMessage("Printing error: " + e.getMessage());
    1088                 }
     1053        public static void print(String file)
     1054        {       
     1055                String errorMessage = EcosystemManager.getMiscManager().print(file);
     1056               
     1057                if (errorMessage != null) MessageBay.errorMessage("Printing error: " + errorMessage);
    10891058        }
    10901059
     
    11291098         * @throws Exception
    11301099         */
    1131         public static void startLoboBrowser(Item text) throws Exception {
     1100/*      public static void startLoboBrowser(Item text) throws Exception {
    11321101                if (!(text instanceof Text)) {
    11331102                        MessageBay.errorMessage("Must be a text item.");
     
    11541123                       
    11551124                FrameMouseActions.pickup(browser.getItems());                                   // attach browser widget to mouse
    1156         }
     1125        }*/
    11571126       
    11581127        /**
     
    11611130         * @throws Exception
    11621131         */
    1163         public static void startLoboBrowserNewFrame(Item text) throws Exception {
     1132        public static void startLoboBrowserNewFrame(Item text) throws Exception
     1133        {
    11641134                if (!(text instanceof Text)) {
    11651135                        MessageBay.errorMessage("Must be a text item.");
    11661136                        return;
    11671137                }
     1138               
    11681139                if(text.getLink() != null) {                                                                                    // text item can't already have a link
    11691140                        MessageBay.errorMessage("Text item already has link.");
     
    11761147                FrameUtils.Parse(frame);
    11771148               
    1178                 for(InteractiveWidget iw : frame.getInteractiveWidgets()) {     // may be other widgets on frame
     1149                for(Widget iw : frame.getInteractiveWidgets()) {        // may be other widgets on frame
    11791150                        if(iw instanceof org.expeditee.items.widgets.Browser) {
    11801151                                // Set browser to 'full screen'
    1181                                 iw.setSize(-1, -1, -1, -1, Browser._theBrowser.getWidth(), Browser._theBrowser.getHeight()
    1182                                                 - MessageBay.MESSAGE_BUFFER_HEIGHT - 80);
     1152                                iw.setSize(-1, -1, -1, -1, DisplayController.getFramePaintArea().getWidth(), DisplayController.getFramePaintArea().getHeight() - 80);
    11831153                               
    11841154                                // If there is a text item attached to cursor use it as url for browser
    1185                                 if(FreeItems.textOnlyAttachedToCursor()) {
     1155                                if (FreeItems.textOnlyAttachedToCursor()) {
    11861156                                        text.setLink("" + frame.getNumber());
    11871157                                        ((org.expeditee.items.widgets.Browser)iw).navigate(text.getText());
     
    11901160                                        ((org.expeditee.items.widgets.Browser)iw).navigate("http://www.waikato.ac.nz");
    11911161                                        Text t = new Text("http://www.waikato.ac.nz");
    1192                                         t.setParent(DisplayIO.getCurrentFrame());               // set parent of text source for InteractiveWidget.createWidget()
    1193                                         t.setXY(FrameMouseActions.getX(), FrameMouseActions.getY());
     1162                                        t.setParent(DisplayController.getCurrentFrame());               // set parent of text source for InteractiveWidget.createWidget()
     1163                                        t.setXY(DisplayController.getFloatMouseX(), DisplayController.getFloatMouseY());
    11941164                                        t.setLink("" + frame.getNumber());                              // link url text to new browser frame
    1195                                         FrameMouseActions.pickup(t);                                    // Attach new text link to cursor
     1165                                        StandardGestureActions.pickup(t);                                       // Attach new text link to cursor
    11961166                                }
    11971167                        }
     
    12011171        }
    12021172       
    1203         private static boolean startWidget(String name) throws Exception {
     1173        private static boolean startWidget(String name) throws Exception
     1174        {
    12041175                String fullName = Actions.getClassName(name);
    12051176                if(fullName == null) {
     
    12101181                FreeItems.getInstance().clear();
    12111182                Text wt = new Text("@iw:" + fullName);                                                  // create new text item for browser widget
    1212                 wt.setParent(DisplayIO.getCurrentFrame());                                              // set parent of text source for InteractiveWidget.createWidget()
    1213                 wt.setXY(FrameMouseActions.getX(), FrameMouseActions.getY());   // move to the mouse cursor
    1214                 InteractiveWidget widget = InteractiveWidget.createWidget(wt);
    1215                 FrameMouseActions.pickup(widget.getItems());
     1183                wt.setParent(DisplayController.getCurrentFrame());                                              // set parent of text source for InteractiveWidget.createWidget()
     1184                wt.setXY(DisplayController.getMouseX(), DisplayController.getMouseY()); // move to the mouse cursor
     1185                Widget widget = Widget.createWidget(wt);
     1186                StandardGestureActions.pickup(widget.getItems());
    12161187               
    12171188                return true;
     
    12231194                }
    12241195               
    1225                 Actions.PerformAction(DisplayIO.getCurrentFrame(), null, command);
     1196                Actions.PerformAction(DisplayController.getCurrentFrame(), null, command);
    12261197        }
    12271198       
     
    12411212                if(name == "action" || name == "agent") {
    12421213                        if(args.length() > 0) {
    1243                                 Actions.PerformAction(DisplayIO.getCurrentFrame(), null, args);
     1214                                Actions.PerformAction(DisplayController.getCurrentFrame(), null, args);
    12441215                        } else {
    12451216                                MessageBay.displayMessage("Please specify an action/agent name");
     
    13241295                        if (i instanceof WidgetEdge || i instanceof WidgetCorner) {
    13251296                                continue;
    1326                         }
    1327                         else {
     1297                        } else {
    13281298                                int new_x = i.getX();
    13291299                                int new_y = i.getY();
     
    13451315                        }
    13461316                        // update the polygon, otherwise stuff moves but leaves it's outline behind
    1347                         i.updatePolygon();
    1348                 }
    1349 
    1350                 for (InteractiveWidget iw : frame.getInteractiveWidgets()) {
     1317                        i.invalidateBounds();
     1318                }
     1319
     1320                for (Widget iw : frame.getInteractiveWidgets()) {
    13511321
    13521322                        int new_x = iw.getX();
     
    13681338                frame.change();
    13691339                // redraw everything
    1370                 FrameKeyboardActions.Refresh();
     1340                StandardGestureActions.Refresh();
    13711341        }
    13721342       
     
    15051475    public static void GitPushFrame() {
    15061476
    1507         FrameKeyboardActions.Save();
    1508        
    1509         Frame current = DisplayIO.getCurrentFrame();
     1477        StandardGestureActions.Save();
     1478       
     1479        Frame current = DisplayController.getCurrentFrame();
    15101480        String userName = UserSettings.ProfileName.get();
    15111481
     
    15441514
    15451515    public static void GitPullFrame() {
    1546         Frame current = DisplayIO.getCurrentFrame();
     1516        Frame current = DisplayController.getCurrentFrame();
    15471517
    15481518        List<String> cmd_array = new ArrayList<String>();
     
    15541524       
    15551525        FrameIO.Reload();
    1556         FrameKeyboardActions.Refresh();
     1526        StandardGestureActions.Refresh();
    15571527    }
    15581528
  • trunk/src/org/expeditee/actions/Navigation.java

    r1032 r1102  
    2121import java.util.List;
    2222
    23 import org.expeditee.gui.DisplayIO;
     23import org.expeditee.gui.DisplayController;
    2424import org.expeditee.gui.Frame;
    2525import org.expeditee.gui.FrameIO;
     
    4949         */
    5050        public static void Back() {
    51                 DisplayIO.Back();
     51                DisplayController.Back();
    5252        }
    5353
    5454        public static void Forward() {
    55                 DisplayIO.Forward();
     55                DisplayController.Forward();
    5656        }
    5757
     
    7878        public static void GotoZero() {
    7979                FrameUtils
    80                                 .DisplayFrame(DisplayIO.getCurrentFrame().getFramesetName() + 0);
     80                                .DisplayFrame(DisplayController.getCurrentFrame().getFramesetName() + 0);
    8181        }
    8282
     
    9696         */
    9797        public static void Goto(Integer value) {
    98                 FrameUtils.DisplayFrame(DisplayIO.getCurrentFrame().getFramesetName()
     98                FrameUtils.DisplayFrame(DisplayController.getCurrentFrame().getFramesetName()
    9999                                + value);
    100100        }
     
    132132         */
    133133        public static void Large() {
    134                 if (DisplayIO.isTwinFramesOn())
    135                         DisplayIO.ToggleTwinFrames();
     134                if (DisplayController.isTwinFramesOn())
     135                        DisplayController.toggleTwinFrames();
    136136        }
    137137
     
    188188
    189189        public static void NextChild(Frame source) {
    190                 String back = DisplayIO.peekFromBackUpStack();
     190                String back = DisplayController.peekFromBackUpStack();
    191191                // if there is no parent frame (i.e. the user is on the home frame) //
    192192                if (back == null) { // No frame was on the Backup stack
     
    259259        // better to say more explicitly/directly what the mode is!!!!
    260260        public static void Small() {
    261                 if (!DisplayIO.isTwinFramesOn())
    262                         DisplayIO.ToggleTwinFrames();
     261                if (!DisplayController.isTwinFramesOn())
     262                        DisplayController.toggleTwinFrames();
    263263        }
    264264
  • trunk/src/org/expeditee/actions/Python.java

    r1080 r1102  
    1919package org.expeditee.actions;
    2020
    21 import java.awt.Color;
    22 import java.util.Collection;
    23 import java.util.LinkedList;
    2421import java.util.List;
    2522
    26 import javax.script.Bindings;
    2723import javax.script.Invocable;
    28 import javax.script.ScriptContext;
    29 import javax.script.ScriptEngine;
    30 import javax.script.ScriptEngineManager;
    31 import javax.script.ScriptException;
    32 import javax.script.SimpleScriptContext;
    3324
    3425import org.expeditee.gui.Frame;
    35 import org.expeditee.gui.FrameIO;
    36 import org.expeditee.gui.FrameUtils;
    3726import org.expeditee.gui.MessageBay;
    38 import org.expeditee.io.flowlayout.XGroupItem;
    3927import org.expeditee.items.Item;
    40 import org.expeditee.items.ItemUtils;
    4128import org.expeditee.items.Text;
    4229
  • trunk/src/org/expeditee/actions/ScriptBase.java

    r1080 r1102  
    1919package org.expeditee.actions;
    2020
    21 import java.awt.Color;
    2221import java.util.Collection;
    2322import java.util.LinkedList;
     
    3231import javax.script.SimpleScriptContext;
    3332
     33import org.expeditee.core.Colour;
    3434import org.expeditee.gui.Frame;
    3535import org.expeditee.gui.FrameIO;
     
    235235        Text errorItem;
    236236        errorItem = errorFrame.addText(x, y, errorItemLines[cl.line], null);
    237         errorItem.setBackgroundColor(Color.RED);
     237        errorItem.setBackgroundColor(Colour.RED);
    238238        for(String line : message.split("[\\n\\r]+")) {
    239239            errorItem.setTooltip("text: " + line);
  • trunk/src/org/expeditee/actions/Simple.java

    r947 r1102  
    1919package org.expeditee.actions;
    2020
    21 import java.awt.Color;
    22 import java.awt.Point;
    23 import java.awt.event.InputEvent;
    24 import java.awt.geom.Point2D;
     21//import java.awt.event.InputEvent;
    2522import java.io.BufferedReader;
    2623import java.io.InputStreamReader;
     
    4744import org.expeditee.agents.SearchTree;
    4845import org.expeditee.agents.WriteTree;
     46import org.expeditee.core.Colour;
     47import org.expeditee.core.Point;
     48import org.expeditee.gio.gesture.StandardGestureActions;
    4949import org.expeditee.gui.AttributeUtils;
    5050import org.expeditee.gui.AttributeValuePair;
    5151import org.expeditee.gui.Browser;
    52 import org.expeditee.gui.DisplayIO;
     52import org.expeditee.gui.DisplayController;
    5353import org.expeditee.gui.Frame;
    54 import org.expeditee.gui.FrameGraphics;
    5554import org.expeditee.gui.FrameIO;
    56 import org.expeditee.gui.FrameMouseActions;
    5755import org.expeditee.gui.FrameUtils;
    5856import org.expeditee.gui.FreeItems;
     
    156154        private static int _stepPause = -1;
    157155
    158         private static Color _stepColor;
     156        private static Colour _stepColor;
    159157
    160158        private static boolean _nextStatement;
     
    173171
    174172        public static void NewSimpleTest() {
    175                 Frame newSimpleTest = FrameIO.CreateFrame(DisplayIO.getCurrentFrame()
     173                Frame newSimpleTest = FrameIO.CreateFrame(DisplayController.getCurrentFrame()
    176174                                .getFramesetName(), "Test", null);
    177175                List<String> actions = new ArrayList<String>();
     
    183181
    184182        public static void NextTest() {
    185                 Frame next = DisplayIO.getCurrentFrame();
     183                Frame next = DisplayController.getCurrentFrame();
    186184                do {
    187185                        next = FrameIO.LoadNext(next);
     
    191189
    192190        public static void PreviousTest() {
    193                 Frame prev = DisplayIO.getCurrentFrame();
     191                Frame prev = DisplayController.getCurrentFrame();
    194192                do {
    195193                        prev = FrameIO.LoadPrevious(prev);
     
    240238                int testsFailed = 0;
    241239
    242                 FrameIO.SaveFrame(DisplayIO.getCurrentFrame(), false);
     240                FrameIO.SaveFrame(DisplayController.getCurrentFrame(), false);
    243241                MessageBay.displayMessage("Starting test suite: " + _frameset,
    244                                 Color.CYAN);
     242                                Colour.CYAN);
    245243
    246244                // Get the next number in the inf file for the _frameset
     
    312310                // Report the number of test passed and failed
    313311                MessageBay.displayMessage(
    314                                 "Total tests: " + (testsPassed + testsFailed), Color.CYAN);
     312                                "Total tests: " + (testsPassed + testsFailed), Colour.CYAN);
    315313                if (testsPassed > 0)
    316314                        MessageBay.displayMessage("Passed: " + testsPassed, Item.GREEN);
    317315                if (testsFailed > 0)
    318                         MessageBay.displayMessage("Failed: " + testsFailed, Color.RED);
     316                        MessageBay.displayMessage("Failed: " + testsFailed, Colour.RED);
    319317                // Remove items from the cursor...
    320318                FreeItems.getInstance().clear();
     
    350348        //Have changed parameters, so it takes an Item, not just a Text item.
    351349        private static void RunFrame(Frame frame, Item current,
    352                         boolean acceptKeyboardInput, boolean step, int pause, Color color) {
     350                        boolean acceptKeyboardInput, boolean step, int pause, Colour color) {
    353351                try {
    354352                        if (current != null) {
     
    358356                                 */
    359357                                // DisplayIO.addToBack(current.getParent());
    360                                 DisplayIO.addToBack(DisplayIO.getCurrentFrame());
     358                                DisplayController.addToBack(DisplayController.getCurrentFrame());
    361359                        } else {
    362360                                /* TODO we should not have to pass an item just to run a frame! */
     
    365363                        }
    366364
    367                         _stepColor = color == null ? Color.green : color;
    368                         _stepColor = new Color(_stepColor.getRed(), _stepColor.getGreen(),
    369                                         _stepColor.getBlue(), 50);
     365                        _stepColor = color == null ? Colour.GREEN : color;
     366                        _stepColor = new Colour(_stepColor.getRed(), _stepColor.getGreen(),
     367                                        _stepColor.getBlue(), Colour.FromComponent255(50));
    370368                        _stepPause = pause;
    371369                        _step = step;
     
    429427         */
    430428        public static void DebugFrame(Frame frame, Text current, float pause,
    431                         Color color) {
     429                        Colour color) {
    432430                if (isProgramRunning()) {
    433431                        stop();
     
    454452                FrameUtils.DisplayFrame(item.getParent().getName(), true, true);
    455453                item.setHighlightMode(HighlightMode.Normal);
    456                 item.setHighlightColor(Color.CYAN);
     454                item.setHighlightColor(Colour.CYAN);
    457455                FrameIO.SaveFrame(item.getParent());
    458456        }
     
    499497
    500498                if (_step) {
    501                         if (child != DisplayIO.getCurrentFrame()) {
    502                                 DisplayIO.setCurrentFrame(child, true);
    503                         }
    504                         DisplayIO.addToBack(child);
     499                        if (child != DisplayController.getCurrentFrame()) {
     500                                DisplayController.setCurrentFrame(child, true);
     501                        }
     502                        DisplayController.addToBack(child);
    505503                }
    506504
     
    524522                        AgentStats.ItemExecuted();
    525523                        try {
    526                                 Color oldColor = item.getBackgroundColor();
     524                                Colour oldColor = item.getBackgroundColor();
    527525                                if (_step) {
    528526                                        pause(item);
     
    534532                                        } else {
    535533                                                item.setHighlightMode(Item.HighlightMode.None);
     534                                                item.setHighlightColorToDefault();
    536535                                        }
    537536                                }
     
    541540                                                        && lastItemStatus != Status.FalseIf) {
    542541                                                if (_step) {
    543                                                         DisplayIO.removeFromBack();
     542                                                        DisplayController.removeFromBack();
    544543                                                }
    545544                                                return lastItemStatus;
     
    565564
    566565                if (_step) {
    567                         DisplayIO.removeFromBack();
    568                         if (DisplayIO.getCurrentFrame() != current.getParent())
    569                                 DisplayIO.setCurrentFrame(current.getParent(), true);
     566                        DisplayController.removeFromBack();
     567                        if (DisplayController.getCurrentFrame() != current.getParent())
     568                                DisplayController.setCurrentFrame(current.getParent(), true);
    570569                }
    571570
     
    583582                        return;
    584583
    585                 Color oldColor = item.getBackgroundColor();
     584                Colour oldColor = item.getBackgroundColor();
    586585                item.setBackgroundColor(_stepColor);
    587586                item.setHighlightMode(Item.HighlightMode.None);
     587                item.setHighlightColorToDefault();
    588588
    589589                // Make sure we are on the frame with this item
    590590                Frame parent = item.getParentOrCurrentFrame();
    591                 if (!parent.equals(DisplayIO.getCurrentFrame())) {
    592                         DisplayIO.setCurrentFrame(parent, true);
     591                if (!parent.equals(DisplayController.getCurrentFrame())) {
     592                        DisplayController.setCurrentFrame(parent, true);
    593593                }
    594594
    595                 FrameGraphics.Repaint();
     595                DisplayController.requestRefresh(true);
    596596
    597597                int timeRemaining;
     
    604604                        if (_stop) {
    605605                                item.setBackgroundColor(oldColor);
    606                                 item.setHighlightMode(HighlightMode.Normal, _stepColor);
     606                                item.setHighlightModeAndColour(HighlightMode.Normal, _stepColor);
    607607                                throw new Exception("Program terminated");
    608608                        }
     
    11251125                                // attribute without the value in the same item
    11261126                                if (!found && attributeItem != null) {
    1127                                         Point2D.Float endPoint = attributeItem
    1128                                                         .getParagraphEndPosition();
     1127                                        Point endPoint = attributeItem.getParagraphEndPosition();
    11291128
    11301129                                        for (Text text : targetFrame.getTextItems()) {
     
    12171216                                        String stringColor = context.getPrimitives().getVariable(
    12181217                                                        tokens[2]).stringValue();
    1219                                         item.setBackgroundColor((Color) Conversion.Convert(
    1220                                                         Color.class, stringColor));
     1218                                        item.setBackgroundColor((Colour) Conversion.Convert(
     1219                                                        Colour.class, stringColor));
    12211220                                } else if (tokens[0].equals("setitemcolor")) {
    12221221                                        assertVariableType(tokens[1], 1, SPointer.itemPrefix);
     
    12261225                                        String stringColor = context.getPrimitives().getVariable(
    12271226                                                        tokens[2]).stringValue();
    1228                                         item.setColor((Color) Conversion.Convert(Color.class,
     1227                                        item.setColor((Colour) Conversion.Convert(Colour.class,
    12291228                                                        stringColor, item.getColor()));
    12301229                                       
     
    13771376                                        // attribute without the value in the same item
    13781377                                        if (!found && attributeItem != null) {
    1379                                                 Point2D.Float endPoint = attributeItem
    1380                                                                 .getParagraphEndPosition();
     1378                                                Point endPoint = attributeItem.getParagraphEndPosition();
    13811379
    13821380                                                for (Text text : targetFrame.getTextItems()) {
     
    14841482                                        assertVariableType(tokens[1], 1, SPointer.framePrefix);
    14851483
    1486                                         Frame currentFrame = DisplayIO.getCurrentFrame();
     1484                                        Frame currentFrame = DisplayController.getCurrentFrame();
    14871485                                        context.getPointers().setObject(tokens[1], currentFrame);
    14881486
     
    15041502                                                        && tokens.length > 2) {
    15051503                                                Text text = (Text) currentItem;
    1506                                                 int cursorLinePos = text
    1507                                                                 .getLinePosition(FrameMouseActions.getY());
     1504                                                int cursorLinePos = text.getLinePosition(DisplayController.getMouseY());
    15081505                                                context.getPrimitives().setValue(tokens[2],
    15091506                                                                new SInteger(cursorLinePos + 1));
    15101507                                                if (tokens.length > 3) {
    15111508                                                        int cursorCharPos = text.getCharPosition(
    1512                                                                         cursorLinePos, DisplayIO.getMouseX())
     1509                                                                        cursorLinePos, DisplayController.getMouseX())
    15131510                                                                        .getCharIndex();
    15141511                                                        context.getPrimitives().setValue(tokens[3],
     
    15321529                   
    15331530                    //no frame specified by user so use current frame.
    1534                     getFrameName = DisplayIO.getCurrentFrame().getName();
     1531                    getFrameName = DisplayController.getCurrentFrame().getName();
    15351532                    getItem = Misc.getItemContainingData(data, FrameUtils.getFrame(getFrameName));
    15361533                }
     
    15691566                                               
    15701567                                                //no frame specified by user so use current frame.
    1571                                                 getFrameName = DisplayIO.getCurrentFrame().getName();
     1568                                                getFrameName = DisplayController.getCurrentFrame().getName();
    15721569                                                getItem = Misc.getItemAtPosition(x, y, FrameUtils.getFrame(getFrameName));
    15731570                                        }
     
    16621659                                        assertVariableType(tokens[1], 1, SPointer.itemPrefix);
    16631660                                        // assertPrimitiveType(tokens[2], 2);
    1664                                         Color itemColor = ((Item) context.getPointers()
     1661                                        Colour itemColor = ((Item) context.getPointers()
    16651662                                                        .getVariable(tokens[1]).getValue())
    16661663                                                        .getPaintBackgroundColor();
     
    16721669                                        assertVariableType(tokens[1], 1, SPointer.itemPrefix);
    16731670                                        // assertPrimitiveType(tokens[2], 2);
    1674                                         Color itemColor = ((Item) context.getPointers()
     1671                                        Colour itemColor = ((Item) context.getPointers()
    16751672                                                        .getVariable(tokens[1]).getValue()).getPaintColor();
    16761673                                        String color = itemColor.getRed() + " "
     
    18341831                        double delay = context.getPrimitives().getDoubleValue(tokens[1]);
    18351832                        String s = getMessage(tokens, context, code.toString(), " ", 2);
    1836                         DisplayIO.typeStringDirect(delay, s);
     1833                        DisplayController.typeStringDirect(delay, s);
    18371834                } else if (tokens[0].equals("type") || tokens[0].equals("typenospaces")) {
    18381835
     
    18401837                                        .equals("type") ? " " : "", 1);
    18411838
    1842                         DisplayIO.typeStringDirect(0.025, s);
     1839                        DisplayController.typeStringDirect(0.025, s);
    18431840                } else if (tokens[0].equals("runstring")) {
    18441841                        String codeText = getMessage(tokens, context, code.toString(), " ",
     
    18581855                                // Process p = Runtime.getRuntime().exec(new String[]{"date",
    18591856                                // ">", "test.date"});
    1860                                 MessageBay.displayMessage(command, Color.darkGray);
     1857                                MessageBay.displayMessage(command, Colour.DARK_GREY);
    18611858
    18621859                                BufferedReader stdInput = new BufferedReader(
     
    20282025                        Item item = (Item) context.getPointers().getVariable(itemVar)
    20292026                                        .getValue();
    2030                         item
    2031                                         .setPosition(FrameMouseActions.MouseX,
    2032                                                         FrameMouseActions.MouseY);
    2033                         FrameMouseActions.pickup(item);
     2027                        item.setPosition(DisplayController.getMouseX(), DisplayController.getMouseY());
     2028                        StandardGestureActions.pickup(item);
    20342029                } else if (tokens[0].equals("attachstrtocursor")) {
    20352030                        String stringVar = DEFAULT_STRING;
     
    20402035                        }
    20412036                        String s = context.getPrimitives().getStringValue(stringVar);
    2042                         Frame frame = DisplayIO.getCurrentFrame();
     2037                        Frame frame = DisplayController.getCurrentFrame();
    20432038                        Item item = frame.createNewText(s);
    2044                         item
    2045                                         .setPosition(FrameMouseActions.MouseX,
    2046                                                         FrameMouseActions.MouseY);
    2047                         FrameMouseActions.pickup(item);
     2039                        item.setPosition(DisplayController.getMouseX(), DisplayController.getMouseY());
     2040                        StandardGestureActions.pickup(item);
    20482041                } else if (tokens[0].equals("additemtoframe")) {
    20492042                        String itemVar = DEFAULT_ITEM;
     
    24102403                                                }
    24112404                                        }
    2412                                         DisplayIO.setCurrentFrame(frame, false);
     2405                                        DisplayController.setCurrentFrame(frame, false);
    24132406                                        pause(thisFramesPause);
    24142407
     
    26292622                                                tokens[3]) * 1000);
    26302623
    2631                         int initialX = DisplayIO.getMouseX();
    2632                         int initialY = FrameMouseActions.getY();
     2624                        int initialX = DisplayController.getMouseX();
     2625                        int initialY = DisplayController.getMouseY();
    26332626
    26342627                        final int timeInterval = 40;
     
    26432636                                Thread.yield();
    26442637                                Thread.sleep(timeInterval);
    2645                                 DisplayIO.setCursorPosition(newX, newY);
     2638                                DisplayController.setCursorPosition(newX, newY);
    26462639                                // DisplayIO.repaint();
    26472640                        }
    26482641                        // Thread.yield();
    26492642                        Thread.sleep(milliseconds % timeInterval);
    2650                         DisplayIO.setCursorPosition(finalX, finalY);
     2643                        DisplayController.setCursorPosition(finalX, finalY);
    26512644                } else if (tokens[0].equals("glideitemto")) {
    26522645                        assertMinParametreCount(tokens, 3);
     
    26862679
    26872680                                item.setPosition(newX, newY);
    2688                                 FrameGraphics.Repaint();
     2681                                DisplayController.requestRefresh(true);
    26892682                        }
    26902683                        // Thread.yield();
     
    26922685                        item.setPosition(finalX, finalY);
    26932686                        // DisplayIO.setCursorPosition(finalX, finalY);
    2694                         FrameMouseActions.anchor(item);
     2687                        StandardGestureActions.anchor(item);
    26952688                        FreeItems.getInstance().clear();
    2696                         FrameGraphics.Repaint();
     2689                        DisplayController.requestRefresh(true);
    26972690                        // FrameMouseActions.updateCursor();
    26982691                }
     
    27402733                } else if (tokens[0].equals("pressleftbutton")) {
    27412734                        assertExactParametreCount(tokens, 0);
    2742                         DisplayIO.pressMouse(InputEvent.BUTTON1_MASK);
     2735                        //DisplayIO.pressMouse(InputEvent.BUTTON1_MASK); TODO: Reinstate. cts16
    27432736                } else if (tokens[0].equals("pressmiddlebutton")) {
    27442737                        assertExactParametreCount(tokens, 0);
    2745                         DisplayIO.pressMouse(InputEvent.BUTTON2_MASK);
     2738                        //DisplayIO.pressMouse(InputEvent.BUTTON2_MASK); TODO: Reinstate. cts16
    27462739                } else if (tokens[0].equals("pressrightbutton")) {
    27472740                        assertExactParametreCount(tokens, 0);
    2748                         DisplayIO.pressMouse(InputEvent.BUTTON3_MASK);
     2741                        //DisplayIO.pressMouse(InputEvent.BUTTON3_MASK); TODO: Reinstate. cts16
    27492742                } else if (tokens[0].equals("releaseleftbutton")) {
    27502743                        assertExactParametreCount(tokens, 0);
    2751                         DisplayIO.releaseMouse(InputEvent.BUTTON1_MASK);
     2744                        //DisplayIO.releaseMouse(InputEvent.BUTTON1_MASK); TODO: Reinstate. cts16
    27522745                } else if (tokens[0].equals("releasemiddlebutton")) {
    27532746                        assertExactParametreCount(tokens, 0);
    2754                         DisplayIO.releaseMouse(InputEvent.BUTTON2_MASK);
     2747                        //DisplayIO.releaseMouse(InputEvent.BUTTON2_MASK); TODO: Reinstate. cts16
    27552748                } else if (tokens[0].equals("releaserightbutton")) {
    27562749                        assertExactParametreCount(tokens, 0);
    2757                         DisplayIO.releaseMouse(InputEvent.BUTTON3_MASK);
     2750                        //DisplayIO.releaseMouse(InputEvent.BUTTON3_MASK); TODO: Reinstate. cts16
    27582751                } else if (tokens[0].equals("clickleftbutton")) {
    27592752                        assertExactParametreCount(tokens, 0);
    2760                         FrameMouseActions.leftButton();
     2753                        // FrameMouseActions.leftButton(); TODO: Reinstate. cts16
    27612754                        // DisplayIO.clickMouse(InputEvent.BUTTON1_MASK);
    27622755                } else if (tokens[0].equals("clickmiddlebutton")) {
    27632756                        assertExactParametreCount(tokens, 0);
    2764                         FrameMouseActions.middleButton();
     2757                        // FrameMouseActions.middleButton(); TODO: Reinstate. cts16
    27652758                        // DisplayIO.clickMouse(InputEvent.BUTTON2_MASK);
    27662759                } else if (tokens[0].equals("clickrightbutton")) {
    27672760                        assertExactParametreCount(tokens, 0);
    2768                         FrameMouseActions.rightButton();
     2761                        // FrameMouseActions.rightButton(); TODO: Reinstate. cts16
    27692762                        // DisplayIO.clickMouse(InputEvent.BUTTON3_MASK);
    27702763                } else if (tokens[0].equals("repaint")) {
    27712764                        assertExactParametreCount(tokens, 0);
    27722765                        // FrameGraphics.Repaint();
    2773                         FrameGraphics.requestRefresh(true);
     2766                        DisplayController.requestRefresh(true);
    27742767                } else if (tokens[0].equals("add")) {
    27752768                        assertMaxParametreCount(tokens, 3);
     
    29312924                        int x = (int) context.getPrimitives().getIntegerValue(tokens[1]);
    29322925                        int y = (int) context.getPrimitives().getIntegerValue(tokens[2]);
    2933                         DisplayIO.setCursorPosition(x, y);
     2926                        DisplayController.setCursorPosition(x, y);
    29342927                       
    29352928                       
     
    29812974
    29822975                if (source == null)
    2983                         source = DisplayIO.getCurrentFrame();
     2976                        source = DisplayController.getCurrentFrame();
    29842977                int lastParam = tokens.length - 1;
    29852978                String resultVarName = null;
     
    31023095                _programsRunning++;
    31033096                AgentStats.reset();
    3104                 MessageBay.displayMessage("Running SimpleProgram...", Color.BLUE);
     3097                MessageBay.displayMessage("Running SimpleProgram...", Colour.BLUE);
    31053098        }
    31063099
  • trunk/src/org/expeditee/agents/DefaultAgent.java

    r919 r1102  
    1919package org.expeditee.agents;
    2020
     21import org.expeditee.gui.DisplayController;
    2122import org.expeditee.gui.Frame;
    22 import org.expeditee.gui.FrameGraphics;
    2323import org.expeditee.gui.MessageBay;
    2424import org.expeditee.gui.TimeKeeper;
     
    128128                AGENTS_RUNNING--;
    129129
    130                 FrameGraphics.requestRefresh(true);
     130                DisplayController.requestRefresh(true);
    131131                SessionStats.setEnabled(true);
    132132        }
  • trunk/src/org/expeditee/agents/DisplayComet.java

    r919 r1102  
    2323import java.util.Stack;
    2424
    25 import org.expeditee.gui.DisplayIO;
     25import org.expeditee.gui.DisplayController;
    2626import org.expeditee.gui.Frame;
    2727import org.expeditee.gui.FrameIO;
     
    4545                Collection<String> seen = new HashSet<String>();
    4646
    47                 DisplayIO.addToBack(frame);
     47                DisplayController.addToBack(frame);
    4848
    4949                // Goto the end of the comet
     
    7474                        if (_stop)
    7575                                return null;
    76                         DisplayIO.setCurrentFrame(_frameList.pop(), true);
     76                        DisplayController.setCurrentFrame(_frameList.pop(), true);
    7777                        _frameCount++;
    7878                        pause(_delay);
  • trunk/src/org/expeditee/agents/DisplayTree.java

    r919 r1102  
    1919package org.expeditee.agents;
    2020
    21 import org.expeditee.gui.DisplayIO;
     21import org.expeditee.gui.DisplayController;
    2222import org.expeditee.gui.Frame;
    2323import org.expeditee.gui.MessageBay;
     
    5454
    5555                // push current frame on to back-stack
    56                 DisplayIO.addToBack(start);
     56                DisplayController.addToBack(start);
    5757
    5858                return super.initialise(start, launcher);
     
    6363                // return the user to the Frame they started on
    6464                if (!_stop) {
    65                         DisplayIO.Back();
     65                        DisplayController.Back();
    6666                }
    6767                super.finalise(start);
     
    7979
    8080                // ignore loops
    81                 if (toProcess != DisplayIO.getCurrentFrame())
    82                         DisplayIO.setCurrentFrame(toProcess, false);
     81                if (toProcess != DisplayController.getCurrentFrame())
     82                        DisplayController.setCurrentFrame(toProcess, false);
    8383                // parse the frame for any pause settings
    8484                delay(toProcess);
  • trunk/src/org/expeditee/agents/Format.java

    r919 r1102  
    2626import java.util.List;
    2727
     28import org.expeditee.gui.DisplayController;
    2829import org.expeditee.gui.Frame;
    29 import org.expeditee.gui.FrameGraphics;
    3030import org.expeditee.gui.FrameUtils;
    3131import org.expeditee.items.Item;
     
    148148                                                + /* item.getX() + */it.getBoundsWidth());
    149149
    150                         if (xCheck < FrameGraphics.getMaxSize().width) {
     150                        if (xCheck < DisplayController.getFramePaintArea().getWidth()) {
    151151                                Item columnHead = columnHeads.get(i + 1);
    152152                                if (columnHead.getX() < maxX && columnHead.getY() < maxY) {
     
    182182                start.setChanged(true);
    183183                start.addToUndoMove(changedItems);
    184                 FrameGraphics.requestRefresh(true);
     184                DisplayController.requestRefresh(true);
    185185                return null;
    186186        }
  • trunk/src/org/expeditee/agents/GraphFramesetLinks.java

    r919 r1102  
    1919package org.expeditee.agents;
    2020
    21 import java.awt.Color;
    2221import java.util.List;
    2322
    2423import org.expeditee.actions.Misc;
     24import org.expeditee.core.Colour;
     25import org.expeditee.core.Font;
     26import org.expeditee.gio.gesture.StandardGestureActions;
     27import org.expeditee.gui.DisplayController;
    2528import org.expeditee.gui.Frame;
    2629import org.expeditee.gui.FrameIO;
    27 import org.expeditee.gui.FrameMouseActions;
    2830import org.expeditee.gui.FrameUtils;
    2931import org.expeditee.items.Item;
     
    4143import com.mxgraph.model.mxGraphModel;
    4244import com.mxgraph.view.mxGraph;
    43 import java.awt.Font;
    4445
    4546/**
     
    7475                String resultsFramesetName = "LinksGraphResults";
    7576
    76                 Color vertColor = new Color(51,145,148);
    77                 Color unlinkedVertColor = new Color(251,107,65);
    78                 Color outgoingVertColor = new Color(246,216,107);
    79                 Color lineColor = new Color(0,0,0, 20);
     77                Colour vertColor = Colour.FromRGB255(51,145,148);
     78                Colour unlinkedVertColor = Colour.FromRGB255(251,107,65);
     79                Colour outgoingVertColor = Colour.FromRGB255(246,216,107);
     80                Colour lineColor = Colour.FromRGBA255(0,0,0, 20);
    8081
    8182                try {
     
    220221                }
    221222               
    222                 Font keyFont = Font.decode(Font.SANS_SERIF + " 14");
     223                Font keyFont = new Font("SansSerif");
     224                keyFont.setSize(14);
    223225               
    224226                Text keyLink = resultsFrame.addText(0, 0, "\u2192 = Link", null);
     
    228230               
    229231                keyLink.setFont(keyFont);
    230                 keyLink.setColor(Color.DARK_GRAY);
     232                keyLink.setColor(Colour.DARK_GREY);
    231233               
    232234                keyFrame.setFont(keyFont);;
     
    239241                keyFrameOutgoing.setColor(outgoingVertColor);
    240242               
    241                 keyFrameOutgoing.setAnchorBottom(10f);
    242                 keyFrameUnlinked.setAnchorBottom(30f);
    243                 keyFrame.setAnchorBottom(50f);
    244                 keyLink.setAnchorBottom(70f);
    245                
    246                 keyFrameOutgoing.setAnchorLeft(10f);
    247                 keyFrameUnlinked.setAnchorLeft(10f);
    248                 keyFrame.setAnchorLeft(10f);
    249                 keyLink.setAnchorLeft(10f);
     243                keyFrameOutgoing.setAnchorBottom(10);
     244                keyFrameUnlinked.setAnchorBottom(30);
     245                keyFrame.setAnchorBottom(50);
     246                keyLink.setAnchorBottom(70);
     247               
     248                keyFrameOutgoing.setAnchorLeft(10);
     249                keyFrameUnlinked.setAnchorLeft(10);
     250                keyFrame.setAnchorLeft(10);
     251                keyLink.setAnchorLeft(10);
    250252
    251253                // Moving to the area of the frame that contains the graph
     
    256258                Text link = new Text(toProcessFramesetName + " graph");
    257259                link.setLink(resultsFrame.getName());
    258                 link.setPosition(FrameMouseActions.getPosition());
    259                 FrameMouseActions.pickup(link);
     260                link.setPosition(DisplayController.getMousePosition());
     261                StandardGestureActions.pickup(link);
    260262                return null;
    261263        }
  • trunk/src/org/expeditee/agents/ScaleFrameset.java

    r919 r1102  
    2121import java.util.Collection;
    2222
     23import org.expeditee.gio.gesture.StandardGestureActions;
    2324import org.expeditee.gui.Frame;
    2425import org.expeditee.gui.FrameIO;
    25 import org.expeditee.gui.FrameKeyboardActions;
    2626import org.expeditee.gui.Vector;
    2727import org.expeditee.items.Item;
     
    6262
    6363                // TODO make this thread safe!
    64                 FrameKeyboardActions.Refresh();
     64                StandardGestureActions.Refresh();
    6565
    6666                return null;
     
    102102                                continue;
    103103                        // if (!(item instanceof Line))
    104                         item.updatePolygon();
     104                        item.invalidateBounds();
    105105
    106106                        if (item instanceof Line) {
  • trunk/src/org/expeditee/agents/SearchAgent.java

    r1069 r1102  
    2121import java.util.Collection;
    2222
     23import org.expeditee.gui.DisplayController;
    2324import org.expeditee.gui.Frame;
    2425import org.expeditee.gui.FrameCreator;
    25 import org.expeditee.gui.FrameGraphics;
    2626import org.expeditee.gui.FrameIO;
    2727import org.expeditee.io.Conversion;
     
    126126        }
    127127
    128         public static boolean searchFrame(FrameCreator results, String frameName,
    129                         String pattern, String replacementString) {
    130                 int oldMode = FrameGraphics.getMode();
    131                 FrameGraphics.forceXRayMode(false);
     128        public static boolean searchFrame(FrameCreator results, String frameName, String pattern, String replacementString)
     129        {
     130                boolean wasXrayMode = DisplayController.isXRayMode();
     131                if (!wasXrayMode) DisplayController.ToggleXRayMode();
    132132                Frame frameToSearch = FrameIO.LoadFrame(frameName);
    133                 FrameGraphics.setMode(oldMode, false);
     133                if (!wasXrayMode) DisplayController.ToggleXRayMode();
    134134                if (frameToSearch == null)
    135135                        return false;
     
    142142                        }
    143143                }
    144                 FrameGraphics.requestRefresh(true);
     144                DisplayController.requestRefresh(true);
    145145                FrameIO.SaveFrame(frameToSearch, false);
    146146                return true;
     
    177177                                _results.addText(surrogate.toString(), null,
    178178                                                frameName, null, false);
    179                                 FrameGraphics.requestRefresh(true);
     179                                DisplayController.requestRefresh(true);
    180180                        }
    181181                }
  • trunk/src/org/expeditee/agents/SearchGreenstone.java

    r919 r1102  
    2323import java.util.Vector;
    2424
     25import org.expeditee.gio.gesture.StandardGestureActions;
    2526import org.expeditee.greenstone.Greenstone3Connection;
    2627import org.expeditee.greenstone.Query;
     
    2930import org.expeditee.greenstone.ResultDocument;
    3031import org.expeditee.gui.AttributeValuePair;
    31 import org.expeditee.gui.DisplayIO;
     32import org.expeditee.gui.DisplayController;
    3233import org.expeditee.gui.Frame;
    3334import org.expeditee.gui.FrameCreator;
    3435import org.expeditee.gui.FrameGraphics;
    35 import org.expeditee.gui.FrameMouseActions;
    3636import org.expeditee.gui.MessageBay;
    3737import org.expeditee.items.Text;
     
    175175                        doQuery(_pattern);
    176176                } else if (_currentResultSet != null) {
    177                         Text newText = DisplayIO.getCurrentFrame().createNewText(
    178                                         getCursorText());
     177                        Text newText = DisplayController.getCurrentFrame().createNewText(getCursorText());
    179178                        _clicked = newText;
    180                         FrameMouseActions.pickup(newText);
     179                        StandardGestureActions.pickup(newText);
    181180                }
    182181
     
    389388                                false);
    390389
    391                 FrameGraphics.requestRefresh(true);
     390                DisplayController.requestRefresh(true);
    392391        }
    393392
  • trunk/src/org/expeditee/agents/SearchTreeAndReplace.java

    r919 r1102  
    2222import java.util.HashSet;
    2323
     24import org.expeditee.gui.DisplayController;
    2425import org.expeditee.gui.Frame;
    25 import org.expeditee.gui.FrameGraphics;
    2626import org.expeditee.gui.FrameIO;
    2727import org.expeditee.items.Text;
     
    7979                        }
    8080                }
    81                 FrameGraphics.requestRefresh(true);
     81                DisplayController.requestRefresh(true);
    8282                FrameIO.SaveFrame(frameToSearch, false);
    8383                return true;
  • trunk/src/org/expeditee/agents/Sort.java

    r919 r1102  
    1919package org.expeditee.agents;
    2020
    21 import java.awt.Point;
    2221import java.util.ArrayList;
    2322import java.util.Collection;
     
    2524import java.util.Comparator;
    2625
     26import org.expeditee.core.Point;
     27import org.expeditee.gui.DisplayController;
    2728import org.expeditee.gui.Frame;
    28 import org.expeditee.gui.FrameGraphics;
    2929import org.expeditee.gui.FrameUtils;
    3030import org.expeditee.items.Text;
     
    6868                // items will need to be resorted after this
    6969                start.setResort(true);
    70                 FrameGraphics.Repaint();
     70                DisplayController.requestRefresh(true);
    7171
    7272                return null;
  • trunk/src/org/expeditee/agents/SwitchyardTree.java

    r919 r1102  
    1919package org.expeditee.agents;
    2020
    21 import java.awt.Color;
    22 import java.awt.geom.Point2D;
    23 
     21import org.expeditee.core.Colour;
     22import org.expeditee.core.Point;
    2423import org.expeditee.gui.Frame;
    2524import org.expeditee.gui.FrameIO;
     
    4443                                        Frame childFrame = FrameIO.LoadFrame(link);
    4544                                        if (childFrame != null) {
    46                                                 Point2D.Float lastItemEnd = textItem.getParagraphEndPosition();
     45                                                Point lastItemEnd = textItem.getParagraphEndPosition();
    4746                                                for (Text childItem : childFrame.getBodyTextItems(false)) {
    4847                                                        // look for red items (remember get color may be null
    49                                                         if (Color.RED.equals(childItem.getPaintColor())) {
     48                                                        if (Colour.RED.equals(childItem.getPaintColor())) {
    5049                                                                // make a copy and add to parent frame
    5150                                                                Text itemCopy = childItem.copy();
    5251                                                                // add to the right of parent item
    53                                                                 lastItemEnd.setLocation(lastItemEnd.x + 20, lastItemEnd.y);
     52                                                                lastItemEnd.set(lastItemEnd.x + 20, lastItemEnd.y);
    5453                                                                itemCopy.setPosition(lastItemEnd.x, lastItemEnd.y);
    5554                                                                lastItemEnd = itemCopy
  • trunk/src/org/expeditee/agents/mail/MailSession.java

    r919 r1102  
    1919package org.expeditee.agents.mail;
    2020
    21 import java.awt.Color;
    22 import java.awt.Point;
    2321import java.io.BufferedReader;
    2422import java.io.InputStream;
     
    4846import javax.mail.internet.MimeMessage;
    4947
     48import org.expeditee.core.Colour;
     49import org.expeditee.core.Point;
     50import org.expeditee.gio.DragAndDropManager;
    5051import org.expeditee.gui.AttributeValuePair;
     52import org.expeditee.gui.DisplayController;
    5153import org.expeditee.gui.Frame;
    5254import org.expeditee.gui.FrameCreator;
    53 import org.expeditee.gui.FrameGraphics;
    5455import org.expeditee.gui.MessageBay;
    55 import org.expeditee.importer.FrameDNDTransferHandler;
    5656import org.expeditee.items.Text;
    5757
     
    208208                                                try {
    209209                                                        MessageBay.displayMessage("New mail message!",
    210                                                                         null, Color.green, true, "getMailByID "
     210                                                                        null, Colour.GREEN, true, "getMailByID "
    211211                                                                                        + _folder.getMessageCount());
    212212                                                        /*
     
    247247
    248248                                MessageBay.displayMessage("Mail connection complete",
    249                                                 Color.GREEN);
     249                                                Colour.GREEN);
    250250
    251251                                displayUnreadMailCount();
     
    262262                int unreadCount = getUnreadCount();
    263263                Text text = new Text(-1, unreadCount + UNREAD_MESSAGE
    264                                 + (unreadCount == 1 ? "" : "s"), Color.BLUE, null);
     264                                + (unreadCount == 1 ? "" : "s"), Colour.BLUE, null);
    265265                if (unreadCount > 0)
    266266                        text.addAction("getUnreadMail " + unreadCount);
     
    517517                        final Frame frame, final Point point) {
    518518
    519                 final Text source = FrameDNDTransferHandler.importString(
    520                                 "Reading message " + messageNo + "...", point);
     519                final Text source = DragAndDropManager.importString("Reading message " + messageNo + "...", point);
    521520
    522521                new Thread() {
     
    598597                                        frames.save();
    599598                                        source.setLink(frames.getName());
    600                                         FrameGraphics.requestRefresh(true);
     599                                        DisplayController.requestRefresh(true);
    601600                                } catch (MessageRemovedException mre) {
    602601                                        source.setText("Message removed from inbox");
  • trunk/src/org/expeditee/gui/AttributeUtils.java

    r1048 r1102  
    1919package org.expeditee.gui;
    2020
    21 import java.awt.Color;
    22 import java.awt.Font;
    23 import java.awt.Point;
    2421import java.lang.reflect.InvocationTargetException;
    2522import java.lang.reflect.Method;
     
    2825import java.util.List;
    2926
     27import org.expeditee.core.Colour;
     28import org.expeditee.core.Font;
     29import org.expeditee.core.Point;
    3030import org.expeditee.io.Conversion;
    3131import org.expeditee.items.DotType;
     
    3333import org.expeditee.items.Justification;
    3434import org.expeditee.items.PermissionPair;
    35 import org.expeditee.items.Picture;
    3635import org.expeditee.items.Text;
    3736import org.expeditee.simple.IncorrectTypeException;
     
    137136                        Class<?>[] pFloat = { float.class };
    138137                        Class<?>[] pFloatO = { Float.class };
    139                         Class<?>[] pColor = { Color.class };
     138                        Class<?>[] pDouble = {double.class };
     139                        Class<?>[] pColor = { Colour.class };
    140140                        Class<?>[] pBool = { boolean.class };
    141141                        //Class[] pDouble = { double.class };
     
    214214                                                            Item.class.getMethod("setBorderColor", pColor));
    215215                        _Attrib.put("AnchorLeft",           Item.class.getMethod("getAnchorLeft"),
    216                                                             Item.class.getMethod("setAnchorLeft", pFloatO));
     216                                                            Item.class.getMethod("setAnchorLeft", pIntO));
    217217                        _Attrib.put("AnchorRight",          Item.class.getMethod("getAnchorRight"),
    218                                                             Item.class.getMethod("setAnchorRight", pFloatO));
     218                                                            Item.class.getMethod("setAnchorRight", pIntO));
    219219                        _Attrib.put("AnchorTop",            Item.class.getMethod("getAnchorTop"),
    220                                                             Item.class.getMethod("setAnchorTop", pFloatO));
     220                                                            Item.class.getMethod("setAnchorTop", pIntO));
    221221                        _Attrib.put("AnchorBottom",         Item.class.getMethod("getAnchorBottom"),
    222                                                             Item.class.getMethod("setAnchorBottom", pFloatO));
     222                                                            Item.class.getMethod("setAnchorBottom", pIntO));
    223223                        _Attrib.put("Position",             Item.class.getMethod("getPosition"),
    224224                                                            Item.class.getMethod("setPosition", pPoint));
     
    248248                                                            Item.class.getMethod("setGradientColor", pColor));
    249249                        _Attrib.put("GradientAngle",        Item.class.getMethod("getGradientAngle"),
    250                                                             Item.class.getMethod("setGradientAngle", pInt));
     250                                                            Item.class.getMethod("setGradientAngle", pDouble));
    251251                        _Attrib.put("FillPattern",          Item.class.getMethod("getFillPattern"),
    252252                                                            Item.class.getMethod("setFillPattern", pString));
     
    417417
    418418                // create the text Item
    419                 Frame current = DisplayIO.getCurrentFrame();
     419                Frame current = DisplayController.getCurrentFrame();
    420420                Item attribs = current.getStatsTextItem(attributes.toString());
    421421                return attribs;
     
    486486                        if (((Double) o) < 0.0001)
    487487                                return null;
    488                 } else if (o instanceof Color) {
     488                } else if (o instanceof Colour) {
    489489                        // converts the color to the Expeditee code
    490                         o = Conversion.getExpediteeColorCode((Color) o);
     490                        o = Conversion.getExpediteeColorCode((Colour) o);
    491491                        if (o == null)
    492492                                return null;
     
    497497                        Font f = (Font) o;
    498498
    499                         String s = f.getName() + "-";
     499                        String s = f.getFamilyName() + "-";
    500500                        if (f.isPlain())
    501501                                s += "Plain";
  • trunk/src/org/expeditee/gui/Browser.java

    r1075 r1102  
    1919package org.expeditee.gui;
    2020
    21 import java.awt.Color;
    22 import java.awt.Dimension;
    23 import java.awt.Graphics;
    24 import java.awt.Graphics2D;
    25 import java.awt.Image;
    26 import java.awt.MouseInfo;
    27 import java.awt.Point;
    28 import java.awt.RenderingHints;
    29 import java.awt.Toolkit;
    30 import java.awt.event.ComponentEvent;
    31 import java.awt.event.ComponentListener;
    32 import java.awt.event.WindowEvent;
    33 import java.awt.event.WindowListener;
    34 import java.awt.event.WindowStateListener;
    3521import java.io.File;
    3622import java.net.Authenticator;
    37 import java.net.URL;
    3823import java.util.ArrayList;
    3924import java.util.Collection;
    40 import java.util.LinkedList;
    41 
    42 import javax.swing.JFrame;
    43 import javax.swing.RepaintManager;
    44 import javax.swing.SwingUtilities;
    45 
    46 import org.expeditee.AbsoluteLayout;
     25
    4726import org.expeditee.actions.Actions;
    4827import org.expeditee.actions.Simple;
    4928import org.expeditee.agents.mail.MailSession;
    50 import org.expeditee.importer.FrameDNDTransferHandler;
     29import org.expeditee.core.BlockingRunnable;
     30import org.expeditee.core.Colour;
     31import org.expeditee.core.Dimension;
     32import org.expeditee.core.Point;
     33import org.expeditee.gio.EcosystemManager;
     34import org.expeditee.gio.EcosystemManager.Ecosystem;
     35import org.expeditee.gio.GraphicsManager;
     36import org.expeditee.gio.InputManager;
     37import org.expeditee.gio.InputManager.WindowEventListener;
     38import org.expeditee.gio.InputManager.WindowEventType;
     39import org.expeditee.gio.gesture.StandardGestureActions;
    5140import org.expeditee.io.ProxyAuth;
    5241import org.expeditee.items.Item;
     42import org.expeditee.items.ItemUtils;
    5343import org.expeditee.items.Text;
    5444import org.expeditee.items.widgets.WidgetCacheManager;
     
    6858 * processes any Events.
    6959 *
     60 * TODO List:
     61 *
     62 * Back to standard:
     63 *  - JavaFX Text-hitting (requires JFX1.9)
     64 *  - Overlays and Vectors review
     65 *  - Pop-ups (unused in base Expeditee, only in Apollo)
     66 *  - Apollo input (test)
     67 *  - The rest of Apollo
     68 *  - Make sure clipping/invalidation takes twin-frames into account
     69 *  - Reinstate Simple input commands
     70 *  - Test LinkedTrack.paintInFreeSpace()
     71 *  - Test EmulatedTextItem.onMouseReleased(MouseEvent) (removed emulatedSource mouse button check)
     72 *  - Constrained placement of items
     73 * 
     74 * Extra:
     75 *  - Self-describing input
     76 *  - Thread safety (most stuff on GIO event thread but Agents can start new threads)
     77 *  - Touch input
     78 *  - Better reflection??? (currently changes to the code break reflection as it relies on names)
     79 *  - JavaFX lag (always rendering to images doesn't gel well with JavaFX)
     80 *  - Swing widgets in JFX
     81 *  - JavaFX Widgets (exception on drawing?)
     82 *  - Reduce reliance on into-image rendering to improve JavaFX performance (utilise enforced-clip)
     83 *  - Block Swing ecosystem setup until window is available, or...
     84 *  - Reconfigure window-resized code so things are properly resized (PREFERRED).
     85 *  - Swing alpha-compositing of colours (currently alpha is ignored e.g. drop-shadow in transition).
     86 *  - Overly-thick extrusion lines (seems to depend on number of connected lines...)
     87 *  - Make FreeItems control pickup etc.
     88 *  - Remove MouseEventRouter
     89 *  - Highlighting (should be controlled by the items themselves)
     90 *  - Make Widgets into fully-fledged items (maybe???)
     91 *  - Merge Widget and HeavyDutyWidget
     92 *  - Redefine TextLayouts (relative/absolute layouts)
     93 *  - Settings exceptions (Password widget in JFX) (currently fixed with hack)
     94 *  - MessageBay (what did I mean by this specifically?)
     95 *  - Order-dependency of start-up code
     96 *  - MessageBay not refreshing at start-up
     97 *  - Invalidation hierarchy (item => frame => display controller area => window)
     98 *  - Add gesture data type checking
     99 *  - Paintable interface
     100 *  - EcosystemSpecific interface (utilise to enable/disable features based on ecosystem)
     101 *  - Remove/modify Mutable class (in Apollo.util, change to InOutReference)
     102 *  - Convert BlockingRunnable to interface
     103 *  - Modify Metronome to utilise Timeouts
     104 *  - Need AWT in FastAlphaEffect???
     105 * 
     106 * General:
     107 *  - Tidy FrameGraphics
     108 *  - Comment
     109 *  - UserSettings.DEFAULT_PROFILE_NAME not actually a user setting
     110 *
     111 * Done:
     112 *  - Timers
     113 *  - Timer input animations
     114 *  - Finish DisplayController/FrameGraphics separation
     115 *  - Anchor constraints (create class)
     116 *  - Make MessageBay take lead from DisplayController
     117 *  - Make message bay display again (to do with above)
     118 *  - Tooltips (layout broken in Swing as window size not correct when tooltips laid out)
     119 *  - Frame transitions
     120 *  - Frame transitions in twin-frames mode drawing over each other
     121 *  - JFX DnD manager
     122 *  - Reinstate Simple
     123 *  - Reinstate exclude source
     124 *  - Reinstate commented code
     125 *  - Twin-frames division 0 at startup
     126 *  - Twin frames off-by-one frame size (draws a line of erroneous pixels)
     127 *  - MessageBay delays showing messages on start-up
     128 *  - JFX Antialiasing done on theScene??? Doesn't apply for our situation
     129 *  - Incorporate Clip class into code
     130 *  - Enforced clip
     131 *
     132 * @author cts16
    70133 * @author jdm18
    71  *
    72134 */
    73 public class Browser extends JFrame implements ComponentListener,
    74                 WindowListener, WindowStateListener, SaveStateChangedEventListener {
    75 
    76         /**
    77          * Default version - just to stop eclipse from complaining about it.
    78          */
    79         private static final long serialVersionUID = 1L;
    80 
    81         // private static final JScrollPane scrollPane = new JScrollPane();
     135public class Browser implements SaveStateChangedEventListener {
     136       
     137        public static final Ecosystem ECOSYSTEM_TYPE = Ecosystem.Swing;
    82138
    83139        public static Browser _theBrowser = null;
     
    86142
    87143        public static boolean _hasExited = false;
    88        
    89         protected MouseEventRouter _mouseEventRouter;
    90 
    91         // A flag which is set once the application is exiting.
     144
     145        /** A flag which is set once the application is exiting. */
    92146        protected boolean _isExiting = false;
    93 
    94         protected boolean _minimum_version6 = false;
    95 
    96         public boolean isMinimumVersion6() {
    97                 return _minimum_version6;
    98         }
    99147
    100148        protected static boolean _initComplete = false;
     
    107155         * @param args
    108156         */
    109         public static void main(String[] args) {
    110                
     157        public static void main(String[] args)
     158        {
     159                // Parse the starting frame command-line argument
    111160                if(args.length > 0) {
    112161                        _startFrame = args[0];
    113                         if(! Character.isDigit(_startFrame.charAt(_startFrame.length() - 1)))
    114                                 _startFrame = _startFrame + "1";
    115                 }
    116                 else {
     162                        if(!Character.isDigit(_startFrame.charAt(_startFrame.length() - 1))) _startFrame = _startFrame + "1";
     163                } else {
    117164                    _startFrame = "home1";
    118165                }
    119166
    120                 // Prepare all expeditee and swing data on the AWT event thread.
    121                 SwingUtilities.invokeLater(new Runnable() {
    122                         public void run() {
    123                                 // MessageBay.supressMessages(true);
    124 
    125                                 // MessageBay.supressMessages(false);
    126 
    127                                 _theBrowser = new Browser();
    128                                
    129                                 DisplayIO.refreshCursor();
    130                                 _theBrowser.requestFocus();
    131                                 FrameMouseActions.MouseX = MouseInfo.getPointerInfo()
    132                                                 .getLocation().x
    133                                                 - _theBrowser.getOrigin().x;
    134                                 FrameMouseActions.MouseY = MouseInfo.getPointerInfo()
    135                                                 .getLocation().y
    136                                                 - _theBrowser.getOrigin().y;
    137                                 _initComplete = true;
    138                                
    139                                 Authenticator.setDefault(proxyAuth);
    140                         }
    141                 });
    142 
    143         }
    144 
    145         public Point getOrigin() {
    146                 return getContentPane().getLocationOnScreen();
    147         }
    148 
    149         /**
    150          * @return The mouse event router used for this browser. Never null after
    151          *         browser constructed.
    152          */
    153         public MouseEventRouter getMouseEventRouter() {
    154                 return _mouseEventRouter;
     167                // Window icon must be set before initialisation
     168                GraphicsManager.setWindowIcon(DisplayController.ICON_IMAGE);
     169               
     170                // Setup the GIO ecosystem so it is ready when we need it
     171                EcosystemManager.createEcosystem(ECOSYSTEM_TYPE);
     172               
     173                try {
     174                        EcosystemManager.getMiscManager().runOnGIOThread(new BlockingRunnable() {
     175                                @Override
     176                                public void execute() {
     177                                        init();
     178                                }
     179                        });
     180                } catch (Throwable e) {
     181                        e.printStackTrace(System.err);
     182                        System.exit(1);
     183                }
     184               
     185                MessageBay.showDelayedMessages();
     186        }
     187       
     188        public static void init()
     189        {
     190                _theBrowser = new Browser();
     191
     192                EcosystemManager.getGraphicsManager().requestFocus();
     193               
     194                Authenticator.setDefault(proxyAuth);
     195               
     196                _initComplete = true;
    155197        }
    156198
     
    165207         *
    166208         */
    167         public boolean isExisting() {
     209        public boolean isExiting() {
    168210                return _isExiting;
    169211        }
     
    173215        }
    174216
    175         public void setSizes(Dimension size) {
    176                 setSize(size);
    177                 setPreferredSize(size);
    178                 Dimension paneSize = getContentPane().getSize();
    179                 FrameGraphics.setMaxSize(paneSize);
    180         }
    181 
    182         protected Browser() {
     217        protected Browser()
     218        {
    183219                // center the frame on the screen
    184                 Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
    185                 double xpos = screen.getWidth() / 2;
    186                 double ypos = screen.getHeight() / 2;
    187                 setLocation((int) (xpos - (UserSettings.InitialWidth.get() / 2)),
    188                                 (int) (ypos - (UserSettings.InitialHeight.get() / 2)));
    189 
    190                 addWindowListener(this);
    191                 addWindowStateListener(this);
    192 
    193                 DisplayIO.addDisplayIOObserver(WidgetCacheManager.getInstance());
    194                 DisplayIO.addDisplayIOObserver(PopupManager.getInstance());
    195 
    196                
    197                 // set up the image used for the icon
    198             try
    199         {
    200           URL iconURL = ClassLoader.getSystemResource("org/expeditee/assets/icons/expediteeicon128.png");
    201           if (iconURL != null)
    202           {
    203             Image localImage = Toolkit.getDefaultToolkit().getImage(iconURL);
    204             this.setIconImage(localImage);
    205           }
    206         }
    207         catch (Exception e)
    208         {
    209           e.printStackTrace();
    210         }
    211            
    212             setSizes(new Dimension(UserSettings.InitialWidth.get(), UserSettings.InitialHeight.get()));
    213            
    214             // set the layout to absolute layout for widgets
    215             // => this used to be done here, but now has been moved to later in the method
    216             //    as is works better when put in a JFXPanel
    217             //this.getContentPane().setLayout(new AbsoluteLayout());
    218 
    219                 _mouseEventRouter = new MouseEventRouter(getJMenuBar(),
    220                                 getContentPane());
    221 
    222                 // enable the glasspane-for capturing all mouse events
    223                 this.setGlassPane(_mouseEventRouter);
    224 
    225                 this.getGlassPane().setVisible(true);
    226                 this.getContentPane().setBackground(Color.white);
    227                 this.getContentPane().setFocusTraversalKeysEnabled(false);
    228 
    229                 addComponentListener(this);
    230                 pack();
    231                 this.getContentPane().setLayout(new AbsoluteLayout()); // moved to here to work with JFXPanel
    232 
     220                GraphicsManager g = EcosystemManager.getGraphicsManager();
     221                Dimension screen = g.getScreenSize();
     222                double xpos = (screen.width - UserSettings.InitialWidth.get()) / 2.0;
     223                double ypos = (screen.height - UserSettings.InitialHeight.get()) / 2.0;
     224                g.setWindowLocation(new Point((int) xpos, (int) ypos));
     225
     226                DisplayController.Init();
     227               
     228                DisplayController.addDisplayObserver(WidgetCacheManager.getInstance());
     229                if (ECOSYSTEM_TYPE == Ecosystem.Swing) {
     230                        DisplayController.addDisplayObserver(PopupManager.getInstance());
     231                }
     232
     233                setInputManagerWindowRoutines();
     234               
    233235                // Reset windows to user specified size
    234                 // Must be done after initialising the content pane above!
    235                 setSizes(new Dimension(UserSettings.InitialWidth.get(), UserSettings.InitialHeight.get()));
    236            
    237                 // UserSettings.ProfileName.set(FrameIO.ConvertToValidFramesetName(System.getProperty("user.name")));
    238                 String userName = UserSettings.ProfileName.get();
    239                 //UserSettings.UserName.set(UserSettings.ProfileName.get());
     236                Dimension initialWindowSize = new Dimension(UserSettings.InitialWidth.get(), UserSettings.InitialHeight.get());
     237                g.setWindowSize(initialWindowSize);
    240238               
    241239                // Load documentation and start pages
    242240                FrameUtils.extractResources(false);
     241               
    243242                // Load fonts before loading any frames so the items on the frames will be able to access their fonts
    244243                Text.InitFonts();
    245 
    246                 Frame profile = loadProfile(userName);
    247 
    248                 // Need to display errors once things have been init otherwise
    249                 // exceptions occur if there are more than four messages neededing to be
    250                 // displayed.
    251 
    252                 Frame defaultProfile = loadProfile(UserSettings.DEFAULT_PROFILE_NAME);
    253 
    254                 Collection<String> warningMessages = new LinkedList<String>();
    255                 warningMessages.addAll(FrameUtils.ParseProfile(defaultProfile));
    256                 //Save the cursor if the defaultProfile had a custom cursor
    257                 Collection<Item> cursor = null;
    258                 if(FreeItems.hasCursor()){
    259                         cursor = new ArrayList<Item>();
    260                         cursor.addAll(FreeItems.getCursor());
    261                 }
    262                 warningMessages.addAll(FrameUtils.ParseProfile(profile));
    263                 if(cursor != null && !FreeItems.hasCursor()){
    264                         FreeItems.setCursor(cursor);
    265                 }
    266 
    267                 /*
    268                  * See Java bug ID 4016934. They say that window closed events are
    269                  * called once the JFrame is disposed.
    270                  */
    271                 setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    272                
    273                 // Expeditee handles its own repainting of AWT/Swing components
    274                 RepaintManager.setCurrentManager(ExpediteeRepaintManager.getInstance());
     244               
     245                Frame userProfile = loadProfiles();
    275246
    276247                // Listen for save status to display during and after runtime
    277248                EntitySaveManager.getInstance().addSaveStateChangedEventListener(this);
    278 
    279                 String full_version = System.getProperty("java.version");
    280                 String[] version_parts = full_version.split("\\.");
    281                 if (version_parts.length>=2) {
    282                         String version_str = version_parts[0] + "." + version_parts[1];
    283                         double version = Double.parseDouble(version_str);
    284                        
    285                         if (version >= 1.6) {
    286                                 // Set the drag and drop handler
    287                                 _minimum_version6 = true;
    288                                 setTransferHandler(FrameDNDTransferHandler.getInstance());
    289                         } else {
    290                                 System.err.println("Upgrade to a (minimum) of Java 1.6 to enable drag and drop support in Expeditee");
    291                         }
    292                 }
    293                 else {
    294                         System.err.println("Unable to parse Java version number " + full_version + " to determin if Drag and Drop supported");
    295                        
    296                 }
    297                
    298 
     249               
    299250                try {
    300                         warningMessages.addAll(Actions.Init());
     251                        MessageBay.warningMessages(Actions.Init());
    301252                       
    302253                        Settings.Init();
    303 
    304                         DisplayIO.Init(this);
    305                         // Set visible must be just after DisplayIO.Init for the message box
    306                         // to
    307                         // be the right size
    308                         setVisible(true);
    309 
    310                         setupGraphics();
    311 
    312                         // required to accept TAB key
    313                         setFocusTraversalKeysEnabled(false);
    314 
    315                         // Must be loaded after setupGraphics if images are on the frame
    316                         // Turn off XRay mode and load the first frame
    317                         FrameGraphics.setMode(FrameGraphics.MODE_NORMAL, false);
    318254                       
    319255                        // Go to the start frame if specified, otherwise go to the profile frame
     
    321257                        if(_startFrame == null) {
    322258                                _startFrame = UserSettings.StartFrame.get();
    323                                 if(_startFrame != null && !Character.isDigit(_startFrame.charAt(_startFrame.length() - 1)))
     259                                if(_startFrame != null && !Character.isDigit(_startFrame.charAt(_startFrame.length() - 1))) {
    324260                                        _startFrame = _startFrame + "1";
    325                         }
     261                                }
     262                        }
     263                       
    326264                if((start = FrameIO.LoadFrame(_startFrame)) != null) {
    327265                        // Make sure HomeFrame gets set
    328266                        UserSettings.HomeFrame.set(start.getName());
    329                         //if (UserSettings.HomeFrame.get() == null) {
    330                                 //UserSettings.HomeFrame.set(profile.getName());
    331 
    332                         //}
    333                         // Make sure the user can get back to the profile frame easily
    334                         //DisplayIO.addToBack(profile);
     267                       
    335268                        // Go to the start frame
    336                         DisplayIO.setCurrentFrame(start, true);
     269                        DisplayController.setCurrentFrame(start, true);
    337270                } else {
    338271                        // If an invalid start frame was specified, show a warning
    339                         if(_startFrame != null) {
    340                                 warningMessages.add("Unknown frame: " + _startFrame);
    341                         }
     272                        if(_startFrame != null) MessageBay.warningMessage("Unknown frame: " + _startFrame);
     273                       
    342274                        // Go to the profile frame
    343                         FrameUtils.loadFirstFrame(profile);
     275                        FrameUtils.loadFirstFrame(userProfile);
    344276                }
    345                         DisplayIO.UpdateTitle();
    346 
    347                         /*
    348                          * I think this can be moved back up to the top of the Go method
    349                          * now... It used to crash the program trying to print error
    350                          * messages up the top
    351                          */
    352                         for (String message : warningMessages)
    353                                 MessageBay.warningMessage(message);
    354 
    355                         this.getContentPane().addKeyListener(FrameKeyboardActions.getInstance());
    356                         this.addKeyListener(FrameKeyboardActions.getInstance());
    357 
    358                         _mouseEventRouter.addExpediteeMouseListener(FrameMouseActions.getInstance());
    359                         _mouseEventRouter.addExpediteeMouseMotionListener(FrameMouseActions.getInstance());
    360                         _mouseEventRouter.addExpediteeMouseWheelListener(FrameMouseActions.getInstance());
    361 
    362                         // Dont refresh for the profile frame otherwise error messages are shown twice
    363                         if (!DisplayIO.getCurrentFrame().equals(profile)) {
    364                                 FrameKeyboardActions.Refresh();
     277               
     278                        DisplayController.updateTitle();
     279
     280                        // Don't refresh for the profile frame otherwise error messages are shown twice
     281                        if (!DisplayController.getCurrentFrame().equals(userProfile)) {
     282                                StandardGestureActions.Refresh();
    365283                        // If it's the profile frame just reparse it in order to display images/circles/widgets correctly
    366284                        } else {
    367                                 FrameUtils.Parse(profile);
    368                         }
    369                         // setVisible(true);
     285                                FrameUtils.Parse(userProfile);
     286                        }
    370287                } catch (Exception e) {
    371288                        e.printStackTrace();
     
    374291        }
    375292
     293        public void saveCompleted(SaveStateChangedEvent event)
     294        {
     295                MessageBay.displayMessage("Save finished!", Colour.BLUE);
     296        }
     297
     298        public void saveStarted(SaveStateChangedEvent event)
     299        {
     300                String name = event.getEntity().getSaveName();
     301                if (name == null) name = "data";
     302                MessageBay.displayMessage("Saving " + name + "...", Colour.BLUE);
     303        }
     304
    376305        /**
    377          * @param userName
     306         * Closes the browser and ends the application. Performs saving operations -
     307         * halting until saves have completed. Feedback is given to the user while
     308         * the application is exiting. Must call on the swing thread.
     309         */
     310        public void exit() {
     311
     312                // Set exiting flag
     313                _isExiting = true;
     314
     315                MessageBay.displayMessage("System exiting...");
     316
     317                /**
     318                 * TODO: Prompt the user etc.
     319                 */
     320
     321                // TODO: Should we should a popup with a progress bar for user feedback?
     322                // this would be nice and easy to do.
     323                // Exit on a dedicated thread so that feedback can be obtained
     324                new Exiter().start(); // this will exit the application
     325        }
     326
     327        /**
     328         * The system must exit on a different thread other than the swing thread so
     329         * that the save threads can fire save-feedback to the swing thread and thus
     330         * provide user feedback on asynchronous save operations.
     331         *
     332         * @author Brook Novak
     333         *
     334         */
     335        private class Exiter extends Thread {
     336
     337                @Override
     338                public void run() {
     339
     340                        // The final save point for saveable entities
     341                        EntitySaveManager.getInstance().saveAll();
     342                        try {
     343                                EntitySaveManager.getInstance().waitUntilAllSavingFinished();
     344                        } catch (InterruptedException e) {
     345                                e.printStackTrace();
     346                        }
     347                       
     348                        // Stop any agents or simple programs
     349                        Simple.stop();
     350                        Actions.stopAgent();
     351                        // Wait for them to stop
     352                        try {
     353                                // Only stop if need to...
     354                                // Brook: What purpose does this serve?
     355                                MessageBay.displayMessage("Stopping Simple programs...");
     356                                while (Simple.isProgramRunning()) {
     357                                        Thread.sleep(100);
     358                                }
     359                               
     360                                MessageBay.displayMessage("Stopping Agents...");
     361                                /* TODO: Only stop if need to... */
     362                                while (Actions.isAgentRunning()) {
     363                                        Thread.sleep(100); // Brook: What purpose does this serve?
     364                                }
     365                        } catch (Exception e) {
     366
     367                        }
     368
     369                        MessageBay.displayMessage("Saving current frame...");
     370                        FrameIO.SaveFrame(DisplayController.getCurrentFrame());
     371
     372                        MessageBay.displayMessage("Saving stats...");
     373                        StatsLogger.WriteStatsFile();
     374
     375                        if (MailSession.getInstance() != null) {
     376                                if (MailSession.getInstance().finalise()) {
     377                                        // TODO display this message before the finalising
     378                                        // is done but only if the mail needs closing
     379                                        MessageBay.displayMessage("Closed ExpMail...");
     380                                }
     381                        }
     382
     383                        if (FrameShare.getInstance() != null) {
     384                                MessageBay.displayMessage("Stopping FrameServer...");
     385                                FrameShare.getInstance().finalise();
     386                        }
     387
     388                        MessageBay.displayMessage("System exited");
     389
     390                        // Finally remove the messages frameset
     391                        FrameIO.moveFrameset("messages", FrameIO.MESSAGES_PATH);
     392
     393                        /*
     394                         * Create a new messages folder so that it doesn't throw
     395                         * Exceptions when two Expeditee's open at once and the
     396                         * second tries to save its messages
     397                         */
     398                        File file = new File(FrameIO.MESSAGES_PATH + "messages");
     399                        file.mkdirs();
     400
     401                        Browser._hasExited = true;
     402                       
     403                        System.exit(0);
     404                }
     405        }
     406
     407        /**
     408         * Used to set up the the browser for use in testing.
     409         *
    378410         * @return
    379411         */
    380         protected Frame loadProfile(String userName) {
     412        public static Browser initializeForTesting()
     413        {
     414                if (Browser._theBrowser == null) {
     415                        FrameShare.disableNetworking = true;
     416                        MailSession._autoConnect = false;
     417
     418                        Browser.main(new String[]{});
     419                        try {
     420                                while (!isInitComplete()) {
     421                                        Thread.sleep(10);
     422                                }
     423                        } catch (Exception e) {
     424                        }
     425                }
     426                return _theBrowser;
     427        }
     428       
     429        private static void setInputManagerWindowRoutines()
     430        {
     431                InputManager manager = EcosystemManager.getInputManager();
     432               
     433            // Refresh the layout when the window resizes
     434                manager.addWindowEventListener(new WindowEventListener() {
     435                        @Override
     436                        public void onWindowEvent(WindowEventType type)
     437                        {
     438                                if (type != WindowEventType.WINDOW_RESIZED) return;
     439                                DisplayController.refreshWindowSize();
     440                                FrameIO.RefreshCacheImages();
     441                                for (Frame frame : DisplayController.getFrames()) {
     442                                        if (frame != null) {
     443                                                ItemUtils.Justify(frame);
     444                                                frame.refreshSize();
     445                                        }
     446                                }
     447                                DisplayController.requestRefresh(false);
     448                        }
     449                });
     450               
     451                manager.addWindowEventListener(new WindowEventListener() {
     452                        @Override
     453                        public void onWindowEvent(WindowEventType type)
     454                        {
     455                                if (type != WindowEventType.MOUSE_EXITED_WINDOW) return;
     456                                StandardGestureActions.mouseExitedWindow();
     457                        }
     458                });
     459               
     460                manager.addWindowEventListener(new WindowEventListener() {
     461                        @Override
     462                        public void onWindowEvent(WindowEventType type)
     463                        {
     464                                if (type != WindowEventType.MOUSE_ENTERED_WINDOW) return;
     465                                StandardGestureActions.mouseEnteredWindow();
     466                        }
     467                });
     468               
     469                manager.addWindowEventListener(new WindowEventListener() {
     470                        @Override
     471                        public void onWindowEvent(WindowEventType type)
     472                        {
     473                                if (type != WindowEventType.WINDOW_CLOSED) return;
     474                                if (Browser._theBrowser != null) Browser._theBrowser.exit();
     475                        }
     476                });
     477        }
     478
     479        /**
     480         * @return The user's profile frame.
     481         */
     482        private static Frame loadProfiles()
     483        {
     484                String defaultProfileName = UserSettings.DEFAULT_PROFILE_NAME;
     485                String userName = UserSettings.ProfileName.get();
     486
     487                Frame defaultProfile = loadProfile(defaultProfileName);
     488                Frame userProfile = loadProfile(userName);
     489
     490                MessageBay.warningMessages(FrameUtils.ParseProfile(defaultProfile));
     491               
     492                // Save the cursor if the defaultProfile had a custom cursor
     493                Collection<Item> cursor = null;
     494                if(FreeItems.hasCursor()) {
     495                        cursor = new ArrayList<Item>();
     496                        cursor.addAll(FreeItems.getCursor());
     497                }
     498               
     499                MessageBay.warningMessages(FrameUtils.ParseProfile(userProfile));
     500               
     501                if (cursor != null && !FreeItems.hasCursor()) FreeItems.setCursor(cursor);
     502               
     503                return userProfile;
     504        }
     505
     506        protected static Frame loadProfile(String userName)
     507        {
    381508                Frame profile = FrameIO.LoadProfile(userName);
     509               
    382510                if (profile == null) {
    383511                        try {
     
    392520                return profile;
    393521        }
    394 
    395         public Graphics2D g;
    396 
    397         protected void setupGraphics() {
    398                 if (g != null)
    399                         g.dispose();
    400                 g = (Graphics2D) this.getContentPane().getGraphics();
    401                 assert (g != null);
    402                 g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
    403                                 RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    404                 g.setFont(g.getFont().deriveFont(40f));
    405                 FrameGraphics.setDisplayGraphics(g);
    406         }
    407 
    408         // private int count = 0;
    409         @Override
    410         public void paint(Graphics g) {
    411                 // All this does is make sure the screen is repainted when the browser
    412                 // is moved so that some of the window is off the edge of the display
    413                 // then moved back into view
    414                 super.paint(g);
    415                 FrameGraphics.ForceRepaint();
    416                 // System.out.println("Paint " + count++);
    417         }
    418 
    419         /**
    420          * @inheritDoc
    421          */
    422         public void componentResized(ComponentEvent e) {
    423                 setSizes(this.getSize());
    424                 setupGraphics();
    425                 FrameIO.RefreshCasheImages();
    426                 FrameGraphics.ForceRepaint();
    427         }
    428 
    429         /**
    430          * @inheritDoc
    431          */
    432         public void componentMoved(ComponentEvent e) {
    433                 // FrameGraphics.setMaxSize(this.getSize());
    434         }
    435 
    436         /**
    437          * @inheritDoc
    438          */
    439         public void componentShown(ComponentEvent e) {
    440                 DisplayIO.fullScreenTransitionPending=false;
    441         }
    442 
    443         /**
    444          * @inheritDoc
    445          */
    446         public void componentHidden(ComponentEvent e) {
    447         }
    448 
    449         public void windowClosing(WindowEvent e) {
    450         }
    451 
    452         public void windowClosed(WindowEvent e) {
    453                 if (!DisplayIO.fullScreenTransitionPending) {
    454                         exit();
    455                 }
    456         }
    457 
    458         public void windowOpened(WindowEvent e) {
    459         }
    460 
    461         public void windowIconified(WindowEvent e) {
    462         }
    463 
    464         public void windowDeiconified(WindowEvent e) {
    465         }
    466 
    467         public void windowActivated(WindowEvent e) {
    468         }
    469 
    470         public void windowDeactivated(WindowEvent e) {
    471         }
    472 
    473         public void windowStateChanged(WindowEvent e) {
    474         }
    475 
    476         public int getDrawingAreaX() {
    477                 // return scrollPane.getLocationOnScreen().x;
    478                 return this.getLocationOnScreen().x;
    479         }
    480 
    481         public int getDrawingAreaY() {
    482                 // return scrollPane.getLocationOnScreen().y;
    483                 return this.getLocationOnScreen().y;
    484         }
    485 
    486         public void saveCompleted(SaveStateChangedEvent event) {
    487                 // if (isExisting()) {
    488 
    489                 // } else {
    490                 MessageBay.displayMessage("Save finished!", Color.BLUE);
    491                 // }
    492         }
    493 
    494         public void saveStarted(SaveStateChangedEvent event) {
    495                 // if (isExisting()) {
    496 
    497                 // } else {
    498                 String name = event.getEntity().getSaveName();
    499                 if (name == null)
    500                         name = "data";
    501                 MessageBay.displayMessage("Saving " + name + "...", Color.BLUE);
    502                 // }
    503         }
    504 
    505         /**
    506          * Closes the browser and ends the application. Performs saving operations -
    507          * halting until saves have completed. Feedback is given to the user while
    508          * the application is exiting. Must call on the swing thread.
    509          */
    510         public void exit() {
    511 
    512                 // Set exiting flag
    513                 _isExiting = true;
    514 
    515                 MessageBay.displayMessage("System exiting...");
    516 
    517                 /**
    518                  * TODO: Prompt the user etc.
    519                  */
    520 
    521                 // TODO: Should we should a popup with a progress bar for user feedback?
    522                 // this would be nice and easy to do.
    523                 // Exit on a dedicated thread so that feedback can be obtained
    524                 new Exiter().start(); // this will exit the application
    525         }
    526 
    527         /**
    528          * The system must exit on a different thread other than the swing thread so
    529          * that the save threads can fire save-feedback to the swing thread and thus
    530          * provide user feedback on asynchronous save operations.
    531          *
    532          * @author Brook Novak
    533          *
    534          */
    535         private class Exiter extends Thread {
    536 
    537                 @Override
    538                 public void run() {
    539 
    540                         // The final save point for saveable entities
    541                         EntitySaveManager.getInstance().saveAll();
    542                         try {
    543                                 EntitySaveManager.getInstance().waitUntilAllSavingFinished();
    544                         } catch (InterruptedException e) {
    545                                 e.printStackTrace();
    546                         }
    547 
    548                         // The final phase must save on the swing thread since dealing with
    549                         // the expeditee data model
    550                         SwingUtilities.invokeLater(new Runnable() {
    551                                 public void run() {
    552 
    553                                         // Stop any agents or simple programs
    554                                         Simple.stop();
    555                                         Actions.stopAgent();
    556                                         // Wait for them to stop
    557                                         try {
    558                                                 MessageBay
    559                                                                 .displayMessage("Stopping Simple programs..."); // TODO:
    560                                                 /**
    561                                                  * Only stop if need to...
    562                                                  */
    563                                                 while (Simple.isProgramRunning()) {
    564                                                         Thread.sleep(100);
    565                                                         /* Brook: What purpose does this serve? */
    566                                                 }
    567                                                 MessageBay.displayMessage("Stopping Agents...");
    568                                                 /* TODO: Only stop if need to... */
    569                                                 while (Actions.isAgentRunning()) {
    570                                                         Thread.sleep(100); // Brook: What purpose does this
    571                                                         // serve?
    572                                                 }
    573                                         } catch (Exception e) {
    574 
    575                                         }
    576 
    577                                         MessageBay.displayMessage("Saving current frame...");
    578                                         FrameIO.SaveFrame(DisplayIO.getCurrentFrame());
    579 
    580                                         MessageBay.displayMessage("Saving stats...");
    581                                         StatsLogger.WriteStatsFile();
    582 
    583                                         if (MailSession.getInstance() != null) {
    584                                                 if (MailSession.getInstance().finalise()) {
    585                                                         // TODO display this message before the finalising
    586                                                         // is done but only if the mail needs closing
    587                                                         MessageBay.displayMessage("Closed ExpMail...");
    588                                                 }
    589                                         }
    590 
    591                                         if (FrameShare.getInstance() != null) {
    592                                                 MessageBay.displayMessage("Stopping FrameServer...");
    593                                                 FrameShare.getInstance().finalise();
    594                                         }
    595 
    596                                         MessageBay.displayMessage("System exited");
    597 
    598                                         // Finally remove the messages frameset
    599                                         FrameIO.moveFrameset("messages", FrameIO.MESSAGES_PATH);
    600 
    601                                         /*
    602                                          * Create a new messages folder so that it doesn't throw
    603                                          * Exceptions when two Expeditee's open at once and the
    604                                          * second tries to save its messages
    605                                          */
    606                                         File file = new File(FrameIO.MESSAGES_PATH + "messages");
    607                                         file.mkdirs();
    608 
    609                                         Browser._hasExited = true;
    610                                        
    611                                         System.exit(0);
    612                                 }
    613                         });
    614                 }
    615         }
    616 
    617         /**
    618          * Used to set up the the browser for use in testing.
    619          *
    620          * @return
    621          */
    622         public static Browser initializeForTesting() {
    623                 if (Browser._theBrowser == null) {
    624                         FrameShare.disableNetworking = true;
    625                         MailSession._autoConnect = false;
    626 
    627                         Browser.main(new String[]{});
    628                         try {
    629                                 while (!isInitComplete()) {
    630                                         Thread.sleep(10);
    631                                 }
    632                         } catch (Exception e) {
    633                         }
    634                 }
    635                 return _theBrowser;
    636         }
    637 
    638522}
  • trunk/src/org/expeditee/gui/ColorUtils.java

    r919 r1102  
    1919package org.expeditee.gui;
    2020
    21 import java.awt.Color;
     21import org.expeditee.core.Colour;
    2222
    2323public class ColorUtils {
     
    3636         * @return the next color on the color wheel
    3737         */
    38         public static Color getNextColor(Color color, Color[] wheel, Color skip) {
     38        public static Colour getNextColor(Colour color, Colour[] wheel, Colour skip) {
    3939                if (color == null) {
    4040                        color = wheel[0];
  • trunk/src/org/expeditee/gui/Frame.java

    r998 r1102  
    1919package org.expeditee.gui;
    2020
    21 import java.awt.Color;
    22 import java.awt.Image;
    23 import java.awt.Polygon;
    24 import java.awt.image.ImageObserver;
    25 import java.awt.image.VolatileImage;
    2621import java.sql.Time;
    2722import java.util.ArrayList;
     
    3732
    3833import org.expeditee.actions.Simple;
     34import org.expeditee.core.Colour;
     35import org.expeditee.core.Image;
     36import org.expeditee.core.bounds.PolygonBounds;
     37import org.expeditee.gio.gesture.StandardGestureActions;
     38import org.expeditee.gio.input.StandardInputEventListeners;
     39import org.expeditee.gio.input.KBMInputEvent.Key;
    3940import org.expeditee.io.Conversion;
    4041import org.expeditee.items.Constraint;
     
    5051import org.expeditee.items.UserAppliedPermission;
    5152import org.expeditee.items.XRayable;
    52 import org.expeditee.items.widgets.InteractiveWidget;
     53import org.expeditee.items.widgets.Widget;
    5354import org.expeditee.items.widgets.WidgetCorner;
    5455import org.expeditee.settings.UserSettings;
     
    6667 *
    6768 */
    68 public class Frame implements ImageObserver {
     69public class Frame {
     70       
     71        /** The frame number to indicate this is a virtual frame. */
     72        public static final int VIRTUAL_FRAME_NUMBER = -1;
     73       
     74        /** The background colour the frame name should take if the frame has user permission level 'none'. */
     75        public static final Colour FRAME_NAME_BACKGROUND_COLOUR_FOR_PERMISSION_NONE = Colour.FromRGB255(255, 220, 220);
     76        /** The background colour the frame name should take if the frame has user permission level 'followLinks'. */
     77        public static final Colour FRAME_NAME_BACKGROUND_COLOUR_FOR_PERMISSION_FOLLOW_LINKS = Colour.FromRGB255(255, 230, 135);
     78        /** The background colour the frame name should take if the frame has user permission level 'copy'. */
     79        public static final Colour FRAME_NAME_BACKGROUND_COLOUR_FOR_PERMISSION_COPY = Colour.FromRGB255(255, 255, 155);
     80        /** The background colour the frame name should take if the frame has user permission level 'createFrames'. */
     81        public static final Colour FRAME_NAME_BACKGROUND_COLOUR_FOR_PERMISSION_CREATE_FRAMES = Colour.FromRGB255(220, 255, 220);
     82        /** The background colour the frame name should take if the frame has user permission level 'full'. */
     83        public static final Colour FRAME_NAME_BACKGROUND_COLOUR_FOR_PERMISSION_FULL = null;
    6984
    7085        private boolean _protectionChanged = false;
    71 
    72         public boolean isReadOnly() {
    73                 return !_frameName.hasPermission(UserAppliedPermission.full)
    74                                 && !_protectionChanged;
    75         }
    7686
    7787        // The various attributes of this Frame
     
    95105
    96106        // Background color is clear
    97         private Color _background = null;
     107        private Colour _background = null;
    98108
    99109        // Foreground color is automatic by default
    100         private Color _foreground = null;
     110        private Colour _foreground = null;
    101111
    102112        private String path;
     
    105115
    106116        private boolean _sorted = true;
    107 
    108         // The items contained in this Frame
    109         // records whether a change has been made to this Frame (for saving
    110         // purposes).
     117       
     118        /** Whether the frame has changed and therefore needs saving. */
    111119        private boolean _change = false;
    112120
     121        /** Whether the frame has been saved. */
    113122        private boolean _saved = false;
    114 
    115         private static final class History {
    116                 public enum Type {
    117                         deletion,
    118                         movement
    119                 }
    120                 public final List<Item> items;
    121                 public final Type type;
    122                
    123                 public History(Collection<Item> items, Type type) {
    124                         this.items = new LinkedList<Item>(items);
    125                         this.type = type;
    126                 }
    127                
    128                 public String toString() {
    129                         return this.type.toString() + ":\n" + this.items.toString();
    130                 }
    131         }
    132123       
    133124        // list of deleted items that can be restored
     
    141132
    142133        // for drawing purposes
    143         private List<InteractiveWidget> _iWidgets = new ArrayList<InteractiveWidget>();
     134        private List<Widget> _iWidgets = new ArrayList<Widget>();
    144135
    145136        private int _lineCount = 0;
     
    170161        private Text _dotTemplate = TemplateSettings.DotTemplate.get().copy();
    171162
    172         /**
    173          * Default constructor, nothing is set.
    174          */
    175         public Frame() {
    176         }
    177 
    178         public void reset() {
     163        Map<String, Text> _annotations = null;
     164
     165        private Collection<FrameObserver> _observers = new HashSet<FrameObserver>();
     166
     167        /** Default constructor, nothing is set. */
     168        public Frame()
     169        {
     170        }
     171
     172        public boolean isReadOnly()
     173        {
     174                return !_frameName.hasPermission(UserAppliedPermission.full) && !_protectionChanged;
     175        }
     176
     177        public void reset()
     178        {
    179179                refreshItemPermissions(UserAppliedPermission.full);
    180                 //System.out.println("Reset");
    181180                resetDot();
    182181                SessionStats.NewFrameSession();
    183182        }
    184183
    185         private void resetDot() {
     184        private void resetDot()
     185        {
    186186            _dotTemplate.setColor(TemplateSettings.ColorWheel.getSafe(1));
    187187            _dotTemplate.setFillColor(TemplateSettings.FillColorWheel.getSafe(0));
    188188        }
    189189
    190         public void nextDot() {
    191                 _dotTemplate.setFillColor(ColorUtils.getNextColor(_dotTemplate
    192                                 .getFillColor(), TemplateSettings.FillColorWheel.get(), null));
    193                 _dotTemplate.setColor(ColorUtils.getNextColor(_dotTemplate.getColor(),
    194                                 TemplateSettings.ColorWheel.get(), null));
    195 
    196                 if (_dotTemplate.getColor() == null || _dotTemplate.getColor().equals(Color.white)) {
    197                         resetDot();
    198                 }
    199         }
    200 
    201         public Image getBuffer() {
     190        public void nextDot()
     191        {
     192                _dotTemplate.setFillColor(ColorUtils.getNextColor(_dotTemplate.getFillColor(), TemplateSettings.FillColorWheel.get(), null));
     193                _dotTemplate.setColor(ColorUtils.getNextColor(_dotTemplate.getColor(), TemplateSettings.ColorWheel.get(), null));
     194                if (_dotTemplate.getColor() == null || _dotTemplate.getColor().equals(Colour.WHITE)) resetDot();
     195        }
     196
     197        public Image getBuffer()
     198        {
    202199                return _buffer;
    203200        }
    204201
    205         public void setBuffer(Image newBuffer) {
     202        public void setBuffer(Image newBuffer)
     203        {
    206204                _buffer = newBuffer;
    207205        }
    208206
    209         public boolean isBufferValid() {
    210                 if (_buffer == null
    211                                 || (_buffer instanceof VolatileImage && ((VolatileImage) _buffer)
    212                                                 .contentsLost()))
    213                         return false;
     207        public boolean isBufferValid()
     208        {
     209                if (_buffer == null) return false;
    214210
    215211                return _validBuffer;
    216212        }
    217213
    218         private void setBufferValid(boolean newValue) {
     214        private void setBufferValid(boolean newValue)
     215        {
    219216                _validBuffer = newValue;
    220217        }
    221218
    222         public int getNextItemID() {
     219        public int getNextItemID()
     220        {
    223221                return ++_itemCount;
    224222        }
    225223
    226         public void updateIDs(List<Item> items) {
    227                 for (Item i : items)
    228                         if (!(i instanceof Line))
     224        public void updateIDs(List<Item> items)
     225        {
     226                for (Item i : items) {
     227                        if (!(i instanceof Line)) {
    229228                                i.setID(getNextItemID());
    230                         else
     229                        } else {
    231230                                i.setID(++_lineCount);
     231                        }
     232                }
    232233        }
    233234
     
    237238         *         Hence it excludes free-widgets. Returns a copy
    238239         */
    239         public List<InteractiveWidget> getInteractiveWidgets() {
    240                 LinkedList<InteractiveWidget> clone = new LinkedList<InteractiveWidget>();
     240        public List<Widget> getInteractiveWidgets()
     241        {
     242                LinkedList<Widget> clone = new LinkedList<Widget>();
    241243                clone.addAll(this._iWidgets);
    242244                return clone;
     
    248250         * @return True if this Frame has been altered, false otherwise.
    249251         */
    250         public boolean hasChanged() {
     252        public boolean hasChanged()
     253        {
    251254                // virtual frames are never saved
    252                 if (_number == -1)
    253                         return false;
     255                if (_number == VIRTUAL_FRAME_NUMBER) return false;
    254256
    255257                return _change;
     
    260262         *
    261263         * @param value
    262          *            False if this Frame should be saved to disk, False otherwise.
    263          */
    264         public void setChanged(boolean value) {
    265                 // System.out.println(getName() + " " + value);
    266                 boolean oldValue = _change;
    267 
    268                 // if (value) {
    269                 // notifyObservers();
    270                 // }
    271 
    272                 if (oldValue == value)
    273                         return;
     264         *            True if this Frame should be saved to disk, False otherwise.
     265         */
     266        public void setChanged(boolean value)
     267        {
     268                if (_change == value) return;
    274269
    275270                _change = value;
     
    281276        }
    282277
    283         // private static int updateCount = 0;
    284 
    285278        /**
    286279         * Notify items observing the data on this frame that the frame content has
     
    290283         *            true if the frame should be recalculated first.
    291284         */
    292         public void notifyObservers(boolean bRecalculate) {
    293                 if (bRecalculate) {
    294                         recalculate();
    295                 }
     285        public void notifyObservers(boolean bRecalculate)
     286        {
     287                if (bRecalculate) recalculate();
    296288                // Notify the frame listeners that the frame has changed
    297289                /*
     
    301293                 * changing this frames observer list.
    302294                 */
    303                 Collection<FrameObserver> observersCopy = new LinkedList<FrameObserver>(
    304                                 _observers);
     295                Collection<FrameObserver> observersCopy = new LinkedList<FrameObserver>(_observers);
    305296                // System.out.println(++updateCount + " update");
    306297
    307298                for (FrameObserver fl : observersCopy) {
    308                         if (/* !Item.isLocked(fl) && */fl.isVisible())
    309                                 fl.update();
     299                        if (fl.isVisible()) fl.update();
    310300                }
    311301        }
    312302
    313303        // indicates the frame has changed
    314         public void change() {
     304        public void change()
     305        {
    315306                setChanged(true);
    316307                _interactableItems.clear();
     
    323314         * @return The list of Item objects that are on this Frame.
    324315         */
    325         public List<Item> getItems(boolean visible) {
     316        public List<Item> getItems(boolean visible)
     317        {
    326318                if (!_sorted) {
    327                         for(int i = 0; i < _body.size();)
    328                                 if(_body.get(i) == null) _body.remove(i);
    329                                 else i++;
     319                        for(int i = 0; i < _body.size();) {
     320                                if(_body.get(i) == null) {
     321                                        _body.remove(i);
     322                                } else {
     323                                        i++;
     324                                }
     325                        }
    330326                        Collections.sort(_body);
    331327                        _sorted = true;
     
    335331
    336332                for (Item i : _body) {
    337                         if (i == null)
    338                                 continue;
     333                        if (i == null) continue;
     334                       
    339335                        if (i.isVisible() || (!visible && !i.isDeleted())) {
    340336                                items.add(i);
     
    345341        }
    346342
    347         public List<Item> getItems() {
     343        /** TODO: Comment. cts16 */
     344        public List<Item> getItems()
     345        {
    348346                return getItems(false);
    349347        }
     
    354352         * @return True if this frame contains i.
    355353         */
    356         public boolean containsItem(Item i) {
    357                 if (i == null)
    358                         throw new NullPointerException("i");
     354        public boolean containsItem(Item i)
     355        {
     356                if (i == null) throw new NullPointerException("i");
     357               
    359358                return _body.contains(i);
    360359        }
     
    372371         * @return the list of body text items.
    373372         */
    374         public List<Text> getBodyTextItems(boolean includeAnnotations) {
     373        public List<Text> getBodyTextItems(boolean includeAnnotations)
     374        {
    375375                List<Text> bodyTextItems = new ArrayList<Text>();
     376               
    376377                for (Item i : getItems(true)) {
    377378                        // only add up normal body text items
    378                         if ((i instanceof Text)
    379                                         && ((includeAnnotations && !((Text) i)
    380                                                         .isSpecialAnnotation()) || !i.isAnnotation())
    381                                         && !i.isLineEnd()) {
     379                        if ((i instanceof Text) && ((includeAnnotations && !((Text) i).isSpecialAnnotation()) || !i.isAnnotation()) && !i.isLineEnd()) {
    382380                                bodyTextItems.add((Text) i);
    383381                        }
    384382                }
     383               
    385384                bodyTextItems.remove(getTitleItem());
    386385
     
    388387        }
    389388
    390         public Collection<Item> getNonAnnotationItems(boolean removeTitle) {
     389        public Collection<Item> getNonAnnotationItems(boolean removeTitle)
     390        {
    391391                Collection<Item> items = new ArrayList<Item>();
    392392                for (Item i : getItems(true)) {
    393393                        // only add up normal body text items
    394                         if (!i.isAnnotation()) {
    395                                 items.add(i);
    396                         }
    397                 }
     394                        if (!i.isAnnotation()) items.add(i);
     395                }
     396               
    398397                if (removeTitle) {
    399398                        items.remove(getTitleItem());
    400399                }
     400               
    401401                return items;
    402402        }
     
    408408         * @return the last non annotation text item.
    409409         */
    410         public Item getLastNonAnnotationTextItem() {
     410        public Item getLastNonAnnotationTextItem()
     411        {
    411412                List<Item> items = getItems();
    412413
     
    431432         *         found.
    432433         */
    433         public Item getItemWithID(int id) {
    434                 for (Item i : _body)
    435                         if (i.getID() == id)
     434        public Item getItemWithID(int id)
     435        {
     436                for (Item i : _body) {
     437                        if (i.getID() == id) {
    436438                                return i;
    437 
     439                        }
     440                }
    438441                return null;
    439442        }
     
    445448         *            The title to assign to this Frame
    446449         */
    447         public void setTitle(String title) {
    448                 if (title == null || title.equals(""))
    449                         return;
     450        public void setTitle(String title)
     451        {
     452                if (title == null || title.equals("")) return;
    450453
    451454                boolean oldchange = _change;
     
    476479                        // title = ItemUtils.StripTagSymbol(title);
    477480                        frameTitle.setText(title);
    478                         // If the @ symbol is followed by numbering or a bullet remove that
    479                         // too
    480                         String autoBulletText = FrameKeyboardActions.getAutoBullet(title);
     481                        // If the @ symbol is followed by numbering or a bullet remove that too
     482                        String autoBulletText = StandardGestureActions.getAutoBullet(title);
    481483                        if (autoBulletText.length() > 0)
    482484                                frameTitle.stripFirstWord();
     
    485487                // Brook: Cannot figure what is going on above... widget annot titles
    486488                // should be stripped always
    487                 if (ItemUtils.startsWithTag(frameTitle, ItemUtils
    488                                 .GetTag(ItemUtils.TAG_IWIDGET))) {
     489                if (ItemUtils.startsWithTag(frameTitle, ItemUtils.GetTag(ItemUtils.TAG_IWIDGET))) {
    489490                        frameTitle.stripFirstWord();
    490491                }
     
    496497        }
    497498
    498         public Text getTitleItem() {
     499        public Text getTitleItem()
     500        {
    499501                List<Item> items = getVisibleItems();
     502               
    500503                for (Item i : items) {
    501                         if (i instanceof Text && i.getX() < UserSettings.TitlePosition.get()
    502                                         && i.getY() < UserSettings.TitlePosition.get())
     504                        if (i instanceof Text && i.getX() < UserSettings.TitlePosition.get() && i.getY() < UserSettings.TitlePosition.get()) {
    503505                                return (Text) i;
     506                        }
    504507                }
    505508
     
    507510        }
    508511
    509         public String getTitle() {
     512        public String getTitle()
     513        {
    510514                Text title = getTitleItem();
    511                 if (title == null)
    512                         return getName();
     515                if (title == null) return getName();
    513516
    514517                return title.getFirstLine();
    515518        }
    516519
    517         public Item getNameItem() {
     520        public Item getNameItem()
     521        {
    518522                return _frameName;
    519523        }
    520524
    521         public Text getItemTemplate() {
    522                 return getTemplate(TemplateSettings.ItemTemplate.get(),
    523                                 ItemUtils.TAG_ITEM_TEMPLATE);
    524         }
    525 
    526         public Text getAnnotationTemplate() {
    527                 Text t = getTemplate(TemplateSettings.AnnotationTemplate.get(),
    528                                 ItemUtils.TAG_ANNOTATION_TEMPLATE);
     525        public Text getItemTemplate()
     526        {
     527                return getTemplate(TemplateSettings.ItemTemplate.get(), ItemUtils.TAG_ITEM_TEMPLATE);
     528        }
     529
     530        public Text getAnnotationTemplate()
     531        {
     532                Text t = getTemplate(TemplateSettings.AnnotationTemplate.get(), ItemUtils.TAG_ANNOTATION_TEMPLATE);
    529533
    530534                if (t == null) {
     
    535539        }
    536540
    537         public Text getStatTemplate() {
     541        public Text getStatTemplate()
     542        {
    538543                SessionStats.CreatedText();
    539                 Text t = getTemplate(TemplateSettings.StatTemplate.get(),
    540                                 ItemUtils.TAG_STAT_TEMPLATE);
     544                Text t = getTemplate(TemplateSettings.StatTemplate.get(), ItemUtils.TAG_STAT_TEMPLATE);
    541545
    542546                if (t == null) {
     
    547551        }
    548552       
    549         public Item getTooltipTextItem(String tooltipText) {
     553        public Item getTooltipTextItem(String tooltipText)
     554        {
    550555                return getTextItem(tooltipText, TemplateSettings.TooltipTemplate.get().copy());
    551556        }
    552557
    553         public Item getStatsTextItem(String itemText) {
     558        public Item getStatsTextItem(String itemText)
     559        {
    554560                return getTextItem(itemText, getStatTemplate());
    555561        }
    556562
    557         public Item getTextItem(String itemText) {
     563        public Item getTextItem(String itemText)
     564        {
    558565                return getTextItem(itemText, getItemTemplate());
    559566        }
    560567
    561         private Item getTextItem(String itemText, Text template) {
     568        private Item getTextItem(String itemText, Text template)
     569        {
    562570                Text t = template;
    563571                // We dont want the stats to wrap at all
    564572                // t.setMaxWidth(Integer.MAX_VALUE);
    565                 t.setPosition(DisplayIO.getMouseX(), FrameMouseActions.getY());
     573                t.setPosition(DisplayController.getMousePosition());
    566574                // The next line is needed to make sure the item is removed from the
    567575                // frame when picked up
     
    571579        }
    572580
    573         public Text getCodeCommentTemplate() {
    574                 Text t = getTemplate(TemplateSettings.CommentTemplate.get(),
    575                                 ItemUtils.TAG_CODE_COMMENT_TEMPLATE);
     581        public Text getCodeCommentTemplate()
     582        {
     583                Text t = getTemplate(TemplateSettings.CommentTemplate.get(), ItemUtils.TAG_CODE_COMMENT_TEMPLATE);
    576584
    577585                if (t == null) {
     
    592600         *         Item.intersects(shape) return true.
    593601         */
    594         public Collection<Item> getItemsWithin(Polygon poly) {
     602        public Collection<Item> getItemsWithin(PolygonBounds poly)
     603        {
    595604                Collection<Item> results = new LinkedHashSet<Item>();
    596605                for (Item i : getVisibleItems()) {
     
    606615                }
    607616
    608                 for (Overlay o : _overlays.keySet())
     617                for (Overlay o : _overlays.keySet()) {
    609618                        results.addAll(o.Frame.getItemsWithin(poly));
    610 
     619                }
     620               
    611621                for (Item i : getVectorItems()) {
    612622                        if (i.intersects(poly)) {
     
    626636         *            The name to use for this Frame.
    627637         */
    628         public void setFrameset(String name) {
     638        public void setFrameset(String name)
     639        {
    629640                _frameset = name;
    630641        }
    631642
    632         public void setName(String framename) {
     643        public void setName(String framename)
     644        {
    633645                int num = Conversion.getFrameNumber(framename);
    634646                String frameset = Conversion.getFramesetName(framename, false);
     
    643655         *            The number to set as the frame number
    644656         */
    645         public void setFrameNumber(int number) {
     657        public void setFrameNumber(int number)
     658        {
    646659                assert (number >= 0);
    647660
    648                 if (_number == number)
    649                         return;
     661                if (_number == number) return;
    650662
    651663                _number = number;
     
    659671                        id = -1 * getNextItemID();
    660672                }
     673               
    661674                _frameName = new Text(id);
    662675                _frameName.setParent(this);
     
    671684         * @return The Frame number of this Frame or -1 if it is not set.
    672685         */
    673         public int getNumber() {
     686        public int getNumber()
     687        {
    674688                return _number;
    675689        }
     
    681695         *            The version to use for this Frame.
    682696         */
    683         public void setVersion(int version) {
     697        public void setVersion(int version)
     698        {
    684699                _version = version;
    685700        }
     
    691706         *            The protection to use for this Frame.
    692707         */
    693         public void setPermission(PermissionPair permission) {
    694                 if (_permissionPair != null && _permissionPair.getPermission(this._owner).equals(permission))
     708        public void setPermission(PermissionPair permission)
     709        {
     710                if (_permissionPair != null && _permissionPair.getPermission(this._owner).equals(permission)) {
    695711                        _protectionChanged = true;
     712                }
    696713
    697714                _permissionPair = new PermissionPair(permission);
    698715
    699                 if (_body.size() > 0)
    700                         refreshItemPermissions(permission.getPermission(_owner));
     716                if (_body.size() > 0) refreshItemPermissions(permission.getPermission(_owner));
    701717        }
    702718
     
    707723         *            The owner to use for this Frame.
    708724         */
    709         public void setOwner(String owner) {
     725        public void setOwner(String owner)
     726        {
    710727                _owner = owner;
    711728        }
     
    717734         *            The date to use for this Frame.
    718735         */
    719         public void setDateCreated(String date) {
     736        public void setDateCreated(String date)
     737        {
    720738                _creationDate = date;
    721739                _modifiedDate = date;
     
    729747         *
    730748         */
    731         public void resetDateCreated() {
     749        public void resetDateCreated()
     750        {
    732751                setDateCreated(Formatter.getDateTime());
    733752                resetTimes();
     
    735754        }
    736755
    737         private void resetTimes() {
     756        private void resetTimes()
     757        {
    738758                setActiveTime(new Time(0));
    739759                setDarkTime(new Time(0));
     
    746766         *            The user to set as the last modifying user.
    747767         */
    748         public void setLastModifyUser(String user) {
     768        public void setLastModifyUser(String user)
     769        {
    749770                _modifiedUser = user;
    750771        }
     
    756777         *            The date to set as the last modified date.
    757778         */
    758         public void setLastModifyDate(String date) {
     779        public void setLastModifyDate(String date)
     780        {
    759781                _modifiedDate = date;
    760782        }
     
    766788         *            The date to set as the last frozen date.
    767789         */
    768         public void setFrozenDate(String date) {
     790        public void setFrozenDate(String date)
     791        {
    769792                _frozenDate = date;
    770793        }
    771794
    772         public void setResort(boolean value) {
     795        public void setResort(boolean value)
     796        {
    773797                _sorted = !value;
    774798        }
     
    780804         *            The Item to add to this Frame.
    781805         */
    782         public void addItem(Item item) {
     806        public void addItem(Item item)
     807        {
    783808                addItem(item, true);
    784809        }
    785810
    786         public void addItem(Item item, boolean recalculate) {
    787                 if (item == null || item.equals(_frameName) || _body.contains(item))
    788                         return;
     811        public void addItem(Item item, boolean recalculate)
     812        {
     813                if (item == null || item.equals(_frameName) || _body.contains(item)) return;
    789814
    790815                // When an annotation item is anchored the annotation list must be
     
    794819                }
    795820
    796                 if (item instanceof Line)
    797                         _lineCount++;
     821                if (item instanceof Line) _lineCount++;
    798822
    799823                _itemCount = Math.max(_itemCount, item.getID());
     
    816840                // add widget items to the list of widgets
    817841                if (item instanceof WidgetCorner) {
    818                         InteractiveWidget iw = ((WidgetCorner) item).getWidgetSource();
     842                        Widget iw = ((WidgetCorner) item).getWidgetSource();
    819843                        if (!this._iWidgets.contains(iw)) { // A set would have been
    820                                 if (FrameMouseActions.isControlDown())
     844                                if (StandardInputEventListeners.kbmStateListener.isKeyDown(Key.CTRL)) {
    821845                                        _iWidgets.add(iw);
    822                                 else
     846                                } else {
    823847                                        _iWidgets.add(0, iw);
    824                         }
    825                 }
    826 
    827                 item.onParentStateChanged(new ItemParentStateChangedEvent(this,
    828                                 ItemParentStateChangedEvent.EVENT_TYPE_ADDED));
     848                                }
     849                        }
     850                }
     851
     852                item.onParentStateChanged(new ItemParentStateChangedEvent(this, ItemParentStateChangedEvent.EVENT_TYPE_ADDED));
    829853
    830854                // if (recalculate && item.recalculateWhenChanged())
     
    834858        }
    835859
    836         public void refreshSize() {
    837                 // assert (size != null);
     860        public void refreshSize()
     861        {
    838862                boolean bReparse = false;
     863               
    839864                for (Item i : getItems()) {
    840                         Float anchorLeft   = i.getAnchorLeft();
    841                         Float anchorRight  = i.getAnchorRight();
    842                         Float anchorTop    = i.getAnchorTop();
    843                         Float anchorBottom = i.getAnchorBottom();
     865                        Integer anchorLeft   = i.getAnchorLeft();
     866                        Integer anchorRight  = i.getAnchorRight();
     867                        Integer anchorTop    = i.getAnchorTop();
     868                        Integer anchorBottom = i.getAnchorBottom();
    844869       
    845870                       
     
    885910        }
    886911
    887         public void addAllItems(Collection<Item> toAdd) {
     912        public void addAllItems(Collection<Item> toAdd)
     913        {
    888914                for (Item i : toAdd) {
    889915                        // If an annotation is being deleted clear the annotation list
    890                         if (i.isAnnotation())
    891                                 i.getParentOrCurrentFrame().clearAnnotations();
     916                        if (i.isAnnotation()) i.getParentOrCurrentFrame().clearAnnotations();
    892917                        // TODO Improve efficiency when addAll is called
    893918                        addItem(i);
     
    895920        }
    896921
    897         public void removeAllItems(Collection<Item> toRemove) {
     922        public void removeAllItems(Collection<Item> toRemove)
     923        {
    898924                for (Item i : toRemove) {
    899925                        // If an annotation is being deleted clear the annotation list
    900                         if (i.isAnnotation())
    901                                 i.getParentOrCurrentFrame().clearAnnotations();
     926                        if (i.isAnnotation()) i.getParentOrCurrentFrame().clearAnnotations();
    902927                        removeItem(i);
    903928                }
    904929        }
    905930
    906         public void removeItem(Item item) {
     931        public void removeItem(Item item)
     932        {
    907933                removeItem(item, true);
    908934        }
    909935
    910         public void removeItem(Item item, boolean recalculate) {
     936        public void removeItem(Item item, boolean recalculate)
     937        {
    911938                // If an annotation is being deleted clear the annotation list
    912                 if (item.isAnnotation())
    913                         item.getParentOrCurrentFrame().clearAnnotations();
     939                if (item.isAnnotation()) item.getParentOrCurrentFrame().clearAnnotations();
    914940
    915941                if (_body.remove(item)) {
     
    917943                        // Remove widgets from the widget list
    918944                        if (item != null) {
    919                                 item.onParentStateChanged(new ItemParentStateChangedEvent(this,
    920                                                 ItemParentStateChangedEvent.EVENT_TYPE_REMOVED));
     945                                item.onParentStateChanged(new ItemParentStateChangedEvent(this, ItemParentStateChangedEvent.EVENT_TYPE_REMOVED));
     946                               
    921947                                if (item instanceof WidgetCorner) {
    922948                                        _iWidgets.remove(((WidgetCorner) item).getWidgetSource());
    923949                                }
     950                               
    924951                                item.invalidateCommonTrait(ItemAppearence.Removed);
    925952                        }
     
    937964         * @param type  The type of event that occurred
    938965         */
    939         private void addToUndo(Collection<Item> items, History.Type type) {
    940                 if (items.size() < 1)
    941                         return;
    942                
    943                 // System.out.println("Added: " + items);
     966        private void addToUndo(Collection<Item> items, History.Type type)
     967        {
     968                if (items.size() < 1) return;
    944969
    945970                _undo.push(new History(items, type));
    946971        }
    947972       
    948         public void addToUndoDelete(Collection<Item> items) {
     973        public void addToUndoDelete(Collection<Item> items)
     974        {
    949975                addToUndo(items, History.Type.deletion);
    950976        }
    951         public void addToUndoMove(Collection<Item> items) {
     977       
     978        public void addToUndoMove(Collection<Item> items)
     979        {
    952980                addToUndo(items, History.Type.movement);
    953981        }
    954982
    955         public void undo() {
     983        public void undo()
     984        {
    956985                boolean bReparse = false;
    957986                boolean bRecalculate = false;
    958987
    959                 if (_undo.size() <= 0)
    960                         return;
     988                if (_undo.size() <= 0) return;
    961989
    962990                History undo = _undo.pop();
     
    9921020                        break;
    9931021                }
     1022               
    9941023                change();
    995                 FrameMouseActions.getInstance().refreshHighlights();
     1024               
     1025                StandardGestureActions.refreshHighlights();
     1026               
    9961027                if (bReparse) {
    9971028                        FrameUtils.Parse(this, false, false);
     
    9991030                        notifyObservers(bRecalculate);
    10001031                }
     1032               
    10011033                // always request a refresh otherwise filled shapes
    10021034                // that were broken by a deletion and then reconnected by the undo
    10031035                // don't get filled until the user otherwise causes them to redraw
    1004                 FrameGraphics.requestRefresh(false);
    1005                 FrameGraphics.Repaint();
     1036                DisplayController.requestRefresh(false);
    10061037                // ItemUtils.EnclosedCheck(_body);
    10071038                ItemUtils.Justify(this);
    10081039        }
    10091040       
    1010         public void redo() {
     1041        public void redo()
     1042        {
    10111043                boolean bReparse = false;
    10121044                boolean bRecalculate = false;
    10131045
    1014                 if (_redo.size() <= 0)
    1015                         return;
     1046                if (_redo.size() <= 0) return;
    10161047
    10171048                History redo = _redo.pop();
     
    10471078                        break;
    10481079                }
     1080               
    10491081                change();
    1050                 FrameMouseActions.getInstance().refreshHighlights();
     1082               
     1083                StandardGestureActions.refreshHighlights();
     1084               
    10511085                if (bReparse) {
    10521086                        FrameUtils.Parse(this, false, false);
     
    10541088                        notifyObservers(bRecalculate);
    10551089                }
     1090               
    10561091                // always request a refresh otherwise filled shapes
    10571092                // that were broken by a deletion and then reconnected by the undo
    10581093                // don't get filled until the user otherwise causes them to redraw
    1059                 FrameGraphics.requestRefresh(false);
    1060                 FrameGraphics.Repaint();
     1094                DisplayController.requestRefresh(false);
    10611095                // ItemUtils.EnclosedCheck(_body);
    10621096                ItemUtils.Justify(this);
     
    10681102         * @return The name of this Frame's frameset.
    10691103         */
    1070         public String getFramesetName() {
     1104        public String getFramesetName()
     1105        {
    10711106                return _frameset;
    10721107        }
    10731108
    1074         public String getName() {
     1109        public String getName()
     1110        {
    10751111                return getFramesetName() + _number;
    10761112        }
     
    10811117         * @return The version of this Frame.
    10821118         */
    1083         public int getVersion() {
     1119        public int getVersion()
     1120        {
    10841121                return _version;
    10851122        }
    10861123
    1087         public PermissionPair getPermission() {
     1124        public PermissionPair getPermission()
     1125        {
    10881126                return _permissionPair;
    10891127        }
    10901128       
    1091         public UserAppliedPermission getUserAppliedPermission() {
     1129        public UserAppliedPermission getUserAppliedPermission()
     1130        {
    10921131                return getUserAppliedPermission(UserAppliedPermission.full);
    10931132        }
    10941133
    1095         public UserAppliedPermission getUserAppliedPermission(UserAppliedPermission defaultPermission) {
    1096                 if (_permissionPair == null)
    1097                         return defaultPermission;
     1134        public UserAppliedPermission getUserAppliedPermission(UserAppliedPermission defaultPermission)
     1135        {
     1136                if (_permissionPair == null) return defaultPermission;
    10981137
    10991138                return _permissionPair.getPermission(_owner);
    11001139        }
    11011140
    1102        
    1103         public String getOwner() {
     1141        public String getOwner()
     1142        {
    11041143                return _owner;
    11051144        }
    11061145
    1107         public String getDateCreated() {
     1146        public String getDateCreated()
     1147        {
    11081148                return _creationDate;
    11091149        }
    11101150
    1111         public String getLastModifyUser() {
     1151        public String getLastModifyUser()
     1152        {
    11121153                return _modifiedUser;
    11131154        }
    11141155
    1115         public String getLastModifyDate() {
     1156        public String getLastModifyDate()
     1157        {
    11161158                return _modifiedDate;
    11171159        }
    11181160
    1119         public String getFrozenDate() {
     1161        public String getFrozenDate()
     1162        {
    11201163                return _frozenDate;
    11211164        }
    11221165
    1123         public void setBackgroundColor(Color back) {
     1166        public void setBackgroundColor(Colour back)
     1167        {
    11241168                _background = back;
     1169               
    11251170                change();
    11261171
    1127                 if (this == DisplayIO.getCurrentFrame()) {
    1128                         FrameGraphics.refresh(false);
    1129                 }
    1130         }
    1131 
    1132         public Color getBackgroundColor() {
     1172                if (this == DisplayController.getCurrentFrame()) {
     1173                        DisplayController.requestRefresh(false);
     1174                }
     1175        }
     1176
     1177        public Colour getBackgroundColor()
     1178        {
    11331179                return _background;
    11341180        }
    11351181
    1136         public Color getPaintBackgroundColor() {
     1182        public Colour getPaintBackgroundColor()
     1183        {
    11371184                // If null... return white
    11381185                if (_background == null) {
     
    11431190        }
    11441191
    1145         public void setForegroundColor(Color front) {
     1192        public void setForegroundColor(Colour front)
     1193        {
    11461194                _foreground = front;
     1195               
    11471196                change();
    1148                 // FrameGraphics.Repaint();
    1149         }
    1150 
    1151         public Color getForegroundColor() {
     1197        }
     1198
     1199        public Colour getForegroundColor()
     1200        {
    11521201                return _foreground;
    11531202        }
    11541203
    1155         public Color getPaintForegroundColor() {
    1156                 final int GRAY = Color.gray.getBlue();
    1157                 final int THRESHOLD = 10;
     1204        public Colour getPaintForegroundColor()
     1205        {
     1206                final int GRAY = Colour.GREY.getBlue();
     1207                final int THRESHOLD = Colour.FromComponent255(10);
    11581208
    11591209                if (_foreground == null) {
    1160                         Color back = getPaintBackgroundColor();
     1210                        Colour back = getPaintBackgroundColor();
    11611211                        if (Math.abs(back.getRed() - GRAY) < THRESHOLD
    11621212                                        && Math.abs(back.getBlue() - GRAY) < THRESHOLD
    11631213                                        && Math.abs(back.getGreen() - GRAY) < THRESHOLD)
    1164                                 return Color.WHITE;
    1165 
    1166                         Color fore = new Color(
    1167                                         Math.abs(Conversion.RGB_MAX - back.getRed()), Math
    1168                                                         .abs(Conversion.RGB_MAX - back.getGreen()), Math
    1169                                                         .abs(Conversion.RGB_MAX - back.getBlue()));
     1214                        {
     1215                                return Colour.WHITE;
     1216                        }
     1217                       
     1218                        Colour fore = back.inverse();
     1219                       
    11701220                        return fore;
    11711221                }
     
    11741224        }
    11751225
    1176         public String toString() {
     1226        public String toString()
     1227        {
    11771228                StringBuilder s = new StringBuilder();
    11781229                s.append(String.format("Name: %s%d%n", _frameset, _number));
     
    11871238        }
    11881239
    1189         public Text getTextAbove(Text current) {
     1240        public Text getTextAbove(Text current)
     1241        {
    11901242                Collection<Text> currentTextItems = FrameUtils.getCurrentTextItems();
    11911243                List<Text> toCheck = new ArrayList<Text>();
     1244               
    11921245                if (currentTextItems.contains(current)) {
    11931246                        toCheck.addAll(currentTextItems);
     
    11951248                        toCheck.addAll(getTextItems());
    11961249                }
     1250               
    11971251                // Make sure the items are sorted
    11981252                Collections.sort(toCheck);
    11991253
    12001254                int ind = toCheck.indexOf(current);
    1201                 if (ind == -1)
    1202                         return null;
     1255                if (ind == -1) return null;
    12031256
    12041257                // loop through all items above this one, return the first match
    12051258                for (int i = ind - 1; i >= 0; i--) {
    12061259                        Text check = toCheck.get(i);
    1207                         if (FrameUtils.inSameColumn(check, current))
    1208                                 return check;
     1260                        if (FrameUtils.inSameColumn(check, current)) return check;
    12091261                }
    12101262
    12111263                return null;
    12121264        }
    1213 
    1214         /**
    1215          * Updates any Images that require it from their ImageObserver (Principally
    1216          * Animated GIFs)
    1217          */
    1218         public boolean imageUpdate(Image img, int infoflags, int x, int y,
    1219                         int width, int height) {
    1220                 FrameGraphics.ForceRepaint();
    1221 
    1222                 if (DisplayIO.getCurrentFrame() == this)
    1223                         return true;
    1224 
    1225                 return false;
    1226         }
    1227 
     1265       
    12281266        /**
    12291267         * Gets the text items that are in the same column and below a specified
     
    12331271         *            The Item to get the column for.
    12341272         */
    1235         public List<Text> getColumn(Item from) {
     1273        public List<Text> getColumn(Item from)
     1274        {
    12361275                // Check that this item is on the current frame
    1237                 if (!_body.contains(from))
    1238                         return null;
     1276                if (!_body.contains(from)) return null;
    12391277
    12401278                if (from == null) {
     
    12421280                }
    12431281
    1244                 if (from == null)
    1245                         return null;
     1282                if (from == null) return null;
    12461283
    12471284                // Get the enclosedItems
    12481285                Collection<Text> enclosed = FrameUtils.getCurrentTextItems();
    12491286                List<Text> toCheck = null;
     1287               
    12501288                if (enclosed.contains(from)) {
    12511289                        toCheck = new ArrayList<Text>();
     
    12561294
    12571295                List<Text> column = new ArrayList<Text>();
     1296               
    12581297                if (toCheck.size() > 0) {
    1259 
    12601298                        // Make sure the items are sorted
    12611299                        Collections.sort(toCheck);
     
    12661304
    12671305                        // If its the title index will be 0
    1268                         if (index < 0)
    1269                                 index = 0;
     1306                        if (index < 0) index = 0;
    12701307
    12711308                        for (int i = index; i < toCheck.size(); i++) {
    12721309                                Text item = toCheck.get(i);
    1273                                 if (FrameUtils.inSameColumn(from, item))
    1274                                         column.add(item);
     1310                                if (FrameUtils.inSameColumn(from, item)) column.add(item);
    12751311                        }
    12761312                }
     
    12891325         *             If overlay is null.
    12901326         */
    1291         protected boolean addVector(Vector toAdd) {
     1327        protected boolean addVector(Vector toAdd)
     1328        {
    12921329                // make sure we dont add this frame as an overlay of itself
    1293                 if (toAdd.Frame == this)
    1294                         return false;
     1330                if (toAdd.Frame == this) return false;
     1331               
    12951332                _vectors.add(toAdd);
     1333               
    12961334                // Items must be notified that they have been added or removed from this
    12971335                // frame via the vector...
    12981336                int maxX = 0;
    12991337                int maxY = 0;
     1338               
    13001339                HighlightMode mode = toAdd.Source.getHighlightMode();
    1301                 if (mode != HighlightMode.None)
    1302                         mode = HighlightMode.Connected;
    1303                 Color highlightColor = toAdd.Source.getHighlightColor();
     1340                if (mode != HighlightMode.None) mode = HighlightMode.Connected;
     1341               
     1342                Colour highlightColor = toAdd.Source.getHighlightColor();
     1343               
    13041344                for (Item i : ItemUtils.CopyItems(toAdd.Frame.getVectorItems(), toAdd)) {
    1305                         i.onParentStateChanged(new ItemParentStateChangedEvent(this,
    1306                                         ItemParentStateChangedEvent.EVENT_TYPE_ADDED_VIA_OVERLAY,
    1307                                         toAdd.permission));
     1345                        i.onParentStateChanged(new ItemParentStateChangedEvent(this, ItemParentStateChangedEvent.EVENT_TYPE_ADDED_VIA_OVERLAY, toAdd.permission));
    13081346                        i.setEditTarget(toAdd.Source);
    1309                         i.setHighlightMode(mode, highlightColor);
     1347                        i.setHighlightModeAndColour(mode, highlightColor);
    13101348                        _vectorItems.add(i);
    13111349                        i.invalidateAll();
    13121350                        i.invalidateFill();
     1351                       
    13131352                        // Get the right most x and bottom most y pos
    13141353                        int itemRight = i.getX() + i.getBoundsWidth();
    1315                         if (itemRight > maxX)
    1316                                 maxX = itemRight;
     1354                        if (itemRight > maxX) maxX = itemRight;
     1355                       
    13171356                        int itemBottom = i.getY() + i.getBoundsHeight();
    1318                         if (itemBottom > maxY)
    1319                                 maxY = itemBottom;
    1320                 }
     1357                        if (itemBottom > maxY) maxY = itemBottom;
     1358                }
     1359               
    13211360                toAdd.setSize(maxX, maxY);
     1361               
    13221362                return true;
    13231363        }
    13241364
    1325         public Collection<Vector> getVectors() {
     1365        public Collection<Vector> getVectors()
     1366        {
    13261367                Collection<Vector> l = new LinkedList<Vector>();
    13271368                l.addAll(_vectors);
     
    13291370        }
    13301371
    1331         public Collection<Overlay> getOverlays() {
     1372        public Collection<Overlay> getOverlays()
     1373        {
    13321374                return new LinkedList<Overlay>(_overlays.keySet());
    13331375        }
    13341376
    13351377        /**
    1336          * @return All vectosr seen by this frame (including its vector's vectors).
    1337          */
    1338         public List<Vector> getVectorsDeep() {
     1378         * @return All vectors seen by this frame (including its vector's vectors).
     1379         */
     1380        public List<Vector> getVectorsDeep()
     1381        {
    13391382                List<Vector> l = new LinkedList<Vector>();
    13401383                getVectorsDeep(l, this, new LinkedList<Frame>());
     
    13421385        }
    13431386
    1344         private boolean getVectorsDeep(List<Vector> vectors, Frame vector,
    1345                         List<Frame> seenVectors) {
    1346 
    1347                 if (seenVectors.contains(vector))
    1348                         return false;
     1387        private boolean getVectorsDeep(List<Vector> vectors, Frame vector, List<Frame> seenVectors)
     1388        {
     1389                if (seenVectors.contains(vector)) return false;
    13491390
    13501391                seenVectors.add(vector);
    13511392
    1352                 for (Vector o : vector.getVectors()) {
    1353                         if (getVectorsDeep(vectors, o.Frame, seenVectors)) {
    1354                                 vectors.add(o);
     1393                for (Vector v : vector.getVectors()) {
     1394                        if (getVectorsDeep(vectors, v.Frame, seenVectors)) {
     1395                                vectors.add(v);
    13551396                        }
    13561397                }
     
    13591400        }
    13601401
    1361         // private boolean getOverlaysDeep(List<Overlay> overlays, Frame overlay,
    1362         // List<Frame> seenOverlays) {
    1363         //
    1364         // if (seenOverlays.contains(overlay))
    1365         // return false;
    1366         //
    1367         // seenOverlays.add(overlay);
    1368         //
    1369         // for (Overlay o : overlay.getOverlays()) {
    1370         // if (getOverlaysDeep(overlays, o.Frame, seenOverlays)) {
    1371         // overlays.add(o);
    1372         // }
    1373         // }
    1374         //
    1375         // return true;
    1376         // }
     1402        public List<Overlay> getOverlaysDeep()
     1403        {
     1404                List<Overlay> ret = new LinkedList<Overlay>();
     1405               
     1406                getOverlaysDeep(ret, new LinkedList<Frame>());
     1407               
     1408                return ret;
     1409        }
     1410       
     1411        private boolean getOverlaysDeep(List<Overlay> overlays, List<Frame> seenOverlays)
     1412        {
     1413                if (seenOverlays.contains(this)) return false;
     1414               
     1415                seenOverlays.add(this);
     1416               
     1417                for (Overlay o : this.getOverlays()) {
     1418                        if (o.Frame.getOverlaysDeep(overlays, seenOverlays)) {
     1419                                overlays.add(o);
     1420                        }
     1421                }
     1422                return true;
     1423        }
     1424       
     1425        /**
     1426         * Recursive function similar to AddAllOverlayItems.
     1427         *
     1428         * @param widgets
     1429         *            The collection the widgets will be added to
     1430         * @param overlay
     1431         *            An "overlay" frame - this initially will be the parent frame
     1432         * @param seenOverlays
     1433         *            Used for state in the recursion stack. Pass as an empty
     1434         *            (non-null) list.
     1435         */
     1436        public List<Widget> getAllOverlayWidgets()
     1437        {
     1438                List<Widget> widgets = new LinkedList<Widget>();
     1439               
     1440                for (Overlay o : getOverlaysDeep()) widgets.addAll(o.Frame.getInteractiveWidgets());
     1441               
     1442                return widgets;
     1443        }
    13771444
    13781445        /**
     
    13811448         * @param item
    13821449         *            The item - must not be null.
    1383          * @return The overlay that contains the itm. Null if no overlay owns the
     1450         * @return The overlay that contains the item. Null if no overlay owns the
    13841451         *         item.
    13851452         */
    1386         public Overlay getOverlayOwner(Item item) {
    1387                 if (item == null)
    1388                         throw new NullPointerException("item");
     1453        public Overlay getOverlayOwner(Item item)
     1454        {
     1455                if (item == null) throw new NullPointerException("item");
    13891456
    13901457                for (Overlay l : getOverlays()) {
    1391                         if (item.getParent() == l.Frame)
    1392                                 return l;
     1458                        if (item.getParent() == l.Frame) return l;
    13931459                }
    13941460
    13951461                // TODO return the correct vector... not just the first vector matching
    1396                 // the vectorFrame
     1462                // the vector frame
    13971463                for (Vector v : getVectors()) {
    1398                         if (item.getParent() == v.Frame)
    1399                                 return v;
     1464                        if (item.getParent() == v.Frame) return v;
    14001465                }
    14011466
     
    14031468        }
    14041469
    1405         public void clearVectors() {
     1470        public void clearVectors()
     1471        {
    14061472                _vectors.clear();
    14071473
     
    14141480        }
    14151481
    1416         protected boolean removeVector(Vector toRemove) {
    1417                 if (!_vectors.remove(toRemove))
    1418                         return false;
     1482        protected boolean removeVector(Vector toRemove)
     1483        {
     1484                if (!_vectors.remove(toRemove)) return false;
     1485               
    14191486                for (Item i : toRemove.Frame.getVectorItems()) {
    14201487                        i.invalidateAll();
     
    14261493
    14271494                }
     1495               
    14281496                return true;
    14291497        }
    14301498
    1431         public void clearOverlays() {
     1499        public void clearOverlays()
     1500        {
    14321501                for (Overlay o : _overlays.keySet()) {
    14331502                        for (Item i : o.Frame.getItems()) {
    1434                                 i
    1435                                                 .onParentStateChanged(new ItemParentStateChangedEvent(
     1503                                i.onParentStateChanged(new ItemParentStateChangedEvent(
    14361504                                                                this,
    14371505                                                                ItemParentStateChangedEvent.EVENT_TYPE_REMOVED_VIA_OVERLAY,
     
    14441512        }
    14451513
    1446         protected boolean removeOverlay(Frame f) {
     1514        protected boolean removeOverlay(Frame f)
     1515        {
    14471516                for (Overlay o : _overlays.keySet()) {
    14481517                        if (o.Frame == f) {
    14491518                                _overlays.remove(o);
     1519                               
    14501520                                for (Item i : f.getItems()) {
    14511521                                        _overlayItems.remove(i);
    1452                                         i
    1453                                                         .onParentStateChanged(new ItemParentStateChangedEvent(
     1522                                        i.onParentStateChanged(new ItemParentStateChangedEvent(
    14541523                                                                        this,
    14551524                                                                        ItemParentStateChangedEvent.EVENT_TYPE_REMOVED_VIA_OVERLAY,
    14561525                                                                        o.permission));
    14571526                                }
     1527                               
    14581528                                return true;
    14591529                        }
    14601530                }
     1531               
    14611532                return false;
    14621533        }
    14631534
    1464         public void addAllVectors(List<Vector> vectors) {
     1535        public void addAllVectors(List<Vector> vectors)
     1536        {
    14651537                for (Vector v : vectors) {
    14661538                        addVector(v);
     
    14681540        }
    14691541
    1470         public void addAllOverlays(Collection<Overlay> overlays) {
     1542        public void addAllOverlays(Collection<Overlay> overlays)
     1543        {
    14711544                for (Overlay o : overlays) {
    14721545                        addOverlay(o);
     
    14741547        }
    14751548
    1476         protected boolean addOverlay(Overlay toAdd) {
     1549        protected boolean addOverlay(Overlay toAdd)
     1550        {
    14771551                // make sure we dont add this frame as an overlay of itself
    1478                 if (toAdd.Frame == this)
    1479                         return false;
     1552                if (toAdd.Frame == this) return false;
     1553               
    14801554                // Dont add the overlay if there is already one for this frame
    1481                 if (_overlays.values().contains(toAdd.Frame))
    1482                         return false;
     1555                if (_overlays.values().contains(toAdd.Frame)) return false;
     1556               
    14831557                // Add the overlay to the map of overlays on this frame
    14841558                _overlays.put(toAdd, toAdd.Frame);
     1559               
    14851560                // Add all the overlays from the overlay frame to this frame
    1486                 for (Overlay o : toAdd.Frame.getOverlays())
    1487                         addOverlay(o);
     1561                // TODO: Can this cause a recursion loop? If A and B are overlays of each other? cts16
     1562                for (Overlay o : toAdd.Frame.getOverlays()) addOverlay(o);
    14881563
    14891564                // Add all the vectors from the overlay frame to this frame
    1490                 for (Vector v : toAdd.Frame.getVectors())
    1491                         addVector(v);
     1565                for (Vector v : toAdd.Frame.getVectors()) addVector(v);
    14921566
    14931567                // Now add the items for this overlay
    1494                 UserAppliedPermission permission = UserAppliedPermission.min(toAdd.Frame.getUserAppliedPermission(),toAdd.permission);
     1568                UserAppliedPermission permission = UserAppliedPermission.min(toAdd.Frame.getUserAppliedPermission(), toAdd.permission);
    14951569
    14961570                // Items must be notified that they have been added or removed from this
    14971571                // frame via the overlay...
    14981572                for (Item i : toAdd.Frame.getVisibleItems()) {
    1499                         i.onParentStateChanged(new ItemParentStateChangedEvent(this,
    1500                                         ItemParentStateChangedEvent.EVENT_TYPE_ADDED_VIA_OVERLAY,
    1501                                         permission));
    1502                         // i.setPermission(permission);
     1573                        i.onParentStateChanged(new ItemParentStateChangedEvent(this, ItemParentStateChangedEvent.EVENT_TYPE_ADDED_VIA_OVERLAY, permission));
    15031574                        _overlayItems.add(i);
    15041575                }
     
    15081579
    15091580        @Override
    1510         public boolean equals(Object o) {
     1581        public boolean equals(Object o)
     1582        {
    15111583                if (o instanceof String) {
    1512                         return (String.CASE_INSENSITIVE_ORDER
    1513                                         .compare((String) o, getName()) == 0);
     1584                        return (String.CASE_INSENSITIVE_ORDER.compare((String) o, getName()) == 0);
    15141585                }
    15151586
     
    15261597         * @param toMergeWith
    15271598         */
    1528         private void merge(Frame toMergeWith) {
    1529                 if (toMergeWith == null)
    1530                         return;
     1599        private void merge(Frame toMergeWith)
     1600        {
     1601                if (toMergeWith == null) return;
    15311602
    15321603                List<Item> copies = ItemUtils.CopyItems(toMergeWith.getItems());
     
    15481619         * @return the items that cant be merged
    15491620         */
    1550         public List<Item> merge(List<Item> toMerge) {
     1621        public List<Item> merge(List<Item> toMerge)
     1622        {
    15511623                ArrayList<Item> remain = new ArrayList<Item>(0);
    15521624
    15531625                for (Item i : toMerge) {
    1554                         if (!(i instanceof Text))
     1626                        if (!(i instanceof Text)) {
    15551627                                remain.add(i);
    1556                         else {
     1628                        } else {
    15571629                                if (!AttributeUtils.setAttribute(this, (Text) i)) {
    1558                                         if (i.getLink() != null)
     1630                                        if (i.getLink() != null) {
    15591631                                                merge(FrameIO.LoadFrame(i.getAbsoluteLink()));
    1560                                         else if (FrameIO
    1561                                                         .isValidFrameName(((Text) i).getFirstLine())) {
     1632                                        } else if (FrameIO.isValidFrameName(((Text) i).getFirstLine())) {
    15621633                                                // If we get hear we are merging frames
    15631634                                                merge(FrameIO.LoadFrame(((Text) i).getFirstLine()));
     
    15741645         * items are added to the backup-stack.
    15751646         */
    1576         public void clear(boolean keepAnnotations) {
     1647        public void clear(boolean keepAnnotations)
     1648        {
    15771649                List<Item> newBody = new ArrayList<Item>(0);
     1650               
    15781651                Item title = getTitleItem();
     1652               
    15791653                if (title != null) {
    15801654                        newBody.add(title);
    15811655                        _body.remove(title);
    15821656                }
     1657               
    15831658                if (keepAnnotations) {
    15841659                        for (Item i : _body) {
    1585                                 if (i.isAnnotation())
    1586                                         newBody.add(i);
    1587                         }
    1588                 }
     1660                                if (i.isAnnotation()) newBody.add(i);
     1661                        }
     1662                }
     1663               
    15891664                _body.removeAll(newBody);
    15901665                addToUndoDelete(_body);
     
    15921667                change();
    15931668
    1594                 if (!keepAnnotations && _annotations != null)
    1595                         _annotations.clear();
     1669                if (!keepAnnotations && _annotations != null) _annotations.clear();
    15961670        }
    15971671
     
    16021676         * @return
    16031677         */
    1604         public Text createNewText(String text) {
     1678        public Text createNewText(String text)
     1679        {
    16051680                Text t = createBlankText(text);
    16061681                t.setText(text);
     
    16151690         * @return The newly created Text Item
    16161691         */
    1617         public Text createBlankText(String templateType) {
     1692        public Text createBlankText(String templateType)
     1693        {
    16181694                SessionStats.CreatedText();
    16191695                Text t;
    1620                 if (templateType.length() == 0)
     1696               
     1697                if (templateType.length() == 0) {
    16211698                        t = getItemTemplate().copy();
    1622                 else
     1699                } else {
    16231700                        t = getItemTemplate(templateType.charAt(0));
    1624 
     1701                }
     1702               
    16251703                // reset attributes
    16261704                t.setID(getNextItemID());
    1627                 t.setPosition(DisplayIO.getMouseX(), FrameMouseActions.getY());
     1705                t.setPosition(DisplayController.getMousePosition());
    16281706                t.setText("");
    16291707                t.setParent(this);
     
    16481726        }
    16491727
    1650         public Item createDot() {
    1651                 Item dot = new Dot(DisplayIO.getMouseX(), FrameMouseActions.getY(),
    1652                                 getNextItemID());
     1728        public Item createDot()
     1729        {
     1730                Item dot = new Dot(DisplayController.getMouseX(), DisplayController.getMouseY(), getNextItemID());
    16531731
    16541732                Item template = getTemplate(_dotTemplate, ItemUtils.TAG_DOT_TEMPLATE);
    16551733                float thickness = template.getThickness();
    1656                 if (thickness > 0)
    1657                         dot.setThickness(template.getThickness());
    1658                 if (template.getLinePattern() != null)
    1659                         dot.setLinePattern(template.getLinePattern());
     1734                if (thickness > 0) dot.setThickness(template.getThickness());
     1735                if (template.getLinePattern() != null) dot.setLinePattern(template.getLinePattern());
    16601736                dot.setColor(template.getColor());
    16611737                dot.setFillColor(template.getFillColor());
     
    16651741        }
    16661742
    1667         private Text getTemplate(Text defaultTemplate, int templateTag) {
     1743        private Text getTemplate(Text defaultTemplate, int templateTag)
     1744        {
    16681745                Text t = null;
    16691746
     
    16771754
    16781755                if (t == null) {
    1679                         if (defaultTemplate == null) {
    1680                                 return null;
    1681                         }
     1756                        if (defaultTemplate == null) return null;
     1757                       
    16821758                        t = defaultTemplate;
    16831759                }
     
    16851761                // If the item is linked apply any attribute pairs on the child frame
    16861762                String link = t.getAbsoluteLink();
     1763               
    16871764                // need to get link first because copy doesnt copy the link
    16881765                t = t.copy();
     
    17011778        }
    17021779
    1703         public Text getItemTemplate(char firstChar) {
     1780        /**
     1781         * TODO: Comment. cts16
     1782         * TODO: Remove magic constants. cts16
     1783         */
     1784        public Text getItemTemplate(char firstChar)
     1785        {
    17041786                switch (firstChar) {
    1705                 case '@':
    1706                         return getAnnotationTemplate();
    1707                 case '/':
    1708                 case '#':
    1709                         return getCodeCommentTemplate();
    1710                 default:
    1711                         return getItemTemplate();
    1712                 }
    1713         }
    1714 
    1715         public Text createNewText() {
     1787                        case '@':
     1788                                return getAnnotationTemplate();
     1789                        case '/':
     1790                        case '#':
     1791                                return getCodeCommentTemplate();
     1792                        default:
     1793                                return getItemTemplate();
     1794                }
     1795        }
     1796
     1797        public Text createNewText()
     1798        {
    17161799                return createNewText("");
    17171800        }
    17181801
    1719         public Text addText(int x, int y, String text, String action) {
     1802        public Text addText(int x, int y, String text, String action)
     1803        {
    17201804                Text t = createNewText(text);
    17211805                t.setPosition(x, y);
     
    17241808        }
    17251809
    1726         public Item addText(int x, int y, String text, String action, String link) {
    1727                 Item t = addText(x, y, text, action);
     1810        public Text addText(int x, int y, String text, String action, String link)
     1811        {
     1812                Text t = addText(x, y, text, action);
    17281813                t.setLink(link);
    17291814                return t;
    17301815        }
    17311816
    1732         public Item addDot(int x, int y) {
    1733                 Item d = new Dot(x, y, getNextItemID());
     1817        public Dot addDot(int x, int y)
     1818        {
     1819                Dot d = new Dot(x, y, getNextItemID());
    17341820                addItem(d);
    17351821                return d;
     
    17541840         *            Color to fill the rectangle with
    17551841         */
    1756         public List<Item> addRectangle(int x, int y, int width, int height, float borderThickness, Color borderColor, Color fillColor) {
     1842        public List<Item> addRectangle(int x, int y, int width, int height, float borderThickness, Colour borderColor, Colour fillColor)
     1843        {
    17571844                List<Item> rectComponents = new ArrayList<Item>();
    17581845                Item[] corners = new Item[4];
     
    17961883                List<Item> rect = new ArrayList<Item>(rectComponents);
    17971884                this.addAllItems(rectComponents);
    1798                 FrameMouseActions.anchor(rectComponents);
     1885                StandardGestureActions.anchor(rectComponents);
    17991886                return rect;
    1800                 // rectComponents.clear();
    1801         }
    1802 
    1803         public boolean isSaved() {
     1887        }
     1888
     1889        public boolean isSaved()
     1890        {
    18041891                return _saved;
    18051892        }
    18061893
    1807         public void setSaved() {
    1808                 // System.out.println(getName() + " saved");
     1894        public void setSaved()
     1895        {
    18091896                _saved = true;
    18101897                _change = false;
    18111898        }
    18121899
    1813         public static boolean rubberbandingLine() {
    1814                 return FreeItems.getInstance().size() == 2
    1815                                 && (FreeItems.getInstance().get(0) instanceof Line || FreeItems
    1816                                                 .getInstance().get(1) instanceof Line);
     1900        public static boolean rubberbandingLine()
     1901        {
     1902                return  FreeItems.getInstance().size() == 2 &&
     1903                                (FreeItems.getInstance().get(0) instanceof Line || FreeItems.getInstance().get(1) instanceof Line);
    18171904        }
    18181905
     
    18251912         * @return true if the item is a normal text item
    18261913         */
    1827         public boolean isNormalTextItem(Item it) {
    1828                 if (it instanceof Text && it != getTitleItem() && it != _frameName
    1829                                 && !((Text) it).isSpecialAnnotation()) {
     1914        public boolean isNormalTextItem(Item it)
     1915        {
     1916                if (it instanceof Text && it != getTitleItem() && it != _frameName && !((Text) it).isSpecialAnnotation()) {
    18301917                        return true;
    18311918                }
     
    18391926         * @param index
    18401927         */
    1841         public boolean moveMouseToTextItem(int index) {
     1928        public boolean moveMouseToTextItem(int index)
     1929        {
    18421930                List<Item> items = getItems();
    18431931                int itemsFound = 0;
    18441932                for (int i = 0; i < items.size(); i++) {
    18451933                        Item it = items.get(i);
    1846                         if (isNormalTextItem(it))
    1847                                 itemsFound++;
     1934                        if (isNormalTextItem(it)) itemsFound++;
    18481935                        if (itemsFound > index) {
    1849                                 DisplayIO.setCursorPosition(((Text) it)
    1850                                                 .getParagraphEndPosition().x, it.getY());
    1851                                 DisplayIO.resetCursorOffset();
    1852                                 FrameGraphics.Repaint();
     1936                                DisplayController.setCursorPosition(((Text) it).getParagraphEndPosition().x, it.getY());
     1937                                DisplayController.resetCursorOffset();
     1938                                DisplayController.requestRefresh(true);
    18531939                                return true;
    18541940                        }
     
    18571943                return false;
    18581944        }
    1859 
    1860         /*
    1861          * public boolean moveMouseToNextTextItem(int index) { List<Item> items =
    1862          * getItems(); int itemsFound = 0; for (int i = 0; i < items.size(); i++) {
    1863          * Item it = items.get(i); if ( isNormalTextItem(it)) itemsFound++; if
    1864          * (itemsFound > index) {
    1865          * DisplayIO.setCursorPosition(((Text)it).getEndParagraphPosition().x,
    1866          * it.getY()); DisplayIO.resetCursorOffset(); FrameGraphics.Repaint();
    1867          * return true; } }
    1868          *
    1869          * return false; }
    1870          */
    18711945
    18721946        /**
    18731947         * Searches for an annotation item called start to be used as the default
    18741948         * cursor location when TDFC occurs.
    1875          */
    1876         public boolean moveMouseToDefaultLocation() {
     1949         *
     1950         * TODO: Remove magic constants. cts16
     1951         */
     1952        public boolean moveMouseToDefaultLocation()
     1953        {
    18771954                List<Item> items = getItems();
    18781955
     
    18801957                        if (it instanceof Text) {
    18811958                                Text t = (Text) it;
    1882                                 if (t.getText().toLowerCase().startsWith("@start")
    1883                                                 || t.getText().toLowerCase().equals("@start:")) {
     1959                                if (t.getText().toLowerCase().startsWith("@start") || t.getText().toLowerCase().equals("@start:")) {
    18841960                                        // Used to allow users the option of putting an initial
    18851961                                        // bullet after the @start
     
    18881964                                        t.setText("");
    18891965
    1890                                         if (t.getText().equals(""))
    1891                                                 DisplayIO.getCurrentFrame().removeItem(t);
    1892                                         if (!FreeItems.itemsAttachedToCursor()) {
    1893                                                 DisplayIO.setCursorPosition(((Text) it)
    1894                                                                 .getParagraphEndPosition());
    1895                                                 DisplayIO.resetCursorOffset();
     1966                                        if (t.getText().equals("")) DisplayController.getCurrentFrame().removeItem(t);
     1967                                       
     1968                                        if (!FreeItems.hasItemsAttachedToCursor()) {
     1969                                                DisplayController.setCursorPosition(((Text) it).getParagraphEndPosition());
     1970                                                DisplayController.resetCursorOffset();
    18961971                                        }
    1897                                         FrameGraphics.Repaint();
     1972                                       
     1973                                        DisplayController.requestRefresh(true);
     1974                                       
    18981975                                        return true;
    18991976                                }
     
    19111988         *         name of the frame if the tag isnt on the frame.
    19121989         */
    1913         public String getExportFileName() {
     1990        public String getExportFileName()
     1991        {
    19141992                String fileName = getExportFileTagValue();
    19151993
     
    19252003        }
    19262004
    1927         public void toggleBackgroundColor() {
    1928                 setBackgroundColor(ColorUtils.getNextColor(_background,
    1929                                 TemplateSettings.BackgroundColorWheel.get(), null));
    1930         }
    1931 
    1932         public void setName(String frameset, int i) {
     2005        public void toggleBackgroundColor()
     2006        {
     2007                setBackgroundColor(ColorUtils.getNextColor(_background, TemplateSettings.BackgroundColorWheel.get(), null));
     2008        }
     2009
     2010        public void setName(String frameset, int i)
     2011        {
    19332012                setFrameset(frameset);
    19342013                setFrameNumber(i);
     
    19402019         *
    19412020         */
    1942         public void refreshItemPermissions(UserAppliedPermission maxPermission) {
    1943                 if(_frameName == null)
    1944                         return;
     2021        public void refreshItemPermissions(UserAppliedPermission maxPermission)
     2022        {
     2023                if(_frameName == null) return;
    19452024               
    19462025                UserAppliedPermission permission = UserAppliedPermission.min(maxPermission, getUserAppliedPermission());
     
    19482027                switch (permission) {
    19492028                case none:
    1950                         _frameName.setBackgroundColor(new Color(255, 220, 220));
     2029                        _frameName.setBackgroundColor(FRAME_NAME_BACKGROUND_COLOUR_FOR_PERMISSION_NONE);
    19512030                        break;
    19522031                case followLinks:
    1953                         _frameName.setBackgroundColor(new Color(255, 230, 135));
     2032                        _frameName.setBackgroundColor(FRAME_NAME_BACKGROUND_COLOUR_FOR_PERMISSION_FOLLOW_LINKS);
    19542033                        break;
    19552034                case copy:
    1956                         _frameName.setBackgroundColor(new Color(255, 255, 155));
     2035                        _frameName.setBackgroundColor(FRAME_NAME_BACKGROUND_COLOUR_FOR_PERMISSION_COPY);
    19572036                        break;
    19582037                case createFrames:
    1959                         _frameName.setBackgroundColor(new Color(220, 255, 220));
     2038                        _frameName.setBackgroundColor(FRAME_NAME_BACKGROUND_COLOUR_FOR_PERMISSION_CREATE_FRAMES);
    19602039                        break;
    19612040                case full:
    1962                         _frameName.setBackgroundColor(null);
     2041                        _frameName.setBackgroundColor(FRAME_NAME_BACKGROUND_COLOUR_FOR_PERMISSION_FULL);
    19632042                        break;
    19642043                default:
     
    19752054        }
    19762055
    1977         public boolean isTestFrame() {
     2056        public boolean isTestFrame()
     2057        {
    19782058                Text title = getTitleItem();
    1979                 if (title == null)
    1980                         return false;
     2059                if (title == null) return false;
    19812060                String action = title.getFirstAction();
    1982                 if (action == null)
    1983                         return false;
     2061                if (action == null) return false;
    19842062                action = action.toLowerCase();
    1985                 return action.startsWith(Simple.RUN_FRAME_ACTION)
    1986                                 || action.startsWith(Simple.DEBUG_FRAME_ACTION);
    1987         }
    1988 
    1989         public void setActiveTime(String activeTime) {
     2063                return action.startsWith(Simple.RUN_FRAME_ACTION) || action.startsWith(Simple.DEBUG_FRAME_ACTION);
     2064        }
     2065
     2066        public void setActiveTime(String activeTime)
     2067        {
    19902068                try {
    1991                         _activeTime = new Time(Time.valueOf(activeTime).getTime() + 12 * 60
    1992                                         * 60 * 1000);
     2069                        _activeTime = new Time(Time.valueOf(activeTime).getTime() + 12 * 60 * 60 * 1000);
    19932070                } catch (Exception e) {
    19942071                        _activeTime = new Time(0);
     
    19962073        }
    19972074
    1998         public void setActiveTime(Time activeTime) {
     2075        public void setActiveTime(Time activeTime)
     2076        {
    19992077                _activeTime = activeTime;
    20002078        }
    20012079
    2002         public void setDarkTime(Time darkTime) {
     2080        public void setDarkTime(Time darkTime)
     2081        {
    20032082                _darkTime = darkTime;
    20042083        }
    20052084
    2006         public void setDarkTime(String darkTime) {
     2085        public void setDarkTime(String darkTime)
     2086        {
    20072087                try {
    2008                         _darkTime = new Time(Time.valueOf(darkTime).getTime() + 12 * 60
    2009                                         * 60 * 1000);
     2088                        _darkTime = new Time(Time.valueOf(darkTime).getTime() + 12 * 60 * 60 * 1000);
    20102089                } catch (Exception e) {
    20112090                        _darkTime = new Time(0);
     
    20182097         * @return the backup frame for this frame
    20192098         */
    2020         public Frame getBackupFrame() {
     2099        public Frame getBackupFrame()
     2100        {
    20212101                Text backupTag = _annotations.get("old");
    2022                 if (backupTag == null)
    2023                         return null;
     2102                if (backupTag == null) return null;
     2103               
    20242104                // TODO want another way to deal with updating of annotations items
    20252105                // without F12 refresh
     
    20312111                        return getBackupFrame();
    20322112                }
     2113               
    20332114                // Now return the name of the backed up frame
    20342115                String link = backupTag.getAbsoluteLink();
    2035                 if (link == null || link.equalsIgnoreCase(getName()))
    2036                         return null;
     2116                if (link == null || link.equalsIgnoreCase(getName())) return null;
    20372117
    20382118                Frame backup = FrameIO.LoadFrame(link);
     
    20402120        }
    20412121
    2042         public Time getDarkTime() {
     2122        public Time getDarkTime()
     2123        {
    20432124                return _darkTime;
    20442125        }
    20452126
    2046         public Time getActiveTime() {
     2127        public Time getActiveTime()
     2128        {
    20472129                return _activeTime;
    20482130        }
     
    20542136         * @return the number of frames in the backed up comet
    20552137         */
    2056         public int getCometLength() {
     2138        public int getCometLength()
     2139        {
    20572140                Frame backup = getBackupFrame();
    20582141                return 1 + (backup == null ? 0 : backup.getCometLength());
    20592142        }
    20602143
    2061         public void addAnnotation(Text item) {
     2144        public void addAnnotation(Text item)
     2145        {
    20622146                if (_annotations == null) {
    20632147                        _annotations = new HashMap<String, Text>();
    20642148                }
     2149               
    20652150                // Check if this item has already been processed
    20662151                String[] tokens = item.getProcessedText();
     
    20742159                String text = item.getText().trim();
    20752160                assert (text.charAt(0) == '@');
     2161               
    20762162                // Ignore annotations with spaces after the tag symbol
    20772163                if (text.length() < 2 || !Character.isLetter(text.charAt(1))) {
     
    20792165                        return;
    20802166                }
     2167               
    20812168                // The separator char must come before the first non letter otherwise we
    20822169                // ignore the annotation item
     
    21012188                        }
    21022189                }
     2190               
    21032191                // If it was nothing but letters and digits save the tag
    21042192                String lowerCaseText = text.substring(1).toLowerCase();
     
    21072195        }
    21082196
    2109         public boolean hasAnnotation(String annotation) {
    2110                 if (_annotations == null)
    2111                         refreshAnnotationList();
     2197        public boolean hasAnnotation(String annotation)
     2198        {
     2199                if (_annotations == null) refreshAnnotationList();
     2200               
    21122201                return _annotations.containsKey(annotation.toLowerCase());
    21132202        }
     
    21212210         *         is not on the frame or has no value.
    21222211         */
    2123         public String getAnnotationValue(String annotation) {
    2124                 if (_annotations == null)
    2125                         refreshAnnotationList();
     2212        public String getAnnotationValue(String annotation)
     2213        {
     2214                if (_annotations == null) refreshAnnotationList();
    21262215
    21272216                Text text = _annotations.get(annotation.toLowerCase());
    2128                 if (text == null)
    2129                         return null;
     2217                if (text == null) return null;
    21302218
    21312219                String[] tokens = text.getProcessedText();
    2132                 if (tokens != null && tokens.length > 1)
    2133                         return tokens[1];
     2220               
     2221                if (tokens != null && tokens.length > 1) return tokens[1];
     2222               
    21342223                return null;
    21352224        }
    21362225
    2137         Map<String, Text> _annotations = null;
    2138 
    2139         private Collection<FrameObserver> _observers = new HashSet<FrameObserver>();
    2140 
    2141         public void clearAnnotations() {
     2226        public void clearAnnotations()
     2227        {
    21422228                _annotations = null;
    21432229        }
    21442230
    2145         public List<Item> getVisibleItems() {
     2231        public List<Item> getVisibleItems()
     2232        {
    21462233                return getItems(true);
    21472234        }
    21482235
    2149         private void refreshAnnotationList() {
    2150                 if (_annotations == null)
     2236        private void refreshAnnotationList()
     2237        {
     2238                if (_annotations == null) {
    21512239                        _annotations = new HashMap<String, Text>();
    2152                 else
     2240                } else {
    21532241                        _annotations.clear();
     2242                }
     2243               
    21542244                for (Text text : getTextItems()) {
    21552245                        if (text.isAnnotation()) {
     
    21592249        }
    21602250
    2161         public Collection<Text> getAnnotationItems() {
     2251        public Collection<Text> getAnnotationItems()
     2252        {
    21622253                if (_annotations == null) {
    21632254                        refreshAnnotationList();
    21642255                }
     2256               
    21652257                return _annotations.values();
    21662258        }
     
    21712263         * @return the list of items to be saved to a text file
    21722264         */
    2173         public List<Item> getItemsToSave() {
    2174 
     2265        public List<Item> getItemsToSave()
     2266        {
    21752267                if (!_sorted) {
    21762268                        Collections.sort(_body);
     
    21792271
    21802272                // iWidgets are handled specially since 8 items are written as one
    2181                 Collection<InteractiveWidget> seenWidgets = new LinkedHashSet<InteractiveWidget>();
     2273                Collection<Widget> seenWidgets = new LinkedHashSet<Widget>();
    21822274
    21832275                List<Item> toSave = new ArrayList<Item>();
    21842276
    21852277                for (Item i : _body) {
    2186                         if (i == null || i.dontSave()) {
    2187                                 continue;
    2188                         }
     2278                        if (i == null || i.dontSave()) continue;
    21892279
    21902280                        // Ensure only one of the WidgetCorners represent a single widget
    21912281                        if (i instanceof WidgetCorner) {
    2192                                 InteractiveWidget iw = ((WidgetCorner) i).getWidgetSource();
    2193                                 if (seenWidgets.contains(iw))
    2194                                         continue;
     2282                                Widget iw = ((WidgetCorner) i).getWidgetSource();
     2283                                if (seenWidgets.contains(iw)) continue;
    21952284                                seenWidgets.add(iw);
    21962285                                toSave.add(iw.getSource());
     
    21982287                                XRayable x = (XRayable) i;
    21992288                                toSave.addAll(x.getItemsToSave());
    2200                         }// Circle centers are items with attached enclosures
    2201                         else if (i.hasEnclosures()) {
     2289                        // Circle centers are items with attached enclosures
     2290                        } else if (i.hasEnclosures()) {
    22022291                                continue;
    22032292                        } else {
     
    22132302        }
    22142303
    2215         public Collection<Item> getOverlayItems() {
     2304        public Collection<Item> getOverlayItems()
     2305        {
    22162306                return _overlayItems;
    22172307        }
     
    22232313         * @return
    22242314         */
    2225         public boolean hasOverlay(Frame frame) {
     2315        public boolean hasOverlay(Frame frame)
     2316        {
    22262317                return _overlays.containsValue(frame);
    22272318        }
    22282319
    2229         public Collection<Item> getAllItems() {
     2320        public Collection<Item> getAllItems()
     2321        {
    22302322                Collection<Item> allItems = new LinkedHashSet<Item>(_body);
    22312323                allItems.addAll(_overlayItems);
     
    22342326        }
    22352327
    2236         public Collection<Item> getVectorItems() {
     2328        public Collection<Item> getVectorItems()
     2329        {
    22372330                Collection<Item> vectorItems = new LinkedHashSet<Item>(_vectorItems);
    22382331                vectorItems.addAll(getNonAnnotationItems(false));
     
    22452338         * @return
    22462339         */
    2247         public Collection<Text> getTextItems() {
     2340        public Collection<Text> getTextItems()
     2341        {
    22482342                Collection<Text> textItems = new ArrayList<Text>();
     2343               
    22492344                for (Item i : getItems(true)) {
    22502345                        // only add up normal body text items
     
    22532348                        }
    22542349                }
     2350               
    22552351                return textItems;
    22562352        }
    22572353
    2258         public Text getAnnotation(String annotation) {
    2259                 if (_annotations == null)
    2260                         refreshAnnotationList();
     2354        public Text getAnnotation(String annotation)
     2355        {
     2356                if (_annotations == null) refreshAnnotationList();
    22612357
    22622358                return _annotations.get(annotation.toLowerCase());
    22632359        }
    22642360
    2265         public void recalculate() {
    2266 
     2361        public void recalculate()
     2362        {
    22672363                for (Item i : getItems()) {
    22682364                        if (i.hasFormula() && !i.isAnnotation()) {
     
    22722368        }
    22732369
    2274         public void removeObserver(FrameObserver observer) {
     2370        public void removeObserver(FrameObserver observer)
     2371        {
    22752372                _observers.remove(observer);
    22762373        }
    22772374
    2278         public void addObserver(FrameObserver observer) {
     2375        public void addObserver(FrameObserver observer)
     2376        {
    22792377                _observers.add(observer);
    22802378        }
    22812379
    2282         public void clearObservers() {
     2380        public void clearObservers()
     2381        {
    22832382                for (FrameObserver fl : _observers) {
    22842383                        fl.removeSubject(this);
    22852384                }
     2385               
    22862386                // The frame listener will call the frames removeListener method
    22872387                assert (_observers.size() == 0);
    22882388        }
    22892389
    2290         public Collection<Text> getNonAnnotationText(boolean removeTitle) {
     2390        public Collection<Text> getNonAnnotationText(boolean removeTitle)
     2391        {
    22912392                Collection<Text> items = new LinkedHashSet<Text>();
     2393               
    22922394                for (Item i : getItems(true)) {
    22932395                        // only add up normal body text items
     
    22962398                        }
    22972399                }
     2400               
    22982401                if (removeTitle) {
    22992402                        items.remove(getTitleItem());
    23002403                }
     2404               
    23012405                return items;
    23022406        }
    23032407
    2304         public void dispose() {
     2408        public void dispose()
     2409        {
    23052410                clearObservers();
     2411               
    23062412                for (Item i : _body) {
    23072413                        i.dispose();
    23082414                }
     2415               
    23092416                _frameName.dispose();
    23102417                _body = null;
     
    23122419        }
    23132420
    2314         public void parse() {
     2421        public void parse()
     2422        {
    23152423                for (Overlay o : getOverlays()) {
    23162424                        o.Frame.parse();
    23172425                }
     2426               
    23182427                // Must parse the frame AFTER the overlays
    23192428                FrameUtils.Parse(this);
    23202429        }
    23212430
    2322         public void setPath(String path) {
     2431        public void setPath(String path)
     2432        {
    23232433                this.path = path;
    23242434        }
    23252435
    2326         public String getPath() {
     2436        public String getPath()
     2437        {
    23272438                return path;
    23282439        }
    23292440
    2330         public void setLocal(boolean isLocal) {
     2441        public void setLocal(boolean isLocal)
     2442        {
    23312443                this._isLocal = isLocal;
    23322444        }
    23332445
    2334         public boolean isLocal() {
     2446        public boolean isLocal()
     2447        {
    23352448                return _isLocal;
    23362449        }
    23372450
    2338         public String getExportFileTagValue() {
     2451        public String getExportFileTagValue()
     2452        {
    23392453                return getAnnotationValue("file");
    23402454        }
    23412455
    2342         public void assertEquals(Frame frame2) {
     2456        public void assertEquals(Frame frame2)
     2457        {
    23432458                // Check that all the items on the frame are the same
    23442459                List<Item> items1 = getVisibleItems();
    23452460                List<Item> items2 = frame2.getVisibleItems();
     2461               
    23462462                if (items1.size() != items2.size()) {
    2347                         throw new UnitTestFailedException(items1.size() + " items", items2
    2348                                         .size()
    2349                                         + " items");
     2463                        throw new UnitTestFailedException(items1.size() + " items", items2.size() + " items");
    23502464                } else {
    23512465                        for (int i = 0; i < items1.size(); i++) {
     
    23612475        }
    23622476
    2363         public boolean hasObservers() {
     2477        public boolean hasObservers()
     2478        {
    23642479                return _observers != null && _observers.size() > 0;
    23652480        }
    23662481
    2367         public Collection<? extends Item> getInteractableItems() {
     2482        public Collection<? extends Item> getInteractableItems()
     2483        {
    23682484                /*
    23692485                 * TODO: Cache the interactableItems list so we dont have to recreate it
    23702486                 * every time this method is called
    23712487                 */
    2372                 if (_interactableItems.size() > 0)
    2373                         return _interactableItems;
     2488                if (_interactableItems.size() > 0) return _interactableItems;
    23742489
    23752490                for (Item i : _body) {
    2376                         if (i == null) {
    2377                                 continue;
    2378                         }
     2491                        if (i == null) continue;
    23792492                        if (i.isVisible()) {
    23802493                                _interactableItems.add(i);
     
    23862499                                _interactableItems.add(i);     
    23872500                        }
    2388                        
    2389                        
    23902501                }
    23912502
     
    23982509                return _interactableItems;
    23992510        }
     2511
     2512        private static final class History {
     2513               
     2514                public enum Type {
     2515                        deletion,
     2516                        movement
     2517                }
     2518               
     2519                public final List<Item> items;
     2520               
     2521                public final Type type;
     2522               
     2523                public History(Collection<Item> items, Type type)
     2524                {
     2525                        this.items = new LinkedList<Item>(items);
     2526                        this.type = type;
     2527                }
     2528               
     2529                public String toString()
     2530                {
     2531                        return this.type.toString() + ":\n" + this.items.toString();
     2532                }
     2533        }
    24002534}
  • trunk/src/org/expeditee/gui/FrameCreator.java

    r1063 r1102  
    1919package org.expeditee.gui;
    2020
    21 import java.awt.Color;
    22 import java.util.*;
     21import java.util.LinkedList;
     22import java.util.List;
    2323
    2424import org.expeditee.agents.ExistingFramesetException;
     25import org.expeditee.core.Colour;
    2526import org.expeditee.items.Item;
    2627import org.expeditee.items.Text;
    2728
    2829public class FrameCreator {
     30       
    2931        public static final int INDENT_FROM_TITLE = 20;
    3032
     
    6062
    6163        public FrameCreator(String frameTitle) {
    62                 this(DisplayIO.getCurrentFrame().getFramesetName(), DisplayIO
     64                this(DisplayController.getCurrentFrame().getFramesetName(), DisplayController
    6365                                .getCurrentFrame().getPath(), frameTitle, false, false);
    6466        }
     
    8385         * @return the newly created button.
    8486         */
    85         public static Item createButton(String text, Float x, Float y, Float right,
    86                         Float bottom) {
     87        public static Item createButton(String text, Integer x, Integer y, Integer right,
     88                        Integer bottom) {
    8789                Text button = new Text(text);
    8890
    89                 button.setBackgroundColor(Color.LIGHT_GRAY);
    90                 button.setBorderColor(Color.DARK_GRAY);
     91                button.setBackgroundColor(Colour.LIGHT_GREY);
     92                button.setBorderColor(Colour.DARK_GREY);
    9193                button.setThickness(2.0F);
    9294                if (bottom != null)
     
    99101                        button.setY(y);
    100102
    101                 button.updatePolygon();
     103                button.invalidateBounds();
    102104
    103105                return button;
    104106        }
    105107
    106         public FrameCreator(String name, String path, String frameTitle,
    107                         boolean recreate, boolean multiColumn) {
     108        public FrameCreator(String name, String path, String frameTitle, boolean recreate, boolean multiColumn)
     109        {
    108110                _multiColumn = multiColumn;
    109                 _Mnext = createButton("@Next", null, null, 10F, 15F);
     111                _Mnext = createButton("@Next", null, null, 10, 15);
    110112
    111113                _Mprev = createButton("@Previous", null, null, _Mnext.getBoundsWidth()
    112                                 + _Mnext.getAnchorRight() + 20F, 15F);
     114                                + _Mnext.getAnchorRight() + 20, 15);
    113115
    114116                _Mfirst = createButton("@First", null, null, _Mprev.getBoundsWidth()
    115                                 + _Mprev.getAnchorRight() + 20F, 15F);
     117                                + _Mprev.getAnchorRight() + 20, 15);
    116118
    117119                Frame toUse = null;
     
    180182        }
    181183
    182         private void resetGlobals(Frame toUse) {
     184        private void resetGlobals(Frame toUse)
     185        {
    183186                Text title = toUse.getTitleItem();
    184187                START_X = INDENT_FROM_TITLE + title.getX();
     
    217220                                // new frame
    218221                                if (!_multiColumn
    219                                                 || toAdd.getBoundsWidth() + _lastX > FrameGraphics
    220                                                                 .getMaxSize().width) {
     222                                                || toAdd.getBoundsWidth() + _lastX > DisplayController.getFramePaintArea().getWidth()) {
    221223                                        // Make sure text items that are created on the current
    222224                                        // frame are removed
     
    229231                        toAdd.setOffset(0, 0);
    230232                        toAdd.setID(_current.getNextItemID());
    231                         toAdd.setRightMargin(FrameGraphics.getMaxFrameSize().width, true);
     233                        toAdd.setRightMargin(DisplayController.getFramePaintArea().getWidth(), true);
    232234
    233235                        _current.addItem(toAdd);
     
    245247        }
    246248
    247         public Text addText(String toAdd, Color c, String link, String action,
     249        public Text addText(String toAdd, Colour c, String link, String action,
    248250                        boolean bSave) {
    249251                Text text = _current.createNewText(toAdd);
  • trunk/src/org/expeditee/gui/FrameGraphics.java

    r1064 r1102  
    1919package org.expeditee.gui;
    2020
    21 import java.awt.Color;
    22 import java.awt.Dimension;
    23 import java.awt.EventQueue;
    24 import java.awt.Graphics;
    25 import java.awt.Graphics2D;
    26 import java.awt.GraphicsDevice;
    27 import java.awt.GraphicsEnvironment;
    28 import java.awt.Image;
    29 import java.awt.Polygon;
    30 import java.awt.Rectangle;
    31 import java.awt.RenderingHints;
    32 import java.awt.geom.Area;
    33 import java.lang.reflect.Method;
    34 import java.awt.image.BufferedImage;
    3521import java.util.Collection;
    3622import java.util.Collections;
     
    4127import java.util.ListIterator;
    4228
     29import org.expeditee.core.Clip;
     30import org.expeditee.core.Colour;
     31import org.expeditee.core.Dimension;
     32import org.expeditee.core.Image;
     33import org.expeditee.core.bounds.PolygonBounds;
     34import org.expeditee.gio.EcosystemManager;
     35import org.expeditee.gio.input.StandardInputEventListeners;
     36import org.expeditee.gio.input.KBMInputEvent.Key;
    4337import org.expeditee.items.Circle;
    4438import org.expeditee.items.Dot;
    4539import org.expeditee.items.Item;
    46 import org.expeditee.items.ItemUtils;
    4740import org.expeditee.items.Line;
    4841import org.expeditee.items.UserAppliedPermission;
    4942import org.expeditee.items.XRayable;
    5043import org.expeditee.items.Item.HighlightMode;
    51 import org.expeditee.items.widgets.InteractiveWidget;
     44import org.expeditee.items.widgets.Widget;
    5245import org.expeditee.items.widgets.WidgetEdge;
    5346import org.expeditee.settings.UserSettings;
     
    5548public class FrameGraphics {
    5649
    57         // the graphics used to paint with
    58         private static Graphics2D _DisplayGraphics;
    59 
    60         // the maximum size that can be used to paint on
    61         private static Dimension _MaxSize = null;
    62 
    6350        // Final passes to rendering the current frame
    6451        private static LinkedList<FrameRenderPass> _frameRenderPasses = new LinkedList<FrameRenderPass>();
    65 
    66         // modes
    67         protected static final int MODE_NORMAL = 0;
    68 
    69         protected static final int MODE_AUDIENCE = 1;
    70 
    71         protected static final int MODE_XRAY = 2;
    7252       
    73         protected static final int MODE_AUDIENCE_FULLSCREEN = 4;
    74        
    75 
    76         // The following used to be true in the past:
    77         //   Start in XRay mode so that errors aren't thrown when parsing the profile
    78         //   frame if it has images on it
    79         // More recently, so Exploratory Search starts up correctly with images
    80         // rendered (rather than their @i form) the following assignment was changed
    81         // to MODE_NORMAL.  No issue of parse errors has not been seen
    82         private static int _Mode = MODE_NORMAL;
    83 
    84         private FrameGraphics() {
    85                 // util constructor
    86         }
    87 
    88         /**
    89          * If Audience Mode is on this method will toggle it to be off, or
    90          * vice-versa. This results in the Frame being re-parsed and repainted.
    91          */
    92         public static void ToggleAudienceMode() {
    93                 Frame current = DisplayIO.getCurrentFrame();
    94                 if (_Mode == MODE_XRAY) {
    95                         ToggleXRayMode();
    96                 }
    97        
    98 
    99                 if (_Mode == MODE_AUDIENCE_FULLSCREEN) {
    100                         _Mode = MODE_NORMAL;
    101                         DisplayIO.leaveFullScreenMode();
    102                 }
    103                 else if (_Mode == MODE_AUDIENCE) {
    104                         if (DisplayIO.fullScreenCapable()) {
    105                                 // Don't need to worry about UpdateConnectedToAnnotations, as this
    106                                 // will have already been taken care of going to the 'first stage' of
    107                                 // audience mode (MODE_AUDIENCE)
    108                                 _Mode = MODE_AUDIENCE_FULLSCREEN;
    109                                 DisplayIO.enterFullScreenMode();
    110                         }
    111                         else {
    112                                 // return to normal mode
    113                                 _Mode = MODE_NORMAL;
    114                         }
    115                 }
    116                 else { // must currently be in regular mode => move to audience mode
    117                         _Mode = MODE_AUDIENCE;
    118                         ItemUtils.UpdateConnectedToAnnotations(current.getItems());
    119                         for (Overlay o : current.getOverlays()) {
    120                                 ItemUtils.UpdateConnectedToAnnotations(o.Frame.getItems());
    121                         }
    122                         for (Vector v : current.getVectorsDeep()) {
    123                                 ItemUtils.UpdateConnectedToAnnotations(v.Frame.getItems());
    124                         }
    125                 }
    126                 FrameUtils.Parse(current);
    127                 DisplayIO.UpdateTitle();
    128                 setMaxSize(new Dimension(_MaxSize.width, MessageBay
    129                                 .getMessageBufferHeight()
    130                                 + _MaxSize.height));
    131                 refresh(false);
    132         }
    133 
    134         /**
    135          * If X-Ray Mode is on this method will toggle it to be off, or vice-versa.
    136          * This results in the Frame being re-parsed and repainted.
    137          */
    138         public static void ToggleXRayMode() {
    139                 if (_Mode == MODE_AUDIENCE) {
    140                         ToggleAudienceMode();
    141                 }
    142 
    143                 if (_Mode == MODE_XRAY) {
    144                         setMode(MODE_NORMAL, true);
    145                 } else {
    146                         setMode(MODE_XRAY, true);
    147                 }
    148                 DisplayIO.getCurrentFrame().refreshSize();
    149                 DisplayIO.UpdateTitle();
    150                 FrameMouseActions.getInstance().refreshHighlights();
    151                 FrameMouseActions.updateCursor();
    152                 refresh(false);
    153         }
    154 
    155         public static void setMode(int mode, boolean parse) {
    156                 if (_Mode == mode)
    157                         return;
    158                 _Mode = mode;
    159                 if (parse) {
    160                         Frame current = DisplayIO.getCurrentFrame();
    161                         current.parse();
    162                 }
    163         }
    164 
    165         public static void forceXRayMode(boolean parse) {
    166                 setMode(MODE_XRAY,parse);
    167         }
    168        
    169         /**
    170          * @return True if Audience Mode is currently on, False otherwise.
    171          */
    172         public static boolean isAudienceMode() {
    173                 return (_Mode == MODE_AUDIENCE) || (_Mode == MODE_AUDIENCE_FULLSCREEN);
    174         }
    175 
    176         /**
    177          * @return True if X-Ray Mode is currently on, False otherwise.
    178          */
    179         public static boolean isXRayMode() {
    180                 return _Mode == MODE_XRAY;
    181         }
    182 
    183         public static void setMaxSize(Dimension max) {
    184                 if (_MaxSize == null)
    185                         _MaxSize = max;
    186 
    187                 // Hide the message buffer if in audience mode
    188                 int newMaxHeight = max.height
    189                                 - (isAudienceMode() ? 0 : MessageBay.MESSAGE_BUFFER_HEIGHT);
    190                 if (newMaxHeight > 0) {
    191                         _MaxSize.setSize(max.width, newMaxHeight);
    192                 }
    193                 Frame current = DisplayIO.getCurrentFrame();
    194                 if (current != null) {
    195                         current.setBuffer(null);
    196                         current.refreshSize();
    197                         if (DisplayIO.isTwinFramesOn()) {
    198                                 Frame opposite = DisplayIO.getOppositeFrame();
    199 
    200                                 /* When running the test suite opposite may be null! */
    201                                 if (opposite != null) {
    202                                         opposite.setBuffer(null);
    203                                         opposite.refreshSize();
    204                                 }
    205                         }
    206                 }
    207 
    208                 if (newMaxHeight > 0) {
    209                         MessageBay.updateSize();
    210                 }
    211         }
    212 
    213         public static Dimension getMaxSize() {
    214                 return _MaxSize;
    215         }
    216 
    217         public static Dimension getMaxFrameSize() {
    218                 if (DisplayIO.isTwinFramesOn()) {
    219                         return new Dimension((_MaxSize.width / 2), _MaxSize.height);
    220                 } else
    221                         return _MaxSize;
    222         }
    223 
    224         /**
    225          * Sets the Graphics2D object that should be used for all painting tasks.
    226          * Note: Actual painting is done by using g.create() to create temporary
    227          * instances that are then disposed of using g.dispose().
    228          *
    229          * @param g
    230          *            The Graphics2D object to use for all painting
    231          */
    232         public static void setDisplayGraphics(Graphics2D g) {
    233                 _DisplayGraphics = g;
    234         }
    235 
    236         /*
    237          * Displays the given Item on the screen
    238          */
    239         static void PaintItem(Graphics2D g, Item i) {
    240                 if (i == null || g == null)
    241                         return;
    242 
    243                 // do not paint annotation items in audience mode
    244                 if (!isAudienceMode()
    245                                 || (isAudienceMode() && !i.isConnectedToAnnotation() && !i
    246                                                 .isAnnotation()) || i == FrameUtils.getLastEdited()) {
    247 
    248                         Graphics2D tg = (Graphics2D) g.create();
    249                         i.paint(tg);
    250                         tg.dispose();
    251                 }
    252         }
    253 
    254         /**
    255          * Adds all the scaled vector items for a frame into a list. It uses
    256          * recursion to get the items from nested vector frames.
    257          *
    258          * @param items
    259          *            the list into which the vector items will be placed.
    260          * @param vector
    261          *            the frame containing vecor items.
    262          * @param seenVectors
    263          *            the vectors which should be ignored to prevent infinate loops.
    264          * @param origin
    265          *            start point for this frame or null if it is a top level frame.
    266          * @param scale
    267          *            the factor by which the item on the vector frame are to be
    268          *            scaled.
    269          */
    270         // public static void AddAllVectorItems(List<Item> items, Vector vector,
    271         // Collection<Frame> seenVectors) {
    272         // // Check all the vector items and add the items on the vectors
    273         // if (seenVectors.contains(vector))
    274         // return;
    275         // seenVectors.add(vector);
    276         //
    277         // float originX = origin == null ? 0 : origin.x;
    278         // float originY = origin == null ? 0 : origin.y;
    279         //
    280         // for (Vector o : vector.getVectors())
    281         // AddAllVectorItems(items, o.Frame, new HashSet<Frame>(seenVectors),
    282         // new Point2D.Float(originX + o.Origin.x * scale, originY
    283         // + o.Origin.y * scale), o.Scale * scale,
    284         // o.Foreground, o.Background);
    285         // // if its the original frame then were done
    286         // if (origin == null) {
    287         // ItemUtils.EnclosedCheck(items);
    288         // return;
    289         // }
    290         // // Put copies of the items shifted to the origin of the VectorTag
    291         // items.addAll(ItemUtils
    292         // .CopyItems(vector.getNonAnnotationItems(), vector));
    293         //             
    294         // }
    295         /**
    296          * Recursive function similar to AddAllOverlayItems.
    297          *
    298          * @param widgets
    299          *            The collection the widgets will be added to
    300          * @param overlay
    301          *            An "overlay" frame - this intially will be the parent frame
    302          * @param seenOverlays
    303          *            Used for state in the recursion stack. Pass as an empty
    304          *            (non-null) list.
    305          */
    306         public static void AddAllOverlayWidgets(List<InteractiveWidget> widgets,
    307                         Frame overlay, List<Frame> seenOverlays) {
    308                 if (seenOverlays.contains(overlay))
    309                         return;
    310 
    311                 seenOverlays.add(overlay);
    312 
    313                 for (Overlay o : overlay.getOverlays())
    314                         AddAllOverlayWidgets(widgets, o.Frame, seenOverlays);
    315 
    316                 widgets.addAll(overlay.getInteractiveWidgets());
    317         }
    318 
    319         private static Image Paint(Frame toPaint, Area clip) {
    320                 return Paint(toPaint, clip, true, true);
    321         }
    322 
    323         /**
    324          *
    325          * @param toPaint
    326          * @param clip
    327          *            If null, then no clip applied.
    328          * @param isActualFrame
    329          * @return
    330          */
    331         private static Image Paint(Frame toPaint, Area clip, boolean isActualFrame,
    332                         boolean createVolitile) {
    333                 if (toPaint == null)
    334                         return null;
     53        private static Item _lastToolTippedItem = null;
     54
     55        /** Static-only class. */
     56        private FrameGraphics()
     57        {
     58        }
     59
     60        /**
     61         * Gets an image of the given frame that has the given dimensions. If clip
     62         * is not null, only the areas inside clip are guaranteed to be drawn.
     63         */
     64        public static Image getFrameImage(Frame toPaint, Clip clip, Dimension size)
     65        {
     66                return getFrameImage(toPaint, clip, size, true, true);
     67        }
     68
     69        /**
     70         * Gets an image of the given frame that has the given dimensions. If clip
     71         * is not null, only the areas inside clip are guaranteed to be drawn.
     72         */
     73        public static Image getFrameImage(Frame toPaint, Clip clip, Dimension size, boolean isActualFrame, boolean createVolatile)
     74        {
     75                if (toPaint == null) return null;
    33576
    33677                // the buffer is not valid, so it must be recreated
    33778                if (!toPaint.isBufferValid()) {
     79                       
    33880                        Image buffer = toPaint.getBuffer();
    339                         if (buffer == null) {
    340                                 GraphicsEnvironment ge = GraphicsEnvironment
    341                                                 .getLocalGraphicsEnvironment();
    342                                 if (createVolitile) {
    343                                         buffer = ge.getDefaultScreenDevice()
    344                                                         .getDefaultConfiguration()
    345                                                         .createCompatibleVolatileImage(_MaxSize.width,
    346                                                                         _MaxSize.height);
     81                        // Get the size if it hasn't been given
     82                        if (size == null) {
     83                                // Can't get the size if there is no buffer
     84                                if (buffer == null) {
     85                                        return null;
    34786                                } else {
    348                                         buffer = new BufferedImage(_MaxSize.width, _MaxSize.height,
    349                                                         BufferedImage.TYPE_INT_ARGB);
    350                                 }
     87                                        size = buffer.getSize();
     88                                }
     89                        }
     90                       
     91                        if (buffer == null || !buffer.getSize().equals(size)) {
     92                                buffer = Image.createImage(size.width, size.height, createVolatile);
    35193                                toPaint.setBuffer(buffer);
    352                         }
    353 
    354                         Graphics2D bg = (Graphics2D) buffer.getGraphics();
    355                         paintFrame(toPaint, clip, isActualFrame, createVolitile, bg);
    356 
    357                         bg.dispose();
     94                                clip = null;
     95                        }
     96                       
     97                        EcosystemManager.getGraphicsManager().pushDrawingSurface(buffer);
     98                        EcosystemManager.getGraphicsManager().pushClip(clip);
     99                        paintFrame(toPaint, isActualFrame, createVolatile);
     100                        EcosystemManager.getGraphicsManager().popDrawingSurface();
    358101                }
    359102
     
    361104        }
    362105
    363         /**
    364          * @param toPaint
    365          * @param clip
    366          * @param isActualFrame
    367          * @param createVolitile
    368          * @param bg
    369          */
    370         public static void paintFrame(Frame toPaint, Area clip,
    371                         boolean isActualFrame, boolean createVolitile, Graphics2D bg) {
    372 
     106        /** TODO: Comment. cts16 */
     107        public static void paintFrame(Frame toPaint, boolean isActualFrame, boolean createVolitile)
     108        {
     109                Clip clip = EcosystemManager.getGraphicsManager().peekClip();
     110               
    373111                // Prepare render passes
    374112                if (isActualFrame) {
    375                         currentClip = clip;
    376113                        for (FrameRenderPass pass : _frameRenderPasses) {
    377                                 currentClip = pass.paintStarted(currentClip);
    378                                 clip = currentClip;
    379                         }
    380                 }
    381 
    382                 bg.setClip(clip);
     114                                clip = pass.paintStarted(clip);
     115                        }
     116                }
    383117
    384118                // TODO: Revise images and clip - VERY IMPORTANT
     
    386120                // Nicer looking lines, but may be too jerky while
    387121                // rubber-banding on older machines
    388                 if (UserSettings.AntiAlias.get())
    389                         bg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
    390                                         RenderingHints.VALUE_ANTIALIAS_ON);
    391                 // If we are doing @f etc... then have a clear background if its the
    392                 // default background color
    393                 Color backgroundColor = null;
     122                if (UserSettings.AntiAlias.get()) EcosystemManager.getGraphicsManager().setAntialiasing(true);
     123               
     124                // If we are doing @f etc... then have a clear background if its the default background color
     125                Colour backgroundColor = null;
     126               
    394127                // Need to allow transparency for frameImages
    395128                if (createVolitile) {
     
    397130                } else {
    398131                        backgroundColor = toPaint.getBackgroundColor();
    399                         if (backgroundColor == null)
    400                                 backgroundColor = Item.TRANSPARENT;
    401                 }
    402 
    403                 // if(isActual)
    404                 bg.setColor(backgroundColor);
    405                 if (isActualFrame) {
    406                         // bg.setColor(Color.white); // TODO: TEMP FOR DEBUGGING
    407 
    408                         // System.out.println("paintPic");
    409                 }
    410                 bg.fillRect(0, 0, _MaxSize.width, _MaxSize.height);
     132                        if (backgroundColor == null) backgroundColor = Item.TRANSPARENT;
     133                }
     134
     135                EcosystemManager.getGraphicsManager().clear(backgroundColor);
    411136
    412137                List<Item> visibleItems = new LinkedList<Item>();
    413                 List<InteractiveWidget> paintWidgets;
     138                List<Widget> paintWidgets;
    414139
    415140                if (isActualFrame) {
     
    417142                        // frames
    418143                        visibleItems.addAll(toPaint.getAllItems());
    419                         paintWidgets = new LinkedList<InteractiveWidget>();
    420                         AddAllOverlayWidgets(paintWidgets, toPaint, new LinkedList<Frame>());
     144                        paintWidgets = toPaint.getAllOverlayWidgets();
     145                        paintWidgets.addAll(toPaint.getInteractiveWidgets());
    421146                } else {
    422147                        visibleItems.addAll(toPaint.getVisibleItems());
     
    425150                }
    426151
    427 
    428                                 HashSet<Item> paintedFillsAndLines = new HashSet<Item>();
     152                HashSet<Item> paintedFillsAndLines = new HashSet<Item>();
    429153                // FIRST: Paint widgets swing gui (not expeditee gui) .
    430154                // Note that these are the anchored widgets
    431                 ListIterator<InteractiveWidget> widgetItor = paintWidgets
    432                                 .listIterator(paintWidgets.size());
     155                ListIterator<Widget> widgetItor = paintWidgets.listIterator(paintWidgets.size());
    433156                while (widgetItor.hasPrevious()) {
    434157                        // Paint first-in-last-serve ordering - like swing
    435158                        // If it is done the other way around then widgets are covered up by
    436159                        // the box that is supposed to be underneath
    437                         InteractiveWidget iw = widgetItor.previous();
    438                         if (clip == null || clip.intersects(iw.getComponant().getBounds())) {
     160                        Widget iw = widgetItor.previous();
     161                        if (clip == null || clip.getBounds() == null || clip.getBounds().intersects(iw.getBounds())) {
    439162                                paintedFillsAndLines.addAll(iw.getItems());
    440163                                //iw.paint(bg);
     
    457180                        paintItems = new LinkedList<Item>();
    458181                        for (Item i : visibleItems) {
    459                                 if (i.isInDrawingArea(clip)) {
     182                                if (clip == null || i.isInDrawingArea(clip.getBounds())) {
    460183                                        paintItems.add(i);
    461184                                } else if (i.isEnclosed()) {
     
    469192                        }
    470193                }
    471                 // Only paint files and lines once ... between anchored AND free
    472                 // items
    473                 PaintPictures(bg, paintItems, fillOnlyItems, paintedFillsAndLines);
    474                 PaintLines(bg, visibleItems);
     194               
     195                // Only paint files and lines once ... between anchored AND free items
     196                PaintPictures(paintItems, fillOnlyItems, paintedFillsAndLines);
     197                PaintLines(visibleItems);
    475198
    476199
     
    480203                        // If it is done the other way around then widgets are covered up by
    481204                        // the box that is supposed to be underneath
    482                         InteractiveWidget iw = widgetItor.previous();
    483                         if (clip == null || clip.intersects(iw.getComponant().getBounds())) {
    484                                 iw.paint(bg);
    485                                 PaintItem(bg, iw.getItems().get(4));
     205                        Widget iw = widgetItor.previous();
     206                        if (clip == null || clip.isNotClipped() || clip.getBounds().intersects(iw.getBounds())) {
     207                                iw.paint();
     208                                PaintItem(iw.getItems().get(4));
    486209                        }
    487210                }
     
    494217                // Dont paint the free items for the other frame in twin frames mode
    495218                // if (toPaint == DisplayIO.getCurrentFrame()) {
    496                 if (clip == null) {
     219                if (clip == null || clip.isNotClipped()) {
    497220                        freeItemsToPaint = FreeItems.getInstance();
    498221                } else {
     
    500223                        fillOnlyItems.clear();
    501224                        for (Item i : FreeItems.getInstance()) {
    502                                 if (i.isInDrawingArea(clip)) {
     225                                if (i.isInDrawingArea(clip.getBounds())) {
    503226                                        freeItemsToPaint.add(i);
    504227                                } else if (i.isEnclosed()) {
     
    509232                // }
    510233
    511                 if (isActualFrame && toPaint == DisplayIO.getCurrentFrame())
    512                         PaintPictures(bg, freeItemsToPaint, fillOnlyItems,
    513                                         paintedFillsAndLines);
     234                if (isActualFrame && toPaint == DisplayController.getCurrentFrame()) {
     235                        PaintPictures(freeItemsToPaint, fillOnlyItems, paintedFillsAndLines);
     236                }
     237               
    514238                // TODO if we can get transparency with FreeItems.getInstance()...
    515239                // then text can be done before freeItems
    516                 PaintNonLinesNonPicture(bg, paintItems);
     240                PaintNonLinesNonPicture(paintItems);
    517241
    518242                // toPaint.setBufferValid(true);
    519243
    520                 if (isActualFrame && !isAudienceMode()) {
    521                         PaintItem(bg, toPaint.getNameItem());
    522                 }
    523 
    524                 if (DisplayIO.isTwinFramesOn()) {
     244                if (isActualFrame && !DisplayController.isAudienceMode()) {
     245                        PaintItem(toPaint.getNameItem());
     246                }
     247
     248                if (DisplayController.isTwinFramesOn()) {
    525249                        List<Item> lines = new LinkedList<Item>();
    526250                        for (Item i : freeItemsToPaint) {
     
    528252                                        Line line = (Line) i;
    529253
    530                                         if (toPaint == DisplayIO.getCurrentFrame()) {
     254                                        if (toPaint == DisplayController.getCurrentFrame()) {
    531255                                                // If exactly one end of the line is floating...
    532256
     
    560284                                }
    561285                        }
    562                         if (isActualFrame)
    563                                 PaintLines(bg, lines);
     286                       
     287                        if (isActualFrame) PaintLines(lines);
    564288                } else {
    565                         // Don't paint the
    566                         if (isActualFrame)
    567                                 PaintLines(bg, freeItemsToPaint);
    568                 }
    569 
    570                 if (isActualFrame && toPaint == DisplayIO.getCurrentFrame())
    571                         PaintNonLinesNonPicture(bg, freeItemsToPaint);
     289                        if (isActualFrame) PaintLines(freeItemsToPaint);
     290                }
     291
     292                if (isActualFrame && toPaint == DisplayController.getCurrentFrame()) {
     293                        PaintNonLinesNonPicture(freeItemsToPaint);
     294                }
    572295
    573296                // Repaint popups / drags... As well as final passes
    574297                if (isActualFrame) {
    575298                        for (FrameRenderPass pass : _frameRenderPasses) {
    576                                 pass.paintPreLayeredPanePass(bg);
    577                         }
    578                         PopupManager.getInstance().paintLayeredPane(bg, clip);
     299                                pass.paintPreLayeredPanePass();
     300                        }
     301                       
     302                        //if (PopupManager.getInstance() != null) PopupManager.getInstance().paintLayeredPane(clip == null ? null : clip.getBounds());
     303                       
    579304                        for (FrameRenderPass pass : _frameRenderPasses) {
    580                                 pass.paintFinalPass(bg);
     305                                pass.paintFinalPass();
    581306                        }
    582307                }
    583308               
    584309                // paint tooltip
    585                 if(!FreeItems.itemsAttachedToCursor()) {
     310                if(!FreeItems.hasItemsAttachedToCursor()) {
    586311                        Item current = FrameUtils.getCurrentItem();
    587                         if(current != null) {
    588                                 current.paintTooltip(bg);
    589                         } //else {
    590 //                              Item.clearTooltipOwner();
    591 //                      }
    592                         if(previous != null) previous.clearTooltips();
    593                         previous = current;
    594                 }
    595 
    596                 if (FreeItems.hasCursor()
    597                                 && DisplayIO.getCursor() == Item.DEFAULT_CURSOR)
    598                         PaintNonLinesNonPicture(bg, FreeItems.getCursor());
    599         }
    600        
    601         private static Item previous = null;
    602 
    603         // creates a new line so that lines are shown correctly when spanning
    604         // across frames in TwinFrames mode
    605         // private static Line TransposeLine(Line line, Item d, Frame toPaint,
    606         // int base, int adj) {
    607         // Line nl = null;
    608         //
    609         // if (toPaint != DisplayIO.getCurrentFrame() && d.getParent() == null
    610         // && line.getOppositeEnd(d).getParent() == toPaint) {
    611         // nl = line.copy();
    612         // if (d == line.getStartItem())
    613         // d = nl.getStartItem();
    614         // else
    615         // d = nl.getEndItem();
    616         //
    617         // if (DisplayIO.FrameOnSide(toPaint) == 0)
    618         // d.setX(base);
    619         // else
    620         // d.setX(base + adj);
    621         //
    622         // } else if (toPaint == DisplayIO.getCurrentFrame()
    623         // && d.getParent() == null
    624         // && line.getOppositeEnd(d).getParent() != toPaint) {
    625         // nl = line.copy();
    626         //
    627         // if (d == line.getStartItem())
    628         // d = nl.getEndItem();
    629         // else
    630         // d = nl.getStartItem();
    631         //
    632         // if (DisplayIO.FrameOnSide(toPaint) == 1)
    633         // d.setX(d.getX() - DisplayIO.getMiddle());
    634         // else
    635         // d.setX(d.getX() + DisplayIO.getMiddle());
    636         // }
    637         // if (nl != null) {
    638         // nl.invalidateAll();
    639         // FrameGraphics.requestRefresh(true);
    640         // }
    641         // return nl;
    642         // }
    643 
    644         private static void Paint(Graphics g, Image left, Image right,
    645                         Color background) {
    646 
    647             // Triggers a FrameTransition is this has been signalled
    648             // through an '@frameTransition: xxxx' on the frame.  The type of
    649             // transition is specified in the 'xxxx' part
    650 
    651 
    652                 // if TwinFrames mode is on, then clipping etc has to be set
    653                 if (DisplayIO.isTwinFramesOn()) {
    654                         // draw the two lines down the middle of the window
    655                         if (left != null)
    656                                 left.getGraphics().drawLine(DisplayIO.getMiddle() - 2, 0,
    657                                                 DisplayIO.getMiddle() - 2, _MaxSize.height);
    658 
    659                         if (right != null)
    660                                 right.getGraphics().drawLine(0, 0, 0, _MaxSize.height);
    661 
    662                         // set the clipping area
    663                         ((Graphics2D) g).setClip(0, 0, DisplayIO.getMiddle() - 1,
    664                                         _MaxSize.height);
    665                         g.drawImage(left, 0, 0, Item.DEFAULT_BACKGROUND, null);
    666                         ((Graphics2D) g).setClip(null);
    667                         g.drawImage(right, DisplayIO.getMiddle() + 1, 0,
    668                                         Item.DEFAULT_BACKGROUND, null);
    669 
    670                        
    671                 }
    672                 // otherwise, just draw whichever side is active
    673                 else {
    674                     if (DisplayIO.getCurrentSide() == 0) {
    675                         if (!paintTransition(g,left)) {
    676                                 // Nothing fancy occurred, just need to render the next slide to screen
    677                                 g.drawImage(left, 0, 0, Item.DEFAULT_BACKGROUND, null);
    678                         }
    679                     }
    680                     else {
    681                         if (!paintTransition(g,right)) {
    682                                 // Nothing fancy occurred, just need to render the next slide to screen
    683                                 g.drawImage(right, 0, 0, Item.DEFAULT_BACKGROUND, null);
    684                         }
    685                     }
    686                 }
    687 
    688         }
    689 
    690        
    691     private static boolean paintTransition(Graphics g, Image image)
    692     {
    693         boolean performed_transition = false;
    694        
    695         //If we are doing a transition
    696         if(FrameTransitions.getSlide() == true){                                               
    697 
    698                 String input = "org.expeditee.gui.FrameTransitions";
    699                 String slide_mode_method = FrameTransitions.getslideModeMethod();
    700 
    701                 try {
    702                         Class<?> c = Class.forName(input);
    703 
    704                         Class[] cArg = new Class[3];
    705                         cArg[0] = Graphics.class;
    706                         cArg[1] = Image.class;
    707                         cArg[2] = Dimension.class;                                                     
    708 
    709                         //Gets the method of transition and calls it
    710                         Method lMethod = c.getDeclaredMethod(slide_mode_method, cArg);
    711 
    712                         if(lMethod != null){
    713                                 // calling static method, so no class parameter needed
    714                                 Object o = lMethod.invoke(null, g, image, _MaxSize);
    715                                 performed_transition = true;
    716                                
    717                         }
    718                         else{
    719                                 System.err.println("Unable to locate the transition '" + slide_mode_method + "'");
    720                         }                                               
    721 
    722                 } catch (Exception e) {                                         
    723 
    724                         System.err.println("An Reflection Exception occurred trying to invoke '" + slide_mode_method + "'");
    725                         e.printStackTrace();
    726                 }       
    727         }               
    728         //Tells the frame to only transition once
    729         FrameTransitions.setSlideFalse();               
    730        
    731         return performed_transition;
    732     }
    733    
    734 
    735         public static void Clear() {
    736                 Graphics g = _DisplayGraphics.create();
    737                 g.setColor(Color.WHITE);
    738                 g.fillRect(0, 0, _MaxSize.width, _MaxSize.height);
    739                 g.dispose();
    740         }
    741 
    742         private static void PaintNonLinesNonPicture(Graphics2D g, List<Item> toPaint) {
    743                 for (Item i : toPaint)
    744                         if (!(i instanceof Line) && !(i instanceof XRayable))
    745                                 PaintItem(g, i);
     312                        if(current != null) current.paintTooltip();
     313                        if (_lastToolTippedItem != null) _lastToolTippedItem.clearTooltips();
     314                        _lastToolTippedItem = current;
     315                }
     316
     317                if (FreeItems.hasCursor() && DisplayController.getCursor() == Item.DEFAULT_CURSOR) {
     318                        PaintNonLinesNonPicture(FreeItems.getCursor());
     319                }
     320        }
     321
     322        private static void PaintNonLinesNonPicture(List<Item> toPaint)
     323        {
     324                for (Item i : toPaint) {
     325                        if (!(i instanceof Line) && !(i instanceof XRayable)) {
     326                                PaintItem(i);
     327                        }
     328                }
    746329        }
    747330
     
    752335         * @param toPaint
    753336         */
    754         private static void PaintLines(Graphics2D g, List<Item> toPaint) {
     337        private static void PaintLines(List<Item> toPaint)
     338        {
    755339                // Use this set to keep track of the items that have been painted
    756340                Collection<Item> done = new HashSet<Item>();
    757                 for (Item i : toPaint)
     341                for (Item i : toPaint) {
    758342                        if (i instanceof Line) {
    759343                                Line l = (Line) i;
    760344                                if (done.contains(l)) {
    761                                         l.paintArrows(g);
     345                                        l.paintArrows();
    762346                                } else {
    763347                                        // When painting a line all connected lines are painted too
    764348                                        done.addAll(l.getAllConnected());
    765                                         if (l.getStartItem().getEnclosedArea() == 0)
    766                                                 PaintItem(g, i);
    767                                 }
    768                         }
     349                                        if (l.getStartItem().getEnclosedArea() == 0) PaintItem(i);
     350                                }
     351                        }
     352                }
    769353        }
    770354
     
    776360         * @param toPaint
    777361         */
    778         private static void PaintPictures(Graphics2D g, List<Item> toPaint,
    779                         HashSet<Item> fillOnlyItems, HashSet<Item> done) {
     362        private static void PaintPictures(List<Item> toPaint, HashSet<Item> fillOnlyItems, HashSet<Item> done)
     363        {
    780364
    781365                List<Item> toFill = new LinkedList<Item>();
     
    783367                        // Ignore items that have already been done!
    784368                        // Also ignore invisible items..
    785                         // TODO possibly ignore invisible items before coming to this
    786                         // method?
    787                         if (done.contains(i))
    788                                 continue;
     369                        // TODO possibly ignore invisible items before coming to this method?
     370                        if (done.contains(i)) continue;
     371                       
    789372                        if (i instanceof XRayable) {
    790373                                toFill.add(i);
     
    792375                        } else if (i.hasEnclosures()) {
    793376                                for (Item enclosure : i.getEnclosures()) {
    794                                         if (!toFill.contains(enclosure))
    795                                                 toFill.add(enclosure);
     377                                        if (!toFill.contains(enclosure)) toFill.add(enclosure);
    796378                                }
    797379                                done.addAll(i.getConnected());
    798                         } else if (i.isLineEnd()
    799                                         && (!isAudienceMode() || !i.isConnectedToAnnotation())) {
     380                        } else if (i.isLineEnd() && (!DisplayController.isAudienceMode() || !i.isConnectedToAnnotation())) {
    800381                                toFill.add(i);
    801382                                done.addAll(i.getAllConnected());
     
    805386                if (fillOnlyItems != null) {
    806387                        for (Item i : fillOnlyItems) {
    807                                 if (done.contains(i))
     388                                if (done.contains(i)) {
    808389                                        continue;
    809                                 else if (!isAudienceMode() || !i.isConnectedToAnnotation()) {
     390                                } else if (!DisplayController.isAudienceMode() || !i.isConnectedToAnnotation()) {
    810391                                        toFill.add(i);
    811392                                }
     
    821402                                int cmp = aArea.compareTo(bArea);
    822403                                if (cmp == 0) {
    823                                         // System.out.println(a.getEnclosureID() + " " +
    824                                         // b.getID());\
    825404                                        // Shapes to the left go underneath
    826                                         Polygon pA = a.getEnclosedShape();
    827                                         Polygon pB = b.getEnclosedShape();
    828                                         if (pA == null || pB == null)
    829                                                 return 0;
    830                                         return new Integer(pA.getBounds().x).compareTo(pB
    831                                                         .getBounds().x);
     405                                        PolygonBounds pA = a.getEnclosedShape();
     406                                        PolygonBounds pB = b.getEnclosedShape();
     407                                        if (pA == null || pB == null) return 0;
     408                                        return new Integer(pA.getMinX()).compareTo(pB.getMinX());
    832409                                }
    833410                                return cmp * -1;
    834411                        }
    835412                });
     413               
    836414                for (Item i : toFill) {
    837415                        if (i instanceof XRayable) {
    838                                 PaintItem(g, i);
     416                                PaintItem(i);
    839417                        } else {
    840418                                // Paint the fill and lines
    841                                 i.paintFill(g);
     419                                i.paintFill();
    842420                                List<Line> lines = i.getLines();
    843                                 if (lines.size() > 0)
    844                                         PaintItem(g, lines.get(0));
    845                         }
     421                                if (lines.size() > 0) PaintItem(lines.get(0));
     422                        }
     423                }
     424        }
     425
     426        /** Displays the given Item on the screen. */
     427        static void PaintItem(Item i)
     428        {
     429                if (i == null) return;
     430
     431                // do not paint annotation items in audience mode
     432                if (!DisplayController.isAudienceMode() || (!i.isConnectedToAnnotation() && !i.isAnnotation()) || i == FrameUtils.getLastEdited())
     433                {
     434                        i.paint();
    846435                }
    847436        }
     
    862451                        // Check if within 20% of the end of the line
    863452                        Line l = (Line) i;
    864                         Item toDisconnect = l.getEndPointToDisconnect(Math
    865                                         .round(FrameMouseActions.MouseX), Math
    866                                         .round(FrameMouseActions.MouseY));
     453                        Item toDisconnect = l.getEndPointToDisconnect(DisplayController.getMousePosition());
    867454
    868455                        // Brook: Widget Edges do not have such a context
    869456                        if (toDisconnect != null && !(i instanceof WidgetEdge)) {
    870457                                Item.HighlightMode newMode = toDisconnect.getHighlightMode();
    871                                 if (FreeItems.itemsAttachedToCursor())
     458                                if (FreeItems.hasItemsAttachedToCursor())
    872459                                        newMode = Item.HighlightMode.Normal;
    873460                                // unhighlight all the other dots
    874461                                for (Item conn : toDisconnect.getAllConnected()) {
    875462                                        conn.setHighlightMode(Item.HighlightMode.None);
     463                                        conn.setHighlightColorToDefault();
    876464                                }
    877465                                l.setHighlightMode(newMode);
     466                                l.setHighlightColorToDefault();
    878467                                // highlight the dot that will be in disconnect mode
    879468                                toDisconnect.setHighlightMode(newMode);
     469                                toDisconnect.setHighlightColorToDefault();
    880470                                i = toDisconnect;
    881471                        } else {
    882                                 if(FrameMouseActions.isShiftDown()) {
     472                                if (StandardInputEventListeners.kbmStateListener.isKeyDown(Key.SHIFT)) {
    883473                                        for(Item j : i.getAllConnected()) {
    884474                                        if(j instanceof Dot && !j.equals(i)) {
    885475                                                j.setHighlightMode(HighlightMode.None);
     476                                                j.setHighlightColorToDefault();
    886477                                        }
    887478                                }
    888479                                l.getStartItem().setHighlightMode(HighlightMode.Connected);
     480                                l.getStartItem().setHighlightColorToDefault();
    889481                                l.getEndItem().setHighlightMode(HighlightMode.Connected);
     482                                l.getEndItem().setHighlightColorToDefault();
    890483                        } else {
    891484                                for(Item j : i.getAllConnected()) {
    892485                                        if(j instanceof Dot && !j.equals(i)) {
    893486                                                j.setHighlightMode(HighlightMode.Connected);
     487                                                j.setHighlightColorToDefault();
    894488                                        }
    895489                                }
     
    902496                } else if (i instanceof Circle) {
    903497                        i.setHighlightMode(Item.HighlightMode.Connected);
     498                        i.setHighlightColorToDefault();
    904499                } else if (!i.isVisible()) {
    905500                        changeHighlightMode(i, Item.HighlightMode.Connected, null);
     
    913508                        // highlight connected dots, but only if there aren't items being carried on the cursor
    914509                        if(FreeItems.getInstance().size() == 0) {
    915                         if(FrameMouseActions.isShiftDown()) {
     510                        if (StandardInputEventListeners.kbmStateListener.isKeyDown(Key.SHIFT)) {
    916511                                for(Item j : i.getAllConnected()) {
    917512                                        if(j instanceof Dot && !j.equals(i)) {
    918513                                                j.setHighlightMode(HighlightMode.Connected);
     514                                                j.setHighlightColorToDefault();
    919515                                        }
    920516                                }
     
    923519                                        if(j instanceof Dot && !j.equals(i)) {
    924520                                                j.setHighlightMode(HighlightMode.None);
     521                                                j.setHighlightColorToDefault();
    925522                                        }
    926523                                }
     
    928525                                        Item j = l.getOppositeEnd(i);
    929526                                        j.setHighlightMode(HighlightMode.Connected);
     527                                        j.setHighlightColorToDefault();
    930528                                }
    931529                        }
     
    936534                        // For polygons need to make sure all other endpoints are
    937535                        // unHighlighted
    938                         if (i.hasPermission(UserAppliedPermission.full))
    939                                 changeHighlightMode(i, Item.HighlightMode.Normal,
    940                                                 Item.HighlightMode.None);
    941                         else
    942                                 changeHighlightMode(i, Item.HighlightMode.Connected,
    943                                                 Item.HighlightMode.Connected);
    944                 }
    945                 Repaint();
     536                        if (i.hasPermission(UserAppliedPermission.full)) {
     537                                changeHighlightMode(i, Item.HighlightMode.Normal, Item.HighlightMode.None);
     538                        } else {
     539                                changeHighlightMode(i, Item.HighlightMode.Connected, Item.HighlightMode.Connected);
     540                        }
     541                }
     542                DisplayController.requestRefresh(true);
    946543                return i;
    947544        }
    948545
    949         public static void changeHighlightMode(Item item, Item.HighlightMode newMode) {
     546        public static void changeHighlightMode(Item item, Item.HighlightMode newMode)
     547        {
    950548                changeHighlightMode(item, newMode, newMode);
    951549        }
    952550
    953         public static void changeHighlightMode(Item item,
    954                         Item.HighlightMode newMode, Item.HighlightMode connectedNewMode) {
    955                 if (item == null)
    956                         return;
     551        public static void changeHighlightMode(Item item, Item.HighlightMode newMode, Item.HighlightMode connectedNewMode)
     552        {
     553                if (item == null) return;
    957554
    958555                if (item.hasVector()) {
     
    960557                                if (i.getEditTarget() == item) {
    961558                                        i.setHighlightMode(newMode);
     559                                        i.setHighlightColorToDefault();
    962560                                }
    963561                        }
    964562                        item.setHighlightMode(newMode);
     563                        item.setHighlightColorToDefault();
    965564                } else {
    966565                        // Mike: TODO comment on why the line below is used!!
    967                         // I forgot already!!Opps
     566                        // I forgot already!! Oops
    968567                        boolean freeItem = FreeItems.getInstance().contains(item);
    969568                        for (Item i : item.getAllConnected()) {
    970569                                if (/* freeItem || */!FreeItems.getInstance().contains(i)) {
    971570                                        i.setHighlightMode(connectedNewMode);
    972                                 }
    973                         }
    974                         if (!freeItem && newMode != connectedNewMode)
     571                                        i.setHighlightColorToDefault();
     572                                }
     573                        }
     574                        if (!freeItem && newMode != connectedNewMode) {
    975575                                item.setHighlightMode(newMode);
    976                 }
    977                 Repaint();
    978         }
    979 
    980         /**
    981          * Repaints the buffer of the given Frame.
    982          *
    983          * @param toUpdate
    984          *            The Frame whose buffer is to be repainted.
    985          */
    986 
    987         public static void UpdateBuffer(Frame toUpdate, boolean paintOverlays,
    988                         boolean useVolitile) {
    989                 toUpdate.setBuffer(getBuffer(toUpdate, paintOverlays, useVolitile));
    990         }
    991 
    992         public static Image getBuffer(Frame toUpdate, boolean paintOverlays,
    993                         boolean useVolitile) {
    994                 if (toUpdate == null)
    995                         return null;
    996 
    997                 return Paint(toUpdate, null, paintOverlays, useVolitile);
    998         }
    999 
    1000         public static int getMode() {
    1001                 return _Mode;
    1002         }
    1003 
    1004         public static Graphics createGraphics() {
    1005                 // Error messages on start up will call this message before
    1006                 // _DisplayGraphics has been initialised
    1007                 if (_DisplayGraphics == null)
    1008                         return null;
    1009                 return _DisplayGraphics.create();
    1010         }
    1011 
    1012         // Damaged areas pending to render. Accessessed by multiple threads
    1013         private static HashSet<Rectangle> damagedAreas = new HashSet<Rectangle>();
    1014 
    1015         /** The clip used while paiting */
    1016         private static Area currentClip;
    1017 
    1018         /**
    1019          * The current clip that is used for painting at this instant.
    1020          *
    1021          * Intention: for extra clipping within an items paint method - the clip is
    1022          * lost in the graphics object for which can be regained via this method.
    1023          *
    1024          * @return The current clip. Null if no clip (e.g. full screen render).
    1025          */
    1026         public static Area getCurrentClip() {
    1027                 return (currentClip != null) ? (Area) currentClip.clone() : null;
    1028         }
    1029 
    1030         /**
    1031          * Checks that the item is visible (on current frame && overlays) - if
    1032          * visible then damaged area will be re-rendered on the next refresh.
    1033          *
    1034          * @param damagedItem
    1035          * @param toRepaint
    1036          */
    1037         public static void invalidateItem(Item damagedItem, Rectangle toRepaint) {
    1038                 // Only add area to repaint if item is visible...
    1039                 if (ItemUtils.isVisible(damagedItem)) {
    1040                         synchronized (damagedAreas) {
    1041                                 damagedAreas.add(toRepaint);
    1042                         }
    1043                 } else if (MessageBay.isMessageItem(damagedItem)) {
    1044                         MessageBay.addDirtyArea(toRepaint);
    1045                 }
    1046         }
    1047 
    1048         /**
    1049          * The given area will be re-rendered in the next refresh. This is the
    1050          * quicker version and is more useful for re-rendering animated areas.
    1051          *
    1052          * @param toRepaint
    1053          */
    1054         public static void invalidateArea(Rectangle toRepaint) {
    1055                 synchronized (damagedAreas) {
    1056                         damagedAreas.add(toRepaint);
    1057                 }
    1058         }
    1059 
    1060         public static void clearInvalidAreas() {
    1061                 synchronized (damagedAreas) {
    1062                         damagedAreas.clear();
    1063                 }
    1064         }
    1065 
    1066         /**
    1067          * Invalidates the buffered image of the current Frame and forces it to be
    1068          * repainted on to the screen. Repaints all items. This is more expensive
    1069          * than refresh.
    1070          */
    1071         public static void ForceRepaint() { // TODO: TEMP: Use refresh
    1072                 Frame current = DisplayIO.getCurrentFrame();
    1073 
    1074                 if (current == null)
    1075                         return;
    1076                 refresh(false);
    1077         }
    1078 
    1079         public static void Repaint() { // TODO: TEMP: Use refresh
    1080                 refresh(true);
    1081         }
    1082 
    1083         /**
    1084          * Called to refresh the display screen. Thread safe.
    1085          */
    1086         public static void refresh(boolean useInvalidation) {
    1087 
    1088                 if (_DisplayGraphics == null || _MaxSize.width <= 0
    1089                                 || _MaxSize.height <= 0)
    1090                         return;
    1091 
    1092                 currentClip = null;
    1093                 if (useInvalidation) { // build clip
    1094 
    1095                         synchronized (damagedAreas) {
    1096                                 if (!damagedAreas.isEmpty()) {
    1097 
    1098                                         for (Rectangle r : damagedAreas) {
    1099                                                 if (currentClip == null)
    1100                                                         currentClip = new Area(r);
    1101                                                 else
    1102                                                         currentClip.add(new Area(r));
    1103                                         }
    1104                                         damagedAreas.clear();
    1105 
    1106                                 } else if (MessageBay.isDirty()) {
    1107                                         // Paint dirty message bay
    1108                                         Graphics dg = _DisplayGraphics.create();
    1109                                         MessageBay.refresh(true, dg, Item.DEFAULT_BACKGROUND);
    1110                                         return;
    1111 
    1112                                 } else
    1113                                         return; // nothing to render
    1114                         }
    1115 
    1116                 } else {
    1117                         synchronized (damagedAreas) {
    1118                                 damagedAreas.clear();
    1119                         }
    1120                         // System.out.println("FULLSCREEN REFRESH"); // TODO: REMOVE
    1121                 }
    1122 
    1123                 Frame[] toPaint = DisplayIO.getFrames();
    1124                 Image left = Paint(toPaint[0], currentClip);
    1125                 Image right = Paint(toPaint[1], currentClip);
    1126 
    1127                 Graphics dg = _DisplayGraphics.create();
    1128 
    1129                 // Paint frame to window
    1130                 Paint(dg, left, right, Item.DEFAULT_BACKGROUND);
    1131 
    1132                 // Paint any animations
    1133                 PopupManager.getInstance().paintAnimations();
    1134 
    1135                 // Paint message bay
    1136                 MessageBay.refresh(useInvalidation, dg, Item.DEFAULT_BACKGROUND);
    1137 
    1138                 dg.dispose();
    1139         }
    1140 
    1141         /**
    1142          * If wanting to refresh from another thread - other than the main thread
    1143          * that handles the expeditee datamodel (modifying / accessing / rendering).
    1144          * Use this method for thread safety.
    1145          */
    1146         public static synchronized void requestRefresh(boolean useInvalidation) {
    1147 
    1148                 _requestMarsheller._useInvalidation = useInvalidation;
    1149 
    1150                 if (_requestMarsheller._isQueued) {
    1151                         return;
    1152                 }
    1153 
    1154                 _requestMarsheller._isQueued = true;
    1155                 EventQueue.invokeLater(_requestMarsheller); // Render on AWT thread
    1156         }
    1157 
    1158         private static RenderRequestMarsheller _requestMarsheller = new FrameGraphics().new RenderRequestMarsheller();
    1159 
    1160         /**
    1161          * Used for marshelling render requests from foreign threads to the event
    1162          * dispatcher thread... (AWT)
    1163          *
    1164          * @author Brook Novak
    1165          */
    1166         private class RenderRequestMarsheller implements Runnable {
    1167 
    1168                 boolean _useInvalidation = true;
    1169 
    1170                 boolean _isQueued = false;
    1171 
    1172                 public void run() {
    1173                         refresh(_useInvalidation);
    1174                         _isQueued = false;
    1175                         _useInvalidation = true;
    1176                 }
    1177 
    1178         }
    1179 
     576                                item.setHighlightColorToDefault();
     577                        }
     578                }
     579                DisplayController.requestRefresh(true);
     580        }
     581
     582        /*
     583         *
     584         * FrameRenderPass stuff. (TODO: Not sure if this is used for anything? In Apollo. cts16)
     585         *
     586         */
     587       
    1180588        /**
    1181589         * Adds a FinalFrameRenderPass to the frame-render pipeline...
     
    1221629         * situations.
    1222630         *
    1223          * Although if there are multiples FinalFrameRenderPasses attatach to the
    1224          * frame painter then it is not garaunteed to be rendered very last.
     631         * Although if there are multiples FinalFrameRenderPasses attach to the
     632         * frame painter then it is not guaranteed to be rendered very last.
    1225633         *
    1226634         * @see FrameGraphics#addFinalFrameRenderPass(org.expeditee.gui.FrameGraphics.FrameRenderPass)
     
    1236644                 *
    1237645                 * @return The clip that the pass should use instead. i.e. if there are
    1238                  *         any effects that cannot invladate prior to paint call.
     646                 *         any effects that cannot invalidate prior to paint call.
    1239647                 */
    1240                 Area paintStarted(Area currentClip);
    1241 
    1242                 void paintFinalPass(Graphics g);
    1243 
    1244                 void paintPreLayeredPanePass(Graphics g);
     648                Clip paintStarted(Clip currentClip);
     649
     650                void paintFinalPass();
     651
     652                void paintPreLayeredPanePass();
    1245653        }
    1246654
  • trunk/src/org/expeditee/gui/FrameIO.java

    r997 r1102  
    195195        }
    196196
    197         public static Frame LoadFrame(String frameName, String path,
    198                         boolean ignoreAnnotations) {
    199                 if (!isValidFrameName(frameName))
    200                         return null;
     197        public static Frame LoadFrame(String frameName, String path, boolean ignoreAnnotations)
     198        {
     199                if (!isValidFrameName(frameName)) return null;
    201200
    202201                String frameNameLower = frameName.toLowerCase();
    203202                // first try reading from cache
    204203                if (isCacheOn() && _Cache.containsKey(frameNameLower)) {
    205                         Logger.Log(Logger.SYSTEM, Logger.LOAD, "Loading " + frameName
    206                                         + " from cache.");
     204                        Logger.Log(Logger.SYSTEM, Logger.LOAD, "Loading " + frameName + " from cache.");
    207205                        Frame frame = _Cache.get(frameNameLower);
    208206                        return frame;
     
    389387
    390388        public static boolean canAccessFrame(String frameName) {
    391                 Frame current = DisplayIO.getCurrentFrame();
     389                Frame current = DisplayController.getCurrentFrame();
    392390                // Just in case the current frame is not yet saved...
    393391                if (frameName.equals(current.getName())) {
     
    490488
    491489                _UseCache = false;
    492                 Frame fresh = FrameIO.LoadFrame(DisplayIO.getCurrentFrame().getName());
     490                Frame fresh = FrameIO.LoadFrame(DisplayController.getCurrentFrame().getName());
    493491                _UseCache = cache;
    494492                if (_Cache.containsKey(fresh.getName().toLowerCase()))
    495493                        addToCache(fresh);
    496                 DisplayIO.setCurrentFrame(fresh, false);
     494                DisplayController.setCurrentFrame(fresh, false);
    497495        }
    498496
     
    599597
    600598        public static Frame LoadZero() {
    601                 Frame current = DisplayIO.getCurrentFrame();
     599                Frame current = DisplayController.getCurrentFrame();
    602600                return LoadZero(current.getFramesetName(), current.getPath());
    603601        }
    604602
    605603        public static Frame LoadLast() {
    606                 Frame current = DisplayIO.getCurrentFrame();
     604                Frame current = DisplayController.getCurrentFrame();
    607605                return LoadLast(current.getFramesetName(), current.getPath());
    608606        }
    609607
    610608        public static Frame LoadNext() {
    611                 return LoadNext(DisplayIO.getCurrentFrame());
     609                return LoadNext(DisplayController.getCurrentFrame());
    612610        }
    613611
    614612        public static Frame LoadPrevious() {
    615                 return LoadPrevious(DisplayIO.getCurrentFrame());
     613                return LoadPrevious(DisplayController.getCurrentFrame());
    616614        }
    617615
     
    747745                }
    748746
    749                 // Remove the old frame from the cashe then add the new one
     747                // Remove the old frame from the cache then add the new one
    750748                // TODO figure out some way that we can put both in the cache
    751749                _Cache.remove(template.getName().toLowerCase());
     
    770768                Item titleItem = template.getTitleItem();
    771769
    772                 if (!DisplayIO.isTwinFramesOn() && !Justification.center.equals(((Text)titleItem).getJustification())) {
     770                if (!DisplayController.isTwinFramesOn() && !Justification.center.equals(((Text)titleItem).getJustification())) {
    773771                        if ((titleItem.getX() + 1) < template.getNameItem().getX()) {
    774772                                while (titleItem.getSize() > Text.MINIMUM_FONT_SIZE
     
    811809        }
    812810
    813         public static void RefreshCasheImages() {
     811        public static void RefreshCacheImages()
     812        {
    814813                SuspendCache();
    815                 for (Frame f : _Cache.values())
    816                         f.setBuffer(null);
     814                for (Frame frame : _Cache.values()) frame.setBuffer(null);
    817815                ResumeCache();
    818816        }
     
    11521150         * @return true if the frame is in the current user profile frameset
    11531151         */
    1154         public static boolean isProfileFrame(Frame toCheck) {
    1155                 if (toCheck.getNumber() == 0)
    1156                         return false;
     1152        public static boolean isProfileFrame(Frame toCheck)
     1153        {
     1154                if (toCheck.getNumber() == 0) return false;
     1155               
    11571156                return toCheck.getPath().equals(PROFILE_PATH);
    11581157                // return toCheck.getFramesetName()
     
    11601159        }
    11611160
    1162         public static Frame LoadProfile(String userName) {
     1161        public static Frame LoadProfile(String userName)
     1162        {
    11631163                return LoadFrame(userName + "1");
    11641164        }
     
    12991299                String templateLink = linker.getAbsoluteLinkTemplate();
    13001300                String framesetLink = linker.getAbsoluteLinkFrameset();
    1301                 String frameset = (framesetLink != null ? framesetLink : DisplayIO
     1301                String frameset = (framesetLink != null ? framesetLink : DisplayController
    13021302                                .getCurrentFrame().getFramesetName());
    13031303
     
    13221322         */
    13231323        public static Frame CreateNewFrameset(String name) throws Exception {
    1324                 String path = DisplayIO.getCurrentFrame().getPath();
     1324                String path = DisplayController.getCurrentFrame().getPath();
    13251325
    13261326                // if current frameset is profile directory change it to framesets
     
    13941394        }
    13951395
    1396         public static Frame CreateFrameset(String frameset, String path,
    1397                         boolean recreate) throws Exception {
     1396        public static Frame CreateFrameset(String frameset, String path, boolean recreate) throws Exception
     1397        {
    13981398                String conversion = frameset + " --> ";
    13991399
    1400                 if (!isValidFramesetName(frameset)) {
    1401                         throw new Exception("Invalid frameset name");
    1402                 }
     1400                if (!isValidFramesetName(frameset)) throw new Exception("Invalid frameset name");
    14031401
    14041402                if (!recreate && FrameIO.canAccessFrameset(frameset)) {
     
    14741472                SaveFrame(base, true);
    14751473
    1476                 Logger.Log(Logger.SYSTEM, Logger.NEW_FRAMESET, "Created new frameset: "
    1477                                 + frameset);
     1474                Logger.Log(Logger.SYSTEM, Logger.NEW_FRAMESET, "Created new frameset: " + frameset);
    14781475
    14791476                return base;
  • trunk/src/org/expeditee/gui/FrameKeyboardActions.java

    r1077 r1102  
    1919package org.expeditee.gui;
    2020
    21 import java.awt.Color;
    22 import java.awt.Rectangle;
    2321import java.awt.Toolkit;
    2422import java.awt.datatransfer.StringSelection;
    2523import java.awt.event.KeyEvent;
    2624import java.awt.event.KeyListener;
    27 import java.awt.geom.Point2D;
    2825import java.text.NumberFormat;
    2926import java.util.ArrayList;
     
    3734import org.expeditee.actions.Navigation;
    3835import org.expeditee.actions.Simple;
     36import org.expeditee.core.AxisAlignedBoxBounds;
     37import org.expeditee.core.Colour;
     38import org.expeditee.core.Point;
    3939import org.expeditee.gui.indirect.keyboard.IndirectKeyboardActions;
    4040import org.expeditee.gui.indirect.keyboard.KeyboardAction;
     
    5151import org.expeditee.items.XRayable;
    5252import org.expeditee.items.MagneticConstraint.MagneticConstraints;
    53 import org.expeditee.items.widgets.InteractiveWidget;
     53/*import org.expeditee.items.widgets.InteractiveWidget; TODO: Reinstate. cts16
    5454import org.expeditee.items.widgets.WidgetCorner;
    55 import org.expeditee.items.widgets.WidgetEdge;
     55import org.expeditee.items.widgets.WidgetEdge;*/
    5656import org.expeditee.settings.experimental.ExperimentalFeatures;
    5757import org.expeditee.settings.templates.TemplateSettings;
     
    6060import org.expeditee.stats.SessionStats;
    6161
    62 public class FrameKeyboardActions implements KeyListener {
     62public class FrameKeyboardActions {
    6363
    6464        private static FrameKeyboardActions _instance = new FrameKeyboardActions();
    6565
    6666        protected FrameKeyboardActions() {
    67                 IndirectKeyboardActions.getInstance().setDropDownAction(
     67                /*IndirectKeyboardActions.getInstance().setDropDownAction(
    6868                                new KeyboardAction() {
    6969                                        @Override
     
    8282                                                } else {
    8383                                                        // Move to the top of the box
    84                                                         Rectangle rect = info.firstConnected
    85                                                                         .getEnclosedShape().getBounds();
    86                                                         int newX = rect.x + Text.MARGIN_LEFT;
     84                                                        AxisAlignedBoxBounds rect = info.firstConnected.getBounds();
     85                                                        int newX = rect.getMinX() + Text.MARGIN_LEFT;
    8786                                                        int newY = Text.MARGIN_LEFT
    88                                                                         + rect.y
     87                                                                        + rect.getMinY()
    8988                                                                        + DisplayIO.getCurrentFrame()
    9089                                                                                        .getItemTemplate()
     
    171170                                                return null;
    172171                                        }
    173                                 });
     172                                });*/
    174173                IndirectKeyboardActions.getInstance().setCreateNewTextAction(
    175174                                new KeyboardAction() {
     
    179178                                                                "" + c);
    180179
    181                                                 Point2D.Float newMouse = t.insertChar(c,
    182                                                                 DisplayIO.getMouseX(), FrameMouseActions.getY());
    183                                                 DisplayIO.setCursorPosition(newMouse.x, newMouse.y,
    184                                                                 false);
     180                                                Point newMouse = t.insertChar(c, DisplayIO.getMouseX(), FrameMouseActions.getY());
     181                                                DisplayIO.setCursorPosition(newMouse.x, newMouse.y, false);
    185182
    186183                                                return t;
     
    192189                                        public Text exec(final KeyboardInfo info, final char c) {
    193190                                                float oldY = FrameMouseActions.MouseY;
    194                                                 Point2D.Float newMouse = null;
     191                                                Point newMouse = null;
    195192                                                if (c == '\t') {
    196193                                                        if (info.isShiftDown) {
     
    212209                                                        // float diff = newMouse.y - oldY;
    213210                                                        // System.out.print("c");
    214                                                         Rectangle rect = info.firstConnected.getPolygon().getBounds();
     211                                                        AxisAlignedBoxBounds rect = info.firstConnected.getBounds();
    215212
    216213                                                        // Text lastEdited = FrameUtils.getLastEdited();
     
    218215
    219216                                                        Item justBelow = FrameUtils.onItem(DisplayIO.getCurrentFrame(),
    220                                                                         info.firstConnected.getX() + 10, rect.y + rect.height + 1, false);
     217                                                                        info.firstConnected.getX() + 10, rect.getMinY() + rect.getHeight() + 1, false);
    221218
    222219                                                        // FrameUtils.setLastEdited(lastEdited);
     
    242239        }
    243240
    244         private static Text _toRemove = null;
    245 
    246         private static Collection<Item> _enclosedItems = null;
    247 
    248         public static void resetEnclosedItems() {
    249                 _enclosedItems = null;
    250         }
    251 
    252241        public synchronized void keyTyped(KeyEvent e) {
    253242                if (Simple.isProgramRunning()) {
    254                         if (e.isControlDown()
    255                                         && (e.getKeyChar() == KeyEvent.VK_ESCAPE || e.getKeyChar() == KeyEvent.VK_C)) {
     243                        if (e.isControlDown() && (e.getKeyChar() == KeyEvent.VK_ESCAPE || e.getKeyChar() == KeyEvent.VK_C)) {
    256244                                Simple.stop();
    257245                                return;
     
    262250                                Simple.KeyStroke(e.getKeyChar());
    263251                        }
    264                         if (Simple.consumeKeyboardInput())
    265                                 return;
     252                       
     253                        if (Simple.consumeKeyboardInput()) return;
    266254                }
    267255
     
    284272                // System.out.println(ch);
    285273
    286                 if (e.isAltDown()) {
    287 
    288                 } else {
    289                         processChar(ch, e.isShiftDown());
    290                 }
     274                if (!e.isAltDown()) processChar(ch, e.isShiftDown());
    291275                // FrameGraphics.Repaint();
    292         }
    293 
    294         public static void processChar(char ch, boolean isShiftDown) {
    295                 Navigation.ResetLastAddToBack();
    296                 Item on = FrameUtils.getCurrentItem();
    297 
    298                 // permission check
    299                 if (on != null && !on.hasPermission(UserAppliedPermission.full)) {
    300                         MessageBay
    301                                         .displayMessage("Insufficient permission to edit this item");
    302                         return;
    303                 }
    304 
    305                 if (isShiftDown && MagneticConstraints.getInstance().keyHit(-ch, on))
    306                         return;
    307                 else if (MagneticConstraints.getInstance().keyHit(ch, on))
    308                         return;
    309 
    310                 if (_toRemove != null && on != _toRemove) {
    311                         assert (_toRemove.getLength() == 0);
    312                         // This line is to protect mistaken removal of items if there is a
    313                         // bug...
    314                         if (_toRemove.getLength() == 0)
    315                                 DisplayIO.getCurrentFrame().removeItem(_toRemove);
    316                 }
    317                 _toRemove = null;
    318 
    319                 // ignore delete and backspace if in free space
    320                 if ((on == null || !(on instanceof Text))
    321                                 && (ch == KeyEvent.VK_BACK_SPACE || ch == KeyEvent.VK_TAB || ch == KeyEvent.VK_DELETE))
    322                         return;
    323 
    324                 SessionStats.TypedChar(ch);
    325 
    326                 // check for dot's being replaced with text
    327                 if (on != null && on instanceof Dot && !(on instanceof WidgetCorner)) {
    328                         if (ch == KeyEvent.VK_BACK_SPACE || ch == KeyEvent.VK_DELETE) {
    329                                 return;
    330                         }
    331                         replaceDot((Item) on, ch);
    332                         return;
    333                 }
    334 
    335                 // only text can interact with keyboard events
    336                 if (on != null && !(on instanceof Text))
    337                         on = null;
    338 
    339                 // DisplayIO.UpdateTitle();
    340 
    341                 Text text = (Text) on;
    342                 // if this text is empty but has not been removed (such as from
    343                 // ESC-pushdown)
    344                 if (text != null && text.isEmpty()
    345                                 && (ch == KeyEvent.VK_BACK_SPACE || ch == KeyEvent.VK_DELETE)) {
    346                         if (text.getLines().size() > 0)
    347                                 replaceText(text);
    348                         else {
    349                                 DisplayIO.setCursor(Item.DEFAULT_CURSOR);
    350                         }
    351                         return;
    352                 }
    353 
    354                 // if the user is in free space, create a new text item
    355                 /*
    356                  * MikeSays: Why do we have to check is highlighted... doing so causes
    357                  * problems if you type characters to fast, they turn into multiple text
    358                  * items. ie. JK together on the Linux laptop.
    359                  */
    360                 if (on == null /* || !on.isHighlighted() */) {
    361                         // DisplayIO.UpdateTitle();
    362                         text = createText(ch);
    363                         text.justify(false);
    364 
    365                         FrameUtils.setLastEdited(text);
    366                         DisplayIO.setTextCursor(text, Text.NONE);
    367                         return;
    368                 } else {
    369                         FrameUtils.setLastEdited(text);
    370                 }
    371 
    372                 DisplayIO.setTextCursor(text, Text.NONE);
    373                 IndirectKeyboardActions.getInstance().getInsertCharacterAction()
    374                                 .exec(new KeyboardInfo(null, ch, isShiftDown, isShiftDown,
    375                                                 _enclosedItems, text, _enclosedItems, _enclosedItems), ch);
    376 
    377                 // This repaint is needed for WINDOWS only?!?!? Mike is not sure why!
    378                 if (ch == KeyEvent.VK_DELETE)
    379                         FrameGraphics.requestRefresh(true);
    380 
    381                 // a change has occured to the Frame
    382                 text.getParent().setChanged(true);
    383 
    384                 // check that the Text item still exists (hasn't been deleted\backspaced
    385                 // away)
    386                 if (text.isEmpty()) {
    387                         _toRemove = text;
    388 
    389                         if (text.hasAction())
    390                                 text.setActionMark(true);
    391                         else if (text.getLink() != null)
    392                                 text.setLinkMark(true);
    393                         else if (text.getLines().size() > 0)
    394                                 replaceText(text);
    395                         else {
    396                                 // DisplayIO.getCurrentFrame().removeItem(text);
    397                                 DisplayIO.setCursor(Item.DEFAULT_CURSOR);
    398                         }
    399                 }
    400         }
    401 
    402         public static Text replaceDot(Item dot, char ch) {
    403                 Text text = createText(ch);
    404                 Item.DuplicateItem(dot, text);
    405                 FrameUtils.setLastEdited(text);
    406 
    407                 // Copy the lines list so it can be modified
    408                 List<Line> lines = new LinkedList<Line>(dot.getLines());
    409                 for (Line line : lines)
    410                         line.replaceLineEnd(dot, text);
    411                 Frame current = dot.getParentOrCurrentFrame();
    412                 current.removeItem(dot);
    413                 ItemUtils.EnclosedCheck(current.getItems());
    414                 return text;
    415         }
    416 
    417         /**
    418          * Replaces the given text item with a dot
    419          */
    420         public static Item replaceText(Item text) {
    421                 Item dot = new Dot(text.getX(), text.getY(), text.getID());
    422                 Item.DuplicateItem(text, dot);
    423 
    424                 List<Line> lines = new LinkedList<Line>();
    425                 lines.addAll(text.getLines());
    426                 if (lines.size() > 0)
    427                         dot.setColor(lines.get(0).getColor());
    428                 for (Line line : lines) {
    429                         line.replaceLineEnd(text, dot);
    430                 }
    431                 text.delete();
    432                 Frame current = text.getParentOrCurrentFrame();
    433                 current.addItem(dot);
    434                 DisplayIO.setCursor(Item.DEFAULT_CURSOR);
    435                 ItemUtils.EnclosedCheck(current.getItems());
    436                 return dot;
    437         }
    438 
    439         /**
    440          * Creates a new Text Item whose text contains the given character. This
    441          * method also moves the mouse cursor to be pointing at the newly created
    442          * Text Item ready to insert the next character.
    443          *
    444          * @param start
    445          *            The character to use as the initial text of this Item.
    446          * @return The newly created Text Item
    447          */
    448         private static Text createText(char start) {
    449                 return IndirectKeyboardActions.getInstance().getCreateNewTextAction()
    450                                 .exec(new KeyboardInfo(null, start, false, false, _enclosedItems, _toRemove, _enclosedItems, _enclosedItems), start);
    451         }
    452 
    453         /**
    454          * Creates a new Text Item with no text. The newly created Item is a copy of
    455          * any ItemTemplate if one is present, and inherits all the attributes of
    456          * the Template
    457          *
    458          * @return The newly created Text Item
    459          */
    460         private static Text createText() {
    461                 return DisplayIO.getCurrentFrame().createNewText();
    462         }
    463 
    464         private void move(int direction, boolean isShiftDown, boolean isCtrlDown) {
    465                 Item on = FrameUtils.getCurrentItem();
    466 
    467                 if ((on == null) || (on instanceof Picture)){
    468                         navigateFrame(direction);
    469                         return;
    470                 }
    471 
    472                 if (on instanceof Text) {
    473                         Text text = (Text) on;
    474                         // When the user hits the left and right button with mouse
    475                         // positions over the the frame name navigation occurs
    476                         if (text.isFrameName()) {
    477                                 navigateFrame(direction);
    478                                 return;
    479                         } else {
    480                                 FrameUtils.setLastEdited(text);
    481                                 DisplayIO.setTextCursor(text, direction, false, isShiftDown,
    482                                                 isCtrlDown, true);
    483                         }
    484                 }
    485         }
    486 
    487         private void navigateFrame(int direction) {
    488                 switch (direction) {
    489                 case Text.RIGHT:
    490                 case Text.PAGE_UP:
    491                         Navigation.NextFrame(false);
    492                         break;
    493                 case Text.LEFT:
    494                 case Text.PAGE_DOWN:
    495                         Navigation.PreviousFrame(false);
    496                         break;
    497                 case Text.HOME:
    498                 case Text.LINE_HOME:
    499                         Navigation.ZeroFrame();
    500                         break;
    501                 case Text.END:
    502                 case Text.LINE_END:
    503                         Navigation.LastFrame();
    504                         break;
    505                 }
    506276        }
    507277
     
    515285                int keyCode = e.getKeyCode();
    516286
    517                 if (keyCode != KeyEvent.VK_F1 && keyCode != KeyEvent.VK_F2) {
     287                // Empty the list of enclosed items if not a size-up or size-down press
     288/*              if (keyCode != KeyEvent.VK_F1 && keyCode != KeyEvent.VK_F2) {
    518289                        resetEnclosedItems();
    519290                }
    520291
     292                // Notify the change in stats
     293                // TODO: Will changing this to the Expeditee KBMInputEvent upset stats? cts16
    521294                SessionStats.AddFrameEvent("k" + KeyEvent.getKeyText(keyCode));
    522295
     296                // Used for calculating frame stats (response time)
    523297                FrameUtils.ResponseTimer.restart();
    524298                // e.consume();
    525299
     300                // Things that should consume input before main Expeditee
    526301                if (Actions.isAgentRunning()) {
    527302                        if (keyCode == KeyEvent.VK_ESCAPE)
     
    534309                }
    535310
     311                // Function keys are handled here
    536312                if (keyCode >= KeyEvent.VK_F1 && keyCode <= KeyEvent.VK_F12) {
    537                         functionKey(FunctionKey.values()[keyCode - KeyEvent.VK_F1 + 1],
    538                                         e.isShiftDown(), e.isControlDown());
    539                         return;
    540                 } else if (e.isAltDown()) {
     313                        functionKey(FunctionKey.values()[keyCode - KeyEvent.VK_F1 + 1], e.isShiftDown(), e.isControlDown());
     314                        return;
     315                }*/
     316               
     317                // Keyboard for mouse emulation
     318                // TODO: Do we need individual mouse button clicks? Are the corresponding gestures enough? cts16
     319                if (e.isAltDown()) {
    541320                        int distance = e.isShiftDown() ? 1 : 20;
    542321                        switch (keyCode) {
     
    553332                                FrameMouseActions.rightButton();
    554333                                break;
    555                         case KeyEvent.VK_LEFT:
     334/*                      case KeyEvent.VK_LEFT:
    556335                                DisplayIO.translateCursor(-distance, 0);
    557336                                break;
     
    564343                        case KeyEvent.VK_DOWN:
    565344                                DisplayIO.translateCursor(0, distance);
    566                                 break;
    567                         }
    568                         return;
    569                 }
     345                                break;*/
     346                        }
     347                        return;
     348                }
     349               
     350                // Notify the mouse handler of the control/shift key state
    570351                switch (keyCode) {
    571352                case KeyEvent.VK_CONTROL:
     
    577358                }
    578359
     360                // Handles all CTRL+KEY combinations
    579361                if (e.isControlDown()) {
    580362                        controlChar(e.getKeyCode(), e.isShiftDown());
     
    582364                }
    583365
    584                 switch (keyCode) {
     366                // Handles all other keystrokes (with possible shift modifier)
     367                // Note: At this point e.isControlDown() must be false
     368/*              switch (keyCode) {
    585369                case KeyEvent.VK_ESCAPE:
    586                         // Do escape after control so Ctl+Escape does not perform DropDown
    587                         functionKey(FunctionKey.DropDown, e.isShiftDown(),
    588                                         e.isControlDown());
     370                        // Do escape after control so Ctrl+Escape does not perform DropDown
     371                        functionKey(FunctionKey.DropDown, e.isShiftDown(), false);
    589372                        SessionStats.Escape();
    590373                        break;
    591374                case KeyEvent.VK_LEFT:
    592                         move(Text.LEFT, e.isShiftDown(), e.isControlDown());
     375                        move(Text.LEFT, e.isShiftDown(), false);
    593376                        break;
    594377                case KeyEvent.VK_RIGHT:
    595                         move(Text.RIGHT, e.isShiftDown(), e.isControlDown());
     378                        move(Text.RIGHT, e.isShiftDown(), false);
    596379                        break;
    597380                case KeyEvent.VK_PAGE_DOWN:
     
    602385                        break;
    603386                case KeyEvent.VK_UP:
    604                         if (e.isControlDown()) {
    605                                 NextTextItem(FrameUtils.getCurrentItem(), false);
    606                         } else {
    607                                 move(Text.UP, e.isShiftDown(), e.isControlDown());
    608                         }
     387                        move(Text.UP, e.isShiftDown(), false);
    609388                        break;
    610389                case KeyEvent.VK_DOWN:
    611                         if (e.isControlDown()) {
    612                                 NextTextItem(FrameUtils.getCurrentItem(), true);
    613                         } else {
    614                                 move(Text.DOWN, e.isShiftDown(), e.isControlDown());
    615                         }
     390                        move(Text.DOWN, e.isShiftDown(), false);
    616391                        break;
    617392                case KeyEvent.VK_END:
    618                         if (e.isControlDown())
    619                                 move(Text.END, e.isShiftDown(), e.isControlDown());
    620                         else
    621                                 move(Text.LINE_END, e.isShiftDown(), e.isControlDown());
     393                        move(Text.LINE_END, e.isShiftDown(), false);
    622394                        break;
    623395                case KeyEvent.VK_HOME:
    624                         if (e.isControlDown())
    625                                 move(Text.HOME, e.isShiftDown(), e.isControlDown());
    626                         else
    627                                 move(Text.LINE_HOME, e.isShiftDown(), e.isControlDown());
     396                        move(Text.LINE_HOME, e.isShiftDown(), false);
    628397                        break;
    629398                // TODO remove this when upgrading Java
     
    636405                        }
    637406                        break;
    638                 }
    639         }
    640 
    641         /**
    642          * Moves the cursor to the next text item on the frame
    643          *
    644          * @param currentItem
    645          * @param direction
    646          *            move up if direction is negative, down if direction is
    647          *            positive
    648          */
    649         public static void NextTextItem(Item currentItem, boolean down) {
    650                 // Move the cursor to the next text item
    651                 Frame current = DisplayIO.getCurrentFrame();
    652                 Text title = current.getTitleItem();
    653 
    654                 Collection<Text> currentItems = FrameUtils.getCurrentTextItems();
    655                 List<Text> textItems = new ArrayList<Text>();
    656                 // Move to the next text item in the box if
    657                 if (currentItems.contains(currentItem)) {
    658                         textItems.addAll(currentItems);
    659                 } else {
    660                         if (title != null)
    661                                 textItems.add(title);
    662                         textItems.addAll(current.getBodyTextItems(true));
    663                 }
    664 
    665                 Collections.sort(textItems);
    666 
    667                 if (textItems.size() == 0) {
    668                         // If there are no text items on the frame its a NoOp
    669                         if (title == null)
    670                                 return;
    671                         if (title != null)
    672                                 DisplayIO.MoveCursorToEndOfItem(title);
    673                         FrameGraphics.Repaint();
    674                         return;
    675                 }
    676 
    677                 // If the user is mouse wheeling in free space...
    678                 if (currentItem == null) {
    679                         // find the nearest item in the correct direction
    680                         int currY = FrameMouseActions.getY();
    681                         for (int i = 0; i < textItems.size(); i++) {
    682                                 Item t = textItems.get(i);
    683                                 if (currY < t.getY()) {
    684                                         if (down) {
    685                                                 DisplayIO.MoveCursorToEndOfItem(t);
    686                                         } else {
    687                                                 if (i == 0) {
    688                                                         DisplayIO.MoveCursorToEndOfItem(current
    689                                                                         .getTitleItem());
    690                                                 } else {
    691                                                         DisplayIO.MoveCursorToEndOfItem(textItems
    692                                                                         .get(i - 1));
    693                                                 }
    694                                         }
    695                                         FrameGraphics.Repaint();
    696                                         return;
    697                                 }
    698                         }
    699                         // If we are at the botton of the screen and the user scrolls down
    700                         // then scroll backup to the title
    701                         if (textItems.size() > 0) {
    702                                 DisplayIO
    703                                                 .MoveCursorToEndOfItem(textItems.get(textItems.size() - 1));
    704                         }
    705                         return;
    706                 }
    707 
    708                 // Find the current item... then move to the next item
    709                 int i = textItems.indexOf(currentItem);
    710 
    711                 int nextIndex = i + (down ? 1 : -1);
    712                 if (nextIndex >= 0 && nextIndex < textItems.size()) {
    713                         DisplayIO.MoveCursorToEndOfItem(textItems.get(nextIndex));
    714                 } else {
    715                         DisplayIO.MoveCursorToEndOfItem(currentItem);
    716                 }
    717                 return;
    718 
     407                }*/
    719408        }
    720409
     
    739428        }
    740429
    741         private static void copyItemToClipboard(Item on) {
    742                 if (on == null || !(on instanceof Text))
    743                         return;
    744 
    745                 Text text = (Text) on;
    746                 String string = text.copySelectedText();
    747 
    748                 if (string == null || string.length() == 0)
    749                         string = text.getText();
    750 
    751                 // add the text of the item to the clipboard
    752                 StringSelection selection = new StringSelection(string);
    753                 Toolkit.getDefaultToolkit().getSystemClipboard()
    754                                 .setContents(selection, null);
    755         }
    756 
    757430        /**
    758431         * Processes all control character keystrokes. Currently Ctrl+C and Ctrl+V
     
    763436         */
    764437        private void controlChar(int key, boolean isShiftDown) {
    765                 Logger.Log(Logger.USER, Logger.CONTROL_CHAR, "User pressing: Ctrl+"
    766                                 + KeyEvent.getKeyText(key));
     438                //Logger.Log(Logger.USER, Logger.CONTROL_CHAR, "User pressing: Ctrl+" + KeyEvent.getKeyText(key));
    767439                //
    768440                // if (FrameUtils.getCurrentItem() == null
     
    776448                int distance = isShiftDown ? 1 : 20;
    777449                switch (key) {
    778                 case KeyEvent.VK_HOME:
     450/*              case KeyEvent.VK_HOME:
    779451                        if (current != null && current instanceof Text) {
    780452                                move(Text.HOME, isShiftDown, true);
     
    802474                        break;
    803475                case KeyEvent.VK_ESCAPE:
    804                         // Do escape after control so Ctl+Escape does not perform DropDown
     476                        // Do escape after control so Ctrl+Escape does not perform DropDown
    805477                        functionKey(FunctionKey.DropDown, isShiftDown, true);
    806                         SessionStats.Escape();
     478                        SessionStats.Escape();*/
    807479                        break;
    808480                case KeyEvent.VK_1:
     
    819491                        break;
    820492                case KeyEvent.VK_LEFT:
    821                         if (current instanceof Text) {
    822                                 DisplayIO.setTextCursor((Text) current, Text.LEFT, false,
    823                                                 isShiftDown, true, true);
    824                         } else {
     493/*                      if (current instanceof Text) {
     494                                DisplayIO.setTextCursor((Text) current, Text.LEFT, false, isShiftDown, true, true);
     495                        } else */{
    825496                                DisplayIO.translateCursor(-distance, 0);
    826497                        }
    827498                        break;
    828499                case KeyEvent.VK_RIGHT:
    829                         if (current instanceof Text) {
    830                                 DisplayIO.setTextCursor((Text) current, Text.RIGHT, false,
    831                                                 isShiftDown, true, true);
    832                         } else {
     500/*                      if (current instanceof Text) {
     501                                DisplayIO.setTextCursor((Text) current, Text.RIGHT, false, isShiftDown, true, true);
     502                        } else */{
    833503                                DisplayIO.translateCursor(distance, 0);
    834504                        }
    835505                        break;
    836                 case KeyEvent.VK_UP:
     506/*              case KeyEvent.VK_UP:
    837507                        // if (current instanceof Text) {
    838508                        NextTextItem(FrameUtils.getCurrentItem(), false);
     
    849519                        break;
    850520                case KeyEvent.VK_L:
    851                         // If its not linked then link it to its self
     521                        // If its not linked then link it to itself
    852522                        if (current instanceof Text && current.getLink() == null) {
    853523                                String text = ((Text) current).getText();
     
    866536                        }
    867537                        break;
    868                 case KeyEvent.VK_G:
    869                         // If its not linked then link it to its self
     538                case KeyEvent.VK_G: // Same as CTRL+L but follows it afterwards
     539                        // If its not linked then link it to itself
    870540                        if (current instanceof Text) {
    871541                                String text = ((Text) current).getText();
     
    922592                        return;
    923593                case KeyEvent.VK_C:
    924                         if (FreeItems.itemsAttachedToCursor()) {
     594                        if (FreeItems.hasItemsAttachedToCursor()) {
    925595                                ItemSelection.copyClone();
    926596                                return;
     
    933603                        if (current instanceof Dot && current.getLines().size() == 1) {
    934604                                item = replaceDot(current, '@');
    935                         } else if (current instanceof Line
    936                                         && current.getAllConnected().size() == 3) {
     605                        } else if (current instanceof Line && current.getAllConnected().size() == 3) {
    937606                                Item end = ((Line) current).getEndItem();
    938607                                if (end instanceof Dot) {
     
    955624                        if (current == null)
    956625                                return;
    957                         if (current != null
    958                                         && !current.hasPermission(UserAppliedPermission.full)) {
    959                                 MessageBay
    960                                                 .displayMessage("Insufficient permission toggle the items mark");
    961                                 return;
    962                         }
    963                         boolean newValue = !(current.getLinkMark() || current
    964                                         .getActionMark());
     626                        if (current != null && !current.hasPermission(UserAppliedPermission.full)) {
     627                                MessageBay.displayMessage("Insufficient permission toggle the items mark");
     628                                return;
     629                        }
     630                        boolean newValue = !(current.getLinkMark() || current.getActionMark());
    965631                        current.setLinkMark(newValue);
    966632                        current.setActionMark(newValue);
     
    980646                        // perform a delete operation
    981647                        FrameMouseActions.delete(current);
    982                         break;
     648                        break;*/
    983649                case KeyEvent.VK_SPACE:
    984650                        if (isShiftDown) {
     
    988654                        }
    989655                        break;
    990                 case KeyEvent.VK_F:
     656/*              case KeyEvent.VK_F:
    991657                        // perform a format operation
    992658                        if (isShiftDown) {
     
    1012678                        break;
    1013679
    1014                 case KeyEvent.VK_R:
     680                case KeyEvent.VK_R: // TODO: What is this? Similar to above? cts16
    1015681                        Text textCurrent = getCurrentTextItem();
    1016682                        if (textCurrent == null) {
     
    1026692                        break;
    1027693                case KeyEvent.VK_S:
    1028                         /*
    1029                          * Only split when shift is down... it is too easy to accidentally
    1030                          * hit Ctrl+S after completing a paragraph because this is the
    1031                          * shortcut for saving a document in most word processors and text
    1032                          * editors!
    1033                          */
     694                        // Only split when shift is down... it is too easy to accidentally
     695                        // hit Ctrl+S after completing a paragraph because this is the
     696                        // shortcut for saving a document in most word processors and text
     697                        // editors!
    1034698                        if (!isShiftDown) {
    1035699                                Save();
     
    1057721                                currentFrame.addItem(newText);
    1058722                        }
    1059                         break;
     723                        break;*/
    1060724                case KeyEvent.VK_ENTER:
    1061725                        FrameMouseActions.leftButton();
    1062726                        break;
    1063                 case KeyEvent.VK_BACK_SPACE:
     727/*              case KeyEvent.VK_BACK_SPACE:
    1064728                        DisplayIO.Back();
    1065                         break;
     729                        break;*/
    1066730                }
    1067731                FrameGraphics.Repaint();
     
    1078742
    1079743                if (item != null && !item.hasPermission(UserAppliedPermission.full)) {
    1080                         MessageBay
    1081                                         .displayMessage("Insufficient permission to copy that item");
     744                        MessageBay.displayMessage("Insufficient permission to copy that item");
    1082745                        return null;
    1083746                }
     
    1093756        }
    1094757
    1095         public static void functionKey(FunctionKey key, boolean isShiftDown,
    1096                         boolean isControlDown) {
     758/*      public static void functionKey(FunctionKey key, boolean isShiftDown, boolean isControlDown)
     759        {
    1097760                functionKey(key, 1, isShiftDown, isControlDown);
    1098761        }
    1099 
     762*/
    1100763        /**
    1101764         * Called when a Function key has been pressed, and performs the specific
    1102765         * action based on the key.
    1103766         */
    1104         public static void functionKey(FunctionKey key, int repeat,
    1105                         boolean isShiftDown, boolean isControlDown) {
     767/*      public static void functionKey(FunctionKey key, int repeat, boolean isShiftDown, boolean isControlDown)
     768        {
    1106769                // get whatever the user is pointing at
    1107770                Item on = FrameUtils.getCurrentItem();
     
    1195858                        }
    1196859                }
     860                               
    1197861                // Show a description of the function key pressed if the user is in free
    1198862                // space and return for the F keys that dont do anything in free space.
    1199863                if (on == null) {
    1200864                       
    1201                         int mouse_x = FrameMouseActions.getX(), mouse_y = FrameMouseActions.getY();
     865                        // int mouse_x = FrameMouseActions.getX(), mouse_y = FrameMouseActions.getY();
    1202866                       
    1203867                        switch (key) {
    1204868                        // These function keys still work in free space
    1205                         case DropDown:
    1206                         case InsertDate:
     869//                      case DropDown:
     870//                      case InsertDate:
    1207871                        case XRayMode:
    1208872                        case AudienceMode:
    1209873                        case Refresh:
    1210                         case Save:
     874//                      case Save:
    1211875                                break;
    1212876                               
     
    1244908                                }
    1245909                        }
    1246                         Drop(on, false);
     910//                      Drop(on, false);
    1247911                        return;
    1248912                case SizeUp:
    1249913                        SetSize(on, repeat, true, false, isControlDown);
    1250914                        if (on instanceof Text) {
    1251                                 DisplayIO.setTextCursor((Text) on, Text.NONE, true, false,
    1252                                                 false, true);
     915                                DisplayIO.setTextCursor((Text) on, Text.NONE, true, false, false, true);
    1253916                        }
    1254917                        break;
     
    1256919                        SetSize(on, -repeat, true, false, isControlDown);
    1257920                        if (on instanceof Text) {
    1258                                 DisplayIO.setTextCursor((Text) on, Text.NONE, true, false,
    1259                                                 false, true);
     921                                DisplayIO.setTextCursor((Text) on, Text.NONE, true, false, false, true);
    1260922                        }
    1261923                        break;
     
    1300962                        MessageBay.displayMessage(displayMessage);
    1301963        }
    1302 
    1303         private static void calculateItem(Item toCalculate) {
    1304                 if (toCalculate == null)
    1305                         return;
    1306 
    1307                 if (!toCalculate.update()) {
    1308                         toCalculate.setFormula(null);
    1309                         MessageBay.errorMessage("Can not calculate formula ["
    1310                                         + toCalculate.getText() + ']');
    1311                 }
    1312         }
    1313 
    1314         public static void Save() {
    1315                 Frame current = DisplayIO.getCurrentFrame();
    1316                 current.change();
    1317                 FrameIO.SaveFrame(current, true, true);
    1318         }
    1319 
    1320         public static final String DEFAULT_NEW_ITEM_TEXT = "";
    1321 
    1322         /**
    1323          * Performs the dropping action: If the cursor is in free space then: the
    1324          * cursor is repositioned below the last non-annotation text item. If the
    1325          * cursor is on an item, and has items attached then: the cusor is
    1326          * positioned below the pointed to item, and the items below are 'pushed
    1327          * down' to make room.
    1328          *
    1329          * @param toDropFrom
    1330          *            The Item being pointed at by the mouse, may be null to
    1331          *            indicate the cursor is in free space.
    1332          */
    1333         public static boolean Drop(Item toDropFrom, boolean bPasting) {
    1334                 try {
    1335                         FrameUtils.setLastEdited(null);
    1336 
    1337                         String newItemText = DEFAULT_NEW_ITEM_TEXT;
    1338 
    1339                         // if a line is being rubber-banded, this is a no-op
    1340                         if (Frame.rubberbandingLine())
    1341                                 return false; // No-op
    1342 
    1343                         // if the cursor is in free space then the drop will happen from the
    1344                         // last non annotation text item on the frame
    1345                         if (toDropFrom == null) {
    1346                                 toDropFrom = DisplayIO.getCurrentFrame()
    1347                                                 .getLastNonAnnotationTextItem();
    1348                         }
    1349 
    1350                         // if no item was found, return
    1351                         if (toDropFrom == null) {
    1352                                 MessageBay.errorMessage("No item could be found to drop from");
    1353                                 return false;
    1354                         }
    1355 
    1356                         if (!(toDropFrom instanceof Text)) {
    1357                                 MessageBay
    1358                                                 .displayMessage("Only text items can be dropped from");
    1359                                 return false;
    1360                         }
    1361 
    1362                         // Get the list of items that must be dropped
    1363                         List<Text> column = DisplayIO.getCurrentFrame().getColumn(
    1364                                         toDropFrom);
    1365 
    1366                         if (column == null) {
    1367                                 MessageBay.errorMessage("No column found to align items to");
    1368                                 return false;
    1369                         }
    1370 
    1371                         Item title = DisplayIO.getCurrentFrame().getTitleItem();
    1372 
    1373                         // We wont do auto bulleting when dropping from titles
    1374                         if (!bPasting && toDropFrom != title) {
    1375                                 newItemText = getAutoBullet(((Text) toDropFrom).getFirstLine());
    1376                         }
    1377 
    1378                         Text dummyItem = null;
    1379                         if (!bPasting && FreeItems.textOnlyAttachedToCursor()) {
    1380                                 dummyItem = (Text) FreeItems.getItemAttachedToCursor();
    1381                                 String autoBullet = getAutoBullet(dummyItem.getText());
    1382 
    1383                                 if (autoBullet.length() > 0)
    1384                                         newItemText = "";
    1385                                 dummyItem.setText(newItemText + dummyItem.getText());
    1386                         }
    1387 
    1388                         dummyItem = createText();
    1389                         if (FreeItems.textOnlyAttachedToCursor()) {
    1390                                 Text t = (Text) FreeItems.getItemAttachedToCursor();
    1391                                 dummyItem.setSize(t.getSize());
    1392                                 int lines = t.getTextList().size();
    1393                                 for (int i = 0; i < lines; i++) {
    1394                                         newItemText += '\n';
    1395                                 }
    1396                         }
    1397 
    1398                         dummyItem.setText(newItemText);
    1399 
    1400                         // If the only item on the frame is the title and the frame name
    1401                         // goto the zero frame and drop to the @start if there is one
    1402                         // or a fixed amount if there is not
    1403                         if (column.size() == 0) {
    1404                                 Frame current = DisplayIO.getCurrentFrame();
    1405                                 // Item itemTemplate = current.getItemTemplate();
    1406                                 int xPos = title.getX() + FrameCreator.INDENT_FROM_TITLE;
    1407                                 int yPos = FrameCreator.getYStart(title);
    1408                                 // Check for @start on the zero frame
    1409                                 Frame zero = FrameIO.LoadFrame(current.getFramesetName() + '0');
    1410                                 Text start = zero.getAnnotation("start");
    1411                                 if (start != null) {
    1412                                         xPos = start.getX();
    1413                                         yPos = start.getY();
    1414                                 }
    1415 
    1416                                 dummyItem.setPosition(xPos, yPos);
    1417                                 // DisplayIO.setCursorPosition(xPos, yPos);
    1418 
    1419                                 checkMovingCursor(dummyItem);
    1420                         } else {
    1421                                 int yPos = column.get(0).getY() + 1;
    1422                                 int xPos = column.get(0).getX();
    1423                                 // Either position the new item below the title or just above
    1424                                 // the first item below the title
    1425                                 if (toDropFrom == title && column.get(0) != title) {
    1426                                         // If dropping from the title position just above top item
    1427                                         yPos = column.get(0).getY() - 1;
    1428 
    1429                                         Frame current = DisplayIO.getCurrentFrame();
    1430                                         // Check for @start on the zero frame
    1431                                         Frame zero = FrameIO
    1432                                                         .LoadFrame(current.getFramesetName() + '0');
    1433                                         Text start = zero.getAnnotation("start");
    1434                                         if (start != null) {
    1435                                                 yPos = Math.min(yPos, start.getY());
    1436                                         }
    1437                                 }
    1438                                 dummyItem.setPosition(xPos, yPos);
    1439                                 column.add(dummyItem);
    1440                                 FrameUtils.Align(column, false, 0);
    1441                                 // Check if it will be outside the frame area
    1442                                 if (dummyItem.getY() < 0
    1443                                                 || dummyItem.getY() > FrameGraphics.getMaxFrameSize()
    1444                                                                 .getHeight()) {
    1445                                         // Check for the 'next' tag!
    1446                                         Frame current = DisplayIO.getCurrentFrame();
    1447                                         Item next = current.getAnnotation("next");
    1448                                         Item prev = current.getAnnotation("previous");
    1449                                         // Check for an unlinked next tag
    1450                                         if ((next != null && !next.hasLink())
    1451                                                         || (prev != null && prev.hasLink())) {
    1452                                                 Frame firstFrame = current;
    1453                                                 if (next != null)
    1454                                                         next.delete();
    1455                                                 FrameCreator frameCreator = new FrameCreator(null);
    1456                                                 // Add the next button
    1457                                                 next = frameCreator.addNextButton(current, null);
    1458 
    1459                                                 // Create the new frame linked to the next tag
    1460                                                 boolean mouseMoved = FrameMouseActions.tdfc(next);
    1461                                                 Frame moreFrame = DisplayIO.getCurrentFrame();
    1462 
    1463                                                 // Add previous button to the new frame
    1464                                                 frameCreator.addPreviousButton(moreFrame,
    1465                                                                 firstFrame.getName());
    1466                                                 Item first = current.getAnnotation("first");
    1467                                                 if (first != null) {
    1468                                                         frameCreator.addFirstButton(moreFrame,
    1469                                                                         first.getLink());
    1470                                                 } else {
    1471                                                         frameCreator.addFirstButton(moreFrame,
    1472                                                                         firstFrame.getName());
    1473                                                 }
    1474                                                 // Add the @next if we are pasting
    1475                                                 // if (bPasting) {
    1476                                                 // Item copy = next.copy();
    1477                                                 // copy.setLink(null);
    1478                                                 // moreFrame.addItem(copy);
    1479                                                 // }
    1480 
    1481                                                 moreFrame.setTitle(firstFrame.getTitleItem().getText());
    1482                                                 // need to move the mouse to the top of the frame if
    1483                                                 // there wasnt an @start on it
    1484                                                 if (!mouseMoved) {
    1485                                                         Item moreTitle = moreFrame.getTitleItem();
    1486                                                         moreTitle
    1487                                                                         .setOverlayPermission(UserAppliedPermission.full);
    1488                                                         Drop(moreTitle, bPasting);
    1489                                                 }
    1490                                                 // Add the bullet text to the item
    1491                                                 dummyItem.setPosition(DisplayIO.getMouseX(),
    1492                                                                 FrameMouseActions.getY());
    1493                                         } else {
    1494                                                 MessageBay
    1495                                                                 .warningMessage("Can not create items outside the frame area");
    1496                                                 // ensures correct repainting when items don't move
    1497                                                 DisplayIO.setCursorPosition(DisplayIO.getMouseX(),
    1498                                                                 FrameMouseActions.getY());
    1499                                                 return false;
    1500                                         }
    1501                                 }
    1502                                 if (!FreeItems.textOnlyAttachedToCursor()
    1503                                                 && !dummyItem.isEmpty()) {
    1504                                         DisplayIO.getCurrentFrame().addItem(dummyItem);
    1505                                 }
    1506 
    1507                                 checkMovingCursor(dummyItem);
    1508                         }
    1509                         if (dummyItem.getText().length() == 0
    1510                                         || FreeItems.itemsAttachedToCursor()) {
    1511                                 dummyItem.getParentOrCurrentFrame().removeItem(dummyItem);
    1512                                 dummyItem.setRightMargin(FrameGraphics.getMaxFrameSize().width,
    1513                                                 false);
    1514                         } else {
    1515                                 dummyItem.setWidth(toDropFrom.getWidth());
    1516                         }
    1517 
    1518                         DisplayIO.resetCursorOffset();
    1519                         FrameGraphics.Repaint();
    1520                 } catch (RuntimeException e) {
    1521                         // MessageBay.errorMessage(e.getMessage());
    1522                         e.printStackTrace();
    1523                         return false;
    1524                 }
    1525                 return true;
    1526         }
    1527 
    1528         /**
    1529          * @param dummyItem
    1530          */
    1531         private static void checkMovingCursor(Text dummyItem) {
    1532                 // Move the item to the cursor position
    1533                 if (FreeItems.itemsAttachedToCursor()) {
    1534                         moveCursorAndFreeItems(dummyItem.getX(), dummyItem.getY());
    1535                 } else {
    1536                         DisplayIO.MoveCursorToEndOfItem(dummyItem);
    1537                 }
    1538         }
    1539 
    1540         /**
    1541          * @param dummyItem
    1542          */
    1543         public static void moveCursorAndFreeItems(int x, int y) {
    1544                 int oldX = FrameMouseActions.getX();
    1545                 int oldY = FrameMouseActions.getY();
    1546 
    1547                 if (oldX == x && oldY == y)
    1548                         return;
    1549 
    1550                 DisplayIO.setCursorPosition(x, y);
    1551                 Item firstItem = FreeItems.getItemAttachedToCursor();
    1552 
    1553                 if (firstItem == null) {
    1554                         firstItem = null;
    1555                         return;
    1556                 }
    1557 
    1558                 int deltaX = firstItem.getX() - x;
    1559                 int deltaY = firstItem.getY() - y;
    1560 
    1561                 for (Item i : FreeItems.getInstance()) {
    1562                         i.setPosition(i.getX() - deltaX, i.getY() - deltaY);
    1563                 }
    1564         }
    1565 
    1566         /**
    1567          * Gets the next letter sequence for a given string to be used in auto
    1568          * lettering.
    1569          *
    1570          * @param s
    1571          *            a sequence of letters
    1572          * @return the next sequence of letters
    1573          */
    1574         static private String nextLetterSequence(String s) {
    1575                 if (s.length() > 1)
    1576                         return s;
    1577 
    1578                 if (s.equals("z"))
    1579                         return "a";
    1580 
    1581                 return (char) ((int) s.charAt(0) + 1) + "";
    1582         }
    1583 
    1584         public static String getBullet(String s) {
    1585                 return getBullet(s, false);
    1586         }
    1587 
    1588         public static String getAutoBullet(String s) {
    1589                 return getBullet(s, true);
    1590         }
    1591 
    1592         private static String getBullet(String s, boolean nextBullet) {
    1593                 String newItemText = DEFAULT_NEW_ITEM_TEXT;
    1594 
    1595                 if (s == null)
    1596                         return newItemText;
    1597                 /*
    1598                  * Item i = ItemUtils.FindTag(DisplayIO.getCurrentFrame().getItems(),
    1599                  * "@NoAutoBullets"); if (i != null) return newItemText;
    1600                  */
    1601                 // Separate the space at the start of the text item
    1602                 String preceedingSpace = "";
    1603                 for (int i = 0; i < s.length(); i++) {
    1604                         if (!Character.isSpaceChar(s.charAt(i))) {
    1605                                 preceedingSpace = s.substring(0, i);
    1606                                 s = s.substring(i);
    1607                                 break;
    1608                         }
    1609                 }
    1610 
    1611                 // figure out the type of the text item
    1612                 // This allows us to do auto bulleting
    1613                 if (s != null && s.length() > 1) {
    1614                         // First check for text beginning with * @ # etc
    1615                         // These are simple auto bullets
    1616                         if (!Character.isLetterOrDigit(s.charAt(0))
    1617                                         && !Character.isSpaceChar(s.charAt(0))) {
    1618                                 if (Text.isBulletChar(s.charAt(0))) {
    1619                                         int nonSpaceIndex = 1;
    1620                                         // Find the end of the bullet and space after the bullet
    1621                                         while (nonSpaceIndex < s.length()
    1622                                                         && s.charAt(nonSpaceIndex) == ' ') {
    1623                                                 nonSpaceIndex++;
    1624                                         }
    1625                                         // we must have a special char followed by >= 1 space
    1626                                         if (nonSpaceIndex > 1)
    1627                                                 newItemText = s.substring(0, nonSpaceIndex);
    1628                                 }
    1629                                 // Auto numbering and lettering
    1630                         } else {
    1631                                 if (Character.isDigit(s.charAt(0))) {
    1632                                         newItemText = getAutoNumber(s, nextBullet);
    1633                                         // Auto lettering
    1634                                 } else if (Character.isLetter(s.charAt(0))) {
    1635                                         newItemText = getAutoLetter(s, nextBullet);
    1636                                 }
    1637                         }
    1638                 }
    1639                 return preceedingSpace + newItemText;
    1640         }
    1641 
    1642         private static boolean isAutoNumberOrLetterChar(char c) {
    1643                 return c == ':' || c == '-' || c == '.' || c == ')' || c == '>';
    1644         }
    1645 
    1646         /**
    1647          * Gets the string to be used to start the next auto numbered text item.
    1648          *
    1649          * @param s
    1650          *            the previous text item
    1651          * @return the beginning of the next auto numbered text item
    1652          */
    1653         private static String getAutoNumber(String s, boolean nextBullet) {
    1654                 String newItemText = DEFAULT_NEW_ITEM_TEXT;
    1655 
    1656                 int nonDigitIndex = 1;
    1657                 while (Character.isDigit(s.charAt(nonDigitIndex))) {
    1658                         nonDigitIndex++;
    1659 
    1660                         if (nonDigitIndex + 1 >= s.length())
    1661                                 return DEFAULT_NEW_ITEM_TEXT;
    1662                 }
    1663 
    1664                 if (isAutoNumberOrLetterChar(s.charAt(nonDigitIndex))) {
    1665 
    1666                         // we must have a number followed one non letter
    1667                         // then one or more spaces
    1668                         int nonSpaceIndex = nonDigitIndex + 1;
    1669                         while (nonSpaceIndex < s.length() && s.charAt(nonSpaceIndex) == ' ') {
    1670                                 nonSpaceIndex++;
    1671                         }
    1672 
    1673                         if (nonSpaceIndex > nonDigitIndex + 1) {
    1674                                 if (nextBullet)
    1675                                         newItemText = (Integer.parseInt(s.substring(0,
    1676                                                         nonDigitIndex)) + 1)
    1677                                                         + s.substring(nonDigitIndex, nonSpaceIndex);
    1678                                 else
    1679                                         newItemText = s.substring(0, nonSpaceIndex);
    1680                         }
    1681                 }
    1682                 return newItemText;
    1683         }
    1684 
    1685         /**
    1686          * Gets the string to be used to start the next auto lettered text item.
    1687          *
    1688          * @param s
    1689          *            the previous text items
    1690          * @return the initial text for the new text item
    1691          */
    1692         private static String getAutoLetter(String s, boolean nextBullet) {
    1693                 String newItemText = DEFAULT_NEW_ITEM_TEXT;
    1694 
    1695                 int nonLetterIndex = 1;
    1696 
    1697                 if (isAutoNumberOrLetterChar(s.charAt(nonLetterIndex))) {
    1698 
    1699                         // Now search for the next non space character
    1700                         int nonSpaceIndex = nonLetterIndex + 1;
    1701                         while (nonSpaceIndex < s.length() && s.charAt(nonSpaceIndex) == ' ') {
    1702                                 nonSpaceIndex++;
    1703                         }
    1704 
    1705                         // If there was a space then we have reached the end of our auto
    1706                         // text
    1707                         if (nonSpaceIndex > nonLetterIndex + 1) {
    1708                                 if (nextBullet)
    1709                                         newItemText = nextLetterSequence(s.substring(0,
    1710                                                         nonLetterIndex))
    1711                                                         + s.substring(nonLetterIndex, nonSpaceIndex);
    1712                                 else
    1713                                         newItemText = s.substring(0, nonSpaceIndex);
    1714                         }
    1715                 }
    1716                 return newItemText;
    1717         }
    1718 
    1719         private static boolean refreshAnchors(Collection<Item> items) {
    1720                 boolean bReparse = false;
    1721 
    1722                 for (Item i : items) {
    1723                         Float anchorLeft = i.getAnchorLeft();
    1724                         Float anchorRight = i.getAnchorRight();
    1725                         Float anchorTop = i.getAnchorTop();
    1726                         Float anchorBottom = i.getAnchorBottom();
    1727 
    1728                         if (anchorLeft != null) {
    1729                                 i.setAnchorLeft(anchorLeft);
    1730                                 if (i.hasVector()) {
    1731                                         bReparse = true;
    1732                                 }
    1733                         }
    1734 
    1735                         if (anchorRight != null) {
    1736                                 i.setAnchorRight(anchorRight);
    1737                                 if (i.hasVector()) {
    1738                                         bReparse = true;
    1739                                 }
    1740                         }
    1741 
    1742                         if (anchorTop != null) {
    1743                                 i.setAnchorTop(anchorTop);
    1744                                 if (i.hasVector()) {
    1745                                         bReparse = true;
    1746                                 }
    1747                         }
    1748 
    1749                         if (anchorBottom != null) {
    1750                                 i.setAnchorBottom(anchorBottom);
    1751                                 if (i.hasVector()) {
    1752                                         bReparse = true;
    1753                                 }
    1754                         }
    1755                 }
    1756                 return bReparse;
    1757         }
    1758 
    1759         protected static void zoomFrame(Frame frame, double scaleFactor, int x, int y) {
    1760 
    1761                 if (frame == null) {
    1762                         return;
    1763                 }
    1764 
    1765                 Collection<Item> items = frame.getVisibleItems();
    1766 
    1767                 for (Item item : items) {
    1768                         if (item instanceof Text
    1769                                         && item.getSize() <= Text.MINIMUM_FONT_SIZE
    1770                                         && scaleFactor < 1) {
    1771                                 return;
    1772                         }
    1773                 }
    1774 
    1775                 for (Vector v : frame.getVectors()) {
    1776                         v.Source.scale((float) scaleFactor, x, y);
    1777                 }
    1778 
    1779                 for (Item item : items) {
    1780                         // This line is only needed for circles!!
    1781                         // Need to really fix up the way this works!!
    1782                         if (item.hasEnclosures())
    1783                                 continue;
    1784                         if (!item.hasPermission(UserAppliedPermission.full))
    1785                                 continue;
    1786                         item.invalidateAll();
    1787                         if (!(item instanceof Line)) {
    1788                                 item.scale((float) scaleFactor, x, y);
    1789                         }
    1790                 }
    1791 
    1792                 for (Item item : items) {
    1793                         if (!item.hasPermission(UserAppliedPermission.full))
    1794                                 continue;
    1795                         // if (!(item instanceof Line))
    1796                         item.updatePolygon();
    1797 
    1798                         if (item instanceof Line) {
    1799                                 ((Line) item).refreshStroke(item.getThickness());
    1800                         }
    1801 
    1802                         item.invalidateAll();
    1803                 }
    1804         }
    1805 
    1806         public static boolean zoomFrameIfEnabled(Frame frame, double scaleFactor, int mouse_x, int mouse_y)
    1807         {
    1808                 boolean zoom_active = ExperimentalFeatures.FrameZoom.get();
    1809                
    1810                 if (zoom_active) {
    1811                        
    1812                         int x, y;
    1813                         if (ExperimentalFeatures.FrameZoomAroundCursor.get()) {
    1814                                 x = mouse_x;
    1815                                 y = mouse_y;
    1816                         }
    1817                         else {
    1818                                 x = 0;
    1819                                 y = 0;
    1820                         }
    1821                        
    1822                         zoomFrame(DisplayIO.getCurrentFrame(), scaleFactor, x, y);
    1823                         DisplayIO.getCurrentFrame().refreshSize();
    1824                         FrameKeyboardActions.Refresh();
    1825                 }
    1826                 else {
    1827                         String frameZoomingDisabledMessage = "Frame Zooming currently disabled. "
    1828                                         + "Access Settings->Experimental->FrameZoom and set to 'true' to enable this";
    1829                         MessageBay.displayMessageOnce(frameZoomingDisabledMessage);
    1830                 }
    1831                
    1832                 return zoom_active;
    1833         }
    1834        
    1835         public static boolean zoomFrameTopLeftIfEnabled(Frame frame, double scaleFactor)
    1836         {
    1837                 return zoomFrameIfEnabled(frame, scaleFactor, 0, 0);
    1838         }
    1839        
    1840         /**
    1841          * Adjusts the size of the given Item, by the given amount. Note: The amount
    1842          * is relative and can be positive or negative.
    1843          *
    1844          * @param toSet
    1845          *            The Item whose size is to be adjusted
    1846          * @param diff
    1847          *            The amount to adjust the Item's size by
    1848          * @param moveCursor
    1849          *            true if the cursor position should be automatically adjusted
    1850          *            with resizing
    1851          */
    1852         public static void SetSize(Item item, int diff, boolean moveCursor,
    1853                         boolean insideEnclosure, boolean isControlDown) {
    1854                 Collection<Item> toSize = new HashSet<Item>();
    1855                 Collection<InteractiveWidget> widgets = new HashSet<InteractiveWidget>();
    1856                 // the mouse is only moved when the Item is on the frame, not free
    1857                 // boolean moveMouse = false;
    1858                 Item toSet = null;
    1859 
    1860                 // if the user is not pointing to any item
    1861                 if (item == null) {
    1862                         if (FreeItems.itemsAttachedToCursor())
    1863                                 toSize.addAll(FreeItems.getInstance());
    1864                         else {
    1865                                 MessageBay
    1866                                                 .displayMessage("There are no Items selected on the Frame or on the Cursor");
    1867                                 return;
    1868                         }
    1869                 } else {
    1870                         if (item.isFrameName()) {
    1871                                 // scale the entire frame
    1872                                 if (diff != 0) {
    1873                                         double scaleFactor = diff > 0 ? 1.1 : 0.909090909;
    1874                                         zoomFrameTopLeftIfEnabled(DisplayIO.getCurrentFrame(), scaleFactor);
    1875                                 }
    1876                                 // MessageBay.displayMessage("Can not resize the frame name");
    1877                                 return;
    1878                         }
    1879                         // check permissions
    1880                         if (!item.hasPermission(UserAppliedPermission.full)) {
    1881                                 Item editTarget = item.getEditTarget();
    1882                                 if (editTarget != item
    1883                                                 && editTarget.hasPermission(UserAppliedPermission.full)) {
    1884                                         item = editTarget;
    1885                                 } else {
    1886                                         MessageBay
    1887                                                         .displayMessage("Insufficient permission to change the size of that item");
    1888                                         return;
    1889                                 }
    1890                         }
    1891                         toSet = item;
    1892                         // For resizing enclosures pick up everything that is attached to
    1893                         // items partly in the enclosure
    1894                         // TODO make this only pick up stuff COMPLETELY enclosed... if we
    1895                         // change copying to copy only the stuff completely enclosed
    1896                         if (insideEnclosure) {
    1897                                 if (_enclosedItems == null) {
    1898                                         for (Item i : FrameUtils.getCurrentItems(toSet)) {
    1899                                                 if (i.hasPermission(UserAppliedPermission.full)
    1900                                                                 && !toSize.contains(i))
    1901                                                         toSize.addAll(i.getAllConnected());
    1902                                         }
    1903                                         _enclosedItems = toSize;
    1904                                 } else {
    1905                                         toSize = _enclosedItems;
    1906                                 }
    1907 
    1908                         }// Enclosed circle centers are resized with the center as origin
    1909                                 // Just add the circle center to the list of items to size
    1910                         else if (!toSet.hasEnclosures() && !(toSet instanceof Text)
    1911                                         && toSet.isLineEnd()) {
    1912                                 toSize.addAll(toSet.getLines());
    1913                         } else if (toSet instanceof Line) {
    1914 
    1915                                 Line line = (Line) toSet;
    1916 
    1917                                 if (!(toSet instanceof WidgetEdge)
    1918                                                 || ((WidgetEdge) toSet).getWidgetSource()
    1919                                                                 .isWidgetEdgeThicknessAdjustable()) {
    1920 
    1921                                         float current = Math.abs(line.getThickness());
    1922                                         current = Math.max(current + diff, Item.MINIMUM_THICKNESS);
    1923                                         line.setThickness(current);
    1924                                         FrameGraphics.Repaint();
    1925                                         return;
    1926 
    1927                                 }
    1928 
    1929                         } else {
    1930                                 toSize.add(toSet);
    1931                         }
    1932                 }
    1933 
    1934                 // add widgets to notify
    1935                 for (Item i : toSize) {
    1936                         if (i instanceof WidgetEdge) {
    1937                                 widgets.add(((WidgetEdge) i).getWidgetSource());
    1938                         } else if (i instanceof WidgetCorner) {
    1939                                 widgets.add(((WidgetCorner) i).getWidgetSource());
    1940                         }
    1941                 }
    1942 
    1943                 Point2D origin = new Point2D.Float(FrameMouseActions.MouseX,
    1944                                 FrameMouseActions.MouseY);
    1945                 // Inside enclosures increase the size of the enclosure
    1946                 double ratio = (100.0 + diff * 2) / 100.0;
    1947                 if (insideEnclosure) {
    1948                         Collection<Item> done = new HashSet<Item>();
    1949                         // adjust the size of all the items
    1950                         for (Item i : toSize) {
    1951                                 if (done.contains(i))
    1952                                         continue;
    1953 
    1954                                 if (i.isLineEnd()) {
    1955 
    1956                                         if (!(i instanceof WidgetCorner)
    1957                                                         || !((WidgetCorner) i).getWidgetSource()
    1958                                                                         .isFixedSize()) { // don't size fixed
    1959                                                 // widgets
    1960 
    1961                                                 Collection<Item> allConnected = i.getAllConnected();
    1962                                                 done.addAll(allConnected);
    1963                                                 for (Item it : allConnected) {
    1964                                                         it.translate(origin, ratio);
    1965                                                         it.setArrowheadLength((float) (it
    1966                                                                         .getArrowheadLength() * ratio));
    1967                                                 }
    1968                                                 i.setThickness((float) (i.getThickness() * ratio));
    1969                                         }
    1970                                 } else if (i instanceof XRayable) {
    1971                                         XRayable xRay = (XRayable) i;
    1972                                         Text source = xRay.getSource();
    1973                                         // Ensure that the source is done before the XRayable
    1974                                         if (!done.contains(source)) {
    1975                                                 scaleText(insideEnclosure, origin, ratio, done, source);
    1976                                         }
    1977 
    1978                                         i.translate(origin, ratio);
    1979                                         i.setThickness((float) (i.getThickness() * ratio));
    1980                                         done.add(i);
    1981                                 } else if (i.hasVector()) {
    1982                                         // TODO Improve the effiency of resizing vectors... ie...
    1983                                         // dont want to have to reparse all the time
    1984                                         assert (i instanceof Text);
    1985                                         Text text = (Text) i;
    1986                                         AttributeValuePair avp = new AttributeValuePair(
    1987                                                         text.getText());
    1988                                         double scale = 1F;
    1989                                         try {
    1990                                                 scale = avp.getDoubleValue();
    1991                                         } catch (Exception e) {
    1992                                         }
    1993                                         scale *= ratio;
    1994                                         NumberFormat nf = Vector.getNumberFormatter();
    1995                                         text.setAttributeValue(nf.format(scale));
    1996                                         text.translate(origin, ratio);
    1997                                         item.getParent().parse();
    1998                                 } else if (i instanceof Text) {
    1999                                         scaleText(insideEnclosure, origin, ratio, done, (Text) i);
    2000                                 }
    2001                         }
    2002                         // refresh anchored items
    2003                         if (refreshAnchors(toSize)) {
    2004                                 FrameUtils.Parse(DisplayIO.getCurrentFrame(), false);
    2005                         }
    2006                         // notify widgets they were resized
    2007                         for (InteractiveWidget iw : widgets) {
    2008                                 iw.onResized();
    2009                         }
    2010                         FrameGraphics.refresh(true);
    2011                         return;
    2012                 }
    2013 
    2014                 // adjust the size of all the items
    2015                 for (Item i : toSize) {
    2016                         // Lines and dots use thickness, not size
    2017                         if (i.hasEnclosures()) {
    2018                                 Circle c = (Circle) i.getEnclosures().iterator().next();
    2019                                 c.setSize(c.getSize() * (float) ratio);
    2020                         } else if (i instanceof Line || i instanceof Circle
    2021                                         && !insideEnclosure) {
    2022                                 float current = Math.abs(i.getThickness());
    2023                                 current = Math.max(current + diff, Item.MINIMUM_THICKNESS);
    2024                                 i.setThickness(current);
    2025                         } else if (i instanceof Dot) {
    2026                                 Item dot = (Item) i;
    2027                                 float current = Math.abs(dot.getThickness());
    2028                                 current = Math.max(current + diff, Item.MINIMUM_THICKNESS);
    2029                                 dot.setThickness(current);
    2030                         } else if (i.hasVector()) {
    2031                                 assert (item instanceof Text);
    2032                                 Text text = (Text) item;
    2033                                 AttributeValuePair avp = new AttributeValuePair(text.getText());
    2034                                 double scale = 1F;
    2035                                 try {
    2036                                         scale = avp.getDoubleValue();
    2037                                 } catch (Exception e) {
    2038                                 }
    2039                                 scale *= ratio;
    2040                                 NumberFormat nf = Vector.getNumberFormatter();
    2041                                 text.setAttributeValue(nf.format(scale));
    2042                                 text.translate(origin, ratio);
    2043                                 item.getParent().parse();
    2044                         } else {
    2045                                 float oldSize = Math.abs(i.getSize());
    2046                                 float newSize = Math
    2047                                                 .max(oldSize + diff, Item.MINIMUM_THICKNESS);
    2048                                 float resizeRatio = newSize / oldSize;
    2049                                 // Set size for Picture also translates
    2050                                 i.setSize(newSize);
    2051                                 if (i instanceof Text && i.getSize() != oldSize) {
    2052                                         if (toSize.size() == 1 && !isControlDown) {
    2053                                                 moveCursorAndFreeItems(i.getX(), i.getY());
    2054                                         } else {
    2055                                                 i.translate(origin, resizeRatio);
    2056                                                 if (i.isLineEnd()) {
    2057                                                         i.setPosition(i.getPosition());
    2058                                                 }
    2059                                         }
    2060                                 }
    2061                         }
    2062                 }
    2063 
    2064                 if (toSet != null)
    2065                         toSet.getParent().setChanged(true);
    2066 
    2067                 // refresh anchored items
    2068                 if (refreshAnchors(toSize)) {
    2069                         FrameUtils.Parse(DisplayIO.getCurrentFrame(), false);
    2070                 }
    2071 
    2072                 // notify widgets they were resized
    2073                 for (InteractiveWidget iw : widgets) {
    2074                         iw.onResized();
    2075                 }
    2076                 FrameGraphics.refresh(true);
    2077         }
    2078 
    2079         /**
    2080          * @param origin
    2081          * @param ratio
    2082          * @param done
    2083          * @param source
    2084          */
    2085         private static void scaleText(boolean insideEnclosure, Point2D origin,
    2086                         double ratio, Collection<Item> done, Text source) {
    2087                 if (insideEnclosure)
    2088                         source.setWidth(Math.round((float) (source.getWidth() * ratio)));
    2089                 source.translate(origin, ratio);
    2090                 source.setSize((float) (source.getSize() * ratio));
    2091                 done.add(source);
    2092         }
    2093 
    2094         private static void SetFillColor(Item item, boolean setTransparent) {
    2095                 if (item == null)
    2096                         return;
    2097 
    2098                 if (!item.hasPermission(UserAppliedPermission.full)) {
    2099                         MessageBay
    2100                                         .displayMessage("Insufficient permission to change fill color");
    2101                         return;
    2102                 }
    2103 
    2104                 Item toSet = item;
    2105                 Color color = toSet.getFillColor();
    2106                 if (setTransparent)
    2107                         color = null;
    2108                 else
    2109                         color = ColorUtils.getNextColor(color,
    2110                                         TemplateSettings.FillColorWheel.get(),
    2111                                         toSet.getGradientColor());
    2112 
    2113                 // if (color == null) {
    2114                 // MessageBay.displayMessage("FillColor is now transparent");
    2115                 // }
    2116 
    2117                 toSet.setFillColor(color);
    2118                 toSet.getParent().setChanged(true);
    2119 
    2120                 FrameGraphics.Repaint();
    2121         }
    2122 
    2123         private static void SetGradientColor(Item item, boolean setTransparent) {
    2124                 if (item == null)
    2125                         return;
    2126 
    2127                 if (!item.hasPermission(UserAppliedPermission.full)) {
    2128                         MessageBay
    2129                                         .displayMessage("Insufficient permission to change gradient color");
    2130                         return;
    2131                 }
    2132 
    2133                 Item toSet = item;
    2134                 Color color = toSet.getGradientColor();
    2135                 if (setTransparent)
    2136                         color = null;
    2137                 else
    2138                         color = ColorUtils.getNextColor(color,
    2139                                         TemplateSettings.ColorWheel.get(), toSet.getFillColor());
    2140 
    2141                 // if (color == null) {
    2142                 // MessageBay.displayMessage("FillColor is now transparent");
    2143                 // }
    2144 
    2145                 toSet.setGradientColor(color);
    2146                 toSet.getParent().setChanged(true);
    2147 
    2148                 FrameGraphics.Repaint();
    2149         }
    2150 
    2151         /**
    2152          * Sets the colour of the current Item based on its current colour. The
    2153          * colours proceed in the order stored in COLOR_WHEEL.
    2154          *
    2155          * @param toSet
    2156          *            The Item whose colour is to be changed
    2157          */
    2158         private static void SetColor(Item item, boolean setTransparent,
    2159                         boolean setBackgroundColor) {
    2160                 // first determine the next color
    2161                 Color color = null;
    2162                 Frame currentFrame = DisplayIO.getCurrentFrame();
    2163                 if (item == null) {
    2164                         if (FreeItems.itemsAttachedToCursor()) {
    2165                                 color = FreeItems.getInstance().get(0).getColor();
    2166                         } else {
    2167                                 return;
    2168                         }
    2169                         // change the background color if the user is pointing on the
    2170                         // frame name
    2171                 } else if (item == currentFrame.getNameItem()) {
    2172                         // check permissions
    2173                         if (!item.hasPermission(UserAppliedPermission.full)) {
    2174                                 MessageBay
    2175                                                 .displayMessage("Insufficient permission to the frame's background color");
    2176                                 return;
    2177                         }
    2178                         if (setTransparent)
    2179                                 currentFrame.setBackgroundColor(null);
    2180                         else
    2181                                 currentFrame.toggleBackgroundColor();
    2182                         // Display a message if the color has changed to transparent
    2183                         // if (currentFrame.getBackgroundColor() == null)
    2184                         // FrameGraphics
    2185                         // .displayMessage("Background color is now transparent");
    2186                         FrameGraphics.Repaint();
    2187                         return;
    2188                 } else {
    2189                         // check permissions
    2190                         if (!item.hasPermission(UserAppliedPermission.full)) {
    2191                                 Item editTarget = item.getEditTarget();
    2192                                 if (editTarget != item
    2193                                                 && editTarget.hasPermission(UserAppliedPermission.full)) {
    2194                                         item = editTarget;
    2195                                 } else {
    2196                                         MessageBay
    2197                                                         .displayMessage("Insufficient permission to change color");
    2198                                         return;
    2199                                 }
    2200                         }
    2201                         // Toggling color of circle center changes the circle fill color
    2202                         if (item.hasEnclosures()) {
    2203                                 if (setBackgroundColor) {
    2204                                         SetGradientColor(item.getEnclosures().iterator().next(),
    2205                                                         setTransparent);
    2206                                 } else {
    2207                                         SetFillColor(item.getEnclosures().iterator().next(),
    2208                                                         setTransparent);
    2209                                 }
    2210                         } else if (setBackgroundColor) {
    2211                                 color = item.getPaintBackgroundColor();
    2212                         } else {
    2213                                 color = item.getPaintColor();
    2214                         }
    2215                 }
    2216                 if (setTransparent)
    2217                         color = null;
    2218                 else if (setBackgroundColor) {
    2219                         color = ColorUtils
    2220                                         .getNextColor(color, TemplateSettings.FillColorWheel.get(),
    2221                                                         item.getPaintColor());
    2222                 } else {
    2223                         color = ColorUtils.getNextColor(color,
    2224                                         TemplateSettings.ColorWheel.get(),
    2225                                         currentFrame.getPaintBackgroundColor());
    2226                 }
    2227                 // if (currentFrame.getPaintForegroundColor().equals(color))
    2228                 // color = null;
    2229 
    2230                 // if color is being set to default display a message to indicate that
    2231                 // if (color == null) {
    2232                 // MessageBay.displayMessage("Color is set to default");
    2233                 // }
    2234 
    2235                 if (setBackgroundColor) {
    2236                         if (item == null && FreeItems.itemsAttachedToCursor()) {
    2237                                 for (Item i : FreeItems.getInstance())
    2238                                         i.setBackgroundColor(color);
    2239                         } else {
    2240                                 item.setBackgroundColor(color);
    2241                                 item.getParent().setChanged(true);
    2242                         }
    2243                 } else {
    2244                         if (item == null && FreeItems.itemsAttachedToCursor()) {
    2245                                 for (Item i : FreeItems.getInstance())
    2246                                         i.setColor(color);
    2247                         } else {
    2248                                 item.setColor(color);
    2249                                 item.getParent().setChanged(true);
    2250                         }
    2251                 }
    2252                 FrameGraphics.Repaint();
    2253         }
    2254 
    2255         /**
    2256          * Toggles the given Item's annotation status on\off.
    2257          *
    2258          * @param toToggle
    2259          *            The Item to toggle
    2260          */
    2261         private static void ToggleAnnotation(Item toToggle) {
    2262                 if (toToggle == null) {
    2263                         MessageBay.displayMessage("There is no Item selected to toggle");
    2264                         return;
    2265                 }
    2266 
    2267                 // check permissions
    2268                 if (!toToggle.hasPermission(UserAppliedPermission.full)) {
    2269                         MessageBay
    2270                                         .displayMessage("Insufficient permission to toggle that item's annotation");
    2271                         return;
    2272                 }
    2273                 toToggle.setAnnotation(!toToggle.isAnnotation());
    2274 
    2275                 toToggle.getParent().setChanged(true);
    2276                 FrameGraphics.Repaint();
    2277         }
    2278 
    2279         /**
    2280          * Toggles the face style of a text item
    2281          *
    2282          * @param toToggle
    2283          *            The Item to toggle
    2284          */
    2285         private static void ToggleFontStyle(Item toToggle) {
    2286                 if (toToggle == null) {
    2287                         MessageBay.displayMessage("There is no Item selected to toggle");
    2288                         return;
    2289                 }
    2290 
    2291                 // check permissions
    2292                 if (!toToggle.hasPermission(UserAppliedPermission.full)) {
    2293                         MessageBay
    2294                                         .displayMessage("Insufficient permission to toggle that item's annotation");
    2295                         return;
    2296                 }
    2297 
    2298                 if (toToggle instanceof Text) {
    2299                         Text text = (Text) toToggle;
    2300                         text.toggleFontStyle();
    2301 
    2302                         text.getParent().setChanged(true);
    2303                         FrameGraphics.Repaint();
    2304                 }
    2305         }
    2306 
    2307         /**
    2308          * Toggles the face style of a text item
    2309          *
    2310          * @param toToggle
    2311          *            The Item to toggle
    2312          */
    2313         private static void ToggleFontFamily(Item toToggle) {
    2314                 if (toToggle == null) {
    2315                         MessageBay.displayMessage("There is no Item selected to toggle");
    2316                         return;
    2317                 }
    2318 
    2319                 // check permissions
    2320                 if (!toToggle.hasPermission(UserAppliedPermission.full)) {
    2321                         MessageBay
    2322                                         .displayMessage("Insufficient permission to toggle that item's annotation");
    2323                         return;
    2324                 }
    2325 
    2326                 if (toToggle instanceof Text) {
    2327                         Text text = (Text) toToggle;
    2328                         text.toggleFontFamily();
    2329 
    2330                         text.getParent().setChanged(true);
    2331                         FrameGraphics.Repaint();
    2332                 }
    2333         }
    2334 
    2335         /**
    2336          * If the given Item is null, then a new Text item is created with the
    2337          * current date If the given Item is not null, then the current date is
    2338          * prepended to the Item's text
    2339          *
    2340          * @param toAdd
    2341          *            The Item to prepend the date to, or null
    2342          */
    2343         public static void AddDate(Item toAdd) {
    2344                 String date1 = Formatter.getDateTime();
    2345                 String date2 = Formatter.getDate();
    2346                 final String leftSeparator = " :";
    2347                 final String rightSeparator = ": ";
    2348                 String dateToAdd = date1 + rightSeparator;
    2349                 boolean prepend = false;
    2350                 boolean append = false;
    2351 
    2352                 // if the user is pointing at an item, add the date where ever the
    2353                 // cursor is pointing
    2354                 if (toAdd != null && toAdd instanceof Text) {
    2355                         // permission check
    2356                         if (!toAdd.hasPermission(UserAppliedPermission.full)) {
    2357                                 MessageBay
    2358                                                 .displayMessage("Insufficicent permission to add the date to that item");
    2359                                 return;
    2360                         }
    2361 
    2362                         Text textItem = (Text) toAdd;
    2363 
    2364                         String text = textItem.getText();
    2365 
    2366                         // check if the default date has already been put on this item
    2367                         if (text.startsWith(date1 + rightSeparator)) {
    2368                                 textItem.removeText(date1 + rightSeparator);
    2369                                 dateToAdd = date2 + rightSeparator;
    2370                                 prepend = true;
    2371                         } else if (text.startsWith(date2 + rightSeparator)) {
    2372                                 textItem.removeText(date2 + rightSeparator);
    2373                                 dateToAdd = leftSeparator + date2;
    2374                                 append = true;
    2375                         } else if (text.endsWith(leftSeparator + date2)) {
    2376                                 textItem.removeEndText(leftSeparator + date2);
    2377                                 append = true;
    2378                                 dateToAdd = leftSeparator + date1;
    2379                         } else if (text.endsWith(leftSeparator + date1)) {
    2380                                 textItem.removeEndText(leftSeparator + date1);
    2381                                 if (textItem.getLength() > 0) {
    2382                                         dateToAdd = "";
    2383                                         prepend = true;
    2384                                 } else {
    2385                                         // use the default date format
    2386                                         prepend = true;
    2387                                 }
    2388                         }
    2389 
    2390                         if (prepend) {
    2391                                 // add the date to the text item
    2392                                 textItem.prependText(dateToAdd);
    2393                                 if (dateToAdd.length() == textItem.getLength())
    2394                                         DisplayIO.setCursorPosition(textItem
    2395                                                         .getParagraphEndPosition());
    2396                         } else if (append) {
    2397                                 textItem.appendText(dateToAdd);
    2398                                 if (dateToAdd.length() == textItem.getLength())
    2399                                         DisplayIO.setCursorPosition(textItem.getPosition());
    2400                         } else {
    2401                                 for (int i = 0; i < date1.length(); i++) {
    2402                                         processChar(date1.charAt(i), false);
    2403                                 }
    2404                         }
    2405 
    2406                         textItem.getParent().setChanged(true);
    2407                         FrameGraphics.Repaint();
    2408                         // } else {
    2409                         // MessageBay
    2410                         // .displayMessage("Only text items can have the date prepended to
    2411                         // them");
    2412                         // }
    2413                         // otherwise, create a new text item
    2414                 } else {
    2415                         Text newText = createText();
    2416                         newText.setText(dateToAdd);
    2417                         DisplayIO.getCurrentFrame().addItem(newText);
    2418                         DisplayIO.getCurrentFrame().setChanged(true);
    2419                         FrameGraphics.Repaint();
    2420 
    2421                         DisplayIO.setCursorPosition(newText.getParagraphEndPosition());
    2422                 }
    2423 
    2424         }
    2425 
    2426         /**
    2427          * Creates a new Frameset with the name given by the Item
    2428          *
    2429          * @param name
    2430          */
    2431         private static void CreateFrameset(Item item) {
    2432                 if (item == null) {
    2433                         MessageBay
    2434                                         .displayMessage("There is no selected item to use for the frameset name");
    2435                         return;
    2436                 }
    2437 
    2438                 if (!(item instanceof Text)) {
    2439                         MessageBay
    2440                                         .displayMessage("Framesets can only be created from text items");
    2441                         return;
    2442                 }
    2443 
    2444                 // dont create frameset if the item is linked
    2445                 if (item.getLink() != null) {
    2446                         MessageBay
    2447                                         .displayMessage("A frameset can not be created from a linked item");
    2448                         return;
    2449                 }
    2450 
    2451                 // check permissions
    2452                 if (!item.hasPermission(UserAppliedPermission.full)) {
    2453                         MessageBay
    2454                                         .displayMessage("Insufficient permission to create a frameset from this item");
    2455                         return;
    2456                 }
    2457 
    2458                 Text text = (Text) item;
    2459                 try {
    2460                         // create the new frameset
    2461                         Frame linkTo = FrameIO.CreateNewFrameset(text.getFirstLine());
    2462                         DisplayIO.setCursor(Item.DEFAULT_CURSOR);
    2463                         text.setLink(linkTo.getName());
    2464                         text.getParent().setChanged(true);
    2465                         FrameUtils.DisplayFrame(linkTo, true, true);
    2466                         linkTo.moveMouseToDefaultLocation();
    2467                         // this needs to be done if the user doesnt move the mouse before
    2468                         // doing Tdfc while the cursor is set to the text cursor
    2469                         DisplayIO.setCursor(Item.DEFAULT_CURSOR);
    2470                 } catch (Exception e) {
    2471                         MessageBay.errorMessage(e.getMessage());
    2472                 }
    2473         }
    2474 
    2475         /**
    2476          * Forces a re-parse and repaint of the current Frame.
    2477          */
    2478         public static void Refresh() {
    2479                 Frame currentFrame = DisplayIO.getCurrentFrame();
    2480 
    2481                 if (FrameMouseActions.isShiftDown()) {
    2482                         currentFrame.refreshSize();
    2483                 }
    2484 
    2485                 // Refresh widgets that use its self as a data source
    2486                 currentFrame.notifyObservers(true);
    2487 
    2488                 if (FrameIO.isProfileFrame(currentFrame)) {
    2489                         // TODO ensure that users can not delete the first frame in a
    2490                         // frameset...
    2491                         // TODO handle the case when users manually delete the first frame
    2492                         // in a frameset from the filesystem
    2493                         Frame profile = FrameIO.LoadFrame(currentFrame.getFramesetName()
    2494                                         + "1");
    2495                         assert (profile != null);
    2496                         FrameUtils.Parse(currentFrame);
    2497                         FrameUtils.ParseProfile(profile);
    2498                 } else {
    2499                         FrameUtils.Parse(currentFrame);
    2500                 }
    2501                 // Need to update the cursor for when text items change to @b pictures
    2502                 // etc and the text cursor is showing
    2503                 FrameMouseActions.updateCursor();
    2504                 FrameMouseActions.getInstance().refreshHighlights();
    2505                 FrameGraphics.ForceRepaint();
    2506         }
    2507 }
     964}*/
  • trunk/src/org/expeditee/gui/FrameMouseActions.java

    r1064 r1102  
    1919package org.expeditee.gui;
    2020
    21 import java.awt.Color;
    22 import java.awt.Image;
    23 import java.awt.Point;
    24 import java.awt.Rectangle;
    25 import java.awt.Toolkit;
    26 import java.awt.datatransfer.Clipboard;
    27 import java.awt.datatransfer.DataFlavor;
    28 import java.awt.datatransfer.Transferable;
    29 import java.awt.event.ActionEvent;
    30 import java.awt.event.ActionListener;
    31 import java.awt.event.KeyEvent;
    3221import java.awt.event.MouseEvent;
    33 import java.awt.event.MouseListener;
    34 import java.awt.event.MouseMotionListener;
    35 import java.awt.event.MouseWheelEvent;
    36 import java.awt.event.MouseWheelListener;
    3722import java.text.NumberFormat;
    3823import java.util.ArrayList;
     
    4530import java.util.List;
    4631import java.util.Set;
    47 import java.util.TimerTask;
    48 
    49 import javax.swing.Timer;
    5032
    5133import org.expeditee.actions.Actions;
    5234import org.expeditee.actions.Misc;
    5335import org.expeditee.actions.Navigation;
     36import org.expeditee.core.AxisAlignedBoxBounds;
     37import org.expeditee.core.Colour;
     38import org.expeditee.core.OSManager;
     39import org.expeditee.core.Point;
     40import org.expeditee.core.swing.SwingConversions;
     41import org.expeditee.gio.gesture.Gesture;
     42import org.expeditee.gio.gesture.GestureListener;
    5443import org.expeditee.gui.indirect.mouse.IndirectMouseActions;
    5544import org.expeditee.gui.indirect.mouse.MouseAction;
     
    7160import org.expeditee.items.UserAppliedPermission;
    7261import org.expeditee.items.XRayable;
    73 import org.expeditee.items.widgets.ButtonWidget;
     62/*import org.expeditee.items.widgets.ButtonWidget; TODO: Reinstate. cts16
    7463import org.expeditee.items.widgets.InteractiveWidget;
    7564import org.expeditee.items.widgets.WidgetCorner;
    76 import org.expeditee.items.widgets.WidgetEdge;
     65import org.expeditee.items.widgets.WidgetEdge;*/
    7766import org.expeditee.settings.UserSettings;
    7867import org.expeditee.settings.experimental.ExperimentalFeatures;
    7968import org.expeditee.stats.SessionStats;
    8069
    81 public class FrameMouseActions implements MouseListener, MouseMotionListener,
    82                 MouseWheelListener {
     70public class FrameMouseActions
     71{
    8372
    8473        private static int _lastMouseClickModifiers = 0;
     
    9281                        @Override
    9382                        public List<Item> exec(MouseInfo info) {
    94                                 //if user is not pointing at something,this is a back
     83                                //if user is not pointing at something, this is a back
    9584                                if (info.isControlDown || info.isShiftDown)
    9685                                        forward();
     
    10594                                // check for TDFC permission
    10695                                if (!info.clicked.hasPermission(UserAppliedPermission.createFrames)) {
    107                                         MessageBay
    108                                                         .displayMessage("Insufficient permission to TDFC (Top Down Frame Creation) from that item");
     96                                        MessageBay.displayMessage("Insufficient permission to TDFC (Top Down Frame Creation) from that item");
    10997                                        return null;
    11098                                }
     
    178166                                copies.add(new Line(d[3], d[0], current.getNextItemID()));
    179167
    180                                 new Constraint(d[0], d[1], current.getNextItemID(),
    181                                                 Constraint.HORIZONTAL);
    182                                 new Constraint(d[2], d[3], current.getNextItemID(),
    183                                                 Constraint.HORIZONTAL);
    184                                 new Constraint(d[1], d[2], current.getNextItemID(),
    185                                                 Constraint.VERTICAL);
    186                                 new Constraint(d[3], d[0], current.getNextItemID(),
    187                                                 Constraint.VERTICAL);
     168                                new Constraint(d[0], d[1], current.getNextItemID(), Constraint.HORIZONTAL);
     169                                new Constraint(d[2], d[3], current.getNextItemID(), Constraint.HORIZONTAL);
     170                                new Constraint(d[1], d[2], current.getNextItemID(), Constraint.VERTICAL);
     171                                new Constraint(d[3], d[0], current.getNextItemID(), Constraint.VERTICAL);
    188172
    189173                                anchor(new ArrayList<Item>(copies));
     
    233217                                Collection<Item> enclosed = getFullyEnclosedItems(info.clickedIn);
    234218                                if (enclosed.size() == 0) {
    235                                         MessageBay
    236                                                         .displayMessage("Insufficient permission to copy items");
     219                                        MessageBay.displayMessage("Insufficient permission to copy items");
    237220                                } else {
    238221                                        copies = copy(enclosed);
     
    308291                                List<Item> copies = new ArrayList<Item>();
    309292                                if (info.clicked != null) {
    310                                         Collection<Item> leftOver = merge(FreeItems
    311                                                         .getInstance(), info.clicked);
     293                                        Collection<Item> leftOver = merge(FreeItems.getInstance(), info.clicked);
    312294                                        anchor(leftOver);
    313295                                }
    314296                                // This is executed when the user is putting down a line
    315297                                // endpoint and unreeling. ie. Normal unreeling
    316                                 copies = ItemUtils.UnreelLine(FreeItems.getInstance(),
    317                                                 _controlDown);
    318 
    319                                 if (copies == null)
    320                                         copies = copy(FreeItems.getInstance());
     298                                copies = ItemUtils.UnreelLine(FreeItems.getInstance(), _controlDown);
     299
     300                                if (copies == null) copies = copy(FreeItems.getInstance());
     301                               
    321302                                anchor(FreeItems.getInstance());
    322                                 for (Item i : copies)
    323                                         i.setOffset(0, 0);
     303                                for (Item i : copies) i.setOffset(0, 0);
    324304                                // need to move to prevent cursor dislocation
    325305                                move(copies);
     
    354334                                                        if (next instanceof Line)
    355335                                                                continue;
    356                                                         double distance = Point.distance(currentX,
    357                                                                         currentY, next.getX(), next.getY());
     336                                                        double distance = Point.distance((int) currentX, (int) currentY, next.getX(), next.getY());
    358337                                                        if (distance < shortestDistance) {
    359338                                                                shortestDistance = distance;
     
    469448                        public List<Item> exec(MouseInfo info) {
    470449                                List<Item> copies = new ArrayList<Item>();
    471                                 Item on = FrameUtils.onItem(DisplayIO.getCurrentFrame(), Math
    472                                                 .round(MouseX), Math.round(MouseY), true);
     450                                Item on = FrameUtils.onItem(DisplayIO.getCurrentFrame(), Math.round(MouseX), Math.round(MouseY), true);
    473451                                // If we have permission to copy this item then pick it up
    474452                                if (on != null && on.isLineEnd()
     
    479457                                }
    480458
    481                                 if (on instanceof WidgetEdge) {
     459/*                              if (on instanceof WidgetEdge) { TODO: Reinstate. cts16
    482460                                        // Don't allow the user to break widget edges.
    483461                                        // Note: had to return here because random dots would
     
    485463                                        // with create line.
    486464                                        return copies;
    487                                 }
     465                                }*/
    488466
    489467                                // if its on a line then split the line and put a point on it and
     
    519497                                List<Item> copies = new ArrayList<Item>();
    520498                                ArrayList<Item> toPickup = new ArrayList<Item>(info.clickedIn.size());
    521                                 for (Item ip : info.clickedIn)
    522                                         if (ip.hasPermission(UserAppliedPermission.full))
    523                                                 toPickup.add(ip);
     499                                for (Item ip : info.clickedIn) {
     500                                        if (ip.hasPermission(UserAppliedPermission.full)) toPickup.add(ip);
     501                                }
    524502                                pickup(toPickup);
    525503                                // otherwise the user is creating a line
     
    532510                                List<Item> items = new ArrayList<Item>();
    533511                                // BROOK: WIDGET RECTANGLES DONT ALLOW DISCONNECTION
    534                                 if (info.clicked instanceof Line && !(info.clicked instanceof WidgetEdge)) {
     512                                if (info.clicked instanceof Line/* && !(info.clicked instanceof WidgetEdge) TODO: Reinstate. cts16*/) {
    535513                                        // Check if within 20% of the end of the line
    536514                                        Line l = (Line) info.clicked;
    537                                         Item toDisconnect = l.getEndPointToDisconnect(_lastMouseClick
    538                                                         .getX(), _lastMouseClick.getY());
     515                                        Item toDisconnect = l.getEndPointToDisconnect(_lastMouseClick.getX(), _lastMouseClick.getY());
    539516
    540517                                        if (toDisconnect == null) {
     
    696673
    697674        public static FrameMouseActions getInstance() {
    698                 if (_instance == null)
    699                         _instance = new FrameMouseActions();
     675                if (_instance == null) _instance = new FrameMouseActions();
     676               
    700677                return _instance;
    701678        }
     
    708685        private static final int MINIMUM_RANGE_DEPRESS_TIME = 250;
    709686
    710         private static final int RECTANGLE_TO_POINT_THRESHOLD = 20;
    711 
    712687        private static Date _lastMouseClickDate = new Date();
    713688
     
    717692
    718693        public static final int BIG_MOUSE_PAUSE = 750;
    719 
    720         public static final int CONTEXT_FREESPACE = 0;
    721 
    722         public static final int CONTEXT_AT_TEXT = 1;
    723 
    724         public static final int CONTEXT_AT_LINE = 2;
    725 
    726         public static final int CONTEXT_AT_DOT = 3;
    727 
    728         public static final int CONTEXT_AT_ENCLOSURE = 4;
    729694
    730695        public static int _alpha = -1;
     
    765730        private static boolean _extrude = false;
    766731
    767         // keeps track of the last highlighted Item
    768         private static Item _lastHighlightedItem = null;
    769 
    770732        // keeps track of the item being 'ranged out' if there is one.
    771733        private static Text _lastRanged = null;
     
    773735        // keeps track of the picture being cropped if there is one
    774736        private static Picture _lastCropped = null;
    775 
    776         // true if lastItem only has highlighting removed when a new item is
    777         // highlighted
    778         private static boolean _lastHoldsHighlight = false;
    779 
    780         private static boolean _forceArrowCursor = true;
    781 
    782         // the current context of the cursor
    783         private static int _context = 0;
    784 
    785         public static void setForceArrow(boolean val) {
    786                 _forceArrowCursor = val;
    787         }
    788737
    789738        public static int getContext() {
     
    807756                                public void actionPerformed(ActionEvent ae) {
    808757                                        // check if we are in free space
    809                                         if (_lastClickedOn == null
    810                                                         && FreeItems.getInstance().size() == 0) {
     758                                        if (_lastClickedOn == null && FreeItems.getInstance().size() == 0) {
    811759                                                // System.out.println("SuperBack!");
    812760                                                _MouseTimer.setDelay(ZERO_MOUSE_PAUSE);
     
    829777                        });
    830778
    831         private static void setPulse(boolean pulseOn) {
    832                 if (_pulseOn == pulseOn) {
    833                         return;
    834                 }
     779        private static void setPulse(boolean pulseOn)
     780        {
     781                if (_pulseOn == pulseOn) return;
     782
    835783                int amount = PULSE_AMOUNT;
    836                 if (!pulseOn) {
    837                         amount *= -1;
    838                         }
     784                if (!pulseOn) amount *= -1;
    839785                _pulseOn = pulseOn;
    840786
     
    859805                                }
    860806                        });
    861 
    862         public void mouseClicked(MouseEvent e) {
    863         }
    864807
    865808        /**
     
    874817
    875818        private void ProccessMousePressedEvent(MouseEvent e, int modifiersEx) {
    876                 // System.out.println("MousePressed " + e.getX() + "," + e.getY() + " "
    877                 // + e.getWhen());
     819                // System.out.println("MousePressed " + e.getX() + "," + e.getY() + " " + e.getWhen());
    878820
    879821                // TODO WHY DID I NOT COMMENT THIS LINE!! MIKE SAYS
    880                 if (LastRobotX != null) {
     822/*              if (LastRobotX != null) {
    881823                        _RobotTimer.stop();
    882824                        LastRobotX = null;
     
    894836                MouseX = panStartX;
    895837                MouseY = panStartY;
    896                 }
     838                }*/
    897839
    898840                // System.out.println(modifiersEx);
    899                 if (_mouseDown == 0)
    900                         _lastMouseClickDate = new Date();
     841                if (_mouseDown == 0) _lastMouseClickDate = new Date();
    901842
    902843                int buttonPressed = e.getButton();
     
    916857                 * backup stack.
    917858                 */
    918                 if (on == null || buttonPressed != MouseEvent.BUTTON1
    919                                 || !on.isFrameName()) {
     859                if (on == null || buttonPressed != MouseEvent.BUTTON1 || !on.isFrameName()) {
    920860                        Navigation.ResetLastAddToBack();
    921861                }
    922862
    923                 SessionStats.MouseClicked(e.getButton());
     863                //SessionStats.MouseClicked(e.getButton());
    924864                if (buttonPressed == MouseEvent.BUTTON1) {
    925                         SessionStats.AddFrameEvent("Ld");
     865                        //SessionStats.AddFrameEvent("Ld");
    926866                        _extrude = false;
    927867                } else if (buttonPressed == MouseEvent.BUTTON2) {
    928                         SessionStats.AddFrameEvent("Md");
     868                        //SessionStats.AddFrameEvent("Md");
    929869                        _extrude = false;
    930870                } else if (buttonPressed == MouseEvent.BUTTON3) {
    931                         SessionStats.AddFrameEvent("Rd");
     871                        //SessionStats.AddFrameEvent("Rd");
    932872
    933873                        // Check if the user picked up a paint brush
    934                         if (FreeItems.getInstance().size() == 1
    935                                         && FreeItems.getItemAttachedToCursor().isAutoStamp()) {
    936                                 int delay = (int) (FreeItems.getItemAttachedToCursor()
    937                                                 .getAutoStamp() * 1000);
     874                        if (FreeItems.getInstance().size() == 1 && FreeItems.getItemAttachedToCursor().isAutoStamp()) {
     875                                int delay = (int) (FreeItems.getItemAttachedToCursor().getAutoStamp() * 1000);
    938876                                if (delay < 10) {
    939877                                        _autoStamp = true;
     
    958896                 */
    959897                if (_lastClickedOn == null && FreeItems.getInstance().size() == 0) {
    960                         // System.out.println(e.getClickCount());
    961898                        if (e.getClickCount() >= 2) {
    962899                                _MouseTimer.start();
    963900                        }
    964                 } else if (_lastClickedOn != null
    965                                 && FreeItems.getInstance().size() == 0
    966                                 && e.getButton() == MouseEvent.BUTTON3) {
     901                } else if (     _lastClickedOn != null &&
     902                                        FreeItems.getInstance().size() == 0 &&
     903                                        e.getButton() == MouseEvent.BUTTON3)
     904                {
    967905                        _ExtrudeMouseTimer.start();
    968 
    969906                } else {
    970907                        _MouseTimer.start();
     
    994931                        _isDelete = false;
    995932                        _isNoOp = true;
    996                 } else
     933                } else {
    997934                        _isDelete = false;
     935                }
    998936
    999937                // This must happen before the previous code
    1000938                // This is when the user is anchoring something
    1001                 if (buttonPressed != MouseEvent.BUTTON1
    1002                                 && (_context == CONTEXT_FREESPACE || _context == CONTEXT_AT_ENCLOSURE)
    1003                                 && FreeItems.itemsAttachedToCursor()) {
    1004                         FrameGraphics.changeHighlightMode(_lastHighlightedItem,
    1005                                         Item.HighlightMode.None);
     939                if (    buttonPressed != MouseEvent.BUTTON1 &&
     940                                (_context == CONTEXT_FREESPACE || _context == CONTEXT_AT_ENCLOSURE) &&
     941                                FreeItems.hasItemsAttachedToCursor())
     942                {
     943                        FrameGraphics.changeHighlightMode(_lastHighlightedItem, Item.HighlightMode.None);
    1006944
    1007945                        _lastHighlightedItem = FreeItems.getItemAttachedToCursor();
     
    1010948                        }
    1011949                        FrameGraphics.Repaint();
    1012                         // this is when the user is picking something up
     950                // this is when the user is picking something up
    1013951                } else if (_lastHighlightedItem != null) {
    1014952                        if (!(_lastHighlightedItem instanceof Line)) {
    1015                                 _lastHighlightedItem
    1016                                                 .setHighlightColor(Item.DEPRESSED_HIGHLIGHT);
     953                                _lastHighlightedItem.setHighlightColor(Item.DEPRESSED_HIGHLIGHT);
    1017954                        } else {
    1018955                                for (Item i : _lastHighlightedItem.getAllConnected()) {
     
    1027964                        _lastRanged = (Text) on;
    1028965                        // set start-drag point
    1029                         _lastRanged.setSelectionStart(DisplayIO.getMouseX(),
    1030                                         FrameMouseActions.getY());
     966                        _lastRanged.setSelectionStart(DisplayIO.getMouseX(), DisplayIO.getMouseY());
    1031967                }
    1032968
     
    1040976                }
    1041977
    1042                 if (on != null && on instanceof Picture
    1043                                 && e.getButton() == MouseEvent.BUTTON3 && !_isDelete) {
     978                if (on != null && on instanceof Picture && e.getButton() == MouseEvent.BUTTON3 && !_isDelete) {
    1044979                        _lastCropped = (Picture) on;
    1045980                        // set start crop point
    1046                         _lastCropped.setStartCrop(DisplayIO.getMouseX(), FrameMouseActions
    1047                                         .getY());
     981                        _lastCropped.setStartCrop(DisplayIO.getMouseX(), DisplayIO.getMouseY());
    1048982                        _lastCropped.setShowCrop(true);
    1049983                }
     
    1055989                // System.out.println("Released " + e.getX() + "," + e.getY() + " " +
    1056990                // e.getWhen());
    1057                 FrameUtils.ResponseTimer.restart();
     991//              FrameUtils.ResponseTimer.restart();
    1058992                _autoStampTimer.stop();
    1059993                _autoStamp = false;
     
    1063997                // the user probably wants to click away the popup - therefore ignore
    1064998                // the event
    1065                 boolean shouldConsume = PopupManager.getInstance()
    1066                                 .shouldConsumeBackClick();
     999/*              boolean shouldConsume = PopupManager.getInstance().shouldConsumeBackClick(); TODO: Reinstate. cts16
    10671000                PopupManager.getInstance().hideAutohidePopups();
    10681001                if (shouldConsume && e.getButton() == MouseEvent.BUTTON1) {
    10691002                        return; // consume back click event
    1070                 }
     1003                }*/
    10711004
    10721005                // _lastMovedDistance = new Point(e.getX() - _lastMouseClick.getX(), e
     
    10841017                // They are probably trying to pick something up in this case
    10851018                if (lastRanged != null) {
    1086                         long depressTime = (new Date()).getTime()
    1087                                         - _lastMouseClickDate.getTime();
     1019                        long depressTime = (new Date()).getTime() - _lastMouseClickDate.getTime();
    10881020                        // double changeInDistance =
    10891021                        // e.getPoint().distance(_currentMouseClick.getPoint());
     
    10921024                        // System.out.println(depressTime);
    10931025
    1094                         if (depressTime < MINIMUM_RANGE_DEPRESS_TIME
    1095                                         || lastRanged.getSelectionSize() <= 0) {// Text.MINIMUM_RANGED_CHARS)
     1026                        if (depressTime < MINIMUM_RANGE_DEPRESS_TIME || lastRanged.getSelectionSize() <= 0) {// Text.MINIMUM_RANGED_CHARS)
    10961027                                // {
    10971028                                lastRanged.clearSelection();
     
    11451076
    11461077                        if (_lastHighlightedItem != null)
    1147                                 FrameGraphics.changeHighlightMode(_lastHighlightedItem,
    1148                                                 Item.HighlightMode.None);
    1149 
    1150                         if (FreeItems.itemsAttachedToCursor()) {
     1078                                FrameGraphics.changeHighlightMode(_lastHighlightedItem, Item.HighlightMode.None);
     1079
     1080                        if (FreeItems.hasItemsAttachedToCursor()) {
    11511081                                move(FreeItems.getInstance());
    11521082                        }
     
    11741104                                        lastRanged.replaceSelectedText(((Text) i).getText());
    11751105                                        FreeItems.getInstance().clear();
    1176                                 } else
     1106                                } else {
    11771107                                        lastRanged.cutSelectedText();
     1108                                }
    11781109                                lastRanged.clearSelection();
    11791110                                FrameGraphics.Repaint();
     
    12311162                                // Check if the user is trying to range an item for which they
    12321163                                // do not have permission to do so... or it is the frame name
    1233                                 if (!lastRanged.hasPermission(UserAppliedPermission.full)
    1234                                                 || lastRanged.isFrameName()) {
    1235                                         MessageBay
    1236                                                         .displayMessage("Insufficient permission to cut text");
     1164                                if (!lastRanged.hasPermission(UserAppliedPermission.full) || lastRanged.isFrameName()) {
     1165                                        MessageBay.displayMessage("Insufficient permission to cut text");
    12371166                                        lastRanged.clearSelection();
    12381167                                        FrameGraphics.Repaint();
     
    12411170                                // if the entire text is selected and its not a line end then
    12421171                                // pickup the item
    1243                                 boolean entireText = lastRanged.getSelectionSize() == lastRanged
    1244                                                 .getLength();
     1172                                boolean entireText = lastRanged.getSelectionSize() == lastRanged.getLength();
    12451173                                if (entireText && !lastRanged.isLineEnd()) {
    12461174                                        lastRanged.clearSelection();
     
    12621190                                // do not have permission to do so... or it is the frame name
    12631191                                if (!lastRanged.hasPermission(UserAppliedPermission.copy)) {
    1264                                         MessageBay
    1265                                                         .displayMessage("Insufficient permission to copy text");
     1192                                        MessageBay.displayMessage("Insufficient permission to copy text");
    12661193                                        lastRanged.clearSelection();
    12671194                                        FrameGraphics.Repaint();
     
    12721199
    12731200                        ranged.setParent(null);
    1274                         ranged.setPosition(DisplayIO.getMouseX(), FrameMouseActions.getY());
     1201                        ranged.setPosition(DisplayIO.getMouseX(), DisplayIO.getMouseY());
    12751202                        pickup(ranged);
    12761203                        lastRanged.clearSelection();
     
    13031230                                // MIKE put the code below up here
    13041231                                _lastCropped.clearCropping();
    1305                                 FrameGraphics.changeHighlightMode(_lastCropped,
    1306                                                 HighlightMode.None);
     1232                                FrameGraphics.changeHighlightMode(_lastCropped, HighlightMode.None);
    13071233                                _lastCropped = null;
    13081234                                FrameGraphics.Repaint();
     
    13411267
    13421268                // error, we should have returned by now
    1343                 System.out.println("Error: mouseReleased should have returned by now. "
    1344                                 + e);
     1269                System.out.println("Error: mouseReleased should have returned by now. " + e);
    13451270        }
    13461271
     
    13481273         * This method handles all left-click actions
    13491274         */
    1350         private void leftButton(Item clicked, Collection<Item> clickedIn,
    1351                         boolean isShiftDown, boolean isControlDown) {
     1275        private void leftButton(Item clicked, Collection<Item> clickedIn, boolean isShiftDown, boolean isControlDown)
     1276        {
    13521277               
    13531278                //Gets the current frame
     
    13551280               
    13561281                //Checks if the current frame is an overlay
    1357                 if(f.getOverlays() != null && FrameUtils.getCurrentItem() != null){
     1282                if (f.getOverlays() != null && FrameUtils.getCurrentItem() != null) {
    13581283                        Item i = FrameUtils.getCurrentItem();
    13591284                       
    13601285                        //Checks if the item clicked in the overlay is a Rubbish Bin. If it is, delete the item attached to the cursor and return.
    1361                         if(i instanceof WidgetCorner){
     1286/*                      if(i instanceof WidgetCorner){ TODO: Reinstate. cts16
    13621287                               
    13631288                                try{
     
    13751300                                        e.printStackTrace();
    13761301                                }
    1377                         }
     1302                        }*/
    13781303                       
    13791304                        Item on = _lastClickedOn;
     
    13871312                        // Check if the user is nearby another item...
    13881313                        int mouseX = DisplayIO.getMouseX();
    1389                         int mouseY = FrameMouseActions.getY();
     1314                        int mouseY = DisplayIO.getMouseY();
    13901315                        // System.out.println(mouseX + "," + mouseY);
    13911316                        for (Item i : DisplayIO.getCurrentFrame().getItems()) {
     
    14111336               
    14121337                // If the user clicked into a widgets free space...
    1413                 if (clicked == null && _lastClickedIn != null
    1414                                 && _lastClickedIn.size() >= 4) {
     1338                if (clicked == null && _lastClickedIn != null && _lastClickedIn.size() >= 4) {
    14151339
    14161340                        // Check to see if the user clicked into a widgets empty space
    1417                         InteractiveWidget iw = null;
     1341/*                      InteractiveWidget iw = null; TODO: Reinstate. cts16
    14181342
    14191343                        for (Item i : _lastClickedIn) {
     
    14411365                                assert (widgetLink != null);
    14421366                                clicked = widgetLink;
    1443                         } else {
     1367                        } else*/ {
    14441368                                for (Item i : _lastClickedIn) {
    14451369                                        /*
     
    14641388                        Picture clickedOnPicture = (Picture)clicked;
    14651389                        Frame current_frame = DisplayIO.getCurrentFrame();
    1466                         Color bg_col = current_frame.getBackgroundColor();
     1390                        Colour bg_col = current_frame.getBackgroundColor();
    14671391                        if (clickedOnPicture.MouseOverBackgroundPixel(mouseX,mouseY,bg_col)) {
    14681392                                // Make 'clicked' null, effectively causing a back() operation
     
    14751399                        boolean hasLinkOrAction = clicked.hasLink() || clicked.hasAction();
    14761400
    1477                         if ((hasLinkOrAction && !clicked
    1478                                         .hasPermission(UserAppliedPermission.followLinks))
    1479                                         || (!hasLinkOrAction && !clicked
    1480                                                         .hasPermission(UserAppliedPermission.createFrames))) {
     1401                        if ((hasLinkOrAction && !clicked.hasPermission(UserAppliedPermission.followLinks))
     1402                                        || (!hasLinkOrAction && !clicked.hasPermission(UserAppliedPermission.createFrames)))
     1403                        {
    14811404                                Item editTarget = clicked.getEditTarget();
    14821405                                if (editTarget != clicked) {
     
    14841407                                                clicked = editTarget;
    14851408                                        } else {
    1486                                                 MessageBay
    1487                                                                 .displayMessage("Insufficient permission to perform action on item");
     1409                                                MessageBay.displayMessage("Insufficient permission to perform action on item");
    14881410                                                return;
    14891411                                        }
     
    14941416
    14951417                        // actions take priority
    1496                         if (_lastMouseClick != null && !_lastMouseClick.isControlDown()
    1497                                         && clickedOn.hasAction()) {
     1418                        if (_lastMouseClick != null && !_lastMouseClick.isControlDown() && clickedOn.hasAction()) {
    14981419                                IndirectMouseActions.getInstance().getExecuteActionAction().exec(new MouseInfo(clicked, clickedIn, isShiftDown, isControlDown));
    14991420                        } else if (clickedOn.getLink() != null) {
    15001421                                IndirectMouseActions.getInstance().getFollowLinkAction().exec(new MouseInfo(clicked, clickedIn, isShiftDown, isControlDown));
    1501                                 // no link is found, perform TDFC
     1422                        // no link is found, perform TDFC
    15021423                        } else {
    15031424                                /*
     
    15191440        }
    15201441
    1521         private static boolean doMerging(Item clicked) {
    1522                 if (clicked == null)
    1523                         return false;
    1524 
    1525                 // // Brook: widgets do not merge
    1526                 // if (clicked instanceof WidgetCorner)
    1527                 // return false;
    1528                 //
    1529                 // // Brook: widgets do not merge
    1530                 // if (clicked instanceof WidgetEdge)
    1531                 // return false;
    1532 
    1533                 // System.out.println(FreeItems.getInstance().size());
    1534                 if (isRubberBandingCorner()) {
    1535                         if (clicked.isLineEnd()
    1536                                         || clicked.getAllConnected().contains(
    1537                                                         FreeItems.getItemAttachedToCursor())) {
    1538                                 return true;
    1539                         }
    1540                 }
    1541 
    1542                 if (FreeItems.getInstance().size() > 2)
    1543                         return false;
    1544 
    1545                 Item attachedToCursor = FreeItems.getItemAttachedToCursor();
    1546 
    1547                 if (clicked instanceof Text
    1548                                 && !(attachedToCursor instanceof Text || attachedToCursor
    1549                                                 .isLineEnd())) {
    1550                         return false;
    1551                 }
    1552 
    1553                 if (clicked instanceof Picture) {
    1554                         int mouseX = DisplayIO.getMouseX();
    1555                         int mouseY = FrameMouseActions.getY();
    1556                         Picture clickedOnPicture = (Picture)clicked;
    1557                         Frame current_frame = DisplayIO.getCurrentFrame();
    1558                         Color bg_col = current_frame.getBackgroundColor();
    1559                         if (clickedOnPicture.MouseOverBackgroundPixel(mouseX,mouseY,bg_col)) {
    1560                                 // Make 'clicked' null, effectively causing a back() operation
    1561                                 return false;
    1562                         }
    1563                 }
    1564                
    1565                 return true;
    1566         }
    1567 
    15681442        public static void middleButton() {
    15691443                Item currentItem = FrameUtils.getCurrentItem();
     
    15821456        public static void leftButton() {
    15831457                Item currentItem = FrameUtils.getCurrentItem();
    1584                 getInstance().leftButton(currentItem,
    1585                                 FrameUtils.getCurrentItems(currentItem), false, false);
     1458                getInstance().leftButton(currentItem, FrameUtils.getCurrentItems(currentItem), false, false);
    15861459                updateCursor();
    15871460        }
     
    15901463         * This method handles all middle-click actions
    15911464         */
    1592         private void middleButton(Item clicked, Collection<Item> clickedIn,
    1593                         boolean isShiftDown) {
     1465        private void middleButton(Item clicked, Collection<Item> clickedIn, boolean isShiftDown)
     1466        {
    15941467               
    15951468                // If the user clicked into a widgets free space...
     
    15981471
    15991472                        // Check to see if the use clicked into a widgets empty space
    1600                         InteractiveWidget iw = null;
     1473/*                      InteractiveWidget iw = null; TODO: Reinstate. cts16
    16011474
    16021475                        for (Item i : _lastClickedIn) {
     
    16171490                                        return;
    16181491                                }
    1619                         }
     1492                        }*/
    16201493                }
    16211494                // if the cursor has Items attached
    1622                 if (FreeItems.itemsAttachedToCursor()) {
    1623                         // if the user is pointing at something, merge the items (if
    1624                         // possible)
     1495                if (FreeItems.hasItemsAttachedToCursor()) {
     1496                        // if the user is pointing at something, merge the items (if possible)
    16251497                        if (doMerging(clicked)) {
    16261498                                IndirectMouseActions.getInstance().getDeleteItemsAction().exec(new MouseInfo(clicked, clickedIn, false, false));
     
    16351507                                Picture clickedOnPicture = (Picture)clicked;
    16361508                                Frame current_frame = DisplayIO.getCurrentFrame();
    1637                                 Color bg_col = current_frame.getBackgroundColor();
     1509                                Colour bg_col = current_frame.getBackgroundColor();
    16381510                                if (clickedOnPicture.MouseOverBackgroundPixel(mouseX,mouseY,bg_col)) {
    16391511                                        clicked = null; // Effectively make it as if they haven't clicked on anything
     
    16451517                                if (!clicked.hasPermission(UserAppliedPermission.full)) {
    16461518                                        Item editTarget = clicked.getEditTarget();
    1647                                         if (editTarget != clicked
    1648                                                         && editTarget.hasPermission(UserAppliedPermission.full)) {
     1519                                        if (editTarget != clicked && editTarget.hasPermission(UserAppliedPermission.full)) {
    16491520                                                clicked = editTarget;
    16501521                                        } else {
    1651                                                 MessageBay
    1652                                                 .displayMessage("Insufficient permission to pick up item");
     1522                                                MessageBay.displayMessage("Insufficient permission to pick up item");
    16531523                                                return;
    16541524                                        }
     
    16631533                }
    16641534                SessionStats.MovedItems(FreeItems.getInstance());
    1665         }
    1666 
    1667         private static Item getFirstFreeLineEnd() {
    1668                 for (Item i : FreeItems.getInstance())
    1669                         if (i.isLineEnd())
    1670                                 return i;
    1671                 return null;
    1672         }
    1673 
    1674         private static boolean isRubberBandingCorner() {
    1675                 return getShapeCorner(FreeItems.getInstance()) != null;
    1676         }
    1677 
    1678         /**
    1679          * Gets the rectangle corner from the list of items that are part of a
    1680          * rectangle.
    1681          *
    1682          * @param partialRectangle
    1683          *            a corner and its two connecting lines.
    1684          * @return the rectangle corner or null if the list of items is not part of
    1685          *         a rectangle.
    1686          */
    1687         private static Item getShapeCorner(List<Item> partialRectangle) {
    1688                 if (partialRectangle.size() < 3)
    1689                         return null;
    1690                 Item lineEnd = null;
    1691                 // only one lineEnd will be present for rectangles
    1692                 // All other items must be lines
    1693                 for (Item i : partialRectangle) {
    1694                         if (i.isLineEnd()) {
    1695                                 if (lineEnd == null) {
    1696                                         lineEnd = i;
    1697                                 } else {
    1698                                         return null;
    1699                                 }
    1700                         } else if (!(i instanceof Line)) {
    1701                                 return null;
    1702                         }
    1703                 }
    1704                 // if this is at least the corner of two connected lines
    1705                 if (lineEnd != null && lineEnd.getAllConnected().size() >= 5)
    1706                         return lineEnd;
    1707 
    1708                 return null;
    17091535        }
    17101536
     
    17191545
    17201546                        // Check to see if the use clicked into a widgets empty space
    1721                         InteractiveWidget iw = null;
     1547/*                      InteractiveWidget iw = null; TODO: Reinstate. cts16
    17221548
    17231549                        for (Item i : _lastClickedIn) {
     
    17381564                                        return;
    17391565                                }
    1740                         }
     1566                        }*/
    17411567                }
    17421568               
     
    17441570
    17451571                List<Item> copies = null;
    1746                 if (FreeItems.itemsAttachedToCursor()) {
    1747                         if (FreeItems.getInstance().size() == 1
    1748                                         && FreeItems.getItemAttachedToCursor().isAutoStamp()) {
     1572                if (FreeItems.hasItemsAttachedToCursor()) {
     1573                        if (FreeItems.getInstance().size() == 1 && FreeItems.getItemAttachedToCursor().isAutoStamp()) {
    17491574                                // Dont stamp if the user is painting... because we dont want to
    17501575                                // save any of the items created!
    17511576                                return;
    1752                                 // if the user is clicking on something, merge the items
    1753                                 // unless it is a point onto something other than a lineEnd or a
    1754                                 // dot
     1577                        // if the user is clicking on something, merge the items unless
     1578                        // it is a point onto something other than a lineEnd or a dot
    17551579                        } else if (clicked != null
    17561580                        // TODO Change the items merge methods so the logic is simplified
     
    17581582                                                        || clicked instanceof Dot || clicked.isLineEnd())) {
    17591583                                // check permissions
    1760                                 if (!clicked.hasPermission(UserAppliedPermission.full)
    1761                                                 && clicked.getParent().getNameItem() != clicked) {
    1762                                         MessageBay
    1763                                                         .displayMessage("Insufficient permission to merge items");
     1584                                if (!clicked.hasPermission(UserAppliedPermission.full) && clicked.getParent().getNameItem() != clicked) {
     1585                                        MessageBay.displayMessage("Insufficient permission to merge items");
    17641586                                        return;
    17651587                                }
    1766                                 if (clicked instanceof Text || clicked instanceof Dot
    1767                                                 || clicked instanceof XRayable) {
     1588                                if (clicked instanceof Text || clicked instanceof Dot || clicked instanceof XRayable) {
    17681589                                        if (isRubberBandingCorner()) {
    17691590                                                copies = IndirectMouseActions.getInstance().getMergeGroupAction().exec(new MouseInfo(clicked, clickedIn, false, false));
    17701591                                                // line onto something
    1771                                         } else if (FreeItems.getInstance().size() == 2
    1772                                         /* && clicked instanceof XRayable */) {
     1592                                        } else if (FreeItems.getInstance().size() == 2 /* && clicked instanceof XRayable */) {
    17731593                                                copies = IndirectMouseActions.getInstance().getMergeTwoItemsAction().exec(new MouseInfo(clicked, clickedIn, false, false));
    17741594                                        } else if (FreeItems.getInstance().size() == 1) {
     
    17781598                                        }
    17791599                                } else {
    1780                                         copies = ItemUtils.UnreelLine(FreeItems.getInstance(),
    1781                                                         _controlDown);
    1782                                         if (copies == null)
    1783                                                 copies = copy(FreeItems.getInstance());
     1600                                        copies = ItemUtils.UnreelLine(FreeItems.getInstance(), _controlDown);
     1601                                        if (copies == null) copies = copy(FreeItems.getInstance());
    17841602                                        for (Item i : copies) {
    17851603                                                i.setOffset(0, 0);
     
    17891607                                        pickup(copies);
    17901608                                }
    1791                                 // otherwise, anchor the items
     1609                        // otherwise, anchor the items
    17921610                        } else {
    17931611                                // check if this is anchoring a rectangle
     
    18121630                                Picture clickedOnPicture = (Picture)clicked;
    18131631                                Frame current_frame = DisplayIO.getCurrentFrame();
    1814                                 Color bg_col = current_frame.getBackgroundColor();
     1632                                Colour bg_col = current_frame.getBackgroundColor();
    18151633                                if (clickedOnPicture.MouseOverBackgroundPixel(mouseX,mouseY,bg_col)) {
    18161634                                        clicked = null; // Effectively make it as if they haven't clicked on anything
     
    18231641                                if (clicked.isLineEnd()) {
    18241642                                        if (!clicked.hasPermission(UserAppliedPermission.full)) {
    1825                                                 MessageBay
    1826                                                                 .displayMessage("Insufficient permission to unreel");
     1643                                                MessageBay.displayMessage("Insufficient permission to unreel");
    18271644                                                return;
    18281645                                        }
     
    18331650                                                clicked = editTarget;
    18341651                                        } else {
    1835                                                 MessageBay
    1836                                                                 .displayMessage("Insufficient permission to copy");
     1652                                                MessageBay.displayMessage("Insufficient permission to copy");
    18371653                                                return;
    18381654                                        }
     
    18461662                                        // otherwise, create a rectangle
    18471663                                } else {
    1848                                         Item on = FrameUtils.onItem(DisplayIO.getCurrentFrame(),
    1849                                                         MouseX, MouseY, true);
     1664                                        Item on = FrameUtils.onItem(DisplayIO.getCurrentFrame(), MouseX, MouseY, true);
    18501665                                        // if its on a line then create a line from that line
    18511666                                        if (on instanceof Line && on.hasPermission(UserAppliedPermission.full)) {
     
    18601675                updateCursor();
    18611676                FrameGraphics.Repaint();
    1862         }
    1863 
    1864         /**
    1865          *
    1866          */
    1867         private static void stampItemsOnCursor(boolean save) {
    1868                 List<Item> copies = copy(FreeItems.getInstance());
    1869                 // MIKE: what does the below 2 lines do?
    1870                 for (Item i : copies) {
    1871                         i.setOffset(0, 0);
    1872                         i.setSave(save);
    1873                 }
    1874                 // The below code has a little problem withflicker when stamp
    1875                 // and dragging
    1876                 move(FreeItems.getInstance());
    1877                 for (Item i : copies) {
    1878                         i.setHighlightMode(HighlightMode.None);
    1879                 }
    1880                 anchor(copies);
    18811677        }
    18821678
     
    19071703        }
    19081704
    1909         /**
    1910          * Marks the items as not belonging to any specific frame. When picking up
    1911          * items the parent will be automatically cleared for items on the current
    1912          * frame but not for overlay items. This method ensures that overlay items
    1913          * will also be cleared. This is useful when picking up copies of items from
    1914          * an overlay (with the right mouse button) to ensure that the copy will be
    1915          * anchored on the current frame rather than the overlay. When items are
    1916          * picked up with the middle button clearParent should NOT be called.
    1917          *
    1918          * @param items
    1919          *            to have their parent cleared
    1920          */
    1921         private static void clearParent(List<Item> items) {
    1922                 for (Item i : items) {
    1923                         // The next line is only necessary for circles...
    1924                         // Need to clean up/refactory some of this stuff
    1925                         i.getParentOrCurrentFrame().removeItem(i);
    1926                         i.setParent(null);
    1927                 }
    1928         }
    1929 
    1930         private static boolean inWindow = false;
    1931         /**
    1932          * event called when mouse exits window
    1933          * (can't use MouseListener callback since that callback doesn't
    1934          *  correctly receive all mouse exit events)
    1935          */
    1936         public static void mouseExitedWindow(MouseEvent e) {
    1937                 inWindow = false;
    1938                 // System.out.println("Left window");
    1939                 if(FreeItems.itemsAttachedToCursor()) {
    1940                         boolean cut = true;
    1941                         for(Item i : FreeItems.getInstance()) {
    1942                                 for(Item j : i.getAllConnected()) {
    1943                                         if(!FreeItems.getInstance().contains(j)) {
    1944                                                 cut = false;
    1945                                                 break;
    1946                                         }
    1947                                 }
    1948                         }
    1949                         if(cut) {
    1950                                 ItemSelection.cut();
    1951                         }
    1952                 }
    1953         }
    1954        
    1955         public void mouseEntered(MouseEvent e) {
    1956                 // check if we are entering the window from outside of the window, or if we were just over a widget
    1957                 if(!inWindow) {
    1958                         inWindow = true;
    1959                         // if there is expeditee data on the clipboard that has not yet been autoPasted, autoPaste it
    1960                 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
    1961                 Transferable content = c.getContents(null);
    1962                 try {
    1963                         if(content.isDataFlavorSupported(ItemSelection.expDataFlavor)) {        // Expeditee data
    1964                                 ExpDataHandler expData = (ExpDataHandler)content.getTransferData(ItemSelection.expDataFlavor);
    1965                                 if(expData.autoPaste) {
    1966                                         List<Item> items = new ExpClipReader(FrameMouseActions.getX(), FrameMouseActions.getY()).read(expData.items);
    1967                                         // generate new IDs and pickup
    1968                                         FrameMouseActions.pickup(ItemUtils.CopyItems(items));
    1969                                         // update the clipboard contents so they won't be autoPasted again
    1970                                         expData.autoPaste = false;
    1971                                         String stringData = "";
    1972                                         Image imageData = null;
    1973                                         if(content.isDataFlavorSupported(DataFlavor.stringFlavor)) {
    1974                                                 stringData = (String) content.getTransferData(DataFlavor.stringFlavor);
    1975                                         }
    1976                                         if(content.isDataFlavorSupported(DataFlavor.imageFlavor)) {
    1977                                                 imageData = (Image) content.getTransferData(DataFlavor.imageFlavor);
    1978                                         }
    1979                                         c.setContents(new ItemSelection(stringData, imageData, expData), null);
    1980                                 }
    1981                         }
    1982                 } catch(Exception ex) {
    1983                         ex.printStackTrace();
    1984                 }
    1985                 }
    1986         }
    1987 
    1988         public void mouseExited(MouseEvent e) {
    1989         }
     1705//      public void mouseExited(MouseEvent e) {
     1706//      }
    19901707
    19911708        private boolean _overFrame;
    19921709        private int panStartX, panStartY;
    19931710        private boolean _isPanOp;
     1711       
    19941712        public void mouseDragged(MouseEvent e) {
    19951713                _lastMouseDragged = e;
     
    19981716                // Stop the longDepress mouse timer if the user drags above a threshold
    19991717                if (_MouseTimer.isRunning()) {
    2000                         if (Math.abs(e.getX() - _lastMouseClick.getX())
    2001                                         + Math.abs(e.getY() - _lastMouseClick.getY()) > 10)
     1718                        if (Math.abs(e.getX() - _lastMouseClick.getX()) + Math.abs(e.getY() - _lastMouseClick.getY()) > 10) {
    20021719                                _MouseTimer.stop();
     1720                        }
    20031721                }
    20041722
     
    20071725                }
    20081726
    2009                 /*
    2010                  * Have the free items follow the cursor if the user clicks in freespace
    2011                  * then moves.
    2012                  */
     1727                // Have the free items follow the cursor if the user clicks in freespace then moves.
    20131728                if (FreeItems.getInstance().size() > 0 && _lastClickedOn == null) {
    20141729                        mouseMoved(e);
     
    20171732               
    20181733                // panning the frame when dragging the mouse while shift-leftclicking
    2019                 if(ExperimentalFeatures.MousePan.get() && _overFrame && e.isShiftDown() &&
     1734/*              if(ExperimentalFeatures.MousePan.get() && _overFrame && e.isShiftDown() &&
    20201735                                (e.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) != 0 &&
    2021                                 (_isPanOp || (Math.max(Math.abs(panStartX - e.getX()), Math.abs(panStartY - e.getY())) > 5))) {
     1736                                (_isPanOp || (Math.max(Math.abs(panStartX - e.getX()), Math.abs(panStartY - e.getY())) > 5)))
     1737                {
    20221738                        int dX = (int) (e.getX() - MouseX);
    20231739                        int dY = (int) (e.getY() - MouseY);
     
    20261742                        MouseY = e.getY();
    20271743                        _isPanOp = true;
    2028                 }
     1744                }*/
    20291745
    20301746                // check if user is dragging across a text item
     
    20361752
    20371753                        int distance = _lastRanged.getY() - FrameMouseActions.getY();
    2038                         if (distance <= 0)
    2039                                 distance = FrameMouseActions.getY() - _lastRanged.getY()
    2040                                                 - _lastRanged.getBoundsHeight();
     1754                        if (distance <= 0) distance = FrameMouseActions.getY() - _lastRanged.getY() - _lastRanged.getBoundsHeight();
    20411755
    20421756                        if (distance > UserSettings.NoOpThreshold.get()) {
     
    20451759                        } else {
    20461760                                // update the ranged section
    2047                                 _lastRanged.setSelectionEnd(DisplayIO.getMouseX(),
    2048                                                 FrameMouseActions.getY());
     1761                                _lastRanged.setSelectionEnd(DisplayIO.getMouseX(), DisplayIO.getMouseY());
    20491762                                _isNoOp = false;
    20501763                        }
    20511764
    2052                         DisplayIO.setTextCursor(_lastRanged, Text.NONE, false, e
    2053                                         .isShiftDown(), e.isControlDown(), false);
     1765                        DisplayIO.setTextCursor(_lastRanged, Text.NONE, false, e.isShiftDown(), e.isControlDown(), false);
    20541766                        FrameGraphics.Repaint();
    20551767                        return;
     
    20581770                // if the user is dragging across a picture
    20591771                if (_lastCropped != null) {
    2060                         // If shift is down then the distance moved is the same in the x and
    2061                         // y
     1772                        // If shift is down then the distance moved is the same in the x and y
    20621773                        MouseX = e.getX();
    20631774                        MouseY = e.getY();
     
    20671778                                int deltaY = Math.abs(e.getY() - _lastMouseClick.getY());
    20681779                                if (deltaX > deltaY) {
    2069                                         MouseY = _lastMouseClick.getY() + deltaX
    2070                                                         * (e.getY() > _lastMouseClick.getY() ? 1 : -1);
     1780                                        MouseY = _lastMouseClick.getY() + deltaX * (e.getY() > _lastMouseClick.getY() ? 1 : -1);
    20711781                                } else {
    2072                                         MouseX = _lastMouseClick.getX() + deltaY
    2073                                                         * (e.getX() > _lastMouseClick.getX() ? 1 : -1);
     1782                                        MouseX = _lastMouseClick.getX() + deltaY * (e.getX() > _lastMouseClick.getX() ? 1 : -1);
    20741783                                }
    20751784                        }
    20761785                        // update the ranged section
    2077                         _lastCropped.setEndCrop(DisplayIO.getMouseX(), FrameMouseActions
    2078                                         .getY());
     1786                        _lastCropped.setEndCrop(DisplayIO.getMouseX(), DisplayIO.getMouseY());
    20791787
    20801788                        FrameGraphics.Repaint();
     
    20821790                }
    20831791
    2084                 /*
    2085                  * This is the context of a user clicking in freespace an dragging onto
    2086                  * the edge of a line
    2087                  */
    2088                 if ((_mouseDown == MouseEvent.BUTTON2 || _mouseDown == MouseEvent.BUTTON3)
    2089                                 && _lastClickedOn == null && _lastClickedIn == null) {
    2090                         Item on = FrameUtils.onItem(DisplayIO.getCurrentFrame(), e.getX(),
    2091                                         e.getY(), true);
     1792                // This is the context of a user clicking in freespace an dragging onto
     1793                // the edge of a line
     1794                if (    (_mouseDown == MouseEvent.BUTTON2 || _mouseDown == MouseEvent.BUTTON3) &&
     1795                                _lastClickedOn == null &&
     1796                                _lastClickedIn == null)
     1797                {
     1798                        Item on = FrameUtils.onItem(DisplayIO.getCurrentFrame(), e.getX(), e.getY(), true);
    20921799
    20931800                        if (FreeItems.getInstance().size() == 0) {
     
    21011808                                        on.setHighlightMode(Item.HighlightMode.Normal);
    21021809                                } else if (_lastHighlightedItem != null) {
    2103                                         _lastHighlightedItem
    2104                                                         .setHighlightMode(Item.HighlightMode.None);
     1810                                        _lastHighlightedItem.setHighlightMode(Item.HighlightMode.None);
    21051811                                        _lastHighlightedItem = null;
    21061812                                }
     
    21101816                // Use the below calculation for better speed. If it causes problems
    21111817                // switch back to the Euclidean distance calculation
    2112                 if (Math.abs(MouseX - e.getX()) > UserSettings.NoOpThreshold.get()
    2113                                 || Math.abs(MouseY - e.getY()) > UserSettings.NoOpThreshold.get())
     1818                if (    Math.abs(MouseX - e.getX()) > UserSettings.NoOpThreshold.get() ||
     1819                                Math.abs(MouseY - e.getY()) > UserSettings.NoOpThreshold.get())
     1820                {
    21141821                        _isNoOp = true;
    2115 
     1822                }
     1823               
    21161824                FrameGraphics.Repaint();
    21171825        }
    21181826
    21191827        private static MouseEvent _lastMouseMoved = null;
    2120 
    2121         private static Integer LastRobotX = null;
    2122 
    2123         private static Integer LastRobotY = null;
    2124 
    2125         // For some reason... sometimes the mouse move gets lost when moving the
    2126         // mouse really quickly after clicking...
    2127         // Use this timer to make sure it gets reset eventually if the Robot
    2128         // generated event never arrives.
    2129         private static Timer _RobotTimer = new Timer(200, new ActionListener() {
    2130                 public void actionPerformed(ActionEvent ae) {
    2131                         _RobotTimer.stop();
    2132                         LastRobotX = null;
    2133                         LastRobotY = null;
    2134                         // System.out.println("RobotTimer");
    2135                 }
    2136         });
    21371828
    21381829        private static Timer _autoStampTimer = new Timer(200, new ActionListener() {
     
    21521843        }
    21531844
    2154         public static boolean isControlDown() {
    2155                 return _controlDown;
    2156         }
    2157 
    2158         public static boolean isShiftDown() {
    2159                 return _shiftDown;
    2160         }
    2161 
    2162         public static void setLastRobotMove(float x, float y) {
    2163                 // Make sure the system is in the right state while waiting for the
    2164                 // Robots event to arrive.
    2165                 MouseX = x;
    2166                 MouseY = y;
    2167                 // System.out.println("MouseMoved: " + MouseX + "," + MouseY + " " +
    2168                 // System.currentTimeMillis());
    2169                 LastRobotX = Math.round(x);
    2170                 LastRobotY = Math.round(y);
    2171                 _RobotTimer.start();
    2172         }
    2173 
    2174         public static boolean isWaitingForRobot() {
    2175                 return LastRobotX != null;
    2176         }
    2177 
    21781845        /**
    21791846         * Updates the stored mouse position and highlights any items as necessary.
     
    21831850        }
    21841851
    2185         private void mouseMoved(MouseEvent e, boolean shiftStateChanged) {
    2186                 // System.out.println("mouseMoved");
    2187                 // System.out.println(_context);
    2188                 if (_context == CONTEXT_FREESPACE)
    2189                         FrameKeyboardActions.resetEnclosedItems();
    2190                 // System.out.println(e.getX() + "," + e.getY() + " " + e.getWhen());
    2191                 if (LastRobotX != null) {
    2192                         // Wait until the last Robot mouse move event arrives before
    2193                         // processing other events
    2194                         if (/* FreeItems.getInstance().size() == 0 || */
    2195                         (LastRobotX == e.getX() && LastRobotY == e.getY())) {
    2196                                 LastRobotX = null;
    2197                                 LastRobotY = null;
    2198                                 _RobotTimer.stop();
    2199                         } else {
    2200                                 // System.out.println("Ignored: " +
    2201                                 // FreeItems.getInstance().size());
    2202                                 return;
    2203                         }
    2204                 }
    2205 
    2206                 MouseX = e.getX();
    2207                 MouseY = e.getY();
    2208                
    2209                 // System.out.println(MouseX + "," + MouseY);
    2210 
    2211                 // Moving the mouse a certain distance removes the last edited text if
    2212                 // it is empty
    2213                 Text lastEdited = FrameUtils.getLastEdited();
    2214                 if (lastEdited != null && lastEdited.getText().length() == 0
    2215                                 && lastEdited.getPosition().distance(e.getPoint()) > 20) {
    2216                         FrameUtils.setLastEdited(null);
    2217                 }
    2218 
    2219                 // If shift is down then the movement is constrained
    2220                 if (_controlDown && FreeItems.getInstance().size() > 0) {
    2221                         // Check if we are rubber banding a line
    2222                         if (shiftStateChanged && rubberBanding()) {
    2223                                 // Get the line end that is being rubber banded
    2224                                 Item thisEnd = FreeItems.getInstance().get(0).isLineEnd() ? FreeItems
    2225                                                 .getInstance().get(0)
    2226                                                 : FreeItems.getInstance().get(1);
    2227                                 Line line = (Line) (FreeItems.getInstance().get(0).isLineEnd() ? FreeItems
    2228                                                 .getInstance().get(1)
    2229                                                 : FreeItems.getInstance().get(0));
    2230                                 Item otherEnd = line.getOppositeEnd(thisEnd);
    2231                                 int deltaX = Math.abs(e.getX() - otherEnd.getX());
    2232                                 int deltaY = Math.abs(e.getY() - otherEnd.getY());
    2233                                 // Check if its a vertical line
    2234                                 if (deltaX < deltaY / 2) {
    2235                                         // otherEnd.setX(thisEnd.getX());
    2236                                         // MouseX = otherEnd.getX();
    2237                                         if (shiftStateChanged) {
    2238                                                 new Constraint(thisEnd, otherEnd, thisEnd
    2239                                                                 .getParentOrCurrentFrame().getNextItemID(),
    2240                                                                 Constraint.VERTICAL);
    2241                                         }
    2242                                 }
    2243                                 // Check if its horizontal
    2244                                 else if (deltaY <= deltaX / 2) {
    2245                                         // MouseY = otherEnd.getY();
    2246                                         // otherEnd.setY(thisEnd.getY());
    2247                                         if (shiftStateChanged) {
    2248                                                 new Constraint(thisEnd, otherEnd, thisEnd
    2249                                                                 .getParentOrCurrentFrame().getNextItemID(),
    2250                                                                 Constraint.HORIZONTAL);
    2251                                         }
    2252                                 } else {
    2253                                         // Add DIAGONAL constraints
    2254                                         // if (deltaX > deltaY) {
    2255                                         // otherEnd.setY(thisEnd.getY() + deltaX
    2256                                         // * (e.getY() < otherEnd.getY() ? 1 : -1));
    2257                                         // } else {
    2258                                         // otherEnd.setX(thisEnd.getX() + deltaY
    2259                                         // * (e.getX() < otherEnd.getX() ? 1 : -1));
    2260                                         // }
    2261                                         if (shiftStateChanged) {
    2262                                                 int constraint = Constraint.DIAGONAL_NEG;
    2263                                                 // Check if the slope is positive
    2264                                                 if ((thisEnd.getY() - otherEnd.getY())
    2265                                                                 / (double) (thisEnd.getX() - otherEnd.getX()) > 0.0) {
    2266                                                         constraint = Constraint.DIAGONAL_POS;
    2267                                                 }
    2268 
    2269                                                 new Constraint(thisEnd, otherEnd, thisEnd
    2270                                                                 .getParentOrCurrentFrame().getNextItemID(),
    2271                                                                 constraint);
    2272                                         }
    2273                                 }
    2274                         }// If its a lineend attached to two lines lengthen the shorter
    2275                         // so it is the same length as the longer line
    2276                         else if (FreeItems.getInstance().size() == 3) {
    2277                                 // check if we are rubber banding the corner of a shape
    2278                                 Item thisEnd = getShapeCorner(FreeItems.getInstance());
    2279                                 if (thisEnd != null) {
    2280                                         Line line1 = thisEnd.getLines().get(0);
    2281                                         Line line2 = thisEnd.getLines().get(1);
    2282                                         // Check if the two lines are constrained and hence it is a
    2283                                         // rectangle
    2284                                         Integer c1 = line1.getPossibleConstraint();
    2285                                         Integer c2 = line2.getPossibleConstraint();
    2286 
    2287                                         if (c1 != null && c2 != null) {
    2288                                                 // This is the case of a constrained rectangle
    2289                                                 if ((c2 == Constraint.VERTICAL || c2 == Constraint.HORIZONTAL)
    2290                                                                 && (c1 == Constraint.VERTICAL || c1 == Constraint.HORIZONTAL)
    2291                                                                 && (c1 != c2)) {
    2292                                                         Line vLine = line2;
    2293                                                         Line hLine = line1;
    2294                                                         if (c1 == Constraint.VERTICAL) {
    2295                                                                 vLine = line1;
    2296                                                                 hLine = line2;
    2297                                                         }
    2298                                                         Item hOtherEnd = hLine.getOppositeEnd(thisEnd);
    2299                                                         Item vOtherEnd = vLine.getOppositeEnd(thisEnd);
    2300 
    2301                                                         double vLength = Math
    2302                                                                         .abs(vOtherEnd.getY() - MouseY);
    2303                                                         double hLength = Math
    2304                                                                         .abs(hOtherEnd.getX() - MouseX);
    2305 
    2306                                                         if (vLength > hLength) {
    2307                                                                 MouseX = Math.round(hOtherEnd.getX() + vLength
    2308                                                                                 * (MouseX > hOtherEnd.getX() ? 1 : -1));
    2309                                                         } else /* if (hLength > vLength) */{
    2310                                                                 MouseY = Math.round(vOtherEnd.getY() + hLength
    2311                                                                                 * (MouseY > vOtherEnd.getY() ? 1 : -1));
    2312                                                         }
    2313                                                 }
    2314                                                 // } else if (c2 != null) {
    2315                                                 //
    2316                                                 // } // Other wise it is a not constrained shape so
    2317                                                 // constrain
    2318                                                 // the two lines lengths to be equal
    2319                                         } else {
    2320                                                 Item lineEnd1 = line1.getOppositeEnd(thisEnd);
    2321                                                 Item lineEnd2 = line2.getOppositeEnd(thisEnd);
    2322                                                 double l1 = Line.getLength(lineEnd1.getPosition(), e
    2323                                                                 .getPoint());
    2324                                                 double l2 = Line.getLength(lineEnd2.getPosition(), e
    2325                                                                 .getPoint());
    2326                                                 double l3 = Line.getLength(lineEnd1.getPosition(),
    2327                                                                 lineEnd2.getPosition());
    2328                                                 // l1 needs to be the shorter end
    2329                                                 if (l1 > l2) {
    2330                                                         Item temp = lineEnd1;
    2331                                                         lineEnd1 = lineEnd2;
    2332                                                         lineEnd2 = temp;
    2333                                                         double tempL = l1;
    2334                                                         l1 = l2;
    2335                                                         l2 = tempL;
    2336                                                 }
    2337                                                 // Now use the cosine rule to calculate the angle
    2338                                                 // between l1 and l3
    2339                                                 double cosTheta = (l1 * l1 + l3 * l3 - l2 * l2)
    2340                                                                 / (2 * l1 * l3);
    2341                                                 // now calculate the new length for the lines using cos
    2342                                                 // rule
    2343                                                 double l_new = l3 / (2 * cosTheta);
    2344                                                 double ratio = l_new / l1;
    2345                                                 MouseX = Math.round((e.getX() - lineEnd1.getX())
    2346                                                                 * ratio)
    2347                                                                 + lineEnd1.getX();
    2348                                                 MouseY = Math.round((e.getY() - lineEnd1.getY())
    2349                                                                 * ratio)
    2350                                                                 + lineEnd1.getY();
    2351 
    2352                                         }
    2353                                 }
    2354                         }
    2355                 } else if (shiftStateChanged && !_controlDown && rubberBanding()) {
    2356                         // Get the line end that is being rubber banded
    2357                         Item thisEnd = FreeItems.getInstance().get(0).isLineEnd() ? FreeItems
    2358                                         .getInstance().get(0)
    2359                                         : FreeItems.getInstance().get(1);
    2360                         thisEnd.removeAllConstraints();
    2361                 }
    2362 
    2363                 if (_lastMouseMoved == null)
    2364                         _lastMouseMoved = e;
    2365 
    2366                 _lastMouseMoved = e;
    2367 
    2368                 refreshHighlights();
    2369 
    2370                 if (FreeItems.hasCursor()) {
    2371                         move(FreeItems.getCursor(), true);
    2372                 }
    2373 
    2374                 if (FreeItems.itemsAttachedToCursor()) {
    2375                         move(FreeItems.getInstance());
    2376                         // System.out.println(FreeItems.getInstance().size());
    2377                 }
    2378 
    2379                 if (_forceArrowCursor)
    2380                         updateCursor();
    2381 
    2382                 _forceArrowCursor = true;
    2383         }
    2384 
    23851852       
    2386         public void refreshHighlights() {
    2387                 // ByMike: Get the item the mouse is hovering over
    2388                 Item click = FrameUtils.getCurrentItem();
    2389                 Item on = null;
    2390                 // System.out.println(click);
    2391                 if (click != null) {
    2392                         on = click;
    2393                         // set the context
    2394                         if (on instanceof Line)
    2395                                 _context = CONTEXT_AT_LINE;
    2396                         else if (on instanceof Dot)
    2397                                 _context = CONTEXT_AT_DOT;
    2398                         else if (on instanceof Text) {
    2399                                 _context = CONTEXT_AT_TEXT;
    2400                         }
    2401                         if (FreeItems.getInstance().size() > 0)
    2402                                 _alpha = 60;
    2403                         else
    2404                                 _alpha = -1;
    2405                 } else {
    2406                         _context = CONTEXT_FREESPACE;
    2407                         _alpha = -1;
    2408                 }
    2409 
    2410                 // if the user is pointing at an item, highlight it
    2411                 if (on != null && !FreeItems.getInstance().contains(on)) {
    2412                         // if the user can spot-weld, show the virtual spot
    2413                         if (FreeItems.getInstance().size() == 2 && on instanceof Line) {
    2414                                 Line line = (Line) on;
    2415                                 Item freeItem0 = FreeItems.getInstance().get(0);
    2416                                 Item freeItem1 = FreeItems.getInstance().get(1);
    2417                                 Item lineEnd = freeItem0.isLineEnd() ? freeItem0 : (freeItem1
    2418                                                 .isLineEnd() ? freeItem1 : null);
    2419                                 if (lineEnd != null) {
    2420                                         if (_mouseDown == 0)
    2421                                                 line.showVirtualSpot(lineEnd, DisplayIO.getMouseX(),
    2422                                                                 FrameMouseActions.getY());
    2423                                 } else
    2424                                         // The user is pointing at another point or text item
    2425                                         // etc
    2426                                         FrameGraphics.changeHighlightMode(on,
    2427                                                         Item.HighlightMode.Normal);
    2428                         } else {
    2429                                 // FrameGraphics.ChangeSelectionMode(on,
    2430                                 // Item.SelectedMode.Connected);
    2431                                 // TODO: The method below is for the most part redundant                               
    2432                                
    2433                                 on = FrameGraphics.Highlight(on.getEditTarget());
    2434                         }
    2435                         // if the last item highlighted is still highlighted, clear it
    2436                         if (_lastHoldsHighlight) {
    2437                                 _lastHoldsHighlight = false;
    2438                                 for (Item i : DisplayIO.getCurrentFrame().getItems())
    2439                                         if (i.isHighlighted() && i != on)
    2440                                                 FrameGraphics.changeHighlightMode(i,
    2441                                                                 Item.HighlightMode.None);
    2442                         }
    2443 
    2444                         // if the user is not pointing at an item, check for enclosure
    2445                         // highlighting
    2446                 } else if (on == null) {
    2447                         Collection<Item> enclosure = FrameUtils.getEnclosingLineEnds();
    2448                         if (enclosure != null && enclosure.size() > 0) {
    2449                                 Item firstLineEnd = enclosure.iterator().next();
    2450                                 HighlightMode hm;
    2451                                 if(isShiftDown()) {
    2452                                         hm = HighlightMode.Connected;
    2453                                 } else {
    2454                                         hm = HighlightMode.Enclosed;
    2455                                 }
    2456                                 if (firstLineEnd.getLines().size() > 1 &&
    2457                                 // check that the enclosure is not part of a point being
    2458                                                 // dragged in space
    2459                                                 !ContainsOneOf(enclosure, FreeItems.getInstance())) {
    2460                                         on = firstLineEnd.getLines().get(0);
    2461                                         // System.out.println(on == null ? "Null" :
    2462                                         // on.toString());
    2463                                         FrameGraphics.changeHighlightMode(on, hm);
    2464                                 } else if (firstLineEnd instanceof XRayable) {
    2465                                         on = firstLineEnd;
    2466                                         FrameGraphics.changeHighlightMode(firstLineEnd, hm);
    2467                                 }
    2468                                 _context = CONTEXT_AT_ENCLOSURE;
    2469                         } else if (_lastHighlightedItem != null) {
    2470                                 // System.out.println("LastHighlightedItem");
    2471                                 _lastHoldsHighlight = false;
    2472                         }
    2473                 }
    2474 
    2475                 // disable cursor changes when the cursor has items attached
    2476                 if (FreeItems.itemsAttachedToCursor()
    2477                                 && DisplayIO.getCursor() != Item.TEXT_CURSOR)
    2478                         _forceArrowCursor = false;
    2479 
    2480                 // setLastHighlightedItem(on);
    2481 
    2482                 if (_lastHighlightedItem != null && _lastHighlightedItem != on
    2483                                 && !_lastHoldsHighlight) {
    2484                         // Turn off the highlighting only if
    2485                         // the last highlighted item is not connected to the currentItem
    2486                         // Otherwise we get flickering in transition from connected to
    2487                         // normal mode while moving the cursor along a line.
    2488                         if (on == null
    2489                                         || (!on.getAllConnected().contains(_lastHighlightedItem))) {
    2490                                 FrameGraphics.changeHighlightMode(_lastHighlightedItem,
    2491                                                 Item.HighlightMode.None);
    2492                         }
    2493                 }
    2494 
    2495                 _lastHighlightedItem = on;
    2496 
    2497         }
    2498 
    2499         private boolean ContainsOneOf(Collection<Item> enclosure,
    2500                         Collection<Item> freeItems) {
    2501                 if (freeItems == null)
    2502                         return false;
    2503                 for (Item i : freeItems) {
    2504                         if (enclosure.contains(i))
    2505                                 return true;
    2506                 }
    2507                 return false;
    2508         }
    2509 
    2510         /**
    2511          * Checks if lines are being rubber banded.
    2512          *
    2513          * @return true if the user is rubberBanding one or more lines
    2514          */
    2515         private static boolean rubberBanding() {
    2516                 if (FreeItems.getInstance().size() != 2) {
    2517                         return false;
    2518                 }
    2519 
    2520                 // if rubber-banding, there will be 1 lineend and the rest will be lines
    2521                 boolean foundLineEnd = false;
    2522                 for (Item i : FreeItems.getInstance()) {
    2523                         if (i.isLineEnd()) {
    2524                                 if (foundLineEnd) {
    2525                                         return false;
    2526                                 }
    2527                                 foundLineEnd = true;
    2528                         } else if (!(i instanceof Line) || !i.isVisible()) {
    2529                                 return false;
    2530                         }
    2531                 }
    2532                 return true;
    2533         }
    2534 
    2535         /**
    2536          * Updates the current mouse cursor to whatever it should be. i.e. Hidden
    2537          * when rubber-banding lines, otherwise default (arrow)
    2538          */
    2539         public static void updateCursor() {
    2540                 if (rubberBanding()) {
    2541                         DisplayIO.setCursor(Item.HIDDEN_CURSOR);
    2542                         return;
    2543                 }
    2544                 // This is to make sure the TEXT_CURSOR doesnt get inadvertantly turned
    2545                 // off!
    2546                 Item on = FrameUtils.getCurrentItem();
    2547                 if (on != null && on instanceof Text) {
    2548                         return;
    2549                 }
    2550                 DisplayIO.setCursor(Item.DEFAULT_CURSOR);
    2551         }
    2552 
    2553         public static void setHighlightHold(boolean hold) {
    2554                 _lastHoldsHighlight = hold;
    2555         }
    2556 
    2557         public static void resetOffset() {
    2558                 if (FreeItems.itemsAttachedToCursor()) {
    2559                         _offX = DisplayIO.getMouseX()
    2560                                         - FreeItems.getInstance().get(0).getX()
    2561                                         + FreeItems.getInstance().get(0).getOffset().x;
    2562                         _offY = getY() - FreeItems.getInstance().get(0).getY()
    2563                                         + FreeItems.getInstance().get(0).getOffset().y;
    2564                 }
    2565         }
    2566 
    2567         /**
    2568          * Moves the items to the current mouse position (plus the current offset)
    2569          *
    2570          * @param toMove
    2571          */
    2572         static void move(Collection<Item> toMove) {
    2573                 move(toMove, false);
    2574         }
    2575 
    2576         static void move(Collection<Item> toMove, boolean cursor) {
    2577 
    2578                 // Gets the origin of the first item to move
    2579                 int xPos = (DisplayIO.getMouseX() - (cursor ? 0 : _offX));
    2580 
    2581                 Item firstDot = toMove.iterator().next();
    2582 
    2583                 int deltax = firstDot.getX() - xPos;
    2584                 int deltay = firstDot.getY() - (getY() - (cursor ? 0 : _offY));
    2585 
    2586                 for (Item move : toMove) {
    2587                         move.setPosition(move.getX() - deltax, move.getY() - deltay);
    2588 
    2589                         if (!cursor && move instanceof Text) {
    2590                                 ((Text) move).setAlpha(_alpha);
    2591                         }
    2592                 }
    2593 
    2594                 FrameGraphics.requestRefresh(true);
    2595                 // FrameGraphics.refresh(true);
    2596         }
    2597 
    2598         private static void load(String toLoad, boolean addToHistory) {
    2599                 if (FrameIO.isValidFrameName(toLoad)) {
    2600                         DisplayIO.clearBackedUpFrames();
    2601                         FrameUtils.DisplayFrame(toLoad, addToHistory, true);
    2602                 } else {
    2603                         MessageBay.errorMessage(toLoad + " is not a valid frame name.");
    2604                 }
    2605         }
    2606 
    2607         private static void back() {
    2608                 DisplayIO.Back();
    2609 
    2610                 // repaint things if necessary
    2611                 if (FreeItems.itemsAttachedToCursor())
    2612                         move(FreeItems.getInstance());
    2613 
    2614                 if (FreeItems.hasCursor())
    2615                         move(FreeItems.getCursor(), true);
    2616         }
    2617 
    2618         private static void forward() {
    2619                 DisplayIO.Forward();
    2620 
    2621                 // repaint things if necessary
    2622                 if (FreeItems.itemsAttachedToCursor())
    2623                         move(FreeItems.getInstance());
    2624 
    2625                 if (FreeItems.hasCursor())
    2626                         move(FreeItems.getCursor(), true);
    2627         }
    2628 
    2629         /**
    2630          * Returns true if the mouse moved during TDFC. This will happen if there is
    2631          * a start annotation item on the frame.
    2632          *
    2633          * @param linker
    2634          * @return
    2635          */
    2636         public static boolean tdfc(Item linker) throws RuntimeException {
    2637                 // if this is a non-usable item
    2638                 if (linker.getID() < 0)
    2639                         return false;
    2640 
    2641                 // Check if its an image that can be resized to fit a box
    2642                 // around it
    2643                 String text = linker.getText();
    2644                 boolean isVector = text.equals("@v") || text.equals("@av");
    2645                 boolean isFrameImage = text.equals("@f");
    2646                 boolean isBitmap = false; // text.equals("@b");
    2647 
    2648                 if (isVector || isFrameImage || isBitmap) {
    2649                         Collection<Item> enclosure = FrameUtils.getEnclosingLineEnds(linker
    2650                                         .getPosition());
    2651                         if (enclosure != null) {
    2652                                 for (Item i : enclosure) {
    2653                                         if (i.isLineEnd() && i.isEnclosed()) {
    2654                                                 if (!isVector)
    2655                                                         DisplayIO.getCurrentFrame().removeAllItems(
    2656                                                                         enclosure);
    2657                                                 Rectangle rect = i.getEnclosedRectangle();
    2658                                                 long width = Math.round(rect.getWidth());
    2659                                                 if (isVector) {
    2660                                                         NumberFormat nf = Vector.getNumberFormatter();
    2661                                                         linker.setText(linker.getText()
    2662                                                                         + ": "
    2663                                                                         + nf.format((width / FrameGraphics
    2664                                                                                         .getMaxFrameSize().getWidth())));
    2665                                                 } else {
    2666                                                         linker.setText(linker.getText() + ": " + width);
    2667                                                 }
    2668 
    2669                                                 linker.setPosition(new Point(rect.x, rect.y));
    2670                                                 linker.setThickness(i.getThickness());
    2671                                                 linker.setBorderColor(i.getColor());
    2672                                                 break;
    2673                                         }
    2674                                 }
    2675                                 if (!isVector)
    2676                                         FrameMouseActions.deleteItems(enclosure, false);
    2677                         }
    2678                 }
    2679 
    2680                 boolean mouseMoved;
    2681 
    2682                 linker.getParent().setChanged(true);
    2683 
    2684                 Frame next = FrameIO.CreateNewFrame(linker, _onFrameAction);
    2685 
    2686                 linker.setLink("" + next.getNumber());
    2687 
    2688                 for (Item i : next.getTextItems()) {
    2689                         // Set the link for @Parent annotation item if one
    2690                         if (ItemUtils.startsWithTag(i, ItemUtils.TAG_PARENT)
    2691                                         && i.getLink() == null) {
    2692                                 Frame parent = linker.getParentOrCurrentFrame();
    2693                                 i.setLink(parent.getName());
    2694                         } else if (ItemUtils.startsWithTag(i, ItemUtils.TAG_BACKUP, false)) {
    2695                                 // Delink backup tag if it is on the frame
    2696                                 i.setLink(null);
    2697                         }
    2698                 }
    2699 
    2700                 FrameUtils.DisplayFrame(next, true, true);
    2701                 FrameUtils.setTdfcItem(linker);
    2702 
    2703                 mouseMoved = next.moveMouseToDefaultLocation();
    2704                 // this needs to be done if the user doesnt move the mouse before doing
    2705                 // tdfc while the cursor is set to the text cursor
    2706                 DisplayIO.setCursor(Item.DEFAULT_CURSOR);
    2707                 // This needs to be done in case there was a @start on the frame which
    2708                 // triggers changed to be set to true when it should stay as false
    2709                 next.setChanged(false);
    2710                 return mouseMoved;
    2711         }
    2712 
    2713         /**
    2714          * Creates a new Text item and fills it with particular attributes extracted
    2715          * from the given Item. Note: Users always have permission to extract
    2716          * attributes, so it is not checked.
    2717          *
    2718          * @param toExtract
    2719          *            Item containing the Item to extract the attributes from.
    2720          */
    2721         private static void extractAttributes(Item toExtract) {
    2722                 if (toExtract == null || toExtract == null)
    2723                         return;
    2724 
    2725                 if (FreeItems.itemsAttachedToCursor())
    2726                         return;
    2727 
    2728                 Item attribs;
    2729                 Item item = toExtract;
    2730                 // Extract the frames attributes when the user clicks on the frame name
    2731                 FrameGraphics.changeHighlightMode(item, HighlightMode.None);
    2732                 if (item.isFrameName())
    2733                         attribs = AttributeUtils.extractAttributes(item.getParent());
    2734                 else {
    2735                         attribs = AttributeUtils.extractAttributes(item);
    2736                 }
    2737 
    2738                 if (attribs == null)
    2739                         MessageBay
    2740                                         .displayMessage("All attributes of that item are default values.");
    2741                 else {
    2742                         // Give the attribute text item the color of the item for which
    2743                         // attributes are being extracted.
    2744                         // attribs.setColor(item.getColor());
    2745                         pickup(attribs);
    2746                 }
    2747         }
    2748 
    2749         public static void delete(Item toDelete) {
    2750                 boolean bRecalculate = false;
    2751 
    2752                 FrameUtils.setLastEdited(null);
    2753                 _offX = _offY = 0;
    2754 
    2755                 Frame currentFrame = DisplayIO.getCurrentFrame();
    2756                 // check if the user is pointing at the frame's framename
    2757                 if (toDelete != null && toDelete == currentFrame.getNameItem()) {
    2758                         currentFrame.clear(false);
    2759                         FrameGraphics.Repaint();
    2760                         return;
    2761                 }
    2762 
    2763                 // if the user is deleting items attached to the cursor
    2764                 if (FreeItems.itemsAttachedToCursor()) {
    2765                         // if this is an item-swap
    2766                         if (FreeItems.getInstance().size() == 1
    2767                                         && FreeItems.getInstance().get(0) instanceof Text
    2768                                         && toDelete != null && toDelete instanceof Text) {
    2769 
    2770                                 // check permissions
    2771                                 if (!toDelete.hasPermission(UserAppliedPermission.full)) {
    2772                                         MessageBay
    2773                                                         .displayMessage("Insufficient permission to swap Item text");
    2774                                         return;
    2775                                 }
    2776                                 Text anchored = (Text) toDelete;
    2777                                 Text free = (Text) FreeItems.getInstance().get(0);
    2778                                 SessionStats.DeletedItem(free);
    2779                                 // List<String> temp = anchored.getText();
    2780                                 anchored.setText(free.getText());
    2781                                 anchored.setFormula(free.getFormula());
    2782 
    2783                                 // free.setTextList(temp);
    2784                                 FreeItems.getInstance().clear();
    2785 
    2786                                 anchored.getParent().setChanged(true);
    2787 
    2788                                 bRecalculate |= free.recalculateWhenChanged();
    2789                                 bRecalculate |= anchored.recalculateWhenChanged();
    2790 
    2791                                 // update the offset since the text has changed
    2792                                 _offX = DisplayIO.getMouseX() - anchored.getX()
    2793                                                 + anchored.getOffset().x;
    2794                                 _offY = getY() - anchored.getY() + anchored.getOffset().y;
    2795                         } else {
    2796                                 // if shift is pressed delete the entire shape attached to the dot
    2797                                 if(isShiftDown()) {
    2798                                 List<Item> tmp = new ArrayList<Item>(FreeItems.getInstance());
    2799                                 for(Item i : tmp) {
    2800                                         // remove entire rectangles instead of just the corner
    2801                                         if(i instanceof Dot) {
    2802                                                 FreeItems.getInstance().addAll(i.getAllConnected());
    2803                                                 for(Item j : i.getAllConnected()) {
    2804                                                         if(j instanceof Dot) {
    2805                                                                 FreeItems.getInstance().addAll(j.getLines());
    2806                                                         }
    2807                                                 }
    2808                                         }
    2809                                 }
    2810                                 }
    2811                                 deleteItems(FreeItems.getInstance());
    2812                         }
    2813                         // reset the mouse cursor
    2814                         updateCursor();
    2815                         // the user is not pointing at an item
    2816                 } else if (toDelete == null) {
    2817                
    2818                         // if the user is pointing inside a closed shape, delete it
    2819                        
    2820                         Collection<Item> items = null;
    2821                         // if shift is down, only delete the enclosing shape (ignore the items inside)
    2822                         if(isShiftDown()) {
    2823                                 Collection<Item> tmp = FrameUtils.getEnclosingLineEnds();
    2824                                 if(tmp != null) {
    2825                                         items = new ArrayList<Item>();
    2826                                         items.addAll(tmp);
    2827                                 for(Item i : tmp) {
    2828                                         if(i instanceof Dot) {
    2829                                                 items.addAll(((Dot)i).getLines());
    2830                                         }
    2831                                 }
    2832                                 }
    2833                         } else {
    2834                                 items = FrameUtils.getCurrentItems(null);
    2835                         }
    2836                        
    2837                         if (items != null) {
    2838                                 Collection<Item> toRemove = new LinkedHashSet<Item>(items
    2839                                                 .size());
    2840                                 for (Item ip : items) {
    2841                                         if (ip.hasPermission(UserAppliedPermission.full)) {
    2842                                                 // Only include lines if one of their enpoints are also
    2843                                                 // being removed
    2844                                                 if (ip instanceof Line) {
    2845                                                         Line l = (Line) ip;
    2846                                                         Item end = l.getEndItem();
    2847                                                         Item start = l.getStartItem();
    2848 
    2849                                                         // If one end of a line is being deleted, remove the
    2850                                                         // other end if all its connecting lines are being
    2851                                                         // deleted
    2852                                                         if (items.contains(end)) {
    2853                                                                 if (!items.contains(start)
    2854                                                                                 && items.containsAll(start.getLines())) {
    2855                                                                         toRemove.add(start);
    2856                                                                 }
    2857                                                         } else if (items.contains(start)) {
    2858                                                                 if (items.containsAll(end.getLines())) {
    2859                                                                         toRemove.add(end);
    2860                                                                 }
    2861                                                         } else {
    2862                                                                 continue;
    2863                                                         }
    2864                                                 }
    2865                                                 toRemove.add(ip);
    2866                                         }
    2867                                 }
    2868 
    2869                                 deleteItems(toRemove);
    2870 
    2871                                 // reset the mouse cursor
    2872                                 updateCursor();
    2873                                 FrameGraphics.Repaint();
    2874 
    2875                                 // otherwise this is an undo command
    2876                         } else {
    2877                                 if(isControlDown()) {
    2878                                         DisplayIO.getCurrentFrame().redo();
    2879                                 } else {
    2880                                         DisplayIO.getCurrentFrame().undo();
    2881                                 }
    2882                         }
    2883                         return;
    2884                         // this is a delete command
    2885                 } else {
    2886                        
    2887                         // Special case if toDelete item is an image: only want to delete if over non-background pixel color
    2888                         if (toDelete instanceof Picture) {
    2889                                 int mouseX = DisplayIO.getMouseX();
    2890                                 int mouseY = FrameMouseActions.getY();
    2891                                 Picture clickedOnPicture = (Picture)toDelete;
    2892                                 Frame current_frame = DisplayIO.getCurrentFrame();
    2893                                 Color bg_col = current_frame.getBackgroundColor();
    2894                                 if (clickedOnPicture.MouseOverBackgroundPixel(mouseX,mouseY,bg_col)) {
    2895                                         // behave as if Redo/Undo request, then return
    2896                                         if(isControlDown()) {
    2897                                                 DisplayIO.getCurrentFrame().redo();
    2898                                         } else {
    2899                                                 DisplayIO.getCurrentFrame().undo();
    2900                                         }
    2901                                         return;
    2902                                 }
    2903                                 // If get to here, then user clicked on an image (non-trival pixel color),
    2904                                 // so go ahead and let it be deleted in the usual way
    2905                         }
    2906                                
    2907                        
    2908                         // check permissions
    2909                         if (!toDelete.hasPermission(UserAppliedPermission.full)) {
    2910                                 Item editTarget = toDelete.getEditTarget();
    2911                                 if (editTarget != toDelete
    2912                                                 && editTarget.hasPermission(UserAppliedPermission.full)) {
    2913                                         toDelete = editTarget;
    2914                                 } else {
    2915                                         MessageBay
    2916                                                         .displayMessage("Insufficient permission to delete item");
    2917                                         return;
    2918                                 }
    2919                         }
    2920 
    2921                         Frame parent = toDelete.getParent();
    2922                         if (parent != null) {
    2923                                 parent.setChanged(true);
    2924                         }
    2925                         Collection<Item> toUndo = null;
    2926                         if (toDelete.isLineEnd()) {
    2927                                 // delete the entire connected shape if shift is down
    2928                                 if(isShiftDown()) {
    2929                                         List<Item> tmp = new ArrayList<Item>();
    2930                                         tmp.add(toDelete);
    2931                                         // remove entire shape instead of just the corner
    2932                                         tmp.addAll(toDelete.getAllConnected());
    2933                                         for(Item j : toDelete.getAllConnected()) {
    2934                                                 if(j instanceof Dot) {
    2935                                                         tmp.addAll(j.getLines());
    2936                                                 }
    2937                                         }
    2938                                         deleteItems(tmp);
    2939                                         return;
    2940                                 } else {
    2941                                         toUndo = deleteLineEnd(toDelete);
    2942                                 }
    2943                                 // delete the entire connected shape if shift is down, unless we're hovering the end of the line
    2944                         } else if (toDelete instanceof WidgetEdge) { // must notify
    2945                                 // widgets that they
    2946                                 // are being deleted
    2947                                 ((WidgetEdge) toDelete).getWidgetSource().onDelete();
    2948                                 toUndo = toDelete.getConnected();
    2949                         } else if (toDelete instanceof Line && isShiftDown() ||
    2950                                         toDelete.getHighlightMode() == Item.HighlightMode.Disconnect) {
    2951                                 Line line = (Line) toDelete;
    2952                                 Item start = line.getStartItem();
    2953                                 Item end = line.getEndItem();
    2954                                 Collection<Item> delete = new LinkedList<Item>();
    2955                                 delete.add(toDelete);
    2956                                 if (end.getLines().size() == 1) {
    2957                                         delete.add(end);
    2958                                 } else {
    2959                                         end.removeLine(line);
    2960                                 }
    2961                                 if (start.getLines().size() == 1) {
    2962                                         delete.add(start);
    2963                                 } else {
    2964                                         start.removeLine(line);
    2965                                 }
    2966                                 toUndo = delete;
    2967                         } else {
    2968                                 bRecalculate |= toDelete.recalculateWhenChanged();
    2969                                 toUndo = toDelete.getConnected(); // copy(toDelete.getConnected());
    2970                         }
    2971                         SessionStats.DeletedItems(toUndo);
    2972                         if (parent != null) {
    2973                                 parent.addToUndoDelete(toUndo);
    2974                                 parent.removeAllItems(toUndo); // toDelete.getConnected()
    2975                         }
    2976                         // reset the mouse cursor
    2977                         updateCursor();
    2978                         if (parent != null)
    2979                                 // ItemUtils.EnclosedCheck(parent.getItems());
    2980                                 ItemUtils.Justify(parent);
    2981                         if (toDelete.hasOverlay()) {
    2982                                 FrameUtils.Parse(parent, false, false);
    2983                                 FrameGraphics.requestRefresh(false);
    2984                         }
    2985 
    2986                         DisplayIO.setCursor(Item.DEFAULT_CURSOR);
    2987 
    2988                 }
    2989 
    2990                 currentFrame.notifyObservers(bRecalculate);
    2991 
    2992                 FrameGraphics.Repaint();
    2993         }
    2994 
    2995         public static void deleteItems(Collection<Item> itemList) {
    2996                 deleteItems(itemList, true);
    2997         }
    2998 
    2999         public static void deleteItems(Collection<Item> itemList, boolean addToUndo) {
    3000                 boolean bReparse = false;
    3001                 boolean bRecalculate = false;
    3002 
    3003                 SessionStats.DeletedItems(itemList);
    3004                 List<Frame> modifiedFrames = new LinkedList<Frame>();
    3005                 // Get a list of all the modified frames
    3006                 for (Item i : itemList) {
    3007                         Frame parent = i.getParent();
    3008                         if (parent != null)
    3009                                 modifiedFrames.add(parent);
    3010                         i.setHighlightMode(HighlightMode.None);
    3011                         bReparse |= i.hasOverlay();
    3012                         bRecalculate |= i.recalculateWhenChanged();
    3013                 }
    3014                 // If they are all free items then add the current frame
    3015                 if (modifiedFrames.size() == 0) {
    3016                         modifiedFrames.add(DisplayIO.getCurrentFrame());
    3017                 }
    3018 
    3019                 Collection<Item> toUndo = new LinkedHashSet<Item>();
    3020                 // disconnect any connected items
    3021                 for (Item i : itemList) {
    3022 
    3023                         // Only delete the current item if have not already deleted.
    3024                         // This is especially important for heavy duty widgets - so they
    3025                         // do not have to expire several times per delete.
    3026                         if (toUndo.contains(i))
    3027                                 continue;
    3028 
    3029                         // Make sure text items attached to cursor are reset back to the
    3030                         // transparency they should have.
    3031                         if (i instanceof Text) {
    3032                                 ((Text) i).setAlpha(-1);
    3033                         }
    3034 
    3035                         if (i.getLines().size() > 0) {
    3036 
    3037                                 Collection<Item> toDelete = deleteLineEnd(i);
    3038                                 if (addToUndo) {
    3039                                         // add the copied items to the undo stack
    3040                                         for (Item itemToUndo : toDelete) {
    3041 
    3042                                                 if (!toUndo.contains(itemToUndo))
    3043                                                         toUndo.add(itemToUndo);
    3044 
    3045                                         }
    3046                                 }
    3047                         } else if (!toUndo.contains(i)) {
    3048                                 if (addToUndo)
    3049                                         toUndo.add(i); // Why was is this a copy
    3050                         }
    3051                 }
    3052 
    3053                 for (Frame f : modifiedFrames) {
    3054                         f.removeAllItems(itemList);
    3055                         // ItemUtils.EnclosedCheck(f.getItems());
    3056                         ItemUtils.Justify(f);
    3057                 }
    3058                 // TODO: How should undelete deal with undo when items are removed from
    3059                 // the current frame as well as the overlay frame
    3060                 Frame currentFrame = DisplayIO.getCurrentFrame();
    3061                 currentFrame.addToUndoDelete(itemList);
    3062                 itemList.clear();
    3063                 if (bReparse) {
    3064                         FrameUtils.Parse(currentFrame, false, false);
    3065                         /*
    3066                          * TODO check if I need to recalculate even if reparse occurs, here
    3067                          * and in anchor, pickup etc
    3068                          */
    3069                 } else {
    3070                         currentFrame.notifyObservers(bRecalculate);
    3071                 }
    3072 
    3073         }
    3074 
    3075         private static Collection<Item> deleteLineEnd(Item lineEnd) {
    3076 
    3077                 if (lineEnd instanceof WidgetCorner) { // Brook
    3078 
    3079                         WidgetCorner wc = (WidgetCorner) lineEnd;
    3080                         Frame parent = wc.getWidgetSource().getParentFrame();
    3081 
    3082                         // Remove from the parent frame
    3083                         if (parent != null) {
    3084                                 parent.removeAllItems(wc.getWidgetSource().getItems());
    3085                         }
    3086 
    3087                         wc.getWidgetSource().onDelete(); // Changes the widgets
    3088                         // corner/edges ID's...
    3089 
    3090                         return wc.getWidgetSource().getItems();
    3091 
    3092                 } else {
    3093 
    3094                         // // create a backup copy of the dot and its lines
    3095                         // List<Item> copy = copy(lineEnd.getConnected());
    3096                         //                     
    3097                         // // Remove lines from their anchored dots
    3098                         // // note: the line is kept so that it can be properly restored
    3099                         // for (Item ic : copy) {
    3100                         // if (ic instanceof Line) {
    3101                         // Line line = (Line) ic;
    3102                         // // Remove the line from the item that is not the copy of the
    3103                         // // line end being deletedF
    3104                         // if (!copy.contains(line.getStartItem()))
    3105                         // line.getStartItem().removeLine(line);
    3106                         // if (!copy.contains(line.getEndItem()))
    3107                         // line.getEndItem().removeLine(line);
    3108                         // }
    3109                         // }
    3110 
    3111                         Collection<Item> copy = lineEnd.getConnected();
    3112 
    3113                         // remove all lines being deleted
    3114                         for (Item ic : lineEnd.getConnected()) {
    3115                                 if (ic instanceof Line
    3116                                                 && ((Line) ic).getOppositeEnd(lineEnd) != null) {
    3117                                         Line line = (Line) ic;
    3118 
    3119                                         // Invalidate the line to make sure we dont get any ghost
    3120                                         // arrowheads.
    3121                                         ic.invalidateAll();
    3122 
    3123                                         Item d = line.getOppositeEnd(lineEnd);
    3124                                         d.removeLine(line);
    3125 
    3126                                         // if the dot was only part of one line, it can be
    3127                                         // removed
    3128                                         if (d.getLines().size() == 0) {
    3129                                                 if (d.getParent() != null)
    3130                                                         d.getParent().removeItem(d);
    3131                                                 if (!copy.contains(d))
    3132                                                         copy.add(d);
    3133                                         }
    3134 
    3135                                         if (lineEnd.getParent() != null)
    3136                                                 lineEnd.getParent().removeItem(ic);
    3137                                 }
    3138                         }
    3139                         return copy;
    3140                 }
    3141         }
    3142 
    3143         private static void removeAllLinesExcept(Item from, Item but) {
    3144                 List<Line> lines = new LinkedList<Line>();
    3145                 lines.addAll(from.getLines());
    3146                 for (Line line : lines)
    3147                         if (line.getOppositeEnd(from) != but)
    3148                                 from.removeLine(line);
    3149 
    3150                 List<Constraint> consts = new LinkedList<Constraint>();
    3151                 consts.addAll(from.getConstraints());
    3152                 for (Constraint c : consts)
    3153                         if (c.getOppositeEnd(from) != but)
    3154                                 from.removeConstraint(c);
    3155         }
    3156 
    3157         public static Collection<Item> merge(List<Item> merger, Item mergee) {
    3158                 assert (mergee != null);
    3159                 if (mergee.isFrameName()) {
    3160                         return mergee.getParent().merge(merger);
    3161                 }
    3162 
    3163                 // if(mergee instanceof XRayable)
    3164                 // return merger;
    3165 
    3166                 // check for rectangle merging
    3167                 if (merger.size() == 3 && mergee.getLines().size() == 2) {
    3168                         Item corner = getShapeCorner(merger);
    3169                         // if this is a corner of a shape
    3170                         if (corner != null) {
    3171                                 Collection<Item> allConnected = corner.getAllConnected();
    3172                                 // Check if we are collapsing a rectangle
    3173                                 if (allConnected.size() == 8 && allConnected.contains(mergee)) {
    3174                                         DisplayIO.setCursorPosition(mergee.getPosition());
    3175                                         DisplayIO.getCurrentFrame().removeAllItems(allConnected);
    3176 
    3177                                         // find the point opposite corner...
    3178                                         Item opposite = null;
    3179                                         List<Line> lines = corner.getLines();
    3180                                         for (Line l : lines) {
    3181                                                 allConnected.remove(l.getOppositeEnd(corner));
    3182                                         }
    3183                                         allConnected.remove(corner);
    3184                                         for (Item i : allConnected) {
    3185                                                 if (i.isLineEnd()) {
    3186                                                         opposite = i;
    3187                                                         break;
    3188                                                 }
    3189                                         }
    3190                                         assert (opposite != null);
    3191 
    3192                                         // check if the rectangle is small enough that it should be
    3193                                         // collapsed to a single point
    3194                                         int x1 = Math.abs(opposite.getX() - mergee.getX());
    3195                                         int x2 = Math.abs(opposite.getY() - mergee.getY());
    3196                                         int distance = (int) Math.sqrt(Math.pow(x1, 2)
    3197                                                         + Math.pow(x2, 2));
    3198 
    3199                                         if (distance < RECTANGLE_TO_POINT_THRESHOLD) {
    3200                                                 mergee.removeAllConstraints();
    3201                                                 mergee.removeAllLines();
    3202                                                 mergee.setThickness(4 * mergee.getThickness());
    3203                                                 return mergee.getAllConnected();
    3204                                         } else {
    3205                                                 removeAllLinesExcept(mergee, opposite);
    3206                                                 removeAllLinesExcept(opposite, mergee);
    3207 
    3208                                                 return mergee.getAllConnected();
    3209                                         }
    3210                                 }
    3211                         }
    3212                 }
    3213 
    3214                 List<Item> remain = new ArrayList<Item>();
    3215                 Item res = null;
    3216 
    3217                 for (Item i : merger) {                 
    3218                         if (!i.isVisible())
    3219                                 continue;
    3220                         // check for link merging
    3221                         if (i instanceof Text
    3222                                         && FrameIO.isValidFrameName((((Text) i).getFirstLine()))
    3223                                         && FrameIO.canAccessFrame((((Text) i).getFirstLine()))) {
    3224                                 // check that we can actually access the frame this link
    3225                                 // corresponds to
    3226                                 mergee.setLink(((Text) i).getFirstLine());
    3227                         } else {
    3228                                 // check for attribute merging
    3229                                 if (i instanceof Text && !i.isLineEnd()) {
    3230                                         Text txt = (Text) i;
    3231 
    3232                                         // if this is not an attribute merge
    3233                                         if (!AttributeUtils.setAttribute(mergee, txt)) {
    3234                                                 // set mouse position for text merges
    3235                                                 if (mergee instanceof Text) {
    3236                                                         ((Text) mergee).insertText(txt.getText(), DisplayIO
    3237                                                                         .getMouseX(), FrameMouseActions.getY());
    3238                                                         //Delete the item which had its text merged
    3239                                                         txt.delete();
    3240                                                         return remain;
    3241                                                 } else if (mergee instanceof WidgetCorner) {
    3242                                                         if (merger.size() == 1 && txt.getLink() != null) {
    3243                                                                 // If the text item is linked then use that
    3244                                                                 ((WidgetCorner) mergee).setLink(txt
    3245                                                                                 .getAbsoluteLink(), txt);
    3246                                                         } else {
    3247                                                                 remain.addAll(merger);
    3248                                                         }
    3249                                                         return remain;
    3250                                                 } else if (mergee instanceof WidgetEdge) {
    3251                                                         if (merger.size() == 1 && txt.getLink() != null) {
    3252                                                                 // If the text item is linked then use that
    3253                                                                 ((WidgetEdge) mergee).setLink(txt
    3254                                                                                 .getAbsoluteLink(), txt);
    3255                                                         } else {
    3256                                                                 remain.addAll(merger);
    3257                                                         }
    3258                                                         return remain;
    3259                                                 } else if (mergee instanceof Dot) {
    3260                                                         DisplayIO.setCursorPosition(mergee.getPosition());
    3261                                                         txt.setPosition(mergee.getPosition());
    3262                                                         txt.setThickness(mergee.getThickness());
    3263                                                         Frame parent = mergee.getParent();
    3264                                                         parent.removeItem(mergee);
    3265                                                         anchor(txt);
    3266                                                         // change the end points of the lines to the text
    3267                                                         // item
    3268                                                         while (mergee.getLines().size() > 0) {
    3269                                                                 Line l = mergee.getLines().get(0);
    3270                                                                 l.replaceLineEnd(mergee, txt);
    3271                                                         }
    3272                                                         break;
    3273                                                 }
    3274 
    3275                                                 // TODO tidy this up...
    3276                                                 // Dot override doesnt use the x and y coords
    3277                                                 // Text does... but could be removed
    3278                                                 res = mergee.merge(i, DisplayIO.getMouseX(), getY());
    3279                                                 if (res != null) {
    3280                                                         remain.add(res);
    3281                                                 }
    3282                                         }
    3283                                 } else {
    3284                                         if (mergee.isLineEnd()) {
    3285                                                 DisplayIO.setCursorPosition(mergee.getPosition());
    3286                                         }
    3287                                         // Moving the cursor ensures shapes are anchored correctly
    3288                                         res = mergee.merge(i, DisplayIO.getMouseX(), getY());
    3289                                         if (res != null)
    3290                                                 remain.addAll(res.getConnected());
    3291 
    3292                                 }
    3293                         }
    3294                 }
    3295                 updateCursor();
    3296 
    3297                 mergee.getParent().setChanged(true);
    3298 
    3299                 ItemUtils.EnclosedCheck(mergee.getParent().getItems());
    3300                 // Mike: Why does parse frame have to be called?!?
    3301                 FrameUtils.Parse(mergee.getParent());
    3302 
    3303                 return remain;
    3304         }
    3305 
    3306         /**
    3307          * Picks up an item on a frame.
    3308          *
    3309          * @param toGrab
    3310          *            item to be picked up
    3311          * @param removeItem
    3312          *            true if the item should be removed from the frame
    3313          */
    3314         public static void pickup(Item toGrab) {
    3315                 if (toGrab.isFrameName())
    3316                         return;
    3317 
    3318                 if (!toGrab.hasPermission(UserAppliedPermission.full)) {
    3319                         if (toGrab.getEditTarget() != toGrab) {
    3320                                 pickup(toGrab.getEditTarget());
    3321                         } else {
    3322                                 MessageBay
    3323                                                 .displayMessage("Insufficient permission pickup the item");
    3324                         }
    3325                         return;
    3326                 }
    3327 
    3328                 if (toGrab instanceof Circle)
    3329                         toGrab.setHighlightMode(HighlightMode.Connected);
    3330                 // Dont set the highlight mode if a vector is being picked up
    3331                 else if (toGrab.isVisible()) {
    3332                         toGrab.setHighlightMode(HighlightMode.Normal);
    3333                 }
    3334 
    3335                 // Brook: If the widget corner is being picked up. Instead refer to
    3336                 // picking up the edge for fixed-sized widgets so it is not so confusing
    3337                 if (toGrab instanceof WidgetCorner) {
    3338                         WidgetCorner wc = (WidgetCorner) toGrab;
    3339                         if (wc.getWidgetSource().isFixedSize()) {
    3340                                 for (Item i : toGrab.getConnected()) {
    3341                                         if (i instanceof WidgetEdge) {
    3342                                                 toGrab = i;
    3343                                                 break;
    3344                                         }
    3345                                 }
    3346                         }
    3347                 }
    3348                 pickup(toGrab.getConnected());
    3349         }
    3350 
    3351         public static void pickup(Collection<Item> toGrab) {
    3352                 if (toGrab == null || toGrab.size() == 0)
    3353                         return;
    3354 
    3355                 boolean bReparse = false;
    3356                 boolean bRecalculate = false;
    3357 
    3358                 Frame currentFrame = DisplayIO.getCurrentFrame();
    3359                 String currentFrameName = currentFrame.getName();
    3360                 Iterator<Item> iter = toGrab.iterator();
    3361                 while (iter.hasNext()) {
    3362                         Item i = iter.next();
    3363                         if (!i.hasPermission(UserAppliedPermission.full)) {
    3364                                 iter.remove();
    3365                                 continue;
    3366                         }
    3367                         if (i.equals(_lastHighlightedItem))
    3368                                 _lastHighlightedItem = null;
    3369 
    3370                         bRecalculate |= i.recalculateWhenChanged();
    3371                         // i.setSelectedMode(SelectedMode.None);
    3372                         // Check if it has a relative link if so make it absolute
    3373                         i.setAbsoluteLink();
    3374                         // parent may be null
    3375                         if (i.getParent() != null) {
    3376                                 i.getParent().removeItem(i);
    3377                                 if (currentFrameName.equals(i.getParent().getName()))
    3378                                         i.setParent(null);
    3379                         }
    3380                         FreeItems.getInstance().add(i);
    3381                         i.setFloating(true);
    3382                         // If its a vector pick up a copy of the stuff on the vector frame
    3383                         if (i.hasVector()) {
    3384                                 bReparse = true;
    3385 
    3386                                 Frame overlayFrame = FrameIO.LoadFrame(i.getAbsoluteLink());
    3387                                 Collection<Item> copies = ItemUtils.CopyItems(overlayFrame
    3388                                                 .getNonAnnotationItems(false), i.getVector());
    3389                                 for (Item copy : copies) {
    3390                                         FreeItems.getInstance().add(copy);
    3391                                         copy.setEditTarget(i);
    3392                                         copy.setFloating(true);
    3393                                         copy.setParent(null);
    3394                                         // copy.setHighlightMode(HighlightMode.Connected);
    3395                                 }
    3396                         }
    3397                 }
    3398                 currentFrame.change();
    3399 
    3400                 _lastHighlightedItem = null;
    3401                 updateCursor();
    3402 
    3403                 // if there are multiple items in the list, determine which to use for
    3404                 // offset calculations
    3405                 if (toGrab.size() > 1) {
    3406                         for (Item i : toGrab) {
    3407                                 // MIKE: Movement goes haywire if these are removed because Line
    3408                                 // class returns 0 for getX
    3409                                 if (!(i instanceof Line) && !(i instanceof XRayable)) {
    3410                                         _offX = DisplayIO.getMouseX() - i.getX() + i.getOffset().x;
    3411                                         _offY = getY() - i.getY() + i.getOffset().y;
    3412 
    3413                                         // make the offset item the first item in the list (so
    3414                                         // move method knows which item to use)
    3415                                         FreeItems.getInstance().set(
    3416                                                         FreeItems.getInstance().indexOf(i),
    3417                                                         FreeItems.getInstance().get(0));
    3418                                         FreeItems.getInstance().set(0, i);
    3419                                         break;
    3420                                 }
    3421                         }
    3422 
    3423                         move(FreeItems.getInstance());
    3424                         ItemUtils.EnclosedCheck(toGrab);
    3425                         // otherwise, just use the first item
    3426                 } else if (toGrab.size() == 1) {
    3427                         Item soleItem = toGrab.iterator().next();
    3428                         _offX = DisplayIO.getMouseX() - soleItem.getX()
    3429                                         + soleItem.getOffset().x;
    3430                         _offY = getY() - soleItem.getY() + soleItem.getOffset().y;
    3431                         // Now call move so that if we are on a message in the message box
    3432                         // It doesnt appear up the top of the scree!!
    3433                         move(toGrab);
    3434                 } else {
    3435                         MessageBay
    3436                                         .displayMessage("Insufficient permission to pickup the items");
    3437                 }
    3438                 if (bReparse)
    3439                         FrameUtils.Parse(currentFrame, false, false);
    3440                 else
    3441                         currentFrame.notifyObservers(bRecalculate);
    3442 
    3443                 FrameGraphics.Repaint();
    3444         }
    3445 
    3446         private static Line createLine() {
    3447                 Frame current = DisplayIO.getCurrentFrame();
    3448                 // create the two endpoints
    3449                 Item end = DisplayIO.getCurrentFrame().createDot();
    3450                 Item start = DisplayIO.getCurrentFrame().createDot();
    3451 
    3452                 // create the Line
    3453                 Line line = new Line(start, end, current.getNextItemID());
    3454                 line.autoArrowheadLength();
    3455 
    3456                 // anchor the start
    3457                 anchor(start);
    3458 
    3459                 // attach the line to the cursor
    3460                 pickup(end);
    3461                 _lastHighlightedItem = null;
    3462 
    3463                 // TODO figure out how to get the end to highlight
    3464                 // end.setSelectedMode(SelectedMode.Normal);
    3465                 // end.setSelectedMode(SelectedMode.None);
    3466 
    3467                 return line;
    3468         }
    3469 
    3470         /**
    3471          * Returns a list of copies of the list passed in
    3472          *
    3473          * @param toCopy
    3474          *            The list of items to copy
    3475          * @return A List of copied Items
    3476          */
    3477         private static List<Item> copy(Collection<Item> toCopy) {
    3478                 return ItemUtils.CopyItems(toCopy);
    3479         }
    3480 
    3481         public static void anchor(Item toAnchor, boolean checkEnclosure) {
    3482                 // Only anchor items we have full permission over... i.e. don't anchor vector items
    3483                 if (!toAnchor.hasPermission(UserAppliedPermission.full))
    3484                         return;
    3485 
    3486                 toAnchor.anchor();
    3487 
    3488                 if (checkEnclosure) {
    3489                         ItemUtils.EnclosedCheck(toAnchor.getParentOrCurrentFrame()
    3490                                         .getItems());
    3491                         FrameGraphics.Repaint();
    3492                 }
    3493         }
    3494 
    3495         public static void anchor(Item toAnchor) {
    3496                 anchor(toAnchor, true);
    3497         }
    3498 
    3499         public static void anchor(Collection<Item> toAnchor) {
    3500                 boolean bReparse = false;
    3501                 boolean bRecalculate = false;
    3502                 // Need to make sure we check enclosure for overlays etc
    3503                 Set<Frame> checkEnclosure = new HashSet<Frame>();
    3504 
    3505                 // Create a clone of toAnchor since in the proccess of anchoring items
    3506                 // they can change the state of the toAnchor collection and thus create
    3507                 // concurrent modification exceptions.
    3508                 // This is especially needed for widgets being removed when anchored:
    3509                 // since they
    3510                 // currently are composed of 8 items this is vital. In the new revision
    3511                 // of
    3512                 // widgets being implemented as a single item this this can be
    3513                 // depreciated
    3514                 // however it may be useful for other applications.
    3515                 Collection<Item> toAnchorCopy = new ArrayList<Item>(toAnchor);
    3516 
    3517                 for (Item i : toAnchorCopy) {
    3518                         if (toAnchor.contains(i)) { // since to anchor could change while
    3519                                 // anchoring
    3520                                 // if (!i.hasVector())
    3521                                 anchor(i, false);
    3522                                 checkEnclosure.add(i.getParentOrCurrentFrame());
    3523                                 bReparse |= i.hasOverlay();
    3524                                 bRecalculate |= i.recalculateWhenChanged();
    3525                         }
    3526                 }
    3527 
    3528                 toAnchor.clear();
    3529                 // Check enclosure for all the frames of the items that were anchored
    3530                 for (Frame f : checkEnclosure) {
    3531                         // ItemUtils.EnclosedCheck(f.getItems());
    3532                         ItemUtils.Justify(f);
    3533                 }
    3534 
    3535                 Frame currentFrame = DisplayIO.getCurrentFrame();
    3536                 if (bReparse)
    3537                         FrameUtils.Parse(currentFrame, false, false);
    3538                 else {
    3539                         currentFrame.notifyObservers(bRecalculate);
    3540                 }
    3541                 FrameGraphics.Repaint();
    3542         }
     1853
     1854       
     1855
     1856
     1857       
     1858
     1859       
     1860
     1861       
    35431862
    35441863        /*
     
    35541873
    35551874                if (FreeItems.getInstance().size() == 2) {
    3556                         if ((FreeItems.getInstance().get(0).isLineEnd() && FreeItems
    3557                                         .getInstance().get(1) instanceof Line)
    3558                                         || (FreeItems.getInstance().get(1).isLineEnd() && FreeItems
    3559                                                         .getInstance().get(0) instanceof Line)) {
    3560 
     1875                        if ((FreeItems.getInstance().get(0).isLineEnd() && FreeItems.getInstance().get(1) instanceof Line) ||
     1876                                        (FreeItems.getInstance().get(1).isLineEnd() && FreeItems.getInstance().get(0) instanceof Line))
     1877                        {
    35611878                                Line line;
    35621879                                if (FreeItems.getInstance().get(0) instanceof Line)
     
    35821899                        }
    35831900
    3584                         FrameKeyboardActions.functionKey(rotationType, 1, arg0
    3585                                         .isShiftDown(), arg0.isControlDown());
     1901                        FrameKeyboardActions.functionKey(rotationType, 1, arg0.isShiftDown(), arg0.isControlDown());
    35861902
    35871903                } else if (clicks >= MOUSE_WHEEL_THRESHOLD) {
     
    36181934         */
    36191935        public static int getLastMouseButton() {
    3620                 if (_lastMouseClick == null)
    3621                         return MouseEvent.NOBUTTON;
     1936                if (_lastMouseClick == null) return MouseEvent.NOBUTTON;
    36221937
    36231938                return _lastMouseClick.getButton();
     
    36251940
    36261941        public static boolean isDelete(int modifiersEx) {
    3627 
    3628                 int onMask = MouseEvent.BUTTON3_DOWN_MASK
    3629                                 | MouseEvent.BUTTON2_DOWN_MASK;
     1942                int onMask = MouseEvent.BUTTON3_DOWN_MASK | MouseEvent.BUTTON2_DOWN_MASK;
    36301943                return (modifiersEx & onMask) == onMask;
    36311944        }
    36321945
    36331946        public static boolean isGetAttributes(int modifiersEx) {
    3634                 int onMask = MouseEvent.BUTTON3_DOWN_MASK
    3635                                 | MouseEvent.BUTTON1_DOWN_MASK;
     1947                int onMask = MouseEvent.BUTTON3_DOWN_MASK | MouseEvent.BUTTON1_DOWN_MASK;
    36361948                return (modifiersEx & onMask) == onMask;
    36371949        }
    36381950
    36391951        public static boolean isTwoClickNoOp(int modifiersEx) {
    3640                 int onMask = MouseEvent.BUTTON2_DOWN_MASK
    3641                                 | MouseEvent.BUTTON1_DOWN_MASK;
     1952                int onMask = MouseEvent.BUTTON2_DOWN_MASK | MouseEvent.BUTTON1_DOWN_MASK;
    36421953                return (modifiersEx & onMask) == onMask;
    36431954        }
     
    37052016        }
    37062017
    3707         public static Item getlastHighlightedItem() {
    3708                 return _lastHighlightedItem;
    3709         }
    3710 
    37112018        public static Point getPosition() {
    37122019                return new Point(getX(), getY());
     
    37222029                getInstance().refreshHighlights();
    37232030        }
     2031
     2032        @Override
     2033        public void onGesture(Gesture gesture) {
     2034                // TODO Auto-generated method stub
     2035               
     2036        }
    37242037}
  • trunk/src/org/expeditee/gui/FrameUtils.java

    r1064 r1102  
    1919package org.expeditee.gui;
    2020
    21 import java.awt.Color;
    22 import java.awt.Point;
    23 import java.awt.Polygon;
    24 import java.awt.Rectangle;
    2521import java.io.File;
    2622import java.io.FileInputStream;
     
    4440import java.util.zip.ZipEntry;
    4541
     42import org.expeditee.core.Colour;
     43import org.expeditee.core.Point;
     44import org.expeditee.core.bounds.AxisAlignedBoxBounds;
     45import org.expeditee.core.bounds.PolygonBounds;
     46import org.expeditee.gio.EcosystemManager;
     47import org.expeditee.gio.gesture.StandardGestureActions;
    4648import org.expeditee.items.Circle;
    4749import org.expeditee.items.Dot;
     
    6062import org.expeditee.items.XRayable;
    6163import org.expeditee.items.widgets.ButtonWidget;
    62 import org.expeditee.items.widgets.InteractiveWidget;
     64import org.expeditee.items.widgets.Widget;
    6365import org.expeditee.items.widgets.InteractiveWidgetInitialisationFailedException;
    6466import org.expeditee.items.widgets.InteractiveWidgetNotAvailableException;
     
    7375public class FrameUtils {
    7476
    75     private static final int COLUMN_WIDTH = 50;
    76 
    77     /**
    78      * Provides a way to monitor the time elapsed between button-down and the
    79      * finished painting.
    80      */
    81     public static TimeKeeper ResponseTimer = new TimeKeeper();
    82 
    83     private static float _ResponseTimeSum = 0;
    84 
    85     private static float _LastResponse = 0;
    86 
    87     private static Text LastEdited = null;
    88 
    89     public static int MINIMUM_INTERITEM_SPACING = -6;
    90 
    91     public static float getResponseTimeTotal() {
    92         return _ResponseTimeSum;
    93     }
    94 
    95     public static float getLastResponseTime() {
    96         return _LastResponse;
    97     }
    98 
    99     /**
    100      * The list of known start pages framesets which will have prepopulated
    101      * links in the home frame.
    102      */
    103     public static final String[] startPages = { "exploratorysearch",
    104             "webbrowser" };
    105 
    106     /**
    107      * Checks if the given top Item is above the given bottom Item, allowing for
    108      * the X coordinates to be off by a certain width...
    109      *
    110      * @param item1
    111      *            The Item to check is above the other Item
    112      * @param item2
    113      *            The Item to check is below the top Item
    114      * @return True if top is above bottom, False otherwise.
    115      */
    116     public static boolean inSameColumn(Item item1, Item item2) {
    117         if (!(item1 instanceof Text) || !(item2 instanceof Text))
    118             return false;
    119 
    120         if (item1.getID() < 0 || item2.getID() < 0)
    121             return false;
    122 
    123         int minX = item2.getX();
    124         int maxX = item2.getX() + item2.getBoundsWidth();
    125 
    126         int startX = item1.getX();
    127         int endX = item1.getX() + item1.getBoundsWidth();
    128 
    129         // Check that the two items left values are close
    130         if (Math.abs(item1.getX() - item2.getX()) > COLUMN_WIDTH)
    131             return false;
    132 
    133         // Ensure the two items
    134         if ((minX >= startX && minX <= endX)
    135                 || (maxX >= startX && maxX <= endX)
    136                 || (startX >= minX && startX <= maxX)
    137                 || (endX >= minX && endX <= maxX))
    138             return true;
    139 
    140         return false;
    141     }
    142 
    143     public static boolean sameBulletType(String bullet1, String bullet2) {
    144         if (bullet1 == null || bullet2 == null)
    145             return false;
    146 
    147         if (bullet1.equals("") || bullet2.equals(""))
    148             return false;
    149 
    150         if (Character.isLetter(bullet1.charAt(0))
    151                 && Character.isLetter(bullet2.charAt(0)))
    152             return true;
    153 
    154         if (Character.isDigit(bullet1.charAt(0))
    155                 && Character.isDigit(bullet2.charAt(0)))
    156             return true;
    157 
    158         // TODO make this more sofisticated
    159 
    160         return false;
    161     }
    162 
    163     private static boolean needsRenumbering(String s) {
    164         if (s == null || s.equals(""))
    165             return false;
    166         if (!Character.isLetterOrDigit(s.charAt(0)))
    167             return false;
    168 
    169         s = s.trim();
    170         // if its all letters then we dont want to auto adjust
    171         if (s.length() > 2) {
    172             for (int i = 0; i < s.length() - 1; i++) {
    173                 if (!Character.isLetter(s.charAt(i)))
    174                     return true;
    175             }
    176         } else
    177             return true;
    178 
    179         return false;
    180     }
    181 
    182     /**
    183      *
    184      * @param toAlign
    185      * @param moveAll
    186      * @param adjust
    187      * @return
    188      */
    189     public static int Align(List<Text> toAlign, boolean moveAll, int adjust,
    190             List<Item> changedItems) {
    191         Collections.sort(toAlign);
    192 
    193         /*
    194          * Single items dont need alignment But if there are two items we may
    195          * still want to format them... ie if they are too close together.
    196          */
    197         if (toAlign.size() < 1)
    198             return 0;
    199 
    200         // get the first item
    201         Text from = toAlign.get(0);
    202         if (from.getParent() == null)
    203             from = toAlign.get(1);
    204         int x = from.getX();
    205 
    206         Frame curr = from.getParent();
    207         Text above = curr.getTextAbove(from);
    208 
    209         String lastBullet = "";
    210 
    211         if (above != null && curr.isNormalTextItem(above))
    212             lastBullet = FrameKeyboardActions.getAutoBullet(above.getText());
    213         else {
    214             lastBullet = FrameKeyboardActions.getBullet(toAlign.get(0)
    215                     .getText());
    216         }
    217         if (needsRenumbering(lastBullet)) {
    218             // renumber...
    219             for (int i = 0; i < toAlign.size(); i++) {
    220 
    221                 Text currentText = toAlign.get(i);
    222                 String currentBullet = FrameKeyboardActions
    223                         .getAutoBullet(currentText.getText());
    224 
    225                 if (sameBulletType(lastBullet, currentBullet)) {
    226                     String oldText = currentText.getText();
    227 
    228                     currentText.stripFirstWord();
    229 
    230                     currentText.setText(lastBullet + currentText.getText());
    231                     lastBullet = FrameKeyboardActions.getAutoBullet(currentText
    232                             .getText());
    233 
    234                     // if we changed the item, add to changedItems list
    235                     if (changedItems != null
    236                             && oldText != currentText.getText()
    237                             && !changedItems.contains(currentText)) {
    238                         Item copy = currentText.copy();
    239                         copy.setID(currentText.getID());
    240                         copy.setText(oldText);
    241                         changedItems.add(copy);
    242                     }
    243                 }
    244             }
    245         }
    246 
    247         // work out the spacing between the first item and the one above it
    248 
    249         int space = 10 + adjust;
    250 
    251         // if we are dropping from the title make the space a little bigger
    252         // than normal
    253 
    254         // If there are only two items get the gap from the start item on the
    255         // zero frame if there is one
    256         if (above == curr.getTitleItem()) {
    257             Frame zero = FrameIO.LoadFrame(curr.getFramesetName() + '0');
    258             String strGap = zero.getAnnotationValue("start");
    259             if (strGap != null) {
     77        /**
     78         * The list of known start pages framesets which will have prepopulated
     79         * links in the home frame.
     80         */
     81        public static final String[] startPages = { "exploratorysearch", "webbrowser" };
     82
     83        private static final int COLUMN_WIDTH = 50;
     84
     85        /**
     86         * Provides a way to monitor the time elapsed between button-down and the
     87         * finished painting.
     88         */
     89        public static TimeKeeper ResponseTimer = new TimeKeeper();
     90
     91        private static float _ResponseTimeSum = 0;
     92
     93        private static float _LastResponse = 0;
     94
     95        private static Text LastEdited = null;
     96
     97        public static int MINIMUM_INTERITEM_SPACING = -6;
     98
     99        private static Item _tdfcItem = null;
     100
     101        public static float getResponseTimeTotal()
     102        {
     103                return _ResponseTimeSum;
     104        }
     105
     106        public static float getLastResponseTime()
     107        {
     108                return _LastResponse;
     109        }
     110
     111        /**
     112         * Checks if the given top Item is above the given bottom Item, allowing for
     113         * the X coordinates to be off by a certain width...
     114         *
     115         * @param item1
     116         *            The Item to check is above the other Item
     117         * @param item2
     118         *            The Item to check is below the top Item
     119         * @return True if top is above bottom, False otherwise.
     120         */
     121        public static boolean inSameColumn(Item item1, Item item2) {
     122                if (!(item1 instanceof Text) || !(item2 instanceof Text))
     123                        return false;
     124
     125                if (item1.getID() < 0 || item2.getID() < 0)
     126                        return false;
     127
     128                int minX = item2.getX();
     129                int maxX = item2.getX() + item2.getBoundsWidth();
     130
     131                int startX = item1.getX();
     132                int endX = item1.getX() + item1.getBoundsWidth();
     133
     134                // Check that the two items left values are close
     135                if (Math.abs(item1.getX() - item2.getX()) > COLUMN_WIDTH)
     136                        return false;
     137
     138                // Ensure the two items
     139                if ((minX >= startX && minX <= endX)
     140                                || (maxX >= startX && maxX <= endX)
     141                                || (startX >= minX && startX <= maxX)
     142                                || (endX >= minX && endX <= maxX))
     143                        return true;
     144
     145                return false;
     146        }
     147
     148        public static boolean sameBulletType(String bullet1, String bullet2)
     149        {
     150                if (bullet1 == null || bullet2 == null)
     151                        return false;
     152
     153                if (bullet1.equals("") || bullet2.equals(""))
     154                        return false;
     155
     156                if (Character.isLetter(bullet1.charAt(0))
     157                                && Character.isLetter(bullet2.charAt(0)))
     158                        return true;
     159
     160                if (Character.isDigit(bullet1.charAt(0))
     161                                && Character.isDigit(bullet2.charAt(0)))
     162                        return true;
     163
     164                // TODO make this more sofisticated
     165
     166                return false;
     167        }
     168
     169        private static boolean needsRenumbering(String s) {
     170                if (s == null || s.equals(""))
     171                        return false;
     172                if (!Character.isLetterOrDigit(s.charAt(0)))
     173                        return false;
     174
     175                s = s.trim();
     176                // if its all letters then we dont want to auto adjust
     177                if (s.length() > 2) {
     178                        for (int i = 0; i < s.length() - 1; i++) {
     179                                if (!Character.isLetter(s.charAt(i)))
     180                                        return true;
     181                        }
     182                } else
     183                        return true;
     184
     185                return false;
     186        }
     187
     188        /**
     189         *
     190         * @param toAlign
     191         * @param moveAll
     192         * @param adjust
     193         * @return
     194         */
     195        public static int Align(List<Text> toAlign, boolean moveAll, int adjust,
     196                        List<Item> changedItems) {
     197                Collections.sort(toAlign);
     198
     199                /*
     200                 * Single items dont need alignment But if there are two items we may
     201                 * still want to format them... ie if they are too close together.
     202                 */
     203                if (toAlign.size() < 1)
     204                        return 0;
     205
     206                // get the first item
     207                Text from = toAlign.get(0);
     208                if (from.getParent() == null)
     209                        from = toAlign.get(1);
     210                int x = from.getX();
     211
     212                Frame curr = from.getParent();
     213                Text above = curr.getTextAbove(from);
     214
     215                String lastBullet = "";
     216
     217                if (above != null && curr.isNormalTextItem(above))
     218                        lastBullet = StandardGestureActions.getAutoBullet(above.getText());
     219                else {
     220                        lastBullet = StandardGestureActions.getBullet(toAlign.get(0)
     221                                        .getText());
     222                }
     223                if (needsRenumbering(lastBullet)) {
     224                        // renumber...
     225                        for (int i = 0; i < toAlign.size(); i++) {
     226
     227                                Text currentText = toAlign.get(i);
     228                                String currentBullet = StandardGestureActions.getAutoBullet(currentText.getText());
     229
     230                                if (sameBulletType(lastBullet, currentBullet)) {
     231                                        String oldText = currentText.getText();
     232
     233                                        currentText.stripFirstWord();
     234
     235                                        currentText.setText(lastBullet + currentText.getText());
     236                                        lastBullet = StandardGestureActions.getAutoBullet(currentText.getText());
     237
     238                                        // if we changed the item, add to changedItems list
     239                                        if (changedItems != null
     240                                                        && oldText != currentText.getText()
     241                                                        && !changedItems.contains(currentText)) {
     242                                                Item copy = currentText.copy();
     243                                                copy.setID(currentText.getID());
     244                                                copy.setText(oldText);
     245                                                changedItems.add(copy);
     246                                        }
     247                                }
     248                        }
     249                }
     250
     251                // work out the spacing between the first item and the one above it
     252
     253                int space = 10 + adjust;
     254
     255                // if we are dropping from the title make the space a little bigger
     256                // than normal
     257
     258                // If there are only two items get the gap from the start item on the
     259                // zero frame if there is one
     260                if (above == curr.getTitleItem()) {
     261                        Frame zero = FrameIO.LoadFrame(curr.getFramesetName() + '0');
     262                        String strGap = zero.getAnnotationValue("start");
     263                        if (strGap != null) {
     264                                try {
     265                                        int gap = Integer.parseInt(strGap);
     266                                        space = gap;
     267                                } catch (NumberFormatException nfe) {
     268
     269                                }
     270                        }
     271                } else if (above != null) {
     272                        // Make the gap between all items the same as the gap between
     273                        // the first two
     274                        space = (int) (from.getBounds().getMinY() - above.getBounds().getMaxY());
     275
     276                        if (space < MINIMUM_INTERITEM_SPACING)
     277                                space = MINIMUM_INTERITEM_SPACING;
     278
     279                        if (UserSettings.FormatSpacingMax.get() != null) {
     280                                double maxSpace = UserSettings.FormatSpacingMax.get()
     281                                                * above.getSize();
     282                                if (maxSpace < space) {
     283                                        space = (int) Math.round(maxSpace);
     284                                }
     285                        }
     286
     287                        if (UserSettings.FormatSpacingMin.get() != null) {
     288                                double minSpace = UserSettings.FormatSpacingMin.get()
     289                                                * above.getSize();
     290                                if (minSpace > space) {
     291                                        space = (int) Math.round(minSpace);
     292                                }
     293                        }
     294
     295                        // Need to do things differently for FORMAT than for DROPPING
     296                        if (moveAll && above != curr.getNameItem()
     297                                        && above != curr.getTitleItem()) {
     298                                x = above.getX();
     299                                int y = (int) above.getBounds().getMaxY()
     300                                                + space
     301                                                + ((int) (from.getY() - from.getBounds().getMinY()));
     302
     303                                if (changedItems != null
     304                                                && (from.getX() != x || from.getY() != y)
     305                                                && !changedItems.contains(from)) {
     306                                        Item copy = from.copy();
     307                                        copy.setID(from.getID());
     308                                        changedItems.add(copy);
     309                                }
     310                                from.setPosition(x, y);
     311                        } else {
     312                                x = from.getX();
     313                        }
     314
     315                        space += adjust;
     316                }
     317                for (int i = 1; i < toAlign.size(); i++) {
     318                        Item current = toAlign.get(i);
     319                        Item top = toAlign.get(i - 1);
     320
     321                        // The bottom of the previous item
     322                        int bottom = (int) top.getBounds().getMaxY();
     323
     324                        // the difference between the current item's Y coordinate and
     325                        // the top of the highlight box
     326                        int diff = (int) (current.getY() - current.getBounds().getMinY());
     327
     328                        int newPos = bottom + space + diff;
     329
     330                        if (changedItems != null
     331                                        && ((moveAll && current.getX() != x) || current.getY() != newPos)
     332                                        && !changedItems.contains(current)) {
     333                                Item copy = current.copy();
     334                                copy.setID(current.getID());
     335                                changedItems.add(copy);
     336                        }
     337
     338                        if (moveAll) {
     339                                current.setPosition(x, newPos);
     340                        } else if (newPos > current.getY()) {
     341                                current.setY(newPos);
     342                        }
     343
     344                }
     345
     346                // if (insert != null)
     347                // return insert.getY();
     348
     349                // Michael thinks we return the y value for the next new item??
     350                int y = from.getY() + from.getBoundsHeight() + space;
     351                return y;
     352        }
     353
     354        public static int Align(List<Text> toAlign, boolean moveAll, int adjust) {
     355                return Align(toAlign, moveAll, adjust, null);
     356        }
     357
     358        public static boolean LeavingFrame(Frame current) {
     359                checkTDFCItemWaiting(current);
     360                // active overlay frames may also require saving if they have been
     361                // changed
     362                for (Overlay o : current.getOverlays())
     363                        if (!SaveCheck(o.Frame))
     364                                return false;
     365
     366                // if the check fails there is no point continuing
     367                if (!SaveCheck(current))
     368                        return false;
     369
     370                for (Item i : current.getItems()) {
     371                        i.setHighlightMode(Item.HighlightMode.None);
     372                        i.setHighlightColorToDefault();
     373                }
     374                return true;
     375        }
     376
     377        private static boolean SaveCheck(Frame toSave) {
     378                // don't bother saving frames that haven't changed
     379                if (!toSave.hasChanged())
     380                        return true;
     381
     382                // if the frame has been changed, then save it
     383                if (DisplayController.isTwinFramesOn()) {
     384                        Frame opposite = DisplayController.getOppositeFrame();
     385
     386                        String side = "left";
     387                        if (DisplayController.getCurrentSide() == DisplayController.TwinFramesSide.RIGHT)
     388                                side = "right";
     389
     390                        // if the two frames both have changes, prompt the user for the
     391                        // next move
     392                        if (opposite.hasChanged() && opposite.equals(toSave)) {
     393                                if (EcosystemManager.getGraphicsManager().showDialog("Changes", "Leaving this frame will discard changes made in the " + side + " Frame. Continue?")) {
     394                                        FrameIO.SaveFrame(toSave);
     395                                        DisplayController.Reload(DisplayController.getSideFrameIsOn(opposite));
     396                                        return true;
     397                                } else
     398                                        return false;
     399                        } else if (opposite.hasOverlay(toSave)) {
     400                                if (toSave.hasChanged())
     401                                        if (EcosystemManager.getGraphicsManager().showDialog("Changes", "Leaving this frame will discard changes made in the " + side + " Frame. Continue?")) {
     402                                                FrameIO.SaveFrame(toSave);
     403                                                DisplayController.Reload(DisplayController.getSideFrameIsOn(opposite));
     404                                                return true;
     405                                        } else
     406                                                return false;
     407                        }
     408
     409                        // save the current frame and restore the other side
     410                        FrameIO.SaveFrame(toSave);
     411                        return true;
     412                }
     413
     414                // single-frame mode can just save and return
     415                FrameIO.SaveFrame(toSave);
     416                return true;
     417        }
     418
     419        // TODO: consider reloating this method to Frame class?   
     420        protected static Item getAnnotation(Frame frame, String annotationStr)
     421        {
     422                Item matched_item = null;
     423
     424                // check for an updated template...
     425                for (Item i : frame.getAnnotationItems()) {                             
     426
     427                        if (ItemUtils.startsWithTag(i, annotationStr)) {
     428
     429                                matched_item = i;
     430                                break;
     431                        }
     432                }
     433
     434                return matched_item;
     435        }
     436
     437        protected static void doFrameTransition(Item frameTransition, Frame from, Frame to)
     438        {
     439                String s = frameTransition.getText();           
     440                String[] s_array = s.split(":");
     441                if(s_array.length > 1){
     442                        String slide_mode_method = s_array[1].trim();
     443                       
     444                        FrameTransition transition = new FrameTransition(from.getBuffer(), slide_mode_method);
     445                       
     446                        DisplayController.setTransition(from, transition);
     447                       
     448                        System.out.println("Triggered on annotation: " + s);
     449                } else {
     450                        System.err.println("Warning: failed to detect frameTransition type");
     451                        // TODO: print list as a result of reflection listing     
     452                }
     453        }                               
     454
     455        /**
     456         * Displays the given Frame on the display. If the current frame has changed
     457         * since the last save then it will be saved before the switch is made. The
     458         * caller can also dictate whether the current frame is added to the
     459         * back-stack or not.
     460         *
     461         * @param toDisplay
     462         *            The Frame to display on the screen
     463         * @param addToBack
     464         *            True if the current Frame should be added to the back-stack,
     465         *            False otherwise
     466         */
     467        public static void DisplayFrame(Frame toDisplay, boolean addToBack, boolean incrementStats)
     468        {
     469                if (toDisplay == null)
     470                        return;
     471
     472                Frame current = DisplayController.getCurrentFrame();
     473
     474                // Dont need to do anything if the frame to display is already being
     475                // displayed
     476                if (current.equals(toDisplay))
     477                        return;
     478
     479                // move any anchored connected items
     480                if (FreeItems.hasItemsAttachedToCursor()) {
     481                        List<Item> toAdd = new ArrayList<Item>();
     482                        List<Item> toCheck = new ArrayList<Item>(FreeItems.getInstance());
     483
     484                        while (toCheck.size() > 0) {
     485                                Item i = toCheck.get(0);
     486                                Collection<Item> connected = i.getAllConnected();
     487
     488                                // // Only move completely enclosed items
     489                                // if (!toCheck.containsAll(connected)) {
     490                                // connected.retainAll(FreeItems.getInstance());
     491                                // FreeItems.getInstance().removeAll(connected);
     492                                // toCheck.removeAll(connected);
     493                                // FrameMouseActions.anchor(connected);
     494                                // } else {
     495                                // toCheck.removeAll(connected);
     496                                // }
     497
     498                                // Anchor overlay items where they belong
     499                                if (i.getParent() != null && i.getParent() != current) {
     500                                        FreeItems.getInstance().removeAll(connected);
     501                                        toCheck.removeAll(connected);
     502                                        StandardGestureActions.anchor(connected);
     503                                } else {
     504                                        // Add stuff that is partially enclosed
     505                                        // remove all the connected items from our list to check
     506                                        toCheck.removeAll(connected);
     507                                        // Dont add the items that are free
     508                                        connected.removeAll(FreeItems.getInstance());
     509                                        toAdd.addAll(connected);
     510                                }
     511                        }
     512
     513                        current.removeAllItems(toAdd);
     514
     515                        boolean oldChange = toDisplay.hasChanged();
     516                        toDisplay.updateIDs(toAdd);
     517                        toDisplay.addAllItems(toAdd);
     518                        toDisplay.setChanged(oldChange);
     519                }
     520
     521                if (addToBack && current != toDisplay) {
     522                        FrameIO.checkTDFC(current);
     523                }
     524
     525                // if the saving happened properly, we can continue
     526                if (!LeavingFrame(current)) {
     527                        MessageBay.displayMessage("Navigation cancelled");
     528                        return;
     529                }
     530
     531                if (addToBack && current != toDisplay) {
     532                        DisplayController.addToBack(current);
     533                }
     534
     535                Parse(toDisplay);
     536
     537                if (DisplayController.isAudienceMode()) {
     538                        // Only need to worry about frame transitions when in Audience Mode
     539
     540                        // Test to see if frame transition specified through annotation, and perform it if one if found
     541                        Item frameTransition = getAnnotation(toDisplay, "@frameTransition");
     542                        if (frameTransition != null) {
     543                                doFrameTransition(frameTransition,current,toDisplay);
     544                        }
     545                }
     546
     547                DisplayController.setCurrentFrame(toDisplay, incrementStats);
     548                StandardGestureActions.updateCursor();
     549                // FrameMouseActions.getInstance().refreshHighlights();
     550                // update response timer
     551                _LastResponse = ResponseTimer.getElapsedSeconds();
     552                _ResponseTimeSum += _LastResponse;
     553                DisplayController.updateTitle();
     554        }
     555
     556        /**
     557         * Loads and displays the Frame with the given framename, and adds the
     558         * current frame to the back-stack if required.
     559         *
     560         * @param framename
     561         *            The name of the Frame to load and display
     562         * @param addToBack
     563         *            True if the current Frame should be added to the back-stack,
     564         *            false otherwise
     565         */
     566        public static void DisplayFrame(String frameName, boolean addToBack,
     567                        boolean incrementStats) {
     568                Frame newFrame = getFrame(frameName);
     569
     570                if (newFrame != null)
     571                        // display the frame
     572                        DisplayFrame(newFrame, addToBack, incrementStats);
     573        }
     574
     575        /**
     576         * Loads and displays the Frame with the given framename and adds the
     577         * current frame to the back-stack. This is the same as calling
     578         * DisplayFrame(framename, true)
     579         *
     580         * @param framename
     581         *            The name of the Frame to load and display
     582         */
     583        public static void DisplayFrame(String framename) {
     584                DisplayFrame(framename, true, true);
     585        }
     586
     587        public static Frame getFrame(String frameName) {
     588                // if the new frame does not exist then tell the user
     589                Frame f = FrameIO.LoadFrame(frameName);
     590
     591                if (f == null) {
     592                        MessageBay.errorMessage("Frame '" + frameName + "' could not be found.");
     593                }
     594
     595                return f;
     596        }
     597
     598        /**
     599         * Creates a new Picture Item from the given Text source Item and adds it to
     600         * the given Frame.
     601         *
     602         * @return True if the image was created successfully, false otherwise
     603         */
     604        private static boolean createPicture(Frame frame, Text txt) {
     605                // attempt to create the picture
     606                Picture pic = ItemUtils.CreatePicture(txt);
     607
     608                // if the picture could not be created successfully
     609                if (pic == null) {
     610                        String imagePath = txt.getText();
     611                        assert (imagePath != null);
     612                        imagePath = new AttributeValuePair(imagePath).getValue().trim();
     613                        if (imagePath.length() == 0) {
     614                                return false;
     615                                // MessageBay.errorMessage("Expected image path after @i:");
     616                        } else {
     617                                MessageBay.errorMessage("Image " + imagePath
     618                                                + " could not be loaded");
     619                        }
     620                        return false;
     621                }
     622                frame.addItem(pic);
     623
     624                return true;
     625        }
     626
     627        /**
     628         * Creates an interactive widget and adds it to a frame. If txt has no
     629         * parent the parent will be set to frame.
     630         *
     631         * @param frame
     632         *            Frame to add widget to. Must not be null.
     633         *
     634         * @param txt
     635         *            Text to create the widget from. Must not be null.
     636         *
     637         * @return True if created/added. False if could not create.
     638         *
     639         * @author Brook Novak
     640         */
     641        private static boolean createWidget(Frame frame, Text txt) {
     642
     643                if (frame == null)
     644                        throw new NullPointerException("frame");
     645                if (txt == null)
     646                        throw new NullPointerException("txt");
     647
     648                // Safety
     649                if (txt.getParent() == null)
     650                        txt.setParent(frame);
     651
     652                Widget iw = null;
     653
    260654                try {
    261                     int gap = Integer.parseInt(strGap);
    262                     space = gap;
    263                 } catch (NumberFormatException nfe) {
    264 
    265                 }
    266             }
    267         } else if (above != null) {
    268             // Make the gap between all items the same as the gap between
    269             // the first two
    270             space = (int) (from.getPolygon().getBounds().getMinY() - above
    271                     .getPolygon().getBounds().getMaxY());
    272 
    273             if (space < MINIMUM_INTERITEM_SPACING)
    274                 space = MINIMUM_INTERITEM_SPACING;
    275 
    276             if (UserSettings.FormatSpacingMax.get() != null) {
    277                 double maxSpace = UserSettings.FormatSpacingMax.get()
    278                         * above.getSize();
    279                 if (maxSpace < space) {
    280                     space = (int) Math.round(maxSpace);
    281                 }
    282             }
    283 
    284             if (UserSettings.FormatSpacingMin.get() != null) {
    285                 double minSpace = UserSettings.FormatSpacingMin.get()
    286                         * above.getSize();
    287                 if (minSpace > space) {
    288                     space = (int) Math.round(minSpace);
    289                 }
    290             }
    291 
    292             // Need to do things differently for FORMAT than for DROPPING
    293             if (moveAll && above != curr.getNameItem()
    294                     && above != curr.getTitleItem()) {
    295                 x = above.getX();
    296                 int y = (int) above.getPolygon().getBounds().getMaxY()
    297                         + space
    298                         + ((int) (from.getY() - from.getPolygon().getBounds()
    299                                 .getMinY()));
    300 
    301                 if (changedItems != null
    302                         && (from.getX() != x || from.getY() != y)
    303                         && !changedItems.contains(from)) {
    304                     Item copy = from.copy();
    305                     copy.setID(from.getID());
    306                     changedItems.add(copy);
    307                 }
    308                 from.setPosition(x, y);
    309             } else {
    310                 x = from.getX();
    311             }
    312 
    313             space += adjust;
    314         }
    315         for (int i = 1; i < toAlign.size(); i++) {
    316             Item current = toAlign.get(i);
    317             Item top = toAlign.get(i - 1);
    318 
    319             // The bottom of the previous item
    320             int bottom = (int) top.getPolygon().getBounds().getMaxY();
    321 
    322             // the difference between the current item's Y coordinate and
    323             // the top of the highlight box
    324             int diff = (int) (current.getY() - current.getPolygon().getBounds()
    325                     .getMinY());
    326 
    327             int newPos = bottom + space + diff;
    328 
    329             if (changedItems != null
    330                     && ((moveAll && current.getX() != x) || current.getY() != newPos)
    331                     && !changedItems.contains(current)) {
    332                 Item copy = current.copy();
    333                 copy.setID(current.getID());
    334                 changedItems.add(copy);
    335             }
    336 
    337             if (moveAll) {
    338                 current.setPosition(x, newPos);
    339             } else if (newPos > current.getY()) {
    340                 current.setY(newPos);
    341             }
    342 
    343         }
    344 
    345         // if (insert != null)
    346         // return insert.getY();
    347 
    348         // Michael thinks we return the y value for the next new item??
    349         int y = from.getY() + from.getBoundsHeight() + space;
    350         return y;
    351     }
    352 
    353     public static int Align(List<Text> toAlign, boolean moveAll, int adjust) {
    354         return Align(toAlign, moveAll, adjust, null);
    355     }
    356 
    357     public static boolean LeavingFrame(Frame current) {
    358         checkTDFCItemWaiting(current);
    359         // active overlay frames may also require saving if they have been
    360         // changed
    361         for (Overlay o : current.getOverlays())
    362             if (!SaveCheck(o.Frame))
    363                 return false;
    364 
    365         // if the check fails there is no point continuing
    366         if (!SaveCheck(current))
    367             return false;
    368 
    369         for (Item i : current.getItems())
    370             i.setHighlightMode(Item.HighlightMode.None);
    371         return true;
    372     }
    373 
    374     private static boolean SaveCheck(Frame toSave) {
    375         // don't bother saving frames that haven't changed
    376         if (!toSave.hasChanged())
    377             return true;
    378 
    379         // if the frame has been changed, then save it
    380         if (DisplayIO.isTwinFramesOn()) {
    381             Frame opposite = DisplayIO.getOppositeFrame();
    382 
    383             String side = "left";
    384             if (DisplayIO.getCurrentSide() == 0)
    385                 side = "right";
    386 
    387             // if the two frames both have changes, prompt the user for the
    388             // next move
    389             if (opposite.hasChanged() && opposite.equals(toSave)) {
    390                 if (DisplayIO.DisplayConfirmDialog(
    391                         "Leaving this frame will discard changes made in the "
    392                                 + side + " Frame. Continue?", "Changes",
    393                         DisplayIO.TYPE_WARNING, DisplayIO.OPTIONS_OK_CANCEL,
    394                         DisplayIO.RESULT_OK)) {
    395                     FrameIO.SaveFrame(toSave);
    396                     DisplayIO.Reload(DisplayIO.FrameOnSide(opposite));
    397                     return true;
    398                 } else
    399                     return false;
    400             } else if (opposite.hasOverlay(toSave)) {
    401                 if (toSave.hasChanged())
    402                     if (DisplayIO.DisplayConfirmDialog(
    403                             "Leaving this frame will discard changes made in the "
    404                                     + side + " Frame. Continue?", "Changes",
    405                             DisplayIO.TYPE_WARNING,
    406                             DisplayIO.OPTIONS_OK_CANCEL, DisplayIO.RESULT_OK)) {
    407                         FrameIO.SaveFrame(toSave);
    408                         DisplayIO.Reload(DisplayIO.FrameOnSide(opposite));
    409                         return true;
    410                     } else
     655
     656                        iw = Widget.createWidget(txt);
     657
     658                } catch (InteractiveWidgetNotAvailableException e) {
     659                        e.printStackTrace();
     660                        MessageBay.errorMessage("Cannot create iWidget: " + e.getMessage());
     661                } catch (InteractiveWidgetInitialisationFailedException e) {
     662                        e.printStackTrace();
     663                        MessageBay.errorMessage("Cannot create iWidget: " + e.getMessage());
     664                } catch (IllegalArgumentException e) {
     665                        e.printStackTrace();
     666                        MessageBay.errorMessage("Cannot create iWidget: " + e.getMessage());
     667                }
     668
     669                if (iw == null)
    411670                        return false;
    412             }
    413 
    414             // save the current frame and restore the other side
    415             FrameIO.SaveFrame(toSave);
    416             return true;
    417         }
    418 
    419         // single-frame mode can just save and return
    420         FrameIO.SaveFrame(toSave);
    421         return true;
    422     }
    423 
    424     // TODO: consider reloating this method to Frame class?   
    425     protected static Item getAnnotation(Frame frame, String annotationStr)
    426     {
    427         Item matched_item = null;
     671
     672                frame.removeItem(txt);
     673
     674                frame.addAllItems(iw.getItems());
     675
     676                return true;
     677        }
     678
     679        public static List<String> ParseProfile(Frame profile)
     680        {
     681                List<String> errors = new LinkedList<String>();
     682               
     683                if (profile == null) return errors;
     684
     685                /*
     686                 * Make sure the correct cursor shows when turning off the custom cursor
     687                 * and reparsing the profile frame
     688                 */
     689                FreeItems.getCursor().clear();
     690                DisplayController.setCursor(Item.HIDDEN_CURSOR);
     691                DisplayController.setCursor(Item.DEFAULT_CURSOR);
     692
     693                // check for settings tags
     694                for (Text item : profile.getBodyTextItems(true)) {
     695                        try {
     696
     697                                AttributeValuePair avp = new AttributeValuePair(item.getText());
     698                                String attributeFullCase = avp.getAttributeOrValue();
     699
     700                                if (attributeFullCase == null) continue;
     701                               
     702                                String attribute = attributeFullCase.trim().toLowerCase().replaceAll("^@", "");
     703
     704                                if (attribute.equals("settings")) Settings.parseSettings(item);
     705
     706                        } catch (Exception e) {
     707                                if (e.getMessage() != null) {
     708                                        errors.add(e.getMessage());
     709                                } else {
     710                                        e.printStackTrace();
     711                                        errors.add("Error parsing [" + item.getText() + "] on " + profile.getName());
     712                                }
     713                        }
     714                }
     715
     716                return errors;
     717        }
     718
     719        /**
     720         * Sets the first frame to be displayed.
     721         *
     722         * @param profile
     723         */
     724        public static void loadFirstFrame(Frame profile)
     725        {
     726                if (UserSettings.HomeFrame.get() == null) UserSettings.HomeFrame.set(profile.getName());
     727
     728                Frame firstFrame = FrameIO.LoadFrame(UserSettings.HomeFrame.get());
     729                if (firstFrame == null) {
     730                        MessageBay.warningMessage("Home frame not found: " + UserSettings.HomeFrame);
     731                        UserSettings.HomeFrame.set(profile.getName());
     732                        DisplayController.setCurrentFrame(profile, true);
     733                } else {
     734                        DisplayController.setCurrentFrame(firstFrame, true);
     735                }
     736
     737        }
     738
     739        public static Colour[] getColorWheel(Frame frame)
     740        {
     741                if (frame != null) {
     742                        List<Text> textItems = frame.getBodyTextItems(false);
     743                        Colour[] colorList = new Colour[textItems.size() + 1];
     744                        for (int i = 0; i < textItems.size(); i++) {
     745                                colorList[i] = textItems.get(i).getColor();
     746                        }
     747                        // Make the last item transparency or default for forecolor
     748                        colorList[colorList.length - 1] = null;
     749
     750                        return colorList;
     751                }
     752                return new Colour[] { Colour.BLACK, Colour.WHITE, null };
     753        }
     754
     755        public static String getLink(Item item, String alt)
     756        {
     757                if (item == null || !(item instanceof Text)) return alt;
     758
     759                AttributeValuePair avp = new AttributeValuePair(item.getText());
     760                assert (avp != null);
     761
     762                if (avp.hasPair() && avp.getValue().trim().length() != 0) {
     763                        item.setLink(avp.getValue());
     764                        return avp.getValue();
     765                } else if (item.getLink() != null) {
     766                        return item.getAbsoluteLink();
     767                }
     768
     769                return alt;
     770        }
     771
     772        public static String getDir(String name)
     773        {
     774                if (name != null) {
     775                        File tester = new File(name);
     776                        if (tester.exists() && tester.isDirectory()) {
     777                                if (name.endsWith(File.separator)) {
     778                                        return name;
     779                                } else {
     780                                        return name + File.separator;
     781                                }
     782                        } else {
     783                                throw new RuntimeException("Directory not found: " + name);
     784                        }
     785                }
     786                throw new RuntimeException("Missing value for profile attribute" + name);
     787        }
     788
     789        public static ArrayList<String> getDirs(Item item)
     790        {
     791                ArrayList<String> dirsToAdd = new ArrayList<String>();
     792                String dirListFrameName = item.getAbsoluteLink();
     793                if (dirListFrameName != null) {
     794                        Frame dirListFrame = FrameIO.LoadFrame(dirListFrameName);
     795                        if (dirListFrame != null) {
     796                                for (Text t : dirListFrame.getBodyTextItems(false)) {
     797                                        String dirName = t.getText().trim();
     798                                        File tester = new File(dirName);
     799                                        if (tester.exists() && tester.isDirectory()) {
     800                                                if (dirName.endsWith(File.separator))
     801                                                        dirsToAdd.add(dirName);
     802                                                else
     803                                                        dirsToAdd.add(dirName + File.separator);
     804                                        }
     805                                }
     806                        }
     807                }
     808
     809                return dirsToAdd;
     810        }
     811
     812        public static void Parse(Frame toParse)
     813        {
     814                Parse(toParse, false);
     815        }
     816
     817        /**
     818         * Checks for any special Annotation items and updates the display as
     819         * necessary. Special Items: Images, overlays, sort.
     820         *
     821         */
     822        public static void Parse(Frame toParse, boolean firstParse)
     823        {
     824                Parse(toParse, firstParse, false);
     825        }
     826
     827        /**
     828         *
     829         * @param toParse
     830         * @param firstParse
     831         * @param ignoreAnnotations
     832         *            used to prevent infinate loops such as when performing TDFC
     833         *            with an ao tag linked to a frame with an frameImage of a frame
     834         *            which also has an ao tag on it.
     835         */
     836        public static void Parse(Frame toParse, boolean firstParse, boolean ignoreAnnotations)
     837        {
     838                // TODO check why we are getting toParse == null... when profile frame
     839                // is being created and change the lines below
     840                if (toParse == null) return;
     841
     842                if (firstParse) ItemUtils.EnclosedCheck(toParse.getItems());
     843               
     844                List<Item> items = toParse.getItems();
     845
     846                // if XRayMode is on, replace pictures with their underlying text
     847                if (DisplayController.isXRayMode()) {
     848
     849                        // BROOK: Must handle these a little different
     850                        List<Widget> widgets = toParse.getInteractiveWidgets();
     851
     852                        for (Item i : items) {
     853                                if (i instanceof XRayable) {
     854                                        toParse.removeItem(i);
     855                                        // Show the items
     856                                        for (Item item : ((XRayable) i).getConnected()) {
     857                                                item.setVisible(true);
     858                                                item.removeEnclosure(i);
     859                                        }
     860                                } else if (i instanceof WidgetCorner) {
     861                                        toParse.removeItem(i);
     862                                } else if (i instanceof WidgetEdge) {
     863                                        toParse.removeItem(i);
     864                                } else if (i.hasFormula()) {
     865                                        i.setText(i.getFormula());
     866                                } else if (i.hasOverlay()) {
     867                                        i.setVisible(true);
     868                                        // int x = i.getBoundsHeight();
     869                                }
     870                        }
     871
     872                        for (Widget iw : widgets) {
     873                                toParse.addItem(iw.getSource());
     874                        }
     875                }
     876
     877                // Text title = null;
     878                // Text template = UserSettingsTemplate.copy();
     879
     880                List<Overlay> overlays = new ArrayList<Overlay>();
     881                List<Vector> vectors = new ArrayList<Vector>();
     882
     883                // disable reading of cached overlays if in twinframes mode
     884                if (DisplayController.isTwinFramesOn()) FrameIO.SuspendCache();
     885
     886                DotType pointtype = DotType.square;
     887                boolean filledPoints = true;
     888
     889                UserAppliedPermission permission = toParse.getUserAppliedPermission();
     890                toParse.clearAnnotations();
     891
     892                // check for any new overlay items
     893                for (Item i : toParse.getItems()) {
     894                        try {
     895                                // reset overlay permission
     896                                i.setOverlayPermission(null);
     897                                // i.setPermission(permission);
     898                                if (i instanceof WidgetCorner) {
     899                                        // TODO improve efficiency so it only updates once... using
     900                                        // observer design pattern
     901                                        i.update();
     902                                } else if (i instanceof Text) {
     903                                        if (i.isAnnotation()) {
     904                                                if (ItemUtils.startsWithTag(i, ItemUtils.TAG_POINTTYPE)) {
     905                                                        Text txt = (Text) i;
     906                                                        String line = txt.getFirstLine();
     907                                                        line = ItemUtils.StripTag(line,
     908                                                                        ItemUtils.GetTag(ItemUtils.TAG_POINTTYPE));
     909
     910                                                        if (line != null) {
     911                                                                line = line.toLowerCase();
     912                                                                if (line.indexOf(" ") > 0) {
     913                                                                        String fill = line.substring(line
     914                                                                                        .indexOf(" ") + 1);
     915                                                                        if (fill.startsWith("nofill"))
     916                                                                                filledPoints = false;
     917                                                                        else
     918                                                                                filledPoints = true;
     919                                                                }
     920
     921                                                                if (line.startsWith("circle"))
     922                                                                        pointtype = DotType.circle;
     923                                                                else
     924                                                                        pointtype = DotType.square;
     925                                                        }
     926                                                }// check for new VECTOR items
     927                                                else if (!DisplayController.isXRayMode()
     928                                                                && ItemUtils.startsWithTag(i,
     929                                                                                ItemUtils.TAG_VECTOR)
     930                                                                && i.getLink() != null) {
     931                                                        if (!i.getAbsoluteLink().equals(toParse.getName()))
     932                                                                addVector(vectors, UserAppliedPermission.none,
     933                                                                                permission, i);
     934                                                } else if (!DisplayController.isXRayMode()
     935                                                                && ItemUtils.startsWithTag(i,
     936                                                                                ItemUtils.TAG_ACTIVE_VECTOR)
     937                                                                && i.getLink() != null) {
     938                                                        if (!i.getAbsoluteLink().equals(toParse.getName()))
     939                                                                addVector(vectors,
     940                                                                                UserAppliedPermission.followLinks,
     941                                                                                permission, i);
     942                                                }
     943                                                // check for new OVERLAY items
     944                                                else if (!ignoreAnnotations && ItemUtils.startsWithTag(i, ItemUtils.TAG_OVERLAY) && i.getLink() != null) {
     945                                                        if (i.getAbsoluteLink().equalsIgnoreCase(toParse.getName())) {
     946                                                                // This frame contains an active overlay which
     947                                                                // points to itself
     948                                                                MessageBay.errorMessage(toParse.getName() + " contains an @o which links to itself");
     949                                                                continue;
     950                                                        }
     951
     952                                                        Frame overlayFrame = FrameIO.LoadFrame(i.getAbsoluteLink());
     953                                                        // Parse(overlay);
     954                                                        if (overlayFrame != null && Overlay.getOverlay(overlays, overlayFrame) == null) {
     955                                                                overlays.add(new Overlay(overlayFrame, UserAppliedPermission.none));
     956                                                        }
     957                                                }
     958                                                // check for ACTIVE_OVERLAY items
     959                                                else if (!ignoreAnnotations
     960                                                                && ItemUtils.startsWithTag(i,
     961                                                                                ItemUtils.TAG_ACTIVE_OVERLAY)
     962                                                                && i.getLink() != null) {
     963                                                        String link = i.getAbsoluteLink();
     964                                                        if (link.equalsIgnoreCase(toParse.getName())) {
     965                                                                // This frame contains an active overlay which
     966                                                                // points to itself
     967                                                                MessageBay
     968                                                                .errorMessage(toParse.getName()
     969                                                                                + " contains an @ao which links to itself");
     970                                                                continue;
     971                                                        }
     972                                                        Frame overlayFrame = null;
     973
     974                                                        Frame current = DisplayController.getCurrentFrame();
     975                                                        if (current != null) {
     976                                                                for (Overlay o : current.getOverlays()) {
     977                                                                        if (o.Frame.getName()
     978                                                                                        .equalsIgnoreCase(link))
     979                                                                                overlayFrame = o.Frame;
     980                                                                }
     981                                                        }
     982                                                        if (overlayFrame == null)
     983                                                                overlayFrame = FrameIO.LoadFrame(link);
     984
     985                                                        // get level if specified
     986                                                        String level = new AttributeValuePair(i.getText())
     987                                                                        .getValue();
     988                                                        // default permission (if none is specified)
     989                                                        PermissionPair permissionLevel = new PermissionPair(
     990                                                                        level, UserAppliedPermission.followLinks);
     991
     992                                                        if (overlayFrame != null) {
     993                                                                Overlay existingOverlay = Overlay.getOverlay(
     994                                                                                overlays, overlayFrame);
     995                                                                // If it wasn't in the list create it and add
     996                                                                // it.
     997                                                                if (existingOverlay == null) {
     998                                                                        Overlay newOverlay = new Overlay(
     999                                                                                        overlayFrame,
     1000                                                                                        permissionLevel
     1001                                                                                        .getPermission(overlayFrame
     1002                                                                                                        .getOwner()));
     1003                                                                        i.setOverlay(newOverlay);
     1004                                                                        overlays.add(newOverlay);
     1005                                                                } else {
     1006                                                                        existingOverlay.Frame
     1007                                                                        .setPermission(permissionLevel);
     1008                                                                }
     1009                                                        }
     1010                                                }
     1011                                                // check for Images and widgets
     1012                                                else {
     1013                                                        if (!DisplayController.isXRayMode()) {
     1014                                                                if (ItemUtils.startsWithTag(i,
     1015                                                                                ItemUtils.TAG_IMAGE, true)) {
     1016                                                                        if (!i.hasEnclosures()) {
     1017                                                                                createPicture(toParse, (Text) i);
     1018                                                                        }
     1019                                                                        // check for frame images
     1020                                                                } else if (ItemUtils.startsWithTag(i,
     1021                                                                                ItemUtils.TAG_FRAME_IMAGE)
     1022                                                                                && i.getLink() != null
     1023                                                                                && !i.getAbsoluteLink()
     1024                                                                                .equalsIgnoreCase(
     1025                                                                                                toParse.getName())) {
     1026                                                                        XRayable image = null;
     1027                                                                        if (i.hasEnclosures()) {
     1028                                                                                // i.setHidden(true);
     1029                                                                                // image =
     1030                                                                                // i.getEnclosures().iterator().next();
     1031                                                                                // image.refresh();
     1032                                                                        } else {
     1033                                                                                image = new FrameImage((Text) i, null);
     1034                                                                        }
     1035                                                                        // TODO Add the image when creating new
     1036                                                                        // FrameImage
     1037                                                                        toParse.addItem(image);
     1038                                                                } else if (ItemUtils.startsWithTag(i,
     1039                                                                                ItemUtils.TAG_BITMAP_IMAGE)
     1040                                                                                && i.getLink() != null
     1041                                                                                && !i.getAbsoluteLink()
     1042                                                                                .equalsIgnoreCase(
     1043                                                                                                toParse.getName())) {
     1044                                                                        XRayable image = null;
     1045                                                                        if (i.hasEnclosures()) {
     1046                                                                                // image =
     1047                                                                                // i.getEnclosures().iterator().next();
     1048                                                                                // image.refresh();
     1049                                                                                // i.setHidden(true);
     1050                                                                        } else {
     1051                                                                                // If a new bitmap is created for a
     1052                                                                                // frame which already has a bitmap dont
     1053                                                                                // recreate the bitmap
     1054                                                                                image = new FrameBitmap((Text) i, null);
     1055                                                                        }
     1056                                                                        toParse.addItem(image);
     1057                                                                } else if (ItemUtils.startsWithTag(i, "@c")) {
     1058                                                                        // Can only have a @c
     1059                                                                        if (!i.hasEnclosures()
     1060                                                                                        && i.getLines().size() == 1) {
     1061                                                                                toParse.addItem(new Circle((Text) i));
     1062                                                                        }
     1063                                                                        // Check for JSItem
     1064                                                                } else if(ItemUtils.startsWithTag(i, "@js")) {
     1065                                                                        toParse.addItem(new JSItem((Text) i));
     1066                                                                        // Check for interactive widgets
     1067                                                                } else if (ItemUtils.startsWithTag(i, ItemUtils.TAG_IWIDGET)) {
     1068                                                                        createWidget(toParse, (Text) i);
     1069                                                                }
     1070                                                        }
     1071                                                        // TODO decide exactly what to do here!!
     1072                                                        toParse.addAnnotation((Text) i);
     1073                                                }
     1074                                        } else if (!DisplayController.isXRayMode() && i.hasFormula()) {
     1075                                                i.calculate(i.getFormula());
     1076                                        }
     1077                                }
     1078                        } catch (Exception e) {
     1079                                Logger.Log(e);
     1080                                e.printStackTrace();
     1081                                MessageBay.warningMessage("Exception occured when loading "
     1082                                                + i.getClass().getSimpleName() + "(ID: " + i.getID()
     1083                                                + ") " + e.getMessage() != null ? e.getMessage() : "");
     1084                        }
     1085                }
     1086
     1087                /*
     1088                 * for (Item i : items) { if (i instanceof Dot) { ((Dot)
     1089                 * i).setPointType(pointtype); ((Dot) i).useFilledPoints(filledPoints);
     1090                 * } }
     1091                 */
     1092
     1093                FrameIO.ResumeCache();
     1094
     1095                toParse.clearOverlays();
     1096                toParse.clearVectors();
     1097                toParse.addAllOverlays(overlays);
     1098                toParse.addAllVectors(vectors);
     1099
     1100        }
     1101
     1102        /**
     1103         * TODO: Comment. cts16
     1104         *
     1105         * @param vectors
     1106         * @param permission
     1107         * @param i
     1108         */
     1109        private static void addVector(List<Vector> vectors, UserAppliedPermission defaultPermission, UserAppliedPermission framePermission, Item i)
     1110        {
     1111                // TODO It is possible to get into an infinite loop if a
     1112                // frame contains an @ao which leads to a frame with an
     1113                // @v which points back to the frame with the @ao
     1114                Frame vector = FrameIO.LoadFrame(i.getAbsoluteLink());
     1115
     1116                // Get the permission from off the vector frame
     1117                UserAppliedPermission vectorPermission = UserAppliedPermission.getPermission(vector.getAnnotationValue("permission"), defaultPermission);
     1118               
     1119                // If the frame permission is lower, use that
     1120                vectorPermission = UserAppliedPermission.min(vectorPermission, framePermission);
     1121               
     1122                // Highest permissable permission for vectors is copy
     1123                vectorPermission = UserAppliedPermission.min(vectorPermission, UserAppliedPermission.copy);
     1124                if (vector != null) {
     1125                        String scaleString = new AttributeValuePair(i.getText()).getValue();
     1126                        Float scale = 1F;
     1127                        try {
     1128                                scale = Float.parseFloat(scaleString);
     1129                        } catch (Exception e) {
     1130                        }
     1131                        Vector newVector = new Vector(vector, vectorPermission, scale, i);
     1132                        i.setOverlay(newVector);
     1133                        i.setVisible(false);
     1134                        vectors.add(newVector);
     1135                }
     1136        }
     1137
     1138        public static Item onItem(float floatX, float floatY, boolean changeLastEdited)
     1139        {
     1140                return onItem(DisplayController.getCurrentFrame(), floatX, floatY, changeLastEdited);
     1141        }
     1142
     1143        /**
     1144         * Searches through the list of items on this frame to find one at the given
     1145         * x,y coordinates.
     1146         *
     1147         * @param x
     1148         *            The x coordinate
     1149         * @param y
     1150         *            The y coordinate
     1151         * @return The Item at the given coordinates, or NULL if none is found.
     1152         */
     1153        public static Item onItem(Frame toCheck, float floatX, float floatY, boolean bResetLastEdited)
     1154        {
     1155                // System.out.println("MouseX: " + floatX + " MouseY: " + floatY);
     1156                int x = Math.round(floatX);
     1157                int y = Math.round(floatY);
     1158                if (toCheck == null)
     1159                        return null;
     1160
     1161                List<Item> possibles = new ArrayList<Item>(0);
     1162
     1163                // if the mouse is in the message area
     1164                if (y >= DisplayController.getMessageBayPaintArea().getMinY()) {
     1165                        // check the individual message items
     1166                        for (Item message : MessageBay.getMessages()) {
     1167                                if (message != null) {
     1168                                        if (message.contains(new Point(x, y))) {
     1169                                                message.setOverlayPermission(UserAppliedPermission.copy);
     1170                                                possibles.add(message);
     1171                                        } else {
     1172                                                // Not sure why but if the line below is removed then
     1173                                                // several items can be highlighted at once
     1174                                                message.setHighlightMode(Item.HighlightMode.None);
     1175                                                message.setHighlightColorToDefault();
     1176                                        }
     1177                                }
     1178                        }
     1179
     1180                        // check the link to the message frame
     1181                        if (MessageBay.getMessageLink() != null) {
     1182                                if (MessageBay.getMessageLink().contains(new Point(x, y))) {
     1183                                        MessageBay.getMessageLink().setOverlayPermission(UserAppliedPermission.copy);
     1184                                        possibles.add(MessageBay.getMessageLink());
     1185                                }
     1186                        }
     1187
     1188                        // this is taken into account in contains
     1189                        // y -= FrameGraphics.getMaxFrameSize().height;
     1190                        // otherwise, the mouse is on the frame
     1191                } else {
     1192                        if (LastEdited != null) {
     1193                                if (LastEdited.contains(x, y)
     1194                                                && !FreeItems.getInstance().contains(LastEdited)
     1195                                                && LastEdited.getParent() == DisplayController.getCurrentFrame()
     1196                                                && LastEdited.getParent().getItems().contains(LastEdited))
     1197                                {
     1198                                        LastEdited.setOverlayPermission(UserAppliedPermission.full);
     1199                                        return LastEdited;
     1200                                } else if (bResetLastEdited) {
     1201                                        setLastEdited(null);
     1202                                }
     1203                        }
     1204                        ArrayList<Item> checkList = new ArrayList<Item>();
     1205                        checkList.addAll(toCheck.getInteractableItems());
     1206                        checkList.add(toCheck.getNameItem());
     1207
     1208                        for (Item i : checkList) {
     1209
     1210                                // do not check annotation items in audience mode
     1211                                //TODO: Upon hover of Rubbish Bin, Undo and Restore Widgets, flickering occurs depending on the mouse distance from a corner. Resolve this.
     1212                                if (i.isVisible() && !(DisplayController.isAudienceMode() && i.isAnnotation())) {
     1213                                        if (i instanceof WidgetCorner) {
     1214                                                WidgetCorner wc = (WidgetCorner) i;
     1215                                                if (wc.getWidgetSource() instanceof ButtonWidget) {
     1216                                                        ButtonWidget bw = (ButtonWidget) wc.getWidgetSource();
     1217
     1218                                                        if (bw.getdropInteractableStatus() == true) {
     1219                                                                Widget iw = wc.getWidgetSource();
     1220
     1221                                                                if(iw.getBounds().contains(x, y)){
     1222
     1223                                                                        if( !FreeItems.getInstance().contains(i))
     1224                                                                        {
     1225                                                                                possibles.add(i);                                                       
     1226                                                                        }
     1227                                                                }       
     1228                                                        }
     1229                                                }
     1230                                        }
     1231
     1232                                        if (i.contains(new Point(x, y))){
     1233                                                if(!FreeItems.getInstance().contains(i)) {
     1234                                                        possibles.add(i);                               
     1235                                                }
     1236                                        }
     1237
     1238                                }
     1239                        }
     1240                }
     1241
     1242                // if there are no possible items, return null
     1243                if (possibles.size() == 0)
     1244                        return null;
     1245
     1246                // if there is only one possibility, return it
     1247                if (possibles.size() == 1)
     1248                        return possibles.get(0);
     1249
     1250                // return closest x,y pair to mouse
     1251                Item closest = possibles.get(0);
     1252                int distance = (int) Math.round(Math.sqrt(Math.pow(
     1253                                Math.abs(closest.getX() - x), 2)
     1254                                + Math.pow(Math.abs(closest.getY() - y), 2)));
     1255
     1256                for (Item i : possibles) {
     1257                        int d = (int) Math.round(Math.sqrt(Math.pow(Math.abs(i.getX() - x),
     1258                                        2) + Math.pow(Math.abs(i.getY() - y), 2)));
     1259
     1260                        // System.out.println(d);
     1261                        if (d <= distance) {
     1262                                distance = d;
     1263
     1264                                // dots take precedence over lines
     1265                                if ((!(closest instanceof Dot && i instanceof Line))
     1266                                                && (!(closest instanceof Text && i instanceof Line)))
     1267                                        closest = i;
     1268
     1269                        }
     1270
     1271                }       
     1272
     1273                return closest;
     1274        }
    4281275       
    429         // check for an updated template...
    430         for (Item i : frame.getAnnotationItems()) {                             
    431            
    432             if (ItemUtils.startsWithTag(i, annotationStr)) {
    433 
    434                 matched_item = i;
    435                 break;
    436             }
    437         }
    438 
    439         return matched_item;
    440     }
    441 
    442     protected static void doFrameTransition(Item frameTransition, Frame from, Frame to)
    443     {
    444         String s = frameTransition.getText();           
    445         String[] s_array = s.split(":");
    446         if(s_array.length > 1){
    447             String slide_mode_method = s_array[1].trim();
    448            
    449             FrameTransitions.setSlideModeMethod(slide_mode_method);
    450             System.out.println("Triggered on annotation: " + s);
    451             FrameTransitions.setSlideTrue();
    452             FrameTransitions.setSlideModeBaseImage(FrameGraphics.getBuffer(from, false, false));
    453         }
    454         else {
    455             System.err.println("Warning: failed to detect frameTransition type");
    456             // TODO: print list as a result of reflection listing         
    457         }
    458     }                           
    459 
    460     /**
    461      * Displays the given Frame on the display. If the current frame has changed
    462      * since the last save then it will be saved before the switch is made. The
    463      * caller can also dictate whether the current frame is added to the
    464      * back-stack or not.
    465      *
    466      * @param toDisplay
    467      *            The Frame to display on the screen
    468      * @param addToBack
    469      *            True if the current Frame should be added to the back-stack,
    470      *            False otherwise
    471      */
    472     public static void DisplayFrame(Frame toDisplay, boolean addToBack,
    473             boolean incrementStats) {
    474         if (toDisplay == null)
    475             return;
    476 
    477         Frame current = DisplayIO.getCurrentFrame();
    478 
    479         // Dont need to do anything if the frame to display is already being
    480         // displayed
    481         if (current.equals(toDisplay))
    482             return;
    483 
    484         // move any anchored connected items
    485         if (FreeItems.itemsAttachedToCursor()) {
    486             List<Item> toAdd = new ArrayList<Item>();
    487             List<Item> toCheck = new ArrayList<Item>(FreeItems.getInstance());
    488 
    489             while (toCheck.size() > 0) {
    490                 Item i = toCheck.get(0);
    491                 Collection<Item> connected = i.getAllConnected();
    492 
    493                 // // Only move completely enclosed items
    494                 // if (!toCheck.containsAll(connected)) {
    495                 // connected.retainAll(FreeItems.getInstance());
    496                 // FreeItems.getInstance().removeAll(connected);
    497                 // toCheck.removeAll(connected);
    498                 // FrameMouseActions.anchor(connected);
    499                 // } else {
    500                 // toCheck.removeAll(connected);
    501                 // }
    502 
    503                 // Anchor overlay items where they belong
    504                 if (i.getParent() != null && i.getParent() != current) {
    505                     FreeItems.getInstance().removeAll(connected);
    506                     toCheck.removeAll(connected);
    507                     FrameMouseActions.anchor(connected);
     1276        /**
     1277         * Checks if the mouse is currently over an item.
     1278         *
     1279         * @return
     1280         *              True if the mouse is over any item, false otherwise.
     1281         */
     1282        public static boolean hasCurrentItem()
     1283        {
     1284                return getCurrentItem() != null;
     1285        }
     1286
     1287        public synchronized static Item getCurrentItem()
     1288        {
     1289                return onItem(DisplayController.getCurrentFrame(), DisplayController.getMouseX(), DisplayController.getMouseY(), true);
     1290        }
     1291
     1292        public static PolygonBounds getEnlosingPolygon()
     1293        {
     1294                Collection<Item> enclosure = getEnclosingLineEnds();
     1295               
     1296                if (enclosure == null || enclosure.size() == 0) return null;
     1297
     1298                return enclosure.iterator().next().getEnclosedShape();
     1299        }
     1300
     1301        /**
     1302         *
     1303         * @param currentItem
     1304         * @return
     1305         */
     1306        public static Collection<Item> getCurrentItems()
     1307        {
     1308                return getCurrentItems(getCurrentItem());
     1309        }
     1310
     1311        public static Collection<Item> getCurrentItems(Item currentItem)
     1312        {
     1313                Collection<Item> enclosure = getEnclosingLineEnds();
     1314               
     1315                if (enclosure == null || enclosure.size() == 0) return null;
     1316
     1317                Item firstItem = enclosure.iterator().next();
     1318
     1319                Collection<Item> enclosed = getItemsEnclosedBy(DisplayController.getCurrentFrame(), firstItem.getEnclosedShape());
     1320
     1321                // Brook: enclosed widgets are to be fully enclosed, never partially
     1322                /*
     1323                 * MIKE says: but doesn't this mean that widgets are treated differently
     1324                 * from ALL other object which only need to be partially enclosed to be
     1325                 * picked up
     1326                 */
     1327                List<Widget> enclosedWidgets = new LinkedList<Widget>();
     1328                for (Item i : enclosed) {
     1329                        // Don't want to lose the highlighting from the current item
     1330                        if (i == currentItem || enclosure.contains(i)) {
     1331                                continue;
     1332                        }
     1333                        // Don't want to lose the highlighting of connected Dots
     1334                        // TODO: this code does nothing (perhaps the continue is meant for the outer
     1335                        // for loop?). cts16
     1336                        if (i instanceof Dot && i.getHighlightMode() == HighlightMode.Connected) {
     1337                                for (Line l : i.getLines()) {
     1338                                        if (l.getOppositeEnd(i).getHighlightMode() == HighlightMode.Normal) {
     1339                                                continue;
     1340                                        }
     1341                                }
     1342                        }
     1343                       
     1344                        if (i instanceof WidgetCorner) {
     1345                                if (!enclosedWidgets.contains(((WidgetCorner) i).getWidgetSource())) {
     1346                                        enclosedWidgets.add(((WidgetCorner) i).getWidgetSource());
     1347                                }
     1348                        }
     1349                       
     1350                        i.setHighlightMode(Item.HighlightMode.None);
     1351                        i.setHighlightColorToDefault();
     1352                }
     1353
     1354                for (Widget iw : enclosedWidgets) {
     1355                        for (Item i : iw.getItems()) {
     1356                                if (!enclosed.contains(i)) {
     1357                                        enclosed.add(i);
     1358                                }
     1359                        }
     1360                }
     1361
     1362                return enclosed;
     1363        }
     1364
     1365        /**
     1366         * Gets the collection of Dot items that form the enclosure nearest to the current mouse position.
     1367         */
     1368        public static Collection<Item> getEnclosingLineEnds()
     1369        {
     1370                return getEnclosingLineEnds(new Point(DisplayController.getMouseX(), DisplayController.getMouseY()));
     1371        }
     1372
     1373        /**
     1374         * Gets the collection of Dot items that form the enclosure nearest to the given position.
     1375         */
     1376        public static Collection<Item> getEnclosingLineEnds(Point position)
     1377        {
     1378                // update enclosed shapes
     1379                Frame current = DisplayController.getCurrentFrame();
     1380                if (current == null) return null;
     1381                List<Item> items = current.getItems();
     1382
     1383                // Remove all items that are connected to freeItems
     1384                List<Item> freeItems = new ArrayList<Item>(FreeItems.getInstance());
     1385                while (freeItems.size() > 0) {
     1386                        Item item = freeItems.get(0);
     1387                        Collection<Item> connected = item.getAllConnected();
     1388                        items.removeAll(connected);
     1389                        freeItems.removeAll(connected);
     1390                }
     1391
     1392                List<Item> used = new ArrayList<Item>(0);
     1393
     1394                while (items.size() > 0) {
     1395                        Item i = items.get(0);
     1396                        items.remove(i);
     1397                        if (i.isEnclosed()) {
     1398                                PolygonBounds p = i.getEnclosedShape();
     1399                                if (p.contains(position)) {
     1400                                        used.add(i);
     1401                                        items.removeAll(i.getEnclosingDots());
     1402                                }
     1403                        }
     1404                }
     1405
     1406                if (used.size() == 0) return null;
     1407
     1408                // if there is only one possibility, return it
     1409                if (used.size() == 1) {
     1410                        return used.get(0).getEnclosingDots();
     1411                // otherwise, determine which polygon is closest to the cursor
    5081412                } else {
    509                     // Add stuff that is partially enclosed
    510                     // remove all the connected items from our list to check
    511                     toCheck.removeAll(connected);
    512                     // Dont add the items that are free
    513                     connected.removeAll(FreeItems.getInstance());
    514                     toAdd.addAll(connected);
    515                 }
    516             }
    517 
    518             current.removeAllItems(toAdd);
    519 
    520             boolean oldChange = toDisplay.hasChanged();
    521             toDisplay.updateIDs(toAdd);
    522             toDisplay.addAllItems(toAdd);
    523             toDisplay.setChanged(oldChange);
    524         }
    525 
    526         if (addToBack && current != toDisplay) {
    527             FrameIO.checkTDFC(current);
    528         }
    529 
    530         // if the saving happened properly, we can continue
    531         if (!LeavingFrame(current)) {
    532             MessageBay.displayMessage("Navigation cancelled");
    533             return;
    534         }
    535 
    536         if (addToBack && current != toDisplay) {
    537             DisplayIO.addToBack(current);
    538         }
    539 
    540         Parse(toDisplay);
    541 
    542         if (FrameGraphics.isAudienceMode()) {
    543                 // Only need to worry about frame transitions when in Audience Mode
     1413                        Collections.sort(used, new Comparator<Item>() {
     1414                                public int compare(Item d1, Item d2) {
     1415                                        PolygonBounds p1 = d1.getEnclosedShape();
     1416                                        PolygonBounds p2 = d2.getEnclosedShape();
     1417
     1418                                        int closest = Integer.MAX_VALUE;
     1419                                        int close2 = Integer.MAX_VALUE;
     1420
     1421                                        int mouseX = DisplayController.getMouseX();
     1422                                        int mouseY = DisplayController.getMouseY();
     1423
     1424                                        for (int i = 0; i < p1.getPointCount(); i++) {
     1425                                                int diff = Math.abs(p1.getPoint(i).x - mouseX) + Math.abs(p1.getPoint(i).y - mouseY);
     1426                                                int diff2 = Integer.MAX_VALUE;
     1427
     1428                                                if (i < p2.getPointCount())
     1429                                                        diff2 = Math.abs(p2.getPoint(i).x - mouseX)  + Math.abs(p2.getPoint(i).y - mouseY);
     1430
     1431                                                if (diff < Math.abs(closest)) {
     1432                                                        close2 = closest;
     1433                                                        closest = diff;
     1434                                                } else if (diff < Math.abs(close2))
     1435                                                        close2 = diff;
     1436
     1437                                                if (diff2 < Math.abs(closest)) {
     1438                                                        close2 = closest;
     1439                                                        closest = -diff2;
     1440                                                } else if (diff2 < Math.abs(close2))
     1441                                                        close2 = diff2;
     1442                                        }
     1443
     1444                                        if (closest > 0 && close2 > 0)
     1445                                                return -10;
     1446
     1447                                        if (closest < 0 && close2 < 0)
     1448                                                return 10;
     1449
     1450                                        if (closest > 0)
     1451                                                return -10;
     1452
     1453                                        return 10;
     1454                                }
     1455
     1456                        });
     1457
     1458                        return used.get(0).getEnclosingDots();
     1459                }
     1460        }
     1461
     1462        // TODO Remove this method!!
     1463        // Can just getItemsWithin be used?
     1464        public static Collection<Item> getItemsEnclosedBy(Frame frame, PolygonBounds poly)
     1465        {
     1466                Collection<Item> contained = frame.getItemsWithin(poly);
     1467
     1468                Collection<Item> results = new LinkedHashSet<Item>(contained.size());
     1469
     1470                // check for correct permissions
     1471                for (Item item : contained) {
     1472                        // if the item is on the frame
     1473                        if (item.getParent() == frame || item.getParent() == null) {
     1474                                // item.Permission = Permission.full;
     1475                                results.add(item);
     1476                                // otherwise, it must be on an overlay frame
     1477                        } else {
     1478                                for (Overlay overlay : frame.getOverlays()) {
     1479                                        if (overlay.Frame == item.getParent()) {
     1480                                                item.setOverlayPermission(overlay.permission);
     1481                                                results.add(item);
     1482                                                break;
     1483                                        }
     1484                                }
     1485                        }
     1486                }
     1487
     1488                return results;
     1489        }
     1490
     1491        /**
     1492         * Fills the given Frame with default profile tags
     1493         */
     1494        public static void CreateDefaultProfile(String username, Frame profile)
     1495        {
     1496                Text title = profile.getTitleItem();
     1497                if (username.equals(UserSettings.DEFAULT_PROFILE_NAME)) {
     1498                        title.setText("Default Profile Frame");
     1499                } else {
     1500                        // if this profile is not the default profile, copy it from the default profile instead of generating a new profile
     1501                        // (this allows the possibility of modifying the default profile and having any new profiles get those modifications)
     1502                        Frame nextDefault = FrameIO.LoadProfile(UserSettings.DEFAULT_PROFILE_NAME);
     1503                        if (nextDefault == null) {
     1504                                try {
     1505                                        nextDefault = FrameIO.CreateNewProfile(UserSettings.DEFAULT_PROFILE_NAME);
     1506                                } catch (Exception e) {
     1507                                        // TODO tell the user that there was a problem creating the
     1508                                        // profile frame and close nicely
     1509                                        e.printStackTrace();
     1510                                }
     1511                        }
     1512                        // load profile frame and set title correctly
     1513                        profile.reset();
     1514                        profile.removeAllItems(profile.getAllItems());
     1515                        // set relative link on all items so their links will correctly point to the page on the current profile rather than on the default profile
     1516                        for(Item i : nextDefault.getAllItems()) {
     1517                                i.setRelativeLink();
     1518                        }
     1519                        profile.addAllItems(ItemUtils.CopyItems(nextDefault.getAllItems()));
     1520                        profile.setTitle(username + "'s Profile Frame");
     1521                        FrameIO.SaveFrame(profile);
     1522
     1523                        Frame nextProfile = profile;
     1524                        MessageBay.suppressMessages(true);
     1525                        while((nextDefault = FrameIO.LoadNext(nextDefault)) != null) {
     1526                                // in case there are gaps in the frame numbering of the default profile (e.g. if a user has edited it),
     1527                                // we need to replicate those gaps in the copied profile so the links will work correctly
     1528                                while(nextProfile.getNumber() < nextDefault.getNumber()) {
     1529                                        nextProfile = FrameIO.CreateFrame(profile.getFramesetName(), null, null);
     1530                                }
     1531                                // if the new profile has a frame number higher than the current frame number in the default profile,
     1532                                // the new profile must already exist, so just exit
     1533                                // (TODO: should we wipe the frames instead?)
     1534                                if(nextProfile.getNumber() > nextDefault.getNumber()) {
     1535                                        break;
     1536                                }
     1537                                nextProfile.reset();
     1538                                nextProfile.removeAllItems(nextProfile.getAllItems());
     1539                                // set relative link on all items so their links will correctly point to the page on the current profile rather than on the default profile
     1540                                for(Item i : nextDefault.getAllItems()) {
     1541                                        i.setRelativeLink();
     1542                                }
     1543                                nextProfile.addAllItems(ItemUtils.CopyItems(nextDefault.getAllItems()));
     1544                                FrameIO.SaveFrame(nextProfile);
     1545                        }
     1546                        MessageBay.suppressMessages(false);
     1547
     1548                        return;
     1549                }
     1550
     1551                // int spacing = 50;
     1552                final int intialYPos = 75;
     1553                int xPos = 75;
     1554                int yPos = intialYPos;
     1555
     1556                // yPos += spacing;
     1557                // profile.addText(xPos, yPos, "@HomeFrame", null, profile.getName());
     1558                // yPos += spacing;
     1559                // String defaultFrameName = profile.getFramesetName() + "0";
     1560                // profile.addText(xPos, yPos, "@DefaultFrame", null, defaultFrameName);
     1561                // yPos += spacing;
     1562                //
     1563                // profile.addText(xPos, yPos, "@InitialWidth: "
     1564                // + UserSettings.InitialWidth, null);
     1565                // yPos += spacing;
     1566                //
     1567                // profile.addText(xPos, yPos, "@InitialHeight: "
     1568                // + UserSettings.InitialHeight, null);
     1569                // yPos += spacing;
     1570                //
     1571                // Text t = profile.addText(xPos, yPos, "@ItemTemplate", null);
     1572                // t.setColor(null);
     1573                //
     1574                // yPos += spacing;
     1575                // t = profile.addText(xPos, yPos, "@AnnotationTemplate", null);
     1576                // t.setColor(Color.gray);
     1577                //
     1578                // yPos += spacing;
     1579                // t = profile.addText(xPos, yPos, "@CommentTemplate", null);
     1580                // t.setColor(Color.green.darker());
     1581                //
     1582                // yPos += spacing;
     1583                // t = profile.addText(xPos, yPos, "@StatsTemplate", null);
     1584                // t.setColor(Color.BLACK);
     1585                // t.setBackgroundColor(new Color(0.9F, 0.9F, 0.9F));
     1586                // t.setFamily(Text.MONOSPACED_FONT);
     1587                // t.setSize(14);
     1588
     1589                Text t;
     1590
     1591                xPos = 300;
     1592                // yPos = intialYPos + spacing;
     1593                yPos = 100;
     1594
     1595                // Add documentation links
     1596                File helpDirectory = new File(FrameIO.HELP_PATH);
     1597                if (helpDirectory != null) {
     1598                        File[] helpFramesets = helpDirectory.listFiles();
     1599                        if (helpFramesets != null) {
     1600
     1601                                // Add the title for the help index
     1602                                Text help = profile.addText(xPos, yPos, "@Expeditee Help", null);
     1603                                help.setSize(25);
     1604                                help.setFontStyle("Bold");
     1605                                help.setFamily("SansSerif");
     1606                                help.setColor(TemplateSettings.ColorWheel.get()[3]);
     1607
     1608                                xPos += 25;
     1609                                System.out.println("Installing frameset: ");
     1610
     1611                                boolean first_item = true;
     1612
     1613                                for (File helpFrameset : helpFramesets) {
     1614                                        String framesetName = helpFrameset.getName();
     1615                                        if (!FrameIO.isValidFramesetName(framesetName)) {
     1616                                                continue;
     1617                                        }
     1618
     1619                                        if (first_item) {
     1620                                                System.out.print("  " + framesetName);
     1621                                                first_item = false;
     1622                                        }
     1623                                        else {
     1624                                                System.out.print(", " + framesetName);
     1625                                        }
     1626                                        System.out.flush();
     1627
     1628                                        Frame indexFrame = FrameIO.LoadFrame(framesetName + '1');
     1629                                        // Look through the folder for help index pages
     1630                                        if (indexFrame != null
     1631                                                        && ItemUtils.FindTag(indexFrame.getItems(),
     1632                                                                        "@HelpIndex") != null) {
     1633                                                // yPos += spacing;
     1634                                                yPos += 30;
     1635                                                t = profile.addText(xPos, yPos,
     1636                                                                '@' + indexFrame.getFramesetName(), null);
     1637                                                t.setLink(indexFrame.getName());
     1638                                                t.setColor(Colour.GREY);
     1639                                        }
     1640                                }
     1641                                System.out.println();
     1642                        }
     1643                }
     1644
     1645                xPos = 50;
     1646                yPos = 100;
     1647
     1648                // Populate Start Pages and Settings
     1649                File framesetDirectory = new File(FrameIO.FRAME_PATH);
     1650
     1651                if (framesetDirectory.exists()) {
     1652                        File[] startpagesFramesets = framesetDirectory.listFiles();
     1653
     1654                        if (startpagesFramesets != null) {
     1655                                // Add Start Page title
     1656                                Text templates = profile.addText(xPos, yPos, "@Start Pages",
     1657                                                null);
     1658                                templates.setSize(25);
     1659                                templates.setFontStyle("Bold");
     1660                                templates.setFamily("SansSerif");
     1661                                templates.setColor(TemplateSettings.ColorWheel.get()[3]);
     1662
     1663                                xPos += 25;
     1664
     1665                                // Start Pages should be the first frame in its own frameset +
     1666                                // frameset name should be present in FrameUtils.startPages[].
     1667                                for (File startpagesFrameset : startpagesFramesets) {
     1668                                        String framesetName = startpagesFrameset.getName();
     1669
     1670                                        // Only add link if frameset is a startpage
     1671                                        for (int i = 0; i < startPages.length; i++) {
     1672                                                if (framesetName.equals(startPages[i])) {
     1673                                                        Frame indexFrame = FrameIO
     1674                                                                        .LoadFrame(framesetName + '1');
     1675
     1676                                                        // Add start page link
     1677                                                        if (indexFrame != null) {
     1678                                                                yPos += 30;
     1679                                                                t = profile.addText(xPos, yPos,
     1680                                                                                '@' + indexFrame.getFramesetName(),
     1681                                                                                null);
     1682                                                                t.setLink(indexFrame.getName());
     1683                                                                t.setColor(Colour.GREY);
     1684                                                        }
     1685                                                }
     1686                                        }
     1687                                }
     1688                        }
     1689                }
     1690
     1691                FrameIO.SaveFrame(profile);
     1692
     1693                // Populate settings frameset
     1694                Settings.Init();
     1695                t = profile.addText(550, 100, "@Settings", null);
     1696                t.setSize((float) 25.0);
     1697                t.setFamily("SansSerif");
     1698                t.setFontStyle("Bold");
     1699                t.setColor(Colour.GREY);
     1700                Settings.generateSettingsTree(t);
     1701
     1702                FrameIO.SaveFrame(profile);
     1703        }
     1704
     1705        private static void checkTDFCItemWaiting(Frame currentFrame)
     1706        {
     1707                Item tdfcItem = FrameUtils.getTdfcItem();
     1708                // if there is a TDFC Item waiting
     1709                if (tdfcItem != null) {
     1710                        boolean change = currentFrame.hasChanged();
     1711                        boolean saved = currentFrame.isSaved();
     1712                        // Save the parent of the item if it has not been saved
     1713                        if (!change && !saved) {
     1714                                tdfcItem.setLink(null);
     1715                                tdfcItem.getParent().setChanged(true);
     1716                                FrameIO.SaveFrame(tdfcItem.getParent());
     1717                                DisplayController.requestRefresh(true);
     1718                        } else {
     1719                                SessionStats.CreatedFrame();
     1720                        }
     1721
     1722                        setTdfcItem(null);
     1723                }
     1724        }
     1725
     1726        public static void setTdfcItem(Item _tdfcItem)
     1727        {
     1728                FrameUtils._tdfcItem = _tdfcItem;
     1729        }
     1730
     1731        public static Item getTdfcItem()
     1732        {
     1733                return FrameUtils._tdfcItem;
     1734        }
     1735
     1736        public static void setLastEdited(Text lastEdited)
     1737        {
     1738                // If the lastEdited is being changed then check if its @i
     1739                Frame toReparse = null;
     1740                Frame toRecalculate = null;
     1741                Frame toUpdateObservers = null;
     1742
     1743                if (LastEdited == null) {
     1744                        // System.out.print("N");
     1745                } else if (LastEdited != null) {
     1746                        // System.out.print("T");
     1747                        Frame parent = LastEdited.getParentOrCurrentFrame();
     1748
     1749                        if (lastEdited != LastEdited) {
     1750                                if (LastEdited.startsWith("@i")) {
     1751                                        // Check if its an image that can be resized to fit a box
     1752                                        // around it
     1753                                        String text = LastEdited.getText();
     1754                                        if (text.startsWith("@i:")
     1755                                                        && !Character
     1756                                                        .isDigit(text.charAt(text.length() - 1))) {
     1757                                                Collection<Item> enclosure = FrameUtils
     1758                                                                .getEnclosingLineEnds(LastEdited.getPosition());
     1759                                                if (enclosure != null) {
     1760                                                        for (Item i : enclosure) {
     1761                                                                if (i.isLineEnd() && i.isEnclosed()) {
     1762                                                                        DisplayController.getCurrentFrame().removeAllItems(
     1763                                                                                        enclosure);
     1764                                                                        AxisAlignedBoxBounds rect = i.getEnclosedBox();
     1765                                                                        LastEdited
     1766                                                                        .setText(LastEdited.getText()
     1767                                                                                        + " "
     1768                                                                                        + Math.round(rect
     1769                                                                                                        .getWidth()));
     1770                                                                        LastEdited.setPosition(rect.getTopLeft());
     1771                                                                        LastEdited.setThickness(i.getThickness());
     1772                                                                        LastEdited.setBorderColor(i.getColor());
     1773                                                                        break;
     1774                                                                }
     1775                                                        }
     1776                                                        StandardGestureActions.deleteItems(enclosure, false);
     1777                                                }
     1778                                        }
     1779                                        toReparse = parent;
     1780                                } else if (LastEdited.recalculateWhenChanged()) {
     1781                                        toRecalculate = parent;
     1782                                }
     1783
     1784                                if (parent.hasObservers()) {
     1785                                        toUpdateObservers = parent;
     1786                                }
     1787                                // Update the formula if in XRay mode
     1788                                if (DisplayController.isXRayMode() && LastEdited.hasFormula()) {
     1789                                        LastEdited.setFormula(LastEdited.getText());
     1790                                }
     1791                        }
     1792                        if (lastEdited != LastEdited && LastEdited.getText().length() == 0) {
     1793                                parent.removeItem(LastEdited);
     1794                        }
     1795                }
     1796                LastEdited = lastEdited;
     1797
     1798                if (!DisplayController.isXRayMode()) {
     1799                        if (toReparse != null) {
     1800                                Parse(toReparse, false, false);
     1801                        } else {
     1802                                if (toRecalculate != null) {
     1803                                        toRecalculate.recalculate();
     1804                                }
     1805
     1806                                if (toUpdateObservers != null) {
     1807                                        toUpdateObservers.notifyObservers(false);
     1808                                }
     1809                        }
     1810                }
     1811        }
     1812
     1813        /**
     1814         * Extracts files/folders from the assets/resources folder directly into
     1815         * ${PARENT_FOLDER} (~/.expeditee)
     1816         *
     1817         * @param force if true, resources will be extracted even if they have already been extracted before
     1818         */
     1819        public static void extractResources(boolean force)
     1820        {
     1821                File check = new File(FrameIO.PARENT_FOLDER + ".res");
    5441822               
    545                 // Test to see if frame transition specified through annotation, and perform it if one if found
    546                 Item frameTransition = getAnnotation(toDisplay, "@frameTransition");
    547                 if (frameTransition != null) {
    548                         doFrameTransition(frameTransition,current,toDisplay);
    549                 }
    550         }
    551        
    552         DisplayIO.setCurrentFrame(toDisplay, incrementStats);
    553         FrameMouseActions.updateCursor();
    554         // FrameMouseActions.getInstance().refreshHighlights();
    555         // update response timer
    556         _LastResponse = ResponseTimer.getElapsedSeconds();
    557         _ResponseTimeSum += _LastResponse;
    558         DisplayIO.UpdateTitle();
    559     }
    560 
    561     /**
    562      * Loads and displays the Frame with the given framename, and adds the
    563      * current frame to the back-stack if required.
    564      *
    565      * @param framename
    566      *            The name of the Frame to load and display
    567      * @param addToBack
    568      *            True if the current Frame should be added to the back-stack,
    569      *            false otherwise
    570      */
    571     public static void DisplayFrame(String frameName, boolean addToBack,
    572             boolean incrementStats) {
    573         Frame newFrame = getFrame(frameName);
    574 
    575         if (newFrame != null)
    576             // display the frame
    577             DisplayFrame(newFrame, addToBack, incrementStats);
    578     }
    579 
    580     /**
    581      * Loads and displays the Frame with the given framename and adds the
    582      * current frame to the back-stack. This is the same as calling
    583      * DisplayFrame(framename, true)
    584      *
    585      * @param framename
    586      *            The name of the Frame to load and display
    587      */
    588     public static void DisplayFrame(String framename) {
    589         DisplayFrame(framename, true, true);
    590     }
    591 
    592     public static Frame getFrame(String frameName) {
    593         // if the new frame does not exist then tell the user
    594         Frame f = FrameIO.LoadFrame(frameName);
    595 
    596         if (f == null) {
    597             MessageBay.errorMessage("Frame '" + frameName
    598                     + "' could not be found.");
    599         }
    600 
    601         return f;
    602     }
    603 
    604     /**
    605      * Creates a new Picture Item from the given Text source Item and adds it to
    606      * the given Frame.
    607      *
    608      * @return True if the image was created successfully, false otherwise
    609      */
    610     private static boolean createPicture(Frame frame, Text txt) {
    611         // attempt to create the picture
    612         Picture pic = ItemUtils.CreatePicture(txt, frame);
    613 
    614         // if the picture could not be created successfully
    615         if (pic == null) {
    616             String imagePath = txt.getText();
    617             assert (imagePath != null);
    618             imagePath = new AttributeValuePair(imagePath).getValue().trim();
    619             if (imagePath.length() == 0) {
    620                 return false;
    621                 // MessageBay.errorMessage("Expected image path after @i:");
    622             } else {
    623                 MessageBay.errorMessage("Image " + imagePath
    624                         + " could not be loaded");
    625             }
    626             return false;
    627         }
    628         frame.addItem(pic);
    629 
    630         return true;
    631     }
    632 
    633     /**
    634      * Creates an interactive widget and adds it to a frame. If txt has no
    635      * parent the parent will be set to frame.
    636      *
    637      * @param frame
    638      *            Frame to add widget to. Must not be null.
    639      *
    640      * @param txt
    641      *            Text to create the widget from. Must not be null.
    642      *
    643      * @return True if created/added. False if coul not create.
    644      *
    645      * @author Brook Novak
    646      */
    647     private static boolean createWidget(Frame frame, Text txt) {
    648 
    649         if (frame == null)
    650             throw new NullPointerException("frame");
    651         if (txt == null)
    652             throw new NullPointerException("txt");
    653 
    654         // Safety
    655         if (txt.getParent() == null)
    656             txt.setParent(frame);
    657 
    658         InteractiveWidget iw = null;
    659 
    660         try {
    661 
    662             iw = InteractiveWidget.createWidget(txt);
    663 
    664         } catch (InteractiveWidgetNotAvailableException e) {
    665             e.printStackTrace();
    666             MessageBay.errorMessage("Cannot create iWidget: " + e.getMessage());
    667         } catch (InteractiveWidgetInitialisationFailedException e) {
    668             e.printStackTrace();
    669             MessageBay.errorMessage("Cannot create iWidget: " + e.getMessage());
    670         } catch (IllegalArgumentException e) {
    671             e.printStackTrace();
    672             MessageBay.errorMessage("Cannot create iWidget: " + e.getMessage());
    673         }
    674 
    675         if (iw == null)
    676             return false;
    677 
    678         frame.removeItem(txt);
    679 
    680         frame.addAllItems(iw.getItems());
    681 
    682         return true;
    683     }
    684 
    685     public static Collection<String> ParseProfile(Frame profile) {
    686         Collection<String> errors = new LinkedList<String>();
    687         if (profile == null)
    688             return errors;
    689 
    690         /*
    691          * Make sure the correct cursor shows when turning off the custom cursor
    692          * and reparsing the profile frame
    693          */
    694         FreeItems.getCursor().clear();
    695         DisplayIO.setCursor(Item.HIDDEN_CURSOR);
    696         DisplayIO.setCursor(Item.DEFAULT_CURSOR);
    697 
    698         // check for settings tags
    699         for (Text item : profile.getBodyTextItems(true)) {
    700             try {
    701 
    702                 AttributeValuePair avp = new AttributeValuePair(item.getText());
    703                 String attributeFullCase = avp.getAttributeOrValue();
    704 
    705                 if (attributeFullCase == null) {
    706                     continue;
    707                 }
    708                 String attribute = attributeFullCase.trim().toLowerCase()
    709                         .replaceAll("^@", "");
    710 
    711                 if (attribute.equals("settings")) {
    712                     Settings.parseSettings(item);
    713                 }
    714 
    715             } catch (Exception e) {
    716                 if (e.getMessage() != null) {
    717                     errors.add(e.getMessage());
    718                 } else {
    719                     e.printStackTrace();
    720                     errors.add("Error parsing [" + item.getText() + "] on "
    721                             + profile.getName());
    722                 }
    723             }
    724         }
    725 
    726         return errors;
    727     }
    728 
    729     /**
    730      * Sets the first frame to be displayed.
    731      *
    732      * @param profile
    733      */
    734     public static void loadFirstFrame(Frame profile) {
    735         if (UserSettings.HomeFrame.get() == null)
    736             UserSettings.HomeFrame.set(profile.getName());
    737 
    738         Frame firstFrame = FrameIO.LoadFrame(UserSettings.HomeFrame.get());
    739         if (firstFrame == null) {
    740             MessageBay.warningMessage("Home frame not found: "
    741                     + UserSettings.HomeFrame);
    742             UserSettings.HomeFrame.set(profile.getName());
    743             DisplayIO.setCurrentFrame(profile, true);
    744         } else {
    745             DisplayIO.setCurrentFrame(firstFrame, true);
    746         }
    747 
    748     }
    749 
    750     public static Color[] getColorWheel(Frame frame) {
    751         if (frame != null) {
    752             List<Text> textItems = frame.getBodyTextItems(false);
    753             Color[] colorList = new Color[textItems.size() + 1];
    754             for (int i = 0; i < textItems.size(); i++) {
    755                 colorList[i] = textItems.get(i).getColor();
    756             }
    757             // Make the last item transparency or default for forecolor
    758             colorList[colorList.length - 1] = null;
    759 
    760             return colorList;
    761         }
    762         return new Color[] { Color.black, Color.white, null };
    763     }
    764 
    765     public static String getLink(Item item, String alt) {
    766         if (item == null || !(item instanceof Text))
    767             return alt;
    768 
    769         AttributeValuePair avp = new AttributeValuePair(item.getText());
    770         assert (avp != null);
    771 
    772         if (avp.hasPair() && avp.getValue().trim().length() != 0) {
    773             item.setLink(avp.getValue());
    774             return avp.getValue();
    775         } else if (item.getLink() != null) {
    776             return item.getAbsoluteLink();
    777         }
    778 
    779         return alt;
    780     }
    781 
    782     public static String getDir(String name) {
    783         if (name != null) {
    784             File tester = new File(name);
    785             if (tester.exists() && tester.isDirectory()) {
    786                 if (name.endsWith(File.separator))
    787                     return name;
    788                 else
    789                     return name + File.separator;
    790             } else {
    791                 throw new RuntimeException("Directory not found: " + name);
    792             }
    793         }
    794         throw new RuntimeException("Missing value for profile attribute" + name);
    795     }
    796 
    797     public static ArrayList<String> getDirs(Item item) {
    798         ArrayList<String> dirsToAdd = new ArrayList<String>();
    799         String dirListFrameName = item.getAbsoluteLink();
    800         if (dirListFrameName != null) {
    801             Frame dirListFrame = FrameIO.LoadFrame(dirListFrameName);
    802             if (dirListFrame != null) {
    803                 for (Text t : dirListFrame.getBodyTextItems(false)) {
    804                     String dirName = t.getText().trim();
    805                     File tester = new File(dirName);
    806                     if (tester.exists() && tester.isDirectory()) {
    807                         if (dirName.endsWith(File.separator))
    808                             dirsToAdd.add(dirName);
    809                         else
    810                             dirsToAdd.add(dirName + File.separator);
    811                     }
    812                 }
    813             }
    814         }
    815 
    816         return dirsToAdd;
    817     }
    818 
    819     public static void Parse(Frame toParse) {
    820         Parse(toParse, false);
    821     }
    822 
    823     /**
    824      * Checks for any special Annotation items and updates the display as
    825      * necessary. Special Items: Images, overlays, sort.
    826      *
    827      */
    828     public static void Parse(Frame toParse, boolean firstParse) {
    829         Parse(toParse, firstParse, false);
    830     }
    831 
    832     /**
    833      *
    834      * @param toParse
    835      * @param firstParse
    836      * @param ignoreAnnotations
    837      *            used to prevent infinate loops such as when performing TDFC
    838      *            with an ao tag linked to a frame with an frameImage of a frame
    839      *            which also has an ao tag on it.
    840      */
    841     public static void Parse(Frame toParse, boolean firstParse,
    842             boolean ignoreAnnotations) {
    843         // TODO check why we are getting toParse == null... when profile frame
    844         // is being created and change the lines below
    845         if (toParse == null)
    846             return;
    847         // System.out.println(firstParse);
    848         if (firstParse)
    849             ItemUtils.EnclosedCheck(toParse.getItems());
    850         List<Item> items = toParse.getItems();
    851 
    852         // if XRayMode is on, replace pictures with their underlying text
    853         if (FrameGraphics.isXRayMode()) {
    854 
    855             // BROOK: Must handle these a little different
    856             List<InteractiveWidget> widgets = toParse.getInteractiveWidgets();
    857 
    858             for (Item i : items) {
    859                 if (i instanceof XRayable) {
    860                     toParse.removeItem(i);
    861                     // Show the items
    862                     for (Item item : ((XRayable) i).getConnected()) {
    863                         item.setVisible(true);
    864                         item.removeEnclosure(i);
    865                     }
    866                 } else if (i instanceof WidgetCorner) {
    867                     toParse.removeItem(i);
    868                 } else if (i instanceof WidgetEdge) {
    869                     toParse.removeItem(i);
    870                 } else if (i.hasFormula()) {
    871                     i.setText(i.getFormula());
    872                 } else if (i.hasOverlay()) {
    873                     i.setVisible(true);
    874                     // int x = i.getBoundsHeight();
    875                 }
    876             }
    877 
    878             for (InteractiveWidget iw : widgets) {
    879                 toParse.addItem(iw.getSource());
    880             }
    881         }
    882 
    883         // Text title = null;
    884         // Text template = UserSettingsTemplate.copy();
    885 
    886         List<Overlay> overlays = new ArrayList<Overlay>();
    887         List<Vector> vectors = new ArrayList<Vector>();
    888 
    889         // disable reading of cached overlays if in twinframes mode
    890         if (DisplayIO.isTwinFramesOn())
    891             FrameIO.SuspendCache();
    892 
    893         DotType pointtype = DotType.square;
    894         boolean filledPoints = true;
    895 
    896         UserAppliedPermission permission = toParse.getUserAppliedPermission();
    897         toParse.clearAnnotations();
    898 
    899         // check for any new overlay items
    900         for (Item i : toParse.getItems()) {
    901             try {
    902                 // reset overlay permission
    903                 i.setOverlayPermission(null);
    904                 // i.setPermission(permission);
    905                 if (i instanceof WidgetCorner) {
    906                     // TODO improve efficiency so it only updates once... using
    907                     // observer design pattern
    908                     i.update();
    909                 } else if (i instanceof Text) {
    910                     if (i.isAnnotation()) {
    911                         if (ItemUtils.startsWithTag(i, ItemUtils.TAG_POINTTYPE)) {
    912                             Text txt = (Text) i;
    913                             String line = txt.getFirstLine();
    914                             line = ItemUtils.StripTag(line,
    915                                     ItemUtils.GetTag(ItemUtils.TAG_POINTTYPE));
    916 
    917                             if (line != null) {
    918                                 line = line.toLowerCase();
    919                                 if (line.indexOf(" ") > 0) {
    920                                     String fill = line.substring(line
    921                                             .indexOf(" ") + 1);
    922                                     if (fill.startsWith("nofill"))
    923                                         filledPoints = false;
    924                                     else
    925                                         filledPoints = true;
    926                                 }
    927 
    928                                 if (line.startsWith("circle"))
    929                                     pointtype = DotType.circle;
    930                                 else
    931                                     pointtype = DotType.square;
    932                             }
    933                         }// check for new VECTOR items
    934                         else if (!FrameGraphics.isXRayMode()
    935                                 && ItemUtils.startsWithTag(i,
    936                                         ItemUtils.TAG_VECTOR)
    937                                 && i.getLink() != null) {
    938                             if (!i.getAbsoluteLink().equals(toParse.getName()))
    939                                 addVector(vectors, UserAppliedPermission.none,
    940                                         permission, i);
    941                         } else if (!FrameGraphics.isXRayMode()
    942                                 && ItemUtils.startsWithTag(i,
    943                                         ItemUtils.TAG_ACTIVE_VECTOR)
    944                                 && i.getLink() != null) {
    945                             if (!i.getAbsoluteLink().equals(toParse.getName()))
    946                                 addVector(vectors,
    947                                         UserAppliedPermission.followLinks,
    948                                         permission, i);
    949                         }
    950                         // check for new OVERLAY items
    951                         else if (!ignoreAnnotations
    952                                 && ItemUtils.startsWithTag(i,
    953                                         ItemUtils.TAG_OVERLAY)
    954                                 && i.getLink() != null) {
    955                             if (i.getAbsoluteLink().equalsIgnoreCase(
    956                                     toParse.getName())) {
    957                                 // This frame contains an active overlay which
    958                                 // points to itself
    959                                 MessageBay
    960                                         .errorMessage(toParse.getName()
    961                                                 + " contains an @o which links to itself");
    962                                 continue;
    963                             }
    964 
    965                             Frame overlayFrame = FrameIO.LoadFrame(i
    966                                     .getAbsoluteLink());
    967                             // Parse(overlay);
    968                             if (overlayFrame != null
    969                                     && Overlay.getOverlay(overlays,
    970                                             overlayFrame) == null)
    971                                 overlays.add(new Overlay(overlayFrame,
    972                                         UserAppliedPermission.none));
    973                         }
    974                         // check for ACTIVE_OVERLAY items
    975                         else if (!ignoreAnnotations
    976                                 && ItemUtils.startsWithTag(i,
    977                                         ItemUtils.TAG_ACTIVE_OVERLAY)
    978                                 && i.getLink() != null) {
    979                             String link = i.getAbsoluteLink();
    980                             if (link.equalsIgnoreCase(toParse.getName())) {
    981                                 // This frame contains an active overlay which
    982                                 // points to itself
    983                                 MessageBay
    984                                         .errorMessage(toParse.getName()
    985                                                 + " contains an @ao which links to itself");
    986                                 continue;
    987                             }
    988                             Frame overlayFrame = null;
    989 
    990                             Frame current = DisplayIO.getCurrentFrame();
    991                             if (current != null) {
    992                                 for (Overlay o : current.getOverlays()) {
    993                                     if (o.Frame.getName()
    994                                             .equalsIgnoreCase(link))
    995                                         overlayFrame = o.Frame;
    996                                 }
    997                             }
    998                             if (overlayFrame == null)
    999                                 overlayFrame = FrameIO.LoadFrame(link);
    1000 
    1001                             // get level if specified
    1002                             String level = new AttributeValuePair(i.getText())
    1003                                     .getValue();
    1004                             // default permission (if none is specified)
    1005                             PermissionPair permissionLevel = new PermissionPair(
    1006                                     level, UserAppliedPermission.followLinks);
    1007 
    1008                             if (overlayFrame != null) {
    1009                                 Overlay existingOverlay = Overlay.getOverlay(
    1010                                         overlays, overlayFrame);
    1011                                 // If it wasn't in the list create it and add
    1012                                 // it.
    1013                                 if (existingOverlay == null) {
    1014                                     Overlay newOverlay = new Overlay(
    1015                                             overlayFrame,
    1016                                             permissionLevel
    1017                                                     .getPermission(overlayFrame
    1018                                                             .getOwner()));
    1019                                     i.setOverlay(newOverlay);
    1020                                     overlays.add(newOverlay);
    1021                                 } else {
    1022                                     existingOverlay.Frame
    1023                                             .setPermission(permissionLevel);
    1024                                 }
    1025                             }
    1026                         }
    1027                         // check for Images and widgets
    1028                         else {
    1029                             if (!FrameGraphics.isXRayMode()) {
    1030                                 if (ItemUtils.startsWithTag(i,
    1031                                         ItemUtils.TAG_IMAGE, true)) {
    1032                                     if (!i.hasEnclosures()) {
    1033                                         createPicture(toParse, (Text) i);
    1034                                     }
    1035                                     // check for frame images
    1036                                 } else if (ItemUtils.startsWithTag(i,
    1037                                         ItemUtils.TAG_FRAME_IMAGE)
    1038                                         && i.getLink() != null
    1039                                         && !i.getAbsoluteLink()
    1040                                                 .equalsIgnoreCase(
    1041                                                         toParse.getName())) {
    1042                                     XRayable image = null;
    1043                                     if (i.hasEnclosures()) {
    1044                                         // i.setHidden(true);
    1045                                         // image =
    1046                                         // i.getEnclosures().iterator().next();
    1047                                         // image.refresh();
    1048                                     } else {
    1049                                         image = new FrameImage((Text) i,
    1050                                                 toParse, null);
    1051                                     }
    1052                                     // TODO Add the image when creating new
    1053                                     // FrameImage
    1054                                     toParse.addItem(image);
    1055                                 } else if (ItemUtils.startsWithTag(i,
    1056                                         ItemUtils.TAG_BITMAP_IMAGE)
    1057                                         && i.getLink() != null
    1058                                         && !i.getAbsoluteLink()
    1059                                                 .equalsIgnoreCase(
    1060                                                         toParse.getName())) {
    1061                                     XRayable image = null;
    1062                                     if (i.hasEnclosures()) {
    1063                                         // image =
    1064                                         // i.getEnclosures().iterator().next();
    1065                                         // image.refresh();
    1066                                         // i.setHidden(true);
    1067                                     } else {
    1068                                         // If a new bitmap is created for a
    1069                                         // frame which already has a bitmap dont
    1070                                         // recreate the bitmap
    1071                                         image = new FrameBitmap((Text) i,
    1072                                                 toParse, null);
    1073                                     }
    1074                                     toParse.addItem(image);
    1075                                 } else if (ItemUtils.startsWithTag(i, "@c")) {
    1076                                     // Can only have a @c
    1077                                     if (!i.hasEnclosures()
    1078                                             && i.getLines().size() == 1) {
    1079                                         toParse.addItem(new Circle((Text) i));
    1080                                     }
    1081                                     // Check for JSItem
    1082                                 } else if(ItemUtils.startsWithTag(i, "@js")) {
    1083                                         toParse.addItem(new JSItem((Text) i));
    1084                                     // Check for interactive widgets
    1085                                 } else if (ItemUtils.startsWithTag(i,
    1086                                         ItemUtils.TAG_IWIDGET)) {
    1087                                     createWidget(toParse, (Text) i);
    1088                                 }
    1089                             }
    1090                             // TODO decide exactly what to do here!!
    1091                             toParse.addAnnotation((Text) i);
    1092                         }
    1093                     } else if (!FrameGraphics.isXRayMode() && i.hasFormula()) {
    1094                         i.calculate(i.getFormula());
    1095                     }
    1096                 }
    1097             } catch (Exception e) {
    1098                 Logger.Log(e);
    1099                 e.printStackTrace();
    1100                 MessageBay.warningMessage("Exception occured when loading "
    1101                         + i.getClass().getSimpleName() + "(ID: " + i.getID()
    1102                         + ") " + e.getMessage() != null ? e.getMessage() : "");
    1103             }
    1104         }
    1105 
    1106         /*
    1107          * for (Item i : items) { if (i instanceof Dot) { ((Dot)
    1108          * i).setPointType(pointtype); ((Dot) i).useFilledPoints(filledPoints);
    1109          * } }
    1110          */
    1111 
    1112         FrameIO.ResumeCache();
    1113 
    1114         toParse.clearOverlays();
    1115         toParse.clearVectors();
    1116         toParse.addAllOverlays(overlays);
    1117         toParse.addAllVectors(vectors);
    1118 
    1119     }
    1120 
    1121     /**
    1122      * @param vectors
    1123      * @param permission
    1124      * @param i
    1125      */
    1126     private static void addVector(List<Vector> vectors,
    1127             UserAppliedPermission defaultPermission,
    1128             UserAppliedPermission framePermission, Item i) {
    1129         // TODO It is possible to get into an infinate loop if a
    1130         // frame contains an @ao which leads to a frame with an
    1131         // @v which points back to the frame with the @ao
    1132         Frame vector = FrameIO.LoadFrame(i.getAbsoluteLink());
    1133 
    1134         // Get the permission from off the vector frame
    1135         UserAppliedPermission vectorPermission = UserAppliedPermission
    1136                 .getPermission(vector.getAnnotationValue("permission"),
    1137                         defaultPermission);
    1138         // If the frame permission is lower, use that
    1139         vectorPermission = UserAppliedPermission.min(vectorPermission,
    1140                 framePermission);
    1141         // Highest permissable permission for vectors is copy
    1142         vectorPermission = UserAppliedPermission.min(vectorPermission,
    1143                 UserAppliedPermission.copy);
    1144         if (vector != null) {
    1145             String scaleString = new AttributeValuePair(i.getText()).getValue();
    1146             Float scale = 1F;
    1147             try {
    1148                 scale = Float.parseFloat(scaleString);
    1149             } catch (Exception e) {
    1150             }
    1151             Vector newVector = new Vector(vector, vectorPermission, scale, i);
    1152             i.setOverlay(newVector);
    1153             i.setVisible(false);
    1154             vectors.add(newVector);
    1155         }
    1156     }
    1157 
    1158     public static Item onItem(float floatX, float floatY,
    1159             boolean changeLastEdited) {
    1160         return onItem(DisplayIO.getCurrentFrame(), floatX, floatY,
    1161                 changeLastEdited);
    1162     }
    1163 
    1164     /**
    1165      * Searches through the list of items on this frame to find one at the given
    1166      * x,y coordinates.
    1167      *
    1168      * @param x
    1169      *            The x coordinate
    1170      * @param y
    1171      *            The y coordinate
    1172      * @return The Item at the given coordinates, or NULL if none is found.
    1173      */
    1174     public static Item onItem(Frame toCheck, float floatX, float floatY,
    1175             boolean bResetLastEdited) {
    1176         // System.out.println("MouseX: " + floatX + " MouseY: " + floatY);
    1177         int x = Math.round(floatX);
    1178         int y = Math.round(floatY);
    1179         if (toCheck == null)
    1180             return null;
    1181 
    1182         List<Item> possibles = new ArrayList<Item>(0);
    1183 
    1184         // if the mouse is in the message area
    1185         if (y > FrameGraphics.getMaxFrameSize().getHeight()) {
    1186             // check the individual message items
    1187             for (Item message : MessageBay.getMessages()) {
    1188                 if (message != null) {
    1189                     if (message.contains(x, y)) {
    1190                         message.setOverlayPermission(UserAppliedPermission.copy);
    1191                         possibles.add(message);
    1192                     } else {
    1193                         // Not sure why but if the line below is removed then
    1194                         // several items can be highlighted at once
    1195                         message.setHighlightMode(Item.HighlightMode.None);
    1196                     }
    1197                 }
    1198             }
    1199 
    1200             // check the link to the message frame
    1201             if (MessageBay.getMessageLink() != null) {
    1202                 if (MessageBay.getMessageLink().contains(x, y)) {
    1203                     MessageBay.getMessageLink().setOverlayPermission(
    1204                             UserAppliedPermission.copy);
    1205                     possibles.add(MessageBay.getMessageLink());
    1206                 }
    1207             }
    1208 
    1209             // this is taken into account in contains
    1210             // y -= FrameGraphics.getMaxFrameSize().height;
    1211             // otherwise, the mouse is on the frame
    1212         } else {
    1213             if (LastEdited != null) {
    1214                 if (LastEdited.contains(x, y)
    1215                         && !FreeItems.getInstance().contains(LastEdited)
    1216                         && LastEdited.getParent() == DisplayIO
    1217                                 .getCurrentFrame()
    1218                         && LastEdited.getParent().getItems()
    1219                                 .contains(LastEdited)) {
    1220                     LastEdited.setOverlayPermission(UserAppliedPermission.full);
    1221                     return LastEdited;
    1222                 } else if (bResetLastEdited) {
    1223                     setLastEdited(null);
    1224                 }
    1225             }
    1226             ArrayList<Item> checkList = new ArrayList<Item>();
    1227             checkList.addAll(toCheck.getInteractableItems());
    1228             checkList.add(toCheck.getNameItem());
    1229            
    1230             for (Item i : checkList) {
    1231                        
    1232                 // do not check annotation items in audience mode
    1233             //TODO: Upon hover of Rubbish Bin, Undo and Restore Widgets, flickering occurs depending on the mouse distance from a corner. Resolve this.
    1234                 if (i.isVisible()
    1235                         && !(FrameGraphics.isAudienceMode() && i.isAnnotation())) {
    1236                         if(i instanceof WidgetCorner){
    1237                                 WidgetCorner wc = (WidgetCorner)i;
    1238                                 if(wc.getWidgetSource() instanceof ButtonWidget){
    1239                                         ButtonWidget bw = (ButtonWidget) wc.getWidgetSource();
    1240                                        
    1241                                         if(bw.getdropInteractableStatus() == true){
    1242                                                 InteractiveWidget iw = wc.getWidgetSource();
    1243                                                
    1244                                                 if(iw.getBounds().contains(x, y)){
    1245                                                        
    1246                                                         if( !FreeItems.getInstance().contains(i))
    1247                                                 {
    1248                                                                 possibles.add(i);                                                       
    1249                                                 }
    1250                                                 }       
    1251                                         }
    1252                                        
    1253                                 }
    1254                                
    1255                 }
    1256 
    1257                     if (i.contains(x, y)){
    1258                         if( !FreeItems.getInstance().contains(i))
    1259                         {
    1260                                 possibles.add(i);                               
    1261                         }
    1262                     }
    1263                            
    1264                 }
    1265             }
    1266         }
    1267 
    1268         // if there are no possible items, return null
    1269         if (possibles.size() == 0)
    1270             return null;
    1271 
    1272         // if there is only one possibility, return it
    1273         if (possibles.size() == 1)
    1274             return possibles.get(0);
    1275        
    1276         // return closest x,y pair to mouse
    1277         Item closest = possibles.get(0);
    1278         int distance = (int) Math.round(Math.sqrt(Math.pow(
    1279                 Math.abs(closest.getX() - x), 2)
    1280                 + Math.pow(Math.abs(closest.getY() - y), 2)));
    1281 
    1282         for (Item i : possibles) {
    1283             int d = (int) Math.round(Math.sqrt(Math.pow(Math.abs(i.getX() - x),
    1284                     2) + Math.pow(Math.abs(i.getY() - y), 2)));
    1285 
    1286             // System.out.println(d);
    1287             if (d <= distance) {
    1288                 distance = d;
    1289 
    1290                 // dots take precedence over lines
    1291                 if ((!(closest instanceof Dot && i instanceof Line))
    1292                         && (!(closest instanceof Text && i instanceof Line)))
    1293                     closest = i;
    1294 
    1295             }
    1296 
    1297         }       
    1298 
    1299         return closest;
    1300     }
    1301 
    1302     public synchronized static Item getCurrentItem() {
    1303         return onItem(DisplayIO.getCurrentFrame(), DisplayIO.getMouseX(),
    1304                 FrameMouseActions.getY(), true);
    1305     }
    1306 
    1307     public static Polygon getEnlosingPolygon() {
    1308         Collection<Item> enclosure = getEnclosingLineEnds();
    1309         if (enclosure == null || enclosure.size() == 0)
    1310             return null;
    1311 
    1312         return enclosure.iterator().next().getEnclosedShape();
    1313     }
    1314 
    1315     /**
    1316      *
    1317      * @param currentItem
    1318      * @return
    1319      */
    1320     public static Collection<Item> getCurrentItems() {
    1321         return getCurrentItems(getCurrentItem());
    1322     }
    1323 
    1324     public static Collection<Item> getCurrentItems(Item currentItem) {
    1325 
    1326         Collection<Item> enclosure = getEnclosingLineEnds();
    1327         if (enclosure == null || enclosure.size() == 0)
    1328             return null;
    1329 
    1330         Item firstItem = enclosure.iterator().next();
    1331 
    1332         Collection<Item> enclosed = getItemsEnclosedBy(
    1333                 DisplayIO.getCurrentFrame(), firstItem.getEnclosedShape());
    1334 
    1335         // Brook: enclosed widgets are to be fully enclosed, never partially
    1336         /*
    1337          * MIKE says: but doesnt this mean that widgets are treated differently
    1338          * from ALL other object which only need to be partially enclosed to be
    1339          * picked up
    1340          */
    1341         List<InteractiveWidget> enclosedWidgets = new LinkedList<InteractiveWidget>();
    1342         for (Item i : enclosed) {
    1343             // Don't want to lose the highlighting from the current item
    1344             if (i == currentItem || enclosure.contains(i)) {
    1345                 continue;
    1346             }
    1347             // Don't want to lose the highlighting of connected Dots
    1348             if (i instanceof Dot
    1349                     && i.getHighlightMode() == HighlightMode.Connected) {
    1350                 for (Line l : i.getLines()) {
    1351                     if (l.getOppositeEnd(i).getHighlightMode() == HighlightMode.Normal) {
    1352                         continue;
    1353                     }
    1354                 }
    1355             }
    1356             if (i instanceof WidgetCorner) {
    1357                 if (!enclosedWidgets.contains(((WidgetCorner) i)
    1358                         .getWidgetSource()))
    1359                     enclosedWidgets.add(((WidgetCorner) i).getWidgetSource());
    1360             }
    1361             i.setHighlightMode(Item.HighlightMode.None);
    1362         }
    1363 
    1364         for (InteractiveWidget iw : enclosedWidgets) {
    1365             for (Item i : iw.getItems()) {
    1366                 if (!enclosed.contains(i)) {
    1367                     enclosed.add(i);
    1368                 }
    1369             }
    1370         }
    1371 
    1372         return enclosed;
    1373     }
    1374 
    1375     public static Collection<Item> getEnclosingLineEnds() {
    1376         return getEnclosingLineEnds(new Point(DisplayIO.getMouseX(),
    1377                 FrameMouseActions.getY()));
    1378     }
    1379 
    1380     public static Collection<Item> getEnclosingLineEnds(Point position) {
    1381         // update enclosed shapes
    1382         Frame current = DisplayIO.getCurrentFrame();
    1383         List<Item> items = current.getItems();
    1384 
    1385         // Remove all items that are connected to freeItems
    1386         List<Item> freeItems = new ArrayList<Item>(FreeItems.getInstance());
    1387         while (freeItems.size() > 0) {
    1388             Item item = freeItems.get(0);
    1389             Collection<Item> connected = item.getAllConnected();
    1390             items.removeAll(connected);
    1391             freeItems.removeAll(connected);
    1392         }
    1393 
    1394         List<Item> used = new ArrayList<Item>(0);
    1395 
    1396         while (items.size() > 0) {
    1397             Item i = items.get(0);
    1398             items.remove(i);
    1399             if (i.isEnclosed()) {
    1400                 Polygon p = i.getEnclosedShape();
    1401                 if (p.contains(position.x, position.y)) {
    1402                     used.add(i);
    1403                     items.removeAll(i.getEnclosingDots());
    1404                 }
    1405             }
    1406         }
    1407 
    1408         if (used.size() == 0)
    1409             return null;
    1410 
    1411         // if there is only one possibility, return it
    1412         if (used.size() == 1) {
    1413             return used.get(0).getEnclosingDots();
    1414             // otherwise, determine which polygon is closest to the cursor
    1415         } else {
    1416             Collections.sort(used, new Comparator<Item>() {
    1417                 public int compare(Item d1, Item d2) {
    1418                     Polygon p1 = d1.getEnclosedShape();
    1419                     Polygon p2 = d2.getEnclosedShape();
    1420 
    1421                     int closest = Integer.MAX_VALUE;
    1422                     int close2 = Integer.MAX_VALUE;
    1423 
    1424                     int mouseX = DisplayIO.getMouseX();
    1425                     int mouseY = FrameMouseActions.getY();
    1426 
    1427                     for (int i = 0; i < p1.npoints; i++) {
    1428                         int diff = Math.abs(p1.xpoints[i] - mouseX)
    1429                                 + Math.abs(p1.ypoints[i] - mouseY);
    1430                         int diff2 = Integer.MAX_VALUE;
    1431 
    1432                         if (i < p2.npoints)
    1433                             diff2 = Math.abs(p2.xpoints[i] - mouseX)
    1434                                     + Math.abs(p2.ypoints[i] - mouseY);
    1435 
    1436                         if (diff < Math.abs(closest)) {
    1437                             close2 = closest;
    1438                             closest = diff;
    1439                         } else if (diff < Math.abs(close2))
    1440                             close2 = diff;
    1441 
    1442                         if (diff2 < Math.abs(closest)) {
    1443                             close2 = closest;
    1444                             closest = -diff2;
    1445                         } else if (diff2 < Math.abs(close2))
    1446                             close2 = diff2;
    1447                     }
    1448 
    1449                     if (closest > 0 && close2 > 0)
    1450                         return -10;
    1451 
    1452                     if (closest < 0 && close2 < 0)
    1453                         return 10;
    1454 
    1455                     if (closest > 0)
    1456                         return -10;
    1457 
    1458                     return 10;
    1459                 }
    1460 
    1461             });
    1462 
    1463             return used.get(0).getEnclosingDots();
    1464         }
    1465     }
    1466 
    1467     // TODO Remove this method!!
    1468     // Can just getItemsWithin be used?
    1469     public static Collection<Item> getItemsEnclosedBy(Frame frame, Polygon poly) {
    1470         Collection<Item> contained = frame.getItemsWithin(poly);
    1471 
    1472         Collection<Item> results = new LinkedHashSet<Item>(contained.size());
    1473 
    1474         // check for correct permissions
    1475         for (Item item : contained) {
    1476             // if the item is on the frame
    1477             if (item.getParent() == frame || item.getParent() == null) {
    1478                 // item.Permission = Permission.full;
    1479                 results.add(item);
    1480                 // otherwise, it must be on an overlay frame
    1481             } else {
    1482                 for (Overlay overlay : frame.getOverlays()) {
    1483                     if (overlay.Frame == item.getParent()) {
    1484                         item.setOverlayPermission(overlay.permission);
    1485                         results.add(item);
    1486                         break;
    1487                     }
    1488                 }
    1489             }
    1490         }
    1491 
    1492         return results;
    1493     }
    1494 
    1495     /**
    1496      * Fills the given Frame with default profile tags
    1497      */
    1498     public static void CreateDefaultProfile(String username, Frame profile) {
    1499         Text title = profile.getTitleItem();
    1500         if (username.equals(UserSettings.DEFAULT_PROFILE_NAME)) {
    1501             title.setText("Default Profile Frame");
    1502         } else {
    1503             // if this profile is not the default profile, copy it from the default profile instead of generating a new profile
    1504                 // (this allows the possibility of modifying the default profile and having any new profiles get those modifications)
    1505                 Frame nextDefault = FrameIO.LoadProfile(UserSettings.DEFAULT_PROFILE_NAME);
    1506                 if (nextDefault == null) {
    1507                         try {
    1508                                 nextDefault = FrameIO.CreateNewProfile(UserSettings.DEFAULT_PROFILE_NAME);
    1509                         } catch (Exception e) {
    1510                                 // TODO tell the user that there was a problem creating the
    1511                                 // profile frame and close nicely
    1512                                 e.printStackTrace();
    1513                         }
    1514                 }
    1515                 // load profile frame and set title correctly
    1516                 profile.reset();
    1517                 profile.removeAllItems(profile.getAllItems());
    1518                 // set relative link on all items so their links will correctly point to the page on the current profile rather than on the default profile
    1519                 for(Item i : nextDefault.getAllItems()) {
    1520                         i.setRelativeLink();
    1521                 }
    1522                 profile.addAllItems(ItemUtils.CopyItems(nextDefault.getAllItems()));
    1523                 profile.setTitle(username + "'s Profile Frame");
    1524                 FrameIO.SaveFrame(profile);
     1823                if(!force && check.exists()) return;
    15251824               
    1526                 Frame nextProfile = profile;
    1527                 MessageBay.suppressMessages(true);
    1528                 while((nextDefault = FrameIO.LoadNext(nextDefault)) != null) {
    1529                         // in case there are gaps in the frame numbering of the default profile (e.g. if a user has edited it),
    1530                         // we need to replicate those gaps in the copied profile so the links will work correctly
    1531                         while(nextProfile.getNumber() < nextDefault.getNumber()) {
    1532                                 nextProfile = FrameIO.CreateFrame(profile.getFramesetName(), null, null);
    1533                         }
    1534                         // if the new profile has a frame number higher than the current frame number in the default profile,
    1535                         // the new profile must already exist, so just exit
    1536                         // (TODO: should we wipe the frames instead?)
    1537                         if(nextProfile.getNumber() > nextDefault.getNumber()) {
    1538                                 break;
    1539                         }
    1540                         nextProfile.reset();
    1541                 nextProfile.removeAllItems(nextProfile.getAllItems());
    1542                 // set relative link on all items so their links will correctly point to the page on the current profile rather than on the default profile
    1543                 for(Item i : nextDefault.getAllItems()) {
    1544                         i.setRelativeLink();
    1545                 }
    1546                 nextProfile.addAllItems(ItemUtils.CopyItems(nextDefault.getAllItems()));
    1547                 FrameIO.SaveFrame(nextProfile);
    1548                 }
    1549                 MessageBay.suppressMessages(false);
     1825                System.out.println("Extracting/Installing resources:");
    15501826               
    1551                 return;
    1552         }
    1553 
    1554         // int spacing = 50;
    1555         final int intialYPos = 75;
    1556         int xPos = 75;
    1557         int yPos = intialYPos;
    1558 
    1559         // yPos += spacing;
    1560         // profile.addText(xPos, yPos, "@HomeFrame", null, profile.getName());
    1561         // yPos += spacing;
    1562         // String defaultFrameName = profile.getFramesetName() + "0";
    1563         // profile.addText(xPos, yPos, "@DefaultFrame", null, defaultFrameName);
    1564         // yPos += spacing;
    1565         //
    1566         // profile.addText(xPos, yPos, "@InitialWidth: "
    1567         // + UserSettings.InitialWidth, null);
    1568         // yPos += spacing;
    1569         //
    1570         // profile.addText(xPos, yPos, "@InitialHeight: "
    1571         // + UserSettings.InitialHeight, null);
    1572         // yPos += spacing;
    1573         //
    1574         // Text t = profile.addText(xPos, yPos, "@ItemTemplate", null);
    1575         // t.setColor(null);
    1576         //
    1577         // yPos += spacing;
    1578         // t = profile.addText(xPos, yPos, "@AnnotationTemplate", null);
    1579         // t.setColor(Color.gray);
    1580         //
    1581         // yPos += spacing;
    1582         // t = profile.addText(xPos, yPos, "@CommentTemplate", null);
    1583         // t.setColor(Color.green.darker());
    1584         //
    1585         // yPos += spacing;
    1586         // t = profile.addText(xPos, yPos, "@StatsTemplate", null);
    1587         // t.setColor(Color.BLACK);
    1588         // t.setBackgroundColor(new Color(0.9F, 0.9F, 0.9F));
    1589         // t.setFamily(Text.MONOSPACED_FONT);
    1590         // t.setSize(14);
    1591 
    1592         Text t;
    1593 
    1594         xPos = 300;
    1595         // yPos = intialYPos + spacing;
    1596         yPos = 100;
    1597 
    1598         // Add documentation links
    1599         File helpDirectory = new File(FrameIO.HELP_PATH);
    1600         if (helpDirectory != null) {
    1601             File[] helpFramesets = helpDirectory.listFiles();
    1602             if (helpFramesets != null) {
    1603 
    1604                 // Add the title for the help index
    1605                 Text help = profile.addText(xPos, yPos, "@Expeditee Help", null);
    1606                 help.setSize(25);
    1607                 help.setFontStyle("Bold");
    1608                 help.setFamily("SansSerif");
    1609                 help.setColor(TemplateSettings.ColorWheel.get()[3]);
    1610 
    1611                 xPos += 25;
    1612                 System.out.println("Installing frameset: ");
    1613 
    1614                 boolean first_item = true;
    1615 
    1616                 for (File helpFrameset : helpFramesets) {
    1617                     String framesetName = helpFrameset.getName();
    1618                     if (!FrameIO.isValidFramesetName(framesetName)) {
    1619                         continue;
    1620                     }
    1621 
    1622                     if (first_item) {
    1623                         System.out.print("  " + framesetName);
    1624                         first_item = false;
    1625                     }
    1626                     else {
    1627                         System.out.print(", " + framesetName);
    1628                     }
    1629                     System.out.flush();
    1630 
    1631                     Frame indexFrame = FrameIO.LoadFrame(framesetName + '1');
    1632                     // Look through the folder for help index pages
    1633                     if (indexFrame != null
    1634                             && ItemUtils.FindTag(indexFrame.getItems(),
    1635                                     "@HelpIndex") != null) {
    1636                         // yPos += spacing;
    1637                         yPos += 30;
    1638                         t = profile.addText(xPos, yPos,
    1639                                 '@' + indexFrame.getFramesetName(), null);
    1640                         t.setLink(indexFrame.getName());
    1641                         t.setColor(Color.gray);
    1642                     }
    1643                 }
    1644                 System.out.println();
    1645             }
    1646         }
    1647 
    1648         xPos = 50;
    1649         yPos = 100;
    1650 
    1651         // Populate Start Pages and Settings
    1652         File framesetDirectory = new File(FrameIO.FRAME_PATH);
    1653 
    1654         if (framesetDirectory.exists()) {
    1655             File[] startpagesFramesets = framesetDirectory.listFiles();
    1656 
    1657             if (startpagesFramesets != null) {
    1658                 // Add Start Page title
    1659                 Text templates = profile.addText(xPos, yPos, "@Start Pages",
    1660                         null);
    1661                 templates.setSize(25);
    1662                 templates.setFontStyle("Bold");
    1663                 templates.setFamily("SansSerif");
    1664                 templates.setColor(TemplateSettings.ColorWheel.get()[3]);
    1665 
    1666                 xPos += 25;
    1667 
    1668                 // Start Pages should be the first frame in its own frameset +
    1669                 // frameset name should be present in FrameUtils.startPages[].
    1670                 for (File startpagesFrameset : startpagesFramesets) {
    1671                     String framesetName = startpagesFrameset.getName();
    1672 
    1673                     // Only add link if frameset is a startpage
    1674                     for (int i = 0; i < startPages.length; i++) {
    1675                         if (framesetName.equals(startPages[i])) {
    1676                             Frame indexFrame = FrameIO
    1677                                     .LoadFrame(framesetName + '1');
    1678 
    1679                             // Add start page link
    1680                             if (indexFrame != null) {
    1681                                 yPos += 30;
    1682                                 t = profile.addText(xPos, yPos,
    1683                                         '@' + indexFrame.getFramesetName(),
    1684                                         null);
    1685                                 t.setLink(indexFrame.getName());
    1686                                 t.setColor(Color.gray);
    1687                             }
    1688                         }
    1689                     }
    1690                 }
    1691             }
    1692         }
    1693 
    1694         FrameIO.SaveFrame(profile);
    1695 
    1696         // Populate settings frameset
    1697         Settings.Init();
    1698         t = profile.addText(550, 100, "@Settings", null);
    1699         t.setSize((float) 25.0);
    1700         t.setFamily("SansSerif");
    1701         t.setFontStyle("Bold");
    1702         t.setColor(Color.gray);
    1703         Settings.generateSettingsTree(t);
    1704 
    1705         FrameIO.SaveFrame(profile);
    1706     }
    1707 
    1708     private static void checkTDFCItemWaiting(Frame currentFrame) {
    1709         Item tdfcItem = FrameUtils.getTdfcItem();
    1710         // if there is a TDFC Item waiting
    1711         if (tdfcItem != null) {
    1712             boolean change = currentFrame.hasChanged();
    1713             boolean saved = currentFrame.isSaved();
    1714             // Save the parent of the item if it has not been saved
    1715             if (!change && !saved) {
    1716                 tdfcItem.setLink(null);
    1717                 tdfcItem.getParent().setChanged(true);
    1718                 FrameIO.SaveFrame(tdfcItem.getParent());
    1719                 FrameGraphics.Repaint();
    1720             } else {
    1721                 SessionStats.CreatedFrame();
    1722             }
    1723 
    1724             setTdfcItem(null);
    1725         }
    1726     }
    1727 
    1728     public static void setTdfcItem(Item _tdfcItem) {
    1729         FrameUtils._tdfcItem = _tdfcItem;
    1730     }
    1731 
    1732     public static Item getTdfcItem() {
    1733         return FrameUtils._tdfcItem;
    1734     }
    1735 
    1736     private static Item _tdfcItem = null;
    1737 
    1738     public static void setLastEdited(Text lastEdited) {
    1739 
    1740         // If the lastEdited is being changed then check if its @i
    1741         Frame toReparse = null;
    1742         Frame toRecalculate = null;
    1743         Frame toUpdateObservers = null;
    1744 
    1745         if (LastEdited == null) {
    1746             // System.out.print("N");
    1747         } else if (LastEdited != null) {
    1748             // System.out.print("T");
    1749             Frame parent = LastEdited.getParentOrCurrentFrame();
    1750 
    1751             if (lastEdited != LastEdited) {
    1752                 if (LastEdited.startsWith("@i")) {
    1753                     // Check if its an image that can be resized to fit a box
    1754                     // around it
    1755                     String text = LastEdited.getText();
    1756                     if (text.startsWith("@i:")
    1757                             && !Character
    1758                                     .isDigit(text.charAt(text.length() - 1))) {
    1759                         Collection<Item> enclosure = FrameUtils
    1760                                 .getEnclosingLineEnds(LastEdited.getPosition());
    1761                         if (enclosure != null) {
    1762                             for (Item i : enclosure) {
    1763                                 if (i.isLineEnd() && i.isEnclosed()) {
    1764                                     DisplayIO.getCurrentFrame().removeAllItems(
    1765                                             enclosure);
    1766                                     Rectangle rect = i.getEnclosedRectangle();
    1767                                     LastEdited
    1768                                             .setText(LastEdited.getText()
    1769                                                     + " "
    1770                                                     + Math.round(rect
    1771                                                             .getWidth()));
    1772                                     LastEdited.setPosition(new Point(rect.x,
    1773                                             rect.y));
    1774                                     LastEdited.setThickness(i.getThickness());
    1775                                     LastEdited.setBorderColor(i.getColor());
    1776                                     break;
    1777                                 }
    1778                             }
    1779                             FrameMouseActions.deleteItems(enclosure, false);
    1780                         }
    1781                     }
    1782                     toReparse = parent;
    1783                 } else if (LastEdited.recalculateWhenChanged()) {
    1784                     toRecalculate = parent;
    1785                 }
    1786 
    1787                 if (parent.hasObservers()) {
    1788                     toUpdateObservers = parent;
    1789                 }
    1790                 // Update the formula if in XRay mode
    1791                 if (FrameGraphics.isXRayMode() && LastEdited.hasFormula()) {
    1792                     LastEdited.setFormula(LastEdited.getText());
    1793                 }
    1794             }
    1795             if (lastEdited != LastEdited && LastEdited.getText().length() == 0) {
    1796                 parent.removeItem(LastEdited);
    1797             }
    1798         }
    1799         LastEdited = lastEdited;
    1800 
    1801         if (!FrameGraphics.isXRayMode()) {
    1802             if (toReparse != null) {
    1803                 Parse(toReparse, false, false);
    1804             } else {
    1805                 if (toRecalculate != null) {
    1806                     toRecalculate.recalculate();
    1807                 }
    1808 
    1809                 if (toUpdateObservers != null) {
    1810                     toUpdateObservers.notifyObservers(false);
    1811                 }
    1812             }
    1813         }
    1814     }
    1815 
    1816     /**
    1817      * Extracts files/folders from the assets/resources folder directly into
    1818      * ${PARENT_FOLDER} (~/.expeditee)
    1819      *
    1820      * @param force if true, resources will be extracted even if they have already been extracted before
    1821      */
    1822     public static void extractResources(boolean force) {
    1823         File check = new File(FrameIO.PARENT_FOLDER + ".res");
    1824         if(!force && check.exists()) {
    1825                 return;
    1826         }
    1827                 System.out.println("Extracting/Installing resources:");
    18281827                try     {
    18291828                        check.getParentFile().mkdirs();
    1830                 check.createNewFile();
    1831                
     1829                        check.createNewFile();
     1830
    18321831                        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    18331832                        URL docURL = classLoader.getResource("org/expeditee/assets/resources");
    1834                        
     1833
    18351834                        // copy files from the jar file to the profile folder
    18361835                        if (docURL.getProtocol().equals("jar")) {
     
    18401839                                String res = "org/expeditee/assets/resources/";
    18411840                                int resLength = res.length();
    1842                                
     1841
    18431842                                ZipEntry ze;
    1844                                
     1843
    18451844                                while(jarEntries.hasMoreElements()) {
    18461845                                        ze = jarEntries.nextElement();
     
    18501849                                        File out = new File(FrameIO.PARENT_FOLDER + ze.getName().substring(resLength));
    18511850                                        // System.out.println("Didn't crash here " + out.getPath());
    1852 //                                      if(out.exists()) {
    1853 //                                              continue;
    1854 //                                      }
     1851                                        //                                      if(out.exists()) {
     1852                                        //                                              continue;
     1853                                        //                                      }
    18551854                                        if(ze.isDirectory()) {
    18561855                                                // System.out.println(out.getPath() + " IS DIRECTORY");
     
    18811880                                        }
    18821881                                }
    1883                                
    1884                         // Copy files from the source folder to the profile folder
     1882
     1883                                // Copy files from the source folder to the profile folder
    18851884                        } else if (docURL.getProtocol().equals("bundleresource")) {
    18861885                                final URLConnection urlConnection = docURL.openConnection();
     
    18991898        }
    19001899
    1901     private static void extractResourcesFromFolder(File folder) throws IOException {
    1902         LinkedList<File> items = new LinkedList<File>();
    1903         items.addAll(Arrays.asList(folder.listFiles()));
    1904         LinkedList<File> files = new LinkedList<File>();
    1905         String res = "org" + File.separator + "expeditee" + File.separator + "assets" + File.separator + "resources";
    1906         int resLength = res.length();
    1907        
    1908         while (items.size() > 0) {
    1909                 File file = items.remove(0);
    1910                 if(file.isFile()) {
    1911                         if(!file.getName().contains(".svn")) {
    1912                                 files.add(file);
    1913                         }
    1914                 } else {
    1915                         if (!file.getName().contains(".svn")) {
    1916                                 items.addAll(Arrays.asList(file.listFiles()));
    1917                         }
    1918                 }
    1919         }
    1920         for (File file : files) {
    1921                 System.out.println(file.getPath());
    1922                 File out = new File(FrameIO.PARENT_FOLDER + file.getPath().substring(file.getPath().indexOf(res) + resLength));
    1923 //              if(out.exists()) {
    1924 //                      continue;
    1925 //              }
    1926                 copyFile(file, out, true);
    1927         }
    1928     }
    1929    
    1930     /**
    1931      * @param src
    1932      * @param dst
    1933      * @throws IOException
    1934      */
    1935     public static void copyFile(File src, File dst, boolean overWrite) throws IOException {
    1936         if(!overWrite && dst.exists())
    1937                 return;
    1938         dst.getParentFile().mkdirs();
     1900        private static void extractResourcesFromFolder(File folder) throws IOException
     1901        {
     1902                LinkedList<File> items = new LinkedList<File>();
     1903                items.addAll(Arrays.asList(folder.listFiles()));
     1904                LinkedList<File> files = new LinkedList<File>();
     1905                String res = "org" + File.separator + "expeditee" + File.separator + "assets" + File.separator + "resources";
     1906                int resLength = res.length();
     1907
     1908                while (items.size() > 0) {
     1909                        File file = items.remove(0);
     1910                        if(file.isFile()) {
     1911                                if(!file.getName().contains(".svn")) {
     1912                                        files.add(file);
     1913                                }
     1914                        } else {
     1915                                if (!file.getName().contains(".svn")) {
     1916                                        items.addAll(Arrays.asList(file.listFiles()));
     1917                                }
     1918                        }
     1919                }
     1920                for (File file : files) {
     1921                        System.out.println(file.getPath());
     1922                        File out = new File(FrameIO.PARENT_FOLDER + file.getPath().substring(file.getPath().indexOf(res) + resLength));
     1923                        //              if(out.exists()) {
     1924                        //                      continue;
     1925                        //              }
     1926                        copyFile(file, out, true);
     1927                }
     1928        }
     1929
     1930        /**
     1931         * @param src
     1932         * @param dst
     1933         * @throws IOException
     1934         */
     1935        public static void copyFile(File src, File dst, boolean overWrite) throws IOException
     1936        {
     1937                if(!overWrite && dst.exists()) return;
     1938               
     1939                dst.getParentFile().mkdirs();
    19391940                FileOutputStream fOut = null;
    19401941                FileInputStream fIn = null;
     
    19591960                        }
    19601961                }
    1961     }
    1962 
    1963     public static Text getLastEdited() {
    1964         return LastEdited;
    1965     }
    1966 
    1967     public static Collection<Text> getCurrentTextItems() {
    1968         Collection<Text> currentTextItems = new LinkedHashSet<Text>();
    1969         Collection<Item> currentItems = getCurrentItems(null);
    1970         if (currentItems != null) {
    1971             for (Item i : getCurrentItems(null)) {
    1972                 if (i instanceof Text && !i.isLineEnd()) {
    1973                     currentTextItems.add((Text) i);
    1974                 }
    1975             }
    1976         }
    1977         return currentTextItems;
    1978     }
     1962        }
     1963
     1964        public static Text getLastEdited()
     1965        {
     1966                return LastEdited;
     1967        }
     1968
     1969        public static Collection<Text> getCurrentTextItems()
     1970        {
     1971                Collection<Text> currentTextItems = new LinkedHashSet<Text>();
     1972                Collection<Item> currentItems = getCurrentItems(null);
     1973                if (currentItems != null) {
     1974                        for (Item i : getCurrentItems(null)) {
     1975                                if (i instanceof Text && !i.isLineEnd()) {
     1976                                        currentTextItems.add((Text) i);
     1977                                }
     1978                        }
     1979                }
     1980                return currentTextItems;
     1981        }
    19791982}
  • trunk/src/org/expeditee/gui/FreeItems.java

    r919 r1102  
    1919package org.expeditee.gui;
    2020
    21 import java.awt.Polygon;
    2221import java.util.ArrayList;
    2322import java.util.Collection;
     
    2928import java.util.Map;
    3029
     30import org.expeditee.core.bounds.PolygonBounds;
    3131import org.expeditee.items.Dot;
    3232import org.expeditee.items.Item;
     
    4242        private static FreeItems _cursor = new FreeItems();
    4343
    44         private FreeItems() {
    45         }
    46 
    47         public static FreeItems getCursor() {
     44        public static FreeItems getCursor()
     45        {
    4846                return _cursor;
    4947        }
    5048       
    51         public static FreeItems getInstance() {
     49        public static FreeItems getInstance()
     50        {
    5251                return _instance;
    5352        }
    5453
    55         @Override
    56         public void clear() {
     54        /** Singleton class (although there are two of them). */
     55        private FreeItems()
     56        {
     57        }
     58       
     59        @Override
     60        public void clear()
     61        {
    5762                for (Item i : this) {
    5863                        i.invalidateAll();
     
    6368
    6469        @Override
    65         public Item remove(int index) {
     70        public Item remove(int index)
     71        {
    6672                Item i = get(index);
    6773                remove(i);
     
    7076
    7177        @Override
    72         public boolean remove(Object o) {
     78        public boolean remove(Object o)
     79        {
    7380                if (o instanceof Item) {
    7481                        ((Item) o).invalidateAll();
    7582                        ((Item) o).invalidateFill();
    7683                }
     84               
    7785                return super.remove(o);
    7886        }
     
    8492         * @return true if at least one item is attached to the cursor.
    8593         */
    86         public static boolean itemsAttachedToCursor() {
     94        public static boolean hasItemsAttachedToCursor()
     95        {
    8796                return getInstance().size() > 0;
    8897        }
     
    94103         *         attached are text items.
    95104         */
    96         public static boolean textOnlyAttachedToCursor() {
    97                 if (!itemsAttachedToCursor())
    98                         return false;
    99                 for (Item i : getInstance()) {
    100                         if (!(i instanceof Text)) {
    101                                 return false;
    102                         }
    103                 }
     105        public static boolean textOnlyAttachedToCursor()
     106        {
     107                if (!hasItemsAttachedToCursor()) return false;
     108               
     109                for (Item i : getInstance()) {
     110                        if (!(i instanceof Text)) return false;
     111                }
     112               
    104113                return true;
    105114        }
    106115
    107         public static Item getItemAttachedToCursor() {
    108                 if (itemsAttachedToCursor())
    109                         return getInstance().get(0);
     116        public static Item getItemAttachedToCursor()
     117        {
     118                if (hasItemsAttachedToCursor()) return getInstance().get(0);
     119               
    110120                return null;
    111121        }
    112122
    113         public static Text getTextAttachedToCursor() {
    114                 if (textOnlyAttachedToCursor())
    115                         return (Text) getInstance().get(0);
     123        public static Text getTextAttachedToCursor()
     124        {
     125                if (textOnlyAttachedToCursor()) return (Text) getInstance().get(0);
     126               
    116127                return null;
    117128        }
     
    121132         * @return the list of free text items
    122133         */
    123         public static Collection<Text> getTextItems() {
     134        public static Collection<Text> getTextItems()
     135        {
    124136                Collection<Text> textItems = new LinkedList<Text>();
    125                 for (Item i : getInstance()) {
    126                         if (i instanceof Text) {
    127                                 textItems.add((Text) i);
    128                         }
     137               
     138                for (Item i : getInstance()) {
     139                        if (i instanceof Text) textItems.add((Text) i);
    129140                }
    130141
     
    132143        }
    133144
    134         public static Map<String, Collection<String>> getGroupedText() {
     145        public static Map<String, Collection<String>> getGroupedText()
     146        {
    135147                Map<String, Collection<String>> groupedText = new HashMap<String, Collection<String>>();
     148               
    136149                // Go throught the lineEnds
    137150                Collection<Item> addedItems = new HashSet<Item>();
    138151                for (Item i : getInstance()) {
    139                         if (!(i instanceof Text) || !i.isLineEnd()) {
    140                                 continue;
    141                         }
     152                        if (!(i instanceof Text) || !i.isLineEnd()) continue;
     153                       
    142154                        // Check for text inside the box
    143155                        Collection<String> textList = new LinkedList<String>();
     
    146158                                addedItems.add(enclosed);
    147159                        }
     160                       
    148161                        if (textList.size() > 0) {
    149162                                groupedText.put(i.getText(), textList);
    150163                        }
    151164                }
     165               
    152166                // Now add the items that were not contained in any of the boxes
    153167                Collection<String> outsideList = new LinkedList<String>();
     
    157171                        }
    158172                }
     173               
    159174                groupedText.put("", outsideList);
    160175
     
    169184         * @return
    170185         */
    171         private Collection<Text> getTextWithin(Item lineEnd) {
    172                 Polygon poly = lineEnd.getEnclosedShape();
     186        private Collection<Text> getTextWithin(Item lineEnd)
     187        {
     188                PolygonBounds poly = lineEnd.getEnclosedShape();
     189               
    173190                Collection<Text> results = new LinkedHashSet<Text>();
    174191                for (Item i : this) {
     
    177194                        }
    178195                }
     196               
    179197                return results;
    180198        }
    181199
    182         public static boolean hasCursor() {
     200        public static boolean hasCursor()
     201        {
    183202                return getCursor().size() > 0;
    184203        }
    185204
    186         public static void setCursor(Collection<Item> cursor) {
     205        public static void setCursor(Collection<Item> cursor)
     206        {
    187207                _cursor.clear();
    188208                _cursor.addAll(cursor);
    189209        }
    190210       
    191         public static boolean hasMultipleVisibleItems() {
     211        public static boolean hasMultipleVisibleItems()
     212        {
    192213                List<Item> toCount = new LinkedList<Item>(getInstance());
     214               
    193215                int c = 0;
    194216                while(!toCount.isEmpty()) {
     
    199221                        }
    200222                }
     223               
    201224                return false;
    202225        }
    203226       
    204         public static boolean isDrawingPolyLine() {
     227        public static boolean isDrawingPolyLine()
     228        {
    205229                List<Item> tmp = getInstance();
     230               
    206231                return tmp.size() == 2 && tmp.get(0) instanceof Dot && tmp.get(1) instanceof Line;
    207232        }
     233
     234        /**
     235         * Checks if lines are being rubber banded.
     236         *
     237         * @return true if the user is rubberBanding one or more lines
     238         */
     239        public static boolean rubberBanding()
     240        {
     241                if (getInstance().size() != 2) return false;
     242
     243                // if rubber-banding, there will be 1 line end and the rest will be lines
     244                boolean foundLineEnd = false;
     245                for (Item i : getInstance()) {
     246                        if (i.isLineEnd()) {
     247                                if (foundLineEnd) return false;
     248                                foundLineEnd = true;
     249                        } else if (!(i instanceof Line) || !i.isVisible()) {
     250                                return false;
     251                        }
     252                }
     253               
     254                return true;
     255        }
     256       
     257        @Override
     258        public FreeItems clone()
     259        {
     260                FreeItems ret = new FreeItems();
     261                ret.addAll(this);
     262                return ret;
     263        }
    208264}
  • trunk/src/org/expeditee/gui/FunctionKey.java

    r919 r1102  
    1919package org.expeditee.gui;
    2020
    21 //these numbers correspond to the Function Key numbers (0 = Escape key)
     21/** Enumerates the Function Key numbers (0 = Escape key) */
    2222public enum FunctionKey {
    23         DropDown, SizeUp, SizeDown, ChangeColor, ToggleAnnotation, InsertDate, NewFrameset, ChangeFontStyle, ChangeFontFamily,
    24         AudienceMode, XRayMode, Save, Refresh;
     23        DropDown,
     24        SizeUp,
     25        SizeDown,
     26        ChangeColor,
     27        ToggleAnnotation,
     28        InsertDate,
     29        NewFrameset,
     30        ChangeFontStyle,
     31        ChangeFontFamily,
     32        AudienceMode,
     33        XRayMode,
     34        Save,
     35        Refresh
    2536}
  • trunk/src/org/expeditee/gui/Help.java

    r919 r1102  
    2626import org.expeditee.items.Picture;
    2727import org.expeditee.items.Text;
    28 import org.expeditee.items.widgets.InteractiveWidget;
     28import org.expeditee.items.widgets.Widget;
    2929import org.expeditee.items.widgets.WidgetCorner;
    3030import org.expeditee.items.widgets.WidgetEdge;
    3131import org.expeditee.settings.experimental.ExperimentalFeatures;
    32 
    3332
    3433public class Help {
     
    120119                        if((mod & shift) == 0)return "Extend line";
    121120                        break;
     121                default:
     122                        break;
    122123                }
    123124                if((other & cursor) != 0) return "Stamp copy";
     
    152153                        }
    153154                        break;
     155                default:
     156                        break;
    154157                }
    155158                return "Delete";
     
    165168                        if((other & cursor) == 0) return "Select text region";
    166169                        break;
     170                default:
     171                        break;
    167172                }
    168173                return null;
     
    174179                case text:
    175180                        if((other & cursor) == 0) return "Cut text region";
     181                default:
     182                        break;
    176183                }
    177184                return null;
     
    187194                case text:
    188195                        if((other & cursor) == 0) return "Copy text region";
     196                default:
     197                        break;
    189198                }
    190199                return null;
     
    192201       
    193202       
    194         public static void updateStatus() {
     203        public static void updateStatus(boolean controlDown, boolean shiftDown)
     204        {
    195205                Item current = FrameUtils.getCurrentItem();
    196206                Collection<Item> currents;
    197207                Context context;
    198                 InteractiveWidget iw = null;
     208                Widget iw = null;
    199209                if(current != null) {
    200210                        if(current instanceof Line) {
     
    232242                        }
    233243                }
    234                 int mod = (FrameMouseActions.isControlDown() ? control : 0) | (FrameMouseActions.isShiftDown() ? shift : 0);
     244                int mod = (controlDown ? control : 0) | (shiftDown ? shift : 0);
    235245                int other = (ExperimentalFeatures.MousePan.get() ? panning : 0) |
    236246                                (current != null && current.hasAction() ? action : 0)|
    237247                                (current != null && current.hasLink() ? link : 0) |
    238                                 (FreeItems.itemsAttachedToCursor() ? cursor : 0);
     248                                (FreeItems.hasItemsAttachedToCursor() ? cursor : 0);
    239249                String status = "";
    240250               
     
    264274                }
    265275               
    266                
    267276                MessageBay.setStatus(status);
    268277        }
  • trunk/src/org/expeditee/gui/MessageBay.java

    r929 r1102  
    1919package org.expeditee.gui;
    2020
    21 import java.awt.Color;
    22 import java.awt.Font;
    23 import java.awt.Graphics;
    24 import java.awt.Graphics2D;
    25 import java.awt.GraphicsEnvironment;
    26 import java.awt.Rectangle;
    27 import java.awt.RenderingHints;
    28 import java.awt.geom.Area;
    29 import java.awt.image.VolatileImage;
    3021import java.util.LinkedList;
    3122import java.util.List;
    3223
     24import org.expeditee.Util;
    3325import org.expeditee.actions.Misc;
     26import org.expeditee.core.Clip;
     27import org.expeditee.core.Colour;
     28import org.expeditee.core.Dimension;
     29import org.expeditee.core.Font;
     30import org.expeditee.core.Image;
     31import org.expeditee.gio.EcosystemManager;
     32import org.expeditee.gio.GraphicsManager;
    3433import org.expeditee.items.Item;
    3534import org.expeditee.items.Text;
    3635
    3736/**
    38  * The bay at the bottom of the expeditee browser which displays messages. TODO
    39  * make it thread safe!
    40  *
     37 * The bay at the bottom of the expeditee browser which displays messages.
     38 * TODO: Make it thread safe!
    4139 */
    4240public final class MessageBay {
    4341
    44 
    45         public static final int MESSAGE_BUFFER_HEIGHT = 105;
    46 
     42        /** The distance from the top of the message bay to the Message frame link. */
    4743        private static final int MESSAGE_LINK_Y_OFFSET = 100;
    4844
     45        /** TODO: Comment. cts16 */
    4946        private static final int MESSAGE_LINK_X = 50;
    5047
    51         public static final Color ERROR_COLOR = Color.red;
    52 
     48        /** TODO: Comment. cts16 */
     49        public static final Colour ERROR_COLOR = Colour.RED;
     50
     51        /** TODO: Comment. cts16 */
    5352        public static final String MESSAGES_FRAMESET_NAME = "Messages";
    5453
    55         // messages shown in the message window
     54        /** The list of messages shown in the message bay. */
    5655        private static List<Item> _messages = new LinkedList<Item>();
     56       
     57        /** Messages which were delayed because they couldn't be shown at time of creation. */
     58        private static List<DelayedMessage> _delayedMessages = new LinkedList<DelayedMessage>();
     59
     60        /** TODO: Comment. cts16 */
    5761        private static Text _status = null;
    5862
    59         // buffer of the message window
    60         private static VolatileImage _messageBuffer = null;
    61 
    62         // creator for creating the message frames
     63        /** Buffer image of the message window. */
     64        private static Image _messageBuffer = null;
     65
     66        /** Creator for creating the message frames. */
    6367        private static FrameCreator _creator = null;
    6468
    65         // font used for the messages
    66         private static Font _messageFont = Font.decode("Serif-Plain-16");
    67 
    68         // the number of messages currently shown (used for scrolling up)
     69        /** Font used for the messages. */
     70        private static Font _messageFont = new Font("Serif-Plain-16");
     71
     72        /** The number of messages currently shown (used for scrolling up). */
    6973        private static int _messageCount = 0;
    7074
    71         // if true, error messages are not shown to the user
     75        /** If true, error messages are not shown to the user. */
    7276        private static boolean _suppressMessages = false;
    7377
    74         // The link to the message frameset
    75         private static Item _messageLink = new Text(-2, "@"
    76                         + MESSAGES_FRAMESET_NAME, Color.black, Color.white);
    77 
    78         private static List<Rectangle> _dirtyAreas = new LinkedList<Rectangle>();
    79 
     78        /** The link to the message frameset. */
     79        private static Item _messageLink = new Text(-2, "@" + MESSAGES_FRAMESET_NAME, Colour.BLACK, Colour.WHITE);
     80
     81        /** TODO: Comment. cts16 */
    8082        private static String _lastMessage = null;
    8183
    82         private MessageBay() {
    83         }
    84 
    85         /**
    86          * Syncs messsage bay size according to FrameGraphics max size.
    87          *
    88          */
    89         static void updateSize() {
    90 
    91                 _messageBuffer = null;
    92 
     84        /** TODO: Comment. cts16 */
     85        private static boolean isLinkInitialized = false;
     86
     87        /** Static-only class. */
     88        private MessageBay()
     89        {
     90        }
     91       
     92        /** Whether the message bay is ready to display messages. */
     93        public static boolean isReady()
     94        {
     95                return Browser.isInitComplete();
     96        }
     97
     98        /** Syncs message bay size according to FrameGraphics max size. */
     99        static void updateSize()
     100        {
    93101                for(Item i : _messages) {
    94102                        if(i != null) {
    95                                 i.setOffset(0, -FrameGraphics.getMaxFrameSize().height);
    96                                 // i.setMaxWidth(FrameGraphics.getMaxFrameSize().width);
     103                                i.setOffset(0, -DisplayController.getMessageBayPaintArea().getMinY());
    97104                        }
    98105                }
    99106
    100                 _messageLink.setOffset(0, -FrameGraphics.getMaxFrameSize().height);
    101                 // _messageLink.setMaxWidth(FrameGraphics.getMaxFrameSize().width);
    102                 // _messageLink.setPosition(FrameGraphics.getMaxFrameSize().width
    103                 // - MESSAGE_LINK_Y_OFFSET, MESSAGE_LINK_X);
     107                _messageLink.setOffset(0, -DisplayController.getMessageBayPaintArea().getMinY());
     108
    104109                updateLink();
    105                 initBuffer();
    106         }
    107 
    108         /**
    109          * @param i
    110          * @return True if i is an item in the message bay
    111          */
    112         public static boolean isMessageItem(Item i) {
    113                
    114                 return _messages.contains(i) || i == _messageLink;
    115         }
    116 
    117         public synchronized static void addDirtyArea(Rectangle r) {
    118                 _dirtyAreas.add(r);
    119         }
    120 
    121         static synchronized int getMessageBufferHeight() {
    122                 if (_messageBuffer != null)
    123                         return _messageBuffer.getHeight();
    124                 return 0;
    125         }
    126 
    127         public synchronized static Item getMessageLink() {
     110        }
     111
     112        /** Whether the given item is an item in the message bay. */
     113        public static boolean isMessageItem(Item i)
     114        {
     115                return _messages.contains(i) || i == _messageLink || i == _status;
     116        }
     117
     118        /** TODO: Comment. cts16 */
     119        public synchronized static Item getMessageLink()
     120        {
    128121                return _messageLink;
    129122        }
    130123
    131         public synchronized static List<Item> getMessages() {
     124        /** TODO: Comment. cts16 */
     125        public synchronized static List<Item> getMessages()
     126        {
    132127                return _messages;
    133128        }
    134129
    135         public synchronized static boolean isDirty() {
    136                 return !_dirtyAreas.isEmpty();
    137         }
    138 
    139         public synchronized static void invalidateFullBay() {
    140                 if (_messageBuffer != null) {
    141                         _dirtyAreas.clear();
    142                         addDirtyArea(new Rectangle(0,
    143                                         FrameGraphics.getMaxFrameSize().height, _messageBuffer
    144                                                         .getWidth(), _messageBuffer.getHeight()));
    145                 }
    146         }
    147 
    148         private synchronized static boolean initBuffer() {
    149                 if (_messageBuffer == null) {
    150                         if (FrameGraphics.isAudienceMode()
    151                                         || FrameGraphics.getMaxSize().width <= 0)
    152                                 return false;
    153 
    154                         GraphicsEnvironment ge = GraphicsEnvironment
    155                                         .getLocalGraphicsEnvironment();
    156                         _messageBuffer = ge.getDefaultScreenDevice()
    157                                         .getDefaultConfiguration().createCompatibleVolatileImage(
    158                                                         FrameGraphics.getMaxSize().width,
    159                                                         MESSAGE_BUFFER_HEIGHT);
    160                 }
    161                 return true;
    162         }
    163 
    164         private static boolean isLinkInitialized = false;
    165 
    166         private static void updateLink() {
    167 
    168                 if (!isLinkInitialized && FrameGraphics.getMaxSize().width > 0) {
     130        /** Causes the entire message bay area to be invalidated. */
     131        public synchronized static void invalidateFullBay()
     132        {
     133                DisplayController.invalidateArea(DisplayController.getMessageBayPaintArea());
     134        }
     135
     136        /** TODO: Comment. cts16 */
     137        private static void updateLink()
     138        {
     139                if (!isLinkInitialized && DisplayController.getFramePaintArea().getWidth() > 0) {
    169140                        // set up 'Messages' link on the right hand side
    170                         _messageLink.setPosition(FrameGraphics.getMaxSize().width
    171                                         - MESSAGE_LINK_Y_OFFSET, MESSAGE_LINK_X);
    172                         _messageLink.setOffset(0, -FrameGraphics.getMaxFrameSize().height);
     141                        _messageLink.setPosition(DisplayController.getMessageBayPaintArea().getWidth() - MESSAGE_LINK_Y_OFFSET, MESSAGE_LINK_X);
     142                        _messageLink.setOffset(0, -DisplayController.getMessageBayPaintArea().getMinY());
    173143                        isLinkInitialized = true;
    174 
    175144                } else {
    176                         _messageLink.setPosition(FrameGraphics.getMaxSize().width
    177                                         - MESSAGE_LINK_Y_OFFSET, MESSAGE_LINK_X);
    178                 }
    179         }
    180 
    181         /**
    182          * Repaints the message bay. Updates the message bay buffer and draws to
    183          * given graphics.
    184          *
    185          * @param useInvalidation
    186          *            Set to true of repinting dirty areas only. Otherwise false for
    187          *            full-repaint.
    188          *
    189          * @param g
    190          *
    191          * @param background
    192          *            The color of the message background
    193          */
    194         public static synchronized void refresh(boolean useInvalidation,
    195                         Graphics g, Color background) {
    196 
    197                 if(g == null)
    198                         return;
    199                
    200                 if (FrameGraphics.getMaxSize().width <= 0)
    201                         return;
    202 
    203                 Area clip = null;
    204 
    205                 if (useInvalidation) { // build clip
    206 
    207                         if (!_dirtyAreas.isEmpty()) {
    208 
    209                                 for (Rectangle r : _dirtyAreas) {
    210                                         r.y = (r.y < 0) ? 0 : r.y;
    211                                         r.x = (r.x < 0) ? 0 : r.x;
    212                                         if (clip == null)
    213                                                 clip = new Area(r);
    214                                         else
    215                                                 clip.add(new Area(r));
     145                        _messageLink.setPosition(DisplayController.getMessageBayPaintArea().getWidth() - MESSAGE_LINK_Y_OFFSET, MESSAGE_LINK_X);
     146                }
     147        }
     148
     149        /** TODO: Comment. cts16 */
     150        public static Image getImage(Clip clip, Dimension size)
     151        {
     152                // Can't get an image with an invalid size
     153                if (size == null || size.width <= 0 || size.height <= 0) return null;
     154
     155                // Update the buffer
     156                updateBuffer(Item.DEFAULT_BACKGROUND, clip, size);
     157               
     158                // Return the image buffer
     159                return _messageBuffer;
     160        }
     161
     162        /** Updates the image buffer to reflect the current state of the message bay. */
     163        private static void updateBuffer(Colour background, Clip clip, Dimension size)
     164        {
     165                // If the buffer doesn't exist or is the wrong size, recreate it
     166                if (_messageBuffer == null || !_messageBuffer.getSize().equals(size)) {
     167                        _messageBuffer = Image.createImage(size, true);
     168                        clip = null; // Need to recreate the entire image;
     169                        updateSize();
     170                }
     171
     172                GraphicsManager g = EcosystemManager.getGraphicsManager();
     173                g.pushDrawingSurface(_messageBuffer);
     174
     175                if (clip != null) g.pushClip(clip);
     176                g.setAntialiasing(true);
     177               
     178                g.clear(background);
     179               
     180                g.setFont(_messageFont);
     181               
     182                for (Item message : _messages) {
     183                        if (message != null) {
     184                                if (clip == null || clip.isNotClipped() || message.isInDrawingArea(clip.getBounds())) {
     185                                        FrameGraphics.PaintItem(message);
    216186                                }
    217                         } else
    218                                 return; // nothing to render
    219                 }
    220 
    221                 _dirtyAreas.clear();
    222 
    223                 // Update the buffer
    224                 updateBuffer(background, clip);
    225 
    226                 // Now repaint to screen
    227                 if (!FrameGraphics.isAudienceMode()) {
    228 
    229                         // Translate clip to messagebox coords
    230                         // clip.transform(t) // TODO
    231                         // g.setClip(clip);
    232 
    233                         g.drawImage(_messageBuffer, 0, FrameGraphics.getMaxFrameSize().height, null);
    234                 }
    235 
    236         }
    237 
    238         private static void updateBuffer(Color background, Area clip) {
    239                 if (!initBuffer())
    240                         return;
    241 
    242                 Graphics2D g = _messageBuffer.createGraphics();
    243 
    244                 g.setClip(clip);
    245 
    246                 g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
    247                                 RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    248                 g.setColor(background);
    249                 g.fillRect(0, 0, FrameGraphics.getMaxSize().width,
    250                                 MESSAGE_BUFFER_HEIGHT);
    251                 g.setFont(_messageFont);
    252                 g.setColor(Color.BLACK);
    253                 g.drawLine(0, 0, FrameGraphics.getMaxSize().width, 0);
    254 
    255                 for (Item t : _messages) {
    256                         if (t == null)
    257                                 continue;
    258                         if (clip == null || t.isInDrawingArea(clip))
    259                                 FrameGraphics.PaintItem(g, t);
    260                 }
    261                 if(_status != null)
    262                         FrameGraphics.PaintItem(g, _status);
    263 
    264                 if (// _messageLink.getLink() != null
    265                 // &&
    266                 (clip == null || _messageLink.isInDrawingArea(clip))) {
    267                         FrameGraphics.PaintItem(g, _messageLink);
    268                 }
    269                 g.dispose();
    270 
    271         }
    272 
    273         private static Text displayMessage(String message, String link,
    274                         List<String> actions, Color color) {
     187                        }
     188                }
     189               
     190                if (_status != null) FrameGraphics.PaintItem(_status);
     191
     192                if (clip == null || clip.isNotClipped() || _messageLink.isInDrawingArea(clip.getBounds())) {
     193                        FrameGraphics.PaintItem(_messageLink);
     194                }
     195               
     196                g.popDrawingSurface();
     197        }
     198
     199        /** TODO: Comment. cts16 */
     200        private static Text displayMessage(String message, String link, List<String> actions, Colour color)
     201        {
    275202                return displayMessage(message, link, actions, color, true);
    276203        }
    277204
    278         public synchronized static Text displayMessage(String message, String link, Color color,
    279                         boolean displayAlways, String action) {
     205        /** TODO: Comment. cts16 */
     206        public synchronized static Text displayMessage(String message, String link, Colour color, boolean displayAlways, String action)
     207        {
    280208                List<String> actions = new LinkedList<String>();
    281                 if (action != null)
    282                         actions.add(action);
     209                if (action != null) actions.add(action);
    283210                return displayMessage(message, link, actions, color, displayAlways);
    284211        }
    285        
    286         private static Text newMessage(String message, String link, List<String> actions, Color color) {
     212
     213        /** TODO: Comment. cts16 */
     214        private static Text newMessage(String message, String link, List<String> actions, Colour color)
     215        {
    287216                Text t = new Text(getMessagePrefix(true) + message);
    288217                t.setPosition(20, 15 + _messages.size() * 25);
    289                 t.setOffset(0, -FrameGraphics.getMaxFrameSize().height);
     218                t.setOffset(0, -DisplayController.getFramePaintArea().getHeight());
    290219                t.setColor(color);
    291220                t.setLink(link);
     
    296225                return t;
    297226        }
    298        
    299         private synchronized static Text displayMessage(String message, String link,
    300                         List<String> actions, Color color, boolean displayAlways, boolean redraw) {
     227
     228        /** TODO: Comment. cts16 */
     229        private synchronized static Text displayMessage(String message, String link, List<String> actions, Colour color, boolean displayAlways, boolean redraw)
     230        {
     231                assert (message != null);
     232               
     233                if (!isReady()) {
     234                        delayMessage(message, link, actions, color, displayAlways, redraw);
     235                        return null;
     236                }
     237               
    301238                System.out.println(message);
    302                 assert (message != null);
    303239
    304240                // Invalidate whole area
    305241                invalidateFullBay();
    306242
    307                 if (_suppressMessages)
    308                         return null;
     243                if (_suppressMessages) return null;
    309244
    310245                if (!displayAlways && message.equals(_lastMessage)) {
     
    312247                        return null;
    313248                }
     249               
    314250                _lastMessage = message;
    315251
    316252                if (_creator == null) {
    317                         _creator = new FrameCreator(MESSAGES_FRAMESET_NAME,
    318                                         FrameIO.MESSAGES_PATH, MESSAGES_FRAMESET_NAME, true, false);
     253                        _creator = new FrameCreator(MESSAGES_FRAMESET_NAME, FrameIO.MESSAGES_PATH, MESSAGES_FRAMESET_NAME, true, false);
    319254                }
    320255
     
    336271                _messageLink.setLink(_creator.getCurrent());
    337272
     273                // TODO: Can we just make this DisplayController.requestRefresh()? cts16
    338274                if(redraw) {
    339                 Graphics g = FrameGraphics.createGraphics();
    340                 if (g != null) {
    341                     refresh(false, g, Item.DEFAULT_BACKGROUND);
    342                 }
     275                        DisplayController.requestRefresh(true);
    343276                }
    344277
     
    346279        }
    347280
    348         public synchronized static Text displayMessage(String message, String link,
    349                         List<String> actions, Color color, boolean displayAlways) {
     281        /** TODO: Comment. cts16 */
     282        public synchronized static Text displayMessage(String message, String link, List<String> actions, Colour color, boolean displayAlways)
     283        {
    350284                return displayMessage(message, link, actions, color, displayAlways, true);
    351285        }
    352286
    353         public synchronized static void overwriteMessage(String message) {
     287        /** TODO: Comment. cts16 */
     288        public synchronized static void overwriteMessage(String message)
     289        {
    354290                overwriteMessage(message, null);
    355291        }
    356292
    357         public synchronized static void overwriteMessage(String message, Color color) {
     293        /** TODO: Comment. cts16 */
     294        public synchronized static void overwriteMessage(String message, Colour color)
     295        {
    358296                _messages.remove(_messages.size() - 1);
    359297                Text t = newMessage(message, null, null, color);
    360298                _messages.add(t);
    361                 Graphics g = FrameGraphics.createGraphics();
    362                 if (g != null) {
    363                     refresh(false, g, Item.DEFAULT_BACKGROUND);
    364                 }
    365         }
    366        
    367         private static String getMessagePrefix(int counter) {
     299                DisplayController.requestRefresh(true);
     300        }
     301
     302        /** TODO: Comment. cts16 */
     303        private static String getMessagePrefix(int counter)
     304        {
    368305                return "@" + counter + ": ";
    369306        }
    370307
    371         private static String getMessagePrefix(boolean incrementCounter) {
    372                 if (incrementCounter)
    373                         _messageCount++;
     308        /** TODO: Comment. cts16 */
     309        private static String getMessagePrefix(boolean incrementCounter)
     310        {
     311                if (incrementCounter) _messageCount++;
     312               
    374313                return getMessagePrefix(_messageCount);
    375314        }
     
    382321         *            the message to be displayed
    383322         */
    384         public synchronized static Text linkedErrorMessage(String message) {
    385                 if (_suppressMessages)
    386                         return null;
     323        public synchronized static Text linkedErrorMessage(String message)
     324        {
     325                if (_suppressMessages) return null;
    387326                Misc.beep();
    388327                String[] tokens = message.split(Text.FRAME_NAME_SEPARATOR);
    389328                String link = null;
    390                 if (tokens.length > 1)
    391                         link = tokens[tokens.length - 1];
     329                if (tokens.length > 1) link = tokens[tokens.length - 1];
    392330                return displayMessage(message, link, null, ERROR_COLOR);
    393331        }
    394332
    395         public synchronized static Text errorMessage(String message) {
    396                 if (_suppressMessages)
    397                         return null;
     333        /** TODO: Comment. cts16 */
     334        public synchronized static Text errorMessage(String message)
     335        {
     336                if (_suppressMessages) return null;
    398337                Misc.beep();
    399338                return displayMessage(message, null, null, ERROR_COLOR, false);
     
    407346         *            The message to display to the user in the message area
    408347         */
    409         public synchronized static Text displayMessage(String message) {
     348        public synchronized static Text displayMessage(String message)
     349        {
    410350                return displayMessageAlways(message);
    411351        }
    412352
    413         public synchronized static Text displayMessageOnce(String message) {
    414                 return displayMessage(message, null, null, Color.BLACK, false);
    415         }
    416 
    417         public synchronized static Text displayMessage(String message, Color textColor) {
     353        /** TODO: Comment. cts16 */
     354        public synchronized static Text displayMessageOnce(String message)
     355        {
     356                return displayMessage(message, null, null, Colour.BLACK, false);
     357        }
     358
     359        /** TODO: Comment. cts16 */
     360        public synchronized static Text displayMessage(String message, Colour textColor)
     361        {
    418362                return displayMessage(message, null, null, textColor);
    419                 // Misc.Beep();
    420         }
    421 
    422         public synchronized static Text displayMessage(Text message) {
     363        }
     364
     365        /** TODO: Comment. cts16 */
     366        public synchronized static Text displayMessage(Text message)
     367        {
    423368                Text t = null;
    424369                String link = message.getLink();
    425370                List<String> action = message.getAction();
    426                 Color color = message.getColor();
     371                Colour color = message.getColor();
    427372                for (String s : message.getTextList()) {
    428373                        t = displayMessage(s, link, action, color);
    429374                }
    430375                return t;
     376        }
     377
     378        /** TODO: Comment. cts16 */
     379        public synchronized static Text displayMessageAlways(String message)
     380        {
     381                return displayMessage(message, null, null, Colour.BLACK);
    431382                // Misc.Beep();
    432383        }
    433384
    434         public synchronized static Text displayMessageAlways(String message) {
    435                 return displayMessage(message, null, null, Color.BLACK);
    436                 // Misc.Beep();
    437         }
    438 
    439         public synchronized static Text warningMessage(String message) {
    440                 return displayMessage(message, null, null, Color.MAGENTA);
    441                 // Misc.Beep();
    442         }
    443 
    444         public synchronized static void suppressMessages(boolean val) {
     385        /** TODO: Comment. cts16 */
     386        public synchronized static Text warningMessage(String message)
     387        {
     388                return displayMessage(message, null, null, Colour.MAGENTA);
     389        }
     390
     391        /** TODO: Comment. cts16 */
     392        public synchronized static List<Text> warningMessages(List<String> messages)
     393        {
     394                if (messages == null) return null;
     395                List<Text> ret = new LinkedList<Text>();
     396                for (String message : messages) ret.add(warningMessage(message));
     397                return ret;
     398        }
     399
     400        /** TODO: Comment. cts16 */
     401        public synchronized static void suppressMessages(boolean val)
     402        {
    445403                _suppressMessages = val;
    446404        }
    447        
    448         public synchronized static void setStatus(String status) {
     405
     406        /** TODO: Comment. cts16 */
     407        public synchronized static void setStatus(String status)
     408        {
    449409                if (_status == null) {
    450410                        _status = new Text(status);
    451411                        _status.setPosition(0, 85);
    452                         _status.setOffset(0, FrameGraphics.getMaxFrameSize().height);
     412                        _status.setOffset(0, -DisplayController.getMessageBayPaintArea().getMinY());
    453413                        _status.setLink(null); // maybe link to a help frame?
    454                         _status.setFont(Font.decode(Text.MONOSPACED_FONT));
     414                        _status.setFont(new Font(Text.MONOSPACED_FONT));
    455415                } else {
    456416                        _status.setText(status);
    457417                }
    458                 Graphics g = FrameGraphics.createGraphics();
    459                 if (g != null) {
    460                         refresh(false, g, Item.DEFAULT_BACKGROUND);
    461                 }
    462         }
    463        
    464         public static final class Progress {
    465                
    466                 private static final String filled = "\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592";
    467                 private static final String unfilled = "\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591";
    468                
    469                 String message;
    470                 Text text;
    471                
    472                 protected Progress(String text) {
    473                         this.text = displayMessage(text, null, null, Color.GREEN.darker(), true, false);
    474                         //this.text.setFont(Font.decode(Text.MONOSPACED_FONT + "-16"));
    475                         this.message = this.text.getText();
    476                         this.text.setText(this.message + " [" + unfilled + "] 0%");
    477                         refresh(false, FrameGraphics.createGraphics(), Item.DEFAULT_BACKGROUND);
    478                 }
    479                
    480                 public void UpdateMessage(final String text, final int newProgress) throws Exception {
    481                         this.message = text;
     418
     419                //invalidateFullBay();
     420                DisplayController.requestRefresh(true);
     421        }
     422
     423        /** TODO: Comment. cts16 */
     424        public static final class Progress
     425        {
     426                /** The colour progress bars should be displayed in. */
     427                private static final Colour BAR_COLOUR = Colour.GREEN.darker();
     428               
     429                /** The character used to assemble the uncompleted portions of the progress bar. */
     430                private static final char UNCOMPLETED_CHARACTER = '\u2591'; // ░
     431                /** The character used to assemble the completed portions of the progress bar. */
     432                private static final char COMPLETED_CHARACTER = '\u2592'; // ▒
     433               
     434                /** What the progress bar should look like when at 100% completion. */
     435                private static final String COMPLETED_BAR = Util.nCopiesOf(20, COMPLETED_CHARACTER);
     436                /** What the progress bar should look like when at 0% completion. */
     437                private static final String UNCOMPLETED_BAR = Util.nCopiesOf(20, UNCOMPLETED_CHARACTER);
     438               
     439                private String _message;
     440                private Text _text;
     441               
     442                protected Progress(String text)
     443                {
     444                        this._text = displayMessage(text, null, null, BAR_COLOUR, true, false);
     445                        this._message = this._text.getText();
     446                        this._text.setText(this._message + " [" + UNCOMPLETED_BAR + "] 0%");
     447                        DisplayController.requestRefresh(true);
     448                }
     449               
     450                public void UpdateMessage(final String text, final int newProgress) throws Exception
     451                {
     452                        this._message = text;
    482453                        set(newProgress);
    483454                }
    484455               
    485                 public String GetMessage() {
    486                         return message;
     456                public String GetMessage()
     457                {
     458                        return _message;
    487459                }
    488460               
     
    493465                 * @throws Exception if progress out of bounds
    494466                 */
    495                 public boolean set(int progress) throws Exception {
     467                public boolean set(int progress) throws Exception
     468                {
    496469                        if(progress < 0 || progress > 100) throw new Exception("Progress value out of bounds");
    497470                        int p = progress / 5;
    498                         if(isMessageItem(this.text)) {
    499                                 this.text.setText(this.message + " [" + filled.substring(0, p) + unfilled.substring(p) + "] " + progress + "%");
    500                                 refresh(false, FrameGraphics.createGraphics(), Item.DEFAULT_BACKGROUND);
     471                        if(isMessageItem(this._text)) {
     472                                this._text.setText(this._message + " [" + COMPLETED_BAR.substring(0, p) + UNCOMPLETED_BAR.substring(p) + "] " + progress + "%");
     473                                DisplayController.requestRefresh(true);
    501474                                return true;
    502475                        }
     
    504477        }
    505478        }
     479
     480        /** TODO: Comment. cts16 */
     481        public synchronized static Progress displayProgress(String message)
     482        {
     483                return new Progress(message);
     484        }
    506485       
    507         public synchronized static Progress displayProgress(String message) {
    508                 return new Progress(message);
     486        /** Remembers the arguments to a displayMessage call for later use. */
     487        private static class DelayedMessage {
     488               
     489                private String _message;
     490                private String _link;
     491                private List<String> _actions;
     492                private Colour _colour;
     493                private boolean _displayAlways;
     494                private boolean _redraw;
     495               
     496                public DelayedMessage(String message, String link, List<String> actions, Colour color, boolean displayAlways, boolean redraw)
     497                {
     498                        _message = message;
     499                        _link = link;
     500                        if (actions == null) {
     501                                _actions = null;
     502                        } else {
     503                                _actions =  new LinkedList<String>();
     504                                _actions.addAll(actions);
     505                        }
     506                        _colour = color == null ? null : color.clone();
     507                        _displayAlways = displayAlways;
     508                        _redraw = redraw;
     509                }
     510               
     511                public void display()
     512                {
     513                        displayMessage(_message, _link, _actions, _colour, _displayAlways, _redraw);
     514                }
     515               
     516        }
     517       
     518        private static void delayMessage(String message, String link, List<String> actions, Colour color, boolean displayAlways, boolean redraw)
     519        {
     520                _delayedMessages.add(new DelayedMessage(message, link, actions, color, displayAlways, redraw));
     521        }
     522       
     523        public static void showDelayedMessages()
     524        {
     525                if (isReady()) {
     526                        for (DelayedMessage message : _delayedMessages) message.display();
     527                        _delayedMessages.clear();
     528                        invalidateFullBay();
     529                        DisplayController.requestRefresh(true);
     530                }
    509531        }
    510532
  • trunk/src/org/expeditee/gui/Overlay.java

    r919 r1102  
    2020
    2121import java.util.Collection;
     22import java.util.LinkedList;
     23import java.util.List;
    2224
    2325import org.expeditee.items.UserAppliedPermission;
     26import org.expeditee.items.widgets.Widget;
    2427
     28/** TODO: Comment. cts16 */
    2529public class Overlay {
     30        /** TODO: Comment. cts16 */
    2631        public Frame Frame;
    2732
     33        /** TODO: Comment. cts16 */
    2834        public UserAppliedPermission permission;
    2935
     36        /** TODO: Comment. cts16 */
    3037        public Overlay(Frame overlay, UserAppliedPermission level) {
    3138                Frame = overlay;
     
    3441
    3542        @Override
    36         public boolean equals(Object o) {
    37                 if (o == null || o.getClass() != Overlay.class)
    38                         return false;
     43        public boolean equals(Object o)
     44        {
     45                if (!(o instanceof Overlay)) return false;
    3946
    4047                return ((Overlay) o).Frame == Frame;
     
    4249
    4350        @Override
    44         public int hashCode() {
     51        public int hashCode()
     52        {
     53                // TODO: Comment. cts16
    4554                return 0;
    4655        }
    47        
    48         public static Overlay getOverlay(Collection<Overlay>overlays, Frame frame){
     56
     57        /** TODO: Comment. cts16 */
     58        public static Overlay getOverlay(Collection<Overlay> overlays, Frame frame)
     59        {
    4960                // Check the frame is in the list of overlays
    5061                for (Overlay o : overlays) {
  • trunk/src/org/expeditee/gui/Popup.java

    r919 r1102  
    1919package org.expeditee.gui;
    2020
    21 import java.awt.BasicStroke;
    22 import java.awt.Color;
    23 import java.awt.Component;
    24 import java.awt.Container;
    25 import java.awt.Graphics;
    26 import java.awt.Graphics2D;
    27 import java.awt.LayoutManager;
    28 
    29 import javax.swing.JComponent;
    30 import javax.swing.JPanel;
    31 
     21import org.expeditee.core.Clip;
     22import org.expeditee.core.Colour;
     23import org.expeditee.core.EnforcedClipStack.EnforcedClipKey;
     24import org.expeditee.core.Fill;
     25import org.expeditee.core.Lifetime;
     26import org.expeditee.core.Stroke;
     27import org.expeditee.core.bounds.AxisAlignedBoxBounds;
     28import org.expeditee.gio.EcosystemManager;
     29import org.expeditee.gio.GraphicsManager;
     30import org.expeditee.gui.PopupManager.PopupAnimator;
    3231import org.expeditee.items.ItemUtils;
    3332
    3433/**
     34 * A Custom swing pop-up in Expeditee.
    3535 *
    36  * A Custom swing popup in Expeditee.
    37  *
    38  * Expeditee popus can be re-used. Popups are always heavyweight (i.e. uses invalidation).
     36 * Expeditee pop-ups can be re-used. Pop-ups are always heavyweight (i.e. uses invalidation).
    3937 *
    4038 * @see {@link PopupManager}
    4139 *
    4240 * @author Brook Novak
    43  *
    4441 */
    45 public abstract class Popup extends JPanel {
    46        
     42public abstract class Popup
     43{
    4744        //Mike says: Can we get the border for the IW to which this popup corresponds?
    48         // Brook says: Would be nice - but popups are actually independant from widgets
     45        // Brook says: Would be nice - but popups are actually independent from widgets
    4946        //   =>Now: It is up to the user of the popup to set the border thickness
    50         private static final BasicStroke DEFAULT_STROKE = new BasicStroke(2.0f);
    51        
    52         private BasicStroke _borderStroke = DEFAULT_STROKE;
    53         private Color _borderColor = Color.BLACK;
    54        
    55         private boolean _isReadyToPaint = false;
     47        private static final Stroke DEFAULT_STROKE = new Stroke(2.0f);
     48       
     49        private Stroke _borderStroke = DEFAULT_STROKE;
     50        private Colour _borderColour = Colour.BLACK;
     51        private Fill _backgroundFill = new Fill(Colour.WHITE);
     52       
     53        private PopupAnimator _animator = null;
     54       
     55        private Lifetime _autoHideTime = new Lifetime(Lifetime.INFINITE_LIFETIME);
     56        private Runnable _autoHideRoutine = new Runnable()
     57        {
     58                @Override
     59                public void run()
     60                {
     61                        hide();
     62                        DisplayController.invalidateArea(getBounds());
     63                        DisplayController.requestRefresh(true);
     64                }
     65        };
     66       
     67        private boolean _hidden = true;
     68
    5669        private boolean _consumeBackClick = false;
    57         private boolean _autoHide = true;
    58 
    59         /**
    60          * Creates a new popup.
    61          * Autohide is set to true.
    62          *
    63          */
    64         public Popup() {
    65                 super();
    66                 setVisible(false);
    67         }
    68        
    69         /**
    70          * Creates a new popup.
    71          *
    72          * @param layout the LayoutManager to use
    73          */
    74         public Popup(LayoutManager layout) {
    75                 super(layout);
    76                 setVisible(false);
    77         }
    78 
    79         @Override
    80         public void paint(Graphics g) {
    81                 super.paint(g);
    82                
    83                 // Draw border - if not transparent
    84                 if (_borderStroke != null && _borderColor != null) {
    85                         g.setColor(_borderColor);
    86                         ((Graphics2D)g).setStroke(_borderStroke);
    87                         g.drawRect(0, 0, getWidth(), getHeight());
    88                 }
    89         }
    90        
    91         private void ignoreAWTPainting(Component c) {
    92                
    93                 if (c instanceof JComponent) {
    94                         ((JComponent)c).setDoubleBuffered(false);
    95                 }
    96                
    97                 c.setIgnoreRepaint(true);
    98                
    99                 if (c instanceof Container) {
    100                         for (Component child : ((Container) c).getComponents()) {
    101 
    102                                 if (child instanceof Container) {
    103                                         ignoreAWTPainting(child);
    104                                 } else {
    105                                         if (child instanceof JComponent) {
    106                                                 ((JComponent)child).setDoubleBuffered(false);
    107                                         }
    108                                        
    109                                         child.setIgnoreRepaint(true);
     70
     71        /**
     72         * Creates a new pop-up.
     73         * Auto-hide is set to true.
     74         */
     75        public Popup(PopupAnimator animator)
     76        {
     77                setAnimator(animator);
     78        }
     79       
     80        public Popup(PopupAnimator animator, long lifetime)
     81        {
     82                this(animator);
     83                _autoHideTime.setLifetime(lifetime);
     84        }
     85       
     86        public Lifetime getAutoHideTime()
     87        {
     88                return _autoHideTime;
     89        }
     90       
     91        public void setAnimator(PopupAnimator animator)
     92        {
     93                _animator = animator;
     94        }
     95       
     96        public PopupAnimator getAnimator()
     97        {
     98                return _animator;
     99        }
     100       
     101        public boolean isShowing()
     102        {
     103                return !_hidden;
     104        }
     105       
     106        public void show()
     107        {
     108                if (_hidden) onShow();
     109               
     110                if (_animator != null) {
     111                        _animator.show();
     112                        if (!_animator.isFinished()) {
     113                                _autoHideTime.cancelExpiry();
     114                        } else {
     115                                _autoHideTime.refresh();
     116                                _autoHideTime.onExpiry(_autoHideRoutine);
     117                        }
     118                } else {
     119                        _autoHideTime.refresh();
     120                        _autoHideTime.onExpiry(_autoHideRoutine);
     121                }
     122               
     123                _hidden = false;
     124        }
     125
     126        public void hide()
     127        {
     128                if (!_hidden) onHide();
     129               
     130                if (_animator != null) _animator.hide();
     131                _autoHideTime.cancelExpiry();
     132                _hidden = true;
     133        }
     134       
     135        public boolean update()
     136        {
     137                if (_animator != null) {
     138                        if (!_hidden && !_animator.isFinished()) {
     139                                if (!_animator.update()) {
     140                                        _autoHideTime.refresh();
     141                                        _autoHideTime.onExpiry(_autoHideRoutine);
    110142                                }
    111143                        }
    112                 }
    113                
    114         }
    115        
    116         /**
    117          * Ensures that AWT painting turned off
    118          */
    119         void prepareToPaint() {
    120                 if (!_isReadyToPaint) {
    121                         _isReadyToPaint = true;
    122                         ignoreAWTPainting(this);
    123                 }
    124         }
    125        
    126         /**
    127          * Invoked when the popup becomes hidden, or when the popup is animating to show but cancelled.
    128          */
    129         public void onHide() {}
    130        
    131         /**
    132          * Invoked when the popup shows. Note this might not eventuate for animated popups.
    133          */
    134         public void onShow() {}
    135        
    136         /**
    137          * Invoked when popups is going to show.
    138          * This always is invoked first.
    139          */
    140         public void onShowing() {}
    141 
    142         public boolean shouldConsumeBackClick() {
     144                       
     145                        if (_hidden && !_animator.isFinished()) {
     146                                return _animator.update();
     147                        }
     148                } else {
     149                        if (_autoHideTime.hasExpired()) hide();
     150                }
     151               
     152                return false;
     153               
     154        }
     155       
     156        public final void paint()
     157        {
     158                GraphicsManager g = EcosystemManager.getGraphicsManager();
     159               
     160                // Make sure the popup isn't hidden
     161                AxisAlignedBoxBounds currentBounds = getBounds();
     162                if (currentBounds == null) return;
     163               
     164                // Draw border and background
     165                g.drawRectangle(currentBounds, 0.0, _backgroundFill, _borderColour, _borderStroke, null);
     166               
     167                EnforcedClipKey key = g.pushClip(new Clip(currentBounds));
     168               
     169                paintInternal();
     170               
     171                g.popClip(key);
     172        }
     173       
     174        /** Draws the interior paint area of the popup. */
     175        protected abstract void paintInternal();
     176       
     177        /** Gets the bounds of this popup when it's fully shown. */
     178        public abstract AxisAlignedBoxBounds getFullBounds();
     179       
     180        /** Gets the bounds of this popup in its current animated state. */
     181        public AxisAlignedBoxBounds getBounds()
     182        {
     183                if (_animator == null) {
     184                        if (_autoHideTime.hasExpired()) {
     185                                return null;
     186                        } else {
     187                                return getFullBounds();
     188                        }
     189                }
     190               
     191                return _animator.getAnimatedBounds(getFullBounds());
     192        }
     193       
     194        /** Invoked when the popup becomes hidden, or when the popup is animating to show but cancelled. */
     195        public abstract void onHide();
     196       
     197        /** Invoked when the popup shows. Note this might not eventuate for animated popups. */
     198        public abstract void onShow();
     199
     200        public boolean shouldConsumeBackClick()
     201        {
    143202                return _consumeBackClick;
    144203        }
     
    150209         *              consume the back-click event.
    151210         */
    152         protected void setConsumeBackClick(boolean consumeBackClick) {
     211        protected void setConsumeBackClick(boolean consumeBackClick)
     212        {
    153213                _consumeBackClick = consumeBackClick;
    154         }
    155        
    156         /**
    157          * @param autoHideOn
    158          *              Set to True if this popup should auto hide. (The default).
    159          *              Set to false if this popup should be manually hidden.
    160          */
    161         protected void setAudoHide(boolean autoHideOn) {
    162                 _autoHide = autoHideOn;
    163214        }
    164215       
     
    167218         *              True if this popup auto hides.
    168219         */
    169         public boolean doesAutoHide() {
    170                 return _autoHide;
     220        public boolean doesAutoHide()
     221        {
     222                return _autoHideTime.remainingLifetime() != Lifetime.INFINITE_LIFETIME;
    171223        }
    172224       
     
    177229         *              The new thickness to set. Null for no border.
    178230         */
    179         public void setBorderThickness(float thickness) {
     231        public void setBorderThickness(float thickness)
     232        {
    180233                assert(thickness >= 0);
    181234               
    182                 if (_borderStroke != null && _borderStroke.getLineWidth() == thickness)
    183                         return;
     235                if (_borderStroke != null && _borderStroke.thickness == thickness) return;
    184236               
    185237                boolean posInvalidate = true;
    186238               
    187                 if (thickness < _borderStroke.getLineWidth()) {
     239                if (thickness < _borderStroke.thickness) {
    188240                        invalidateAppearance();
    189241                        posInvalidate = false;
    190242                }
    191243               
    192                 if (thickness == 0) _borderStroke = null;
    193                 else _borderStroke = new BasicStroke(thickness);
     244                if (thickness == 0) {
     245                        _borderStroke = null;
     246                } else {
     247                        _borderStroke = new Stroke(thickness);
     248                }
    194249               
    195250                if (posInvalidate) invalidateAppearance();
     
    201256         *              The border thickness of this popup. Zero or more.
    202257         */
    203         public float getBorderThickness() {
     258        public float getBorderThickness()
     259        {
    204260                if (_borderStroke == null) return 0.0f;
    205                 return _borderStroke.getLineWidth();
    206 
     261
     262                return _borderStroke.thickness;
    207263        }
    208264       
     
    214270         *              The new color. Null for transparent.
    215271         */
    216         public void setBorderColor(Color c) {
    217                
    218                 if (c == null && _borderColor != null)
     272        public void setBorderColor(Colour c)
     273        {
     274                if (c == null && _borderColour != null)  invalidateAppearance();
     275               
     276                if (c != _borderColour) {
     277                        _borderColour = c;
    219278                        invalidateAppearance();
    220                
    221                 if (c != _borderColor) {
    222                         _borderColor = c;
    223                         invalidateAppearance();
    224                 }
    225         }
    226        
    227         /**
    228          *
     279                }
     280        }
     281       
     282        /**
    229283         * @return
    230284         *              The border color for the popup. NUll if transparent
    231285         */
    232         public Color getBorderColor() {
    233                 return _borderColor;
    234         }
    235        
    236         /**
    237          * Invalidates the whole popup so that it must be fully repainted.
    238          */
    239         public void invalidateAppearance() {
    240                
    241                 if (_borderColor != null && _borderStroke != null && _borderStroke.getLineWidth() > 0) { // border
    242                         FrameGraphics.invalidateArea(ItemUtils.expandRectangle(getBounds(),
    243                                         (int)Math.ceil(getBorderThickness()) + 1));
     286        public Colour getBorderColor()
     287        {
     288                return _borderColour;
     289        }
     290       
     291        /**
     292         * Invalidates the whole pop-up so that it must be fully repainted.
     293         */
     294        public void invalidateAppearance()
     295        {
     296                AxisAlignedBoxBounds bounds = getBounds();
     297               
     298                if (bounds == null) return;
     299               
     300                if (_borderColour != null && _borderStroke != null && _borderStroke.thickness > 0) { // border
     301                        DisplayController.invalidateArea(ItemUtils.expandRectangle(bounds, (int)Math.ceil(getBorderThickness()) + 1));
    244302                } else { // no border
    245                         FrameGraphics.invalidateArea(getBounds());
    246                 }
    247 
    248         }
    249        
    250 
    251        
     303                        DisplayController.invalidateArea(bounds);
     304                }
     305
     306        }
    252307}
  • trunk/src/org/expeditee/gui/PopupManager.java

    r919 r1102  
    1919package org.expeditee.gui;
    2020
    21 import java.awt.BasicStroke;
    22 import java.awt.Color;
    23 import java.awt.Component;
    24 import java.awt.Graphics;
    25 import java.awt.Graphics2D;
    26 import java.awt.Point;
    27 import java.awt.Rectangle;
    28 import java.awt.Stroke;
    29 import java.awt.geom.Area;
    30 import java.util.HashMap;
    31 import java.util.HashSet;
    3221import java.util.LinkedList;
    33 
    34 import javax.swing.JLayeredPane;
    35 import javax.swing.SwingUtilities;
     22import java.util.List;
     23
     24import org.expeditee.core.Point;
     25import org.expeditee.core.bounds.AxisAlignedBoxBounds;
     26import org.expeditee.gio.EcosystemManager;
     27import org.expeditee.gio.EcosystemManager.Ecosystem;
    3628
    3729/**
    38  * A centralized container for all custom popups in expeditee.
     30 * A centralised container for all custom pop-ups in expeditee.
    3931 *
    4032 * @author Brook Novak
    4133 */
    42 public final class PopupManager implements DisplayIOObserver {
    43        
     34public final class PopupManager implements DisplayObserver
     35{
    4436        /** Singleton */
    45         private PopupManager() {}
     37        private static PopupManager _instance = null;
     38       
     39        /**
     40         * @return The singleton instance.
     41         */
     42        public static PopupManager getInstance()
     43        {
     44                // Only valid for Swing ecosystems
     45                if (EcosystemManager.getType() != Ecosystem.Swing) return null;
     46               
     47                // Construct the instance
     48                if (_instance == null) _instance = new PopupManager();
     49               
     50                return _instance;
     51        }
    4652       
    4753        /** Singleton */
    48         private static PopupManager _instance = new PopupManager();
    49        
    50         /**
    51          * @return The singleton instance.
    52          */
    53         public static PopupManager getInstance() {
    54                 return _instance;
    55         }
    56        
    57         // popup->invoker
    58         private HashMap<Popup, Component> _popups = new HashMap<Popup, Component>();
    59         // quick ref to invokers
    60         private HashSet<Component> _invokers = new HashSet<Component>();
    61        
    62         private LinkedList<AnimatedPopup> _animatingPopups = new LinkedList<AnimatedPopup>();
    63         private AnimationThread _animationThread = null;
    64 
    65         private final int ANIMATION_DURATION = 180; // Tume its takes for a maximize . minimize to animate. In ms.
    66         private final int ANIMATION_RATE = 30; // in ms
    67        
    68         /**
    69          * Determines whether a given point is over a popup.
     54        private PopupManager()
     55        {
     56        }
     57       
     58        private LinkedList<Popup> _popups = new LinkedList<Popup>();
     59
     60        /** Time its takes for a maximise/minimise to animate, in milliseconds. */
     61        //private final int ANIMATION_DURATION = 180;
     62        /** in milliseconds. TODO: Expand. cts16 */
     63        //private final int ANIMATION_RATE = 30;
     64       
     65        public void add(Popup p)
     66        {
     67                if (p == null) return;
     68
     69                synchronized(_popups) {
     70                        if (!_popups.contains(p)) _popups.add(p);
     71                }
     72        }
     73       
     74        public void remove(Popup p)
     75        {
     76                if (p == null) return;
     77
     78                synchronized(_popups) {
     79                        if (_popups.contains(p)) _popups.remove(p);
     80                }
     81        }
     82       
     83        public List<Popup> getPopups()
     84        {
     85                synchronized(_popups) {
     86                        return new LinkedList<Popup>(_popups);
     87                }
     88        }
     89       
     90        /**
     91         * Determines whether a given point is over a pop-up.
    7092         *
    7193         * @param p
    7294         *
    73          * @return True if p is over a popup
     95         * @return True if p is over a pop-up
    7496         *
    7597         * @throws NullPointerException
    7698         *              If p is null
    7799         */
    78         public boolean isPointOverPopup(Point p) {
     100        public boolean isPointOverPopup(Point p)
     101        {
    79102                if (p == null) throw new NullPointerException("p");
    80                 for (Popup pp : _popups.keySet()) {
    81                         if (pp.getBounds().contains(p)) {
    82                                 return true;
     103
     104                synchronized(_popups) {
     105                        for (Popup popup : _popups) {
     106                                if (popup.getBounds().contains(p)) return true;
    83107                        }
    84108                }
    85109               
    86110                return false;
    87         }
    88        
    89         /**
    90          * Tests a component to see if it is in invoker of an existing popup.
    91          *
    92          * @param c
    93          *      Must not be null.
    94          *
    95          * @return
    96          *              True if c is an invoker
    97          *
    98          * @throws NullPointerException
    99          *              If c is null
    100          */
    101         public boolean isInvoker(Component c) {
    102                 if (c == null) throw new NullPointerException("c");
    103                 return _invokers.contains(c);
    104         }
    105        
    106         /**
    107          * Gets an invoker for a popup
    108          *
    109          * @param p
    110          *              The popup to get the invoker for.
    111          *
    112          * @return
    113          *              The invoker for the given popup.
    114          *              Null if popup does not exist.
    115          */
    116         public Component getInvoker(Popup p) {
    117                 if (p == null) throw new NullPointerException("p");
    118                 return _popups.get(p);
    119111        }
    120112       
     
    130122         *              If p is null
    131123         */
    132         public boolean isShowing(Popup p) {
     124        public boolean isShowing(Popup p)
     125        {
    133126                if (p == null) throw new NullPointerException("p");
    134                 return _popups.containsKey(p);
     127
     128                synchronized(_popups) {
     129                        return _popups.contains(p) && p.isShowing();
     130                }
    135131        }
    136132       
    137133        /**
    138134         * @return
    139          *              True if a poup is showing. False otherwise.
    140          */
    141         public boolean isAnyPopupsShowing () {
    142                 return !_popups.isEmpty();
     135         *              True if a pop-up is showing. False otherwise.
     136         */
     137        public boolean isAnyPopupsShowing()
     138        {
     139                synchronized(_popups) {
     140                        return !_popups.isEmpty();
     141                }
     142        }
     143       
     144        public void hideAutoHidePopups()
     145        {
     146                synchronized(_popups) {
     147                        for (Popup p : _popups) {
     148                                if (p.doesAutoHide()) p.hide();
     149                        }
     150                }
    143151        }
    144152       
     
    146154         * @return
    147155         *              True if the mouse click event for going back a frame should be consumed
    148          *              Due to a popup requesting this event to be consumed currently showing.
    149          */
    150         public boolean shouldConsumeBackClick() {
    151                 for (Popup p : _popups.keySet()) {
    152                         if (p.shouldConsumeBackClick())
    153                                 return true;
     156         *              due to a pop-up requesting this event to be consumed currently showing.
     157         */
     158        public boolean shouldConsumeBackClick()
     159        {
     160                synchronized(_popups) {
     161                        for (Popup p : _popups) {
     162                                if (p.shouldConsumeBackClick()) return true;
     163                        }
    154164                }
    155165               
     
    157167        }
    158168       
    159         /**
    160          * Clears all popups from the browser that are autohidden.
    161          * Stops animations.
    162          */
    163         public void hideAutohidePopups() {
    164                
    165 
    166                 // Get rid of all animations that are not non-auto-hidden pops that are expanding
    167                 synchronized (_animatingPopups) {
    168                        
    169                         LinkedList<AnimatedPopup> animationsToClear = new LinkedList<AnimatedPopup>();
    170                        
    171                         for (AnimatedPopup ap : _animatingPopups) {
    172                                 if (!(ap.popup != null && !ap.popup.doesAutoHide())) {
    173                                         animationsToClear.add(ap);
    174                                 }
    175                         }
    176                        
    177                         _animatingPopups.removeAll(animationsToClear);
    178                        
    179                 }
    180                
    181                 LinkedList<Popup> popupsToClear = new LinkedList<Popup>();
    182                 LinkedList<Component> invokersToClear = new LinkedList<Component>();
    183 
    184                 // Get ride of the actual popups
    185                 for (Popup p : _popups.keySet()) {
    186                         if (p.doesAutoHide()) {
    187                                
    188                                 popupsToClear.add(p);
    189                                 invokersToClear.add(_popups.get(p));
    190                                
    191                                 p.invalidateAppearance();
    192                                 p.setVisible(false);
    193                                 Browser._theBrowser.getLayeredPane().remove(p);
    194                                 p.onHide();
    195                         }
    196                 }
    197                
    198                 assert (popupsToClear.size() == invokersToClear.size());
    199                
    200                 for (int i = 0; i < popupsToClear.size(); i++) {
    201                         _popups.remove(popupsToClear.get(i));
    202                         _invokers.remove(invokersToClear.get(i));
    203                 }
    204                
    205 
    206                
    207         }
    208        
    209        
    210        
    211 //      public void hideAllPopups() {
    212 //             
    213 //              for (Popup p : _popups.keySet()) {
    214 //                      invalidatePopup(p);
    215 //                      p.setVisible(false);
    216 //                      Browser._theBrowser.getLayeredPane().remove(p);
    217 //                      p.onHide();
    218 //              }
    219 //              _popups.clear();
    220 //              _invokers.clear();
    221 //             
    222 //              // Get rid of all animations
    223 //              synchronized (_animatingPopups) {
    224 //                      _animatingPopups.clear();
    225 //              }
    226 //      }
    227        
    228         public void frameChanged() {
    229                 // Remove any popups that are showing on the current frame
    230                 hideAutohidePopups();
    231         }
    232 
    233         /**
    234          * Hides a popup - if not already hidden.
    235          *
    236          * @param p
    237          *              Must not be null.
    238          *
    239          * @throws NullPointerException
    240          *              If p is null
    241          */
    242         public void hidePopup(Popup p) {
    243                 if (p == null) throw new NullPointerException("p");
    244                
    245                 if (!isShowing(p) && (!p.isVisible() || p.getParent() == null)) return;
    246                
    247 
    248                 // Cancel any showing animations
    249                 synchronized (_animatingPopups) {
    250                         AnimatedPopup toRemove = null;
    251                         for (AnimatedPopup ap : _animatingPopups) {
    252                                 if (ap.popup == p) {
    253                                         toRemove = ap;
    254                                         break;
    255                                 }
    256                         }
    257                         if (toRemove != null)
    258                                 _animatingPopups.remove(toRemove);
    259                 }
    260 
    261                 p.invalidateAppearance();
    262                 p.setVisible(false);
    263                 Browser._theBrowser.getLayeredPane().remove(p);
    264                 Component invoker = _popups.remove(p);
    265                 if (invoker != null) _invokers.remove(invoker);
    266                 p.onHide();
    267                
    268         }
    269        
    270         /**
    271          * Hides a popup - with animation. - if not already hidden.
    272          *
    273          * @param p
    274          *              Must not be null.
    275          * @param animator
    276          *              Must not be null.
    277          *
    278          * @throws NullPointerException
    279          *              If p or animator is null
    280          *
    281          */
    282         public void hidePopup(Popup p, PopupAnimator animator) {
    283                
    284                 if (p == null) throw new NullPointerException("p");
    285                 if (animator == null) throw new NullPointerException("animator");
    286                
    287                 if (!isShowing(p) && (!p.isVisible() || p.getParent() == null)) return;
    288                
    289                 hidePopup(p);
    290                 AnimatedPopup ap = new AnimatedPopup(
    291                                 animator,
    292                                 System.currentTimeMillis(),
    293                                 null,
    294                                 false,
    295                                 p.getLocation());
    296 
    297                 animator.starting(false, p.getBounds());
    298                
    299                 synchronized (_animatingPopups) {
    300                         _animatingPopups.add(ap);
    301                 }
    302 
    303                 if (_animationThread == null || !_animationThread.isAlive() || _animationThread.willDie) {
    304                         _animationThread = new AnimationThread();
    305                         _animationThread.start();
    306                 }
    307         }
    308        
    309        
    310        
    311         /**
    312          * Displays a popup at a specific location.
    313          *
    314          * @param p
    315          *              Must not be null.
    316          *
    317          * @param invoker
    318          *                      The component responsible for showing the popup. can be null.
    319          *                      Used such that when invoker pressed, the popup will not auto hide.
    320          *
    321          * @param loc
    322          *              Must not be null.
    323          *
    324          * @throws NullPointerException
    325          *              If p or loc is null
    326          *
    327          */
    328         public void showPopup(Popup p, Point loc, Component invoker) {
    329                 if (p == null) throw new NullPointerException("p");
    330                 if (loc == null) throw new NullPointerException("animator");
    331                
    332                
    333                 if (_popups.containsKey(p)) return;
    334 
    335                 p.prepareToPaint();
    336                 p.setLocation(loc);
    337                 p.setVisible(true);
    338 
    339                 Browser._theBrowser.getLayeredPane().add(p, JLayeredPane.POPUP_LAYER, 0);
    340 
    341                 _popups.put(p, invoker);
    342                 if (invoker != null) _invokers.add(invoker);
    343                
    344                 p.onShowing();
    345                 p.onShow();
    346                
    347                 // Invalidate the popup border
    348                 if (p.getBorderThickness() > 0.0f) {
    349                         p.invalidateAppearance();
    350                 }
    351         }
    352        
    353         /**
    354          * Displays a popup at a specific location - with animation.
    355          *
    356          * @param p
    357          *              Must not be null.
    358          *
    359          * @param invoker
    360          *                      The component responsible for showing the popup. can be null.
    361          *                      Used such that when invoker pressed, the popup will not auto hide.
    362          *
    363          * @param loc
    364          *              Must not be null.
    365          *
    366          * @param animator
    367          *              Must not be null.
    368          *
    369          * @throws NullPointerException
    370          *              If p, animator or loc is null
    371          */
    372         public void showPopup(Popup p, Point loc, Component invoker, PopupAnimator animator) {
    373                 if (animator == null)
    374                         throw new NullPointerException("animator");
    375                 if (p == null)
    376                         throw new NullPointerException("p");
    377                 if (loc == null)
    378                         throw new NullPointerException("loc");
    379                
    380                 if (_popups.containsKey(p)) return;
    381                
    382                 _popups.put(p, invoker);
    383                 if (invoker != null) _invokers.add(invoker);
    384                
    385                
    386                 AnimatedPopup ap = new AnimatedPopup(
    387                                 animator,
    388                                 System.currentTimeMillis(),
    389                                 p,
    390                                 true,
    391                                 loc);
    392                
    393                
    394                 animator.starting(true, new Rectangle(loc.x, loc.y, p.getWidth(), p.getHeight()));
    395                
    396                 p.onShowing();
    397                
    398                 synchronized (_animatingPopups) {
    399                         _animatingPopups.add(ap);
    400                 }
    401 
    402                 if (_animationThread == null || !_animationThread.isAlive() || _animationThread.willDie) {
    403                         _animationThread = new AnimationThread();
    404                         _animationThread.start();
    405                 }
    406 
    407         }
    408        
    409         /**
    410          * Does a pure asynch animation with no popups involved.
    411          *
    412          * For example you may want to have an effect such that an item is expanding
    413          * or moving into a new location on the screen.
    414          *
    415          * @param animator
    416          *              Must not be null.
    417          *
    418          * @param target
    419          *              Must not be null.
    420          *
    421          * @throws NullPointerException
    422          *              If animator or target is null
    423          *
    424          */
    425         public void doPureAnimation(PopupAnimator animator, Rectangle target) {
    426                
    427                 if (animator == null)
    428                         throw new NullPointerException("animator");
    429                 if (target == null)
    430                         throw new NullPointerException("target");
    431                
    432                 AnimatedPopup ap = new AnimatedPopup(
    433                                 animator,
    434                                 System.currentTimeMillis(),
    435                                 null,
    436                                 false,
    437                                 target.getLocation());
    438                
    439                
    440                 animator.starting(true, target);
    441 
    442                 synchronized (_animatingPopups) {
    443                         _animatingPopups.add(ap);
    444                 }
    445 
    446                 if (_animationThread == null || !_animationThread.isAlive() || _animationThread.willDie) {
    447                         _animationThread = new AnimationThread();
    448                         _animationThread.start();
    449                 }
    450                
    451         }
    452        
    453 
    454         /**
    455          * Paints all popups in the browsers popup pane with the given graphics.
    456          *
    457          * @param g
    458          *              Where to paint to.
    459          *
    460          * @param clip
    461          */
    462         void paintLayeredPane(Graphics g, Area clip) {
    463                  if (Browser._theBrowser == null) return;
    464                  
    465                 Component[] compsOnPopup = Browser._theBrowser.getLayeredPane().getComponentsInLayer(JLayeredPane.POPUP_LAYER);
    466 
    467                 for (int i = 0; i < compsOnPopup.length; i++) {
    468                         Component c = compsOnPopup[i];
    469        
    470                         Point p = c.getLocation();
    471 
    472                         if (clip == null || clip.intersects(c.getBounds())) {
    473                                 g.translate(p.x, p.y);
    474                                 c.paint(g);
    475                                 g.translate(-p.x, -p.y);
    476                         }
    477                        
    478                 }
     169        public void frameChanged()
     170        {
    479171        }
    480172
     
    482174         * Paints current popup animations to the expeditee browser content pane.
    483175         */
    484         void paintAnimations() {
    485                
    486                 if (Browser._theBrowser == null
    487                                 || Browser._theBrowser.g == null) return;
    488                
    489                 Graphics g = Browser._theBrowser.g;
    490                
    491                 synchronized (_animatingPopups) {
    492                        
    493                         for (AnimatedPopup ap : _animatingPopups) {
    494                                 ap.animator.paint(g);
    495                         }
    496                        
    497                 }
    498         }
    499        
    500         /**
    501          * Proccesses animation on a dedicated thread.
     176        public void paint()
     177        {
     178                synchronized (_popups) {
     179                        for (Popup popup : _popups) {
     180                                popup.update();
     181                                popup.paint();
     182                        }
     183                }
     184        }
     185       
     186        /**
     187         * Provides animations for a popup when hiding or when showing.
     188         *
     189         * Note that {@link PopupAnimator#paint(Graphics)} and {@link PopupAnimator#update(float)}
     190         * will always be invoked at seperate times - so do not have to worry about thread-safety.
     191         *
     192         * These should only be used once... one per popup at a time.
    502193         *
    503194         * @author Brook Novak
    504          *
    505          */
    506         private class AnimationThread extends Thread {
    507                
    508                 private boolean willDie = false;
     195         */
     196        public static abstract class PopupAnimator
     197        {
     198                /** True if animating to show the popup, false if to hide. */
     199                private boolean _showing = true;
     200               
     201                /** Whether the animation is currently paused. */
     202                private boolean _paused = true;
     203               
     204                private long _startTime;
     205                private long _duration;
     206                private long _animationCurrentTime;
     207               
     208                public PopupAnimator()
     209                {
     210                        _animationCurrentTime = _startTime = System.currentTimeMillis();
     211                        _duration = getDurationMillis();
     212                }
     213               
     214                /**
     215                 * @return False if the animation has finished, true if further updates are required.
     216                 */
     217                public boolean update()
     218                {
     219                        long currentTime = System.currentTimeMillis();
     220                       
     221                        if (currentTime > _startTime + _duration) {
     222                                currentTime = _startTime + _duration;
     223                        }
     224                       
     225                        // If paused, make sure elapsed time stays constant
     226                        if (_paused) {
     227                                _startTime += currentTime - _animationCurrentTime;
     228                        }
     229                       
     230                        _animationCurrentTime = currentTime;
     231                       
     232                        return !isFinished();
     233                }
     234               
     235                public void hide()
     236                {
     237                        if (!_showing) return;
     238                       
     239                        _showing = false;
     240                        complementAnimationProgress();
     241                }
     242               
     243                public void show()
     244                {
     245                        if (_showing) return;
     246                       
     247                        _showing = true;
     248                        complementAnimationProgress();
     249                }
     250               
     251                public boolean isShowing()
     252                {
     253                        return _showing;
     254                }
     255               
     256                public void start()
     257                {
     258                        _animationCurrentTime = _startTime = System.currentTimeMillis();
     259                        unpause();
     260                }
     261               
     262                public void pause()
     263                {
     264                        pause(true);
     265                }
     266               
     267                public void unpause()
     268                {
     269                        pause(false);
     270                }
     271               
     272                public void pause(boolean pause)
     273                {
     274                        _paused = pause;
     275                }
     276               
     277                private void complementAnimationProgress()
     278                {
     279                        _startTime = _animationCurrentTime - ((_startTime + _duration) - _animationCurrentTime);
     280                }
     281               
     282                public float getProgress()
     283                {
     284                        return (_animationCurrentTime - _startTime) / ((float) _duration);
     285                }
     286               
     287                public boolean isFinished()
     288                {
     289                        return _animationCurrentTime != _startTime + _duration;
     290                }
     291               
     292                public abstract long getDurationMillis();
     293               
     294                public abstract AxisAlignedBoxBounds getAnimatedBounds(AxisAlignedBoxBounds fullBounds);
     295               
     296        }
     297       
     298        public static class ExpandShrinkAnimator extends PopupAnimator
     299        {
     300                public static final long DURATION_MS = 2000;
     301               
     302                public AxisAlignedBoxBounds _initialBounds = null;
     303               
     304                public ExpandShrinkAnimator()
     305                {
     306                }
     307               
     308                public ExpandShrinkAnimator(AxisAlignedBoxBounds initialBounds)
     309                {
     310                        setInitialBounds(initialBounds);
     311                }
     312               
     313                public void setInitialBounds(AxisAlignedBoxBounds initialBounds)
     314                {
     315                        _initialBounds = initialBounds;
     316                }
    509317               
    510318                @Override
    511                 public void run() {
    512                        
    513                        
    514                          LinkedList<AnimatedPopup> finishedAnimations;
    515                          
    516                          while (true) {
    517                          
    518                                  // Perform animation logic
    519                                  finishedAnimations = animate();
    520                                
    521                                  // Check if finished all animations
    522                                  if (finishedAnimations == null) return; // done
    523                                  
    524                                  // Check for finalization of animation. That is, adding the popups to the layered pane
    525                                  boolean needsFinalization = false;
    526                                  for (AnimatedPopup ap : finishedAnimations) {
    527                                          if (ap.isShowing) {
    528                                                  needsFinalization = true;
    529                                                  break;
    530                                          }
    531                                          
    532                                          // FInal invalidation
    533                                          FrameGraphics.invalidateArea(ap.animator.getCurrentDrawingArea());
    534                                          
    535                                  }
    536                                  
    537                                  if (needsFinalization) {
    538                                          SwingUtilities.invokeLater(new AnimationFinalizor(finishedAnimations));
    539                                          // Will repaint when a popup becomes anchored...
    540                                  } else {
    541                                          FrameGraphics.requestRefresh(true);
    542                                  }
    543 
    544                                  // Limit animation rate
    545                                  try {
    546                                          sleep(ANIMATION_RATE);
    547                                  } catch (InterruptedException e) {
    548                                         e.printStackTrace();
    549                                  }
    550                        
    551                          }
    552                        
    553                 }
    554                
    555                 /**
    556                  * Performs animations
    557                  * @return
    558                  */
    559                 private LinkedList<AnimatedPopup> animate() {
    560                        
    561                         LinkedList<AnimatedPopup> finishedPopups = null;
    562                        
    563                         synchronized (_animatingPopups) {
    564                                
    565                                 if (_animatingPopups.isEmpty()) {
    566                                         willDie = true;
    567                                         return null;
    568                                 }
    569 
    570                                 long currentTime = System.currentTimeMillis();
    571                                
    572                                 finishedPopups = new LinkedList<AnimatedPopup>();
    573                                
    574                                 for (AnimatedPopup ap : _animatingPopups) {
    575                                        
    576                                         long duration = currentTime - ap.startTime;
    577                                        
    578                                         if (duration >= ANIMATION_DURATION) { // check if complete
    579                                                
    580                                                 finishedPopups.add(ap);
    581        
    582                                         } else {
    583                                                
    584                                                 float percent = ((float)duration / (float)ANIMATION_DURATION);
    585                                                 assert (percent >= 0.0f);
    586                                                 assert (percent < 1.0f);
    587                                                
    588                                                 Rectangle dirty = ap.animator.update(percent);
    589                                                 if (dirty != null)
    590                                                         FrameGraphics.invalidateArea(dirty);
    591                                                
    592                                         }
    593 
    594                                 }
    595                                
    596                                 _animatingPopups.removeAll(finishedPopups);
    597                                
    598                         }
    599                        
    600                         return finishedPopups;
    601                        
    602                 }
    603                
    604                 /**
    605                  * Adds popups to layered pane
    606                  * @author Brook Novak
    607                  *
    608                  */
    609                 private class AnimationFinalizor implements Runnable {
    610 
    611                         private LinkedList<AnimatedPopup> finished;
    612                        
    613                         AnimationFinalizor(LinkedList<AnimatedPopup> finished) {
    614                                 this.finished = finished;
    615                         }
    616                        
    617                         public void run() {
    618                                
    619                                 for (AnimatedPopup ap : finished) {
    620                                        
    621                                         if (ap.isShowing && _popups.containsKey(ap.popup)) {
    622 
    623                                                 ap.popup.prepareToPaint();
    624                                                 ap.popup.setLocation(ap.popupLocation);
    625                                                 ap.popup.setVisible(true);
    626 
    627                                                 Browser._theBrowser.getLayeredPane().add(ap.popup, JLayeredPane.POPUP_LAYER, 0);
    628                                                
    629                                                 ap.popup.onShow();
    630                                                
    631                                                 // Invalidate the popup border
    632                                                 if (ap.popup.getBorderThickness() > 0.0f) {
    633                                                         ap.popup.invalidateAppearance();
    634                                                 }
    635                                         }
    636                                        
    637                                 }
    638                                
    639                         }
    640                 }
    641         }
    642        
    643         private class AnimatedPopup {
    644                
    645                 PopupAnimator animator;
    646                 long startTime;
    647                 Popup popup = null;
    648                 boolean isShowing;
    649                 Point popupLocation;
    650                
    651                 public AnimatedPopup(PopupAnimator animator, long startTime, Popup popup,
    652                                 boolean isShowing, Point popupLocation) {
    653                        
    654                         assert(animator != null);
    655                         assert(popupLocation != null);
    656                        
    657                         // Only have popup if showing
    658                         assert (!isShowing && popup == null || (isShowing && popup != null));
    659                        
    660                        
    661                         this.animator = animator;
    662                         this.startTime = startTime;
    663                         this.popup = popup;
    664                         this.isShowing = isShowing;
    665                         this.popupLocation = popupLocation;
    666 
    667                 }
    668 
    669         }
    670        
    671         /**
    672          * Provides animations for a popup when hiding or when showing.
    673          *
    674          * Note that {@link PopupAnimator#paint(Graphics)} and {@link PopupAnimator#update(float)}
    675          * will always be invoked at seperate times - so do not have to worry about thread-saefty.
    676          *
    677          * These should only be used once... one per popup at a time.
    678          *
    679          * @author Brook Novak
    680          *
    681          */
    682         public interface PopupAnimator {
    683                
    684                 /**
    685                  * Invoked before showing. Any prepaations are done here.
    686                  *
    687                  * @param isShowing
    688                  *              True if this animation will be for a popup that is showing.
    689                  *              False if this animation will be for a popup that is hiding.
    690                  *
    691                  * @param popupBounds
    692                  *              The location of the popup. I.E. where it is, or where it will be.
    693                  *
    694                  */
    695                 void starting(boolean isShowing, Rectangle popupBounds);
    696                
    697                 /**
    698                  *
    699                  * Called on an animation thread.
    700                  *
    701                  * @param percent
    702                  *              The percent complete of the animations.
    703                  *              Rangles from 0 to 1.
    704                  *
    705                  * @return dirty area that needs painting for last update... Null for no invalidation
    706                  *             
    707                  *
    708                  */
    709                 Rectangle update(float percent);
    710                
    711                 /**
    712                  * Paints the animation - on the swing thread.
    713                  * Note that this is always on the content pane - not the expeditee frame buffer.
    714                  *
    715                  * @param g
    716                  *
    717                  */
    718                 void paint(Graphics g);
    719                
    720                
    721                 /**
    722                  *
    723                  * @return
    724                  *              The area which the animation is drawn. Used for final invalidation. Null for no final invaliation
    725                  */
    726                 Rectangle getCurrentDrawingArea();
    727                
    728         }
    729        
    730        
    731         public class ExpandShrinkAnimator implements PopupAnimator {
    732                
    733                 private boolean isShowing;
    734                 private Rectangle popupBounds;
    735                 private Rectangle sourceRectangle;
    736                 private Rectangle currentRectangle;
    737                 private Color fillColor;
    738                
    739                 private final Stroke stroke = new BasicStroke(2.0f);
    740                
    741                 /**
    742                  *
    743                  * @param sourceRectangle
    744                  * @param fillColor
    745                  *              The fill color of the animated rectangle. Null for no fill.
    746                  */
    747                 public ExpandShrinkAnimator(Rectangle sourceRectangle, Color fillColor) {
    748                         if (sourceRectangle == null) throw new NullPointerException("sourceRectangle");
    749                        
    750                         this.fillColor = fillColor;
    751                         this.sourceRectangle = (Rectangle)sourceRectangle.clone();
    752                         this.currentRectangle = (Rectangle)sourceRectangle.clone();
    753                 }
    754 
    755                 public void paint(Graphics g) {
    756                        
    757                         if (fillColor != null) {
    758                                 g.setColor(fillColor);
    759                                 g.fillRect(currentRectangle.x, currentRectangle.y, currentRectangle.width, currentRectangle.height);
    760                         }
    761                        
    762                         g.setColor(Color.BLACK);
    763                         ((Graphics2D)g).setStroke(stroke);
    764                         g.drawRect(currentRectangle.x, currentRectangle.y, currentRectangle.width, currentRectangle.height);
    765                 }
    766 
    767                 public void starting(boolean isShowing, Rectangle popupBounds) {
    768                         this.isShowing = isShowing;
    769                         this.popupBounds = popupBounds;
    770                        
    771                         if (isShowing) {
    772                                 this.currentRectangle = (Rectangle)sourceRectangle.clone();
    773                         } else {
    774                                 this.currentRectangle = (Rectangle)sourceRectangle.clone();
    775                         }
    776                        
    777                 }
    778 
    779                 public Rectangle update(float percent) {
    780 
    781                         Rectangle oldBounds = currentRectangle;
    782                        
    783                         if (!isShowing) { // if minimizing just reverse percent
    784                                 percent = 1 - percent;
    785                         }
    786                        
    787                         // update X
    788                         currentRectangle.x = sourceRectangle.x +
    789                                 (int)((popupBounds.x - sourceRectangle.x) * percent);
    790                        
    791                         // update Y
    792                         currentRectangle.y = sourceRectangle.y +
    793                                 (int)((popupBounds.y - sourceRectangle.y) * percent);
    794                        
    795                         // update width
    796                         currentRectangle.width = sourceRectangle.width +
    797                                 (int)((popupBounds.width - sourceRectangle.width) * percent);
    798                        
    799                         // update height
    800                         currentRectangle.height = sourceRectangle.height +
    801                                 (int)((popupBounds.height - sourceRectangle.height) * percent);
    802                        
    803                         int x = Math.min(oldBounds.x, currentRectangle.x);
    804                         int y = Math.min(oldBounds.y, currentRectangle.y);
    805                         int width = Math.min(oldBounds.x + oldBounds.width, currentRectangle.x + currentRectangle.width) - x;
    806                         int height = Math.min(oldBounds.y + oldBounds.height, currentRectangle.y + currentRectangle.height) - y;
    807                        
    808                         return new Rectangle(x, y, width, height);
    809                        
    810                 }
    811                
    812                 public Rectangle getCurrentDrawingArea() {
    813                         return currentRectangle;
    814                 }
    815 
    816 
    817         }
    818        
    819 
     319                public long getDurationMillis() { return DURATION_MS; }
     320
     321                @Override
     322                public AxisAlignedBoxBounds getAnimatedBounds(AxisAlignedBoxBounds fullBounds)
     323                {
     324                        if (_initialBounds == null) {
     325                                setInitialBounds(fullBounds.clone());
     326                                _initialBounds.getTopLeft().y += _initialBounds.getSize().height;
     327                                _initialBounds.getSize().height = 0;
     328                        }
     329                       
     330                        float percentShown = getProgress();
     331                        if (!isShowing()) percentShown = 1 - percentShown;
     332                       
     333                        return AxisAlignedBoxBounds.lerp(_initialBounds, fullBounds, percentShown);
     334                }
     335        }
    820336}
  • trunk/src/org/expeditee/gui/Reminders.java

    r919 r1102  
    1919package org.expeditee.gui;
    2020
    21 import java.awt.Color;
    2221import java.util.Date;
    2322
     23import org.expeditee.Util;
    2424import org.expeditee.actions.Misc;
     25import org.expeditee.core.Colour;
    2526import org.expeditee.items.Text;
    26 import org.expeditee.items.widgets.charts.TimeSeries;
    2727
    2828public class Reminders {
     
    4646                                }
    4747
    48                                 Date date = TimeSeries.parseDate(dateString);
     48                                Date date = Util.parseDate(dateString);
    4949                                long millisToWait = date.getTime() - new Date().getTime();
    5050                                final long adjustedToWait;
     
    6969                                                                MessageBay.displayMessage(
    7070                                                                                "Reminder: " + reminderString, null,
    71                                                                                 Color.red, false, "StopReminder");
     71                                                                                Colour.RED, false, "StopReminder");
    7272                                                                Thread.sleep(5000);
    7373                                                                // newMessage.setColor(new Color(100, 70, 70));
  • trunk/src/org/expeditee/gui/Vector.java

    r919 r1102  
    1919package org.expeditee.gui;
    2020
    21 import java.awt.Color;
    22 import java.awt.Dimension;
    23 import java.awt.Point;
    2421import java.text.NumberFormat;
    2522
     23import org.expeditee.core.Colour;
     24import org.expeditee.core.Dimension;
     25import org.expeditee.core.Point;
    2626import org.expeditee.items.Item;
    2727import org.expeditee.items.UserAppliedPermission;
    2828
     29/**
     30 * TODO: Explain WTF this is. cts16
     31 */
    2932public class Vector extends Overlay {
    3033
     34        /** TODO: Comment. cts16 */
    3135        public Point Origin;
    3236
     37        /** TODO: Comment. cts16 */
    3338        public float Scale;
    3439
    35         public Color Foreground;
     40        /** TODO: Comment. cts16 */
     41        public Colour Foreground;
    3642
    37         public Color Background;
    38        
     43        /** TODO: Comment. cts16 */
     44        public Colour Background;
     45
     46        /** TODO: Comment. cts16 */
    3947        public Item Source;
    40        
     48
     49        /** TODO: Comment. cts16 */
    4150        public Dimension Size;
    4251
    43         public Vector(Frame overlay, UserAppliedPermission permission,
    44                         Float scale, Item source) {
     52        /** TODO: Comment. cts16 */
     53        public Vector(Frame overlay, UserAppliedPermission permission, Float scale, Item source)
     54        {
    4555                super(overlay, permission);
    4656                Origin = source.getPosition();
     
    5262
    5363        @Override
    54         public boolean equals(Object o) {
    55                 if (o == null || o.getClass() != Vector.class)
    56                         return false;
    57                 Vector v = (Vector) o;
    58 
    59                 return v.Frame == Frame && Origin.equals(v.Origin)
    60                                 && Scale == v.Scale && Foreground == v.Foreground
    61                                 && Background == v.Background;
     64        public boolean equals(Object o)
     65        {
     66                if (o instanceof Vector) {
     67                        Vector v = (Vector) o;
     68                        return v.Frame == Frame &&
     69                                        Origin.equals(v.Origin) &&
     70                                        Scale == v.Scale &&
     71                                        Foreground.equals(v.Foreground) &&
     72                                        Background.equals(v.Background);
     73                }
     74               
     75                return false;
     76               
    6277        }
    6378
    6479        @Override
    65         public int hashCode() {
     80        public int hashCode()
     81        {
    6682                return 0;
    6783        }
    6884
    69         /**
    70          * Converts the given x position to be relative to the overlay frame.
    71          *
    72          * @param x
    73          * @return
    74          */
    75         public float getX(int x) {
     85        /** Converts the given x position to be relative to the overlay frame. */
     86        public float getX(int x)
     87        {
    7688                return (x - Origin.x) / Scale;
    7789        }
    7890
    79         public float getY(int y) {
     91        /** Converts the given y position to be relative to the overlay frame. */
     92        public float getY(int y)
     93        {
    8094                return (y - Origin.y) / Scale;
    8195        }
    8296
    83         public void setSize(int maxX, int maxY) {
     97        /** TODO: Comment. cts16 */
     98        public void setSize(int maxX, int maxY)
     99        {
    84100                Size = new Dimension(maxX, maxY);
    85101        }
    86102
    87         public static NumberFormat getNumberFormatter() {
     103        /** TODO: Comment. cts16 */
     104        public static NumberFormat getNumberFormatter()
     105        {
    88106                NumberFormat nf = NumberFormat.getInstance();
    89107                nf.setMaximumFractionDigits(4);
  • trunk/src/org/expeditee/importer/FileImporter.java

    r919 r1102  
    1919package org.expeditee.importer;
    2020
    21 import java.awt.Point;
    2221import java.io.File;
    2322import java.io.IOException;
    2423
     24import org.expeditee.core.Point;
    2525import org.expeditee.items.Item;
    2626
  • trunk/src/org/expeditee/importer/FilePathImporter.java

    r919 r1102  
    1919package org.expeditee.importer;
    2020
    21 import java.awt.Point;
    2221import java.io.File;
    2322import java.io.IOException;
    2423
     24import org.expeditee.core.Point;
     25import org.expeditee.gio.DragAndDropManager;
    2526import org.expeditee.items.Item;
    2627
     
    3637        public Item importFile(File f, Point location) throws IOException {
    3738                if (location != null && f != null) {
    38                         return FrameDNDTransferHandler.importString(f.getAbsolutePath(), location);                     
     39                        return DragAndDropManager.importString(f.getAbsolutePath(), location);                 
    3940                }
    4041
  • trunk/src/org/expeditee/importer/FrameDNDTransferHandler.java

    r919 r1102  
    1919package org.expeditee.importer;
    2020
    21 import java.awt.Point;
    2221import java.awt.datatransfer.DataFlavor;
    2322import java.awt.datatransfer.UnsupportedFlavorException;
     
    3231import javax.swing.TransferHandler;
    3332
     33import org.expeditee.core.Point;
     34import org.expeditee.gio.swing.SwingConversions;
    3435import org.expeditee.gui.DisplayIO;
    3536import org.expeditee.gui.FrameGraphics;
     
    6566        }
    6667
    67         private FrameDNDTransferHandler() {
    68 
     68        private FrameDNDTransferHandler()
     69        {
    6970                // Add standard file importers - order from most ideal to last resort
    7071                // (if competing)
     
    7475                _standardFileImporters.add(new pdfImporter());
    7576                _standardFileImporters.add(new TextImporter());
    76                 _standardFileImporters.add(new FilePathImporter()); // Filepath importer
    77                 // as last resort
     77                _standardFileImporters.add(new FilePathImporter()); // Filepath importer as last resort
    7878
    7979                try {
    80                         _URIListDataflavorString = new DataFlavor(
    81                                         "text/uri-list;class=java.lang.String");
    82                         _URIListDataflavorCharArray = new DataFlavor(
    83                                         "text/uri-list;class=\"[C\"");
    84                 } catch (ClassNotFoundException e) { // This would never happen,
    85                         // java.lang.String is always
    86                         // present
     80                        _URIListDataflavorString = new DataFlavor("text/uri-list;class=java.lang.String");
     81                        _URIListDataflavorCharArray = new DataFlavor("text/uri-list;class=\"[C\"");
     82                       
     83                // This would never happen, java.lang.String is always present
     84                } catch (ClassNotFoundException e) {
    8785                        e.printStackTrace();
    8886                        _URIListDataflavorString = null;
     
    104102         *             if importer is null.
    105103         */
    106         public void addCustomFileImporter(FileImporter importer) {
    107                 if (importer == null)
    108                         throw new NullPointerException("importer");
    109                 if (!_customFileImporters.contains(importer))
     104        public void addCustomFileImporter(FileImporter importer)
     105        {
     106                if (importer == null) throw new NullPointerException("importer");
     107               
     108                if (!_customFileImporters.contains(importer)) {
    110109                        _customFileImporters.add(importer);
     110                }
    111111
    112112        }
     
    121121         *             if importer is null.
    122122         */
    123         public void removeCustomFileImporter(FileImporter importer) {
    124                 if (importer == null)
    125                         throw new NullPointerException("importer");
     123        public void removeCustomFileImporter(FileImporter importer)
     124        {
     125                if (importer == null) throw new NullPointerException("importer");
     126               
    126127                _customFileImporters.remove(importer);
    127128        }
     
    135136
    136137                // we only import Strings
    137                 if (support.isDataFlavorSupported(DataFlavor.stringFlavor)
    138                                 || support.isDataFlavorSupported(DataFlavor.javaFileListFlavor)
    139                                 || support.isDataFlavorSupported(_URIListDataflavorString)
    140                                 || support.isDataFlavorSupported(_URIListDataflavorCharArray)) {
    141 
     138                if (    support.isDataFlavorSupported(DataFlavor.stringFlavor) ||
     139                                support.isDataFlavorSupported(DataFlavor.javaFileListFlavor) ||
     140                                support.isDataFlavorSupported(_URIListDataflavorString) ||
     141                                support.isDataFlavorSupported(_URIListDataflavorCharArray))
     142                {
    142143                        // check if the source actions (a bitwise-OR of supported actions)
    143144                        // contains the COPY action
     
    154155
    155156        @Override
    156         public boolean importData(TransferSupport support) {
    157 
    158                 if (!canImport(support) || DisplayIO.getCurrentFrame() == null)
    159                         return false;
    160 
    161                 // Get the drop location of where to lot the import
     157        public boolean importData(TransferSupport support)
     158        {
     159                if (!canImport(support) || DisplayIO.getCurrentFrame() == null) return false;
     160
     161                // Get the location of where to drop the import
    162162                DropLocation location = support.getDropLocation();
    163163
    164                 // Covert it into expeditee space
    165                 Point expediteeDropPoint = location.getDropPoint();
     164                // Convert it into expeditee space
     165                Point expediteeDropPoint = SwingConversions.fromSwingPoint(location.getDropPoint());
    166166
    167167                try {
     
    170170                        // keep trying until first
    171171                        // data flavor recognized.
    172                         for (DataFlavor df : support.getTransferable()
    173                                         .getTransferDataFlavors()) {
     172                        for (DataFlavor df : support.getTransferable().getTransferDataFlavors()) {
    174173
    175174                                System.out.println(df);
     
    177176                                if (df == DataFlavor.stringFlavor) { // import as text item
    178177
    179                                         String str = (String) support.getTransferable()
    180                                                         .getTransferData(DataFlavor.stringFlavor);
     178                                        String str = (String) support.getTransferable().getTransferData(DataFlavor.stringFlavor);
    181179
    182180                                        if (str != null && str.length() > 0) {
     
    185183                                        }
    186184
    187                                         // Usually Windows and MAC enviroments
    188                                 } else if (df == DataFlavor.javaFileListFlavor
    189                                                 || df.getSubType().equals("x-java-file-list")) { // Windows
    190                                         // has
    191                                         // other
    192                                         // random
    193                                         // types...
    194 
    195                                         List<? extends File> files = (List<? extends File>) support
    196                                                         .getTransferable().getTransferData(
    197                                                                         DataFlavor.javaFileListFlavor);
     185                                // Usually Windows and MAC enviroments
     186                                // Windows has other random types...
     187                                } else if (df == DataFlavor.javaFileListFlavor || df.getSubType().equals("x-java-file-list")) {
     188
     189                                        List<? extends File> files = (List<? extends File>) support.getTransferable().getTransferData(DataFlavor.javaFileListFlavor);
    198190
    199191                                        importFileList(files, expediteeDropPoint);
     
    201193                                        return true;
    202194
    203                                         // Usually GNOME and KDE enviroments
     195                                // Usually GNOME and KDE enviroments
    204196                                } else if (df.equals(_URIListDataflavorString)) {
    205197
    206                                         String data = (String) support.getTransferable()
    207                                                         .getTransferData(_URIListDataflavorString);
     198                                        String data = (String) support.getTransferable().getTransferData(_URIListDataflavorString);
    208199
    209200                                        List<File> files = textURIListToFileList(data);
     
    215206                                } else if (df.equals(_URIListDataflavorCharArray)) {
    216207
    217                                         char[] data = (char[]) support.getTransferable()
    218                                                         .getTransferData(_URIListDataflavorCharArray);
     208                                        char[] data = (char[]) support.getTransferable().getTransferData(_URIListDataflavorCharArray);
    219209
    220210                                        String uriString = new String(data);
     
    229219
    230220                } catch (UnsupportedFlavorException e) {
    231                         MessageBay
    232                                         .displayMessage("Drag and drop for that type of data is not supported");
     221                        MessageBay.displayMessage("Drag and drop for that type of data is not supported");
    233222                } catch (IOException e) {
    234223                        e.printStackTrace();
     
    246235         *
    247236         * @param expediteeDropPoint
    248          *            The location in the current ecpeditee frame of where to drop
     237         *            The location in the current expeditee frame of where to drop
    249238         *            the text item.
    250239         */
    251         public static Text importString(String text, Point expediteeDropPoint) {
    252 
     240        public static Text importString(String text, Point expediteeDropPoint)
     241        {
    253242                assert (DisplayIO.getCurrentFrame() != null);
    254243                assert (text != null && text.length() > 0);
    255244
    256                 Text importedTextItem = new Text(DisplayIO.getCurrentFrame()
    257                                 .getNextItemID(), text);
     245                Text importedTextItem = new Text(DisplayIO.getCurrentFrame().getNextItemID(), text);
    258246                importedTextItem.setPosition(expediteeDropPoint);
    259247
     
    264252        }
    265253
    266         public void importFileList(List<? extends File> files,
    267                         Point expediteeDropPoint) throws IOException {
    268 
    269                 Point currentPoint = expediteeDropPoint.getLocation();
    270 
    271                 for (File fileToImport : files) { // import files one by one
     254        public void importFileList(List<? extends File> files, Point expediteeDropPoint) throws IOException
     255        {
     256                Point currentPoint = new Point(expediteeDropPoint);
     257
     258                 // import files one by one
     259                for (File fileToImport : files) {
    272260
    273261                        Item lastItem = importFile(fileToImport, currentPoint);
     
    296284         * @throws IOException
    297285         */
    298         public Item importFile(File f, Point expediteeDropPoint) throws IOException {
     286        public Item importFile(File f, Point expediteeDropPoint) throws IOException
     287        {
    299288                assert (f != null);
    300289
     
    302291                // importing routines...
    303292                Item lastCreatedItem;
    304                 if (null == (lastCreatedItem = performFileImport(_customFileImporters,
    305                                 f, expediteeDropPoint))) {
    306 
     293                if (null == (lastCreatedItem = performFileImport(_customFileImporters, f, expediteeDropPoint))) {
    307294                        // Standard file importing
    308                         lastCreatedItem = performFileImport(_standardFileImporters, f,
    309                                         expediteeDropPoint);
    310 
    311                 }
     295                        lastCreatedItem = performFileImport(_standardFileImporters, f, expediteeDropPoint);
     296                }
     297               
    312298                return lastCreatedItem;
    313299        }
    314300
    315         private Item performFileImport(List<FileImporter> importers, File f,
    316                         Point expediteeDropPoint) throws IOException {
    317 
     301        private Item performFileImport(List<FileImporter> importers, File f, Point expediteeDropPoint) throws IOException
     302        {
    318303                for (FileImporter fi : importers) {
    319304                        Item lastCreated = fi.importFile(f, expediteeDropPoint);
    320                         if (lastCreated != null)
    321                                 return lastCreated;
     305                       
     306                        if (lastCreated != null) return lastCreated;
    322307                }
    323308
     
    326311
    327312        /**
     313         * Converts a string formatted as a list of URIs into a list of Files.
     314         *
    328315         * Code adopted from SUN - java BUG ID 4899516 workaround for KDE/GNOME
    329316         * Desktops
     
    334321         * @return The list of FILES in the uriListString. Never null.
    335322         */
    336         private List<File> textURIListToFileList(String uriListString) {
    337 
     323        private List<File> textURIListToFileList(String uriListString)
     324        {
    338325                List<File> fileList = new LinkedList<File>();
    339326
    340                 for (StringTokenizer st = new StringTokenizer(uriListString, "\r\n"); st
    341                                 .hasMoreTokens();) {
     327                for (StringTokenizer st = new StringTokenizer(uriListString, "\r\n"); st.hasMoreTokens();) {
    342328
    343329                        String s = st.nextToken();
  • trunk/src/org/expeditee/importer/ImageImporter.java

    r919 r1102  
    1919package org.expeditee.importer;
    2020
    21 import java.awt.Color;
    22 import java.awt.Point;
    23 import java.awt.Rectangle;
    2421import java.io.File;
    2522import java.io.IOException;
     
    2724import java.util.HashSet;
    2825
    29 import org.expeditee.gui.DisplayIO;
    30 import org.expeditee.gui.FrameKeyboardActions;
    31 import org.expeditee.gui.FrameMouseActions;
     26import org.expeditee.core.Colour;
     27import org.expeditee.core.Point;
     28import org.expeditee.core.bounds.AxisAlignedBoxBounds;
     29import org.expeditee.gio.DragAndDropManager;
     30import org.expeditee.gio.gesture.StandardGestureActions;
     31import org.expeditee.gui.DisplayController;
    3232import org.expeditee.gui.FrameUtils;
    3333import org.expeditee.items.Item;
     
    6565                }
    6666
    67                 Color borderColor = null;
     67                Colour borderColor = null;
    6868                float thickness = 0;
    6969                String size = "";
     
    7272                        for (Item i : enclosure) {
    7373                                if (i.isLineEnd() && i.isEnclosed()) {
    74                                         DisplayIO.getCurrentFrame().removeAllItems(enclosure);
    75                                         Rectangle rect = i.getEnclosedRectangle();
     74                                        DisplayController.getCurrentFrame().removeAllItems(enclosure);
     75                                        AxisAlignedBoxBounds rect = i.getEnclosedBox();
    7676                                        size = " " + Math.round(rect.getWidth());
    77                                         location = new Point(rect.x, rect.y);
     77                                        location = new Point(rect.getMinX(), rect.getMinY());
    7878                                        thickness = i.getThickness();
    7979                                        borderColor = i.getColor();
     
    8181                                }
    8282                        }
    83                         FrameMouseActions.deleteItems(enclosure, false);
     83                        StandardGestureActions.deleteItems(enclosure, false);
    8484                }
    8585
    86                 Text source = FrameDNDTransferHandler.importString("@i: " + fullPath
    87                                 + size, location);
     86                Text source = DragAndDropManager.importString("@i: " + fullPath + size, location);
    8887                source.setThickness(thickness);
    8988                source.setBorderColor(borderColor);
    9089
    91                 FrameKeyboardActions.Refresh();
     90                StandardGestureActions.Refresh();
    9291                Collection<? extends XRayable> pictures = source.getEnclosures();
    9392                if (pictures.size() == 0)
  • trunk/src/org/expeditee/importer/TextImporter.java

    r919 r1102  
    1919package org.expeditee.importer;
    2020
    21 import java.awt.Color;
    22 import java.awt.Point;
    2321import java.io.BufferedReader;
    2422import java.io.File;
     
    2624import java.io.IOException;
    2725
     26import org.expeditee.core.Colour;
     27import org.expeditee.core.Point;
     28import org.expeditee.gio.DragAndDropManager;
     29import org.expeditee.gui.DisplayController;
    2830import org.expeditee.gui.FrameCreator;
    2931import org.expeditee.gui.FrameGraphics;
     
    4446                final String fullPath = f.getAbsolutePath();
    4547
    46                 final Text source = FrameDNDTransferHandler.importString(f.getPath(),
    47                                 location);
     48                final Text source = DragAndDropManager.importString(f.getPath(), location);
    4849
    4950                // Create a frameCreator to write the text
     
    5455                                try {
    5556                                        // Open a file stream to the file
    56                                         BufferedReader br = new BufferedReader(new FileReader(
    57                                                         fullPath));
     57                                        BufferedReader br = new BufferedReader(new FileReader(fullPath));
    5858
    5959                                        MessageBay.displayMessage("Importing " + f.getName() + "...");
     
    6767                                        frames.save();
    6868                                        source.setLink(frames.getName());
    69                                         MessageBay.displayMessage(f.getName() + " import complete", Color.GREEN);
    70                                         FrameGraphics.requestRefresh(true);
     69                                        MessageBay.displayMessage(f.getName() + " import complete", Colour.GREEN);
     70                                        DisplayController.requestRefresh(true);
    7171                                } catch (Exception e) {
    7272                                        e.printStackTrace();
     
    7575                        }
    7676                }.start();
    77                 FrameGraphics.refresh(true);
     77                DisplayController.requestRefresh(true);
    7878                return source;
    7979        }
  • trunk/src/org/expeditee/importer/pdfImporter.java

    r919 r1102  
    1919package org.expeditee.importer;
    2020
    21 import java.awt.Color;
    22 import java.awt.Graphics;
    23 import java.awt.Image;
    24 import java.awt.Point;
    25 import java.awt.Rectangle;
    26 import java.awt.image.BufferedImage;
    2721import java.io.File;
    2822import java.io.IOException;
     
    3125import java.nio.channels.FileChannel;
    3226
    33 import javax.imageio.ImageIO;
    34 
    35 import org.expeditee.gui.Browser;
     27import org.expeditee.core.Colour;
     28import org.expeditee.core.Image;
     29import org.expeditee.core.Point;
     30import org.expeditee.gio.DragAndDropManager;
     31import org.expeditee.gio.EcosystemManager;
     32import org.expeditee.gio.GraphicsManager;
     33import org.expeditee.gui.DisplayController;
    3634import org.expeditee.gui.Frame;
    3735import org.expeditee.gui.FrameCreator;
     
    5452                final int x = 0;
    5553                final int y = 60;
    56                 final int width = Browser._theBrowser.getSize().width;
     54                final int width = EcosystemManager.getGraphicsManager().getWindowSize().width;
    5755                System.out.println(width);
    5856               
     
    6563                }
    6664               
    67                 final Text link = FrameDNDTransferHandler.importString(name, location);
     65                final Text link = DragAndDropManager.importString(name, location);
    6866                link.setLink(name+"1");
    6967               
     
    9795                                        Frame _currentFrame=null;
    9896                                        Text nextButton=null, prevButton=null;
    99                                         final float spacing=((Text)FrameCreator.createButton("Next", null, null, 10F, 10F)).getBoundsWidth() + 30F;
     97                                        final int spacing=((Text)FrameCreator.createButton("Next", null, null, 10, 10)).getBoundsWidth() + 30;
    10098                     
    10199                      //make images from the pdf pages, write frames with those images
     
    128126                              }
    129127                              //generate the image
    130                               Image img = page.getImage(w, h, //width & height
    131                                       new Rectangle(0, 0, (int)page.getBBox().getWidth(), (int)page.getBBox().getHeight()), //clip rect
    132                                       null, //null for the ImageObserver
    133                                       true, //fill background with white
    134                                       true //block until drawing is done
    135                                       );
     128                              Image img = Image.createImage(w, h, page);
    136129                              //Create a buffered image to store the image in
    137                               BufferedImage bimg = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
    138                               Graphics g = bimg.createGraphics();
     130                              Image bimg = Image.createImage(img.getWidth(), img.getHeight(), false);
     131                              GraphicsManager g = EcosystemManager.getGraphicsManager();
    139132                              //Paint the image onto the buffered image
    140                               g.drawImage(img, 0, 0, null);
    141                               g.dispose();
     133                              g.pushDrawingSurface(bimg);
     134                              g.drawImage(img, new Point(0, 0));
     135                              g.popDrawingSurface();
    142136                              //save it as a file
    143137                              File out = new File(framesetPath+i+".png");
    144                               ImageIO.write(bimg, "png", out);
     138                              bimg.writeToDisk("png", out);
    145139                              //generate a frame with that image
    146140                              System.out.println(width);
     
    150144                                                {
    151145                                                  //put a next button on the previous frame (points to current frame)
    152                                                   nextButton=(Text)FrameCreator.createButton("Next", null, null, 10F, 10F);
     146                                                  nextButton=(Text)FrameCreator.createButton("Next", null, null, 10, 10);
    153147                                                        nextButton.setID(_currentFrame.getNextItemID());
    154148                                                        nextButton.addAction("next");
    155149                                                        _currentFrame.addItem(nextButton);
    156150                                                        //put a previous button on the current frame (points to previous frame)
    157                                                         prevButton=(Text)FrameCreator.createButton("Prev", null, null, (i<pages)?spacing:10F, 10F);
     151                                                        prevButton=(Text)FrameCreator.createButton("Prev", null, null, (i<pages)?spacing:10, 10);
    158152                                                        prevButton.setID(currentFrame.getNextItemID());
    159153                                                        prevButton.addAction("previous");
     
    162156                                                else
    163157                                                {
    164                                                         prevButton=(Text)FrameCreator.createButton("Home", null, null, (i<pages)?spacing:10F, 10F);
     158                                                        prevButton=(Text)FrameCreator.createButton("Home", null, null, (i<pages)?spacing:10, 10);
    165159                                                        prevButton.setID(currentFrame.getNextItemID());
    166160                                                        prevButton.addAction("GotoHome");
     
    171165                                                if(i<pages) currentFrame = FrameIO.CreateFrame(frameset.getFramesetName(), name, null);
    172166                                        }
    173                                         prevButton=(Text)FrameCreator.createButton("Home", null, null, spacing, 10F);
     167                                        prevButton=(Text)FrameCreator.createButton("Home", null, null, spacing, 10);
    174168                                        prevButton.setID(currentFrame.getNextItemID());
    175169                                        prevButton.addAction("gotohome");
    176170                                        currentFrame.addItem(prevButton);
    177171                                        FrameIO.SaveFrame(currentFrame,true);
    178                                         MessageBay.displayMessage(f.getName() + " import complete", Color.GREEN);
    179                                         FrameGraphics.requestRefresh(true);
     172                                        MessageBay.displayMessage(f.getName() + " import complete", Colour.GREEN);
     173                                        DisplayController.requestRefresh(true);
    180174                                } catch (Exception e) {
    181175                                        e.printStackTrace();
     
    184178                        }
    185179                }.start();
    186                 FrameGraphics.refresh(true);
     180                DisplayController.requestRefresh(true);
    187181                //return source;
    188182                return link;
  • trunk/src/org/expeditee/io/AbstractHTMLWriter.java

    r919 r1102  
    1919package org.expeditee.io;
    2020
    21 import java.awt.Color;
    22 import java.awt.Font;
    2321import java.io.File;
    2422import java.io.IOException;
     
    2624import java.util.List;
    2725
     26import org.expeditee.core.Colour;
     27import org.expeditee.core.Font;
    2828import org.expeditee.gui.Frame;
    2929import org.expeditee.gui.FrameIO;
     
    8888                        return;
    8989
    90                 writer.write(styleName + " { font-family: "
    91                                 + Conversion.getCssFontFamily(font.getFamily()));
     90                writer.write(styleName + " { font-family: " + Conversion.getCssFontFamily(font.getFamilyName()));
    9291
    9392                // writer.write("; font-size: " + Math.round(style.getSize()) + "px");
     
    104103                        writer.write("; font-style: normal");
    105104                }
    106                 Color c = style.getBackgroundColor();
     105                Colour c = style.getBackgroundColor();
    107106                if (c != null) {
    108107                        writer.write("; background-color: " + Conversion.getCssColor(c));
  • trunk/src/org/expeditee/io/Conversion.java

    r919 r1102  
    1919package org.expeditee.io;
    2020
    21 import java.awt.Color;
    22 import java.awt.Font;
    23 import java.awt.Point;
    2421import java.lang.reflect.Field;
    2522import java.lang.reflect.Method;
     
    2926
    3027import org.expeditee.actions.Actions;
     28import org.expeditee.core.Colour;
     29import org.expeditee.core.Font;
     30import org.expeditee.core.Point;
    3131import org.expeditee.items.Item;
    3232import org.expeditee.items.Text;
     
    4343public class Conversion {
    4444
    45         public static final int RGB_MAX = 255;
    46 
    47         private static final float RGB_CONVERSION_FACTOR = 2.55F;
     45        public static final short RGB_MAX = Colour.COMPONENT_MAX_VALUE;
     46
     47        private static final float RGB_CONVERSION_FACTOR = RGB_MAX / 100.0f;
    4848
    4949        /**
     
    5656         * @return The Color object corresponding to the given code
    5757         */
    58         public static Color getColor(String colorCode, Color current) {
     58        public static Colour getColor(String colorCode, Colour current) {
    5959                if (colorCode == null) {
    6060                        return null;
     
    6666
    6767                // check if its a normal rgb code ie. 100 0 40
    68                 Color rgb = getRGBColor(colorCode, current);
     68                Colour rgb = getRGBColor(colorCode, current);
    6969                if (rgb != null)
    7070                        return rgb;
     
    104104                        return null;
    105105
    106                 return new Color(color[0], color[1], color[2]);
    107         }
    108 
    109         private static Color getRGBColor(String colorCode, Color current) {
     106                return new Colour(color[0], color[1], color[2]);
     107        }
     108
     109        private static Colour getRGBColor(String colorCode, Colour current) {
    110110                int color[] = new int[4];
    111111                // Assert.assertTrue(color.length == 3);
     
    135135                                color[i] = toRGB(color[i]);
    136136                        }
    137                         return new Color(color[0], color[1], color[2], color[3]);
     137                        return new Colour(color[0], color[1], color[2], color[3]);
    138138                } catch (Exception e) {
    139139                        return null;
     
    175175         *         is black.
    176176         */
    177         public static String getExpediteeColorCode(Color color) {
     177        public static String getExpediteeColorCode(Colour color) {
    178178                if (color == null)
    179179                        return null;
     
    195195         */
    196196        public static String getExpediteeFontCode(Font font) {
    197                 String fontName = font.getFamily();
    198                 String code = font.getFamily() + '_';
     197                String fontName = font.getFamilyName();
     198                String code = font.getFamilyName() + '_';
    199199
    200200                for (int i = 0; i < Text.FONT_WHEEL.length; i++) {
     
    206206
    207207                switch (font.getStyle()) {
    208                 case Font.BOLD:
     208                case BOLD:
    209209                        code += "b";
    210210                        break;
    211                 case Font.PLAIN:
     211                case PLAIN:
    212212                        code += "r";
    213213                        break;
    214                 case Font.ITALIC:
     214                case ITALIC:
    215215                        code += "i";
    216216                        break;
     
    237237
    238238                int separator = fontCode.indexOf('_');
    239                 String code = Text.FONT_WHEEL[0];
     239                String familyName = Text.FONT_WHEEL[0];
    240240                if (separator > 0) {
    241                         code = Actions.getCapitalizedFontName(fontCode.substring(0,
    242                                         separator)) + '-';
     241                        familyName = Actions.getCapitalizedFontName(fontCode.substring(0, separator));
    243242                        fontCode = fontCode.substring(separator);
    244243                } else {
     
    246245                        for (int i = 0; i < Text.FONT_CHARS.length; i++) {
    247246                                if (c == Text.FONT_CHARS[i]) {
    248                                         code = Text.FONT_WHEEL[i] + '-';
     247                                        familyName = Text.FONT_WHEEL[i];
    249248                                        break;
    250249                                }
    251250                        }
    252251                }
     252               
     253                Font font = new Font(familyName);
    253254
    254255                switch (fontCode.charAt(1)) {
    255256                case 'r':
    256                         code += "Plain";
     257                        font.setStyle(Font.Style.PLAIN);
    257258                        break;
    258259                case 'b':
    259                         code += "Bold";
     260                        font.setStyle(Font.Style.BOLD);
    260261                        break;
    261262                case 'i':
    262                         code += "Italic";
     263                        font.setStyle(Font.Style.ITALIC);
    263264                        break;
    264265                case 'p':
    265                         code += "BoldItalic";
     266                        font.setStyle(Font.Style.BOLD_ITALIC);
    266267                        break;
    267268                }
    268 
    269                 code += "-";
    270 
    271                 Font font = null;
    272269
    273270                try {
    274271                        int size = Integer.parseInt(fontCode.substring(2));
    275                         // double dsize = size * FONT_SCALE;
    276                         // if (dsize - ((int) dsize) > FONT_ROUNDING)
    277                         // dsize = Math.ceil(dsize);
    278 
    279                         // code += (int) dsize;
    280                         code += size;
    281 
    282                         font = Font.decode(code);
     272                       
     273                        font.setSize(size);
    283274                } catch (NumberFormatException nfe) {
    284                         font = Font.decode(fontCode);
     275                        // Just keep going
    285276                }
    286277
     
    362353                }
    363354
    364                 if (type.equals(Color.class)) {
     355                if (type.equals(Colour.class)) {
    365356                        if (value.length() == 0)
    366357                                return null;
     
    368359                        try {
    369360                                // Try to decode the string as a hex or octal color code
    370                                 return Color.decode(value);
     361                                return Colour.decode(value);
    371362                        } catch (NumberFormatException nfe) {
    372363                                try {
    373                                         // Try to find the field in the Color class with the same name as the given string
    374                                         Field[] fields = java.awt.Color.class.getFields();
     364                                        // Try to find the field in the Colour class with the same name as the given string
     365                                        Field[] fields = Colour.class.getFields();
    375366                                        Field field = null;
    376367                                        for (int i = 0; i < fields.length; i++) {
     
    380371                                                }
    381372                                        }
    382                                         return (Color) field.get(null);
     373                                        return (Colour) field.get(null);
    383374                                } catch (Exception e) {
    384                                         return getColor(value, (Color) orig);
     375                                        return getColor(value, (Colour) orig);
    385376                                }
    386377                        }
     
    388379
    389380                if (type.equals(int.class)) {
    390                         if (orig instanceof Integer
    391                                         && (value.startsWith("+") || value.startsWith("-"))) {
     381                        if (orig instanceof Integer && (value.startsWith("+") || value.startsWith("-"))) {
    392382                                value = value.replace("+", "");
    393383
     
    395385                        }
    396386
    397                         if (value.length() == 0 || value.equals("null"))
    398                                 return Item.DEFAULT_INTEGER;
     387                        if (value.length() == 0 || value.equals("null")) return Item.DEFAULT_INTEGER;
    399388
    400389                        return Integer.decode(value);
     
    427416
    428417                if (type.equals(Integer.class)) {
    429                         if (orig instanceof Integer
    430                                         && (value.startsWith("+") || value.startsWith("-"))) {
     418                        if (orig instanceof Integer && (value.startsWith("+") || value.startsWith("-"))) {
    431419                                value = value.replace("+", "");
    432420
    433                                 Integer newValue = ((Integer) orig) + Integer.parseInt(value);
     421                                Integer newValue = ((Integer) orig) + Integer.valueOf((int) Double.parseDouble(value));
    434422                                if (newValue <= 0)
    435423                                        return null;
     
    440428                                return null;
    441429
    442                         return Integer.parseInt(value);
     430                        return Integer.valueOf((int) Double.parseDouble(value));
    443431                }
    444432
     
    700688
    701689                // convert colors
    702                 if (output instanceof Color)
    703                         return getExpediteeColorCode((Color) output);
     690                if (output instanceof Colour)
     691                        return getExpediteeColorCode((Colour) output);
    704692
    705693                // covert points
     
    737725        }
    738726
    739         public static String getCssColor(Color c) {
     727        public static String getCssColor(Colour c) {
    740728                assert (c != null);
    741                 return "rgb(" + c.getRed() + "," + c.getGreen() + "," + c.getBlue()
     729                return "rgb(" + c.getRed255() + "," + c.getGreen255() + "," + c.getBlue255()
    742730                                + ")";
    743731        }
  • trunk/src/org/expeditee/io/DefaultFrameReader.java

    r919 r1102  
    1919package org.expeditee.io;
    2020
    21 import java.awt.Color;
    22 import java.awt.Font;
    23 import java.awt.Point;
    2421import java.io.BufferedReader;
    2522import java.io.FileInputStream;
     
    3229import java.util.LinkedList;
    3330
     31import org.expeditee.core.Colour;
     32import org.expeditee.core.Font;
     33import org.expeditee.core.Point;
    3434import org.expeditee.gui.Frame;
    3535import org.expeditee.items.Constraint;
     36import org.expeditee.items.Dot;
    3637import org.expeditee.items.DotType;
    3738import org.expeditee.items.Item;
     
    4243
    4344public abstract class DefaultFrameReader implements FrameReader {
     45       
    4446        protected static LinkedHashMap<Character, Method> _ItemTags = null;
    4547       
     
    5355        protected static Class[] pFloat = { float.class };
    5456        protected static Class[] pFloatO = { Float.class };
    55         protected static Class[] pColor = { Color.class };
     57        protected static Class[] pDouble = { double.class };
     58        protected static Class[] pColor = { Colour.class };
    5659        protected static Class[] pBool = { boolean.class };
    5760        protected static Class[] pFont = { Font.class };
     
    6366        protected static Class[] pJustification = { Justification.class };
    6467        protected static Class[] pPermission = { PermissionPair.class };
     68        protected static Class[] pDotType = { DotType.class };
    6569       
    6670        public DefaultFrameReader(){
     
    100104                                        pColor));
    101105
    102                         _ItemTags.put('R', Item.class.getMethod("setAnchorLeft", pFloatO));
    103                         _ItemTags.put('H', Item.class.getMethod("setAnchorRight", pFloatO));
    104                         _ItemTags.put('N', Item.class.getMethod("setAnchorTop", pFloatO));
    105                         _ItemTags.put('I', Item.class.getMethod("setAnchorBottom", pFloatO));
     106                        _ItemTags.put('R', Item.class.getMethod("setAnchorLeft", pIntO));
     107                        _ItemTags.put('H', Item.class.getMethod("setAnchorRight", pIntO));
     108                        _ItemTags.put('N', Item.class.getMethod("setAnchorTop", pIntO));
     109                        _ItemTags.put('I', Item.class.getMethod("setAnchorBottom", pIntO));
    106110
    107111                        _ItemTags.put('P', Item.class.getMethod("setPosition", pPoint));
     
    123127                        _ItemTags.put('e', Item.class.getMethod("setFillColor", pColor));
    124128                        _ItemTags.put('E', Item.class.getMethod("setGradientColor", pColor));
    125                         _ItemTags.put('Q', Item.class.getMethod("setGradientAngle", pInt));
     129                        _ItemTags.put('Q', Item.class.getMethod("setGradientAngle", pDouble));
    126130                       
    127131                        _ItemTags.put('i', Item.class.getMethod("setFillPattern", pString));
     
    136140                        _ItemTags.put('j', Item.class.getMethod("setArrow", pArrow));
    137141
    138                         _ItemTags.put('v', Item.class.getMethod("setDotType", new Class[]{DotType.class}));
    139                         _ItemTags.put('z', Item.class.getMethod("setFilled", pBool));
     142                        _ItemTags.put('v', Dot.class.getMethod("setDotType", pDotType));
     143                        _ItemTags.put('z', Dot.class.getMethod("setFilled", pBool));
    140144                       
    141145                        _ItemTags.put('f', Text.class.getMethod("setFont", pFont));
  • trunk/src/org/expeditee/io/DefaultFrameWriter.java

    r919 r1102  
    1919package org.expeditee.io;
    2020
    21 import java.awt.Desktop;
    2221import java.io.BufferedOutputStream;
    2322import java.io.File;
     
    3332
    3433import org.expeditee.agents.WriteTree;
     34import org.expeditee.gio.EcosystemManager;
    3535import org.expeditee.gui.Browser;
    3636import org.expeditee.gui.Frame;
     
    258258                        _writer.close();
    259259                }
    260                 try {
    261                         if (Browser._theBrowser.isMinimumVersion6()) {
    262                                 if (Desktop.isDesktopSupported()) {
    263                                         Desktop.getDesktop().open(new File(_output));
    264                                 }
    265                         }
    266                 } catch (Exception e) {
    267                         e.printStackTrace();
    268                 }
     260                String errorMessage = EcosystemManager.getMiscManager().open(_output);
     261                if (errorMessage != null) System.err.println(errorMessage);
    269262                return " exported to " + _output;
    270263        }
  • trunk/src/org/expeditee/io/ExaReader.java

    r919 r1102  
    173173                                        // refresh the last item loaded
    174174                                        if(item != null) {
    175                                                 item.updatePolygon();
     175                                                item.invalidateBounds();
    176176                                                item.invalidateAll();
    177177                                        }
     
    200200                // refresh the last item loaded
    201201                if(item != null) {
    202                         item.updatePolygon();
     202                        item.invalidateBounds();
    203203                        item.invalidateAll();
    204204                }
  • trunk/src/org/expeditee/io/ExaWriter.java

    r919 r1102  
    2929
    3030import org.expeditee.gui.AttributeUtils;
    31 import org.expeditee.gui.AttributeUtils.Attribute;
    3231import org.expeditee.gui.Frame;
    3332import org.expeditee.items.Constraint;
  • trunk/src/org/expeditee/io/ExpClipReader.java

    r919 r1102  
    2525import java.util.List;
    2626
    27 import org.expeditee.gui.DisplayIO;
     27import org.expeditee.core.Point;
     28import org.expeditee.gui.DisplayController;
    2829import org.expeditee.gui.Frame;
    2930import org.expeditee.gui.FrameGraphics;
     
    3738import org.expeditee.items.Line;
    3839import org.expeditee.items.Text;
    39 import org.expeditee.items.widgets.InteractiveWidget;
     40import org.expeditee.items.widgets.Widget;
    4041
    4142/**
     
    5253        private int dX, dY;
    5354       
     55        public ExpClipReader(Point p)
     56        {
     57                this(p.x, p.y);
     58        }
     59       
    5460        public ExpClipReader(int dX, int dY) {
    5561                super("");
     
    6369         */
    6470        public static void updateItems(List<Item> items) {
    65                 if(FrameGraphics.isXRayMode()) {
     71                if(DisplayController.isXRayMode()) {
    6672                        return;
    6773                }
     
    7278                                continue;
    7379                        }
    74                         if (ItemUtils.startsWithTag(item,
    75                                         ItemUtils.TAG_IMAGE, true)) {
     80                        if (ItemUtils.startsWithTag(item, ItemUtils.TAG_IMAGE, true)) {
    7681                                if (!item.hasEnclosures()) {
    77                                         items.add(ItemUtils.CreatePicture((Text) item, DisplayIO.getCurrentFrame()));
     82                                        items.add(ItemUtils.CreatePicture((Text) item));
    7883                                }
    7984                                // check for frame images
     
    8388                                        && !item.getAbsoluteLink()
    8489                                                        .equalsIgnoreCase(
    85                                                                         DisplayIO.getCurrentFrame().getName())) {
     90                                                                        DisplayController.getCurrentFrame().getName())) {
    8691                                if (item.hasEnclosures()) {
    8792                                        // item.setHidden(true);
     
    9095                                        // image.refresh();
    9196                                } else {
    92                                         items.add(new FrameImage((Text) item, DisplayIO.getCurrentFrame(), null));
     97                                        items.add(new FrameImage((Text) item, null));
    9398                                }
    9499                        } else if (ItemUtils.startsWithTag(item,
     
    97102                                        && !item.getAbsoluteLink()
    98103                                                        .equalsIgnoreCase(
    99                                                                         DisplayIO.getCurrentFrame().getName())) {
     104                                                                        DisplayController.getCurrentFrame().getName())) {
    100105                                if (item.hasEnclosures()) {
    101106                                        // image =
     
    107112                                        // frame which already has a bitmap dont
    108113                                        // recreate the bitmap
    109                                         items.add(new FrameBitmap((Text) item, DisplayIO.getCurrentFrame(), null));
     114                                        items.add(new FrameBitmap((Text) item, null));
    110115                                }
    111116                        } else if (ItemUtils.startsWithTag(item, "@c")) {
     
    116121                                }
    117122                                // Check for interactive widgets
    118                         } else if (ItemUtils.startsWithTag(item,
    119                                         ItemUtils.TAG_IWIDGET)) {
     123                        } else if (ItemUtils.startsWithTag(item, ItemUtils.TAG_IWIDGET)) {
    120124                                items.remove(item);
    121                                 item.setParent(DisplayIO.getCurrentFrame());
     125                                item.setParent(DisplayController.getCurrentFrame());
    122126                                try {
    123                                         items.addAll(InteractiveWidget.createWidget((Text) item).getItems());
     127                                        items.addAll(Widget.createWidget((Text) item).getItems());
    124128                                } catch (Exception e) {
    125129                                        System.err.println("Failed to create widget");
     
    176180                        while(index < lines.length && !(lines[++index].equals("Z"))) {
    177181                                if (isValidLine(lines[index])) {
    178                                         java.awt.Point idtype = separateValues(lines[index].substring(2));
     182                                        Point idtype = separateValues(lines[index].substring(2));
    179183                                        // The next line must be the endpoints
    180184                                        if (index >= lines.length)
    181185                                                throw new Exception("Unexpected end of file");
    182186                                        ++index;
    183                                         java.awt.Point startend = separateValues(lines[index].substring(2));
     187                                        Point startend = separateValues(lines[index].substring(2));
    184188                                        int start = startend.x;
    185189                                        int end = startend.y;
     
    199203                        while(index < lines.length && !(lines[++index].equals("Z"))) {
    200204                                if (isValidLine(lines[index])) {
    201                                         java.awt.Point idtype = separateValues(lines[index].substring(2));
     205                                        Point idtype = separateValues(lines[index].substring(2));
    202206                                        // The next line must be the endpoints
    203207                                        if (index >= lines.length)
    204208                                                throw new Exception("Unexpected end of file");
    205209                                        ++index;
    206                                         java.awt.Point startend = separateValues(lines[index].substring(2));
     210                                        Point startend = separateValues(lines[index].substring(2));
    207211       
    208212                                        Item a = _linePoints.get(startend.x);
  • trunk/src/org/expeditee/io/ExpClipWriter.java

    r919 r1102  
    2323import java.util.List;
    2424
     25import org.expeditee.core.Point;
    2526import org.expeditee.gui.Frame;
    2627import org.expeditee.items.Item;
    2728import org.expeditee.items.Line;
    2829import org.expeditee.items.XRayable;
    29 import org.expeditee.items.widgets.InteractiveWidget;
     30import org.expeditee.items.widgets.Widget;
    3031import org.expeditee.items.widgets.WidgetCorner;
    3132import org.expeditee.items.widgets.WidgetEdge;
     
    4142        private int dX, dY;
    4243
     44        public ExpClipWriter(Point p)
     45        {
     46                this(p.x, p.y);
     47        }
     48       
    4349        public ExpClipWriter(int dX, int dY) {
    4450                super();
     
    6066        public void output(List<Item> items) throws IOException {
    6167                // switch to savable items
    62                 LinkedList<InteractiveWidget> widgets = new LinkedList<InteractiveWidget>();
     68                LinkedList<Widget> widgets = new LinkedList<Widget>();
    6369                // make an array to iterate over instead of the list so we don't get stuck when we remove items from the list
    6470                Item[] tmpitems = items.toArray(new Item[0]);
     
    7278                                }
    7379                        } else if (i instanceof WidgetCorner) {
    74                                 InteractiveWidget iw = ((WidgetCorner)i).getWidgetSource();
     80                                Widget iw = ((WidgetCorner)i).getWidgetSource();
    7581                                if(!widgets.contains(iw)) {
    7682                                        widgets.add(iw);
     
    7884                                items.remove(i);
    7985                        } else if (i instanceof WidgetEdge) {
    80                                 InteractiveWidget iw = ((WidgetEdge)i).getWidgetSource();
     86                                Widget iw = ((WidgetEdge)i).getWidgetSource();
    8187                                if(!widgets.contains(iw)) {
    8288                                        widgets.add(iw);
     
    9096                        }
    9197                }
    92                 for (InteractiveWidget iw : widgets) {
     98                for (Widget iw : widgets) {
    9399                        items.add(iw.getSource());
    94100                }
  • trunk/src/org/expeditee/io/ExpReader.java

    r919 r1102  
    2727import java.util.List;
    2828
     29import org.expeditee.core.Point;
    2930import org.expeditee.gui.Frame;
    3031import org.expeditee.items.Constraint;
     
    130131                        while (_reader.ready() && !(next = _reader.readLine()).equals("Z")) {
    131132                                if (isValidLine(next)) {
    132                                         java.awt.Point idtype = separateValues(next.substring(2));
     133                                        Point idtype = separateValues(next.substring(2));
    133134                                        // The next line must be the endpoints
    134135                                        if (!_reader.ready())
    135136                                                throw new Exception("Unexpected end of file");
    136137                                        next = _reader.readLine();
    137                                         java.awt.Point startend = separateValues(next.substring(2));
     138                                        Point startend = separateValues(next.substring(2));
    138139                                        int start = startend.x;
    139140                                        int end = startend.y;
     
    153154                        while (_reader.ready() && !(next = _reader.readLine()).equals("Z")) {
    154155                                if (isValidLine(next)) {
    155                                         java.awt.Point idtype = separateValues(next.substring(2));
     156                                        Point idtype = separateValues(next.substring(2));
    156157                                        // The next line must be the endpoints
    157158                                        if (!_reader.ready())
    158159                                                throw new Exception("Unexpected end of file");
    159160                                        next = _reader.readLine();
    160                                         java.awt.Point startend = separateValues(next.substring(2));
     161                                        Point startend = separateValues(next.substring(2));
    161162
    162163                                        Item a = _linePoints.get(startend.x);
     
    233234
    234235                Method toRun = _ItemTags.get(tag);
    235                 if (toRun == null)
    236                         System.out.println("Error accessing tag method: " + tag);
     236                if (toRun == null) System.out.println("Error accessing tag method: " + tag);
    237237                Object[] vals = Conversion.Convert(toRun, value);
    238238
    239239                try {
    240                         if (vals != null)
    241                                 toRun.invoke(item, vals);
     240                        if (vals != null) toRun.invoke(item, vals);
    242241                } catch (Exception e) {
    243242                        System.out.println("Error running tag method: " + tag);
     
    297296
    298297        // Returns a point from a String containing two ints separated by a space
    299         protected java.awt.Point separateValues(String line) {
     298        protected Point separateValues(String line) {
    300299                int x = Integer.parseInt(line.substring(0, line.indexOf(" ")));
    301300                int y = Integer.parseInt(line.substring(line.indexOf(" ") + 1));
    302301
    303                 return new java.awt.Point(x, y);
     302                return new Point(x, y);
    304303        }
    305304
  • trunk/src/org/expeditee/io/HTMLWriter.java

    r919 r1102  
    1919package org.expeditee.io;
    2020
    21 import java.awt.Image;
    22 import java.awt.image.BufferedImage;
    2321import java.io.IOException;
    2422import java.util.List;
    2523
    2624import org.expeditee.actions.Misc;
     25import org.expeditee.core.Dimension;
     26import org.expeditee.core.Image;
     27import org.expeditee.core.Point;
     28import org.expeditee.gio.EcosystemManager;
     29import org.expeditee.gio.GraphicsManager;
     30import org.expeditee.gio.swing.SwingMiscManager;
    2731import org.expeditee.gui.FrameIO;
    2832import org.expeditee.items.FramePicture;
     
    6569                        image = pic.getImage();
    6670                        // Crop the image
    67                         BufferedImage bufferedImage = new BufferedImage(pic
    68                                         .getUnscaledWidth(), pic.getUnscaledHeight(),
    69                                         BufferedImage.TYPE_INT_ARGB);
    70                         bufferedImage.getGraphics().drawImage(image, 0, 0,
    71                                         pic.getUnscaledWidth(), pic.getUnscaledHeight(),
    72                                         pic.getStart().x, pic.getStart().y, pic.getEnd().x,
    73                                         pic.getEnd().y, null);
     71                        Image bufferedImage = Image.createImage(pic.getUnscaledWidth(), pic.getUnscaledHeight());
     72                        GraphicsManager g = EcosystemManager.getGraphicsManager();
     73                        g.pushDrawingSurface(bufferedImage);
     74                        g.drawImage(image,
     75                                                new Point(0, 0),
     76                                                new Dimension(pic.getUnscaledWidth(), pic.getUnscaledHeight()),
     77                                                0.0,
     78                                                pic.getStart(),
     79                                                new Dimension(pic.getEnd().x - pic.getStart().x, pic.getEnd().y - pic.getStart().y));
     80                        g.popDrawingSurface();
    7481                        image = bufferedImage;
    7582                } else {
     
    8188                // If its a bufferedImage then just write it out to the files directory
    8289                // This means it is probably a FrameImage
    83                 if (image instanceof BufferedImage) {
     90                if (!image.isStoredOnDisk()) {
    8491                        String link = pic.getAbsoluteLink();
    85                         // Account for the possiblitly of an unlinked buffered image
     92                        // Account for the possibility of an unlinked buffered image
    8693                        fileName = link == null ? ("Image" + pic.getID()) : link;
    87                         fileName = Misc.SaveImage((BufferedImage) image, "PNG",
    88                                         FrameIO.EXPORTS_DIR + filesFolder, fileName);
     94                        fileName = Misc.SaveImage(image, "PNG", FrameIO.EXPORTS_DIR + filesFolder, fileName);
    8995                } else {// It is a normal Image stored somewhere
    9096                        fileName = pic.getName();
  • trunk/src/org/expeditee/io/ItemSelection.java

    r964 r1102  
    1919package org.expeditee.io;
    2020
    21 
    22 import java.awt.Image;
    23 import java.awt.Toolkit;
    24 import java.awt.datatransfer.Clipboard;
    25 import java.awt.datatransfer.DataFlavor;
    26 import java.awt.datatransfer.Transferable;
    27 import java.awt.datatransfer.UnsupportedFlavorException;
    28 import java.awt.image.BufferedImage;
    2921import java.io.File;
    3022import java.io.IOException;
    3123import java.io.Serializable;
    3224import java.util.ArrayList;
    33 import java.util.Arrays;
    3425import java.util.List;
    3526
    36 import javax.imageio.ImageIO;
    37 
    38 import org.expeditee.gui.DisplayIO;
     27import org.expeditee.core.Image;
     28import org.expeditee.gio.ClipboardManager.ClipboardData;
     29import org.expeditee.gio.EcosystemManager;
     30import org.expeditee.gio.gesture.StandardGestureActions;
     31import org.expeditee.gui.DisplayController;
    3932import org.expeditee.gui.FrameGraphics;
    4033import org.expeditee.gui.FrameIO;
    41 import org.expeditee.gui.FrameMouseActions;
    4234import org.expeditee.gui.FreeItems;
    4335import org.expeditee.gui.MessageBay;
     
    5345 * @author jts21
    5446 */
    55 public class ItemSelection implements Transferable {
    56        
     47public class ItemSelection {
     48        // TODO : Tidy commented code once tested. cts16
    5749        /**
    5850         * Class used for storing data which can be used to reconstruct expeditee objects from the clipboard
     
    6860                // exp save data
    6961                public String items;
    70         }
    71        
    72         public static final DataFlavor expDataFlavor = new DataFlavor(ExpDataHandler.class, "expDataHandler");
    73        
    74         private static final int STRING = 0;
    75     private static final int IMAGE = 1;
    76     private static final int EXP_DATA = 2;
    77        
    78         private static final DataFlavor[] flavors = {
    79         DataFlavor.stringFlavor,
    80         DataFlavor.imageFlavor,
    81         expDataFlavor
    82     };
    83        
    84         private String data;
    85         private Image image;
    86         private ExpDataHandler expData;
    87        
    88         public ItemSelection(String data, Image image, ExpDataHandler expData) {
    89         this.data = data;
    90         this.image = image;
    91         this.expData = expData;
    92     }
    93        
    94         @Override
    95         public DataFlavor[] getTransferDataFlavors() {
    96                 return (DataFlavor[])flavors.clone();
    97         }
    98 
    99         @Override
    100         public boolean isDataFlavorSupported(DataFlavor flavor) {
    101                 for (int i = 0; i < flavors.length; i++) {
    102             if (flavor.equals(flavors[i])) {
    103                 return true;
    104             }
    105         }
    106         return false;
    107         }
    108 
    109         @Override
    110         public Object getTransferData(DataFlavor flavor)
    111                         throws UnsupportedFlavorException, IOException {
    112         if (flavor.equals(flavors[STRING])) {
    113             return (Object)data;
    114         } else if (flavor.equals(flavors[IMAGE])) {
    115                 return (Object)image;
    116         } else if (flavor.equals(flavors[EXP_DATA])) {
    117             return (Object)expData;
    118         } else {
    119             throw new UnsupportedFlavorException(flavor);
    120         }
    121         }
    122        
     62                public Image image;
     63                public String text;
     64        }
     65
    12366        private static List<Item> getAllToCopy() {
    12467                List<Item> tmp = new ArrayList<Item>(FreeItems.getInstance());
     
    12871                                if(! toCopy.contains(c)) {
    12972                                        toCopy.add(c);
    130                                         FrameMouseActions.pickup(c);
     73                                        StandardGestureActions.pickup(c);
    13174                                }
    13275                        }
     
    14285               
    14386                // remove the items attached to the cursor
    144                 DisplayIO.getCurrentFrame().removeAllItems(toCopy);
     87                DisplayController.getCurrentFrame().removeAllItems(toCopy);
    14588                FreeItems.getInstance().clear();
    14689               
    147                 FrameGraphics.refresh(false);
     90                DisplayController.requestRefresh(false);
    14891        }
    14992       
     
    161104                        return;
    162105                }
    163                
     106
    164107                StringBuilder clipboardText = new StringBuilder();
    165108                ExpDataHandler expData = new ExpDataHandler();
     
    179122               
    180123                // get expeditee item data
    181                 ExpClipWriter ecw = new ExpClipWriter(FrameMouseActions.getX(), FrameMouseActions.getY());
     124                ExpClipWriter ecw = new ExpClipWriter(EcosystemManager.getInputManager().getCursorPosition());
    182125                try {
    183126                        ecw.output(items);
     
    186129                }
    187130                expData.items = ecw.getFileContents();
     131                expData.image = image;
     132                expData.text = clipboardText.toString();
     133               
     134                // Format the data for the clipboard
     135                ClipboardData clipboardData = new ClipboardData(expData, expData.image, expData.text);
     136               
    188137                // System.out.println(expData.items);
    189                
     138
    190139                // write out to clipboard
    191                 ItemSelection selection = new ItemSelection(clipboardText.toString(), image, expData);
    192                 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, null);
     140                //ItemSelection selection = new ItemSelection(clipboardText.toString(), image, expData);
     141                //Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, null);
     142                EcosystemManager.getClipboardManager().set(clipboardData);
    193143        }
    194144       
     
    196146         * Generates items from the clipboard data
    197147         *  TODO: Enable pasting raw image data (would require saving the data as an image file and generating a Text item pointing to it)
     148         *  TODO: Above TODO seems to be done? cts16
    198149         */
    199150        public static void paste() {
    200                 if(FreeItems.itemsAttachedToCursor()) {
     151                if(FreeItems.hasItemsAttachedToCursor()) {
    201152                        MessageBay.displayMessage("Drop any items being carried on the cursor, then try pasting again");
    202153                        return;
     
    204155                String type = "";
    205156                FreeItems f = FreeItems.getInstance();
    206                 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
    207                 Transferable content = c.getContents(null);
     157                //Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
     158                //Transferable content = c.getContents(null);
     159                ClipboardData content = EcosystemManager.getClipboardManager().get();
     160               
    208161                try {
    209                         if(content.isDataFlavorSupported(ItemSelection.expDataFlavor)) {        // Expeditee data
     162                        if (content.data instanceof ExpDataHandler) {   // Expeditee data
    210163                                type = "Expeditee ";
    211                                 ExpDataHandler expData = (ExpDataHandler)content.getTransferData(ItemSelection.expDataFlavor);
     164                                ExpDataHandler expData = (ExpDataHandler) content.data;
    212165                                if(expData != null) {
    213                                         List<Item> items = new ExpClipReader(FrameMouseActions.getX(), FrameMouseActions.getY()).read(expData.items);
     166                                        List<Item> items = new ExpClipReader(EcosystemManager.getInputManager().getCursorPosition()).read(expData.items);
    214167                                        // generate new IDs and pickup
    215                                         FrameMouseActions.pickup(ItemUtils.CopyItems(items));
     168                                        StandardGestureActions.pickup(ItemUtils.CopyItems(items));
    216169                                }
    217                         } else if(content.isDataFlavorSupported(DataFlavor.imageFlavor)) {      // Image data
     170                        } else if (content.imageRepresentation != null) {       // Image data
    218171                                // System.out.println("IZ PIKTUR");
    219172                                type = "Image ";
    220                                 BufferedImage img = (BufferedImage)content.getTransferData(DataFlavor.imageFlavor);
    221                                 int hashcode = Arrays.hashCode(img.getData().getPixels(0, 0, img.getWidth(), img.getHeight(), (int[])null));
     173                                Image img = content.imageRepresentation;
     174                                //int hashcode = Arrays.hashCode(img.getData().getPixels(0, 0, img.getWidth(), img.getHeight(), (int[])null));
     175                                int hashcode = img.hashCode();
    222176                                File out = new File(FrameIO.IMAGES_PATH + Integer.toHexString(hashcode) + ".png");
    223177                                out.mkdirs();
    224                                 ImageIO.write(img, "png", out);
    225                                 Text item = DisplayIO.getCurrentFrame().createNewText("@i: " + out.getPath());
     178                                img.writeToDisk("png", out);
     179                                Text item = DisplayController.getCurrentFrame().createNewText("@i: " + out.getPath());
    226180                                f.add(item);
    227181                                ExpClipReader.updateItems(f);
    228                         } else if(content.isDataFlavorSupported(DataFlavor.stringFlavor)) {     // Plain text
     182                        } else if (content.stringRepresentation != null) {      // Plain text
    229183                                type = "Plain Text ";
    230                                 String clip = ((String) content.getTransferData(DataFlavor.stringFlavor));
     184                                String clip = content.stringRepresentation;
    231185                                // Covert the line separator char when pasting in
    232186                                // windows (\r\n) or max (\r)
     
    235189                                String[] items = clip.split("\n\n");
    236190                                Item item, prevItem = null;
    237                                 final int x = DisplayIO.getMouseX();
    238                                 final int y = DisplayIO.getMouseY();
    239                                 final Text template = DisplayIO.getCurrentFrame().getItemTemplate();
     191                                final int x = DisplayController.getMouseX();
     192                                final int y = DisplayController.getMouseY();
     193                                final Text template = DisplayController.getCurrentFrame().getItemTemplate();
    240194                                for(int i = 0; i < items.length; i++) {
    241195                                        // System.out.println(items[i]);
  • trunk/src/org/expeditee/io/ItemWriter.java

    r919 r1102  
    2828import org.expeditee.items.Picture;
    2929import org.expeditee.items.Text;
    30 import org.expeditee.items.widgets.InteractiveWidget;
     30import org.expeditee.items.widgets.Widget;
    3131import org.expeditee.items.widgets.WidgetEdge;
    3232
     
    115115        }
    116116
    117         protected void writeWidget(InteractiveWidget toWrite) throws IOException {
     117        protected void writeWidget(Widget toWrite) throws IOException {
    118118        }
    119119
  • trunk/src/org/expeditee/io/JavaWriter.java

    r919 r1102  
    1919package org.expeditee.io;
    2020
    21 import java.awt.Desktop;
    22 import java.awt.Point;
    23 import java.awt.Polygon;
    24 import java.awt.Rectangle;
    25 import java.awt.geom.Area;
    26 import java.io.File;
    2721import java.io.IOException;
    2822import java.io.Writer;
    29 import java.lang.reflect.Array;
    30 import java.util.ArrayList;
    31 import java.util.Collection;
    32 import java.util.Collections;
    33 import java.util.Comparator;
    3423import java.util.List;
    3524
    36 import org.expeditee.gui.Browser;
    3725import org.expeditee.gui.Frame;
    38 import org.expeditee.gui.FrameUtils;
    39 import org.expeditee.io.flowlayout.AreaPolygon;
    40 import org.expeditee.io.flowlayout.DimensionExtent;
    4126import org.expeditee.io.flowlayout.XGroupItem;
    42 import org.expeditee.io.flowlayout.XItem;
    43 import org.expeditee.io.flowlayout.XOrderedLine;
    44 import org.expeditee.io.flowlayout.XRawItem;
    45 import org.expeditee.io.flowlayout.YOverlappingItemsShadow;
    46 import org.expeditee.io.flowlayout.YOverlappingItemsSpan;
    47 import org.expeditee.io.flowlayout.YOverlappingItemsTopEdge;
    4827import org.expeditee.items.Item;
    49 import org.expeditee.items.ItemUtils;
    5028import org.expeditee.items.Text;
    5129
  • trunk/src/org/expeditee/io/KMSReader.java

    r1049 r1102  
    2929import java.util.LinkedHashMap;
    3030
     31import org.expeditee.core.Point;
    3132import org.expeditee.gui.Frame;
    3233import org.expeditee.gui.MessageBay;
    3334import org.expeditee.items.Constraint;
    3435import org.expeditee.items.Dot;
    35 import org.expeditee.items.DotType;
    3636import org.expeditee.items.Item;
    3737import org.expeditee.items.Line;
     
    107107                        _ItemTags.put("e", Item.class.getMethod("setFillColor", pColor));
    108108                        _ItemTags.put("E", Item.class.getMethod("setGradientColor", pColor));
    109                         _ItemTags.put("Q", Item.class.getMethod("setGradientAngle", pInt));
     109                        _ItemTags.put("Q", Item.class.getMethod("setGradientAngle", pDouble));
    110110                       
    111111                        _ItemTags.put("i", Item.class.getMethod("setFillPattern", pString));
     
    267267
    268268                // get the line ID and type
    269                 java.awt.Point idtype = separateValues(s);
     269                Point idtype = separateValues(s);
    270270
    271271                // get the end points
     
    273273                _data.remove("s");
    274274
    275                 java.awt.Point startend = separateValues(s);
     275                Point startend = separateValues(s);
    276276
    277277                int start = startend.x;
     
    299299         */
    300300        private void createConstraint() {
    301                 java.awt.Point idtype = separateValues(_data.get("C"));
    302                 java.awt.Point startend = separateValues(_data.get("s"));
     301                Point idtype = separateValues(_data.get("C"));
     302                Point startend = separateValues(_data.get("s"));
    303303
    304304                Item a = _linePoints.get(startend.x);
     
    398398
    399399        // returns two ints separated by a space from the given String
    400         private java.awt.Point separateValues(String line) {
     400        private Point separateValues(String line) {
    401401                int x = Integer.parseInt(line.substring(0, line.indexOf(" ")));
    402402                int y = Integer.parseInt(line.substring(line.indexOf(" ") + 1));
    403403
    404                 return new java.awt.Point(x, y);
     404                return new Point(x, y);
    405405        }
    406406
  • trunk/src/org/expeditee/io/PDF2Writer.java

    r919 r1102  
    1919package org.expeditee.io;
    2020
    21 import java.awt.Color;
    22 import java.awt.Dimension;
    23 import java.awt.Image;
    24 import java.awt.Polygon;
    25 import java.awt.geom.AffineTransform;
    2621import java.io.FileOutputStream;
    2722import java.io.IOException;
     
    3429import java.util.Set;
    3530
     31import org.expeditee.core.Colour;
     32import org.expeditee.core.Dimension;
     33import org.expeditee.core.Image;
     34import org.expeditee.core.bounds.PolygonBounds;
     35import org.expeditee.gio.swing.SwingConversions;
     36import org.expeditee.gio.swing.SwingMiscManager;
     37import org.expeditee.gui.DisplayController;
    3638import org.expeditee.gui.Frame;
    3739import org.expeditee.gui.FrameGraphics;
     
    145147
    146148        public PDF2Writer() {
    147                 _pageSize = FrameGraphics.getMaxSize();
     149                _pageSize = DisplayController.getFramePaintArea().getSize();
    148150                _pdfDocument = new Document(new Rectangle(_pageSize.width, _pageSize.height));
    149151        }
     
    233235                // set bg color
    234236                PdfContentByte cb = _pdfWriter.getDirectContent();
    235                 cb.setColorFill(starting.getPaintBackgroundColor());
     237                cb.setColorFill(SwingConversions.toSwingColor(starting.getPaintBackgroundColor()));
    236238                cb.rectangle(0, 0, _pageSize.width, _pageSize.height);
    237239                cb.fill();
     
    239241        }
    240242       
    241         private void drawPolygon(PdfContentByte cb, Polygon poly, Color fill, Color line, float lineThickness) {
     243        private void drawPolygon(PdfContentByte cb, PolygonBounds poly, Colour fill, Colour line, float lineThickness) {
    242244                if(poly != null) {
    243                         cb.moveTo(poly.xpoints[0], _height - poly.ypoints[0]);
    244                         for(int i = 1; i < poly.npoints; i++) {
    245                                 cb.lineTo(poly.xpoints[i], _height - poly.ypoints[i]);
     245                        cb.moveTo(poly.toArray()[0].x, _height - poly.toArray()[0].y);
     246                        for(int i = 1; i < poly.toArray().length; i++) {
     247                                cb.lineTo(poly.toArray()[i].x, _height - poly.toArray()[i].y);
    246248                        }
    247249                        cb.closePath();
    248250                        if(fill != null) {
    249                                 cb.setColorFill(fill);
     251                                cb.setColorFill(SwingConversions.toSwingColor(fill));
    250252                                if(lineThickness > 0) {
    251253                                cb.setLineWidth(lineThickness);
    252                                 cb.setColorStroke(line);
     254                                cb.setColorStroke(SwingConversions.toSwingColor(line));
    253255                                cb.fillStroke();
    254256                        } else {
     
    257259                        } else {
    258260                                cb.setLineWidth(lineThickness);
    259                                 cb.setColorStroke(line);
     261                                cb.setColorStroke(SwingConversions.toSwingColor(line));
    260262                                cb.stroke();
    261263                        }
     
    269271                if (hasLink) {
    270272                       
    271                         Color lineColor = Color.BLACK, fillColor = null;
    272                         Polygon poly = i.getLinkPoly();
    273                         poly = new Polygon(poly.xpoints, poly.ypoints, poly.npoints);
     273                        Colour lineColor = Colour.BLACK, fillColor = null;
     274                        PolygonBounds poly = new PolygonBounds(i.getLinkBounds().getPolygon(16));
    274275                        poly.translate((int) (x - Item.LEFT_MARGIN), (int) (_height - y - i.getBoundsHeight() / 2));
    275276                       
     
    298299        protected void writeText(Text text) throws IOException {
    299300                PdfContentByte cb = _pdfWriter.getDirectContent();
    300                 Font font = FontFactory.getFont(
    301                                 Conversion.getPdfFont(text.getFamily()), text.getSize(), text
    302                                                 .getPaintFont().getStyle(), text.getPaintColor());
     301                Font font = FontFactory.getFont(Conversion.getPdfFont(text.getFamily()),
     302                                                                                text.getSize(),
     303                                                                                SwingConversions.toSwingFontStyle(text.getPaintFont().getStyle()),
     304                                                                                SwingConversions.toSwingColor(text.getPaintColor()));
    303305               
    304306                // we draw some text on a certain position
     
    318320                try {
    319321                        PdfContentByte cb = _pdfWriter.getDirectContent();
    320                         com.lowagie.text.Image iTextImage = com.lowagie.text.Image.getInstance(image, null);
     322                        com.lowagie.text.Image iTextImage = com.lowagie.text.Image.getInstance(SwingMiscManager.getIfUsingSwingImageManager().getInternalImage(image), null);
    321323                        float angle = (float) (pic.getRotate() * Math.PI / 180);
    322324                        double sin = Math.sin(angle), cos = Math.cos(angle);
     
    339341                PdfContentByte cb = _pdfWriter.getDirectContent();
    340342                cb.circle(circle.getCenter().getX(), _pdfWriter.getPageSize().getHeight() - circle.getCenter().getY(), (float) circle.getRadius());
    341                 cb.setColorFill(circle.getFillColor());
     343                cb.setColorFill(SwingConversions.toSwingColor(circle.getFillColor()));
    342344                if(circle.getThickness() > 0) {
    343345                        cb.setLineWidth(circle.getThickness());
    344                         cb.setColorStroke(circle.getPaintColor());
     346                        cb.setColorStroke(SwingConversions.toSwingColor(circle.getPaintColor()));
    345347                        cb.fillStroke();
    346348                } else {
     
    377379                        }
    378380                        cb.closePath();
    379                         Color fill = currentItem.getFillColor();
     381                        Colour fill = currentItem.getFillColor();
    380382                        if(fill != null) {
    381                         cb.setColorFill(fill);
     383                        cb.setColorFill(SwingConversions.toSwingColor(fill));
    382384                        if(currentItem.getThickness() > 0) {
    383385                                cb.setLineWidth(currentItem.getThickness());
    384                                 cb.setColorStroke(currentLine.getPaintColor());
     386                                cb.setColorStroke(SwingConversions.toSwingColor(currentLine.getPaintColor()));
    385387                                cb.fillStroke();
    386388                        } else {
     
    389391                        } else if(currentItem.getThickness() > 0) {
    390392                                cb.setLineWidth(currentItem.getThickness());
    391                                 cb.setColorStroke(currentLine.getPaintColor());
     393                                cb.setColorStroke(SwingConversions.toSwingColor(currentLine.getPaintColor()));
    392394                                cb.stroke();
    393395                        }
     
    403405                                        if(l.getThickness() >= 0) {
    404406                                                cb.setLineWidth(l.getThickness());
    405                                                 cb.setColorStroke(l.getPaintColor());
     407                                                cb.setColorStroke(SwingConversions.toSwingColor(l.getPaintColor()));
    406408                                                cb.stroke();
    407409                                        }
  • trunk/src/org/expeditee/io/PDFWriter.java

    r919 r1102  
    1919package org.expeditee.io;
    2020
    21 import java.awt.Image;
    2221import java.io.FileOutputStream;
    2322import java.io.IOException;
     
    2524import java.util.List;
    2625
     26import org.expeditee.core.Image;
     27import org.expeditee.gio.swing.SwingConversions;
     28import org.expeditee.gio.swing.SwingMiscManager;
    2729import org.expeditee.gui.Frame;
    2830import org.expeditee.items.Item;
     
    5456                if (UserSettings.Style.get().size() > 0) {
    5557                        Text text = UserSettings.Style.get().get(0);
    56                         _bodyFont = FontFactory.getFont(Conversion.getPdfFont(text
    57                                         .getFamily()), text.getSize(), text.getPaintFont()
    58                                         .getStyle(), text.getColor());
     58                        _bodyFont = FontFactory.getFont(Conversion.getPdfFont(text.getFamily()),
     59                                                                                        text.getSize(),
     60                                                                                        SwingConversions.toSwingFontStyle(text.getPaintFont().getStyle()),
     61                                                                                        SwingConversions.toSwingColor(text.getColor()));
    5962                }
    6063                _pdfDocument = new Document();
     
    114117
    115118                        if (font == null) {
    116                                 font = FontFactory.getFont(Conversion.getPdfFont(text
    117                                                 .getFamily()), text.getSize(), text.getPaintFont()
    118                                                 .getStyle(), text.getColor());
     119                                font = FontFactory.getFont(Conversion.getPdfFont(text.getFamily()),
     120                                                                                        text.getSize(),
     121                                                                                        SwingConversions.toSwingFontStyle(text.getPaintFont().getStyle()),
     122                                                                                        SwingConversions.toSwingColor(text.getColor()));
    119123                        }
    120124                       
     
    130134                Image image = pic.getCroppedImage();
    131135                try {
    132                         _pdfDocument.add(com.lowagie.text.Image.getInstance(image, null));
     136                        _pdfDocument.add(com.lowagie.text.Image.getInstance(SwingMiscManager.getIfUsingSwingImageManager().getInternalImage(image), null));
    133137                } catch (DocumentException e) {
    134138                        // TODO Auto-generated catch block
  • trunk/src/org/expeditee/io/PdfFramesetWriter.java

    r919 r1102  
    1919package org.expeditee.io;
    2020
    21 import java.awt.Dimension;
    2221import java.awt.Graphics2D;
    23 import java.awt.Image;
    2422import java.io.FileOutputStream;
    2523import java.io.IOException;
     
    2826import java.util.List;
    2927
     28import org.expeditee.core.Dimension;
     29import org.expeditee.core.Image;
     30import org.expeditee.gio.EcosystemManager;
     31import org.expeditee.gio.GraphicsManager;
     32import org.expeditee.gio.swing.SwingConversions;
     33import org.expeditee.gio.swing.SwingMiscManager;
     34import org.expeditee.gui.DisplayController;
    3035import org.expeditee.gui.Frame;
    3136import org.expeditee.gui.FrameGraphics;
     
    3540import org.expeditee.items.Picture;
    3641import org.expeditee.items.Text;
    37 import org.expeditee.items.widgets.InteractiveWidget;
     42import org.expeditee.items.widgets.Widget;
    3843import org.expeditee.settings.UserSettings;
    3944
     
    5964        private boolean _showFrameNames;
    6065
    61         public PdfFramesetWriter(long firstFrame, long maxFrame,
    62                         boolean showFrameNames) {
     66        public PdfFramesetWriter(long firstFrame, long maxFrame, boolean showFrameNames)
     67        {
    6368                super(firstFrame, maxFrame);
    64                 Dimension d = FrameGraphics.getMaxSize();
     69                Dimension d = DisplayController.getFramePaintArea().getSize();
    6570                _pdfDocument = new Document(new Rectangle(d.width, d.height));
    6671                _showFrameNames = showFrameNames;
     
    130135                // we tell the ContentByte we're ready to draw text
    131136                cb.beginText();
    132                 Font font = FontFactory.getFont(
    133                                 Conversion.getPdfFont(text.getFamily()), text.getSize(), text
    134                                                 .getPaintFont().getStyle(), text.getPaintColor());
     137                Font font = FontFactory.getFont(Conversion.getPdfFont(text.getFamily()),
     138                                                                                text.getSize(),
     139                                                                                SwingConversions.toSwingFontStyle(text.getPaintFont().getStyle()),
     140                                                                                SwingConversions.toSwingColor(text.getPaintColor()));
    135141                cb.setFontAndSize(font.getBaseFont(), text.getSize());
    136142                // cb.setColorStroke(text.getPaintColor());
    137                 cb.setColorFill(text.getPaintColor());
     143                cb.setColorFill(SwingConversions.toSwingColor(text.getPaintColor()));
    138144
    139145                // we draw some text on a certain position
     
    158164                        PdfContentByte cb = _pdfWriter.getDirectContent();
    159165                        com.lowagie.text.Image iTextImage = com.lowagie.text.Image
    160                                         .getInstance(image, null);
     166                                        .getInstance(SwingMiscManager.getIfUsingSwingImageManager().getInternalImage(image), null);
    161167                        iTextImage.setAbsolutePosition(pic.getX(), _pdfWriter.getPageSize()
    162168                                        .getHeight()
     
    175181//                      cb.setColorFill(fill);
    176182//              }
    177                 Graphics2D g = cb.createGraphicsShapes(
     183/*              Graphics2D g = cb.createGraphicsShapes(
    178184                                FrameGraphics.getMaxSize().width,
    179                                 FrameGraphics.getMaxSize().height);
    180                 lineEnd.paint(g);
     185                                FrameGraphics.getMaxSize().height);*/
     186                GraphicsManager g = EcosystemManager.getGraphicsManager();
     187                Image temp = EcosystemManager.getImageManager().createImage(DisplayController.getFramePaintArea().getSize());
     188                lineEnd.paint();
    181189//              if (fill != null) {
    182190//                      g.setPaint(fill);
     
    191199       
    192200        @Override
    193         protected void writeCircle(Circle toWrite) throws IOException {
    194                 PdfContentByte cb = _pdfWriter.getDirectContent();
    195                 Graphics2D g = cb.createGraphicsShapes(
    196                                 FrameGraphics.getMaxSize().width,
    197                                 FrameGraphics.getMaxSize().height);
    198                 toWrite.paint(g);
     201        protected void writeCircle(Circle toWrite) throws IOException
     202        {
     203                PdfContentByte cb = _pdfWriter.getDirectContent();
     204                Graphics2D g = cb.createGraphicsShapes(DisplayController.getFramePaintArea().getWidth(), DisplayController.getFramePaintArea().getHeight());
     205                Image temp = EcosystemManager.getImageManager().createImage(DisplayController.getFramePaintArea().getSize());
     206                EcosystemManager.getGraphicsManager().pushDrawingSurface(temp);
     207                toWrite.paint();
     208                EcosystemManager.getGraphicsManager().popDrawingSurface();
     209                g.drawImage(SwingMiscManager.getIfUsingSwingImageManager().getInternalImage(temp), 0, 0, null);
    199210        }
    200211       
    201        
    202         @Override
    203         protected void writeWidget(InteractiveWidget toWrite) throws IOException {
    204                 PdfContentByte cb = _pdfWriter.getDirectContent();
    205                 Graphics2D g = cb.createGraphicsShapes(
    206                                 FrameGraphics.getMaxSize().width,
    207                                 FrameGraphics.getMaxSize().height);
    208                 toWrite.paint(g);
     212        @Override
     213        protected void writeWidget(Widget toWrite) throws IOException
     214        {
     215                PdfContentByte cb = _pdfWriter.getDirectContent();
     216                Graphics2D g = cb.createGraphicsShapes(DisplayController.getFramePaintArea().getWidth(), DisplayController.getFramePaintArea().getHeight());
     217                Image temp = EcosystemManager.getImageManager().createImage(DisplayController.getFramePaintArea().getSize());
     218                EcosystemManager.getGraphicsManager().pushDrawingSurface(temp);
     219                toWrite.paint();
     220                EcosystemManager.getGraphicsManager().popDrawingSurface();
     221                g.drawImage(SwingMiscManager.getIfUsingSwingImageManager().getInternalImage(temp), 0, 0, null);
    209222        }
    210223}
  • trunk/src/org/expeditee/io/ProxyAuth.java

    r919 r1102  
    2424public class ProxyAuth extends Authenticator {
    2525
     26        public static final int MAX_ATTEMPTS = 5;
     27       
    2628        private String httpUser = null, httpPass = null, httpsUser = null, httpsPass = null;
    2729        private int attempts = 0;
     
    3739                // stop it from breaking from a redirect loop
    3840                attempts++;
    39                 if(attempts > 5) {
     41                if(attempts > MAX_ATTEMPTS) {
    4042                        return null;
    4143                }
  • trunk/src/org/expeditee/io/ProxyWriter.java

    r919 r1102  
    1919package org.expeditee.io;
    2020
    21 import java.awt.Toolkit;
    22 import java.awt.datatransfer.StringSelection;
    2321import java.io.BufferedWriter;
    2422import java.io.IOException;
    2523import java.io.PipedWriter;
    2624import java.io.Writer;
     25
     26import org.expeditee.gio.ClipboardManager.ClipboardData;
     27import org.expeditee.gio.EcosystemManager;
    2728
    2829public class ProxyWriter extends BufferedWriter {
     
    5556        public void flush() throws IOException {
    5657                if (_contents != null) {
    57                         StringSelection selection = new StringSelection(_contents
    58                                         .toString());
    59                         Toolkit.getDefaultToolkit().getSystemClipboard().setContents(
    60                                         selection, null);
    61                 } else
     58                        EcosystemManager.getClipboardManager().set(ClipboardData.fromString(_contents.toString()));
     59                } else {
    6260                        super.flush();
     61                }
    6362        }
    6463
  • trunk/src/org/expeditee/io/StreamGobbler.java

    r919 r1102  
    1919package org.expeditee.io;
    2020
    21 
    22 import java.util.*;
    2321import java.io.*;
    24 
    25 import javax.swing.SwingUtilities;
    2622
    2723import org.expeditee.gui.MessageBay;
     
    8278                // MessageBay is on the AWT event thread, so need to use 'invokeLater' to avoid thread deadlock
    8379                Runnable updateMessageBayTask = new UpdateMessageBay(type,line);
    84                 SwingUtilities.invokeLater(updateMessageBayTask);
     80                updateMessageBayTask.run();
    8581               
    8682            }
  • trunk/src/org/expeditee/io/WebParser.java

    r919 r1102  
    1919package org.expeditee.io;
    2020
    21 import java.awt.Color;
    22 import java.awt.Font;
    23 import java.awt.image.BufferedImage;
    2421import java.io.File;
    2522import java.io.IOException;
     
    4542import javafx.beans.value.ObservableValue;
    4643import javafx.concurrent.Worker.State;
    47 import javafx.embed.swing.SwingFXUtils;
    4844import javafx.scene.SnapshotParameters;
    4945import javafx.scene.image.WritableImage;
     
    5147import javafx.scene.web.WebView;
    5248
    53 import javax.imageio.ImageIO;
    54 
    5549import netscape.javascript.JSObject;
    5650
    57 import org.expeditee.gui.DisplayIO;
     51import org.expeditee.core.Colour;
     52import org.expeditee.core.Font;
     53import org.expeditee.core.Image;
     54import org.expeditee.core.InOutReference;
     55import org.expeditee.gio.EcosystemManager;
     56import org.expeditee.gio.gesture.StandardGestureActions;
     57import org.expeditee.gio.swing.SwingMiscManager;
     58import org.expeditee.gui.DisplayController;
    5859import org.expeditee.gui.Frame;
    59 import org.expeditee.gui.FrameGraphics;
    6060import org.expeditee.gui.FrameIO;
    61 import org.expeditee.gui.FrameMouseActions;
    6261import org.expeditee.gui.FrameUtils;
    6362import org.expeditee.gui.MessageBay;
     
    303302                try {
    304303                       
    305                         final int verticalScrollPerPage = (int) (FrameGraphics.getMaxFrameSize().getHeight() * 0.85);
    306                         final int horizontalScrollPerPage = (int) (FrameGraphics.getMaxFrameSize().getWidth() * 0.85);
     304                        final int verticalScrollPerPage = (int) (DisplayController.getFramePaintArea().getHeight() * 0.85);
     305                        final int horizontalScrollPerPage = (int) (DisplayController.getFramePaintArea().getWidth() * 0.85);
    307306                                               
    308307                        Platform.runLater(new Runnable() {
     
    320319                        final Object notifier = new Object();
    321320                                               
    322                         final MutableInt verticalCount = new MutableInt(0);
    323                         final MutableInt horizontalCount = new MutableInt(0);
     321                        final InOutReference<Integer> verticalCount = new InOutReference<Integer>(0);
     322                        final InOutReference<Integer> horizontalCount = new InOutReference<Integer>(0);
    324323                       
    325                         final MutableInt pagesVertical = new MutableInt(1);
    326                         final MutableInt pagesHorizontal = new MutableInt(1);
     324                        final InOutReference<Integer> pagesVertical = new InOutReference<Integer>(1);
     325                        final InOutReference<Integer> pagesHorizontal = new InOutReference<Integer>(1);
    327326
    328327                        final String pageTitle;
     
    341340                        frameset.getTitleItem().setSize(14);
    342341
    343                         WebParser.addButton("Return to original frame", frame.getName(), null, 200, frameset, null, 0f, 10f, null);
    344 
    345                         Text link = DisplayIO.getCurrentFrame().addText(FrameMouseActions.getX(), FrameMouseActions.getY(), pageTitle, null);
     342                        WebParser.addButton("Return to original frame", frame.getName(), null, 200, frameset, null, 0, 10, null);
     343
     344                        Text link = DisplayController.getCurrentFrame().addText(DisplayController.getMouseX(), DisplayController.getMouseY(), pageTitle, null);
    346345                        link.setLink(frameset.getName());
    347346
    348                         FrameMouseActions.pickup(link);
     347                        StandardGestureActions.pickup(link);
    349348
    350349                        // Timer that fires every time JFX is redrawn. After a few redraws, the handle method of this takes a screenshot of the page,
     
    364363                                                this.stop();
    365364                                               
    366                                                 verticalCount.setValue(verticalCount.getValue() + 1);
     365                                                verticalCount.set(verticalCount.get() + 1);
    367366
    368367                                                frameToAddTo = FrameIO.CreateFrame(frameToAddTo.getFramesetName(), pageTitle, null);
     
    395394
    396395                                                // Getting a BufferedImage from the JavaFX image
    397                                                 BufferedImage image = SwingFXUtils.fromFXImage(img, null);
     396                                                //BufferedImage image = SwingFXUtils.fromFXImage(img, null);
     397                                                Image image = SwingMiscManager.getImageForJavaFXImage(img);
    398398
    399399                                                try {
    400                                                         int hashcode = Arrays.hashCode(image.getData().getPixels(0, 0, image.getWidth(), image.getHeight(), (int[]) null));
    401 
     400                                                        // TODO: tidy. cts16
     401                                                        //int hashcode = Arrays.hashCode(image.getData().getPixels(0, 0, image.getWidth(), image.getHeight(), (int[]) null));
     402                                                        int hashcode = image.hashCode();
     403                                                       
    402404                                                        File out = new File(FrameIO.IMAGES_PATH + "webpage-" + Integer.toHexString(hashcode) + ".png");
    403405                                                        out.mkdirs();
    404                                                         ImageIO.write(image, "png", out);
     406                                                        image.writeToDisk("png", out);
    405407
    406408                                                        // Adding the image to the frame
     
    408410                                                       
    409411                                                        // Adding thumbnail to the overview page
    410                                                         Text thumb = frameset.addText((int) (thumbWidth * 1.1 * horizontalCount.getValue()) + 10,
    411                                                                         (int) ((((float) thumbWidth / image.getWidth()) * image.getHeight()) * 1.1 * verticalCount.getValue()),
     412                                                        Text thumb = frameset.addText((int) (thumbWidth * 1.1 * horizontalCount.get()) + 10,
     413                                                                        (int) ((((float) thumbWidth / image.getWidth()) * image.getHeight()) * 1.1 * verticalCount.get()),
    412414                                                                        "@i: " + out.getName() + " " + thumbWidth,
    413415                                                                        null);
    414416                                                       
    415417                                                        thumb.setLink(frameToAddTo.getName());
    416                                                         thumb.setBorderColor(Color.lightGray);
     418                                                        thumb.setBorderColor(Colour.LIGHT_GREY);
    417419                                                        thumb.setThickness(1);
    418420
    419421                                                        // Button to go to the next frame/page
    420                                                         WebParser.addButton("Next", null, "next", 70, frameToAddTo, null, 0f, 10f, null);
     422                                                        WebParser.addButton("Next", null, "next", 70, frameToAddTo, null, 0, 10, null);
    421423
    422424                                                        // Button to go to the previous frame/page
    423                                                         if (verticalCount.getValue() > 1 || horizontalCount.getValue() > 0) {
    424                                                                 WebParser.addButton("Previous", null, "previous", 70, frameToAddTo, null, 85f, 10f, null);
     425                                                        if (verticalCount.get() > 1 || horizontalCount.get() > 0) {
     426                                                                WebParser.addButton("Previous", null, "previous", 70, frameToAddTo, null, 85, 10, null);
    425427                                                        }
    426428
    427429                                                        // Button to return to the index/overview page
    428                                                         WebParser.addButton("Index", frameset.getName(), null, 70, frameToAddTo, null, null, 10f, 5f);
     430                                                        WebParser.addButton("Index", frameset.getName(), null, 70, frameToAddTo, null, null, 10, 5);
    429431
    430432                                                        FrameIO.SaveFrame(frameToAddTo);
     
    435437                                                }
    436438
    437                                                 image.flush();
     439                                                image.releaseImage();
    438440
    439441                                                synchronized (notifier) {
     
    468470                                                // but if the webpage fits in a single converted page, there's no need for any overlap, so just use 1 as the number of pages
    469471                                                if((Boolean) webEngine.executeScript("document.documentElement.scrollHeight > window.innerHeight")) {
    470                                                         pagesVertical.setValue((int) Math.ceil((Integer) webEngine.executeScript("document.documentElement.scrollHeight") / (float) verticalScrollPerPage));
     472                                                        pagesVertical.set((int) Math.ceil((Integer) webEngine.executeScript("document.documentElement.scrollHeight") / (float) verticalScrollPerPage));
    471473                                                }
    472474                                               
    473475                                                if((Boolean) webEngine.executeScript("document.documentElement.scrollWidth > window.innerWidth")) {
    474                                                         pagesHorizontal.setValue((int) Math.ceil((Integer) webEngine.executeScript("document.documentElement.scrollWidth") / (float) horizontalScrollPerPage));
     476                                                        pagesHorizontal.set((int) Math.ceil((Integer) webEngine.executeScript("document.documentElement.scrollWidth") / (float) horizontalScrollPerPage));
    475477                                                }
    476478                                               
    477479                                                System.out.println(webEngine.executeScript("document.documentElement.scrollWidth") + "/" + horizontalScrollPerPage);
    478                                                 System.out.println(pagesVertical.getValue() + "x" + pagesHorizontal.getValue());
     480                                                System.out.println(pagesVertical.get() + "x" + pagesHorizontal.get());
    479481                                               
    480482                                                // Setting up the element that contains the CSS to hide all text. Also hiding readability mode buttons.
     
    628630
    629631                        // Loop that scrolls the page horizontally
    630                         for(int i = 0; i < pagesHorizontal.getValue() && browserWidget.isParserRunning(); i++) {
     632                        for(int i = 0; i < pagesHorizontal.get() && browserWidget.isParserRunning(); i++) {
    631633                                                               
    632634                                Platform.runLater(new Runnable() {
     
    647649                               
    648650                                // Loop that scrolls the page vertically (for each horizontal scroll position)
    649                                 for(int j = 0; j < pagesVertical.getValue()  && browserWidget.isParserRunning(); j++) {
     651                                for(int j = 0; j < pagesVertical.get()  && browserWidget.isParserRunning(); j++) {
    650652                                       
    651653                                        try {
    652                                                 progressBar.set((int) (50 + ((float)(j+1)/(pagesVertical.getValue() * pagesHorizontal.getValue())  + ((float)(i) / pagesHorizontal.getValue())) * 50));
     654                                                progressBar.set((int) (50 + ((float)(j+1)/(pagesVertical.get() * pagesHorizontal.get())  + ((float)(i) / pagesHorizontal.get())) * 50));
    653655                                        } catch (Exception e) {
    654656                                                e.printStackTrace();
     
    698700                                }
    699701
    700                                 horizontalCount.setValue(horizontalCount.getValue() + 1);
    701                                 verticalCount.setValue(0);
     702                                horizontalCount.set(horizontalCount.get() + 1);
     703                                verticalCount.set(0);
    702704                        }
    703705
     
    742744         * @return A Color object that should match the rgb string passed int. Returns null if alpha is 0
    743745         */
    744         private static Color rgbStringToColor(String rgbString) {
     746        private static Colour rgbStringToColor(String rgbString) {
    745747
    746748                if (rgbString == null) {
     
    764766
    765767                if (components[3] > 0) {
    766                         return new Color(components[0], components[1], components[2], components[3]);
     768                        return Colour.FromRGBA255(components[0], components[1], components[2], components[3]);
    767769                } else {
    768770                        return null;
     
    854856
    855857                                        Boolean fontFound = false;
    856                                         Font font = new Font(null);
     858                                        Font font = null;
    857859
    858860                                        // Looping through all font-families listed in the element's CSS until one that is installed is
     
    869871                                               
    870872                                                // Regex will remove any inverted commas surrounding multi-word typeface names
    871                                                 font = new Font(typefaces[j].replaceAll("^'|'$", ""), Font.PLAIN, 12);
    872                                                
    873                                                 // If the font isn't found, Java just uses Font.DIALOG, so this check checks whether the font was found
    874                                                 if (!(font.getFamily().toLowerCase().equals(Font.DIALOG.toLowerCase()))) {
     873                                                String familyName = typefaces[j].replaceAll("^'|'$", "");
     874                                                font = new Font(familyName);
     875                                                font.setStyle(Font.Style.PLAIN);
     876                                                font.setSize(12);
     877                                               
     878                                                // Check whether the font was found
     879                                                if (EcosystemManager.getFontManager().getActualFont(font).getFamilyName().toLowerCase().equals(familyName.toLowerCase())) {
    875880                                                        fontFound = true;
    876881                                                }
    877882                                        }
    878883
    879                                         if (font.getFamily().toLowerCase().equals(Font.DIALOG.toLowerCase())) {
    880                                                 font = new Font("Times New Roman", Font.PLAIN, 12);
     884                                        if (!fontFound) {
     885                                                font = new Font("Times New Roman");
     886                                                font.setStyle(Font.Style.PLAIN);
     887                                                font.setSize(12);
    881888                                        }
    882889
     
    975982                                        String bgColorString = (String) style.call("getPropertyValue", new Object[] { "background-color" });
    976983
    977                                         Color bgColor = rgbStringToColor(bgColorString);
     984                                        Colour bgColor = rgbStringToColor(bgColorString);
    978985
    979986                                        // If the element has a background color then add it (to Expeditee) as a rectangle with that background color
     
    10771084                HttpURLConnection connection = (HttpURLConnection) (imgUrl.openConnection());
    10781085
    1079                 // Spoofing a widely accepted User Agent, since some sites refuse to serve non-webbrowser clients
    1080                 connection.setRequestProperty("User-Agent", "Mozilla/5.0");
    1081 
    1082                 BufferedImage img = ImageIO.read(connection.getInputStream());
    1083 
    1084                 int hashcode = Arrays.hashCode(img.getData().getPixels(0, 0, img.getWidth(), img.getHeight(), (int[]) null));
     1086                Image img = Image.getImage(connection);
     1087               
     1088                int hashcode = img.hashCode();
     1089               
    10851090                File out = new File(FrameIO.IMAGES_PATH + Integer.toHexString(hashcode) + ".png");
    10861091                out.mkdirs();
    1087                 ImageIO.write(img, "png", out);
     1092                img.writeToDisk("png", out);
    10881093
    10891094                if (repeat == null && cropEndX == null && cropStartX == null && cropEndY == null && cropStartY == null) {
     
    11531158                text.setPosition(x, y);
    11541159
    1155                 Picture pic = ItemUtils.CreatePicture(text, frame);
     1160                Picture pic = ItemUtils.CreatePicture(text);
    11561161               
    11571162                float invScale = 1 / pic.getScale();
     
    13241329
    13251330                                Boolean fontFound = false;
    1326                                 Font font = new Font(null);
     1331                                Font font = null;
    13271332
    13281333                                // Looping through all font-families listed in the element's CSS until one that is installed is
     
    13421347
    13431348                                        // Regex will remove any inverted commas surrounding multi-word typeface names
    1344                                         font = new Font(typefaces[j].replaceAll("^'|'$", ""), Font.PLAIN, 12);
     1349                                        String familyName = typefaces[j].replaceAll("^'|'$", "");
     1350                                        font = new Font(familyName);
     1351                                        font.setStyle(Font.Style.PLAIN);
     1352                                        font.setSize(12);
    13451353
    13461354                                        // If the font isn't found, Java just uses Font.DIALOG, so this check checks whether the font was found
    1347                                         if (!(font.getFamily().toLowerCase().equals(Font.DIALOG.toLowerCase()))) {
     1355                                        if (EcosystemManager.getFontManager().getActualFont(font).getFamilyName().toLowerCase().equals(familyName.toLowerCase())) {
    13481356                                                fontFound = true;
    13491357                                        }
    13501358                                }
    13511359
    1352                                 if (font.getFamily().toLowerCase().equals(Font.DIALOG.toLowerCase())) {
    1353                                         font = new Font("Times New Roman", Font.PLAIN, 12);
     1360                                if (!fontFound) {
     1361                                        font = new Font("Times New Roman");
     1362                                        font.setStyle(Font.Style.PLAIN);
     1363                                        font.setSize(12);
    13541364                                }
    13551365
     
    14641474         * @param anchorLeft
    14651475         */
    1466         private static void addButton(String text, String link, String action, int width, Frame toAddTo, Float anchorTop, Float anchorRight, Float anchorBottom, Float anchorLeft) {
     1476        private static void addButton(String text, String link, String action, int width, Frame toAddTo, Integer anchorTop, Integer anchorRight, Integer anchorBottom, Integer anchorLeft) {
    14671477                // Button to go to the next frame/page
    14681478                Text button = new Text(text);
     
    14701480                button.setLink(link);
    14711481                button.addAction(action);
    1472                 button.setBorderColor(new Color(0.7f, 0.7f, 0.7f));
    1473                 button.setBackgroundColor(new Color(0.9f, 0.9f, 0.9f));
     1482                button.setBorderColor(new Colour(0.7f, 0.7f, 0.7f));
     1483                button.setBackgroundColor(new Colour(0.9f, 0.9f, 0.9f));
    14741484                button.setThickness(1);
    14751485                button.setLinkMark(false);
     
    14991509
    15001510        }
    1501 
    1502 
    1503         private static class MutableBool {
    1504                 private boolean value;
    1505 
    1506                 public MutableBool(boolean value) {
    1507                         this.value = value;
    1508                 }
    1509 
    1510                 public boolean getValue() {
    1511                         return value;
    1512                 }
    1513 
    1514                 public void setValue(boolean value) {
    1515                         this.value = value;
    1516                 }
    1517         }
    1518 
    1519         private static class MutableInt {
    1520                 private int value;
    1521 
    1522                 public MutableInt(int value) {
    1523                         this.value = value;
    1524                 }
    1525 
    1526                 public int getValue() {
    1527                         return value;
    1528                 }
    1529 
    1530                 public void setValue(int value) {
    1531                         this.value = value;
    1532                 }
    1533         }
    15341511}
  • trunk/src/org/expeditee/io/flowlayout/DimensionExtent.java

    r919 r1102  
    1919package org.expeditee.io.flowlayout;
    2020
    21 import java.awt.Polygon;
    22 import java.awt.Rectangle;
    23 import java.awt.geom.Area;
    2421import java.util.List;
    2522
     23import org.expeditee.core.bounds.AxisAlignedBoxBounds;
     24import org.expeditee.core.bounds.PolygonBounds;
    2625import org.expeditee.items.Item;
    2726
     
    4443               
    4544                for (Item item : items) {
    46                         Area area = item.getArea();
    47                         Rectangle rect = area.getBounds();
    48                         int xl = rect.x;
    49                         int xr = xl + rect.width-1;
     45                        AxisAlignedBoxBounds bounds = item.getBoundingBox();
     46                        int xl = bounds.getMinX();
     47                        int xr = xl + bounds.getWidth()-1;
    5048                       
    5149                        min_x = Math.min(min_x, xl);
     
    6664               
    6765                for (Item item : items) {
    68                         Area area = item.getArea();
    69                         Rectangle rect = area.getBounds();
    70                         int yt = rect.y;
    71                         int yb = yt + rect.height-1;
     66                        AxisAlignedBoxBounds bounds = item.getBoundingBox();
     67                        int yt = bounds.getMinY();
     68                        int yb = yt + bounds.getHeight()-1;
    7269                       
    7370                        min_y = Math.min(min_y, yt);
     
    8279
    8380       
    84         public static DimensionExtent calcMinMaxXExtent(Polygon polygon)
     81        public static DimensionExtent calcMinMaxXExtent(PolygonBounds polygon)
    8582        {
    8683
    87                 int min_x = Integer.MAX_VALUE;
    88                 int max_x = Integer.MIN_VALUE;
    89                
    90                 int npoints = polygon.npoints;
    91 
    92                 for (int i=0; i<npoints; i++) {
    93 
    94                         int x = polygon.xpoints[i];
    95 
    96                         min_x = Math.min(min_x, x);
    97                         max_x = Math.max(max_x, x);
    98                 }
    99                
    100                 DimensionExtent extent = new DimensionExtent(min_x,max_x);
     84                DimensionExtent extent = new DimensionExtent(polygon.getMinX(), polygon.getMaxX());
    10185               
    10286                return extent;
    10387        }
    10488       
    105         public static DimensionExtent calcMinMaxYExtent(Polygon polygon)
     89        public static DimensionExtent calcMinMaxYExtent(PolygonBounds polygon)
    10690        {
    10791
    108                 int min_y = Integer.MAX_VALUE;
    109                 int max_y = Integer.MIN_VALUE;
    110                
    111                 int npoints = polygon.npoints;
    112                
    113                 for (int i=0; i<npoints; i++) {
    114 
    115                         int y = polygon.ypoints[i];
    116                                
    117                         min_y = Math.min(min_y, y);
    118                         max_y = Math.max(max_y, y);
    119                 }
    120                
    121                 DimensionExtent extent = new DimensionExtent(min_y,max_y);
     92                DimensionExtent extent = new DimensionExtent(polygon.getMinY(), polygon.getMaxY());
    12293               
    12394                return extent;
    12495        }
    12596       
    126         public static Polygon boundingBoxPolygon(List<Item> items)
     97        public static PolygonBounds boundingBoxPolygon(List<Item> items)
    12798        {
    128                 DimensionExtent xextent = DimensionExtent.calcMinMaxXExtent(items);
    129                 DimensionExtent yextent = DimensionExtent.calcMinMaxYExtent(items);
    130        
    131                 int xl=xextent.min;
    132                 int xr=xextent.max;
    133                 int yt=yextent.min;
    134                 int yb=yextent.max;
     99                AxisAlignedBoxBounds box = null;
    135100               
    136                 int[] xpoints = new int[]{xl,xr,xr,xl};
    137                 int[] ypoints = new int[]{yt,yt,yb,yb};
     101                for (Item i : items) {
     102                        if (box == null) {
     103                                box = i.getBoundingBox();
     104                        } else {
     105                                box.combineWith(i.getBoundingBox());
     106                        }
     107                }
    138108               
    139                
    140                 Polygon polygon = new Polygon(xpoints,ypoints,4);
    141                
    142                 return polygon;
     109                return new PolygonBounds(box.getBorderLines());
    143110        }
    144111}
  • trunk/src/org/expeditee/io/flowlayout/XGroupItem.java

    r976 r1102  
    1919package org.expeditee.io.flowlayout;
    2020
    21 import java.awt.Point;
    22 import java.awt.Polygon;
    23 import java.awt.Rectangle;
    2421import java.util.ArrayList;
    2522import java.util.Collection;
     
    3128import java.util.List;
    3229
     30import org.expeditee.core.Point;
     31import org.expeditee.core.bounds.AxisAlignedBoxBounds;
     32import org.expeditee.core.bounds.PolygonBounds;
    3333import org.expeditee.gui.Frame;
    3434import org.expeditee.gui.FrameUtils;
     
    110110        }
    111111
    112         public XGroupItem(Frame frame, List<Item> y_ordered_items,
    113                         Polygon enclosing_polygon) {
     112        public XGroupItem(Frame frame, List<Item> y_ordered_items, PolygonBounds enclosing_polygon) {
    114113                this.frame = frame;
    115114                this.out_of_flow = FlowType.in_flow;
     
    124123                }
    125124
    126                 Rectangle enclosing_bounding_rect = enclosing_polygon.getBounds();
     125                AxisAlignedBoxBounds enclosing_bounding_rect = AxisAlignedBoxBounds.getEnclosing(enclosing_polygon);
    127126                initSpanArray(enclosing_bounding_rect);
    128127
     
    134133                remaining_item_list = new ArrayList<Item>();
    135134
    136                 separateYOverlappingItems(frame, y_ordered_items, enclosing_polygon,
    137                                 raw_text_item_list, grouped_item_list, remaining_item_list);
     135                separateYOverlappingItems(frame, y_ordered_items, enclosing_polygon, raw_text_item_list, grouped_item_list, remaining_item_list);
    138136
    139137                // Step 2: Add in the raw-text items
     
    161159        }
    162160
    163         protected XGroupItem(XGroupItem imprint, Rectangle copy_to_bounding_rect) {
     161        protected XGroupItem(XGroupItem imprint, AxisAlignedBoxBounds copy_to_bounding_rect)
     162        {
    164163                super();
    165164
     
    192191                                                                                                // straight away?
    193192
    194                 this.bounding_rect = new Rectangle(copy_to_bounding_rect); // deep copy
     193                this.bounding_rect = new AxisAlignedBoxBounds(copy_to_bounding_rect); // deep copy
    195194                                                                                                                                        // to be on
    196195                                                                                                                                        // the safe
     
    198197        }
    199198
    200         protected void initSpanArray(Rectangle bounding_rect) {
     199        protected void initSpanArray(AxisAlignedBoxBounds bounding_rect) {
    201200                this.bounding_rect = bounding_rect;
    202201
     
    533532                                                        // to make it appear where the start of the arrow is
    534533
    535                                                         Rectangle start_rect = start_item.getArea()
    536                                                                         .getBounds();
     534                                                        AxisAlignedBoxBounds start_rect = start_item.getBoundingBox();
    537535
    538536                                                        XGroupItem xgroup_item_shallow_copy = new XGroupItem(
     
    630628         * @return
    631629         */
    632         public Collection<Item> getItemsInNestedEnclosure(Item given_item,
    633                         AreaPolygon outer_polygon) {
     630        public Collection<Item> getItemsInNestedEnclosure(Item given_item, PolygonBounds outer_polygon)
     631        {
    634632                Collection<Item> sameEnclosure = null;
    635633                Collection<Item> seen = new HashSet<Item>();
     
    649647                                seen.addAll(i_enclosing_dots);
    650648
    651                                 Polygon i_polygon = new Polygon();
     649                                PolygonBounds i_polygon = new PolygonBounds();
    652650                                for (int di = 0; di < i_enclosing_dots.size(); di++) {
    653651                                        Item d = i_enclosing_dots.get(di);
     
    684682
    685683        public void separateYOverlappingItems(Frame frame, List<Item> item_list,
    686                         Polygon enclosing_polygon, List<Text> raw_text_item_list,
     684                        PolygonBounds enclosing_polygon, List<Text> raw_text_item_list,
    687685                        List<XGroupItem> grouped_item_list, List<Item> remaining_item_list) {
    688686                final List<Item> origonal_item_list = new ArrayList<Item>(item_list);
     
    692690                // of lines/polylines/polygons
    693691
    694                 AreaPolygon area_enclosing_polygon = new AreaPolygon(enclosing_polygon);
    695 
    696                 List<AreaPolygon> area_enclosed_polygon_list = new ArrayList<AreaPolygon>();
     692                PolygonBounds area_enclosing_polygon = new PolygonBounds(enclosing_polygon);
     693
     694                List<PolygonBounds> area_enclosed_polygon_list = new ArrayList<PolygonBounds>();
    697695
    698696                while (item_list.size() > 0) {
     
    724722                                                                .remove(0); // shift
    725723
    726                                                 Polygon enclosed_polygon = enclosure_item
    727                                                                 .getEnclosedShape();
     724                                                PolygonBounds enclosed_polygon = enclosure_item.getEnclosedShape();
    728725
    729726                                                if (enclosed_polygon != null) {
     
    739736                                                        // group)
    740737
    741                                                         AreaPolygon area_enclosed_polygon = new AreaPolygon(
    742                                                                         enclosed_polygon);
    743                                                         area_enclosed_polygon_list
    744                                                                         .add(area_enclosed_polygon);
     738                                                        PolygonBounds area_enclosed_polygon = new PolygonBounds(enclosed_polygon);
     739                                                        area_enclosed_polygon_list.add(area_enclosed_polygon);
    745740
    746741                                                        item_list.remove(enclosure_item);
     
    763758                                                        while (item_iterator.hasNext()) {
    764759                                                                Item item_to_check = item_iterator.next();
    765                                                                 Point pt_to_check = new Point(
    766                                                                                 item_to_check.getX(),
    767                                                                                 item_to_check.getY());
    768 
    769                                                                 if (area_enclosed_polygon
    770                                                                                 .isPerimeterPoint(pt_to_check)) {
     760                                                                Point pt_to_check = new Point(item_to_check.getX(), item_to_check.getY());
     761
     762                                                                if (area_enclosed_polygon.isVertex(pt_to_check)) {
    771763                                                                        items_on_perimeter.add(item_to_check);
    772764                                                                }
     
    801793                // Sort areas, smallest to largest
    802794                Collections.sort(area_enclosed_polygon_list,
    803                                 new Comparator<AreaPolygon>() {
    804 
    805                                         public int compare(AreaPolygon ap1, AreaPolygon ap2) {
     795                                new Comparator<PolygonBounds>() {
     796
     797                                        public int compare(PolygonBounds ap1, PolygonBounds ap2) {
    806798                                                Double ap1_area = ap1.getArea();
    807799                                                Double ap2_area = ap2.getArea();
     
    817809                        // ri = remove index pos
    818810
    819                         AreaPolygon rpoly = area_enclosed_polygon_list.get(ri);
     811                        PolygonBounds rpoly = area_enclosed_polygon_list.get(ri);
    820812
    821813                        for (int ci = ri + 1; ci < area_enclosed_polygon_list.size(); ci++) {
    822814                                // ci = check index pos
    823                                 AreaPolygon cpoly = area_enclosed_polygon_list.get(ci);
     815                                PolygonBounds cpoly = area_enclosed_polygon_list.get(ci);
    824816                                if (rpoly.completelyContains(cpoly)) {
    825817                                        area_enclosed_polygon_list.remove(ci);
     
    837829                // recursive call below
    838830
    839                 for (AreaPolygon area_polygon : area_enclosed_polygon_list) {
    840 
    841                         Collection<Item> enclosed_items = FrameUtils.getItemsEnclosedBy(
    842                                         frame, area_polygon);
     831                for (PolygonBounds area_polygon : area_enclosed_polygon_list) {
     832
     833                        Collection<Item> enclosed_items = FrameUtils.getItemsEnclosedBy(frame, area_polygon);
    843834                        List<Item> enclosed_item_list = new ArrayList<Item>(enclosed_items);
    844835
     
    849840                                // Filter out enclosed-items points that are part of the
    850841                                // polygon's perimeter
    851                                 if (area_polygon.isPerimeterPoint(enclosed_item.getPosition())) {
     842                                if (area_polygon.isVertex(enclosed_item.getPosition())) {
    852843                                        enclosed_item_list.remove(i);
    853844                                        // Don't include items the user hasn't asked us to.
     
    863854                        // Recursively work on the identified sub-group
    864855
    865                         XGroupItem xgroup_item = new XGroupItem(frame, enclosed_item_list,
    866                                         area_polygon);
     856                        XGroupItem xgroup_item = new XGroupItem(frame, enclosed_item_list, area_polygon);
    867857
    868858                        grouped_item_list.add(xgroup_item);
  • trunk/src/org/expeditee/io/flowlayout/XItem.java

    r919 r1102  
    1919package org.expeditee.io.flowlayout;
    2020
    21 import java.awt.Point;
    22 import java.awt.Rectangle;
    2321
     22import org.expeditee.core.Point;
     23import org.expeditee.core.bounds.AxisAlignedBoxBounds;
    2424import org.expeditee.items.Item;
    2525
    2626public abstract class XItem
    2727{
    28         protected Rectangle bounding_rect;
     28        protected AxisAlignedBoxBounds bounding_rect;
    2929               
    3030        protected XItem()
     
    3333        }
    3434       
    35         protected XItem(Rectangle imprint_bounding_rect)
     35        protected XItem(AxisAlignedBoxBounds imprint_bounding_rect)
    3636        {
    3737                this.bounding_rect = imprint_bounding_rect;
     
    4040        public int getX()
    4141        {
    42                 return bounding_rect.x;
     42                return bounding_rect.getMinX();
    4343        }
    4444       
     
    4646        {
    4747                // name alias for getX()
    48                 return bounding_rect.x;
     48                return bounding_rect.getMinX();
    4949        }
    5050       
    5151        public int getY()
    5252        {
    53                 return bounding_rect.y;
     53                return bounding_rect.getMinY();
    5454        }
    5555       
     
    5757        {
    5858                // name alias for getY()
    59                 return bounding_rect.y;
     59                return bounding_rect.getMinY();
    6060        }
    6161       
    6262        public int getBoundingYBot()
    6363        {
    64                 return bounding_rect.y + bounding_rect.height -1;
     64                return bounding_rect.getMaxY();
    6565        }
    6666       
    6767        public int getBoundingXRight()
    6868        {
    69                 return bounding_rect.x + bounding_rect.width -1;
     69                return bounding_rect.getMaxX();
    7070        }
    7171       
    7272        public int getBoundingWidth()
    7373        {
    74                 return bounding_rect.width;
     74                return bounding_rect.getWidth();
    7575        }
    7676       
    7777        public int getBoundingHeight()
    7878        {
    79                 return bounding_rect.height;
     79                return bounding_rect.getHeight();
    8080        }
    8181       
    82         public Rectangle getBoundingRect()
     82        public AxisAlignedBoxBounds getBoundingRect()
    8383        {
    8484                return bounding_rect;
    8585        }
    8686       
    87         public Rectangle setBoundingRect(Rectangle rect)
     87        public AxisAlignedBoxBounds setBoundingRect(AxisAlignedBoxBounds rect)
    8888        {
    8989                return bounding_rect = rect;
  • trunk/src/org/expeditee/io/flowlayout/XOrderedLine.java

    r919 r1102  
    1919package org.expeditee.io.flowlayout;
    2020
    21 import java.awt.Rectangle;
    2221import java.util.ArrayList;
    2322import java.util.List;
     23
     24import org.expeditee.core.bounds.AxisAlignedBoxBounds;
    2425
    2526public class XOrderedLine
     
    8384                {
    8485                        // Simple case => want to insert based on the new_item's xl position
    85                         Rectangle rect = new_item.getBoundingRect();
    86                         int xl = rect.x;
     86                        AxisAlignedBoxBounds rect = new_item.getBoundingRect();
     87                        int xl = rect.getMinX();
    8788                        orderedMergeItem(xl,new_item);
    8889                }
  • trunk/src/org/expeditee/io/flowlayout/XRawItem.java

    r972 r1102  
    4141                else {
    4242                        // Just in case it isn't a text item
    43                         bounding_rect = item.getArea().getBounds();
     43                        bounding_rect = item.getBoundingBox();
    4444                }
    4545               
  • trunk/src/org/expeditee/items/Circle.java

    r919 r1102  
    1919package org.expeditee.items;
    2020
    21 import java.awt.Color;
    22 import java.awt.Graphics2D;
    23 import java.awt.Polygon;
    24 import java.awt.Rectangle;
    25 import java.awt.geom.Point2D;
    2621import java.util.Collection;
    2722import java.util.LinkedList;
     23
     24import org.expeditee.core.Colour;
     25import org.expeditee.core.Dimension;
     26import org.expeditee.core.Fill;
     27import org.expeditee.core.Point;
     28import org.expeditee.core.Stroke;
     29import org.expeditee.core.bounds.AxisAlignedBoxBounds;
     30import org.expeditee.core.bounds.CombinationBoxBounds;
     31import org.expeditee.core.bounds.EllipticalBounds;
     32import org.expeditee.core.bounds.PolygonBounds;
     33import org.expeditee.gio.EcosystemManager;
    2834
    2935/**
     
    4248         * @param _source
    4349         */
    44         public Circle(Text source) {
     50        public Circle(Text source)
     51        {
    4552                super(source);
    4653                // Collection<Item> connected = source.getAllConnected();
     
    5057                _center.addEnclosure(this);
    5158                _line.setHidden(true);
    52                 updatePolygon();
     59                invalidateBounds();
    5360        }
    5461
     
    8794
    8895        @Override
    89         public Polygon getEnclosedShape() {
     96        public PolygonBounds getEnclosedShape() {
    9097                // assert(_poly != null);
    9198                // Ensure that vector items will gradient fill are painted OK!!
    92                 if (_poly == null) {
    93                         updatePolygon();
    94                 }
    95                 return _poly;
     99                return ((EllipticalBounds) updateBounds()).getPolygon(16);
    96100        }
    97101
     
    138142                newCircle._line.setVisible(_line.isVisible());
    139143                newCircle._source.setVisible(_source.isVisible());
    140                 newCircle.updatePolygon();
     144                newCircle.invalidateBounds();
    141145                return newCircle;
    142146        }
     
    152156
    153157        @Override
    154         public boolean contains(int x, int y) {
     158        public boolean contains(Point p) {
    155159                double radius = getRadius();
    156160
    157                 double distance = Math.sqrt(Math.pow(Math.abs(_center.getX() - x), 2)
    158                                 + Math.pow(Math.abs(_center.getY() - y), 2));
     161                double distance = Math.sqrt(Math.pow(Math.abs(_center.getX() - p.x), 2)
     162                                + Math.pow(Math.abs(_center.getY() - p.y), 2));
    159163
    160164                return Math.abs(distance - radius) < getGravity() * 2;
     
    167171         */
    168172        @Override
    169         public void paint(Graphics2D g) {
     173        public void paint() {
    170174                int radius = (int) Math.round(getRadius());
    171                 int diameter = radius * 2;
    172                 Color fillColor = getFillColor();
    173                 if (fillColor != null) {
    174                         setFillPaint(g);
    175                         g.fillOval(_center.getX() - radius, _center.getY() - radius,
    176                                         diameter, diameter);
     175                Point centre = new Point(_center.getX(), _center.getY());
     176                Dimension diameters = new Dimension(radius * 2, radius * 2);
     177                Fill fill = new Fill(getFillColor());
     178                Colour lineColour = null;
     179                Stroke lineStroke = null;
     180                if (isHighlighted()) {
     181                        lineColour = getHighlightColor();
     182                        lineStroke = HIGHLIGHT_STROKE;
     183                } else if (getThickness() > 0 || getFillColor() == null) {
     184                        lineColour = getPaintColor();
     185                        lineStroke = _line.getStroke();
    177186                }
    178                 if (getThickness() > 0 || fillColor == null) {
    179                         Color lineColor = getPaintColor();
    180                         g.setColor(lineColor);
    181                         g.setStroke(_line.getStroke());
    182                         g.drawOval(_center.getX() - radius, _center.getY() - radius,
    183                                         diameter, diameter);
     187               
     188                EcosystemManager.getGraphicsManager().drawOval(centre, diameters, 0.0f, fill, lineColour, lineStroke);
     189               
     190                if (isHighlighted()) {
     191                        _center.paint();
    184192                }
    185                 // Arc version, same result but allows for portions of the circle to be
    186                 // drawn
    187                 // g.drawArc(end.getX() - (distance / 2), end.getY() - (distance / 2),
    188                 // distance, distance, 0, 360);
    189 
    190                 if (isHighlighted()) {
    191                         // Flag the background color of the circle so that the item will be
    192                         // drawn with alternate color if the background is the same as
    193                         // the highlight}
    194                         _center.paint(g);
    195                         Color highlightColor = getHighlightColor();
    196                         g.setColor(highlightColor);
    197                         g.setStroke(HIGHLIGHT_STROKE);
    198                         g.drawOval(_center.getX() - radius, _center.getY() - radius,
    199                                         diameter, diameter);
    200                 }
    201         }
    202 
    203         @Override
    204         public void setHighlightMode(HighlightMode mode, Color color) {
    205                 _center.setHighlightMode(mode, color);
    206                 super.setHighlightMode(mode, color);
    207         }
    208 
    209         @Override
    210         public int setHighlightColor(Color c) {
     193        }
     194
     195        @Override
     196        public void setHighlightModeAndColour(HighlightMode mode, Colour color) {
     197                _center.setHighlightModeAndColour(mode, color);
     198                super.setHighlightModeAndColour(mode, color);
     199        }
     200
     201        @Override
     202        public void setHighlightColor(Colour c) {
    211203                _center.setHighlightColor(c);
    212                 return super.setHighlightColor(c);
    213         }
    214 
    215         @Override
    216         public void setFillColor(Color c) {
     204                /*return*/ super.setHighlightColor(c);
     205        }
     206
     207        @Override
     208        public void setFillColor(Colour c) {
    217209                super.setFillColor(c);
    218210                _center.setColor(c);
     
    221213
    222214        @Override
    223         public void setGradientColor(Color c) {
     215        public void setGradientColor(Colour c) {
    224216                super.setGradientColor(c);
    225217                invalidateCommonTrait(ItemAppearence.GradientColor);
     
    255247         */
    256248        @Override
    257         public void updatePolygon() {
    258                 double radius = getRadius();
    259                 // Approximation of circle for mouse interaction
    260                 int points = 20;
    261 
    262                 double radians = 0.0;
    263                 int xPoints[] = new int[points];
    264                 int yPoints[] = new int[xPoints.length];
    265 
    266                 for (int i = 0; i < xPoints.length; i++) {
    267                         xPoints[i] = (int) Math.round(radius * Math.cos(radians));
    268                         yPoints[i] = (int) Math.round(radius * Math.sin(radians));
    269                         radians += (2.0 * Math.PI) / xPoints.length;
    270                 }
    271 
    272                 _poly = new Polygon(xPoints, yPoints, xPoints.length);
    273                 _poly.translate(_center.getX(), _center.getY());
    274                 return;
     249        public EllipticalBounds updateBounds()
     250        {
     251                return new EllipticalBounds(_center.getPosition(), (int) (getRadius() * 2));
    275252        }
    276253
     
    280257        }
    281258
    282         /**
    283          * Resizes the circle from the center.
    284          */
    285         @Override
    286         public void setSize(float size) {
     259        /** Resizes the circle from the center. */
     260        @Override
     261        public void setSize(float size)
     262        {
    287263                double ratio = size / getRadius();
    288264               
     
    290266                _source.translate(_center.getPosition(), ratio);
    291267
    292                 updatePolygon();
     268                invalidateBounds();
    293269        }
    294270
     
    303279        }
    304280
    305         @Override
    306         public void translate(Point2D origin, double ratio) {
    307                 updatePolygon();
     281        // TODO: Why is this commented out? cts16
     282        @Override
     283        public void translate(Point origin, double ratio)
     284        {
     285                invalidateBounds();
    308286                // _center.translate(origin, ratio);
    309287                // super.translate(origin, ratio);
     
    311289
    312290        @Override
    313         public Rectangle[] getDrawingArea() {
     291        public AxisAlignedBoxBounds getDrawingArea() {
    314292
    315293                float thickness = getThickness();
     
    318296                int size = (int) ((2 * radius) + 3.0 + thickness);
    319297
    320                 return new Rectangle[] { new Rectangle((int) (_center.getX() - radius
     298                return new AxisAlignedBoxBounds((int) (_center.getX() - radius
    321299                                - 0.5 - (thickness / 2.0)), (int) (_center.getY() - radius
    322                                 - 0.5 - (thickness / 2.0)), size, size) };
     300                                - 0.5 - (thickness / 2.0)), size, size);
    323301        }
    324302
  • trunk/src/org/expeditee/items/Constraint.java

    r919 r1102  
    2828 */
    2929public class Constraint {
     30       
    3031        public static final int VERTICAL = 2;
    3132
  • trunk/src/org/expeditee/items/Dot.java

    r919 r1102  
    1919package org.expeditee.items;
    2020
    21 import java.awt.Color;
    22 import java.awt.Graphics2D;
    23 import java.awt.Polygon;
    24 import java.awt.Rectangle;
    2521import java.util.ArrayList;
    2622import java.util.LinkedList;
    2723import java.util.List;
    2824
    29 import org.expeditee.gui.DisplayIO;
     25import org.expeditee.core.Colour;
     26import org.expeditee.core.Dimension;
     27import org.expeditee.core.Fill;
     28import org.expeditee.core.Point;
     29import org.expeditee.core.bounds.AxisAlignedBoxBounds;
     30import org.expeditee.core.bounds.Bounds;
     31import org.expeditee.core.bounds.PolygonBounds;
     32import org.expeditee.gio.EcosystemManager;
     33import org.expeditee.gio.GraphicsManager;
     34import org.expeditee.gui.DisplayController;
    3035import org.expeditee.gui.Frame;
    3136import org.expeditee.gui.FrameGraphics;
    32 import org.expeditee.gui.FrameKeyboardActions;
    3337
    3438/**
     
    7074
    7175        @Override
    72         public void setColor(Color c) {
     76        public void setColor(Colour c) {
    7377                super.setColor(c);
    7478
     
    7983
    8084        @Override
    81         public void setAnchorLeft(Float anchor) {
     85        public void setAnchorLeft(Integer anchor) {
    8286                if (!isLineEnd()) {
    8387                        super.setAnchorLeft(anchor);
     
    8892                invalidateCommonTrait(ItemAppearence.PreMoved);
    8993               
    90                 this._anchorLeft = anchor;
    91                 this._anchorRight = null;
     94                this._anchoring.setLeftAnchor(anchor);
    9295               
    9396                int oldX = getX();
     
    102105
    103106        @Override
    104         public void setAnchorRight(Float anchor) {
     107        public void setAnchorRight(Integer anchor) {
    105108                if (!isLineEnd()) {
    106109                        super.setAnchorRight(anchor);
     
    110113                invalidateCommonTrait(ItemAppearence.PreMoved);
    111114               
    112                 this._anchorRight = anchor;
    113                 this._anchorLeft = null;
     115                this._anchoring.setRightAnchor(anchor);
    114116               
    115117                int oldX = getX();
    116118                if (anchor != null) {
    117                         float deltaX = FrameGraphics.getMaxFrameSize().width - anchor
    118                                         - getBoundsWidth() - oldX;
     119                        float deltaX = DisplayController.getFramePaintArea().getWidth() - anchor - getBoundsWidth() - oldX;
    119120
    120121                        anchorConnected(AnchorEdgeType.Right, deltaX);
     
    126127
    127128        @Override
    128         public void setAnchorTop(Float anchor) {
     129        public void setAnchorTop(Integer anchor) {
    129130                if (!isLineEnd()) {
    130131                        super.setAnchorTop(anchor);
     
    134135                invalidateCommonTrait(ItemAppearence.PreMoved);
    135136               
    136                 this._anchorTop = anchor;
    137                 this._anchorBottom = null;
     137                this._anchoring.setTopAnchor(anchor);
    138138               
    139139                int oldY = getY();
     
    148148
    149149        @Override
    150         public void setAnchorBottom(Float anchor) {
     150        public void setAnchorBottom(Integer anchor) {
    151151                if (!isLineEnd()) {
    152152                        super.setAnchorBottom(anchor);
     
    156156                invalidateCommonTrait(ItemAppearence.PreMoved);
    157157               
    158                 this._anchorBottom = anchor;
    159                 this._anchorTop = null;
     158                this._anchoring.setBottomAnchor(anchor);
    160159               
    161160                int oldY = getY();
    162161                if (anchor != null) {
    163                         float deltaY = FrameGraphics.getMaxFrameSize().height - anchor
    164                                         - getBoundsHeight() - oldY;
     162                        float deltaY = DisplayController.getFramePaintArea().getHeight() - anchor - getBoundsHeight() - oldY;
    165163                        anchorConnected(AnchorEdgeType.Bottom, deltaY);
    166164                }
     
    173171
    174172        @Override
    175         public void paint(Graphics2D g) {
     173        public void paint() {
     174                GraphicsManager g = EcosystemManager.getGraphicsManager();
    176175                if (isHighlighted() /* && !FreeItems.getInstance().contains(this) */) {
    177                         Color highlightColor = getHighlightColor();
    178                         g.setColor(highlightColor);
    179                         g.setStroke(DOT_STROKE);
     176                        Colour highlightColor = getHighlightColor();
     177                        Fill fill = new Fill(highlightColor);
    180178                        // g.setStroke()
    181179                        // Draw the highlighting rectangle surrounding the dot
    182180                        // this is drawn even if its part of a rectangle
    183181
    184                         if (isVectorItem())
    185                                 updatePolygon();
    186 
    187                         Rectangle rect = getPolygon().getBounds();
    188                         if (_mode == HighlightMode.Enclosed ||
    189                         // Make sure single dots are highlighted filled
    190                                         this.getConnected().size() <= 1)
    191                                 g.fillRect(rect.x, rect.y, rect.width, rect.height);
    192                         else if (_mode == HighlightMode.Connected){
    193                                 g.setStroke(HIGHLIGHT_STROKE);
    194                                 g.drawRect(rect.x, rect.y, rect.width, rect.height);
    195                         }else if (_mode == HighlightMode.Normal) {
    196                                 g.fillOval(rect.x, rect.y, rect.width, rect.height);
     182                        if (isVectorItem()) invalidateBounds();
     183
     184                        AxisAlignedBoxBounds bounds = getBoundingBox();
     185                        if (_highlightMode == HighlightMode.Enclosed || this.getConnected().size() <= 1) { // Make sure single dots are highlighted filled
     186                                g.drawRectangle(bounds.getTopLeft(), bounds.getSize(), 0.0f, fill, highlightColor, DOT_STROKE, null);
     187                        } else if (_highlightMode == HighlightMode.Connected) {
     188                                g.drawRectangle(bounds.getTopLeft(), bounds.getSize(), 0.0f, null, highlightColor, HIGHLIGHT_STROKE, null);
     189                        } else if (_highlightMode == HighlightMode.Normal) {
     190                                g.drawOval(bounds.getCentre(), bounds.getSize(), 0.0f, fill, highlightColor, DOT_STROKE);
    197191                        }
    198192                        // System.out.println(_mode.toString());
     
    200194
    201195                // dots on lines are hidden
    202                 if (getLines().size() > 0)
    203                         return;
    204 
    205                 g.setColor(getPaintColor());
     196                if (getLines().size() > 0) return;
    206197
    207198                int thick = (int) getThickness();
    208                 if (thick < MINIMUM_DOT_SIZE)
    209                         thick = MINIMUM_DOT_SIZE;
    210 
    211                 int width = thick / 2;
    212 
     199                if (thick < MINIMUM_DOT_SIZE) thick = MINIMUM_DOT_SIZE;
     200               
     201                Fill fill = _filled ? new Fill(getPaintColor()) : null;
     202
     203                // TODO: On testing, this code doesn't seem to work (can't change to any type except square). cts16
    213204                switch (_type) {
    214                 case circle:
    215                         if (_filled)
    216                                 g.fillOval(getX() - width, getY() - width, thick, thick);
    217                         else {
    218                                 g.drawOval(getX() - width, getY() - width, thick, thick);
    219                         }
    220                         break;
    221                 case diamond:
    222                         int[] x = new int[4];
    223                         int[] y = new int[4];
    224 
    225                         x[0] = x[2] = getX();
    226                         x[1] = getX() - width;
    227                         x[3] = getX() + width;
    228 
    229                         y[1] = y[3] = getY();
    230                         y[0] = getY() - width;
    231                         y[2] = getY() + width;
    232 
    233                         if (_filled)
    234                                 g.fillPolygon(x, y, 4);
    235                         else {
    236                                 g.drawPolygon(x, y, 4);
    237                         }
    238                         break;
    239                 case triangle:
    240                         x = new int[3];
    241                         y = new int[3];
    242 
    243                         x[0] = getX();
    244                         x[1] = getX() - width;
    245                         x[2] = getX() + width;
    246 
    247                         y[0] = getY() - width;
    248                         y[1] = y[2] = getY() + width;
    249 
    250                         if (_filled)
    251                                 g.fillPolygon(x, y, 3);
    252                         else {
    253                                 g.drawPolygon(x, y, 3);
    254                         }
    255                         break;
    256                 case roundSquare:
    257                         int arc = thick / 2;
    258                         if (_filled)
    259                                 g.fillRoundRect(getX() - width, getY() - width, thick, thick,
    260                                                 arc, arc);
    261                         else {
    262                                 g.drawRoundRect(getX() - width, getY() - width, thick, thick,
    263                                                 arc, arc);
    264                         }
    265                         break;
    266                 default:
    267                         if (_filled)
    268                                 g.fillRect(getX() - width, getY() - width, thick, thick);
    269                         else {
    270                                 g.drawRect(getX() - width, getY() - width, thick, thick);
    271                         }
    272 
     205                        case circle:
     206                                g.drawOval(
     207                                                new Point(getX(), getY()),
     208                                                new Dimension(thick, thick),
     209                                                0.0,
     210                                                fill,
     211                                                getPaintColor(),
     212                                                null
     213                                );
     214                                break;
     215                        case diamond:
     216                                PolygonBounds diamond = PolygonBounds.getDiamond(thick, thick).translate(getX(), getY()).close();
     217                                g.drawPolygon(diamond, null, null, 0.0, fill, getPaintColor(), null);
     218                                break;
     219                        case triangle:
     220                                PolygonBounds triangle = PolygonBounds.getTriangle(thick, thick).translate(getX(), getY()).close();
     221                                g.drawPolygon(triangle, null, null, 0.0, fill, getPaintColor(), null);
     222                                break;
     223                        case roundSquare:
     224                                int arc = thick / 4;
     225                                g.drawRectangle(
     226                                        new Point(getX(), getY()),
     227                                        new Dimension(thick, thick),
     228                                        0.0,
     229                                        fill,
     230                                        getPaintColor(),
     231                                        null,
     232                                        new Dimension(arc, arc)
     233                                );
     234                                break;
     235                        default:
     236                                g.drawRectangle(
     237                                                new Point(getX(), getY()),
     238                                                new Dimension(thick, thick),
     239                                                0.0,
     240                                                fill,
     241                                                getPaintColor(),
     242                                                null,
     243                                                null
     244                                );
    273245                }
    274246
     
    276248
    277249        /**
    278          * Updates the points of the polygon surrounding this Dot
     250         * Updates the bounds surrounding this Dot.
     251         * TODO: Standardise Dot minimum size. cts16
    279252         */
    280         public void updatePolygon() {
     253        public Bounds updateBounds()
     254        {
    281255                int thick = Math.round(getThickness());
     256               
    282257                // Sets a minimum size for the dot
    283258                thick = Math.max(thick, getGravity() * 2);
     259               
     260                // Include the gravity in the thickness
     261                thick += 2 * getGravity();
     262               
    284263
    285264                int x = getX() - thick / 2;
    286265                int y = getY() - thick / 2;
    287 
    288                 _poly = new Polygon();
    289                 _poly.addPoint(x - getGravity(), y - getGravity());
    290                 _poly.addPoint(x + thick + getGravity(), y - getGravity());
    291                 _poly.addPoint(x + thick + getGravity(), y + thick + getGravity());
    292                 _poly.addPoint(x - getGravity(), y + thick + getGravity());
     266               
     267                return new AxisAlignedBoxBounds(x, y, thick, thick);
    293268        }
    294269
     
    303278
    304279        @Override
    305         public int setHighlightColor() {
    306                 super.setHighlightColor();
    307 
    308                 return Item.DEFAULT_CURSOR;
     280        public void setHighlightColorToDefault() {
     281                super.setHighlightColorToDefault();
     282
     283                //return Item.DEFAULT_CURSOR;
    309284        }
    310285
    311286        @Override
    312287        public void setAnnotation(boolean val) {
    313                 DisplayIO.setCursorPosition(this.getPosition());
    314                 FrameKeyboardActions.replaceDot(this, '@');
     288                DisplayController.setCursorPosition(this.getPosition());
     289                Item.replaceDot(this, '@');
    315290        }
    316291
     
    406381                        if (parent != null && parent != current) {
    407382                                this.setParent(parent);
    408                                 if (DisplayIO.getCurrentSide() == 0)
    409                                         this.setX(this.getX() - DisplayIO.getMiddle());
     383                                if (DisplayController.getCurrentSide() == DisplayController.TwinFramesSide.LEFT)
     384                                        this.setX(this.getX() - DisplayController.getTwinFramesSeparatorX());
    410385                                else
    411                                         this.setX(this.getX() + DisplayIO.getMiddle());
     386                                        this.setX(this.getX() + DisplayController.getTwinFramesSeparatorX());
    412387                        }
    413388                        break;
     
    420395                        if (line.getID() < 0 && !current.getItems().contains(line)) {
    421396                                line.setID(current.getNextItemID());
    422                                 line.setHighlightColor();
     397                                line.setHighlightColorToDefault();
    423398                                // Mike: Why was this line here?
    424399                                // anchor(line);
     
    436411
    437412        @Override
    438         public void lineColorChanged(Color c) {
     413        public void lineColorChanged(Colour c) {
    439414                if (getColor() != c) {
    440415                        setColor(c);
     
    450425                return super.dontSave();
    451426        }
     427
     428        @Override
     429        public float getSize()
     430        {
     431                return getThickness();
     432        }
    452433}
  • trunk/src/org/expeditee/items/FrameBitmap.java

    r919 r1102  
    1919package org.expeditee.items;
    2020
    21 import java.awt.Color;
    22 import java.awt.Image;
    23 import java.awt.image.BufferedImage;
    24 import java.awt.image.ImageObserver;
    2521import java.util.List;
    2622
     23import org.expeditee.core.Colour;
     24import org.expeditee.core.Image;
    2725import org.expeditee.gui.Frame;
    2826import org.expeditee.gui.FrameIO;
     
    3129
    3230public class FrameBitmap extends FramePicture {
    33         public FrameBitmap(Text source, ImageObserver observer, Image image){
    34                 super(source, observer, image);
     31        public FrameBitmap(Text source, Image image){
     32                super(source, image);
    3533        }
    3634
     
    5957                        return false;
    6058               
    61                 BufferedImage bi = new BufferedImage(width, height,
    62                                 BufferedImage.TYPE_INT_ARGB);
     59                Image bi = Image.createImage(width, height);
    6360                // now set the bits on the image
    64                 final int transparent = (new Color(0F, 0F, 0F, 0F)).getRGB();
    65                 final int main = _source.getPaintColor().getRGB();
    66                 final Color c = _source.getPaintColor();
     61                final int transparent = (new Colour(0F, 0F, 0F, 0F)).getARGB32BitPacked();
     62                final int main = _source.getPaintColor().getARGB32BitPacked();
     63                final Colour c = _source.getPaintColor();
    6764                int currentColor = main;
    6865                int row = 0;
     
    7471                                        // Space is transparent as is 0
    7572                                        if (Character.isDigit(currentPixel)) {
    76                                                 int alpha = Math.round((currentPixel - '0') * 25.5F);
    77                                                 currentColor = new Color(c.getRed(), c.getGreen(), c
    78                                                                 .getBlue(), alpha).getRGB();
     73                                                int alpha = Math.round((currentPixel - '0') * (Colour.COMPONENT_MAX_VALUE / 10.0f));
     74                                                currentColor = new Colour(c.getRed(), c.getGreen(), c
     75                                                                .getBlue(), alpha).getARGB32BitPacked();
    7976                                        }else if (currentPixel != ' ') {
    8077                                                currentColor = main;
    8178                                        }
    8279                                }
    83                                 bi.setRGB(i, row, currentColor);
     80                                bi.setPixel(i, row, Colour.fromARGB32BitPacked(currentColor));
    8481                        }
    8582                        row++;
     
    9289        @Override
    9390        protected Picture createPicture() {
    94                 return new FrameBitmap((Text) _source.copy(),
    95                                 _imageObserver, _image);
     91                return new FrameBitmap((Text) _source.copy(), _image);
    9692        }
    9793
  • trunk/src/org/expeditee/items/FrameImage.java

    r919 r1102  
    1919package org.expeditee.items;
    2020
    21 import java.awt.Image;
    22 import java.awt.image.ImageObserver;
    23 
     21import org.expeditee.core.Image;
    2422import org.expeditee.gui.Frame;
    2523import org.expeditee.gui.FrameGraphics;
     
    4139         *            screen.
    4240         */
    43         public FrameImage(Text source, ImageObserver observer, Image image) {
    44                 super(source, observer, image);
     41        public FrameImage(Text source, Image image) {
     42                super(source, image);
    4543        }
    4644
    4745        @Override
    4846        protected Picture createPicture() {
    49                 return new FrameImage(_source.copy(), _imageObserver, _image);
     47                return new FrameImage(_source.copy(), _image);
    5048        }
    5149
     
    5957                        return false;
    6058
    61                 frame.setBuffer(null);
    62                 FrameGraphics.UpdateBuffer(frame, false, false);
     59                frame.setBuffer(FrameGraphics.getFrameImage(frame, null, null, false, false));
    6360                _image = frame.getBuffer();
    6461
     
    6663                // been created to begin with
    6764                parseSize();
    68                 updatePolygon();
     65                invalidateBounds();
    6966                return true;
    7067        }
  • trunk/src/org/expeditee/items/FramePicture.java

    r919 r1102  
    1919package org.expeditee.items;
    2020
    21 import java.awt.Color;
    22 import java.awt.Image;
    23 import java.awt.image.ImageObserver;
    24 
     21import org.expeditee.core.Colour;
     22import org.expeditee.core.Image;
    2523import org.expeditee.gui.AttributeValuePair;
    2624import org.expeditee.gui.Frame;
    2725
    2826public abstract class FramePicture extends Picture {
    29         protected FramePicture(Text source, ImageObserver observer, Image image) {
    30                 super(source, observer, image);
     27        protected FramePicture(Text source, Image image) {
     28                super(source, image);
    3129        }
    3230
    3331        @Override
    34         public void setColor(Color c) {
     32        public void setColor(Colour c) {
    3533                super.setColor(c);
    3634                refresh();
     
    5553                        }
    5654                }
    57                 updatePolygon();
     55                invalidateBounds();
    5856        }
    5957       
  • trunk/src/org/expeditee/items/Item.java

    r977 r1102  
    1919package org.expeditee.items;
    2020
    21 import java.awt.BasicStroke;
    22 import java.awt.Color;
    23 import java.awt.Cursor;
    24 import java.awt.GradientPaint;
    25 import java.awt.Graphics2D;
    26 import java.awt.Point;
    27 import java.awt.Polygon;
    28 import java.awt.Rectangle;
    29 import java.awt.Shape;
    30 import java.awt.Stroke;
    31 import java.awt.geom.AffineTransform;
    32 import java.awt.geom.Area;
    33 import java.awt.geom.Point2D;
    34 import java.awt.geom.Rectangle2D;
    3521import java.util.ArrayList;
    3622import java.util.Collection;
     
    4632import org.expeditee.actions.Misc;
    4733import org.expeditee.actions.Simple;
     34import org.expeditee.core.Anchoring;
     35import org.expeditee.core.Colour;
     36import org.expeditee.core.Cursor;
     37import org.expeditee.core.Dimension;
     38import org.expeditee.core.Fill;
     39import org.expeditee.core.GradientFill;
     40import org.expeditee.core.Point;
     41import org.expeditee.core.Stroke;
     42import org.expeditee.core.bounds.AxisAlignedBoxBounds;
     43import org.expeditee.core.bounds.Bounds;
     44import org.expeditee.core.bounds.EllipticalBounds;
     45import org.expeditee.core.bounds.PolygonBounds;
     46import org.expeditee.gio.EcosystemManager;
     47import org.expeditee.gio.GraphicsManager;
     48import org.expeditee.gio.gesture.StandardGestureActions;
    4849import org.expeditee.gui.AttributeValuePair;
    49 import org.expeditee.gui.DisplayIO;
     50import org.expeditee.gui.DisplayController;
    5051import org.expeditee.gui.Frame;
    5152import org.expeditee.gui.FrameGraphics;
    5253import org.expeditee.gui.FrameIO;
    53 import org.expeditee.gui.FrameKeyboardActions;
    54 import org.expeditee.gui.FrameMouseActions;
    5554import org.expeditee.gui.FrameUtils;
    5655import org.expeditee.gui.FreeItems;
     
    7574public abstract class Item implements Comparable<Item>, Runnable {
    7675
    77         public static final Float DEFAULT_THICKNESS = 2f;
    78 
    79         public static final Float MINIMUM_THICKNESS = 0f;
    80 
    81         public static final Float MINIMUM_PAINT_THICKNESS = 1f;
    82 
    83         protected final int JOIN = BasicStroke.JOIN_ROUND;
    84 
    85         protected final int CAP = BasicStroke.CAP_BUTT;
    86 
    87         protected final Stroke DOT_STROKE = new BasicStroke(DEFAULT_THICKNESS,
    88                         CAP, JOIN, 4.0F);
    89 
    90         protected final Stroke HIGHLIGHT_STROKE = new BasicStroke(
    91                         MINIMUM_THICKNESS, CAP, JOIN, 4.0F);
    92 
    93         // contains all dots (including this one) that form an enclosure
    94         // if this dot is part of an enclosing shape
    95         private Collection<Item> _enclosure = null;
    96 
    97         public static final int LEFT_MARGIN = 13;
    98 
    99         // indicates which end the arrowhead should be drawn at
    100         protected Polygon _poly = null;
    101 
    102         protected boolean _connectedToAnnotation = false;
    103 
    104         protected boolean _save = true;
    105 
    106         private int _gradientAngle = 0;
    107 
    108         public static final int NEAR_DISTANCE = 15;
    109 
    110         /**
    111          * The default Color to draw highlighting in
    112          */
    113         public static final int DEFAULT_HIGHLIGHT_THICKNESS = 2;
    114 
    115         public static final Color DEFAULT_HIGHLIGHT = Color.RED;
    116 
    117         public static final Color DEPRESSED_HIGHLIGHT = Color.GREEN;
    118 
    119         public static final Color ALTERNATE_HIGHLIGHT = Color.BLUE;
    120 
    121         public static final Color LINK_COLOR = Color.BLACK;
    122 
    123         public static final Color ACTION_COLOR = Color.BLACK;
    124 
    125         public static final Color LINK_ACTION_COLOR = Color.RED;
    126 
    127         public static final Color DEFAULT_FOREGROUND = Color.BLACK;
    128 
    129         public static final Color DEFAULT_BACKGROUND = Color.white;
    130 
    131         public static final Color TRANSPARENT = new Color(0, 0, 0, 0);
    132 
    133         /**
    134          * The number of pixels highlighting should extend around Items.
    135          */
    136         public static final int XGRAVITY = 3;
    137 
    138         public static final int MARGIN_RIGHT = 2;
    139 
    140         public static final int MARGIN_LEFT = 15;
    141 
    142         protected static final double DEFAULT_ARROWHEAD_RATIO     = 0.3; // used to be 0.5
    143 
    144         public static final double DEFAULT_ARROWHEAD_NIB_PERC  = 0.75;
    145        
    146         public static final Color GREEN = Color.GREEN.darker();
    147 
    148         public static final int UNCHANGED_CURSOR = -100;
    149 
    150         public static final int DEFAULT_CURSOR = Cursor.DEFAULT_CURSOR;
    151 
    152         public static final int HIDDEN_CURSOR = Cursor.CUSTOM_CURSOR;
    153 
    154         public static final int TEXT_CURSOR = Cursor.TEXT_CURSOR;
    155 
    156         public static final int CROP_CURSOR = Cursor.CROSSHAIR_CURSOR;
    157 
    158         // The default value for integer attributes
    159         public static final int DEFAULT_INTEGER = -1;
    160 
    161         protected DotType _type = DotType.square;
    162 
    163         protected boolean _filled = true;
    164        
    165         private Tooltip _tooltip = new Tooltip();
    166 
     76        public enum HighlightMode {
     77                None, // The item has no highlighting
     78                Enclosed, // The item is part of the current enclosure
     79                Connected, // The item is connected to the current item
     80                Disconnect, // The item is a free item
     81                Normal // The item is the current item
     82        }
     83
     84        /** Which edge of the window things are anchored to. */
    16785        public enum AnchorEdgeType {
    16886                None, Left, Right, Top, Bottom
    16987        }
    170 
    171         public static void DuplicateItem(Item source, Item dest) {
    172                 dest.setX(source.getX());
    173                 dest.setY(source.getY());
    174 
    175                 dest.setActions(source.getAction());
    176                 dest.setActionCursorEnter(source.getActionCursorEnter());
    177                 dest.setActionCursorLeave(source.getActionCursorLeave());
    178                 dest.setActionEnterFrame(source.getActionEnterFrame());
    179                 dest.setActionLeaveFrame(source.getActionLeaveFrame());
    180                 dest.setActionMark(source.getActionMark());
    181 
    182                 dest.setBackgroundColor(source.getBackgroundColor());
    183                 dest.setBottomShadowColor(source.getBottomShadowColor());
    184                 dest.setColor(source.getColor());
    185                 dest.setBorderColor(source.getBorderColor());
    186 
    187                 dest.setTooltips(source.getTooltip());
    188                 dest.setData(source.getData());
    189                 dest.setTag(source.getTag());
    190                 dest.setFillColor(source.getFillColor());
    191                 dest.setGradientColor(source.getGradientColor());
    192                 dest.setGradientAngle(source.getGradientAngle());
    193                 dest.setFillPattern(source.getFillPattern());
    194 
    195                 dest.setHighlight(source.getHighlight());
    196                 dest.setLink(source.getLink());
    197                 dest.setLinkFrameset(source.getLinkFrameset());
    198                 dest.setLinkMark(source.getLinkMark());
    199                 dest.setLinkTemplate(source.getLinkTemplate());
    200 
    201                 // dest.setMaxWidth(source.getMaxWidth());
    202 
    203                 dest.setOffset(source.getOffset());
    204                 // dest.setOwner(source.getOwner());
    205                 dest.setThickness(source.getThickness());
    206                 dest.setSize(source.getSize());
    207                 dest.setTopShadowColor(source.getTopShadowColor());
    208                 dest.setLinePattern(source.getLinePattern());
    209 
    210                 dest.setFloating(source.isFloating());
    211                 dest.setArrow(source.getArrowheadLength(), source.getArrowheadRatio(), source.getArrowheadNibPerc());
    212 
    213                 dest.setDotType(source.getDotType());
    214                 dest.setFilled(source.getFilled());
     88       
     89        public static final float SIZE_NOT_APPLICABLE = Float.NaN;
     90       
     91        public static final Float DEFAULT_THICKNESS = 2f;
     92
     93        public static final Float MINIMUM_THICKNESS = 0f;
     94
     95        public static final Float MINIMUM_PAINT_THICKNESS = 1f;
     96
     97        protected static final Stroke.JOIN DEFAULT_JOIN = Stroke.JOIN.ROUND;
     98
     99        protected static final Stroke.CAP DEFAULT_CAP = Stroke.CAP.BUTT;
     100
     101        protected static final Stroke DOT_STROKE = new Stroke(DEFAULT_THICKNESS, DEFAULT_CAP, DEFAULT_JOIN);
     102
     103        protected static final Stroke HIGHLIGHT_STROKE = new Stroke(MINIMUM_THICKNESS, DEFAULT_CAP, DEFAULT_JOIN);
     104       
     105        public static final int LEFT_MARGIN = 13;
     106
     107        public static final int NEAR_DISTANCE = 15;
     108
     109        public static final int DEFAULT_HIGHLIGHT_THICKNESS = 2;
     110
     111        /** The default colour to draw highlighting in */
     112        public static final Colour DEFAULT_HIGHLIGHT = Colour.RED;
     113
     114        public static final Colour DEPRESSED_HIGHLIGHT = Colour.GREEN;
     115
     116        public static final Colour ALTERNATE_HIGHLIGHT = Colour.BLUE;
     117
     118        public static final Colour LINK_COLOR = Colour.BLACK;
     119
     120        public static final Colour ACTION_COLOR = Colour.BLACK;
     121
     122        public static final Colour LINK_ACTION_COLOR = Colour.RED;
     123
     124        public static final Colour DEFAULT_FOREGROUND = Colour.BLACK;
     125
     126        public static final Colour DEFAULT_BACKGROUND = Colour.WHITE;
     127
     128        public static final Colour TRANSPARENT = new Colour(0, 0, 0, 0);
     129
     130        /** The number of pixels highlighting should extend around Items. */
     131        public static final int XGRAVITY = 3;
     132
     133        public static final int MARGIN_RIGHT = 2;
     134
     135        public static final int MARGIN_LEFT = 15;
     136
     137        protected static final double DEFAULT_ARROWHEAD_RATIO = 0.3; // used to be 0.5
     138
     139        public static final double DEFAULT_ARROWHEAD_NIB_PERC  = 0.75;
     140       
     141        public static final Colour GREEN = Colour.GREEN.darker();
     142
     143        //public static final int UNCHANGED_CURSOR = -100;
     144
     145        public static final Cursor.CursorType DEFAULT_CURSOR = Cursor.CursorType.DEFAULT;
     146
     147        public static final Cursor.CursorType HIDDEN_CURSOR = Cursor.CursorType.CUSTOM;
     148
     149        public static final Cursor.CursorType TEXT_CURSOR = Cursor.CursorType.TEXT;
     150
     151        public static final Cursor.CursorType CROP_CURSOR = Cursor.CursorType.CROSSHAIR;
     152
     153        /** The default value for integer attributes */
     154        public static final int DEFAULT_INTEGER = -1;
     155
     156        private static final int BRIGHTNESS = 185;
     157
     158        /** Contains all dots (including this one) that form an enclosure if this dot is part of an enclosing shape. */
     159        private Collection<Item> _enclosure = null;
     160
     161        /** The area which this item covers (including its gravity). */
     162        private Bounds _bounds = null;
     163       
     164        /** The area this item covered before it was invalidated. */
     165        private Bounds _oldBounds = null;
     166
     167        protected boolean _connectedToAnnotation = false;
     168
     169        protected boolean _save = true;
     170
     171        /** The angle of change for gradient colour fills (in radians). */
     172        private double _gradientAngle = 0.0;
     173       
     174        private Tooltip _tooltip = new Tooltip();
     175
     176        protected Anchoring _anchoring = new Anchoring();
     177
     178        /** The highlight mode for this item. */
     179        protected HighlightMode _highlightMode = HighlightMode.None;
     180
     181        private Point _offset = new Point(0, 0);
     182
     183        protected float _x;
     184        protected float _y;
     185
     186        private int _id;
     187
     188        private Item _editTarget = this;
     189
     190        private String _creationDate = null;
     191
     192        /** Whether or not this item should display a mark indicating it has a link. */
     193        private boolean _linkMark = true;
     194
     195        /** Whether or not this item should display a mark indicating it has an action. */
     196        private boolean _actionMark = true;
     197
     198        /** TODO: Appears unused? cts16 */
     199        private boolean _highlight = true;
     200
     201        // private int _maxWidth = -1;
     202
     203        private String _owner = null;
     204
     205        private String _link = null;
     206       
     207        private boolean _linkHistory = true;
     208
     209        private StringBuffer _tag = new StringBuffer();
     210
     211        private List<String> _actionCursorEnter = null;
     212
     213        private List<String> _actionCursorLeave = null;
     214
     215        private List<String> _actionEnterFrame = null;
     216
     217        private List<String> _actionLeaveFrame = null;
     218
     219        private PermissionPair _permissionPair = null;
     220       
     221        private UserAppliedPermission _overlayPermission = null;
     222
     223        /** The primary fill colour of this item. A fill colour of null represents transparent. */
     224        private Colour _fillColour = null;
     225
     226        /** The secondary fill colour if this item has a gradient fill. Null represents no gradient. */
     227        private Colour _gradientColour = null;
     228
     229        /** The primary draw colour of this item. Null represents the default colour. */
     230        private Colour _foregroundColour = null;
     231
     232        /** The colour to draw highlights on this item. */
     233        protected Colour _highlightColour = DEFAULT_HIGHLIGHT;
     234
     235        /** The background colour for this item. */
     236        private Colour _backgroundColour = null;
     237
     238        private Colour _colorBorder = null;
     239
     240        private Colour _colorTopShadow = null;
     241
     242        private Colour _colorBottomShadow = null;
     243
     244        /** The shape representing the circle drawn next to link/action items. */
     245        private static EllipticalBounds _linkCircle = null;
     246
     247        /** The shape representing the cross drawn next to invalid links. */
     248        private static PolygonBounds _linkCircleCross = null;
     249
     250        private Frame _parent = null;
     251        private Frame _oldParent = null;
     252
     253        protected int _highlightThickness = 2;
     254
     255        protected int _vectorHighlightThickness = 1;
     256
     257        // arrowhead parameters
     258        private float  _arrowheadLength  = 0;
     259        private double _arrowheadRatio   = DEFAULT_ARROWHEAD_RATIO;
     260        private double _arrowheadNibPerc = DEFAULT_ARROWHEAD_NIB_PERC;
     261       
     262        private PolygonBounds _arrowhead = null;
     263
     264        // the list of lines that this point is part of.
     265        private List<Line> _lines = new ArrayList<Line>();
     266
     267        private int[] _linePattern = null;
     268
     269        private boolean _floating = false;
     270
     271        // list of points constrained with this point
     272        private List<Constraint> _constraints = new ArrayList<Constraint>();
     273
     274        private List<String> _actions = null;
     275
     276        private List<String> _data = null;
     277
     278        private String _formula = null;
     279
     280        private String _link_frameset = null;
     281
     282        private String _link_template = null;
     283
     284        private String _fillPattern = null;
     285
     286        private boolean _visible = true;
     287
     288        private float _thickness = -1.0F;
     289
     290        protected Collection<XRayable> _enclosures = new HashSet<XRayable>();
     291
     292        private boolean _deleted = false;
     293
     294        private Overlay _overlay = null;
     295
     296        protected AttributeValuePair _attributeValuePair = null;
     297
     298        private Float _autoStamp = null;
     299       
     300        private Item _magnetizedItemLeft = null;
     301       
     302        private Item _magnetizedItemRight = null;
     303       
     304        private Item _magnetizedItemTop = null;
     305       
     306        private Item _magnetizedItemBottom = null;
     307
     308        protected DotType _type = DotType.square;
     309
     310        protected boolean _filled = true;
     311
     312        /** Just calls source.duplicateOnto(dest). */
     313        public static void DuplicateItem(Item source, Item dest)
     314        {
     315                if (source == null) return;
     316               
     317                source.duplicateOnto(dest);
     318        }
     319       
     320        /** Sets the properties of dest so that they match this item's properties. */
     321        public void duplicateOnto(Item dest)
     322        {
     323                if (dest == null) return;
     324               
     325                dest.setX(this.getX());
     326                dest.setY(this.getY());
     327
     328                dest.setActions(this.getAction());
     329                dest.setActionCursorEnter(this.getActionCursorEnter());
     330                dest.setActionCursorLeave(this.getActionCursorLeave());
     331                dest.setActionEnterFrame(this.getActionEnterFrame());
     332                dest.setActionLeaveFrame(this.getActionLeaveFrame());
     333                dest.setActionMark(this.getActionMark());
     334
     335                dest.setBackgroundColor(this.getBackgroundColor());
     336                dest.setBottomShadowColor(this.getBottomShadowColor());
     337                dest.setColor(this.getColor());
     338                dest.setBorderColor(this.getBorderColor());
     339
     340                dest.setTooltips(this.getTooltip());
     341                dest.setData(this.getData());
     342                dest.setTag(this.getTag());
     343                dest.setFillColor(this.getFillColor());
     344                dest.setGradientColor(this.getGradientColor());
     345                dest.setGradientAngle(this.getGradientAngle());
     346                dest.setFillPattern(this.getFillPattern());
     347
     348                dest.setHighlight(this.getHighlight());
     349                dest.setLink(this.getLink());
     350                dest.setLinkFrameset(this.getLinkFrameset());
     351                dest.setLinkMark(this.getLinkMark());
     352                dest.setLinkTemplate(this.getLinkTemplate());
     353
     354                // dest.setMaxWidth(this.getMaxWidth());
     355
     356                dest.setOffset(this.getOffset());
     357                // dest.setOwner(this.getOwner());
     358                dest.setThickness(this.getThickness());
     359                dest.setSize(this.getSize());
     360                dest.setTopShadowColor(this.getTopShadowColor());
     361                dest.setLinePattern(this.getLinePattern());
     362
     363                dest.setFloating(this.isFloating());
     364                dest.setArrow(this.getArrowheadLength(), this.getArrowheadRatio(), this.getArrowheadNibPerc());
     365                dest.setDotType(this.getDotType());
     366                dest.setFilled(this.getFilled());
    215367                /*
    216368                 * Calling the methods will move the item... This messes things up when
    217369                 * the user uses backspace to delete a text line end
    218370                 */
    219                 // dest._anchorLeft = source._anchorLeft;
    220                 // dest._anchorRight = source._anchorRight;
    221                 // dest._anchorTop = source._anchorTop;
    222                 // dest._anchorBottom = source._anchorBottom;
    223                 dest.setFormula(source.getFormula());
    224                 dest._overlay = source._overlay;
    225                 dest._mode = source._mode;// SelectedMode.None;
    226                 // dest._highlightColor = source._highlightColor;
    227                 // dest.setHighlight(source.getHighlight());
    228 
    229                 dest._visible = source._visible;
    230 
    231                 Frame parent = DisplayIO.getCurrentFrame();
    232                 if (parent == null)
    233                         parent = source.getParentOrCurrentFrame();
     371                // dest._anchorLeft = this._anchorLeft;
     372                // dest._anchorRight = this._anchorRight;
     373                // dest._anchorTop = this._anchorTop;
     374                // dest._anchorBottom = this._anchorBottom;
     375                dest.setFormula(this.getFormula());
     376                dest._overlay = this._overlay;
     377                dest._highlightMode = this._highlightMode;// SelectedMode.None;
     378                // dest._highlightColor = this._highlightColor;
     379                // dest.setHighlight(this.getHighlight());
     380
     381                dest._visible = this._visible;
     382
     383                Frame parent = DisplayController.getCurrentFrame();
     384                if (parent == null) parent = this.getParentOrCurrentFrame();
    234385                dest.setParent(parent);
    235386
     
    246397                }
    247398        }
    248 
    249         public void setGradientAngle(int gradientAngle) {
     399       
     400        public void setDotType(DotType type) {
     401                invalidateAll();
     402                _type = type;
     403                invalidateAll();
     404        }
     405
     406        public DotType getDotType() {
     407                return _type;
     408        }
     409
     410       
     411        public void setFilled(boolean filled)
     412        {
     413                invalidateAll();
     414                _filled = filled;
     415                invalidateAll();
     416        }
     417
     418        public boolean getFilled() {
     419                return _filled;
     420        }
     421
     422        /**
     423         * Sets the angle of colour change for gradient colour fills.
     424         *
     425         * @param gradientAngle The new angle of colour change.
     426         */
     427        public void setGradientAngle(double gradientAngle)
     428        {
    250429                _gradientAngle = gradientAngle;
    251430
    252431                for (Line line : _lines) {
    253432                        Item other = line.getOppositeEnd(this);
    254                         if (other.getGradientAngle() != gradientAngle)
    255                                 other.setGradientAngle(gradientAngle);
     433                        if (other.getGradientAngle() != gradientAngle) other.setGradientAngle(gradientAngle);
    256434                }
    257435
     
    260438        }
    261439
    262         public int getGradientAngle() {
     440        /**
     441         * Gets the angle of colour change for gradient fills.
     442         *
     443         * @return The angle of colour change.
     444         */
     445        public double getGradientAngle() {
    263446                return _gradientAngle;
    264447        }
    265448
    266         public int getGravity() {
    267                 if (isVectorItem()) {
    268                         return 2;
    269                 }
     449        /**
     450         * Gets the gravity for this item. Gravity is the distance from the item at which mouse interaction
     451         * applies to the item (like a small buffer zone so you don't need to click exactly on the item).
     452         *
     453         * @return The gravity distance for this item.
     454         */
     455        public int getGravity()
     456        {
     457                if (isVectorItem()) return 2;
     458               
    270459                return UserSettings.Gravity.get();
    271460        }
    272461
    273         public static boolean showLineHighlight() {
     462        /**
     463         * Whether or not line highlights should be shown.
     464         * TODO: Not really an item method is it? Goes straight to user settings. Refactor. cts16
     465         *
     466         * @return <code>true</code> if line highlighting should be shown, <code>false</code> otherwise.
     467         */
     468        public static boolean shouldShowLineHighlight()
     469        {
    274470                return UserSettings.LineHighlight.get();
    275471        }
    276472
    277         public enum HighlightMode {
    278                 None, Enclosed, Connected, Disconnect, Normal
    279         }
    280 
    281         public void setHighlightMode(HighlightMode mode) {
    282                 setHighlightMode(mode, DEFAULT_HIGHLIGHT);
    283         }
    284 
    285         protected Float _anchorLeft = null;
    286         protected Float _anchorRight = null;
    287 
    288         protected Float _anchorTop = null;
    289         protected Float _anchorBottom = null;
    290 
    291         protected HighlightMode _mode = HighlightMode.None;
    292 
    293         private Point _offset = new Point(0, 0);
    294 
    295         protected float _x;
    296         protected float _y;
    297 
    298         private int _id;
    299 
    300         private Item _editTarget = this;
    301 
    302         private String _creationDate = null;
    303 
    304         private boolean _linkMark = true;
    305 
    306         private boolean _actionMark = true;
    307 
    308         private boolean _highlight = true;
    309 
    310         // private int _maxWidth = -1;
    311 
    312         private String _owner = null;
    313 
    314         private String _link = null;
    315        
    316         private boolean _linkHistory = true;
    317 
    318         private StringBuffer _tag = new StringBuffer();
    319 
    320         private List<String> _actionCursorEnter = null;
    321 
    322         private List<String> _actionCursorLeave = null;
    323 
    324         private List<String> _actionEnterFrame = null;
    325 
    326         private List<String> _actionLeaveFrame = null;
    327 
    328         private PermissionPair _permissionPair = null;
    329        
    330         private UserAppliedPermission _overlayPermission = null;
    331        
    332         public void setOverlayPermission(UserAppliedPermission overlayPermission) {
     473        /**
     474         * Sets the highlight mode for this item.
     475         *
     476         * @param mode The new highlight mode.
     477         */
     478        public void setHighlightMode(HighlightMode mode)
     479        {
     480                if (hasPermission(UserAppliedPermission.followLinks) || getEditTarget().hasPermission(UserAppliedPermission.followLinks)) {
     481                        if (_highlightMode != mode) {
     482                                _highlightMode = mode;
     483                                this.invalidateCommonTrait(ItemAppearence.HighlightModeChanged);
     484                        }
     485                }
     486        }
     487       
     488        public void setOverlayPermission(UserAppliedPermission overlayPermission)
     489        {
    333490                _overlayPermission = overlayPermission;
    334491        }
    335492
    336         public void setPermission(PermissionPair permissionPair) {
     493        public void setPermission(PermissionPair permissionPair)
     494        {
    337495                _permissionPair = permissionPair;
    338496        }
     
    354512        }
    355513
    356         // A fill color of null represents transparent
    357         private Color _colorFill = null;
    358 
    359         // A gradient color of null represents NO gradient
    360         private Color _colorGradient = null;
    361 
    362         // A fore color of null represents the default color
    363         private Color _color = null;
    364 
    365         protected Color _highlightColor = DEFAULT_HIGHLIGHT;
    366 
    367         private Color _colorBackground = null;
    368 
    369         private Color _colorBorder = null;
    370 
    371         private Color _colorTopShadow = null;
    372 
    373         private Color _colorBottomShadow = null;
    374 
    375         // the link\action circle
    376         private Polygon _circle = null;
    377 
    378         // the invalid link cross
    379         private Polygon _circleCross = null;
    380 
    381         private Frame _parent = null;
    382         private Frame _oldParent = null;
    383 
    384         protected int _highlightThickness = 2;
    385 
    386         protected int _vectorHighlightThickness = 1;
    387 
    388         // arrowhead parameters
    389         private float  _arrowheadLength  = 0;
    390         private double _arrowheadRatio   = DEFAULT_ARROWHEAD_RATIO;
    391         private double _arrowheadNibPerc = DEFAULT_ARROWHEAD_NIB_PERC;
    392        
    393         private Polygon _arrowhead = null;
    394 
    395         // the list of lines that this point is part of.
    396         private List<Line> _lines = new ArrayList<Line>();
    397 
    398         private int[] _linePattern = null;
    399 
    400         private boolean _floating = false;
    401 
    402         // list of points constrained with this point
    403         private List<Constraint> _constraints = new ArrayList<Constraint>();
    404 
    405         private List<String> _actions = null;
    406 
    407         private List<String> _data = null;
    408 
    409         private String _formula = null;
    410 
    411         private String _link_frameset = null;
    412 
    413         private String _link_template = null;
    414 
    415         private String _fillPattern = null;
    416 
    417         private boolean _visible = true;
    418 
    419         private float _thickness = -1.0F;
    420 
    421514        protected Item() {
    422515                _creationDate = Formatter.getLongDateTime();
     
    427520         *
    428521         * @param action
    429          *            The action to add to this Item
    430          */
    431         public void addAction(String action) {
    432                 if (action == null || action.equals("")) {
    433                         return;
    434                 }
     522         *            The name of the action to add to this Item.
     523         */
     524        public void addAction(String action)
     525        {
     526                if (action == null || action.equals("")) return;
    435527
    436528                if (_actions == null) {
    437529                        _actions = new LinkedList<String>();
    438530                }
     531               
    439532                _actions.add(action);
     533               
    440534                if (_actions.size() == 1) {
    441                         _poly = null;
     535                        invalidateBounds();
    442536                        invalidateCommonTrait(ItemAppearence.LinkChanged);
    443537                }
    444538        }
    445539
    446         public void addAllConnected(Collection<Item> connected) {
    447                 if (!connected.contains(this))
    448                         connected.add(this);
     540        public void addAllConnected(Collection<Item> connected)
     541        {
     542                if (!connected.contains(this)) connected.add(this);
    449543
    450544                for (Item item : getConnected()) {
    451                         if (!connected.contains(item))
     545                        if (!connected.contains(item)) {
    452546                                item.addAllConnected(connected);
     547                        }
    453548                }
    454549        }
     
    460555         *            The Constraint to set this Dot as a member of.
    461556         */
    462         public void addConstraint(Constraint c) {
     557        public void addConstraint(Constraint c)
     558        {
    463559                // do not add duplicate constraint
    464560                if (_constraints.contains(c))
     
    474570         *            The Line that this Point is an end of.
    475571         */
    476         public void addLine(Line line) {
     572        public void addLine(Line line)
     573        {
    477574                if (_lines.contains(line)) {
    478575                        return;
     
    490587         *         less than, equal to, or greater than the specified object.
    491588         */
    492         public int compareTo(Item i) {
     589        public int compareTo(Item i)
     590        {
    493591                return getY() - i.getY();
    494592        }
     
    499597         * the area and false otherwise.
    500598         *
    501          * @param x
    502          *            The x coordinate to check
    503          * @param y
    504          *            The y coordinate to check
     599         * @param p
     600         *            The coordinate to check
    505601         * @return True if the Shape around this Item contains the given x,y pair,
    506602         *         false otherwise.
    507603         */
    508         public boolean contains(int x, int y) {
    509                 return getPolygon().contains(x, y);
     604        public boolean contains(Point p)
     605        {
     606                return getBounds().contains(p);
    510607        }
    511608
     
    518615        public abstract Item copy();
    519616
    520         public void delete() {
     617        public void delete()
     618        {
    521619                _deleted = true;
    522620        }
    523621
    524622        @Override
    525         public boolean equals(Object o) {
     623        public boolean equals(Object o)
     624        {
    526625                if (o == null)
    527626                        return false;
     
    542641         *         has been assigned.
    543642         */
    544         public List<String> getAction() {
     643        public List<String> getAction()
     644        {
    545645                return _actions;
    546646        }
    547647
    548         public List<String> getData() {
     648        public List<String> getData()
     649        {
    549650                return _data;
    550651        }
    551652
    552         public List<String> getActionCursorEnter() {
     653        public List<String> getActionCursorEnter()
     654        {
    553655                return _actionCursorEnter;
    554656        }
    555657
    556         public List<String> getActionCursorLeave() {
     658        public List<String> getActionCursorLeave()
     659        {
    557660                return _actionCursorLeave;
    558661        }
    559662
    560         public List<String> getActionEnterFrame() {
     663        public List<String> getActionEnterFrame()
     664        {
    561665                return _actionEnterFrame;
    562666        }
    563667
    564         public List<String> getActionLeaveFrame() {
     668        public List<String> getActionLeaveFrame()
     669        {
    565670                return _actionLeaveFrame;
    566671        };
    567672
    568         public boolean getActionMark() {
     673        public boolean getActionMark()
     674        {
    569675                return _actionMark;
    570676        }
     
    576682         * @return
    577683         */
    578         public Collection<Item> getAllConnected() {
     684        public Collection<Item> getAllConnected()
     685        {
    579686                Collection<Item> list = new LinkedHashSet<Item>();
    580687                addAllConnected(list);
     
    582689        }
    583690
    584         public Area getArea() {
     691/*      public Area getArea() {
    585692                return new Area(getPolygon());
    586         }
    587 
    588         public String getArrow() {
     693        }*/
     694
     695        public String getArrow()
     696        {
    589697                if (!hasVisibleArrow())
    590698                        return null;
     
    597705        }
    598706
    599         public Polygon getArrowhead() {
     707        public PolygonBounds getArrowhead()
     708        {
    600709                return _arrowhead;
    601710        }
    602711
    603         public float getArrowheadLength() {
     712        public float getArrowheadLength()
     713        {
    604714                return _arrowheadLength;
    605715        }
    606716
    607         public double getArrowheadRatio() {
     717        public double getArrowheadRatio()
     718        {
    608719                return _arrowheadRatio;
    609720        }
    610721
    611         public double getArrowheadNibPerc() {
     722        public double getArrowheadNibPerc()
     723        {
    612724                return _arrowheadNibPerc;
    613725        }
    614726       
    615         public Color getBackgroundColor() {
    616                 return _colorBackground;
    617         }
    618 
    619         public Color getBorderColor() {
     727        public Colour getBackgroundColor()
     728        {
     729                return _backgroundColour;
     730        }
     731
     732        public Colour getBorderColor()
     733        {
    620734                return _colorBorder;
    621735        }
     
    628742         *         border.
    629743         */
    630         public Color getBottomShadowColor() {
     744        public Colour getBottomShadowColor()
     745        {
    631746                return _colorBottomShadow;
    632747        }
     
    638753         *         returned by getArea().
    639754         */
    640         public int getBoundsHeight() {
    641                 return getPolygon().getBounds().height;
     755        public int getBoundsHeight()
     756        {
     757                return AxisAlignedBoxBounds.getEnclosing(getBounds()).getHeight();
    642758        }
    643759
     
    648764         *         by getArea().
    649765         */
    650         public int getBoundsWidth() {
    651                 return getPolygon().getBounds().width;
    652         }
    653 
    654         // TODO draw the link with a circle rather than a polygon!!
    655         public Polygon getLinkPoly() {
    656                 if (_circle == null) {
    657                         int points = 16;
    658 
    659                         double radians = 0.0;
    660                         int xPoints[] = new int[points];
    661                         int yPoints[] = new int[xPoints.length];
    662 
    663                         for (int i = 0; i < xPoints.length; i++) {
    664                                 // circle looks best if these values are not related to gravity
    665                                 xPoints[i] = (int) (3.5 * Math.cos(radians)) + 6;// (2 *
    666                                 // GRAVITY);
    667                                 yPoints[i] = (int) (3.5 * Math.sin(radians)) + 3;// GRAVITY;
    668                                 radians += (2.0 * Math.PI) / xPoints.length;
    669                         }
    670 
    671                         _circle = new Polygon(xPoints, yPoints, xPoints.length);
    672                 }
    673 
    674                 return _circle;
    675         }
    676 
    677         protected Polygon getCircleCross() {
    678 
    679                 if (_circleCross == null) {
    680                         _circleCross = new Polygon();
    681 
    682                         Rectangle bounds = getLinkPoly().getBounds();
    683                         int x1 = (int) bounds.getMinX();
    684                         int x2 = (int) bounds.getMaxX();
    685                         int y1 = (int) bounds.getMinY();
    686                         int y2 = (int) bounds.getMaxY();
    687                         int midX = ((x2 - x1) / 2) + x1;
    688                         int midY = ((y2 - y1) / 2) + y1;
    689 
    690                         _circleCross.addPoint(x1, y1);
    691                         _circleCross.addPoint(x2, y2);
    692                         _circleCross.addPoint(midX, midY);
    693                         _circleCross.addPoint(x1, y2);
    694                         _circleCross.addPoint(x2, y1);
    695                         _circleCross.addPoint(midX, midY);
    696                 }
    697 
    698                 return _circleCross;
    699         }
    700 
    701         public Color getColor() {
    702                 return _color;
    703         }
    704 
    705         public Collection<Item> getConnected() {
     766        public int getBoundsWidth()
     767        {
     768                return AxisAlignedBoxBounds.getEnclosing(getBounds()).getWidth();
     769        }
     770
     771        // TODO: Remove magic constants. cts16
     772        public EllipticalBounds getLinkBounds()
     773        {
     774                if (_linkCircle == null) {
     775                        _linkCircle = new EllipticalBounds(new Point(6, 3), 7);
     776                }
     777
     778                return _linkCircle;
     779        }
     780
     781        protected PolygonBounds getCircleCross()
     782        {
     783
     784                if (_linkCircleCross == null) {
     785                        _linkCircleCross = new PolygonBounds();
     786
     787                        EllipticalBounds poly = getLinkBounds();
     788                        int x1 = poly.getMinX();
     789                        int x2 = poly.getMaxX();
     790                        int y1 = poly.getMinY();
     791                        int y2 = poly.getMaxY();
     792                        int midX = (x2 + x1) / 2;
     793                        int midY = (y2 + y1) / 2;
     794
     795                        _linkCircleCross.addPoint(new Point(x1, y1));
     796                        _linkCircleCross.addPoint(new Point(x2, y2));
     797                        _linkCircleCross.addPoint(new Point(midX, midY));
     798                        _linkCircleCross.addPoint(new Point(x1, y2));
     799                        _linkCircleCross.addPoint(new Point(x2, y1));
     800                        _linkCircleCross.addPoint(new Point(midX, midY));
     801                }
     802
     803                return _linkCircleCross;
     804        }
     805
     806        public Colour getColor()
     807        {
     808                return _foregroundColour;
     809        }
     810
     811        public Collection<Item> getConnected()
     812        {
    706813                List<Item> conn = new LinkedList<Item>();
    707814                conn.add(this);
     
    711818        }
    712819
    713         public String getConstraintIDs() {
     820        public String getConstraintIDs()
     821        {
    714822                if (_constraints == null || _constraints.size() == 0)
    715823                        return null;
     
    732840         * @return a List of Constraints that this Dot is a member of.
    733841         */
    734         public List<Constraint> getConstraints() {
     842        public List<Constraint> getConstraints()
     843        {
    735844                return _constraints;
    736845        }
    737846
    738         public String getTag() {
     847        public String getTag()
     848        {
    739849                if (_tag != null && _tag.length() > 0)
    740850                        return _tag.toString();
     
    742852        }
    743853
    744         public String getDateCreated() {
     854        public String getDateCreated()
     855        {
    745856                return _creationDate;
    746857        }
    747858
    748         public Color getFillColor() {
    749                 return _colorFill;
    750         }
    751 
    752         public String getFillPattern() {
     859        public Colour getFillColor()
     860        {
     861                return _fillColour;
     862        }
     863
     864        public String getFillPattern()
     865        {
    753866                return _fillPattern;
    754867        }
    755868
    756         public String getFirstAction() {
     869        public String getFirstAction()
     870        {
    757871                if (_actions == null || _actions.size() == 0)
    758872                        return null;
     
    760874        }
    761875
    762         public boolean getHighlight() {
     876        /**
     877         * Gets the value of <code>_highlight</code> for this item.
     878         * TODO: Appears unused? cts16.
     879         *
     880         * @return The value of <code>_highlight</code>.
     881         */
     882        public boolean getHighlight()
     883        {
    763884                return _highlight;
    764885        }
    765886
    766         public Color getHighlightColor() {
    767                 if (_highlightColor.equals(getPaintColor()))
    768                         return getAlternateHighlightColor();
     887        public Colour getHighlightColor()
     888        {
     889                if (_highlightColour.equals(getPaintColor())) return getAlternateHighlightColor();
     890               
    769891                return getDefaultHighlightColor();
    770892        }
     
    774896         *
    775897         * @return The ID of this Item.
    776          */
    777         public int getID() {
     898         *
     899         * TODO: What does it mean to have a negative ID# (as used in TDFC)? cts16
     900         */
     901        public int getID()
     902        {
    778903                return _id;
    779904        }
     
    784909         * @return The list of Line IDs that this point is part of.
    785910         */
    786         public String getLineIDs() {
     911        public String getLineIDs()
     912        {
    787913                String lineID = null;
    788914
     
    797923        }
    798924
    799         public int[] getLinePattern() {
     925        public int[] getLinePattern()
     926        {
    800927                return _linePattern;
    801928        }
     
    807934         *         Lines have been added.
    808935         */
    809         public List<Line> getLines() {
     936        public List<Line> getLines()
     937        {
    810938                return _lines;
    811939        }
     
    818946         *         this Item does not link to anything.
    819947         */
    820         public String getLink() {
     948        public String getLink()
     949        {
    821950                return _link;
    822951        }
    823952
    824         public String getFormula() {
     953        public String getFormula()
     954        {
    825955                return _formula;
    826956        }
    827957
    828         public boolean hasFormula() {
     958        public boolean hasFormula()
     959        {
    829960                return _formula != null;
    830961        }
    831962
    832         public boolean hasAttributeValuePair() {
     963        public boolean hasAttributeValuePair()
     964        {
    833965                return _attributeValuePair != null && _attributeValuePair.hasPair();
    834966        }
    835967
    836         public void setFormula(String formula) {
     968        public void setFormula(String formula)
     969        {
    837970                _formula = formula;
    838971        }
    839972
    840         public boolean calculate(String formula) {
     973        public boolean calculate(String formula)
     974        {
    841975                setFormula(formula);
    842976                return true;
    843977        }
    844978
    845         public String getLinkFrameset() {
     979        public String getLinkFrameset()
     980        {
    846981                return _link_frameset;
    847982        }
    848983
    849         public boolean getLinkMark() {
     984        public boolean getLinkMark()
     985        {
    850986                return _linkMark;
    851987        }
    852988
    853         public String getLinkTemplate() {
     989        public String getLinkTemplate()
     990        {
    854991                return _link_template;
    855992        }
    856993
    857         // public int getMaxWidth() {
     994        // public int getMaxWidth()
     995        // {
    858996        // return _maxWidth;
    859997        // }
    860998
    861         public Point getOffset() {
     999        public Point getOffset()
     1000        {
    8621001                return _offset;
    8631002        }
    8641003
    865         public String getOwner() {
     1004        public String getOwner()
     1005        {
    8661006                return _owner;
    8671007        }
    8681008
    869         public Color getPaintBackgroundColor() {
    870                 Color colorBackground = getBackgroundColor();
     1009        public Colour getPaintBackgroundColor()
     1010        {
     1011                Colour colorBackground = getBackgroundColor();
    8711012                if (colorBackground == null) {
    8721013                        if (getParent() != null && getParent().getBackgroundColor() != null)
     
    8841025         * @return The Color of this item (foreground)
    8851026         */
    886         public final Color getPaintColor() {
     1027        public final Colour getPaintColor()
     1028        {
    8871029                // If color is null then get the paint foregroundColor for the frame the
    8881030                // item is on which is a color adjusted to suit the background
    889                 Color color = getColor();
     1031                Colour color = getColor();
    8901032
    8911033                if (color == null) {
     
    8931035                                return getParent().getPaintForegroundColor();
    8941036
    895                         Frame current = DisplayIO.getCurrentFrame();
     1037                        Frame current = DisplayController.getCurrentFrame();
    8961038                        if (current == null) {
    8971039                                return DEFAULT_FOREGROUND;
     
    9031045        }
    9041046
    905         public final Color getPaintBorderColor() {
     1047        public final Colour getPaintBorderColor()
     1048        {
    9061049                // If color is null then get the paint foregroundColor for the frame the
    9071050                // item is on which is a color adjusted to suit the background
    908                 Color color = getBorderColor();
     1051                Colour color = getBorderColor();
    9091052
    9101053                if (color == null) {
     
    9121055                                return getParent().getPaintForegroundColor();
    9131056
    914                         Frame current = DisplayIO.getCurrentFrame();
     1057                        Frame current = DisplayController.getCurrentFrame();
    9151058                        if (current == null) {
    9161059                                return DEFAULT_FOREGROUND;
     
    9221065        }
    9231066
    924         protected Color getPaintHighlightColor() {
    925                 Color highlightColor = getDefaultHighlightColor();
     1067        protected Colour getPaintHighlightColor()
     1068        {
     1069                Colour highlightColor = getDefaultHighlightColor();
    9261070                if (hasVisibleBorder()) {
    9271071                        if (getPaintBorderColor().equals(highlightColor)) {
     
    9311075                        highlightColor = getDefaultHighlightColor();
    9321076                }
    933                 if (getParent() != null
    934                                 && getParent().getPaintBackgroundColor().equals(highlightColor))
     1077               
     1078                if (getParent() != null && getParent().getPaintBackgroundColor().equals(highlightColor)) {
    9351079                        highlightColor = getParent().getPaintForegroundColor();
     1080                }
    9361081
    9371082                if (hasVisibleBorder()) {
    938                         if (highlightColor.equals(getBorderColor())
    939                                         && getThickness() == getHighlightThickness()) {
    940                                 highlightColor = new Color(highlightColor.getRed(),
    941                                                 highlightColor.getGreen(), highlightColor.getBlue(),
    942                                                 150);
     1083                        if (highlightColor.equals(getBorderColor()) && getThickness() == getHighlightThickness()) {
     1084                                highlightColor = highlightColor.clone();
     1085                                highlightColor.setAlpha(Colour.FromComponent255(150));
    9431086                        }
    9441087                }
     
    9471090        }
    9481091
    949         static final int BRIGHTNESS = 185;
    950 
    951         protected Color getDefaultHighlightColor() {
    952                 if (isVectorItem()
    953                                 && !this.contains(FrameMouseActions.getX(), FrameMouseActions
    954                                                 .getY())) {
    955                         return new Color(255, BRIGHTNESS, BRIGHTNESS);
    956                 }
    957                 return _highlightColor;
    958         }
    959 
    960         protected Color getAlternateHighlightColor() {
    961                 if (isVectorItem()
    962                                 && !this.contains(FrameMouseActions.getX(), FrameMouseActions
    963                                                 .getY())) {
    964                         return new Color(BRIGHTNESS, BRIGHTNESS, 255);
     1092        protected Colour getDefaultHighlightColor()
     1093        {
     1094                if (isVectorItem() && !this.contains(EcosystemManager.getInputManager().getCursorPosition())) {
     1095                        return Colour.FromRGB255(255, BRIGHTNESS, BRIGHTNESS);
     1096                }
     1097                return _highlightColour;
     1098        }
     1099
     1100        protected Colour getAlternateHighlightColor()
     1101        {
     1102                if (isVectorItem() && !this.contains(EcosystemManager.getInputManager().getCursorPosition())) {
     1103                        return Colour.FromRGB255(BRIGHTNESS, BRIGHTNESS, 255);
    9651104                }
    9661105                return ALTERNATE_HIGHLIGHT;
    9671106        }
    9681107
    969         protected int getHighlightThickness() {
    970                 if (isVectorItem())
    971                         return _vectorHighlightThickness;
     1108        protected int getHighlightThickness()
     1109        {
     1110                if (isVectorItem()) return _vectorHighlightThickness;
     1111               
    9721112                return _highlightThickness;
    9731113        }
    9741114
    975         public final Frame getParent() {
     1115        public final Frame getParent()
     1116        {
    9761117                return _parent;
    9771118        }
    9781119
    979         public final Point getPosition() {
     1120        /** Gets the position of this item. */
     1121        public final Point getPosition()
     1122        {
    9801123                return new Point(getX(), getY());
    9811124        }
     
    9871130         * @return The size of this Item.
    9881131         */
    989         public float getSize() {
    990                 return -1.0F;
     1132        public float getSize()
     1133        {
     1134                return SIZE_NOT_APPLICABLE;
    9911135        }
    9921136
     
    9971141         * @return The Color displayed on the top\left half of this Item's border.
    9981142         */
    999         public Color getTopShadowColor() {
     1143        public Colour getTopShadowColor()
     1144        {
    10001145                return _colorTopShadow;
    10011146        }
    10021147
    1003         public String getTypeAndID() {
     1148        public String getTypeAndID()
     1149        {
    10041150                return "T " + getID();
    10051151        }
    10061152
    1007         public Integer getWidthToSave() {
     1153        public Integer getWidthToSave()
     1154        {
    10081155                return getWidth();
    10091156        }
    10101157
    1011         public Integer getWidth() {
     1158        public Integer getWidth()
     1159        {
    10121160                return null;
    10131161        }
    10141162
    1015         public int getHeight() {
     1163        public int getHeight()
     1164        {
    10161165                return 0;
    10171166        }
     
    10221171         * @return The X coordinate of this Item on the screen
    10231172         */
    1024         public int getX() {
     1173        public int getX()
     1174        {
    10251175                return Math.round(_x);
    10261176        }
     
    10311181         * @return The Y coordinate of this Item on the screen
    10321182         */
    1033         public int getY() {
     1183        public int getY()
     1184        {
    10341185                return Math.round(_y);
    10351186        }
    10361187
    1037         public boolean hasVisibleArrow() {
     1188        public boolean hasVisibleArrow()
     1189        {
    10381190                return isLineEnd() && getArrowheadRatio() != 0 && getArrowheadLength() != 0;
    10391191        }
     
    10461198         * @return True if the two Shapes overlap, False otherwise.
    10471199         */
    1048         public boolean intersects(Polygon p) {
    1049                 if (p == null)
    1050                         return false;
    1051 
    1052                 Area a = new Area(p);
    1053                 Area thisArea = this.getArea();
     1200        public boolean intersects(PolygonBounds otherBounds)
     1201        {
     1202                if (otherBounds == null) return false;
     1203               
     1204                Bounds thisBounds = getBounds();
     1205               
    10541206                // Need to do this check for circles
    1055                 if (a.equals(thisArea))
    1056                         return true;
    1057 
    1058                 a.intersect(thisArea);
     1207                if (otherBounds.equals(thisBounds)) return true;
     1208
     1209                return otherBounds.intersects(thisBounds);
    10591210
    10601211                // Need to check the second equality so that we dont pick up circles
    10611212                // inside other circles
    1062                 return !a.isEmpty() && !a.equals(new Area(p));
     1213                //return !a.isEmpty() && !a.equals(new Area(p));
    10631214        }
    10641215
     
    10691220         * @return True if this Item is an annotation, False otherwise.
    10701221         */
    1071         public boolean isAnnotation() {
     1222        public boolean isAnnotation()
     1223        {
    10721224                return false;
    10731225        }
    10741226
    1075         public boolean isFloating() {
     1227        public boolean isFloating()
     1228        {
    10761229                return _floating;
    10771230        }
    10781231
    1079         public boolean isFrameName() {
     1232        public boolean isFrameName()
     1233        {
    10801234                if (this.getParent() == null || this.getParent().getNameItem() != this)
    10811235                        return false;
     
    10831237        }
    10841238
    1085         public boolean isFrameTitle() {
     1239        public boolean isFrameTitle()
     1240        {
    10861241                if (this.getParent() == null || this.getParent().getTitleItem() != this)
    10871242                        return false;
     
    10951250         *         otherwise.
    10961251         */
    1097         public boolean isHighlighted() {
     1252        public boolean isHighlighted()
     1253        {
    10981254                if (isFloating())
    10991255                        return false;
    1100                 return _mode != HighlightMode.None;
     1256                return _highlightMode != HighlightMode.None;
    11011257        }
    11021258
     
    11091265         * @return True if the given framename is proper, false otherwise.
    11101266         */
    1111         public boolean isLinkValid() {
     1267        public boolean isLinkValid()
     1268        {
    11121269                if (FrameIO.isPositiveInteger(getLink()))
    11131270                        return true;
     
    11181275        }
    11191276
    1120         public boolean isNear(int x, int y) {
    1121 
    1122                 int xLeft = getPolygon().getBounds().x;
    1123                 int yTop = getPolygon().getBounds().y;
    1124 
    1125                 return (x > xLeft - NEAR_DISTANCE && y > yTop - NEAR_DISTANCE
    1126                                 && x < xLeft + getBoundsWidth() + NEAR_DISTANCE && y < yTop
    1127                                 + getBoundsHeight() + NEAR_DISTANCE);
    1128         }
    1129 
    1130         public boolean isOldTag() {
     1277        /**
     1278         * Checks if the given point is 'near' to the item. Here 'near' means within a certain distance
     1279         * of the axis-aligned box bounding the item's polygon.
     1280         *
     1281         * @param x
     1282         *              The x-coordinate of the point to check.
     1283         *
     1284         * @param y
     1285         *              The y-coordinate of the point to check.
     1286         *
     1287         * @return
     1288         *              True if the given point is 'near' to the item, false otherwise.
     1289         */
     1290        public boolean isNear(int x, int y)
     1291        {
     1292                AxisAlignedBoxBounds box = ItemUtils.expandRectangle(getBoundingBox(), NEAR_DISTANCE * 2);
     1293               
     1294                return box.contains(x, y);
     1295        }
     1296
     1297        public boolean isOldTag()
     1298        {
    11311299                if (this instanceof Text)
    11321300                        if (((Text) this).getTextList().get(0).toLowerCase().equals("@old"))
     
    11531321         *            The Graphics to draw this Item on.
    11541322         */
    1155         public abstract void paint(Graphics2D g);
    1156        
    1157         public void setTooltips(final List<String> tooltips) {
    1158                 if(tooltips == null || tooltips.size() == 0) _tooltip = new Tooltip();
    1159                 else for(final String content: tooltips) _tooltip.addTooltip(content, this);
    1160         }
    1161        
    1162         public void setTooltip(final String tooltip) {
     1323        public abstract void paint();
     1324       
     1325        public void setTooltips(final List<String> tooltips)
     1326        {
     1327                if (tooltips == null || tooltips.size() == 0) {
     1328                        _tooltip = new Tooltip();
     1329                } else {
     1330                        for (final String content: tooltips) _tooltip.addTooltip(content, this);
     1331                }
     1332        }
     1333       
     1334        public void setTooltip(final String tooltip)
     1335        {
    11631336                if(tooltip != null && tooltip.trim().length() > 0) {
    11641337                        _tooltip.addTooltip(tooltip, this);
     
    11661339        }
    11671340       
    1168         public List<String> getTooltip() {
     1341        public List<String> getTooltip()
     1342        {
    11691343                return _tooltip.asStringList();
    11701344        }
    11711345       
    1172         public Collection<Text> getTooltipItems() {
     1346        public Collection<Text> getTooltipItems()
     1347        {
    11731348                return _tooltip.getTooltips();
    11741349        }
    11751350
    1176         public void clearTooltips() {
     1351        public void clearTooltips()
     1352        {
    11771353                final Frame frame = this.getParent();
    1178                 if(_tooltip != null)
     1354                if(_tooltip != null) {
    11791355                        for(final Text tooltip: _tooltip.getTooltips()) frame.removeItem(tooltip);
    1180         }
    1181        
    1182         public void paintTooltip(final Graphics2D g) {
    1183                 final Rectangle bounds = this.getPolygon().getBounds();
    1184                 int x = bounds.x + bounds.width;
    1185                 if(x + _tooltip.getWidth() > FrameGraphics.getMaxFrameSize().width) {
    1186                         x -= x + _tooltip.getWidth() - FrameGraphics.getMaxFrameSize().width;
    1187                 }
    1188                 int y = bounds.y + bounds.height;
    1189                 if(y + _tooltip.getCollectiveHeight() > FrameGraphics.getMaxFrameSize().height) {
    1190                         y = bounds.y + bounds.height / 2 - _tooltip.getCollectiveHeight();
    1191                 }
     1356                }
     1357        }
     1358       
     1359        public void paintTooltip()
     1360        {
     1361                final Bounds bounds = AxisAlignedBoxBounds.getEnclosing(this.getBoundingBox());
     1362                Dimension frameSize = DisplayController.getFramePaintArea().getSize();
     1363               
     1364                int x = bounds.getMaxX();
     1365               
     1366                // If the tooltip goes off the right side of the window, move it left so it's completely on
     1367                if(x + _tooltip.getWidth() > frameSize.getWidth()) {
     1368                        x = frameSize.getWidth() - _tooltip.getWidth();
     1369                }
     1370               
     1371                int y = bounds.getMaxY();
     1372               
     1373                if(y + _tooltip.getCollectiveHeight() > frameSize.getHeight()) {
     1374                        y = (bounds.getMinY() + bounds.getMaxY()) / 2 - _tooltip.getCollectiveHeight();
     1375                }
     1376               
    11921377                for(final Text tooltip : _tooltip.getTooltips()) {
    11931378                        this.getParent().addItem(tooltip);
    11941379                        tooltip.setPosition(x, y);
    1195                         tooltip.paint(g);
     1380                        tooltip.paint();
    11961381                        y += tooltip.getHeight();
    11971382                }
    11981383        }
    11991384       
    1200         public void paintFill(Graphics2D g) {
    1201                 Color fillColor = getFillColor();
     1385        public void paintFill() {
     1386                Colour fillColor = getFillColor();
    12021387                if (fillColor != null && getEnclosingDots() != null) {
    1203                         setFillPaint(g);
    1204                         g.fillPolygon(getEnclosedShape());
    1205                 }
    1206         }
    1207 
    1208         protected void setFillPaint(Graphics2D g) {
    1209                 Color fillColor = getFillColor();
     1388                        Fill fill = getFill();
     1389                        EcosystemManager.getGraphicsManager().drawPolygon(getEnclosedShape(), null, null, 0.0f, fill, null, null);
     1390                }
     1391        }
     1392
     1393        protected Fill getFill() {
     1394                Fill fill;
     1395                Colour fillColour = getFillColor();
    12101396                if (isFloating()) {
    12111397                        // TODO experiment with adding alpha when picking up filled
    12121398                        // items... Slows things down quite alot!!
    1213                         fillColor = new Color(fillColor.getRed(), fillColor.getGreen(),
    1214                                         fillColor.getBlue(), fillColor.getAlpha());
    1215                 }
    1216                 g.setColor(fillColor);
    1217                 Color gradientColor = getGradientColor();
    1218                 if (gradientColor != null) {
     1399                        // TODO: Does nothing as it stands... cts16
     1400                        fillColour = new Colour(fillColour.getRed(), fillColour.getGreen(),
     1401                                        fillColour.getBlue(), fillColour.getAlpha());
     1402                }
     1403                Colour gradientColor = getGradientColor();
     1404                PolygonBounds poly = getEnclosedShape();
     1405                if (gradientColor != null && poly != null) {
    12191406                        /*
    12201407                         * It is slow when painting gradients... modify so this is only done
    12211408                         * once unless it is resized...
    12221409                         */
    1223                         Shape s = getEnclosedShape();
    1224                         if (s != null) {
    1225                                 Rectangle b = s.getBounds();
    1226                                 double rads = getGradientAngle() * Math.PI / 180;
    1227                                 double cos = Math.cos(rads);
    1228                                 double sin = Math.sin(rads);
    1229 
    1230                                 GradientPaint gp = new GradientPaint((int) (b.x + b.width
    1231                                                 * (0.2 * cos + 0.5)), (int) (b.y + b.height
    1232                                                 * (0.2 * sin + 0.5)), fillColor, (int) (b.x + b.width
    1233                                                 * (-0.8 * cos + 0.5)), (int) (b.y + b.height
    1234                                                 * (-0.8 * sin + 0.5)), gradientColor);
    1235                                 g.setPaint(gp);
    1236                         }
    1237                 }
     1410                        AxisAlignedBoxBounds b = AxisAlignedBoxBounds.getEnclosing(poly);
     1411                        double rads = getGradientAngle();
     1412                        double cos = Math.cos(rads);
     1413                        double sin = Math.sin(rads);
     1414
     1415                        Point fromPoint = new Point((int) (b.getMinX() + b.getWidth() * (0.2 * cos + 0.5)), (int) (b.getMinY() + b.getHeight() * (0.2 * sin + 0.5)));
     1416                        Point toPoint = new Point((int) (b.getMinX() + b.getWidth() * (-0.8 * cos + 0.5)), (int) (b.getMinY() + b.getHeight() * (-0.8 * sin + 0.5)));
     1417                       
     1418                        fill = new GradientFill(fillColour, fromPoint, gradientColor, toPoint);
     1419                } else {
     1420                        fill = new Fill(fillColour);
     1421                }
     1422               
     1423                return fill;
    12381424        }
    12391425
    12401426        /**
    12411427         * This method performs all the actions in an items list. If it contains a
    1242          * link as well the link is used as the source frame for all acitons.
     1428         * link as well the link is used as the source frame for all actions.
    12431429         */
    12441430        public void performActions() {
     
    12681454                        // For actions like format they rely on this being set to the
    12691455                        // current frame incase the item being activated is on an overlay
    1270                         sourceFrame = DisplayIO.getCurrentFrame();
     1456                        sourceFrame = DisplayController.getCurrentFrame();
    12711457                }
    12721458
     
    13881574                        MessageBay.displayMessage("See SIMPLE doc for ["
    13891575                                        + ise.getStatement() + "] statement", ise.getStatement()
    1390                                         + "1", Color.CYAN.darker(), true, null);
     1576                                        + "1", Colour.CYAN.darker(), true, null);
    13911577                } catch (Exception e) {
    13921578                        MessageBay.linkedErrorMessage(e.getMessage());
     
    13941580                Simple.ProgramFinished();
    13951581                // Need to repaint any highlights etc
    1396                 FrameGraphics.requestRefresh(true);
     1582                DisplayController.requestRefresh(true);
    13971583        }
    13981584
     
    14141600
    14151601                if (_parent == null)
    1416                         framesetName = DisplayIO.getCurrentFrame().getFramesetName();
     1602                        framesetName = DisplayController.getCurrentFrame().getFramesetName();
    14171603                else
    14181604                        framesetName = _parent.getFramesetName();
     
    14281614         *            The lines of code to associate with this Item
    14291615         */
    1430         public void setActions(List<String> actions) {
     1616        public void setActions(List<String> actions)
     1617        {
    14311618                if (actions == null || actions.size() == 0) {
    14321619                        invalidateCommonTrait(ItemAppearence.LinkChanged);
    14331620                        _actions = null;
    1434                 } else
     1621                } else {
    14351622                        _actions = new LinkedList<String>(actions);
    1436 
    1437                 // Want to resize the highlight box for text items if actions have been
    1438                 // added
    1439                 _poly = null;
     1623                }
     1624               
     1625                // Want to resize the highlight box for text items if actions have been added
     1626                invalidateBounds();
    14401627                invalidateCommonTrait(ItemAppearence.LinkChanged);
    14411628        }
     
    14811668        }
    14821669
    1483         public void setActionMark(boolean val) {
    1484                 if (!val)
    1485                         invalidateCommonTrait(ItemAppearence.LinkChanged);
    1486                 _poly = null;
     1670        public void setActionMark(boolean val)
     1671        {
     1672                if (!val) invalidateCommonTrait(ItemAppearence.LinkChanged);
     1673                invalidateBounds();
    14871674                _actionMark = val;
    1488                 if (val)
    1489                         invalidateCommonTrait(ItemAppearence.LinkChanged);
     1675                if (val) invalidateCommonTrait(ItemAppearence.LinkChanged);
    14901676        }
    14911677
     
    15191705        }
    15201706       
    1521         public void setArrowhead(Polygon arrow) {
     1707        public void setArrowhead(PolygonBounds arrow) {
    15221708                _arrowhead = arrow;
    15231709        }
     
    15381724        }
    15391725
    1540         public void setBackgroundColor(Color c) {
    1541                 if (c != _colorBackground) {
    1542                         _colorBackground = c;
     1726        public void setBackgroundColor(Colour c) {
     1727                if (c != _backgroundColour) {
     1728                        _backgroundColour = c;
    15431729                        invalidateCommonTrait(ItemAppearence.BackgroundColorChanged);
    15441730                }
    15451731        }
    15461732
    1547         public void setBorderColor(Color c) {
     1733        public void setBorderColor(Colour c) {
    15481734                if (c != _colorBorder) {
    15491735                        _colorBorder = c;
     
    15601746         *            Item's border.
    15611747         */
    1562         public void setBottomShadowColor(Color bottom) {
     1748        public void setBottomShadowColor(Colour bottom) {
    15631749                _colorBottomShadow = bottom;
    15641750        }
     
    15691755         * @param c
    15701756         */
    1571         public void setColor(Color c) {
    1572                 if (c != _color) {
    1573                         _color = c;
     1757        public void setColor(Colour c) {
     1758                if (c != _foregroundColour) {
     1759                        _foregroundColour = c;
    15741760                        invalidateCommonTrait(ItemAppearence.ForegroundColorChanged);
    15751761                        if (hasVector()) {
    15761762                                // TODO make this more efficient so it only repaints the items
    15771763                                // for this vector
    1578                                 FrameKeyboardActions.Refresh();
     1764                                StandardGestureActions.Refresh();
    15791765                        }
    15801766                }
     
    16051791        }
    16061792
    1607         public void setFillColor(Color c) {
    1608 
    1609                 _colorFill = c;
     1793        public void setFillColor(Colour c) {
     1794
     1795                _fillColour = c;
    16101796
    16111797                for (Line line : _lines) {
     
    16201806        }
    16211807
    1622         public void setGradientColor(Color c) {
    1623                 _colorGradient = c;
     1808        public void setGradientColor(Colour c)
     1809        {
     1810                _gradientColour = c;
    16241811
    16251812                for (Line line : _lines) {
     
    16331820        }
    16341821
    1635         public Color getGradientColor() {
    1636                 return _colorGradient;
     1822        public Colour getGradientColor() {
     1823                return _gradientColour;
    16371824        }
    16381825
     
    16471834        }
    16481835
     1836        /**
     1837         * Sets the value <code>_highlight</code> for this item.
     1838         * TODO: Appears unused? cts16
     1839         *
     1840         * @param val The new value for <code>_highlight</code>.
     1841         */
    16491842        public void setHighlight(boolean val) {
    16501843                _highlight = val;
     
    16931886         *            The name of the Frame to link this item to.
    16941887         */
    1695         public void setLink(String frameName) {
    1696                 if (frameName == null) {
    1697                         invalidateCommonTrait(ItemAppearence.LinkChanged);
    1698                 }
    1699 
    1700                 // If a link is being removed or set then need to reset poly so the
     1888        public void setLink(String frameName)
     1889        {
     1890                if (frameName == null) invalidateCommonTrait(ItemAppearence.LinkChanged);
     1891
     1892                // If a link is being removed or set then need to reset _bounds so the
    17011893                // highlighting is drawn with the correct width
    1702                 if (frameName == null || getLink() == null)
    1703                         _poly = null;
    1704 
    1705                 if (FrameIO.isValidLink(frameName))
     1894                if (frameName == null || getLink() == null) invalidateBounds();
     1895
     1896                if (FrameIO.isValidLink(frameName)) {
    17061897                        _link = frameName;
    1707                 else
    1708                         MessageBay.errorMessage("[" + frameName
    1709                                         + "] is not a valid frame name");
     1898                } else {
     1899                        MessageBay.errorMessage("[" + frameName + "] is not a valid frame name");
     1900                }
    17101901                // TODO make this throw exceptions etc...
    17111902
     
    17211912        }
    17221913
    1723         public void setLinkFrameset(String frameset) {
    1724                 if (frameset == null || FrameIO.isValidFramesetName(frameset))
     1914        public void setLinkFrameset(String frameset)
     1915        {
     1916                if (frameset == null || FrameIO.isValidFramesetName(frameset)) {
    17251917                        _link_frameset = frameset;
    1726                 else
    1727                         MessageBay.errorMessage("[" + frameset
    1728                                         + "] is not a valid frameset name");
     1918                } else {
     1919                        MessageBay.errorMessage("[" + frameset + "] is not a valid frameset name");
     1920                }
    17291921                // TODO make this throw exceptions etc...
    17301922        }
    17311923
    1732         public void setLinkMark(boolean val) {
    1733                 if (!val)
    1734                         invalidateCommonTrait(ItemAppearence.LinkChanged);
    1735                 _poly = null;
     1924        public void setLinkMark(boolean val)
     1925        {
     1926                if (!val) invalidateCommonTrait(ItemAppearence.LinkChanged);
     1927                invalidateBounds();
    17361928                _linkMark = val;
    1737                 if (val)
    1738                         invalidateCommonTrait(ItemAppearence.LinkChanged);
    1739         }
    1740 
    1741         public void setLinkTemplate(String template) {
    1742                 if (FrameIO.isValidLink(template))
     1929                if (val) invalidateCommonTrait(ItemAppearence.LinkChanged);
     1930        }
     1931
     1932        public void setLinkTemplate(String template)
     1933        {
     1934                if (FrameIO.isValidLink(template)) {
    17431935                        _link_template = template;
    1744                 else
    1745                         MessageBay.errorMessage("[" + template
    1746                                         + "] is not a valid frame name");
     1936                } else {
     1937                        MessageBay.errorMessage("[" + template + "] is not a valid frame name");
     1938                }
    17471939                // TODO make this throw exceptions etc...
    17481940        }
     
    17631955
    17641956        public void setOffset(int x, int y) {
    1765                 _offset.setLocation(x, y);
     1957                _offset.set(x, y);
    17661958        }
    17671959
    17681960        public void setOffset(Point p) {
    1769                 _offset.setLocation(p);
     1961                _offset.set(p);
    17701962        }
    17711963
     
    18051997                        }
    18061998                }
    1807                 if (_colorFill != null) {
     1999                if (_fillColour != null) {
    18082000                        invalidateFill(); // only invalidates if has fill
    18092001                }
     
    18142006        }
    18152007
    1816        
    1817        
    1818        
    1819        
    18202008        protected void anchorConstraints()
    18212009        {
     
    18302018                                        if (isAnchoredY()) {
    18312019                                                // Make the 'other' item have the same anchor top/bottom values as this
    1832                                                 other._anchorTop    = _anchorTop;
    1833                                                 other._anchorBottom = _anchorBottom;
     2020                                                other._anchoring.setYAnchor(this._anchoring);
    18342021                                        }
    18352022                                } else if (c.getType() == Constraint.VERTICAL) {
    18362023                                        if (isAnchoredX()) {
    18372024                                                // Make the 'other' item have the same anchor left/right values as this
    1838                                                 other._anchorLeft  = _anchorLeft;
    1839                                                 other._anchorRight = _anchorRight;
     2025                                                other._anchoring.setXAnchor(this._anchoring);
    18402026                                        }
    18412027                                } else if (c.isDiagonal()) {
     
    18552041         *            The new Y coordinate
    18562042         */
    1857         public void setPosition(float x, float y) {
     2043        public void setPosition(float x, float y)
     2044        {
    18582045                float deltaX = x - _x;
    18592046                float deltaY = y - _y;
    18602047
    1861                 if (deltaX == 0 && deltaY == 0)
    1862                         return;
     2048                if (deltaX == 0 && deltaY == 0) return;
    18632049
    18642050                invalidateCommonTraitForAll(ItemAppearence.PreMoved);
     
    18682054
    18692055                for (Item i : getEnclosures()) {
    1870                         i.updatePolygon();
    1871                 }
    1872                 updatePolygon();
     2056                        i.invalidateBounds();
     2057                }
     2058                invalidateBounds();
    18732059
    18742060                // update the position of any dots that are constrained by this one
     
    19512137
    19522138                for (Line line : getLines()) {
    1953                         line.updatePolygon();
     2139                        line.invalidateBounds();
    19542140                }
    19552141
     
    20072193         *            their thickness set
    20082194         */
    2009         public void setThickness(float thick, boolean setConnectedThickness) {
    2010                 if (thick == _thickness)
    2011                         return;
     2195        public void setThickness(float thick, boolean setConnectedThickness)
     2196        {
     2197                if (thick == _thickness) return;
     2198               
    20122199                boolean bigger = thick > _thickness;
    20132200
     
    20152202                        if (setConnectedThickness) {
    20162203                                // TODO is there a more efficient way of doing this?
    2017                                 for (Item i : getConnected())
    2018                                         i.invalidateCommonTrait(ItemAppearence.Thickness);
     2204                                for (Item i : getConnected()) i.invalidateCommonTrait(ItemAppearence.Thickness);
    20192205                        } else {
    20202206                                invalidateCommonTrait(ItemAppearence.Thickness);
     
    20282214                 * etc...
    20292215                 */
    2030                 for (Line line : getLines())
    2031                         line.setThickness(thick, setConnectedThickness);
    2032 
    2033                 if (setConnectedThickness)
    2034                         updatePolygon();
     2216                for (Line line : getLines()) line.setThickness(thick, setConnectedThickness);
     2217
     2218                if (setConnectedThickness) invalidateBounds();
    20352219
    20362220                if (bigger) {
    20372221                        if (setConnectedThickness) {
    2038                                 for (Item i : getConnected())
    2039                                         i.invalidateCommonTrait(ItemAppearence.Thickness);
     2222                                for (Item i : getConnected()) i.invalidateCommonTrait(ItemAppearence.Thickness);
    20402223                        } else {
    20412224                                invalidateCommonTrait(ItemAppearence.Thickness);
     
    20502233         *         set).
    20512234         */
    2052         public float getThickness() {
     2235        public float getThickness()
     2236        {
    20532237                return _thickness;
    20542238        }
     
    20622246         *            Item's border.
    20632247         */
    2064         public void setTopShadowColor(Color top) {
     2248        public void setTopShadowColor(Colour top) {
    20652249                _colorTopShadow = top;
    20662250        }
    20672251
    2068         public void setWidth(Integer width) throws UnsupportedOperationException {
    2069                 throw new UnsupportedOperationException(
    2070                                 "Item type does not support width attribute!");
    2071         }
    2072 
    2073         public void setRightMargin(int i, boolean fixWidth) {
     2252        public void setWidth(Integer width) throws UnsupportedOperationException
     2253        {
     2254                throw new UnsupportedOperationException("Item type does not support width attribute!");
     2255        }
     2256
     2257        public void setRightMargin(int i, boolean fixWidth)
     2258        {
    20742259                int newWidth = i - getX() - Item.MARGIN_LEFT;
     2260                if (newWidth < 0) newWidth = 0;
    20752261                if (!fixWidth) {
    20762262                        newWidth *= -1;
     
    21132299         *         means no change)
    21142300         */
    2115         public int setHighlightColor() {
    2116                 return setHighlightColor(DEFAULT_HIGHLIGHT);
    2117         }
    2118 
    2119         public int setHighlightColor(Color c) {
     2301       
     2302        /**
     2303         *
     2304         *
     2305         * @return
     2306         */
     2307        public void setHighlightColorToDefault() {
     2308                setHighlightColor(DEFAULT_HIGHLIGHT);
     2309        }
     2310
     2311        public void setHighlightColor(Colour c) {
     2312                if (c == null) return;
     2313               
    21202314                if (!this.isVisible() && this.hasVector()) {
    21212315                        for (Item i : this.getParentOrCurrentFrame().getVectorItems()) {
     
    21282322                _highlightThickness = DEFAULT_HIGHLIGHT_THICKNESS;
    21292323
    2130                 Color selColor = (c != null) ? c : DEFAULT_HIGHLIGHT;
    2131                 if (_highlightColor != c) {
    2132                         _highlightColor = selColor;
     2324                Colour selColor = (c != null) ? c : DEFAULT_HIGHLIGHT;
     2325                if (_highlightColour != c) {
     2326                        _highlightColour = selColor;
    21332327                        this.invalidateCommonTrait(ItemAppearence.HighlightColorChanged);
    21342328                }
    2135 
    2136                 return Item.UNCHANGED_CURSOR;
    21372329
    21382330        }
     
    21462338        }
    21472339
    2148         public abstract void updatePolygon();
     2340        /** Returns a Bounds which represents the area covered by the item (including its gravity). */
     2341        public abstract Bounds updateBounds();
    21492342
    21502343        public void setHidden(boolean state) {
     
    21722365        }
    21732366
    2174         public void setHighlightMode(HighlightMode mode, Color color) {
    2175                 setHighlightColor(color);
    2176                 if (hasPermission(UserAppliedPermission.followLinks)
    2177                                 || getEditTarget().hasPermission(UserAppliedPermission.followLinks)) {
    2178                         if (_mode != mode) {
    2179                                 _mode = mode;
    2180                                 this.invalidateCommonTrait(ItemAppearence.HighlightModeChanged);
    2181                         }
    2182                 }
     2367        /**
     2368         * Sets the highlight mode and colour at the same time.
     2369         *
     2370         * @param mode The new highlight mode.
     2371         * @param colour The new highlight colour.
     2372         */
     2373        public void setHighlightModeAndColour(HighlightMode mode, Colour colour)
     2374        {
     2375                setHighlightMode(mode);
     2376                setHighlightColor(colour);
    21832377        }
    21842378
    21852379        public HighlightMode getHighlightMode() {
    2186                 return _mode;
     2380                return _highlightMode;
    21872381        }
    21882382
     
    21912385                // only set the id if we've moved to a different frame, or if the frame already has an item with that id
    21922386                if(!current.equals(_oldParent) || current.getItemWithID(getID()) != null) {
    2193                         int id = _id;
    21942387                        setID(current.getNextItemID());
    2195                         // System.out.println(this + " - Set ID to " + _id + " (was " + id + ")");
    21962388                } else {
    21972389                        // System.out.println(this + " - Kept old ID of " + _id);
     
    22392431                // if the item is from an overlay the parent will NOT be null
    22402432                if (getParent() == null) {
    2241                         return DisplayIO.getCurrentFrame();
     2433                        return DisplayController.getCurrentFrame();
    22422434                }
    22432435                return getParent();
     
    22752467         *         the enclosed list.
    22762468         */
    2277         public Polygon getEnclosedShape() {
    2278                 if (_enclosure == null)
    2279                         return null;
    2280 
    2281                 Polygon poly = new Polygon();
     2469        public PolygonBounds getEnclosedShape()
     2470        {
     2471                if (_enclosure == null) return null;
     2472
     2473                PolygonBounds poly = new PolygonBounds();
    22822474                for (Item d : _enclosure) {
    2283                         poly.addPoint(d.getX(), d.getY());
     2475                        poly.addPoint(new Point(d.getX(), d.getY()));
    22842476                }
    22852477
     
    23322524         *            the new color for the line
    23332525         */
    2334         protected void lineColorChanged(Color c) {
     2526        protected void lineColorChanged(Colour c) {
    23352527                for (Line l : getLines()) {
    23362528                        if (l.getColor() != c)
     
    23452537         */
    23462538        public boolean offScreenTopOrLeft() {
    2347                 Rectangle itemRect = getArea().getBounds();
     2539                Bounds bounds = getBoundingBox();
     2540               
    23482541                // Check that the bottom right corner of this item is on the screen
    2349                 if (itemRect.x + itemRect.width >= 0
    2350                                 && itemRect.y + itemRect.height >= 0)
     2542                if (bounds.getMaxX() >= 0 && bounds.getMaxY() >= 0) {
    23512543                        return false;
     2544                }
     2545               
    23522546                // Check if all the items it is connected to are offscreen
    23532547                for (Item i : getAllConnected()) {
    2354                         Rectangle iRect = i.getArea().getBounds();
     2548                        bounds = i.getBoundingBox();
    23552549                        // Check that the bottom right corner of this item is on the screen
    2356                         if (iRect.x + iRect.width >= 0 && iRect.y + iRect.height >= 0) {
     2550                        if (bounds.getMaxX() >= 0 && bounds.getMaxY() >= 0) {
    23572551                                return false;
    23582552                        }
    23592553                }
     2554               
    23602555                return true;
    23612556        }
     
    23742569        }
    23752570
    2376         public void setAction(String action) {
    2377                 // Want to resize the highlight box for text items if actions are been
    2378                 // added
     2571        public void setAction(String action)
     2572        {
     2573                // Want to resize the highlight box for text items if actions are been added
    23792574                if (action == null || action.length() == 0) {
    23802575                        invalidateCommonTrait(ItemAppearence.LinkChanged);
    23812576                }
     2577               
    23822578                if (_actions == null || _actions.size() == 0) {
    2383                         _poly = null;
     2579                        invalidateBounds();
    23842580                        _actions = new LinkedList<String>();
    23852581                } else {
    23862582                        _actions.clear();
    23872583                }
    2388                 if (action != null && action.length() > 0)
    2389                         _actions.add(action);
     2584               
     2585                if (action != null && action.length() > 0) _actions.add(action);
     2586               
    23902587                invalidateCommonTrait(ItemAppearence.LinkChanged);
    23912588        }
     
    23952592        }
    23962593
    2397         protected Rectangle getLinkDrawArea() {
     2594        protected AxisAlignedBoxBounds getLinkDrawArea() {
    23982595                return getLinkDrawArea(getX() - LEFT_MARGIN, getY() + getLinkYOffset());
    23992596        }
     
    24102607         * @return The drawing area of the link at the given coordinates.
    24112608         */
    2412         public Rectangle getLinkDrawArea(int x, int y) {
    2413                 return new Rectangle(x + 2, y - 1, 8, 8);
     2609        public AxisAlignedBoxBounds getLinkDrawArea(int x, int y) {
     2610                return new AxisAlignedBoxBounds(x + 2, y - 1, 8, 8);
    24142611        }
    24152612
     
    24192616         * @param g
    24202617         */
    2421         protected void paintLink(Graphics2D g) {
    2422                 paintLinkGraphic(g, getX() - LEFT_MARGIN, getY() + getLinkYOffset());
     2618        protected void paintLink() {
     2619                paintLinkGraphic(getX() - LEFT_MARGIN, getY() + getLinkYOffset());
    24232620        }
    24242621
     
    24382635         *            centered)
    24392636         */
    2440         public void paintLinkGraphic(Graphics2D g, int x, int y) {
    2441 
    2442                 boolean hasLink = getLink() != null;
     2637        public void paintLinkGraphic(int x, int y) {
     2638
     2639                boolean hasLink = hasLink();
    24432640                boolean hasAction = hasAction();
    24442641
    24452642                if (hasLink || hasAction) {
    2446                         g.setStroke(HIGHLIGHT_STROKE);
     2643                        GraphicsManager g = EcosystemManager.getGraphicsManager();
     2644                        Fill fill = new Fill();
     2645                        Colour colour = null;
     2646                        Point offset = new Point(x, y);
     2647                       
    24472648                        if (hasLink && hasAction) {
    2448                                 g.setColor(LINK_ACTION_COLOR);
     2649                                colour = LINK_ACTION_COLOR;
    24492650                        } else if (hasLink) {
    2450                                 g.setColor(LINK_COLOR);
     2651                                colour = LINK_COLOR;
    24512652                        } else if (hasAction) {
    2452                                 g.setColor(ACTION_COLOR);
     2653                                colour = ACTION_COLOR;
    24532654                        }
    2454 
    2455                         AffineTransform at = new AffineTransform();
    2456                         AffineTransform orig = g.getTransform();
    2457                         at.translate(x, y);
    2458                         g.setTransform(at);
    2459 
    2460                         if (getLinkMark() && getLink() != null) {
    2461                                 g.drawPolygon(getLinkPoly());
    2462 
     2655                        fill.setColour(colour);
     2656
     2657                        // Small circles look rubbish without AA. cts16
     2658                        g.setAntialiasing(true);
     2659                       
     2660                        if (hasLink && getLinkMark()) {
     2661                                g.drawOval(offset, getLinkBounds().getDiameters(), 0.0f, null, colour, HIGHLIGHT_STROKE);
     2662                               
    24632663                                // if the link is not valid, cross out the circle
    2464                                 if (!isLinkValid())
    2465                                         g.drawPolygon(getCircleCross());
     2664                                if (!isLinkValid()) {
     2665                                        g.drawPolygon(getCircleCross(), offset, null, 0.0f, null, colour, HIGHLIGHT_STROKE);
     2666                                }
    24662667                        }
    24672668
    2468                         if (getActionMark() && hasAction()) {
    2469                                 g.drawPolygon(getLinkPoly());
    2470                                 g.fillPolygon(getLinkPoly());
     2669                        if (hasAction && getActionMark()) {
     2670                                g.drawOval(offset, getLinkBounds().getDiameters(), 0.0f, fill, colour, HIGHLIGHT_STROKE);
    24712671
    24722672                                // if the link is not valid, cross out the circle
    24732673                                if (!isLinkValid() && getLink() != null) {
    2474                                         g.setColor(getParent().getPaintBackgroundColor());
    2475                                         g.drawPolygon(getCircleCross());
     2674                                        g.drawPolygon(getCircleCross(), offset, null, 0.0f, null, getParent().getPaintBackgroundColor(), HIGHLIGHT_STROKE);
    24762675                                }
    24772676                        }
    2478 
    2479                         // reset the graphics tranformation
    2480                         g.setTransform(orig);
     2677                       
     2678                        g.setAntialiasing(false);
    24812679                }
    24822680        }
     
    25392737                        return null;
    25402738                // assert (_parent!= null);
    2541                 Frame parent = DisplayIO.getCurrentFrame();
     2739                Frame parent = DisplayController.getCurrentFrame();
    25422740                assert (parent != null);
    25432741
     
    25872785                while (!lines.isEmpty()) {
    25882786                        Line l = lines.remove();
    2589                         // if we havnt visited the line yet visit it
     2787                        // if we haven't visited the line yet visit it
    25902788                        if (!visited.contains(l)) {
    25912789                                visited.add(l);
    25922790                                Item otherEnd = l.getOppositeEnd(this);
    2593                                 // Add all the enexplored lines to our list
     2791                                // Add all the unexplored lines to our list
    25942792                                while (!lines.isEmpty()) {
    25952793                                        l = lines.remove();
     
    26132811         *         is part of
    26142812         */
    2615         public double getEnclosedArea() {
    2616                 if (_enclosure == null)
    2617                         return 0.0;
    2618                 Rectangle2D box = getEnclosedShape().getBounds2D();
     2813        public double getEnclosedArea()
     2814        {
     2815                AxisAlignedBoxBounds box = getEnclosedBox();
     2816                if (box == null) return 0.0;
    26192817                return box.getWidth() * box.getHeight();
    26202818        }
    26212819
    2622         public Rectangle getEnclosedRectangle() {
    2623                 if (_enclosure == null)
    2624                         return null;
    2625                 return getEnclosedShape().getBounds();
    2626         }
    2627 
    2628         public int getEnclosureID() {
     2820        /**
     2821         * Gets the box encompassing all points that form an enclosure with this item.
     2822         *
     2823         * @return An axis-aligned box around all enclosure points.
     2824         */
     2825        public AxisAlignedBoxBounds getEnclosedBox()
     2826        {
     2827                if (_enclosure == null) return null;
     2828               
     2829                return AxisAlignedBoxBounds.getEnclosing(getEnclosedShape());
     2830        }
     2831
     2832        public int getEnclosureID()
     2833        {
    26292834                return _enclosure == null ? 0 : _enclosure.hashCode();
    26302835        }
    26312836
    26322837        /**
    2633          * Returns the Shape that surrounds this Item representing this Item's
     2838         * Returns the Bounds that surrounds this Item representing this Item's
    26342839         * 'gravity'.
    26352840         *
    2636          * @return The Shape (rectangle) surrounding this Item, which represents
     2841         * @return The Bounds surrounding this Item, which represents
    26372842         *         this Items 'gravity'.
    26382843         */
    2639         public final Polygon getPolygon() {
    2640                 if (_poly == null)
    2641                         updatePolygon();
    2642 
    2643                 return new Polygon(_poly.xpoints, _poly.ypoints, _poly.npoints);
     2844        public final Bounds getBounds()
     2845        {
     2846                if (_bounds == null) _bounds = updateBounds();
     2847               
     2848                // DEBUG
     2849                if (_bounds == null) {
     2850                        //System.out.println("updateBounds failed!");
     2851                }
     2852
     2853                return _bounds;
     2854        }
     2855       
     2856        public final Bounds getOldBounds()
     2857        {
     2858                return _oldBounds;
     2859        }
     2860       
     2861        public final void invalidateBounds()
     2862        {
     2863                if (_bounds != null) _oldBounds = _bounds;
     2864                _bounds = null;
     2865        }
     2866       
     2867        public final AxisAlignedBoxBounds getBoundingBox()
     2868        {
     2869                return AxisAlignedBoxBounds.getEnclosing(getBounds());
    26442870        }
    26452871
     
    26512877         * @param ratio
    26522878         */
    2653         public void translate(Point2D origin, double ratio) {
     2879        public void translate(Point origin, double ratio) {
    26542880
    26552881                invalidateCommonTraitForAll(ItemAppearence.PreMoved);
    26562882
    2657                 _x = (float) (origin.getX() + ratio * (_x - origin.getX()));
    2658                 _y = (float) (origin.getY() + ratio * (_y - origin.getY()));
    2659                 updatePolygon();
     2883                _x = (float) (origin.x + ratio * (_x - origin.x));
     2884                _y = (float) (origin.y + ratio * (_y - origin.y));
     2885                invalidateBounds();
    26602886                for (Line line : getLines())
    2661                         line.updatePolygon();
     2887                        line.invalidateBounds();
    26622888
    26632889                invalidateCommonTraitForAll(ItemAppearence.PostMoved);
     
    26982924        }
    26992925
    2700         Collection<XRayable> _enclosures = new HashSet<XRayable>();
    2701 
    2702         private boolean _deleted = false;
    2703 
    2704         private Overlay _overlay = null;
    2705 
    2706         protected AttributeValuePair _attributeValuePair = null;
    2707 
    2708         private Float _autoStamp = null;
    2709 
    27102926        /**
    27112927         * For now there can only be one enclosure per item
     
    27412957         *         highlighting bounds
    27422958         */
    2743         public Rectangle[] getDrawingArea() {
    2744 
    2745                 return new Rectangle[] { ItemUtils.expandRectangle(getPolygon()
    2746                                 .getBounds(), (int) Math.ceil(Math.max(_highlightThickness,
    2747                                 getThickness()))) };
    2748 
     2959        public AxisAlignedBoxBounds getDrawingArea() {
     2960
     2961                return ItemUtils.expandRectangle(
     2962                                        getBoundingBox(),
     2963                                        (int) Math.ceil(Math.max(_highlightThickness, getThickness())) + 1 // + 1 to make sure
     2964                );
    27492965        }
    27502966
     
    27542970         * @return True if area intersects with this items drawing area.
    27552971         */
    2756         public final boolean isInDrawingArea(Area area) {
    2757                 for (Rectangle r : getDrawingArea()) {
    2758                         if (area.intersects(r))
    2759                                 return true;
    2760                 }
    2761                 return false;
    2762         }
    2763 
    2764         /**
    2765          * Completetly invalidates the item - so that it should be redrawed. Note:
    2766          * This is handled internally, it should be reare to invoke this externally
    2767          */
    2768         public final void invalidateAll() {
     2972        public final boolean isInDrawingArea(AxisAlignedBoxBounds area)
     2973        {
     2974                AxisAlignedBoxBounds drawingArea = getDrawingArea();
     2975               
     2976                if (drawingArea == null) return false;
     2977               
     2978                return drawingArea.intersects(area);
     2979        }
     2980
     2981        /**
     2982         * Completely invalidates the item - so that it should be redrawn. Note:
     2983         * This is handled internally, it should be rare to invoke this externally
     2984         */
     2985        public final void invalidateAll()
     2986        {
    27692987                invalidate(getDrawingArea());
    27702988        }
     
    27762994         * @param damagedAreas
    27772995         */
    2778         protected final void invalidate(Rectangle[] damagedAreas) {
    2779                 for (Rectangle r : damagedAreas)
    2780                         invalidate(r);
     2996        protected final void invalidate(Bounds[] damagedAreas)
     2997        {
     2998                if (damagedAreas != null) for (Bounds b : damagedAreas) invalidate(b);
    27812999        }
    27823000
     
    27873005         * @param damagedAreas
    27883006         */
    2789         protected final void invalidate(Rectangle damagedArea) {
    2790                 FrameGraphics.invalidateItem(this, damagedArea);
     3007        protected final void invalidate(Bounds damagedArea)
     3008        {
     3009                if (damagedArea != null) DisplayController.invalidateItem(this, damagedArea);
    27913010        }
    27923011
     
    27963015         * @param trait
    27973016         */
    2798         public final void invalidateCommonTrait(ItemAppearence trait) {
     3017        public final void invalidateCommonTrait(ItemAppearence trait)
     3018        {
    27993019                invalidate(getDamagedArea(trait));
    28003020
    2801                 if (_colorFill != null
    2802                                 && (trait == ItemAppearence.Added || trait == ItemAppearence.Removed)) {
     3021                if (_fillColour != null && (trait == ItemAppearence.Added || trait == ItemAppearence.Removed)) {
    28033022                        invalidateFill();
    28043023                }
     
    28083027         * Invalidates fill if has one, even if no color is set.
    28093028         */
    2810         public void invalidateFill() {
     3029        public void invalidateFill()
     3030        {
    28113031                if (isLineEnd() && _enclosure != null) {
    2812                         invalidate(getEnclosedShape().getBounds());
     3032                        invalidate(getEnclosedBox());
    28133033                }
    28143034        }
     
    28263046         * @return The damaged area according to the visual trait that has changed.
    28273047         */
    2828         protected Rectangle[] getDamagedArea(ItemAppearence trait) {
    2829 
     3048        protected AxisAlignedBoxBounds getDamagedArea(ItemAppearence trait)
     3049        {
    28303050                if (trait == ItemAppearence.LinkChanged)
    2831                         return new Rectangle[] { getLinkDrawArea() }; // Invalidate area
    2832                 // where link is
    2833                 // drawn
     3051                        return getLinkDrawArea(); // Invalidate area where link is drawn
    28343052
    28353053                return getDrawingArea();
    2836 
    28373054        }
    28383055
     
    28643081        }
    28653082
    2866         public void setAnchorLeft(Float anchor) {
    2867                 this._anchorLeft = anchor;
    2868                 this._anchorRight = null;
     3083        public void setAnchorLeft(Integer anchor)
     3084        {
     3085                this._anchoring.setLeftAnchor(anchor);
    28693086                if (anchor != null) {
    28703087                        anchorConstraints();
     
    28733090        }
    28743091
    2875         public void setAnchorRight(Float anchor) {
    2876                 this._anchorRight = anchor;
    2877                 this._anchorLeft = null;
     3092        public void setAnchorRight(Integer anchor)
     3093        {
     3094                this._anchoring.setRightAnchor(anchor);
    28783095                if (anchor != null) {
    28793096                        anchorConstraints();
    2880                         setX(FrameGraphics.getMaxFrameSize().width - anchor
    2881                                         - getBoundsWidth());
    2882                 }
    2883         }
    2884 
    2885         public void setAnchorTop(Float anchor) {
    2886                 this._anchorTop = anchor;
    2887                 this._anchorBottom = null;
     3097                        setX(DisplayController.getFramePaintArea().getMaxX() - anchor - getBoundsWidth());
     3098                }
     3099        }
     3100
     3101        public void setAnchorTop(Integer anchor)
     3102        {
     3103                this._anchoring.setTopAnchor(anchor);
    28883104                if (anchor != null) {
    28893105                        anchorConstraints();
     
    28933109
    28943110
    2895         public void setAnchorBottom(Float anchor) {
    2896                 this._anchorBottom = anchor;
    2897                 this._anchorTop = null;
     3111        public void setAnchorBottom(Integer anchor)
     3112        {
     3113                this._anchoring.setBottomAnchor(anchor);
    28983114                if (anchor != null) {
    28993115                        anchorConstraints();
    2900                         setY(FrameGraphics.getMaxFrameSize().height - anchor);
    2901                 }
    2902         }
    2903 
    2904 
    2905         public boolean isAnchored() {
    2906             return ((_anchorLeft != null) || (_anchorRight != null)
    2907                     || (_anchorTop != null) || (_anchorBottom != null));
     3116                        setY(DisplayController.getFramePaintArea().getMaxY() - anchor);
     3117                }
     3118        }
     3119
     3120        public boolean isAnchored()
     3121        {
     3122            return _anchoring.isAnchored();
    29083123        }
    29093124
    29103125        public boolean isAnchoredX() {
    2911             return ((_anchorLeft != null) || (_anchorRight != null));
     3126            return _anchoring.isXAnchored();
    29123127        }
    29133128
    29143129        public boolean isAnchoredY() {
    2915             return ((_anchorTop != null) || (_anchorBottom != null));
    2916         }
    2917 
    2918         public Float getAnchorLeft() {
    2919                 return _anchorLeft;
    2920         }
    2921 
    2922         public Float getAnchorRight() {
    2923                 return _anchorRight;
    2924         }
    2925 
    2926         public Float getAnchorTop() {
    2927                 return _anchorTop;
    2928         }
    2929 
    2930         public Float getAnchorBottom() {
    2931                 return _anchorBottom;
     3130            return _anchoring.isYAnchored();
     3131        }
     3132
     3133        public Integer getAnchorLeft() {
     3134                return _anchoring.getLeftAnchor();
     3135        }
     3136
     3137        public Integer getAnchorRight() {
     3138                return _anchoring.getRightAnchor();
     3139        }
     3140
     3141        public Integer getAnchorTop() {
     3142                return _anchoring.getTopAnchor();
     3143        }
     3144
     3145        public Integer getAnchorBottom() {
     3146                return _anchoring.getBottomAnchor();
    29323147        }
    29333148
     
    30243239                // Invalidate them again!!
    30253240                for (Item i : this.getAllConnected()) {
    3026                         i.updatePolygon();
     3241                        i.invalidateBounds();
    30273242                        i.invalidateAll();
    30283243                }
    30293244        }
    30303245
    3031        
    30323246        protected void anchorConnected(AnchorEdgeType anchorEdgeType, Float delta) {
    30333247               
     
    30873301                // Invalidate them again!!
    30883302                for (Item i : this.getAllConnected()) {
    3089                         i.updatePolygon();
     3303                        i.invalidateBounds();
    30903304                        i.invalidateAll();
    30913305                }
     
    31233337                // DONT PUT SIZE IN HERE CAUSE IT STUFFS UP CIRCLES
    31243338
    3125                 updatePolygon();
     3339                invalidateBounds();
    31263340        }
    31273341
     
    31683382                return _autoStamp != null && _autoStamp >= 0.0;
    31693383        }
    3170 
    3171         public void setDotType(DotType type) {
    3172                 invalidateAll();
    3173                 _type = type;
    3174                 invalidateAll();
    3175         }
    3176 
    3177         public DotType getDotType() {
    3178                 return _type;
    3179         }
    3180 
    3181         public void setFilled(boolean filled) {
    3182                 invalidateAll();
    3183                 _filled = filled;
    3184                 invalidateAll();
    3185         }
    3186 
    3187         public boolean getFilled() {
    3188                 return _filled;
    3189         }
    3190                
    3191         private Item _magnetizedItemLeft = null;
    3192         private Item _magnetizedItemRight = null;
    3193         private Item _magnetizedItemTop = null;
    3194         private Item _magnetizedItemBottom = null;
    31953384       
    31963385        public int getMagnetizedItemLeft() {
     
    32453434                setMagnetizedItemBottom(this.getParent().getItemWithID(id));
    32463435        }
     3436
     3437        /**
     3438         * Replaces the given dot item with a text item displaying the given character.
     3439         *
     3440         * @param dot
     3441         *              The Dot item to replace.
     3442         *
     3443         * @param ch
     3444         *              The character to display as the text for the created Text item.
     3445         *
     3446         * @return
     3447         *              The created Text item.
     3448         */
     3449        public static Text replaceDot(Item dot, char ch) {
     3450                // TODO: Should this make sure 'dot' is actually a Dot and not some other item? cts16
     3451                Text text = Text.createText(ch);
     3452                Item.DuplicateItem(dot, text);
     3453                FrameUtils.setLastEdited(text);
     3454
     3455                // Copy the lines list so it can be modified
     3456                List<Line> lines = new LinkedList<Line>(dot.getLines());
     3457                for (Line line : lines)
     3458                        line.replaceLineEnd(dot, text);
     3459                Frame current = dot.getParentOrCurrentFrame();
     3460                current.removeItem(dot);
     3461                ItemUtils.EnclosedCheck(current.getItems());
     3462                return text;
     3463                // TODO: Should this add the newly-created Text item to the frame? cts16
     3464        }
     3465
     3466        /**
     3467         * Replaces the given text item with a dot
     3468         */
     3469        public static Item replaceText(Item text) {
     3470                Item dot = new Dot(text.getX(), text.getY(), text.getID());
     3471                Item.DuplicateItem(text, dot);
     3472
     3473                List<Line> lines = new LinkedList<Line>();
     3474                lines.addAll(text.getLines());
     3475                if (lines.size() > 0)
     3476                        dot.setColor(lines.get(0).getColor());
     3477                for (Line line : lines) {
     3478                        line.replaceLineEnd(text, dot);
     3479                }
     3480                text.delete();
     3481                Frame current = text.getParentOrCurrentFrame();
     3482                current.addItem(dot);
     3483                DisplayController.setCursor(Item.DEFAULT_CURSOR);
     3484                ItemUtils.EnclosedCheck(current.getItems());
     3485                return dot;
     3486        }
    32473487}
  • trunk/src/org/expeditee/items/ItemAppearence.java

    r919 r1102  
    2020
    2121/**
    22  * Used for invlaidation on items.
     22 * Used for invalidation on items.
    2323 * @author Brook Novak
    2424 */
     
    3737        Removed,
    3838        ToggleDashed,
    39         Thickness, GradientColor, BorderColorChanged
     39        Thickness,
     40        GradientColor,
     41        BorderColorChanged
    4042}
  • trunk/src/org/expeditee/items/ItemUtils.java

    r922 r1102  
    1919package org.expeditee.items;
    2020
    21 import java.awt.Color;
    22 import java.awt.Rectangle;
    23 import java.awt.image.ImageObserver;
    2421import java.io.File;
    2522import java.io.UnsupportedEncodingException;
     
    3431import java.util.Map;
    3532
    36 import org.expeditee.gui.DisplayIO;
     33import org.expeditee.core.Colour;
     34import org.expeditee.core.bounds.AxisAlignedBoxBounds;
     35import org.expeditee.gui.DisplayController;
     36import org.expeditee.gui.DisplayController.TwinFramesSide;
    3737import org.expeditee.gui.Frame;
    3838import org.expeditee.gui.FrameUtils;
     
    4040import org.expeditee.gui.Vector;
    4141import org.expeditee.items.Item.HighlightMode;
    42 import org.expeditee.items.widgets.InteractiveWidget;
     42import org.expeditee.items.widgets.Widget;
    4343import org.expeditee.items.widgets.InteractiveWidgetInitialisationFailedException;
    4444import org.expeditee.items.widgets.InteractiveWidgetNotAvailableException;
     
    360360         *
    361361         * @param source
    362          *            The Text file containing the Picture infomation
     362         *            The Text file containing the Picture information
    363363         * @return The Picture object representing the file, or Null if the file is
    364364         *         not found.
    365365         */
    366         public static Picture CreatePicture(Text source, ImageObserver observer, boolean tryRemote) {
     366        public static Picture CreatePicture(Text source, boolean tryRemote) {
    367367                String text = source.getText();
    368368                String path = "";
     
    424424                                // call CreatePicture again, but with tryRemote set to false so we won't get into an infinite loop
    425425                                // if something goes wrong with finding the downloaded image
    426                                 return CreatePicture(source, observer, false);
     426                                return CreatePicture(source, false);
    427427                        }
    428428                                return null;
     
    434434
    435435                try {
    436                         Picture pic = new Picture(source, fileName, path, size, observer);
     436                        Picture pic = new Picture(source, fileName, path, size);
    437437
    438438                        return pic;
     
    444444        }
    445445       
    446         public static Picture CreatePicture(Text source, ImageObserver observer) {
    447                 return CreatePicture(source, observer, true);
     446        public static Picture CreatePicture(Text source) {
     447                return CreatePicture(source, true);
    448448        }
    449449
     
    483483
    484484                // Widgets are super special
    485                 List<InteractiveWidget> widgets = new ArrayList<InteractiveWidget>();
     485                List<Widget> widgets = new ArrayList<Widget>();
    486486
    487487                for (Item i : toCopy) {
     
    596596                        Item start = lineEndMap.get(c.getStart());
    597597                        Item end = lineEndMap.get(c.getEnd());
    598                         int id = DisplayIO.getCurrentFrame().getNextItemID();
     598                        int id = DisplayController.getCurrentFrame().getNextItemID();
    599599                        if (start != null && end != null) {
    600600                                new Constraint(start, end, id, c.getType());
     
    603603
    604604                // BROOK
    605                 for (InteractiveWidget iw : widgets) {
     605                for (Widget iw : widgets) {
    606606                        try {
    607607
    608                                 InteractiveWidget icopy = iw.copy();
     608                                Widget icopy = iw.copy();
    609609                                copies.addAll(icopy.getItems());
    610610
     
    680680                Item copy = origEnd.copy();
    681681                origEnd.setHighlightMode(HighlightMode.None);
     682                origEnd.setHighlightColorToDefault();
    682683                copy.removeAllLines();
    683684                copy.removeAllConstraints();
     
    688689
    689690                // create a new line
    690                 Frame currentFrame = DisplayIO.getCurrentFrame();
     691                Frame currentFrame = DisplayController.getCurrentFrame();
    691692                Line line = new Line(origEnd, copy, currentFrame.getNextItemID());
    692693                // if the previous line was constrained then make the new line
     
    694695                // TODO add later a diagonal constraint if getLines() == 3 or 4
    695696                Collection<Constraint> constraints = origEnd.getConstraints();
    696                 if (constrain && constraints.size() > 0
    697                                 && origEnd.getLines().size() == 2) {
     697                if (constrain && constraints.size() > 0 && origEnd.getLines().size() == 2) {
    698698                        Integer type = null;
    699699                        for (Constraint c : constraints) {
     
    710710                        }
    711711                        if (type != null) {
    712                                 new Constraint(origEnd, copy, currentFrame.getNextItemID(),
    713                                                 type);
     712                                new Constraint(origEnd, copy, currentFrame.getNextItemID(), type);
    714713                        }
    715714                }
     
    726725
    727726        public static void New() {
    728                 EnclosedCheck(DisplayIO.getCurrentFrame().getItems());
     727                EnclosedCheck(DisplayController.getCurrentFrame().getItems());
    729728        }
    730729
    731730        public static void Old() {
    732                 OldEnclosedCheck(DisplayIO.getCurrentFrame().getItems());
     731                OldEnclosedCheck(DisplayController.getCurrentFrame().getItems());
    733732        }
    734733
     
    902901         */
    903902        public static boolean isVisible(Item i) {
    904                 if (DisplayIO.isTwinFramesOn()) {
    905                         if (!isVisible(DisplayIO.getFrames()[0], i)) {
    906                                 return isVisible(DisplayIO.getFrames()[1], i);
     903                if (DisplayController.isTwinFramesOn()) {
     904                        if (!isVisible(DisplayController.getFrameOnSide(TwinFramesSide.LEFT), i)) {
     905                                return isVisible(DisplayController.getFrameOnSide(TwinFramesSide.RIGHT), i);
    907906                        } else {
    908907                                return true;
    909908                        }
    910909                } else {
    911                         return isVisible(DisplayIO.getCurrentFrame(), i);
     910                        return isVisible(DisplayController.getCurrentFrame(), i);
    912911                }
    913912        }
     
    923922         * @return True if visible/free from given frame.
    924923         */
    925         public static boolean isVisible(Frame fromFrame, Item i) {
    926                 if (fromFrame == null)
    927                         return false;
     924        public static boolean isVisible(Frame fromFrame, Item i)
     925        {
     926                if (fromFrame == null) return false;
    928927
    929928                Frame parent = i.getParent();
    930929
    931                 if (parent == fromFrame)
     930                if (parent == fromFrame) {
    932931                        return true;
     932                } else if (parent == null) {
     933                        return FreeItems.getInstance().contains(i) || FreeItems.getCursor().contains(i);
     934                }
    933935               
    934                 else if (parent == null)
    935                         return FreeItems.getInstance().contains(i)
    936                                         || FreeItems.getCursor().contains(i);
    937 
    938936                return fromFrame.getAllItems().contains(i) && i.isVisible();
    939937        }
    940938
    941         public static Rectangle expandRectangle(Rectangle r, int n) {
    942                 return new Rectangle(r.x - (n >> 1), r.y - (n >> 1), r.width + n,
    943                                 r.height + n);
     939        public static AxisAlignedBoxBounds expandRectangle(AxisAlignedBoxBounds r, int n)
     940        {
     941                if (r == null) return null;
     942               
     943                return new AxisAlignedBoxBounds(r.getMinX() - (n >> 1), r.getMinY() - (n >> 1), r.getWidth() + n, r.getHeight() + n);
    944944        }
    945945
     
    973973                int originX = v.Origin.x;
    974974                int originY = v.Origin.y;
    975                 Color defaultForeground = v.Foreground;
    976                 Color defaultBackground = v.Background;
     975                Colour defaultForeground = v.Foreground;
     976                Colour defaultBackground = v.Background;
    977977                UserAppliedPermission permission = v.permission;
    978978                // TODO should this be checking if the frame has the
     
    10141014         * @return List of (unique)widgets in items. Never null.
    10151015         */
    1016         public static List<InteractiveWidget> extractWidgets(List<Item> items) {
     1016        public static List<Widget> extractWidgets(List<Item> items) {
    10171017                assert (items != null);
    10181018
    1019                 List<InteractiveWidget> iWidgets = new LinkedList<InteractiveWidget>();
     1019                List<Widget> iWidgets = new LinkedList<Widget>();
    10201020
    10211021                for (Item i : items) {
     
    10531053         * @param frame
    10541054         */
    1055         public static void Justify(Frame frame) {
     1055        public static void Justify(Frame frame)
     1056        {
     1057                if (frame == null) return;
    10561058                EnclosedCheck(frame.getItems());
    10571059                Justify(frame.getItems());
  • trunk/src/org/expeditee/items/JSItem.java

    r1080 r1102  
    1919package org.expeditee.items;
    2020
    21 import java.awt.Graphics2D;
    22 import java.awt.Polygon;
    2321import java.util.LinkedList;
    2422import java.util.List;
     
    2927import javax.script.ScriptException;
    3028
    31 import org.expeditee.gui.DisplayIO;
    32 import org.expeditee.items.widgets.InteractiveWidget;
     29import org.expeditee.Util;
     30import org.expeditee.core.bounds.AxisAlignedBoxBounds;
     31import org.expeditee.gui.DisplayController;
    3332
    3433public class JSItem extends XRayable implements JSThreadable {
     
    6463   
    6564        private static Text getSauce(int width, int height) {
    66                 Text source = new Text(DisplayIO.getCurrentFrame().getNextItemID(), "@js: " + width + " " + height);
    67                 source.setParent(DisplayIO.getCurrentFrame());
     65                Text source = new Text(DisplayController.getCurrentFrame().getNextItemID(), "@js: " + width + " " + height);
     66                source.setParent(DisplayController.getCurrentFrame());
    6867                return source;
    6968        }
     
    115114
    116115        @Override
    117         public void paint(Graphics2D g) {
    118                 try {
    119                 this.invocable.invokeFunction("paint", (Object)g);
     116        public void paint(/*Graphics2D g*/) {
     117                try {
     118                        // Not sure of the consequences of changing this? cts16
     119                //this.invocable.invokeFunction("paint", (Object)g);
     120                        this.invocable.invokeFunction("paint");
    120121        } catch (Exception e) {
    121122                e.printStackTrace();
     
    130131
    131132        @Override
    132         public void updatePolygon() {
    133                 _poly = new Polygon();
    134                 _poly.addPoint(getX(), getY());
    135                 _poly.addPoint(getX() + _width, getY());
    136                 _poly.addPoint(getX() + _width, getY() + _height);
    137                 _poly.addPoint(getX(), getY() + _height);
     133        public AxisAlignedBoxBounds updateBounds()
     134        {
     135                return new AxisAlignedBoxBounds(getX(), getY(), _width, _height);
    138136        }
    139137       
     
    158156                        return;
    159157                }
    160                 String[] args = InteractiveWidget.parseArgs(text.substring(index));
     158                String[] args = Util.parseArgs(text.substring(index));
    161159                try {
    162160                        this.scriptEngine.eval("load = " + this.load);
     
    189187                newText.append(_width).append(" ").append(_height);
    190188               
    191                 String stateArgs = InteractiveWidget.formatArgs(saveArgs());
     189                String stateArgs = Util.formatArgs(saveArgs());
    192190                if (stateArgs != null) {
    193191                        newText.append(':');
     
    239237        }
    240238
     239        @Override
     240        public float getSize() {
     241                // TODO Auto-generated method stub
     242                return 0;
     243        }
     244
    241245}
  • trunk/src/org/expeditee/items/Line.java

    r919 r1102  
    1919package org.expeditee.items;
    2020
    21 import java.awt.BasicStroke;
    22 import java.awt.Color;
    23 import java.awt.Graphics2D;
    24 import java.awt.Point;
    25 import java.awt.Polygon;
    26 import java.awt.Rectangle;
    27 import java.awt.RenderingHints;
    28 import java.awt.Shape;
    29 import java.awt.Stroke;
    30 import java.awt.geom.AffineTransform;
    31 import java.awt.geom.Point2D;
    3221import java.util.ArrayList;
    3322import java.util.Collection;
     
    3726import java.util.List;
    3827
    39 import org.expeditee.gui.DisplayIO;
     28import org.expeditee.core.Colour;
     29import org.expeditee.core.Dimension;
     30import org.expeditee.core.Fill;
     31import org.expeditee.core.Point;
     32import org.expeditee.core.Stroke;
     33import org.expeditee.core.bounds.AxisAlignedBoxBounds;
     34import org.expeditee.core.bounds.CombinationBoxBounds;
     35import org.expeditee.core.bounds.PolygonBounds;
     36import org.expeditee.gio.EcosystemManager;
     37import org.expeditee.gio.GraphicsManager;
     38import org.expeditee.gui.DisplayController;
    4039import org.expeditee.gui.Frame;
    4140import org.expeditee.gui.FrameGraphics;
     
    5958
    6059       
    61         public static Polygon createArrowheadPolygon(double x0, double y0, float arrowLength0, double arrowRatio0, double arrowNibPerc0)
     60        public static PolygonBounds createArrowheadPolygon(double x0, double y0, float arrowLength0, double arrowRatio0, double arrowNibPerc0)
    6261        {
    63                
    64                 Polygon arrowhead = new Polygon();
     62                PolygonBounds arrowhead = new PolygonBounds();
    6563           
    6664                int ix0 = (int)Math.round(x0);
     
    7371                int flange_iy_left = (int) Math.round((y0 - flange_y_width));
    7472                int flange_iy_right = (int) Math.round((y0 + flange_y_width));
    75                                
    76                
    77                 arrowhead.addPoint(ix0, iy0);
    78                 arrowhead.addPoint(flange_ix_project, flange_iy_left);
    79                
    80                 arrowhead.addPoint(ix_nib, iy0);
    81                
    82                 arrowhead.addPoint(flange_ix_project, flange_iy_right);
     73               
     74                arrowhead.addPoint(new Point(ix0, iy0));
     75                arrowhead.addPoint(new Point(flange_ix_project, flange_iy_left));
     76                arrowhead.addPoint(new Point(ix_nib, iy0));
     77                arrowhead.addPoint(new Point(flange_ix_project, flange_iy_right));
    8378               
    8479                return arrowhead;
     
    9590
    9691        // brush strokes used for painting this line and highlighting
    97         private Stroke _lineStroke = new BasicStroke(DEFAULT_THICKNESS, CAP, JOIN, 4.0F);
     92        private Stroke _lineStroke = new Stroke(DEFAULT_THICKNESS, DEFAULT_CAP, DEFAULT_JOIN);
    9893
    9994        Stroke getStroke() {
     
    143138                        for (int i = 0; i < pattern.length; i++)
    144139                                dash[i] = (float) pattern[i];
    145                         _lineStroke = new BasicStroke(Math.max(thick,
    146                                         MINIMUM_PAINT_THICKNESS), CAP, JOIN, 10f, dash, 0.0f);
     140                        _lineStroke = new Stroke(Math.max(thick, MINIMUM_PAINT_THICKNESS), DEFAULT_CAP, DEFAULT_JOIN, dash, 0.0f);
    147141                } else {
    148                         _lineStroke = new BasicStroke(Math.max(thick,
    149                                         MINIMUM_PAINT_THICKNESS), CAP, JOIN);
    150                 }
    151 
    152                 updatePolygon();
     142                        _lineStroke = new Stroke(Math.max(thick, MINIMUM_PAINT_THICKNESS), DEFAULT_CAP, DEFAULT_JOIN);
     143                }
     144
     145                invalidateBounds();
    153146        }
    154147
     
    240233                        _start = start;
    241234                        _start.addLine(this);
    242                         updatePolygon();
     235                        invalidateBounds();
    243236                }
    244237        }
     
    258251                        _end = end;
    259252                        _end.addLine(this);
    260                         updatePolygon();
     253                        invalidateBounds();
    261254                }
    262255        }
     
    317310                        for (int i = 0; i < pattern.length; i++)
    318311                                dash[i] = (float) pattern[i];
    319                         _lineStroke = new BasicStroke(Math.max(thick, MINIMUM_THICKNESS),
    320                                         CAP, JOIN, 10f, dash, 0.0f);
     312                        _lineStroke = new Stroke(Math.max(thick, MINIMUM_THICKNESS), DEFAULT_CAP, DEFAULT_JOIN, dash, 0.0f);
    321313                } else
    322                         _lineStroke = new BasicStroke(Math.max(thick, MINIMUM_THICKNESS),
    323                                         CAP, JOIN);
     314                        _lineStroke = new Stroke(Math.max(thick, MINIMUM_THICKNESS), DEFAULT_CAP, DEFAULT_JOIN);
    324315
    325316                if (_start.getLinePattern() != pattern)
     
    333324
    334325        @Override
    335         public void paint(Graphics2D g) {
    336                 if (!isVisible())
    337                         return;
    338 
    339                 // Dont paint lines with thickness 0 if they are the border on a filled
    340                 // shape
    341                 if (dontPaint())
    342                         return;
    343 
    344                 g.setColor(getPaintColor());
     326        public void paint()
     327        {
     328                if (!isVisible()) return;
     329
     330                // Dont paint lines with thickness 0 if they are the border on a filled shape
     331                if (dontPaint()) return;
    345332
    346333                // if (this._mode == Item.SelectedMode.Disconnect)
    347334                // System.out.println("Disconnect mode!");
    348                 g.setStroke(_lineStroke);
    349335                // Get a path of points
    350                 int[][][] paths = getPaths();
    351                 for (int i = 0; i < paths.length; i++) {
    352                         int[][] path = paths[i];
    353                         int last = path[0].length - 1;
    354                         if (path[0][0] == path[0][last] && path[1][0] == path[1][last]) {
    355                                 g.drawPolygon(path[0], path[1], last);
    356                         } else {
    357                                 g.drawPolyline(path[0], path[1], last + 1);
    358                         }
    359                 }
     336                PolygonBounds[] paths = getPaths();
     337                for (PolygonBounds path : paths) {
     338                        EcosystemManager.getGraphicsManager().drawPolygon(path, null, null, 0.0f, null, getPaintColor(), _lineStroke);
     339                }
     340               
    360341                // paint the arrowhead (if necessary)
    361                 paintArrows(g);
    362 
    363                 if (showLineHighlight() && isHighlighted()) {
    364                         g.setColor(getHighlightColor());
    365                         g.setStroke(HIGHLIGHT_STROKE);
    366                         ((Graphics2D) g).draw(this.getArea());
     342                paintArrows();
     343
     344                if (shouldShowLineHighlight() && isHighlighted()) {
     345                        PolygonBounds poly = (PolygonBounds) getBounds();
     346                        EcosystemManager.getGraphicsManager().drawPolygon(poly, null, null, 0.0f, null, getHighlightColor(), HIGHLIGHT_STROKE);
    367347                }
    368348        }
     
    371351                // enable invisible shapes (for web browser divs) only when XRayMode is off
    372352                return getThickness() <= 0 && _start.isEnclosed()
    373                                 && (_start.getFillColor() != null || !FrameGraphics.isXRayMode());
    374         }
    375 
    376         protected int[][][] getPaths() {
     353                                && (_start.getFillColor() != null || !DisplayController.isXRayMode());
     354        }
     355
     356        protected PolygonBounds[] getPaths() {
    377357                List<List<Point>> pointPaths = new LinkedList<List<Point>>();
    378358                Collection<Line> visited = new HashSet<Line>();
     
    388368                }
    389369                // Put the paths into int arrays
    390                 int[][][] paths = new int[pointPaths.size()][][];
     370                PolygonBounds[] paths = new PolygonBounds[pointPaths.size()];
    391371                Iterator<List<Point>> iter = pointPaths.iterator();
    392372
    393373                for (int i = 0; i < paths.length; i++) {
    394374                        List<Point> pointPath = iter.next();
    395                         int[][] path = new int[2][pointPath.size()];
     375                        PolygonBounds path = new PolygonBounds();
    396376                        paths[i] = path;
    397377                        // Add all the x and y's to the array
    398                         for (int j = 0; j < path[0].length; j++) {
    399                                 path[0][j] = pointPath.get(j).x;
    400                                 path[1][j] = pointPath.get(j).y;
    401                         }
    402                 }
     378                        for (int j = 0; j < pointPath.size(); j++) {
     379                                path.addPoint(pointPath.get(j).x, pointPath.get(j).y);
     380                        }
     381                }
     382               
    403383                return paths;
    404384        }
    405385
    406         protected List<Point> getPath(Collection<Line> visited,
    407                         LinkedList<Line> toExplore) {
     386        protected List<Point> getPath(Collection<Line> visited, LinkedList<Line> toExplore)
     387        {
    408388                LinkedList<Point> points = new LinkedList<Point>();
    409389                // put the start item points into our list
     
    417397        }
    418398
    419         public void paintArrows(Graphics2D g) {
    420                 if (dontPaint())
    421                         return;
    422 
    423                 g.setColor(getPaintColor());
    424                 g.setStroke(new BasicStroke(getPaintThickness(), CAP,
    425                                 BasicStroke.JOIN_MITER));
    426                 paintArrow(g, getStartArrow());
    427                 paintArrow(g, getEndArrow());
    428 
     399        public void paintArrows()
     400        {
     401                if (dontPaint()) return;
     402
     403                paintArrow(getStartArrow());
     404                paintArrow(getEndArrow());
     405
     406                // TODO: What is a virtual spot? cts16
    429407                if (_virtualSpot != null) {
    430                         _virtualSpot.paint(g);
     408                        _virtualSpot.paint();
    431409                        invalidateVirtualSpot();
    432410                        _virtualSpot = null;
     
    456434         * @return
    457435         */
    458         private Shape getArrow(Item withArrow, Point startOffset, Point endOffset) {
    459                 boolean disconnectMode = withArrow._mode == Item.HighlightMode.Disconnect;
     436        private PolygonBounds getArrow(Item withArrow, Point startOffset, Point endOffset)
     437        {
     438                boolean disconnectMode = withArrow._highlightMode == Item.HighlightMode.Disconnect;
     439               
    460440                // only draw an arrowhead if necessary
    461                 if (!(this._mode == Item.HighlightMode.Disconnect && disconnectMode)
    462                                 && (!withArrow.hasVisibleArrow() || withArrow.getLines().size() > 1))
     441                if (    !(this._highlightMode == Item.HighlightMode.Disconnect && disconnectMode) &&
     442                                (!withArrow.hasVisibleArrow() || withArrow.getLines().size() > 1))
     443                {
    463444                        return null;
    464 
     445                }
     446               
    465447                int x0, x1, y0, y1;
    466448
     
    475457               
    476458                // set the size of the disconnect indicator arrowhead
    477                 if (this._mode == Item.HighlightMode.Disconnect) {
     459                if (this._highlightMode == Item.HighlightMode.Disconnect) {
    478460                        arrowLength  = 15;
    479461                        arrowRatio   = 0.3;
     
    494476                // The length of the line must at least be as long as the arrow or we
    495477                // wont show the arrow
    496                 if (length <= MINIMUM_ARROW_HEAD_LENGTH)
    497                         return null;
     478                if (length <= MINIMUM_ARROW_HEAD_LENGTH) return null;
     479               
    498480                if (arrowLength == AUTO_ARROWHEAD_LENGTH) {
    499481                        arrowLength = getAutoArrowheadLength(length);
     
    508490
    509491                // only calculate the arrowhead polygon if necessary
    510                 Polygon arrowhead = withArrow.getArrowhead();
     492                PolygonBounds arrowhead = withArrow.getArrowhead();
    511493                if (arrowhead == null || disconnectMode) {
    512                         arrowhead = createArrowheadPolygon(x0,y0,arrowLength,arrowRatio,arrowNibPerc);
     494                        arrowhead = createArrowheadPolygon(x0, y0, arrowLength, arrowRatio, arrowNibPerc);
    513495                       
    514496                        if (!disconnectMode)
    515                                 withArrow.setArrowhead(arrowhead);
    516                 }
     497                                withArrow.setArrowhead(new PolygonBounds(arrowhead));
     498                }
     499                arrowhead = arrowhead.clone();
    517500                double rad = calcAngle((float) x0, (float) y0, (float) x1, (float) y1);
    518                 arrowhead.translate((x0 + length) - arrowhead.xpoints[0], y0
    519                                 - arrowhead.ypoints[0]);
    520                 AffineTransform tx = AffineTransform.getRotateInstance(rad, x0, y0);
    521                
    522         int[] rx = new int[arrowhead.npoints];
    523         int[] ry = new int[arrowhead.npoints];
    524        
    525         for(int i = 0; i < arrowhead.npoints; i++){
    526             Point2D p = new Point2D.Double(arrowhead.xpoints[i], arrowhead.ypoints[i]);
    527             tx.transform(p,p);
    528             rx[i] = (int) p.getX();
    529             ry[i] = (int) p.getY();
    530         }
    531        
    532         return new Polygon(rx, ry, arrowhead.npoints);
     501                arrowhead.translate((x0 + length) - arrowhead.toArray()[0].x, y0 - arrowhead.toArray()[0].y);
     502                arrowhead.rotate(rad, x0, y0);
     503               
     504                return arrowhead;
    533505        }
    534506       
    535         public Polygon getStartArrow() {
    536                 return (Polygon) getArrow(_start, _startOffset, _endOffset);
     507        public PolygonBounds getStartArrow() {
     508                return getArrow(_start, _startOffset, _endOffset);
    537509        }
    538510       
    539         public Polygon getEndArrow() {
    540                 return (Polygon) getArrow(_end, _endOffset, _startOffset);
     511        public PolygonBounds getEndArrow() {
     512                return getArrow(_end, _endOffset, _startOffset);
    541513        }
    542514
     
    544516         * Based on code from DeSL (Arrow2D) http://sourceforge.net/projects/desl/
    545517         */
    546         private void paintArrow(Graphics2D g, Shape arrow) {
     518        private void paintArrow(PolygonBounds arrow)
     519        {
     520                Colour arrowColour = getPaintColor();
     521                Fill arrowFill = new Fill(arrowColour);
     522                Stroke arrowStroke = new Stroke(getPaintThickness(), DEFAULT_CAP, Stroke.JOIN.MITER);
    547523               
    548524                if(arrow == null) {
     
    557533                // ****
    558534               
    559                 g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    560                
    561                 g.draw(arrow);
    562                 g.fill(arrow);
     535                GraphicsManager g = EcosystemManager.getGraphicsManager();
     536               
     537                g.setAntialiasing(true);
     538                g.drawPolygon(arrow.close(), null, null, 0.0f, arrowFill, arrowColour, arrowStroke);
    563539       
    564540        }
     
    630606                return temp;
    631607        }
     608       
     609        public Item getEndPointToDisconnect(Point p)
     610        {
     611                return getEndPointToDisconnect(p.x, p.y);
     612        }
    632613
    633614        public Item getEndPointToDisconnect(int x, int y) {
     
    653634
    654635                if (distStart < NORMAL_THRESHHOLD) {
    655                         start._mode = Item.HighlightMode.Normal;
     636                        start._highlightMode = Item.HighlightMode.Normal;
    656637                        return start;
    657638                } else if (distEnd < NORMAL_THRESHHOLD) {
    658                         end._mode = Item.HighlightMode.Normal;
     639                        end._highlightMode = Item.HighlightMode.Normal;
    659640                        return end;
    660641                } else if (distStart < DISCONNECT_THRESHHOLD) {
    661642                        if (start.getLines().size() > 1
    662643                                        || start.getConstraints().size() > 0)
    663                                 start._mode = Item.HighlightMode.Disconnect;
     644                                start._highlightMode = Item.HighlightMode.Disconnect;
    664645                        else
    665                                 start._mode = Item.HighlightMode.Normal;
     646                                start._highlightMode = Item.HighlightMode.Normal;
    666647                        return start;
    667648                } else if (distEnd < DISCONNECT_THRESHHOLD) {
    668649                        if (end.getLines().size() > 1 || end.getConstraints().size() > 0)
    669                                 end._mode = Item.HighlightMode.Disconnect;
     650                                end._highlightMode = Item.HighlightMode.Disconnect;
    670651                        else
    671                                 end._mode = Item.HighlightMode.Normal;
     652                                end._highlightMode = Item.HighlightMode.Normal;
    672653                        return end;
    673654                }
     
    677658
    678659        @Override
    679         public int setHighlightColor() {
    680                 super.setHighlightColor();
    681 
    682                 return Item.UNCHANGED_CURSOR;
     660        public void setHighlightColorToDefault() {
     661                super.setHighlightColorToDefault();
     662
     663                //return Item.UNCHANGED_CURSOR;
    683664        }
    684665
     
    690671         */
    691672        @Override
    692         public void setColor(Color c) {
     673        public void setColor(Colour c) {
    693674                super.setColor(c);
    694675
     
    698679
    699680        @Override
    700         public Color getFillColor() {
     681        public Colour getFillColor() {
    701682                return _start.getFillColor();
    702683        }
     
    882863        private Item _virtualSpot = null;
    883864
    884         public void showVirtualSpot(Item orig, int mouseX, int mouseY) {
    885                 if (orig.getLines().size() != 1)
    886                         return;
     865        public void showVirtualSpot(Item orig, int mouseX, int mouseY)
     866        {
     867                if (orig.getLines().size() != 1) return;
    887868
    888869                // lines that are in 'connected' mode, also cannot be attached
    889                 if (orig.getLines().get(0).getOppositeEnd(orig).isFloating())
    890                         return;
     870                if (orig.getLines().get(0).getOppositeEnd(orig).isFloating()) return;
    891871
    892872                Item spot = new Dot(-1, orig.getX(), orig.getY());
    893873                Item.DuplicateItem(orig, spot);
    894874                spot.setThickness(Math.max(this.getThickness(), 5));
    895                 if (this.getColor() != Color.RED)
    896                         spot.setColor(Color.RED);
    897                 else
    898                         spot.setColor(Color.BLUE);
    899 
     875                if (!this.getColor().equals(Colour.RED)) {
     876                        spot.setColor(Colour.RED);
     877                } else {
     878                        spot.setColor(Colour.BLUE);
     879                }
     880               
    900881                // unhighlight all the dots
    901882                for (Item conn : getAllConnected()) {
    902883                        conn.setHighlightMode(Item.HighlightMode.None);
    903                 }
     884                        conn.setHighlightColorToDefault();
     885                }
     886
     887                // calculate nearest point on line from spot
     888                org.expeditee.core.Line line = new org.expeditee.core.Line(_start.getPosition(), _end.getPosition());
     889                Point nearest = line.getPointNearestTo(spot.getPosition());
     890
     891                // position spot on the line
     892                spot.setPosition(nearest);
     893                _virtualSpot = spot;
     894                invalidateVirtualSpot();
     895        }
     896
     897        public void showVirtualSpot(int mouseX, int mouseY) {
     898                Item spot = new Dot(mouseX, mouseY, -1);
     899                spot.setThickness(Math.max(this.getThickness(), 5));
     900                if (DEFAULT_HIGHLIGHT.equals(this.getColor()))
     901                        spot.setColor(ALTERNATE_HIGHLIGHT);
     902                else
     903                        spot.setColor(DEFAULT_HIGHLIGHT);
     904
     905
     906                // calculate nearest point on line from spot
     907                org.expeditee.core.Line line = new org.expeditee.core.Line(_start.getPosition(), _end.getPosition());
     908                Point nearest = line.getPointNearestTo(spot.getPosition());
     909
     910                // position spot on the line
     911                spot.setPosition(nearest);
     912                _virtualSpot = spot;
     913                invalidateVirtualSpot();
     914        }
     915
     916        public Item forceMerge(Item spot, int mouseX, int mouseY) {
    904917
    905918                // calculate nearest point on line from spot
     
    930943                // position spot on the line
    931944                spot.setPosition((int) x, (int) y);
    932                 _virtualSpot = spot;
    933                 invalidateVirtualSpot();
    934         }
    935 
    936         public void showVirtualSpot(int mouseX, int mouseY) {
    937                 Item spot = new Dot(mouseX, mouseY, -1);
    938                 spot.setThickness(Math.max(this.getThickness(), 5));
    939                 if (DEFAULT_HIGHLIGHT.equals(this.getColor()))
    940                         spot.setColor(ALTERNATE_HIGHLIGHT);
    941                 else
    942                         spot.setColor(DEFAULT_HIGHLIGHT);
    943 
    944                 // calculate nearest point on line from spot
    945                 double slope1;
    946                 double slope2;
    947                 double x, y;
    948 
    949                 slope1 = (_start.getY() - _end.getY() * 1.0)
    950                                 / (_start.getX() - _end.getX());
    951                 slope2 = -1 / slope1;
    952 
    953                 // if the line is horizontal
    954                 if (slope1 == 0) {
    955                         x = spot.getX();
    956                         y = _start.getY();
    957                         // if the line is vertical
    958                 } else if (slope2 == 0) {
    959                         x = _start.getX();
    960                         y = spot.getY();
    961                         // otherwise, the line is sloped
    962                 } else {
    963                         x = (-1 * slope2 * spot.getX() + spot.getY() - _start.getY() + slope1
    964                                         * _start.getX())
    965                                         / (slope1 - slope2);
    966                         y = slope1 * (x - _start.getX()) + _start.getY();
    967                 }
    968 
    969                 // position spot on the line
    970                 spot.setPosition((int) x, (int) y);
    971                 _virtualSpot = spot;
    972                 invalidateVirtualSpot();
    973         }
    974 
    975         public Item forceMerge(Item spot, int mouseX, int mouseY) {
    976 
    977                 // calculate nearest point on line from spot
    978                 double slope1;
    979                 double slope2;
    980                 double x, y;
    981 
    982                 slope1 = (_start.getY() - _end.getY() * 1.0)
    983                                 / (_start.getX() - _end.getX());
    984                 slope2 = -1 / slope1;
    985 
    986                 // if the line is horizontal
    987                 if (slope1 == 0) {
    988                         x = spot.getX();
    989                         y = _start.getY();
    990                         // if the line is vertical
    991                 } else if (slope2 == 0) {
    992                         x = _start.getX();
    993                         y = spot.getY();
    994                         // otherwise, the line is sloped
    995                 } else {
    996                         x = (-1 * slope2 * spot.getX() + spot.getY() - _start.getY() + slope1
    997                                         * _start.getX())
    998                                         / (slope1 - slope2);
    999                         y = slope1 * (x - _start.getX()) + _start.getY();
    1000                 }
    1001 
    1002                 // position spot on the line
    1003                 spot.setPosition((int) x, (int) y);
    1004945
    1005946                // Keep constraints
     
    1018959                Line temp = copy();
    1019960
    1020                 Frame currentFrame = DisplayIO.getCurrentFrame();
     961                Frame currentFrame = DisplayController.getCurrentFrame();
    1021962                temp.setID(currentFrame.getNextItemID());
    1022963                temp.setEndItem(_end);
     
    11011042
    11021043        @Override
    1103         public void updatePolygon() {
    1104                 _poly = new Polygon();
    1105 
    1106                 Rectangle one;
    1107                 Rectangle two;
     1044        public PolygonBounds updateBounds() {
     1045                PolygonBounds ret = new PolygonBounds();
     1046
     1047                AxisAlignedBoxBounds one;
     1048                AxisAlignedBoxBounds two;
    11081049
    11091050                /**
     
    11211062                        Item e = new Dot(_end.getX(), _end.getY(), -1);
    11221063
    1123                         one = s.getPolygon().getBounds();
    1124                         two = e.getPolygon().getBounds();
     1064                        one = AxisAlignedBoxBounds.getEnclosing(s.getBounds());
     1065                        two = AxisAlignedBoxBounds.getEnclosing(e.getBounds());
    11251066                } else {
    11261067                        Item s = new Dot(_start.getX(), _start.getY(), -1);
    11271068                        Item e = new Dot(_end.getX(), _end.getY(), -1);
    11281069
    1129                         one = e.getPolygon().getBounds();
    1130                         two = s.getPolygon().getBounds();
     1070                        one = AxisAlignedBoxBounds.getEnclosing(e.getBounds());
     1071                        two = AxisAlignedBoxBounds.getEnclosing(s.getBounds());
    11311072                        /*
    11321073                         * one = _end.getPolygon().getBounds(); two =
     
    11361077
    11371078                // if one is above two
    1138                 if (one.getY() < two.getY()) {
    1139                         _poly.addPoint((int) one.getMaxX(), (int) one.getMinY());
    1140                         _poly.addPoint((int) two.getMaxX(), (int) two.getMinY());
    1141                         _poly.addPoint((int) two.getMinX(), (int) two.getMaxY());
    1142                         _poly.addPoint((int) one.getMinX(), (int) one.getMaxY());
     1079                if (one.getMinY() < two.getMinY()) {
     1080                        ret.addPoint(one.getMaxX(), one.getMinY());
     1081                        ret.addPoint(two.getMaxX(), two.getMinY());
     1082                        ret.addPoint(two.getMinX(), two.getMaxY());
     1083                        ret.addPoint(one.getMinX(), one.getMaxY());
    11431084                        // if one is below two
    11441085                } else {
    1145                         _poly.addPoint((int) one.getMinX(), (int) one.getMinY());
    1146                         _poly.addPoint((int) two.getMinX(), (int) two.getMinY());
    1147                         _poly.addPoint((int) two.getMaxX(), (int) two.getMaxY());
    1148                         _poly.addPoint((int) one.getMaxX(), (int) one.getMaxY());
    1149                 }
    1150 
     1086                        ret.addPoint(one.getMinX(), one.getMinY());
     1087                        ret.addPoint(two.getMinX(), two.getMinY());
     1088                        ret.addPoint(two.getMaxX(), two.getMaxY());
     1089                        ret.addPoint(one.getMaxX(), one.getMaxY());
     1090                }
     1091               
     1092                return ret.close();
    11511093        }
    11521094
     
    11991141
    12001142        public double getLength() {
    1201                 return getLength(_start.getPosition(), _end.getPosition());
     1143                return Point.distanceBetween(_start.getPosition(), _end.getPosition());
    12021144        }
    12031145
     
    12101152        }
    12111153
    1212         public static double getLength(Point p1, Point p2) {
    1213                 return Point.distance(p1.x, p1.y, p2.x, p2.y);
    1214         }
    1215 
    1216         @Override
    1217         public Rectangle[] getDrawingArea() { // TODO: CACHE - LIKE UPDATE POLYGON
     1154/*      public static double getLength(Point p1, Point p2) {
     1155                return Point.distance(p1, p2);
     1156        }*/
     1157
     1158        @Override
     1159        public AxisAlignedBoxBounds getDrawingArea() { // TODO: CACHE - LIKE UPDATE POLYGON
    12181160
    12191161                float currentThickness = this.getThickness() + 4;
     
    12361178                y -= halfThickness;
    12371179
    1238                 Rectangle bounds = new Rectangle(x, y, w, h);
     1180                AxisAlignedBoxBounds bounds = new AxisAlignedBoxBounds(x, y, w, h);
    12391181
    12401182                // TODO: Cap bounds
     
    12571199                         overall as opposed to advanced/expensive calculations for getting exact
    12581200                         bounding box */
    1259                         Rectangle arrowBounds = new Rectangle(_end.getX() - nArrowLength,
     1201                        AxisAlignedBoxBounds arrowBounds = new AxisAlignedBoxBounds(_end.getX() - nArrowLength,
    12601202                                        _end.getY() - nArrowLength, 2 * nArrowLength,
    12611203                                        2 * nArrowLength);
     
    12631205                        if (currentThickness > 0.0f) {
    12641206
    1265                                 arrowBounds = new Rectangle(arrowBounds.x - halfThickness,
    1266                                                 arrowBounds.y - halfThickness, arrowBounds.width
    1267                                                                 + thickness, arrowBounds.height + thickness);
    1268                         }
    1269 
    1270                         return new Rectangle[] { bounds, arrowBounds };
     1207                                arrowBounds = new AxisAlignedBoxBounds(arrowBounds.getMinX() - halfThickness,
     1208                                                arrowBounds.getMinY() - halfThickness, arrowBounds.getWidth()
     1209                                                                + thickness, arrowBounds.getHeight() + thickness);
     1210                        }
     1211
     1212                        return bounds.combineWith(arrowBounds);
    12711213                } else {
    1272                         return new Rectangle[] { bounds };
     1214                        return bounds;
    12731215                }
    12741216
     
    12941236        public void scale(Float scale, int originX, int originY) {
    12951237        }
     1238
     1239        @Override
     1240        public float getSize()
     1241        {
     1242                return getThickness();
     1243        }
    12961244}
  • trunk/src/org/expeditee/items/MagneticConstraint/Actions/AttractTextAction.java

    r974 r1102  
    11package org.expeditee.items.MagneticConstraint.Actions;
    22
    3 import java.awt.Point;
    4 
     3import org.expeditee.core.Point;
    54import org.expeditee.gui.FrameUtils;
    65import org.expeditee.items.Item;
  • trunk/src/org/expeditee/items/MagneticConstraint/Actions/BackspaceAction.java

    r967 r1102  
    11package org.expeditee.items.MagneticConstraint.Actions;
    22
    3 import org.expeditee.gui.DisplayIO;
     3import org.expeditee.gui.DisplayController;
    44import org.expeditee.items.Item;
    55import org.expeditee.items.Text;
     
    1515                if(item.getParent() == null || !this.isSpIDERCodePage(item.getParent())) return false;
    1616                if(item == null || ((Text) item).isEmpty()) {
    17                         final Text temp = DisplayIO.getCurrentFrame().createNewText(".");
     17                        final Text temp = DisplayController.getCurrentFrame().createNewText(".");
    1818                        callback(temp);
    1919                        if(temp.getMagnetizedItemLeft() != -1)
    20                                 DisplayIO.setTextCursor((Text) temp.getParent().getItemWithID(temp.getMagnetizedItemLeft()), Text.END);
     20                                DisplayController.setTextCursor((Text) temp.getParent().getItemWithID(temp.getMagnetizedItemLeft()), Text.END);
    2121                        else if(temp.getMagnetizedItemTop() != -1)
    22                                 DisplayIO.setTextCursor((Text) temp.getParent().getItemWithID(temp.getMagnetizedItemTop()), Text.END);
     22                                DisplayController.setTextCursor((Text) temp.getParent().getItemWithID(temp.getMagnetizedItemTop()), Text.END);
    2323                        temp.delete();
    2424                        callback(temp);
    2525                        return true;
    26                 } else if(item.getMagnetizedItemLeft() != -1 && TextLogic.XIsBeforeCharacters((Text) item, DisplayIO.getMouseX())) {
     26                } else if(item.getMagnetizedItemLeft() != -1 && TextLogic.XIsBeforeCharacters((Text) item, DisplayController.getMouseX())) {
    2727                        new LastItemAction().exec(item);
    2828                        return true;
    29                 } else if(item.getMagnetizedItemTop() != -1 && TextLogic.XIsBeforeCharacters((Text) item, DisplayIO.getMouseX())) {
     29                } else if(item.getMagnetizedItemTop() != -1 && TextLogic.XIsBeforeCharacters((Text) item, DisplayController.getMouseX())) {
    3030                        callback(item);
    3131                        final Line currentLine = Line.getLineFromToken(item);
     
    3333                        if(lastLine != null && Paragraph.getParagraphFromLine(lastLine).contains(currentLine)) {
    3434                                lastLine.appendLine(currentLine);
    35                                 DisplayIO.setTextCursor((Text) item, Text.HOME);
     35                                DisplayController.setTextCursor((Text) item, Text.HOME);
    3636                                callback(item);
    3737                                return true;
  • trunk/src/org/expeditee/items/MagneticConstraint/Actions/DeleteAction.java

    r967 r1102  
    11package org.expeditee.items.MagneticConstraint.Actions;
    22
    3 import org.expeditee.gui.DisplayIO;
     3import org.expeditee.gui.DisplayController;
    44import org.expeditee.items.Item;
    55import org.expeditee.items.Text;
     
    1515                if(item.getParent() == null || !this.isSpIDERCodePage(item.getParent())) return false;
    1616                if(item == null || ((Text) item).isEmpty()) {
    17                         final Text temp = DisplayIO.getCurrentFrame().createNewText(".");
     17                        final Text temp = DisplayController.getCurrentFrame().createNewText(".");
    1818                        callback(temp);
    1919                        if(temp.getMagnetizedItemRight() != -1)
    20                                 DisplayIO.setTextCursor((Text) temp.getParent().getItemWithID(temp.getMagnetizedItemRight()), Text.HOME);
     20                                DisplayController.setTextCursor((Text) temp.getParent().getItemWithID(temp.getMagnetizedItemRight()), Text.HOME);
    2121                        else if(temp.getMagnetizedItemBottom() != -1)
    22                                 DisplayIO.setTextCursor((Text) temp.getParent().getItemWithID(temp.getMagnetizedItemBottom()), Text.HOME);
     22                                DisplayController.setTextCursor((Text) temp.getParent().getItemWithID(temp.getMagnetizedItemBottom()), Text.HOME);
    2323                        temp.delete();
    2424                        callback(temp);
    2525                        return true;
    26                 } else if(item.getMagnetizedItemRight() != -1 && TextLogic.XIsAfterCharacters((Text) item, DisplayIO.getMouseX())) {
     26                } else if(item.getMagnetizedItemRight() != -1 && TextLogic.XIsAfterCharacters((Text) item, DisplayController.getMouseX())) {
    2727                        new NextItemAction().exec(item);
    2828                        return true;
    29                 } else if(item.getMagnetizedItemBottom() != -1 && TextLogic.XIsAfterCharacters((Text) item, DisplayIO.getMouseX())) {
     29                } else if(item.getMagnetizedItemBottom() != -1 && TextLogic.XIsAfterCharacters((Text) item, DisplayController.getMouseX())) {
    3030                        callback(item);
    3131                        final Line currentLine = Line.getLineFromToken(item);
     
    3333                        if(nextLine != null && Paragraph.getParagraphFromLine(currentLine).contains(nextLine)) {
    3434                                currentLine.appendLine(nextLine);
    35                                 DisplayIO.setTextCursor((Text) item, Text.END);
     35                                DisplayController.setTextCursor((Text) item, Text.END);
    3636                                callback(item);
    3737                                return true;
  • trunk/src/org/expeditee/items/MagneticConstraint/Actions/DownALineAction.java

    r967 r1102  
    11package org.expeditee.items.MagneticConstraint.Actions;
    22
    3 import org.expeditee.gui.DisplayIO;
     3import org.expeditee.gui.DisplayController;
    44import org.expeditee.items.Item;
    55import org.expeditee.items.Text;
     
    1919                final int nextLineLength =
    2020                                nextLine.get(nextLine.size() - 1).getX() + nextLine.get(nextLine.size() - 1).getBoundsWidth() - nextLine.get(0).getX();
    21                 final int distanceThroughCurrentLine = DisplayIO.getMouseX() - startOfThisLine.getX();
     21                final int distanceThroughCurrentLine = DisplayController.getMouseX() - startOfThisLine.getX();
    2222                if(distanceThroughCurrentLine <= nextLineLength) {
    2323                        Item beneith = nextLine.get(0);
     
    4343                if(toMoveTo instanceof Text) {
    4444                        final Text asText = (Text) toMoveTo;
    45                         DisplayIO.setTextCursor(asText, Text.END);
    46                 } else DisplayIO.setCursorPosition(toMoveTo.getPosition(), false);
     45                        DisplayController.setTextCursor(asText, Text.END);
     46                } else DisplayController.setCursorPosition(toMoveTo.getPosition(), false);
    4747                return true;
    4848        }
  • trunk/src/org/expeditee/items/MagneticConstraint/Actions/LastItemAction.java

    r977 r1102  
    11package org.expeditee.items.MagneticConstraint.Actions;
    22
    3 import org.expeditee.gui.DisplayIO;
     3import org.expeditee.gui.DisplayController;
    44import org.expeditee.gui.FrameGraphics;
    55import org.expeditee.gui.FrameUtils;
     
    4444//                      DisplayIO.setCursorPosition(position.x + asText.getPixelBoundsUnion().width, position.y, false);
    4545//                      FrameGraphics.refresh(false);
    46                         DisplayIO.setTextCursor((Text)toMoveTo, Text.END);
     46                        DisplayController.setTextCursor((Text)toMoveTo, Text.END);
    4747                        if(FrameUtils.getCurrentItem() != toMoveTo) {
    4848                                Line.getLineFromToken(toMoveFrom).deltaX(1);
    4949                                moveCursor(toMoveTo, toMoveFrom);
    5050                        }
    51                 } else DisplayIO.setCursorPosition(toMoveTo.getPosition(), false);
     51                } else DisplayController.setCursorPosition(toMoveTo.getPosition(), false);
    5252                return true;
    5353        }
  • trunk/src/org/expeditee/items/MagneticConstraint/Actions/NextItemAction.java

    r967 r1102  
    11package org.expeditee.items.MagneticConstraint.Actions;
    22
    3 import org.expeditee.gui.DisplayIO;
     3import org.expeditee.gui.DisplayController;
    44import org.expeditee.items.Item;
    55import org.expeditee.items.Text;
     
    3434                        return false;
    3535                //System.err.println("Next item requests move to item with text: " + toMoveTo.getText());
    36                 DisplayIO.setTextCursor((Text)toMoveTo, Text.HOME);
     36                DisplayController.setTextCursor((Text)toMoveTo, Text.HOME);
    3737                return true;
    3838        }
  • trunk/src/org/expeditee/items/MagneticConstraint/Actions/RepelTextAction.java

    r974 r1102  
    11package org.expeditee.items.MagneticConstraint.Actions;
    22
    3 import java.awt.Point;
    4 
    5 import org.expeditee.gui.Browser;
     3import org.expeditee.core.Point;
     4import org.expeditee.gio.EcosystemManager;
    65import org.expeditee.gui.FrameUtils;
    76import org.expeditee.items.Item;
     
    4544                        return false;
    4645                } else {
    47                         final int charDistance = Browser._theBrowser.getFontMetrics(((Text)item).getFont()).stringWidth("X");
     46                        final int charDistance = EcosystemManager.getTextLayoutManager().getStringWidth(((Text)item).getFont(), "X");
    4847                        final Line tokensToMove = Line.getLineFromToken(item);
    4948                        tokensToMove.removeFirst();
  • trunk/src/org/expeditee/items/MagneticConstraint/Actions/RepelTextDownAction.java

    r967 r1102  
    11package org.expeditee.items.MagneticConstraint.Actions;
    22
    3 import java.awt.Point;
    4 
    5 import org.expeditee.gui.DisplayIO;
     3import org.expeditee.core.Point;
     4import org.expeditee.gui.DisplayController;
    65import org.expeditee.gui.FrameIO;
    76import org.expeditee.gui.FrameUtils;
     
    2827                                (FrameUtils.getCurrentItem().getPosition().equals(item.getPosition())
    2928                                && remainderOfLine.size() > 0
    30                                 && TextLogic.XIsTowardsRight(DisplayIO.getMouseX(), (Text) remainderOfLine.getFirst()))) {
     29                                && TextLogic.XIsTowardsRight(DisplayController.getMouseX(), (Text) remainderOfLine.getFirst()))) {
    3130                        remainderOfLine.removeFirst();
    3231                }
     
    4241                if(!remainderOfLine.isEmpty() && currentParagraph.contains(nextLine) && MergeSameLineParagraphCollisions) {
    4342                        nextLine.prependLine(remainderOfLine);
    44                         DisplayIO.setTextCursor((Text) remainderOfLine.getFirst(), Text.HOME);
     43                        DisplayController.setTextCursor((Text) remainderOfLine.getFirst(), Text.HOME);
    4544                        callback(remainderOfLine.getFirst());
    4645                        FrameIO.SaveFrame(remainderOfLine.getLast().getParent());
    4746                } else if(!remainderOfLine.isEmpty()) {
    4847                        newLineAt = currentParagraph.split(currentLine);
    49                         final Point first = remainderOfLine.getBoundingBox().getLocation();
     48                        final Point first = remainderOfLine.getBoundingBox().getTopLeft();
    5049                        for(final Item token : remainderOfLine) {
    5150                                double newX = token.getX() - first.getX() + newLineAt.getX();
    5251                                token.setPosition((float) newX, (float) newLineAt.getY());
    5352                        }
    54                         DisplayIO.setTextCursor((Text) remainderOfLine.getFirst(), Text.HOME);
     53                        DisplayController.setTextCursor((Text) remainderOfLine.getFirst(), Text.HOME);
    5554                        callback(remainderOfLine.getFirst());
    5655                        FrameIO.SaveFrame(remainderOfLine.getLast().getParent());
     
    5857                                //3a No. Move the cursor
    5958                        newLineAt = currentParagraph.split(currentLine);
    60                         DisplayIO.setCursorPosition(newLineAt);
     59                        DisplayController.setCursorPosition(newLineAt);
    6160                }
    6261               
  • trunk/src/org/expeditee/items/MagneticConstraint/Actions/UpALineAction.java

    r967 r1102  
    11package org.expeditee.items.MagneticConstraint.Actions;
    22
    3 import org.expeditee.gui.DisplayIO;
     3import org.expeditee.gui.DisplayController;
    44import org.expeditee.items.Item;
    55import org.expeditee.items.Text;
     
    1919                final int lastLineLength =
    2020                                lastLine.get(lastLine.size() - 1).getX() + lastLine.get(lastLine.size() - 1).getBoundsWidth() - lastLine.get(0).getX();
    21                 final int distanceThroughCurrentLine = DisplayIO.getMouseX() - startOfThisLine.getX();
     21                final int distanceThroughCurrentLine = DisplayController.getMouseX() - startOfThisLine.getX();
    2222                if(distanceThroughCurrentLine <= lastLineLength) {
    2323                        Item above = lastLine.get(0);
     
    3737                if(toMoveTo instanceof Text) {
    3838                        final Text asText = (Text) toMoveTo;
    39                         DisplayIO.setTextCursor(asText, Text.END);
    40                 } else DisplayIO.setCursorPosition(toMoveTo.getPosition(), false);
     39                        DisplayController.setTextCursor(asText, Text.END);
     40                } else DisplayController.setCursorPosition(toMoveTo.getPosition(), false);
    4141                return true;
    4242        }
  • trunk/src/org/expeditee/items/MagneticConstraint/Actions/VerticalTabAction.java

    r967 r1102  
    11package org.expeditee.items.MagneticConstraint.Actions;
    22
    3 import org.expeditee.gui.Browser;
    4 import org.expeditee.gui.DisplayIO;
     3import org.expeditee.gio.EcosystemManager;
     4import org.expeditee.gui.DisplayController;
    55import org.expeditee.items.Item;
    66import org.expeditee.items.MagneticConstraint.MagneticConstraintAction;
     
    1212        public boolean exec(final Item item) {
    1313                if(item.getParent() == null || !this.isSpIDERCodePage(item.getParent())) return false;
    14                 final int tabWidth = Browser._theBrowser.getFontMetrics(Browser._theBrowser.getFont()).stringWidth("          ");
     14                final int tabWidth = EcosystemManager.getTextLayoutManager().getStringWidth(null, "     ");
    1515                tab(item, tabWidth);
    1616                return true;
     
    2020        public boolean invert(Item item) {
    2121                if(item.getParent() == null || !this.isSpIDERCodePage(item.getParent())) return false;
    22                 final int tabWidth = -(Browser._theBrowser.getFontMetrics(Browser._theBrowser.getFont()).stringWidth("     "));
     22                final int tabWidth = -(EcosystemManager.getTextLayoutManager().getStringWidth(null, "     "));
    2323                tab(item, tabWidth);
    2424                return true;
     
    2727        private void tab(final Item item, final int tabWidth) {
    2828                if(item == null) {
    29                         DisplayIO.setCursorPosition(DisplayIO.getMouseX() + tabWidth, DisplayIO.getMouseY());
     29                        DisplayController.setCursorPosition(DisplayController.getMouseX() + tabWidth, DisplayController.getMouseY());
    3030                } else {
    3131                        final Line postTabLine = Line.getLineFromToken(item);
    3232                        postTabLine.deltaX(tabWidth);
    3333                        if(postTabLine.size() > 0)
    34                                 DisplayIO.setCursorPosition(postTabLine.get(0).getPosition());
     34                                DisplayController.setCursorPosition(postTabLine.get(0).getPosition());
    3535                }
    3636        }
  • trunk/src/org/expeditee/items/MagneticConstraint/Utilities/BoxLogic.java

    r963 r1102  
    11package org.expeditee.items.MagneticConstraint.Utilities;
    22
    3 import java.awt.Rectangle;
    43import java.util.Collection;
    54import java.util.LinkedList;
    65import java.util.List;
    76
     7import org.expeditee.core.bounds.AxisAlignedBoxBounds;
    88import org.expeditee.gui.Frame;
    99import org.expeditee.items.Dot;
     
    4040                        final int bottomPos = Math.max(canditate.getStartItem().getY(),
    4141                                        canditate.getEndItem().getY());
    42                         final Rectangle itemHitBox = item.getArea().getBounds();
    43                         if (topPos < itemHitBox.getY() && bottomPos > itemHitBox.getY()) {
    44                                 if (itemHitBox.getX() + itemHitBox.getWidth() > canditate
    45                                                 .getStartItem().getX()
    46                                                 && itemHitBox.getX() < canditate.getStartItem().getX()) {
     42                        final AxisAlignedBoxBounds itemHitBox = item.getBoundingBox();
     43                        if (topPos < itemHitBox.getMinY() && bottomPos > itemHitBox.getMinY()) {
     44                                if (itemHitBox.getMinX() + itemHitBox.getWidth() > canditate.getStartItem().getX() &&
     45                                                itemHitBox.getMinX() < canditate.getStartItem().getX())
     46                                {
    4747                                        return true;
    4848                                }
  • trunk/src/org/expeditee/items/MagneticConstraint/Utilities/Line.java

    r966 r1102  
    11package org.expeditee.items.MagneticConstraint.Utilities;
    22
    3 import java.awt.Rectangle;
    43import java.util.LinkedList;
    54
     5import org.expeditee.core.bounds.AxisAlignedBoxBounds;
    66import org.expeditee.items.Item;
    77
     
    1818       
    1919        public Line prependLine(final Line line) {
    20                 final int x = this.getBoundingBox().x;
    21                 final int width = line.getBoundingBox().width;
     20                final int x = this.getBoundingBox().getMinX();
     21                final int width = line.getBoundingBox().getWidth();
    2222                this.deltaX(width);
    2323                line.setX(x);
     
    2727       
    2828        public Line appendLine(final Line line) {
    29                 final int x = this.getBoundingBox().x;
    30                 final int width = this.getBoundingBox().width;
     29                final int x = this.getBoundingBox().getMinX();
     30                final int width = this.getBoundingBox().getWidth();
    3131                line.setX(x + width);
    3232                line.setY(this.getFirst().getY());
     
    8383        }
    8484       
    85         public Rectangle getBoundingBox() {
     85        public AxisAlignedBoxBounds getBoundingBox() {
    8686//              final Rectangle rect = new Rectangle(this.getFirst().getX(), this.getFirst().getY(), this.getFirst().getBoundsWidth(), this.getFirst().getBoundsHeight());
    8787//              for(final Item token : this)
    8888//                      rect.add(new Rectangle(token.getX(), token.getY(), token.getBoundsWidth(), token.getBoundsHeight()));
    8989//              return rect;
    90                 final Rectangle rect = this.getFirst().getArea().getBounds();
     90                final AxisAlignedBoxBounds rect = this.getFirst().getBoundingBox();
    9191                for(final Item token : this)
    92                         rect.add(token.getArea().getBounds());
     92                        rect.combineWith(token.getBoundingBox());
    9393                return rect;
    9494        }
  • trunk/src/org/expeditee/items/MagneticConstraint/Utilities/Paragraph.java

    r962 r1102  
    11package org.expeditee.items.MagneticConstraint.Utilities;
    22
    3 import java.awt.*;
    43import java.util.LinkedList;
     4
     5import org.expeditee.core.Point;
     6import org.expeditee.core.bounds.AxisAlignedBoxBounds;
    57import org.expeditee.items.Text;
    68
     
    3032        }
    3133       
    32         public Rectangle getBoundingBox() {
    33                 final Rectangle rect = new Rectangle();
    34                 for(final Line ln : this) rect.add(ln.getBoundingBox());
     34        public AxisAlignedBoxBounds getBoundingBox() {
     35                AxisAlignedBoxBounds rect = null;
     36                for(final Line ln : this) {
     37                        if (rect == null) rect = ln.getBoundingBox();
     38                        else rect.combineWith(ln.getBoundingBox());
     39                }
    3540                return rect;
    3641        }
     
    5055                if(nextLine == null) {
    5156                        //2a. No; then we simply need to calculate the position of where it would be and return that.
    52                         final Rectangle boundingBox = splitAt.getBoundingBox();
    53                         return new Point((int)boundingBox.getX(), (int)boundingBox.getMaxY() + lineHeight);
     57                        final AxisAlignedBoxBounds boundingBox = splitAt.getBoundingBox();
     58                        return new Point((int)boundingBox.getMinX(), (int)boundingBox.getMaxY() + lineHeight);
    5459                }
    5560                //3. Get paragraph starting from the next line
     
    5863                if(!this.containsAll(paragraphStartingAtNextLine)) {
    5964                        //4b. No; then we simply need to calculate the position of the next line and return that.
    60                         final Rectangle boundingBox = splitAt.getBoundingBox();
     65                        final AxisAlignedBoxBounds boundingBox = splitAt.getBoundingBox();
    6166                        return new Point(((Text) splitAt.getFirst()).getX(), (int)boundingBox.getMaxY() + lineHeight);
    6267                }
     
    6671                //6. Return the position of the new line we have made space for.
    6772               
    68                 final Rectangle boundingBox = splitAt.getBoundingBox();
     73                final AxisAlignedBoxBounds boundingBox = splitAt.getBoundingBox();
    6974                final int x = ((Text) splitAt.getFirst()).getX();
    7075                return new Point(x, (int)boundingBox.getMaxY() + lineHeight);
     
    7277       
    7378        private static int getLineHeight(final Line line) {
    74                 return (int) (line.get(0).getArea().getBounds().getHeight() * 1.2);
     79                return (int) (line.get(0).getBoundingBox().getHeight() * 1.2);
    7580        }
    7681       
     
    8994        private static boolean isInSameParagraph(final Line thisLine, final Line nextLine, final int lineHeight) {
    9095                if(!XGroupLogic.areInSameXGroup(thisLine.get(0), nextLine.get(0))) return false;
    91                 final Rectangle thisLineBoundingBox = thisLine.getBoundingBox();
    92                 final Rectangle nextLineBoundingBox = nextLine.getBoundingBox();
    93                 final Point toAdd = new Point(Math.min((int)thisLineBoundingBox.getX(),(int) nextLineBoundingBox.getX()), (int)thisLineBoundingBox.getMaxY() + lineHeight);
    94                 final Rectangle overlappingSection = new Rectangle(thisLineBoundingBox);
    95                 overlappingSection.add(toAdd);
     96                final AxisAlignedBoxBounds thisLineBoundingBox = thisLine.getBoundingBox();
     97                final AxisAlignedBoxBounds nextLineBoundingBox = nextLine.getBoundingBox();
     98                final Point toAdd = new Point(Math.min((int)thisLineBoundingBox.getMinX(),(int) nextLineBoundingBox.getMinX()), (int)thisLineBoundingBox.getMaxY() + lineHeight);
     99                final AxisAlignedBoxBounds overlappingSection = new AxisAlignedBoxBounds(thisLineBoundingBox);
     100                overlappingSection.combineWith(toAdd);
    96101                return overlappingSection.intersects(nextLineBoundingBox);
    97102        }
  • trunk/src/org/expeditee/items/MagneticConstraint/Utilities/TextLogic.java

    r963 r1102  
    11package org.expeditee.items.MagneticConstraint.Utilities;
    22
    3 import org.expeditee.gui.Browser;
    4 import org.expeditee.gui.DisplayIO;
     3import org.expeditee.gio.EcosystemManager;
     4import org.expeditee.gui.DisplayController;
    55import org.expeditee.items.Text;
    66
     
    99        public static boolean XIsTowardsRight(final int x, final Text text) {
    1010                if(text.getPixelBoundsUnion() == null) return false;
    11                 final double distanceThroughText = x - text.getPixelBoundsUnion().getX();
     11                final double distanceThroughText = x - text.getPixelBoundsUnion().getMinX();
    1212                return /*text.getText().length() == 1 ||*/ distanceThroughText > (text.getPixelBoundsUnion().getWidth() / 2);
    1313        }
     
    1515        public static boolean XIsTowardsLeft(final Text text, final int x) {
    1616                if(text.getPixelBoundsUnion() == null) return false;
    17                 final double distanceThroughText = x - text.getPixelBoundsUnion().getX();
     17                final double distanceThroughText = x - text.getPixelBoundsUnion().getMinX();
    1818                return distanceThroughText < (text.getPixelBoundsUnion().getWidth() / 2);
    1919        }
     
    2121        public static boolean XIsBeforeCharacters(final Text text, final int x) {
    2222                try {
    23                         final int firstLetterWidth = Browser._theBrowser.getFontMetrics(Browser._theBrowser.getFont()).stringWidth(text.getText().substring(0, 1));
    24                         final double distanceThroughText = x - text.getPixelBoundsUnion().getX();
     23                        final int firstLetterWidth = EcosystemManager.getTextLayoutManager().getStringWidth(null, text.getText().substring(0, 1));
     24                        final double distanceThroughText = x - text.getPixelBoundsUnion().getMinX();
    2525                        return firstLetterWidth > distanceThroughText;
    2626                } catch (NullPointerException e) {
     
    3333        public static boolean XIsAfterCharacters(final Text text, final int x) {
    3434                try {
    35                         final double distanceThroughText = x - text.getPixelBoundsUnion().getX();
     35                        final double distanceThroughText = x - text.getPixelBoundsUnion().getMinX();
    3636                        return distanceThroughText > text.getPixelBoundsUnion().getWidth();
    3737                } catch (NullPointerException e) {
     
    4141       
    4242        public static int GetInsertionIndexSelected(final Text text) {
    43                 return text.getCharPosition(0, DisplayIO.getMouseX()).getInsertionIndex();
     43                return text.getCharPosition(0, DisplayController.getMouseX()).getInsertionIndex();
    4444        }
    4545}
  • trunk/src/org/expeditee/items/Picture.java

    r1047 r1102  
    1919package org.expeditee.items;
    2020
    21 import java.awt.AlphaComposite;
    22 import java.awt.BasicStroke;
    23 import java.awt.Color;
    24 import java.awt.Graphics2D;
    25 import java.awt.Image;
    26 import java.awt.Point;
    27 import java.awt.Polygon;
    28 import java.awt.Rectangle;
    29 import java.awt.Shape;
    30 import java.awt.Stroke;
    31 import java.awt.Toolkit;
    32 import java.awt.geom.AffineTransform;
    33 import java.awt.geom.Point2D;
    34 import java.awt.image.BufferedImage;
    35 import java.awt.image.CropImageFilter;
    36 import java.awt.image.FilteredImageSource;
    37 import java.awt.image.ImageObserver;
    38 import java.awt.image.PixelGrabber;
    3921import java.io.File;
    4022import java.io.IOException;
    4123import java.text.DecimalFormat;
    42 
    43 import javax.imageio.ImageIO;
    44 import javax.swing.ImageIcon;
    4524
    4625import org.apache.commons.cli.CommandLine;
     
    4928import org.apache.commons.cli.Options;
    5029import org.apache.commons.cli.ParseException;
    51 import org.expeditee.gui.DisplayIO;
     30import org.expeditee.core.Clip;
     31import org.expeditee.core.Colour;
     32import org.expeditee.core.Dimension;
     33import org.expeditee.core.EnforcedClipStack.EnforcedClipKey;
     34import org.expeditee.core.Image;
     35import org.expeditee.core.Point;
     36import org.expeditee.core.Stroke;
     37import org.expeditee.core.bounds.AxisAlignedBoxBounds;
     38import org.expeditee.core.bounds.CombinationBoxBounds;
     39import org.expeditee.core.bounds.PolygonBounds;
     40import org.expeditee.gio.EcosystemManager;
     41import org.expeditee.gio.GraphicsManager;
     42import org.expeditee.gui.DisplayController;
    5243import org.expeditee.gui.FrameGraphics;
    5344import org.expeditee.gui.FrameIO;
    54 import org.expeditee.gui.FrameMouseActions;
    5545import org.expeditee.gui.FrameUtils;
    56 import org.expeditee.items.widgets.InteractiveWidget;
    57 import org.expeditee.stats.Logger;
    5846
    5947/**
     
    7563 */
    7664public class Picture extends XRayable {
     65       
     66        private static final float CROPPING_COMPOSITE_ALPHA = 0.5f;
    7767
    7868        private static final int MINIMUM_WIDTH = 10;
     
    114104        private String _fileName = null;
    115105
    116         // used to repaint animated GIF images, among other things.
    117         protected ImageObserver _imageObserver = null;
    118 
    119         protected Picture(Text source, ImageObserver observer, Image image) {
     106        protected Picture(Text source, Image image) {
    120107                super(source);
    121                 _imageObserver = observer;
    122108                _image = image;
    123109
     
    150136         *            screen.
    151137         */
    152         public Picture(Text source, String fileName, String path, String size,
    153                         ImageObserver observer) {
     138        public Picture(Text source, String fileName, String path, String size)
     139        {
    154140                super(source);
    155                 _imageObserver = observer;
    156141                _fileName = fileName;
    157142                _path = path;
     
    226211
    227212                // set the default values for start and end
    228                 _start.setLocation(0, 0);
     213                _start.set(0, 0);
    229214                if (_image == null)
    230                         _end.setLocation(0, 0);
     215                        _end.set(0, 0);
    231216                else
    232                         _end.setLocation(_image.getWidth(null), _image.getHeight(null));
     217                        _end.set(_image.getWidth(), _image.getHeight());
    233218                size = size.trim();
    234219                String sizeLower = size.toLowerCase();
     
    272257                try {
    273258                        if (size.length() == 0) {
    274                                 size = "" + _image.getWidth(null);
     259                                size = "" + _image.getWidth();
    275260                                _source.setText(getTagText() + size);
    276261                                return;
     
    293278        }
    294279
     280        public void setStartCrop(Point p)
     281        {
     282                if (p != null) setStartCrop(p.x, p.y);
     283        }
     284       
    295285        public void setStartCrop(int x, int y) {
    296286                invalidateCroppedArea();
    297287                _cropStart = new Point(x - getX(), y - getY());
    298288                invalidateCroppedArea();
     289        }
     290
     291        public void setEndCrop(Point p)
     292        {
     293                if (p != null) setEndCrop(p.x, p.y);
    299294        }
    300295
     
    312307                        int startY = getY() + topLeft.y - _highlightThickness;
    313308                        int border = 2 * _highlightThickness;
    314                         invalidate(new Rectangle(startX, startY, bottomRight.x - topLeft.x
    315                                         + 2 * border, bottomRight.y - topLeft.y + 2 * border));
     309                        // TODO: Why invalidate specific area just before invalidateAll? cts16
     310                        invalidate(new AxisAlignedBoxBounds(startX, startY,
     311                                        bottomRight.x - topLeft.x + 2 * border, bottomRight.y - topLeft.y + 2 * border));
    316312                        invalidateAll();
    317313                } else {
     
    325321        }
    326322
    327         public Point getBottomRightCrop() {
    328                 return new Point(Math.max(_cropStart.x, _cropEnd.x), Math.max(
    329                                 _cropStart.y, _cropEnd.y));
     323        public Point getBottomRightCrop()
     324        {
     325                return new Point(Math.max(_cropStart.x, _cropEnd.x), Math.max(_cropStart.y, _cropEnd.y));
    330326        }
    331327
     
    335331                invalidateCroppedArea();
    336332        }
    337 
    338         public boolean isCropTooSmall() {
    339                 if (_cropStart == null || _cropEnd == null)
    340                         return true;
     333       
     334        public boolean isBeingCropped()
     335        {
     336                return (_cropStart != null && _cropEnd != null);
     337        }
     338
     339        public boolean isCropTooSmall()
     340        {
     341                if (!isBeingCropped()) return true;
    341342
    342343                int cropWidth = Math.abs(_cropEnd.x - _cropStart.x);
     
    353354        }
    354355
    355         public void updatePolygon() {
     356        public PolygonBounds updateBounds()
     357        {
    356358                if (_image == null) {
    357359                        refresh();
     
    360362               
    361363                Point[] ori = new Point[4];
    362                 Point2D[] rot = new Point2D[4];
    363364                Point centre = new Point();
    364365
     
    393394                        centre.y = base_y + (bottomRight.y - topLeft.y) / 2;
    394395                       
    395                         Rectangle clip = new Rectangle(topLeft.x + base_x,
     396                        AxisAlignedBoxBounds clip = new AxisAlignedBoxBounds(topLeft.x + base_x,
    396397                                        topLeft.y + base_y, bottomRight.x - topLeft.x,
    397                                         bottomRight.y - topLeft.y).getBounds();
     398                                        bottomRight.y - topLeft.y);
    398399//                      _poly.addPoint((int) clip.getMinX() - 1, (int) clip.getMinY() - 1);
    399400//                      _poly.addPoint((int) clip.getMinX() - 1, (int) clip.getMaxY());
     
    408409                }
    409410               
    410                 AffineTransform.getRotateInstance(Math.PI * _rotate / 180, centre.x, centre.y).transform(ori, 0, rot, 0, 4);
    411                
    412                 _poly = new Polygon();
    413                 for(Point2D p : rot) {
    414                         _poly.addPoint((int)p.getX(), (int)p.getY());
    415                 }
     411                PolygonBounds poly = new PolygonBounds();
     412                for (Point p : ori) {
     413                        poly.addPoint(p);
     414                }
     415                poly.rotate(Math.PI * _rotate / 180, centre);
     416               
     417                return poly.close();
    416418        }
    417419
     
    454456         */
    455457        @Override
    456         protected void paintLink(Graphics2D g) {
    457                 if (FrameGraphics.isAudienceMode())
    458                         return;
    459                 super.paintLink(g);
    460         }
    461        
    462         public void paintImageTiling(Graphics2D g) {
    463                 if (_image == null) {
    464                         return;
    465                 }
    466                
    467                 int iw = _image.getWidth(null);
    468                 int ih = _image.getHeight(null);
    469                 if(iw <= 0 || ih <= 0) {
    470                         return;
    471                 }
    472                
    473                 int base_x = (_anchorLeft!=null) ? _anchorLeft : _source.getX();
    474                 int base_y = (_anchorTop!=null) ? _anchorTop : _source.getY();
     458        protected void paintLink()
     459        {
     460                if (DisplayController.isAudienceMode()) return;
     461                super.paintLink();
     462        }
     463       
     464        /**
     465         * Paint the image repeatedly tiled over the drawing area.
     466         */
     467        public void paintImageTiling()
     468        {       
     469                if (_image == null) return;
     470               
     471                int iw = _image.getWidth();
     472                int ih = _image.getHeight();
     473                if(iw <= 0 || ih <= 0) return;
     474               
     475                int base_x = (_anchorLeft != null) ? _anchorLeft : _source.getX();
     476                int base_y = (_anchorTop != null) ? _anchorTop : _source.getY();
    475477               
    476478                int dX1 = base_x;
     
    479481                int dY2 = base_y + getHeight();
    480482               
    481                 BufferedImage tmp = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
    482                 Graphics2D g2d = tmp.createGraphics();
     483                Image tmp = Image.createImage(getWidth(), getHeight());
     484                EcosystemManager.getGraphicsManager().pushDrawingSurface(tmp);
     485
    483486                int offX = (tmp.getWidth() - getWidth()) / 2;
    484487                int offY = (tmp.getHeight() - getHeight()) / 2;
    485                
    486                 // g2d.rotate(rotate, tmp.getWidth() / 2, tmp.getHeight() / 2);
    487488               
    488489                int cropStartX = _start.x;
     
    491492                cropEndX = iw;
    492493        }
     494       
    493495                for(int x = dX1; x < dX2; ) {
    494496                        // end - start = (cropEnd - cropStart) * scale
     
    506508                        cropEndY = ih;
    507509                }
     510               
    508511                        for(int y = dY1; y < dY2; ) {
    509512                                int h = (int) ((cropEndY - cropStartY) * _scale);
     
    518521                                int sy = _flipY ? cropEndY : cropStartY;
    519522                                int ey = _flipY ? cropStartY : cropEndY;
    520                                 g2d.drawImage(_image, x - dX1 + offX, y - dY1 + offY, endX - dX1 + offX, endY - dY1 + offY, sx, sy, ex, ey, null);
     523                               
     524                                Point topLeft = new Point(x - dX1 + offX, y - dY1 + offY);
     525                                Dimension size = new Dimension(endX - x, endY - y);
     526                                Point cropTopLeft = new Point(sx, sy);
     527                                Dimension cropSize = new Dimension(ex - sx, ey - sy);
     528                                if (cropSize.width > 0 && cropSize.height > 0) {
     529                                        EcosystemManager.getGraphicsManager().drawImage(_image, topLeft, size, 0.0, cropTopLeft, cropSize);
     530                                }
    521531                               
    522532                                cropStartY = 0;
     
    531541                        x = endX;
    532542                }
    533                
    534                 AffineTransform at = new AffineTransform();
    535                 at.translate(dX1, dY1);
    536                 at.rotate(Math.PI * _rotate / 180, tmp.getWidth() / 2, tmp.getHeight() / 2);
    537                 g.drawImage(tmp, at, _imageObserver);
    538                 // g.drawImage(tmp, dX1, dY1, dX2, dY2, 0, 0, tmp.getWidth(), tmp.getHeight(), _imageObserver);
    539         }
    540 
    541         @Override
    542         public void paint(Graphics2D g) {
    543                 if (_image == null)
    544                         return;
    545 
    546                 paintLink(g);
    547 
    548                 // if we are showing the cropping, then show the original as transparent
     543
     544                EcosystemManager.getGraphicsManager().popDrawingSurface();
     545                EcosystemManager.getGraphicsManager().drawImage(tmp, new Point(dX1, dY1), null, Math.PI * _rotate / 180);
     546                tmp.releaseImage();
     547        }
     548
     549        @Override
     550        public void paint()
     551        {
     552                if (_image == null) return;
     553
     554                paintLink();
     555               
     556                GraphicsManager g = EcosystemManager.getGraphicsManager();
     557
     558                // if we are showing the cropping
    549559                if (_showCropping && !isCropTooSmall()) {
    550                         // show the full image as transparent
    551                         float alpha = .5f;
    552                         g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
    553                                         alpha));
    554                        
    555                         paintImageTiling(g);
    556 
    557                         g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
    558                                         1.0f));
     560                        // show the uncropped area as transparent
     561                        g.setCompositeAlpha(CROPPING_COMPOSITE_ALPHA);
     562                        paintImageTiling();
     563                        g.setCompositeAlpha(1.0f);
     564                       
    559565                        // show the cropped area normally
    560566                        Point topLeft = getTopLeftCrop();
    561567                        Point bottomRight = getBottomRightCrop();
    562                         int base_x = (_anchorLeft!=null) ? _anchorLeft : _source.getX();
    563                         int base_y = (_anchorTop!=null) ? _anchorTop : _source.getY();
    564                        
    565                         Shape clip = new Rectangle(base_x + topLeft.x, base_y + topLeft.y,
    566                                         bottomRight.x - topLeft.x, bottomRight.y - topLeft.y);
    567                         g.setColor(getPaintHighlightColor());
    568                         g.draw(clip);
    569                         g.setClip(clip);
    570 
    571                         paintImageTiling(g);
    572                        
    573                         g.draw(clip);
    574                         // if the image is cropped, but we are not showing the cropping
    575                         // otherwise, paint normally
     568                        int base_x = (_anchorLeft != null) ? _anchorLeft : _source.getX();
     569                        int base_y = (_anchorTop != null) ? _anchorTop : _source.getY();
     570                       
     571                        Clip clip = new Clip(new AxisAlignedBoxBounds(  base_x + topLeft.x,
     572                                                                                                                                        base_y + topLeft.y,
     573                                                                                                                                        bottomRight.x - topLeft.x,
     574                                                                                                                                        bottomRight.y - topLeft.y));
     575                        EnforcedClipKey key = g.pushClip(clip);
     576                        paintImageTiling();
     577                        g.popClip(key);
     578
     579                        // Draw an outline for the crop selection box
     580                        g.drawRectangle(clip.getBounds(), 0.0, null, getPaintHighlightColor(), HIGHLIGHT_STROKE, null);
     581
     582                // otherwise, paint normally
    576583                } else {
    577                         paintImageTiling(g);
    578                 }
    579 
     584                        paintImageTiling();
     585                }
     586
     587                PolygonBounds poly = (PolygonBounds) getBounds();
     588               
    580589                if (hasVisibleBorder()) {
    581                         g.setColor(getPaintBorderColor());
    582                         Stroke borderStroke = new BasicStroke(getThickness(), CAP, JOIN);
    583                         g.setStroke(borderStroke);
    584                         g.drawPolygon(getPolygon());
     590                        Stroke borderStroke = new Stroke(getThickness(), DEFAULT_CAP, DEFAULT_JOIN);
     591                        g.drawPolygon(poly, null, null, 0.0, null, getPaintBorderColor(), borderStroke);
    585592                }
    586593
    587594                if (isHighlighted()) {
    588                         Stroke borderStroke = new BasicStroke(1, CAP, JOIN);
    589                         g.setStroke(borderStroke);
    590                         g.setColor(getHighlightColor());
    591                         g.drawPolygon(getPolygon());
    592                 }
    593                
    594                 //System.out.print("p_");       
    595         }
    596 
    597         @Override
    598         public Color getHighlightColor() {
    599                 if (_highlightColor.equals(getBorderColor()))
    600                         return ALTERNATE_HIGHLIGHT;
    601                 return _highlightColor;
    602         }
    603 
    604         @Override
    605         public int setHighlightColor() {
    606                 super.setHighlightColor();
    607 
    608                 return Item.DEFAULT_CURSOR;
    609         }
    610 
    611         protected Picture createPicture() {
    612                 return ItemUtils.CreatePicture((Text) _source.copy(), _imageObserver);
     595                        Stroke borderStroke = new Stroke(1, DEFAULT_CAP, DEFAULT_JOIN);
     596                        g.drawPolygon(poly, null, null, 0.0, null, getHighlightColor(), borderStroke);
     597                }
     598        }
     599
     600        @Override
     601        public Colour getHighlightColor()
     602        {
     603                if (_highlightColour.equals(getBorderColor())) return ALTERNATE_HIGHLIGHT;
     604                return _highlightColour;
     605        }
     606
     607        protected Picture createPicture()
     608        {
     609                return ItemUtils.CreatePicture((Text) _source.copy());
    613610        }
    614611
     
    617614                Picture p = createPicture();
    618615                p._image = _image;
    619                 p._mode = _mode;
     616                p._highlightMode = _highlightMode;
    620617                // Doing Duplicate item duplicates link mark which we dont want to do
    621618                // when in audience mode because the linkMark will be copied incorrectly
     
    632629                        int endX = Math.round(bottomRight.x / _scale + _start.x);
    633630                        int endY = Math.round(bottomRight.y / _scale + _start.y);
    634                         int width = _image.getWidth(null);
    635                         int height = _image.getHeight(null);
     631                        int width = _image.getWidth();
     632                        int height = _image.getHeight();
    636633                        // adjust our start and end if the user has dragged outside of the
    637634                        // shape
     
    663660
    664661                p.updateSource();
    665                 p.updatePolygon();
     662                p.invalidateBounds();
    666663
    667664                return p;
     
    678675        public void scaleCrop() {
    679676                // scale crop values to within image bounds
    680                 int iw = _image.getWidth(null);
    681                 int ih = _image.getHeight(null);
     677                int iw = _image.getWidth();
     678                int ih = _image.getHeight();
    682679                if(iw > 0 || ih > 0) {
    683680                        while(_start.x >= iw) {
     
    723720                        _scale = oldScale;
    724721                } else {
    725                         _source.translate(new Point2D.Float(FrameMouseActions.MouseX,
    726                                         FrameMouseActions.MouseY), multiplier);
     722                        _source.translate(EcosystemManager.getInputManager().getCursorPosition(), multiplier);
    727723                }
    728724                updateSource();
    729                 updatePolygon();
     725                invalidateBounds();
    730726                // Make sure items that are resized display the border
    731727                invalidateAll();
     
    753749                }
    754750               
    755                 return Toolkit.getDefaultToolkit().createImage(
    756                                 new FilteredImageSource(_image.getSource(),
    757                                                 new CropImageFilter(_start.x, _start.y,
    758                                                                 getUnscaledWidth(), getUnscaledHeight())));
     751                return Image.createImageAsCroppedCopy(_image, _start.x, _start.y, getUnscaledWidth(), getUnscaledHeight());
    759752        }
    760753
     
    771764         */
    772765        public boolean isCropped() {
    773                 return (_end.x != 0 && _end.x != _image.getWidth(null)) || (_end.y != 0 && _end.y != _image.getHeight(null)) || _start.y != 0 || _start.x != 0;
     766                return (_end.x != 0 && _end.x != _image.getWidth()) || (_end.y != 0 && _end.y != _image.getHeight()) || _start.y != 0 || _start.x != 0;
    774767        }
    775768
     
    779772                // (notably.bmp) hence, we try this first, then if it fails we try
    780773                // ImageIO
     774                /*
    781775                try {
    782776                        _image = new ImageIcon(_path).getImage();
     
    785779
    786780                // if ImageIcon failed to read the image
    787                 if (_image == null || _image.getWidth(null) <= 0) {
     781                if (_image == null || _image.getWidth() <= 0) {
    788782                        try {
    789783                                _image = ImageIO.read(new File(_path));
     
    795789                        }
    796790                }
     791*/
     792                _image = Image.getImage(_path);
    797793                return true;
    798794        }
     
    827823        @Override
    828824        public boolean getLinkMark() {
    829                 return !FrameGraphics.isAudienceMode() && _source.getLinkMark();
     825                return !DisplayController.isAudienceMode() && _source.getLinkMark();
    830826        }
    831827
     
    892888                // If the image is cropped add the position for the start and finish of
    893889                // the crop to the soure text
    894                 if (_start.x > 0 || _start.y > 0 || _end.x != _image.getWidth(null)
    895                                 || _end.y != _image.getHeight(null)) {
     890                if (_start.x > 0 || _start.y > 0 || _end.x != _image.getWidth()
     891                                || _end.y != _image.getHeight()) {
    896892                        newText.append(" ").append(_start.x).append(" ").append(_start.y);
    897893                        newText.append(" ").append(_end.x).append(" ").append(_end.y);
     
    912908
    913909        @Override
    914         public void translate(Point2D origin, double ratio) {
     910        public void translate(Point origin, double ratio) {
    915911                _scale *= ratio;
    916912                updateSource();
     
    919915
    920916        @Override
    921         public Rectangle[] getDrawingArea() {
    922 
    923                 Rectangle[] da = super.getDrawingArea();
     917        public AxisAlignedBoxBounds getDrawingArea() {
     918
     919                AxisAlignedBoxBounds da = super.getDrawingArea();
    924920
    925921                if (getLink() != null || hasAction()) {
    926                         Rectangle[] da2 = new Rectangle[da.length + 1];
    927                         System.arraycopy(da, 0, da2, 0, da.length);
    928                         da2[da.length] = getLinkPoly().getBounds();
    929                         da2[da.length].translate(getX() - LEFT_MARGIN, getY()
    930                                         + getLinkYOffset());
    931                         da2[da.length].width += 2;
    932                         da2[da.length].height += 2;
    933                         da = da2;
     922                        AxisAlignedBoxBounds linkBounds = AxisAlignedBoxBounds.getEnclosing(getLinkBounds());
     923                        linkBounds.getTopLeft().add(getX() - LEFT_MARGIN, getY() + getLinkYOffset());
     924                        linkBounds.getSize().width += 2;
     925                        linkBounds.getSize().height += 2;
     926                        da.combineWith(linkBounds);
    934927                }
    935928
     
    963956                _rotate = rotate;
    964957                updateSource();
    965                 updatePolygon();
     958                invalidateBounds();
    966959        }
    967960       
     
    970963        }
    971964
    972         public boolean MouseOverBackgroundPixel(int mouseX, int mouseY, Color bg_col)
    973         {
    974                 int[] pixels = new int[1];
    975                  
     965        public boolean MouseOverBackgroundPixel(int mouseX, int mouseY, Colour bg_col)
     966        {
    976967                int base_x = (_anchorLeft!=null) ? _anchorLeft : _source.getX();
    977968                int base_y = (_anchorTop!=null) ? _anchorTop : _source.getY();
     
    979970                int y = mouseY - base_y;
    980971               
    981                 // Consider making this a slightly larger area to check, say 3 x 3?
    982                 // Back op if all are the same sought after color?
    983                 PixelGrabber grabber = new PixelGrabber(_image, x,y, 1, 1, pixels, 0, 1);
    984                
    985                 // The following might be a better approach, as it sets the color model
    986                 // when getPixels() is called, however, it might return an int[] or byte[]
    987                 // array (handled as Object), as so some extra complexity would exist in
    988                 // handling the returned result
    989                
    990                 //PixelGrabber pg = new PixelGrabber(_image, mouseX, mouseY, 1, 1, true);
    991                
    992                 try {
    993                         grabber.grabPixels(0);
    994                 }
    995                 catch (Exception e) {
    996                         e.printStackTrace();
    997                 }
    998                
    999        
    1000                 int c = pixels[0];
    1001                 int c_red    = (c & 0x00ff0000) >> 16;
    1002                 int c_green  = (c & 0x0000ff00) >> 8;
    1003                 int c_blue   =  c & 0x000000ff;
    1004                
    1005                 int bg_red   = (bg_col!=null) ? bg_col.getRed()   : 0xff;
    1006                 int bg_green = (bg_col!=null) ? bg_col.getGreen() : 0xff;
    1007                 int bg_blue  = (bg_col!=null) ? bg_col.getBlue()  : 0xff;
     972                Colour c = _image.getPixel(x, y);
     973
     974                int c_red    = c.getRed255();
     975                int c_green  = c.getGreen255();
     976                int c_blue   = c.getBlue255();
     977               
     978                int bg_red   = (bg_col!=null) ? bg_col.getRed255()   : 0xff;
     979                int bg_green = (bg_col!=null) ? bg_col.getGreen255() : 0xff;
     980                int bg_blue  = (bg_col!=null) ? bg_col.getBlue255()  : 0xff;
    1008981               
    1009982                int red_diff   = Math.abs(c_red   - bg_red);
  • trunk/src/org/expeditee/items/Tooltip.java

    r977 r1102  
    99import org.expeditee.settings.templates.TemplateSettings;
    1010
     11/**
     12 * TODO: Comment. cts16
     13 *
     14 * @author cts16
     15 */
    1116public class Tooltip {
     17
     18        /** TODO: Comment. cts16 */
     19        private Map<Text, Item> _tooltipItems = new HashMap<Text, Item>();
    1220       
    13         Tooltip() { }
    14        
    15         private Map<Text, Item> tooltipItems = new HashMap<Text, Item>();
    16        
    17         public Text addTooltip(String content, final Item toItem) {
    18                 if(content.trim().toLowerCase().startsWith("text") && content.contains(":"))
     21        /** TODO: Comment. cts16 */
     22        Tooltip()
     23        {
     24        }
     25
     26        /** TODO: Comment. cts16 */
     27        public Text addTooltip(String content, final Item toItem)
     28        {
     29                if(content.trim().toLowerCase().startsWith("text") && content.contains(":")) {
    1930                        content = content.substring(content.indexOf(':') + 1);
     31                }
    2032                final Text tooltip = TemplateSettings.TooltipTemplate.get().copy();
     33                tooltip.setWidth(Integer.MAX_VALUE); // Tooltip shouldn't be width-limited
    2134                tooltip.setText(content);
    2235                return addTooltip(tooltip, toItem);
    2336        }
    24        
    25         public Text addTooltip(final Text tooltip, final Item toItem) {
    26                 tooltipItems.put(tooltip, toItem);
     37
     38        /** TODO: Comment. cts16 */
     39        public Text addTooltip(final Text tooltip, final Item toItem)
     40        {
     41                _tooltipItems.put(tooltip, toItem);
    2742                return tooltip;
    2843        }
    29        
    30         public Collection<Text> getTooltips() { return tooltipItems.keySet(); }
    31        
    32         public List<String> asStringList() {
     44
     45        /** TODO: Comment. cts16 */
     46        public Collection<Text> getTooltips()
     47        {
     48                return _tooltipItems.keySet();
     49        }
     50
     51        /** TODO: Comment. cts16 */
     52        public List<String> asStringList()
     53        {
    3354                final List<String> ret = new LinkedList<String>();
    34                 for(final Text tooltip: tooltipItems.keySet()) ret.add(tooltip.getText());
     55                for(final Text tooltip: _tooltipItems.keySet()) ret.add(tooltip.getText());
    3556                return ret;
    3657        }
    37        
    38         public int getWidth() {
     58
     59        /** TODO: Comment. cts16 */
     60        public int getWidth()
     61        {
    3962                int max = 0;
    40                 for(final Text tooltip: tooltipItems.keySet())
     63                for(final Text tooltip: _tooltipItems.keySet()) {
    4164                        if(tooltip.getBoundsWidth() > max) max = tooltip.getBoundsWidth();
     65                }
    4266                return max;
    4367        }
    4468
    45         public int getHeight() {
     69        /** TODO: Comment. cts16 */
     70        public int getHeight()
     71        {
    4672                int max = 0;
    47                 for(final Text tooltip: tooltipItems.keySet())
     73                for(final Text tooltip: _tooltipItems.keySet()) {
    4874                        if(tooltip.getBoundsWidth() > max) max = tooltip.getBoundsHeight();
     75                }
    4976                return max;
    5077        }
    51        
    52         public int getCollectiveHeight() {
     78
     79        /** TODO: Comment. cts16 */
     80        public int getCollectiveHeight()
     81        {
    5382                int height = 0;
    54                 for(final Text tooltip: tooltipItems.keySet()) height += tooltip.getBoundsHeight();
     83                for(final Text tooltip: _tooltipItems.keySet()) height += tooltip.getBoundsHeight();
    5584                return height;
    5685        }
  • trunk/src/org/expeditee/items/XRayable.java

    r919 r1102  
    1919package org.expeditee.items;
    2020
    21 import java.awt.Color;
    22 import java.awt.geom.Point2D;
    2321import java.util.Collection;
    2422import java.util.LinkedList;
    2523import java.util.List;
    2624
     25import org.expeditee.core.Colour;
     26import org.expeditee.core.Point;
     27import org.expeditee.gui.DisplayController;
    2728import org.expeditee.gui.FrameGraphics;
    2829
     
    101102       
    102103        @Override
    103         public Color getColor() {
     104        public Colour getColor() {
    104105                return _source.getColor();
    105106        }
    106107
    107108        @Override
    108         public void setColor(Color c) {
     109        public void setColor(Colour c) {
    109110                _source.setColor(c);
    110111                invalidateCommonTrait(ItemAppearence.ForegroundColorChanged);
     
    112113       
    113114        @Override
    114         public void setBackgroundColor(Color c) {
     115        public void setBackgroundColor(Colour c) {
    115116                _source.setBackgroundColor(c);
    116117        }
    117118       
    118119        @Override
    119         public void setFillColor(Color c) {
     120        public void setFillColor(Colour c) {
    120121                _source.setFillColor(c);
    121122        }
    122123       
    123124        @Override
    124         public void setBorderColor(Color c) {
     125        public void setBorderColor(Colour c) {
    125126                _source.setBorderColor(c);
    126127                invalidateCommonTrait(ItemAppearence.BorderColorChanged);
     
    128129       
    129130        @Override
    130         public void setGradientColor(Color c) {
     131        public void setGradientColor(Colour c) {
    131132                _source.setGradientColor(c);
    132133        }
     
    153154       
    154155        @Override
    155         public Float getAnchorLeft() {
     156        public Integer getAnchorLeft() {
    156157                return _source.getAnchorLeft();
    157158        }
    158159       
    159160        @Override
    160         public Float getAnchorRight() {
     161        public Integer getAnchorRight() {
    161162                return _source.getAnchorRight();
    162163        }
    163164
    164165        @Override
    165         public Float getAnchorTop() {
     166        public Integer getAnchorTop() {
    166167                return _source.getAnchorTop();
    167168        }
    168169
    169170        @Override
    170         public Float getAnchorBottom() {
     171        public Integer getAnchorBottom() {
    171172                return _source.getAnchorBottom();
    172173        }
     
    174175       
    175176        @Override
    176         public Color getBorderColor() {
     177        public Colour getBorderColor() {
    177178                return _source.getBorderColor();
    178179        }
     
    186187       
    187188        @Override
    188         public Color getBackgroundColor() {
     189        public Colour getBackgroundColor() {
    189190                return _source.getBackgroundColor();
    190191        }
    191192       
    192193        @Override
    193         public Color getFillColor() {
     194        public Colour getFillColor() {
    194195                return _source.getFillColor();
    195196        }
    196197       
    197198        @Override
    198         public Color getGradientColor() {
     199        public Colour getGradientColor() {
    199200                return _source.getGradientColor();
    200201        }
     
    226227                        invalidateAll();
    227228                _source.setLink(frameName);
    228                 updatePolygon();
     229                invalidateBounds();
    229230                //TODO: only invalidate the link bit
    230231                invalidateAll();
     
    239240                        invalidateAll();
    240241                _source.setActions(action);
    241                 updatePolygon();
     242                invalidateBounds();
    242243                invalidateAll();
    243244        }
     
    252253       
    253254        @Override
    254         public void translate(Point2D origin, double ratio){
     255        public void translate(Point origin, double ratio){
    255256                //_source.translate(origin, ratio);
    256                 updatePolygon();
     257                invalidateBounds();
    257258        }
    258259       
     
    279280
    280281        @Override
    281         public void setAnchorTop(Float anchor) {
     282        public void setAnchorTop(Integer anchor) {
    282283                _source.setAnchorTop(anchor);
    283284                if (anchor != null)
     
    286287
    287288        @Override
    288         public void setAnchorBottom(Float anchor) {
     289        public void setAnchorBottom(Integer anchor) {
    289290                _source.setAnchorBottom(anchor);
    290291                if (anchor != null)
    291                         _source.setY(FrameGraphics.getMaxFrameSize().height - getHeight() - anchor);
    292         }
    293 
    294        
    295         @Override
    296         public void setAnchorLeft(Float anchor) {
     292                        _source.setY(DisplayController.getFramePaintArea().getHeight() - getHeight() - anchor);
     293        }
     294
     295       
     296        @Override
     297        public void setAnchorLeft(Integer anchor) {
    297298                _source.setAnchorLeft(anchor);
    298299        }
    299300
    300301        @Override
    301         public void setAnchorRight(Float anchor) {
     302        public void setAnchorRight(Integer anchor) {
    302303                _source.setAnchorRight(anchor);
    303                 _source.setX(FrameGraphics.getMaxFrameSize().width - anchor - this.getWidth());
     304                _source.setX(DisplayController.getFramePaintArea().getWidth() - anchor - this.getWidth());
    304305        }
    305306       
  • trunk/src/org/expeditee/items/widgets/ButtonWidget.java

    r1005 r1102  
    11package org.expeditee.items.widgets;
    22import java.awt.BorderLayout;
    3 import java.awt.Color;
    43import java.awt.Dimension;
    54import java.net.URL;
     
    98import javax.swing.border.EmptyBorder;
    109
     10import org.expeditee.core.Colour;
     11import org.expeditee.gio.swing.SwingConversions;
    1112import org.expeditee.items.Text;
    1213
     
    1415
    1516//Will be the default class for Rubbish Bin, Reset and Undo Button Widgets
    16 public class ButtonWidget extends InteractiveWidget{
    17 
     17public class ButtonWidget extends SwingWidget
     18{
    1819        protected JButton clicked_ = new JButton("");   
    1920        protected SVGIcon icon_ = null;
    20        
     21
    2122        public ButtonWidget(int dimension, String filePath, Text source, String[] args)
    2223        {
     
    2526                               
    2627                clicked_.setBorder(new EmptyBorder(0, 0, 0, 0));
    27                 clicked_.setBackground(Color.white);
     28                clicked_.setBackground(SwingConversions.toSwingColor(Colour.WHITE));
    2829               
    2930                Dimension size = new Dimension(dimension, dimension);
    3031                icon_ = new SVGIcon();
    31                 try{
     32               
     33                try {
    3234                        URL imageURL = ClassLoader.getSystemResource(filePath);         
    3335                        icon_.setSvgURI(imageURL.toURI());
    34                         //This STILL works, unsure why. Don't remove it has an affect on the button appearance.         
     36                        // This STILL works, unsure why. Don't remove it has an affect on the button appearance.
    3537                        icon_.setUseAntiAlias(true);
    3638                        icon_.setScaleToFit(true);
     
    3941                        _swingComponent.add(clicked_);
    4042                        this.setWidgetEdgeThickness(0.0f);
    41                         this.setWidgetEdgeColor(Color.white);   
    42                 }
    43                 catch(Exception e){
    44                        
     43                        this.setWidgetEdgeColor(Colour.WHITE); 
     44                } catch(Exception e) {
    4545                        //Set a default image if image is missing
    4646                        System.out.println("Unable to load image from directory");                     
     
    4949
    5050        @Override
    51         protected String[] getArgs() {
     51        protected String[] getArgs()
     52        {
    5253                // TODO Auto-generated method stub
    5354                return null;
    5455        }
    55         public boolean itemHeldWhileClicked(InteractiveWidget bw) {
     56       
     57        public boolean itemHeldWhileClicked(Widget bw)
     58        {
    5659                // TODO Auto-generated method stub
    5760                return false;
    5861        }
    59         public boolean getdropInteractableStatus(){
     62       
     63        public boolean getdropInteractableStatus()
     64        {
    6065                return false;
    6166        }
    6267
    6368        @Override
    64         boolean setPositions(WidgetCorner src, float x, float y) {
     69        public boolean setPositions(WidgetCorner src, float x, float y)
     70        {
    6571                boolean result = super.setPositions(src, x, y);
    6672
  • trunk/src/org/expeditee/items/widgets/DataFrameWidget.java

    r919 r1102  
    1919package org.expeditee.items.widgets;
    2020
    21 import java.awt.Color;
    22 import java.awt.Graphics;
    2321import java.util.Collection;
    2422import java.util.HashSet;
     
    2624import javax.swing.JComponent;
    2725
    28 import org.expeditee.gui.DisplayIO;
     26import org.expeditee.core.Colour;
     27import org.expeditee.core.Point;
     28import org.expeditee.gio.EcosystemManager;
     29import org.expeditee.gio.GraphicsManager;
     30import org.expeditee.gui.DisplayController;
    2931import org.expeditee.gui.Frame;
    3032import org.expeditee.gui.FrameIO;
     
    3436import org.expeditee.items.Text;
    3537
    36 public abstract class DataFrameWidget extends InteractiveWidget implements
     38public abstract class DataFrameWidget extends SwingWidget implements
    3739                FrameObserver {
    3840
     
    118120        public void update() {
    119121                Frame parent = getParentFrame();
    120                 if (parent != null && parent == DisplayIO.getCurrentFrame()) {
     122                if (parent != null && parent == DisplayController.getCurrentFrame()) {
    121123                        refresh();
    122124                }
     
    166168        }
    167169
    168         protected void paintInFreeSpace(Graphics g) {
    169                 super.paintInFreeSpace(g);
    170                 g.setFont(((Text) getSource()).getFont());
    171                 g.setColor(Color.WHITE);
    172                 g.drawString(this.getClass().getSimpleName(), getX() + 10, getY() + 20);
     170        protected void paintInFreeSpace()
     171        {
     172                super.paintInFreeSpace();
     173                GraphicsManager g = EcosystemManager.getGraphicsManager();
     174                g.drawString(this.getClass().getSimpleName(), new Point(getX() + 10, getY() + 20), ((Text) getSource()).getFont(), Colour.WHITE);
    173175
    174176        }
  • trunk/src/org/expeditee/items/widgets/HeavyDutyInteractiveWidget.java

    r1046 r1102  
    1919package org.expeditee.items.widgets;
    2020
    21 import java.awt.Color;
    2221import java.awt.Font;
    2322import java.awt.FontMetrics;
     
    3332import javax.swing.SwingUtilities;
    3433
     34import org.expeditee.core.Colour;
     35import org.expeditee.gio.swing.SwingConversions;
     36import org.expeditee.gio.swing.SwingGraphicsManager;
     37import org.expeditee.gio.swing.SwingMiscManager;
    3538import org.expeditee.gui.Browser;
    36 import org.expeditee.gui.DisplayIO;
    37 import org.expeditee.gui.FrameGraphics;
     39import org.expeditee.gui.DisplayController;
    3840import org.expeditee.gui.FreeItems;
    3941import org.expeditee.items.Item;
     
    5355 * until expeditee allocates a thread to begin loading. The swing component is set as not-visible.
    5456 *
    55  * At the the loading stage, a loadable widget proccesses its load task and renders a
     57 * At the the loading stage, a loadable widget processes its load task and renders a
    5658 * load message/bar.
    5759 *
     
    5961 *
    6062 * When a HeavyDutyInteractiveWidget becomes visible / is anchored, it will register itself for saving at the next
    61  * save point according to SaveEntityManager. Heavey duty widgets will only save at the save points
     63 * save point according to SaveEntityManager. Heavy duty widgets will only save at the save points
    6264 * if the widget still belongs to a frame (i.e. is not removed) and is anchored.
    6365 *
    64  * Heavey duty widgets can also have an expiry on how long they should stay cached for. If they do have an
     66 * Heavy duty widgets can also have an expiry on how long they should stay cached for. If they do have an
    6567 * expiry then it they unload once expired, and will re-load once in view again. Must take care for
    6668 * unloadable widgets because you must check your unloadable elements to whether they are unloaded or not
    67  * every time your widget accessess them.
     69 * every time your widget accesses them.
    6870 *
    6971 * When a heavy duty widget is deleted - any data consuming memory can be dumped temporarily if needed.
     
    7274 *
    7375 */
    74 public abstract class HeavyDutyInteractiveWidget extends InteractiveWidget implements LoadableEntity, SaveableEntity {
     76public abstract class HeavyDutyInteractiveWidget extends SwingWidget implements LoadableEntity, SaveableEntity {
    7577       
    7678        /** load finished */
     
    9092        private static final String PENDING_MESSAGE = "Pending";
    9193       
    92         private static final Color LOAD_BAR_PROGRESS_COLOR = new Color(103, 171, 203);
    93         private static final Color LOAD_BAR_INDETERM_COLOR = Color.ORANGE;
    94         private static final Color LOAD_BAR_HIGHLIGHT_COLOR = new Color(240, 240, 240);
    95         private static final Color LOAD_SCREEN_COLOR = Color.LIGHT_GRAY;
    96         private static final Color LOAD_SCREEN_COLOR_FREESPACE = FREESPACE_BACKCOLOR;
     94        private static final Colour LOAD_BAR_PROGRESS_COLOR = Colour.FromRGB255(103, 171, 203);
     95        private static final Colour LOAD_BAR_INDETERM_COLOR = Colour.ORANGE;
     96        private static final Colour LOAD_BAR_HIGHLIGHT_COLOR = Colour.FromRGB255(240, 240, 240);
     97        private static final Colour LOAD_SCREEN_COLOR = Colour.LIGHT_GREY;
     98        private static final Colour LOAD_SCREEN_COLOR_FREESPACE = FREESPACE_BACKCOLOR;
    9799       
    98100        private static final Font LOAD_NORMAL_FONT = new Font("Arial", Font.BOLD, 12);
     
    140142         */
    141143        protected HeavyDutyInteractiveWidget(Text source, JComponent component,
    142                         int minWidth, int maxWidth, int minHeight, int maxHeight, int cacheDepth, boolean skipLoad) {
     144                        int minWidth, int maxWidth, int minHeight, int maxHeight, int cacheDepth, boolean skipLoad)
     145        {
    143146                super(source, component, minWidth, maxWidth, minHeight, maxHeight);
    144147               
     
    173176         *
    174177         * @param percent
    175          *              Must be between 0.0 and 1.0 inclusive for percentage. Or neagtive if indeterminant.
     178         *              Must be between 0.0 and 1.0 inclusive for percentage. Or negative if indeterminate.
    176179         *
    177180         * @throws IllegalArgumentException
     
    182185         *             
    183186         */
    184         protected final void updateLoadPercentage(float percent) {
     187        protected final void updateLoadPercentage(float percent)
     188        {
    185189                if (percent > 1.0f)
    186190                        throw new IllegalArgumentException("loadState is larger than 1.0");
     
    199203         * @return The current load state.
    200204         */
    201         protected float getLoadState() {
     205        protected float getLoadState()
     206        {
    202207                return loadState;
    203208        }
     
    206211         * @return True if in a loading phase.
    207212         */
    208         protected boolean isInLoadProgress() {
     213        protected boolean isInLoadProgress()
     214        {
    209215                return loadState <= 1.0f;
    210216        }
     
    226232               
    227233                // Re-render loading state
    228                 FrameGraphics.invalidateArea(_swingComponent.getBounds());
    229                 FrameGraphics.requestRefresh(true);
     234                DisplayController.invalidateArea(getBounds());
     235                DisplayController.requestRefresh(true);
    230236        }
    231237       
    232238        @Override
    233         public void paintInFreeSpace(Graphics g) {
    234                 if (loadState == LOAD_STATE_COMPLETED) super.paintInFreeSpace(g);
    235                 else paintLoadScreen(g, LOAD_SCREEN_COLOR_FREESPACE);
     239        public void paintInFreeSpace() {
     240                if (loadState == LOAD_STATE_COMPLETED) super.paintInFreeSpace();
     241                else paintLoadScreen(LOAD_SCREEN_COLOR_FREESPACE);
    236242        }
    237243
    238244        @Override
    239         public void paint(Graphics g) {
     245        protected final void paintSwingWidget(Graphics2D g)
     246        {
    240247                if (loadState == LOAD_STATE_COMPLETED) {
    241                         super.paint(g);
     248                        paintHeavyDutyWidget(g);
    242249                } else {
    243                         paintLoadScreen(g, LOAD_SCREEN_COLOR);
    244                         this.paintLink((Graphics2D)g);
    245                 }
    246                
    247         }
    248        
    249         /**
    250          * Rendersthe load bar / load messages
     250                        paintLoadScreen(LOAD_SCREEN_COLOR);
     251                }
     252               
     253        }
     254       
     255        /** Can be overridden to provide custom drawing. */
     256        protected void paintHeavyDutyWidget(Graphics2D g)
     257        {
     258                super.paintSwingWidget(g);
     259        }
     260       
     261        /**
     262         * Renders the load bar / load messages
    251263         *
    252264         * @param g
    253265         */
    254         private void paintLoadScreen(Graphics g, Color backgroundColor) {
     266        private void paintLoadScreen(Colour backgroundColor) {
    255267
    256268                if (Browser._theBrowser == null) return;
    257269               
     270                SwingGraphicsManager manager = SwingMiscManager.getIfUsingSwingGraphicsManager();
     271                Graphics g = manager.getCurrentSurface();
     272               
    258273                // Render shaded window over widget
    259                 g.setColor(backgroundColor);
     274                g.setColor(SwingConversions.toSwingColor(backgroundColor));
    260275                g.fillRect(getX(), getY(), getWidth(), getHeight());
    261276               
     
    291306                Rectangle tmpClip = (clipBackUp != null) ? clipBackUp.getBounds() :
    292307                        new Rectangle(0, 0,
    293                                         Browser._theBrowser.getContentPane().getWidth(),
    294                                         Browser._theBrowser.getContentPane().getHeight());
    295                        
    296                 g.setClip(tmpClip.intersection(getBounds()));
     308                                        manager.getContentPane().getWidth(),
     309                                        manager.getContentPane().getHeight());
     310                       
     311                g.setClip(tmpClip.intersection(SwingConversions.toSwingRectangle(getBounds())));
    297312       
    298313               
     
    300315
    301316                        GradientPaint gp = new GradientPaint(
    302                                         0, barY + (int)(BAR_HEIGHT * 0.8), LOAD_BAR_INDETERM_COLOR,
    303                                         0, barY, LOAD_BAR_HIGHLIGHT_COLOR);
     317                                        0, barY + (int)(BAR_HEIGHT * 0.8), SwingConversions.toSwingColor(LOAD_BAR_INDETERM_COLOR),
     318                                        0, barY, SwingConversions.toSwingColor(LOAD_BAR_HIGHLIGHT_COLOR));
    304319                        ((Graphics2D)g).setPaint(gp);
    305320               
     
    311326                       
    312327                        GradientPaint gp = new GradientPaint(
    313                                         0, barY + (int)(BAR_HEIGHT * 0.8), LOAD_BAR_PROGRESS_COLOR,
    314                                         0, barY, LOAD_BAR_HIGHLIGHT_COLOR);
     328                                        0, barY + (int)(BAR_HEIGHT * 0.8), SwingConversions.toSwingColor(LOAD_BAR_PROGRESS_COLOR),
     329                                        0, barY, SwingConversions.toSwingColor(LOAD_BAR_HIGHLIGHT_COLOR));
    315330                        ((Graphics2D)g).setPaint(gp);
    316331                       
     
    319334                }
    320335               
    321                 g.setColor(Color.DARK_GRAY);
     336                g.setColor(SwingConversions.toSwingColor(Colour.DARK_GREY));
    322337                g.drawRect(barX, barY, barWidth, BAR_HEIGHT);
    323338               
    324339                if (loadState == LOAD_STATE_FAILED)
    325                         g.setColor(Color.RED);
    326                
    327                 else g.setColor(Color.BLACK);
     340                        g.setColor(SwingConversions.toSwingColor(Colour.RED));
     341               
     342                else g.setColor(SwingConversions.toSwingColor(Colour.BLACK));
    328343               
    329344
     
    638653                        // Re-render loading state - if not expired
    639654                        if (!expired) {
    640                                 FrameGraphics.invalidateArea(new Rectangle(getX(), getY(), getWidth(), getHeight()));
    641                                 FrameGraphics.requestRefresh(true);
     655                                DisplayController.invalidateArea(getBounds());
     656                                DisplayController.requestRefresh(true);
    642657                        }
    643658                }
     
    680695                       
    681696                        // Only load if in view
    682                         if (!isFloating() && getParentFrame() != DisplayIO.getCurrentFrame())
     697                        if (!isFloating() && getParentFrame() != DisplayController.getCurrentFrame())
    683698                                return;
    684699                       
  • trunk/src/org/expeditee/items/widgets/JSWidget.java

    r1080 r1102  
    3232import javax.swing.JPanel;
    3333
    34 import org.expeditee.gui.DisplayIO;
     34import org.expeditee.gui.DisplayController;
    3535import org.expeditee.items.ItemParentStateChangedEvent;
    3636import org.expeditee.items.JSThreadable;
     
    7575   
    7676        private static Text getSauce() {
    77                 Text source = new Text(DisplayIO.getCurrentFrame().getNextItemID(), "@iw: org.expeditee.items.widgets.JSWidget");
    78                 source.setParent(DisplayIO.getCurrentFrame());
     77                Text source = new Text(DisplayController.getCurrentFrame().getNextItemID(), "@iw: org.expeditee.items.widgets.JSWidget");
     78                source.setParent(DisplayController.getCurrentFrame());
    7979                return source;
    8080        }
     
    172172   
    173173    @Override
    174         protected void paintLink(Graphics2D g) {
     174        protected void paintLink() {
    175175        return;
    176176        }
  • trunk/src/org/expeditee/items/widgets/JfxBrowser.java

    r1060 r1102  
    7676import netscape.javascript.JSObject;
    7777
    78 import org.expeditee.gui.DisplayIO;
    79 import org.expeditee.gui.FrameMouseActions;
     78import org.expeditee.gio.gesture.StandardGestureActions;
     79import org.expeditee.gio.swing.SwingConversions;
     80import org.expeditee.gui.DisplayController;
    8081import org.expeditee.gui.FreeItems;
    8182import org.expeditee.gui.MessageBay;
     
    468469                                public void handle(KeyEvent e) {
    469470                                        // Hiding the cursor when typing, to be more Expeditee-like
    470                                         DisplayIO.setCursor(org.expeditee.items.Item.HIDDEN_CURSOR);
     471                                        DisplayController.setCursor(org.expeditee.items.Item.HIDDEN_CURSOR);
    471472                                }
    472473                        });
     
    481482                                        }
    482483                                        // Checking if the user has been typing - if so, move the cursor to the caret position
    483                                         if (DisplayIO.getCursor() == Item.HIDDEN_CURSOR) {
    484                                                 DisplayIO.setCursor(org.expeditee.items.Item.TEXT_CURSOR);
    485                                                 DisplayIO.setCursorPosition(getCoordFromCaret(JfxBrowser.this._urlField));
     484                                        if (DisplayController.getCursor() == Item.HIDDEN_CURSOR) {
     485                                                DisplayController.setCursor(org.expeditee.items.Item.TEXT_CURSOR);
     486                                                DisplayController.setCursorPosition(SwingConversions.fromSwingPoint(getCoordFromCaret(JfxBrowser.this._urlField)));
    486487                                        } else {
    487488                                                // Otherwise, move the caret to the cursor location
     
    523524                public void changed(ObservableValue<? extends Boolean> property, Boolean oldValue, Boolean newValue) {
    524525                                        if(newValue.booleanValue()) {
    525                                                 DisplayIO.setCursor(org.expeditee.items.Item.TEXT_CURSOR);
     526                                                DisplayController.setCursor(org.expeditee.items.Item.TEXT_CURSOR);
    526527                                        } else {
    527528                                                // Restoring the standard cursor, since it is changed to a text cursor when focus is gained
    528                                                 DisplayIO.setCursor(org.expeditee.items.Item.DEFAULT_CURSOR);
     529                                                DisplayController.setCursor(org.expeditee.items.Item.DEFAULT_CURSOR);
    529530                                        }
    530531                }
     
    545546                                        if (e.getButton() == MouseButton.SECONDARY) {
    546547                                                // Right mouse button released, so copy the selection (i.e. don't remove the original)
    547                                                 item = DisplayIO.getCurrentFrame().createNewText(JfxBrowser.this._urlField.getSelectedText());
    548                                                 FrameMouseActions.pickup(item);
     548                                                item = DisplayController.getCurrentFrame().createNewText(JfxBrowser.this._urlField.getSelectedText());
     549                                                StandardGestureActions.pickup(item);
    549550                                        } else if (e.getButton() == MouseButton.MIDDLE) {
    550551                                                // Middle mouse button released, so copy the selection then remove it from the URL field
    551                                                 item = DisplayIO.getCurrentFrame().createNewText(JfxBrowser.this._urlField.getSelectedText());
     552                                                item = DisplayController.getCurrentFrame().createNewText(JfxBrowser.this._urlField.getSelectedText());
    552553                                                JfxBrowser.this._urlField.setText(
    553554                                                                JfxBrowser.this._urlField.getText().substring(0, JfxBrowser.this._urlField.getSelection().getStart())
     
    555556                                                                                JfxBrowser.this._urlField.getText().length()));
    556557
    557                                                 FrameMouseActions.pickup(item);
     558                                                StandardGestureActions.pickup(item);
    558559                                        }
    559560                }
     
    660661                                                                       
    661662                                                                        if (((String) style.call("getPropertyValue", new Object[] { "background-image" })).startsWith("url(")) {
    662                                                                                 pic = WebParser.getBackgroundImageFromNode(node, style, DisplayIO.getCurrentFrame(), null,
    663                                                                                         (float) FrameMouseActions.getX(), (float) FrameMouseActions.getY(), width, height);
     663                                                                                pic = WebParser.getBackgroundImageFromNode(node, style, DisplayController.getCurrentFrame(), null,
     664                                                                                        (float) DisplayController.getMouseX(), (float) DisplayController.getMouseY(), width, height);
    664665                                                                               
    665666                                                                        } else {
     
    667668                                                                                if(node.getNodeName().toLowerCase().equals("img") &&
    668669                                                                                                (imgSrc = ((JSObject) node).getMember("src").toString()) != null) {
    669                                                                                         pic = WebParser.getImageFromUrl(imgSrc, null, DisplayIO.getCurrentFrame(),
    670                                                                                                         (float) FrameMouseActions.getX(), (float) FrameMouseActions.getY(), (int) width, null, null, null, null, null, 0, 0);
     670                                                                                        pic = WebParser.getImageFromUrl(imgSrc, null, DisplayController.getCurrentFrame(),
     671                                                                                                        (float) DisplayController.getMouseX(), (float) DisplayController.getMouseY(), (int) width, null, null, null, null, null, 0, 0);
    671672                                                                                } else {
    672673                                                                                        return;
     
    685686                                                                        }
    686687                                                                       
    687                                                                         pic.setXY(FrameMouseActions.getX(), FrameMouseActions.getY());
    688                                                 FrameMouseActions.pickup(pic);
     688                                                                        pic.setXY(DisplayController.getMouseX(), DisplayController.getMouseY());
     689                                                StandardGestureActions.pickup(pic);
    689690                                        } catch (Exception e1) {
    690691                                        // TODO Auto-generated catch block
     
    714715                                                                                        + ((JSObject)node).getMember("height")
    715716                                                                                        + ":" + src);
    716                                                                         t.setParent(DisplayIO.getCurrentFrame());
    717                                                                         t.setXY(FrameMouseActions.getX(), FrameMouseActions.getY());
     717                                                                        t.setParent(DisplayController.getCurrentFrame());
     718                                                                        t.setXY(DisplayController.getMouseX(), DisplayController.getMouseY());
    718719                                                                        JfxMedia media = new JfxMedia(t, new String[] { src });
    719                                                                         FrameMouseActions.pickup(media.getItems());
     720                                                                        StandardGestureActions.pickup(media.getItems());
    720721                                                                       
    721722                                                                } else if(node.getNodeName().toLowerCase().equals("a") && ((JSObject)node).getMember("href") != null) {
    722723                                                                        // If a link is right clicked, copy the text content and give it an action to create
    723724                                                                        // a new frame containing a browser pointing to the linked page
    724                                                                         Text t = DisplayIO.getCurrentFrame().createNewText(((String) ((JSObject)node).getMember("textContent")).trim());
     725                                                                        Text t = DisplayController.getCurrentFrame().createNewText(((String) ((JSObject)node).getMember("textContent")).trim());
    725726                                                                        t.addAction("createFrameWithBrowser " + (String) ((JSObject)node).getMember("href"));
    726                                                                         t.setXY(FrameMouseActions.getX(), FrameMouseActions.getY());
    727                                                                         FrameMouseActions.pickup(t);
     727                                                                        t.setXY(DisplayController.getMouseX(), DisplayController.getMouseY());
     728                                                                        StandardGestureActions.pickup(t);
    728729                                                                }
    729730                                                        }
    730731                                                } else {
    731732                                                        // Copy text and attach to cursor
    732                                                         Text t = DisplayIO.getCurrentFrame().createNewText(selection);
    733                                                         t.setXY(FrameMouseActions.getX(), FrameMouseActions.getY());
    734                                                         FrameMouseActions.pickup(t);
     733                                                        Text t = DisplayController.getCurrentFrame().createNewText(selection);
     734                                                        t.setXY(DisplayController.getMouseX(), DisplayController.getMouseY());
     735                                                        StandardGestureActions.pickup(t);
    735736                                                }
    736737                                        }
     
    871872        public void getFrame() {
    872873                try {
    873                         WebParser.parsePageSimple(this, _webEngine, _webView, DisplayIO.getCurrentFrame());
     874                        WebParser.parsePageSimple(this, _webEngine, _webView, DisplayController.getCurrentFrame());
    874875                } catch (Exception e) {
    875876                        e.printStackTrace();
     
    886887                        new Thread(new Runnable() {
    887888                                public void run() {
    888                                         WebParser.parsePageSimple(JfxBrowser.this, JfxBrowser.this._webEngine, JfxBrowser.this._webView, DisplayIO.getCurrentFrame());
     889                                        WebParser.parsePageSimple(JfxBrowser.this, JfxBrowser.this._webEngine, JfxBrowser.this._webView, DisplayController.getCurrentFrame());
    889890                                }
    890891                        }).start();
     
    954955                }
    955956
    956                 final int x = FrameMouseActions.getX() - this.getX(), y = FrameMouseActions.getY() - this.getY();
     957                final int x = DisplayController.getMouseX() - this.getX(), y = DisplayController.getMouseY() - this.getY();
    957958                if(!this._urlField.getBoundsInParent().contains(x, y)) {
    958959                        // fails if not clicking on urlField
  • trunk/src/org/expeditee/items/widgets/MemoryMonitor.java

    r919 r1102  
    1919package org.expeditee.items.widgets;
    2020
    21 import java.awt.Color;
    2221import java.awt.Font;
    2322import java.awt.Graphics;
     
    2726import javax.swing.SwingUtilities;
    2827
     28import org.expeditee.core.Colour;
     29import org.expeditee.gio.swing.SwingConversions;
     30import org.expeditee.gio.swing.SwingMiscManager;
    2931import org.expeditee.items.ItemParentStateChangedEvent;
    3032import org.expeditee.items.Text;
     
    3638 *
    3739 */
    38 public class MemoryMonitor extends InteractiveWidget {
     40public class MemoryMonitor extends SwingWidget {
    3941       
    4042        private long totalMemoryInBytes;
     
    6365       
    6466        @Override
    65         public void paint(Graphics g) {
    66                
     67        public void paintSwingWidget(Graphics2D g)
     68        {
    6769                int height = getHeight();
    6870                int width = getWidth();
     
    7072                int memHeight = (int)(height * currentMemoryUsage);
    7173               
    72                 Color memColor;
     74                Colour memColor;
    7375                if (currentMemoryUsage > 0.8f) {
    74                         memColor = Color.RED;
     76                        memColor = Colour.RED;
    7577                } else if (currentMemoryUsage > 0.5f) {
    76                         memColor = Color.ORANGE;
     78                        memColor = Colour.ORANGE;
    7779                } else  {
    78                         memColor = Color.GREEN;
     80                        memColor = Colour.GREEN;
    7981                }
    8082               
    81                 g.setColor(memColor);
     83                g.setColor(SwingConversions.toSwingColor(memColor));
    8284                g.fillRect(getX(), getY() + height - memHeight, width, memHeight);
    8385               
    84                 g.setColor(Color.WHITE);
     86                g.setColor(SwingConversions.toSwingColor(Colour.WHITE));
    8587                g.fillRect(getX(), getY(), width, height - memHeight);
    8688               
    8789                int percent = (int)(currentMemoryUsage * 100.0f);
    8890               
    89                 g.setColor(Color.BLACK);
     91                g.setColor(SwingConversions.toSwingColor(Colour.BLACK));
    9092                g.setFont(USAGE_FONT);
    9193                g.drawString(percent + "%", getX() + 12, getY() + (height / 2) + 8);
    92                
    93                 paintLink((Graphics2D)g);
    9494        }
    9595
  • trunk/src/org/expeditee/items/widgets/Password.java

    r919 r1102  
    3232 * @author jts21
    3333 */
    34 public class Password extends InteractiveWidget {
     34public class Password extends SwingWidget {
    3535
    3636        private JPasswordField passwordField;
  • trunk/src/org/expeditee/items/widgets/RefreshButton.java

    r1005 r1102  
    44import java.awt.event.ActionListener;
    55
    6 import org.expeditee.gui.DisplayIO;
     6import org.expeditee.gui.DisplayController;
    77import org.expeditee.gui.Frame;
    88import org.expeditee.gui.FrameGraphics;
     
    2020                public void actionPerformed(ActionEvent e) {                   
    2121                 
    22                    Frame f = DisplayIO.getCurrentFrame();         
     22                   Frame f = DisplayController.getCurrentFrame();         
    2323                   try{
    2424                           FrameIO.ForceSaveFrame(f);
    2525                           Frame g = FrameIO.LoadRestoreFrame(f);       
    26                            DisplayIO.setCurrentFrame(g, false);
    27                            FrameGraphics.refresh(true);
     26                           DisplayController.setCurrentFrame(g, false);
     27                           DisplayController.requestRefresh(true);
    2828                   }
    2929                   catch(Exception e1){
  • trunk/src/org/expeditee/items/widgets/RubbishBin.java

    r1005 r1102  
    44import java.awt.event.ActionListener;
    55
    6 import org.expeditee.gui.DisplayIO;
    7 import org.expeditee.gui.FrameMouseActions;
     6import org.expeditee.gio.gesture.StandardGestureActions;
     7import org.expeditee.gui.DisplayController;
    88import org.expeditee.gui.FreeItems;
    99import org.expeditee.items.Item;
    1010import org.expeditee.items.Text;
    1111
    12 //When the Rubbish Bin Widget is clicked by any of the mouse buttons, whatever is currently being picked up by the mouse is destroyed
    13 public class RubbishBin extends ButtonWidget{   
    14                
    15         public RubbishBin(Text source, String[] args){ 
    16                                        
     12/**
     13 * When the Rubbish Bin Widget is clicked by any of the mouse buttons,
     14 * whatever is currently being picked up by the mouse is destroyed.
     15 *
     16 * @author cts16
     17 */
     18public class RubbishBin extends ButtonWidget
     19{       
     20        public RubbishBin(Text source, String[] args)
     21        {
    1722                super(80, "org/expeditee/assets/images/bin.svg", source, args);
    1823
    19                 clicked_.addActionListener(new ActionListener() {
    20                 public void actionPerformed(ActionEvent e) {   
     24                clicked_.addActionListener(new ActionListener()
     25                {
     26                public void actionPerformed(ActionEvent e)
     27                {       
    2128                       
    2229                }         
    23              });               
     30                });             
    2431        }
    25         public boolean ItemsLeftClickDropped() {
    26                
     32       
     33        public boolean ItemsLeftClickDropped()
     34        {
    2735                //Find what the mouse was holding at the time and delete it
    2836                Item freeItems = FreeItems.getItemAttachedToCursor();
    29                 if( freeItems != null){
    30                         freeItems.setParent(DisplayIO.getCurrentFrame());
     37               
     38                if( freeItems != null) {
     39                        freeItems.setParent(DisplayController.getCurrentFrame());
    3140                       
    32                         try{
    33                        
    34                         FrameMouseActions.delete(freeItems);           
    35                         }
    36                         catch(Exception e){
    37                                
     41                        try {
     42                                StandardGestureActions.delete(freeItems, null, null, false);           
     43                        } catch(Exception e) {
    3844                                e.printStackTrace();
    3945                        }                       
    4046                }
     47               
    4148                return true;
    4249        }
    4350       
    4451        @Override
    45         protected String[] getArgs() {
     52        protected String[] getArgs()
     53        {
    4654                // TODO Auto-generated method stub
    4755                return null;
    4856        }
    49         //this should be a generic method for any widget that is clicked while an item is being held
    50         public boolean itemHeldWhileClicked(InteractiveWidget iw){
    51                        
     57       
     58        /**
     59         * This should be a generic method for any widget that is clicked while an item is being held.
     60         */
     61        public boolean itemHeldWhileClicked(Widget iw)
     62        {
    5263                ItemsLeftClickDropped();
    53                 return true;
    54                        
    55         }
    56         public boolean getdropInteractableStatus(){
     64               
    5765                return true;
    5866        }
    5967       
     68        public boolean getdropInteractableStatus()
     69        {
     70                return true;
     71        }
    6072}
  • trunk/src/org/expeditee/items/widgets/SampleWidget2.java

    r919 r1102  
    1919package org.expeditee.items.widgets;
    2020
    21 
    22 import java.awt.Color;
    2321import java.awt.FlowLayout;
    2422import java.awt.Font;
     
    3230import javax.swing.JToggleButton;
    3331
     32import org.expeditee.core.Colour;
     33import org.expeditee.gio.swing.SwingConversions;
    3434import org.expeditee.items.Text;
    3535
    36 public class SampleWidget2 extends InteractiveWidget {
     36public class SampleWidget2 extends SwingWidget {
    3737       
    3838        private JComboBox _combo;
     
    4747               
    4848                JPanel p = new JPanel(new FlowLayout());
    49                 p.setBackground(new Color(255,228,195));
     49                p.setBackground(SwingConversions.toSwingColor(Colour.FromRGB255(255,228,195)));
    5050
    5151                JLabel lbl = new JLabel("This is an example InteractiveWidget!");
  • trunk/src/org/expeditee/items/widgets/Undo.java

    r1005 r1102  
    44import java.awt.event.ActionListener;
    55
    6 import org.expeditee.gui.DisplayIO;
     6import org.expeditee.gui.DisplayController;
    77import org.expeditee.items.Text;
    88
     
    1717                public void actionPerformed(ActionEvent e) {
    1818                                           
    19                    DisplayIO.getCurrentFrame().undo();               
     19                   DisplayController.getCurrentFrame().undo();               
    2020                }         
    2121             });               
  • trunk/src/org/expeditee/items/widgets/WidgetCacheManager.java

    r919 r1102  
    2525import java.util.Set;
    2626
    27 import org.expeditee.gui.DisplayIOObserver;
     27import org.expeditee.gui.DisplayObserver;
    2828import org.expeditee.gui.FrameIO;
    2929
     
    3737 *
    3838 */
    39 public final class WidgetCacheManager implements DisplayIOObserver {
     39public final class WidgetCacheManager implements DisplayObserver {
    4040       
    4141        private static HashMap<HeavyDutyInteractiveWidget, Integer> transientWidgets = new HashMap<HeavyDutyInteractiveWidget, Integer>();
  • trunk/src/org/expeditee/items/widgets/WidgetCorner.java

    r919 r1102  
    1919package org.expeditee.items.widgets;
    2020
    21 import java.awt.Color;
    22 import java.awt.Graphics2D;
    23 import java.awt.Polygon;
    2421import java.util.List;
    2522
     23import org.expeditee.core.Colour;
     24import org.expeditee.core.Point;
     25import org.expeditee.core.bounds.PolygonBounds;
    2626import org.expeditee.items.Dot;
    2727import org.expeditee.items.ItemParentStateChangedEvent;
     
    3030public class WidgetCorner extends Dot {
    3131
    32         private InteractiveWidget _widgetSource;
    33 
    34         WidgetCorner(int x, int y, int id, InteractiveWidget widgetSource) {
     32        private Widget _widgetSource;
     33
     34        WidgetCorner(int x, int y, int id, Widget widgetSource) {
    3535                super(x, y, id);
    3636
     
    3838                        throw new NullPointerException("widgetSource");
    3939                _widgetSource = widgetSource;
    40         }
    41 
    42         @Override
    43         public void updatePolygon() {
    44                 super.updatePolygon();
    45                 if (_widgetSource != null)
    46                         _widgetSource.onBoundsChanged();
    4740        }
    4841
     
    8174
    8275        @Override
    83         public void onParentStateChanged(ItemParentStateChangedEvent e) {
     76        public void onParentStateChanged(ItemParentStateChangedEvent e)
     77        {
    8478                super.onParentStateChanged(e);
    8579                _widgetSource.onParentStateChanged(e);
    8680        }
    8781
    88         public InteractiveWidget getWidgetSource() {
     82        public Widget getWidgetSource() {
    8983                return _widgetSource;
    9084        }
    9185
    9286        @Override
    93         public void paint(Graphics2D g) {
     87        public void paint()
     88        {
    9489                // For fixed widgets, always have corner selected with connected context
    95                 HighlightMode tmp = _mode; // save mode
    96                 if (_mode == HighlightMode.Normal && _widgetSource.isFixedSize()) {
    97                         _mode = HighlightMode.Connected; // draw as connected context for
     90                HighlightMode tmp = _highlightMode; // save mode
     91                if (_highlightMode == HighlightMode.Normal && _widgetSource.isFixedSize()) {
     92                        _highlightMode = HighlightMode.Connected; // draw as connected context for
    9893                        // fixed widgets
    9994                }
    100                 super.paint(g);
    101                 _mode = tmp; // restore mode
    102         }
    103 
    104         @Override
    105         public void paintFill(Graphics2D g) {
    106                 _widgetSource.paintFill(g); // only paints a fill if floating
     95                super.paint();
     96                _highlightMode = tmp; // restore mode
     97        }
     98
     99        @Override
     100        public void paintFill() {
     101                _widgetSource.paintFill(); // only paints a fill if floating
    107102        }
    108103
     
    127122
    128123        @Override
    129         public void setArrowhead(Polygon arrow) {
     124        public void setArrowhead(PolygonBounds arrow) {
    130125        }
    131126
     
    139134
    140135        @Override
    141         public void setBackgroundColor(Color c) {
     136        public void setBackgroundColor(Colour c) {
    142137                if (_widgetSource != null) {
    143138                        super.setBackgroundColor(c);
     
    147142
    148143        @Override
    149         public void setBottomShadowColor(Color bottom) {
    150         }
    151 
    152         @Override
    153         public void setFillColor(Color c) {
     144        public void setBottomShadowColor(Colour bottom) {
     145        }
     146
     147        @Override
     148        public void setFillColor(Colour c) {
    154149        }
    155150
     
    186181        }
    187182
    188         public void setAnchorCornerX(Float anchorLeft, Float anchorRight) {
    189                 _anchorLeft = anchorLeft;
    190                 _anchorRight = anchorRight;
    191         }
    192        
    193         public void setAnchorCornerY(Float anchorTop, Float anchorBottom) {
    194                 _anchorTop = anchorTop;
    195                 _anchorBottom= anchorBottom;
    196         }
    197        
    198         @Override
    199         public void setAnchorLeft(Float anchor) {
     183        public void setAnchorCornerX(Integer anchorLeft, Integer anchorRight)
     184        {
     185                _anchoring.setLeftAnchor(anchorLeft);
     186                _anchoring.setRightAnchor(anchorRight);
     187        }
     188       
     189        public void setAnchorCornerY(Integer anchorTop, Integer anchorBottom)
     190        {
     191                _anchoring.setTopAnchor(anchorTop);
     192                _anchoring.setBottomAnchor(anchorBottom);
     193        }
     194       
     195        @Override
     196        public void setAnchorLeft(Integer anchor) {
    200197                _widgetSource.setAnchorLeft(anchor);
    201                 _anchorLeft = anchor;
    202                 _anchorRight = null;
    203         }
    204 
    205         @Override
    206         public void setAnchorRight(Float anchor) {
     198                _anchoring.setLeftAnchor(anchor);
     199        }
     200
     201        @Override
     202        public void setAnchorRight(Integer anchor) {
    207203                _widgetSource.setAnchorRight(anchor);
    208                 _anchorLeft = null;
    209                 _anchorRight = anchor;
    210         }
    211        
    212         @Override
    213         public void setAnchorTop(Float anchor) {
     204                _anchoring.setRightAnchor(anchor);
     205        }
     206       
     207        @Override
     208        public void setAnchorTop(Integer anchor) {
    214209                _widgetSource.setAnchorTop(anchor);
    215                 _anchorTop = anchor;
    216                 _anchorBottom = null;
    217         }
    218 
    219         @Override
    220         public void setAnchorBottom(Float anchor) {
     210                _anchoring.setTopAnchor(anchor);
     211        }
     212
     213        @Override
     214        public void setAnchorBottom(Integer anchor) {
    221215                _widgetSource.setAnchorBottom(anchor);
    222                 _anchorTop = null;
    223                 _anchorBottom = anchor;
     216                _anchoring.setBottomAnchor(anchor);
    224217        }
    225218       
     
    251244
    252245        @Override
    253         public boolean contains(int x, int y) {
    254                 return super.contains(x, y)
    255                                 && !_widgetSource.getBounds().contains(x, y);
     246        public boolean contains(Point p)
     247        {
     248                return super.contains(p) && !_widgetSource.getBounds().contains(p);
    256249        }
    257250
     
    268261
    269262        @Override
    270         public void setColor(Color color) {
     263        public void setColor(Colour color) {
    271264                if (_widgetSource != null) {
    272265                        super.setColor(color);
  • trunk/src/org/expeditee/items/widgets/WidgetEdge.java

    r919 r1102  
    1919package org.expeditee.items.widgets;
    2020
    21 import java.awt.Color;
    22 import java.awt.Polygon;
    2321import java.util.List;
    2422
     23import org.expeditee.core.Colour;
     24import org.expeditee.core.Point;
     25import org.expeditee.core.bounds.PolygonBounds;
    2526import org.expeditee.items.Item;
    2627import org.expeditee.items.Line;
     
    2829
    2930/**
    30  * Widget edges define the boundries of an interactive widget.
     31 * Widget edges define the boundaries of an interactive widget.
    3132 *
    3233 * @author Brook Novak
     
    3435public class WidgetEdge extends Line {
    3536
    36         private InteractiveWidget _widgetSource;
     37        private Widget _widgetSource;
    3738
    3839        WidgetEdge(WidgetCorner start, WidgetCorner end, int id,
    39                         InteractiveWidget widgetSource) {
     40                        Widget widgetSource) {
    4041                super(start, end, id);
    4142               
     
    4546        }
    4647
    47         public InteractiveWidget getWidgetSource() {
     48        public Widget getWidgetSource() {
    4849                return _widgetSource;
    4950        }
     
    8990
    9091        @Override
    91         public void setArrowhead(Polygon arrow) {
     92        public void setArrowhead(PolygonBounds arrow) {
    9293        }
    9394
     
    101102
    102103        @Override
    103         public void setBottomShadowColor(Color bottom) {
    104         }
    105 
    106         @Override
    107         public void setFillColor(Color c) {
     104        public void setBottomShadowColor(Colour bottom) {
     105        }
     106
     107        @Override
     108        public void setFillColor(Colour c) {
    108109        }
    109110
     
    121122       
    122123        @Override
    123         public void setAnchorTop(Float anchor) {
     124        public void setAnchorTop(Integer anchor) {
    124125                _widgetSource.setAnchorTop(anchor);
    125126        }
    126127
    127128        @Override
    128         public void setAnchorBottom(Float anchor) {
     129        public void setAnchorBottom(Integer anchor) {
    129130                _widgetSource.setAnchorBottom(anchor);
    130131        }
    131132
    132133        @Override
    133         public void setAnchorLeft(Float anchor) {
     134        public void setAnchorLeft(Integer anchor) {
    134135                _widgetSource.setAnchorLeft(anchor);
    135136        }
    136137
    137138        @Override
    138         public void setAnchorRight(Float anchor) {
     139        public void setAnchorRight(Integer anchor) {
    139140                _widgetSource.setAnchorRight(anchor);
    140141        }
     
    156157       
    157158        @Override
    158         public Float getAnchorTop() {
     159        public Integer getAnchorTop() {
    159160                return _widgetSource.getSource().getAnchorTop();
    160161        }
    161162
    162163        @Override
    163         public Float getAnchorBottom() {
     164        public Integer getAnchorBottom() {
    164165                return _widgetSource.getSource().getAnchorBottom();
    165166        }
    166167       
    167168        @Override
    168         public Float getAnchorLeft() {
     169        public Integer getAnchorLeft() {
    169170                return _widgetSource.getSource().getAnchorLeft();
    170171        }
    171172
    172173        @Override
    173         public Float getAnchorRight() {
     174        public Integer getAnchorRight() {
    174175                return _widgetSource.getSource().getAnchorRight();
    175176        }
    176177       
    177178        @Override
    178         public boolean contains(int x, int y) {
    179                 return super.contains(x, y) && !_widgetSource.getBounds().contains(x, y);
    180         }
    181 
    182         @Override
    183         public Polygon getEnclosedShape() {
     179        public boolean contains(Point p) {
     180                return super.contains(p) && !_widgetSource.getBounds().contains(p);
     181        }
     182
     183        @Override
     184        public PolygonBounds getEnclosedShape() {
    184185                return getStartItem().getEnclosedShape();
    185186        }
     
    219220       
    220221        @Override
    221         public void setBackgroundColor(Color c) {
     222        public void setBackgroundColor(Colour c) {
    222223                if (_widgetSource != null) {
    223224                        super.setBackgroundColor(c);
     
    227228       
    228229        @Override
    229         public void setColor(Color c) {
     230        public void setColor(Colour c) {
    230231                if (_widgetSource != null) {
    231232                        super.setColor(c);
  • trunk/src/org/expeditee/items/widgets/charts/AbstractCategory.java

    r919 r1102  
    1919package org.expeditee.items.widgets.charts;
    2020
    21 import java.awt.Color;
    2221import java.util.Collection;
    2322
     23import org.expeditee.core.Colour;
     24import org.expeditee.gio.swing.SwingConversions;
    2425import org.expeditee.gui.AttributeValuePair;
    2526import org.expeditee.items.Text;
     
    4950                        Collection<Text> items, boolean swap) {
    5051                boolean foundData = false;
    51                 Color newColor = null;
     52                Colour newColor = null;
    5253                for (Text i : items) {
    5354                        try {
     
    6162                                                                        categoryName);
    6263                                                        if (_paints.get(attribute) == null) {
    63                                                                 _paints.put(attribute, i.getBackgroundColor());
     64                                                                _paints.put(attribute, SwingConversions.toSwingColor(i.getBackgroundColor()));
    6465                                                        }
    6566                                                } else {
     
    7778                }
    7879                if (foundData && !swap) {
    79                         _paints.put(categoryName, newColor);
     80                        _paints.put(categoryName, SwingConversions.toSwingColor(newColor));
    8081                }
    8182                return foundData;
  • trunk/src/org/expeditee/items/widgets/charts/AbstractChart.java

    r919 r1102  
    2020
    2121import java.awt.BasicStroke;
    22 import java.awt.Color;
    2322import java.awt.Component;
    2423import java.awt.Font;
    2524import java.awt.Paint;
    26 import java.awt.Point;
    2725import java.awt.event.KeyEvent;
    2826import java.awt.event.KeyListener;
     
    3533import javax.swing.JPanel;
    3634
     35import org.expeditee.core.Colour;
     36import org.expeditee.core.Point;
     37import org.expeditee.gio.gesture.StandardGestureActions;
     38import org.expeditee.gio.swing.SwingConversions;
    3739import org.expeditee.gui.ColorUtils;
     40import org.expeditee.gui.DisplayController;
    3841import org.expeditee.gui.Frame;
    3942import org.expeditee.gui.FrameGraphics;
    4043import org.expeditee.gui.FrameIO;
    41 import org.expeditee.gui.FrameKeyboardActions;
    42 import org.expeditee.gui.FrameMouseActions;
    4344import org.expeditee.gui.FunctionKey;
    4445import org.expeditee.items.Text;
     
    103104                                case SizeUp:
    104105                                        invalidateLink();
    105                                         FrameKeyboardActions.SetSize(getFirstCorner(), 1, false,
    106                                                         true, false);
     106                                        StandardGestureActions.SetSize(getFirstCorner(), 1, false, true, false);
    107107                                        invalidateSelf();
    108                                         FrameGraphics.refresh(true);
     108                                        DisplayController.requestRefresh(true);
    109109                                        // FrameGraphics.requestRefresh(true);
    110110                                        break;
    111111                                case SizeDown:
    112112                                        invalidateLink();
    113                                         FrameKeyboardActions.SetSize(getFirstCorner(), -1, false,
     113                                        StandardGestureActions.SetSize(getFirstCorner(), -1, false,
    114114                                                        true, false);
    115115                                        invalidateSelf();
    116                                         FrameGraphics.refresh(true);
     116                                        DisplayController.requestRefresh(true);
    117117                                        // FrameGraphics.ForceRepaint();
    118118                                        // FrameGraphics.refresh(true);
     
    125125                                                        setSourceFillColor(null);
    126126                                                } else {
    127                                                         Color newColor = ColorUtils.getNextColor(
     127                                                        Colour newColor = ColorUtils.getNextColor(
    128128                                                                        getSource().getFillColor(),
    129129                                                                        TemplateSettings.BackgroundColorWheel.get(), null);
     
    134134                                                        setBackgroundColor(null);
    135135                                                } else {
    136                                                         Color newColor = ColorUtils.getNextColor(
     136                                                        Colour newColor = ColorUtils.getNextColor(
    137137                                                                        getSource().getColor(), TemplateSettings.ColorWheel.get(),
    138138                                                                        null);
     
    141141                                        }
    142142                                        break;
     143                                default:
     144                                        break;
    143145                                }
    144146                        }
     
    148150
    149151                        public void keyTyped(KeyEvent e) {
    150                                 FrameKeyboardActions.processChar(e.getKeyChar(), e
     152                                StandardGestureActions.processChar(e.getKeyChar(), e
    151153                                                .isShiftDown());
    152154                        }
     
    155157
    156158                        public void mouseClicked(MouseEvent e) {
    157                                 FrameMouseActions.getInstance().mouseClicked(translateEvent(e));
     159                                //StandardGestureActions.mouseClicked(translateEvent(e));
    158160                        }
    159161
     
    167169
    168170                        public void mousePressed(MouseEvent e) {
    169                                 FrameMouseActions.getInstance().mousePressed(translateEvent(e));
     171                                //StandardGestureActions.mousePressed(translateEvent(e));
    170172                        }
    171173
     
    180182
    181183                        public void mouseReleased(MouseEvent e) {
    182                                 FrameMouseActions.getInstance()
    183                                                 .mouseReleased(translateEvent(e));
     184                                //StandardGestureActions.mouseReleased(translateEvent(e));
    184185                        }
    185186
     
    272273                                if (foundData |= addCategoryData(categoryName, linkFrame
    273274                                                .getNonAnnotationText(true), swap)) {
    274                                         Color backgroundColor = category.getBackgroundColor();
     275                                        Colour backgroundColor = category.getBackgroundColor();
    275276                                        if (backgroundColor != null)
    276                                                 _paints.put(categoryName, backgroundColor);
     277                                                _paints.put(categoryName, SwingConversions.toSwingColor(backgroundColor));
    277278                                        addSubject(linkFrame);
    278279                                }
     
    307308
    308309        @Override
    309         public void setBackgroundColor(Color c) {
     310        public void setBackgroundColor(Colour c) {
    310311                super.setBackgroundColor(c);
    311312                if (_chart == null)
     
    314315                        _chart.setBackgroundPaint(JFreeChart.DEFAULT_BACKGROUND_PAINT);
    315316                } else {
    316                         _chart.setBackgroundPaint(c);
    317                 }
    318         }
    319 
    320         @Override
    321         public void setSourceColor(Color c) {
     317                        _chart.setBackgroundPaint(SwingConversions.toSwingColor(c));
     318                }
     319        }
     320
     321        @Override
     322        public void setSourceColor(Colour c) {
    322323                super.setSourceColor(c);
    323324                if (_chart == null)
     
    326327                        _chart.getTitle().setPaint(TextTitle.DEFAULT_TEXT_PAINT);
    327328                } else {
    328                         _chart.getTitle().setPaint(c);
     329                        _chart.getTitle().setPaint(SwingConversions.toSwingColor(c));
    329330                }
    330331                for (Title t : _chart.getSubtitles()) {
     
    332333                                t.setPaint(TextTitle.DEFAULT_TEXT_PAINT);
    333334                        } else {
    334                                 t.setPaint(c);
     335                                t.setPaint(SwingConversions.toSwingColor(c));
    335336                        }
    336337                }
     
    338339                if (legend != null) {
    339340                        if (c == null) {
    340                                 legend.setFrame(new BlockBorder(Color.black));
     341                                legend.setFrame(new BlockBorder(SwingConversions.toSwingColor(Colour.BLACK)));
    341342                        } else {
    342                                 legend.setFrame(new BlockBorder(c));
    343                         }
    344                 }
    345         }
    346 
    347         @Override
    348         public void setSourceBorderColor(Color c) {
     343                                legend.setFrame(new BlockBorder(SwingConversions.toSwingColor(c)));
     344                        }
     345                }
     346        }
     347
     348        @Override
     349        public void setSourceBorderColor(Colour c) {
    349350                super.setSourceBorderColor(c);
    350351                if (_chart == null)
     
    353354                        _chart.getPlot().setOutlinePaint(Plot.DEFAULT_OUTLINE_PAINT);
    354355                } else {
    355                         _chart.getPlot().setOutlinePaint(c);
    356                 }
    357         }
    358 
    359         @Override
    360         public void setSourceFillColor(Color c) {
     356                        _chart.getPlot().setOutlinePaint(SwingConversions.toSwingColor(c));
     357                }
     358        }
     359
     360        @Override
     361        public void setSourceFillColor(Colour c) {
    361362                super.setSourceFillColor(c);
    362363                if (_chart == null)
     
    368369                                legend.setBackgroundPaint(null);
    369370                } else {
    370                         _chart.getPlot().setBackgroundPaint(c);
     371                        _chart.getPlot().setBackgroundPaint(SwingConversions.toSwingColor(c));
    371372                        if (legend != null)
    372                                 legend.setBackgroundPaint(c);
     373                                legend.setBackgroundPaint(SwingConversions.toSwingColor(c));
    373374                }
    374375        }
     
    387388                if (legend != null) {
    388389                        legend.setFrame(new BlockBorder(newThickness, newThickness,
    389                                         newThickness, newThickness, getSource().getPaintColor()));
     390                                        newThickness, newThickness, SwingConversions.toSwingColor(getSource().getPaintColor())));
    390391                        legend.setItemFont(legend.getItemFont().deriveFont(fontSize));
    391392                        float pad = newThickness + 1;
  • trunk/src/org/expeditee/items/widgets/charts/AbstractPie.java

    r919 r1102  
    2020
    2121import java.awt.BasicStroke;
    22 import java.awt.Color;
    2322
     23import org.expeditee.core.Colour;
     24import org.expeditee.gio.swing.SwingConversions;
    2425import org.expeditee.gui.AttributeValuePair;
    2526import org.expeditee.gui.Frame;
     
    8586                                try {
    8687                                        _data.setValue(avp.getAttribute(), avp.getDoubleValue());
    87                                         _paints.put(avp.getAttribute(), t.getBackgroundColor());
     88                                        _paints.put(avp.getAttribute(), SwingConversions.toSwingColor(t.getBackgroundColor()));
    8889                                } catch (NumberFormatException nfe) {
    8990
     
    9495
    9596        @Override
    96         public void setSourceBorderColor(Color c) {
     97        public void setSourceBorderColor(Colour c) {
    9798                super.setSourceBorderColor(c);
    9899                if (getChart() == null)
     
    106107                        plot.setShadowPaint(PiePlot.DEFAULT_SHADOW_PAINT);
    107108                } else {
    108                         plot.setBaseSectionOutlinePaint(c);
    109                         plot.setLabelLinkPaint(c);
    110                         plot.setLabelOutlinePaint(c);
    111                         Color newC = c.darker();
    112                         Color faded = new Color(newC.getRed(), newC.getGreen(), newC
    113                                         .getBlue(), 128);
     109                        plot.setBaseSectionOutlinePaint(SwingConversions.toSwingColor(c));
     110                        plot.setLabelLinkPaint(SwingConversions.toSwingColor(c));
     111                        plot.setLabelOutlinePaint(SwingConversions.toSwingColor(c));
     112                        Colour newC = c.darker();
     113                        Colour faded = new Colour(newC.getRed(), newC.getGreen(), newC
     114                                        .getBlue(), Colour.FromComponent255(128));
    114115
    115                         plot.setLabelShadowPaint(faded);
    116                         plot.setShadowPaint(c);
     116                        plot.setLabelShadowPaint(SwingConversions.toSwingColor(faded));
     117                        plot.setShadowPaint(SwingConversions.toSwingColor(c));
    117118                }
    118119        }
    119120
    120121        @Override
    121         public void setSourceColor(Color c) {
     122        public void setSourceColor(Colour c) {
    122123                super.setSourceColor(c);
    123124                if (getChart() == null)
     
    127128                        plot.setLabelPaint(PiePlot.DEFAULT_LABEL_PAINT);
    128129                } else {
    129                         plot.setLabelPaint(c);
     130                        plot.setLabelPaint(SwingConversions.toSwingColor(c));
    130131                }
    131132        }
  • trunk/src/org/expeditee/items/widgets/charts/AbstractValueAxis.java

    r919 r1102  
    2020
    2121import java.awt.BasicStroke;
    22 import java.awt.Color;
    2322import java.awt.Stroke;
    2423
     24import org.expeditee.core.Colour;
     25import org.expeditee.gio.swing.SwingConversions;
    2526import org.expeditee.gui.Frame;
    2627import org.expeditee.items.Text;
     
    5657
    5758        @Override
    58         public void setSourceColor(Color c) {
     59        public void setSourceColor(Colour c) {
    5960                super.setSourceColor(c);
    6061                if (getChart() == null)
     
    7071                                        .setTickLabelPaint(Axis.DEFAULT_TICK_LABEL_PAINT);
    7172                } else {
    72                         plot.getDomainAxis().setLabelPaint(c);
    73                         plot.getRangeAxis().setLabelPaint(c);
    74                         plot.getDomainAxis().setTickLabelPaint(c);
    75                         plot.getRangeAxis().setTickLabelPaint(c);
     73                        plot.getDomainAxis().setLabelPaint(SwingConversions.toSwingColor(c));
     74                        plot.getRangeAxis().setLabelPaint(SwingConversions.toSwingColor(c));
     75                        plot.getDomainAxis().setTickLabelPaint(SwingConversions.toSwingColor(c));
     76                        plot.getRangeAxis().setTickLabelPaint(SwingConversions.toSwingColor(c));
    7677                }
    7778        }
    7879
    7980        @Override
    80         public void setSourceBorderColor(Color c) {
     81        public void setSourceBorderColor(Colour c) {
    8182                super.setSourceBorderColor(c);
    8283                if (getChart() == null)
     
    8990                        plot.getRangeAxis().setTickMarkPaint(Plot.DEFAULT_OUTLINE_PAINT);
    9091                } else {
    91                         Color brighter = c.brighter();
    92                         plot.setDomainGridlinePaint(brighter);
    93                         plot.setRangeGridlinePaint(brighter);
    94                         plot.getDomainAxis().setTickMarkPaint(c);
    95                         plot.getRangeAxis().setTickMarkPaint(c);
     92                        Colour brighter = c.brighter();
     93                        plot.setDomainGridlinePaint(SwingConversions.toSwingColor(brighter));
     94                        plot.setRangeGridlinePaint(SwingConversions.toSwingColor(brighter));
     95                        plot.getDomainAxis().setTickMarkPaint(SwingConversions.toSwingColor(c));
     96                        plot.getRangeAxis().setTickMarkPaint(SwingConversions.toSwingColor(c));
    9697                }
    9798        }
  • trunk/src/org/expeditee/items/widgets/charts/AbstractXY.java

    r919 r1102  
    1919package org.expeditee.items.widgets.charts;
    2020
    21 import java.awt.Color;
    2221import java.util.Collection;
    2322import java.util.HashSet;
    2423
     24import org.expeditee.core.Colour;
     25import org.expeditee.gio.swing.SwingConversions;
    2526import org.expeditee.gui.AttributeValuePair;
    2627import org.expeditee.items.Item;
     
    5556                        Collection<Text> items, boolean swap) {
    5657                XYSeries newSeries = new XYSeries(categoryName);
    57                 Color categoryColor = null;
     58                Colour categoryColor = null;
    5859                boolean foundData = false;
    5960                Collection<Item> seen = new HashSet<Item>();
     
    123124                if (foundData) {
    124125                        _data.addSeries(newSeries);
    125                         _paints.put(categoryName, categoryColor);
     126                        _paints.put(categoryName, SwingConversions.toSwingColor(categoryColor));
    126127                }
    127128                return foundData;
  • trunk/src/org/expeditee/items/widgets/charts/Polar.java

    r919 r1102  
    1919package org.expeditee.items.widgets.charts;
    2020
    21 import java.awt.Color;
    22 
     21import org.expeditee.core.Colour;
     22import org.expeditee.gio.swing.SwingConversions;
    2323import org.expeditee.items.Text;
    2424import org.jfree.chart.ChartFactory;
     
    4343
    4444        @Override
    45         public void setSourceColor(Color c) {
     45        public void setSourceColor(Colour c) {
    4646                super.setSourceColor(c);
    4747                if (getChart() == null)
     
    5353                        plot.setAngleLabelPaint(Axis.DEFAULT_AXIS_LABEL_PAINT);
    5454                } else {
    55                         plot.setAngleLabelPaint(c);
     55                        plot.setAngleLabelPaint(SwingConversions.toSwingColor(c));
    5656                }
    5757        }
  • trunk/src/org/expeditee/items/widgets/charts/TimeSeries.java

    r919 r1102  
    1919package org.expeditee.items.widgets.charts;
    2020
    21 import java.awt.Color;
    2221import java.text.DateFormat;
    2322import java.text.ParseException;
     
    2726import java.util.Date;
    2827
     28import org.expeditee.Util;
     29import org.expeditee.core.Colour;
     30import org.expeditee.gio.swing.SwingConversions;
    2931import org.expeditee.gui.AttributeValuePair;
    3032import org.expeditee.gui.Frame;
     
    100102                        String startDateString = dataFrame.getAnnotationValue("start");
    101103                        if (startDateString != null) {
    102                                 _startDate = parseDate(startDateString);
     104                                _startDate = Util.parseDate(startDateString);
    103105                        }
    104106                } catch (Exception e) {
     
    135137
    136138                boolean foundData = false;
    137                 Color newColor = null;
     139                Colour newColor = null;
    138140                for (Text i : items) {
    139141                        if (!i.isLineEnd()) {
     
    157159                                                RegularTimePeriod rtp = null;
    158160                                                if (attribute == null) {
    159                                                         Date date = parseDate(avp.getAttribute());
     161                                                        Date date = Util.parseDate(avp.getAttribute());
    160162                                                        rtp = _periodType.getConstructor(
    161163                                                                        new Class[] { Date.class }).newInstance(
     
    212214                if (foundData) {
    213215                        _data.addSeries(newSeries);
    214                         _paints.put(categoryName, newColor);
     216                        _paints.put(categoryName, SwingConversions.toSwingColor(newColor));
    215217                }
    216218                return foundData;
    217219        }
    218 
    219         /**
    220          * @param avp
    221          * @return
    222          * @throws ParseException
    223          */
    224         public static Date parseDate(String dateString) throws ParseException {
    225                 // Select the best match for a date or time format
    226                 DateFormat df = null;
    227                 if (dateString.length() > Formatter.DATE_FORMAT
    228                                 .length()) {
    229                         df = new SimpleDateFormat(Formatter.DATE_TIME_FORMAT);
    230                 } else if (dateString.length() <= Formatter.TIME_FORMAT.length()) {
    231                         df = new SimpleDateFormat(Formatter.TIME_FORMAT);
    232                 }else {
    233                         df = new SimpleDateFormat(Formatter.DATE_FORMAT);
    234                 }
    235                 Date date = df.parse(dateString);
    236                 return date;
    237         }
    238220}
  • trunk/src/org/expeditee/reflection/PackageLoader.java

    r919 r1102  
    3636public class PackageLoader {
    3737
    38     // The following is adapted from:
    39     // http://stackoverflow.com/questions/1456930/how-do-i-read-all-classes-from-a-java-package-in-the-classpath
    40 
    41     public static List<Class<?>> getClassesNew(String packageName)
    42             throws ClassNotFoundException {
    43 
    44         ClassLoader classLoader = Thread.currentThread()
    45                 .getContextClassLoader();
    46 
    47         ArrayList<String> names = new ArrayList<String>();
    48         ;
    49         final ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
    50 
    51         String realPackageName = packageName;
    52         packageName = packageName.replace(".", "/");
    53         URL packageURL = classLoader.getResource(packageName);
    54 
    55         if (packageURL.getProtocol().equals("jar")) {
    56 
    57             // build jar file name, then loop through zipped entries
    58 
    59             String jarFileNameUndecoded = packageURL.getFile();
    60 
    61             try {
    62                 JarURLConnection ju_connection = (JarURLConnection) packageURL
    63                         .openConnection();
    64                 JarFile jf = ju_connection.getJarFile();
    65 
    66                 Enumeration<JarEntry> jarEntries = jf.entries();
    67                 while (jarEntries.hasMoreElements()) {
    68                     String entryName = jarEntries.nextElement().getName();
    69 
    70                     if (entryName.startsWith(packageName)) {
    71 
    72                         if (entryName.endsWith(".class")
    73                                 && !entryName.contains("$")) {
    74 
    75                             // Deal with situation where the class found might
    76                             // be a further sub-package
    77                             // e.g. for "org.expeditee.action"
    78                             // there is:
    79                             // org/expeditee/action/widgets/Chart.class
    80                             // which would produce a value of 'entryName' as
    81                             // widgets/Chart.class
    82 
    83                             entryName = entryName.substring(0,
    84                                     entryName.length() - 6); // 6 = '.class'
    85                             entryName = entryName.replace('/', '.');
    86 
    87                             names.add(entryName);
    88                             classes.add(Class.forName(entryName));
    89                         }
    90                     }
     38        // The following is adapted from:
     39        // http://stackoverflow.com/questions/1456930/how-do-i-read-all-classes-from-a-java-package-in-the-classpath
     40
     41        public static List<Class<?>> getClassesNew(String packageName) throws ClassNotFoundException
     42        {
     43                ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
     44
     45                ArrayList<String> names = new ArrayList<String>();
     46
     47                final ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
     48
     49                String realPackageName = packageName;
     50                packageName = packageName.replace(".", "/");
     51                URL packageURL = classLoader.getResource(packageName);
     52
     53                if (packageURL.getProtocol().equals("jar")) {
     54
     55                        // build jar file name, then loop through zipped entries
     56
     57                        String jarFileNameUndecoded = packageURL.getFile();
     58
     59                        try {
     60                                JarURLConnection ju_connection = (JarURLConnection) packageURL
     61                                                .openConnection();
     62                                JarFile jf = ju_connection.getJarFile();
     63
     64                                Enumeration<JarEntry> jarEntries = jf.entries();
     65                                while (jarEntries.hasMoreElements()) {
     66                                        String entryName = jarEntries.nextElement().getName();
     67
     68                                        if (entryName.startsWith(packageName)) {
     69
     70                                                if (entryName.endsWith(".class")
     71                                                                && !entryName.contains("$")) {
     72
     73                                                        // Deal with situation where the class found might
     74                                                        // be a further sub-package
     75                                                        // e.g. for "org.expeditee.action"
     76                                                        // there is:
     77                                                        // org/expeditee/action/widgets/Chart.class
     78                                                        // which would produce a value of 'entryName' as
     79                                                        // widgets/Chart.class
     80
     81                                                        entryName = entryName.substring(0,
     82                                                                        entryName.length() - 6); // 6 = '.class'
     83                                                        entryName = entryName.replace('/', '.');
     84
     85                                                        names.add(entryName);
     86                                                        classes.add(Class.forName(entryName));
     87                                                }
     88                                        }
     89                                }
     90                        } catch (Exception e) {
     91                                System.err.println("Failed to decode jar file: "
     92                                                + jarFileNameUndecoded);
     93                                e.printStackTrace();
     94                        }
     95                } else if (packageURL.getProtocol().equals("bundleresource")) {
     96                        try {
     97                                final URLConnection urlConnection = packageURL.openConnection();
     98                                final Class<?> c = urlConnection.getClass();
     99                                final java.lang.reflect.Method toInvoke = c.getMethod("getFileURL");
     100                                final URL fileURL = (URL)toInvoke.invoke(urlConnection);
     101                                final File folder = new File(fileURL.getFile());
     102                                final List<String> files = findFiles(folder);
     103                                for (final String s : files) {
     104                                        String entryName = realPackageName + s;
     105                                        if (entryName.endsWith(".class") && !entryName.contains("$")) {
     106                                                entryName = entryName.substring(0, entryName.lastIndexOf('.'));
     107                                                entryName = entryName.replace('/', '.');
     108                                                names.add(entryName);
     109                                                try {
     110                                                        final Class<?> tmpc = Class.forName(entryName);
     111                                                        classes.add(tmpc);
     112                                                } catch (NoClassDefFoundError e) {
     113                                                        System.err.println("Unable to instantiate class " + entryName);
     114                                                        System.err.println(e.getMessage());
     115                                                }
     116                                        }
     117                                }
     118                        } catch (final Exception e) {
     119                                System.err.println("Failed to process file: " + packageName);
     120                                e.printStackTrace();
     121                        }
     122                } else {
     123                        // loop through files in classpath
     124
     125                        String packageURLString = packageURL.toString();
     126                        try {
     127                                URI uri = new URI(packageURLString);
     128                                File folder = new File(uri.getPath());
     129
     130                                List<String> files = findFiles(folder);
     131                                for (String s : files) {
     132                                        String entryName = realPackageName + s;
     133
     134                                        if (entryName.endsWith(".class")
     135                                                        && !entryName.contains("$")) {
     136                                                entryName = entryName.substring(0,
     137                                                                entryName.lastIndexOf('.'));
     138                                                entryName = entryName.replace('/', '.');
     139
     140                                                names.add(entryName);
     141                                                classes.add(Class.forName(entryName));
     142                                        }
     143                                }
     144                        } catch (Exception e) {
     145                                System.err.println("Failed to process file: "
     146                                                + packageURLString);
     147                                e.printStackTrace();
     148                        }
    91149                }
    92             } catch (Exception e) {
    93                 System.err.println("Failed to decode jar file: "
    94                         + jarFileNameUndecoded);
    95                 e.printStackTrace();
    96             }
    97         } else if (packageURL.getProtocol().equals("bundleresource")) {
    98             try {
    99                 final URLConnection urlConnection = packageURL.openConnection();
    100                 final Class<?> c = urlConnection.getClass();
    101                 final java.lang.reflect.Method toInvoke = c.getMethod("getFileURL");
    102                 final URL fileURL = (URL)toInvoke.invoke(urlConnection);
    103                 final File folder = new File(fileURL.getFile());
    104                 final List<String> files = findFiles(folder);
    105                 for (final String s : files) {
    106                     String entryName = realPackageName + s;
    107                     if (entryName.endsWith(".class") && !entryName.contains("$")) {
    108                         entryName = entryName.substring(0, entryName.lastIndexOf('.'));
    109                         entryName = entryName.replace('/', '.');
    110                         names.add(entryName);
     150
     151                return classes;
     152        }
     153
     154        /**
     155         * Finds all files in a directory and it's subdirectories
     156         *
     157         * @param directory
     158         *            The folder to start in
     159         *
     160         * @return A list of Strings containing file paths relative to the starting
     161         *         directory
     162         */
     163        private static List<String> findFiles(File directory) {
     164                List<String> files = new LinkedList<String>();
     165                for (File f : directory.listFiles()) {
     166                        if (f.isDirectory()) {
     167                                for (String s : findFiles(f)) {
     168                                        files.add(f.getName() + "/" + s);
     169                                }
     170                        } else {
     171                                files.add(f.getName());
     172                        }
     173                }
     174                return files;
     175        }
     176
     177        public static List<Class<?>> getClasses(final String pckgname)
     178                        throws ClassNotFoundException {
     179
     180                final ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
     181
     182                // Must be a forward slash for loading resources
     183                final String packagePath = pckgname.replace('.', '/');
     184
     185                if (System.getProperty("eclipse.expeditee.home") == null) {
     186                        final ClassLoader cld = Thread.currentThread()
     187                                        .getContextClassLoader();
     188                        if (cld == null) {
     189                                throw new ClassNotFoundException("Can't get class loader.");
     190                        }
     191                        URL resource = null;
    111192                        try {
    112                             final Class<?> tmpc = Class.forName(entryName);
    113                             classes.add(tmpc);
    114                         } catch (NoClassDefFoundError e) {
    115                             System.err.println("Unable to instantiate class " + entryName);
    116                             System.err.println(e.getMessage());
    117                         }
    118                     }
     193                                final Enumeration<URL> resources = cld
     194                                                .getResources(packagePath);
     195                                while (resources.hasMoreElements()) {
     196                                        URL url = resources.nextElement();
     197                                        resource = url;
     198                                }
     199                        } catch (IOException e) {
     200                                System.err
     201                                .println("A IO Error has occured when trying to use the ContextClassLoader"
     202                                                + System.getProperty("line.separator")
     203                                                + "Are you running from within Eclipse? (or just not with Jar)  Then make sure your"
     204                                                + " 'eclipse.expeditee.home' property is set correctly.  It is currently: '"
     205                                                + System.getProperty("eclipse.expeditee.home")
     206                                                + "'"
     207                                                + System.getProperty("line.separator")
     208                                                + "You can set it by adding a VM argument.  "
     209                                                + "Example: -Declipse.expeditee.home=D:\\Desktop\\Research\\expeditee-svn");
     210                                e.printStackTrace();
     211                        }
     212                        if (resource == null) {
     213                                throw new ClassNotFoundException("No resource for "
     214                                                + packagePath);
     215                        }
     216                        final File directory = new File(resource.getFile());
     217
     218                        final int splitPoint = directory.getPath().indexOf('!');
     219                        if (splitPoint > 0) {
     220                                String jarName = directory.getPath().substring(
     221                                                "file:".length(), splitPoint);
     222                                // Windows HACK
     223                                if (jarName.indexOf(":") >= 0)
     224                                        jarName = jarName.substring(1);
     225
     226                                if (jarName.indexOf("%20") > 0) {
     227                                        jarName = jarName.replace("%20", " ");
     228                                }
     229                                // System.out.println("JarName:" + jarName);
     230                                try {
     231                                        final JarFile jarFile = new JarFile(jarName);
     232                                        final Enumeration<?> entries = jarFile.entries();
     233                                        while (entries.hasMoreElements()) {
     234                                                final ZipEntry entry = (ZipEntry) entries.nextElement();
     235                                                final String className = entry.getName();
     236                                                if (className.startsWith(packagePath)) {
     237                                                        if (className.endsWith(".class")
     238                                                                        && !className.contains("$")) {
     239                                                                // The forward slash below is a forwards slash
     240                                                                // for
     241                                                                // both windows and linux
     242
     243                                                                String class_forname = className.substring(0,
     244                                                                                className.length() - 6);
     245                                                                class_forname = class_forname.replace('/', '.');
     246
     247                                                                classes.add(Class.forName(class_forname));
     248                                                        }
     249                                                }
     250                                        }
     251                                        try {
     252                                                jarFile.close();
     253                                        } catch (IOException e) {
     254                                                System.err
     255                                                .println("Error attempting to close Jar file");
     256                                                e.printStackTrace();
     257                                        }
     258                                } catch (IOException e) {
     259                                        System.err.println("Error Instantiating Jar File Object");
     260                                        e.printStackTrace();
     261                                }
     262                        } else {
     263
     264                                System.err
     265                                .println("A Error has occured when trying to use a Jar file to find actions or agents."
     266                                                + System.getProperty("line.separator")
     267                                                + "Are you running from within Eclipse? (or just not with Jar)  Then make sure your"
     268                                                + " 'eclipse.expeditee.home' property is set correctly.  It is currently: '"
     269                                                + System.getProperty("eclipse.expeditee.home")
     270                                                + "'"
     271                                                + System.getProperty("line.separator")
     272                                                + "You can set it by adding a VM argument.  "
     273                                                + "Example: -Declipse.expeditee.home=D:\\Desktop\\Research\\expeditee-svn");
     274                        }
     275                } else {
     276                        String eclipse_expeditee_home = System.getProperty(
     277                                        "eclipse.expeditee.home", "");
     278                        String full_package_path = eclipse_expeditee_home + File.separator
     279                                        + "bin" + File.separator + packagePath;
     280
     281                        final File directory = new File(full_package_path);
     282
     283                        if (directory.exists()) {
     284                                // Get the list of the files contained in the package
     285                                String[] files = directory.list();
     286                                for (int i = 0; i < files.length; i++) {
     287                                        // we are only interested in .class files
     288                                        if (files[i].endsWith(".class") && !files[i].contains("$")
     289                                                        && !files[i].equals("Actions.class")) {
     290                                                // removes the .class extension
     291                                                classes.add(Class.forName(pckgname
     292                                                                + files[i].substring(0, files[i].length() - 6)));
     293                                        }
     294                                }
     295                        } else {
     296                                throw new ClassNotFoundException("The package '" + pckgname
     297                                                + "' in the directory '" + directory
     298                                                + "' does not appear to be a valid package");
     299                        }
    119300                }
    120             } catch (final Exception e) {
    121                 System.err.println("Failed to process file: " + packageName);
    122                 e.printStackTrace();
    123             }
    124         } else {
    125             // loop through files in classpath
    126 
    127             String packageURLString = packageURL.toString();
    128             try {
    129                 URI uri = new URI(packageURLString);
    130                 File folder = new File(uri.getPath());
    131 
    132                 List<String> files = findFiles(folder);
    133                 for (String s : files) {
    134                     String entryName = realPackageName + s;
    135 
    136                     if (entryName.endsWith(".class")
    137                             && !entryName.contains("$")) {
    138                         entryName = entryName.substring(0,
    139                                 entryName.lastIndexOf('.'));
    140                         entryName = entryName.replace('/', '.');
    141 
    142                         names.add(entryName);
    143                         classes.add(Class.forName(entryName));
    144                     }
    145                 }
    146             } catch (Exception e) {
    147                 System.err.println("Failed to process file: "
    148                         + packageURLString);
    149                 e.printStackTrace();
    150             }
     301                return classes;
    151302        }
    152303
    153         return classes;
    154     }
    155 
    156     /**
    157      * Finds all files in a directory and it's subdirectories
    158      *
    159      * @param directory
    160      *            The folder to start in
    161      *
    162      * @return A list of Strings containing file paths relative to the starting
    163      *         directory
    164      */
    165     private static List<String> findFiles(File directory) {
    166         List<String> files = new LinkedList<String>();
    167         for (File f : directory.listFiles()) {
    168             if (f.isDirectory()) {
    169                 for (String s : findFiles(f)) {
    170                     files.add(f.getName() + "/" + s);
    171                 }
    172             } else {
    173                 files.add(f.getName());
    174             }
    175         }
    176         return files;
    177     }
    178 
    179     public static List<Class<?>> getClasses(final String pckgname)
    180             throws ClassNotFoundException {
    181 
    182         final ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
    183 
    184         // Must be a forward slash for loading resources
    185         final String packagePath = pckgname.replace('.', '/');
    186 
    187         if (System.getProperty("eclipse.expeditee.home") == null) {
    188             final ClassLoader cld = Thread.currentThread()
    189                     .getContextClassLoader();
    190             if (cld == null) {
    191                 throw new ClassNotFoundException("Can't get class loader.");
    192             }
    193             URL resource = null;
    194             try {
    195                 final Enumeration<URL> resources = cld
    196                         .getResources(packagePath);
    197                 while (resources.hasMoreElements()) {
    198                     URL url = resources.nextElement();
    199                     resource = url;
    200                 }
    201             } catch (IOException e) {
    202                 System.err
    203                         .println("A IO Error has occured when trying to use the ContextClassLoader"
    204                                 + System.getProperty("line.separator")
    205                                 + "Are you running from within Eclipse? (or just not with Jar)  Then make sure your"
    206                                 + " 'eclipse.expeditee.home' property is set correctly.  It is currently: '"
    207                                 + System.getProperty("eclipse.expeditee.home")
    208                                 + "'"
    209                                 + System.getProperty("line.separator")
    210                                 + "You can set it by adding a VM argument.  "
    211                                 + "Example: -Declipse.expeditee.home=D:\\Desktop\\Research\\expeditee-svn");
    212                 e.printStackTrace();
    213             }
    214             if (resource == null) {
    215                 throw new ClassNotFoundException("No resource for "
    216                         + packagePath);
    217             }
    218             final File directory = new File(resource.getFile());
    219 
    220             final int splitPoint = directory.getPath().indexOf('!');
    221             if (splitPoint > 0) {
    222                 String jarName = directory.getPath().substring(
    223                         "file:".length(), splitPoint);
    224                 // Windows HACK
    225                 if (jarName.indexOf(":") >= 0)
    226                     jarName = jarName.substring(1);
    227 
    228                 if (jarName.indexOf("%20") > 0) {
    229                     jarName = jarName.replace("%20", " ");
    230                 }
    231                 // System.out.println("JarName:" + jarName);
    232                 try {
    233                     final JarFile jarFile = new JarFile(jarName);
    234                     final Enumeration<?> entries = jarFile.entries();
    235                     while (entries.hasMoreElements()) {
    236                         final ZipEntry entry = (ZipEntry) entries.nextElement();
    237                         final String className = entry.getName();
    238                         if (className.startsWith(packagePath)) {
    239                             if (className.endsWith(".class")
    240                                     && !className.contains("$")) {
    241                                 // The forward slash below is a forwards slash
    242                                 // for
    243                                 // both windows and linux
    244 
    245                                 String class_forname = className.substring(0,
    246                                         className.length() - 6);
    247                                 class_forname = class_forname.replace('/', '.');
    248 
    249                                 classes.add(Class.forName(class_forname));
    250                             }
    251                         }
    252                     }
    253                     try {
    254                         jarFile.close();
    255                     } catch (IOException e) {
    256                         System.err
    257                                 .println("Error attempting to close Jar file");
    258                         e.printStackTrace();
    259                     }
    260                 } catch (IOException e) {
    261                     System.err.println("Error Instantiating Jar File Object");
    262                     e.printStackTrace();
    263                 }
    264             } else {
    265 
    266                 System.err
    267                         .println("A Error has occured when trying to use a Jar file to find actions or agents."
    268                                 + System.getProperty("line.separator")
    269                                 + "Are you running from within Eclipse? (or just not with Jar)  Then make sure your"
    270                                 + " 'eclipse.expeditee.home' property is set correctly.  It is currently: '"
    271                                 + System.getProperty("eclipse.expeditee.home")
    272                                 + "'"
    273                                 + System.getProperty("line.separator")
    274                                 + "You can set it by adding a VM argument.  "
    275                                 + "Example: -Declipse.expeditee.home=D:\\Desktop\\Research\\expeditee-svn");
    276             }
    277         } else {
    278             String eclipse_expeditee_home = System.getProperty(
    279                     "eclipse.expeditee.home", "");
    280             String full_package_path = eclipse_expeditee_home + File.separator
    281                     + "bin" + File.separator + packagePath;
    282 
    283             final File directory = new File(full_package_path);
    284 
    285             if (directory.exists()) {
    286                 // Get the list of the files contained in the package
    287                 String[] files = directory.list();
    288                 for (int i = 0; i < files.length; i++) {
    289                     // we are only interested in .class files
    290                     if (files[i].endsWith(".class") && !files[i].contains("$")
    291                             && !files[i].equals("Actions.class")) {
    292                         // removes the .class extension
    293                         classes.add(Class.forName(pckgname
    294                                 + files[i].substring(0, files[i].length() - 6)));
    295                     }
    296                 }
    297             } else {
    298                 throw new ClassNotFoundException("The package '" + pckgname
    299                         + "' in the directory '" + directory
    300                         + "' does not appear to be a valid package");
    301             }
    302         }
    303         return classes;
    304     }
    305 
    306304}
  • trunk/src/org/expeditee/settings/Settings.java

    r919 r1102  
    2626
    2727import org.expeditee.gui.AttributeValuePair;
    28 import org.expeditee.gui.DisplayIO;
    2928import org.expeditee.gui.Frame;
    3029import org.expeditee.gui.FrameCreator;
     
    3231import org.expeditee.gui.FrameUtils;
    3332import org.expeditee.gui.MessageBay;
    34 import org.expeditee.items.Item;
    3533import org.expeditee.items.Text;
    3634import org.expeditee.items.widgets.Password;
     
    5654                        // populate map of settings
    5755                        for(Field f : clazz.getFields()) {
    58                                 // only allow valid types
    59                                 if(! Setting.class.isAssignableFrom(f.getType())) {
    60                                         continue;
    61                                 }
     56                                // Only allow classes that inherit from Setting
     57                                if(!Setting.class.isAssignableFrom(f.getType())) continue;
     58                               
    6259                                try {
    6360                                        Setting s = (Setting) f.get(null);
    6461                        settings.put(f.getName().toLowerCase(), s);
    65                         if(s instanceof VariableSetting) {
    66                                 settingsList.add((VariableSetting) s);
    67                         }
     62                        if (s instanceof VariableSetting) settingsList.add((VariableSetting) s);
    6863                        orderedEntries.add(f.getName());
    6964                } catch (Exception e) {
     
    7166                }
    7267                        }
     68                       
    7369                        Method m = null;
     70                       
    7471                        try {
    7572                                m = clazz.getMethod("onParsed", Text.class);
     
    7774                                // System.err.println(clazz.getName() + " has no onParsed(Text t) callback");
    7875                        }
     76                       
    7977                        this.onParsed = m;
    8078                }
    8179        }
     80       
    8281        private static HashMap<String, PageDescriptor> _pages = new HashMap<String, PageDescriptor>();
    8382
    8483        private static boolean _init = false;
    85         public static void Init() {
     84       
     85        public static void Init()
     86        {
    8687                if(_init) return;
     88               
    8789                _init = true;
     90               
    8891                try {
    8992                        for(Class<?> clazz : PackageLoader.getClassesNew(SETTINGS_PACKAGE)) {
    9093                                // Ignore this class since it's the controller
    91                                 if(clazz.equals(Settings.class)) {
    92                                         continue;
    93                                 }
    94                                 String settingsPage = clazz.getPackage().getName().toLowerCase().substring(SETTINGS_PACKAGE_PARENT.length());
     94                                if(clazz.equals(Settings.class)) continue;
     95                               
     96                                String settingsPageName = clazz.getPackage().getName().toLowerCase().substring(SETTINGS_PACKAGE_PARENT.length());
    9597                                // System.out.println(settingsPage + " : " + clazz.getName());
    96                                 _pages.put(settingsPage, new PageDescriptor(clazz));
     98                                _pages.put(settingsPageName, new PageDescriptor(clazz));
    9799                        }
    98100
     
    100102                        e.printStackTrace();
    101103                }
    102                 FrameUtils.ParseProfile(FrameIO.LoadProfile(UserSettings.ProfileName.get()));
    103         }
    104        
    105         /**
    106          * Parses the settings tree, then resets any settings that were not set
    107          */
    108         public static void parseSettings(Text text) {
     104        }
     105       
     106        /** Parses the settings tree, then resets any settings that were not set. */
     107        public static void parseSettings(Text text)
     108        {
    109109                List<VariableSetting> set = parseSettings(text, "");
    110110                List<VariableSetting> toDefault = new LinkedList<VariableSetting>();
    111                 for(PageDescriptor pd : _pages.values()) {
    112                         toDefault.addAll(pd.settingsList);
    113                 }
     111               
     112                for(PageDescriptor pd : _pages.values()) toDefault.addAll(pd.settingsList);
     113               
    114114                toDefault.removeAll(set);
     115               
    115116                for(VariableSetting s : toDefault) {
    116117                        try {
    117                                 // System.out.println("Resetting " + s.getTooltip());
    118118                    s.reset();
    119                     // System.out.println("Set " + f.getName() + " to default value " + f.get(null));
    120119            } catch (Exception e) {
    121120                    e.printStackTrace();
     
    135134               
    136135                List<VariableSetting> set = new LinkedList<VariableSetting>();
     136               
    137137                Frame child = text.getChild();
    138                 if(child == null) {
    139                         return set;
    140                 }
     138               
     139                if(child == null) return set;
     140               
    141141                String settingsPage = prefix + text.getText().trim().toLowerCase().replaceAll("^@", "");
    142142                PageDescriptor pd = _pages.get(settingsPage);
    143                 if(pd == null) {
    144                         return set;
    145                 }
     143                if(pd == null) return set;
     144               
    146145                try {
    147146                        // set the fields
     
    160159                                }
    161160                        }
     161                       
    162162                        // parse all the settings items on this page
    163163                        for(Text t : items) {                           
     
    186186                                                        }
    187187                                                }
    188                                                 // System.out.println(s);
    189                                                 if(s == null) {
    190                                                         continue;
    191                                                 }
     188
     189                                                if(s == null) continue;
     190                                               
    192191                                                if(validPages.size() > 1) {
    193192                                                        StringBuffer warnMessage = new StringBuffer("Found multiple matching settings in the following settings subpages: ");
     
    202201                                                }
    203202                                        }
    204                                         if(s.setSetting(t) && s instanceof VariableSetting) {
    205                                                 set.add((VariableSetting) s);
    206                                         }
     203                                       
     204                                        if(s.setSetting(t) && s instanceof VariableSetting) set.add((VariableSetting) s);
     205                                       
    207206                                } catch (Exception e) {
    208207                                        e.printStackTrace();
    209208                                }
    210209                        }
     210                       
    211211                        // call the onParsed method if one exists
    212212                        if(pd.onParsed != null) {
    213213                                pd.onParsed.invoke(null, text);
    214214                        }
     215                       
    215216        } catch (Exception e) {
    216217            e.printStackTrace();
    217218            return set;
    218219        }
     220               
    219221                // if the page was a settings page, check if it has any subpages
    220222                for(Text t : child.getTextItems()) {
     
    224226        }
    225227       
    226         public static void generateSettingsTree(Text link) {
     228        public static void generateSettingsTree(Text link)
     229        {
    227230                generateSettingsTree("settings", link);
    228231        }
    229232       
    230         /**
    231          *
    232          * Generates settings tree
    233          *
    234          */
    235         private static void generateSettingsTree(String page, Text text) {
     233        /** Generates settings tree */
     234        private static void generateSettingsTree(String page, Text text)
     235        {
    236236                FrameCreator frames = new FrameCreator(text.getParentOrCurrentFrame().getFramesetName(), text.getParentOrCurrentFrame().getPath(), page, false, false);
    237237                // Frame frame = FrameIO.CreateFrame(text.getParentOrCurrentFrame().getFramesetName(), page, null);
  • trunk/src/org/expeditee/settings/network/proxy/ProxySettings.java

    r919 r1102  
    2323import org.expeditee.items.Item;
    2424import org.expeditee.items.Text;
    25 import org.expeditee.items.widgets.InteractiveWidget;
     25import org.expeditee.items.widgets.Widget;
     26import org.expeditee.items.widgets.JavaFXSwingWidget;
    2627import org.expeditee.items.widgets.Password;
    2728import org.expeditee.items.widgets.WidgetCorner;
     
    5253                                                if (passwordWidget == null) {
    5354                                                        try {
    54                                                                 passwordWidget = (Password) InteractiveWidget.createWidget((Text) i);
     55                                                                passwordWidget = (Password) Widget.createWidget((Text) i);
    5556                                                                if (Pass.get() != null) {
    5657                                                                        // MessageBay.displayMessage("pass was defined multiple times!", Color.ORANGE);
     
    6566                        } else if(i instanceof WidgetCorner || i instanceof WidgetEdge) {
    6667                                if(passwordWidget == null) {
    67                                         InteractiveWidget iw;
     68                                        Widget iw;
    6869                                        if(i instanceof WidgetCorner) {
    6970                                                iw = ((WidgetCorner)i).getWidgetSource();
     
    7374                                        if(iw instanceof Password) {
    7475                                                passwordWidget = (Password) iw;
     76                                        } else if (iw instanceof JavaFXSwingWidget && ((JavaFXSwingWidget) iw).getSwingWidget() instanceof Password) {
     77                                                passwordWidget = (Password) ((JavaFXSwingWidget) iw).getSwingWidget();
    7578                                        }
    7679                                        if(Pass.get() != null) {
  • trunk/src/org/expeditee/settings/templates/TemplateSettings.java

    r919 r1102  
    1919package org.expeditee.settings.templates;
    2020
    21 import java.awt.Color;
    22 
    23 import org.expeditee.gui.DisplayIO;
     21import org.expeditee.core.Colour;
     22import org.expeditee.gui.DisplayController;
    2423import org.expeditee.gui.Frame;
    2524import org.expeditee.gui.FrameUtils;
     
    5049                                i.setParent(null);
    5150                        }
    52                         DisplayIO.setCursor(Item.HIDDEN_CURSOR);
    53                         DisplayIO.setCursor(Item.DEFAULT_CURSOR);
     51                        DisplayController.setCursor(Item.HIDDEN_CURSOR);
     52                        DisplayController.setCursor(Item.DEFAULT_CURSOR);
    5453                }
    5554        };
    5655       
    57         public static final ArraySetting<Color> ColorWheel = new ArraySetting<Color>("The colours of items in the child frame are used to populate the colour wheel",
    58                         new Color[] { Color.BLACK, Color.RED, Color.BLUE, Item.GREEN, Color.MAGENTA, Color.YELLOW.darker(), Color.WHITE }) {
     56        public static final ArraySetting<Colour> ColorWheel = new ArraySetting<Colour>("The colours of items in the child frame are used to populate the colour wheel",
     57                        new Colour[] { Colour.BLACK, Colour.RED, Colour.BLUE, Item.GREEN, Colour.MAGENTA, Colour.YELLOW.darker(), Colour.WHITE }) {
    5958                @Override
    6059                public boolean setSetting(Text text) {
     
    6867        };
    6968       
    70         public static final ArraySetting<Color> FillColorWheel = new ArraySetting<Color>("The colours of items in the child frame are used to populate the colour wheel",
    71                         new Color[] { new Color(255, 150, 150), new Color(150, 150, 255), new Color(150, 255, 150),
    72                         new Color(255, 150, 255), new Color(255, 255, 100), Color.WHITE, Color.BLACK }) {
     69        public static final ArraySetting<Colour> FillColorWheel = new ArraySetting<Colour>("The colours of items in the child frame are used to populate the colour wheel",
     70                        new Colour[] { Colour.FromRGB255(255, 150, 150), Colour.FromRGB255(150, 150, 255), Colour.FromRGB255(150, 255, 150),
     71                        Colour.FromRGB255(255, 150, 255), Colour.FromRGB255(255, 255, 100), Colour.WHITE, Colour.BLACK }) {
    7372                @Override
    7473                public boolean setSetting(Text text) {
     
    8281        };
    8382       
    84         public static final ArraySetting<Color> BackgroundColorWheel = new ArraySetting<Color>("The colours of items in the child frame are used to populate the colour wheel",
    85                         new Color[] { new Color(235, 235, 235), new Color(225, 225, 255), new Color(195, 255, 255),
    86                         new Color(225, 255, 225), new Color(255, 255, 195), new Color(255, 225, 225),
    87                         new Color(255, 195, 255), Color.WHITE, Color.GRAY, Color.DARK_GRAY, Color.BLACK, null }) {
     83        public static final ArraySetting<Colour> BackgroundColorWheel = new ArraySetting<Colour>("The colours of items in the child frame are used to populate the colour wheel",
     84                        new Colour[] { Colour.FromRGB255(235, 235, 235), Colour.FromRGB255(225, 225, 255), Colour.FromRGB255(195, 255, 255),
     85                                        Colour.FromRGB255(225, 255, 225), Colour.FromRGB255(255, 255, 195), Colour.FromRGB255(255, 225, 225),
     86                                        Colour.FromRGB255(255, 195, 255), Colour.WHITE, Colour.GREY, Colour.DARK_GREY, Colour.BLACK, null }) {
    8887                @Override
    8988                public boolean setSetting(Text text) {
     
    107106                public Text generateText() {
    108107                        Text t = new Text("AnnotationTemplate");
    109                 t.setColor(Color.gray);
     108                t.setColor(Colour.GREY);
    110109                return t;
    111110                }
     
    116115                public Text generateText() {
    117116                        Text t = new Text("CommentTemplate");
    118                 t.setColor(Color.green.darker());
     117                t.setColor(Colour.GREEN.darker());
    119118                return t;
    120119                }
     
    125124                public Text generateText() {
    126125                        Text t = new Text("StatsTemplate");
    127                 t.setColor(Color.BLACK);
    128                 t.setBackgroundColor(new Color(0.9F, 0.9F, 0.9F));
     126                t.setColor(Colour.BLACK);
     127                t.setBackgroundColor(new Colour(0.9F, 0.9F, 0.9F));
    129128                t.setFamily(Text.MONOSPACED_FONT);
    130129                t.setSize(14);
     
    140139                t.setFontStyle("Bold");
    141140                t.setFamily("SansSerif");
    142                 t.setColor(Color.BLUE);
     141                t.setColor(Colour.BLUE);
    143142                t.setPosition(25, 50);
    144143                return t;
     
    157156                public Text generateText() {
    158157                        Text t = new Text("TooltipTemplate");
    159                 t.setColor(Color.BLACK);
    160                 t.setBackgroundColor(new Color(0.7F, 0.7F, 0.9F));
     158                t.setColor(Colour.BLACK);
     159                t.setBackgroundColor(new Colour(0.7F, 0.7F, 0.9F));
    161160                // t.setFamily(Text.MONOSPACED_FONT);
    162161                t.setSize(14);
  • trunk/src/org/expeditee/stats/SessionStats.java

    r919 r1102  
    1919package org.expeditee.stats;
    2020
    21 import java.awt.event.KeyEvent;
    22 import java.awt.event.MouseEvent;
    2321import java.sql.Time;
    2422import java.util.ArrayList;
     
    2725import java.util.List;
    2826
    29 import org.expeditee.gui.DisplayIO;
     27import org.expeditee.gio.input.KBMInputEvent;
     28import org.expeditee.gui.DisplayController;
    3029import org.expeditee.gui.Frame;
    31 import org.expeditee.gui.FrameMouseActions;
    3230import org.expeditee.gui.FrameUtils;
    3331import org.expeditee.gui.TimeKeeper;
     
    103101                stats.append(getCharacterStats());
    104102
    105                 stats.append("Version: ").append(DisplayIO.TITLE);
     103                stats.append("Version: ").append(DisplayController.TITLE);
    106104
    107105                return stats.toString();
     
    159157                        chars += counts[i];
    160158
    161                 chars -= counts[KeyEvent.VK_BACK_SPACE];
    162                 chars -= counts[KeyEvent.VK_DELETE];
     159                chars -= counts[Text.BACKSPACE_CHARACTER];
     160                chars -= counts[Text.DELETE_CHARACTER];
    163161
    164162                int EOS = counts['.'] + counts[','] + counts['!'] + counts['?'];
     
    177175                appendStat(stats, "Escape", _EscapeCount);
    178176                appendStat(stats, "Backspace", _BackspaceCount);
    179                 appendStat(stats, "Left", _MouseCounters[MouseEvent.BUTTON1]);
    180                 appendStat(stats, "Middle", _MouseCounters[MouseEvent.BUTTON2]);
    181                 appendStat(stats, "Right", _MouseCounters[MouseEvent.BUTTON3]);
     177                appendStat(stats, "Left", _MouseCounters[KBMInputEvent.MouseButton.LEFT.ordinal()]);
     178                appendStat(stats, "Middle", _MouseCounters[KBMInputEvent.MouseButton.MIDDLE.ordinal()]);
     179                appendStat(stats, "Right", _MouseCounters[KBMInputEvent.MouseButton.RIGHT.ordinal()]);
    182180
    183181                return stats.toString();
     
    231229         *            ascii value for the typed character
    232230         */
    233         public static void TypedChar(int ch) {
    234                 if (ch == KeyEvent.VK_BACK_SPACE || ch == KeyEvent.VK_DELETE)
    235                         _BackspaceCount++;
     231        public static void TypedChar(int ch)
     232        {
     233                if (ch == ((int) Text.BACKSPACE_CHARACTER) || ch == ((int) Text.DELETE_CHARACTER)) _BackspaceCount++;
    236234                UserEvent();
    237235                _CharCounts[ch]++;
     
    252250
    253251                _FrameEvents.add(Formatter.getTimeWithMillis(elapsedTime) + " "
    254                                 + DisplayIO.getMouseX() + " " + FrameMouseActions.getY() + " "
     252                                + DisplayController.getMouseX() + " " + DisplayController.getMouseY() + " "
    255253                                + description);
    256254        }
     
    278276        }
    279277
    280         public static void MouseClicked(int button) {
     278        public static void MouseClicked(KBMInputEvent.MouseButton button) {
    281279                UserEvent();
    282                 _MouseCounters[button]++;
     280                _MouseCounters[button.ordinal()]++;
    283281        }
    284282
  • trunk/src/org/expeditee/stats/StatsFrame.java

    r919 r1102  
    1919package org.expeditee.stats;
    2020
    21 import java.awt.event.MouseEvent;
    2221import java.lang.reflect.Method;
    2322import java.util.HashMap;
    2423import java.util.Map;
     24
     25import org.expeditee.gio.input.KBMInputEvent;
    2526
    2627public class StatsFrame extends SessionStats {
     
    162163       
    163164        public static String getLeftButtonCount() {
    164                 return _MouseCounters[MouseEvent.BUTTON1] + "";
     165                return _MouseCounters[KBMInputEvent.MouseButton.LEFT.ordinal()] + "";
    165166        }
    166167       
    167168        public static String getMiddleButtonCount() {
    168                 return _MouseCounters[MouseEvent.BUTTON2] + "";
     169                return _MouseCounters[KBMInputEvent.MouseButton.MIDDLE.ordinal()] + "";
    169170        }
    170171       
    171172        public static String getRightButtonCount() {
    172                 return _MouseCounters[MouseEvent.BUTTON3] + "";
     173                return _MouseCounters[KBMInputEvent.MouseButton.RIGHT.ordinal()] + "";
    173174        }
    174175}
  • trunk/src/org/expeditee/taskmanagement/EntitySaveManager.java

    r919 r1102  
    2424import java.util.Set;
    2525
    26 import javax.swing.SwingUtilities;
    27 
    2826
    2927/**
    30  * Manages time/resource-consuming saving procedures. For enties in an expeditee Frame that
     28 * Manages time/resource-consuming saving procedures. For entities in an expeditee Frame that
    3129 * requires heavy-duty saving, implement the entity as a SaveableEntity.
    3230 *
     
    135133         * Saves all current registered entities and clears registrations.
    136134         *
    137          * Returns immediatly.
     135         * Returns immediately.
    138136         */
    139137        public synchronized void saveAll() {
     
    167165        /**
    168166         * If something is saving, this will block the thread until all entities that
    169          * have been requested to be saved has finished their saving proccesses.
     167         * have been requested to be saved has finished their saving processes.
    170168         *
    171169         * @throws InterruptedException
     
    237235                                if (entity.doesNeedSaving()) {
    238236                                       
    239                                         // notify observers that save has started - on swing thread
    240                                         SwingUtilities.invokeLater(new SafeFireEvent(entity, true));
     237                                        // notify observers that save has started
     238                                        (new SafeFireEvent(entity, true)).run();
    241239       
    242240                                        // Complete the save
     
    248246       
    249247                                        // notify observers that save has finished - on swing thread
    250                                         SwingUtilities.invokeLater(new SafeFireEvent(entity, false));
     248                                        (new SafeFireEvent(entity, false)).run();
    251249                                }
    252250                        }
     
    254252               
    255253                /**
    256                  * Notifies all listners of save start/completion event when run.
     254                 * Notifies all listeners of save start/completion event when run.
    257255                 *
    258256                 * @author Brook Novak
  • trunk/tests/org/expeditee/gui/AttributeValuePairTest.java

    r310 r1102  
    11package org.expeditee.gui;
    2 
    3 import java.awt.Color;
    42
    53import junit.framework.TestCase;
    64
     5import org.expeditee.core.Colour;
    76import org.expeditee.items.Text;
    87
     
    3534                attributes.setText("c:red");
    3635                assertTrue(AttributeUtils.setAttribute(attributes, attributes));
    37                 assertEquals(Color.red, attributes.getColor());
     36                assertEquals(Colour.RED, attributes.getColor());
    3837                attributes.setText("color:green");
    3938                assertTrue(AttributeUtils.setAttribute(attributes, attributes));
    40                 assertEquals(Color.green, attributes.getColor());
     39                assertEquals(Colour.GREEN, attributes.getColor());
    4140        }
    4241
  • trunk/tests/org/expeditee/gui/DisplayIOTest.java

    r361 r1102  
    1111                showBlankFrame();
    1212
    13                 DisplayIO.ToggleTwinFrames();
    14                 assertTrue(DisplayIO.isTwinFramesOn());
    15                 DisplayIO.ToggleTwinFrames();
    16                 assertFalse(DisplayIO.isTwinFramesOn());
     13                DisplayController.toggleTwinFrames();
     14                assertTrue(DisplayController.isTwinFramesOn());
     15                DisplayController.toggleTwinFrames();
     16                assertFalse(DisplayController.isTwinFramesOn());
    1717        }
    1818
     
    2222               
    2323                //Draw a rectangle
    24                 DisplayIO.setCursorPosition(250, 250);
     24                DisplayController.setCursorPosition(250, 250);
    2525                Thread.sleep(100);
    26                 DisplayIO.clickMouse(InputEvent.BUTTON3_MASK);
     26                DisplayController.clickMouse(InputEvent.BUTTON3_MASK);
    2727                Thread.sleep(100);
    28                 DisplayIO.setCursorPosition(500, 500);
     28                DisplayController.setCursorPosition(500, 500);
    2929                Thread.sleep(100);
    30                 DisplayIO.clickMouse(InputEvent.BUTTON3_MASK);
     30                DisplayController.clickMouse(InputEvent.BUTTON3_MASK);
    3131                Thread.sleep(1000);
    3232                //Check that the line is there
     
    4242        public static void drawLine() throws InterruptedException {
    4343                //Draw a line
    44                 DisplayIO.setCursorPosition(100, 100);
     44                DisplayController.setCursorPosition(100, 100);
    4545                Thread.sleep(500);
    46                 DisplayIO.clickMouse(InputEvent.BUTTON2_MASK);
     46                DisplayController.clickMouse(InputEvent.BUTTON2_MASK);
    4747                Thread.sleep(100);
    48                 DisplayIO.setCursorPosition(200, 200);
     48                DisplayController.setCursorPosition(200, 200);
    4949                Thread.sleep(100);
    50                 DisplayIO.clickMouse(InputEvent.BUTTON2_MASK);
     50                DisplayController.clickMouse(InputEvent.BUTTON2_MASK);
    5151                Thread.sleep(100);
    5252        }
  • trunk/tests/org/expeditee/gui/FrameKeyboardsActionsTest.java

    r347 r1102  
    1212        public final void testTypeText() throws Exception {
    1313                Frame testFrame = showBlankFrame();
    14                 DisplayIO.typeKey(KeyEvent.VK_ESCAPE);
    15                 DisplayIO.typeText("hello");
     14                DisplayController.typeKey(KeyEvent.VK_ESCAPE);
     15                DisplayController.typeText("hello");
    1616                // Pick the item up in the middle
    1717                Item currentItem = FrameUtils.getCurrentItem();
    1818                assertNotNull(currentItem);
    19                 DisplayIO.setCursorPosition(currentItem.getX()
     19                DisplayController.setCursorPosition(currentItem.getX()
    2020                                + currentItem.getBoundsWidth() / 2,
    2121                                FrameMouseActions.MouseY - 2);
    2222                Thread.sleep(DELAY);
    23                 DisplayIO.clickMouse(InputEvent.BUTTON2_MASK);
     23                DisplayController.clickMouse(InputEvent.BUTTON2_MASK);
    2424                Thread.sleep(DELAY);
    25                 DisplayIO.setCursorPosition(
     25                DisplayController.setCursorPosition(
    2626                                Math.round(FrameGraphics.getMaxFrameSize().getWidth() / 2),
    2727                                FrameMouseActions.MouseY);
    2828                Thread.sleep(DELAY);
    29                 DisplayIO.typeKey(KeyEvent.VK_ESCAPE);
     29                DisplayController.typeKey(KeyEvent.VK_ESCAPE);
    3030                Thread.sleep(DELAY);
    31                 DisplayIO.clickMouse(InputEvent.BUTTON2_MASK);
     31                DisplayController.clickMouse(InputEvent.BUTTON2_MASK);
    3232                Thread.sleep(DELAY);
    3333
     
    3535                assertEquals(currentItem.getX(), FrameMouseActions.getX());
    3636
    37                 DisplayIO.typeKey(KeyEvent.VK_ESCAPE);
     37                DisplayController.typeKey(KeyEvent.VK_ESCAPE);
    3838
    39                 DisplayIO.typeStringDirect(0.05, "Hello Again!");
     39                DisplayController.typeStringDirect(0.05, "Hello Again!");
    4040
    41                 DisplayIO.typeKey(KeyEvent.VK_ESCAPE);
     41                DisplayController.typeKey(KeyEvent.VK_ESCAPE);
    4242
    43                 DisplayIO.typeText("Hello Again");
     43                DisplayController.typeText("Hello Again");
    4444
    4545                assertEquals(4, testFrame.getItems(false).size());
  • trunk/tests/org/expeditee/gui/FrameMouseActionsTest.java

    r361 r1102  
    1616                testLeftRanging(title);
    1717
    18                 String newFrameName = DisplayIO.getCurrentFrame().getName();
     18                String newFrameName = DisplayController.getCurrentFrame().getName();
    1919                Navigation.Back();
    2020
     
    3030                DisplayIOTest.drawLine();
    3131               
    32                 newFrameName = DisplayIO.getCurrentFrame().getName();
     32                newFrameName = DisplayController.getCurrentFrame().getName();
    3333                Navigation.Back();
    3434               
     
    4545        private void testLeftRanging(Text title) throws InterruptedException {
    4646                int y = title.getY() - 2;
    47                 DisplayIO.setCursorPosition(title.getX(), y);
     47                DisplayController.setCursorPosition(title.getX(), y);
    4848                Thread.sleep(500);
    49                 DisplayIO.pressMouse(InputEvent.BUTTON1_MASK);
     49                DisplayController.pressMouse(InputEvent.BUTTON1_MASK);
    5050                Thread.sleep(100);
    51                 DisplayIO.setCursorPosition(title.getX() + title.getBoundsWidth() / 2,
     51                DisplayController.setCursorPosition(title.getX() + title.getBoundsWidth() / 2,
    5252                                y);
    5353                Thread.sleep(500);
    54                 DisplayIO.releaseMouse(InputEvent.BUTTON1_MASK);
     54                DisplayController.releaseMouse(InputEvent.BUTTON1_MASK);
    5555                Thread.sleep(100);
    5656
     
    5959
    6060                // Highlight then unhighlight
    61                 DisplayIO.setCursorPosition(title.getX(), y);
     61                DisplayController.setCursorPosition(title.getX(), y);
    6262                Thread.sleep(500);
    63                 DisplayIO.pressMouse(InputEvent.BUTTON1_MASK);
     63                DisplayController.pressMouse(InputEvent.BUTTON1_MASK);
    6464                Thread.sleep(100);
    65                 DisplayIO.setCursorPosition(title.getX() + title.getBoundsWidth() / 2,
     65                DisplayController.setCursorPosition(title.getX() + title.getBoundsWidth() / 2,
    6666                                y);
    6767                Thread.sleep(500);
    68                 DisplayIO.setCursorPosition(title.getX(), y);
     68                DisplayController.setCursorPosition(title.getX(), y);
    6969                Thread.sleep(500);
    70                 DisplayIO.releaseMouse(InputEvent.BUTTON1_MASK);
     70                DisplayController.releaseMouse(InputEvent.BUTTON1_MASK);
    7171                Thread.sleep(500);
    7272
  • trunk/tests/org/expeditee/gui/FreeItemsTest.java

    r330 r1102  
    1313
    1414                FrameMouseActions.pickup(testFrame.getTitleItem());
    15                 assertTrue(FreeItems.itemsAttachedToCursor());
     15                assertTrue(FreeItems.hasItemsAttachedToCursor());
    1616                assertTrue(FreeItems.textOnlyAttachedToCursor());
    1717
    1818                FrameMouseActions.anchor(FreeItems.getInstance());
    19                 assertFalse(FreeItems.itemsAttachedToCursor());
     19                assertFalse(FreeItems.hasItemsAttachedToCursor());
    2020                assertFalse(FreeItems.textOnlyAttachedToCursor());
    2121
    2222                FrameMouseActions.pickup(testFrame.getAllItems());
    23                 assertTrue(FreeItems.itemsAttachedToCursor());
     23                assertTrue(FreeItems.hasItemsAttachedToCursor());
    2424                assertFalse(FreeItems.textOnlyAttachedToCursor());
    2525                assertEquals(8, FreeItems.getTextItems().size());
     
    3131
    3232                FrameMouseActions.anchor(FreeItems.getInstance());
    33                 assertFalse(FreeItems.itemsAttachedToCursor());
     33                assertFalse(FreeItems.hasItemsAttachedToCursor());
    3434                assertFalse(FreeItems.textOnlyAttachedToCursor());
    3535        }
  • trunk/tests/org/expeditee/gui/GuiTestCase.java

    r330 r1102  
    1818                Frame testFrame = FrameIO.LoadFrame("ExpediteeTest1");
    1919                testFrame.clear(false);
    20                 DisplayIO.setCurrentFrame(testFrame, true);
     20                DisplayController.setCurrentFrame(testFrame, true);
    2121                return testFrame;
    2222        }
     
    2525                Frame testFrame = FrameIO.LoadFrame(frameName);
    2626                testFrame.clear(false);
    27                 DisplayIO.setCurrentFrame(testFrame, true);
     27                DisplayController.setCurrentFrame(testFrame, true);
    2828                return testFrame;
    2929        }
  • trunk/tests/org/expeditee/io/ConversionTest.java

    r428 r1102  
    11package org.expeditee.io;
    22
    3 import java.awt.Color;
    43import java.awt.Font;
    54import java.awt.Point;
     
    109import junit.framework.TestCase;
    1110
     11import org.expeditee.core.Colour;
    1212import org.expeditee.items.Item;
    1313import org.expeditee.items.Justification;
     
    1717
    1818        public final void testGetColor() {
    19                 assertEquals(null, Conversion.getColor("TrAnSpArEnT", Color.white));
    20                 assertEquals(null, Conversion.getColor("Clear", Color.white));
    21                 assertEquals(null, Conversion.getColor("Auto", Color.white));
    22                 assertEquals(null, Conversion.getColor("Default", Color.white));
    23                 assertEquals(null, Conversion.getColor("adf", Color.red));
    24                 assertEquals(null, Conversion.getColor("none", Color.red));
    25                 assertEquals(null, Conversion.getColor("null", Color.red));
    26                 assertEquals(null, Conversion.getColor(null, Color.red));
    27                 assertEquals(null, Conversion.getColor("a0a0a0", Color.white));
    28 
    29                 assertEquals(Color.red, Conversion.getColor("100 0 0", Color.white));
    30                 assertEquals(Color.green, Conversion.getColor("0 100 0", Color.white));
    31                 assertEquals(Color.blue, Conversion.getColor("0 0 100", Color.white));
    32                 assertEquals(Color.white, Conversion.getColor("100 100 100",
    33                                 Color.white));
    34                 assertEquals(Color.gray, Conversion.getColor("50 50 50", Color.white));
    35                 assertEquals(Color.green, Conversion.getColor("-100 +0 -100",
    36                                 Color.white));
    37                 assertEquals(Color.green, Conversion.getColor("-10 +100 +0",
    38                                 Color.black));
    39                 assertEquals(Color.green, Conversion.getColor("+0 +110 +0", null));
    40 
    41                 assertEquals(Conversion.getColor("red9", Color.white), new Color(0.9F,
     19                assertEquals(null, Conversion.getColor("TrAnSpArEnT", Colour.WHITE));
     20                assertEquals(null, Conversion.getColor("Clear", Colour.WHITE));
     21                assertEquals(null, Conversion.getColor("Auto", Colour.WHITE));
     22                assertEquals(null, Conversion.getColor("Default", Colour.WHITE));
     23                assertEquals(null, Conversion.getColor("adf", Colour.RED));
     24                assertEquals(null, Conversion.getColor("none", Colour.RED));
     25                assertEquals(null, Conversion.getColor("null", Colour.RED));
     26                assertEquals(null, Conversion.getColor(null, Colour.RED));
     27                assertEquals(null, Conversion.getColor("a0a0a0", Colour.WHITE));
     28
     29                assertEquals(Colour.RED, Conversion.getColor("100 0 0", Colour.WHITE));
     30                assertEquals(Colour.GREEN, Conversion.getColor("0 100 0", Colour.WHITE));
     31                assertEquals(Colour.BLUE, Conversion.getColor("0 0 100", Colour.WHITE));
     32                assertEquals(Colour.WHITE, Conversion.getColor("100 100 100",
     33                                Colour.WHITE));
     34                assertEquals(Colour.GREY, Conversion.getColor("50 50 50", Colour.WHITE));
     35                assertEquals(Colour.GREEN, Conversion.getColor("-100 +0 -100",
     36                                Colour.WHITE));
     37                assertEquals(Colour.GREEN, Conversion.getColor("-10 +100 +0",
     38                                Colour.BLACK));
     39                assertEquals(Colour.GREEN, Conversion.getColor("+0 +110 +0", null));
     40
     41                assertEquals(Conversion.getColor("red9", Colour.WHITE), new Colour(0.9F,
    4242                                0.0F, 0.0F));
    43                 assertEquals(Conversion.getColor("BlUe15", Color.white), new Color(
     43                assertEquals(Conversion.getColor("BlUe15", Colour.WHITE), new Colour(
    4444                                0.0F, 0.0F, 1.0F));
    45                 assertEquals(Conversion.getColor("GREEN0", Color.white), new Color(
     45                assertEquals(Conversion.getColor("GREEN0", Colour.WHITE), new Colour(
    4646                                0.0F, 0.0F, 0.0F));
    47                 assertEquals(Conversion.getColor("GREEN3", Color.white), new Color(
     47                assertEquals(Conversion.getColor("GREEN3", Colour.WHITE), new Colour(
    4848                                0.0F, 0.3F, 0.0F));
    49                 assertEquals(Conversion.getColor("Blue1", Color.white), new Color(0.0F,
     49                assertEquals(Conversion.getColor("Blue1", Colour.WHITE), new Colour(0.0F,
    5050                                0.0F, 0.1F));
    5151        }
    5252
    5353        public final void testGetExpediteeColorCode() {
    54                 assertTrue(Conversion.getExpediteeColorCode(Color.red)
     54                assertTrue(Conversion.getExpediteeColorCode(Colour.RED)
    5555                                .equals("100 0 0"));
    56                 assertTrue(Conversion.getExpediteeColorCode(Color.green).equals(
     56                assertTrue(Conversion.getExpediteeColorCode(Colour.GREEN).equals(
    5757                                "0 100 0"));
    58                 assertTrue(Conversion.getExpediteeColorCode(Color.blue).equals(
     58                assertTrue(Conversion.getExpediteeColorCode(Colour.BLUE).equals(
    5959                                "0 0 100"));
    6060        }
     
    127127
    128128                // Test Color Conversion
    129                 assertEquals(Color.darkGray, Conversion.Convert(Color.class,
     129                assertEquals(Colour.DARK_GREY, Conversion.Convert(Colour.class,
    130130                                "dark_gray"));
    131                 assertEquals(Color.darkGray, Conversion
    132                                 .Convert(Color.class, "DARKGRAY"));
    133                 assertEquals(Color.red, Conversion.Convert(Color.class, "red"));
    134                 assertEquals(Color.red, Conversion.Convert(Color.class, "Red"));
    135                 assertEquals(Color.red, Conversion.Convert(Color.class, "RED"));
    136                 assertEquals(Color.red, Conversion.Convert(Color.class, " 100 "));
    137                 assertEquals(Color.green, Conversion.Convert(Color.class, "0  100"));
    138                 assertEquals(Color.blue, Conversion.Convert(Color.class, "0 0 100"));
     131                assertEquals(Colour.DARK_GREY, Conversion
     132                                .Convert(Colour.class, "DARKGRAY"));
     133                assertEquals(Colour.RED, Conversion.Convert(Colour.class, "red"));
     134                assertEquals(Colour.RED, Conversion.Convert(Colour.class, "Red"));
     135                assertEquals(Colour.RED, Conversion.Convert(Colour.class, "RED"));
     136                assertEquals(Colour.RED, Conversion.Convert(Colour.class, " 100 "));
     137                assertEquals(Colour.GREEN, Conversion.Convert(Colour.class, "0  100"));
     138                assertEquals(Colour.BLUE, Conversion.Convert(Colour.class, "0 0 100"));
    139139                // Test Boolean Conversion
    140140                assertEquals(true, Conversion.Convert(boolean.class, ""));
     
    151151
    152152        public final void testConvertClassStringObject() {
    153                 assertEquals(new Color(255, 0, 255), Conversion.Convert(Color.class,
     153                assertEquals(Colour.FromRGB255(255, 0, 255), Conversion.Convert(Colour.class,
    154154                                "+100 +0 +100", null));
    155                 assertEquals(Color.red, Conversion.Convert(Color.class, "+100 +0 -100",
    156                                 Color.blue));
    157                 assertEquals(Color.black, Conversion.Convert(Color.class, "-0 +0 -100",
    158                                 Color.blue));
     155                assertEquals(Colour.RED, Conversion.Convert(Colour.class, "+100 +0 -100",
     156                                Colour.BLUE));
     157                assertEquals(Colour.BLACK, Conversion.Convert(Colour.class, "-0 +0 -100",
     158                                Colour.BLUE));
    159159                // Float test
    160160                assertEquals(2.0F, Conversion.Convert(float.class, "2.0", null));
     
    305305
    306306                        assertEquals("100 0 0", Conversion.ConvertToExpeditee(getPosition,
    307                                         Color.red));
     307                                        Colour.RED));
    308308
    309309                        assertEquals(null, Conversion.ConvertToExpeditee(getPosition, null));
     
    325325
    326326        public final void testGetCssColor() {
    327                 assertEquals("rgb(255,0,0)", Conversion.getCssColor(Color.red));
    328                 assertEquals("rgb(255,0,255)", Conversion.getCssColor(Color.magenta));
    329                 assertEquals("rgb(128,128,128)", Conversion.getCssColor(Color.gray));
     327                assertEquals("rgb(255,0,0)", Conversion.getCssColor(Colour.RED));
     328                assertEquals("rgb(255,0,255)", Conversion.getCssColor(Colour.MAGENTA));
     329                assertEquals("rgb(128,128,128)", Conversion.getCssColor(Colour.GREY));
    330330        }
    331331}
  • trunk/tests/org/expeditee/items/widgets/InteractiveWidgetTest.java

    r227 r1102  
    77        public void testParseArgs1() {
    88               
    9                 assertNull(InteractiveWidget.parseArgs(null));
    10                 assertNull(InteractiveWidget.parseArgs(""));
    11                 assertNull(InteractiveWidget.parseArgs("         "));
     9                assertNull(Widget.parseArgs(null));
     10                assertNull(Widget.parseArgs(""));
     11                assertNull(Widget.parseArgs("         "));
    1212               
    13                 String[] args = InteractiveWidget.parseArgs("arg1");
     13                String[] args = Widget.parseArgs("arg1");
    1414                assertEquals(1, args.length);
    1515                assertEquals("arg1", args[0]);
    1616               
    17                 args = InteractiveWidget.parseArgs("arg1 arg2");
     17                args = Widget.parseArgs("arg1 arg2");
    1818                assertEquals(2, args.length);
    1919                assertEquals("arg1", args[0]);
    2020                assertEquals("arg2", args[1]);
    2121               
    22                 args = InteractiveWidget.parseArgs("  )*^*$^   24224 5775    13 :  ");
     22                args = Widget.parseArgs("  )*^*$^   24224 5775    13 :  ");
    2323                assertEquals(5, args.length);
    2424                assertEquals(")*^*$^", args[0]);
     
    3131        public void testParseArgs2() {
    3232               
    33                 String[] args = InteractiveWidget.parseArgs("\"");
     33                String[] args = Widget.parseArgs("\"");
    3434                assertNull(args);
    3535               
    36                 args = InteractiveWidget.parseArgs("\"\"");
     36                args = Widget.parseArgs("\"\"");
    3737                assertEquals(1, args.length);
    3838                assertEquals("\"", args[0]);
    3939               
    40                 args = InteractiveWidget.parseArgs("\"\"\"\"\"\"\"");
     40                args = Widget.parseArgs("\"\"\"\"\"\"\"");
    4141                assertEquals(1, args.length);
    4242                assertEquals("\"\"\"", args[0]);
    4343               
    44                 args = InteractiveWidget.parseArgs("  \"         \"   ");
     44                args = Widget.parseArgs("  \"         \"   ");
    4545                assertEquals(1, args.length);
    4646                assertEquals("         ", args[0]);
    4747               
    48                 args = InteractiveWidget.parseArgs("arg1\" \"");
     48                args = Widget.parseArgs("arg1\" \"");
    4949                assertEquals(1, args.length);
    5050                assertEquals("arg1 ", args[0]);
    5151               
    52                 args = InteractiveWidget.parseArgs("arg1\" \"+8");
     52                args = Widget.parseArgs("arg1\" \"+8");
    5353                assertEquals(1, args.length);
    5454                assertEquals("arg1 +8", args[0]);
    5555               
    56                 args = InteractiveWidget.parseArgs("abc\" \"de 123\" \"45");
     56                args = Widget.parseArgs("abc\" \"de 123\" \"45");
    5757                assertEquals(2, args.length);
    5858                assertEquals("abc de", args[0]);
    5959                assertEquals("123 45", args[1]);
    6060               
    61                 args = InteractiveWidget.parseArgs("adgdag\" adgdgadag");
     61                args = Widget.parseArgs("adgdag\" adgdgadag");
    6262                assertEquals(1, args.length);
    6363                assertEquals("adgdag adgdgadag", args[0]);
    6464               
    65                 args = InteractiveWidget.parseArgs("abc\"\"\" s \"   ggg");
     65                args = Widget.parseArgs("abc\"\"\" s \"   ggg");
    6666                assertEquals(2, args.length);
    6767                assertEquals("abc\" s ", args[0]);
    6868                assertEquals("ggg", args[1]);
    6969               
    70                 args = InteractiveWidget.parseArgs("abc\"\"123");
     70                args = Widget.parseArgs("abc\"\"123");
    7171                assertEquals(1, args.length);
    7272                assertEquals("abc\"123", args[0]);
    7373               
    74                 args = InteractiveWidget.parseArgs("file=\"a URL with spaces\" title=\"A title with spaces and \"\"quotes\"\"\"");
     74                args = Widget.parseArgs("file=\"a URL with spaces\" title=\"A title with spaces and \"\"quotes\"\"\"");
    7575                assertEquals(2, args.length);
    7676                assertEquals("file=a URL with spaces", args[0]);
     
    101101        private void AssertArgParsingAndFormatting(String str) {
    102102               
    103                 String[] args1 = InteractiveWidget.parseArgs(str);
     103                String[] args1 = Widget.parseArgs(str);
    104104               
    105                 String formatted = InteractiveWidget.formatArgs(args1);
     105                String formatted = Widget.formatArgs(args1);
    106106               
    107                 String[] args2 = InteractiveWidget.parseArgs(formatted);
     107                String[] args2 = Widget.parseArgs(formatted);
    108108               
    109109                if (args1 == null || args2 == null) assertEquals(args1, args2);
Note: See TracChangeset for help on using the changeset viewer.