Changeset 23192 in osm for applications/editors/josm


Ignore:
Timestamp:
2010-09-15T18:59:53+02:00 (14 years ago)
Author:
stoecker
Message:

remove tabs

Location:
applications/editors/josm/plugins
Files:
140 edited

Legend:

Unmodified
Added
Removed
  • applications/editors/josm/plugins/00_plugin_dir_template/src/org/openstreetmap/josm/plugins/ImportImagePlugin/ImageImportPlugin.java

    r23139 r23192  
    3131 */
    3232public class ImageImportPlugin extends Plugin{
    33        
    34         private static Logger logger;
    35        
    36         JMenu mainmenu = null;
    37         JosmAction loadFileAction = null;
    38        
    39         // custom Classloader
    40         static ClassLoader pluginClassLoader;
    41        
    42         // plugin proerties
    43         static Properties pluginProps;
    44        
    45         // path constants
    46         static final String PLUGIN_DIR = Main.pref.getPluginsDirectory().getAbsolutePath() + "/ImageImportPlugin/";
    47         static final String PLUGINPROPERTIES_PATH = Main.pref.getPluginsDirectory().getAbsolutePath() + "/ImageImportPlugin/pluginProperties.properties";
    48         static final String PLUGINLIBRARIES_DIR = Main.pref.getPluginsDirectory().getAbsolutePath() + "/ImageImportPlugin/lib/";
    49         static final String PLUGINPROPERTIES_FILENAME = "pluginProperties.properties";
    50         static final String LOGGING_PROPERTIES_FILEPATH = Main.pref.getPluginsDirectory().getAbsolutePath() + "/ImageImportPlugin/log4j.properties/";
    51        
    52        
    53         public Properties getPluginProps() {
    54                 return pluginProps;
    55         }
    56 
    57 
    58         /**
    59         * constructor
    60         *
    61         * @param info
    62         */
    63         public ImageImportPlugin(PluginInformation info){
    64                 super(info);
    65                
    66                 try {
    67                        
    68                         // First create custom ClassLoader to load resources from the main JAR
    69                         pluginClassLoader = createPluginClassLoader();
    70                        
    71                         // Initialize logger
    72                         initializeLogger(pluginClassLoader);
    73                        
    74                         // Check whether plugin has already been installed. Otherwise install
    75                         checkInstallation();
    76                        
    77                         // If resources are available load properties from plugin directory
    78                         if(pluginProps == null || pluginProps.isEmpty())
    79                         {
    80                                 pluginProps = new Properties();
    81                                 pluginProps.load(new File(PLUGINPROPERTIES_PATH).toURI().toURL().openStream());
    82                                 logger.debug("Plugin properties loaded");
    83                         }
    84 
    85                         /* Change class path:
    86                         * Use java reflection methods to add URLs to the class-path.
    87                         * Changes take effect when calling methods of other plugin classes
    88                         * (new threads)
    89                         * */
    90                         URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    91                         String[] libraryNames = pluginProps.getProperty("libraries").split(",");
    92                         Class<URLClassLoader> sysclass = URLClassLoader.class;
    93                         Method method = sysclass.getDeclaredMethod("addURL", new Class[]{URL.class});
    94                         method.setAccessible(true);
    95                         for (int i = 0; i < libraryNames.length; i++) {
    96                                 File library = new File(PLUGINLIBRARIES_DIR + "/" + libraryNames[i]);
    97                                 method.invoke(sysLoader, new Object[]{library.toURI().toURL()});
    98                         }
    99                
    100                
    101                         // load information about supported reference systems
    102                         PluginOperations.loadCRSData(pluginProps);
    103                        
    104                         // create new Action for menu entry
    105                         LoadImageAction loadFileAction = new LoadImageAction();
    106                         loadFileAction.setEnabled(true);
    107                        
    108                         // add menu entries
    109                         Main.main.menu.fileMenu.insert(loadFileAction, 8);
    110                         Main.main.menu.fileMenu.insertSeparator(9);
    111                        
    112 
    113                 } catch (Exception e) {
    114                         logger.fatal("Error while loading plugin", e);
    115                         try {
    116                                 throw e;
    117                         } catch (Exception e1) {
    118                                 e1.printStackTrace();
    119                         }
    120                 }
    121 
    122                 logger.info("Plugin successfully loaded.");
    123                
    124         }
    125 
    126        
    127        
    128         /**
    129         * Checks whether plugin resources are available.
    130         * If not, start install procedure.
    131         *
    132         * @throws IOException
    133         */
    134         private void checkInstallation() throws IOException
    135         {
    136                
    137                 // check plugin resource state
    138                 boolean isInstalled = true;
    139                 if(!new File(PLUGINPROPERTIES_PATH).exists()
    140                                 || !new File(PLUGIN_DIR).exists()
    141                                 || !new File(PLUGINLIBRARIES_DIR).exists())
    142                         isInstalled = false;
    143                
    144                
    145                 // if properties file doesn't exist, install plugin
    146                 if(!isInstalled)
    147                 {
    148                        
    149                         /*----------- Begin installation ---------------*/
    150                        
    151                         // check if plugin directory exist
    152                         File pluginDir = new File(PLUGIN_DIR);
    153                         if(!pluginDir.exists()){
    154                                 pluginDir.mkdir();
    155                         }
    156                        
    157                         // check if "lib" directory exist
    158                         File libDir = new File(PLUGINLIBRARIES_DIR);
    159                         if(!libDir.exists()){
    160                                 libDir.mkdir();
    161                         }
    162                        
    163                         // create local properties file
    164                         if(pluginProps == null || pluginProps.isEmpty()){
    165                                
    166                                 FileWriter fw = new FileWriter(new File(PLUGINPROPERTIES_PATH));
    167                                 URL propertiesURL = pluginClassLoader.getResource("resources/" + PLUGINPROPERTIES_FILENAME);
    168                                 pluginProps = new Properties();
    169                                 pluginProps.load(propertiesURL.openStream());
    170                                 pluginProps.store(fw, null);
    171                                 fw.close();
    172                                 logger.debug("Plugin properties loaded");
    173                         }
    174                        
    175                         if(!new File(LOGGING_PROPERTIES_FILEPATH).exists())
    176                         {
    177                                 FileWriter fw = new FileWriter(new File(LOGGING_PROPERTIES_FILEPATH));
    178                                 URL propertiesURL = pluginClassLoader.getResource("resources/log4j.properties");
    179                                 Properties loggingProps = new Properties();
    180                                 loggingProps.load(propertiesURL.openStream());
    181                                 loggingProps.store(fw, null);
    182                                 fw.close();
    183                                 logger.debug("Logging properties created");
    184                         }
    185 
    186                        
    187                         // Copy all needed JAR files to $PLUGIN_DIR$/lib/ 
    188                         String[] libStrings = pluginProps.getProperty("libraries").split(",");
    189                        
    190                         for (int i = 0; i < libStrings.length; i++) {
    191                                
    192                                 URL url = pluginClassLoader.getResource("lib/" + libStrings[i]);
    193                                
    194                                 FileOutputStream out = null;
    195                                
    196                                 try{
    197                                         out = new FileOutputStream(new File(libDir, libStrings[i]));
    198                                 } catch (FileNotFoundException e) {
    199                                         break;
    200                                 }
    201                                
    202                                 BufferedInputStream in = null;
    203                                 try
    204                                 {
    205                                         in = new BufferedInputStream(url.openStream());
    206 
    207                                         byte[] buffer = new byte[1024];
    208                                         while (true)
    209                                         {
    210                                                 int count = in.read(buffer);
    211                                                 if (count == -1)
    212                                                         break;
    213                                                 out.write(buffer, 0, count);
    214                                         }
    215                                 }
    216                                 finally
    217                                 {
    218                                         if (in != null)
    219                                                 in.close();
    220                                 }
    221                         }
    222                         logger.debug("Plugin successfully installed");
    223                 }
    224         }
    225 
    226 
    227         /**
    228         * Initialize logger using plugin classloader.
    229         *
    230         * @param cl
    231         */
    232         private void initializeLogger(ClassLoader cl) {
    233 
    234                 Properties props = new Properties();
    235                 try {
    236                         props.load(new File(LOGGING_PROPERTIES_FILEPATH).toURI().toURL().openStream());
    237                        
    238                         // Set file for logging here:
    239                         props.setProperty("log4j.appender.MyRoFiAppender.file",
    240                                         (Main.pref.getPluginsDirectory().getAbsolutePath() + "/ImageImportPlugin/" + "log.log"));
    241                        
    242                         PropertyConfigurator.configure(props);
    243 
    244                         logger = Logger.getLogger(ImageImportPlugin.class);
    245                        
    246                         logger.info("Logger successfully initialized.");
    247                        
    248                         return;
    249                
    250                 } catch (IOException e) {
    251                         System.out.println("Logging properties file not found. Using standard settings.");
    252                 }
    253                
    254                 // if no log4j.properties file can be found, initialize manually:
    255                
    256                 props.setProperty("log4j.rootLogger", "INFO, A");
    257                 props.setProperty("log4j.appender.A", "org.apache.log4j.FileAppender");
    258 
    259                 props.setProperty("log4j.appender.A.layout",
    260                                 "org.apache.log4j.PatternLayout ");
    261                 props.setProperty("log4j.appender.A.layout.ConversionPattern",
    262                                 "%d{ISO8601} %-5p [%t] %c: %m%n");
    263 
    264                 // Set file for logging here:
    265                 props.setProperty("log4j.appender.A.file",
    266                                 (Main.pref.getPluginsDirectory().getAbsolutePath() + "/ImageImportPlugin/" + "log.log"));
    267                
    268                 PropertyConfigurator.configure(props);
    269                 logger = Logger.getLogger(ImageImportPlugin.class);
    270                 logger.info("Logger successfully initialized with standard settings.");
    271                
    272         }
    273        
    274         /**
    275         * get a plugin-specific classloader.
    276         *
    277         * @return
    278         * @throws MalformedURLException
    279         */
    280         private ClassLoader createPluginClassLoader() throws MalformedURLException
    281         {
    282                 ClassLoader loader = null;
    283                 loader = URLClassLoader.newInstance(
    284                             new URL[] { new File(Main.pref.getPluginsDirectory().getAbsolutePath() + "/ImportImagePlugin.jar").toURI().toURL()},
    285                             ImageImportPlugin.class.getClassLoader()
    286                                 );
    287                
    288                 return loader;
    289         }
    290        
     33   
     34    private static Logger logger;
     35   
     36    JMenu mainmenu = null;
     37    JosmAction loadFileAction = null;
     38   
     39    // custom Classloader
     40    static ClassLoader pluginClassLoader;
     41   
     42    // plugin proerties
     43    static Properties pluginProps;
     44   
     45    // path constants
     46    static final String PLUGIN_DIR = Main.pref.getPluginsDirectory().getAbsolutePath() + "/ImageImportPlugin/";
     47    static final String PLUGINPROPERTIES_PATH = Main.pref.getPluginsDirectory().getAbsolutePath() + "/ImageImportPlugin/pluginProperties.properties";
     48    static final String PLUGINLIBRARIES_DIR = Main.pref.getPluginsDirectory().getAbsolutePath() + "/ImageImportPlugin/lib/";
     49    static final String PLUGINPROPERTIES_FILENAME = "pluginProperties.properties";
     50    static final String LOGGING_PROPERTIES_FILEPATH = Main.pref.getPluginsDirectory().getAbsolutePath() + "/ImageImportPlugin/log4j.properties/";
     51   
     52   
     53    public Properties getPluginProps() {
     54        return pluginProps;
     55    }
     56
     57
     58    /**
     59    * constructor
     60    *
     61    * @param info
     62    */
     63    public ImageImportPlugin(PluginInformation info){
     64        super(info);
     65       
     66        try {
     67           
     68            // First create custom ClassLoader to load resources from the main JAR
     69            pluginClassLoader = createPluginClassLoader();
     70           
     71            // Initialize logger
     72            initializeLogger(pluginClassLoader);
     73           
     74            // Check whether plugin has already been installed. Otherwise install
     75            checkInstallation();
     76           
     77            // If resources are available load properties from plugin directory
     78            if(pluginProps == null || pluginProps.isEmpty())
     79            {
     80                pluginProps = new Properties();
     81                pluginProps.load(new File(PLUGINPROPERTIES_PATH).toURI().toURL().openStream());
     82                logger.debug("Plugin properties loaded");
     83            }
     84
     85            /* Change class path:
     86            * Use java reflection methods to add URLs to the class-path.
     87            * Changes take effect when calling methods of other plugin classes
     88            * (new threads)
     89            * */
     90            URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
     91            String[] libraryNames = pluginProps.getProperty("libraries").split(",");
     92            Class<URLClassLoader> sysclass = URLClassLoader.class;
     93            Method method = sysclass.getDeclaredMethod("addURL", new Class[]{URL.class});
     94            method.setAccessible(true);
     95            for (int i = 0; i < libraryNames.length; i++) {
     96                File library = new File(PLUGINLIBRARIES_DIR + "/" + libraryNames[i]);
     97                method.invoke(sysLoader, new Object[]{library.toURI().toURL()});
     98            }
     99           
     100           
     101            // load information about supported reference systems
     102            PluginOperations.loadCRSData(pluginProps);
     103           
     104            // create new Action for menu entry
     105            LoadImageAction loadFileAction = new LoadImageAction();
     106            loadFileAction.setEnabled(true);
     107           
     108            // add menu entries
     109            Main.main.menu.fileMenu.insert(loadFileAction, 8);
     110            Main.main.menu.fileMenu.insertSeparator(9);
     111           
     112
     113        } catch (Exception e) {
     114            logger.fatal("Error while loading plugin", e);
     115            try {
     116                throw e;
     117            } catch (Exception e1) {
     118                e1.printStackTrace();
     119            }
     120        }
     121
     122        logger.info("Plugin successfully loaded.");
     123       
     124    }
     125
     126   
     127   
     128    /**
     129    * Checks whether plugin resources are available.
     130    * If not, start install procedure.
     131    *
     132    * @throws IOException
     133    */
     134    private void checkInstallation() throws IOException
     135    {
     136       
     137        // check plugin resource state
     138        boolean isInstalled = true;
     139        if(!new File(PLUGINPROPERTIES_PATH).exists()
     140                || !new File(PLUGIN_DIR).exists()
     141                || !new File(PLUGINLIBRARIES_DIR).exists())
     142            isInstalled = false;
     143       
     144       
     145        // if properties file doesn't exist, install plugin
     146        if(!isInstalled)
     147        {
     148           
     149            /*----------- Begin installation ---------------*/
     150           
     151            // check if plugin directory exist
     152            File pluginDir = new File(PLUGIN_DIR);
     153            if(!pluginDir.exists()){
     154                pluginDir.mkdir();
     155            }
     156           
     157            // check if "lib" directory exist
     158            File libDir = new File(PLUGINLIBRARIES_DIR);
     159            if(!libDir.exists()){
     160                libDir.mkdir();
     161            }
     162           
     163            // create local properties file
     164            if(pluginProps == null || pluginProps.isEmpty()){
     165               
     166                FileWriter fw = new FileWriter(new File(PLUGINPROPERTIES_PATH));
     167                URL propertiesURL = pluginClassLoader.getResource("resources/" + PLUGINPROPERTIES_FILENAME);
     168                pluginProps = new Properties();
     169                pluginProps.load(propertiesURL.openStream());
     170                pluginProps.store(fw, null);
     171                fw.close();
     172                logger.debug("Plugin properties loaded");
     173            }
     174           
     175            if(!new File(LOGGING_PROPERTIES_FILEPATH).exists())
     176            {
     177                FileWriter fw = new FileWriter(new File(LOGGING_PROPERTIES_FILEPATH));
     178                URL propertiesURL = pluginClassLoader.getResource("resources/log4j.properties");
     179                Properties loggingProps = new Properties();
     180                loggingProps.load(propertiesURL.openStream());
     181                loggingProps.store(fw, null);
     182                fw.close();
     183                logger.debug("Logging properties created");
     184            }
     185
     186           
     187            // Copy all needed JAR files to $PLUGIN_DIR$/lib/ 
     188            String[] libStrings = pluginProps.getProperty("libraries").split(",");
     189           
     190            for (int i = 0; i < libStrings.length; i++) {
     191               
     192                URL url = pluginClassLoader.getResource("lib/" + libStrings[i]);
     193               
     194                FileOutputStream out = null;
     195               
     196                try{
     197                    out = new FileOutputStream(new File(libDir, libStrings[i]));
     198                } catch (FileNotFoundException e) {
     199                    break;
     200                }
     201               
     202                BufferedInputStream in = null;
     203                try
     204                {
     205                    in = new BufferedInputStream(url.openStream());
     206
     207                    byte[] buffer = new byte[1024];
     208                    while (true)
     209                    {
     210                        int count = in.read(buffer);
     211                        if (count == -1)
     212                            break;
     213                        out.write(buffer, 0, count);
     214                    }
     215                }
     216                finally
     217                {
     218                    if (in != null)
     219                        in.close();
     220                }
     221            }
     222            logger.debug("Plugin successfully installed");
     223        }
     224    }
     225
     226
     227    /**
     228    * Initialize logger using plugin classloader.
     229    *
     230    * @param cl
     231    */
     232    private void initializeLogger(ClassLoader cl) {
     233
     234        Properties props = new Properties();
     235        try {
     236            props.load(new File(LOGGING_PROPERTIES_FILEPATH).toURI().toURL().openStream());
     237           
     238            // Set file for logging here:
     239            props.setProperty("log4j.appender.MyRoFiAppender.file",
     240                    (Main.pref.getPluginsDirectory().getAbsolutePath() + "/ImageImportPlugin/" + "log.log"));
     241           
     242            PropertyConfigurator.configure(props);
     243
     244            logger = Logger.getLogger(ImageImportPlugin.class);
     245           
     246            logger.info("Logger successfully initialized.");
     247           
     248            return;
     249       
     250        } catch (IOException e) {
     251            System.out.println("Logging properties file not found. Using standard settings.");
     252        }
     253       
     254        // if no log4j.properties file can be found, initialize manually:
     255       
     256        props.setProperty("log4j.rootLogger", "INFO, A");
     257        props.setProperty("log4j.appender.A", "org.apache.log4j.FileAppender");
     258
     259        props.setProperty("log4j.appender.A.layout",
     260                "org.apache.log4j.PatternLayout ");
     261        props.setProperty("log4j.appender.A.layout.ConversionPattern",
     262                "%d{ISO8601} %-5p [%t] %c: %m%n");
     263
     264        // Set file for logging here:
     265        props.setProperty("log4j.appender.A.file",
     266                (Main.pref.getPluginsDirectory().getAbsolutePath() + "/ImageImportPlugin/" + "log.log"));
     267       
     268        PropertyConfigurator.configure(props);
     269        logger = Logger.getLogger(ImageImportPlugin.class);
     270        logger.info("Logger successfully initialized with standard settings.");
     271       
     272    }
     273   
     274    /**
     275    * get a plugin-specific classloader.
     276    *
     277    * @return
     278    * @throws MalformedURLException
     279    */
     280    private ClassLoader createPluginClassLoader() throws MalformedURLException
     281    {
     282        ClassLoader loader = null;
     283        loader = URLClassLoader.newInstance(
     284                new URL[] { new File(Main.pref.getPluginsDirectory().getAbsolutePath() + "/ImportImagePlugin.jar").toURI().toURL()},
     285                ImageImportPlugin.class.getClassLoader()
     286                );
     287       
     288        return loader;
     289    }
     290   
    291291}
  • applications/editors/josm/plugins/00_plugin_dir_template/src/org/openstreetmap/josm/plugins/ImportImagePlugin/ImageLayer.java

    r23139 r23192  
    4040
    4141/**
    42  *      Layer which contains spatial referenced image data.
     42 *  Layer which contains spatial referenced image data.
    4343 *
    4444 * @author Christoph Beekmans, Fabian Kowitz, Anna Robaszkiewicz, Oliver Kuhn, Martin Ulitzny
     
    4747public class ImageLayer extends Layer {
    4848
    49         private Logger logger = Logger.getLogger(ImageLayer.class);
    50 
    51         private File imageFile;
    52        
    53         private BufferedImage image = null;
    54 
    55         // coordinates of upper left corner
    56         private EastNorth upperLeft;
    57         // Angle of rotation of the image
    58         private double angle = 0.0;
    59 
    60         // current bbox
    61         private Envelope2D bbox;
    62        
    63         // Layer icon
    64         private Icon layericon = null;
    65        
    66         // reference system of the oringinal image
    67         private CoordinateReferenceSystem sourceRefSys;
    68 
    69 
    70 
    71         /**
    72         * Constructor
    73         *
    74         * @param file
    75         * @throws IOException
    76         */
    77         public ImageLayer(File file) throws IOException {
    78                 super(file.getName());
    79                
    80                 this.imageFile = file;
    81                 this.image = (BufferedImage) createImage();
    82                 layericon = new ImageIcon(ImageImportPlugin.pluginClassLoader.getResource("images/layericon.png"));
    83                
    84         }
    85 
    86         /**
    87         * create spatial referenced image.
    88         *
    89         * @return
    90         * @throws IOException
    91         */
    92         private Image createImage() throws IOException {
    93 
    94                 // geotools type for images and value coverages
    95                 GridCoverage2D coverage = null;
    96                 try {
    97                         // create a grid coverage from the image
    98                         coverage = PluginOperations.createGridFromFile(imageFile, null);
    99                         this.sourceRefSys = coverage.getCoordinateReferenceSystem();
    100                        
    101                         // now reproject grid coverage
    102                         coverage = PluginOperations.reprojectCoverage(coverage, CRS.decode(Main.proj.toCode()));
    103                
    104                 } catch (FactoryException e) {
    105                         logger.error("Error while creating GridCoverage:",e);
    106                         throw new IOException(e.getMessage());
    107                 } catch (Exception e) {
    108                         if(e.getMessage().contains("No projection file found"))
    109                         {
    110                                 int useDefaultCRS = JOptionPane.showConfirmDialog(Main.parent, "<html>No projection file (.prj) found.<br>Use the default Coordinate Reference System instead?</html>", "Missing projection", JOptionPane.YES_NO_OPTION);
    111                                 if (useDefaultCRS == 0)
    112                                 {
    113                                         try {
    114                                                 // create a grid coverage from the image
    115                                                 coverage = PluginOperations.createGridFromFile(imageFile, PluginOperations.defaultSourceCRS);
    116                                                 this.sourceRefSys = coverage.getCoordinateReferenceSystem();
    117                                                
    118                                                 // now reproject grid coverage
    119                                                 coverage = PluginOperations.reprojectCoverage(coverage, CRS.decode(Main.proj.toCode()));
    120                                         } catch (Exception e1) {
    121                                                 logger.error("Error while creating GridCoverage:",e1);
    122                                                 throw new IOException(e1);
    123                                         }
    124                                 }
    125                                 else{
    126                                         logger.debug("Layer creation cancled by user due to missing projection information.");
    127                                         throw new LayerCreationCancledException();
    128                                 }
    129 
    130                         }
    131                         else
    132                         {
    133                                 logger.error("Error while creating GridCoverage:",e);
    134                                 throw new IOException(e);
    135                         }
    136 
    137                 }
    138                 logger.debug("Coverage created: " + coverage);
    139 
    140                 // TODO
    141                 upperLeft = new EastNorth(coverage.getEnvelope2D().y, coverage
    142                                 .getEnvelope2D().x
    143                                 + coverage.getEnvelope2D().width);
    144                 angle = 0;
    145                 bbox = coverage.getEnvelope2D();
    146 
    147                 // Refresh
    148                 // Main.map.mapView.repaint();
    149 //              PlanarImage image = (PlanarImage) coverage.getRenderedImage();
    150 //              logger.info("Color Model: " + coverage.getRenderedImage().getColorModel());
    151                 ImageWorker worker = new ImageWorker(coverage.getRenderedImage());
    152 
    153                 return worker.getBufferedImage();
    154         }
    155 
    156         @Override
    157         public void paint(Graphics2D g2, MapView mv, Bounds bounds) {
    158 
    159                 if (image != null && g2 != null) {
    160 
    161                         // Position image at the right graphical place
    162                         EastNorth center = Main.map.mapView.getCenter();
    163                         EastNorth leftop = Main.map.mapView.getEastNorth(0, 0);
    164                         double pixel_per_lon_degree = (Main.map.mapView.getWidth() / 2.0)
    165                                         / (center.east() - leftop.east());
    166                         double pixel_per_lat_degree = (Main.map.mapView.getHeight() / 2.0)
    167                                         / (leftop.north() - center.north());
    168 
    169                         // This is now the offset in screen pixels
    170                         double pic_offset_x = ((upperLeft.east() - leftop.east()) * pixel_per_lon_degree);
    171                         double pic_offset_y = ((leftop.north() - upperLeft.north()) * pixel_per_lat_degree);
    172 
    173                         Graphics2D g = (Graphics2D) g2.create();
    174 
    175                         // Move picture by offset from upper left corner
    176                         g.translate(pic_offset_x, pic_offset_y);
    177 
    178                         // Rotate image by angle
    179                         g.rotate(angle * Math.PI / 180.0);
    180                        
    181                         // Determine scale to fit JOSM extents
    182                         ProjectionBounds projbounds = Main.map.mapView
    183                                         .getProjectionBounds();
    184 
    185                         double width = projbounds.max.getX() - projbounds.min.getX();
    186                         double height = projbounds.max.getY() - projbounds.min.getY();
    187 
    188                         double ratio_x = (this.bbox.getMaxY() - this.bbox.getMinY())
    189                                         / width;
    190                         double ratio_y = (this.bbox.getMaxX() - this.bbox.getMinX())
    191                                         / height;
    192 
    193                         double pixels4bbox_width = ratio_x * Main.map.mapView.getWidth();
    194                         double pixels4bbox_height = ratio_y * Main.map.mapView.getHeight();
    195 
    196                         // Scale image to JOSM extents
    197                         double scalex = pixels4bbox_width / image.getWidth();
    198                         double scaley = pixels4bbox_height / image.getHeight();
    199 
    200                         g.scale(scalex, scaley);
    201 
    202                         // Draw picture
    203                         g.drawImage(image, 0, 0, null);
    204                        
    205                 } else {
    206                         logger.error("Error while dawing image: image == null or Graphics == null");
    207                 }
    208         }
    209        
    210         public Envelope2D getBbox() {
    211                 return bbox;
    212         }
    213 
    214         @Override
    215         public Icon getIcon() {
    216                 // TODO Auto-generated method stub
    217                 return this.layericon;
    218         }
    219 
    220         @Override
    221         public Object getInfoComponent() {
    222                 // TODO Auto-generated method stub
    223                 return null;
    224         }
    225 
    226         @Override
    227         public Component[] getMenuEntries() {
     49    private Logger logger = Logger.getLogger(ImageLayer.class);
     50
     51    private File imageFile;
     52   
     53    private BufferedImage image = null;
     54
     55    // coordinates of upper left corner
     56    private EastNorth upperLeft;
     57    // Angle of rotation of the image
     58    private double angle = 0.0;
     59
     60    // current bbox
     61    private Envelope2D bbox;
     62   
     63    // Layer icon
     64    private Icon layericon = null;
     65   
     66    // reference system of the oringinal image
     67    private CoordinateReferenceSystem sourceRefSys;
     68
     69
     70
     71    /**
     72    * Constructor
     73    *
     74    * @param file
     75    * @throws IOException
     76    */
     77    public ImageLayer(File file) throws IOException {
     78        super(file.getName());
     79       
     80        this.imageFile = file;
     81        this.image = (BufferedImage) createImage();
     82        layericon = new ImageIcon(ImageImportPlugin.pluginClassLoader.getResource("images/layericon.png"));
     83       
     84    }
     85
     86    /**
     87    * create spatial referenced image.
     88    *
     89    * @return
     90    * @throws IOException
     91    */
     92    private Image createImage() throws IOException {
     93
     94        // geotools type for images and value coverages
     95        GridCoverage2D coverage = null;
     96        try {
     97            // create a grid coverage from the image
     98            coverage = PluginOperations.createGridFromFile(imageFile, null);
     99            this.sourceRefSys = coverage.getCoordinateReferenceSystem();
     100           
     101            // now reproject grid coverage
     102            coverage = PluginOperations.reprojectCoverage(coverage, CRS.decode(Main.proj.toCode()));
     103       
     104        } catch (FactoryException e) {
     105            logger.error("Error while creating GridCoverage:",e);
     106            throw new IOException(e.getMessage());
     107        } catch (Exception e) {
     108            if(e.getMessage().contains("No projection file found"))
     109            {
     110                int useDefaultCRS = JOptionPane.showConfirmDialog(Main.parent, "<html>No projection file (.prj) found.<br>Use the default Coordinate Reference System instead?</html>", "Missing projection", JOptionPane.YES_NO_OPTION);
     111                if (useDefaultCRS == 0)
     112                {
     113                    try {
     114                        // create a grid coverage from the image
     115                        coverage = PluginOperations.createGridFromFile(imageFile, PluginOperations.defaultSourceCRS);
     116                        this.sourceRefSys = coverage.getCoordinateReferenceSystem();
     117                       
     118                        // now reproject grid coverage
     119                        coverage = PluginOperations.reprojectCoverage(coverage, CRS.decode(Main.proj.toCode()));
     120                    } catch (Exception e1) {
     121                        logger.error("Error while creating GridCoverage:",e1);
     122                        throw new IOException(e1);
     123                    }
     124                }
     125                else{
     126                    logger.debug("Layer creation cancled by user due to missing projection information.");
     127                    throw new LayerCreationCancledException();
     128                }
     129
     130            }
     131            else
     132            {
     133                logger.error("Error while creating GridCoverage:",e);
     134                throw new IOException(e);
     135            }
     136
     137        }
     138        logger.debug("Coverage created: " + coverage);
     139
     140        // TODO
     141        upperLeft = new EastNorth(coverage.getEnvelope2D().y, coverage
     142                .getEnvelope2D().x
     143                + coverage.getEnvelope2D().width);
     144        angle = 0;
     145        bbox = coverage.getEnvelope2D();
     146
     147        // Refresh
     148        // Main.map.mapView.repaint();
     149//      PlanarImage image = (PlanarImage) coverage.getRenderedImage();
     150//      logger.info("Color Model: " + coverage.getRenderedImage().getColorModel());
     151        ImageWorker worker = new ImageWorker(coverage.getRenderedImage());
     152
     153        return worker.getBufferedImage();
     154    }
     155
     156    @Override
     157    public void paint(Graphics2D g2, MapView mv, Bounds bounds) {
     158
     159        if (image != null && g2 != null) {
     160
     161            // Position image at the right graphical place
     162            EastNorth center = Main.map.mapView.getCenter();
     163            EastNorth leftop = Main.map.mapView.getEastNorth(0, 0);
     164            double pixel_per_lon_degree = (Main.map.mapView.getWidth() / 2.0)
     165                    / (center.east() - leftop.east());
     166            double pixel_per_lat_degree = (Main.map.mapView.getHeight() / 2.0)
     167                    / (leftop.north() - center.north());
     168
     169            // This is now the offset in screen pixels
     170            double pic_offset_x = ((upperLeft.east() - leftop.east()) * pixel_per_lon_degree);
     171            double pic_offset_y = ((leftop.north() - upperLeft.north()) * pixel_per_lat_degree);
     172
     173            Graphics2D g = (Graphics2D) g2.create();
     174
     175            // Move picture by offset from upper left corner
     176            g.translate(pic_offset_x, pic_offset_y);
     177
     178            // Rotate image by angle
     179            g.rotate(angle * Math.PI / 180.0);
     180           
     181            // Determine scale to fit JOSM extents
     182            ProjectionBounds projbounds = Main.map.mapView
     183                    .getProjectionBounds();
     184
     185            double width = projbounds.max.getX() - projbounds.min.getX();
     186            double height = projbounds.max.getY() - projbounds.min.getY();
     187
     188            double ratio_x = (this.bbox.getMaxY() - this.bbox.getMinY())
     189                    / width;
     190            double ratio_y = (this.bbox.getMaxX() - this.bbox.getMinX())
     191                    / height;
     192
     193            double pixels4bbox_width = ratio_x * Main.map.mapView.getWidth();
     194            double pixels4bbox_height = ratio_y * Main.map.mapView.getHeight();
     195
     196            // Scale image to JOSM extents
     197            double scalex = pixels4bbox_width / image.getWidth();
     198            double scaley = pixels4bbox_height / image.getHeight();
     199
     200            g.scale(scalex, scaley);
     201
     202            // Draw picture
     203            g.drawImage(image, 0, 0, null);
     204           
     205        } else {
     206            logger.error("Error while dawing image: image == null or Graphics == null");
     207        }
     208    }
     209   
     210    public Envelope2D getBbox() {
     211        return bbox;
     212    }
     213
     214    @Override
     215    public Icon getIcon() {
     216        // TODO Auto-generated method stub
     217        return this.layericon;
     218    }
     219
     220    @Override
     221    public Object getInfoComponent() {
     222        // TODO Auto-generated method stub
     223        return null;
     224    }
     225
     226    @Override
     227    public Component[] getMenuEntries() {
    228228        return new Component[]{
    229229                new JMenuItem(LayerListDialog.getInstance().createActivateLayerAction(this)),
     
    235235                new JSeparator(),
    236236                new JMenuItem(new LayerListPopup.InfoAction(this))};
    237         }
    238 
    239         @Override
    240         public boolean isMergable(Layer arg0) {
    241                 // TODO Auto-generated method stub
    242                 return false;
    243         }
    244 
    245         @Override
    246         public void mergeFrom(Layer arg0) {
    247                 // TODO Auto-generated method stub
    248 
    249         }
    250 
    251         @Override
    252         public void visitBoundingBox(BoundingXYVisitor arg0) {
    253                 // TODO Auto-generated method stub
    254         }
    255        
    256 
    257         @Override
    258         public String getToolTipText() {
    259                 // TODO Auto-generated method stub
    260                 return this.getName();
    261         }
    262        
    263 
    264         public File getImageFile() {
    265                 return imageFile;
    266         }
    267 
    268         public BufferedImage getImage() {
    269                 return image;
    270         }
    271        
    272         /**
    273         * loads the image and reprojects it using a transformation
    274         * calculated by the new reference system.
    275         *
    276         * @param newRefSys
    277         * @throws IOException
    278         * @throws FactoryException
    279         * @throws NoSuchAuthorityCodeException
    280         */
    281         void resample(CoordinateReferenceSystem refSys) throws IOException, NoSuchAuthorityCodeException, FactoryException
    282         {
    283                
    284                 GridCoverage2D coverage =  PluginOperations.createGridFromFile(this.imageFile, refSys);
    285                 coverage = PluginOperations.reprojectCoverage(coverage, CRS.decode(Main.proj.toCode()));
    286                 this.bbox = coverage.getEnvelope2D();
    287                 this.image = ((PlanarImage)coverage.getRenderedImage()).getAsBufferedImage();
    288                
    289                 // TODO
    290                 upperLeft = new EastNorth(coverage.getEnvelope2D().y, coverage
    291                                 .getEnvelope2D().x
    292                                 + coverage.getEnvelope2D().width);
    293                 angle = 0;
    294 
    295                 // repaint and zoom to new bbox
    296                 Main.map.mapView.repaint();
    297                 LatLon min = new LatLon(bbox.getMinX(), bbox.getMinY());
    298                 LatLon max = new LatLon(bbox.getMaxX(), bbox.getMaxY());
    299                 Main.map.mapView.zoomTo(new Bounds(min, max));
    300                
    301                
    302         }
    303        
    304         /**
    305         * Action that creates a dialog GUI element with properties of a layer.
    306         *
    307         */
    308         public class LayerPropertiesAction extends AbstractAction
    309         {
    310                 public ImageLayer imageLayer;
    311                
    312                 public LayerPropertiesAction(ImageLayer imageLayer){
    313                         super(tr("Layer Properties"));
    314                         this.imageLayer = imageLayer;
    315                 }
    316 
    317                 public void actionPerformed(ActionEvent arg0) {
    318                        
    319                         LayerPropertiesDialog layerProps = new LayerPropertiesDialog(imageLayer, PluginOperations.crsDescriptions);
    320                         layerProps.setLocation(Main.parent.getWidth() / 4 , Main.parent.getHeight() / 4);
    321                         layerProps.setVisible(true);
    322                 }
    323                
    324         }
    325        
    326         /**
    327         * Exception which represents that the layer creation has been cancled by the
    328         * user.
    329         *
    330         */
    331         class LayerCreationCancledException extends IOException{
    332         }
    333        
    334        
    335        
    336         public CoordinateReferenceSystem getSourceRefSys() {
    337                 return sourceRefSys;
    338         }
    339 
    340         public void setSourceRefSys(CoordinateReferenceSystem sourceRefSys) {
    341                 this.sourceRefSys = sourceRefSys;
    342         }
     237    }
     238
     239    @Override
     240    public boolean isMergable(Layer arg0) {
     241        // TODO Auto-generated method stub
     242        return false;
     243    }
     244
     245    @Override
     246    public void mergeFrom(Layer arg0) {
     247        // TODO Auto-generated method stub
     248
     249    }
     250
     251    @Override
     252    public void visitBoundingBox(BoundingXYVisitor arg0) {
     253        // TODO Auto-generated method stub
     254    }
     255   
     256
     257    @Override
     258    public String getToolTipText() {
     259        // TODO Auto-generated method stub
     260        return this.getName();
     261    }
     262   
     263
     264    public File getImageFile() {
     265        return imageFile;
     266    }
     267
     268    public BufferedImage getImage() {
     269        return image;
     270    }
     271   
     272    /**
     273    * loads the image and reprojects it using a transformation
     274    * calculated by the new reference system.
     275    *
     276    * @param newRefSys
     277    * @throws IOException
     278    * @throws FactoryException
     279    * @throws NoSuchAuthorityCodeException
     280    */
     281    void resample(CoordinateReferenceSystem refSys) throws IOException, NoSuchAuthorityCodeException, FactoryException
     282    {
     283       
     284        GridCoverage2D coverage =  PluginOperations.createGridFromFile(this.imageFile, refSys);
     285        coverage = PluginOperations.reprojectCoverage(coverage, CRS.decode(Main.proj.toCode()));
     286        this.bbox = coverage.getEnvelope2D();
     287        this.image = ((PlanarImage)coverage.getRenderedImage()).getAsBufferedImage();
     288       
     289        // TODO
     290        upperLeft = new EastNorth(coverage.getEnvelope2D().y, coverage
     291                .getEnvelope2D().x
     292                + coverage.getEnvelope2D().width);
     293        angle = 0;
     294
     295        // repaint and zoom to new bbox
     296        Main.map.mapView.repaint();
     297        LatLon min = new LatLon(bbox.getMinX(), bbox.getMinY());
     298        LatLon max = new LatLon(bbox.getMaxX(), bbox.getMaxY());
     299        Main.map.mapView.zoomTo(new Bounds(min, max));
     300       
     301       
     302    }
     303   
     304    /**
     305    * Action that creates a dialog GUI element with properties of a layer.
     306    *
     307    */
     308    public class LayerPropertiesAction extends AbstractAction
     309    {
     310        public ImageLayer imageLayer;
     311       
     312        public LayerPropertiesAction(ImageLayer imageLayer){
     313            super(tr("Layer Properties"));
     314            this.imageLayer = imageLayer;
     315        }
     316
     317        public void actionPerformed(ActionEvent arg0) {
     318           
     319            LayerPropertiesDialog layerProps = new LayerPropertiesDialog(imageLayer, PluginOperations.crsDescriptions);
     320            layerProps.setLocation(Main.parent.getWidth() / 4 , Main.parent.getHeight() / 4);
     321            layerProps.setVisible(true);
     322        }
     323       
     324    }
     325   
     326    /**
     327    * Exception which represents that the layer creation has been cancled by the
     328    * user.
     329    *
     330    */
     331    class LayerCreationCancledException extends IOException{
     332    }
     333   
     334   
     335   
     336    public CoordinateReferenceSystem getSourceRefSys() {
     337        return sourceRefSys;
     338    }
     339
     340    public void setSourceRefSys(CoordinateReferenceSystem sourceRefSys) {
     341        this.sourceRefSys = sourceRefSys;
     342    }
    343343}
  • applications/editors/josm/plugins/00_plugin_dir_template/src/org/openstreetmap/josm/plugins/ImportImagePlugin/LayerPropertiesDialog.java

    r23139 r23192  
    4242 */
    4343public class LayerPropertiesDialog extends JFrame{
    44        
    45         private Vector<String> supportedCRS;
    46         private ImageLayer imageLayer;
    47 
    48         private JPanel mainPanel = null;
    49         private JPanel jPanel = null;
    50         private JPanel buttonPanel = null;
    51         private JTabbedPane jTabbedPane = null;
    52         private JPanel infoPanel = null;
    53         private JPanel crsPanel = null;
    54         private JButton okButton = null;
    55         private JLabel layerNameLabel = null;
    56         private JLabel layerNameValueLabel = null;
    57         private JLabel imageFileLabel = null;
    58         private JLabel imageFileValueLabel = null;
    59         private JLabel sizeLabel = null;
    60         private JLabel sizeValueLabel = null;
    61         private JLabel crsLabel = null;
    62         private JLabel crsValueLabel = null;
    63         private JLabel extentLabel = null;
    64         private JLabel defaultCRSDescriptorLabel = null;
    65         private JLabel defaultCRSLabel = null;
    66         private JTextField searchField = null;
    67         private JScrollPane crsListScrollPane = null;
    68         private JList crsJList = null;
    69         private JButton useDefaultCRSButton = null;
    70         private JButton applySelectedCRSButton = null;
    71         private JButton setSelectedCRSAsDefaultButton = null;
    72         private JLabel searchFieldLabel = null;
    73         private JCheckBox eastingFirstCheckBox = null;
    74         private JLabel eastingFirstLabel = null;
    75         private JLabel tabDescriptionLabel = null;
    76         private JLabel upperLeftLabel = null;
    77         private JLabel lowerLeftLabel = null;
    78         private JLabel upperRightLabel = null;
    79         private JLabel lowerRightLabel = null;
    80         private JLabel upperLeftValueLabel = null;
    81         private JLabel upperRightValueLabel = null;
    82         private JLabel lowerLeftValueLabel = null;
    83         private JLabel lowerRightValueLabel = null;
    84         private JLabel currentCRSLabel = null;
    85         private JLabel currentCRSValueLabel = null;
    86 
    87         /**
    88         * This method initializes
    89         *
    90         */
    91         public LayerPropertiesDialog(ImageLayer imageLayer, Vector<String> supportedCRS) {
    92                 super(imageLayer.getName());
    93                 this.supportedCRS = supportedCRS;
    94                 this.imageLayer = imageLayer;
    95                 initialize();
    96         }
    97        
    98         /**
    99         * This method initializes
    100         *
    101         */
    102         public LayerPropertiesDialog(Vector<String> supportedCRS) {
    103                 super();
    104                 this.supportedCRS = supportedCRS;
    105                 initialize();
    106         }
    107        
    108 
    109         /**
    110         * This method initializes this
    111         *
    112         */
    113         private void initialize() {
     44   
     45    private Vector<String> supportedCRS;
     46    private ImageLayer imageLayer;
     47
     48    private JPanel mainPanel = null;
     49    private JPanel jPanel = null;
     50    private JPanel buttonPanel = null;
     51    private JTabbedPane jTabbedPane = null;
     52    private JPanel infoPanel = null;
     53    private JPanel crsPanel = null;
     54    private JButton okButton = null;
     55    private JLabel layerNameLabel = null;
     56    private JLabel layerNameValueLabel = null;
     57    private JLabel imageFileLabel = null;
     58    private JLabel imageFileValueLabel = null;
     59    private JLabel sizeLabel = null;
     60    private JLabel sizeValueLabel = null;
     61    private JLabel crsLabel = null;
     62    private JLabel crsValueLabel = null;
     63    private JLabel extentLabel = null;
     64    private JLabel defaultCRSDescriptorLabel = null;
     65    private JLabel defaultCRSLabel = null;
     66    private JTextField searchField = null;
     67    private JScrollPane crsListScrollPane = null;
     68    private JList crsJList = null;
     69    private JButton useDefaultCRSButton = null;
     70    private JButton applySelectedCRSButton = null;
     71    private JButton setSelectedCRSAsDefaultButton = null;
     72    private JLabel searchFieldLabel = null;
     73    private JCheckBox eastingFirstCheckBox = null;
     74    private JLabel eastingFirstLabel = null;
     75    private JLabel tabDescriptionLabel = null;
     76    private JLabel upperLeftLabel = null;
     77    private JLabel lowerLeftLabel = null;
     78    private JLabel upperRightLabel = null;
     79    private JLabel lowerRightLabel = null;
     80    private JLabel upperLeftValueLabel = null;
     81    private JLabel upperRightValueLabel = null;
     82    private JLabel lowerLeftValueLabel = null;
     83    private JLabel lowerRightValueLabel = null;
     84    private JLabel currentCRSLabel = null;
     85    private JLabel currentCRSValueLabel = null;
     86
     87    /**
     88    * This method initializes
     89    *
     90    */
     91    public LayerPropertiesDialog(ImageLayer imageLayer, Vector<String> supportedCRS) {
     92        super(imageLayer.getName());
     93        this.supportedCRS = supportedCRS;
     94        this.imageLayer = imageLayer;
     95        initialize();
     96    }
     97   
     98    /**
     99    * This method initializes
     100    *
     101    */
     102    public LayerPropertiesDialog(Vector<String> supportedCRS) {
     103        super();
     104        this.supportedCRS = supportedCRS;
     105        initialize();
     106    }
     107   
     108
     109    /**
     110    * This method initializes this
     111    *
     112    */
     113    private void initialize() {
    114114        this.setMinimumSize(new Dimension(404, 485));
    115115        this.setContentPane(getMainPanel());
    116116        this.setPreferredSize(new Dimension(404, 485));
    117                        
    118         }
    119 
    120         /**
    121          * This method initializes mainPanel   
    122          *     
    123          * @return javax.swing.JPanel   
    124         */
    125         private JPanel getMainPanel() {
    126                 if (mainPanel == null) {
    127                         mainPanel = new JPanel();
    128                         mainPanel.setLayout(null);
    129                         mainPanel.add(getJPanel(), null);
    130                         mainPanel.add(getButtonPanel(), null);
    131                 }
    132                 return mainPanel;
    133         }
    134 
    135         /**
    136          * This method initializes jPanel       
    137          *     
    138          * @return javax.swing.JPanel   
    139         */
    140         private JPanel getJPanel() {
    141                 if (jPanel == null) {
    142                         GridBagConstraints gridBagConstraints = new GridBagConstraints();
    143                         gridBagConstraints.fill = GridBagConstraints.BOTH;
    144                         gridBagConstraints.gridy = 0;
    145                         gridBagConstraints.weightx = 1.0;
    146                         gridBagConstraints.weighty = 1.0;
    147                         gridBagConstraints.gridx = 0;
    148                         jPanel = new JPanel();
    149                         jPanel.setLayout(new GridBagLayout());
    150                         jPanel.setBounds(new Rectangle(0, 0, 391, 406));
    151                         jPanel.add(getJTabbedPane(), gridBagConstraints);
    152                 }
    153                 return jPanel;
    154         }
    155 
    156         /**
    157          * This method initializes buttonPanel 
    158          *     
    159          * @return javax.swing.JPanel   
    160         */
    161         private JPanel getButtonPanel() {
    162                 if (buttonPanel == null) {
    163                         buttonPanel = new JPanel();
    164                         buttonPanel.setLayout(null);
    165                         buttonPanel.setBounds(new Rectangle(0, 405, 391, 46));
    166                         buttonPanel.add(getOkButton(), null);
    167                 }
    168                 return buttonPanel;
    169         }
    170 
    171         /**
    172          * This method initializes jTabbedPane 
    173          *     
    174          * @return javax.swing.JTabbedPane     
    175         */
    176         private JTabbedPane getJTabbedPane() {
    177                 if (jTabbedPane == null) {
    178                         jTabbedPane = new JTabbedPane();
    179                         jTabbedPane.addTab("General Information", null, getInfoPanel(), null);
    180                         jTabbedPane.addTab("Source Reference System", null, getCrsPanel(), null);
    181                 }
    182                 return jTabbedPane;
    183         }
    184 
    185         /**
    186          * This method initializes infoPanel   
    187          *     
    188          * @return javax.swing.JPanel   
    189         */
    190         private JPanel getInfoPanel() {
    191                 if (infoPanel == null) {
    192                         lowerRightValueLabel = new JLabel();
    193                         lowerRightValueLabel.setBounds(new Rectangle(210, 315, 134, 16));
    194                         lowerRightValueLabel.setHorizontalAlignment(SwingConstants.RIGHT);
    195                         lowerRightValueLabel.setText((float)imageLayer.getBbox().getMinX() + ", " + (float)imageLayer.getBbox().getMaxY());
    196                         lowerLeftValueLabel = new JLabel();
    197                         lowerLeftValueLabel.setBounds(new Rectangle(30, 315, 133, 16));
    198                         lowerLeftValueLabel.setHorizontalAlignment(SwingConstants.LEFT);
    199                         lowerLeftValueLabel.setText((float)imageLayer.getBbox().getMinX() + ", " + (float)imageLayer.getBbox().getMinY());
    200                         upperRightValueLabel = new JLabel();
    201                         upperRightValueLabel.setBounds(new Rectangle(210, 255, 138, 16));
    202                         upperRightValueLabel.setHorizontalAlignment(SwingConstants.RIGHT);
    203                         upperRightValueLabel.setText((float)imageLayer.getBbox().getMaxX() + ", " + (float)imageLayer.getBbox().getMaxY());
    204                         upperLeftValueLabel = new JLabel();
    205                         upperLeftValueLabel.setBounds(new Rectangle(30, 255, 133, 16));
    206                         upperLeftValueLabel.setHorizontalAlignment(SwingConstants.LEFT);
    207                         upperLeftValueLabel.setText((float)imageLayer.getBbox().getMaxX() + ", " + (float)imageLayer.getBbox().getMinY());
    208                         lowerRightLabel = new JLabel();
    209                         lowerRightLabel.setBounds(new Rectangle(287, 344, 74, 16));
    210                         lowerRightLabel.setText("Lower Right");
    211                         upperRightLabel = new JLabel();
    212                         upperRightLabel.setBounds(new Rectangle(285, 225, 91, 16));
    213                         upperRightLabel.setText("Upper Right");
    214                         lowerLeftLabel = new JLabel();
    215                         lowerLeftLabel.setBounds(new Rectangle(15, 345, 92, 16));
    216                         lowerLeftLabel.setText("Lower Left");
    217                         upperLeftLabel = new JLabel();
    218                         upperLeftLabel.setBounds(new Rectangle(15, 224, 91, 16));
    219                         upperLeftLabel.setText("Upper Left");
    220                         extentLabel = new JLabel();
    221                         extentLabel.setBounds(new Rectangle(120, 195, 136, 16));
    222                         extentLabel.setEnabled(false);
    223                         extentLabel.setHorizontalAlignment(SwingConstants.CENTER);
    224                         extentLabel.setDisplayedMnemonic(KeyEvent.VK_UNDEFINED);
    225                         extentLabel.setText("Extent");
    226                         crsValueLabel = new JLabel();
    227                         crsValueLabel.setBounds(new Rectangle(150, 150, 226, 16));
    228                        
    229                         String crsDescription = "";
    230                         try {
    231                                 crsDescription = imageLayer.getBbox().getCoordinateReferenceSystem().getIdentifiers().iterator().next().toString();
    232                         } catch (Exception e) {
    233                         }
    234                         crsValueLabel.setText(crsDescription + "(" + imageLayer.getBbox().getCoordinateReferenceSystem().getName().toString() + ")");
    235                        
    236                         crsLabel = new JLabel();
    237                         crsLabel.setBounds(new Rectangle(15, 150, 118, 16));
    238                         crsLabel.setText("Reference System");
    239                         sizeValueLabel = new JLabel();
    240                         sizeValueLabel.setBounds(new Rectangle(150, 105, 226, 16));
    241                         sizeValueLabel.setText(imageLayer.getImage().getHeight() + " x " + imageLayer.getImage().getWidth());
    242                         sizeLabel = new JLabel();
    243                         sizeLabel.setBounds(new Rectangle(15, 105, 121, 16));
    244                         sizeLabel.setText("Image size");
    245                         imageFileValueLabel = new JLabel();
    246                         imageFileValueLabel.setBounds(new Rectangle(150, 60, 226, 16));
    247                         imageFileValueLabel.setText(imageLayer.getImageFile().getAbsolutePath());
    248                         imageFileValueLabel.setToolTipText(imageLayer.getImageFile().getAbsolutePath());
    249                         imageFileLabel = new JLabel();
    250                         imageFileLabel.setBounds(new Rectangle(15, 60, 121, 16));
    251                         imageFileLabel.setText("Image file");
    252                         layerNameValueLabel = new JLabel();
    253                         layerNameValueLabel.setBounds(new Rectangle(150, 15, 226, 16));
    254                         layerNameValueLabel.setText(imageLayer.getName());
    255                         layerNameLabel = new JLabel();
    256                         layerNameLabel.setBounds(new Rectangle(15, 15, 121, 16));
    257                         layerNameLabel.setText("Layer name");
    258                         infoPanel = new JPanel();
    259                         infoPanel.setLayout(null);
    260                         infoPanel.setFont(new Font("Dialog", Font.BOLD, 12));
    261                         infoPanel.add(layerNameLabel, null);
    262                         infoPanel.add(layerNameValueLabel, null);
    263                         infoPanel.add(imageFileLabel, null);
    264                         infoPanel.add(imageFileValueLabel, null);
    265                         infoPanel.add(sizeLabel, null);
    266                         infoPanel.add(sizeValueLabel, null);
    267                         infoPanel.add(crsLabel, null);
    268                         infoPanel.add(crsValueLabel, null);
    269                         infoPanel.add(extentLabel, null);
    270                         infoPanel.add(upperLeftLabel, null);
    271                         infoPanel.add(lowerLeftLabel, null);
    272                         infoPanel.add(upperRightLabel, null);
    273                         infoPanel.add(lowerRightLabel, null);
    274                         infoPanel.add(upperLeftValueLabel, null);
    275                         infoPanel.add(upperRightValueLabel, null);
    276                         infoPanel.add(lowerLeftValueLabel, null);
    277                         infoPanel.add(lowerRightValueLabel, null);
    278                 }
    279                 return infoPanel;
    280         }
    281 
    282         /**
    283          * This method initializes crsPanel     
    284          *     
    285          * @return javax.swing.JPanel   
    286         */
    287         private JPanel getCrsPanel() {
    288                 if (crsPanel == null) {
    289                         currentCRSValueLabel = new JLabel();
    290                         currentCRSValueLabel.setBounds(new Rectangle(78, 33, 297, 16));
    291                         String crsDescription = "unknown";
    292                         try {
    293                                 crsDescription = imageLayer.getSourceRefSys().getIdentifiers().iterator().next().toString();
    294                         } catch (Exception e) {
    295                         }
    296                         currentCRSValueLabel.setText(crsDescription);
    297                        
    298                         currentCRSLabel = new JLabel();
    299                         currentCRSLabel.setBounds(new Rectangle(15, 33, 52, 16));
    300                         currentCRSLabel.setText("Current:");
    301                         tabDescriptionLabel = new JLabel();
    302                         tabDescriptionLabel.setBounds(new Rectangle(15, 9, 361, 16));
    303                         tabDescriptionLabel.setText("Set here the source reference system of the image");
    304                         eastingFirstLabel = new JLabel();
    305                         eastingFirstLabel.setBounds(new Rectangle(315, 210, 76, 46));
    306                         eastingFirstLabel.setHorizontalTextPosition(SwingConstants.TRAILING);
    307                         eastingFirstLabel.setHorizontalAlignment(SwingConstants.CENTER);
    308                         eastingFirstLabel.setText("<html>Easting<br>first</html>");
    309                         searchFieldLabel = new JLabel();
    310                         searchFieldLabel.setBounds(new Rectangle(298, 114, 84, 16));
    311                         searchFieldLabel.setDisplayedMnemonic(KeyEvent.VK_UNDEFINED);
    312                         searchFieldLabel.setHorizontalTextPosition(SwingConstants.TRAILING);
    313                         searchFieldLabel.setHorizontalAlignment(SwingConstants.CENTER);
    314                         searchFieldLabel.setText("Search");
    315                         defaultCRSLabel = new JLabel();
    316                         defaultCRSLabel.setBounds(new Rectangle(15, 89, 361, 16));
    317                         defaultCRSLabel.setText(PluginOperations.defaultSourceCRSDescription);
    318                         defaultCRSDescriptorLabel = new JLabel();
    319                         defaultCRSDescriptorLabel.setBounds(new Rectangle(15, 63, 226, 16));
    320                         defaultCRSDescriptorLabel.setText("Default Reference System:");
    321                         crsPanel = new JPanel();
    322                         crsPanel.setLayout(null);
    323                         crsPanel.add(defaultCRSDescriptorLabel, null);
    324                         crsPanel.add(defaultCRSLabel, null);
    325                         crsPanel.add(getSearchField(), null);
    326                         crsPanel.add(getCrsListScrollPane(), null);
    327                         crsPanel.add(getUseDefaultCRSButton(), null);
    328                         crsPanel.add(getApplySelectedCRSButton(), null);
    329                         crsPanel.add(getSetSelectedCRSAsDefaultButton(), null);
    330                         crsPanel.add(searchFieldLabel, null);
    331                         crsPanel.add(getEastingFirstCheckBox(), null);
    332                         crsPanel.add(eastingFirstLabel, null);
    333                         crsPanel.add(tabDescriptionLabel, null);
    334                         crsPanel.add(currentCRSLabel, null);
    335                         crsPanel.add(currentCRSValueLabel, null);
    336                 }
    337                 return crsPanel;
    338         }
    339 
    340         /**
    341          * This method initializes okButton     
    342          *     
    343          * @return javax.swing.JButton 
    344         */
    345         private JButton getOkButton() {
    346                 if (okButton == null) {
    347                         okButton = new JButton();
    348                         okButton.setBounds(new Rectangle(134, 5, 136, 31));
    349                         okButton.setText("OK");
    350                         okButton.addActionListener(new java.awt.event.ActionListener() {
    351                                 public void actionPerformed(java.awt.event.ActionEvent e) {
    352                                        
    353                                         setVisible(false);
    354                                         dispose();
    355                                 }
    356                         });
    357                 }
    358                 return okButton;
    359         }
    360 
    361         /**
    362          * This method initializes searchField 
    363          *     
    364          * @return javax.swing.JTextField       
    365         */
    366         private JTextField getSearchField() {
    367                 if (searchField == null) {
    368                         searchField = new JTextField();
    369                         searchField.setBounds(new Rectangle(13, 111, 282, 20));
    370                         searchField.setToolTipText("Enter keywords or EPSG codes");
    371                         searchField.addKeyListener(new java.awt.event.KeyAdapter() {
    372                                 public void keyTyped(java.awt.event.KeyEvent e) {
    373                                        
    374                                         for (Iterator iterator = supportedCRS.iterator(); iterator
    375                                                         .hasNext();) {
    376                                                 String type = (String) iterator.next();
    377                                                 if(type.contains(searchField.getText()))
    378                                                 {
    379                                                         crsJList.setSelectedIndex(supportedCRS.indexOf(type));
    380                                                         crsJList.ensureIndexIsVisible(supportedCRS.indexOf(type));
    381                                                         break;
    382                                                 }
    383                                                
    384                                         }
    385                                 }
    386                         });
    387                 }
    388                 return searchField;
    389         }
    390 
    391         /**
    392          * This method initializes crsListScrollPane   
    393          *     
    394          * @return javax.swing.JScrollPane     
    395         */
    396         private JScrollPane getCrsListScrollPane() {
    397                 if (crsListScrollPane == null) {
    398                         crsListScrollPane = new JScrollPane();
    399                         crsListScrollPane.setBounds(new Rectangle(15, 135, 301, 241));
    400                         crsListScrollPane.setViewportView(getCrsJList());
    401                 }
    402                 return crsListScrollPane;
    403         }
    404 
    405         /**
    406          * This method initializes crsJList     
    407          *     
    408          * @return javax.swing.JList   
    409         */
    410         private JList getCrsJList() {
    411                 if (crsJList == null) {
    412                         crsJList = new JList(supportedCRS);
    413                         crsJList.addListSelectionListener(new ListSelectionHandler());
    414                 }
    415                 return crsJList;
    416         }
    417 
    418         /**
    419          * This method initializes useDefaultCRSButton 
    420          *     
    421          * @return javax.swing.JButton 
    422         */
    423         private JButton getUseDefaultCRSButton() {
    424                 if (useDefaultCRSButton == null) {
    425                         useDefaultCRSButton = new JButton();
    426                         useDefaultCRSButton.setBounds(new Rectangle(253, 54, 118, 28));
    427                         useDefaultCRSButton.setText("Apply Default");
    428                         useDefaultCRSButton.addActionListener(new java.awt.event.ActionListener() {
    429                                 public void actionPerformed(java.awt.event.ActionEvent e) {
    430                                        
    431                                         try {
    432                                                
    433                                                 setCursor(new Cursor(Cursor.WAIT_CURSOR));
    434                                                 if(PluginOperations.defaultSourceCRS != null){
    435                                                         imageLayer.resample(PluginOperations.defaultSourceCRS);
    436                                                 }else
    437                                                 {
    438                                                         JOptionPane.showMessageDialog(getContentPane(), "<html>No default reference system available.<br>Please select one from the list</html>");
    439                                                 }
    440                                                
    441                                         } catch (NoSuchAuthorityCodeException e1) {
    442                                                 // TODO Auto-generated catch block
    443                                                 e1.printStackTrace();
    444                                         } catch (FactoryException e1) {
    445                                                 // TODO Auto-generated catch block
    446                                                 e1.printStackTrace();
    447                                         } catch (IOException e2) {
    448                                                 // TODO Auto-generated catch block
    449                                                 e2.printStackTrace();
    450                                         }
    451                                         finally{
    452                                                 setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
    453                                         }
    454                                 }
    455                         });
    456                 }
    457                 return useDefaultCRSButton;
    458         }
    459 
    460         /**
    461          * This method initializes applySelectedCRSButton       
    462          *     
    463          * @return javax.swing.JButton 
    464         */
    465         private JButton getApplySelectedCRSButton() {
    466                 if (applySelectedCRSButton == null) {
    467                         applySelectedCRSButton = new JButton();
    468                         applySelectedCRSButton.setBounds(new Rectangle(315, 135, 69, 61));
    469                         applySelectedCRSButton.setHorizontalAlignment(SwingConstants.CENTER);
    470                         applySelectedCRSButton.setHorizontalTextPosition(SwingConstants.TRAILING);
    471                         applySelectedCRSButton.setText("<html>Apply<br>Selection</html>");
    472                         applySelectedCRSButton.addActionListener(new java.awt.event.ActionListener() {
    473                                 public void actionPerformed(java.awt.event.ActionEvent e) {
    474                                        
    475                                         String selection = (String) crsJList.getSelectedValue();
    476                                         String code = selection.substring(selection.indexOf("[-") + 2, selection.indexOf("-]"));
    477                                        
    478                                         CoordinateReferenceSystem newRefSys = null;
    479                                         try {
    480                                                 newRefSys = CRS.decode(code, eastingFirstCheckBox.isSelected());
    481                                                
    482                                                 setCursor(new Cursor(Cursor.WAIT_CURSOR));
    483                                                
    484                                                 imageLayer.resample(newRefSys);
    485 
    486                                         } catch (NoSuchAuthorityCodeException e1) {
    487                                                 // TODO Auto-generated catch block
    488                                                 e1.printStackTrace();
    489                                         } catch (FactoryException e1) {
    490                                                 // TODO Auto-generated catch block
    491                                                 e1.printStackTrace();
    492                                         } catch (IOException e2) {
    493                                                 // TODO Auto-generated catch block
    494                                                 e2.printStackTrace();
    495                                         }
    496                                         finally{
    497                                                 setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
    498                                         }
    499                                        
    500                                        
    501                                 }
    502                         });
    503                 }
    504                 return applySelectedCRSButton;
    505         }
    506 
    507         /**
    508          * This method initializes setSelectedCRSAsDefaultButton       
    509          *     
    510          * @return javax.swing.JButton 
    511         */
    512         private JButton getSetSelectedCRSAsDefaultButton() {
    513                 if (setSelectedCRSAsDefaultButton == null) {
    514                         setSelectedCRSAsDefaultButton = new JButton();
    515                         setSelectedCRSAsDefaultButton.setBounds(new Rectangle(315, 300, 69, 61));
    516                         setSelectedCRSAsDefaultButton.setText("<html>Set as<br>Default</html>");
    517                         setSelectedCRSAsDefaultButton
    518                                         .addActionListener(new java.awt.event.ActionListener() {
    519                                                 public void actionPerformed(java.awt.event.ActionEvent e) {
    520                                                        
    521                                                         if(crsJList.getSelectedValue() != null){
    522                                                                 String selection = (String) crsJList.getSelectedValue();
    523                                                                 String code = selection.substring(selection.indexOf("[-") + 2, selection.indexOf("-]"));
    524                                                                
    525                                                                 try {
    526                                                                         PluginOperations.defaultSourceCRS = CRS.decode(code, eastingFirstCheckBox.isSelected());
    527                                                                         PluginOperations.defaultSourceCRSDescription = selection;
    528                                                                        
    529                                                                         ImageImportPlugin.pluginProps.setProperty("default_crs_eastingfirst", "" + eastingFirstCheckBox.isSelected());
    530                                                                         ImageImportPlugin.pluginProps.setProperty("default_crs_srid", code);
    531                                                                         FileWriter fileWriter = new FileWriter(new File(ImageImportPlugin.PLUGINPROPERTIES_PATH));
    532                                                                         ImageImportPlugin.pluginProps.store(fileWriter, null);
    533                                                                         fileWriter.close();
    534                                                                        
    535                                                                         defaultCRSLabel.setText(selection);
    536                                                                        
    537                                                                 } catch (IOException e2) {
    538                                                                         // TODO Auto-generated catch block
    539                                                                         e2.printStackTrace();
    540                                                                 } catch (NoSuchAuthorityCodeException e3) {
    541                                                                         // TODO Auto-generated catch block
    542                                                                         e3.printStackTrace();
    543                                                                 } catch (FactoryException e4) {
    544                                                                         // TODO Auto-generated catch block
    545                                                                         e4.printStackTrace();
    546                                                                 }
    547                                                         }else{
    548                                                                 JOptionPane.showMessageDialog(getContentPane(), "Please make a selection from the list.");
    549                                                         }
    550 
    551                                                        
    552                                                 }
    553                                         });
    554                 }
    555                 return setSelectedCRSAsDefaultButton;
    556         }
    557        
    558         /**
    559          * This method initializes eastingFirstCheckBox
    560          *     
    561          * @return javax.swing.JCheckBox       
    562         */
    563         private JCheckBox getEastingFirstCheckBox() {
    564                 if (eastingFirstCheckBox == null) {
    565                         eastingFirstCheckBox = new JCheckBox();
    566                         eastingFirstCheckBox.setBounds(new Rectangle(345, 255, 21, 21));
    567                 }
    568                 return eastingFirstCheckBox;
    569         }
    570 
    571        
    572        
    573         /**
    574         * Listener setting text in the search field if selection has changed.
    575         *
    576         */
     117           
     118    }
     119
     120    /**
     121     * This method initializes mainPanel   
     122     * 
     123     * @return javax.swing.JPanel   
     124    */
     125    private JPanel getMainPanel() {
     126        if (mainPanel == null) {
     127            mainPanel = new JPanel();
     128            mainPanel.setLayout(null);
     129            mainPanel.add(getJPanel(), null);
     130            mainPanel.add(getButtonPanel(), null);
     131        }
     132        return mainPanel;
     133    }
     134
     135    /**
     136     * This method initializes jPanel   
     137     * 
     138     * @return javax.swing.JPanel   
     139    */
     140    private JPanel getJPanel() {
     141        if (jPanel == null) {
     142            GridBagConstraints gridBagConstraints = new GridBagConstraints();
     143            gridBagConstraints.fill = GridBagConstraints.BOTH;
     144            gridBagConstraints.gridy = 0;
     145            gridBagConstraints.weightx = 1.0;
     146            gridBagConstraints.weighty = 1.0;
     147            gridBagConstraints.gridx = 0;
     148            jPanel = new JPanel();
     149            jPanel.setLayout(new GridBagLayout());
     150            jPanel.setBounds(new Rectangle(0, 0, 391, 406));
     151            jPanel.add(getJTabbedPane(), gridBagConstraints);
     152        }
     153        return jPanel;
     154    }
     155
     156    /**
     157     * This method initializes buttonPanel 
     158     * 
     159     * @return javax.swing.JPanel   
     160    */
     161    private JPanel getButtonPanel() {
     162        if (buttonPanel == null) {
     163            buttonPanel = new JPanel();
     164            buttonPanel.setLayout(null);
     165            buttonPanel.setBounds(new Rectangle(0, 405, 391, 46));
     166            buttonPanel.add(getOkButton(), null);
     167        }
     168        return buttonPanel;
     169    }
     170
     171    /**
     172     * This method initializes jTabbedPane 
     173     * 
     174     * @return javax.swing.JTabbedPane 
     175    */
     176    private JTabbedPane getJTabbedPane() {
     177        if (jTabbedPane == null) {
     178            jTabbedPane = new JTabbedPane();
     179            jTabbedPane.addTab("General Information", null, getInfoPanel(), null);
     180            jTabbedPane.addTab("Source Reference System", null, getCrsPanel(), null);
     181        }
     182        return jTabbedPane;
     183    }
     184
     185    /**
     186     * This method initializes infoPanel   
     187     * 
     188     * @return javax.swing.JPanel   
     189    */
     190    private JPanel getInfoPanel() {
     191        if (infoPanel == null) {
     192            lowerRightValueLabel = new JLabel();
     193            lowerRightValueLabel.setBounds(new Rectangle(210, 315, 134, 16));
     194            lowerRightValueLabel.setHorizontalAlignment(SwingConstants.RIGHT);
     195            lowerRightValueLabel.setText((float)imageLayer.getBbox().getMinX() + ", " + (float)imageLayer.getBbox().getMaxY());
     196            lowerLeftValueLabel = new JLabel();
     197            lowerLeftValueLabel.setBounds(new Rectangle(30, 315, 133, 16));
     198            lowerLeftValueLabel.setHorizontalAlignment(SwingConstants.LEFT);
     199            lowerLeftValueLabel.setText((float)imageLayer.getBbox().getMinX() + ", " + (float)imageLayer.getBbox().getMinY());
     200            upperRightValueLabel = new JLabel();
     201            upperRightValueLabel.setBounds(new Rectangle(210, 255, 138, 16));
     202            upperRightValueLabel.setHorizontalAlignment(SwingConstants.RIGHT);
     203            upperRightValueLabel.setText((float)imageLayer.getBbox().getMaxX() + ", " + (float)imageLayer.getBbox().getMaxY());
     204            upperLeftValueLabel = new JLabel();
     205            upperLeftValueLabel.setBounds(new Rectangle(30, 255, 133, 16));
     206            upperLeftValueLabel.setHorizontalAlignment(SwingConstants.LEFT);
     207            upperLeftValueLabel.setText((float)imageLayer.getBbox().getMaxX() + ", " + (float)imageLayer.getBbox().getMinY());
     208            lowerRightLabel = new JLabel();
     209            lowerRightLabel.setBounds(new Rectangle(287, 344, 74, 16));
     210            lowerRightLabel.setText("Lower Right");
     211            upperRightLabel = new JLabel();
     212            upperRightLabel.setBounds(new Rectangle(285, 225, 91, 16));
     213            upperRightLabel.setText("Upper Right");
     214            lowerLeftLabel = new JLabel();
     215            lowerLeftLabel.setBounds(new Rectangle(15, 345, 92, 16));
     216            lowerLeftLabel.setText("Lower Left");
     217            upperLeftLabel = new JLabel();
     218            upperLeftLabel.setBounds(new Rectangle(15, 224, 91, 16));
     219            upperLeftLabel.setText("Upper Left");
     220            extentLabel = new JLabel();
     221            extentLabel.setBounds(new Rectangle(120, 195, 136, 16));
     222            extentLabel.setEnabled(false);
     223            extentLabel.setHorizontalAlignment(SwingConstants.CENTER);
     224            extentLabel.setDisplayedMnemonic(KeyEvent.VK_UNDEFINED);
     225            extentLabel.setText("Extent");
     226            crsValueLabel = new JLabel();
     227            crsValueLabel.setBounds(new Rectangle(150, 150, 226, 16));
     228           
     229            String crsDescription = "";
     230            try {
     231                crsDescription = imageLayer.getBbox().getCoordinateReferenceSystem().getIdentifiers().iterator().next().toString();
     232            } catch (Exception e) {
     233            }
     234            crsValueLabel.setText(crsDescription + "(" + imageLayer.getBbox().getCoordinateReferenceSystem().getName().toString() + ")");
     235           
     236            crsLabel = new JLabel();
     237            crsLabel.setBounds(new Rectangle(15, 150, 118, 16));
     238            crsLabel.setText("Reference System");
     239            sizeValueLabel = new JLabel();
     240            sizeValueLabel.setBounds(new Rectangle(150, 105, 226, 16));
     241            sizeValueLabel.setText(imageLayer.getImage().getHeight() + " x " + imageLayer.getImage().getWidth());
     242            sizeLabel = new JLabel();
     243            sizeLabel.setBounds(new Rectangle(15, 105, 121, 16));
     244            sizeLabel.setText("Image size");
     245            imageFileValueLabel = new JLabel();
     246            imageFileValueLabel.setBounds(new Rectangle(150, 60, 226, 16));
     247            imageFileValueLabel.setText(imageLayer.getImageFile().getAbsolutePath());
     248            imageFileValueLabel.setToolTipText(imageLayer.getImageFile().getAbsolutePath());
     249            imageFileLabel = new JLabel();
     250            imageFileLabel.setBounds(new Rectangle(15, 60, 121, 16));
     251            imageFileLabel.setText("Image file");
     252            layerNameValueLabel = new JLabel();
     253            layerNameValueLabel.setBounds(new Rectangle(150, 15, 226, 16));
     254            layerNameValueLabel.setText(imageLayer.getName());
     255            layerNameLabel = new JLabel();
     256            layerNameLabel.setBounds(new Rectangle(15, 15, 121, 16));
     257            layerNameLabel.setText("Layer name");
     258            infoPanel = new JPanel();
     259            infoPanel.setLayout(null);
     260            infoPanel.setFont(new Font("Dialog", Font.BOLD, 12));
     261            infoPanel.add(layerNameLabel, null);
     262            infoPanel.add(layerNameValueLabel, null);
     263            infoPanel.add(imageFileLabel, null);
     264            infoPanel.add(imageFileValueLabel, null);
     265            infoPanel.add(sizeLabel, null);
     266            infoPanel.add(sizeValueLabel, null);
     267            infoPanel.add(crsLabel, null);
     268            infoPanel.add(crsValueLabel, null);
     269            infoPanel.add(extentLabel, null);
     270            infoPanel.add(upperLeftLabel, null);
     271            infoPanel.add(lowerLeftLabel, null);
     272            infoPanel.add(upperRightLabel, null);
     273            infoPanel.add(lowerRightLabel, null);
     274            infoPanel.add(upperLeftValueLabel, null);
     275            infoPanel.add(upperRightValueLabel, null);
     276            infoPanel.add(lowerLeftValueLabel, null);
     277            infoPanel.add(lowerRightValueLabel, null);
     278        }
     279        return infoPanel;
     280    }
     281
     282    /**
     283     * This method initializes crsPanel
     284     * 
     285     * @return javax.swing.JPanel   
     286    */
     287    private JPanel getCrsPanel() {
     288        if (crsPanel == null) {
     289            currentCRSValueLabel = new JLabel();
     290            currentCRSValueLabel.setBounds(new Rectangle(78, 33, 297, 16));
     291            String crsDescription = "unknown";
     292            try {
     293                crsDescription = imageLayer.getSourceRefSys().getIdentifiers().iterator().next().toString();
     294            } catch (Exception e) {
     295            }
     296            currentCRSValueLabel.setText(crsDescription);
     297           
     298            currentCRSLabel = new JLabel();
     299            currentCRSLabel.setBounds(new Rectangle(15, 33, 52, 16));
     300            currentCRSLabel.setText("Current:");
     301            tabDescriptionLabel = new JLabel();
     302            tabDescriptionLabel.setBounds(new Rectangle(15, 9, 361, 16));
     303            tabDescriptionLabel.setText("Set here the source reference system of the image");
     304            eastingFirstLabel = new JLabel();
     305            eastingFirstLabel.setBounds(new Rectangle(315, 210, 76, 46));
     306            eastingFirstLabel.setHorizontalTextPosition(SwingConstants.TRAILING);
     307            eastingFirstLabel.setHorizontalAlignment(SwingConstants.CENTER);
     308            eastingFirstLabel.setText("<html>Easting<br>first</html>");
     309            searchFieldLabel = new JLabel();
     310            searchFieldLabel.setBounds(new Rectangle(298, 114, 84, 16));
     311            searchFieldLabel.setDisplayedMnemonic(KeyEvent.VK_UNDEFINED);
     312            searchFieldLabel.setHorizontalTextPosition(SwingConstants.TRAILING);
     313            searchFieldLabel.setHorizontalAlignment(SwingConstants.CENTER);
     314            searchFieldLabel.setText("Search");
     315            defaultCRSLabel = new JLabel();
     316            defaultCRSLabel.setBounds(new Rectangle(15, 89, 361, 16));
     317            defaultCRSLabel.setText(PluginOperations.defaultSourceCRSDescription);
     318            defaultCRSDescriptorLabel = new JLabel();
     319            defaultCRSDescriptorLabel.setBounds(new Rectangle(15, 63, 226, 16));
     320            defaultCRSDescriptorLabel.setText("Default Reference System:");
     321            crsPanel = new JPanel();
     322            crsPanel.setLayout(null);
     323            crsPanel.add(defaultCRSDescriptorLabel, null);
     324            crsPanel.add(defaultCRSLabel, null);
     325            crsPanel.add(getSearchField(), null);
     326            crsPanel.add(getCrsListScrollPane(), null);
     327            crsPanel.add(getUseDefaultCRSButton(), null);
     328            crsPanel.add(getApplySelectedCRSButton(), null);
     329            crsPanel.add(getSetSelectedCRSAsDefaultButton(), null);
     330            crsPanel.add(searchFieldLabel, null);
     331            crsPanel.add(getEastingFirstCheckBox(), null);
     332            crsPanel.add(eastingFirstLabel, null);
     333            crsPanel.add(tabDescriptionLabel, null);
     334            crsPanel.add(currentCRSLabel, null);
     335            crsPanel.add(currentCRSValueLabel, null);
     336        }
     337        return crsPanel;
     338    }
     339
     340    /**
     341     * This method initializes okButton
     342     * 
     343     * @return javax.swing.JButton 
     344    */
     345    private JButton getOkButton() {
     346        if (okButton == null) {
     347            okButton = new JButton();
     348            okButton.setBounds(new Rectangle(134, 5, 136, 31));
     349            okButton.setText("OK");
     350            okButton.addActionListener(new java.awt.event.ActionListener() {
     351                public void actionPerformed(java.awt.event.ActionEvent e) {
     352                   
     353                    setVisible(false);
     354                    dispose();
     355                }
     356            });
     357        }
     358        return okButton;
     359    }
     360
     361    /**
     362     * This method initializes searchField 
     363     * 
     364     * @return javax.swing.JTextField   
     365    */
     366    private JTextField getSearchField() {
     367        if (searchField == null) {
     368            searchField = new JTextField();
     369            searchField.setBounds(new Rectangle(13, 111, 282, 20));
     370            searchField.setToolTipText("Enter keywords or EPSG codes");
     371            searchField.addKeyListener(new java.awt.event.KeyAdapter() {
     372                public void keyTyped(java.awt.event.KeyEvent e) {
     373                   
     374                    for (Iterator iterator = supportedCRS.iterator(); iterator
     375                            .hasNext();) {
     376                        String type = (String) iterator.next();
     377                        if(type.contains(searchField.getText()))
     378                        {
     379                            crsJList.setSelectedIndex(supportedCRS.indexOf(type));
     380                            crsJList.ensureIndexIsVisible(supportedCRS.indexOf(type));
     381                            break;
     382                        }
     383                       
     384                    }
     385                }
     386            });
     387        }
     388        return searchField;
     389    }
     390
     391    /**
     392     * This method initializes crsListScrollPane   
     393     * 
     394     * @return javax.swing.JScrollPane 
     395    */
     396    private JScrollPane getCrsListScrollPane() {
     397        if (crsListScrollPane == null) {
     398            crsListScrollPane = new JScrollPane();
     399            crsListScrollPane.setBounds(new Rectangle(15, 135, 301, 241));
     400            crsListScrollPane.setViewportView(getCrsJList());
     401        }
     402        return crsListScrollPane;
     403    }
     404
     405    /**
     406     * This method initializes crsJList
     407     * 
     408     * @return javax.swing.JList   
     409    */
     410    private JList getCrsJList() {
     411        if (crsJList == null) {
     412            crsJList = new JList(supportedCRS);
     413            crsJList.addListSelectionListener(new ListSelectionHandler());
     414        }
     415        return crsJList;
     416    }
     417
     418    /**
     419     * This method initializes useDefaultCRSButton 
     420     * 
     421     * @return javax.swing.JButton 
     422    */
     423    private JButton getUseDefaultCRSButton() {
     424        if (useDefaultCRSButton == null) {
     425            useDefaultCRSButton = new JButton();
     426            useDefaultCRSButton.setBounds(new Rectangle(253, 54, 118, 28));
     427            useDefaultCRSButton.setText("Apply Default");
     428            useDefaultCRSButton.addActionListener(new java.awt.event.ActionListener() {
     429                public void actionPerformed(java.awt.event.ActionEvent e) {
     430                   
     431                    try {
     432                       
     433                        setCursor(new Cursor(Cursor.WAIT_CURSOR));
     434                        if(PluginOperations.defaultSourceCRS != null){
     435                            imageLayer.resample(PluginOperations.defaultSourceCRS);
     436                        }else
     437                        {
     438                            JOptionPane.showMessageDialog(getContentPane(), "<html>No default reference system available.<br>Please select one from the list</html>");
     439                        }
     440                       
     441                    } catch (NoSuchAuthorityCodeException e1) {
     442                        // TODO Auto-generated catch block
     443                        e1.printStackTrace();
     444                    } catch (FactoryException e1) {
     445                        // TODO Auto-generated catch block
     446                        e1.printStackTrace();
     447                    } catch (IOException e2) {
     448                        // TODO Auto-generated catch block
     449                        e2.printStackTrace();
     450                    }
     451                    finally{
     452                        setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
     453                    }
     454                }
     455            });
     456        }
     457        return useDefaultCRSButton;
     458    }
     459
     460    /**
     461     * This method initializes applySelectedCRSButton   
     462     * 
     463     * @return javax.swing.JButton 
     464    */
     465    private JButton getApplySelectedCRSButton() {
     466        if (applySelectedCRSButton == null) {
     467            applySelectedCRSButton = new JButton();
     468            applySelectedCRSButton.setBounds(new Rectangle(315, 135, 69, 61));
     469            applySelectedCRSButton.setHorizontalAlignment(SwingConstants.CENTER);
     470            applySelectedCRSButton.setHorizontalTextPosition(SwingConstants.TRAILING);
     471            applySelectedCRSButton.setText("<html>Apply<br>Selection</html>");
     472            applySelectedCRSButton.addActionListener(new java.awt.event.ActionListener() {
     473                public void actionPerformed(java.awt.event.ActionEvent e) {
     474                   
     475                    String selection = (String) crsJList.getSelectedValue();
     476                    String code = selection.substring(selection.indexOf("[-") + 2, selection.indexOf("-]"));
     477                   
     478                    CoordinateReferenceSystem newRefSys = null;
     479                    try {
     480                        newRefSys = CRS.decode(code, eastingFirstCheckBox.isSelected());
     481                       
     482                        setCursor(new Cursor(Cursor.WAIT_CURSOR));
     483                       
     484                        imageLayer.resample(newRefSys);
     485
     486                    } catch (NoSuchAuthorityCodeException e1) {
     487                        // TODO Auto-generated catch block
     488                        e1.printStackTrace();
     489                    } catch (FactoryException e1) {
     490                        // TODO Auto-generated catch block
     491                        e1.printStackTrace();
     492                    } catch (IOException e2) {
     493                        // TODO Auto-generated catch block
     494                        e2.printStackTrace();
     495                    }
     496                    finally{
     497                        setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
     498                    }
     499                   
     500                   
     501                }
     502            });
     503        }
     504        return applySelectedCRSButton;
     505    }
     506
     507    /**
     508     * This method initializes setSelectedCRSAsDefaultButton   
     509     * 
     510     * @return javax.swing.JButton 
     511    */
     512    private JButton getSetSelectedCRSAsDefaultButton() {
     513        if (setSelectedCRSAsDefaultButton == null) {
     514            setSelectedCRSAsDefaultButton = new JButton();
     515            setSelectedCRSAsDefaultButton.setBounds(new Rectangle(315, 300, 69, 61));
     516            setSelectedCRSAsDefaultButton.setText("<html>Set as<br>Default</html>");
     517            setSelectedCRSAsDefaultButton
     518                    .addActionListener(new java.awt.event.ActionListener() {
     519                        public void actionPerformed(java.awt.event.ActionEvent e) {
     520                           
     521                            if(crsJList.getSelectedValue() != null){
     522                                String selection = (String) crsJList.getSelectedValue();
     523                                String code = selection.substring(selection.indexOf("[-") + 2, selection.indexOf("-]"));
     524                               
     525                                try {
     526                                    PluginOperations.defaultSourceCRS = CRS.decode(code, eastingFirstCheckBox.isSelected());
     527                                    PluginOperations.defaultSourceCRSDescription = selection;
     528                                   
     529                                    ImageImportPlugin.pluginProps.setProperty("default_crs_eastingfirst", "" + eastingFirstCheckBox.isSelected());
     530                                    ImageImportPlugin.pluginProps.setProperty("default_crs_srid", code);
     531                                    FileWriter fileWriter = new FileWriter(new File(ImageImportPlugin.PLUGINPROPERTIES_PATH));
     532                                    ImageImportPlugin.pluginProps.store(fileWriter, null);
     533                                    fileWriter.close();
     534                                   
     535                                    defaultCRSLabel.setText(selection);
     536                                   
     537                                } catch (IOException e2) {
     538                                    // TODO Auto-generated catch block
     539                                    e2.printStackTrace();
     540                                } catch (NoSuchAuthorityCodeException e3) {
     541                                    // TODO Auto-generated catch block
     542                                    e3.printStackTrace();
     543                                } catch (FactoryException e4) {
     544                                    // TODO Auto-generated catch block
     545                                    e4.printStackTrace();
     546                                }
     547                            }else{
     548                                JOptionPane.showMessageDialog(getContentPane(), "Please make a selection from the list.");
     549                            }
     550
     551                           
     552                        }
     553                    });
     554        }
     555        return setSelectedCRSAsDefaultButton;
     556    }
     557   
     558    /**
     559     * This method initializes eastingFirstCheckBox
     560     * 
     561     * @return javax.swing.JCheckBox   
     562    */
     563    private JCheckBox getEastingFirstCheckBox() {
     564        if (eastingFirstCheckBox == null) {
     565            eastingFirstCheckBox = new JCheckBox();
     566            eastingFirstCheckBox.setBounds(new Rectangle(345, 255, 21, 21));
     567        }
     568        return eastingFirstCheckBox;
     569    }
     570
     571   
     572   
     573    /**
     574    * Listener setting text in the search field if selection has changed.
     575    *
     576    */
    577577    class ListSelectionHandler implements ListSelectionListener {
    578578        public void valueChanged(ListSelectionEvent e) {
    579                 if(e.getValueIsAdjusting())
    580                 {
    581                 searchField.setText(supportedCRS.get(e.getLastIndex()));
    582                 searchField.setEditable(true);
    583                 }
     579            if(e.getValueIsAdjusting())
     580            {
     581                searchField.setText(supportedCRS.get(e.getLastIndex()));
     582                searchField.setEditable(true);
     583            }
    584584        }
    585585    }
  • applications/editors/josm/plugins/00_plugin_dir_template/src/org/openstreetmap/josm/plugins/ImportImagePlugin/LoadImageAction.java

    r23139 r23192  
    2626 */
    2727public class LoadImageAction extends JosmAction {
    28        
    29         private Logger logger = Logger.getLogger(LoadImageAction.class);
     28   
     29    private Logger logger = Logger.getLogger(LoadImageAction.class);
    3030
    31         /**
    32         * Constructor...
    33         */
    34         public LoadImageAction() {
    35                 super(tr("Import image"), null, tr("Import georeferenced image"), null, false);
    36         }
     31    /**
     32    * Constructor...
     33    */
     34    public LoadImageAction() {
     35        super(tr("Import image"), null, tr("Import georeferenced image"), null, false);
     36    }
    3737
    38         public void actionPerformed(ActionEvent arg0) {
     38    public void actionPerformed(ActionEvent arg0) {
    3939
    40                 // Choose a file
    41                 JFileChooser fc = new JFileChooser();
    42                 fc.setAcceptAllFileFilterUsed(false);
    43                 int result = fc.showOpenDialog(Main.parent);
    44                
    45                 ImageLayer layer = null;
    46                 if (result == JFileChooser.APPROVE_OPTION) {
    47                         logger.info("File choosed:" + fc.getSelectedFile());
    48                         try {
    49                                 layer = new ImageLayer(fc.getSelectedFile());
    50                         } catch (LayerCreationCancledException e) {
    51                                 // if user decides that layer should not be created just return.
    52                                 return;
    53                         }catch (Exception e) {
    54                                 logger.error("Error while creating image layer: \n" + e.getMessage());
    55                                 JOptionPane.showMessageDialog(null, marktr("Error while creating image layer: " + e.getCause()));
    56                                 return;
    57                                
    58                         }
    59                        
    60                         // Add layer:
    61                         Main.main.addLayer(layer);
    62                         LatLon min = new LatLon(layer.getBbox().getMinX(), layer.getBbox().getMinY());
    63                         LatLon max = new LatLon(layer.getBbox().getMaxX(), layer.getBbox().getMaxY());
    64                         BoundingXYVisitor boundingXYVisitor = new BoundingXYVisitor();
    65                         boundingXYVisitor.visit(new Bounds(min, max));
    66                         Main.map.mapView.recalculateCenterScale(boundingXYVisitor);
    67                         Main.map.mapView.zoomTo(new Bounds(min, max));
    68                 }
    69         }
     40        // Choose a file
     41        JFileChooser fc = new JFileChooser();
     42        fc.setAcceptAllFileFilterUsed(false);
     43        int result = fc.showOpenDialog(Main.parent);
     44       
     45        ImageLayer layer = null;
     46        if (result == JFileChooser.APPROVE_OPTION) {
     47            logger.info("File choosed:" + fc.getSelectedFile());
     48            try {
     49                layer = new ImageLayer(fc.getSelectedFile());
     50            } catch (LayerCreationCancledException e) {
     51                // if user decides that layer should not be created just return.
     52                return;
     53            }catch (Exception e) {
     54                logger.error("Error while creating image layer: \n" + e.getMessage());
     55                JOptionPane.showMessageDialog(null, marktr("Error while creating image layer: " + e.getCause()));
     56                return;
     57               
     58            }
     59           
     60            // Add layer:
     61            Main.main.addLayer(layer);
     62            LatLon min = new LatLon(layer.getBbox().getMinX(), layer.getBbox().getMinY());
     63            LatLon max = new LatLon(layer.getBbox().getMaxX(), layer.getBbox().getMaxY());
     64            BoundingXYVisitor boundingXYVisitor = new BoundingXYVisitor();
     65            boundingXYVisitor.visit(new Bounds(min, max));
     66            Main.map.mapView.recalculateCenterScale(boundingXYVisitor);
     67            Main.map.mapView.zoomTo(new Bounds(min, max));
     68        }
     69    }
    7070}
  • applications/editors/josm/plugins/00_plugin_dir_template/src/org/openstreetmap/josm/plugins/ImportImagePlugin/PluginOperations.java

    r23139 r23192  
    4747public class PluginOperations {
    4848
    49         private static final Logger logger = Logger.getLogger(PluginOperations.class);
    50        
    51         // contains descriptions of all available CRS
    52         static Vector<String> crsDescriptions;
    53 
    54         // the standard native CRS of user images
    55         static CoordinateReferenceSystem defaultSourceCRS;
    56         // description of 'defaultSourceCRS'
    57         static String defaultSourceCRSDescription;
    58        
    59        
    60        
    61         public static enum SUPPORTEDIMAGETYPES {
    62                 tiff, tif, jpg, jpeg, bmp, png
    63         }
    64 
    65         public static enum POSTFIXES_WORLDFILE {
    66                 wld, jgw, jpgw, pgw, pngw, tfw, tifw, bpw, bmpw,
    67         };
    68        
    69         /**
    70         * Reprojects a GridCoverage to a given CRS.
    71         *
    72         * @param coverage
    73         * @param targetCrs
    74         * @return destination
    75         * @throws FactoryException
    76         * @throws NoSuchAuthorityCodeException
    77         */
    78         public static GridCoverage2D reprojectCoverage(GridCoverage2D coverage,
    79                         CoordinateReferenceSystem targetCrs) throws NoSuchAuthorityCodeException, FactoryException {
    80 
    81                 // TODO: add category for NO_DATA values in coverage (transparency in
    82                 // image)
    83                
    84                 GridCoverage2D destination = null;
    85 
    86                 DefaultProcessor processor = new DefaultProcessor(null);
    87                 ParameterValueGroup resampleParams = processor.getOperation("Resample")
    88                                 .getParameters();
    89 
    90                 // set parameters
    91                 resampleParams.parameter("Source").setValue(coverage);
    92                 resampleParams.parameter("CoordinateReferenceSystem").setValue(
    93                                 targetCrs);
    94 
    95                 // resample coverage with given parameters
    96                 destination = (GridCoverage2D) processor.doOperation(resampleParams);
    97 
    98                 return destination;
    99         }
    100 
    101         /**
    102         * Creates a org.geotools.coverage.grid.GridCoverage2D from a given file.
    103         *
    104         * @param file
    105         * @return
    106         * @throws IOException
    107         * @throws Exception
    108         */
    109         public static GridCoverage2D createGridFromFile(File file, CoordinateReferenceSystem refSys) throws IOException{
    110 
    111                 GridCoverage2D coverage = null;
    112                
    113                 if (!file.exists()) throw new FileNotFoundException("File not found.");
    114 
    115                 String extension = null;
    116                 String fileNameWithoutExt = null;
    117                 int dotPos = file.getAbsolutePath().lastIndexOf(".");
    118                 extension = file.getAbsolutePath().substring(dotPos);
    119                 fileNameWithoutExt = file.getAbsolutePath().substring(0, dotPos);
    120 
    121                 /*------- switch for file type -----------*/
    122                 if (extension.equalsIgnoreCase(".tif")
    123                                 || extension.equalsIgnoreCase(".tiff"))
    124                 {
    125                        
    126                         // try to read GeoTIFF:
    127                         try{
    128                                 coverage = readGeoTiff(file, refSys);
    129                                 return coverage;
    130                         }catch (DataSourceException dse) {
    131                                 if(!dse.getMessage().contains("Coordinate Reference System is not available")){
    132                                         dse.printStackTrace();
    133                                 }
    134                         } catch (FactoryException facte) {
    135                                 logger.fatal("Error while reading from GeoTIFF:", facte);
    136                                 throw new IOException(facte);
    137                         }
    138                        
    139                         // file is no GeoTiff, searching for Worldfile and projection file:
    140                         String[] postfixes = {"wld", "tfw", "tifw"};
    141                         // try to read Worldfile:
    142                         WorldFileReader tfwReader = null;
    143                         for (int i = 0; i < postfixes.length; i++) {
    144                                 File prjFile = new File(fileNameWithoutExt + "." + postfixes[i]);
    145                                 if(prjFile.exists()){
    146                                         tfwReader = new WorldFileReader(prjFile);
    147                                 }
    148                         }
    149                         if(tfwReader == null){
    150                                 throw new IOException("No Worldfile found.");
    151                         }
    152                        
    153                         if(refSys == null){
    154                                 // if no crs is delivered try to read projection file:
    155                                 refSys = readPrjFile(file);
    156                                 if(refSys == null) throw new IOException("No projection file found.");
    157                         }
    158                        
    159                         BufferedImage img = ImageIO.read(file);
    160                        
    161                         // create Envelope
    162                         double width = (double) (img.getWidth() * tfwReader.getXPixelSize());
    163                         double height = (double) (img.getHeight() * (-tfwReader.getYPixelSize()));
    164                         double lowerLeft_x = (double) tfwReader.getXULC();
    165                         double lowerLeft_y = (double) tfwReader.getYULC() - height;
    166                         Envelope2D bbox = new Envelope2D(null, new Rectangle2D.Double(lowerLeft_x, lowerLeft_y, width, height));
    167                        
    168                         coverage = createGridCoverage(img, bbox, refSys);
    169                        
    170                 }
    171                 //
    172                 else if (extension.equalsIgnoreCase(".jpg")
    173                                 || extension.equalsIgnoreCase(".jpeg"))
    174                 {
    175                         String[] postfixes = {"wld", "jgw", "jpgw"};
    176                         // try to read Worldfile:
    177                         WorldFileReader tfwReader = null;
    178                         for (int i = 0; i < postfixes.length; i++) {
    179                                 File prjFile = new File(fileNameWithoutExt + "." + postfixes[i]);
    180                                 if(prjFile.exists()){
    181                                         tfwReader = new WorldFileReader(prjFile);
    182                                 }
    183                         }
    184                         if(tfwReader == null) throw new IOException("No Worldfile found.");
    185                        
    186                         if(refSys == null){
    187                                 // if no crs is delivered try to read projection file:
    188                                 refSys = readPrjFile(file);
    189                                 if(refSys == null) throw new IOException("No projection file found.");
    190                         }
    191                        
    192                         BufferedImage img = ImageIO.read(file);
    193                        
    194                         // create Envelope
    195                         double width = (double) (img.getWidth() * tfwReader.getXPixelSize());
    196                         double height = (double) (img.getHeight() * (-tfwReader.getYPixelSize()));
    197                         double lowerLeft_x = (double) tfwReader.getXULC();
    198                         double lowerLeft_y = (double) tfwReader.getYULC() - height;
    199                         Envelope2D bbox = new Envelope2D(null, new Rectangle2D.Double(lowerLeft_x, lowerLeft_y, width, height));
    200                        
    201                         coverage = createGridCoverage(img, bbox, refSys);
    202                        
    203                 }
    204                 else if(extension.equalsIgnoreCase(".bmp"))
    205                 {
    206                         String[] postfixes = {"wld", "bmpw", "bpw"};
    207                         // try to read Worldfile:
    208                         WorldFileReader tfwReader = null;
    209                         for (int i = 0; i < postfixes.length; i++) {
    210                                 File prjFile = new File(fileNameWithoutExt + "." + postfixes[i]);
    211                                 if(prjFile.exists()){
    212                                         tfwReader = new WorldFileReader(prjFile);
    213                                 }
    214                         }
    215                         if(tfwReader == null) throw new IOException("No Worldfile found.");
    216 
    217                         if(refSys == null){
    218                                 // if no crs is delivered try to read projection file:
    219                                 refSys = readPrjFile(file);
    220                                 if(refSys == null) throw new IOException("No projection file found.");
    221                         }
    222                        
    223                         BufferedImage img = ImageIO.read(file);
    224                        
    225                         // create Envelope
    226                         double width = (double) (img.getWidth() * tfwReader.getXPixelSize());
    227                         double height = (double) (img.getHeight() * (-tfwReader.getYPixelSize()));
    228                         double lowerLeft_x = (double) tfwReader.getXULC();
    229                         double lowerLeft_y = (double) tfwReader.getYULC() - height;
    230                         Envelope2D bbox = new Envelope2D(null, new Rectangle2D.Double(lowerLeft_x, lowerLeft_y, width, height));
    231                        
    232                         coverage = createGridCoverage(img, bbox, refSys);
    233                 }
    234                 else if(extension.equalsIgnoreCase(".png"))
    235                 {
    236                        
    237                         String[] postfixes = {"wld", "pgw", "pngw"};
    238                         // try to read Worldfile:
    239                         WorldFileReader tfwReader = null;
    240                         for (int i = 0; i < postfixes.length; i++) {
    241                                 File prjFile = new File(fileNameWithoutExt + "." + postfixes[i]);
    242                                 if(prjFile.exists()){
    243                                         tfwReader = new WorldFileReader(prjFile);
    244                                 }
    245                         }
    246                         if(tfwReader == null) throw new IOException("No Worldfile found.");
    247                        
    248                         if(refSys == null){
    249                                 // if no crs is delivered try to read projection file:
    250                                 refSys = readPrjFile(file);
    251                                 if(refSys == null) throw new IOException("No projection file found.");
    252                         }
    253                        
    254                         BufferedImage img = ImageIO.read(file);
    255                        
    256                         // create Envelope
    257                         double width = (double) (img.getWidth() * tfwReader.getXPixelSize());
    258                         double height = (double) (img.getHeight() * (-tfwReader.getYPixelSize()));
    259                         double lowerLeft_x = (double) tfwReader.getXULC();
    260                         double lowerLeft_y = (double) tfwReader.getYULC() - height;
    261                         Envelope2D bbox = new Envelope2D(null, new Rectangle2D.Double(lowerLeft_x, lowerLeft_y, width, height));
    262                        
    263                         coverage = createGridCoverage(img, bbox, refSys);
    264                 }
    265                 else{
    266                         throw new IOException("Image type not supported. Supported formats are: \n" +
    267                                         Arrays.toString(SUPPORTEDIMAGETYPES.values()));
    268                 }
    269 
    270                 return coverage;
    271         }
    272        
    273         /**
    274         * Searches for a projection file (.prj) with the same name of 'file'
    275         * tries to parse it.
    276         *
    277         *
    278         * @param file image file, not the real world file (will be searched)
    279         * @return
    280         * @throws IOException
    281         */
    282         public static CoordinateReferenceSystem readPrjFile(File file) throws IOException
    283         {
    284                
    285                 CoordinateReferenceSystem refSys = null;
    286                
    287                 String prjFilename = null;
    288                 int dotPos = file.getAbsolutePath().lastIndexOf(".");
    289                 prjFilename = file.getAbsolutePath().substring(0, dotPos) + ".prj";
    290                
    291                 File prjFile = new File(prjFilename);
    292                 if(!prjFile.exists()) throw new IOException("No projection file found (.prj) for image '" + file.getName() + "'");
    293                 logger.debug("Loading .prj file: " + prjFile.getAbsolutePath());
    294                
    295                 StringBuilder sb = new StringBuilder();
    296                 String content = null;
    297                 BufferedReader br = new BufferedReader(new FileReader(prjFile));
    298                 while((content = br.readLine()) != null)
    299                 {
    300                         sb.append(content);
    301                 }
    302                
    303                 try {
    304                         refSys = CRS.parseWKT(sb.toString().trim());
    305                 } catch (FactoryException e) {
    306                         throw new IOException("Unable to parse prj-file: '" + prjFile.getName() + "'");
    307                 }
    308                
    309                 return refSys;
    310                
    311         }
    312        
    313        
    314         /**
    315         * Method for external use.
    316         *
    317         * @param img
    318         * @param bbox
    319         * @param crs
    320         * @return
    321         */
    322         public static GridCoverage2D createGridCoverage(BufferedImage img, Envelope2D bbox, CoordinateReferenceSystem crs)
    323         {
    324                 bbox.setCoordinateReferenceSystem(crs);
    325                 return new GridCoverageFactory().create("", img, bbox);
    326         }
    327        
    328         /**
    329         * Method for reading a GeoTIFF file.
    330         *
    331         * @param file
    332         * @param refSys if delivered, the coverage will be forced to use this crs
    333         * @return
    334         * @throws IOException
    335         * @throws FactoryException
    336         */
    337         public static GridCoverage2D readGeoTiff(File file, CoordinateReferenceSystem refSys) throws IOException, FactoryException
    338         {
    339                 GridCoverage2D coverage = null;
    340                 Hints hints = new Hints();
    341                 if(refSys != null)
    342                 {
    343                         hints.put(Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM, refSys);
    344 
    345                 }
    346                 // dont't use the EPSG-Factory because of wrong behaviour
    347                 hints.put(Hints.CRS_AUTHORITY_FACTORY, CRS.getAuthorityFactory(true));
    348                
    349                 GeoTiffReader reader = new GeoTiffReader(file, hints);
    350                
    351                 coverage = (GridCoverage2D) reader.read(null);
    352                
    353                 return coverage;
    354         }
    355        
    356        
    357         /**
    358         * Loads CRS data from an EPSG database and creates descrptions for each one.
    359         *
    360         * @param pluginProps
    361         * @throws Exception
    362         */
    363         public static void loadCRSData(Properties pluginProps)
    364         {
    365                 String defaultcrsString = pluginProps.getProperty("default_crs_srid");
    366                
    367                 crsDescriptions = new Vector<String>();
    368                 Set<String> supportedCodes = CRS.getSupportedCodes("EPSG");
    369                 CRSAuthorityFactory fac = CRS.getAuthorityFactory(false);
    370                
    371                 for (Iterator iterator = supportedCodes.iterator(); iterator.hasNext();) {
    372                         String string = (String) iterator.next();
    373                         try {
    374                                 InternationalString desc = fac.getDescriptionText("EPSG:" + string);
    375 
    376                                 String description = desc.toString() + " [-EPSG:" + string + "-]";
    377                                
    378                                 crsDescriptions.add(description);
    379                                
    380                                 if(defaultcrsString != null && defaultcrsString.equalsIgnoreCase("EPSG:" + string)){
    381                                         boolean isEastingFirst = Boolean.valueOf(pluginProps.getProperty("default_crs_eastingfirst"));
    382                                         defaultSourceCRS = CRS.decode("EPSG:" + string, isEastingFirst);
    383                                         defaultSourceCRSDescription = description;
    384                                 }
    385                         } catch (NoSuchAuthorityCodeException e) {
    386                                 if(!string.equalsIgnoreCase("WGS84(DD)")){
    387                                         logger.error("Error while loading EPSG data: " + e.getMessage());
    388                                 }
    389                         } catch (FactoryException e) {
    390                                 logger.error("Error while loading EPSG data: " + e.getMessage());
    391                         }
    392                 }
    393         }
    394        
     49    private static final Logger logger = Logger.getLogger(PluginOperations.class);
     50   
     51    // contains descriptions of all available CRS
     52    static Vector<String> crsDescriptions;
     53
     54    // the standard native CRS of user images
     55    static CoordinateReferenceSystem defaultSourceCRS;
     56    // description of 'defaultSourceCRS'
     57    static String defaultSourceCRSDescription;
     58   
     59   
     60   
     61    public static enum SUPPORTEDIMAGETYPES {
     62        tiff, tif, jpg, jpeg, bmp, png
     63    }
     64
     65    public static enum POSTFIXES_WORLDFILE {
     66        wld, jgw, jpgw, pgw, pngw, tfw, tifw, bpw, bmpw,
     67    };
     68   
     69    /**
     70    * Reprojects a GridCoverage to a given CRS.
     71    *
     72    * @param coverage
     73    * @param targetCrs
     74    * @return destination
     75    * @throws FactoryException
     76    * @throws NoSuchAuthorityCodeException
     77    */
     78    public static GridCoverage2D reprojectCoverage(GridCoverage2D coverage,
     79            CoordinateReferenceSystem targetCrs) throws NoSuchAuthorityCodeException, FactoryException {
     80
     81        // TODO: add category for NO_DATA values in coverage (transparency in
     82        // image)
     83       
     84        GridCoverage2D destination = null;
     85
     86        DefaultProcessor processor = new DefaultProcessor(null);
     87        ParameterValueGroup resampleParams = processor.getOperation("Resample")
     88                .getParameters();
     89
     90        // set parameters
     91        resampleParams.parameter("Source").setValue(coverage);
     92        resampleParams.parameter("CoordinateReferenceSystem").setValue(
     93                targetCrs);
     94
     95        // resample coverage with given parameters
     96        destination = (GridCoverage2D) processor.doOperation(resampleParams);
     97
     98        return destination;
     99    }
     100
     101    /**
     102    * Creates a org.geotools.coverage.grid.GridCoverage2D from a given file.
     103    *
     104    * @param file
     105    * @return
     106    * @throws IOException
     107    * @throws Exception
     108    */
     109    public static GridCoverage2D createGridFromFile(File file, CoordinateReferenceSystem refSys) throws IOException{
     110
     111        GridCoverage2D coverage = null;
     112       
     113        if (!file.exists()) throw new FileNotFoundException("File not found.");
     114
     115        String extension = null;
     116        String fileNameWithoutExt = null;
     117        int dotPos = file.getAbsolutePath().lastIndexOf(".");
     118        extension = file.getAbsolutePath().substring(dotPos);
     119        fileNameWithoutExt = file.getAbsolutePath().substring(0, dotPos);
     120
     121        /*------- switch for file type -----------*/
     122        if (extension.equalsIgnoreCase(".tif")
     123                || extension.equalsIgnoreCase(".tiff"))
     124        {
     125           
     126            // try to read GeoTIFF:
     127            try{
     128                coverage = readGeoTiff(file, refSys);
     129                return coverage;
     130            }catch (DataSourceException dse) {
     131                if(!dse.getMessage().contains("Coordinate Reference System is not available")){
     132                    dse.printStackTrace();
     133                }
     134            } catch (FactoryException facte) {
     135                logger.fatal("Error while reading from GeoTIFF:", facte);
     136                throw new IOException(facte);
     137            }
     138           
     139            // file is no GeoTiff, searching for Worldfile and projection file:
     140            String[] postfixes = {"wld", "tfw", "tifw"};
     141            // try to read Worldfile:
     142            WorldFileReader tfwReader = null;
     143            for (int i = 0; i < postfixes.length; i++) {
     144                File prjFile = new File(fileNameWithoutExt + "." + postfixes[i]);
     145                if(prjFile.exists()){
     146                    tfwReader = new WorldFileReader(prjFile);
     147                }
     148            }
     149            if(tfwReader == null){
     150                throw new IOException("No Worldfile found.");
     151            }
     152           
     153            if(refSys == null){
     154                // if no crs is delivered try to read projection file:
     155                refSys = readPrjFile(file);
     156                if(refSys == null) throw new IOException("No projection file found.");
     157            }
     158           
     159            BufferedImage img = ImageIO.read(file);
     160           
     161            // create Envelope
     162            double width = (double) (img.getWidth() * tfwReader.getXPixelSize());
     163            double height = (double) (img.getHeight() * (-tfwReader.getYPixelSize()));
     164            double lowerLeft_x = (double) tfwReader.getXULC();
     165            double lowerLeft_y = (double) tfwReader.getYULC() - height;
     166            Envelope2D bbox = new Envelope2D(null, new Rectangle2D.Double(lowerLeft_x, lowerLeft_y, width, height));
     167           
     168            coverage = createGridCoverage(img, bbox, refSys);
     169           
     170        }
     171        //
     172        else if (extension.equalsIgnoreCase(".jpg")
     173                || extension.equalsIgnoreCase(".jpeg"))
     174        {
     175            String[] postfixes = {"wld", "jgw", "jpgw"};
     176            // try to read Worldfile:
     177            WorldFileReader tfwReader = null;
     178            for (int i = 0; i < postfixes.length; i++) {
     179                File prjFile = new File(fileNameWithoutExt + "." + postfixes[i]);
     180                if(prjFile.exists()){
     181                    tfwReader = new WorldFileReader(prjFile);
     182                }
     183            }
     184            if(tfwReader == null) throw new IOException("No Worldfile found.");
     185           
     186            if(refSys == null){
     187                // if no crs is delivered try to read projection file:
     188                refSys = readPrjFile(file);
     189                if(refSys == null) throw new IOException("No projection file found.");
     190            }
     191           
     192            BufferedImage img = ImageIO.read(file);
     193           
     194            // create Envelope
     195            double width = (double) (img.getWidth() * tfwReader.getXPixelSize());
     196            double height = (double) (img.getHeight() * (-tfwReader.getYPixelSize()));
     197            double lowerLeft_x = (double) tfwReader.getXULC();
     198            double lowerLeft_y = (double) tfwReader.getYULC() - height;
     199            Envelope2D bbox = new Envelope2D(null, new Rectangle2D.Double(lowerLeft_x, lowerLeft_y, width, height));
     200           
     201            coverage = createGridCoverage(img, bbox, refSys);
     202           
     203        }
     204        else if(extension.equalsIgnoreCase(".bmp"))
     205        {
     206            String[] postfixes = {"wld", "bmpw", "bpw"};
     207            // try to read Worldfile:
     208            WorldFileReader tfwReader = null;
     209            for (int i = 0; i < postfixes.length; i++) {
     210                File prjFile = new File(fileNameWithoutExt + "." + postfixes[i]);
     211                if(prjFile.exists()){
     212                    tfwReader = new WorldFileReader(prjFile);
     213                }
     214            }
     215            if(tfwReader == null) throw new IOException("No Worldfile found.");
     216
     217            if(refSys == null){
     218                // if no crs is delivered try to read projection file:
     219                refSys = readPrjFile(file);
     220                if(refSys == null) throw new IOException("No projection file found.");
     221            }
     222           
     223            BufferedImage img = ImageIO.read(file);
     224           
     225            // create Envelope
     226            double width = (double) (img.getWidth() * tfwReader.getXPixelSize());
     227            double height = (double) (img.getHeight() * (-tfwReader.getYPixelSize()));
     228            double lowerLeft_x = (double) tfwReader.getXULC();
     229            double lowerLeft_y = (double) tfwReader.getYULC() - height;
     230            Envelope2D bbox = new Envelope2D(null, new Rectangle2D.Double(lowerLeft_x, lowerLeft_y, width, height));
     231           
     232            coverage = createGridCoverage(img, bbox, refSys);
     233        }
     234        else if(extension.equalsIgnoreCase(".png"))
     235        {
     236           
     237            String[] postfixes = {"wld", "pgw", "pngw"};
     238            // try to read Worldfile:
     239            WorldFileReader tfwReader = null;
     240            for (int i = 0; i < postfixes.length; i++) {
     241                File prjFile = new File(fileNameWithoutExt + "." + postfixes[i]);
     242                if(prjFile.exists()){
     243                    tfwReader = new WorldFileReader(prjFile);
     244                }
     245            }
     246            if(tfwReader == null) throw new IOException("No Worldfile found.");
     247           
     248            if(refSys == null){
     249                // if no crs is delivered try to read projection file:
     250                refSys = readPrjFile(file);
     251                if(refSys == null) throw new IOException("No projection file found.");
     252            }
     253           
     254            BufferedImage img = ImageIO.read(file);
     255           
     256            // create Envelope
     257            double width = (double) (img.getWidth() * tfwReader.getXPixelSize());
     258            double height = (double) (img.getHeight() * (-tfwReader.getYPixelSize()));
     259            double lowerLeft_x = (double) tfwReader.getXULC();
     260            double lowerLeft_y = (double) tfwReader.getYULC() - height;
     261            Envelope2D bbox = new Envelope2D(null, new Rectangle2D.Double(lowerLeft_x, lowerLeft_y, width, height));
     262           
     263            coverage = createGridCoverage(img, bbox, refSys);
     264        }
     265        else{
     266            throw new IOException("Image type not supported. Supported formats are: \n" +
     267                    Arrays.toString(SUPPORTEDIMAGETYPES.values()));
     268        }
     269
     270        return coverage;
     271    }
     272   
     273    /**
     274    * Searches for a projection file (.prj) with the same name of 'file'
     275    * tries to parse it.
     276    *
     277    *
     278    * @param file image file, not the real world file (will be searched)
     279    * @return
     280    * @throws IOException
     281    */
     282    public static CoordinateReferenceSystem readPrjFile(File file) throws IOException
     283    {
     284       
     285        CoordinateReferenceSystem refSys = null;
     286       
     287        String prjFilename = null;
     288        int dotPos = file.getAbsolutePath().lastIndexOf(".");
     289        prjFilename = file.getAbsolutePath().substring(0, dotPos) + ".prj";
     290       
     291        File prjFile = new File(prjFilename);
     292        if(!prjFile.exists()) throw new IOException("No projection file found (.prj) for image '" + file.getName() + "'");
     293        logger.debug("Loading .prj file: " + prjFile.getAbsolutePath());
     294       
     295        StringBuilder sb = new StringBuilder();
     296        String content = null;
     297        BufferedReader br = new BufferedReader(new FileReader(prjFile));
     298        while((content = br.readLine()) != null)
     299        {
     300            sb.append(content);
     301        }
     302       
     303        try {
     304            refSys = CRS.parseWKT(sb.toString().trim());
     305        } catch (FactoryException e) {
     306            throw new IOException("Unable to parse prj-file: '" + prjFile.getName() + "'");
     307        }
     308       
     309        return refSys;
     310       
     311    }
     312   
     313   
     314    /**
     315    * Method for external use.
     316    *
     317    * @param img
     318    * @param bbox
     319    * @param crs
     320    * @return
     321    */
     322    public static GridCoverage2D createGridCoverage(BufferedImage img, Envelope2D bbox, CoordinateReferenceSystem crs)
     323    {
     324        bbox.setCoordinateReferenceSystem(crs);
     325        return new GridCoverageFactory().create("", img, bbox);
     326    }
     327   
     328    /**
     329    * Method for reading a GeoTIFF file.
     330    *
     331    * @param file
     332    * @param refSys if delivered, the coverage will be forced to use this crs
     333    * @return
     334    * @throws IOException
     335    * @throws FactoryException
     336    */
     337    public static GridCoverage2D readGeoTiff(File file, CoordinateReferenceSystem refSys) throws IOException, FactoryException
     338    {
     339        GridCoverage2D coverage = null;
     340        Hints hints = new Hints();
     341        if(refSys != null)
     342        {
     343            hints.put(Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM, refSys);
     344
     345        }
     346        // dont't use the EPSG-Factory because of wrong behaviour
     347        hints.put(Hints.CRS_AUTHORITY_FACTORY, CRS.getAuthorityFactory(true));
     348       
     349        GeoTiffReader reader = new GeoTiffReader(file, hints);
     350       
     351        coverage = (GridCoverage2D) reader.read(null);
     352       
     353        return coverage;
     354    }
     355   
     356   
     357    /**
     358    * Loads CRS data from an EPSG database and creates descrptions for each one.
     359    *
     360    * @param pluginProps
     361    * @throws Exception
     362    */
     363    public static void loadCRSData(Properties pluginProps)
     364    {
     365        String defaultcrsString = pluginProps.getProperty("default_crs_srid");
     366       
     367        crsDescriptions = new Vector<String>();
     368        Set<String> supportedCodes = CRS.getSupportedCodes("EPSG");
     369        CRSAuthorityFactory fac = CRS.getAuthorityFactory(false);
     370       
     371        for (Iterator iterator = supportedCodes.iterator(); iterator.hasNext();) {
     372            String string = (String) iterator.next();
     373            try {
     374                InternationalString desc = fac.getDescriptionText("EPSG:" + string);
     375
     376                String description = desc.toString() + " [-EPSG:" + string + "-]";
     377               
     378                crsDescriptions.add(description);
     379               
     380                if(defaultcrsString != null && defaultcrsString.equalsIgnoreCase("EPSG:" + string)){
     381                    boolean isEastingFirst = Boolean.valueOf(pluginProps.getProperty("default_crs_eastingfirst"));
     382                    defaultSourceCRS = CRS.decode("EPSG:" + string, isEastingFirst);
     383                    defaultSourceCRSDescription = description;
     384                }
     385            } catch (NoSuchAuthorityCodeException e) {
     386                if(!string.equalsIgnoreCase("WGS84(DD)")){
     387                    logger.error("Error while loading EPSG data: " + e.getMessage());
     388                }
     389            } catch (FactoryException e) {
     390                logger.error("Error while loading EPSG data: " + e.getMessage());
     391            }
     392        }
     393    }
     394   
    395395}
  • applications/editors/josm/plugins/Create_grid_of_ways/src/CreateGridOfWaysPlugin/CreateGridOfWaysPlugin.java

    r19428 r23192  
    88public class CreateGridOfWaysPlugin extends Plugin {
    99    public CreateGridOfWaysPlugin(PluginInformation info) {
    10         super(info);
     10        super(info);
    1111        MainMenu.add(Main.main.menu.toolsMenu, new CreateGridOfWaysAction());
    1212    }
  • applications/editors/josm/plugins/ImportImagePlugin

    • Property svn:ignore set to
      build
  • applications/editors/josm/plugins/OpeningHoursEditor/src/org/openstreetmap/josm/plugins/ohe/OhePlugin.java

    r22873 r23192  
    3838public class OhePlugin extends Plugin {
    3939
    40         // Strings for choosing which key of an object with given tags should be
    41         // edited
    42         // the order is referencing the preference of the keys
    43         // String[] -> {key, value, to-editing-key} key and value can contain regexp
    44         private final String[][] TAG_EDIT_STRINGS = new String[][] {
    45                         { "opening_hours", ".*", "opening_hours" },
    46                         { "collection_times", ".*", "collection_times" },
    47                         { "collection_times:local", ".*", "collection_times:local" },
    48                         { "lit", ".*", "lit" },
    49                         { "amenity", "post_box", "collection_times" },
    50                         { "amenity", ".*", "opening_hours" },
    51                         { "shop", ".*", "opening_hours" }, { "highway", ".*", "lit" } };
    52 
    53         /**
    54         * Will be invoked by JOSM to bootstrap the plugin
    55          *
    56         * @param info
    57         *            information about the plugin and its local installation
    58         */
    59         public OhePlugin(PluginInformation info) {
    60                 super(info);
    61                 Main.main.menu.toolsMenu.add(new OheMenuAction());
    62         }
    63 
    64         class OheMenuAction extends JosmAction {
    65                 public OheMenuAction() {
    66                         super(
    67                                         tr("Edit opening hours"),
    68                                         "opening_hours.png",
    69                                         tr("Edit time-tag of selected element in a graphical interface"),
    70                                         Shortcut.registerShortcut("tools:opening_hourseditor", tr(
    71                                                         "Tool: {0}", tr("Edit opening hours")),
    72                                                         KeyEvent.VK_T, Shortcut.GROUP_MENU), false);
    73                 }
    74 
    75                 @Override
    76                 protected void updateEnabledState() {
    77                         if (getCurrentDataSet() == null) {
    78                                 setEnabled(false);
    79                         } else {
    80                                 updateEnabledState(getCurrentDataSet().getSelected());
    81                         }
    82                 }
    83 
    84                 @Override
    85                 protected void updateEnabledState(
    86                                 Collection<? extends OsmPrimitive> selection) {
    87                         setEnabled(selection != null && !selection.isEmpty());
    88                 }
    89 
    90                 public void actionPerformed(ActionEvent evt) {
    91                         // fetch active Layer
    92                         OsmDataLayer osmlayer = Main.main.getEditLayer();
    93                         if (osmlayer != null) {
    94                                 Collection<OsmPrimitive> selection = osmlayer.data
    95                                                 .getSelected();
    96                                 if (selection.size() == 1) { // one object selected
    97                                         OsmPrimitive object = selection.iterator().next();
    98                                         String[] keyValuePair = editTimeTags(object.getKeys());
    99                                         if (keyValuePair != null) {
    100                                                 String key = keyValuePair[0].trim();
    101                                                 String newkey = keyValuePair[1].trim();
    102                                                 String value = keyValuePair[2].trim();
    103 
    104                                                 if (value.equals("")) {
    105                                                         value = null; // delete the key
    106                                                 }
    107                                                 if (newkey.equals("")) {
    108                                                         newkey = key;
    109                                                         value = null; // delete the key instead
    110                                                 }
    111                                                 if (key.equals(newkey)
    112                                                                 && tr("<different>").equals(value))
    113                                                         return;
    114                                                 if (key.equals(newkey) || value == null) {
    115                                                         Main.main.undoRedo.add(new ChangePropertyCommand(
    116                                                                         object, newkey, value));
    117                                                 } else {
    118                                                         Collection<Command> commands = new Vector<Command>();
    119                                                         commands.add(new ChangePropertyCommand(object, key,
    120                                                                         null));
    121                                                         commands.add(new ChangePropertyCommand(object,
    122                                                                         newkey, value));
    123                                                         Main.main.undoRedo.add(new SequenceCommand(
    124                                                                         tr("Change properties of 1 object"),
    125                                                                         commands));
    126                                                 }
    127                                         }
    128                                 } else { // Not possible to edit 0, 2 or more objects
    129                                         JOptionPane
    130                                                         .showMessageDialog(
    131                                                                         Main.parent,
    132                                                                         tr(
    133                                                                                         "You have {0} Elements selected. But you can edit only one element!",
    134                                                                                         selection.size()),
    135                                                                         "openingHoursEditor Warning",
    136                                                                         JOptionPane.ERROR_MESSAGE);
    137                                 }
    138                         }
    139                 }
    140         }
    141 
    142         // opens up dialogs to change one of the key-value-pairs and returns the
    143         // changed pair
    144         private String[] editTimeTags(Map<String, String> keyValueMap) {
    145                 String selectedKey = "";
    146 
    147                 if ((selectedKey = tagChooseDialog(keyValueMap)) == null)
    148                         return null;
    149 
    150                 final String value = (keyValueMap.containsKey(selectedKey)) ? keyValueMap
    151                                 .get(selectedKey)
    152                                 : "";
    153                 OheDialogPanel panel = new OheDialogPanel(this, selectedKey, value);
    154 
    155                 final JOptionPane optionPane = new JOptionPane(panel,
    156                                 JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
    157                 final JDialog dlg = optionPane.createDialog(Main.parent, tr("Edit"));
    158 
    159                 dlg.setResizable(true);
    160                 dlg.setVisible(true);
    161 
    162                 Object answer = optionPane.getValue();
    163                 if (!(answer == null || answer == JOptionPane.UNINITIALIZED_VALUE || (answer instanceof Integer && (Integer) answer != JOptionPane.OK_OPTION)))
    164                         return panel.getChangedKeyValuePair();
    165 
    166                 return null;
    167         }
    168 
    169         // opens a dialog for choosing from a set of tags which can be edited
    170         // the chosen one is returned
    171         private String tagChooseDialog(Map<String, String> keyValueMap) {
    172                 String preSelectedKey = getPreSelectedKey(keyValueMap);
    173                 int preSelectedRow = -1;
    174 
    175                 String[][] rowData = new String[keyValueMap.size()][2];
    176                 int cnt = 0;
    177                 for (Object key : keyValueMap.keySet().toArray()) {
    178                         rowData[cnt][0] = key.toString();
    179                         rowData[cnt][1] = keyValueMap.get(key);
    180                         if (key.toString().equals(preSelectedKey))
    181                                 preSelectedRow = cnt;
    182                         cnt++;
    183                 }
    184 
    185                 final JTable table = new JTable(rowData,
    186                                 new String[] { "key", "value" }) {
    187                         public boolean isCellEditable(int rowIndex, int colIndex) {
    188                                 return false; // Disallow the editing of any cell
    189                         }
    190                 };
    191                 table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    192                 JScrollPane sp = new JScrollPane(
    193                                 JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
    194                                 JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    195                 sp.setViewportView(table);
    196 
    197                 final JTextField tf = new JTextField();
    198 
    199                 ActionListener al = new ActionListener() {
    200                         @Override
    201                         public void actionPerformed(ActionEvent e) {
    202                                 if (e.getActionCommand().equals("edit")) {
    203                                         table.setEnabled(true);
    204                                         tf.setEnabled(false);
    205                                 } else if (e.getActionCommand().equals("new")) {
    206                                         table.setEnabled(false);
    207                                         tf.setEnabled(true);
    208                                 }
    209                         }
    210                 };
    211 
    212                 JRadioButton editButton = new JRadioButton("edit existing tag");
    213                 editButton.setActionCommand("edit");
    214                 editButton.addActionListener(al);
    215                 JRadioButton newButton = new JRadioButton("edit new tag");
    216                 newButton.setActionCommand("new");
    217                 newButton.addActionListener(al);
    218                 ButtonGroup group = new ButtonGroup();
    219                 group.add(newButton);
    220                 group.add(editButton);
    221 
    222                 if (preSelectedRow != -1) {
    223                         table.setEnabled(true);
    224                         tf.setEnabled(false);
    225                         table.setRowSelectionInterval(preSelectedRow, preSelectedRow);
    226                         editButton.setSelected(true);
    227                 } else {
    228                         table.setEnabled(false);
    229                         tf.setEnabled(true);
    230                         tf.setText(preSelectedKey);
    231                         newButton.setSelected(true);
    232                 }
    233 
    234                 JPanel dlgPanel = new JPanel(new GridBagLayout());
    235                 dlgPanel.add(editButton, GBC.std().anchor(GBC.CENTER));
    236                 dlgPanel.add(sp, GBC.eol().fill(GBC.BOTH));
    237                 dlgPanel.add(newButton, GBC.std().anchor(GBC.CENTER));
    238                 dlgPanel.add(tf, GBC.eol().fill(GBC.HORIZONTAL));
    239 
    240                 JOptionPane optionPane = new JOptionPane(dlgPanel,
    241                                 JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
    242                 JDialog dlg = optionPane.createDialog(Main.parent, tr("Choose key"));
    243 
    244                 dlg.pack();
    245                 dlg.setResizable(true);
    246                 dlg.setVisible(true);
    247 
    248                 Object answer = optionPane.getValue();
    249                 if (answer != null
    250                                 && answer != JOptionPane.UNINITIALIZED_VALUE
    251                                 && (answer instanceof Integer && (Integer) answer == JOptionPane.OK_OPTION))
    252                         if (editButton.isSelected() && table.getSelectedRow() != -1)
    253                                 return rowData[table.getSelectedRow()][0];
    254                         else if (newButton.isSelected())
    255                                 return tf.getText();
    256 
    257                 return null;
    258         }
    259 
    260         private String getPreSelectedKey(Map<String, String> keyValueMap) {
    261                 for (String[] pattern : TAG_EDIT_STRINGS) {
    262                         Pattern keyPattern = Pattern.compile(pattern[0]);
    263                         Pattern valuePattern = Pattern.compile(pattern[1]);
    264                         for (Object key : keyValueMap.keySet().toArray()) {
    265                                 Matcher keyMatcher = keyPattern.matcher(key.toString());
    266                                 if (keyMatcher.matches()) {
    267                                         Matcher valueMatcher = valuePattern.matcher(keyValueMap
    268                                                         .get(key));
    269                                         if (valueMatcher.matches()) {
    270                                                 return pattern[2];
    271                                         }
    272                                 }
    273                         }
    274                 }
    275                 return "";
    276         }
     40    // Strings for choosing which key of an object with given tags should be
     41    // edited
     42    // the order is referencing the preference of the keys
     43    // String[] -> {key, value, to-editing-key} key and value can contain regexp
     44    private final String[][] TAG_EDIT_STRINGS = new String[][] {
     45            { "opening_hours", ".*", "opening_hours" },
     46            { "collection_times", ".*", "collection_times" },
     47            { "collection_times:local", ".*", "collection_times:local" },
     48            { "lit", ".*", "lit" },
     49            { "amenity", "post_box", "collection_times" },
     50            { "amenity", ".*", "opening_hours" },
     51            { "shop", ".*", "opening_hours" }, { "highway", ".*", "lit" } };
     52
     53    /**
     54    * Will be invoked by JOSM to bootstrap the plugin
     55     *
     56    * @param info
     57    *            information about the plugin and its local installation
     58    */
     59    public OhePlugin(PluginInformation info) {
     60        super(info);
     61        Main.main.menu.toolsMenu.add(new OheMenuAction());
     62    }
     63
     64    class OheMenuAction extends JosmAction {
     65        public OheMenuAction() {
     66            super(
     67                    tr("Edit opening hours"),
     68                    "opening_hours.png",
     69                    tr("Edit time-tag of selected element in a graphical interface"),
     70                    Shortcut.registerShortcut("tools:opening_hourseditor", tr(
     71                            "Tool: {0}", tr("Edit opening hours")),
     72                            KeyEvent.VK_T, Shortcut.GROUP_MENU), false);
     73        }
     74
     75        @Override
     76        protected void updateEnabledState() {
     77            if (getCurrentDataSet() == null) {
     78                setEnabled(false);
     79            } else {
     80                updateEnabledState(getCurrentDataSet().getSelected());
     81            }
     82        }
     83
     84        @Override
     85        protected void updateEnabledState(
     86                Collection<? extends OsmPrimitive> selection) {
     87            setEnabled(selection != null && !selection.isEmpty());
     88        }
     89
     90        public void actionPerformed(ActionEvent evt) {
     91            // fetch active Layer
     92            OsmDataLayer osmlayer = Main.main.getEditLayer();
     93            if (osmlayer != null) {
     94                Collection<OsmPrimitive> selection = osmlayer.data
     95                        .getSelected();
     96                if (selection.size() == 1) { // one object selected
     97                    OsmPrimitive object = selection.iterator().next();
     98                    String[] keyValuePair = editTimeTags(object.getKeys());
     99                    if (keyValuePair != null) {
     100                        String key = keyValuePair[0].trim();
     101                        String newkey = keyValuePair[1].trim();
     102                        String value = keyValuePair[2].trim();
     103
     104                        if (value.equals("")) {
     105                            value = null; // delete the key
     106                        }
     107                        if (newkey.equals("")) {
     108                            newkey = key;
     109                            value = null; // delete the key instead
     110                        }
     111                        if (key.equals(newkey)
     112                                && tr("<different>").equals(value))
     113                            return;
     114                        if (key.equals(newkey) || value == null) {
     115                            Main.main.undoRedo.add(new ChangePropertyCommand(
     116                                    object, newkey, value));
     117                        } else {
     118                            Collection<Command> commands = new Vector<Command>();
     119                            commands.add(new ChangePropertyCommand(object, key,
     120                                    null));
     121                            commands.add(new ChangePropertyCommand(object,
     122                                    newkey, value));
     123                            Main.main.undoRedo.add(new SequenceCommand(
     124                                    tr("Change properties of 1 object"),
     125                                    commands));
     126                        }
     127                    }
     128                } else { // Not possible to edit 0, 2 or more objects
     129                    JOptionPane
     130                            .showMessageDialog(
     131                                    Main.parent,
     132                                    tr(
     133                                            "You have {0} Elements selected. But you can edit only one element!",
     134                                            selection.size()),
     135                                    "openingHoursEditor Warning",
     136                                    JOptionPane.ERROR_MESSAGE);
     137                }
     138            }
     139        }
     140    }
     141
     142    // opens up dialogs to change one of the key-value-pairs and returns the
     143    // changed pair
     144    private String[] editTimeTags(Map<String, String> keyValueMap) {
     145        String selectedKey = "";
     146
     147        if ((selectedKey = tagChooseDialog(keyValueMap)) == null)
     148            return null;
     149
     150        final String value = (keyValueMap.containsKey(selectedKey)) ? keyValueMap
     151                .get(selectedKey)
     152                : "";
     153        OheDialogPanel panel = new OheDialogPanel(this, selectedKey, value);
     154
     155        final JOptionPane optionPane = new JOptionPane(panel,
     156                JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
     157        final JDialog dlg = optionPane.createDialog(Main.parent, tr("Edit"));
     158
     159        dlg.setResizable(true);
     160        dlg.setVisible(true);
     161
     162        Object answer = optionPane.getValue();
     163        if (!(answer == null || answer == JOptionPane.UNINITIALIZED_VALUE || (answer instanceof Integer && (Integer) answer != JOptionPane.OK_OPTION)))
     164            return panel.getChangedKeyValuePair();
     165
     166        return null;
     167    }
     168
     169    // opens a dialog for choosing from a set of tags which can be edited
     170    // the chosen one is returned
     171    private String tagChooseDialog(Map<String, String> keyValueMap) {
     172        String preSelectedKey = getPreSelectedKey(keyValueMap);
     173        int preSelectedRow = -1;
     174
     175        String[][] rowData = new String[keyValueMap.size()][2];
     176        int cnt = 0;
     177        for (Object key : keyValueMap.keySet().toArray()) {
     178            rowData[cnt][0] = key.toString();
     179            rowData[cnt][1] = keyValueMap.get(key);
     180            if (key.toString().equals(preSelectedKey))
     181                preSelectedRow = cnt;
     182            cnt++;
     183        }
     184
     185        final JTable table = new JTable(rowData,
     186                new String[] { "key", "value" }) {
     187            public boolean isCellEditable(int rowIndex, int colIndex) {
     188                return false; // Disallow the editing of any cell
     189            }
     190        };
     191        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
     192        JScrollPane sp = new JScrollPane(
     193                JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
     194                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
     195        sp.setViewportView(table);
     196
     197        final JTextField tf = new JTextField();
     198
     199        ActionListener al = new ActionListener() {
     200            @Override
     201            public void actionPerformed(ActionEvent e) {
     202                if (e.getActionCommand().equals("edit")) {
     203                    table.setEnabled(true);
     204                    tf.setEnabled(false);
     205                } else if (e.getActionCommand().equals("new")) {
     206                    table.setEnabled(false);
     207                    tf.setEnabled(true);
     208                }
     209            }
     210        };
     211
     212        JRadioButton editButton = new JRadioButton("edit existing tag");
     213        editButton.setActionCommand("edit");
     214        editButton.addActionListener(al);
     215        JRadioButton newButton = new JRadioButton("edit new tag");
     216        newButton.setActionCommand("new");
     217        newButton.addActionListener(al);
     218        ButtonGroup group = new ButtonGroup();
     219        group.add(newButton);
     220        group.add(editButton);
     221
     222        if (preSelectedRow != -1) {
     223            table.setEnabled(true);
     224            tf.setEnabled(false);
     225            table.setRowSelectionInterval(preSelectedRow, preSelectedRow);
     226            editButton.setSelected(true);
     227        } else {
     228            table.setEnabled(false);
     229            tf.setEnabled(true);
     230            tf.setText(preSelectedKey);
     231            newButton.setSelected(true);
     232        }
     233
     234        JPanel dlgPanel = new JPanel(new GridBagLayout());
     235        dlgPanel.add(editButton, GBC.std().anchor(GBC.CENTER));
     236        dlgPanel.add(sp, GBC.eol().fill(GBC.BOTH));
     237        dlgPanel.add(newButton, GBC.std().anchor(GBC.CENTER));
     238        dlgPanel.add(tf, GBC.eol().fill(GBC.HORIZONTAL));
     239
     240        JOptionPane optionPane = new JOptionPane(dlgPanel,
     241                JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
     242        JDialog dlg = optionPane.createDialog(Main.parent, tr("Choose key"));
     243
     244        dlg.pack();
     245        dlg.setResizable(true);
     246        dlg.setVisible(true);
     247
     248        Object answer = optionPane.getValue();
     249        if (answer != null
     250                && answer != JOptionPane.UNINITIALIZED_VALUE
     251                && (answer instanceof Integer && (Integer) answer == JOptionPane.OK_OPTION))
     252            if (editButton.isSelected() && table.getSelectedRow() != -1)
     253                return rowData[table.getSelectedRow()][0];
     254            else if (newButton.isSelected())
     255                return tf.getText();
     256
     257        return null;
     258    }
     259
     260    private String getPreSelectedKey(Map<String, String> keyValueMap) {
     261        for (String[] pattern : TAG_EDIT_STRINGS) {
     262            Pattern keyPattern = Pattern.compile(pattern[0]);
     263            Pattern valuePattern = Pattern.compile(pattern[1]);
     264            for (Object key : keyValueMap.keySet().toArray()) {
     265                Matcher keyMatcher = keyPattern.matcher(key.toString());
     266                if (keyMatcher.matches()) {
     267                    Matcher valueMatcher = valuePattern.matcher(keyValueMap
     268                            .get(key));
     269                    if (valueMatcher.matches()) {
     270                        return pattern[2];
     271                    }
     272                }
     273            }
     274        }
     275        return "";
     276    }
    277277}
  • applications/editors/josm/plugins/OpeningHoursEditor/src/org/openstreetmap/josm/plugins/ohe/OpeningTimeUtils.java

    r22751 r23192  
    77
    88public class OpeningTimeUtils {
    9         // implements the subtraction of daytimes in spans of days when a day in
    10         // the list occurs direct afterwards
    11         public static ArrayList<int[]> convert(ArrayList<DateTime> dateTimes) {
    12                 ArrayList<int[]> ret = new ArrayList<int[]>(); // the list which is
    13                 // returned
    14                 for (int i = 0; i < dateTimes.size(); ++i) { // iterate over every entry
    15                         DateTime dateTime = dateTimes.get(i);
    16                         ArrayList<DateTime> newDateTimes = new ArrayList<DateTime>();
    17 
    18                         // test if the given entry is a single dayspan
    19                         if (dateTime.daySpans.size() == 1
    20                                         && dateTime.daySpans.get(0).isSpan()) {
    21                                 ArrayList<DaySpan> partDaySpans = new ArrayList<DaySpan>();
    22                                 int start_day = dateTime.daySpans.get(0).startDay;
    23 
    24                                 // look in every entry behind
    25                                 while (i + 1 < dateTimes.size()) {
    26                                         ArrayList<DaySpan> following = dateTimes.get(i + 1).daySpans;
    27                                         if (following.size() == 1
    28                                                         && following.get(0).startDay > dateTime.daySpans
    29                                                                         .get(0).startDay
    30                                                         && following.get(0).endDay < dateTime.daySpans
    31                                                                         .get(0).endDay) {
    32                                                 partDaySpans.add(new DaySpan(start_day, following
    33                                                                 .get(0).startDay - 1));
    34                                                 start_day = following.get(0).endDay + 1;
    35                                                 newDateTimes.add(dateTimes.get(i + 1));
    36                                                 i++;
    37                                         } else
    38                                                 break;
    39                                 }
    40 
    41                                 partDaySpans.add(new DaySpan(start_day, dateTime.daySpans
    42                                                 .get(0).endDay));
    43                                 newDateTimes.add(new DateTime(partDaySpans,
    44                                                 dateTime.daytimeSpans));
    45                         }
    46                         if (newDateTimes.isEmpty())
    47                                 newDateTimes.add(dateTime);
    48 
    49                         // create the int-array
    50                         for (int j = 0; j < newDateTimes.size(); ++j) {
    51                                 DateTime dateTime2 = newDateTimes.get(j);
    52                                 for (DaySpan dayspan : dateTime2.daySpans) {
    53                                         for (DaytimeSpan timespan : dateTime2.daytimeSpans) {
    54                                                 if (!timespan.isOff())
    55                                                         ret.add(new int[] { dayspan.startDay,
    56                                                                         dayspan.endDay, timespan.startMinute,
    57                                                                         timespan.endMinute });
    58                                         }
    59                                 }
    60                         }
    61                 }
    62                 return ret;
    63         }
    64 
    65         public static class DaySpan {
    66                 public int startDay;
    67                 public int endDay;
    68 
    69                 public DaySpan(int startDay, int endDay) {
    70                         this.startDay = startDay;
    71                         this.endDay = endDay;
    72                 }
    73 
    74                 public boolean isSpan() {
    75                         return endDay > startDay;
    76                 }
    77 
    78                 public boolean isSingleDay() {
    79                         return startDay == endDay;
    80                 }
    81         }
    82 
    83         public static class DaytimeSpan {
    84                 public int startMinute;
    85                 public int endMinute;
    86 
    87                 public DaytimeSpan(int startMinute, int endMinute) {
    88                         this.startMinute = startMinute;
    89                         this.endMinute = endMinute;
    90                 }
    91 
    92                 public boolean isOff() {
    93                         return startMinute == -1;
    94                 }
    95 
    96                 public boolean isSpan() {
    97                         return endMinute > startMinute;
    98                 }
    99         }
    100 
    101         public static class DateTime {
    102                 public ArrayList<DaySpan> daySpans;
    103                 public ArrayList<DaytimeSpan> daytimeSpans;
    104 
    105                 public DateTime(ArrayList<DaySpan> daySpans,
    106                                 ArrayList<DaytimeSpan> daytimeSpans) {
    107                         this.daySpans = daySpans;
    108                         this.daytimeSpans = daytimeSpans;
    109                 }
    110         }
    111 
    112         // returns a String (e.g "Mo-Sa 10:00-20:00; Tu off") representing the
    113         // TimeRects
    114         public static String makeStringFromRects(ArrayList<TimeRect> givenTimeRects) {
    115                 // create an array of booleans representing every minute on all the days
    116                 // in a week
    117                 boolean[][] minuteArray = new boolean[7][24 * 60 + 2];
    118                 for (int day = 0; day < 7; ++day)
    119                         for (int minute = 0; minute < 24 * 60 + 2; ++minute)
    120                                 minuteArray[day][minute] = false;
    121                 for (TimeRect timeRect : givenTimeRects)
    122                         for (int day = timeRect.getDayStart(); day <= timeRect.getDayEnd(); ++day)
    123                                 for (int minute = timeRect.getMinuteStart(); minute <= timeRect
    124                                                 .getMinuteEnd(); ++minute)
    125                                         minuteArray[day][minute] = true;
    126 
    127                 String ret = "";
    128                 int[] days = new int[7]; // an array representing the status of the days
    129                 // 0 means nothing done with this day yet
    130                 // 8 means the day is off
    131                 // 0<x<8 means the day have the openinghours of day x
    132                 // -8<x<0 means nothing done with this day yet, but it intersects a
    133                 // range of days with same opening_hours
    134                 for (int i = 0; i < 7; ++i) {
    135                         String add = "";
    136 
    137                         if (isArrayEmpty(minuteArray[i]) && days[i] == 0) {
    138                                 days[i] = 8;
    139                         } else if (isArrayEmpty(minuteArray[i]) && days[i] < 0) {
    140                                 add = OpeningTimeCompiler.WEEKDAYS[i] + " off";
    141                                 days[i] = -8;
    142                         } else if (days[i] <= 0) {
    143                                 days[i] = i + 1;
    144                                 int lastSameDay = i;
    145                                 int sameDayCount = 1;
    146                                 for (int j = i + 1; j < 7; ++j) {
    147                                         if (arraysEqual(minuteArray[i], minuteArray[j])) {
    148                                                 days[j] = i + 1;
    149                                                 lastSameDay = j;
    150                                                 sameDayCount++;
    151                                         }
    152                                 }
    153                                 if (sameDayCount == 1) {
    154                                         // a single Day with this special opening_hours
    155                                         add = OpeningTimeCompiler.WEEKDAYS[i] + " "
    156                                                         + makeStringFromMinuteArray(minuteArray[i]);
    157                                 } else if (sameDayCount == 2) {
    158                                         // exactly two Days with this special opening_hours
    159                                         add = OpeningTimeCompiler.WEEKDAYS[i] + ","
    160                                                         + OpeningTimeCompiler.WEEKDAYS[lastSameDay] + " "
    161                                                         + makeStringFromMinuteArray(minuteArray[i]);
    162                                 } else if (sameDayCount > 2) {
    163                                         // more than two Days with this special opening_hours
    164                                         add = OpeningTimeCompiler.WEEKDAYS[i] + "-"
    165                                                         + OpeningTimeCompiler.WEEKDAYS[lastSameDay] + " "
    166                                                         + makeStringFromMinuteArray(minuteArray[i]);
    167                                         for (int j = i + 1; j < lastSameDay; ++j) {
    168                                                 if (days[j] == 0)
    169                                                         days[j] = -i - 1;
    170                                         }
    171                                 }
    172                         }
    173 
    174                         if (!add.isEmpty()) {
    175                                 if (!ret.isEmpty())
    176                                         ret += "; ";
    177                                 ret += add;
    178                         }
    179                 }
    180                 return ret;
    181         }
    182 
    183         // returns a String representing the openinghours on one special day (e.g.
    184         // "10:00-20:00")
    185         private static String makeStringFromMinuteArray(boolean[] minutes) {
    186                 String ret = "";
    187                 for (int i = 0; i < minutes.length; ++i) {
    188                         if (minutes[i]) {
    189                                 int start = i;
    190                                 while (i < minutes.length && minutes[i])
    191                                         ++i;
    192                                 String addString = timeString(start);
    193                                 if (i - 1 == 24 * 60 + 1) // open end
    194                                         addString += "+";
    195                                 else if (start != i - 1) // closing time
    196                                         addString += "-" + timeString(i - 1);
    197                                 if (!ret.isEmpty())
    198                                         ret += ",";
    199                                 ret += addString;
    200                         }
    201                 }
    202                 return ret;
    203         }
    204 
    205         public static String timeString(int minutes) {
    206                 int h = minutes / 60;
    207                 int m = minutes % 60;
    208                 return (h < 10 ? "0" : "") + h + ":" + (m < 10 ? "0" : "") + m;
    209         }
    210 
    211         private static boolean isArrayEmpty(boolean[] bs) {
    212                 for (int i = 0; i < bs.length; i++)
    213                         if (bs[i])
    214                                 return false;
    215                 return true;
    216         }
    217 
    218         private static boolean arraysEqual(boolean[] bs, boolean[] bs2) {
    219                 boolean ret = true;
    220                 for (int i = 0; i < bs.length; i++)
    221                         ret &= bs[i] == bs2[i];
    222                 return ret;
    223         }
     9    // implements the subtraction of daytimes in spans of days when a day in
     10    // the list occurs direct afterwards
     11    public static ArrayList<int[]> convert(ArrayList<DateTime> dateTimes) {
     12        ArrayList<int[]> ret = new ArrayList<int[]>(); // the list which is
     13        // returned
     14        for (int i = 0; i < dateTimes.size(); ++i) { // iterate over every entry
     15            DateTime dateTime = dateTimes.get(i);
     16            ArrayList<DateTime> newDateTimes = new ArrayList<DateTime>();
     17
     18            // test if the given entry is a single dayspan
     19            if (dateTime.daySpans.size() == 1
     20                    && dateTime.daySpans.get(0).isSpan()) {
     21                ArrayList<DaySpan> partDaySpans = new ArrayList<DaySpan>();
     22                int start_day = dateTime.daySpans.get(0).startDay;
     23
     24                // look in every entry behind
     25                while (i + 1 < dateTimes.size()) {
     26                    ArrayList<DaySpan> following = dateTimes.get(i + 1).daySpans;
     27                    if (following.size() == 1
     28                            && following.get(0).startDay > dateTime.daySpans
     29                                    .get(0).startDay
     30                            && following.get(0).endDay < dateTime.daySpans
     31                                    .get(0).endDay) {
     32                        partDaySpans.add(new DaySpan(start_day, following
     33                                .get(0).startDay - 1));
     34                        start_day = following.get(0).endDay + 1;
     35                        newDateTimes.add(dateTimes.get(i + 1));
     36                        i++;
     37                    } else
     38                        break;
     39                }
     40
     41                partDaySpans.add(new DaySpan(start_day, dateTime.daySpans
     42                        .get(0).endDay));
     43                newDateTimes.add(new DateTime(partDaySpans,
     44                        dateTime.daytimeSpans));
     45            }
     46            if (newDateTimes.isEmpty())
     47                newDateTimes.add(dateTime);
     48
     49            // create the int-array
     50            for (int j = 0; j < newDateTimes.size(); ++j) {
     51                DateTime dateTime2 = newDateTimes.get(j);
     52                for (DaySpan dayspan : dateTime2.daySpans) {
     53                    for (DaytimeSpan timespan : dateTime2.daytimeSpans) {
     54                        if (!timespan.isOff())
     55                            ret.add(new int[] { dayspan.startDay,
     56                                    dayspan.endDay, timespan.startMinute,
     57                                    timespan.endMinute });
     58                    }
     59                }
     60            }
     61        }
     62        return ret;
     63    }
     64
     65    public static class DaySpan {
     66        public int startDay;
     67        public int endDay;
     68
     69        public DaySpan(int startDay, int endDay) {
     70            this.startDay = startDay;
     71            this.endDay = endDay;
     72        }
     73
     74        public boolean isSpan() {
     75            return endDay > startDay;
     76        }
     77
     78        public boolean isSingleDay() {
     79            return startDay == endDay;
     80        }
     81    }
     82
     83    public static class DaytimeSpan {
     84        public int startMinute;
     85        public int endMinute;
     86
     87        public DaytimeSpan(int startMinute, int endMinute) {
     88            this.startMinute = startMinute;
     89            this.endMinute = endMinute;
     90        }
     91
     92        public boolean isOff() {
     93            return startMinute == -1;
     94        }
     95
     96        public boolean isSpan() {
     97            return endMinute > startMinute;
     98        }
     99    }
     100
     101    public static class DateTime {
     102        public ArrayList<DaySpan> daySpans;
     103        public ArrayList<DaytimeSpan> daytimeSpans;
     104
     105        public DateTime(ArrayList<DaySpan> daySpans,
     106                ArrayList<DaytimeSpan> daytimeSpans) {
     107            this.daySpans = daySpans;
     108            this.daytimeSpans = daytimeSpans;
     109        }
     110    }
     111
     112    // returns a String (e.g "Mo-Sa 10:00-20:00; Tu off") representing the
     113    // TimeRects
     114    public static String makeStringFromRects(ArrayList<TimeRect> givenTimeRects) {
     115        // create an array of booleans representing every minute on all the days
     116        // in a week
     117        boolean[][] minuteArray = new boolean[7][24 * 60 + 2];
     118        for (int day = 0; day < 7; ++day)
     119            for (int minute = 0; minute < 24 * 60 + 2; ++minute)
     120                minuteArray[day][minute] = false;
     121        for (TimeRect timeRect : givenTimeRects)
     122            for (int day = timeRect.getDayStart(); day <= timeRect.getDayEnd(); ++day)
     123                for (int minute = timeRect.getMinuteStart(); minute <= timeRect
     124                        .getMinuteEnd(); ++minute)
     125                    minuteArray[day][minute] = true;
     126
     127        String ret = "";
     128        int[] days = new int[7]; // an array representing the status of the days
     129        // 0 means nothing done with this day yet
     130        // 8 means the day is off
     131        // 0<x<8 means the day have the openinghours of day x
     132        // -8<x<0 means nothing done with this day yet, but it intersects a
     133        // range of days with same opening_hours
     134        for (int i = 0; i < 7; ++i) {
     135            String add = "";
     136
     137            if (isArrayEmpty(minuteArray[i]) && days[i] == 0) {
     138                days[i] = 8;
     139            } else if (isArrayEmpty(minuteArray[i]) && days[i] < 0) {
     140                add = OpeningTimeCompiler.WEEKDAYS[i] + " off";
     141                days[i] = -8;
     142            } else if (days[i] <= 0) {
     143                days[i] = i + 1;
     144                int lastSameDay = i;
     145                int sameDayCount = 1;
     146                for (int j = i + 1; j < 7; ++j) {
     147                    if (arraysEqual(minuteArray[i], minuteArray[j])) {
     148                        days[j] = i + 1;
     149                        lastSameDay = j;
     150                        sameDayCount++;
     151                    }
     152                }
     153                if (sameDayCount == 1) {
     154                    // a single Day with this special opening_hours
     155                    add = OpeningTimeCompiler.WEEKDAYS[i] + " "
     156                            + makeStringFromMinuteArray(minuteArray[i]);
     157                } else if (sameDayCount == 2) {
     158                    // exactly two Days with this special opening_hours
     159                    add = OpeningTimeCompiler.WEEKDAYS[i] + ","
     160                            + OpeningTimeCompiler.WEEKDAYS[lastSameDay] + " "
     161                            + makeStringFromMinuteArray(minuteArray[i]);
     162                } else if (sameDayCount > 2) {
     163                    // more than two Days with this special opening_hours
     164                    add = OpeningTimeCompiler.WEEKDAYS[i] + "-"
     165                            + OpeningTimeCompiler.WEEKDAYS[lastSameDay] + " "
     166                            + makeStringFromMinuteArray(minuteArray[i]);
     167                    for (int j = i + 1; j < lastSameDay; ++j) {
     168                        if (days[j] == 0)
     169                            days[j] = -i - 1;
     170                    }
     171                }
     172            }
     173
     174            if (!add.isEmpty()) {
     175                if (!ret.isEmpty())
     176                    ret += "; ";
     177                ret += add;
     178            }
     179        }
     180        return ret;
     181    }
     182
     183    // returns a String representing the openinghours on one special day (e.g.
     184    // "10:00-20:00")
     185    private static String makeStringFromMinuteArray(boolean[] minutes) {
     186        String ret = "";
     187        for (int i = 0; i < minutes.length; ++i) {
     188            if (minutes[i]) {
     189                int start = i;
     190                while (i < minutes.length && minutes[i])
     191                    ++i;
     192                String addString = timeString(start);
     193                if (i - 1 == 24 * 60 + 1) // open end
     194                    addString += "+";
     195                else if (start != i - 1) // closing time
     196                    addString += "-" + timeString(i - 1);
     197                if (!ret.isEmpty())
     198                    ret += ",";
     199                ret += addString;
     200            }
     201        }
     202        return ret;
     203    }
     204
     205    public static String timeString(int minutes) {
     206        int h = minutes / 60;
     207        int m = minutes % 60;
     208        return (h < 10 ? "0" : "") + h + ":" + (m < 10 ? "0" : "") + m;
     209    }
     210
     211    private static boolean isArrayEmpty(boolean[] bs) {
     212        for (int i = 0; i < bs.length; i++)
     213            if (bs[i])
     214                return false;
     215        return true;
     216    }
     217
     218    private static boolean arraysEqual(boolean[] bs, boolean[] bs2) {
     219        boolean ret = true;
     220        for (int i = 0; i < bs.length; i++)
     221            ret &= bs[i] == bs2[i];
     222        return ret;
     223    }
    224224}
  • applications/editors/josm/plugins/OpeningHoursEditor/src/org/openstreetmap/josm/plugins/ohe/gui/OheDialogPanel.java

    r22751 r23192  
    2626public class OheDialogPanel extends JPanel {
    2727
    28         private final JTextField keyField;
     28    private final JTextField keyField;
    2929
    30         // The Component for showing the Time as a Text
    31         private final JTextField valueField;
     30    // The Component for showing the Time as a Text
     31    private final JTextField valueField;
    3232
    33         private final JButton twentyfourSevenButton;
    34         private final JLabel actualPostionLabel;
     33    private final JButton twentyfourSevenButton;
     34    private final JLabel actualPostionLabel;
    3535
    36         // The important Panel for showing/editing the Time graphical
    37         private final OheEditor editorPanel;
     36    // The important Panel for showing/editing the Time graphical
     37    private final OheEditor editorPanel;
    3838
    39         private final String oldkey;
     39    private final String oldkey;
    4040
    41         public OheDialogPanel(OhePlugin plugin, String key, String value) {
    42                 oldkey = key;
    43                 keyField = new JTextField(key);
     41    public OheDialogPanel(OhePlugin plugin, String key, String value) {
     42        oldkey = key;
     43        keyField = new JTextField(key);
    4444
    45                 valueField = new JTextField(value);
    46                 valueField.addActionListener(new ActionListener() {
    47                         @Override
    48                         public void actionPerformed(ActionEvent evt) {
    49                                 // on every action in the textfield the timeRects are reloaded
    50                                 editorPanel.initTimeRects();
    51                         }
    52                 });
     45        valueField = new JTextField(value);
     46        valueField.addActionListener(new ActionListener() {
     47            @Override
     48            public void actionPerformed(ActionEvent evt) {
     49                // on every action in the textfield the timeRects are reloaded
     50                editorPanel.initTimeRects();
     51            }
     52        });
    5353
    54                 twentyfourSevenButton = new JButton(tr("apply {0}", "24/7"));
    55                 twentyfourSevenButton.addActionListener(new ActionListener() {
    56                         @Override
    57                         public void actionPerformed(ActionEvent arg0) {
    58                                 valueField.setText("24/7");
    59                                 editorPanel.initTimeRects();
    60                         }
    61                 });
     54        twentyfourSevenButton = new JButton(tr("apply {0}", "24/7"));
     55        twentyfourSevenButton.addActionListener(new ActionListener() {
     56            @Override
     57            public void actionPerformed(ActionEvent arg0) {
     58                valueField.setText("24/7");
     59                editorPanel.initTimeRects();
     60            }
     61        });
    6262
    63                 actualPostionLabel = new JLabel("Mo 00:00");
    64                 JPanel toolsPanel = new JPanel(new GridBagLayout());
    65                 toolsPanel.add(twentyfourSevenButton, GBC.std());
    66                 toolsPanel.add(Box.createGlue(), GBC.std().fill(GBC.HORIZONTAL));
    67                 toolsPanel.add(actualPostionLabel, GBC.eop());
     63        actualPostionLabel = new JLabel("Mo 00:00");
     64        JPanel toolsPanel = new JPanel(new GridBagLayout());
     65        toolsPanel.add(twentyfourSevenButton, GBC.std());
     66        toolsPanel.add(Box.createGlue(), GBC.std().fill(GBC.HORIZONTAL));
     67        toolsPanel.add(actualPostionLabel, GBC.eop());
    6868
    69                 editorPanel = new OheEditor(this);
     69        editorPanel = new OheEditor(this);
    7070
    71                 // adding all Components in a Gridbaglayout
    72                 setLayout(new GridBagLayout());
    73                 add(new JLabel(tr("Key")), GBC.std());
    74                 add(Box.createHorizontalStrut(10), GBC.std());
    75                 add(keyField, GBC.eol().fill(GBC.HORIZONTAL));
    76                 add(new JLabel(tr("Value")), GBC.std());
    77                 add(Box.createHorizontalStrut(10), GBC.std());
    78                 add(valueField, GBC.eop().fill(GBC.HORIZONTAL));
    79                 add(toolsPanel, GBC.eol().fill(GBC.HORIZONTAL));
    80                 add(editorPanel, GBC.eol().fill());
     71        // adding all Components in a Gridbaglayout
     72        setLayout(new GridBagLayout());
     73        add(new JLabel(tr("Key")), GBC.std());
     74        add(Box.createHorizontalStrut(10), GBC.std());
     75        add(keyField, GBC.eol().fill(GBC.HORIZONTAL));
     76        add(new JLabel(tr("Value")), GBC.std());
     77        add(Box.createHorizontalStrut(10), GBC.std());
     78        add(valueField, GBC.eop().fill(GBC.HORIZONTAL));
     79        add(toolsPanel, GBC.eol().fill(GBC.HORIZONTAL));
     80        add(editorPanel, GBC.eol().fill());
    8181
    82                 valueField.requestFocus();
    83                 setPreferredSize(new Dimension(480, 520));
    84         }
     82        valueField.requestFocus();
     83        setPreferredSize(new Dimension(480, 520));
     84    }
    8585
    86         public String[] getChangedKeyValuePair() {
    87                 return new String[] { oldkey, keyField.getText(), valueField.getText() };
    88         }
     86    public String[] getChangedKeyValuePair() {
     87        return new String[] { oldkey, keyField.getText(), valueField.getText() };
     88    }
    8989
    90         // returns the compiled Time from the valueField
    91         public ArrayList<int[]> getTime() throws Exception {
    92                 String value = valueField.getText();
    93                 ArrayList<int[]> time = null;
    94                 if (value.length() > 0) {
    95                         OpeningTimeCompiler compiler = new OpeningTimeCompiler(value);
    96                         try {
    97                                 time = OpeningTimeUtils.convert(compiler.startCompile());
    98                         } catch (Throwable t) {
    99                                 int tColumns[] = null;
    100                                 String info = null;
     90    // returns the compiled Time from the valueField
     91    public ArrayList<int[]> getTime() throws Exception {
     92        String value = valueField.getText();
     93        ArrayList<int[]> time = null;
     94        if (value.length() > 0) {
     95            OpeningTimeCompiler compiler = new OpeningTimeCompiler(value);
     96            try {
     97                time = OpeningTimeUtils.convert(compiler.startCompile());
     98            } catch (Throwable t) {
     99                int tColumns[] = null;
     100                String info = null;
    101101
    102                                 if (t instanceof ParseException) {
    103                                         ParseException parserExc = (ParseException) t;
    104                                         tColumns = new int[] {
    105                                                         parserExc.currentToken.beginColumn - 1,
    106                                                         parserExc.currentToken.endColumn + 1 };
    107                                 } else if (t instanceof SyntaxException) {
    108                                         SyntaxException syntaxError = (SyntaxException) t;
    109                                         tColumns = new int[] { syntaxError.getStartColumn(),
    110                                                         syntaxError.getEndColumn() };
    111                                         info = syntaxError.getInfo();
    112                                 } else if (t instanceof TokenMgrError) {
    113                                         TokenMgrError tokenMgrError = (TokenMgrError) t;
    114                                         tColumns = new int[] { tokenMgrError.errorColumn - 1,
    115                                                         tokenMgrError.errorColumn + 1 };
    116                                 } else {
    117                                         t.printStackTrace();
    118                                 }
     102                if (t instanceof ParseException) {
     103                    ParseException parserExc = (ParseException) t;
     104                    tColumns = new int[] {
     105                            parserExc.currentToken.beginColumn - 1,
     106                            parserExc.currentToken.endColumn + 1 };
     107                } else if (t instanceof SyntaxException) {
     108                    SyntaxException syntaxError = (SyntaxException) t;
     109                    tColumns = new int[] { syntaxError.getStartColumn(),
     110                            syntaxError.getEndColumn() };
     111                    info = syntaxError.getInfo();
     112                } else if (t instanceof TokenMgrError) {
     113                    TokenMgrError tokenMgrError = (TokenMgrError) t;
     114                    tColumns = new int[] { tokenMgrError.errorColumn - 1,
     115                            tokenMgrError.errorColumn + 1 };
     116                } else {
     117                    t.printStackTrace();
     118                }
    119119
    120                                 // shows a Information Dialog, where the Error occurred
    121                                 if (tColumns != null) {
    122                                         int first = Math.max(0, tColumns[0]);
    123                                         int last = Math.min(value.length(), tColumns[1]);
    124                                         String begin = value.substring(0, first);
    125                                         String middle = value.substring(first, last);
    126                                         String end = value.substring(last);
    127                                         String message = "<html>"
    128                                                         + tr("There is something wrong in the value near:")
    129                                                         + "<br>" + begin
    130                                                         + "<span style='background-color:red;'>" + middle
    131                                                         + "</span>" + end;
    132                                         if (info != null)
    133                                                 message += "<br>" + tr("Info: {0}", tr(info));
    134                                         message += "<br>"
    135                                                         + tr("Correct the value manually and than press Enter.");
    136                                         message += "</html>";
    137                                         JOptionPane.showMessageDialog(this, message,
    138                                                         tr("Error in timeformat"),
    139                                                         JOptionPane.INFORMATION_MESSAGE);
    140                                 }
     120                // shows a Information Dialog, where the Error occurred
     121                if (tColumns != null) {
     122                    int first = Math.max(0, tColumns[0]);
     123                    int last = Math.min(value.length(), tColumns[1]);
     124                    String begin = value.substring(0, first);
     125                    String middle = value.substring(first, last);
     126                    String end = value.substring(last);
     127                    String message = "<html>"
     128                            + tr("There is something wrong in the value near:")
     129                            + "<br>" + begin
     130                            + "<span style='background-color:red;'>" + middle
     131                            + "</span>" + end;
     132                    if (info != null)
     133                        message += "<br>" + tr("Info: {0}", tr(info));
     134                    message += "<br>"
     135                            + tr("Correct the value manually and than press Enter.");
     136                    message += "</html>";
     137                    JOptionPane.showMessageDialog(this, message,
     138                            tr("Error in timeformat"),
     139                            JOptionPane.INFORMATION_MESSAGE);
     140                }
    141141
    142                                 throw new Exception("Error in the TimeValue");
    143                         }
    144                 }
     142                throw new Exception("Error in the TimeValue");
     143            }
     144        }
    145145
    146                 return time;
    147         }
     146        return time;
     147    }
    148148
    149         // updates the valueField with the given timeRects
    150         public void updateValueField(ArrayList<TimeRect> timeRects) {
    151                 if (valueField != null && timeRects != null)
    152                         valueField.setText(OpeningTimeUtils.makeStringFromRects(timeRects));
    153         }
     149    // updates the valueField with the given timeRects
     150    public void updateValueField(ArrayList<TimeRect> timeRects) {
     151        if (valueField != null && timeRects != null)
     152            valueField.setText(OpeningTimeUtils.makeStringFromRects(timeRects));
     153    }
    154154
    155         public void setMousePositionText(String positionText) {
    156                 actualPostionLabel.setText(positionText);
    157         }
     155    public void setMousePositionText(String positionText) {
     156        actualPostionLabel.setText(positionText);
     157    }
    158158}
  • applications/editors/josm/plugins/OpeningHoursEditor/src/org/openstreetmap/josm/plugins/ohe/gui/OheEditor.java

    r22751 r23192  
    2020
    2121public class OheEditor extends JPanel implements MouseListener,
    22                 MouseMotionListener {
    23         final OheDialogPanel dialog;
    24 
    25         final private JScrollPane scrollPane;
    26         final JPanel contentPanel;
    27 
    28         ArrayList<TimeRect> timeRects;
    29 
    30         final private int dayAxisHeight = 20;
    31         final private int timeAxisWidth = 45;
    32 
    33         public OheEditor(OheDialogPanel oheDialogPanel) {
    34                 dialog = oheDialogPanel;
    35 
    36                 // the MainPanel for showing the TimeRects
    37                 contentPanel = new JPanel() {
    38                         @Override
    39                         public void setSize(Dimension d) {
    40                                 super.setSize(d);
    41                                 repositionTimeRects();
    42                         }
    43 
    44                         @Override
    45                         public void paintComponent(Graphics g) {
    46                                 if (OheEditor.this.isEnabled()) {
    47                                         g.setColor(Color.WHITE);
    48                                         g.fillRect(0, 0, getWidth(), getHeight());
    49 
    50                                         // horizontal Lines
    51                                         for (int i = 1; i < 24; ++i) {
    52                                                 if (i % 3 == 0)
    53                                                         g.setColor(Color.BLACK);
    54                                                 else
    55                                                         g.setColor(Color.LIGHT_GRAY);
    56 
    57                                                 g.drawLine(0, getMinutePosition(i * 60), getWidth(),
    58                                                                 getMinutePosition(i * 60));
    59                                         }
    60 
    61                                         // vertical Lines
    62                                         g.setColor(Color.BLACK);
    63                                         for (int i = 1; i < 7; ++i)
    64                                                 g.drawLine(getDayPosition(i), 0, getDayPosition(i),
    65                                                                 getHeight());
    66 
    67                                         // if a new Rect is dragged draw it
    68                                         if (day0 >= 0) {
    69                                                 Graphics2D g2D = (Graphics2D) g;
    70 
    71                                                 int day2 = Math.min(day0, day1);
    72                                                 int day3 = Math.max(day0, day1);
    73                                                 int minute2 = Math.min(minute0, minute1);
    74                                                 int minute3 = Math.max(minute0, minute1);
    75                                                 Rectangle bounds = getPanelBoundsForTimeinterval(day2,
    76                                                                 day3 + 1, minute2, minute3);
    77 
    78                                                 TimeRect.drawTimeRect(g2D, bounds, minute2 == minute3, false);
    79                                         }
    80                                 } else {
    81                                         g.setColor(Color.LIGHT_GRAY);
    82                                         g.fillRect(0, 0, getWidth(), getHeight());
    83                                 }
    84                         }
    85                 };
    86                 contentPanel.addMouseListener(this);
    87                 contentPanel.addMouseMotionListener(this);
    88                 contentPanel.setLayout(null);
    89                 contentPanel.setPreferredSize(new Dimension(180, 384));
    90 
    91                 initTimeRects();
    92 
    93                 scrollPane = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
    94                                 JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    95                 scrollPane.setViewportView(contentPanel);
    96 
    97                 // the upper Panel for showing Weekdays
    98                 scrollPane.setColumnHeaderView(new JPanel() {
    99                         @Override
    100                         public Dimension getPreferredSize() {
    101                                 return new Dimension(contentPanel.getWidth(), dayAxisHeight);
    102                         }
    103 
    104                         @Override
    105                         public void paintComponent(Graphics g) {
    106                                 g.setColor(Color.WHITE);
    107                                 g.fillRect(0, 0, getWidth(), getHeight());
    108 
    109                                 g.setColor(Color.BLACK);
    110                                 for (int i = 0; i < 7; ++i) {
    111                                         if (i > 0)
    112                                                 g.drawLine(getDayPosition(i) + 1, 0,
    113                                                                 getDayPosition(i) + 1, getHeight());
    114 
    115                                         String text = OpeningTimeCompiler.WEEKDAYS[i];
    116                                         g.drawString(text, (int) (getDayPosition(i + 0.5) - g
    117                                                         .getFontMetrics().stringWidth(text) * 0.5),
    118                                                         (int) (dayAxisHeight * 0.5 + g.getFontMetrics()
    119                                                                         .getHeight() * 0.35));
    120                                 }
    121                         }
    122                 });
    123 
    124                 // the left Panel for showing the hours
    125                 scrollPane.setRowHeaderView(new JPanel() {
    126                         @Override
    127                         public Dimension getPreferredSize() {
    128                                 return new Dimension(timeAxisWidth, contentPanel.getHeight());
    129                         }
    130 
    131                         @Override
    132                         public void paintComponent(Graphics g) {
    133                                 g.setColor(Color.WHITE);
    134                                 g.fillRect(0, 0, getWidth(), getHeight());
    135 
    136                                 for (int i = 1; i < 24; ++i) {
    137                                         if (i % 3 == 0) {
    138                                                 g.setColor(Color.BLACK);
    139                                                 String text = ((i < 10) ? "0" + i : i) + ":00";
    140                                                 g
    141                                                                 .drawString(text, timeAxisWidth - 10
    142                                                                                 - g.getFontMetrics().stringWidth(text),
    143                                                                                 getMinutePosition(i * 60)
    144                                                                                                 + (int) (g.getFontMetrics()
    145                                                                                                                 .getHeight() * 0.35));
    146                                         } else
    147                                                 g.setColor(Color.LIGHT_GRAY);
    148 
    149                                         g.drawLine(getWidth() - 4, getMinutePosition(i * 60) + 1,
    150                                                         getWidth(), getMinutePosition(i * 60) + 1);
    151                                 }
    152                         }
    153                 });
    154 
    155                 setLayout(new BorderLayout());
    156                 add(scrollPane, BorderLayout.CENTER);
    157         }
    158 
    159         // update all the TimeRects with new Data
    160         public void initTimeRects() {
    161                 contentPanel.removeAll();
    162 
    163                 ArrayList<int[]> time;
    164                 try {
    165                         time = dialog.getTime();
    166                 } catch (Exception exc) {
    167                         setEnabled(false);
    168                         return;
    169                 }
    170 
    171                 setEnabled(true);
    172                 timeRects = new ArrayList<TimeRect>();
    173                 if (time != null) {
    174                         for (int[] timeRectValues : time) {
    175                                 int day0 = timeRectValues[0];
    176                                 int day1 = timeRectValues[1];
    177                                 int minute0 = timeRectValues[2];
    178                                 int minute1 = timeRectValues[3];
    179                                 TimeRect timeRect = new TimeRect(OheEditor.this, day0, day1,
    180                                                 minute0, minute1);
    181                                 timeRects.add(timeRect);
    182                                 contentPanel.add(timeRect);
    183                         }
    184                 }
    185 
    186                 repositionTimeRects();
    187                 repaint();
    188         }
    189 
    190         protected void repositionTimeRects() {
    191                 if (timeRects != null)
    192                         for (TimeRect timeRect : timeRects)
    193                                 timeRect.reposition();
    194         }
    195 
    196         // returns the physical Borders of the TimeRect on the mainPanel
    197         public Rectangle getPanelBoundsForTimeinterval(int dayStart, int dayEnd,
    198                         int minutesStart, int minutesEnd) {
    199                 int x = getDayPosition(dayStart);
    200                 int y = getMinutePosition(minutesStart);
    201                 int width = getDayPosition(dayEnd) - getDayPosition(dayStart);
    202                 int height = getMinutePosition(minutesEnd)
    203                                 - getMinutePosition(minutesStart);
    204 
    205                 // work around openjdk bug
    206                 if (Main.isOpenjdk) {
    207                         x++;
    208                         y++;
    209                 }
    210 
    211                 if (minutesStart == minutesEnd)
    212                         return new Rectangle(x, y - 2 - TimeRect.verticalNonDrawedPixels,
    213                                         width, height + 5 + 2 * TimeRect.verticalNonDrawedPixels);
    214 
    215                 return new Rectangle(x, y, width, height + 1);
    216         }
    217 
    218         public double getDayWidth() {
    219                 return (contentPanel.getWidth() - 1) / 7.0;
    220         }
    221 
    222         public int getDayPosition(double d) {
    223                 return (int) (d * getDayWidth());
    224         }
    225 
    226         public double getMinuteHeight() {
    227                 return (contentPanel.getHeight() - 1) / (24.0 * 60);
    228         }
    229 
    230         public int getMinutePosition(int minute) {
    231                 return (int) (minute * getMinuteHeight());
    232         }
    233 
    234         // removes the given timerect from the panel and from the arraylist
    235         public void removeTimeRect(TimeRect timeRectToRemove) {
    236                 timeRects.remove(timeRectToRemove);
    237                 contentPanel.remove(timeRectToRemove);
    238                 dialog.updateValueField(timeRects);
    239                 repaint();
    240         }
    241 
    242         // drawing a new Rect
    243         private int day0 = -1;
    244         private int minute0;
    245         private int day1;
    246         private int minute1;
    247         private int xDragStart;
    248         private int yDragStart;
    249 
    250         @Override
    251         public void mouseClicked(MouseEvent evt) {
    252         }
    253 
    254         @Override
    255         public void mouseEntered(MouseEvent evt) {
    256         }
    257 
    258         @Override
    259         public void mouseExited(MouseEvent evt) {
    260         }
    261 
    262         @Override
    263         public void mousePressed(MouseEvent evt) {
    264                 day0 = (int) Math.floor(evt.getX() / getDayWidth());
    265                 minute0 = (int) Math.floor(evt.getY()
    266                                 / (getMinuteHeight() * TimeRect.minuteResterize))
    267                                 * TimeRect.minuteResterize;
    268                 day1 = day0;
    269                 minute1 = minute0;
    270                 xDragStart = evt.getX();
    271                 yDragStart = evt.getY();
    272         }
    273 
    274         @Override
    275         public void mouseReleased(MouseEvent evt) {
    276                 // mouse must be moved 5px before creating a rect
    277                 if (xDragStart == -1
    278                                 || Math.abs(evt.getX() - xDragStart)
    279                                                 + Math.abs(evt.getY() - yDragStart) > 5) {
    280                         int day2 = Math.min(day0, day1);
    281                         int day3 = Math.max(day0, day1);
    282                         int minute2 = Math.min(minute0, minute1);
    283                         int minute3 = Math.max(minute0, minute1);
    284 
    285                         TimeRect timeRect = new TimeRect(OheEditor.this, day2, day3,
    286                                         minute2, minute3);
    287                         timeRects.add(timeRect);
    288                         contentPanel.add(timeRect);
    289                         timeRect.reposition();
    290                         dialog.updateValueField(timeRects);
    291 
    292                         day0 = -1;
    293                         repaint();
    294                 }
    295         }
    296 
    297         @Override
    298         public void mouseDragged(MouseEvent evt) {
    299                 // mouse must be moved 5px before drawing a rect
    300                 if (xDragStart == -1
    301                                 || Math.abs(evt.getX() - xDragStart)
    302                                                 + Math.abs(evt.getY() - yDragStart) > 5) {
    303                         xDragStart = -1;
    304                         day1 = (int) Math.floor(evt.getX() / getDayWidth());
    305                         minute1 = (int) Math.floor(evt.getY()
    306                                         / (getMinuteHeight() * TimeRect.minuteResterize))
    307                                         * TimeRect.minuteResterize;
    308                         repaint();
    309                 }
    310         }
    311 
    312         @Override
    313         public void mouseMoved(MouseEvent evt) {
    314                 mousePositionChanged(evt.getX(), evt.getY());
    315         }
    316 
    317         public void mousePositionChanged(int x, int y) {
    318                 int actualDay = (int) Math.floor(x / getDayWidth());
    319                 int minutes = (int) Math.floor(y
    320                                 / (getMinuteHeight() * TimeRect.minuteResterize))
    321                                 * TimeRect.minuteResterize;
    322                 actualDay = Math.max(0, Math.min(6, actualDay));
    323                 minutes = Math.max(0, Math.min(24 * 60, minutes));
    324                 dialog.setMousePositionText(OpeningTimeCompiler.WEEKDAYS[actualDay]
    325                                 + " " + OpeningTimeUtils.timeString(minutes));
    326         }
     22        MouseMotionListener {
     23    final OheDialogPanel dialog;
     24
     25    final private JScrollPane scrollPane;
     26    final JPanel contentPanel;
     27
     28    ArrayList<TimeRect> timeRects;
     29
     30    final private int dayAxisHeight = 20;
     31    final private int timeAxisWidth = 45;
     32
     33    public OheEditor(OheDialogPanel oheDialogPanel) {
     34        dialog = oheDialogPanel;
     35
     36        // the MainPanel for showing the TimeRects
     37        contentPanel = new JPanel() {
     38            @Override
     39            public void setSize(Dimension d) {
     40                super.setSize(d);
     41                repositionTimeRects();
     42            }
     43
     44            @Override
     45            public void paintComponent(Graphics g) {
     46                if (OheEditor.this.isEnabled()) {
     47                    g.setColor(Color.WHITE);
     48                    g.fillRect(0, 0, getWidth(), getHeight());
     49
     50                    // horizontal Lines
     51                    for (int i = 1; i < 24; ++i) {
     52                        if (i % 3 == 0)
     53                            g.setColor(Color.BLACK);
     54                        else
     55                            g.setColor(Color.LIGHT_GRAY);
     56
     57                        g.drawLine(0, getMinutePosition(i * 60), getWidth(),
     58                                getMinutePosition(i * 60));
     59                    }
     60
     61                    // vertical Lines
     62                    g.setColor(Color.BLACK);
     63                    for (int i = 1; i < 7; ++i)
     64                        g.drawLine(getDayPosition(i), 0, getDayPosition(i),
     65                                getHeight());
     66
     67                    // if a new Rect is dragged draw it
     68                    if (day0 >= 0) {
     69                        Graphics2D g2D = (Graphics2D) g;
     70
     71                        int day2 = Math.min(day0, day1);
     72                        int day3 = Math.max(day0, day1);
     73                        int minute2 = Math.min(minute0, minute1);
     74                        int minute3 = Math.max(minute0, minute1);
     75                        Rectangle bounds = getPanelBoundsForTimeinterval(day2,
     76                                day3 + 1, minute2, minute3);
     77
     78                        TimeRect.drawTimeRect(g2D, bounds, minute2 == minute3, false);
     79                    }
     80                } else {
     81                    g.setColor(Color.LIGHT_GRAY);
     82                    g.fillRect(0, 0, getWidth(), getHeight());
     83                }
     84            }
     85        };
     86        contentPanel.addMouseListener(this);
     87        contentPanel.addMouseMotionListener(this);
     88        contentPanel.setLayout(null);
     89        contentPanel.setPreferredSize(new Dimension(180, 384));
     90
     91        initTimeRects();
     92
     93        scrollPane = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
     94                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
     95        scrollPane.setViewportView(contentPanel);
     96
     97        // the upper Panel for showing Weekdays
     98        scrollPane.setColumnHeaderView(new JPanel() {
     99            @Override
     100            public Dimension getPreferredSize() {
     101                return new Dimension(contentPanel.getWidth(), dayAxisHeight);
     102            }
     103
     104            @Override
     105            public void paintComponent(Graphics g) {
     106                g.setColor(Color.WHITE);
     107                g.fillRect(0, 0, getWidth(), getHeight());
     108
     109                g.setColor(Color.BLACK);
     110                for (int i = 0; i < 7; ++i) {
     111                    if (i > 0)
     112                        g.drawLine(getDayPosition(i) + 1, 0,
     113                                getDayPosition(i) + 1, getHeight());
     114
     115                    String text = OpeningTimeCompiler.WEEKDAYS[i];
     116                    g.drawString(text, (int) (getDayPosition(i + 0.5) - g
     117                            .getFontMetrics().stringWidth(text) * 0.5),
     118                            (int) (dayAxisHeight * 0.5 + g.getFontMetrics()
     119                                    .getHeight() * 0.35));
     120                }
     121            }
     122        });
     123
     124        // the left Panel for showing the hours
     125        scrollPane.setRowHeaderView(new JPanel() {
     126            @Override
     127            public Dimension getPreferredSize() {
     128                return new Dimension(timeAxisWidth, contentPanel.getHeight());
     129            }
     130
     131            @Override
     132            public void paintComponent(Graphics g) {
     133                g.setColor(Color.WHITE);
     134                g.fillRect(0, 0, getWidth(), getHeight());
     135
     136                for (int i = 1; i < 24; ++i) {
     137                    if (i % 3 == 0) {
     138                        g.setColor(Color.BLACK);
     139                        String text = ((i < 10) ? "0" + i : i) + ":00";
     140                        g
     141                                .drawString(text, timeAxisWidth - 10
     142                                        - g.getFontMetrics().stringWidth(text),
     143                                        getMinutePosition(i * 60)
     144                                                + (int) (g.getFontMetrics()
     145                                                        .getHeight() * 0.35));
     146                    } else
     147                        g.setColor(Color.LIGHT_GRAY);
     148
     149                    g.drawLine(getWidth() - 4, getMinutePosition(i * 60) + 1,
     150                            getWidth(), getMinutePosition(i * 60) + 1);
     151                }
     152            }
     153        });
     154
     155        setLayout(new BorderLayout());
     156        add(scrollPane, BorderLayout.CENTER);
     157    }
     158
     159    // update all the TimeRects with new Data
     160    public void initTimeRects() {
     161        contentPanel.removeAll();
     162
     163        ArrayList<int[]> time;
     164        try {
     165            time = dialog.getTime();
     166        } catch (Exception exc) {
     167            setEnabled(false);
     168            return;
     169        }
     170
     171        setEnabled(true);
     172        timeRects = new ArrayList<TimeRect>();
     173        if (time != null) {
     174            for (int[] timeRectValues : time) {
     175                int day0 = timeRectValues[0];
     176                int day1 = timeRectValues[1];
     177                int minute0 = timeRectValues[2];
     178                int minute1 = timeRectValues[3];
     179                TimeRect timeRect = new TimeRect(OheEditor.this, day0, day1,
     180                        minute0, minute1);
     181                timeRects.add(timeRect);
     182                contentPanel.add(timeRect);
     183            }
     184        }
     185
     186        repositionTimeRects();
     187        repaint();
     188    }
     189
     190    protected void repositionTimeRects() {
     191        if (timeRects != null)
     192            for (TimeRect timeRect : timeRects)
     193                timeRect.reposition();
     194    }
     195
     196    // returns the physical Borders of the TimeRect on the mainPanel
     197    public Rectangle getPanelBoundsForTimeinterval(int dayStart, int dayEnd,
     198            int minutesStart, int minutesEnd) {
     199        int x = getDayPosition(dayStart);
     200        int y = getMinutePosition(minutesStart);
     201        int width = getDayPosition(dayEnd) - getDayPosition(dayStart);
     202        int height = getMinutePosition(minutesEnd)
     203                - getMinutePosition(minutesStart);
     204
     205        // work around openjdk bug
     206        if (Main.isOpenjdk) {
     207            x++;
     208            y++;
     209        }
     210
     211        if (minutesStart == minutesEnd)
     212            return new Rectangle(x, y - 2 - TimeRect.verticalNonDrawedPixels,
     213                    width, height + 5 + 2 * TimeRect.verticalNonDrawedPixels);
     214
     215        return new Rectangle(x, y, width, height + 1);
     216    }
     217
     218    public double getDayWidth() {
     219        return (contentPanel.getWidth() - 1) / 7.0;
     220    }
     221
     222    public int getDayPosition(double d) {
     223        return (int) (d * getDayWidth());
     224    }
     225
     226    public double getMinuteHeight() {
     227        return (contentPanel.getHeight() - 1) / (24.0 * 60);
     228    }
     229
     230    public int getMinutePosition(int minute) {
     231        return (int) (minute * getMinuteHeight());
     232    }
     233
     234    // removes the given timerect from the panel and from the arraylist
     235    public void removeTimeRect(TimeRect timeRectToRemove) {
     236        timeRects.remove(timeRectToRemove);
     237        contentPanel.remove(timeRectToRemove);
     238        dialog.updateValueField(timeRects);
     239        repaint();
     240    }
     241
     242    // drawing a new Rect
     243    private int day0 = -1;
     244    private int minute0;
     245    private int day1;
     246    private int minute1;
     247    private int xDragStart;
     248    private int yDragStart;
     249
     250    @Override
     251    public void mouseClicked(MouseEvent evt) {
     252    }
     253
     254    @Override
     255    public void mouseEntered(MouseEvent evt) {
     256    }
     257
     258    @Override
     259    public void mouseExited(MouseEvent evt) {
     260    }
     261
     262    @Override
     263    public void mousePressed(MouseEvent evt) {
     264        day0 = (int) Math.floor(evt.getX() / getDayWidth());
     265        minute0 = (int) Math.floor(evt.getY()
     266                / (getMinuteHeight() * TimeRect.minuteResterize))
     267                * TimeRect.minuteResterize;
     268        day1 = day0;
     269        minute1 = minute0;
     270        xDragStart = evt.getX();
     271        yDragStart = evt.getY();
     272    }
     273
     274    @Override
     275    public void mouseReleased(MouseEvent evt) {
     276        // mouse must be moved 5px before creating a rect
     277        if (xDragStart == -1
     278                || Math.abs(evt.getX() - xDragStart)
     279                        + Math.abs(evt.getY() - yDragStart) > 5) {
     280            int day2 = Math.min(day0, day1);
     281            int day3 = Math.max(day0, day1);
     282            int minute2 = Math.min(minute0, minute1);
     283            int minute3 = Math.max(minute0, minute1);
     284
     285            TimeRect timeRect = new TimeRect(OheEditor.this, day2, day3,
     286                    minute2, minute3);
     287            timeRects.add(timeRect);
     288            contentPanel.add(timeRect);
     289            timeRect.reposition();
     290            dialog.updateValueField(timeRects);
     291
     292            day0 = -1;
     293            repaint();
     294        }
     295    }
     296
     297    @Override
     298    public void mouseDragged(MouseEvent evt) {
     299        // mouse must be moved 5px before drawing a rect
     300        if (xDragStart == -1
     301                || Math.abs(evt.getX() - xDragStart)
     302                        + Math.abs(evt.getY() - yDragStart) > 5) {
     303            xDragStart = -1;
     304            day1 = (int) Math.floor(evt.getX() / getDayWidth());
     305            minute1 = (int) Math.floor(evt.getY()
     306                    / (getMinuteHeight() * TimeRect.minuteResterize))
     307                    * TimeRect.minuteResterize;
     308            repaint();
     309        }
     310    }
     311
     312    @Override
     313    public void mouseMoved(MouseEvent evt) {
     314        mousePositionChanged(evt.getX(), evt.getY());
     315    }
     316
     317    public void mousePositionChanged(int x, int y) {
     318        int actualDay = (int) Math.floor(x / getDayWidth());
     319        int minutes = (int) Math.floor(y
     320                / (getMinuteHeight() * TimeRect.minuteResterize))
     321                * TimeRect.minuteResterize;
     322        actualDay = Math.max(0, Math.min(6, actualDay));
     323        minutes = Math.max(0, Math.min(24 * 60, minutes));
     324        dialog.setMousePositionText(OpeningTimeCompiler.WEEKDAYS[actualDay]
     325                + " " + OpeningTimeUtils.timeString(minutes));
     326    }
    327327}
  • applications/editors/josm/plugins/OpeningHoursEditor/src/org/openstreetmap/josm/plugins/ohe/gui/TimeRect.java

    r22751 r23192  
    2020
    2121public class TimeRect extends JPanel implements MouseListener,
    22                 MouseMotionListener {
    23         public static final int[] transformCursorTypes = new int[] {
    24                         Cursor.MOVE_CURSOR, Cursor.N_RESIZE_CURSOR,
    25                         Cursor.NE_RESIZE_CURSOR, Cursor.E_RESIZE_CURSOR,
    26                         Cursor.SE_RESIZE_CURSOR, Cursor.S_RESIZE_CURSOR,
    27                         Cursor.SW_RESIZE_CURSOR, Cursor.W_RESIZE_CURSOR,
    28                         Cursor.NW_RESIZE_CURSOR };
    29 
    30         public static final int minuteResterize = 15;
    31         public static final int verticalNonDrawedPixels = 5;
    32 
    33         public static final boolean[][] transformDirections = new boolean[][] {
    34                         { true, true, true, true }, // Drag
    35                         { true, false, false, false }, // N
    36                         { true, true, false, false }, // NE
    37                         { false, true, false, false }, // E
    38                         { false, true, true, false }, // SE
    39                         { false, false, true, false }, // S
    40                         { false, false, true, true }, // SW
    41                         { false, false, false, true }, // W
    42                         { true, false, false, true }, // NW
    43         };
    44 
    45         public static final int roundCornerSize = 8;
    46         private final int clickAreaSize = 16;
    47 
    48         private OheEditor editor;
    49 
    50         private int dayStart;
    51         private int dayEnd;
    52         private int minuteStart;
    53         private int minuteEnd;
    54 
    55         public TimeRect(OheEditor editor, int dayStart, int dayEnd,
    56                         int minutesStart, int minutesEnd) {
    57                 this.editor = editor;
    58 
    59                 this.dayStart = dayStart;
    60                 this.dayEnd = dayEnd;
    61                 this.minuteStart = minutesStart;
    62                 this.minuteEnd = minutesEnd;
    63 
    64                 transformType = -1;
    65 
    66                 setOpaque(true);
    67 
    68                 addMouseListener(this);
    69                 addMouseMotionListener(this);
    70         }
    71 
    72         public int getDayStart() {
    73                 return dayStart;
    74         }
    75 
    76         public int getDayEnd() {
    77                 return dayEnd;
    78         }
    79 
    80         public int getMinuteStart() {
    81                 return minuteStart;
    82         }
    83 
    84         public int getMinuteEnd() {
    85                 return minuteEnd;
    86         }
    87 
    88         public void reposition() {
    89                 setBounds(editor.getPanelBoundsForTimeinterval(dayStart, dayEnd + 1,
    90                                 minuteStart, minuteEnd));
    91                 editor.contentPanel.repaint();
    92         }
    93 
    94         private boolean isZeroMinuteInterval() {
    95                 return minuteStart == minuteEnd;
    96         }
    97 
    98         private boolean isOpenEndInterval() {
    99                 return minuteEnd == 24 * 60 + 1;
    100         }
    101 
    102         private void updateTimeInterval(int newDayStart, int newDayEnd,
    103                         int newMinuteStart, int newMinuteEnd) {
    104                 dayStart = newDayStart;
    105                 dayEnd = newDayEnd;
    106                 minuteStart = newMinuteStart;
    107                 minuteEnd = newMinuteEnd;
    108 
    109                 editor.dialog.updateValueField(editor.timeRects);
    110                 reposition();
    111         }
    112 
    113         @Override
    114         public void paintComponent(Graphics g) {
    115                 drawTimeRect((Graphics2D) g, new Rectangle(0, 0, getWidth(),
    116                                 getHeight()), isZeroMinuteInterval(), isOpenEndInterval());
    117         }
    118 
    119         public static void drawTimeRect(Graphics2D g2D, Rectangle bounds,
    120                         boolean isZeroMinuteInterval, boolean isOpenEndInterval) {
    121 
    122                 Color innerColor = new Color(135, 135, 234);
    123                 if (isOpenEndInterval)
    124                         innerColor = new Color(234, 135, 135);
    125 
    126                 int tmpRoundCornerSize = TimeRect.roundCornerSize;
    127                 int verticalNonFilledBorder = 1;
    128                 if (isZeroMinuteInterval) {
    129                         innerColor = new Color(135, 234, 135);
    130                         tmpRoundCornerSize = 0;
    131                         verticalNonFilledBorder = verticalNonDrawedPixels;
    132                 }
    133 
    134                 g2D.setColor(innerColor);
    135                 g2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
    136                                 .6f));
    137                 g2D.fillRoundRect(bounds.x + 1, bounds.y + verticalNonFilledBorder,
    138                                 bounds.width - 2, bounds.height - 1 - 2
    139                                                 * verticalNonFilledBorder, tmpRoundCornerSize,
    140                                 tmpRoundCornerSize);
    141 
    142                 g2D.setColor(new Color(255, 0, 0));
    143                 g2D.setComposite(AlphaComposite
    144                                 .getInstance(AlphaComposite.SRC_OVER, 1f));
    145                 g2D.drawRoundRect(bounds.x + 1, bounds.y + verticalNonFilledBorder,
    146                                 bounds.width - 2, bounds.height - 1 - 2
    147                                                 * verticalNonFilledBorder, tmpRoundCornerSize,
    148                                 tmpRoundCornerSize);
    149 
    150         }
    151 
    152         private int actualDayDrag;
    153         private int actualMinuteDrag;
    154         private int dragX;
    155         private int dragY;
    156         private int transformType;
    157 
    158         // Calculate where the Component was clicked and returns the
    159         // transformtype
    160         private int getTransformType(MouseEvent evt) {
    161                 int tmpClickAreaWidth = Math.min(clickAreaSize, getWidth() / 3);
    162                 int tmpClickAreaHeight = Math.min(clickAreaSize, getHeight() / 3);
    163 
    164                 boolean isInNorthernTransformClickArea = evt.getY() < tmpClickAreaHeight;
    165                 boolean isInEasternTransformClickArea = evt.getX() > getWidth()
    166                                 - tmpClickAreaWidth;
    167                 boolean isInSouthernTransformClickArea = evt.getY() > getHeight()
    168                                 - tmpClickAreaHeight;
    169                 boolean isInWesternTransformClickArea = evt.getX() < tmpClickAreaWidth;
    170 
    171                 if (isZeroMinuteInterval()) {
    172                         isInNorthernTransformClickArea = false;
    173                         isInSouthernTransformClickArea = false;
    174                 }
    175 
    176                 int tType = 0;
    177                 for (int i = 1; i < transformDirections.length && tType == 0; i++) {
    178                         if (isInNorthernTransformClickArea == transformDirections[i][0]
    179                                         && isInEasternTransformClickArea == transformDirections[i][1]
    180                                         && isInSouthernTransformClickArea == transformDirections[i][2]
    181                                         && isInWesternTransformClickArea == transformDirections[i][3])
    182                                 tType = i;
    183                 }
    184 
    185                 return tType;
    186         }
    187 
    188         public void showMenu(MouseEvent evt) {
    189                 JPopupMenu menu = new JPopupMenu();
    190                 final JCheckBoxMenuItem cbMenuItem = new JCheckBoxMenuItem(
    191                                 tr("open end"), isOpenEndInterval());
    192                 menu.add(cbMenuItem);
    193                 cbMenuItem.addActionListener(new ActionListener() {
    194                         @Override
    195                         public void actionPerformed(ActionEvent e) {
    196                                 if (cbMenuItem.isSelected())
    197                                         updateTimeInterval(dayStart, dayEnd, minuteStart,
    198                                                         24 * 60 + 1);
    199                                 else
    200                                         updateTimeInterval(dayStart, dayEnd, minuteStart, 24 * 60);
    201                         }
    202                 });
    203                 menu.show(this, evt.getX(), evt.getY());
    204         }
    205 
    206         @Override
    207         public void mouseClicked(MouseEvent evt) {
    208         }
    209 
    210         @Override
    211         public void mouseEntered(MouseEvent evt) {
    212         }
    213 
    214         @Override
    215         public void mouseExited(MouseEvent evt) {
    216                 if (transformType < 0)
    217                         setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
    218         }
    219 
    220         @Override
    221         public void mousePressed(MouseEvent evt) {
    222                 if (evt.isPopupTrigger()) {
    223                         showMenu(evt);
    224                 } else {
    225                         actualDayDrag = 0;
    226                         actualMinuteDrag = 0;
    227                         dragX = evt.getXOnScreen();
    228                         dragY = evt.getYOnScreen();
    229                         transformType = getTransformType(evt);
    230                 }
    231         }
    232 
    233         @Override
    234         public void mouseReleased(MouseEvent evt) {
    235                 transformType = -1;
    236         }
    237 
    238         @Override
    239         public void mouseDragged(MouseEvent evt) {
    240                 if (transformType >= 0) {
    241                         int xDiff = evt.getXOnScreen() - dragX;
    242                         int yDiff = evt.getYOnScreen() - dragY;
    243 
    244                         xDiff = (int) Math.round(xDiff / editor.getDayWidth())
    245                                         - actualDayDrag;
    246                         yDiff = (int) Math.round(yDiff
    247                                         / (editor.getMinuteHeight() * minuteResterize))
    248                                         * minuteResterize - actualMinuteDrag;
    249 
    250                         if (xDiff != 0) {
    251                                 int newDayStart = dayStart;
    252                                 int newDayEnd = dayEnd;
    253 
    254                                 if (transformDirections[transformType][3])
    255                                         newDayStart += xDiff;
    256                                 if (transformDirections[transformType][1])
    257                                         newDayEnd += xDiff;
    258 
    259                                 if (newDayStart > newDayEnd) {
    260                                         editor.removeTimeRect(this);
    261                                         transformType = -1;
    262                                         setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
    263                                 } else if (newDayStart >= 0 && newDayEnd <= 6) {
    264                                         actualDayDrag += xDiff;
    265                                         updateTimeInterval(newDayStart, newDayEnd, minuteStart,
    266                                                         minuteEnd);
    267                                 }
    268                         }
    269                         if (yDiff != 0 && transformType >= 0) {
    270                                 int newMinutesStart = minuteStart;
    271                                 int newMinutesEnd = minuteEnd;
    272 
    273                                 if (transformDirections[transformType][0])
    274                                         newMinutesStart = newMinutesStart + yDiff;
    275                                 if (transformDirections[transformType][2]
    276                                                 && !isOpenEndInterval())
    277                                         newMinutesEnd = newMinutesEnd + yDiff;
    278 
    279                                 if (newMinutesStart >= 0
    280                                                 && (newMinutesEnd <= 24 * 60 || isOpenEndInterval())) {
    281                                         actualMinuteDrag += yDiff;
    282                                         updateTimeInterval(dayStart, dayEnd, newMinutesStart,
    283                                                         newMinutesEnd);
    284                                 }
    285                         }
    286                 }
    287                 editor.mousePositionChanged(evt.getX() + getX(), evt.getY() + getY());
    288         }
    289 
    290         @Override
    291         public void mouseMoved(MouseEvent evt) {
    292                 if (transformType < 0)
    293                         setCursor(new Cursor(transformCursorTypes[getTransformType(evt)]));
    294                 editor.mousePositionChanged(evt.getX() + getX(), evt.getY() + getY());
    295         }
     22        MouseMotionListener {
     23    public static final int[] transformCursorTypes = new int[] {
     24            Cursor.MOVE_CURSOR, Cursor.N_RESIZE_CURSOR,
     25            Cursor.NE_RESIZE_CURSOR, Cursor.E_RESIZE_CURSOR,
     26            Cursor.SE_RESIZE_CURSOR, Cursor.S_RESIZE_CURSOR,
     27            Cursor.SW_RESIZE_CURSOR, Cursor.W_RESIZE_CURSOR,
     28            Cursor.NW_RESIZE_CURSOR };
     29
     30    public static final int minuteResterize = 15;
     31    public static final int verticalNonDrawedPixels = 5;
     32
     33    public static final boolean[][] transformDirections = new boolean[][] {
     34            { true, true, true, true }, // Drag
     35            { true, false, false, false }, // N
     36            { true, true, false, false }, // NE
     37            { false, true, false, false }, // E
     38            { false, true, true, false }, // SE
     39            { false, false, true, false }, // S
     40            { false, false, true, true }, // SW
     41            { false, false, false, true }, // W
     42            { true, false, false, true }, // NW
     43    };
     44
     45    public static final int roundCornerSize = 8;
     46    private final int clickAreaSize = 16;
     47
     48    private OheEditor editor;
     49
     50    private int dayStart;
     51    private int dayEnd;
     52    private int minuteStart;
     53    private int minuteEnd;
     54
     55    public TimeRect(OheEditor editor, int dayStart, int dayEnd,
     56            int minutesStart, int minutesEnd) {
     57        this.editor = editor;
     58
     59        this.dayStart = dayStart;
     60        this.dayEnd = dayEnd;
     61        this.minuteStart = minutesStart;
     62        this.minuteEnd = minutesEnd;
     63
     64        transformType = -1;
     65
     66        setOpaque(true);
     67
     68        addMouseListener(this);
     69        addMouseMotionListener(this);
     70    }
     71
     72    public int getDayStart() {
     73        return dayStart;
     74    }
     75
     76    public int getDayEnd() {
     77        return dayEnd;
     78    }
     79
     80    public int getMinuteStart() {
     81        return minuteStart;
     82    }
     83
     84    public int getMinuteEnd() {
     85        return minuteEnd;
     86    }
     87
     88    public void reposition() {
     89        setBounds(editor.getPanelBoundsForTimeinterval(dayStart, dayEnd + 1,
     90                minuteStart, minuteEnd));
     91        editor.contentPanel.repaint();
     92    }
     93
     94    private boolean isZeroMinuteInterval() {
     95        return minuteStart == minuteEnd;
     96    }
     97
     98    private boolean isOpenEndInterval() {
     99        return minuteEnd == 24 * 60 + 1;
     100    }
     101
     102    private void updateTimeInterval(int newDayStart, int newDayEnd,
     103            int newMinuteStart, int newMinuteEnd) {
     104        dayStart = newDayStart;
     105        dayEnd = newDayEnd;
     106        minuteStart = newMinuteStart;
     107        minuteEnd = newMinuteEnd;
     108
     109        editor.dialog.updateValueField(editor.timeRects);
     110        reposition();
     111    }
     112
     113    @Override
     114    public void paintComponent(Graphics g) {
     115        drawTimeRect((Graphics2D) g, new Rectangle(0, 0, getWidth(),
     116                getHeight()), isZeroMinuteInterval(), isOpenEndInterval());
     117    }
     118
     119    public static void drawTimeRect(Graphics2D g2D, Rectangle bounds,
     120            boolean isZeroMinuteInterval, boolean isOpenEndInterval) {
     121
     122        Color innerColor = new Color(135, 135, 234);
     123        if (isOpenEndInterval)
     124            innerColor = new Color(234, 135, 135);
     125
     126        int tmpRoundCornerSize = TimeRect.roundCornerSize;
     127        int verticalNonFilledBorder = 1;
     128        if (isZeroMinuteInterval) {
     129            innerColor = new Color(135, 234, 135);
     130            tmpRoundCornerSize = 0;
     131            verticalNonFilledBorder = verticalNonDrawedPixels;
     132        }
     133
     134        g2D.setColor(innerColor);
     135        g2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
     136                .6f));
     137        g2D.fillRoundRect(bounds.x + 1, bounds.y + verticalNonFilledBorder,
     138                bounds.width - 2, bounds.height - 1 - 2
     139                        * verticalNonFilledBorder, tmpRoundCornerSize,
     140                tmpRoundCornerSize);
     141
     142        g2D.setColor(new Color(255, 0, 0));
     143        g2D.setComposite(AlphaComposite
     144                .getInstance(AlphaComposite.SRC_OVER, 1f));
     145        g2D.drawRoundRect(bounds.x + 1, bounds.y + verticalNonFilledBorder,
     146                bounds.width - 2, bounds.height - 1 - 2
     147                        * verticalNonFilledBorder, tmpRoundCornerSize,
     148                tmpRoundCornerSize);
     149
     150    }
     151
     152    private int actualDayDrag;
     153    private int actualMinuteDrag;
     154    private int dragX;
     155    private int dragY;
     156    private int transformType;
     157
     158    // Calculate where the Component was clicked and returns the
     159    // transformtype
     160    private int getTransformType(MouseEvent evt) {
     161        int tmpClickAreaWidth = Math.min(clickAreaSize, getWidth() / 3);
     162        int tmpClickAreaHeight = Math.min(clickAreaSize, getHeight() / 3);
     163
     164        boolean isInNorthernTransformClickArea = evt.getY() < tmpClickAreaHeight;
     165        boolean isInEasternTransformClickArea = evt.getX() > getWidth()
     166                - tmpClickAreaWidth;
     167        boolean isInSouthernTransformClickArea = evt.getY() > getHeight()
     168                - tmpClickAreaHeight;
     169        boolean isInWesternTransformClickArea = evt.getX() < tmpClickAreaWidth;
     170
     171        if (isZeroMinuteInterval()) {
     172            isInNorthernTransformClickArea = false;
     173            isInSouthernTransformClickArea = false;
     174        }
     175
     176        int tType = 0;
     177        for (int i = 1; i < transformDirections.length && tType == 0; i++) {
     178            if (isInNorthernTransformClickArea == transformDirections[i][0]
     179                    && isInEasternTransformClickArea == transformDirections[i][1]
     180                    && isInSouthernTransformClickArea == transformDirections[i][2]
     181                    && isInWesternTransformClickArea == transformDirections[i][3])
     182                tType = i;
     183        }
     184
     185        return tType;
     186    }
     187
     188    public void showMenu(MouseEvent evt) {
     189        JPopupMenu menu = new JPopupMenu();
     190        final JCheckBoxMenuItem cbMenuItem = new JCheckBoxMenuItem(
     191                tr("open end"), isOpenEndInterval());
     192        menu.add(cbMenuItem);
     193        cbMenuItem.addActionListener(new ActionListener() {
     194            @Override
     195            public void actionPerformed(ActionEvent e) {
     196                if (cbMenuItem.isSelected())
     197                    updateTimeInterval(dayStart, dayEnd, minuteStart,
     198                            24 * 60 + 1);
     199                else
     200                    updateTimeInterval(dayStart, dayEnd, minuteStart, 24 * 60);
     201            }
     202        });
     203        menu.show(this, evt.getX(), evt.getY());
     204    }
     205
     206    @Override
     207    public void mouseClicked(MouseEvent evt) {
     208    }
     209
     210    @Override
     211    public void mouseEntered(MouseEvent evt) {
     212    }
     213
     214    @Override
     215    public void mouseExited(MouseEvent evt) {
     216        if (transformType < 0)
     217            setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
     218    }
     219
     220    @Override
     221    public void mousePressed(MouseEvent evt) {
     222        if (evt.isPopupTrigger()) {
     223            showMenu(evt);
     224        } else {
     225            actualDayDrag = 0;
     226            actualMinuteDrag = 0;
     227            dragX = evt.getXOnScreen();
     228            dragY = evt.getYOnScreen();
     229            transformType = getTransformType(evt);
     230        }
     231    }
     232
     233    @Override
     234    public void mouseReleased(MouseEvent evt) {
     235        transformType = -1;
     236    }
     237
     238    @Override
     239    public void mouseDragged(MouseEvent evt) {
     240        if (transformType >= 0) {
     241            int xDiff = evt.getXOnScreen() - dragX;
     242            int yDiff = evt.getYOnScreen() - dragY;
     243
     244            xDiff = (int) Math.round(xDiff / editor.getDayWidth())
     245                    - actualDayDrag;
     246            yDiff = (int) Math.round(yDiff
     247                    / (editor.getMinuteHeight() * minuteResterize))
     248                    * minuteResterize - actualMinuteDrag;
     249
     250            if (xDiff != 0) {
     251                int newDayStart = dayStart;
     252                int newDayEnd = dayEnd;
     253
     254                if (transformDirections[transformType][3])
     255                    newDayStart += xDiff;
     256                if (transformDirections[transformType][1])
     257                    newDayEnd += xDiff;
     258
     259                if (newDayStart > newDayEnd) {
     260                    editor.removeTimeRect(this);
     261                    transformType = -1;
     262                    setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
     263                } else if (newDayStart >= 0 && newDayEnd <= 6) {
     264                    actualDayDrag += xDiff;
     265                    updateTimeInterval(newDayStart, newDayEnd, minuteStart,
     266                            minuteEnd);
     267                }
     268            }
     269            if (yDiff != 0 && transformType >= 0) {
     270                int newMinutesStart = minuteStart;
     271                int newMinutesEnd = minuteEnd;
     272
     273                if (transformDirections[transformType][0])
     274                    newMinutesStart = newMinutesStart + yDiff;
     275                if (transformDirections[transformType][2]
     276                        && !isOpenEndInterval())
     277                    newMinutesEnd = newMinutesEnd + yDiff;
     278
     279                if (newMinutesStart >= 0
     280                        && (newMinutesEnd <= 24 * 60 || isOpenEndInterval())) {
     281                    actualMinuteDrag += yDiff;
     282                    updateTimeInterval(dayStart, dayEnd, newMinutesStart,
     283                            newMinutesEnd);
     284                }
     285            }
     286        }
     287        editor.mousePositionChanged(evt.getX() + getX(), evt.getY() + getY());
     288    }
     289
     290    @Override
     291    public void mouseMoved(MouseEvent evt) {
     292        if (transformType < 0)
     293            setCursor(new Cursor(transformCursorTypes[getTransformType(evt)]));
     294        editor.mousePositionChanged(evt.getX() + getX(), evt.getY() + getY());
     295    }
    296296}
  • applications/editors/josm/plugins/OpeningHoursEditor/src/org/openstreetmap/josm/plugins/ohe/parser/OpeningTimeCompilerTokenManager.java

    r22751 r23192  
    274274/** Token literal values. */
    275275public static final String[] jjstrLiteralImages = {
    276 "", null, null, "\53", "\157\146\146", "\62\64\57\67", "\73\40", "\40", "\54", 
     276"", null, null, "\53", "\157\146\146", "\62\64\57\67", "\73\40", "\40", "\54",
    277277"\55", "\72", };
    278278
     
    362362
    363363/** Get the next Token. */
    364 public Token getNextToken() 
     364public Token getNextToken()
    365365{
    366366  Token matchedToken;
  • applications/editors/josm/plugins/OpeningHoursEditor/src/org/openstreetmap/josm/plugins/ohe/parser/SyntaxException.java

    r22751 r23192  
    33public class SyntaxException extends Exception {
    44
    5         private int startColumn;
    6         private int endColumn;
    7         private String info;
     5    private int startColumn;
     6    private int endColumn;
     7    private String info;
    88
    9         public int getStartColumn() {
    10                 return startColumn;
    11         }
     9    public int getStartColumn() {
     10        return startColumn;
     11    }
    1212
    13         public int getEndColumn() {
    14                 return endColumn;
    15         }
     13    public int getEndColumn() {
     14        return endColumn;
     15    }
    1616
    17         public String getInfo() {
    18                 return info;
    19         }
     17    public String getInfo() {
     18        return info;
     19    }
    2020
    21         public SyntaxException(String info, int startColumn, int endColumn) {
    22                 this.startColumn = startColumn;
    23                 this.endColumn = endColumn;
    24                 this.info = info;
    25         }
     21    public SyntaxException(String info, int startColumn, int endColumn) {
     22        this.startColumn = startColumn;
     23        this.endColumn = endColumn;
     24        this.info = info;
     25    }
    2626}
  • applications/editors/josm/plugins/OpeningHoursEditor/src/org/openstreetmap/josm/plugins/ohe/parser/TokenMgrError.java

    r22751 r23192  
    66public class TokenMgrError extends Error {
    77
    8         /**
    9         * The version identifier for this Serializable class. Increment only if the
    10         * <i>serialized</i> form of the class changes.
    11         */
    12         private static final long serialVersionUID = 1L;
     8    /**
     9    * The version identifier for this Serializable class. Increment only if the
     10    * <i>serialized</i> form of the class changes.
     11    */
     12    private static final long serialVersionUID = 1L;
    1313
    14         /*
    15         * Ordinals for various reasons why an Error of this type can be thrown.
    16         */
     14    /*
     15    * Ordinals for various reasons why an Error of this type can be thrown.
     16    */
    1717
    18         /**
    19         * Lexical error occurred.
    20         */
    21         static final int LEXICAL_ERROR = 0;
     18    /**
     19    * Lexical error occurred.
     20    */
     21    static final int LEXICAL_ERROR = 0;
    2222
    23         /**
    24         * An attempt was made to create a second instance of a static token
    25         * manager.
    26         */
    27         static final int STATIC_LEXER_ERROR = 1;
     23    /**
     24    * An attempt was made to create a second instance of a static token
     25    * manager.
     26    */
     27    static final int STATIC_LEXER_ERROR = 1;
    2828
    29         /**
    30         * Tried to change to an invalid lexical state.
    31         */
    32         static final int INVALID_LEXICAL_STATE = 2;
     29    /**
     30    * Tried to change to an invalid lexical state.
     31    */
     32    static final int INVALID_LEXICAL_STATE = 2;
    3333
    34         /**
    35         * Detected (and bailed out of) an infinite loop in the token manager.
    36         */
    37         static final int LOOP_DETECTED = 3;
     34    /**
     35    * Detected (and bailed out of) an infinite loop in the token manager.
     36    */
     37    static final int LOOP_DETECTED = 3;
    3838
    39         /**
    40         * Indicates the reason why the exception is thrown. It will have one of the
    41         * above 4 values.
    42         */
    43         int errorCode;
     39    /**
     40    * Indicates the reason why the exception is thrown. It will have one of the
     41    * above 4 values.
     42    */
     43    int errorCode;
    4444
    45         /**
    46         * Replaces unprintable characters by their escaped (or unicode escaped)
    47         * equivalents in the given string
    48         */
    49         protected static final String addEscapes(String str) {
    50                 StringBuffer retval = new StringBuffer();
    51                 char ch;
    52                 for (int i = 0; i < str.length(); i++) {
    53                         switch (str.charAt(i)) {
    54                         case 0:
    55                                 continue;
    56                         case '\b':
    57                                 retval.append("\\b");
    58                                 continue;
    59                         case '\t':
    60                                 retval.append("\\t");
    61                                 continue;
    62                         case '\n':
    63                                 retval.append("\\n");
    64                                 continue;
    65                         case '\f':
    66                                 retval.append("\\f");
    67                                 continue;
    68                         case '\r':
    69                                 retval.append("\\r");
    70                                 continue;
    71                         case '\"':
    72                                 retval.append("\\\"");
    73                                 continue;
    74                         case '\'':
    75                                 retval.append("\\\'");
    76                                 continue;
    77                         case '\\':
    78                                 retval.append("\\\\");
    79                                 continue;
    80                         default:
    81                                 if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {
    82                                         String s = "0000" + Integer.toString(ch, 16);
    83                                         retval.append("\\u"
    84                                                         + s.substring(s.length() - 4, s.length()));
    85                                 } else {
    86                                         retval.append(ch);
    87                                 }
    88                                 continue;
    89                         }
    90                 }
    91                 return retval.toString();
    92         }
     45    /**
     46    * Replaces unprintable characters by their escaped (or unicode escaped)
     47    * equivalents in the given string
     48    */
     49    protected static final String addEscapes(String str) {
     50        StringBuffer retval = new StringBuffer();
     51        char ch;
     52        for (int i = 0; i < str.length(); i++) {
     53            switch (str.charAt(i)) {
     54            case 0:
     55                continue;
     56            case '\b':
     57                retval.append("\\b");
     58                continue;
     59            case '\t':
     60                retval.append("\\t");
     61                continue;
     62            case '\n':
     63                retval.append("\\n");
     64                continue;
     65            case '\f':
     66                retval.append("\\f");
     67                continue;
     68            case '\r':
     69                retval.append("\\r");
     70                continue;
     71            case '\"':
     72                retval.append("\\\"");
     73                continue;
     74            case '\'':
     75                retval.append("\\\'");
     76                continue;
     77            case '\\':
     78                retval.append("\\\\");
     79                continue;
     80            default:
     81                if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {
     82                    String s = "0000" + Integer.toString(ch, 16);
     83                    retval.append("\\u"
     84                            + s.substring(s.length() - 4, s.length()));
     85                } else {
     86                    retval.append(ch);
     87                }
     88                continue;
     89            }
     90        }
     91        return retval.toString();
     92    }
    9393
    94         /**
    95         * Returns a detailed message for the Error when it is thrown by the token
    96         * manager to indicate a lexical error. Parameters : EOFSeen : indicates if
    97         * EOF caused the lexical error curLexState : lexical state in which this
    98         * error occurred errorLine : line number when the error occurred
    99         * errorColumn : column number when the error occurred errorAfter : prefix
    100         * that was seen before this error occurred curchar : the offending
    101         * character Note: You can customize the lexical error message by modifying
    102         * this method.
    103         */
    104         protected static String LexicalError(boolean EOFSeen, int lexState,
    105                         int errorLine, int errorColumn, String errorAfter, char curChar) {
    106                 return ("Lexical error at line "
    107                                 + errorLine
    108                                 + ", column "
    109                                 + errorColumn
    110                                 + ".  Encountered: "
    111                                 + (EOFSeen ? "<EOF> " : ("\""
    112                                                 + addEscapes(String.valueOf(curChar)) + "\"")
    113                                                 + " (" + (int) curChar + "), ") + "after : \""
    114                                 + addEscapes(errorAfter) + "\"");
    115         }
     94    /**
     95    * Returns a detailed message for the Error when it is thrown by the token
     96    * manager to indicate a lexical error. Parameters : EOFSeen : indicates if
     97    * EOF caused the lexical error curLexState : lexical state in which this
     98    * error occurred errorLine : line number when the error occurred
     99    * errorColumn : column number when the error occurred errorAfter : prefix
     100    * that was seen before this error occurred curchar : the offending
     101    * character Note: You can customize the lexical error message by modifying
     102    * this method.
     103    */
     104    protected static String LexicalError(boolean EOFSeen, int lexState,
     105            int errorLine, int errorColumn, String errorAfter, char curChar) {
     106        return ("Lexical error at line "
     107                + errorLine
     108                + ", column "
     109                + errorColumn
     110                + ".  Encountered: "
     111                + (EOFSeen ? "<EOF> " : ("\""
     112                        + addEscapes(String.valueOf(curChar)) + "\"")
     113                        + " (" + (int) curChar + "), ") + "after : \""
     114                + addEscapes(errorAfter) + "\"");
     115    }
    116116
    117         /**
    118         * You can also modify the body of this method to customize your error
    119         * messages. For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE
    120         * are not of end-users concern, so you can return something like :
    121         *
    122         * "Internal Error : Please file a bug report .... "
    123         *
    124         * from this method for such cases in the release version of your parser.
    125         */
    126         @Override
    127         public String getMessage() {
    128                 return super.getMessage();
    129         }
     117    /**
     118    * You can also modify the body of this method to customize your error
     119    * messages. For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE
     120    * are not of end-users concern, so you can return something like :
     121    *
     122    * "Internal Error : Please file a bug report .... "
     123    *
     124    * from this method for such cases in the release version of your parser.
     125    */
     126    @Override
     127    public String getMessage() {
     128        return super.getMessage();
     129    }
    130130
    131         /*
    132         * Constructors of various flavors follow.
    133         */
     131    /*
     132    * Constructors of various flavors follow.
     133    */
    134134
    135         /** No arg constructor. */
    136         public TokenMgrError() {
    137         }
     135    /** No arg constructor. */
     136    public TokenMgrError() {
     137    }
    138138
    139         /** Constructor with message and reason. */
    140         public TokenMgrError(String message, int reason) {
    141                 super(message);
    142                 errorCode = reason;
    143         }
     139    /** Constructor with message and reason. */
     140    public TokenMgrError(String message, int reason) {
     141        super(message);
     142        errorCode = reason;
     143    }
    144144
    145         public boolean EOFSeen;
    146         public int lexState;
    147         public int errorLine;
    148         public int errorColumn;
    149         public String errorAfter;
    150         public char curChar;
    151         public int reason;
     145    public boolean EOFSeen;
     146    public int lexState;
     147    public int errorLine;
     148    public int errorColumn;
     149    public String errorAfter;
     150    public char curChar;
     151    public int reason;
    152152
    153         /** Full Constructor. */
    154         public TokenMgrError(boolean EOFSeen, int lexState, int errorLine,
    155                         int errorColumn, String errorAfter, char curChar, int reason) {
    156                 this.EOFSeen = EOFSeen;
    157                 this.lexState = lexState;
    158                 this.errorLine = errorLine;
    159                 this.errorColumn = errorColumn;
    160                 this.errorAfter = errorAfter;
    161                 this.curChar = curChar;
    162                 this.reason = reason;
    163         }
     153    /** Full Constructor. */
     154    public TokenMgrError(boolean EOFSeen, int lexState, int errorLine,
     155            int errorColumn, String errorAfter, char curChar, int reason) {
     156        this.EOFSeen = EOFSeen;
     157        this.lexState = lexState;
     158        this.errorLine = errorLine;
     159        this.errorColumn = errorColumn;
     160        this.errorAfter = errorAfter;
     161        this.curChar = curChar;
     162        this.reason = reason;
     163    }
    164164}
    165165/*
  • applications/editors/josm/plugins/alignways/src/org/openstreetmap/josm/plugins/alignways/AlignWaysMode.java

    r23165 r23192  
    2828public class AlignWaysMode extends MapMode /* implements MapViewPaintable */{
    2929
    30         private static final long serialVersionUID = -1090955708412011141L;
    31         private final AlignWaysState noneSelected;
    32         private final AlignWaysState referenceSelected;
    33         private final AlignWaysState aligneeSelected;
    34         private final AlignWaysState bothSelected;
    35         private AlignWaysState currentState;
    36         private AlignWaysSegmentMgr awSegs;
    37         boolean tipShown;
     30    private static final long serialVersionUID = -1090955708412011141L;
     31    private final AlignWaysState noneSelected;
     32    private final AlignWaysState referenceSelected;
     33    private final AlignWaysState aligneeSelected;
     34    private final AlignWaysState bothSelected;
     35    private AlignWaysState currentState;
     36    private AlignWaysSegmentMgr awSegs;
     37    boolean tipShown;
    3838
    39         public AlignWaysMode(MapFrame mapFrame, String name, String desc) {
    40                 super(tr(name), "alignways.png", tr(desc),
    41                                 Shortcut.registerShortcut("mapmode:alignways",
    42                                                 tr("Mode: {0}", tr("Align Ways")),
    43                                                 KeyEvent.VK_N, Shortcut.GROUP_EDIT, Shortcut.SHIFT_DEFAULT),
    44                                                 mapFrame, Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    45                 noneSelected = new AlignWaysSelNoneState();
    46                 referenceSelected = new AlignWaysSelRefState();
    47                 aligneeSelected = new AlignWaysSelAlgnState();
    48                 bothSelected = new AlignWaysSelBothState();
    49                 tipShown = false;
     39    public AlignWaysMode(MapFrame mapFrame, String name, String desc) {
     40        super(tr(name), "alignways.png", tr(desc),
     41                Shortcut.registerShortcut("mapmode:alignways",
     42                        tr("Mode: {0}", tr("Align Ways")),
     43                        KeyEvent.VK_N, Shortcut.GROUP_EDIT, Shortcut.SHIFT_DEFAULT),
     44                        mapFrame, Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
     45        noneSelected = new AlignWaysSelNoneState();
     46        referenceSelected = new AlignWaysSelRefState();
     47        aligneeSelected = new AlignWaysSelAlgnState();
     48        bothSelected = new AlignWaysSelBothState();
     49        tipShown = false;
    5050
    51         }
     51    }
    5252
    53         @Override
    54         public void enterMode() {
    55                 super.enterMode();
    56                 boolean showTips = Boolean.parseBoolean(Main.pref.get("alignways.showtips", "true"));
    57                 if ((showTips) && (!tipShown)) {
    58                         showTips();
    59                 }
    60                 awSegs = AlignWaysSegmentMgr.getInstance(Main.map.mapView);
    61                 Main.map.mapView.addMouseListener(this);
    62                 setCurrentState(noneSelected);
    63         }
     53    @Override
     54    public void enterMode() {
     55        super.enterMode();
     56        boolean showTips = Boolean.parseBoolean(Main.pref.get("alignways.showtips", "true"));
     57        if ((showTips) && (!tipShown)) {
     58            showTips();
     59        }
     60        awSegs = AlignWaysSegmentMgr.getInstance(Main.map.mapView);
     61        Main.map.mapView.addMouseListener(this);
     62        setCurrentState(noneSelected);
     63    }
    6464
    65         @Override
    66         public void exitMode() {
    67                 super.exitMode();
    68                 setCurrentState(noneSelected);
    69                 Main.map.mapView.removeMouseListener(this);
    70                 AlignWaysPlugin.getAwAction().setEnabled(false);
    71         }
     65    @Override
     66    public void exitMode() {
     67        super.exitMode();
     68        setCurrentState(noneSelected);
     69        Main.map.mapView.removeMouseListener(this);
     70        AlignWaysPlugin.getAwAction().setEnabled(false);
     71    }
    7272
    73         @Override
    74         public void mouseClicked(MouseEvent e) {
     73    @Override
     74    public void mouseClicked(MouseEvent e) {
    7575
    76                 boolean ctrlPressed = (e.getModifiers() & ActionEvent.CTRL_MASK) != 0;
    77                 boolean altPressed = (e.getModifiers() & (ActionEvent.ALT_MASK | InputEvent.ALT_GRAPH_MASK)) != 0;
     76        boolean ctrlPressed = (e.getModifiers() & ActionEvent.CTRL_MASK) != 0;
     77        boolean altPressed = (e.getModifiers() & (ActionEvent.ALT_MASK | InputEvent.ALT_GRAPH_MASK)) != 0;
    7878
    79                 if (e.getButton() == MouseEvent.BUTTON1) {
     79        if (e.getButton() == MouseEvent.BUTTON1) {
    8080
    81                         if (altPressed) {
    82                                 currentState.altLClick(this);
     81            if (altPressed) {
     82                currentState.altLClick(this);
    8383
    84                         } else {
    85                                 Point clickedPoint = new Point(e.getX(), e.getY());
     84            } else {
     85                Point clickedPoint = new Point(e.getX(), e.getY());
    8686
    87                                 if (!ctrlPressed) {
    88                                         // Alignee could change
     87                if (!ctrlPressed) {
     88                    // Alignee could change
    8989
    90                                         if (awSegs.algnUpdate(clickedPoint)) {
    91                                                 currentState.leftClick(this);
    92                                         }
     90                    if (awSegs.algnUpdate(clickedPoint)) {
     91                        currentState.leftClick(this);
     92                    }
    9393
    94                                 } else {
    95                                         // Reference could change
    96                                         if (awSegs.refUpdate(clickedPoint)) {
    97                                                 currentState.ctrlLClick(this);
    98                                         }
    99                                 }
    100                         }
    101                 }
     94                } else {
     95                    // Reference could change
     96                    if (awSegs.refUpdate(clickedPoint)) {
     97                        currentState.ctrlLClick(this);
     98                    }
     99                }
     100            }
     101        }
    102102
    103                 // Activate the Align Ways button if we have enough selections
    104                 if (currentState == bothSelected) {
    105                         AlignWaysPlugin.getAwAction().setEnabled(true);
    106                 } else {
    107                         AlignWaysPlugin.getAwAction().setEnabled(false);
    108                 }
    109                 Main.map.mapView.repaint();
    110         }
     103        // Activate the Align Ways button if we have enough selections
     104        if (currentState == bothSelected) {
     105            AlignWaysPlugin.getAwAction().setEnabled(true);
     106        } else {
     107            AlignWaysPlugin.getAwAction().setEnabled(false);
     108        }
     109        Main.map.mapView.repaint();
     110    }
    111111
    112         /**
    113         * @param currentState
    114         *            One of the AlignWays states
    115         */
    116         public void setCurrentState(AlignWaysState currentState) {
    117                 this.currentState = currentState;
    118                 currentState.setHelpText();
     112    /**
     113    * @param currentState
     114    *            One of the AlignWays states
     115    */
     116    public void setCurrentState(AlignWaysState currentState) {
     117        this.currentState = currentState;
     118        currentState.setHelpText();
    119119
    120                 if (currentState == noneSelected) {
    121                         awSegs.cleanupWays();
    122                         // FIX: getCurrentDataSet may return null when the editable layer had
    123                         // already been removed by JOSM. This happens e.g. when the user closes
    124                         // JOSM while AlignWays mode is still active.
    125                         if (getCurrentDataSet() != null) {
    126                                 getCurrentDataSet().clearSelection();
    127                         }
    128                 }
    129         }
     120        if (currentState == noneSelected) {
     121            awSegs.cleanupWays();
     122            // FIX: getCurrentDataSet may return null when the editable layer had
     123            // already been removed by JOSM. This happens e.g. when the user closes
     124            // JOSM while AlignWays mode is still active.
     125            if (getCurrentDataSet() != null) {
     126                getCurrentDataSet().clearSelection();
     127            }
     128        }
     129    }
    130130
    131         /**
    132         * @return the noneSelected
    133         */
    134         public AlignWaysState getNoneSelected() {
    135                 return noneSelected;
    136         }
     131    /**
     132    * @return the noneSelected
     133    */
     134    public AlignWaysState getNoneSelected() {
     135        return noneSelected;
     136    }
    137137
    138         /**
    139         * @return the referenceSelected
    140         */
    141         public AlignWaysState getReferenceSelected() {
    142                 return referenceSelected;
    143         }
     138    /**
     139    * @return the referenceSelected
     140    */
     141    public AlignWaysState getReferenceSelected() {
     142        return referenceSelected;
     143    }
    144144
    145         /**
    146         * @return the aligneeSelected
    147         */
    148         public AlignWaysState getAligneeSelected() {
    149                 return aligneeSelected;
    150         }
     145    /**
     146    * @return the aligneeSelected
     147    */
     148    public AlignWaysState getAligneeSelected() {
     149        return aligneeSelected;
     150    }
    151151
    152         /**
    153         * @return the bothSelected
    154         */
    155         public AlignWaysState getBothSelected() {
    156                 return bothSelected;
    157         }
     152    /**
     153    * @return the bothSelected
     154    */
     155    public AlignWaysState getBothSelected() {
     156        return bothSelected;
     157    }
    158158
    159         /**
    160         * @return the current state
    161         */
    162         public AlignWaysState getCurrentState() {
    163                 return currentState;
    164         }
     159    /**
     160    * @return the current state
     161    */
     162    public AlignWaysState getCurrentState() {
     163        return currentState;
     164    }
    165165
    166         private void showTips() {
     166    private void showTips() {
    167167
    168                 AlignWaysTipsPanel atd = new AlignWaysTipsPanel();
    169                 Object[] okButton = {tr("I''m ready!")};
    170                 JOptionPane tipPane = new JOptionPane(atd, JOptionPane.PLAIN_MESSAGE, JOptionPane.DEFAULT_OPTION, null, okButton, okButton[0]);
    171                 // JDialog tipDialog = tipPane.createDialog(null, tr("AlignWays Tips"));
    172                 // Take Main.map as frame as it's better to inherit its icon than the default Java cup
    173                 JDialog tipDialog = tipPane.createDialog(Main.parent, tr("AlignWays Tips"));
    174                 // ((Frame)tipDialog.getOwner()).setIconImage(new ImageIcon(getClass().getResource("/images/blank.png")).getImage());
     168        AlignWaysTipsPanel atd = new AlignWaysTipsPanel();
     169        Object[] okButton = {tr("I''m ready!")};
     170        JOptionPane tipPane = new JOptionPane(atd, JOptionPane.PLAIN_MESSAGE, JOptionPane.DEFAULT_OPTION, null, okButton, okButton[0]);
     171        // JDialog tipDialog = tipPane.createDialog(null, tr("AlignWays Tips"));
     172        // Take Main.map as frame as it's better to inherit its icon than the default Java cup
     173        JDialog tipDialog = tipPane.createDialog(Main.parent, tr("AlignWays Tips"));
     174        // ((Frame)tipDialog.getOwner()).setIconImage(new ImageIcon(getClass().getResource("/images/blank.png")).getImage());
    175175
    176                 tipDialog.setResizable(true);
    177                 tipDialog.setVisible(true);
    178                 tipShown = true;
     176        tipDialog.setResizable(true);
     177        tipDialog.setVisible(true);
     178        tipShown = true;
    179179
    180                 tipDialog.dispose();
     180        tipDialog.dispose();
    181181
    182                 Main.pref.put("alignways.showtips", !atd.isChkBoxSelected());
     182        Main.pref.put("alignways.showtips", !atd.isChkBoxSelected());
    183183
    184         }
     184    }
    185185}
  • applications/editors/josm/plugins/colorscheme/src/at/dallermassl/josm/plugin/colorscheme/ColorSchemePlugin.java

    r19426 r23192  
    2020     */
    2121    public ColorSchemePlugin(PluginInformation info) {
    22         super(info);
     22        super(info);
    2323    }
    2424
  • applications/editors/josm/plugins/download_along/src/org/openstreetmap/josm/plugin/download_along/DownloadAlong.java

    r22427 r23192  
    4848  private static class DownloadAlongAction extends JosmAction {
    4949    /**
    50                  *
    51                 */
     50         *
     51        */
    5252    private static final long serialVersionUID = 1L;
    5353
     
    193193       * however we can only download rectangles, so the following is an attempt
    194194       * at finding a number of rectangles to download.
    195        * 
     195       *
    196196       * The idea is simply: Start out with the full bounding box. If it is too
    197197       * large, then split it in half and repeat recursively for each half until
  • applications/editors/josm/plugins/nearclick/src/nearclick/NearClickPlugin.java

    r19458 r23192  
    1313public class NearClickPlugin implements AWTEventListener {
    1414
    15         private int mouseDownX = -1;
    16         private int mouseDownY = -1;
    17         private long mouseDownTime = -1;
    18         private int radiussquared = 49;
    19         private int delay = 250;
     15    private int mouseDownX = -1;
     16    private int mouseDownY = -1;
     17    private long mouseDownTime = -1;
     18    private int radiussquared = 49;
     19    private int delay = 250;
    2020
    21         public NearClickPlugin(PluginInformation info) {
    22                 Toolkit.getDefaultToolkit().addAWTEventListener(this,
    23                                 AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK);
    24                 try {
    25                         int radius = Integer.parseInt(Main.pref
    26                                         .get("nearclick.radius", "7"));
    27                         radiussquared = radius * radius;
    28                         delay = Integer.parseInt(Main.pref.get("nearclick.delay", "250"));
    29                 } catch (NumberFormatException ex) {
    30                         delay = 250;
    31                         radiussquared = 7 * 7;
    32                 }
    33         }
     21    public NearClickPlugin(PluginInformation info) {
     22        Toolkit.getDefaultToolkit().addAWTEventListener(this,
     23                AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK);
     24        try {
     25            int radius = Integer.parseInt(Main.pref
     26                    .get("nearclick.radius", "7"));
     27            radiussquared = radius * radius;
     28            delay = Integer.parseInt(Main.pref.get("nearclick.delay", "250"));
     29        } catch (NumberFormatException ex) {
     30            delay = 250;
     31            radiussquared = 7 * 7;
     32        }
     33    }
    3434
    35         public void eventDispatched(AWTEvent event) {
    36                 if (event instanceof MouseEvent) {
    37                         MouseEvent e = (MouseEvent) event;
    38                         if (e.getButton() != MouseEvent.BUTTON1)
    39                                 return;
    40                         int xdiff = e.getPoint().x - mouseDownX;
    41                         int ydiff = e.getPoint().y - mouseDownY;
     35    public void eventDispatched(AWTEvent event) {
     36        if (event instanceof MouseEvent) {
     37            MouseEvent e = (MouseEvent) event;
     38            if (e.getButton() != MouseEvent.BUTTON1)
     39                return;
     40            int xdiff = e.getPoint().x - mouseDownX;
     41            int ydiff = e.getPoint().y - mouseDownY;
    4242
    43                         if (e.getID() == MouseEvent.MOUSE_RELEASED) {
    44                                 if (e.getWhen() - mouseDownTime < delay
    45                                                 && (e.getPoint().x != mouseDownX || e.getPoint().y != mouseDownY)
    46                                                 && xdiff * xdiff + ydiff * ydiff < radiussquared) {
    47                                         try {
    48                                                 Robot r = new Robot(GraphicsEnvironment
    49                                                                 .getLocalGraphicsEnvironment()
    50                                                                 .getDefaultScreenDevice());
    51                                                 r.mousePress(MouseEvent.BUTTON1_MASK);
    52                                                 r.mouseRelease(MouseEvent.BUTTON1_MASK);
    53                                         } catch (AWTException e1) {
    54                                         }
    55                                 }
    56                         }
    57                         if (e.getID() == MouseEvent.MOUSE_PRESSED) {
    58                                 mouseDownX = e.getPoint().x;
    59                                 mouseDownY = e.getPoint().y;
    60                                 mouseDownTime = e.getWhen();
    61                         }
    62                 }
    63         }
     43            if (e.getID() == MouseEvent.MOUSE_RELEASED) {
     44                if (e.getWhen() - mouseDownTime < delay
     45                        && (e.getPoint().x != mouseDownX || e.getPoint().y != mouseDownY)
     46                        && xdiff * xdiff + ydiff * ydiff < radiussquared) {
     47                    try {
     48                        Robot r = new Robot(GraphicsEnvironment
     49                                .getLocalGraphicsEnvironment()
     50                                .getDefaultScreenDevice());
     51                        r.mousePress(MouseEvent.BUTTON1_MASK);
     52                        r.mouseRelease(MouseEvent.BUTTON1_MASK);
     53                    } catch (AWTException e1) {
     54                    }
     55                }
     56            }
     57            if (e.getID() == MouseEvent.MOUSE_PRESSED) {
     58                mouseDownX = e.getPoint().x;
     59                mouseDownY = e.getPoint().y;
     60                mouseDownTime = e.getWhen();
     61            }
     62        }
     63    }
    6464}
  • applications/editors/josm/plugins/osmarender/src/org/openstreetmap/josm/plugins/osmarender/OsmarenderPlugin.java

    r21423 r23192  
    8080                        for (Node n : ((Way) p).getNodes()) {
    8181                            if (n.getCoor().isWithin(b))
    82                                 parents.add(n);
     82                                parents.add(n);
    8383                        }
    8484                    }
     
    8787                // Write ways
    8888                for (OsmPrimitive p: parents) {
    89                         if (p instanceof Way) {
    90                                 w.visit((Way)p);
    91                         }
     89                    if (p instanceof Way) {
     90                        w.visit((Way)p);
     91                    }
    9292                }
    9393
    9494                // Write relations (should be parent relation also written?)
    9595                for (OsmPrimitive p: parents) {
    96                         if (p instanceof Relation) {
    97                                 w.visit((Relation)p);
    98                         }
     96                    if (p instanceof Relation) {
     97                        w.visit((Relation)p);
     98                    }
    9999                }
    100100
     
    120120
    121121    public OsmarenderPlugin(PluginInformation info) throws IOException {
    122         super(info);
     122        super(info);
    123123        osmarenderMenu = MainMenu.add(Main.main.menu.viewMenu, new Action());
    124124        osmarenderMenu.setVisible(false);
  • applications/editors/josm/plugins/photo_geotagging/src/org/openstreetmap/josm/plugins/photo_geotagging/GeotaggingAction.java

    r22551 r23192  
    5050
    5151    public GeotaggingAction() {
    52         super(tr("Write coordinates to image header"), ImageProvider.get("geotagging"));
     52        super(tr("Write coordinates to image header"), ImageProvider.get("geotagging"));
    5353    }
    5454
    5555    public void actionPerformed(ActionEvent arg0) {
    5656
    57         GeoImageLayer layer = getLayer();
     57        GeoImageLayer layer = getLayer();
    5858
    5959        final List<ImageEntry> images = new ArrayList<ImageEntry>();
     
    316316
    317317    private GeoImageLayer getLayer() {
    318         return (GeoImageLayer)LayerListDialog.getInstance().getModel().getSelectedLayers().get(0);
     318        return (GeoImageLayer)LayerListDialog.getInstance().getModel().getSelectedLayers().get(0);
    319319    }
    320320
     
    330330    }
    331331
    332         public Component createMenuComponent() {
     332    public Component createMenuComponent() {
    333333        JMenuItem geotaggingItem = new JMenuItem(this);
    334334        geotaggingItem.setEnabled(enabled(getLayer()));
    335335        return geotaggingItem;
    336         }
    337 
    338         public boolean supportLayers(List<Layer> layers) {
    339                 return layers.size() == 1 && layers.get(0) instanceof GeoImageLayer;
    340         }
     336    }
     337
     338    public boolean supportLayers(List<Layer> layers) {
     339        return layers.size() == 1 && layers.get(0) instanceof GeoImageLayer;
     340    }
    341341}
  • applications/editors/josm/plugins/public_transport/src/public_transport/GTFSAddCommand.java

    r22148 r23192  
    1616  private GTFSStopTableModel gtfsStopTM = null;
    1717  private String type = null;
    18  
     18
    1919  public GTFSAddCommand(GTFSImporterAction controller)
    2020  {
     
    2323    workingLines = new Vector< Integer >();
    2424    typesForUndo = new Vector< String >();
    25    
     25
    2626    // use either selected lines or all lines if no line is selected
    2727    int[] selectedLines = controller.getDialog().getGTFSStopTable().getSelectedRows();
     
    3030    {
    3131      for (int i = 0; i < selectedLines.length; ++i)
    32         consideredLines.add(selectedLines[i]);
     32    consideredLines.add(selectedLines[i]);
    3333    }
    3434    else
    3535    {
    3636      for (int i = 0; i < gtfsStopTM.getRowCount(); ++i)
    37         consideredLines.add(new Integer(i));
     37    consideredLines.add(new Integer(i));
    3838    }
    39    
     39
    4040    // keep only lines where a node can be added
    4141    for (int i = 0; i < consideredLines.size(); ++i)
    4242    {
    4343      if (gtfsStopTM.nodes.elementAt(consideredLines.elementAt(i)) == null)
    44         workingLines.add(consideredLines.elementAt(i));
     44    workingLines.add(consideredLines.elementAt(i));
    4545    }
    4646  }
    47  
     47
    4848  public boolean executeCommand()
    4949  {
     
    6161    return true;
    6262  }
    63  
     63
    6464  public void undoCommand()
    6565  {
     
    7171      gtfsStopTM.setValueAt(typesForUndo.elementAt(i), j, 2);
    7272      if (node == null)
    73         continue;
     73    continue;
    7474      Main.main.getCurrentDataSet().removePrimitive(node);
    7575      node.setDeleted(true);
    7676    }
    7777  }
    78  
     78
    7979  public void fillModifiedData
    8080    (Collection< OsmPrimitive > modified, Collection< OsmPrimitive > deleted,
     
    8282  {
    8383  }
    84  
     84
    8585  @Override public JLabel getDescription()
    8686  {
  • applications/editors/josm/plugins/public_transport/src/public_transport/GTFSCatchCommand.java

    r22148 r23192  
    1818  private GTFSStopTableModel gtfsStopTM = null;
    1919  private String type = null;
    20  
     20
    2121  public GTFSCatchCommand(GTFSImporterAction controller)
    2222  {
    2323    gtfsStopTM = controller.getGTFSStopTableModel();
    2424    workingLines = new Vector< Integer >();
    25    
     25
    2626    // use either selected lines or all lines if no line is selected
    2727    int[] selectedLines = controller.getDialog().getGTFSStopTable().getSelectedRows();
     
    3030    workingLines.add(selectedLines[0]);
    3131  }
    32  
     32
    3333  public boolean executeCommand()
    3434  {
     
    4343      Node n = iter.next();
    4444      if ((n != null) && (n.equals(gtfsStopTM.nodes.elementAt(j))))
    45         continue;
     45    continue;
    4646      if (dest != null)
    47         return false;
     47    return false;
    4848      dest = n;
    4949    }
     
    5151      return false;
    5252    undoMapNode = new Node(dest);
    53    
     53
    5454    Node node = gtfsStopTM.nodes.elementAt(j);
    5555    undoTableNode = node;
     
    5959      node.setDeleted(true);
    6060    }
    61    
     61
    6262    dest.setCoor(gtfsStopTM.coors.elementAt(j));
    6363    dest.put("highway", "bus_stop");
     
    6969    type = (String)gtfsStopTM.getValueAt(j, 2);
    7070    gtfsStopTM.setValueAt("fed", j, 2);
    71    
     71
    7272    return true;
    7373  }
    74  
     74
    7575  public void undoCommand()
    7676  {
     
    7878      return;
    7979    int j = workingLines.elementAt(0);
    80    
     80
    8181    Node node = gtfsStopTM.nodes.elementAt(j);
    8282    if (node != null)
     
    8585      node.setDeleted(true);
    8686    }
    87    
     87
    8888    if (undoMapNode != null)
    8989    {
     
    9999    gtfsStopTM.setValueAt(type, j, 2);
    100100  }
    101  
     101
    102102  public void fillModifiedData
    103103    (Collection< OsmPrimitive > modified, Collection< OsmPrimitive > deleted,
     
    105105  {
    106106  }
    107  
     107
    108108  @Override public JLabel getDescription()
    109109  {
  • applications/editors/josm/plugins/public_transport/src/public_transport/GTFSDeleteCommand.java

    r22148 r23192  
    1616  private Vector< String > typesForUndo = null;
    1717  private GTFSStopTableModel gtfsStopTM = null;
    18  
     18
    1919  public GTFSDeleteCommand(GTFSImporterAction controller)
    2020  {
     
    2323    nodesForUndo = new Vector< Node >();
    2424    typesForUndo = new Vector< String >();
    25    
     25
    2626    // use either selected lines or all lines if no line is selected
    2727    int[] selectedLines = controller.getDialog().getGTFSStopTable().getSelectedRows();
     
    3030    {
    3131      for (int i = 0; i < selectedLines.length; ++i)
    32         consideredLines.add(selectedLines[i]);
     32    consideredLines.add(selectedLines[i]);
    3333    }
    3434    else
    3535    {
    3636      for (int i = 0; i < gtfsStopTM.getRowCount(); ++i)
    37         consideredLines.add(new Integer(i));
     37    consideredLines.add(new Integer(i));
    3838    }
    39    
     39
    4040    // keep only lines where a node can be added
    4141    for (int i = 0; i < consideredLines.size(); ++i)
    4242    {
    4343      if (gtfsStopTM.nodes.elementAt(consideredLines.elementAt(i)) != null)
    44         workingLines.add(consideredLines.elementAt(i));
     44    workingLines.add(consideredLines.elementAt(i));
    4545    }
    4646  }
    47  
     47
    4848  public boolean executeCommand()
    4949  {
     
    5757      typesForUndo.add((String)gtfsStopTM.getValueAt(j, 2));
    5858      if (node == null)
    59         continue;
     59    continue;
    6060      gtfsStopTM.nodes.set(j, null);
    6161      gtfsStopTM.setValueAt("skipped", j, 2);
     
    6565    return true;
    6666  }
    67  
     67
    6868  public void undoCommand()
    6969  {
     
    7575      gtfsStopTM.setValueAt(typesForUndo.elementAt(i), j, 2);
    7676      if (node == null)
    77         continue;
     77    continue;
    7878      node.setDeleted(false);
    7979      Main.main.getCurrentDataSet().addPrimitive(node);
    8080    }
    8181  }
    82  
     82
    8383  public void fillModifiedData
    8484    (Collection< OsmPrimitive > modified, Collection< OsmPrimitive > deleted,
     
    8686  {
    8787  }
    88  
     88
    8989  @Override public JLabel getDescription()
    9090  {
  • applications/editors/josm/plugins/public_transport/src/public_transport/GTFSImporterAction.java

    r23094 r23192  
    6363
    6464public class GTFSImporterAction extends JosmAction
    65 { 
     65{
    6666  private static GTFSImporterDialog dialog = null;
    6767  private static DefaultListModel tracksListModel = null;
     
    7070  private static GTFSStopTableModel gtfsStopTM = null;
    7171  public boolean inEvent = false;
    72  
     72
    7373  public GTFSImporterAction()
    7474  {
    7575    super(tr("Create Stops from GTFS ..."), null,
    76           tr("Create Stops from a GTFS file"), null, true);
     76      tr("Create Stops from a GTFS file"), null, true);
    7777  }
    7878
     
    8181    return gtfsStopTM;
    8282  }
    83  
     83
    8484  public GTFSImporterDialog getDialog()
    8585  {
     
    9393    return tracksListModel;
    9494  }
    95  
     95
    9696  public TrackReference getCurrentTrack()
    9797  {
     
    102102  {
    103103    DataSet mainDataSet = Main.main.getCurrentDataSet();
    104    
     104
    105105    if (dialog == null)
    106106      dialog = new GTFSImporterDialog(this);
    107    
     107
    108108    dialog.setVisible(true);
    109109
     
    113113      if (curDir.equals(""))
    114114      {
    115         curDir = ".";
     115    curDir = ".";
    116116      }
    117117      JFileChooser fc = new JFileChooser(new File(curDir));
    118       fc.setDialogTitle("Select GTFS file (stops.txt)"); 
     118      fc.setDialogTitle("Select GTFS file (stops.txt)");
    119119      fc.setMultiSelectionEnabled(false);
    120      
     120
    121121      int answer = fc.showOpenDialog(Main.parent);
    122122      if (answer != JFileChooser.APPROVE_OPTION)
    123         return;
    124      
     123    return;
     124
    125125      if (!fc.getCurrentDirectory().getAbsolutePath().equals(curDir))
    126         Main.pref.put("lastDirectory", fc.getCurrentDirectory().getAbsolutePath());
    127      
     126    Main.pref.put("lastDirectory", fc.getCurrentDirectory().getAbsolutePath());
     127
    128128      importData(fc.getSelectedFile());
    129      
     129
    130130      refreshData();
    131131    }
     
    133133    {
    134134      if ((!inEvent) && (dialog.gpsTimeStartValid()) && (currentTrack != null))
    135         Main.main.undoRedo.add(new TrackStoplistRelocateCommand(this));
     135    Main.main.undoRedo.add(new TrackStoplistRelocateCommand(this));
    136136    }
    137137    else if ("stopImporter.settingsStopwatchStart".equals(event.getActionCommand()))
    138138    {
    139139      if ((!inEvent) && (dialog.stopwatchStartValid()) && (currentTrack != null))
    140         Main.main.undoRedo.add(new TrackStoplistRelocateCommand(this));
     140    Main.main.undoRedo.add(new TrackStoplistRelocateCommand(this));
    141141    }
    142142    else if ("stopImporter.settingsTimeWindow".equals(event.getActionCommand()))
    143143    {
    144144      if (currentTrack != null)
    145         currentTrack.timeWindow = dialog.getTimeWindow();
     145    currentTrack.timeWindow = dialog.getTimeWindow();
    146146    }
    147147    else if ("stopImporter.settingsThreshold".equals(event.getActionCommand()))
    148148    {
    149149      if (currentTrack != null)
    150         currentTrack.threshold = dialog.getThreshold();
     150    currentTrack.threshold = dialog.getThreshold();
    151151    }
    152152    else if ("stopImporter.settingsSuggestStops".equals(event.getActionCommand()))
     
    181181  private void importData(final File file)
    182182  {
    183     try 
     183    try
    184184    {
    185185      FileReader is = new FileReader(file);
    186186      final BufferedReader r = new BufferedReader(is);
    187      
     187
    188188      if (data == null)
    189         data = new Vector< String >();
     189    data = new Vector< String >();
    190190      else
    191         data.clear();
    192      
     191    data.clear();
     192
    193193      while (r.ready())
    194         data.add(r.readLine());
    195     }
    196     catch (FileNotFoundException e) 
     194    data.add(r.readLine());
     195    }
     196    catch (FileNotFoundException e)
    197197    {
    198198      e.printStackTrace();
     
    211211    {
    212212      Vector< Node > existingStops = new Vector< Node >();
    213      
     213
    214214      if (Main.main.getCurrentDataSet() == null)
    215215      {
    216216        JOptionPane.showMessageDialog(null, "There exists no dataset."
    217             + " Try to download data from the server or open an OSM file.",
     217        + " Try to download data from the server or open an OSM file.",
    218218     "No data found", JOptionPane.ERROR_MESSAGE);
    219      
     219
    220220        System.out.println("Public Transport: StopInserter: No data found");
    221221
     
    224224      else
    225225      {
    226         Iterator< Node > iter =
    227             Main.main.getCurrentDataSet().getNodes().iterator();
    228         while (iter.hasNext())
    229         {
    230           Node node = iter.next();
    231           if ("bus_stop".equals(node.get("highway")))
    232             existingStops.add(node);
    233         }
    234       }
    235      
     226    Iterator< Node > iter =
     227        Main.main.getCurrentDataSet().getNodes().iterator();
     228    while (iter.hasNext())
     229    {
     230      Node node = iter.next();
     231      if ("bus_stop".equals(node.get("highway")))
     232        existingStops.add(node);
     233    }
     234      }
     235
    236236      Iterator< String > iter = data.iterator();
    237237      if (iter.hasNext())
    238         gtfsStopTM = new GTFSStopTableModel(this, iter.next());
     238    gtfsStopTM = new GTFSStopTableModel(this, iter.next());
    239239      else
    240240      {
    241         JOptionPane.showMessageDialog
    242         (null, "The GTFS file was empty.", "No data found",
    243         JOptionPane.ERROR_MESSAGE);
    244          
     241    JOptionPane.showMessageDialog
     242    (null, "The GTFS file was empty.", "No data found",
     243    JOptionPane.ERROR_MESSAGE);
     244
    245245        System.out.println("Public Transport: GTFSImporter: No data found");
    246246
    247247        return;
    248248      }
    249      
     249
    250250      while (iter.hasNext())
    251251      {
    252         String s = iter.next();
    253         gtfsStopTM.addRow(s, existingStops);
     252    String s = iter.next();
     253    gtfsStopTM.addRow(s, existingStops);
    254254      }
    255255      dialog.setGTFSStopTableModel(gtfsStopTM);
     
    260260      (null, "The GTFS file was empty.", "No data found",
    261261       JOptionPane.ERROR_MESSAGE);
    262      
     262
    263263      System.out.println("Public Transport: GTFSImporter: No data found");
    264264    }
    265265  }
    266  
     266
    267267//   public void tracksSelectionChanged(int selectedPos)
    268268//   {
     
    271271//       currentTrack = ((TrackReference)tracksListModel.elementAt(selectedPos));
    272272//       dialog.setTrackValid(true);
    273 //       
     273//
    274274//       //Prepare Settings
    275275//       dialog.setSettings
    276 //        (currentTrack.gpsSyncTime, currentTrack.stopwatchStart,
    277 //         currentTrack.timeWindow, currentTrack.threshold);
    278 //       
     276//    (currentTrack.gpsSyncTime, currentTrack.stopwatchStart,
     277//     currentTrack.timeWindow, currentTrack.threshold);
     278//
    279279//       //Prepare Stoplist
    280280//       dialog.setStoplistTableModel
     
    297297    {
    298298      JOptionPane.showMessageDialog(null, "There exists no dataset."
    299           + " Try to download data from the server or open an OSM file.",
     299      + " Try to download data from the server or open an OSM file.",
    300300   "No data found", JOptionPane.ERROR_MESSAGE);
    301      
     301
    302302      System.out.println("Public Transport: StopInserter: No data found");
    303            
     303
    304304      return null;
    305305    }
     
    317317    {
    318318      for (int i = 0; i < selectedLines.length; ++i)
    319         consideredLines.add(selectedLines[i]);
     319    consideredLines.add(selectedLines[i]);
    320320    }
    321321    else
    322322    {
    323323      for (int i = 0; i < table.getRowCount(); ++i)
    324         consideredLines.add(new Integer(i));
     324    consideredLines.add(new Integer(i));
    325325    }
    326326    return consideredLines;
     
    332332    if (Main.main.getCurrentDataSet() == null)
    333333      return;
    334      
     334
    335335    table.clearSelection();
    336      
     336
    337337    for (int i = 0; i < table.getRowCount(); ++i)
    338338    {
    339339      if ((nodes.elementAt(i) != null) &&
    340            (Main.main.getCurrentDataSet().isSelected(nodes.elementAt(i))))
    341         table.addRowSelectionInterval(i, i);
    342     }
    343   }
    344  
     340       (Main.main.getCurrentDataSet().isSelected(nodes.elementAt(i))))
     341    table.addRowSelectionInterval(i, i);
     342    }
     343  }
     344
    345345  /* shows the nodes that correspond to the marked lines in the table.
    346346     If no lines are marked in the table, show all nodes from the vector */
     
    353353      int j = consideredLines.elementAt(i);
    354354      if (nodes.elementAt(j) != null)
    355         nodes.elementAt(j).visit(box);
     355    nodes.elementAt(j).visit(box);
    356356    }
    357357    if (box.getBounds() == null)
     
    360360    Main.map.mapView.recalculateCenterScale(box);
    361361  }
    362  
     362
    363363  /* marks the nodes that correspond to the marked lines in the table.
    364364  If no lines are marked in the table, mark all nodes from the vector */
     
    372372      int j = consideredLines.elementAt(i);
    373373      if (nodes.elementAt(j) != null)
    374         Main.main.getCurrentDataSet().addSelected(nodes.elementAt(j));
    375     }
    376   }
    377  
     374    Main.main.getCurrentDataSet().addSelected(nodes.elementAt(j));
     375    }
     376  }
     377
    378378  public static String timeOf(double t)
    379379  {
    380380    t -= Math.floor(t/24/60/60)*24*60*60;
    381    
     381
    382382    int hour = (int)Math.floor(t/60/60);
    383383    t -=  Math.floor(t/60/60)*60*60;
     
    385385    t -=  Math.floor(t/60)*60;
    386386    double second = t;
    387    
     387
    388388    Format format = new DecimalFormat("00");
    389389    Format formatS = new DecimalFormat("00.###");
    390390    return (format.format(hour) + ":" + format.format(minute) + ":"
    391         + formatS.format(second));
    392   }
    393  
     391    + formatS.format(second));
     392  }
     393
    394394  public Action getFocusAddAction()
    395395  {
    396396    return new FocusAddAction();
    397397  }
    398  
     398
    399399  private class FocusAddAction extends AbstractAction
    400400  {
     
    405405    }
    406406  };
    407  
     407
    408408/*  public Action getFocusWaypointShelterAction(String shelter)
    409409  {
     
    417417      public void actionPerformed(ActionEvent e)
    418418      {
    419         JTable table = dialog.getWaypointsTable();
    420         int row = table.getEditingRow();
    421         if (row < 0)
    422           return;
    423         table.clearSelection();
    424         table.addRowSelectionInterval(row, row);
    425 /*      Main.main.undoRedo.add
    426             (new WaypointsDisableCommand(GTFSImporterAction.this));*
     419    JTable table = dialog.getWaypointsTable();
     420    int row = table.getEditingRow();
     421    if (row < 0)
     422      return;
     423    table.clearSelection();
     424    table.addRowSelectionInterval(row, row);
     425/*  Main.main.undoRedo.add
     426        (new WaypointsDisableCommand(GTFSImporterAction.this));*
    427427      }
    428428    };
     
    433433    return new FocusTrackStoplistNameAction();
    434434  }
    435  
     435
    436436  public Action getFocusTrackStoplistShelterAction(String shelter)
    437437  {
     
    445445      public void actionPerformed(ActionEvent e)
    446446      {
    447         JTable table = dialog.getStoplistTable();
    448         int row = table.getEditingRow();
    449         if (row < 0)
    450           return;
    451         table.clearSelection();
    452         table.addRowSelectionInterval(row, row);
    453 /*      Main.main.undoRedo.add
    454             (new TrackStoplistDeleteCommand(GTFSImporterAction.this));*
     447    JTable table = dialog.getStoplistTable();
     448    int row = table.getEditingRow();
     449    if (row < 0)
     450      return;
     451    table.clearSelection();
     452    table.addRowSelectionInterval(row, row);
     453/*  Main.main.undoRedo.add
     454        (new TrackStoplistDeleteCommand(GTFSImporterAction.this));*
    455455      }
    456456    };
     
    466466      int row = table.getEditingRow();
    467467      if (row < 0)
    468         row = 0;
     468    row = 0;
    469469      waypointTM.inEvent = true;
    470470      if (table.getCellEditor() != null)
    471471      {
    472         if (!table.getCellEditor().stopCellEditing())
    473           table.getCellEditor().cancelCellEditing();
     472    if (!table.getCellEditor().stopCellEditing())
     473      table.getCellEditor().cancelCellEditing();
    474474      }
    475475      table.editCellAt(row, 1);
    476476      table.getCellEditor().getTableCellEditorComponent
    477           (table, "", true, row, 1);
     477      (table, "", true, row, 1);
    478478      waypointTM.inEvent = false;
    479479    }
    480480  };
    481  
     481
    482482  private class FocusWaypointShelterAction extends AbstractAction
    483483  {
    484484    private String defaultShelter = null;
    485    
     485
    486486    public FocusWaypointShelterAction(String defaultShelter)
    487487    {
    488488      this.defaultShelter = defaultShelter;
    489489    }
    490    
     490
    491491    public void actionPerformed(ActionEvent e)
    492492    {
     
    496496      int row = table.getEditingRow();
    497497      if (row < 0)
    498         row = 0;
     498    row = 0;
    499499      waypointTM.inEvent = true;
    500500      if (table.getCellEditor() != null)
    501501      {
    502         if (!table.getCellEditor().stopCellEditing())
    503           table.getCellEditor().cancelCellEditing();
     502    if (!table.getCellEditor().stopCellEditing())
     503      table.getCellEditor().cancelCellEditing();
    504504      }
    505505      table.editCellAt(row, 2);
     
    509509    }
    510510  };
    511  
     511
    512512  private class FocusTrackStoplistNameAction extends AbstractAction
    513513  {
     
    519519      int row = table.getEditingRow();
    520520      if (row < 0)
    521         row = 0;
     521    row = 0;
    522522      currentTrack.inEvent = true;
    523523      if (table.getCellEditor() != null)
    524524      {
    525         if (!table.getCellEditor().stopCellEditing())
    526           table.getCellEditor().cancelCellEditing();
     525    if (!table.getCellEditor().stopCellEditing())
     526      table.getCellEditor().cancelCellEditing();
    527527      }
    528528      table.editCellAt(row, 1);
     
    532532    }
    533533  };
    534  
     534
    535535  private class FocusTrackStoplistShelterAction extends AbstractAction
    536536  {
    537537    private String defaultShelter = null;
    538    
     538
    539539    public FocusTrackStoplistShelterAction(String defaultShelter)
    540540    {
    541541      this.defaultShelter = defaultShelter;
    542542    }
    543    
     543
    544544    public void actionPerformed(ActionEvent e)
    545545    {
     
    549549      int row = table.getEditingRow();
    550550      if (row < 0)
    551         row = 0;
     551    row = 0;
    552552      currentTrack.inEvent = true;
    553553      if (table.getCellEditor() != null)
    554554      {
    555         if (!table.getCellEditor().stopCellEditing())
    556           table.getCellEditor().cancelCellEditing();
     555    if (!table.getCellEditor().stopCellEditing())
     556      table.getCellEditor().cancelCellEditing();
    557557      }
    558558      table.editCellAt(row, 2);
  • applications/editors/josm/plugins/public_transport/src/public_transport/GTFSImporterDialog.java

    r22148 r23192  
    6363
    6464public class GTFSImporterDialog
    65 { 
     65{
    6666  private JDialog jDialog = null;
    6767  private JTabbedPane tabbedPane = null;
     
    7474  private JTable stoplistTable = null;
    7575  private JTable gtfsStopTable = null;
    76  
     76
    7777  public GTFSImporterDialog(GTFSImporterAction controller)
    7878  {
     
    8787    tabbedPane.setEnabledAt(1, true);
    8888    jDialog.add(tabbedPane);
    89      
     89
    9090    //Settings Tab
    9191    JPanel contentPane = tabSettings;
     
    9393    GridBagConstraints layoutCons = new GridBagConstraints();
    9494    contentPane.setLayout(gridbag);
    95      
     95
    9696    JLabel label = new JLabel("Type of stops to add");
    97      
     97
    9898    layoutCons.gridx = 0;
    9999    layoutCons.gridy = 0;
     
    104104    gridbag.setConstraints(label, layoutCons);
    105105    contentPane.add(label);
    106    
     106
    107107    cbStoptype = new JComboBox();
    108108    cbStoptype.setEditable(false);
     
    114114    cbStoptype.setActionCommand("gtfsImporter.settingsStoptype");
    115115    cbStoptype.addActionListener(controller);
    116    
     116
    117117    layoutCons.gridx = 0;
    118118    layoutCons.gridy = 1;
     
    123123    gridbag.setConstraints(cbStoptype, layoutCons);
    124124    contentPane.add(cbStoptype);
    125      
     125
    126126    label = new JLabel("Time on your GPS device");
    127      
     127
    128128    layoutCons.gridx = 0;
    129129    layoutCons.gridy = 2;
     
    134134    gridbag.setConstraints(label, layoutCons);
    135135    contentPane.add(label);
    136      
     136
    137137    tfGPSTimeStart = new JTextField("00:00:00", 15);
    138138    tfGPSTimeStart.setActionCommand("gtfsImporter.settingsGPSTimeStart");
    139139    tfGPSTimeStart.addActionListener(controller);
    140      
     140
    141141    layoutCons.gridx = 0;
    142142    layoutCons.gridy = 3;
     
    147147    gridbag.setConstraints(tfGPSTimeStart, layoutCons);
    148148    contentPane.add(tfGPSTimeStart);
    149      
     149
    150150    label = new JLabel("HH:MM:SS.sss");
    151      
     151
    152152    layoutCons.gridx = 1;
    153153    layoutCons.gridy = 3;
     
    158158    gridbag.setConstraints(label, layoutCons);
    159159    contentPane.add(label);
    160            
     160
    161161    label = new JLabel("Time on your stopwatch");
    162      
     162
    163163    layoutCons.gridx = 0;
    164164    layoutCons.gridy = 4;
     
    169169    gridbag.setConstraints(label, layoutCons);
    170170    contentPane.add(label);
    171      
     171
    172172    tfStopwatchStart = new JTextField("00:00:00", 15);
    173173    tfStopwatchStart.setActionCommand("gtfsImporter.settingsStopwatchStart");
    174174    tfStopwatchStart.addActionListener(controller);
    175      
     175
    176176    layoutCons.gridx = 0;
    177177    layoutCons.gridy = 5;
     
    182182    gridbag.setConstraints(tfStopwatchStart, layoutCons);
    183183    contentPane.add(tfStopwatchStart);
    184      
     184
    185185    label = new JLabel("HH:MM:SS.sss");
    186      
     186
    187187    layoutCons.gridx = 1;
    188188    layoutCons.gridy = 5;
     
    193193    gridbag.setConstraints(label, layoutCons);
    194194    contentPane.add(label);
    195      
     195
    196196    label = new JLabel("Time window");
    197      
     197
    198198    layoutCons.gridx = 0;
    199199    layoutCons.gridy = 6;
     
    204204    gridbag.setConstraints(label, layoutCons);
    205205    contentPane.add(label);
    206      
     206
    207207    tfTimeWindow = new JTextField("15", 4);
    208208    tfTimeWindow.setActionCommand("gtfsImporter.settingsTimeWindow");
    209209    tfTimeWindow.addActionListener(controller);
    210      
     210
    211211    layoutCons.gridx = 0;
    212212    layoutCons.gridy = 7;
     
    217217    gridbag.setConstraints(tfTimeWindow, layoutCons);
    218218    contentPane.add(tfTimeWindow);
    219      
     219
    220220    label = new JLabel("seconds");
    221      
     221
    222222    layoutCons.gridx = 1;
    223223    layoutCons.gridy = 7;
     
    228228    gridbag.setConstraints(label, layoutCons);
    229229    contentPane.add(label);
    230      
     230
    231231    label = new JLabel("Move Threshold");
    232      
     232
    233233    layoutCons.gridx = 0;
    234234    layoutCons.gridy = 8;
     
    239239    gridbag.setConstraints(label, layoutCons);
    240240    contentPane.add(label);
    241      
     241
    242242    tfThreshold = new JTextField("20", 4);
    243243    tfThreshold.setActionCommand("gtfsImporter.settingsThreshold");
    244244    tfThreshold.addActionListener(controller);
    245      
     245
    246246    layoutCons.gridx = 0;
    247247    layoutCons.gridy = 9;
     
    252252    gridbag.setConstraints(tfThreshold, layoutCons);
    253253    contentPane.add(tfThreshold);
    254      
     254
    255255    label = new JLabel("meters");
    256      
     256
    257257    layoutCons.gridx = 1;
    258258    layoutCons.gridy = 9;
     
    263263    gridbag.setConstraints(label, layoutCons);
    264264    contentPane.add(label);
    265      
     265
    266266    JButton bSuggestStops = new JButton("Suggest Stops");
    267267    bSuggestStops.setActionCommand("gtfsImporter.settingsSuggestStops");
    268268    bSuggestStops.addActionListener(controller);
    269      
     269
    270270    layoutCons.gridx = 0;
    271271    layoutCons.gridy = 10;
     
    276276    gridbag.setConstraints(bSuggestStops, layoutCons);
    277277    contentPane.add(bSuggestStops);
    278      
     278
    279279    //Waypoints Tab
    280280    contentPane = tabWaypoints;
     
    285285        (KeyStroke.getKeyStroke("alt N"), "gtfsImporter.gtfsStopsFocusAdd");
    286286    contentPane.getActionMap().put
    287         ("gtfsImporter.gtfsStopsFocusAdd", controller.getFocusAddAction());
     287    ("gtfsImporter.gtfsStopsFocusAdd", controller.getFocusAddAction());
    288288/*    contentPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put
    289289        (KeyStroke.getKeyStroke("alt S"), "gtfsImporter.focusShelterYes");
    290290    contentPane.getActionMap().put
    291         ("gtfsImporter.focusShelterYes",
    292         controller.getFocusWaypointShelterAction("yes"));
     291    ("gtfsImporter.focusShelterYes",
     292    controller.getFocusWaypointShelterAction("yes"));
    293293    contentPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put
    294294        (KeyStroke.getKeyStroke("alt T"), "gtfsImporter.focusShelterNo");
    295295    contentPane.getActionMap().put
    296         ("gtfsImporter.focusShelterNo",
    297         controller.getFocusWaypointShelterAction("no"));
     296    ("gtfsImporter.focusShelterNo",
     297    controller.getFocusWaypointShelterAction("no"));
    298298    contentPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put
    299299        (KeyStroke.getKeyStroke("alt U"), "gtfsImporter.focusShelterImplicit");
    300300    contentPane.getActionMap().put
    301         ("gtfsImporter.focusShelterImplicit",
    302         controller.getFocusWaypointShelterAction("implicit"));
     301    ("gtfsImporter.focusShelterImplicit",
     302    controller.getFocusWaypointShelterAction("implicit"));
    303303    contentPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put
    304304        (KeyStroke.getKeyStroke("alt D"), "gtfsImporter.gtfsStopsDelete");
    305305    contentPane.getActionMap().put
    306         ("gtfsImporter.gtfsStopsDelete",
    307         controller.getFocusWaypointDeleteAction());*/
    308      
     306    ("gtfsImporter.gtfsStopsDelete",
     307    controller.getFocusWaypointDeleteAction());*/
     308
    309309    gtfsStopTable = new JTable();
    310310    JScrollPane tableSP = new JScrollPane(gtfsStopTable);
    311    
     311
    312312    layoutCons.gridx = 0;
    313313    layoutCons.gridy = 0;
     
    318318    gridbag.setConstraints(tableSP, layoutCons);
    319319    contentPane.add(tableSP);
    320      
     320
    321321    JButton bFind = new JButton("Find");
    322322    bFind.setActionCommand("gtfsImporter.gtfsStopsFind");
    323323    bFind.addActionListener(controller);
    324      
     324
    325325    layoutCons.gridx = 0;
    326326    layoutCons.gridy = 1;
     
    331331    gridbag.setConstraints(bFind, layoutCons);
    332332    contentPane.add(bFind);
    333      
     333
    334334    JButton bShow = new JButton("Show");
    335335    bShow.setActionCommand("gtfsImporter.gtfsStopsShow");
    336336    bShow.addActionListener(controller);
    337      
     337
    338338    layoutCons.gridx = 0;
    339339    layoutCons.gridy = 2;
     
    344344    gridbag.setConstraints(bShow, layoutCons);
    345345    contentPane.add(bShow);
    346      
     346
    347347    JButton bMark = new JButton("Mark");
    348348    bMark.setActionCommand("gtfsImporter.gtfsStopsMark");
    349349    bMark.addActionListener(controller);
    350      
     350
    351351    layoutCons.gridx = 1;
    352352    layoutCons.gridy = 1;
     
    358358    gridbag.setConstraints(bMark, layoutCons);
    359359    contentPane.add(bMark);
    360      
     360
    361361    JButton bCatch = new JButton("Catch");
    362362    bCatch.setActionCommand("gtfsImporter.gtfsStopsCatch");
    363363    bCatch.addActionListener(controller);
    364      
     364
    365365    layoutCons.gridx = 2;
    366366    layoutCons.gridy = 1;
     
    372372    gridbag.setConstraints(bCatch, layoutCons);
    373373    contentPane.add(bCatch);
    374      
     374
    375375    JButton bJoin = new JButton("Join");
    376376    bJoin.setActionCommand("gtfsImporter.gtfsStopsJoin");
    377377    bJoin.addActionListener(controller);
    378      
     378
    379379    layoutCons.gridx = 2;
    380380    layoutCons.gridy = 2;
     
    386386    gridbag.setConstraints(bJoin, layoutCons);
    387387    contentPane.add(bJoin);
    388      
     388
    389389    JButton bAdd = new JButton("Enable");
    390390    bAdd.setActionCommand("gtfsImporter.gtfsStopsAdd");
    391391    bAdd.addActionListener(controller);
    392      
     392
    393393    layoutCons.gridx = 3;
    394394    layoutCons.gridy = 1;
     
    400400    gridbag.setConstraints(bAdd, layoutCons);
    401401    contentPane.add(bAdd);
    402      
     402
    403403    JButton bDelete = new JButton("Disable");
    404404    bDelete.setActionCommand("gtfsImporter.gtfsStopsDelete");
    405405    bDelete.addActionListener(controller);
    406      
     406
    407407    layoutCons.gridx = 3;
    408408    layoutCons.gridy = 2;
     
    413413    gridbag.setConstraints(bDelete, layoutCons);
    414414    contentPane.add(bDelete);
    415      
     415
    416416    jDialog.pack();
    417417    jDialog.setLocationRelativeTo(frame);
    418418  }
    419  
     419
    420420  public void setTrackValid(boolean valid)
    421421  {
    422422    tabbedPane.setEnabledAt(2, valid);
    423423  }
    424  
     424
    425425  public void setVisible(boolean visible)
    426426  {
    427427    jDialog.setVisible(visible);
    428428  }
    429  
     429
    430430  public void setSettings
    431431      (String gpsSyncTime, String stopwatchStart,
     
    437437    tfThreshold.setText(Double.toString(threshold));
    438438  }
    439  
     439
    440440  public String getStoptype()
    441441  {
    442442    return (String)cbStoptype.getSelectedItem();
    443443  }
    444  
     444
    445445  public boolean gpsTimeStartValid()
    446446  {
     
    452452    {
    453453      JOptionPane.showMessageDialog
    454           (null, "Can't parse a time from this string.", "Invalid value",
    455            JOptionPane.ERROR_MESSAGE);
     454      (null, "Can't parse a time from this string.", "Invalid value",
     455       JOptionPane.ERROR_MESSAGE);
    456456      return false;
    457457    }
    458458  }
    459  
     459
    460460  public String getGpsTimeStart()
    461461  {
    462462    return tfGPSTimeStart.getText();
    463463  }
    464  
     464
    465465  public void setGpsTimeStart(String s)
    466466  {
    467467    tfGPSTimeStart.setText(s);
    468468  }
    469  
     469
    470470  public boolean stopwatchStartValid()
    471471  {
     
    477477    {
    478478      JOptionPane.showMessageDialog
    479           (null, "Can't parse a time from this string.", "Invalid value",
    480            JOptionPane.ERROR_MESSAGE);
     479      (null, "Can't parse a time from this string.", "Invalid value",
     480       JOptionPane.ERROR_MESSAGE);
    481481      return false;
    482482    }
    483483  }
    484  
     484
    485485  public String getStopwatchStart()
    486486  {
    487487    return tfStopwatchStart.getText();
    488488  }
    489  
     489
    490490  public void setStopwatchStart(String s)
    491491  {
    492492    tfStopwatchStart.setText(s);
    493493  }
    494  
     494
    495495  public double getTimeWindow()
    496496  {
    497497    return Double.parseDouble(tfTimeWindow.getText());
    498498  }
    499  
     499
    500500  public double getThreshold()
    501501  {
    502502    return Double.parseDouble(tfThreshold.getText());
    503503  }
    504  
     504
    505505  public JTable getGTFSStopTable()
    506506  {
    507507    return gtfsStopTable;
    508508  }
    509  
     509
    510510  public void setGTFSStopTableModel(GTFSStopTableModel model)
    511511  {
     
    516516    gtfsStopTable.getColumnModel().getColumn(2).setPreferredWidth((int)(width * 0.1));
    517517  }
    518  
     518
    519519  public static double parseTime(String s)
    520520  {
    521521    double result = 0;
    522522    if ((s.charAt(2) != ':') || (s.charAt(2) != ':')
    523         || (s.length() < 8))
     523    || (s.length() < 8))
    524524      return -1;
    525525    int hour = Integer.parseInt(s.substring(0, 2));
     
    527527    double second = Double.parseDouble(s.substring(6, s.length()));
    528528    if ((hour < 0) || (hour > 23) || (minute < 0) || (minute > 59)
    529         || (second < 0) || (second >= 60.0))
     529    || (second < 0) || (second >= 60.0))
    530530      return -1;
    531531    return (second + minute*60 + hour*60*60);
    532532  }
    533  
     533
    534534/*  private class TracksLSL implements ListSelectionListener
    535535  {
    536536    GTFSImporterAction root = null;
    537    
     537
    538538    public TracksLSL(GTFSImporterAction sia)
    539539    {
    540540      root = sia;
    541541    }
    542    
     542
    543543    public void valueChanged(ListSelectionEvent e)
    544544    {
    545545      int selectedPos = tracksList.getAnchorSelectionIndex();
    546546      if (tracksList.isSelectedIndex(selectedPos))
    547         root.tracksSelectionChanged(selectedPos);
     547    root.tracksSelectionChanged(selectedPos);
    548548      else
    549         root.tracksSelectionChanged(-1);
     549    root.tracksSelectionChanged(-1);
    550550    }
    551551  };*/
  • applications/editors/josm/plugins/public_transport/src/public_transport/GTFSJoinCommand.java

    r22148 r23192  
    1818  private GTFSStopTableModel gtfsStopTM = null;
    1919  private String type = null;
    20  
     20
    2121  public GTFSJoinCommand(GTFSImporterAction controller)
    2222  {
    2323    gtfsStopTM = controller.getGTFSStopTableModel();
    2424    workingLines = new Vector< Integer >();
    25    
     25
    2626    // use either selected lines or all lines if no line is selected
    2727    int[] selectedLines = controller.getDialog().getGTFSStopTable().getSelectedRows();
     
    3030    workingLines.add(selectedLines[0]);
    3131  }
    32  
     32
    3333  public boolean executeCommand()
    3434  {
     
    4343      Node n = iter.next();
    4444      if ((n != null) && (n.equals(gtfsStopTM.nodes.elementAt(j))))
    45         continue;
     45    continue;
    4646      if (dest != null)
    47         return false;
     47    return false;
    4848      dest = n;
    4949    }
     
    5151      return false;
    5252    undoMapNode = new Node(dest);
    53    
     53
    5454    Node node = gtfsStopTM.nodes.elementAt(j);
    5555    undoTableNode = node;
     
    5959      node.setDeleted(true);
    6060    }
    61    
     61
    6262    dest.put("highway", "bus_stop");
    6363    dest.put("stop_id", (String)gtfsStopTM.getValueAt(j, 0));
     
    6767    type = (String)gtfsStopTM.getValueAt(j, 2);
    6868    gtfsStopTM.setValueAt("moved", j, 2);
    69    
     69
    7070    return true;
    7171  }
    72  
     72
    7373  public void undoCommand()
    7474  {
     
    7676      return;
    7777    int j = workingLines.elementAt(0);
    78    
     78
    7979    Node node = gtfsStopTM.nodes.elementAt(j);
    8080    if (node != null)
     
    8383      node.setDeleted(true);
    8484    }
    85    
     85
    8686    if (undoMapNode != null)
    8787    {
     
    9797    gtfsStopTM.setValueAt(type, j, 2);
    9898  }
    99  
     99
    100100  public void fillModifiedData
    101101    (Collection< OsmPrimitive > modified, Collection< OsmPrimitive > deleted,
     
    103103  {
    104104  }
    105  
     105
    106106  @Override public JLabel getDescription()
    107107  {
  • applications/editors/josm/plugins/public_transport/src/public_transport/GTFSStopTableModel.java

    r23095 r23192  
    2727  private int lonCol = -1;
    2828  private char separator = ',';
    29  
     29
    3030  public GTFSStopTableModel(GTFSImporterAction controller,
    31                             String columnConfig)
     31                String columnConfig)
    3232  {
    3333    int pos = columnConfig.indexOf(separator);
     
    4848      String title = columnConfig.substring(oldPos, pos);
    4949      if ("stop_id".equals(title))
    50         idCol = i;
     50    idCol = i;
    5151      else if ("stop_name".equals(title))
    52         nameCol = i;
     52    nameCol = i;
    5353      else if ("stop_lat".equals(title))
    54         latCol = i;
     54    latCol = i;
    5555      else if ("stop_lon".equals(title))
    56         lonCol = i;
     56    lonCol = i;
    5757      ++i;
    5858      oldPos = pos + 1;
     
    6868    else if ("stop_lon".equals(title))
    6969      lonCol = i;
    70    
     70
    7171    this.controller = controller;
    7272    addColumn("Id");
     
    7575    addTableModelListener(this);
    7676  }
    77    
     77
    7878  public boolean isCellEditable(int row, int column)
    7979  {
    8080    return false;
    8181  }
    82    
     82
    8383  public void addRow(Object[] obj)
    8484  {
    8585    throw new UnsupportedOperationException();
    8686  }
    87    
     87
    8888  public void insertRow(int insPos, Object[] obj)
    8989  {
    9090    throw new UnsupportedOperationException();
    9191  }
    92    
     92
    9393  public void addRow(String s)
    9494  {
    9595    insertRow(-1, s, new Vector< Node >());
    9696  }
    97  
     97
    9898  public void addRow(String s, Vector< Node > existingStops)
    9999  {
     
    135135    return s;
    136136  }
    137  
     137
    138138  public void insertRow(int insPos, String s, Vector< Node > existingStops)
    139139  {
     
    147147    {
    148148      if (i == idCol)
    149         buf[0] = stripQuot(s.substring(oldPos, pos));
     149    buf[0] = stripQuot(s.substring(oldPos, pos));
    150150      else if (i == nameCol)
    151         buf[1] = stripQuot(s.substring(oldPos, pos));
     151    buf[1] = stripQuot(s.substring(oldPos, pos));
    152152      else if (i == latCol)
    153         lat = Double.parseDouble(stripQuot(s.substring(oldPos, pos)));
     153    lat = Double.parseDouble(stripQuot(s.substring(oldPos, pos)));
    154154      else if (i == lonCol)
    155         lon = Double.parseDouble(stripQuot(s.substring(oldPos, pos)));
     155    lon = Double.parseDouble(stripQuot(s.substring(oldPos, pos)));
    156156      ++i;
    157157      oldPos = pos + 1;
     
    166166    else if (i == lonCol)
    167167      lon = Double.parseDouble(stripQuot(s.substring(oldPos)));
    168    
     168
    169169    LatLon coor = new LatLon(lat, lon);
    170    
     170
    171171    if (Main.main.getCurrentDataSet() != null)
    172172    {
     
    176176      while (iter.hasNext())
    177177      {
    178         if (iter.next().bounds.contains(coor))
    179         {
    180           inside = true;
    181           break;
    182         }
     178    if (iter.next().bounds.contains(coor))
     179    {
     180      inside = true;
     181      break;
     182    }
    183183      }
    184184      if (!inside)
    185         buf[2] = "outside";
    186     }
    187    
     185    buf[2] = "outside";
     186    }
     187
    188188    boolean nearBusStop = false;
    189189    Iterator< Node > iter = existingStops.iterator();
     
    193193      if (coor.greatCircleDistance(node.getCoor()) < 1000)
    194194      {
    195         nearBusStop = true;
    196         break;
    197       }
    198     }
    199    
     195    nearBusStop = true;
     196    break;
     197      }
     198    }
     199
    200200    if (insPos == -1)
    201201    {
    202202      if ((nearBusStop) || !("pending".equals(buf[2])))
    203         nodes.addElement(null);
     203    nodes.addElement(null);
    204204      else
    205205      {
    206         Node node = GTFSImporterAction.createNode(coor, buf[0], buf[1]);
    207         nodes.addElement(node);
    208         buf[2] = "added";
     206    Node node = GTFSImporterAction.createNode(coor, buf[0], buf[1]);
     207    nodes.addElement(node);
     208    buf[2] = "added";
    209209      }
    210210      coors.addElement(coor);
     
    214214    {
    215215      if ((nearBusStop) || !("pending".equals(buf[2])))
    216         nodes.insertElementAt(null, insPos);
     216    nodes.insertElementAt(null, insPos);
    217217      else
    218218      {
    219         Node node = GTFSImporterAction.createNode(coor, buf[0], buf[1]);
    220         nodes.insertElementAt(node, insPos);
    221         buf[2] = "added";
     219    Node node = GTFSImporterAction.createNode(coor, buf[0], buf[1]);
     220    nodes.insertElementAt(node, insPos);
     221    buf[2] = "added";
    222222      }
    223223      coors.insertElementAt(coor, insPos);
     
    225225    }
    226226  }
    227    
     227
    228228  public void clear()
    229229  {
     
    231231    super.setRowCount(0);
    232232  }
    233  
     233
    234234  public void tableChanged(TableModelEvent e)
    235235  {
  • applications/editors/josm/plugins/public_transport/src/public_transport/ItineraryTableModel.java

    r20895 r23192  
    33// import static org.openstreetmap.josm.tools.I18n.marktr;
    44// import static org.openstreetmap.josm.tools.I18n.tr;
    5 // 
     5//
    66// import java.awt.BorderLayout;
    77// import java.awt.Container;
     
    2121// import java.util.TreeSet;
    2222import java.util.Vector;
    23 // 
     23//
    2424// import javax.swing.DefaultCellEditor;
    2525// import javax.swing.DefaultListModel;
     
    4343import javax.swing.table.DefaultTableModel;
    4444// import javax.swing.table.TableCellEditor;
    45 // 
     45//
    4646// import org.openstreetmap.josm.Main;
    4747// import org.openstreetmap.josm.actions.JosmAction;
     
    6464  public Vector<Way> ways = new Vector<Way>();
    6565  public boolean inEvent = false;
    66  
     66
    6767  public boolean isCellEditable(int row, int column)
    6868  {
     
    7373    return true;
    7474  }
    75  
     75
    7676  public void addRow(Object[] obj)
    7777  {
     
    7979    super.addRow(obj);
    8080  }
    81  
     81
    8282  public void insertRow(int insPos, Object[] obj)
    8383  {
     
    9393    }
    9494  }
    95  
     95
    9696  public void addRow(Way way, String role)
    9797  {
    9898    insertRow(-1, way, role);
    9999  }
    100  
     100
    101101  public void insertRow(int insPos, Way way, String role)
    102102  {
     
    123123    }
    124124  }
    125  
     125
    126126  public void clear()
    127127  {
     
    129129    super.setRowCount(0);
    130130  }
    131  
     131
    132132  public void cleanupGaps()
    133133  {
    134134    inEvent = true;
    135135    Node lastNode = null;
    136    
     136
    137137    for (int i = 0; i < getRowCount(); ++i)
    138138    {
    139139      if (ways.elementAt(i) == null)
    140140      {
    141         ++i;
    142         if (i >= getRowCount())
    143           break;
     141    ++i;
     142    if (i >= getRowCount())
     143      break;
    144144      }
    145145      while ((ways.elementAt(i) == null) &&
    146         ((i == 0) || (ways.elementAt(i-1) == null)))
    147       {
    148         ways.removeElementAt(i);
    149         removeRow(i);
    150         if (i >= getRowCount())
    151           break;
     146    ((i == 0) || (ways.elementAt(i-1) == null)))
     147      {
     148    ways.removeElementAt(i);
     149    removeRow(i);
     150    if (i >= getRowCount())
     151      break;
    152152      }
    153153      if (i >= getRowCount())
    154         break;
    155      
     154    break;
     155
    156156      boolean gapRequired = gapNecessary
    157157      (ways.elementAt(i), (String)(getValueAt(i, 1)), lastNode);
    158158      if ((i > 0) && (!gapRequired) && (ways.elementAt(i-1) == null))
    159159      {
    160         ways.removeElementAt(i-1);
    161         removeRow(i-1);
    162         --i;
     160    ways.removeElementAt(i-1);
     161    removeRow(i-1);
     162    --i;
    163163      }
    164164      else if ((i > 0) && gapRequired && (ways.elementAt(i-1) != null))
    165165      {
    166         String[] buf = { "", "" };
    167         buf[0] = "[gap]";
    168         insertRow(i, buf);
    169         ++i;
     166    String[] buf = { "", "" };
     167    buf[0] = "[gap]";
     168    insertRow(i, buf);
     169    ++i;
    170170      }
    171171      lastNode = getLastNode(ways.elementAt(i), (String)(getValueAt(i, 1)));
     
    179179    inEvent = false;
    180180  }
    181  
     181
    182182  public void tableChanged(TableModelEvent e)
    183183  {
     
    185185    {
    186186      if (inEvent)
    187         return;
     187    return;
    188188      cleanupGaps();
    189189      RoutePatternAction.rebuildWays();
    190190    }
    191191  }
    192  
     192
    193193  private Node getLastNode(Way way, String role)
    194194  {
     
    200200      return way.getNode(0);
    201201      else
    202         return way.getNode(way.getNodesCount() - 1);
    203     }
    204   }
    205  
     202    return way.getNode(way.getNodesCount() - 1);
     203    }
     204  }
     205
    206206  private boolean gapNecessary(Way way, String role, Node lastNode)
    207207  {
     
    212212      firstNode = way.getNode(way.getNodesCount() - 1);
    213213      else
    214         firstNode = way.getNode(0);
     214    firstNode = way.getNode(0);
    215215      if ((lastNode != null) && (!lastNode.equals(firstNode)))
    216         return true;
     216    return true;
    217217    }
    218218    return false;
  • applications/editors/josm/plugins/public_transport/src/public_transport/PublicTransportPlugin.java

    r22148 r23192  
    2323
    2424public class PublicTransportPlugin extends Plugin {
    25    
     25
    2626  static JMenu jMenu;
    2727
  • applications/editors/josm/plugins/public_transport/src/public_transport/RoutePatternAction.java

    r21867 r23192  
    6060
    6161public class RoutePatternAction extends JosmAction {
    62  
     62
    6363  private class RoutesLSL implements ListSelectionListener {
    6464    RoutePatternAction root = null;
    65    
     65
    6666    public RoutesLSL(RoutePatternAction rpa) {
    6767      root = rpa;
    6868    }
    69    
     69
    7070    public void valueChanged(ListSelectionEvent e) {
    7171      root.routesSelectionChanged();
    7272    }
    7373  };
    74  
     74
    7575  private class RouteReference implements Comparable< RouteReference > {
    7676    Relation route;
    77    
     77
    7878    public RouteReference(Relation route) {
    7979      this.route = route;
    8080    }
    81    
     81
    8282    public int compareTo(RouteReference rr) {
    8383      if (route.get("route") != null)
    8484      {
    85         if (rr.route.get("route") == null)
    86           return -1;
    87         int result = route.get("route").compareTo(rr.route.get("route"));
    88         if (result != 0)
    89           return result;
     85    if (rr.route.get("route") == null)
     86      return -1;
     87    int result = route.get("route").compareTo(rr.route.get("route"));
     88    if (result != 0)
     89      return result;
    9090      }
    9191      else if (rr.route.get("route") != null)
    92         return 1;
     92    return 1;
    9393      if (route.get("ref") != null)
    9494      {
    95         if (rr.route.get("ref") == null)
    96           return -1;
    97         int result = route.get("ref").compareTo(rr.route.get("ref"));
    98         if (result != 0)
    99           return result;
     95    if (rr.route.get("ref") == null)
     96      return -1;
     97    int result = route.get("ref").compareTo(rr.route.get("ref"));
     98    if (result != 0)
     99      return result;
    100100      }
    101101      else if (rr.route.get("ref") != null)
    102         return 1;
     102    return 1;
    103103      if (route.get("to") != null)
    104104      {
    105         if (rr.route.get("to") == null)
    106           return -1;
    107         int result = route.get("to").compareTo(rr.route.get("to"));
    108         if (result != 0)
    109           return result;
     105    if (rr.route.get("to") == null)
     106      return -1;
     107    int result = route.get("to").compareTo(rr.route.get("to"));
     108    if (result != 0)
     109      return result;
    110110      }
    111111      else if (rr.route.get("to") != null)
    112         return 1;
     112    return 1;
    113113      if (route.get("direction") != null)
    114114      {
    115         if (rr.route.get("direction") == null)
    116           return -1;
    117         int result = route.get("direction").compareTo(rr.route.get("direction"));
    118         if (result != 0)
    119           return result;
     115    if (rr.route.get("direction") == null)
     116      return -1;
     117    int result = route.get("direction").compareTo(rr.route.get("direction"));
     118    if (result != 0)
     119      return result;
    120120      }
    121121      else if (rr.route.get("direction") != null)
    122         return 1;
     122    return 1;
    123123      if (route.getId() < rr.route.getId())
    124         return -1;
     124    return -1;
    125125      else if (route.getId() > rr.route.getId())
    126         return 1;
     126    return 1;
    127127      return 0;
    128128    }
    129    
     129
    130130    public String toString() {
    131131      String buf = route.get("route");
    132132      if ((route.get("ref") != null) && (route.get("ref") != ""))
    133133      {
    134         if ((route.get("to") != null) && (route.get("to") != ""))
    135         {
    136           buf += " " + route.get("ref") + ": " + route.get("to");
    137         }
    138         else if ((route.get("direction") != null) && (route.get("direction") != ""))
    139         {
    140           buf += " " + route.get("ref") + ": " + route.get("direction");
    141         }
    142         else
    143         {
    144           buf += " " + route.get("ref");
    145         }
     134    if ((route.get("to") != null) && (route.get("to") != ""))
     135    {
     136      buf += " " + route.get("ref") + ": " + route.get("to");
     137    }
     138    else if ((route.get("direction") != null) && (route.get("direction") != ""))
     139    {
     140      buf += " " + route.get("ref") + ": " + route.get("direction");
     141    }
     142    else
     143    {
     144      buf += " " + route.get("ref");
     145    }
    146146      }
    147147      buf += " [ID " + Long.toString(route.getId()) + "]";
    148      
     148
    149149      return buf;
    150150    }
    151151  };
    152  
     152
    153153  private class TagTableModel extends DefaultTableModel implements TableModelListener {
    154154    Relation relation = null;
    155155    TreeSet< String > blacklist = null;
    156156    boolean hasFixedKeys = true;
    157    
     157
    158158    public TagTableModel(boolean hasFixedKeys) {
    159159      this.hasFixedKeys = hasFixedKeys;
     
    162162    public boolean isCellEditable(int row, int column) {
    163163      if ((column == 0) && (hasFixedKeys))
    164         return false;
     164    return false;
    165165      return true;
    166166    }
    167    
     167
    168168    public void readRelation(Relation rel) {
    169169      relation = rel;
    170      
     170
    171171      for (int i = 0; i < getRowCount(); ++i)
    172172      {
    173         String value = rel.get((String)getValueAt(i, 0));
    174         if (value == null)
    175           value = "";
    176         setValueAt(value, i, 1);
    177       }
    178     }
    179    
     173    String value = rel.get((String)getValueAt(i, 0));
     174    if (value == null)
     175      value = "";
     176    setValueAt(value, i, 1);
     177      }
     178    }
     179
    180180    public void readRelation(Relation rel, TreeSet< String > blacklist) {
    181181      relation = rel;
    182182      this.blacklist = blacklist;
    183      
     183
    184184      setRowCount(0);
    185185      Iterator< Map.Entry< String, String > > iter = rel.getKeys().entrySet().iterator();
    186186      while (iter.hasNext())
    187187      {
    188         Map.Entry< String, String > entry = iter.next();
    189         if (!blacklist.contains(entry.getKey()))
    190         {
    191           Vector< String > newRow = new Vector< String >();
    192           newRow.add(entry.getKey());
    193           newRow.add(entry.getValue());
    194           addRow(newRow);
    195         }
    196       }
    197      
     188    Map.Entry< String, String > entry = iter.next();
     189    if (!blacklist.contains(entry.getKey()))
     190    {
     191      Vector< String > newRow = new Vector< String >();
     192      newRow.add(entry.getKey());
     193      newRow.add(entry.getValue());
     194      addRow(newRow);
     195    }
     196      }
     197
    198198      for (int i = 0; i < getRowCount(); ++i)
    199199      {
    200         String value = rel.get((String)getValueAt(i, 0));
    201         if (value == null)
    202           value = "";
    203         setValueAt(value, i, 1);
    204       }
    205     }
    206  
     200    String value = rel.get((String)getValueAt(i, 0));
     201    if (value == null)
     202      value = "";
     203    setValueAt(value, i, 1);
     204      }
     205    }
     206
    207207    public void tableChanged(TableModelEvent e)
    208208    {
    209209      if (e.getType() == TableModelEvent.UPDATE)
    210210      {
    211         relation.setModified(true);
    212        
    213         String key = (String)getValueAt(e.getFirstRow(), 0);
    214         if (key == null)
    215           return;
    216         if ((blacklist == null) || (!blacklist.contains(key)))
    217         {
    218           relation.setModified(true);
    219           if ("".equals(getValueAt(e.getFirstRow(), 1)))
    220             relation.remove(key);
    221           else
    222             relation.put(key, (String)getValueAt(e.getFirstRow(), 1));
    223         }
    224         else
    225         {
    226           if (e.getColumn() == 0)
    227             setValueAt("", e.getFirstRow(), 0);
    228         }
     211    relation.setModified(true);
     212
     213    String key = (String)getValueAt(e.getFirstRow(), 0);
     214    if (key == null)
     215      return;
     216    if ((blacklist == null) || (!blacklist.contains(key)))
     217    {
     218      relation.setModified(true);
     219      if ("".equals(getValueAt(e.getFirstRow(), 1)))
     220        relation.remove(key);
     221      else
     222        relation.put(key, (String)getValueAt(e.getFirstRow(), 1));
     223    }
     224    else
     225    {
     226      if (e.getColumn() == 0)
     227        setValueAt("", e.getFirstRow(), 0);
     228    }
    229229      }
    230230    }
    231231  };
    232  
     232
    233233  private class CustomCellEditorTable extends JTable {
    234234    TreeMap< Integer, TableCellEditor > col1 = null;
    235235    TreeMap< Integer, TableCellEditor > col2 = null;
    236    
     236
    237237    public CustomCellEditorTable() {
    238238      col1 = new TreeMap< Integer, TableCellEditor >();
    239239      col2 = new TreeMap< Integer, TableCellEditor >();
    240240    }
    241    
     241
    242242    public TableCellEditor getCellEditor(int row, int column) {
    243243      TableCellEditor editor = null;
    244244      if (column == 0)
    245         editor = col1.get(new Integer(row));
     245    editor = col1.get(new Integer(row));
    246246      else
    247         editor = col2.get(new Integer(row));
     247    editor = col2.get(new Integer(row));
    248248      if (editor == null)
    249         return new DefaultCellEditor(new JTextField());
     249    return new DefaultCellEditor(new JTextField());
    250250      else
    251         return editor;
    252     }
    253    
     251    return editor;
     252    }
     253
    254254    public void setCellEditor(int row, int column, TableCellEditor editor) {
    255255      if (column == 0)
    256         col1.put(new Integer(row), editor);
     256    col1.put(new Integer(row), editor);
    257257      else
    258         col2.put(new Integer(row), editor);
     258    col2.put(new Integer(row), editor);
    259259    }
    260260  };
    261  
     261
    262262  private class StoplistTableModel extends DefaultTableModel {
    263263    public Vector<Node> nodes = new Vector<Node>();
    264    
     264
    265265    public boolean isCellEditable(int row, int column) {
    266266      if (column != 1)
    267         return false;
     267    return false;
    268268      return true;
    269269    }
    270  
     270
    271271    public void addRow(Object[] obj) {
    272272      throw new UnsupportedOperationException();
    273273    }
    274    
     274
    275275    public void insertRow(int insPos, Object[] obj) {
    276276      throw new UnsupportedOperationException();
    277277    }
    278    
     278
    279279    public void addRow(Node node, String role) {
    280280      insertRow(-1, node, role);
    281281    }
    282    
     282
    283283    public void insertRow(int insPos, Node node, String role) {
    284284      String[] buf = { "", "" };
     
    286286      if (curName != null)
    287287      {
    288         buf[0] = curName;
     288    buf[0] = curName;
    289289      }
    290290      else
    291291      {
    292         buf[0] = "[ID] " + (new Long(node.getId())).toString();
     292    buf[0] = "[ID] " + (new Long(node.getId())).toString();
    293293      }
    294294      buf[1] = role;
    295295      if (insPos == -1)
    296296      {
    297         nodes.addElement(node);
    298         super.addRow(buf);
     297    nodes.addElement(node);
     298    super.addRow(buf);
    299299      }
    300300      else
    301301      {
    302         nodes.insertElementAt(node, insPos);
    303         super.insertRow(insPos, buf);
    304       }
    305     }
    306    
     302    nodes.insertElementAt(node, insPos);
     303    super.insertRow(insPos, buf);
     304      }
     305    }
     306
    307307    public void clear()
    308308    {
     
    311311    }
    312312  };
    313  
     313
    314314  private class StoplistTableModelListener implements TableModelListener {
    315315    public void tableChanged(TableModelEvent e)
     
    317317      if (e.getType() == TableModelEvent.UPDATE)
    318318      {
    319         rebuildNodes();
     319    rebuildNodes();
    320320      }
    321321    }
    322322  };
    323  
     323
    324324  private class SegmentMetric {
    325325    public double aLat, aLon;
    326326    public double length;
    327327    public double d1, d2, o1, o2;
    328    
     328
    329329    public SegmentMetric(double fromLat, double fromLon, double toLat, double toLon) {
    330330      aLat = fromLat;
    331331      aLon = fromLon;
    332      
     332
    333333      //Compute length and direction
    334334      //length is in units of latitude degrees
     
    336336      d2 = (toLon - fromLon) * Math.cos(fromLat * Math.PI/180.0);
    337337      length = Math.sqrt(d1*d1 + d2*d2);
    338    
     338
    339339      //Normalise direction
    340340      d1 = d1 / length;
    341341      d2 = d2 / length;
    342    
     342
    343343      //Compute orthogonal direction (right hand size is positive)
    344344      o1 = - d2;
    345345      o2 = d1;
    346    
     346
    347347      //Prepare lon direction to reduce the number of necessary multiplications
    348348      d2 = d2 * Math.cos(fromLat * Math.PI/180.0);
     
    350350    }
    351351  };
    352  
     352
    353353  private class StopReference implements Comparable< StopReference > {
    354354    public int index = 0;
     
    358358    public String role = "";
    359359    public Node node;
    360    
     360
    361361    public StopReference(int inIndex, double inPos, double inDistance,
    362                         String inName, String inRole, Node inNode) {
     362            String inName, String inRole, Node inNode) {
    363363      index = inIndex;
    364364      pos = inPos;
     
    368368      node = inNode;
    369369    }
    370    
     370
    371371    public int compareTo(StopReference sr) {
    372372      if (this.index < sr.index)
    373         return -1;
     373    return -1;
    374374      if (this.index > sr.index)
    375         return 1;
     375    return 1;
    376376      if (this.pos < sr.pos)
    377         return -1;
     377    return -1;
    378378      if (this.pos > sr.pos)
    379         return 1;
     379    return 1;
    380380      return 0;
    381381    }
    382382  };
    383  
     383
    384384  private static JDialog jDialog = null;
    385385  private static JTabbedPane tabbedPane = null;
     
    403403  private static Vector< RelationMember > markedWays = new Vector< RelationMember >();
    404404  private static Vector< RelationMember > markedNodes = new Vector< RelationMember >();
    405  
     405
    406406  private static Relation copy = null;
    407  
     407
    408408  public RoutePatternAction() {
    409409    super(tr("Route patterns ..."), null,
    410           tr("Edit Route patterns for public transport"), null, true);
     410      tr("Edit Route patterns for public transport"), null, true);
    411411  }
    412412
     
    414414    Frame frame = JOptionPane.getFrameForComponent(Main.parent);
    415415    DataSet mainDataSet = Main.main.getCurrentDataSet();
    416    
     416
    417417    if (jDialog == null)
    418418    {
     
    435435      tabbedPane.setEnabledAt(4, false);
    436436      jDialog.add(tabbedPane);
    437      
     437
    438438      //Overview Tab
    439439      Container contentPane = tabOverview;
     
    441441      GridBagConstraints layoutCons = new GridBagConstraints();
    442442      contentPane.setLayout(gridbag);
    443      
     443
    444444      JLabel headline = new JLabel("Existing route patterns:");
    445        
     445
    446446      layoutCons.gridx = 0;
    447447      layoutCons.gridy = 0;
     
    452452      gridbag.setConstraints(headline, layoutCons);
    453453      contentPane.add(headline);
    454        
     454
    455455      relsListModel = new DefaultListModel();
    456456      relsList = new JList(relsListModel);
     
    460460      relsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    461461      relsList.addListSelectionListener(new RoutesLSL(this));
    462      
     462
    463463      layoutCons.gridx = 0;
    464464      layoutCons.gridy = 1;
     
    469469      gridbag.setConstraints(rpListSP, layoutCons);
    470470      contentPane.add(rpListSP);
    471        
     471
    472472      JButton bRefresh = new JButton("Refresh");
    473473      bRefresh.setActionCommand("routePattern.refresh");
    474474      bRefresh.addActionListener(this);
    475        
     475
    476476      layoutCons.gridx = 0;
    477477      layoutCons.gridy = 2;
     
    483483      gridbag.setConstraints(bRefresh, layoutCons);
    484484      contentPane.add(bRefresh);
    485        
     485
    486486      JButton bNew = new JButton("New");
    487487      bNew.setActionCommand("routePattern.overviewNew");
    488488      bNew.addActionListener(this);
    489        
     489
    490490      layoutCons.gridx = 1;
    491491      layoutCons.gridy = 2;
     
    497497      gridbag.setConstraints(bNew, layoutCons);
    498498      contentPane.add(bNew);
    499        
     499
    500500      JButton bDelete = new JButton("Delete");
    501501      bDelete.setActionCommand("routePattern.overviewDelete");
    502502      bDelete.addActionListener(this);
    503        
     503
    504504      layoutCons.gridx = 1;
    505505      layoutCons.gridy = 3;
     
    511511      gridbag.setConstraints(bDelete, layoutCons);
    512512      contentPane.add(bDelete);
    513      
     513
    514514      JButton bDuplicate = new JButton("Duplicate");
    515515      bDuplicate.setActionCommand("routePattern.overviewDuplicate");
    516516      bDuplicate.addActionListener(this);
    517        
     517
    518518      layoutCons.gridx = 2;
    519519      layoutCons.gridy = 2;
     
    525525      gridbag.setConstraints(bDuplicate, layoutCons);
    526526      contentPane.add(bDuplicate);
    527        
     527
    528528      JButton bReflect = new JButton("Reflect");
    529529      bReflect.setActionCommand("routePattern.overviewReflect");
    530530      bReflect.addActionListener(this);
    531        
     531
    532532      layoutCons.gridx = 2;
    533533      layoutCons.gridy = 3;
     
    539539      gridbag.setConstraints(bReflect, layoutCons);
    540540      contentPane.add(bReflect);
    541      
     541
    542542      //Tags Tab
    543543      /*Container*/ contentPane = tabTags;
     
    545545      /*GridBagConstraints*/ layoutCons = new GridBagConstraints();
    546546      contentPane.setLayout(gridbag);
    547      
     547
    548548      /*JLabel*/ headline = new JLabel("Required tags:");
    549        
     549
    550550      layoutCons.gridx = 0;
    551551      layoutCons.gridy = 0;
     
    555555      gridbag.setConstraints(headline, layoutCons);
    556556      contentPane.add(headline);
    557        
     557
    558558      requiredTagsTable = new CustomCellEditorTable();
    559559      requiredTagsData = new TagTableModel(true);
     
    600600      JScrollPane tableSP = new JScrollPane(requiredTagsTable);
    601601      requiredTagsData.addTableModelListener(requiredTagsData);
    602      
     602
    603603      layoutCons.gridx = 0;
    604604      layoutCons.gridy = 1;
     
    611611      tableSP.setPreferredSize(preferredSize);
    612612      contentPane.add(tableSP);
    613        
     613
    614614      headline = new JLabel("Common tags:");
    615        
     615
    616616      layoutCons.gridx = 0;
    617617      layoutCons.gridy = 2;
     
    621621      gridbag.setConstraints(headline, layoutCons);
    622622      contentPane.add(headline);
    623      
     623
    624624      commonTagsTable = new CustomCellEditorTable();
    625625      commonTagsData = new TagTableModel(true);
     
    654654      /*JScrollPane*/ tableSP = new JScrollPane(commonTagsTable);
    655655      commonTagsData.addTableModelListener(commonTagsData);
    656      
     656
    657657      layoutCons.gridx = 0;
    658658      layoutCons.gridy = 3;
     
    665665      tableSP.setPreferredSize(preferredSize);
    666666      contentPane.add(tableSP);
    667        
     667
    668668      headline = new JLabel("Additional tags:");
    669        
     669
    670670      layoutCons.gridx = 0;
    671671      layoutCons.gridy = 4;
     
    675675      gridbag.setConstraints(headline, layoutCons);
    676676      contentPane.add(headline);
    677        
     677
    678678      otherTagsTable = new CustomCellEditorTable();
    679679      otherTagsData = new TagTableModel(false);
     
    683683      /*JScrollPane*/ tableSP = new JScrollPane(otherTagsTable);
    684684      otherTagsData.addTableModelListener(otherTagsData);
    685      
     685
    686686      layoutCons.gridx = 0;
    687687      layoutCons.gridy = 5;
     
    694694      tableSP.setPreferredSize(preferredSize);
    695695      contentPane.add(tableSP);
    696      
     696
    697697      JButton bAddTag = new JButton("Add a new Tag");
    698698      bAddTag.setActionCommand("routePattern.tagAddTag");
    699699      bAddTag.addActionListener(this);
    700      
     700
    701701      layoutCons.gridx = 0;
    702702      layoutCons.gridy = 6;
     
    707707      gridbag.setConstraints(bAddTag, layoutCons);
    708708      contentPane.add(bAddTag);
    709        
     709
    710710      //Itinerary Tab
    711711      contentPane = tabItinerary;
     
    713713      layoutCons = new GridBagConstraints();
    714714      contentPane.setLayout(gridbag);
    715      
     715
    716716      itineraryTable = new JTable();
    717717      itineraryData = new ItineraryTableModel();
     
    725725      comboBox.addItem("backward");
    726726      itineraryTable.getColumnModel().getColumn(1)
    727           .setCellEditor(new DefaultCellEditor(comboBox));
     727      .setCellEditor(new DefaultCellEditor(comboBox));
    728728      itineraryData.addTableModelListener(itineraryData);
    729      
     729
    730730      layoutCons.gridx = 0;
    731731      layoutCons.gridy = 0;
     
    736736      gridbag.setConstraints(tableSP, layoutCons);
    737737      contentPane.add(tableSP);
    738        
     738
    739739      JButton bFind = new JButton("Find");
    740740      bFind.setActionCommand("routePattern.itineraryFind");
    741741      bFind.addActionListener(this);
    742        
     742
    743743      layoutCons.gridx = 0;
    744744      layoutCons.gridy = 1;
     
    749749      gridbag.setConstraints(bFind, layoutCons);
    750750      contentPane.add(bFind);
    751      
     751
    752752      JButton bShow = new JButton("Show");
    753753      bShow.setActionCommand("routePattern.itineraryShow");
    754754      bShow.addActionListener(this);
    755        
     755
    756756      layoutCons.gridx = 0;
    757757      layoutCons.gridy = 2;
     
    762762      gridbag.setConstraints(bShow, layoutCons);
    763763      contentPane.add(bShow);
    764        
     764
    765765      JButton bMark = new JButton("Mark");
    766766      bMark.setActionCommand("routePattern.itineraryMark");
    767767      bMark.addActionListener(this);
    768        
     768
    769769      layoutCons.gridx = 1;
    770770      layoutCons.gridy = 1;
     
    776776      gridbag.setConstraints(bMark, layoutCons);
    777777      contentPane.add(bMark);
    778        
     778
    779779      JButton bAdd = new JButton("Add");
    780780      bAdd.setActionCommand("routePattern.itineraryAdd");
    781781      bAdd.addActionListener(this);
    782        
     782
    783783      layoutCons.gridx = 2;
    784784      layoutCons.gridy = 1;
     
    790790      gridbag.setConstraints(bAdd, layoutCons);
    791791      contentPane.add(bAdd);
    792        
     792
    793793      /*JButton*/ bDelete = new JButton("Delete");
    794794      bDelete.setActionCommand("routePattern.itineraryDelete");
    795795      bDelete.addActionListener(this);
    796        
     796
    797797      layoutCons.gridx = 2;
    798798      layoutCons.gridy = 2;
     
    803803      gridbag.setConstraints(bDelete, layoutCons);
    804804      contentPane.add(bDelete);
    805        
     805
    806806      JButton bSort = new JButton("Sort");
    807807      bSort.setActionCommand("routePattern.itinerarySort");
    808808      bSort.addActionListener(this);
    809        
     809
    810810      layoutCons.gridx = 3;
    811811      layoutCons.gridy = 1;
     
    816816      gridbag.setConstraints(bSort, layoutCons);
    817817      contentPane.add(bSort);
    818        
     818
    819819      /*JButton*/ bReflect = new JButton("Reflect");
    820820      bReflect.setActionCommand("routePattern.itineraryReflect");
    821821      bReflect.addActionListener(this);
    822      
     822
    823823      layoutCons.gridx = 3;
    824824      layoutCons.gridy = 2;
     
    829829      gridbag.setConstraints(bReflect, layoutCons);
    830830      contentPane.add(bReflect);
    831      
     831
    832832      //Stoplist Tab
    833833      contentPane = tabStoplist;
     
    835835      layoutCons = new GridBagConstraints();
    836836      contentPane.setLayout(gridbag);
    837      
     837
    838838      stoplistTable = new JTable();
    839839      stoplistData = new StoplistTableModel();
     
    847847      comboBox.addItem("backward_stop");
    848848      stoplistTable.getColumnModel().getColumn(1)
    849           .setCellEditor(new DefaultCellEditor(comboBox));
     849      .setCellEditor(new DefaultCellEditor(comboBox));
    850850      stoplistData.addTableModelListener(new StoplistTableModelListener());
    851      
     851
    852852      layoutCons.gridx = 0;
    853853      layoutCons.gridy = 0;
     
    858858      gridbag.setConstraints(tableSP, layoutCons);
    859859      contentPane.add(tableSP);
    860        
     860
    861861      /*JButton*/ bFind = new JButton("Find");
    862862      bFind.setActionCommand("routePattern.stoplistFind");
    863863      bFind.addActionListener(this);
    864        
     864
    865865      layoutCons.gridx = 0;
    866866      layoutCons.gridy = 1;
     
    871871      gridbag.setConstraints(bFind, layoutCons);
    872872      contentPane.add(bFind);
    873        
     873
    874874      /*JButton*/ bShow = new JButton("Show");
    875875      bShow.setActionCommand("routePattern.stoplistShow");
    876876      bShow.addActionListener(this);
    877        
     877
    878878      layoutCons.gridx = 0;
    879879      layoutCons.gridy = 2;
     
    884884      gridbag.setConstraints(bShow, layoutCons);
    885885      contentPane.add(bShow);
    886        
     886
    887887      /*JButton*/ bMark = new JButton("Mark");
    888888      bMark.setActionCommand("routePattern.stoplistMark");
    889889      bMark.addActionListener(this);
    890        
     890
    891891      layoutCons.gridx = 1;
    892892      layoutCons.gridy = 1;
     
    898898      gridbag.setConstraints(bMark, layoutCons);
    899899      contentPane.add(bMark);
    900        
     900
    901901      /*JButton*/ bAdd = new JButton("Add");
    902902      bAdd.setActionCommand("routePattern.stoplistAdd");
    903903      bAdd.addActionListener(this);
    904        
     904
    905905      layoutCons.gridx = 2;
    906906      layoutCons.gridy = 1;
     
    912912      gridbag.setConstraints(bAdd, layoutCons);
    913913      contentPane.add(bAdd);
    914        
     914
    915915      /*JButton*/ bDelete = new JButton("Delete");
    916916      bDelete.setActionCommand("routePattern.stoplistDelete");
    917917      bDelete.addActionListener(this);
    918        
     918
    919919      layoutCons.gridx = 2;
    920920      layoutCons.gridy = 2;
     
    925925      gridbag.setConstraints(bDelete, layoutCons);
    926926      contentPane.add(bDelete);
    927        
     927
    928928      /*JButton*/ bSort = new JButton("Sort");
    929929      bSort.setActionCommand("routePattern.stoplistSort");
    930930      bSort.addActionListener(this);
    931        
     931
    932932      layoutCons.gridx = 3;
    933933      layoutCons.gridy = 1;
     
    938938      gridbag.setConstraints(bSort, layoutCons);
    939939      contentPane.add(bSort);
    940        
     940
    941941      /*JButton*/ bReflect = new JButton("Reflect");
    942942      bReflect.setActionCommand("routePattern.stoplistReflect");
    943943      bReflect.addActionListener(this);
    944      
     944
    945945      layoutCons.gridx = 3;
    946946      layoutCons.gridy = 2;
     
    951951      gridbag.setConstraints(bReflect, layoutCons);
    952952      contentPane.add(bReflect);
    953      
     953
    954954      //Meta Tab
    955955      contentPane = tabMeta;
     
    957957      layoutCons = new GridBagConstraints();
    958958      contentPane.setLayout(gridbag);
    959      
     959
    960960      JLabel rightleft = new JLabel("Stops are possible on the");
    961      
     961
    962962      layoutCons.gridx = 0;
    963963      layoutCons.gridy = 1;
     
    968968      gridbag.setConstraints(rightleft, layoutCons);
    969969      contentPane.add(rightleft);
    970        
     970
    971971      cbRight = new JCheckBox("right hand side", true);
    972      
     972
    973973      layoutCons.gridx = 0;
    974974      layoutCons.gridy = 2;
     
    979979      gridbag.setConstraints(cbRight, layoutCons);
    980980      contentPane.add(cbRight);
    981        
     981
    982982      cbLeft = new JCheckBox("left hand side", false);
    983      
     983
    984984      layoutCons.gridx = 0;
    985985      layoutCons.gridy = 3;
     
    990990      gridbag.setConstraints(cbLeft, layoutCons);
    991991      contentPane.add(cbLeft);
    992      
     992
    993993      JLabel maxdist = new JLabel("Maximum distance from route");
    994      
     994
    995995      layoutCons.gridx = 0;
    996996      layoutCons.gridy = 4;
     
    10011001      gridbag.setConstraints(maxdist, layoutCons);
    10021002      contentPane.add(maxdist);
    1003      
     1003
    10041004      tfSuggestStopsLimit = new JTextField("20", 4);
    1005      
     1005
    10061006      layoutCons.gridx = 0;
    10071007      layoutCons.gridy = 5;
     
    10121012      gridbag.setConstraints(tfSuggestStopsLimit, layoutCons);
    10131013      contentPane.add(tfSuggestStopsLimit);
    1014      
     1014
    10151015      JLabel meters = new JLabel("meters");
    1016      
     1016
    10171017      layoutCons.gridx = 1;
    10181018      layoutCons.gridy = 5;
     
    10231023      gridbag.setConstraints(meters, layoutCons);
    10241024      contentPane.add(meters);
    1025      
     1025
    10261026      JButton bSuggestStops = new JButton("Suggest Stops");
    10271027      bSuggestStops.setActionCommand("routePattern.metaSuggestStops");
    10281028      bSuggestStops.addActionListener(this);
    1029        
     1029
    10301030      layoutCons.gridx = 0;
    10311031      layoutCons.gridy = 6;
     
    10361036      gridbag.setConstraints(bSuggestStops, layoutCons);
    10371037      contentPane.add(bSuggestStops);
    1038        
     1038
    10391039      jDialog.pack();
    10401040    }
    1041      
     1041
    10421042    if ("routePattern.refresh".equals(event.getActionCommand()))
    10431043    {
     
    10501050      currentRoute.put("route", "bus");
    10511051      mainDataSet.addPrimitive(currentRoute);
    1052      
     1052
    10531053      refreshData();
    1054      
     1054
    10551055      for (int i = 0; i < relsListModel.size(); ++i)
    10561056      {
    1057         if (currentRoute == ((RouteReference)relsListModel.elementAt(i)).route)
    1058           relsList.setSelectedIndex(i);
     1057    if (currentRoute == ((RouteReference)relsListModel.elementAt(i)).route)
     1058      relsList.setSelectedIndex(i);
    10591059      }
    10601060    }
     
    10651065      currentRoute.put("route", "bus");
    10661066      mainDataSet.addPrimitive(currentRoute);
    1067      
     1067
    10681068      refreshData();
    1069        
     1069
    10701070      for (int i = 0; i < relsListModel.size(); ++i)
    10711071      {
    1072         if (currentRoute == ((RouteReference)relsListModel.elementAt(i)).route)
    1073           relsList.setSelectedIndex(i);
     1072    if (currentRoute == ((RouteReference)relsListModel.elementAt(i)).route)
     1073      relsList.setSelectedIndex(i);
    10741074      }
    10751075    }
     
    10811081      currentRoute.put("from", tag_to);
    10821082      currentRoute.put("to", tag_from);
    1083      
     1083
    10841084      Vector< RelationMember > itemsToReflect = new Vector< RelationMember >();
    10851085      Vector< RelationMember > otherItems = new Vector< RelationMember >();
    10861086      int insPos = itineraryTable.getSelectedRow();
    1087      
     1087
    10881088      for (int i = 0; i < currentRoute.getMembersCount(); ++i)
    10891089      {
    1090         RelationMember item = currentRoute.getMember(i);
    1091        
    1092         if (item.isWay())
    1093         {
    1094           String role = item.getRole();
    1095           if ("backward".equals(role))
    1096             role = "forward";
    1097           else if ("forward".equals(role))
    1098             role = "backward";
    1099           else
    1100             role = "backward";
    1101          
    1102           itemsToReflect.add(new RelationMember(role, item.getWay()));
    1103         }
    1104         else if (item.isNode())
    1105           itemsToReflect.add(item);
    1106         else
    1107           otherItems.add(item);
    1108       }
    1109        
     1090    RelationMember item = currentRoute.getMember(i);
     1091
     1092    if (item.isWay())
     1093    {
     1094      String role = item.getRole();
     1095      if ("backward".equals(role))
     1096        role = "forward";
     1097      else if ("forward".equals(role))
     1098        role = "backward";
     1099      else
     1100        role = "backward";
     1101
     1102      itemsToReflect.add(new RelationMember(role, item.getWay()));
     1103    }
     1104    else if (item.isNode())
     1105      itemsToReflect.add(item);
     1106    else
     1107      otherItems.add(item);
     1108      }
     1109
    11101110      currentRoute.setMembers(null);
    11111111      for (int i = itemsToReflect.size()-1; i >= 0; --i)
    1112         currentRoute.addMember(itemsToReflect.elementAt(i));
     1112    currentRoute.addMember(itemsToReflect.elementAt(i));
    11131113      for (int i = 0; i < otherItems.size(); ++i)
    1114         currentRoute.addMember(otherItems.elementAt(i));
    1115      
     1114    currentRoute.addMember(otherItems.elementAt(i));
     1115
    11161116      refreshData();
    1117      
     1117
    11181118      for (int i = 0; i < relsListModel.size(); ++i)
    11191119      {
    1120         if (currentRoute == ((RouteReference)relsListModel.elementAt(i)).route)
    1121           relsList.setSelectedIndex(i);
     1120    if (currentRoute == ((RouteReference)relsListModel.elementAt(i)).route)
     1121      relsList.setSelectedIndex(i);
    11221122      }
    11231123    }
     
    11251125    {
    11261126      DeleteAction.deleteRelation(Main.main.getEditLayer(), currentRoute);
    1127      
     1127
    11281128      currentRoute = null;
    11291129      tabbedPane.setEnabledAt(1, false);
     
    11311131      tabbedPane.setEnabledAt(3, false);
    11321132      tabbedPane.setEnabledAt(4, false);
    1133      
     1133
    11341134      refreshData();
    11351135    }
     
    11441144    {
    11451145      if (mainDataSet == null)
    1146         return;
    1147      
     1146    return;
     1147
    11481148      itineraryTable.clearSelection();
    1149      
     1149
    11501150      for (int i = 0; i < itineraryData.getRowCount(); ++i)
    11511151      {
    1152         if ((itineraryData.ways.elementAt(i) != null) &&
    1153             (mainDataSet.isSelected(itineraryData.ways.elementAt(i))))
    1154             itineraryTable.addRowSelectionInterval(i, i);
     1152    if ((itineraryData.ways.elementAt(i) != null) &&
     1153        (mainDataSet.isSelected(itineraryData.ways.elementAt(i))))
     1154        itineraryTable.addRowSelectionInterval(i, i);
    11551155      }
    11561156    }
     
    11601160      if (itineraryTable.getSelectedRowCount() > 0)
    11611161      {
    1162         for (int i = 0; i < itineraryData.getRowCount(); ++i)
    1163         {
    1164           if ((itineraryTable.isRowSelected(i)) && (itineraryData.ways.elementAt(i) != null))
    1165           {
    1166             itineraryData.ways.elementAt(i).visit(box);
    1167           }
    1168         }
     1162    for (int i = 0; i < itineraryData.getRowCount(); ++i)
     1163    {
     1164      if ((itineraryTable.isRowSelected(i)) && (itineraryData.ways.elementAt(i) != null))
     1165      {
     1166        itineraryData.ways.elementAt(i).visit(box);
     1167      }
     1168    }
    11691169      }
    11701170      else
    11711171      {
    1172         for (int i = 0; i < itineraryData.getRowCount(); ++i)
    1173         {
    1174           if (itineraryData.ways.elementAt(i) != null)
    1175           {
    1176             itineraryData.ways.elementAt(i).visit(box);
    1177           }
    1178         }
     1172    for (int i = 0; i < itineraryData.getRowCount(); ++i)
     1173    {
     1174      if (itineraryData.ways.elementAt(i) != null)
     1175      {
     1176        itineraryData.ways.elementAt(i).visit(box);
     1177      }
     1178    }
    11791179      }
    11801180      if (box.getBounds() == null)
    1181         return;
     1181    return;
    11821182      box.enlargeBoundingBox();
    11831183      Main.map.mapView.recalculateCenterScale(box);
     
    11901190      if (itineraryTable.getSelectedRowCount() > 0)
    11911191      {
    1192         for (int i = 0; i < itineraryData.getRowCount(); ++i)
    1193         {
    1194           if ((itineraryTable.isRowSelected(i)) && (itineraryData.ways.elementAt(i) != null))
    1195           {
    1196             mainDataSet.addSelected(itineraryData.ways.elementAt(i));
    1197            
    1198             RelationMember markedWay = new RelationMember
    1199                 ((String)(itineraryData.getValueAt(i, 1)), itineraryData.ways.elementAt(i));
    1200             markedWays.addElement(markedWay);
    1201           }
    1202         }
     1192    for (int i = 0; i < itineraryData.getRowCount(); ++i)
     1193    {
     1194      if ((itineraryTable.isRowSelected(i)) && (itineraryData.ways.elementAt(i) != null))
     1195      {
     1196        mainDataSet.addSelected(itineraryData.ways.elementAt(i));
     1197
     1198        RelationMember markedWay = new RelationMember
     1199        ((String)(itineraryData.getValueAt(i, 1)), itineraryData.ways.elementAt(i));
     1200        markedWays.addElement(markedWay);
     1201      }
     1202    }
    12031203      }
    12041204      else
    12051205      {
    1206         for (int i = 0; i < itineraryData.getRowCount(); ++i)
    1207         {
    1208           if (itineraryData.ways.elementAt(i) != null)
    1209           {
    1210             mainDataSet.addSelected(itineraryData.ways.elementAt(i));
    1211            
    1212             RelationMember markedWay = new RelationMember
    1213                 ((String)(itineraryData.getValueAt(i, 1)), itineraryData.ways.elementAt(i));
    1214             markedWays.addElement(markedWay);
    1215           }
    1216         }
     1206    for (int i = 0; i < itineraryData.getRowCount(); ++i)
     1207    {
     1208      if (itineraryData.ways.elementAt(i) != null)
     1209      {
     1210        mainDataSet.addSelected(itineraryData.ways.elementAt(i));
     1211
     1212        RelationMember markedWay = new RelationMember
     1213        ((String)(itineraryData.getValueAt(i, 1)), itineraryData.ways.elementAt(i));
     1214        markedWays.addElement(markedWay);
     1215      }
     1216    }
    12171217      }
    12181218    }
     
    12231223      TreeSet<Way> addedWays = new TreeSet<Way>();
    12241224      if (mainDataSet == null)
    1225         return;
    1226      
     1225    return;
     1226
    12271227      while (relIter.hasNext())
    12281228      {
    1229         RelationMember curMember = relIter.next();
    1230         if ((curMember.isWay()) && (mainDataSet.isSelected(curMember.getWay())))
    1231         {
    1232           itineraryData.insertRow(insPos, curMember.getWay(), curMember.getRole());
    1233           if (insPos >= 0)
    1234             ++insPos;
    1235          
    1236           addedWays.add(curMember.getWay());
    1237         }
    1238       }
    1239      
     1229    RelationMember curMember = relIter.next();
     1230    if ((curMember.isWay()) && (mainDataSet.isSelected(curMember.getWay())))
     1231    {
     1232      itineraryData.insertRow(insPos, curMember.getWay(), curMember.getRole());
     1233      if (insPos >= 0)
     1234        ++insPos;
     1235
     1236      addedWays.add(curMember.getWay());
     1237    }
     1238      }
     1239
    12401240      Collection<Way> selectedWays = mainDataSet.getSelectedWays();
    12411241      Iterator<Way> wayIter = selectedWays.iterator();
    1242      
     1242
    12431243      while (wayIter.hasNext())
    12441244      {
    1245         Way curMember = wayIter.next();
    1246         if (!(addedWays.contains(curMember)))
    1247         {
    1248           itineraryData.insertRow(insPos, curMember, "");
    1249           if (insPos >= 0)
    1250             ++insPos;
    1251         }
    1252       }
    1253      
     1245    Way curMember = wayIter.next();
     1246    if (!(addedWays.contains(curMember)))
     1247    {
     1248      itineraryData.insertRow(insPos, curMember, "");
     1249      if (insPos >= 0)
     1250        ++insPos;
     1251    }
     1252      }
     1253
    12541254      if ((insPos > 0) && (insPos < itineraryData.getRowCount()))
    12551255      {
    1256         while ((insPos < itineraryData.getRowCount())
    1257                        && (itineraryData.ways.elementAt(insPos) == null))
    1258           ++insPos;
    1259         itineraryTable.removeRowSelectionInterval(0, itineraryData.getRowCount()-1);
    1260         if (insPos < itineraryData.getRowCount())
    1261           itineraryTable.addRowSelectionInterval(insPos, insPos);
     1256    while ((insPos < itineraryData.getRowCount())
     1257               && (itineraryData.ways.elementAt(insPos) == null))
     1258      ++insPos;
     1259    itineraryTable.removeRowSelectionInterval(0, itineraryData.getRowCount()-1);
     1260    if (insPos < itineraryData.getRowCount())
     1261      itineraryTable.addRowSelectionInterval(insPos, insPos);
    12621262      }
    12631263
     
    12691269      for (int i = itineraryData.getRowCount()-1; i >=0; --i)
    12701270      {
    1271         if ((itineraryTable.isRowSelected(i)) && (itineraryData.ways.elementAt(i) != null))
    1272         {
    1273           itineraryData.ways.removeElementAt(i);
    1274           itineraryData.removeRow(i);
    1275         }
    1276       }
    1277    
     1271    if ((itineraryTable.isRowSelected(i)) && (itineraryData.ways.elementAt(i) != null))
     1272    {
     1273      itineraryData.ways.removeElementAt(i);
     1274      itineraryData.removeRow(i);
     1275    }
     1276      }
     1277
    12781278      itineraryData.cleanupGaps();
    12791279      rebuildWays();
     
    12831283      TreeSet<Way> usedWays = new TreeSet<Way>();
    12841284      TreeMap<Node, LinkedList<RelationMember> > frontNodes =
    1285           new TreeMap<Node, LinkedList<RelationMember> >();
     1285      new TreeMap<Node, LinkedList<RelationMember> >();
    12861286      TreeMap<Node, LinkedList<RelationMember> > backNodes =
    1287           new TreeMap<Node, LinkedList<RelationMember> >();
     1287      new TreeMap<Node, LinkedList<RelationMember> >();
    12881288      Vector< LinkedList<RelationMember> > loops =
    1289           new Vector< LinkedList<RelationMember> >();
     1289      new Vector< LinkedList<RelationMember> >();
    12901290      int insPos = itineraryTable.getSelectedRow();
    1291      
     1291
    12921292      if (itineraryTable.getSelectedRowCount() > 0)
    12931293      {
    1294         for (int i = itineraryData.getRowCount()-1; i >=0; --i)
    1295         {
    1296           if ((itineraryTable.isRowSelected(i)) && (itineraryData.ways.elementAt(i) != null))
    1297           {
    1298             if (!(usedWays.contains(itineraryData.ways.elementAt(i))))
    1299             {
    1300               addWayToSortingData
    1301                   (itineraryData.ways.elementAt(i), frontNodes, backNodes, loops);
    1302               usedWays.add(itineraryData.ways.elementAt(i));
    1303             }
    1304            
    1305             itineraryData.ways.removeElementAt(i);
    1306             itineraryData.removeRow(i);
    1307           }
    1308         }
     1294    for (int i = itineraryData.getRowCount()-1; i >=0; --i)
     1295    {
     1296      if ((itineraryTable.isRowSelected(i)) && (itineraryData.ways.elementAt(i) != null))
     1297      {
     1298        if (!(usedWays.contains(itineraryData.ways.elementAt(i))))
     1299        {
     1300          addWayToSortingData
     1301          (itineraryData.ways.elementAt(i), frontNodes, backNodes, loops);
     1302          usedWays.add(itineraryData.ways.elementAt(i));
     1303        }
     1304
     1305        itineraryData.ways.removeElementAt(i);
     1306        itineraryData.removeRow(i);
     1307      }
     1308    }
    13091309      }
    13101310      else
    13111311      {
    1312         for (int i = itineraryData.getRowCount()-1; i >=0; --i)
    1313         {
    1314           if (itineraryData.ways.elementAt(i) != null)
    1315           {
    1316             if (!(usedWays.contains(itineraryData.ways.elementAt(i))))
    1317             {
    1318               addWayToSortingData
    1319                   (itineraryData.ways.elementAt(i), frontNodes, backNodes, loops);
    1320               usedWays.add(itineraryData.ways.elementAt(i));
    1321             }
    1322           }
    1323         }
    1324        
    1325         itineraryData.clear();
     1312    for (int i = itineraryData.getRowCount()-1; i >=0; --i)
     1313    {
     1314      if (itineraryData.ways.elementAt(i) != null)
     1315      {
     1316        if (!(usedWays.contains(itineraryData.ways.elementAt(i))))
     1317        {
     1318          addWayToSortingData
     1319          (itineraryData.ways.elementAt(i), frontNodes, backNodes, loops);
     1320          usedWays.add(itineraryData.ways.elementAt(i));
     1321        }
     1322      }
     1323    }
     1324
     1325    itineraryData.clear();
    13261326      }
    13271327
    13281328      Iterator< Map.Entry< Node, LinkedList<RelationMember> > > entryIter
    1329           = frontNodes.entrySet().iterator();
     1329      = frontNodes.entrySet().iterator();
    13301330      while (entryIter.hasNext())
    13311331      {
    1332         Iterator<RelationMember> relIter = entryIter.next().getValue().iterator();
    1333         while (relIter.hasNext())
    1334         {
    1335           RelationMember curMember = relIter.next();
    1336           itineraryData.insertRow(insPos, curMember.getWay(), curMember.getRole());
    1337           if (insPos >= 0)
    1338             ++insPos;
    1339         }
    1340       }
    1341      
     1332    Iterator<RelationMember> relIter = entryIter.next().getValue().iterator();
     1333    while (relIter.hasNext())
     1334    {
     1335      RelationMember curMember = relIter.next();
     1336      itineraryData.insertRow(insPos, curMember.getWay(), curMember.getRole());
     1337      if (insPos >= 0)
     1338        ++insPos;
     1339    }
     1340      }
     1341
    13421342      Iterator< LinkedList<RelationMember> > listIter = loops.iterator();
    13431343      while (listIter.hasNext())
    13441344      {
    1345         Iterator<RelationMember> relIter = listIter.next().iterator();
    1346         while (relIter.hasNext())
    1347         {
    1348           RelationMember curMember = relIter.next();
    1349           itineraryData.insertRow(insPos, curMember.getWay(), curMember.getRole());
    1350           if (insPos >= 0)
    1351             ++insPos;
    1352         }
    1353       }
    1354      
     1345    Iterator<RelationMember> relIter = listIter.next().iterator();
     1346    while (relIter.hasNext())
     1347    {
     1348      RelationMember curMember = relIter.next();
     1349      itineraryData.insertRow(insPos, curMember.getWay(), curMember.getRole());
     1350      if (insPos >= 0)
     1351        ++insPos;
     1352    }
     1353      }
     1354
    13551355      itineraryData.cleanupGaps();
    13561356      rebuildWays();
     
    13601360      Vector<RelationMember> itemsToReflect = new Vector<RelationMember>();
    13611361      int insPos = itineraryTable.getSelectedRow();
    1362      
     1362
    13631363      if (itineraryTable.getSelectedRowCount() > 0)
    13641364      {
    1365         for (int i = itineraryData.getRowCount()-1; i >=0; --i)
    1366         {
    1367           if ((itineraryTable.isRowSelected(i)) && (itineraryData.ways.elementAt(i) != null))
    1368           {
    1369             String role = (String)(itineraryData.getValueAt(i, 1));
    1370             if ("backward".equals(role))
    1371               role = "forward";
    1372             else if ("forward".equals(role))
    1373               role = "backward";
    1374             else
    1375               role = "backward";
    1376             RelationMember markedWay = new RelationMember
    1377                 (role, itineraryData.ways.elementAt(i));
    1378             itemsToReflect.addElement(markedWay);
    1379            
    1380             itineraryData.ways.removeElementAt(i);
    1381             itineraryData.removeRow(i);
    1382           }
    1383         }
     1365    for (int i = itineraryData.getRowCount()-1; i >=0; --i)
     1366    {
     1367      if ((itineraryTable.isRowSelected(i)) && (itineraryData.ways.elementAt(i) != null))
     1368      {
     1369        String role = (String)(itineraryData.getValueAt(i, 1));
     1370        if ("backward".equals(role))
     1371          role = "forward";
     1372        else if ("forward".equals(role))
     1373          role = "backward";
     1374        else
     1375          role = "backward";
     1376        RelationMember markedWay = new RelationMember
     1377        (role, itineraryData.ways.elementAt(i));
     1378        itemsToReflect.addElement(markedWay);
     1379
     1380        itineraryData.ways.removeElementAt(i);
     1381        itineraryData.removeRow(i);
     1382      }
     1383    }
    13841384      }
    13851385      else
    13861386      {
    1387         for (int i = itineraryData.getRowCount()-1; i >=0; --i)
    1388         {
    1389           if (itineraryData.ways.elementAt(i) != null)
    1390           {
    1391             String role = (String)(itineraryData.getValueAt(i, 1));
    1392             if ("backward".equals(role))
    1393               role = "forward";
    1394             else if ("forward".equals(role))
    1395               role = "backward";
    1396             else
    1397               role = "backward";
    1398             RelationMember markedWay = new RelationMember
    1399                 (role, itineraryData.ways.elementAt(i));
    1400             itemsToReflect.addElement(markedWay);
    1401           }
    1402         }
    1403        
    1404         itineraryData.clear();
     1387    for (int i = itineraryData.getRowCount()-1; i >=0; --i)
     1388    {
     1389      if (itineraryData.ways.elementAt(i) != null)
     1390      {
     1391        String role = (String)(itineraryData.getValueAt(i, 1));
     1392        if ("backward".equals(role))
     1393          role = "forward";
     1394        else if ("forward".equals(role))
     1395          role = "backward";
     1396        else
     1397          role = "backward";
     1398        RelationMember markedWay = new RelationMember
     1399        (role, itineraryData.ways.elementAt(i));
     1400        itemsToReflect.addElement(markedWay);
     1401      }
     1402    }
     1403
     1404    itineraryData.clear();
    14051405      }
    14061406
     
    14091409      while (relIter.hasNext())
    14101410      {
    1411         RelationMember curMember = relIter.next();
    1412         if (curMember.isWay())
    1413         {
    1414           itineraryData.insertRow(insPos, curMember.getWay(), curMember.getRole());
    1415           if (insPos >= 0)
    1416             ++insPos;
    1417         }
    1418       }
     1411    RelationMember curMember = relIter.next();
     1412    if (curMember.isWay())
     1413    {
     1414      itineraryData.insertRow(insPos, curMember.getWay(), curMember.getRole());
    14191415      if (insPos >= 0)
    1420         itineraryTable.addRowSelectionInterval(startPos, insPos-1);
    1421      
     1416        ++insPos;
     1417    }
     1418      }
     1419      if (insPos >= 0)
     1420    itineraryTable.addRowSelectionInterval(startPos, insPos-1);
     1421
    14221422      itineraryData.cleanupGaps();
    14231423      rebuildWays();
     
    14261426    {
    14271427      if (mainDataSet == null)
    1428         return;
    1429      
     1428    return;
     1429
    14301430      stoplistTable.clearSelection();
    1431      
     1431
    14321432      for (int i = 0; i < stoplistData.getRowCount(); ++i)
    14331433      {
    1434         if ((stoplistData.nodes.elementAt(i) != null) &&
    1435               (mainDataSet.isSelected(stoplistData.nodes.elementAt(i))))
    1436           stoplistTable.addRowSelectionInterval(i, i);
     1434    if ((stoplistData.nodes.elementAt(i) != null) &&
     1435          (mainDataSet.isSelected(stoplistData.nodes.elementAt(i))))
     1436      stoplistTable.addRowSelectionInterval(i, i);
    14371437      }
    14381438    }
     
    14421442      if (stoplistTable.getSelectedRowCount() > 0)
    14431443      {
    1444         for (int i = 0; i < stoplistData.getRowCount(); ++i)
    1445         {
    1446           if (stoplistTable.isRowSelected(i))
    1447           {
    1448             stoplistData.nodes.elementAt(i).visit(box);
    1449           }
    1450         }
     1444    for (int i = 0; i < stoplistData.getRowCount(); ++i)
     1445    {
     1446      if (stoplistTable.isRowSelected(i))
     1447      {
     1448        stoplistData.nodes.elementAt(i).visit(box);
     1449      }
     1450    }
    14511451      }
    14521452      else
    14531453      {
    1454         for (int i = 0; i < stoplistData.getRowCount(); ++i)
    1455         {
    1456           stoplistData.nodes.elementAt(i).visit(box);
    1457         }
     1454    for (int i = 0; i < stoplistData.getRowCount(); ++i)
     1455    {
     1456      stoplistData.nodes.elementAt(i).visit(box);
     1457    }
    14581458      }
    14591459      if (box.getBounds() == null)
    1460         return;
     1460    return;
    14611461      box.enlargeBoundingBox();
    14621462      Main.map.mapView.recalculateCenterScale(box);
     
    14691469      if (stoplistTable.getSelectedRowCount() > 0)
    14701470      {
    1471         for (int i = 0; i < stoplistData.getRowCount(); ++i)
    1472         {
    1473           if (stoplistTable.isRowSelected(i))
    1474           {
    1475             mainDataSet.addSelected(stoplistData.nodes.elementAt(i));
    1476            
    1477             RelationMember markedNode = new RelationMember
    1478                 ((String)(stoplistData.getValueAt(i, 1)), stoplistData.nodes.elementAt(i));
    1479             markedNodes.addElement(markedNode);
    1480           }
    1481         }
     1471    for (int i = 0; i < stoplistData.getRowCount(); ++i)
     1472    {
     1473      if (stoplistTable.isRowSelected(i))
     1474      {
     1475        mainDataSet.addSelected(stoplistData.nodes.elementAt(i));
     1476
     1477        RelationMember markedNode = new RelationMember
     1478        ((String)(stoplistData.getValueAt(i, 1)), stoplistData.nodes.elementAt(i));
     1479        markedNodes.addElement(markedNode);
     1480      }
     1481    }
    14821482      }
    14831483      else
    14841484      {
    1485         for (int i = 0; i < stoplistData.getRowCount(); ++i)
    1486         {
    1487           mainDataSet.addSelected(stoplistData.nodes.elementAt(i));
    1488            
    1489           RelationMember markedNode = new RelationMember
    1490               ((String)(stoplistData.getValueAt(i, 1)), stoplistData.nodes.elementAt(i));
    1491           markedNodes.addElement(markedNode);
    1492         }
     1485    for (int i = 0; i < stoplistData.getRowCount(); ++i)
     1486    {
     1487      mainDataSet.addSelected(stoplistData.nodes.elementAt(i));
     1488
     1489      RelationMember markedNode = new RelationMember
     1490          ((String)(stoplistData.getValueAt(i, 1)), stoplistData.nodes.elementAt(i));
     1491      markedNodes.addElement(markedNode);
     1492    }
    14931493      }
    14941494    }
     
    14991499      TreeSet<Node> addedNodes = new TreeSet<Node>();
    15001500      if (mainDataSet == null)
    1501         return;
    1502      
     1501    return;
     1502
    15031503      while (relIter.hasNext())
    15041504      {
    1505         RelationMember curMember = relIter.next();
    1506         if ((curMember.isNode()) && (mainDataSet.isSelected(curMember.getNode())))
    1507         {
    1508           stoplistData.insertRow(insPos, curMember.getNode(), curMember.getRole());
    1509           if (insPos >= 0)
    1510             ++insPos;
    1511          
    1512           addedNodes.add(curMember.getNode());
    1513         }
    1514       }
    1515      
     1505    RelationMember curMember = relIter.next();
     1506    if ((curMember.isNode()) && (mainDataSet.isSelected(curMember.getNode())))
     1507    {
     1508      stoplistData.insertRow(insPos, curMember.getNode(), curMember.getRole());
     1509      if (insPos >= 0)
     1510        ++insPos;
     1511
     1512      addedNodes.add(curMember.getNode());
     1513    }
     1514      }
     1515
    15161516      Collection<Node> selectedNodes = mainDataSet.getSelectedNodes();
    15171517      Iterator<Node> nodeIter = selectedNodes.iterator();
    1518      
     1518
    15191519      while (nodeIter.hasNext())
    15201520      {
    1521         Node curMember = nodeIter.next();
    1522         if (!(addedNodes.contains(curMember)))
    1523         {
    1524           stoplistData.insertRow(insPos, curMember, "");
    1525           if (insPos >= 0)
    1526             ++insPos;
    1527         }
    1528       }
    1529      
     1521    Node curMember = nodeIter.next();
     1522    if (!(addedNodes.contains(curMember)))
     1523    {
     1524      stoplistData.insertRow(insPos, curMember, "");
     1525      if (insPos >= 0)
     1526        ++insPos;
     1527    }
     1528      }
     1529
    15301530      if ((insPos > 0) && (insPos < stoplistData.getRowCount()))
    15311531      {
    1532         while ((insPos < stoplistData.getRowCount())
    1533                        && (stoplistData.nodes.elementAt(insPos) == null))
    1534           ++insPos;
    1535         stoplistTable.removeRowSelectionInterval(0, stoplistData.getRowCount()-1);
    1536         if (insPos < stoplistData.getRowCount())
    1537           stoplistTable.addRowSelectionInterval(insPos, insPos);
     1532    while ((insPos < stoplistData.getRowCount())
     1533               && (stoplistData.nodes.elementAt(insPos) == null))
     1534      ++insPos;
     1535    stoplistTable.removeRowSelectionInterval(0, stoplistData.getRowCount()-1);
     1536    if (insPos < stoplistData.getRowCount())
     1537      stoplistTable.addRowSelectionInterval(insPos, insPos);
    15381538      }
    15391539
     
    15441544      for (int i = stoplistData.getRowCount()-1; i >=0; --i)
    15451545      {
    1546         if (stoplistTable.isRowSelected(i))
    1547         {
    1548           stoplistData.nodes.removeElementAt(i);
    1549           stoplistData.removeRow(i);
    1550         }
    1551       }
    1552    
     1546    if (stoplistTable.isRowSelected(i))
     1547    {
     1548      stoplistData.nodes.removeElementAt(i);
     1549      stoplistData.removeRow(i);
     1550    }
     1551      }
     1552
    15531553      rebuildNodes();
    15541554    }
     
    15601560      for (int i = 0; i < itineraryData.getRowCount(); ++i)
    15611561      {
    1562         if (itineraryData.ways.elementAt(i) != null)
    1563         {
    1564           Way way = itineraryData.ways.elementAt(i);
    1565           if (!(way.isIncomplete()))
    1566           {
    1567             if ("backward".equals((String)(itineraryData.getValueAt(i, 1))))
    1568             {
    1569               for (int j = way.getNodesCount()-2; j >= 0; --j)
    1570               {
    1571                 SegmentMetric sm = new SegmentMetric
    1572                     (way.getNode(j+1).getCoor().lat(), way.getNode(j+1).getCoor().lon(),
    1573                      way.getNode(j).getCoor().lat(), way.getNode(j).getCoor().lon());
    1574                 segmentMetrics.add(sm);
    1575               }
    1576             }
    1577             else
    1578             {
    1579               for (int j = 0; j < way.getNodesCount()-1; ++j)
    1580               {
    1581                 SegmentMetric sm = new SegmentMetric
    1582                     (way.getNode(j).getCoor().lat(), way.getNode(j).getCoor().lon(),
    1583                      way.getNode(j+1).getCoor().lat(), way.getNode(j+1).getCoor().lon());
    1584                 segmentMetrics.add(sm);
    1585               }
    1586             }
    1587           }
    1588         }
    1589         else
    1590         {
    1591           segmentMetrics.add(null);
    1592         }
    1593       }
    1594      
     1562    if (itineraryData.ways.elementAt(i) != null)
     1563    {
     1564      Way way = itineraryData.ways.elementAt(i);
     1565      if (!(way.isIncomplete()))
     1566      {
     1567        if ("backward".equals((String)(itineraryData.getValueAt(i, 1))))
     1568        {
     1569          for (int j = way.getNodesCount()-2; j >= 0; --j)
     1570          {
     1571        SegmentMetric sm = new SegmentMetric
     1572            (way.getNode(j+1).getCoor().lat(), way.getNode(j+1).getCoor().lon(),
     1573             way.getNode(j).getCoor().lat(), way.getNode(j).getCoor().lon());
     1574        segmentMetrics.add(sm);
     1575          }
     1576        }
     1577        else
     1578        {
     1579          for (int j = 0; j < way.getNodesCount()-1; ++j)
     1580          {
     1581        SegmentMetric sm = new SegmentMetric
     1582            (way.getNode(j).getCoor().lat(), way.getNode(j).getCoor().lon(),
     1583             way.getNode(j+1).getCoor().lat(), way.getNode(j+1).getCoor().lon());
     1584        segmentMetrics.add(sm);
     1585          }
     1586        }
     1587      }
     1588    }
     1589    else
     1590    {
     1591      segmentMetrics.add(null);
     1592    }
     1593      }
     1594
    15951595      Vector< StopReference > srm = new Vector< StopReference >();
    15961596      int insPos = stoplistTable.getSelectedRow();
     
    15991599        // Determine for each member its position on the itinerary: position means here the
    16001600        // point on the itinerary that has minimal distance to the coor
    1601         for (int i = stoplistData.getRowCount()-1; i >= 0; --i)
    1602         {
    1603           if (stoplistTable.isRowSelected(i))
    1604           {
    1605             StopReference sr = detectMinDistance
    1606                 (stoplistData.nodes.elementAt(i), segmentMetrics,
    1607                 cbRight.isSelected(), cbLeft.isSelected());
    1608             if (sr != null)
    1609             {
    1610               if (sr.distance <
    1611                         Double.parseDouble(tfSuggestStopsLimit.getText()) * 9.0 / 1000000.0 )
    1612               {
    1613                 sr.role = (String)stoplistData.getValueAt(i, 1);
    1614                 srm.addElement(sr);
    1615               }
    1616               else
    1617               {
    1618                 sr.role = (String)stoplistData.getValueAt(i, 1);
    1619                 sr.index = segmentMetrics.size()*2;
    1620                 sr.pos = 0;
    1621                 srm.addElement(sr);
    1622               }
    1623              
    1624               stoplistData.nodes.removeElementAt(i);
    1625               stoplistData.removeRow(i);
    1626             }
    1627          
    1628           }
    1629         }
     1601    for (int i = stoplistData.getRowCount()-1; i >= 0; --i)
     1602    {
     1603      if (stoplistTable.isRowSelected(i))
     1604      {
     1605        StopReference sr = detectMinDistance
     1606        (stoplistData.nodes.elementAt(i), segmentMetrics,
     1607        cbRight.isSelected(), cbLeft.isSelected());
     1608        if (sr != null)
     1609        {
     1610          if (sr.distance <
     1611            Double.parseDouble(tfSuggestStopsLimit.getText()) * 9.0 / 1000000.0 )
     1612          {
     1613        sr.role = (String)stoplistData.getValueAt(i, 1);
     1614        srm.addElement(sr);
     1615          }
     1616          else
     1617          {
     1618        sr.role = (String)stoplistData.getValueAt(i, 1);
     1619        sr.index = segmentMetrics.size()*2;
     1620        sr.pos = 0;
     1621        srm.addElement(sr);
     1622          }
     1623
     1624          stoplistData.nodes.removeElementAt(i);
     1625          stoplistData.removeRow(i);
     1626        }
     1627
     1628      }
     1629    }
    16301630      }
    16311631      else
    16321632      {
    1633         // Determine for each member its position on the itinerary: position means here the
     1633    // Determine for each member its position on the itinerary: position means here the
    16341634        // point on the itinerary that has minimal distance to the coor
    1635         for (int i = stoplistData.getRowCount()-1; i >= 0; --i)
    1636         {
    1637           StopReference sr = detectMinDistance
    1638               (stoplistData.nodes.elementAt(i), segmentMetrics,
    1639                cbRight.isSelected(), cbLeft.isSelected());
    1640           if (sr != null)
    1641           {
    1642             if (sr.distance <
    1643                        Double.parseDouble(tfSuggestStopsLimit.getText()) * 9.0 / 1000000.0 )
    1644             {
    1645               sr.role = (String)stoplistData.getValueAt(i, 1);
    1646               srm.addElement(sr);
    1647             }
    1648             else
    1649             {
    1650               sr.role = (String)stoplistData.getValueAt(i, 1);
    1651               sr.index = segmentMetrics.size()*2;
    1652               sr.pos = 0;
    1653               srm.addElement(sr);
    1654             }
    1655           }
    1656         }
    1657      
    1658         stoplistData.clear();
     1635    for (int i = stoplistData.getRowCount()-1; i >= 0; --i)
     1636    {
     1637      StopReference sr = detectMinDistance
     1638          (stoplistData.nodes.elementAt(i), segmentMetrics,
     1639           cbRight.isSelected(), cbLeft.isSelected());
     1640      if (sr != null)
     1641      {
     1642        if (sr.distance <
     1643               Double.parseDouble(tfSuggestStopsLimit.getText()) * 9.0 / 1000000.0 )
     1644        {
     1645          sr.role = (String)stoplistData.getValueAt(i, 1);
     1646          srm.addElement(sr);
     1647        }
     1648        else
     1649        {
     1650          sr.role = (String)stoplistData.getValueAt(i, 1);
     1651          sr.index = segmentMetrics.size()*2;
     1652          sr.pos = 0;
     1653          srm.addElement(sr);
     1654        }
     1655      }
     1656    }
     1657
     1658    stoplistData.clear();
    16591659      }
    16601660
    16611661      Collections.sort(srm);
    1662      
     1662
    16631663      for (int i = 0; i < srm.size(); ++i)
    16641664      {
    1665         stoplistData.insertRow(insPos, srm.elementAt(i).node, srm.elementAt(i).role);
    1666         if (insPos >= 0)
    1667           ++insPos;
    1668       }
    1669      
     1665    stoplistData.insertRow(insPos, srm.elementAt(i).node, srm.elementAt(i).role);
     1666    if (insPos >= 0)
     1667      ++insPos;
     1668      }
     1669
    16701670      rebuildNodes();
    16711671    }
     
    16741674      Vector<RelationMember> itemsToReflect = new Vector<RelationMember>();
    16751675      int insPos = stoplistTable.getSelectedRow();
    1676      
     1676
    16771677      if (stoplistTable.getSelectedRowCount() > 0)
    16781678      {
    1679         for (int i = stoplistData.getRowCount()-1; i >=0; --i)
    1680         {
    1681           if (stoplistTable.isRowSelected(i))
    1682           {
    1683             String role = (String)(stoplistData.getValueAt(i, 1));
    1684             RelationMember markedNode = new RelationMember
    1685                 (role, stoplistData.nodes.elementAt(i));
    1686             itemsToReflect.addElement(markedNode);
    1687            
    1688             stoplistData.nodes.removeElementAt(i);
    1689             stoplistData.removeRow(i);
    1690           }
    1691         }
     1679    for (int i = stoplistData.getRowCount()-1; i >=0; --i)
     1680    {
     1681      if (stoplistTable.isRowSelected(i))
     1682      {
     1683        String role = (String)(stoplistData.getValueAt(i, 1));
     1684        RelationMember markedNode = new RelationMember
     1685        (role, stoplistData.nodes.elementAt(i));
     1686        itemsToReflect.addElement(markedNode);
     1687
     1688        stoplistData.nodes.removeElementAt(i);
     1689        stoplistData.removeRow(i);
     1690      }
     1691    }
    16921692      }
    16931693      else
    16941694      {
    1695         for (int i = stoplistData.getRowCount()-1; i >=0; --i)
    1696         {
    1697           String role = (String)(stoplistData.getValueAt(i, 1));
    1698           RelationMember markedNode = new RelationMember
    1699               (role, stoplistData.nodes.elementAt(i));
    1700           itemsToReflect.addElement(markedNode);
    1701         }
    1702        
    1703         stoplistData.clear();
     1695    for (int i = stoplistData.getRowCount()-1; i >=0; --i)
     1696    {
     1697      String role = (String)(stoplistData.getValueAt(i, 1));
     1698      RelationMember markedNode = new RelationMember
     1699          (role, stoplistData.nodes.elementAt(i));
     1700      itemsToReflect.addElement(markedNode);
     1701    }
     1702
     1703    stoplistData.clear();
    17041704      }
    17051705
     
    17081708      while (relIter.hasNext())
    17091709      {
    1710         RelationMember curMember = relIter.next();
    1711         if (curMember.isNode())
    1712         {
    1713           stoplistData.insertRow(insPos, curMember.getNode(), curMember.getRole());
    1714           if (insPos >= 0)
    1715             ++insPos;
    1716         }
    1717       }
     1710    RelationMember curMember = relIter.next();
     1711    if (curMember.isNode())
     1712    {
     1713      stoplistData.insertRow(insPos, curMember.getNode(), curMember.getRole());
    17181714      if (insPos >= 0)
    1719         stoplistTable.addRowSelectionInterval(startPos, insPos-1);
    1720      
     1715        ++insPos;
     1716    }
     1717      }
     1718      if (insPos >= 0)
     1719    stoplistTable.addRowSelectionInterval(startPos, insPos-1);
     1720
    17211721      rebuildNodes();
    17221722    }
     
    17281728      for (int i = 0; i < itineraryData.getRowCount(); ++i)
    17291729      {
    1730         if (itineraryData.ways.elementAt(i) != null)
    1731         {
    1732           Way way = itineraryData.ways.elementAt(i);
    1733           if (!(way.isIncomplete()))
    1734           {
    1735             if ("backward".equals((String)(itineraryData.getValueAt(i, 1))))
    1736             {
    1737               for (int j = way.getNodesCount()-2; j >= 0; --j)
    1738               {
    1739                 SegmentMetric sm = new SegmentMetric
    1740                     (way.getNode(j+1).getCoor().lat(), way.getNode(j+1).getCoor().lon(),
    1741                      way.getNode(j).getCoor().lat(), way.getNode(j).getCoor().lon());
    1742                 segmentMetrics.add(sm);
    1743               }
    1744             }
    1745             else
    1746             {
    1747               for (int j = 0; j < way.getNodesCount()-1; ++j)
    1748               {
    1749                 SegmentMetric sm = new SegmentMetric
    1750                     (way.getNode(j).getCoor().lat(), way.getNode(j).getCoor().lon(),
    1751                      way.getNode(j+1).getCoor().lat(), way.getNode(j+1).getCoor().lon());
    1752                 segmentMetrics.add(sm);
    1753               }
    1754             }
    1755           }
    1756         }
    1757         else
    1758         {
    1759           segmentMetrics.add(null);
    1760         }
    1761       }
    1762      
     1730    if (itineraryData.ways.elementAt(i) != null)
     1731    {
     1732      Way way = itineraryData.ways.elementAt(i);
     1733      if (!(way.isIncomplete()))
     1734      {
     1735        if ("backward".equals((String)(itineraryData.getValueAt(i, 1))))
     1736        {
     1737          for (int j = way.getNodesCount()-2; j >= 0; --j)
     1738          {
     1739        SegmentMetric sm = new SegmentMetric
     1740            (way.getNode(j+1).getCoor().lat(), way.getNode(j+1).getCoor().lon(),
     1741             way.getNode(j).getCoor().lat(), way.getNode(j).getCoor().lon());
     1742        segmentMetrics.add(sm);
     1743          }
     1744        }
     1745        else
     1746        {
     1747          for (int j = 0; j < way.getNodesCount()-1; ++j)
     1748          {
     1749        SegmentMetric sm = new SegmentMetric
     1750            (way.getNode(j).getCoor().lat(), way.getNode(j).getCoor().lon(),
     1751             way.getNode(j+1).getCoor().lat(), way.getNode(j+1).getCoor().lon());
     1752        segmentMetrics.add(sm);
     1753          }
     1754        }
     1755      }
     1756    }
     1757    else
     1758    {
     1759      segmentMetrics.add(null);
     1760    }
     1761      }
     1762
    17631763      Vector< StopReference > srm = new Vector< StopReference >();
    17641764      // Determine for each member its position on the itinerary: position means here the
     
    17671767      if (mainDataSet != null)
    17681768      {
    1769         String stopKey = "";
    1770         String stopValue = "";
    1771         if ("bus".equals(currentRoute.get("route")))
    1772         {
    1773           stopKey = "highway";
    1774           stopValue = "bus_stop";
    1775         }
    1776         else if ("trolleybus".equals(currentRoute.get("route")))
    1777         {
    1778           stopKey = "highway";
    1779           stopValue = "bus_stop";
    1780         }
    1781         else if ("tram".equals(currentRoute.get("route")))
    1782         {
    1783           stopKey = "railway";
    1784           stopValue = "tram_stop";
    1785         }
    1786         else if ("light_rail".equals(currentRoute.get("route")))
    1787         {
    1788           stopKey = "railway";
    1789           stopValue = "station";
    1790         }
    1791         else if ("subway".equals(currentRoute.get("route")))
    1792         {
    1793           stopKey = "railway";
    1794           stopValue = "station";
    1795         }
    1796         else if ("rail".equals(currentRoute.get("route")))
    1797         {
    1798           stopKey = "railway";
    1799           stopValue = "station";
    1800         }
    1801 
    1802         Collection< Node > nodeCollection = mainDataSet.getNodes();
    1803         Iterator< Node > nodeIter = nodeCollection.iterator();
    1804         while (nodeIter.hasNext())
    1805         {
    1806           Node currentNode = nodeIter.next();
    1807           if (!currentNode.isUsable())
    1808             continue;
    1809           if (stopValue.equals(currentNode.get(stopKey)))
    1810           {
    1811             StopReference sr = detectMinDistance
    1812                 (currentNode, segmentMetrics,
    1813                 cbRight.isSelected(), cbLeft.isSelected());
    1814             if ((sr != null) && (sr.distance <
    1815                         Double.parseDouble(tfSuggestStopsLimit.getText()) * 9.0 / 1000000.0 ))
    1816               srm.addElement(sr);
    1817           }
    1818         }
     1769    String stopKey = "";
     1770    String stopValue = "";
     1771    if ("bus".equals(currentRoute.get("route")))
     1772    {
     1773      stopKey = "highway";
     1774      stopValue = "bus_stop";
     1775    }
     1776    else if ("trolleybus".equals(currentRoute.get("route")))
     1777    {
     1778      stopKey = "highway";
     1779      stopValue = "bus_stop";
     1780    }
     1781    else if ("tram".equals(currentRoute.get("route")))
     1782    {
     1783      stopKey = "railway";
     1784      stopValue = "tram_stop";
     1785    }
     1786    else if ("light_rail".equals(currentRoute.get("route")))
     1787    {
     1788      stopKey = "railway";
     1789      stopValue = "station";
     1790    }
     1791    else if ("subway".equals(currentRoute.get("route")))
     1792    {
     1793      stopKey = "railway";
     1794      stopValue = "station";
     1795    }
     1796    else if ("rail".equals(currentRoute.get("route")))
     1797    {
     1798      stopKey = "railway";
     1799      stopValue = "station";
     1800    }
     1801
     1802    Collection< Node > nodeCollection = mainDataSet.getNodes();
     1803    Iterator< Node > nodeIter = nodeCollection.iterator();
     1804    while (nodeIter.hasNext())
     1805    {
     1806      Node currentNode = nodeIter.next();
     1807      if (!currentNode.isUsable())
     1808        continue;
     1809      if (stopValue.equals(currentNode.get(stopKey)))
     1810      {
     1811        StopReference sr = detectMinDistance
     1812        (currentNode, segmentMetrics,
     1813        cbRight.isSelected(), cbLeft.isSelected());
     1814        if ((sr != null) && (sr.distance <
     1815            Double.parseDouble(tfSuggestStopsLimit.getText()) * 9.0 / 1000000.0 ))
     1816          srm.addElement(sr);
     1817      }
     1818    }
    18191819      }
    18201820      else
    18211821      {
    1822         JOptionPane.showMessageDialog(null, "There exists no dataset."
    1823             + " Try to download data from the server or open an OSM file.",
     1822    JOptionPane.showMessageDialog(null, "There exists no dataset."
     1823        + " Try to download data from the server or open an OSM file.",
    18241824     "No data found", JOptionPane.ERROR_MESSAGE);
    1825      
    1826         System.out.println("Public Transport: RoutePattern: No data found");
    1827       }
    1828      
     1825
     1826    System.out.println("Public Transport: RoutePattern: No data found");
     1827      }
     1828
    18291829      for (int i = 0; i < stoplistData.getRowCount(); ++i)
    18301830      {
     
    18321832
    18331833      Collections.sort(srm);
    1834      
     1834
    18351835      stoplistData.clear();
    18361836      for (int i = 0; i < srm.size(); ++i)
    18371837      {
    1838         stoplistData.addRow(srm.elementAt(i).node, srm.elementAt(i).role);
    1839       }
    1840      
     1838    stoplistData.addRow(srm.elementAt(i).node, srm.elementAt(i).role);
     1839      }
     1840
    18411841      rebuildNodes();
    18421842    }
     
    18441844    {
    18451845      refreshData();
    1846      
     1846
    18471847      jDialog.setLocationRelativeTo(frame);
    18481848      jDialog.setVisible(true);
    18491849    }
    18501850  }
    1851  
     1851
    18521852  private void refreshData() {
    18531853    Relation copy = currentRoute;
    18541854    relsListModel.clear();
    18551855    currentRoute = copy;
    1856        
     1856
    18571857    DataSet mainDataSet = Main.main.getCurrentDataSet();
    18581858    if (mainDataSet != null)
     
    18611861      Collection< Relation > relCollection = mainDataSet.getRelations();
    18621862      Iterator< Relation > relIter = relCollection.iterator();
    1863      
     1863
    18641864      while (relIter.hasNext())
    18651865      {
    1866         Relation currentRel = relIter.next();
    1867         if (!currentRel.isDeleted())
    1868         {
    1869           String routeVal = currentRel.get("route");
    1870           if ("bus".equals(routeVal))
    1871             relRefs.add(new RouteReference(currentRel));
    1872           else if ("trolleybus".equals(routeVal))
    1873             relRefs.add(new RouteReference(currentRel));
    1874           else if ("tram".equals(routeVal))
    1875             relRefs.add(new RouteReference(currentRel));
    1876           else if ("light_rail".equals(routeVal))
    1877             relRefs.add(new RouteReference(currentRel));
    1878           else if ("subway".equals(routeVal))
    1879             relRefs.add(new RouteReference(currentRel));
    1880           else if ("rail".equals(routeVal))
    1881             relRefs.add(new RouteReference(currentRel));
    1882         }
    1883       }
    1884      
     1866    Relation currentRel = relIter.next();
     1867    if (!currentRel.isDeleted())
     1868    {
     1869      String routeVal = currentRel.get("route");
     1870      if ("bus".equals(routeVal))
     1871        relRefs.add(new RouteReference(currentRel));
     1872      else if ("trolleybus".equals(routeVal))
     1873        relRefs.add(new RouteReference(currentRel));
     1874      else if ("tram".equals(routeVal))
     1875        relRefs.add(new RouteReference(currentRel));
     1876      else if ("light_rail".equals(routeVal))
     1877        relRefs.add(new RouteReference(currentRel));
     1878      else if ("subway".equals(routeVal))
     1879        relRefs.add(new RouteReference(currentRel));
     1880      else if ("rail".equals(routeVal))
     1881        relRefs.add(new RouteReference(currentRel));
     1882    }
     1883      }
     1884
    18851885      Collections.sort(relRefs);
    18861886
    18871887      Iterator< RouteReference > iter = relRefs.iterator();
    18881888      while (iter.hasNext())
    1889         relsListModel.addElement(iter.next());
     1889    relsListModel.addElement(iter.next());
    18901890    }
    18911891    else
    18921892    {
    18931893      JOptionPane.showMessageDialog(null, "There exists no dataset."
    1894           + " Try to download data from the server or open an OSM file.",
     1894      + " Try to download data from the server or open an OSM file.",
    18951895   "No data found", JOptionPane.ERROR_MESSAGE);
    1896      
     1896
    18971897      System.out.println("Public Transport: No data found");
    18981898    }
    18991899  }
    1900  
     1900
    19011901  //Rebuild ways in the relation currentRoute
    19021902  public static void rebuildWays() {
     
    19071907    {
    19081908      if (iter.next().isWay())
    1909         iter.remove();
     1909    iter.remove();
    19101910    }
    19111911    for (int i = 0; i < itineraryData.getRowCount(); ++i)
     
    19131913      if (itineraryData.ways.elementAt(i) != null)
    19141914      {
    1915         RelationMember member = new RelationMember
    1916             ((String)(itineraryData.getValueAt(i, 1)),
    1917              itineraryData.ways.elementAt(i));
    1918         members.add(member);
     1915    RelationMember member = new RelationMember
     1916        ((String)(itineraryData.getValueAt(i, 1)),
     1917         itineraryData.ways.elementAt(i));
     1918    members.add(member);
    19191919      }
    19201920    }
    19211921    currentRoute.setMembers(members);
    19221922  }
    1923  
     1923
    19241924  //Rebuild nodes in the relation currentRoute
    19251925  private void rebuildNodes() {
     
    19291929      if (currentRoute.getMember(i).isNode())
    19301930      {
    1931         currentRoute.removeMember(i);
     1931    currentRoute.removeMember(i);
    19321932      }
    19331933    }
     
    19351935    {
    19361936      RelationMember member = new RelationMember
    1937           ((String)(stoplistData.getValueAt(i, 1)), stoplistData.nodes.elementAt(i));
     1937      ((String)(stoplistData.getValueAt(i, 1)), stoplistData.nodes.elementAt(i));
    19381938      currentRoute.addMember(member);
    19391939    }
    19401940  }
    1941  
     1941
    19421942  private void addWayToSortingData
    19431943      (Way way, TreeMap<Node, LinkedList<RelationMember> > frontNodes,
     
    19471947    if (way.getNodesCount() < 1)
    19481948      return;
    1949    
     1949
    19501950    Node firstNode = way.getNode(0);
    19511951    Node lastNode = way.getNode(way.getNodesCount() - 1);
    1952    
     1952
    19531953    if (frontNodes.get(firstNode) != null)
    19541954    {
     
    19561956      list.addFirst(new RelationMember("backward", way));
    19571957      frontNodes.remove(firstNode);
    1958      
     1958
    19591959      Node lastListNode = null;
    19601960      if ("backward".equals(list.getLast().getRole()))
    1961         lastListNode = list.getLast().getWay().getNode(0);
     1961    lastListNode = list.getLast().getWay().getNode(0);
    19621962      else
    1963         lastListNode = list.getLast().getWay().getNode
    1964             (list.getLast().getWay().getNodesCount() - 1);
     1963    lastListNode = list.getLast().getWay().getNode
     1964        (list.getLast().getWay().getNodesCount() - 1);
    19651965      if (lastNode.equals(lastListNode))
    19661966      {
    1967         backNodes.remove(lastListNode);
    1968         loops.add(list);
     1967    backNodes.remove(lastListNode);
     1968    loops.add(list);
    19691969      }
    19701970      else if (frontNodes.get(lastNode) != null)
    19711971      {
    1972         backNodes.remove(lastListNode);
    1973         LinkedList<RelationMember> listToAppend = frontNodes.get(lastNode);
    1974         Iterator<RelationMember> memberIter = list.iterator();
    1975         while (memberIter.hasNext())
    1976         {
    1977           RelationMember member = memberIter.next();
    1978           if ("backward".equals(member.getRole()))
    1979             listToAppend.addFirst(new RelationMember("forward", member.getWay()));
    1980           else
    1981             listToAppend.addFirst(new RelationMember("backward", member.getWay()));
    1982         }
    1983         frontNodes.remove(lastNode);
    1984         frontNodes.put(lastListNode, listToAppend);
     1972    backNodes.remove(lastListNode);
     1973    LinkedList<RelationMember> listToAppend = frontNodes.get(lastNode);
     1974    Iterator<RelationMember> memberIter = list.iterator();
     1975    while (memberIter.hasNext())
     1976    {
     1977      RelationMember member = memberIter.next();
     1978      if ("backward".equals(member.getRole()))
     1979        listToAppend.addFirst(new RelationMember("forward", member.getWay()));
     1980      else
     1981        listToAppend.addFirst(new RelationMember("backward", member.getWay()));
     1982    }
     1983    frontNodes.remove(lastNode);
     1984    frontNodes.put(lastListNode, listToAppend);
    19851985      }
    19861986      else if (backNodes.get(lastNode) != null)
    19871987      {
    1988         backNodes.remove(lastListNode);
    1989         LinkedList<RelationMember> listToAppend = backNodes.get(lastNode);
    1990         Iterator<RelationMember> memberIter = list.iterator();
    1991         while (memberIter.hasNext())
    1992         {
    1993           RelationMember member = memberIter.next();
    1994           listToAppend.addLast(member);
    1995         }
    1996         backNodes.remove(lastNode);
    1997         backNodes.put(lastListNode, listToAppend);
     1988    backNodes.remove(lastListNode);
     1989    LinkedList<RelationMember> listToAppend = backNodes.get(lastNode);
     1990    Iterator<RelationMember> memberIter = list.iterator();
     1991    while (memberIter.hasNext())
     1992    {
     1993      RelationMember member = memberIter.next();
     1994      listToAppend.addLast(member);
     1995    }
     1996    backNodes.remove(lastNode);
     1997    backNodes.put(lastListNode, listToAppend);
    19981998      }
    19991999      else
    2000         frontNodes.put(lastNode, list);
     2000    frontNodes.put(lastNode, list);
    20012001    }
    20022002    else if (backNodes.get(firstNode) != null)
     
    20052005      list.addLast(new RelationMember("forward", way));
    20062006      backNodes.remove(firstNode);
    2007      
     2007
    20082008      Node firstListNode = null;
    20092009      if ("backward".equals(list.getFirst().getRole()))
    2010         firstListNode = list.getFirst().getWay().getNode
    2011             (list.getFirst().getWay().getNodesCount() - 1);
     2010    firstListNode = list.getFirst().getWay().getNode
     2011        (list.getFirst().getWay().getNodesCount() - 1);
    20122012      else
    2013         firstListNode = list.getFirst().getWay().getNode(0);
     2013    firstListNode = list.getFirst().getWay().getNode(0);
    20142014      if (lastNode.equals(firstListNode))
    20152015      {
    2016         frontNodes.remove(firstListNode);
    2017         loops.add(list);
     2016    frontNodes.remove(firstListNode);
     2017    loops.add(list);
    20182018      }
    20192019      else if (frontNodes.get(lastNode) != null)
    20202020      {
    2021         frontNodes.remove(firstListNode);
    2022         LinkedList<RelationMember> listToAppend = frontNodes.get(lastNode);
    2023         ListIterator<RelationMember> memberIter = list.listIterator(list.size());
    2024         while (memberIter.hasPrevious())
    2025         {
    2026           RelationMember member = memberIter.previous();
    2027           listToAppend.addFirst(member);
    2028         }
    2029         frontNodes.remove(lastNode);
    2030         frontNodes.put(firstListNode, listToAppend);
     2021    frontNodes.remove(firstListNode);
     2022    LinkedList<RelationMember> listToAppend = frontNodes.get(lastNode);
     2023    ListIterator<RelationMember> memberIter = list.listIterator(list.size());
     2024    while (memberIter.hasPrevious())
     2025    {
     2026      RelationMember member = memberIter.previous();
     2027      listToAppend.addFirst(member);
     2028    }
     2029    frontNodes.remove(lastNode);
     2030    frontNodes.put(firstListNode, listToAppend);
    20312031      }
    20322032      else if (backNodes.get(lastNode) != null)
    20332033      {
    2034         frontNodes.remove(firstListNode);
    2035         LinkedList<RelationMember> listToAppend = backNodes.get(lastNode);
    2036         ListIterator<RelationMember> memberIter = list.listIterator(list.size());
    2037         while (memberIter.hasPrevious())
    2038         {
    2039           RelationMember member = memberIter.previous();
    2040           if ("backward".equals(member.getRole()))
    2041             listToAppend.addLast(new RelationMember("forward", member.getWay()));
    2042           else
    2043             listToAppend.addLast(new RelationMember("backward", member.getWay()));
    2044         }
    2045         backNodes.remove(lastNode);
    2046         backNodes.put(firstListNode, listToAppend);
    2047       }
     2034    frontNodes.remove(firstListNode);
     2035    LinkedList<RelationMember> listToAppend = backNodes.get(lastNode);
     2036    ListIterator<RelationMember> memberIter = list.listIterator(list.size());
     2037    while (memberIter.hasPrevious())
     2038    {
     2039      RelationMember member = memberIter.previous();
     2040      if ("backward".equals(member.getRole()))
     2041        listToAppend.addLast(new RelationMember("forward", member.getWay()));
    20482042      else
    2049         backNodes.put(lastNode, list);
     2043        listToAppend.addLast(new RelationMember("backward", member.getWay()));
     2044    }
     2045    backNodes.remove(lastNode);
     2046    backNodes.put(firstListNode, listToAppend);
     2047      }
     2048      else
     2049    backNodes.put(lastNode, list);
    20502050    }
    20512051    else if (frontNodes.get(lastNode) != null)
     
    20712071    }
    20722072  }
    2073  
     2073
    20742074  private void routesSelectionChanged() {
    20752075    int selectedPos = relsList.getAnchorSelectionIndex();
     
    20812081      tabbedPane.setEnabledAt(3, true);
    20822082      tabbedPane.setEnabledAt(4, true);
    2083      
     2083
    20842084      //Prepare Tags
    20852085      requiredTagsData.readRelation(currentRoute);
    20862086      commonTagsData.readRelation(currentRoute);
    20872087      otherTagsData.readRelation(currentRoute, tagBlacklist);
    2088      
     2088
    20892089      //Prepare Itinerary
    20902090      itineraryData.clear();
     
    20922092      Iterator<RelationMember> relIter = relMembers.iterator();
    20932093      fillItineraryTable(relIter, 0, -1);
    2094    
     2094
    20952095      //Prepare Stoplist
    20962096      stoplistData.clear();
     
    21082108    }
    21092109  }
    2110  
     2110
    21112111  private void fillItineraryTable
    21122112      (Iterator<RelationMember> relIter, long lastNodeId, int insPos) {
     
    21162116      if (curMember.isWay())
    21172117      {
    2118         itineraryData.insertRow(insPos, curMember.getWay(), curMember.getRole());
    2119         if (insPos >= 0)
    2120           ++insPos;
     2118    itineraryData.insertRow(insPos, curMember.getWay(), curMember.getRole());
     2119    if (insPos >= 0)
     2120      ++insPos;
    21212121      }
    21222122    }
    21232123    itineraryData.cleanupGaps();
    21242124  }
    2125  
     2125
    21262126  private void fillStoplistTable
    21272127      (Iterator<RelationMember> relIter, int insPos) {
     
    21312131      if (curMember.isNode())
    21322132      {
    2133         stoplistData.insertRow(insPos, curMember.getNode(), curMember.getRole());
    2134         if (insPos >= 0)
    2135           ++insPos;
     2133    stoplistData.insertRow(insPos, curMember.getNode(), curMember.getRole());
     2134    if (insPos >= 0)
     2135      ++insPos;
    21362136      }
    21372137    }
    21382138  }
    2139  
     2139
    21402140  private StopReference detectMinDistance
    21412141      (Node node, Vector< SegmentMetric > segmentMetrics,
     
    21462146    double lat = node.getCoor().lat();
    21472147    double lon = node.getCoor().lon();
    2148        
     2148
    21492149    int curIndex = -2;
    21502150    double angleLat = 100.0;
     
    21552155      curIndex += 2;
    21562156      SegmentMetric sm = iter.next();
    2157          
     2157
    21582158      if (sm == null)
    21592159      {
    2160         angleLat = 100.0;
    2161         angleLon = 200.0;
    2162            
    2163         continue;
    2164       }
    2165          
     2160    angleLat = 100.0;
     2161    angleLon = 200.0;
     2162
     2163    continue;
     2164      }
     2165
    21662166      double curPosition = (lat - sm.aLat)*sm.d1 + (lon - sm.aLon)*sm.d2;
    2167          
     2167
    21682168      if (curPosition < 0)
    21692169      {
    2170         if (angleLat <= 90.0)
    2171         {
    2172           double lastSegAngle = Math.atan2(angleLat - sm.aLat, angleLon - sm.aLon);
    2173           double segAngle = Math.atan2(sm.d1, -sm.o1);
    2174           double vertexAngle = Math.atan2(lat - sm.aLat, lon - sm.aLon);
    2175 
    2176           boolean vertexOnSeg = (vertexAngle == segAngle) ||
    2177               (vertexAngle == lastSegAngle);
    2178           boolean vertexOnTheLeft = (!vertexOnSeg) &&
    2179               (((lastSegAngle > vertexAngle) && (vertexAngle > segAngle))
    2180               || ((vertexAngle > segAngle) && (segAngle > lastSegAngle))
    2181               || ((segAngle > lastSegAngle) && (lastSegAngle > vertexAngle)));
    2182 
    2183           double currentDistance = Math.sqrt((lat - sm.aLat)*(lat - sm.aLat)
    2184                 + (lon - sm.aLon)*(lon - sm.aLon)
    2185                 *Math.cos(sm.aLat * Math.PI/180.0)*Math.cos(sm.aLat * Math.PI/180.0));
    2186           curPosition = vertexAngle - segAngle;
    2187           if (vertexOnTheLeft)
    2188             curPosition = -curPosition;
    2189           if (curPosition < 0)
    2190             curPosition += 2*Math.PI;
    2191           if ((Math.abs(currentDistance) < distance)
    2192             && (((!vertexOnTheLeft) && (rhsPossible))
    2193                 || ((vertexOnTheLeft) && (lhsPossible))
    2194                || (vertexOnSeg)))
    2195           {
    2196             distance = Math.abs(currentDistance);
    2197             minIndex = curIndex-1;
    2198             position = curPosition;
    2199           }
    2200         }
    2201         angleLat = 100.0;
    2202         angleLon = 200.0;
     2170    if (angleLat <= 90.0)
     2171    {
     2172      double lastSegAngle = Math.atan2(angleLat - sm.aLat, angleLon - sm.aLon);
     2173      double segAngle = Math.atan2(sm.d1, -sm.o1);
     2174      double vertexAngle = Math.atan2(lat - sm.aLat, lon - sm.aLon);
     2175
     2176      boolean vertexOnSeg = (vertexAngle == segAngle) ||
     2177          (vertexAngle == lastSegAngle);
     2178      boolean vertexOnTheLeft = (!vertexOnSeg) &&
     2179          (((lastSegAngle > vertexAngle) && (vertexAngle > segAngle))
     2180          || ((vertexAngle > segAngle) && (segAngle > lastSegAngle))
     2181          || ((segAngle > lastSegAngle) && (lastSegAngle > vertexAngle)));
     2182
     2183      double currentDistance = Math.sqrt((lat - sm.aLat)*(lat - sm.aLat)
     2184        + (lon - sm.aLon)*(lon - sm.aLon)
     2185        *Math.cos(sm.aLat * Math.PI/180.0)*Math.cos(sm.aLat * Math.PI/180.0));
     2186      curPosition = vertexAngle - segAngle;
     2187      if (vertexOnTheLeft)
     2188        curPosition = -curPosition;
     2189      if (curPosition < 0)
     2190        curPosition += 2*Math.PI;
     2191      if ((Math.abs(currentDistance) < distance)
     2192        && (((!vertexOnTheLeft) && (rhsPossible))
     2193        || ((vertexOnTheLeft) && (lhsPossible))
     2194           || (vertexOnSeg)))
     2195      {
     2196        distance = Math.abs(currentDistance);
     2197        minIndex = curIndex-1;
     2198        position = curPosition;
     2199      }
     2200    }
     2201    angleLat = 100.0;
     2202    angleLon = 200.0;
    22032203      }
    22042204      else if (curPosition > sm.length)
    22052205      {
    2206         angleLat = sm.aLat;
    2207         angleLon = sm.aLon;
     2206    angleLat = sm.aLat;
     2207    angleLon = sm.aLon;
    22082208      }
    22092209      else
    22102210      {
    2211         double currentDistance = (lat - sm.aLat)*sm.o1 + (lon - sm.aLon)*sm.o2;
    2212         if ((Math.abs(currentDistance) < distance)
    2213                     && (((currentDistance >= 0) && (rhsPossible))
    2214                     || ((currentDistance <= 0) && (lhsPossible))))
    2215         {
    2216           distance = Math.abs(currentDistance);
    2217           minIndex = curIndex;
    2218           position = curPosition;
    2219         }
    2220            
    2221         angleLat = 100.0;
    2222         angleLon = 200.0;
    2223       }
    2224     }
    2225        
     2211    double currentDistance = (lat - sm.aLat)*sm.o1 + (lon - sm.aLon)*sm.o2;
     2212    if ((Math.abs(currentDistance) < distance)
     2213            && (((currentDistance >= 0) && (rhsPossible))
     2214            || ((currentDistance <= 0) && (lhsPossible))))
     2215    {
     2216      distance = Math.abs(currentDistance);
     2217      minIndex = curIndex;
     2218      position = curPosition;
     2219    }
     2220
     2221    angleLat = 100.0;
     2222    angleLon = 200.0;
     2223      }
     2224    }
     2225
    22262226    if (minIndex == -1)
    22272227      return new StopReference(segmentMetrics.size()*2, 0, 180.0, node.get("name"),
    2228                                "", node);
    2229          
     2228                   "", node);
     2229
    22302230    return new StopReference(minIndex, position, distance, node.get("name"),
    2231                              "", node);
     2231                 "", node);
    22322232  }
    22332233}
  • applications/editors/josm/plugins/public_transport/src/public_transport/SettingsStoptypeCommand.java

    r22048 r23192  
    2121      railway = node.get("railway");
    2222    }
    23    
     23
    2424    public Node node;
    2525    public String highway;
    2626    public String railway;
    2727  };
    28  
     28
    2929  private Vector< HighwayRailway > oldStrings = null;
    3030  private WaypointTableModel waypointTM = null;
    3131  private DefaultListModel tracksListModel = null;
    3232  private String type = null;
    33  
     33
    3434  public SettingsStoptypeCommand(StopImporterAction controller)
    3535  {
     
    3939    oldStrings = new Vector< HighwayRailway >();
    4040  }
    41  
     41
    4242  public boolean executeCommand()
    4343  {
     
    4747      if ((Node)waypointTM.nodes.elementAt(i) != null)
    4848      {
    49         Node node = (Node)waypointTM.nodes.elementAt(i);
    50         oldStrings.add(new HighwayRailway(node));
    51         StopImporterAction.setTagsWrtType(node, type);
     49    Node node = (Node)waypointTM.nodes.elementAt(i);
     50    oldStrings.add(new HighwayRailway(node));
     51    StopImporterAction.setTagsWrtType(node, type);
    5252      }
    5353    }
     
    5757      for (int i = 0; i < track.stoplistTM.getRowCount(); ++i)
    5858      {
    59         if (track.stoplistTM.nodeAt(i) != null)
    60         {
    61           Node node = track.stoplistTM.nodeAt(i);
    62           oldStrings.add(new HighwayRailway(node));
    63           StopImporterAction.setTagsWrtType(node, type);
    64         }
     59    if (track.stoplistTM.nodeAt(i) != null)
     60    {
     61      Node node = track.stoplistTM.nodeAt(i);
     62      oldStrings.add(new HighwayRailway(node));
     63      StopImporterAction.setTagsWrtType(node, type);
     64    }
    6565      }
    6666    }
    6767    return true;
    6868  }
    69  
     69
    7070  public void undoCommand()
    7171  {
     
    7777    }
    7878  }
    79  
     79
    8080  public void fillModifiedData
    8181    (Collection< OsmPrimitive > modified, Collection< OsmPrimitive > deleted,
     
    8383  {
    8484  }
    85  
     85
    8686  @Override public JLabel getDescription()
    8787  {
    8888    return new JLabel("public_transport.Settings.ChangeStoptype");
    8989  }
    90  
     90
    9191};
  • applications/editors/josm/plugins/public_transport/src/public_transport/StopImporterAction.java

    r20867 r23192  
    6262
    6363public class StopImporterAction extends JosmAction
    64 { 
     64{
    6565  private static StopImporterDialog dialog = null;
    6666  private static DefaultListModel tracksListModel = null;
     
    6969  private static WaypointTableModel waypointTM = null;
    7070  public boolean inEvent = false;
    71  
     71
    7272  public StopImporterAction()
    7373  {
    7474    super(tr("Create Stops from GPX ..."), null,
    75           tr("Create Stops from a GPX file"), null, true);
     75      tr("Create Stops from a GPX file"), null, true);
    7676  }
    7777
     
    8080    return waypointTM;
    8181  }
    82  
     82
    8383  public StopImporterDialog getDialog()
    8484  {
     
    9292    return tracksListModel;
    9393  }
    94  
     94
    9595  public TrackReference getCurrentTrack()
    9696  {
     
    101101  {
    102102    DataSet mainDataSet = Main.main.getCurrentDataSet();
    103    
     103
    104104    if (dialog == null)
    105105      dialog = new StopImporterDialog(this);
    106    
     106
    107107    dialog.setVisible(true);
    108108
     
    112112      if (curDir.equals(""))
    113113      {
    114         curDir = ".";
     114    curDir = ".";
    115115      }
    116116      JFileChooser fc = new JFileChooser(new File(curDir));
    117       fc.setDialogTitle("Select GPX file"); 
     117      fc.setDialogTitle("Select GPX file");
    118118      fc.setMultiSelectionEnabled(false);
    119      
     119
    120120      int answer = fc.showOpenDialog(Main.parent);
    121121      if (answer != JFileChooser.APPROVE_OPTION)
    122         return;
    123      
     122    return;
     123
    124124      if (!fc.getCurrentDirectory().getAbsolutePath().equals(curDir))
    125         Main.pref.put("lastDirectory", fc.getCurrentDirectory().getAbsolutePath());
    126      
     125    Main.pref.put("lastDirectory", fc.getCurrentDirectory().getAbsolutePath());
     126
    127127      importData(fc.getSelectedFile());
    128      
     128
    129129      refreshData();
    130130    }
     
    132132    {
    133133      if ((!inEvent) && (dialog.gpsTimeStartValid()) && (currentTrack != null))
    134         Main.main.undoRedo.add(new TrackStoplistRelocateCommand(this));
     134    Main.main.undoRedo.add(new TrackStoplistRelocateCommand(this));
    135135    }
    136136    else if ("stopImporter.settingsStopwatchStart".equals(event.getActionCommand()))
    137137    {
    138138      if ((!inEvent) && (dialog.stopwatchStartValid()) && (currentTrack != null))
    139         Main.main.undoRedo.add(new TrackStoplistRelocateCommand(this));
     139    Main.main.undoRedo.add(new TrackStoplistRelocateCommand(this));
    140140    }
    141141    else if ("stopImporter.settingsTimeWindow".equals(event.getActionCommand()))
    142142    {
    143143      if (currentTrack != null)
    144         currentTrack.timeWindow = dialog.getTimeWindow();
     144    currentTrack.timeWindow = dialog.getTimeWindow();
    145145    }
    146146    else if ("stopImporter.settingsThreshold".equals(event.getActionCommand()))
    147147    {
    148148      if (currentTrack != null)
    149         currentTrack.threshold = dialog.getThreshold();
     149    currentTrack.threshold = dialog.getThreshold();
    150150    }
    151151    else if ("stopImporter.settingsSuggestStops".equals(event.getActionCommand()))
     
    189189  private void importData(final File file)
    190190  {
    191     try 
     191    try
    192192    {
    193193      InputStream is;
    194194      if (file.getName().endsWith(".gpx.gz"))
    195         is = new GZIPInputStream(new FileInputStream(file));
     195    is = new GZIPInputStream(new FileInputStream(file));
    196196      else
    197         is = new FileInputStream(file);
     197    is = new FileInputStream(file);
    198198      // Workaround for SAX BOM bug
    199199      // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6206835
    200200      if (!((is.read() == 0xef) && (is.read() == 0xbb) && (is.read() == 0xbf)))
    201201      {
    202         is.close();
    203         if (file.getName().endsWith(".gpx.gz"))
    204           is = new GZIPInputStream(new FileInputStream(file));
    205         else
    206           is = new FileInputStream(file);
     202    is.close();
     203    if (file.getName().endsWith(".gpx.gz"))
     204      is = new GZIPInputStream(new FileInputStream(file));
     205    else
     206      is = new FileInputStream(file);
    207207      }
    208208      final GpxReader r = new GpxReader(is);
    209209      final boolean parsedProperly = r.parse(true);
    210210      data = r.data;
    211      
     211
    212212      if (!parsedProperly)
    213213      {
    214         JOptionPane.showMessageDialog(null, tr("Error occured while parsing gpx file {0}. Only part of the file will be available", file.getName()));
    215       }
    216     }
    217     catch (FileNotFoundException e) 
     214    JOptionPane.showMessageDialog(null, tr("Error occured while parsing gpx file {0}. Only part of the file will be available", file.getName()));
     215      }
     216    }
     217    catch (FileNotFoundException e)
    218218    {
    219219      e.printStackTrace();
     
    241241      while (trackIter.hasNext())
    242242      {
    243         GpxTrack track = trackIter.next();
    244         trackRefs.add(new TrackReference(track, this));
    245       }
    246      
     243    GpxTrack track = trackIter.next();
     244    trackRefs.add(new TrackReference(track, this));
     245      }
     246
    247247      Collections.sort(trackRefs);
    248248
    249249      Iterator< TrackReference > iter = trackRefs.iterator();
    250250      while (iter.hasNext())
    251         tracksListModel.addElement(iter.next());
    252      
     251    tracksListModel.addElement(iter.next());
     252
    253253      waypointTM = new WaypointTableModel(this);
    254254      Iterator< WayPoint > waypointIter = data.waypoints.iterator();
    255255      while (waypointIter.hasNext())
    256256      {
    257         WayPoint waypoint = waypointIter.next();
    258         waypointTM.addRow(waypoint);
     257    WayPoint waypoint = waypointIter.next();
     258    waypointTM.addRow(waypoint);
    259259      }
    260260      dialog.setWaypointsTableModel(waypointTM);
     
    265265      (null, "The GPX file contained no tracks or waypoints.", "No data found",
    266266       JOptionPane.ERROR_MESSAGE);
    267      
     267
    268268      System.out.println("Public Transport: StopImporter: No data found");
    269269    }
    270270  }
    271  
     271
    272272  public void tracksSelectionChanged(int selectedPos)
    273273  {
     
    276276      currentTrack = ((TrackReference)tracksListModel.elementAt(selectedPos));
    277277      dialog.setTrackValid(true);
    278      
     278
    279279      //Prepare Settings
    280280      dialog.setSettings
    281           (currentTrack.gpsSyncTime, currentTrack.stopwatchStart,
    282            currentTrack.timeWindow, currentTrack.threshold);
    283      
     281      (currentTrack.gpsSyncTime, currentTrack.stopwatchStart,
     282       currentTrack.timeWindow, currentTrack.threshold);
     283
    284284      //Prepare Stoplist
    285285      dialog.setStoplistTableModel
     
    297297    return createNode(latLon, dialog.getStoptype(), name);
    298298  }
    299    
     299
    300300  public static Node createNode(LatLon latLon, String type, String name)
    301301  {
     
    306306    {
    307307      JOptionPane.showMessageDialog(null, "There exists no dataset."
    308           + " Try to download data from the server or open an OSM file.",
     308      + " Try to download data from the server or open an OSM file.",
    309309   "No data found", JOptionPane.ERROR_MESSAGE);
    310      
     310
    311311      System.out.println("Public Transport: StopInserter: No data found");
    312            
     312
    313313      return null;
    314314    }
     
    333333      node.put("railway", "station");
    334334  }
    335  
     335
    336336  /* returns a collection of all selected lines or
    337337     a collection of all lines otherwise */
     
    343343    {
    344344      for (int i = 0; i < selectedLines.length; ++i)
    345         consideredLines.add(selectedLines[i]);
     345    consideredLines.add(selectedLines[i]);
    346346    }
    347347    else
    348348    {
    349349      for (int i = 0; i < table.getRowCount(); ++i)
    350         consideredLines.add(new Integer(i));
     350    consideredLines.add(new Integer(i));
    351351    }
    352352    return consideredLines;
     
    358358    if (Main.main.getCurrentDataSet() == null)
    359359      return;
    360      
     360
    361361    table.clearSelection();
    362      
     362
    363363    for (int i = 0; i < table.getRowCount(); ++i)
    364364    {
    365365      if ((nodes.elementAt(i) != null) &&
    366            (Main.main.getCurrentDataSet().isSelected(nodes.elementAt(i))))
    367         table.addRowSelectionInterval(i, i);
    368     }
    369   }
    370  
     366       (Main.main.getCurrentDataSet().isSelected(nodes.elementAt(i))))
     367    table.addRowSelectionInterval(i, i);
     368    }
     369  }
     370
    371371  /* shows the nodes that correspond to the marked lines in the table.
    372372     If no lines are marked in the table, show all nodes from the vector */
     
    379379      int j = consideredLines.elementAt(i);
    380380      if (nodes.elementAt(j) != null)
    381         nodes.elementAt(j).visit(box);
     381    nodes.elementAt(j).visit(box);
    382382    }
    383383    if (box.getBounds() == null)
     
    386386    Main.map.mapView.recalculateCenterScale(box);
    387387  }
    388  
     388
    389389  /* marks the nodes that correspond to the marked lines in the table.
    390390  If no lines are marked in the table, mark all nodes from the vector */
     
    398398      int j = consideredLines.elementAt(i);
    399399      if (nodes.elementAt(j) != null)
    400         Main.main.getCurrentDataSet().addSelected(nodes.elementAt(j));
    401     }
    402   }
    403  
     400    Main.main.getCurrentDataSet().addSelected(nodes.elementAt(j));
     401    }
     402  }
     403
    404404  public static String timeOf(double t)
    405405  {
    406406    t -= Math.floor(t/24/60/60)*24*60*60;
    407    
     407
    408408    int hour = (int)Math.floor(t/60/60);
    409409    t -=  Math.floor(t/60/60)*60*60;
     
    411411    t -=  Math.floor(t/60)*60;
    412412    double second = t;
    413    
     413
    414414    Format format = new DecimalFormat("00");
    415415    Format formatS = new DecimalFormat("00.###");
    416416    return (format.format(hour) + ":" + format.format(minute) + ":"
    417         + formatS.format(second));
    418   }
    419  
     417    + formatS.format(second));
     418  }
     419
    420420  public Action getFocusWaypointNameAction()
    421421  {
    422422    return new FocusWaypointNameAction();
    423423  }
    424  
     424
    425425  public Action getFocusWaypointShelterAction(String shelter)
    426426  {
     
    434434      public void actionPerformed(ActionEvent e)
    435435      {
    436         JTable table = dialog.getWaypointsTable();
    437         int row = table.getEditingRow();
    438         if (row < 0)
    439           return;
    440         table.clearSelection();
    441         table.addRowSelectionInterval(row, row);
    442         Main.main.undoRedo.add
    443             (new WaypointsDisableCommand(StopImporterAction.this));
     436    JTable table = dialog.getWaypointsTable();
     437    int row = table.getEditingRow();
     438    if (row < 0)
     439      return;
     440    table.clearSelection();
     441    table.addRowSelectionInterval(row, row);
     442    Main.main.undoRedo.add
     443        (new WaypointsDisableCommand(StopImporterAction.this));
    444444      }
    445445    };
     
    450450    return new FocusTrackStoplistNameAction();
    451451  }
    452  
     452
    453453  public Action getFocusTrackStoplistShelterAction(String shelter)
    454454  {
     
    462462      public void actionPerformed(ActionEvent e)
    463463      {
    464         JTable table = dialog.getStoplistTable();
    465         int row = table.getEditingRow();
    466         if (row < 0)
    467           return;
    468         table.clearSelection();
    469         table.addRowSelectionInterval(row, row);
    470         Main.main.undoRedo.add
    471             (new TrackStoplistDeleteCommand(StopImporterAction.this));
     464    JTable table = dialog.getStoplistTable();
     465    int row = table.getEditingRow();
     466    if (row < 0)
     467      return;
     468    table.clearSelection();
     469    table.addRowSelectionInterval(row, row);
     470    Main.main.undoRedo.add
     471        (new TrackStoplistDeleteCommand(StopImporterAction.this));
    472472      }
    473473    };
     
    483483      int row = table.getEditingRow();
    484484      if (row < 0)
    485         row = 0;
     485    row = 0;
    486486      waypointTM.inEvent = true;
    487487      if (table.getCellEditor() != null)
    488488      {
    489         if (!table.getCellEditor().stopCellEditing())
    490           table.getCellEditor().cancelCellEditing();
     489    if (!table.getCellEditor().stopCellEditing())
     490      table.getCellEditor().cancelCellEditing();
    491491      }
    492492      table.editCellAt(row, 1);
    493493      table.getCellEditor().getTableCellEditorComponent
    494           (table, "", true, row, 1);
     494      (table, "", true, row, 1);
    495495      waypointTM.inEvent = false;
    496496    }
    497497  };
    498  
     498
    499499  private class FocusWaypointShelterAction extends AbstractAction
    500500  {
    501501    private String defaultShelter = null;
    502    
     502
    503503    public FocusWaypointShelterAction(String defaultShelter)
    504504    {
    505505      this.defaultShelter = defaultShelter;
    506506    }
    507    
     507
    508508    public void actionPerformed(ActionEvent e)
    509509    {
     
    513513      int row = table.getEditingRow();
    514514      if (row < 0)
    515         row = 0;
     515    row = 0;
    516516      waypointTM.inEvent = true;
    517517      if (table.getCellEditor() != null)
    518518      {
    519         if (!table.getCellEditor().stopCellEditing())
    520           table.getCellEditor().cancelCellEditing();
     519    if (!table.getCellEditor().stopCellEditing())
     520      table.getCellEditor().cancelCellEditing();
    521521      }
    522522      table.editCellAt(row, 2);
     
    526526    }
    527527  };
    528  
     528
    529529  private class FocusTrackStoplistNameAction extends AbstractAction
    530530  {
     
    536536      int row = table.getEditingRow();
    537537      if (row < 0)
    538         row = 0;
     538    row = 0;
    539539      currentTrack.inEvent = true;
    540540      if (table.getCellEditor() != null)
    541541      {
    542         if (!table.getCellEditor().stopCellEditing())
    543           table.getCellEditor().cancelCellEditing();
     542    if (!table.getCellEditor().stopCellEditing())
     543      table.getCellEditor().cancelCellEditing();
    544544      }
    545545      table.editCellAt(row, 1);
     
    549549    }
    550550  };
    551  
     551
    552552  private class FocusTrackStoplistShelterAction extends AbstractAction
    553553  {
    554554    private String defaultShelter = null;
    555    
     555
    556556    public FocusTrackStoplistShelterAction(String defaultShelter)
    557557    {
    558558      this.defaultShelter = defaultShelter;
    559559    }
    560    
     560
    561561    public void actionPerformed(ActionEvent e)
    562562    {
     
    566566      int row = table.getEditingRow();
    567567      if (row < 0)
    568         row = 0;
     568    row = 0;
    569569      currentTrack.inEvent = true;
    570570      if (table.getCellEditor() != null)
    571571      {
    572         if (!table.getCellEditor().stopCellEditing())
    573           table.getCellEditor().cancelCellEditing();
     572    if (!table.getCellEditor().stopCellEditing())
     573      table.getCellEditor().cancelCellEditing();
    574574      }
    575575      table.editCellAt(row, 2);
  • applications/editors/josm/plugins/public_transport/src/public_transport/StopImporterDialog.java

    r20867 r23192  
    6363
    6464public class StopImporterDialog
    65 { 
     65{
    6666  private JDialog jDialog = null;
    6767  private JTabbedPane tabbedPane = null;
     
    7474  private JTable stoplistTable = null;
    7575  private JTable waypointTable = null;
    76  
     76
    7777  public StopImporterDialog(StopImporterAction controller)
    7878  {
     
    9393    tabbedPane.setEnabledAt(3, true);
    9494    jDialog.add(tabbedPane);
    95      
     95
    9696    //Tracks Tab
    9797    JPanel contentPane = tabTracks;
     
    9999    GridBagConstraints layoutCons = new GridBagConstraints();
    100100    contentPane.setLayout(gridbag);
    101      
     101
    102102    JLabel label = new JLabel("Tracks in this GPX file:");
    103      
     103
    104104    layoutCons.gridx = 0;
    105105    layoutCons.gridy = 0;
     
    110110    gridbag.setConstraints(label, layoutCons);
    111111    contentPane.add(label);
    112      
     112
    113113    DefaultListModel tracksListModel = controller.getTracksListModel();
    114114    tracksList = new JList(tracksListModel);
     
    118118    tracksList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    119119    tracksList.addListSelectionListener(new TracksLSL(controller));
    120      
     120
    121121    layoutCons.gridx = 0;
    122122    layoutCons.gridy = 1;
     
    124124    layoutCons.weightx = 1.0;
    125125    layoutCons.weighty = 1.0;
    126     layoutCons.fill = GridBagConstraints.BOTH;     
     126    layoutCons.fill = GridBagConstraints.BOTH;
    127127    gridbag.setConstraints(rpListSP, layoutCons);
    128128    contentPane.add(rpListSP);
    129      
     129
    130130    //Settings Tab
    131131    contentPane = tabSettings;
     
    133133    layoutCons = new GridBagConstraints();
    134134    contentPane.setLayout(gridbag);
    135      
     135
    136136    label = new JLabel("Type of stops to add");
    137      
     137
    138138    layoutCons.gridx = 0;
    139139    layoutCons.gridy = 0;
     
    144144    gridbag.setConstraints(label, layoutCons);
    145145    contentPane.add(label);
    146    
     146
    147147    cbStoptype = new JComboBox();
    148148    cbStoptype.setEditable(false);
     
    154154    cbStoptype.setActionCommand("stopImporter.settingsStoptype");
    155155    cbStoptype.addActionListener(controller);
    156    
     156
    157157    layoutCons.gridx = 0;
    158158    layoutCons.gridy = 1;
     
    163163    gridbag.setConstraints(cbStoptype, layoutCons);
    164164    contentPane.add(cbStoptype);
    165      
     165
    166166    label = new JLabel("Time on your GPS device");
    167      
     167
    168168    layoutCons.gridx = 0;
    169169    layoutCons.gridy = 2;
     
    174174    gridbag.setConstraints(label, layoutCons);
    175175    contentPane.add(label);
    176      
     176
    177177    tfGPSTimeStart = new JTextField("00:00:00", 15);
    178178    tfGPSTimeStart.setActionCommand("stopImporter.settingsGPSTimeStart");
    179179    tfGPSTimeStart.addActionListener(controller);
    180      
     180
    181181    layoutCons.gridx = 0;
    182182    layoutCons.gridy = 3;
     
    187187    gridbag.setConstraints(tfGPSTimeStart, layoutCons);
    188188    contentPane.add(tfGPSTimeStart);
    189      
     189
    190190    label = new JLabel("HH:MM:SS.sss");
    191      
     191
    192192    layoutCons.gridx = 1;
    193193    layoutCons.gridy = 3;
     
    198198    gridbag.setConstraints(label, layoutCons);
    199199    contentPane.add(label);
    200            
     200
    201201    label = new JLabel("Time on your stopwatch");
    202      
     202
    203203    layoutCons.gridx = 0;
    204204    layoutCons.gridy = 4;
     
    209209    gridbag.setConstraints(label, layoutCons);
    210210    contentPane.add(label);
    211      
     211
    212212    tfStopwatchStart = new JTextField("00:00:00", 15);
    213213    tfStopwatchStart.setActionCommand("stopImporter.settingsStopwatchStart");
    214214    tfStopwatchStart.addActionListener(controller);
    215      
     215
    216216    layoutCons.gridx = 0;
    217217    layoutCons.gridy = 5;
     
    222222    gridbag.setConstraints(tfStopwatchStart, layoutCons);
    223223    contentPane.add(tfStopwatchStart);
    224      
     224
    225225    label = new JLabel("HH:MM:SS.sss");
    226      
     226
    227227    layoutCons.gridx = 1;
    228228    layoutCons.gridy = 5;
     
    233233    gridbag.setConstraints(label, layoutCons);
    234234    contentPane.add(label);
    235      
     235
    236236    label = new JLabel("Time window");
    237      
     237
    238238    layoutCons.gridx = 0;
    239239    layoutCons.gridy = 6;
     
    244244    gridbag.setConstraints(label, layoutCons);
    245245    contentPane.add(label);
    246      
     246
    247247    tfTimeWindow = new JTextField("15", 4);
    248248    tfTimeWindow.setActionCommand("stopImporter.settingsTimeWindow");
    249249    tfTimeWindow.addActionListener(controller);
    250      
     250
    251251    layoutCons.gridx = 0;
    252252    layoutCons.gridy = 7;
     
    257257    gridbag.setConstraints(tfTimeWindow, layoutCons);
    258258    contentPane.add(tfTimeWindow);
    259      
     259
    260260    label = new JLabel("seconds");
    261      
     261
    262262    layoutCons.gridx = 1;
    263263    layoutCons.gridy = 7;
     
    268268    gridbag.setConstraints(label, layoutCons);
    269269    contentPane.add(label);
    270      
     270
    271271    label = new JLabel("Move Threshold");
    272      
     272
    273273    layoutCons.gridx = 0;
    274274    layoutCons.gridy = 8;
     
    279279    gridbag.setConstraints(label, layoutCons);
    280280    contentPane.add(label);
    281      
     281
    282282    tfThreshold = new JTextField("20", 4);
    283283    tfThreshold.setActionCommand("stopImporter.settingsThreshold");
    284284    tfThreshold.addActionListener(controller);
    285      
     285
    286286    layoutCons.gridx = 0;
    287287    layoutCons.gridy = 9;
     
    292292    gridbag.setConstraints(tfThreshold, layoutCons);
    293293    contentPane.add(tfThreshold);
    294      
     294
    295295    label = new JLabel("meters");
    296      
     296
    297297    layoutCons.gridx = 1;
    298298    layoutCons.gridy = 9;
     
    303303    gridbag.setConstraints(label, layoutCons);
    304304    contentPane.add(label);
    305      
     305
    306306    JButton bSuggestStops = new JButton("Suggest Stops");
    307307    bSuggestStops.setActionCommand("stopImporter.settingsSuggestStops");
    308308    bSuggestStops.addActionListener(controller);
    309      
     309
    310310    layoutCons.gridx = 0;
    311311    layoutCons.gridy = 10;
     
    316316    gridbag.setConstraints(bSuggestStops, layoutCons);
    317317    contentPane.add(bSuggestStops);
    318      
     318
    319319    //Stops Tab
    320320    contentPane = tabStops;
     
    325325        (KeyStroke.getKeyStroke("alt N"), "stopImporter.focusName");
    326326    contentPane.getActionMap().put
    327         ("stopImporter.focusName", controller.getFocusTrackStoplistNameAction());
     327    ("stopImporter.focusName", controller.getFocusTrackStoplistNameAction());
    328328    contentPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put
    329329        (KeyStroke.getKeyStroke("alt S"), "stopImporter.focusShelterYes");
    330330    contentPane.getActionMap().put
    331         ("stopImporter.focusShelterYes",
    332         controller.getFocusTrackStoplistShelterAction("yes"));
     331    ("stopImporter.focusShelterYes",
     332    controller.getFocusTrackStoplistShelterAction("yes"));
    333333    contentPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put
    334334        (KeyStroke.getKeyStroke("alt T"), "stopImporter.focusShelterNo");
    335335    contentPane.getActionMap().put
    336         ("stopImporter.focusShelterNo",
    337         controller.getFocusTrackStoplistShelterAction("no"));
     336    ("stopImporter.focusShelterNo",
     337    controller.getFocusTrackStoplistShelterAction("no"));
    338338    contentPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put
    339339        (KeyStroke.getKeyStroke("alt U"), "stopImporter.focusShelterImplicit");
    340340    contentPane.getActionMap().put
    341         ("stopImporter.focusShelterImplicit",
    342         controller.getFocusTrackStoplistShelterAction("implicit"));
     341    ("stopImporter.focusShelterImplicit",
     342    controller.getFocusTrackStoplistShelterAction("implicit"));
    343343    contentPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put
    344344        (KeyStroke.getKeyStroke("alt D"), "stopImporter.stoplistDelete");
    345345    contentPane.getActionMap().put
    346         ("stopImporter.stoplistDelete",
    347         controller.getFocusStoplistDeleteAction());
    348      
     346    ("stopImporter.stoplistDelete",
     347    controller.getFocusStoplistDeleteAction());
     348
    349349    stoplistTable = new JTable();
    350350    JScrollPane tableSP = new JScrollPane(stoplistTable);
    351    
     351
    352352    layoutCons.gridx = 0;
    353353    layoutCons.gridy = 0;
     
    358358    gridbag.setConstraints(tableSP, layoutCons);
    359359    contentPane.add(tableSP);
    360      
     360
    361361    JButton bFind = new JButton("Find");
    362362    bFind.setActionCommand("stopImporter.stoplistFind");
    363363    bFind.addActionListener(controller);
    364      
     364
    365365    layoutCons.gridx = 0;
    366366    layoutCons.gridy = 1;
     
    371371    gridbag.setConstraints(bFind, layoutCons);
    372372    contentPane.add(bFind);
    373      
     373
    374374    JButton bShow = new JButton("Show");
    375375    bShow.setActionCommand("stopImporter.stoplistShow");
    376376    bShow.addActionListener(controller);
    377      
     377
    378378    layoutCons.gridx = 0;
    379379    layoutCons.gridy = 2;
     
    384384    gridbag.setConstraints(bShow, layoutCons);
    385385    contentPane.add(bShow);
    386      
     386
    387387    JButton bMark = new JButton("Mark");
    388388    bMark.setActionCommand("stopImporter.stoplistMark");
    389389    bMark.addActionListener(controller);
    390      
     390
    391391    layoutCons.gridx = 1;
    392392    layoutCons.gridy = 1;
     
    398398    gridbag.setConstraints(bMark, layoutCons);
    399399    contentPane.add(bMark);
    400      
     400
    401401    JButton bDetach = new JButton("Detach");
    402402    bDetach.setActionCommand("stopImporter.stoplistDetach");
    403403    bDetach.addActionListener(controller);
    404      
     404
    405405    layoutCons.gridx = 1;
    406406    layoutCons.gridy = 2;
     
    412412    gridbag.setConstraints(bDetach, layoutCons);
    413413    contentPane.add(bDetach);
    414      
     414
    415415    JButton bAdd = new JButton("Add");
    416416    bAdd.setActionCommand("stopImporter.stoplistAdd");
    417417    bAdd.addActionListener(controller);
    418      
     418
    419419    layoutCons.gridx = 2;
    420420    layoutCons.gridy = 1;
     
    426426    gridbag.setConstraints(bAdd, layoutCons);
    427427    contentPane.add(bAdd);
    428      
     428
    429429    JButton bDelete = new JButton("Delete");
    430430    bDelete.setActionCommand("stopImporter.stoplistDelete");
    431431    bDelete.addActionListener(controller);
    432      
     432
    433433    layoutCons.gridx = 2;
    434434    layoutCons.gridy = 2;
     
    439439    gridbag.setConstraints(bDelete, layoutCons);
    440440    contentPane.add(bDelete);
    441      
     441
    442442    JButton bSort = new JButton("Sort");
    443443    bSort.setActionCommand("stopImporter.stoplistSort");
    444444    bSort.addActionListener(controller);
    445      
     445
    446446    layoutCons.gridx = 3;
    447447    layoutCons.gridy = 1;
     
    453453    gridbag.setConstraints(bSort, layoutCons);
    454454    contentPane.add(bSort);
    455      
     455
    456456    //Waypoints Tab
    457457    contentPane = tabWaypoints;
     
    462462        (KeyStroke.getKeyStroke("alt N"), "stopImporter.focusName");
    463463    contentPane.getActionMap().put
    464         ("stopImporter.focusName", controller.getFocusWaypointNameAction());
     464    ("stopImporter.focusName", controller.getFocusWaypointNameAction());
    465465    contentPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put
    466466        (KeyStroke.getKeyStroke("alt S"), "stopImporter.focusShelterYes");
    467467    contentPane.getActionMap().put
    468         ("stopImporter.focusShelterYes",
    469         controller.getFocusWaypointShelterAction("yes"));
     468    ("stopImporter.focusShelterYes",
     469    controller.getFocusWaypointShelterAction("yes"));
    470470    contentPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put
    471471        (KeyStroke.getKeyStroke("alt T"), "stopImporter.focusShelterNo");
    472472    contentPane.getActionMap().put
    473         ("stopImporter.focusShelterNo",
    474         controller.getFocusWaypointShelterAction("no"));
     473    ("stopImporter.focusShelterNo",
     474    controller.getFocusWaypointShelterAction("no"));
    475475    contentPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put
    476476        (KeyStroke.getKeyStroke("alt U"), "stopImporter.focusShelterImplicit");
    477477    contentPane.getActionMap().put
    478         ("stopImporter.focusShelterImplicit",
    479         controller.getFocusWaypointShelterAction("implicit"));
     478    ("stopImporter.focusShelterImplicit",
     479    controller.getFocusWaypointShelterAction("implicit"));
    480480    contentPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put
    481481        (KeyStroke.getKeyStroke("alt D"), "stopImporter.waypointsDelete");
    482482    contentPane.getActionMap().put
    483         ("stopImporter.waypointsDelete",
    484         controller.getFocusWaypointDeleteAction());
    485      
     483    ("stopImporter.waypointsDelete",
     484    controller.getFocusWaypointDeleteAction());
     485
    486486    waypointTable = new JTable();
    487487    tableSP = new JScrollPane(waypointTable);
    488    
     488
    489489    layoutCons.gridx = 0;
    490490    layoutCons.gridy = 0;
     
    495495    gridbag.setConstraints(tableSP, layoutCons);
    496496    contentPane.add(tableSP);
    497      
     497
    498498    bFind = new JButton("Find");
    499499    bFind.setActionCommand("stopImporter.waypointsFind");
    500500    bFind.addActionListener(controller);
    501      
     501
    502502    layoutCons.gridx = 0;
    503503    layoutCons.gridy = 1;
     
    508508    gridbag.setConstraints(bFind, layoutCons);
    509509    contentPane.add(bFind);
    510      
     510
    511511    bShow = new JButton("Show");
    512512    bShow.setActionCommand("stopImporter.waypointsShow");
    513513    bShow.addActionListener(controller);
    514      
     514
    515515    layoutCons.gridx = 0;
    516516    layoutCons.gridy = 2;
     
    521521    gridbag.setConstraints(bShow, layoutCons);
    522522    contentPane.add(bShow);
    523      
     523
    524524    bMark = new JButton("Mark");
    525525    bMark.setActionCommand("stopImporter.waypointsMark");
    526526    bMark.addActionListener(controller);
    527      
     527
    528528    layoutCons.gridx = 1;
    529529    layoutCons.gridy = 1;
     
    535535    gridbag.setConstraints(bMark, layoutCons);
    536536    contentPane.add(bMark);
    537      
     537
    538538    bDetach = new JButton("Detach");
    539539    bDetach.setActionCommand("stopImporter.waypointsDetach");
    540540    bDetach.addActionListener(controller);
    541      
     541
    542542    layoutCons.gridx = 1;
    543543    layoutCons.gridy = 2;
     
    549549    gridbag.setConstraints(bDetach, layoutCons);
    550550    contentPane.add(bDetach);
    551      
     551
    552552    bAdd = new JButton("Enable");
    553553    bAdd.setActionCommand("stopImporter.waypointsAdd");
    554554    bAdd.addActionListener(controller);
    555      
     555
    556556    layoutCons.gridx = 2;
    557557    layoutCons.gridy = 1;
     
    563563    gridbag.setConstraints(bAdd, layoutCons);
    564564    contentPane.add(bAdd);
    565      
     565
    566566    bDelete = new JButton("Disable");
    567567    bDelete.setActionCommand("stopImporter.waypointsDelete");
    568568    bDelete.addActionListener(controller);
    569      
     569
    570570    layoutCons.gridx = 2;
    571571    layoutCons.gridy = 2;
     
    576576    gridbag.setConstraints(bDelete, layoutCons);
    577577    contentPane.add(bDelete);
    578      
     578
    579579    jDialog.pack();
    580580    jDialog.setLocationRelativeTo(frame);
    581581  }
    582  
     582
    583583  public void setTrackValid(boolean valid)
    584584  {
    585585    tabbedPane.setEnabledAt(2, valid);
    586586  }
    587  
     587
    588588  public void setVisible(boolean visible)
    589589  {
    590590    jDialog.setVisible(visible);
    591591  }
    592  
     592
    593593  public void setSettings
    594594      (String gpsSyncTime, String stopwatchStart,
     
    600600    tfThreshold.setText(Double.toString(threshold));
    601601  }
    602  
     602
    603603  public String getStoptype()
    604604  {
    605605    return (String)cbStoptype.getSelectedItem();
    606606  }
    607  
     607
    608608  public boolean gpsTimeStartValid()
    609609  {
     
    615615    {
    616616      JOptionPane.showMessageDialog
    617           (null, "Can't parse a time from this string.", "Invalid value",
    618            JOptionPane.ERROR_MESSAGE);
     617      (null, "Can't parse a time from this string.", "Invalid value",
     618       JOptionPane.ERROR_MESSAGE);
    619619      return false;
    620620    }
    621621  }
    622  
     622
    623623  public String getGpsTimeStart()
    624624  {
    625625    return tfGPSTimeStart.getText();
    626626  }
    627  
     627
    628628  public void setGpsTimeStart(String s)
    629629  {
    630630    tfGPSTimeStart.setText(s);
    631631  }
    632  
     632
    633633  public boolean stopwatchStartValid()
    634634  {
     
    640640    {
    641641      JOptionPane.showMessageDialog
    642           (null, "Can't parse a time from this string.", "Invalid value",
    643            JOptionPane.ERROR_MESSAGE);
     642      (null, "Can't parse a time from this string.", "Invalid value",
     643       JOptionPane.ERROR_MESSAGE);
    644644      return false;
    645645    }
    646646  }
    647  
     647
    648648  public String getStopwatchStart()
    649649  {
    650650    return tfStopwatchStart.getText();
    651651  }
    652  
     652
    653653  public void setStopwatchStart(String s)
    654654  {
    655655    tfStopwatchStart.setText(s);
    656656  }
    657  
     657
    658658  public double getTimeWindow()
    659659  {
    660660    return Double.parseDouble(tfTimeWindow.getText());
    661661  }
    662  
     662
    663663  public double getThreshold()
    664664  {
    665665    return Double.parseDouble(tfThreshold.getText());
    666666  }
    667  
     667
    668668  public JTable getStoplistTable()
    669669  {
    670670    return stoplistTable;
    671671  }
    672  
     672
    673673  public void setStoplistTableModel(TrackStoplistTableModel model)
    674674  {
     
    680680    comboBox.addItem("implicit");
    681681    stoplistTable.getColumnModel().getColumn(2)
    682         .setCellEditor(new DefaultCellEditor(comboBox));
     682    .setCellEditor(new DefaultCellEditor(comboBox));
    683683    int width = stoplistTable.getPreferredSize().width;
    684684    stoplistTable.getColumnModel().getColumn(0).setPreferredWidth((int)(width * 0.4));
     
    686686    stoplistTable.getColumnModel().getColumn(2).setPreferredWidth((int)(width * 0.1));
    687687  }
    688  
     688
    689689  public JTable getWaypointsTable()
    690690  {
    691691    return waypointTable;
    692692  }
    693  
     693
    694694  public void setWaypointsTableModel(WaypointTableModel model)
    695695  {
     
    701701    comboBox.addItem("implicit");
    702702    waypointTable.getColumnModel().getColumn(2)
    703         .setCellEditor(new DefaultCellEditor(comboBox));
     703    .setCellEditor(new DefaultCellEditor(comboBox));
    704704    int width = waypointTable.getPreferredSize().width;
    705705    waypointTable.getColumnModel().getColumn(0).setPreferredWidth((int)(width * 0.4));
     
    707707    waypointTable.getColumnModel().getColumn(2).setPreferredWidth((int)(width * 0.1));
    708708  }
    709  
     709
    710710  public static double parseTime(String s)
    711711  {
    712712    double result = 0;
    713713    if ((s.charAt(2) != ':') || (s.charAt(2) != ':')
    714         || (s.length() < 8))
     714    || (s.length() < 8))
    715715      return -1;
    716716    int hour = Integer.parseInt(s.substring(0, 2));
     
    718718    double second = Double.parseDouble(s.substring(6, s.length()));
    719719    if ((hour < 0) || (hour > 23) || (minute < 0) || (minute > 59)
    720         || (second < 0) || (second >= 60.0))
     720    || (second < 0) || (second >= 60.0))
    721721      return -1;
    722722    return (second + minute*60 + hour*60*60);
    723723  }
    724  
     724
    725725  private class TracksLSL implements ListSelectionListener
    726726  {
    727727    StopImporterAction root = null;
    728    
     728
    729729    public TracksLSL(StopImporterAction sia)
    730730    {
    731731      root = sia;
    732732    }
    733    
     733
    734734    public void valueChanged(ListSelectionEvent e)
    735735    {
    736736      int selectedPos = tracksList.getAnchorSelectionIndex();
    737737      if (tracksList.isSelectedIndex(selectedPos))
    738         root.tracksSelectionChanged(selectedPos);
     738    root.tracksSelectionChanged(selectedPos);
    739739      else
    740         root.tracksSelectionChanged(-1);
     740    root.tracksSelectionChanged(-1);
    741741    }
    742742  };
  • applications/editors/josm/plugins/public_transport/src/public_transport/TrackReference.java

    r20839 r23192  
    3232  private StopImporterAction controller = null;
    3333  public boolean inEvent = false;
    34    
     34
    3535  public TrackReference(GpxTrack track, StopImporterAction controller)
    3636  {
     
    4646      while ((siter.hasNext()) && (this.gpsSyncTime == null))
    4747      {
    48         Iterator< WayPoint > witer = siter.next().getWayPoints().iterator();
    49         if (witer.hasNext())
    50         {
    51           this.gpsStartTime = witer.next().getString("time");
    52           if (this.gpsStartTime != null)
    53             this.gpsSyncTime = this.gpsStartTime.substring(11, 19);
    54         }
     48    Iterator< WayPoint > witer = siter.next().getWayPoints().iterator();
     49    if (witer.hasNext())
     50    {
     51      this.gpsStartTime = witer.next().getString("time");
     52      if (this.gpsStartTime != null)
     53        this.gpsSyncTime = this.gpsStartTime.substring(11, 19);
     54    }
    5555      }
    5656      if (this.gpsSyncTime == null)
    5757      {
    58         JOptionPane.showMessageDialog
    59             (null, "The GPX file doesn't contain valid trackpoints. "
    60             + "Please use a GPX file that has trackpoints.", "GPX File Trouble",
     58    JOptionPane.showMessageDialog
     59        (null, "The GPX file doesn't contain valid trackpoints. "
     60        + "Please use a GPX file that has trackpoints.", "GPX File Trouble",
    6161     JOptionPane.ERROR_MESSAGE);
    62          
    63         this.gpsStartTime = "1970-01-01T00:00:00Z";
    64         this.gpsSyncTime = this.stopwatchStart;
     62
     63    this.gpsStartTime = "1970-01-01T00:00:00Z";
     64    this.gpsSyncTime = this.stopwatchStart;
    6565      }
    6666    }
     
    7070    this.threshold = 20;
    7171  }
    72  
     72
    7373  public GpxTrack getGpxTrack()
    7474  {
    7575    return track;
    7676  }
    77    
     77
    7878  public int compareTo(TrackReference tr)
    7979  {
     
    8383    {
    8484      if (tr_name == null)
    85         return -1;
     85    return -1;
    8686      return name.compareTo(tr_name);
    8787    }
    8888    return 1;
    8989  }
    90    
     90
    9191  public String toString()
    9292  {
     
    9696    return buf;
    9797  }
    98    
     98
    9999  public void tableChanged(TableModelEvent e)
    100100  {
     
    102102    {
    103103      if (inEvent)
    104         return;
    105      
     104    return;
     105
    106106      double time = StopImporterDialog.parseTime
    107             ((String)stoplistTM.getValueAt(e.getFirstRow(), 0));
     107        ((String)stoplistTM.getValueAt(e.getFirstRow(), 0));
    108108      if (time < 0)
    109109      {
    110         stoplistTM.setValueAt
    111             (stoplistTM.timeAt(e.getFirstRow()), e.getFirstRow(), 0);
    112         JOptionPane.showMessageDialog
    113             (null, "Can't parse a time from this string.", "Invalid value",
    114              JOptionPane.ERROR_MESSAGE);
    115         return;
     110    stoplistTM.setValueAt
     111        (stoplistTM.timeAt(e.getFirstRow()), e.getFirstRow(), 0);
     112    JOptionPane.showMessageDialog
     113        (null, "Can't parse a time from this string.", "Invalid value",
     114         JOptionPane.ERROR_MESSAGE);
     115    return;
    116116      }
    117117
     
    119119              (this, e.getFirstRow()));
    120120      stoplistTM.setTimeAt
    121           (e.getFirstRow(), (String)stoplistTM.getValueAt(e.getFirstRow(), 0));
     121      (e.getFirstRow(), (String)stoplistTM.getValueAt(e.getFirstRow(), 0));
    122122    }
    123123  }
    124    
     124
    125125  public LatLon computeCoor(double time)
    126126  {
     
    131131    double timeDelta = gpsSyncTime - StopImporterDialog.parseTime(stopwatchStart);
    132132    time += timeDelta;
    133        
     133
    134134    WayPoint wayPoint = null;
    135135    WayPoint lastWayPoint = null;
     
    142142      while (witer.hasNext())
    143143      {
    144         wayPoint = witer.next();
    145         String startTime = wayPoint.getString("time");
    146         wayPointTime = StopImporterDialog.parseTime(startTime.substring(11, 19));
    147         if (startTime.substring(11, 19).compareTo(gpsStartTime.substring(11, 19)) == -1)
    148           wayPointTime += 24*60*60;
    149         if (wayPointTime >= time)
    150           break;
    151         lastWayPoint = wayPoint;
    152         lastWayPointTime = wayPointTime;
     144    wayPoint = witer.next();
     145    String startTime = wayPoint.getString("time");
     146    wayPointTime = StopImporterDialog.parseTime(startTime.substring(11, 19));
     147    if (startTime.substring(11, 19).compareTo(gpsStartTime.substring(11, 19)) == -1)
     148      wayPointTime += 24*60*60;
     149    if (wayPointTime >= time)
     150      break;
     151    lastWayPoint = wayPoint;
     152    lastWayPointTime = wayPointTime;
    153153      }
    154154      if (wayPointTime >= time)
    155         break;
     155    break;
    156156    }
    157        
     157
    158158    double lat = 0;
    159159    if ((wayPointTime == lastWayPointTime) || (lastWayPoint == null))
     
    161161    else
    162162      lat = wayPoint.getCoor().lat()
    163           *(time - lastWayPointTime)/(wayPointTime - lastWayPointTime)
    164           + lastWayPoint.getCoor().lat()
    165           *(wayPointTime - time)/(wayPointTime - lastWayPointTime);
     163      *(time - lastWayPointTime)/(wayPointTime - lastWayPointTime)
     164      + lastWayPoint.getCoor().lat()
     165      *(wayPointTime - time)/(wayPointTime - lastWayPointTime);
    166166    double lon = 0;
    167167    if ((wayPointTime == lastWayPointTime) || (lastWayPoint == null))
     
    169169    else
    170170      lon = wayPoint.getCoor().lon()
    171           *(time - lastWayPointTime)/(wayPointTime - lastWayPointTime)
    172           + lastWayPoint.getCoor().lon()
    173           *(wayPointTime - time)/(wayPointTime - lastWayPointTime);
    174      
     171      *(time - lastWayPointTime)/(wayPointTime - lastWayPointTime)
     172      + lastWayPoint.getCoor().lon()
     173      *(wayPointTime - time)/(wayPointTime - lastWayPointTime);
     174
    175175    return new LatLon(lat, lon);
    176176  }
    177    
     177
    178178  public void relocateNodes()
    179179  {
     
    182182      Node node = stoplistTM.nodeAt(i);
    183183      if (node == null)
    184         continue;
    185        
     184    continue;
     185
    186186      double time = StopImporterDialog.parseTime
    187             ((String)stoplistTM.getValueAt(i, 0));
     187        ((String)stoplistTM.getValueAt(i, 0));
    188188      LatLon latLon = computeCoor(time);
    189189
     
    193193      if (cmd != null)
    194194      {
    195         Main.main.undoRedo.add(cmd);
     195    Main.main.undoRedo.add(cmd);
    196196      }
    197197    }
  • applications/editors/josm/plugins/public_transport/src/public_transport/TrackStoplistAddCommand.java

    r22048 r23192  
    1414  private int workingLine;
    1515  private TrackStoplistTableModel stoplistTM = null;
    16  
     16
    1717  public TrackStoplistAddCommand(StopImporterAction controller)
    1818  {
     
    2020    workingLine = controller.getDialog().getStoplistTable().getSelectedRow();
    2121  }
    22  
     22
    2323  public boolean executeCommand()
    2424  {
     
    2626    return true;
    2727  }
    28  
     28
    2929  public void undoCommand()
    3030  {
     
    3434    stoplistTM.removeRow(workingLine);
    3535  }
    36  
     36
    3737  public void fillModifiedData
    3838    (Collection< OsmPrimitive > modified, Collection< OsmPrimitive > deleted,
     
    4040  {
    4141  }
    42  
     42
    4343  @Override public JLabel getDescription()
    4444  {
  • applications/editors/josm/plugins/public_transport/src/public_transport/TrackStoplistDeleteCommand.java

    r22048 r23192  
    2121      this.shelter = shelter;
    2222    }
    23    
     23
    2424    public Node node;
    2525    public String time;
     
    2727    public String shelter;
    2828  };
    29  
     29
    3030  private Vector< Integer > workingLines = null;
    3131  private Vector< NodeTimeName > nodesForUndo = null;
    3232  private TrackStoplistTableModel stoplistTM = null;
    33  
     33
    3434  public TrackStoplistDeleteCommand(StopImporterAction controller)
    3535  {
     
    3737    workingLines = new Vector< Integer >();
    3838    nodesForUndo = new Vector< NodeTimeName >();
    39    
     39
    4040    // use selected lines or all lines if no line is selected
    4141    int[] selectedLines = controller.getDialog().getStoplistTable().getSelectedRows();
     
    4444      for (int i = 0; i < selectedLines.length; ++i)
    4545      {
    46         workingLines.add(selectedLines[i]);
     46    workingLines.add(selectedLines[i]);
    4747      }
    4848    }
     
    5050    {
    5151      for (int i = 0; i < stoplistTM.getRowCount(); ++i)
    52         workingLines.add(new Integer(i));
     52    workingLines.add(new Integer(i));
    5353    }
    5454  }
    55  
     55
    5656  public boolean executeCommand()
    5757  {
     
    6262      Node node = stoplistTM.nodeAt(j);
    6363      nodesForUndo.add(new NodeTimeName
    64           (node, (String)stoplistTM.getValueAt(j, 0),
    65            (String)stoplistTM.getValueAt(j, 1),
    66            (String)stoplistTM.getValueAt(j, 2)));
     64      (node, (String)stoplistTM.getValueAt(j, 0),
     65       (String)stoplistTM.getValueAt(j, 1),
     66       (String)stoplistTM.getValueAt(j, 2)));
    6767      stoplistTM.removeRow(j);
    6868      if (node == null)
    69         continue;
     69    continue;
    7070      Main.main.getCurrentDataSet().removePrimitive(node);
    7171      node.setDeleted(true);
     
    7373    return true;
    7474  }
    75  
     75
    7676  public void undoCommand()
    7777  {
     
    8282      stoplistTM.insertRow(j, ntn.node, ntn.time, ntn.name, ntn.shelter);
    8383      if (ntn.node == null)
    84         continue;
     84    continue;
    8585      ntn.node.setDeleted(false);
    8686      Main.main.getCurrentDataSet().addPrimitive(ntn.node);
    8787    }
    8888  }
    89  
     89
    9090  public void fillModifiedData
    9191    (Collection< OsmPrimitive > modified, Collection< OsmPrimitive > deleted,
     
    9393  {
    9494  }
    95  
     95
    9696  @Override public JLabel getDescription()
    9797  {
  • applications/editors/josm/plugins/public_transport/src/public_transport/TrackStoplistDetachCommand.java

    r22048 r23192  
    1515  private Vector< Node > nodesForUndo = null;
    1616  private TrackStoplistTableModel stoplistTM = null;
    17  
     17
    1818  public TrackStoplistDetachCommand(StopImporterAction controller)
    1919  {
     
    2121    workingLines = new Vector< Integer >();
    2222    nodesForUndo = new Vector< Node >();
    23    
     23
    2424    // use either selected lines or all lines if no line is selected
    2525    int[] selectedLines = controller.getDialog().getStoplistTable().getSelectedRows();
     
    2828    {
    2929      for (int i = 0; i < selectedLines.length; ++i)
    30         consideredLines.add(selectedLines[i]);
     30    consideredLines.add(selectedLines[i]);
    3131    }
    3232    else
    3333    {
    3434      for (int i = 0; i < stoplistTM.getRowCount(); ++i)
    35         consideredLines.add(new Integer(i));
     35    consideredLines.add(new Integer(i));
    3636    }
    37    
     37
    3838    // keep only lines where a node can be added
    3939    for (int i = 0; i < consideredLines.size(); ++i)
    4040    {
    4141      if (stoplistTM.nodeAt(consideredLines.elementAt(i)) != null)
    42         workingLines.add(consideredLines.elementAt(i));
     42    workingLines.add(consideredLines.elementAt(i));
    4343    }
    4444  }
    45  
     45
    4646  public boolean executeCommand()
    4747  {
     
    5656    return true;
    5757  }
    58  
     58
    5959  public void undoCommand()
    6060  {
     
    6666    }
    6767  }
    68  
     68
    6969  public void fillModifiedData
    7070    (Collection< OsmPrimitive > modified, Collection< OsmPrimitive > deleted,
     
    7272  {
    7373  }
    74  
     74
    7575  @Override public JLabel getDescription()
    7676  {
  • applications/editors/josm/plugins/public_transport/src/public_transport/TrackStoplistNameCommand.java

    r22048 r23192  
    2222  private String shelter = null;
    2323  private LatLon oldLatLon = null;
    24  
     24
    2525  @SuppressWarnings("unchecked")
    2626  public TrackStoplistNameCommand(TrackReference trackref, int workingLine)
     
    4242      this.shelter = null;
    4343  }
    44  
     44
    4545  public boolean executeCommand()
    4646  {
     
    6969    return true;
    7070  }
    71  
     71
    7272  public void undoCommand()
    7373  {
     
    9494    trackref.inEvent = false;
    9595  }
    96  
     96
    9797  public void fillModifiedData
    9898    (Collection< OsmPrimitive > modified, Collection< OsmPrimitive > deleted,
     
    100100  {
    101101  }
    102  
     102
    103103  @Override public JLabel getDescription()
    104104  {
  • applications/editors/josm/plugins/public_transport/src/public_transport/TrackStoplistRelocateCommand.java

    r22048 r23192  
    2121  private String gpsSyncTime = null;
    2222  private String stopwatchStart = null;
    23  
     23
    2424  public TrackStoplistRelocateCommand(StopImporterAction controller)
    2525  {
     
    3131    this.oldStopwatchStart = currentTrack.stopwatchStart;
    3232  }
    33  
     33
    3434  public boolean executeCommand()
    3535  {
     
    4040      Node node = currentTrack.stoplistTM.nodeAt(i);
    4141      if (node == null)
    42         continue;
    43        
     42    continue;
     43
    4444      double time = StopImporterDialog.parseTime
    45             ((String)currentTrack.stoplistTM.getValueAt(i, 0));
     45        ((String)currentTrack.stoplistTM.getValueAt(i, 0));
    4646      node.setCoor(currentTrack.computeCoor(time));
    4747    }
     
    5353      controller.inEvent = false;
    5454    }
    55    
     55
    5656    return true;
    5757  }
    58  
     58
    5959  public void undoCommand()
    6060  {
     
    6565      Node node = currentTrack.stoplistTM.nodeAt(i);
    6666      if (node == null)
    67         continue;
    68        
     67    continue;
     68
    6969      double time = StopImporterDialog.parseTime
    70             ((String)currentTrack.stoplistTM.getValueAt(i, 0));
     70        ((String)currentTrack.stoplistTM.getValueAt(i, 0));
    7171      node.setCoor(currentTrack.computeCoor(time));
    7272    }
     
    7979    }
    8080  }
    81  
     81
    8282  public void fillModifiedData
    8383    (Collection< OsmPrimitive > modified, Collection< OsmPrimitive > deleted,
     
    8585  {
    8686  }
    87  
     87
    8888  @Override public JLabel getDescription()
    8989  {
  • applications/editors/josm/plugins/public_transport/src/public_transport/TrackStoplistSortCommand.java

    r22048 r23192  
    2222  private int insPos;
    2323  private String stopwatchStart;
    24  
     24
    2525  public TrackStoplistSortCommand(StopImporterAction controller)
    2626  {
     
    2929    insPos = controller.getDialog().getStoplistTable().getSelectedRow();
    3030    stopwatchStart = controller.getCurrentTrack().stopwatchStart;
    31    
     31
    3232    // use either selected lines or all lines if no line is selected
    3333    int[] selectedLines = controller.getDialog().getStoplistTable().getSelectedRows();
     
    3535    {
    3636      for (int i = 0; i < selectedLines.length; ++i)
    37         workingLines.add(selectedLines[i]);
     37    workingLines.add(selectedLines[i]);
    3838    }
    3939    else
    4040    {
    4141      for (int i = 0; i < stoplistTM.getRowCount(); ++i)
    42         workingLines.add(new Integer(i));
     42    workingLines.add(new Integer(i));
    4343    }
    4444  }
    45  
     45
    4646  @SuppressWarnings("unchecked")
    4747  public boolean executeCommand()
    4848  {
    4949    tableDataModel = (Vector< Vector< Object > >)stoplistTM.getDataVector()
    50         .clone();
     50    .clone();
    5151    nodes = (Vector< Node >)stoplistTM.getNodes().clone();
    5252    times = (Vector< String >)stoplistTM.getTimes().clone();
    53    
     53
    5454    Vector< NodeSortEntry > nodesToSort = new Vector< NodeSortEntry >();
    5555    for (int i = workingLines.size()-1; i >= 0; --i)
     
    5757      int j = workingLines.elementAt(i).intValue();
    5858      nodesToSort.add(new NodeSortEntry
    59           (stoplistTM.nodeAt(j), (String)stoplistTM.getValueAt(j, 0),
    60             (String)stoplistTM.getValueAt(j, 1),
    61             (String)stoplistTM.getValueAt(j, 2),
    62              StopImporterDialog.parseTime(stopwatchStart)));
     59      (stoplistTM.nodeAt(j), (String)stoplistTM.getValueAt(j, 0),
     60        (String)stoplistTM.getValueAt(j, 1),
     61        (String)stoplistTM.getValueAt(j, 2),
     62         StopImporterDialog.parseTime(stopwatchStart)));
    6363      stoplistTM.removeRow(j);
    6464    }
    65    
     65
    6666    Collections.sort(nodesToSort);
    67    
     67
    6868    int insPos = this.insPos;
    6969    Iterator< NodeSortEntry > iter = nodesToSort.iterator();
     
    7373      stoplistTM.insertRow(insPos, nse.node, nse.time, nse.name, nse.shelter);
    7474      if (insPos >= 0)
    75         ++insPos;
     75    ++insPos;
    7676    }
    7777    return true;
    7878  }
    79  
     79
    8080  public void undoCommand()
    8181  {
     
    8484    stoplistTM.setTimes(times);
    8585  }
    86  
     86
    8787  public void fillModifiedData
    8888    (Collection< OsmPrimitive > modified, Collection< OsmPrimitive > deleted,
     
    9090  {
    9191  }
    92  
     92
    9393  @Override public JLabel getDescription()
    9494  {
    9595    return new JLabel("public_transport.TrackStoplist.Sort");
    9696  }
    97  
     97
    9898  private class NodeSortEntry implements Comparable< NodeSortEntry >
    9999  {
     
    103103    public String shelter = null;
    104104    public double startTime = 0;
    105    
     105
    106106    public NodeSortEntry
    107107        (Node node, String time, String name, String shelter, double startTime)
     
    112112      this.shelter = shelter;
    113113    }
    114    
     114
    115115    public int compareTo(NodeSortEntry nse)
    116116    {
    117117      double time = StopImporterDialog.parseTime(this.time);
    118118      if (time - startTime > 12*60*60)
    119         time -= 24*60*60;
    120      
     119    time -= 24*60*60;
     120
    121121      double nseTime = StopImporterDialog.parseTime(nse.time);
    122122      if (nseTime - startTime > 12*60*60)
    123         nseTime -= 24*60*60;
    124      
     123    nseTime -= 24*60*60;
     124
    125125      if (time < nseTime)
    126         return -1;
     126    return -1;
    127127      else if (time > nseTime)
    128         return 1;
     128    return 1;
    129129      else
    130         return 0;
     130    return 0;
    131131    }
    132132  };
  • applications/editors/josm/plugins/public_transport/src/public_transport/TrackStoplistTableModel.java

    r20839 r23192  
    1414  private Vector< String > times = null;
    1515  private static Vector< String > columns = null;
    16    
     16
    1717  public TrackStoplistTableModel(TrackReference tr)
    1818  {
     
    2626    nodes = new Vector< Node >();
    2727    times = new Vector< String >();
    28      
     28
    2929    setColumnIdentifiers(columns);
    3030    addTableModelListener(tr);
    3131  }
    32    
     32
    3333  public boolean isCellEditable(int row, int column) {
    3434    return true;
    3535  }
    36    
     36
    3737  public void addRow(Object[] obj) {
    3838    throw new UnsupportedOperationException();
    3939  }
    40    
     40
    4141  public void insertRow(int insPos, Object[] obj) {
    4242    throw new UnsupportedOperationException();
    4343  }
    44    
     44
    4545  public void addRow(String time) {
    4646    insertRow(-1, time);
    4747  }
    48    
     48
    4949  public void insertRow(int insPos, String time)
    5050  {
     
    118118    }
    119119  }
    120    
     120
    121121  public void clear()
    122122  {
     
    125125    super.setRowCount(0);
    126126  }
    127    
     127
    128128  public void setDataVector(Vector< Vector< Object > > dataVector)
    129129  {
  • applications/editors/josm/plugins/public_transport/src/public_transport/TrackSuggestStopsCommand.java

    r22048 r23192  
    2929  private Vector< Node > nodes = null;
    3030  private Vector< String > times = null;
    31  
     31
    3232  public TrackSuggestStopsCommand(StopImporterAction controller)
    3333  {
     
    4343    segments = controller.getCurrentTrack().getGpxTrack().getSegments();
    4444  }
    45  
     45
    4646  @SuppressWarnings("unchecked")
    4747  public boolean executeCommand()
     
    5050      return false;
    5151    tableDataModel = (Vector< Vector< Object > >)stoplistTM.getDataVector()
    52         .clone();
     52    .clone();
    5353    nodes = (Vector< Node >)stoplistTM.getNodes().clone();
    5454    times = (Vector< String >)stoplistTM.getTimes().clone();
    55    
     55
    5656    for (int i = 0; i < stoplistTM.getNodes().size(); ++i)
    5757    {
    5858      Node node = stoplistTM.nodeAt(i);
    5959      if (node == null)
    60         continue;
     60    continue;
    6161      Main.main.getCurrentDataSet().removePrimitive(node);
    6262      node.setDeleted(true);
     
    7070      Iterator< WayPoint > witer = siter.next().getWayPoints().iterator();
    7171      while (witer.hasNext())
    72         wayPoints.add(witer.next());
     72    wayPoints.add(witer.next());
    7373    }
    7474    Vector< Double > wayPointsDist = new Vector< Double >(wayPoints.size());
    75      
     75
    7676    int i = 0;
    7777    double time = -48*60*60;
     
    8080    {
    8181      if (wayPoints.elementAt(i).getString("time") != null)
    82         time = StopImporterDialog.parseTime(wayPoints.elementAt(i)
    83             .getString("time").substring(11,19));
     82    time = StopImporterDialog.parseTime(wayPoints.elementAt(i)
     83        .getString("time").substring(11,19));
    8484      if (time < dGpsStartTime)
    85         time += 24*60*60;
     85    time += 24*60*60;
    8686      wayPointsDist.add(Double.valueOf(Double.POSITIVE_INFINITY));
    8787      ++i;
     
    9393      while ((j > 0) && (time - timeWindow/2 < time2))
    9494      {
    95         --j;
    96         if (wayPoints.elementAt(j).getString("time") != null)
    97           time2 = StopImporterDialog.parseTime(wayPoints.elementAt(j)
    98               .getString("time").substring(11,19));
    99         if (time2 < dGpsStartTime)
    100           time2 += 24*60*60;
     95    --j;
     96    if (wayPoints.elementAt(j).getString("time") != null)
     97      time2 = StopImporterDialog.parseTime(wayPoints.elementAt(j)
     98          .getString("time").substring(11,19));
     99    if (time2 < dGpsStartTime)
     100      time2 += 24*60*60;
    101101      }
    102102      int k = i + 1;
     
    104104      while ((k < wayPoints.size()) && (time + timeWindow/2 > time2))
    105105      {
    106         if (wayPoints.elementAt(k).getString("time") != null)
    107           time2 = StopImporterDialog.parseTime(wayPoints.elementAt(k)
    108               .getString("time").substring(11,19));
    109         if (time2 < dGpsStartTime)
    110           time2 += 24*60*60;
    111         ++k;
    112       }
    113        
     106    if (wayPoints.elementAt(k).getString("time") != null)
     107      time2 = StopImporterDialog.parseTime(wayPoints.elementAt(k)
     108          .getString("time").substring(11,19));
     109    if (time2 < dGpsStartTime)
     110      time2 += 24*60*60;
     111    ++k;
     112      }
     113
    114114      if (j < k)
    115115      {
    116         double dist = 0;
    117         LatLon latLonI = wayPoints.elementAt(i).getCoor();
    118         for (int l = j; l < k; ++l)
    119         {
    120           double distL = latLonI.greatCircleDistance(wayPoints.elementAt(l).getCoor());
    121           if (distL > dist)
    122             dist = distL;
    123         }
    124         wayPointsDist.add(Double.valueOf(dist));
     116    double dist = 0;
     117    LatLon latLonI = wayPoints.elementAt(i).getCoor();
     118    for (int l = j; l < k; ++l)
     119    {
     120      double distL = latLonI.greatCircleDistance(wayPoints.elementAt(l).getCoor());
     121      if (distL > dist)
     122        dist = distL;
     123    }
     124    wayPointsDist.add(Double.valueOf(dist));
    125125      }
    126126      else
    127         wayPointsDist.add(Double.valueOf(Double.POSITIVE_INFINITY));
    128        
     127    wayPointsDist.add(Double.valueOf(Double.POSITIVE_INFINITY));
     128
    129129      if (wayPoints.elementAt(i).getString("time") != null)
    130         time = StopImporterDialog.parseTime(wayPoints.elementAt(i)
    131             .getString("time").substring(11,19));
     130    time = StopImporterDialog.parseTime(wayPoints.elementAt(i)
     131        .getString("time").substring(11,19));
    132132      if (time < dGpsStartTime)
    133         time += 24*60*60;
     133    time += 24*60*60;
    134134      ++i;
    135135    }
    136      
     136
    137137    LatLon lastStopCoor = null;
    138138    for (i = 1; i < wayPoints.size()-1; ++i)
    139139    {
    140140      if (wayPointsDist.elementAt(i).doubleValue() >= threshold)
    141         continue;
     141    continue;
    142142      if ((wayPointsDist.elementAt(i).compareTo(wayPointsDist.elementAt(i-1)) != -1)
    143            || (wayPointsDist.elementAt(i).compareTo(wayPointsDist.elementAt(i+1)) != -1))
    144         continue;
    145        
     143       || (wayPointsDist.elementAt(i).compareTo(wayPointsDist.elementAt(i+1)) != -1))
     144    continue;
     145
    146146      LatLon latLon = wayPoints.elementAt(i).getCoor();
    147147      if ((lastStopCoor != null) &&  (lastStopCoor.greatCircleDistance(latLon) < threshold))
    148         continue;
    149        
     148    continue;
     149
    150150      if (wayPoints.elementAt(i).getString("time") != null)
    151151      {
    152         time = StopImporterDialog.parseTime(wayPoints.elementAt(i)
    153             .getString("time").substring(11,19));
    154         double gpsSyncTime = StopImporterDialog.parseTime(this.gpsSyncTime);
    155         if (gpsSyncTime < dGpsStartTime - 12*60*60)
    156           gpsSyncTime += 24*60*60;
    157         double timeDelta = gpsSyncTime - StopImporterDialog.parseTime(stopwatchStart);
    158         time -= timeDelta;
    159         Node node = StopImporterAction.createNode(latLon, type, "");
    160         stoplistTM.insertRow(-1, node, StopImporterAction.timeOf(time), "", "");
    161       }
    162        
     152    time = StopImporterDialog.parseTime(wayPoints.elementAt(i)
     153        .getString("time").substring(11,19));
     154    double gpsSyncTime = StopImporterDialog.parseTime(this.gpsSyncTime);
     155    if (gpsSyncTime < dGpsStartTime - 12*60*60)
     156      gpsSyncTime += 24*60*60;
     157    double timeDelta = gpsSyncTime - StopImporterDialog.parseTime(stopwatchStart);
     158    time -= timeDelta;
     159    Node node = StopImporterAction.createNode(latLon, type, "");
     160    stoplistTM.insertRow(-1, node, StopImporterAction.timeOf(time), "", "");
     161      }
     162
    163163      lastStopCoor = latLon;
    164164    }
    165    
     165
    166166    return true;
    167167  }
    168  
     168
    169169  public void undoCommand()
    170170  {
     
    175175      Node node = stoplistTM.nodeAt(i);
    176176      if (node == null)
    177         continue;
     177    continue;
    178178      Main.main.getCurrentDataSet().removePrimitive(node);
    179179      node.setDeleted(true);
    180180    }
    181    
     181
    182182    stoplistTM.setDataVector(tableDataModel);
    183183    stoplistTM.setNodes(nodes);
    184184    stoplistTM.setTimes(times);
    185    
     185
    186186    for (int i = 0; i < stoplistTM.getNodes().size(); ++i)
    187187    {
    188188      Node node = stoplistTM.nodeAt(i);
    189189      if (node == null)
    190         continue;
     190    continue;
    191191      node.setDeleted(false);
    192192      Main.main.getCurrentDataSet().addPrimitive(node);
    193193    }
    194194  }
    195  
     195
    196196  public void fillModifiedData
    197197    (Collection< OsmPrimitive > modified, Collection< OsmPrimitive > deleted,
     
    199199  {
    200200  }
    201  
     201
    202202  @Override public JLabel getDescription()
    203203  {
    204204    return new JLabel("public_transport.TrackStoplist.SuggestStops");
    205205  }
    206  
     206
    207207  private class NodeSortEntry implements Comparable< NodeSortEntry >
    208208  {
     
    211211    public String name = null;
    212212    public double startTime = 0;
    213    
     213
    214214    public NodeSortEntry(Node node, String time, String name, double startTime)
    215215    {
     
    218218      this.name = name;
    219219    }
    220    
     220
    221221    public int compareTo(NodeSortEntry nse)
    222222    {
    223223      double time = StopImporterDialog.parseTime(this.time);
    224224      if (time - startTime > 12*60*60)
    225         time -= 24*60*60;
    226      
     225    time -= 24*60*60;
     226
    227227      double nseTime = StopImporterDialog.parseTime(nse.time);
    228228      if (nseTime - startTime > 12*60*60)
    229         nseTime -= 24*60*60;
    230      
     229    nseTime -= 24*60*60;
     230
    231231      if (time < nseTime)
    232         return -1;
     232    return -1;
    233233      else if (time > nseTime)
    234         return 1;
     234    return 1;
    235235      else
    236         return 0;
     236    return 0;
    237237    }
    238238  };
  • applications/editors/josm/plugins/public_transport/src/public_transport/WaypointTableModel.java

    r20835 r23192  
    2121  public Vector< Node > nodes = new Vector< Node >();
    2222  public Vector< LatLon > coors = new Vector< LatLon >();
    23    
     23
    2424  public WaypointTableModel(StopImporterAction controller)
    2525  {
     
    3030    addTableModelListener(this);
    3131  }
    32    
     32
    3333  public boolean isCellEditable(int row, int column)
    3434  {
     
    3737    return false;
    3838  }
    39    
     39
    4040  public void addRow(Object[] obj)
    4141  {
    4242    throw new UnsupportedOperationException();
    4343  }
    44    
     44
    4545  public void insertRow(int insPos, Object[] obj)
    4646  {
    4747    throw new UnsupportedOperationException();
    4848  }
    49    
     49
    5050  public void addRow(WayPoint wp)
    5151  {
    5252    insertRow(-1, wp);
    5353  }
    54    
     54
    5555  public void insertRow(int insPos, WayPoint wp)
    5656  {
     
    6464
    6565    Node node = controller.createNode(wp.getCoor(), buf[1]);
    66    
     66
    6767    if (insPos == -1)
    6868    {
     
    7878    }
    7979  }
    80    
     80
    8181  public void clear()
    8282  {
     
    8484    super.setRowCount(0);
    8585  }
    86  
     86
    8787  public void tableChanged(TableModelEvent e)
    8888  {
     
    9090    {
    9191      if (inEvent)
    92         return;
     92    return;
    9393      Main.main.undoRedo.add(new WaypointsNameCommand
    94           (this, e.getFirstRow(), (String)getValueAt(e.getFirstRow(), 1),
    95            (String)getValueAt(e.getFirstRow(), 2)));
     94      (this, e.getFirstRow(), (String)getValueAt(e.getFirstRow(), 1),
     95       (String)getValueAt(e.getFirstRow(), 2)));
    9696    }
    9797  }
  • applications/editors/josm/plugins/public_transport/src/public_transport/WaypointsDetachCommand.java

    r22048 r23192  
    1515  private Vector< Node > nodesForUndo = null;
    1616  private WaypointTableModel waypointTM = null;
    17  
     17
    1818  public WaypointsDetachCommand(StopImporterAction controller)
    1919  {
     
    2121    workingLines = new Vector< Integer >();
    2222    nodesForUndo = new Vector< Node >();
    23    
     23
    2424    // use either selected lines or all lines if no line is selected
    2525    int[] selectedLines = controller.getDialog().getWaypointsTable().getSelectedRows();
     
    2828    {
    2929      for (int i = 0; i < selectedLines.length; ++i)
    30         consideredLines.add(selectedLines[i]);
     30    consideredLines.add(selectedLines[i]);
    3131    }
    3232    else
    3333    {
    3434      for (int i = 0; i < waypointTM.getRowCount(); ++i)
    35         consideredLines.add(new Integer(i));
     35    consideredLines.add(new Integer(i));
    3636    }
    37    
     37
    3838    // keep only lines where a node can be added
    3939    for (int i = 0; i < consideredLines.size(); ++i)
    4040    {
    4141      if (waypointTM.nodes.elementAt(consideredLines.elementAt(i)) != null)
    42         workingLines.add(consideredLines.elementAt(i));
     42    workingLines.add(consideredLines.elementAt(i));
    4343    }
    4444  }
    45  
     45
    4646  public boolean executeCommand()
    4747  {
     
    5656    return true;
    5757  }
    58  
     58
    5959  public void undoCommand()
    6060  {
     
    6666    }
    6767  }
    68  
     68
    6969  public void fillModifiedData
    7070    (Collection< OsmPrimitive > modified, Collection< OsmPrimitive > deleted,
     
    7272  {
    7373  }
    74  
     74
    7575  @Override public JLabel getDescription()
    7676  {
  • applications/editors/josm/plugins/public_transport/src/public_transport/WaypointsDisableCommand.java

    r22048 r23192  
    1515  private Vector< Node > nodesForUndo = null;
    1616  private WaypointTableModel waypointTM = null;
    17  
     17
    1818  public WaypointsDisableCommand(StopImporterAction controller)
    1919  {
     
    2121    workingLines = new Vector< Integer >();
    2222    nodesForUndo = new Vector< Node >();
    23    
     23
    2424    // use either selected lines or all lines if no line is selected
    2525    int[] selectedLines = controller.getDialog().getWaypointsTable().getSelectedRows();
     
    2828    {
    2929      for (int i = 0; i < selectedLines.length; ++i)
    30         consideredLines.add(selectedLines[i]);
     30    consideredLines.add(selectedLines[i]);
    3131    }
    3232    else
    3333    {
    3434      for (int i = 0; i < waypointTM.getRowCount(); ++i)
    35         consideredLines.add(new Integer(i));
     35    consideredLines.add(new Integer(i));
    3636    }
    37    
     37
    3838    // keep only lines where a node can be added
    3939    for (int i = 0; i < consideredLines.size(); ++i)
    4040    {
    4141      if (waypointTM.nodes.elementAt(consideredLines.elementAt(i)) != null)
    42         workingLines.add(consideredLines.elementAt(i));
     42    workingLines.add(consideredLines.elementAt(i));
    4343    }
    4444  }
    45  
     45
    4646  public boolean executeCommand()
    4747  {
     
    5353      nodesForUndo.add(node);
    5454      if (node == null)
    55         continue;
     55    continue;
    5656      waypointTM.nodes.set(j, null);
    5757      Main.main.getCurrentDataSet().removePrimitive(node);
     
    6060    return true;
    6161  }
    62  
     62
    6363  public void undoCommand()
    6464  {
     
    6969      waypointTM.nodes.set(j, node);
    7070      if (node == null)
    71         continue;
     71    continue;
    7272      node.setDeleted(false);
    7373      Main.main.getCurrentDataSet().addPrimitive(node);
    7474    }
    7575  }
    76  
     76
    7777  public void fillModifiedData
    7878    (Collection< OsmPrimitive > modified, Collection< OsmPrimitive > deleted,
     
    8080  {
    8181  }
    82  
     82
    8383  @Override public JLabel getDescription()
    8484  {
  • applications/editors/josm/plugins/public_transport/src/public_transport/WaypointsEnableCommand.java

    r22048 r23192  
    1515  private WaypointTableModel waypointTM = null;
    1616  private String type = null;
    17  
     17
    1818  public WaypointsEnableCommand(StopImporterAction controller)
    1919  {
     
    2121    type = controller.getDialog().getStoptype();
    2222    workingLines = new Vector< Integer >();
    23    
     23
    2424    // use either selected lines or all lines if no line is selected
    2525    int[] selectedLines = controller.getDialog().getWaypointsTable().getSelectedRows();
     
    2828    {
    2929      for (int i = 0; i < selectedLines.length; ++i)
    30         consideredLines.add(selectedLines[i]);
     30    consideredLines.add(selectedLines[i]);
    3131    }
    3232    else
    3333    {
    3434      for (int i = 0; i < waypointTM.getRowCount(); ++i)
    35         consideredLines.add(new Integer(i));
     35    consideredLines.add(new Integer(i));
    3636    }
    37    
     37
    3838    // keep only lines where a node can be added
    3939    for (int i = 0; i < consideredLines.size(); ++i)
    4040    {
    4141      if (waypointTM.nodes.elementAt(consideredLines.elementAt(i)) == null)
    42         workingLines.add(consideredLines.elementAt(i));
     42    workingLines.add(consideredLines.elementAt(i));
    4343    }
    4444  }
    45  
     45
    4646  public boolean executeCommand()
    4747  {
     
    5252        (waypointTM.coors.elementAt(j), type, (String)waypointTM.getValueAt(j, 1));
    5353      if ("".equals((String)waypointTM.getValueAt(j, 2)))
    54         node.put("shelter", null);
     54    node.put("shelter", null);
    5555      else
    56         node.put("shelter", (String)waypointTM.getValueAt(j, 2));
     56    node.put("shelter", (String)waypointTM.getValueAt(j, 2));
    5757      waypointTM.nodes.set(j, node);
    5858    }
    5959    return true;
    6060  }
    61  
     61
    6262  public void undoCommand()
    6363  {
     
    6868      waypointTM.nodes.set(j, null);
    6969      if (node == null)
    70         continue;
     70    continue;
    7171      Main.main.getCurrentDataSet().removePrimitive(node);
    7272      node.setDeleted(true);
    7373    }
    7474  }
    75  
     75
    7676  public void fillModifiedData
    7777    (Collection< OsmPrimitive > modified, Collection< OsmPrimitive > deleted,
     
    7979  {
    8080  }
    81  
     81
    8282  @Override public JLabel getDescription()
    8383  {
  • applications/editors/josm/plugins/public_transport/src/public_transport/WaypointsNameCommand.java

    r22048 r23192  
    1818  private String oldShelter = null;
    1919  private String shelter = null;
    20  
     20
    2121  public WaypointsNameCommand
    2222      (WaypointTableModel waypointTM, int workingLine, String name, String shelter)
     
    3434      this.shelter = null;
    3535  }
    36  
     36
    3737  public boolean executeCommand()
    3838  {
     
    5454    return true;
    5555  }
    56  
     56
    5757  public void undoCommand()
    5858  {
     
    7373    waypointTM.inEvent = false;
    7474  }
    75  
     75
    7676  public void fillModifiedData
    7777    (Collection< OsmPrimitive > modified, Collection< OsmPrimitive > deleted,
     
    7979  {
    8080  }
    81  
     81
    8282  @Override public JLabel getDescription()
    8383  {
  • applications/editors/josm/plugins/reverter/src/reverter/ChangesetIdQuery.java

    r22533 r23192  
    3131        try {
    3232          return NumberFormat.getInstance().parse(tcid.getText()).intValue();
    33         } catch (ParseException e) {           
     33        } catch (ParseException e) {
    3434          return 0;
    3535        }
     
    5050        panel.add(new JLabel(tr("Changeset id:")));
    5151        panel.add(tcid, GBC.eol().fill(GBC.HORIZONTAL));
    52        
     52
    5353        bgRevertType.add(rbFull);
    5454        bgRevertType.add(rbSelection);
    5555        bgRevertType.add(rbSelectionUndelete);
    56        
     56
    5757        rbFull.setSelected(true);
    5858        panel.add(rbFull, GBC.eol().insets(0,10,0,0).fill(GBC.HORIZONTAL));
    5959        panel.add(rbSelection, GBC.eol().fill(GBC.HORIZONTAL));
    6060        panel.add(rbSelectionUndelete, GBC.eol().fill(GBC.HORIZONTAL));
    61        
     61
    6262        setContent(panel);
    63         setupDialog();       
     63        setupDialog();
    6464    }
    6565}
  • applications/editors/josm/plugins/reverter/src/reverter/ChangesetReverter.java

    r21807 r23192  
    5454    public final RevertType revertType;
    5555
    56     private final OsmDataLayer layer; // data layer associated with reverter 
    57     private final DataSet ds; // DataSet associated with reverter 
    58     private final ChangesetDataSet cds; // Current changeset data 
     56    private final OsmDataLayer layer; // data layer associated with reverter
     57    private final DataSet ds; // DataSet associated with reverter
     58    private final ChangesetDataSet cds; // Current changeset data
    5959    private DataSet nds; // Dataset that contains new objects downloaded by reverter
    6060
     
    6868    ////////////////////////////////////////
    6969    private void addIfMissing(PrimitiveId id) {
    70         OsmPrimitive p = ds.getPrimitiveById(id); 
     70        OsmPrimitive p = ds.getPrimitiveById(id);
    7171        if (p == null || p.isIncomplete()) {
    7272            missing.add(id);
     
    9494        }
    9595    }
    96    
     96
    9797    /**
    9898     * Checks if {@see ChangesetDataSetEntry} conforms to current RevertType
    9999     * @param entry entry to be checked
    100      * @return <code>true</code> if {@see ChangesetDataSetEntry} conforms to current RevertType 
     100     * @return <code>true</code> if {@see ChangesetDataSetEntry} conforms to current RevertType
    101101     */
    102102    private boolean CheckOsmChangeEntry(ChangesetDataSetEntry entry) {
     
    110110        return p.isSelected();
    111111    }
    112    
     112
    113113    /**
    114114     * creates a reverter for specific changeset and fetches initial data
     
    132132            monitor.finishTask();
    133133        }
    134        
     134
    135135        // Build our own lists of created/updated/modified objects for better performance
    136136        for (Iterator<ChangesetDataSetEntry> it = cds.iterator();it.hasNext();) {
     
    163163    public void downloadObjectsHistory(ProgressMonitor progressMonitor) throws OsmTransferException {
    164164        final OsmServerMultiObjectReader rdr = new OsmServerMultiObjectReader();
    165        
     165
    166166        progressMonitor.beginTask("Downloading objects history",updated.size()+deleted.size()+1);
    167167        try {
     
    182182        }
    183183    }
    184    
     184
    185185    public void downloadMissingPrimitives(ProgressMonitor monitor) throws OsmTransferException {
    186186        if (!hasMissingObjects()) return;
     
    200200            }
    201201        }
    202         DataSet source = rdr.parseOsm(monitor); 
     202        DataSet source = rdr.parseOsm(monitor);
    203203        for (OsmPrimitive p : source.allPrimitives()) {
    204204            if (!p.isVisible() && !p.isDeleted()) {
     
    210210        missing.clear();
    211211    }
    212    
     212
    213213    private static Conflict<? extends OsmPrimitive> CreateConflict(OsmPrimitive p, boolean isMyDeleted) {
    214214        switch (p.getType()) {
     
    222222        }
    223223    }
    224    
     224
    225225    private static boolean hasEqualSemanticAttributes(OsmPrimitive current,HistoryOsmPrimitive history) {
    226226        if (!current.getKeys().equals(history.getTags())) return false;
     
    237237            return true;
    238238        case RELATION:
    239             List<org.openstreetmap.josm.data.osm.RelationMember> currentMembers = 
     239            List<org.openstreetmap.josm.data.osm.RelationMember> currentMembers =
    240240                ((Relation)current).getMembers();
    241241            List<RelationMember> historyMembers = ((HistoryRelation)history).getMembers();
    242242            if (currentMembers.size() != historyMembers.size()) return false;
    243243            for (int i = 0; i < currentMembers.size(); i++) {
    244                 org.openstreetmap.josm.data.osm.RelationMember currentMember = 
     244                org.openstreetmap.josm.data.osm.RelationMember currentMember =
    245245                    currentMembers.get(i);
    246246                RelationMember historyMember = historyMembers.get(i);
     
    253253        }
    254254    }
    255    
     255
    256256    /**
    257257     * Builds a list of commands that will revert the changeset
    258      * 
     258     *
    259259     */
    260260    public List<Command> getCommands() {
    261261        if (this.nds == null) return null;
    262        
     262
    263263        //////////////////////////////////////////////////////////////////////////
    264264        // Create commands to restore/update all affected objects
     
    282282            if (p != null) toDelete.add(p);
    283283        }
    284        
     284
    285285
    286286        //////////////////////////////////////////////////////////////////////////
    287287        // Check reversion against current dataset and create necessary conflicts
    288        
     288
    289289        HashSet<OsmPrimitive> conflicted = new HashSet<OsmPrimitive>();
    290        
     290
    291291        for (Conflict<? extends OsmPrimitive> conflict : merger.getConflicts()) {
    292292            cmds.add(new ConflictAddCommand(layer,conflict));
    293293        }
    294        
     294
    295295        // Check objects versions
    296296        for (Iterator<ChangesetDataSetEntry> it = cds.iterator();it.hasNext();) {
     
    302302                throw new IllegalStateException(tr("Missing merge target for {0} with id {1}",
    303303                        hp.getType(), hp.getId()));
    304            
     304
    305305            if (hp.getVersion() != dp.getVersion()
    306306                    && (hp.isVisible() || dp.isVisible()) &&
     
    309309                     */
    310310                    !hasEqualSemanticAttributes(dp,hp)) {
    311                
    312                
    313                 cmds.add(new ConflictAddCommand(layer,CreateConflict(dp, 
     311
     312
     313                cmds.add(new ConflictAddCommand(layer,CreateConflict(dp,
    314314                        entry.getModificationType() == ChangesetModificationType.CREATED)));
    315315                conflicted.add(dp);
    316316            }
    317317        }
    318        
     318
    319319        /* Check referrers for deleted objects: if object is referred by another object that
    320320         * isn't going to be deleted or modified, create a conflict.
     
    340340            }
    341341        }
    342        
     342
    343343        // Create a Command to delete all marked objects
    344344        List<? extends OsmPrimitive> list;
  • applications/editors/josm/plugins/reverter/src/reverter/MultiOsmReader.java

    r21634 r23192  
    561561        processRelationsAfterParsing();
    562562    }
    563    
    564    
     563
     564
    565565}
  • applications/editors/josm/plugins/reverter/src/reverter/ObjectsHistoryAction.java

    r21634 r23192  
    1616                Shortcut.registerShortcut("tool:history",
    1717                        "Tool: Display objects history dialog",
    18                         KeyEvent.VK_H, Shortcut.GROUP_EDIT, 
     18                        KeyEvent.VK_H, Shortcut.GROUP_EDIT,
    1919                        Shortcut.SHIFT_DEFAULT),
    2020                true);
  • applications/editors/josm/plugins/reverter/src/reverter/ObjectsHistoryDialog.java

    r22533 r23192  
    1818        setButtonIcons(new String[] {"ok.png", "cancel.png" });
    1919        setContent(new JPanel(new GridBagLayout()));
    20         setupDialog();       
     20        setupDialog();
    2121    }
    2222}
  • applications/editors/josm/plugins/reverter/src/reverter/PrimitiveIdVersion.java

    r21700 r23192  
    2020        return version;
    2121    }
    22    
     22
    2323    @Override
    2424    public int hashCode() {
  • applications/editors/josm/plugins/reverter/src/reverter/RevertChangesetAction.java

    r21726 r23192  
    2727                Shortcut.registerShortcut("tool:revert",
    2828                        tr("Tool: {0}", tr("Revert changeset")),
    29                         KeyEvent.VK_T, Shortcut.GROUP_EDIT, 
    30                         Shortcut.SHIFT_DEFAULT), 
     29                        KeyEvent.VK_T, Shortcut.GROUP_EDIT,
     30                        Shortcut.SHIFT_DEFAULT),
    3131                true);
    3232    }
    33    
     33
    3434    @Override
    3535    protected void updateEnabledState() {
     
    4747        if (changesetId == 0) return;
    4848        if (revertType == null) return;
    49        
     49
    5050        Main.worker.submit(new PleaseWaitRunnable(tr("Reverting...")) {
    5151            private ChangesetReverter rev;
    5252            private boolean downloadConfirmed = false;
    53            
     53
    5454            private boolean checkAndDownloadMissing() throws OsmTransferException {
    5555                if (!rev.hasMissingObjects()) return true;
    5656                if (!downloadConfirmed) {
    5757                    downloadConfirmed = JOptionPane.showConfirmDialog(Main.parent,
    58                             tr("This changeset has objects that are not present in current dataset.\n" + 
     58                            tr("This changeset has objects that are not present in current dataset.\n" +
    5959                                    "It is needed to download them before reverting. Do you want to continue?"),
    6060                            tr("Confirm"), JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION;
    6161                    if (!downloadConfirmed) return false;
    6262                }
    63                 final PleaseWaitProgressMonitor monitor = 
     63                final PleaseWaitProgressMonitor monitor =
    6464                    new PleaseWaitProgressMonitor(tr("Fetching missing primitives"));
    6565                try {
     
    7070                return !monitor.isCancelled();
    7171            }
    72            
     72
    7373            @Override
    7474            protected void realRun() throws OsmTransferException {
     
    9090                    rev.downloadMissingPrimitives(progressMonitor.createSubTaskMonitor(0, false));
    9191                }
    92                
     92
    9393                if (progressMonitor.isCancelled()) return;
    9494                rev.downloadObjectsHistory(progressMonitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false));
     
    9696                if (!checkAndDownloadMissing()) return;
    9797                List<Command> cmds = rev.getCommands();
    98                 Command cmd = new SequenceCommand(tr(revertType == RevertType.FULL ? "Revert changeset #{0}" : 
     98                Command cmd = new SequenceCommand(tr(revertType == RevertType.FULL ? "Revert changeset #{0}" :
    9999                        "Partially revert changeset #{0}",changesetId),cmds);
    100100                Main.main.undoRedo.add(cmd);
  • applications/editors/josm/plugins/reverter/src/reverter/ReverterPlugin.java

    r21807 r23192  
    1818        JMenu historyMenu = Main.main.menu.addMenu(marktr("History"), KeyEvent.VK_R,
    1919                Main.main.menu.defaultMenuPos,ht("/Plugin/Reverter"));
    20         //MainMenu.add(historyMenu, new ObjectsHistoryAction());       
     20        //MainMenu.add(historyMenu, new ObjectsHistoryAction());
    2121        MainMenu.add(historyMenu, new RevertChangesetAction());
    2222    }
  • applications/editors/josm/plugins/roadsigns/src/org/openstreetmap/josm/plugins/roadsigns/RoadSignInputDialog.java

    r22423 r23192  
    471471    public JComponent buildPreviewPanel() {
    472472        JPanel previewPanel = new JPanel(new GridBagLayout());
    473        
     473
    474474        String[] columnNames = {tr("Key"), tr("Value")};
    475475        String[][] data = {{}};
     
    495495        scroll.setPreferredSize(dim);
    496496        scroll.setMinimumSize(dim); /* minimum size is relevant for multisplit layout */
    497        
     497
    498498        addTrafficSignTag = new JCheckBox(tr("{0} tag", "traffic_sign"));
    499499        addTrafficSignTag.setSelected(Main.pref.getBoolean("plugin.roadsigns.addTrafficSignTag"));
     
    503503            }
    504504        });
    505        
     505
    506506        previewPanel.add(scroll, GBC.eol().fill());
    507507        previewPanel.add(addTrafficSignTag, GBC.eol());
     
    544544            final TreeMap<String, String> map= new TreeMap<String, String>();
    545545            String traffic_sign = "";
    546            
     546
    547547            for (SignCombination sc : sel.combos) {
    548548                final Map<String, String> env = new HashMap<String, String>();
     
    596596                    }
    597597                }
    598                
     598
    599599                Map<String, TagEvaluater> tags = new LinkedHashMap<String, TagEvaluater>();
    600600                for (SignWrapper sw : sc.signs) {
     
    654654                    map.putAll(result);
    655655                }
    656                
     656
    657657                if (combo_traffic_sign.length() != 0) {
    658658                    if (traffic_sign.length() != 0) {
  • applications/editors/josm/plugins/roadsigns/src/org/openstreetmap/josm/plugins/roadsigns/RoadSignsReader.java

    r22420 r23192  
    104104                }
    105105                curSign.iconURL = iconURL;
    106                  
     106
    107107                if ("yes".equals(atts.getValue("supplementary"))) {
    108108                    curSign.isSupplementing = true;
    109109                }
    110                
     110
    111111                curSign.wiki = atts.getValue("wiki");
    112112                curSign.loc_wiki = getLocalized(atts, "wiki");
     
    296296        }
    297297    }
    298    
     298
    299299    /**
    300300     *
  • applications/editors/josm/plugins/roadsigns/src/org/openstreetmap/josm/plugins/roadsigns/javacc/ParamStringScannerConstants.java

    r21967 r23192  
    33
    44
    5 /** 
     5/**
    66 * Token literal values and constants.
    77 * Generated by org.javacc.parser.OtherFilesGen#start()
  • applications/editors/josm/plugins/roadsigns/src/org/openstreetmap/josm/plugins/roadsigns/javacc/ParamStringScannerTokenManager.java

    r21967 r23192  
    167167}
    168168static final int[] jjnextStates = {
    169    1, 3, 5, 6, 9, 10, 
     169   1, 3, 5, 6, 9, 10,
    170170};
    171171
     
    176176/** Lexer state names. */
    177177public static final String[] lexStateNames = {
    178    "DEFAULT", 
     178   "DEFAULT",
    179179};
    180180protected SimpleCharStream input_stream;
     
    259259
    260260/** Get the next Token. */
    261 public Token getNextToken() 
     261public Token getNextToken()
    262262{
    263263  Token matchedToken;
     
    266266  EOFLoop :
    267267  for (;;)
    268   {   
    269    try   
    270    {     
     268  {
     269   try
     270   {
    271271      curChar = input_stream.BeginToken();
    272    }     
     272   }
    273273   catch(java.io.IOException e)
    274    {       
     274   {
    275275      jjmatchedKind = 0;
    276276      matchedToken = jjFillToken();
  • applications/editors/josm/plugins/roadsigns/src/org/openstreetmap/josm/plugins/roadsigns/javacc/ParseException.java

    r21967 r23192  
    127127      retval += add_escapes(tok.image);
    128128      retval += " \"";
    129       tok = tok.next; 
     129      tok = tok.next;
    130130    }
    131131    retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn;
     
    144144   */
    145145  protected String eol = System.getProperty("line.separator", "\n");
    146  
     146
    147147  /**
    148148   * Used to convert raw characters to their escaped version
  • applications/editors/josm/plugins/roadsigns/src/org/openstreetmap/josm/plugins/roadsigns/javacc/SimpleCharStream.java

    r21967 r23192  
    205205
    206206  /**
    207    * @deprecated 
     207   * @deprecated
    208208   * @see #getEndColumn
    209209   */
     
    214214
    215215  /**
    216    * @deprecated 
     216   * @deprecated
    217217   * @see #getEndLine
    218218   */
     
    449449        columnDiff = nextColDiff;
    450450        i++;
    451      } 
     451     }
    452452
    453453     if (i < len)
  • applications/editors/josm/plugins/roadsigns/src/org/openstreetmap/josm/plugins/roadsigns/javacc/TokenMgrError.java

    r21967 r23192  
    8989    * Returns a detailed message for the Error when it is thrown by the
    9090    * token manager to indicate a lexical error.
    91     * Parameters : 
     91    * Parameters :
    9292    *    EOFSeen     : indicates if EOF caused the lexical error
    9393    *    curLexState : lexical state in which this error occurred
     
    109109    * You can also modify the body of this method to customize your error messages.
    110110    * For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE are not
    111     * of end-users concern, so you can return something like : 
     111    * of end-users concern, so you can return something like :
    112112    *
    113113    *     "Internal Error : Please file a bug report .... "
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/CreateOrEditTurnRestrictionAction.java

    r20701 r23192  
    2929 */
    3030public class CreateOrEditTurnRestrictionAction extends JosmAction {
    31         static private final Logger logger = Logger.getLogger(CreateOrEditTurnRestrictionAction.class.getName());
    32        
    33         /**
    34         * Installs the global key stroke with which creating/editing a turn restriction
    35         * is triggered.
    36         *
    37         * @param keyStroke the key stroke
    38         */
    39         static public void install(KeyStroke keyStroke){
    40                 InputMap im = Main.contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    41                 Object actionMapKey = im.get(keyStroke);
    42                 if (actionMapKey != null && !actionMapKey.toString().equals("turnrestrictions:create-or-edit")) {
    43                         System.out.println(tr("Warning: turnrestrictions plugin replaces already existing action ''{0}'' behind shortcut ''{1}'' by action ''{2}''", actionMapKey.toString(), keyStroke.toString(), "turnrestrictions:create-or-edit"));                       
    44                 }
    45                 KeyStroke[] keys = im.keys();
    46                 if (keys != null){
    47                         for(KeyStroke ks: im.keys()){
    48                                 if (im.get(ks).equals("turnrestrictions:create-or-edit")) {
    49                                         im.remove(ks);
    50                                 }
    51                         }
    52                 }
    53                 im.put(keyStroke, "turnrestrictions:create-or-edit");
    54                 ActionMap am = Main.contentPane.getActionMap();
    55                 am.put("turnrestrictions:create-or-edit", getInstance());
    56         }
    57        
    58         /**
    59         * Installs  global key stroke configured in the preferences.
    60         *
    61         * @param keyStroke the key stroke
    62         */
    63         static public void install(){
    64                 String value = Main.pref.get(PreferenceKeys.EDIT_SHORTCUT, "shift ctrl T");
    65                 KeyStroke key = KeyStroke.getKeyStroke(value);
    66                 if (key == null){
    67                         System.out.println(tr("Warning: illegal value ''{0}'' for preference key ''{1}''. Falling back to default value ''shift ctrl T''.", value, PreferenceKeys.EDIT_SHORTCUT));
    68                         key = KeyStroke.getKeyStroke("shift ctrl T");
    69                 }
    70                 install(key);
    71         }
    72        
    73         /** the singleton instance of this action */
    74         private static CreateOrEditTurnRestrictionAction instance;
    75        
    76         /**
    77         * Replies the unique instance of this action
    78         *
    79         * @return
    80         */
    81         public static CreateOrEditTurnRestrictionAction getInstance() {
    82                 if (instance == null){
    83                         instance = new CreateOrEditTurnRestrictionAction();
    84                 }
    85                 return instance;
    86         }
    87        
    88         protected CreateOrEditTurnRestrictionAction() {
    89                 super(
    90                     tr("Create/Edit turn restriction..."),
    91                     null,
    92                     tr("Create or edit a turn restriction."),
    93                     null, // shortcut is going to be registered later
    94                         false
    95             );
    96         }       
    97        
    98         public void actionPerformed(ActionEvent e) {
    99                 OsmDataLayer layer = Main.main.getEditLayer();
    100                 if (layer == null) return;
    101                 Collection<Relation> trs = TurnRestrictionSelectionPopupPanel.getTurnRestrictionsParticipatingIn(layer.data.getSelected());
    102                 if (layer == null) return;
    103                 if (trs.isEmpty()){
    104                         // current selection isn't participating in turn restrictions. Launch
    105                         // an editor for a new turn restriction
    106                         //
    107                         Relation tr = new TurnRestrictionBuilder().buildFromSelection(layer);
    108                         TurnRestrictionEditor editor = new TurnRestrictionEditor(Main.map.mapView,layer,tr);
    109                         TurnRestrictionEditorManager.getInstance().positionOnScreen(editor);
    110                         TurnRestrictionEditorManager.getInstance().register(layer, tr, editor);
    111                         editor.setVisible(true);
    112                 } else {
    113                         // let the user choose whether he wants to create a new turn restriction or
    114                         // edit one of the turn restrictions participating in the current selection
    115                         TurnRestrictionSelectionPopupPanel pnl = new TurnRestrictionSelectionPopupPanel(
    116                                         layer
    117                         );
    118                         pnl.launch();
    119                 }
    120         }
     31    static private final Logger logger = Logger.getLogger(CreateOrEditTurnRestrictionAction.class.getName());
     32   
     33    /**
     34    * Installs the global key stroke with which creating/editing a turn restriction
     35    * is triggered.
     36    *
     37    * @param keyStroke the key stroke
     38    */
     39    static public void install(KeyStroke keyStroke){
     40        InputMap im = Main.contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
     41        Object actionMapKey = im.get(keyStroke);
     42        if (actionMapKey != null && !actionMapKey.toString().equals("turnrestrictions:create-or-edit")) {
     43            System.out.println(tr("Warning: turnrestrictions plugin replaces already existing action ''{0}'' behind shortcut ''{1}'' by action ''{2}''", actionMapKey.toString(), keyStroke.toString(), "turnrestrictions:create-or-edit"));           
     44        }
     45        KeyStroke[] keys = im.keys();
     46        if (keys != null){
     47            for(KeyStroke ks: im.keys()){
     48                if (im.get(ks).equals("turnrestrictions:create-or-edit")) {
     49                    im.remove(ks);
     50                }
     51            }
     52        }
     53        im.put(keyStroke, "turnrestrictions:create-or-edit");
     54        ActionMap am = Main.contentPane.getActionMap();
     55        am.put("turnrestrictions:create-or-edit", getInstance());
     56    }
     57   
     58    /**
     59    * Installs  global key stroke configured in the preferences.
     60    *
     61    * @param keyStroke the key stroke
     62    */
     63    static public void install(){
     64        String value = Main.pref.get(PreferenceKeys.EDIT_SHORTCUT, "shift ctrl T");
     65        KeyStroke key = KeyStroke.getKeyStroke(value);
     66        if (key == null){
     67            System.out.println(tr("Warning: illegal value ''{0}'' for preference key ''{1}''. Falling back to default value ''shift ctrl T''.", value, PreferenceKeys.EDIT_SHORTCUT));
     68            key = KeyStroke.getKeyStroke("shift ctrl T");
     69        }
     70        install(key);
     71    }
     72   
     73    /** the singleton instance of this action */
     74    private static CreateOrEditTurnRestrictionAction instance;
     75   
     76    /**
     77    * Replies the unique instance of this action
     78    *
     79    * @return
     80    */
     81    public static CreateOrEditTurnRestrictionAction getInstance() {
     82        if (instance == null){
     83            instance = new CreateOrEditTurnRestrictionAction();
     84        }
     85        return instance;
     86    }
     87   
     88    protected CreateOrEditTurnRestrictionAction() {
     89        super(
     90            tr("Create/Edit turn restriction..."),
     91            null,
     92            tr("Create or edit a turn restriction."),
     93            null, // shortcut is going to be registered later
     94            false
     95        );
     96    }   
     97   
     98    public void actionPerformed(ActionEvent e) {
     99        OsmDataLayer layer = Main.main.getEditLayer();
     100        if (layer == null) return;
     101        Collection<Relation> trs = TurnRestrictionSelectionPopupPanel.getTurnRestrictionsParticipatingIn(layer.data.getSelected());
     102        if (layer == null) return;
     103        if (trs.isEmpty()){
     104            // current selection isn't participating in turn restrictions. Launch
     105            // an editor for a new turn restriction
     106            //
     107            Relation tr = new TurnRestrictionBuilder().buildFromSelection(layer);
     108            TurnRestrictionEditor editor = new TurnRestrictionEditor(Main.map.mapView,layer,tr);
     109            TurnRestrictionEditorManager.getInstance().positionOnScreen(editor);
     110            TurnRestrictionEditorManager.getInstance().register(layer, tr, editor);
     111            editor.setVisible(true);
     112        } else {
     113            // let the user choose whether he wants to create a new turn restriction or
     114            // edit one of the turn restrictions participating in the current selection
     115            TurnRestrictionSelectionPopupPanel pnl = new TurnRestrictionSelectionPopupPanel(
     116                    layer
     117            );
     118            pnl.launch();
     119        }
     120    }
    121121}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/TurnRestrictionBuilder.java

    r20724 r23192  
    2121public class TurnRestrictionBuilder {
    2222
    23         private Way from;
    24         private Way to;
    25         private final ArrayList<OsmPrimitive> vias = new ArrayList<OsmPrimitive>();
    26        
    27         public TurnRestrictionBuilder(){
    28         }
    29        
    30         /**
    31         * Initializes the 'from' leg. Proposes the  first element
    32         * in {@code primitives} as 'from' leg if this element is a
    33         * non-deleted, visible way.
    34         *
    35         * @param primitives
    36         */
    37         protected void initFromLeg(List<OsmPrimitive> primitives){
    38                 if (primitives == null || primitives.isEmpty()) return;
    39                 OsmPrimitive p = primitives.get(0);
    40                 if (! (p instanceof Way)) return;
    41                 Way fromLeg = (Way)p;
    42                 if (fromLeg.isDeleted() || ! fromLeg.isVisible()) return;
    43                 this.from = fromLeg;
    44         }
     23    private Way from;
     24    private Way to;
     25    private final ArrayList<OsmPrimitive> vias = new ArrayList<OsmPrimitive>();
     26   
     27    public TurnRestrictionBuilder(){
     28    }
     29   
     30    /**
     31    * Initializes the 'from' leg. Proposes the  first element
     32    * in {@code primitives} as 'from' leg if this element is a
     33    * non-deleted, visible way.
     34    *
     35    * @param primitives
     36    */
     37    protected void initFromLeg(List<OsmPrimitive> primitives){
     38        if (primitives == null || primitives.isEmpty()) return;
     39        OsmPrimitive p = primitives.get(0);
     40        if (! (p instanceof Way)) return;
     41        Way fromLeg = (Way)p;
     42        if (fromLeg.isDeleted() || ! fromLeg.isVisible()) return;
     43        this.from = fromLeg;
     44    }
    4545
    46         /**
    47         * Initializes the 'to' leg. Proposes the last element
    48         * in {@code primitives} as 'to' leg if this element is a
    49         * non-deleted, visible way.
    50         *
    51         * @param primitives
    52         */
    53         protected void initToLeg(List<OsmPrimitive> primitives){
    54                 if (primitives == null || primitives.isEmpty()) return;
    55                 if (primitives.size() < 2) return;
    56                 OsmPrimitive p = primitives.get(primitives.size()-1);
    57                 if (! (p instanceof Way)) return;
    58                 Way toLeg = (Way)p;
    59                 if (toLeg.isDeleted() || ! toLeg.isVisible()) return;
    60                 this.to = toLeg;
    61         }
    62        
    63         /**
    64         * Initializes the vias from the two turn restriction legs. The two
    65         * legs have to be defined, otherwise no via is proposed. This methods
    66         * proposes exactly one node as via, if the two turn restriction
    67         * legs intersect at exactly one node.
    68         */
    69         protected void initViaFromLegs(){
    70                 if (from == null || to == null) return;         
    71                 // check whether 'from' and 'to' have exactly one intersecting
    72                 // node. This node is proposed as via node. The turn restriction
    73                 // node will also provide functionality to split either or both
    74                 // of 'from' and 'to' way if they aren't connected from tail to
    75                 // head
    76                 //
    77                 HashSet<Node> nodes = new HashSet<Node>();
    78                 nodes.addAll(from.getNodes());
    79                 nodes.retainAll(to.getNodes());
    80                 if (nodes.size() == 1){
    81                         vias.add(nodes.iterator().next());
    82                 }               
    83         }
    84        
    85         /**
    86         * Initializes the vias with the primitives (1..size-2), provided
    87         * these primitives aren't relations and they are visible and non-deleted.
    88         *
    89         * @param primitives
    90         */
    91         protected void initViasFromPrimitives(List<OsmPrimitive> primitives) {
    92                 if (primitives == null || primitives.size() <=2) return;
    93                 // if we didn't find a from or a to way, we don't propose via objects
    94                 // either
    95                 if (from == null || to == null) return;
    96                 for(int i=1; i< primitives.size() -2;i++){
    97                         OsmPrimitive p = primitives.get(i);
    98                         if (p == null) continue;
    99                         if (p instanceof Relation) continue;
    100                         if (p.isDeleted() || ! p.isVisible()) continue;
    101                         vias.add(p);
    102                 }
    103         }
    104        
    105         /**
    106         * Resets the builder
    107         */
    108         protected void reset() {
    109                 this.from = null;
    110                 this.to = null;
    111                 this.vias.clear();
    112         }
    113        
    114         /**
    115         * Creates and initializes a new turn restriction based on the primitives
    116         * currently selected in layer {@code layer}.
    117        
    118         * @param layer the layer. Must not be null.
    119         * @return the new initialized turn restriction. The turn restriction isn't
    120         * added to the layer yet.
    121         * @throws IllegalArgumentException thrown if layer is null
    122         */
    123         public synchronized Relation buildFromSelection(OsmDataLayer layer) {
    124                 CheckParameterUtil.ensureParameterNotNull(layer, "layer");
    125                 List<OsmPrimitive> selection = new ArrayList<OsmPrimitive>(layer.data.getSelected());
    126                 return build(selection);
    127         }
     46    /**
     47    * Initializes the 'to' leg. Proposes the last element
     48    * in {@code primitives} as 'to' leg if this element is a
     49    * non-deleted, visible way.
     50    *
     51    * @param primitives
     52    */
     53    protected void initToLeg(List<OsmPrimitive> primitives){
     54        if (primitives == null || primitives.isEmpty()) return;
     55        if (primitives.size() < 2) return;
     56        OsmPrimitive p = primitives.get(primitives.size()-1);
     57        if (! (p instanceof Way)) return;
     58        Way toLeg = (Way)p;
     59        if (toLeg.isDeleted() || ! toLeg.isVisible()) return;
     60        this.to = toLeg;
     61    }
     62   
     63    /**
     64    * Initializes the vias from the two turn restriction legs. The two
     65    * legs have to be defined, otherwise no via is proposed. This methods
     66    * proposes exactly one node as via, if the two turn restriction
     67    * legs intersect at exactly one node.
     68    */
     69    protected void initViaFromLegs(){
     70        if (from == null || to == null) return;     
     71        // check whether 'from' and 'to' have exactly one intersecting
     72        // node. This node is proposed as via node. The turn restriction
     73        // node will also provide functionality to split either or both
     74        // of 'from' and 'to' way if they aren't connected from tail to
     75        // head
     76        //
     77        HashSet<Node> nodes = new HashSet<Node>();
     78        nodes.addAll(from.getNodes());
     79        nodes.retainAll(to.getNodes());
     80        if (nodes.size() == 1){
     81            vias.add(nodes.iterator().next());
     82        }       
     83    }
     84   
     85    /**
     86    * Initializes the vias with the primitives (1..size-2), provided
     87    * these primitives aren't relations and they are visible and non-deleted.
     88    *
     89    * @param primitives
     90    */
     91    protected void initViasFromPrimitives(List<OsmPrimitive> primitives) {
     92        if (primitives == null || primitives.size() <=2) return;
     93        // if we didn't find a from or a to way, we don't propose via objects
     94        // either
     95        if (from == null || to == null) return;
     96        for(int i=1; i< primitives.size() -2;i++){
     97            OsmPrimitive p = primitives.get(i);
     98            if (p == null) continue;
     99            if (p instanceof Relation) continue;
     100            if (p.isDeleted() || ! p.isVisible()) continue;
     101            vias.add(p);
     102        }
     103    }
     104   
     105    /**
     106    * Resets the builder
     107    */
     108    protected void reset() {
     109        this.from = null;
     110        this.to = null;
     111        this.vias.clear();
     112    }
     113   
     114    /**
     115    * Creates and initializes a new turn restriction based on the primitives
     116    * currently selected in layer {@code layer}.
     117   
     118    * @param layer the layer. Must not be null.
     119    * @return the new initialized turn restriction. The turn restriction isn't
     120    * added to the layer yet.
     121    * @throws IllegalArgumentException thrown if layer is null
     122    */
     123    public synchronized Relation buildFromSelection(OsmDataLayer layer) {
     124        CheckParameterUtil.ensureParameterNotNull(layer, "layer");
     125        List<OsmPrimitive> selection = new ArrayList<OsmPrimitive>(layer.data.getSelected());
     126        return build(selection);
     127    }
    128128
    129         /**
    130         * Creates and initializes a new turn restriction based on primitives
    131         * in {@code primitives}.
    132         *
    133         * @param primitives the primitives
    134         * @return the new initialized turn restriction. The turn restriction isn't
    135         * added to the layer yet.
    136         */
    137         public synchronized Relation build(List<OsmPrimitive> primitives){
    138                 Relation tr = new Relation();
    139                 tr.put("type", "restriction");
    140                 if (primitives == null || primitives.isEmpty()) return tr;
    141                 if (primitives.size() <=2){
    142                         initFromLeg(primitives);
    143                         initToLeg(primitives);
    144                         initViaFromLegs();
    145                 } else if (primitives.size() > 2) {
    146                         initFromLeg(primitives);
    147                         initToLeg(primitives);
    148                         initViasFromPrimitives(primitives);
    149                 }
    150                
    151                 if (from != null){
    152                         tr.addMember(new RelationMember("from", from));
    153                 }
    154                 if (to != null){
    155                         tr.addMember(new RelationMember("to", to));
    156                 }
    157                 for(OsmPrimitive via: vias){
    158                         tr.addMember(new RelationMember("via", via));
    159                 }
    160                 return tr;
    161         }               
     129    /**
     130    * Creates and initializes a new turn restriction based on primitives
     131    * in {@code primitives}.
     132    *
     133    * @param primitives the primitives
     134    * @return the new initialized turn restriction. The turn restriction isn't
     135    * added to the layer yet.
     136    */
     137    public synchronized Relation build(List<OsmPrimitive> primitives){
     138        Relation tr = new Relation();
     139        tr.put("type", "restriction");
     140        if (primitives == null || primitives.isEmpty()) return tr;
     141        if (primitives.size() <=2){
     142            initFromLeg(primitives);
     143            initToLeg(primitives);
     144            initViaFromLegs();
     145        } else if (primitives.size() > 2) {
     146            initFromLeg(primitives);
     147            initToLeg(primitives);
     148            initViasFromPrimitives(primitives);
     149        }
     150       
     151        if (from != null){
     152            tr.addMember(new RelationMember("from", from));
     153        }
     154        if (to != null){
     155            tr.addMember(new RelationMember("to", to));
     156        }
     157        for(OsmPrimitive via: vias){
     158            tr.addMember(new RelationMember("via", via));
     159        }
     160        return tr;
     161    }       
    162162}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/TurnRestrictionsPlugin.java

    r20701 r23192  
    1313 */
    1414public class TurnRestrictionsPlugin extends Plugin{
    15        
    16         public TurnRestrictionsPlugin(PluginInformation info) {
    17                 super(info);           
    18         }
    19        
    20         /**
    21         * Called when the JOSM map frame is created or destroyed.
    22         */
    23         @Override
    24         public void mapFrameInitialized(MapFrame oldFrame, MapFrame newFrame) {                         
    25                 if (oldFrame == null && newFrame != null) { // map frame added
    26                         TurnRestrictionsListDialog dialog  = new TurnRestrictionsListDialog();
    27                         // add the dialog
    28                         newFrame.addToggleDialog(dialog);
    29                         CreateOrEditTurnRestrictionAction.install();
    30                 }
    31         }
     15   
     16    public TurnRestrictionsPlugin(PluginInformation info) {
     17        super(info);       
     18    }
     19   
     20    /**
     21    * Called when the JOSM map frame is created or destroyed.
     22    */
     23    @Override
     24    public void mapFrameInitialized(MapFrame oldFrame, MapFrame newFrame) {             
     25        if (oldFrame == null && newFrame != null) { // map frame added
     26            TurnRestrictionsListDialog dialog  = new TurnRestrictionsListDialog();
     27            // add the dialog
     28            newFrame.addToggleDialog(dialog);
     29            CreateOrEditTurnRestrictionAction.install();
     30        }
     31    }
    3232
    33         @Override
    34         public PreferenceSetting getPreferenceSetting() {
    35                 return new PreferenceEditor();
    36         }
     33    @Override
     34    public PreferenceSetting getPreferenceSetting() {
     35        return new PreferenceEditor();
     36    }
    3737}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/dnd/PrimitiveIdListProvider.java

    r20489 r23192  
    55import org.openstreetmap.josm.data.osm.PrimitiveId;;
    66public interface PrimitiveIdListProvider {
    7         /**
    8         * Replies the list of currently selected primitive IDs. Replies an empty list if no primitive IDs
    9         * are selected.
    10         *
    11         * @return the list of currently selected primitive IDs
    12         */
    13         List<PrimitiveId> getSelectedPrimitiveIds();
     7    /**
     8    * Replies the list of currently selected primitive IDs. Replies an empty list if no primitive IDs
     9    * are selected.
     10    *
     11    * @return the list of currently selected primitive IDs
     12    */
     13    List<PrimitiveId> getSelectedPrimitiveIds();
    1414}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/dnd/PrimitiveIdListTransferHandler.java

    r20724 r23192  
    2020 */
    2121public class PrimitiveIdListTransferHandler extends TransferHandler {
    22         static private final Logger logger = Logger.getLogger(PrimitiveIdListTransferHandler.class.getName());
    23         private PrimitiveIdListProvider provider;
    24        
    25         /**
    26         * Replies true if {@code transferFlavors} includes the data flavor {@see PrimitiveIdTransferable#PRIMITIVE_ID_LIST_FLAVOR}.
     22    static private final Logger logger = Logger.getLogger(PrimitiveIdListTransferHandler.class.getName());
     23    private PrimitiveIdListProvider provider;
     24   
     25    /**
     26    * Replies true if {@code transferFlavors} includes the data flavor {@see PrimitiveIdTransferable#PRIMITIVE_ID_LIST_FLAVOR}.
    2727
    28         * @param transferFlavors an array of transferFlavors
    29         * @return true if {@code transferFlavors} includes the data flavor {@see PrimitiveIdTransferable#PRIMITIVE_ID_LIST_FLAVOR}.
    30         */
    31         public static boolean isSupportedFlavor(DataFlavor[] transferFlavors) {
    32                 for (DataFlavor df: transferFlavors) {
    33                         if (df.equals(PrimitiveIdTransferable.PRIMITIVE_ID_LIST_FLAVOR)) return true;
    34                 }
    35                 return false;
    36         }
    37        
    38         /**
    39         * Creates the transfer handler
    40         *
    41         * @param provider the provider of the primitive IDs. Must not be null.
    42         * @throws IllegalArgumentException thrown if provider is null.
    43         */
    44         public PrimitiveIdListTransferHandler(PrimitiveIdListProvider provider) throws IllegalArgumentException{
    45                 CheckParameterUtil.ensureParameterNotNull(provider, "provider");
    46                 this.provider = provider;
    47         }
     28    * @param transferFlavors an array of transferFlavors
     29    * @return true if {@code transferFlavors} includes the data flavor {@see PrimitiveIdTransferable#PRIMITIVE_ID_LIST_FLAVOR}.
     30    */
     31    public static boolean isSupportedFlavor(DataFlavor[] transferFlavors) {
     32        for (DataFlavor df: transferFlavors) {
     33            if (df.equals(PrimitiveIdTransferable.PRIMITIVE_ID_LIST_FLAVOR)) return true;
     34        }
     35        return false;
     36    }
     37   
     38    /**
     39    * Creates the transfer handler
     40    *
     41    * @param provider the provider of the primitive IDs. Must not be null.
     42    * @throws IllegalArgumentException thrown if provider is null.
     43    */
     44    public PrimitiveIdListTransferHandler(PrimitiveIdListProvider provider) throws IllegalArgumentException{
     45        CheckParameterUtil.ensureParameterNotNull(provider, "provider");
     46        this.provider = provider;
     47    }
    4848
    49        
    50        
    51         protected Transferable createTransferable(JComponent c) {
    52                 return new PrimitiveIdTransferable(provider.getSelectedPrimitiveIds());                 
    53         }
     49   
     50   
     51    protected Transferable createTransferable(JComponent c) {
     52        return new PrimitiveIdTransferable(provider.getSelectedPrimitiveIds());         
     53    }
    5454
    55         public int getSourceActions(JComponent c) {
    56                 return COPY;
    57         }
     55    public int getSourceActions(JComponent c) {
     56        return COPY;
     57    }
    5858
    59         @Override
    60         public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
    61                 return isSupportedFlavor(transferFlavors);     
    62         }       
     59    @Override
     60    public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
     61        return isSupportedFlavor(transferFlavors); 
     62    }   
    6363}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/dnd/PrimitiveIdTransferable.java

    r20489 r23192  
    1818 */
    1919public class PrimitiveIdTransferable implements Transferable{
    20        
    21         /** the data flower for the set of of primitive ids */
    22         static public final DataFlavor PRIMITIVE_ID_LIST_FLAVOR =
    23                 new DataFlavor(Set.class, "a set of OSM primitive ids");
    24        
    25         /**
    26         * this transferable supports two flavors: (1) {@see #PRIMITIVE_ID_LIST_FLAVOR} and
    27         * (2) {@see DataFlavor#stringFlavor}.
    28         *
    29         * See also {@see #getPrimitiveIds()} and {@see #getAsString()}
    30         */
    31         static public final DataFlavor[] SUPPORTED_FLAVORS = new DataFlavor[] {
    32                 PRIMITIVE_ID_LIST_FLAVOR,
    33                 DataFlavor.stringFlavor
    34         };
     20   
     21    /** the data flower for the set of of primitive ids */
     22    static public final DataFlavor PRIMITIVE_ID_LIST_FLAVOR =
     23        new DataFlavor(Set.class, "a set of OSM primitive ids");
     24   
     25    /**
     26    * this transferable supports two flavors: (1) {@see #PRIMITIVE_ID_LIST_FLAVOR} and
     27    * (2) {@see DataFlavor#stringFlavor}.
     28    *
     29    * See also {@see #getPrimitiveIds()} and {@see #getAsString()}
     30    */
     31    static public final DataFlavor[] SUPPORTED_FLAVORS = new DataFlavor[] {
     32        PRIMITIVE_ID_LIST_FLAVOR,
     33        DataFlavor.stringFlavor
     34    };
    3535
    36        
    37         private List<PrimitiveId> ids = new ArrayList<PrimitiveId>();
    38        
    39         /**
    40         * Creates a transferable from a collection of {@see PrimitiveId}s
    41         *
    42         * @param ids
    43         */
    44         public PrimitiveIdTransferable(List<PrimitiveId> ids) {
    45                 if (ids == null) return;
    46                 for(PrimitiveId id: ids) {
    47                         this.ids.add(new SimplePrimitiveId(id.getUniqueId(), id.getType()));
    48                 }
    49         }
    50        
    51         /**
    52         * If flavor is {@see #PRIMITIVE_ID_SET_FLAVOR}, replies a the list of
    53         * transferred {@see PrimitiveId}s
    54         *
    55         * If flavor is {@see DataFlavor#stringFlavor}, replies a string representation
    56         * of the list of transferred {@see PrimitiveId}s
    57         */
    58         public Object getTransferData(DataFlavor flavor)
    59                         throws UnsupportedFlavorException, IOException {
    60                 if (PRIMITIVE_ID_LIST_FLAVOR.equals(flavor)) {
    61                         return getPrimitiveIds();
    62                 } else if (DataFlavor.stringFlavor.equals(flavor)) {
    63                         return getAsString();
    64                 }
    65                 throw new UnsupportedFlavorException(flavor);
    66         }
    67        
    68         /**
    69         * Replies the list of OSM primitive ids
    70         *
    71         * @return the list of OSM primitive ids
    72         */
    73         public List<PrimitiveId> getPrimitiveIds() {
    74                 return ids;
    75         }
    76        
    77         /**
    78         * Replies a string representation of the list of OSM primitive ids
    79        
    80         * @return a string representation of the list of OSM primitive ids
    81         */
    82         public String getAsString() {
    83                 StringBuffer sb = new StringBuffer();
    84                 for(PrimitiveId id: ids) {
    85                         if (sb.length() > 0) sb.append(",");
    86                         sb.append(id.getType().getAPIName()).append("/").append(id.getUniqueId());
    87                 }
    88                 return sb.toString();
    89         }
     36   
     37    private List<PrimitiveId> ids = new ArrayList<PrimitiveId>();
     38   
     39    /**
     40    * Creates a transferable from a collection of {@see PrimitiveId}s
     41    *
     42    * @param ids
     43    */
     44    public PrimitiveIdTransferable(List<PrimitiveId> ids) {
     45        if (ids == null) return;
     46        for(PrimitiveId id: ids) {
     47            this.ids.add(new SimplePrimitiveId(id.getUniqueId(), id.getType()));
     48        }
     49    }
     50   
     51    /**
     52    * If flavor is {@see #PRIMITIVE_ID_SET_FLAVOR}, replies a the list of
     53    * transferred {@see PrimitiveId}s
     54    *
     55    * If flavor is {@see DataFlavor#stringFlavor}, replies a string representation
     56    * of the list of transferred {@see PrimitiveId}s
     57    */
     58    public Object getTransferData(DataFlavor flavor)
     59            throws UnsupportedFlavorException, IOException {
     60        if (PRIMITIVE_ID_LIST_FLAVOR.equals(flavor)) {
     61            return getPrimitiveIds();
     62        } else if (DataFlavor.stringFlavor.equals(flavor)) {
     63            return getAsString();
     64        }
     65        throw new UnsupportedFlavorException(flavor);
     66    }
     67   
     68    /**
     69    * Replies the list of OSM primitive ids
     70    *
     71    * @return the list of OSM primitive ids
     72    */
     73    public List<PrimitiveId> getPrimitiveIds() {
     74        return ids;
     75    }
     76   
     77    /**
     78    * Replies a string representation of the list of OSM primitive ids
     79   
     80    * @return a string representation of the list of OSM primitive ids
     81    */
     82    public String getAsString() {
     83        StringBuffer sb = new StringBuffer();
     84        for(PrimitiveId id: ids) {
     85            if (sb.length() > 0) sb.append(",");
     86            sb.append(id.getType().getAPIName()).append("/").append(id.getUniqueId());
     87        }
     88        return sb.toString();
     89    }
    9090
    91         public DataFlavor[] getTransferDataFlavors() {
    92                 return SUPPORTED_FLAVORS;
    93         }
     91    public DataFlavor[] getTransferDataFlavors() {
     92        return SUPPORTED_FLAVORS;
     93    }
    9494
    95         public boolean isDataFlavorSupported(DataFlavor flavor) {
    96                 for(DataFlavor df: SUPPORTED_FLAVORS) {
    97                         if (df.equals(flavor)) return true;
    98                 }
    99                 return false;
    100         }                       
     95    public boolean isDataFlavorSupported(DataFlavor flavor) {
     96        for(DataFlavor df: SUPPORTED_FLAVORS) {
     97            if (df.equals(flavor)) return true;
     98        }
     99        return false;
     100    }           
    101101}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/AdvancedEditorPanel.java

    r20735 r23192  
    2323 */
    2424public class AdvancedEditorPanel extends JPanel {
    25         private static final Logger logger = Logger.getLogger(AdvancedEditorPanel.class.getName());
     25    private static final Logger logger = Logger.getLogger(AdvancedEditorPanel.class.getName());
    2626
    27         private TurnRestrictionEditorModel model;
    28         private TagEditorPanel pnlTagEditor;
    29         private JPanel pnlRelationMemberEditor;
    30         private JTable tblRelationMemberEditor;
    31         private JSplitPane spEditors;
    32        
    33         /**
    34         * Creates the panel with the tag editor
    35         *
    36         * @return
    37         */
    38         protected JPanel buildTagEditorPanel() {
    39                 JPanel pnl = new JPanel(new BorderLayout());
    40                 HtmlPanel msg = new HtmlPanel();
    41                 msg.setText("<html><body>" +
    42                                 tr("In the following table you can edit the <strong>raw tags</strong>"
    43                           + " of the OSM relation representing this turn restriction.")
    44                           + "</body></html>"
    45                 );
    46                 pnl.add(msg, BorderLayout.NORTH);
    47                 pnlTagEditor = new TagEditorPanel(model.getTagEditorModel());   
    48                 pnlTagEditor.initAutoCompletion(model.getLayer());
    49                 pnl.add(pnlTagEditor, BorderLayout.CENTER);
    50                 return pnl;
    51         }
    52        
    53         /**
    54         * Builds the panel with the table for editing relation members
    55         *
    56         * @return
    57         */
    58         protected JPanel buildMemberEditorPanel() {
    59                 JPanel pnl = new JPanel(new BorderLayout());
    60                 HtmlPanel msg = new HtmlPanel();
    61                 msg.setText("<html><body>" 
    62                           + tr("In the following table you can edit the <strong>raw members</strong>"
    63                           + " of the OSM relation representing this turn restriction.") + "</body></html>"
    64                 );
    65                 pnl.add(msg, BorderLayout.NORTH);
    66                
    67                 tblRelationMemberEditor = new RelationMemberTable(model);
    68                 JScrollPane pane = new JScrollPane(tblRelationMemberEditor);
    69                 pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
    70                 pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    71                 pnl.add(pane);
    72                 return pnl;
    73         }
    74        
    75         /**
    76         * Creates the main split panel
    77         * @return
    78         */
    79         protected JSplitPane buildSplitPane() {
    80                 spEditors = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
    81                 spEditors.setTopComponent(buildTagEditorPanel());
    82                 spEditors.setBottomComponent(buildMemberEditorPanel());
    83                 spEditors.setOneTouchExpandable(false);
    84                 spEditors.setDividerSize(5);
    85                 spEditors.addHierarchyListener(new SplitPaneDividerInitializer());
    86                 return spEditors;
    87         }
    88        
    89         /**
    90         * Builds the user interface
    91         */
    92         protected void build() {
    93                 setLayout(new BorderLayout());
    94                 add(buildSplitPane(), BorderLayout.CENTER);
    95         }
    96        
    97         /**
    98         * Creates the advanced editor
    99         *
    100         * @param model the editor model. Must not be null.
    101         * @throws IllegalArgumentException thrown if model is null
    102         */
    103         public AdvancedEditorPanel(TurnRestrictionEditorModel model) throws IllegalArgumentException{
    104                 CheckParameterUtil.ensureParameterNotNull(model, "model");
    105                 this.model = model;
    106                 build();
    107                 HelpUtil.setHelpContext(this, HelpUtil.ht("/Plugins/turnrestrictions#AdvancedEditor"));
    108         }
    109        
    110         /**
    111         * Initializes the divider location when the components becomes visible the
    112         * first time
    113         */
    114         class SplitPaneDividerInitializer implements HierarchyListener {
    115                 public void hierarchyChanged(HierarchyEvent e) {
    116                         if (isShowing()) {
    117                                 spEditors.setDividerLocation(0.5);
    118                                 spEditors.removeHierarchyListener(this);
    119                         }                       
    120                 }               
    121         }
     27    private TurnRestrictionEditorModel model;
     28    private TagEditorPanel pnlTagEditor;
     29    private JPanel pnlRelationMemberEditor;
     30    private JTable tblRelationMemberEditor;
     31    private JSplitPane spEditors;
     32   
     33    /**
     34    * Creates the panel with the tag editor
     35    *
     36    * @return
     37    */
     38    protected JPanel buildTagEditorPanel() {
     39        JPanel pnl = new JPanel(new BorderLayout());
     40        HtmlPanel msg = new HtmlPanel();
     41        msg.setText("<html><body>" +
     42                tr("In the following table you can edit the <strong>raw tags</strong>"
     43              + " of the OSM relation representing this turn restriction.")
     44              + "</body></html>"
     45        );
     46        pnl.add(msg, BorderLayout.NORTH);
     47        pnlTagEditor = new TagEditorPanel(model.getTagEditorModel());   
     48        pnlTagEditor.initAutoCompletion(model.getLayer());
     49        pnl.add(pnlTagEditor, BorderLayout.CENTER);
     50        return pnl;
     51    }
     52   
     53    /**
     54    * Builds the panel with the table for editing relation members
     55    *
     56    * @return
     57    */
     58    protected JPanel buildMemberEditorPanel() {
     59        JPanel pnl = new JPanel(new BorderLayout());
     60        HtmlPanel msg = new HtmlPanel();
     61        msg.setText("<html><body>" 
     62              + tr("In the following table you can edit the <strong>raw members</strong>"
     63              + " of the OSM relation representing this turn restriction.") + "</body></html>"
     64        );
     65        pnl.add(msg, BorderLayout.NORTH);
     66       
     67        tblRelationMemberEditor = new RelationMemberTable(model);
     68        JScrollPane pane = new JScrollPane(tblRelationMemberEditor);
     69        pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
     70        pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
     71        pnl.add(pane);
     72        return pnl;
     73    }
     74   
     75    /**
     76    * Creates the main split panel
     77    * @return
     78    */
     79    protected JSplitPane buildSplitPane() {
     80        spEditors = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
     81        spEditors.setTopComponent(buildTagEditorPanel());
     82        spEditors.setBottomComponent(buildMemberEditorPanel());
     83        spEditors.setOneTouchExpandable(false);
     84        spEditors.setDividerSize(5);
     85        spEditors.addHierarchyListener(new SplitPaneDividerInitializer());
     86        return spEditors;
     87    }
     88   
     89    /**
     90    * Builds the user interface
     91    */
     92    protected void build() {
     93        setLayout(new BorderLayout());
     94        add(buildSplitPane(), BorderLayout.CENTER);
     95    }
     96   
     97    /**
     98    * Creates the advanced editor
     99    *
     100    * @param model the editor model. Must not be null.
     101    * @throws IllegalArgumentException thrown if model is null
     102    */
     103    public AdvancedEditorPanel(TurnRestrictionEditorModel model) throws IllegalArgumentException{
     104        CheckParameterUtil.ensureParameterNotNull(model, "model");
     105        this.model = model;
     106        build();
     107        HelpUtil.setHelpContext(this, HelpUtil.ht("/Plugins/turnrestrictions#AdvancedEditor"));
     108    }
     109   
     110    /**
     111    * Initializes the divider location when the components becomes visible the
     112    * first time
     113    */
     114    class SplitPaneDividerInitializer implements HierarchyListener {
     115        public void hierarchyChanged(HierarchyEvent e) {
     116            if (isShowing()) {
     117                spEditors.setDividerLocation(0.5);
     118                spEditors.removeHierarchyListener(this);
     119            }           
     120        }       
     121    }
    122122}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/BasicEditorPanel.java

    r20917 r23192  
    2828public class BasicEditorPanel extends VerticallyScrollablePanel {
    2929
    30         /** the turn restriction model */
    31         private TurnRestrictionEditorModel model;
    32        
    33         /** the UI widgets */
    34         private TurnRestrictionLegEditor fromEditor;
    35         private TurnRestrictionLegEditor toEditor;
    36         private ViaList lstVias;
    37         private JLabel lblVias;
    38         private JScrollPane spVias;
    39         private TurnRestrictionComboBox cbTurnRestrictions;
    40         private VehicleExceptionEditor vehicleExceptionsEditor;
    41        
    42         /**
    43         * builds the UI
    44         */
    45         protected void build() {
    46                 setLayout(new GridBagLayout());
    47                 GridBagConstraints gc = new GridBagConstraints();
    48                 gc.anchor = GridBagConstraints.WEST;
    49                 gc.fill = GridBagConstraints.HORIZONTAL;
    50                 gc.weightx = 0.0;
    51                
    52                 // the editor for selecting the 'from' leg
    53             gc.insets = new Insets(0,0,5,5);   
    54             add(new JLabel(tr("Type:")), gc);
    55            
    56             gc.gridx = 1;
    57             gc.weightx = 1.0;
    58             add(cbTurnRestrictions = new TurnRestrictionComboBox(new TurnRestrictionComboBoxModel(model)), gc);
     30    /** the turn restriction model */
     31    private TurnRestrictionEditorModel model;
     32   
     33    /** the UI widgets */
     34    private TurnRestrictionLegEditor fromEditor;
     35    private TurnRestrictionLegEditor toEditor;
     36    private ViaList lstVias;
     37    private JLabel lblVias;
     38    private JScrollPane spVias;
     39    private TurnRestrictionComboBox cbTurnRestrictions;
     40    private VehicleExceptionEditor vehicleExceptionsEditor;
     41   
     42    /**
     43    * builds the UI
     44    */
     45    protected void build() {
     46        setLayout(new GridBagLayout());
     47        GridBagConstraints gc = new GridBagConstraints();
     48        gc.anchor = GridBagConstraints.WEST;
     49        gc.fill = GridBagConstraints.HORIZONTAL;
     50        gc.weightx = 0.0;
     51       
     52        // the editor for selecting the 'from' leg
     53        gc.insets = new Insets(0,0,5,5);   
     54        add(new JLabel(tr("Type:")), gc);
     55       
     56        gc.gridx = 1;
     57        gc.weightx = 1.0;
     58        add(cbTurnRestrictions = new TurnRestrictionComboBox(new TurnRestrictionComboBoxModel(model)), gc);
    5959
    60                 // the editor for selecting the 'from' leg
    61             gc.gridx = 0;
    62             gc.gridy = 1;       
    63             gc.weightx = 0.0;
    64             add(new JLabel(tr("From:")), gc);
    65            
    66             gc.gridx = 1;
    67             gc.weightx = 1.0;
    68             add(fromEditor = new TurnRestrictionLegEditor(model, TurnRestrictionLegRole.FROM),gc);
     60        // the editor for selecting the 'from' leg
     61        gc.gridx = 0;
     62        gc.gridy = 1;   
     63        gc.weightx = 0.0;
     64        add(new JLabel(tr("From:")), gc);
     65       
     66        gc.gridx = 1;
     67        gc.weightx = 1.0;
     68        add(fromEditor = new TurnRestrictionLegEditor(model, TurnRestrictionLegRole.FROM),gc);
    6969
    70             // the editor for selecting the 'to' leg
    71             gc.gridx = 0;
    72             gc.gridy = 2;
    73                 gc.weightx = 0.0;
    74             gc.insets = new Insets(0,0,5,5);   
    75             add(new JLabel(tr("To:")), gc);
    76            
    77             gc.gridx = 1;
    78             gc.weightx = 1.0;
    79             add(toEditor = new TurnRestrictionLegEditor(model, TurnRestrictionLegRole.TO),gc);
    80            
    81             // the editor for selecting the 'vias'
    82             gc.gridx = 0;
    83             gc.gridy = 3;
    84                 gc.weightx = 0.0;
    85             gc.insets = new Insets(0,0,5,5);   
    86             add(lblVias = new JLabel(tr("Vias:")), gc);
    87            
    88             gc.gridx = 1;
    89             gc.weightx = 1.0;
    90             DefaultListSelectionModel selectionModel = new DefaultListSelectionModel();
    91             add(spVias = new JScrollPane(lstVias = new ViaList(new ViaListModel(model, selectionModel), selectionModel)),gc);
    92             if (!Main.pref.getBoolean(PreferenceKeys.SHOW_VIAS_IN_BASIC_EDITOR, false)) {
    93                 lblVias.setVisible(false);
    94                 spVias.setVisible(false);
    95             }
    96            
    97             // the editor for vehicle exceptions
    98             vehicleExceptionsEditor = new VehicleExceptionEditor(model);
    99             gc.gridx = 0;
    100             gc.gridy = 4;
    101                 gc.weightx = 1.0;
    102                 gc.gridwidth = 2;
    103             gc.insets = new Insets(0,0,5,5);   
    104             add(vehicleExceptionsEditor, gc);
    105            
    106             // just a filler - grabs remaining space
    107             gc.gridx = 0;
    108             gc.gridy = 5;
    109             gc.gridwidth = 2;
    110             gc.weighty = 1.0;
    111             gc.fill = GridBagConstraints.BOTH;
    112             add(new JPanel(), gc);
    113                    
    114             setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
    115         }
    116        
    117        
    118         /**
    119         * Creates the panel.
    120         *
    121         * @param model the editor model. Must not be null.
    122         * @throws IllegalArgumentException thrown if model is null
    123         */
    124         public BasicEditorPanel(TurnRestrictionEditorModel model) {
    125                 CheckParameterUtil.ensureParameterNotNull(model, "model");
    126                 this.model = model;
    127                 build();
    128                 HelpUtil.setHelpContext(this, HelpUtil.ht("/Plugins/turnrestrictions#BasicEditor"));
    129         }
    130        
    131         /**
    132         * Requests the focus on one of the input widgets for turn
    133         * restriction data.
    134         *
    135         * @param focusTarget the target component to request focus for.
    136         * Ignored if null.
    137         */
    138         public void requestFocusFor(BasicEditorFokusTargets focusTarget){
    139                 if (focusTarget == null) return;
    140                 switch(focusTarget){
    141                 case RESTRICION_TYPE:
    142                         cbTurnRestrictions.requestFocusInWindow();
    143                         break;
    144                 case FROM:
    145                         fromEditor.requestFocusInWindow();
    146                         break;
    147                 case TO:
    148                         toEditor.requestFocusInWindow();
    149                         break;
    150                 case VIA:
    151                         lstVias.requestFocusInWindow();
    152                         break;
    153                 }
    154         }       
    155        
    156         /**
    157         * Initializes the set of icons used from the preference key
    158         * {@see PreferenceKeys#ROAD_SIGNS}.
    159         *
    160         * @param prefs the JOSM preferences
    161         */
    162         public void initIconSetFromPreferences(Preferences prefs){             
    163                 cbTurnRestrictions.initIconSetFromPreferences(prefs);
    164         }
    165        
    166         /**
    167         * Initializes the visibility of the list of via-objects depending
    168         * on values in the JOSM preferences
    169         *
    170         * @param prefs the JOSM preferences
    171         */
    172         public void initViasVisibilityFromPreferences(Preferences prefs){
    173                 boolean value = prefs.getBoolean(PreferenceKeys.SHOW_VIAS_IN_BASIC_EDITOR, false);
    174                 if (value != lblVias.isVisible()){
    175                         lblVias.setVisible(value);
    176                         spVias.setVisible(value);
    177                 }
    178         }
     70        // the editor for selecting the 'to' leg
     71        gc.gridx = 0;
     72        gc.gridy = 2;
     73        gc.weightx = 0.0;
     74        gc.insets = new Insets(0,0,5,5);   
     75        add(new JLabel(tr("To:")), gc);
     76       
     77        gc.gridx = 1;
     78        gc.weightx = 1.0;
     79        add(toEditor = new TurnRestrictionLegEditor(model, TurnRestrictionLegRole.TO),gc);
     80       
     81        // the editor for selecting the 'vias'
     82        gc.gridx = 0;
     83        gc.gridy = 3;
     84        gc.weightx = 0.0;
     85        gc.insets = new Insets(0,0,5,5);   
     86        add(lblVias = new JLabel(tr("Vias:")), gc);
     87       
     88        gc.gridx = 1;
     89        gc.weightx = 1.0;
     90        DefaultListSelectionModel selectionModel = new DefaultListSelectionModel();
     91        add(spVias = new JScrollPane(lstVias = new ViaList(new ViaListModel(model, selectionModel), selectionModel)),gc);
     92        if (!Main.pref.getBoolean(PreferenceKeys.SHOW_VIAS_IN_BASIC_EDITOR, false)) {
     93            lblVias.setVisible(false);
     94            spVias.setVisible(false);
     95        }
     96       
     97        // the editor for vehicle exceptions
     98        vehicleExceptionsEditor = new VehicleExceptionEditor(model);
     99        gc.gridx = 0;
     100        gc.gridy = 4;
     101        gc.weightx = 1.0;
     102        gc.gridwidth = 2;
     103        gc.insets = new Insets(0,0,5,5);   
     104        add(vehicleExceptionsEditor, gc);
     105       
     106        // just a filler - grabs remaining space
     107        gc.gridx = 0;
     108        gc.gridy = 5;
     109        gc.gridwidth = 2;
     110        gc.weighty = 1.0;
     111        gc.fill = GridBagConstraints.BOTH;
     112        add(new JPanel(), gc);
     113           
     114        setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
     115    }
     116   
     117   
     118    /**
     119    * Creates the panel.
     120    *
     121    * @param model the editor model. Must not be null.
     122    * @throws IllegalArgumentException thrown if model is null
     123    */
     124    public BasicEditorPanel(TurnRestrictionEditorModel model) {
     125        CheckParameterUtil.ensureParameterNotNull(model, "model");
     126        this.model = model;
     127        build();
     128        HelpUtil.setHelpContext(this, HelpUtil.ht("/Plugins/turnrestrictions#BasicEditor"));
     129    }
     130   
     131    /**
     132    * Requests the focus on one of the input widgets for turn
     133    * restriction data.
     134    *
     135    * @param focusTarget the target component to request focus for.
     136    * Ignored if null.
     137    */
     138    public void requestFocusFor(BasicEditorFokusTargets focusTarget){
     139        if (focusTarget == null) return;
     140        switch(focusTarget){
     141        case RESTRICION_TYPE:
     142            cbTurnRestrictions.requestFocusInWindow();
     143            break;
     144        case FROM:
     145            fromEditor.requestFocusInWindow();
     146            break;
     147        case TO:
     148            toEditor.requestFocusInWindow();
     149            break;
     150        case VIA:
     151            lstVias.requestFocusInWindow();
     152            break;
     153        }
     154    }   
     155   
     156    /**
     157    * Initializes the set of icons used from the preference key
     158    * {@see PreferenceKeys#ROAD_SIGNS}.
     159    *
     160    * @param prefs the JOSM preferences
     161    */
     162    public void initIconSetFromPreferences(Preferences prefs){     
     163        cbTurnRestrictions.initIconSetFromPreferences(prefs);
     164    }
     165   
     166    /**
     167    * Initializes the visibility of the list of via-objects depending
     168    * on values in the JOSM preferences
     169    *
     170    * @param prefs the JOSM preferences
     171    */
     172    public void initViasVisibilityFromPreferences(Preferences prefs){
     173        boolean value = prefs.getBoolean(PreferenceKeys.SHOW_VIAS_IN_BASIC_EDITOR, false);
     174        if (value != lblVias.isVisible()){
     175            lblVias.setVisible(value);
     176            spVias.setVisible(value);
     177        }
     178    }
    179179}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/ExceptValueModel.java

    r20586 r23192  
    1414 */
    1515public class ExceptValueModel {
    16         /**
    17         * The set of standard vehicle types which can be used in the
    18         * 'except' tag
    19         */
    20         static public final Set<String> STANDARD_VEHICLE_EXCEPTION_VALUES;
    21         static {
    22                 HashSet<String> s = new HashSet<String>();
    23                 s.add("psv");
    24                 s.add("hgv");
    25                 s.add("bicycle");
    26                 s.add("motorcar");
    27                 STANDARD_VEHICLE_EXCEPTION_VALUES = Collections.unmodifiableSet(s);
    28         }
    29        
    30         /**
    31         * Replies true, if {@code v} is a standard vehicle type. Replies
    32         * false if {@code v} is null
    33         *
    34         * @param v the vehicle type.
    35         * @return true, if {@code v} is a standard vehicle type.
    36         */
    37         static public boolean isStandardVehicleExceptionValue(String v){
    38                 if (v == null) return false;
    39                 v = v.trim().toLowerCase();
    40                 return STANDARD_VEHICLE_EXCEPTION_VALUES.contains(v);
    41         }
    42                
    43         private String value = "";
    44         private boolean isStandard = true;
    45         private final Set<String> vehicleExceptions = new HashSet<String>();
    46        
    47        
    48         protected void parseValue(String value) {
    49                 if (value == null || value.trim().equals("")) value = "";
    50                 this.value = value;
    51                 isStandard = true;
    52                 vehicleExceptions.clear();
    53                 if (value.equals("")) return;
    54                 String[] values = value.split(";");
    55                 for (String v: values){
    56                         v = v.trim().toLowerCase();
    57                         if (isStandardVehicleExceptionValue(v)) {
    58                                 vehicleExceptions.add(v);
    59                         } else {
    60                                 isStandard = false;
    61                         }
    62                 }
    63         }
    64        
    65         /**
    66         * Creates a new model for an empty standard value
    67         */
    68         public ExceptValueModel() {}
    69        
    70         /**
    71         * Creates a new model for the tag value {@code value}.
    72         *
    73         * @param value the tag value
    74         * @see #parseValue(String)
    75         */
    76         public ExceptValueModel(String value){
    77                 if (value == null || value.trim().equals(""))
    78                         return;
    79                 parseValue(value);
    80         }
    81 
    82         /**
    83         * Replies the tag value representing the state of this model.
    84         *
    85         * @return
    86         */
    87         public String getValue() {
    88                 if (isStandard){
    89                         StringBuffer sb = new StringBuffer();
    90                         // we use an ordered list because equals()
    91                         // is based on getValue()
    92                         //
    93                         List<String> values = new ArrayList<String>(vehicleExceptions);
    94                         Collections.sort(values);
    95                         for (String v: values){
    96                                 if (sb.length() > 0) {
    97                                         sb.append(";");
    98                                 }
    99                                 sb.append(v);
    100                         }
    101                         return sb.toString();
    102                 } else {
    103                         return value;
    104                 }
    105         }
    106 
    107         /**
    108         * Sets the value in this model
    109         *
    110         * @param value
    111         */
    112         public void setValue(String value) {
    113                 parseValue(value);
    114         }
    115 
    116         /**
    117         * Replies true if this model currently holds a standard 'except' value
    118         *
    119         * @return
    120         */
    121         public boolean isStandard() {
    122                 return isStandard;
    123         }       
    124        
    125         /**
    126         * Tells this model to use standard values only.
    127         *
    128         */
    129         public void setStandard(boolean isStandard) {
    130                 this.isStandard = isStandard;
    131         }
    132        
    133         /**
    134         * Replies true if {@code vehicleType} is currently set as exception in this
    135         * model.
    136         *
    137         * @param vehicleType one of the standard vehicle types from {@see #STANDARD_VEHICLE_EXCEPTION_VALUES}
    138         * @return true if {@code vehicleType} is currently set as exception in this
    139         * model.
    140         * @exception IllegalArgumentException thrown if {@code vehicleType} isn't a standard vehicle type
    141         */
    142         public boolean isVehicleException(String vehicleType) throws IllegalArgumentException{
    143                 if (vehicleType == null) return false;
    144                 if (!isStandardVehicleExceptionValue(vehicleType)) {
    145                         throw new IllegalArgumentException(MessageFormat.format("vehicleType ''{0}'' isn''t a valid standard vehicle type", vehicleType));
    146                 }
    147                 vehicleType = vehicleType.trim().toLowerCase();
    148                 return vehicleExceptions.contains(vehicleType);
    149         }
    150        
    151         /**
    152         * Sets the {@code vehicleType} as exception in this turn restriction.
    153         *
    154         * @param vehicleType one of the standard vehicle types from {@see #STANDARD_VEHICLE_EXCEPTION_VALUES}
    155         * @exception IllegalArgumentException thrown if {@code vehicleType} isn't a standard vehicle type
    156         */
    157         public void setVehicleException(String vehicleType) throws IllegalArgumentException{
    158                 if (!isStandardVehicleExceptionValue(vehicleType)) {
    159                         throw new IllegalArgumentException(MessageFormat.format("vehicleType ''{0}'' isn''t a valid standard vehicle type", vehicleType));
    160                 }
    161                 vehicleExceptions.add(vehicleType.trim().toLowerCase());
    162         }
    163        
    164 
    165         /**
    166         * Sets or removes the {@code vehicleType} as exception in this turn restriction, depending
    167         * on whether {@code setOrRemove} is true or false, respectively.
    168         *
    169         * @param vehicleType one of the standard vehicle types from {@see #STANDARD_VEHICLE_EXCEPTION_VALUES}
    170         * @param setOrRemove if true, the exception is set; otherwise, it is removed
    171         * @exception IllegalArgumentException thrown if {@code vehicleType} isn't a standard vehicle type
    172         */
    173         public void setVehicleException(String vehicleType, boolean setOrRemove) throws IllegalArgumentException{
    174                 if (setOrRemove){
    175                         setVehicleException(vehicleType);
    176                 } else {
    177                         removeVehicleException(vehicleType);
    178                 }
    179         }
    180        
    181         /**
    182         * Removes the {@code vehicleType} as exception in this turn restriction
    183         *
    184         * @param vehicleType one of the standard vehicle types from {@see #STANDARD_VEHICLE_EXCEPTION_VALUES}
    185         * @exception IllegalArgumentException thrown if {@code vehicleType} isn't a standard vehicle type
    186         */
    187         public void removeVehicleException(String vehicleType) throws IllegalArgumentException{
    188                 if (!isStandardVehicleExceptionValue(vehicleType)) {
    189                         throw new IllegalArgumentException(MessageFormat.format("vehicleType ''{0}'' isn''t a valid standard vehicle type", vehicleType));
    190                 }
    191                 vehicleExceptions.remove(vehicleType.trim().toLowerCase());
    192         }
    193 
    194         @Override
    195         public int hashCode() {
    196                 final int prime = 31;
    197                 int result = 1;
    198                 result = prime * result + getValue().hashCode();
    199                 return result;
    200         }
    201 
    202         @Override
    203         public boolean equals(Object obj) {
    204                 if (this == obj)
    205                         return true;
    206                 if (obj == null)
    207                         return false;
    208                 if (getClass() != obj.getClass())
    209                         return false;
    210                 ExceptValueModel other = (ExceptValueModel) obj;
    211                 return getValue().equals(other.getValue());
    212         }               
     16    /**
     17    * The set of standard vehicle types which can be used in the
     18    * 'except' tag
     19    */
     20    static public final Set<String> STANDARD_VEHICLE_EXCEPTION_VALUES;
     21    static {
     22        HashSet<String> s = new HashSet<String>();
     23        s.add("psv");
     24        s.add("hgv");
     25        s.add("bicycle");
     26        s.add("motorcar");
     27        STANDARD_VEHICLE_EXCEPTION_VALUES = Collections.unmodifiableSet(s);
     28    }
     29   
     30    /**
     31    * Replies true, if {@code v} is a standard vehicle type. Replies
     32    * false if {@code v} is null
     33    *
     34    * @param v the vehicle type.
     35    * @return true, if {@code v} is a standard vehicle type.
     36    */
     37    static public boolean isStandardVehicleExceptionValue(String v){
     38        if (v == null) return false;
     39        v = v.trim().toLowerCase();
     40        return STANDARD_VEHICLE_EXCEPTION_VALUES.contains(v);
     41    }
     42       
     43    private String value = "";
     44    private boolean isStandard = true;
     45    private final Set<String> vehicleExceptions = new HashSet<String>();
     46   
     47   
     48    protected void parseValue(String value) {
     49        if (value == null || value.trim().equals("")) value = "";
     50        this.value = value;
     51        isStandard = true;
     52        vehicleExceptions.clear();
     53        if (value.equals("")) return;
     54        String[] values = value.split(";");
     55        for (String v: values){
     56            v = v.trim().toLowerCase();
     57            if (isStandardVehicleExceptionValue(v)) {
     58                vehicleExceptions.add(v);
     59            } else {
     60                isStandard = false;
     61            }
     62        }
     63    }
     64   
     65    /**
     66    * Creates a new model for an empty standard value
     67    */
     68    public ExceptValueModel() {}
     69   
     70    /**
     71    * Creates a new model for the tag value {@code value}.
     72    *
     73    * @param value the tag value
     74    * @see #parseValue(String)
     75    */
     76    public ExceptValueModel(String value){
     77        if (value == null || value.trim().equals(""))
     78            return;
     79        parseValue(value);
     80    }
     81
     82    /**
     83    * Replies the tag value representing the state of this model.
     84    *
     85    * @return
     86    */
     87    public String getValue() {
     88        if (isStandard){
     89            StringBuffer sb = new StringBuffer();
     90            // we use an ordered list because equals()
     91            // is based on getValue()
     92            //
     93            List<String> values = new ArrayList<String>(vehicleExceptions);
     94            Collections.sort(values);
     95            for (String v: values){
     96                if (sb.length() > 0) {
     97                    sb.append(";");
     98                }
     99                sb.append(v);
     100            }
     101            return sb.toString();
     102        } else {
     103            return value;
     104        }
     105    }
     106
     107    /**
     108    * Sets the value in this model
     109    *
     110    * @param value
     111    */
     112    public void setValue(String value) {
     113        parseValue(value);
     114    }
     115
     116    /**
     117    * Replies true if this model currently holds a standard 'except' value
     118    *
     119    * @return
     120    */
     121    public boolean isStandard() {
     122        return isStandard;
     123    }   
     124   
     125    /**
     126    * Tells this model to use standard values only.
     127    *
     128    */
     129    public void setStandard(boolean isStandard) {
     130        this.isStandard = isStandard;
     131    }
     132   
     133    /**
     134    * Replies true if {@code vehicleType} is currently set as exception in this
     135    * model.
     136    *
     137    * @param vehicleType one of the standard vehicle types from {@see #STANDARD_VEHICLE_EXCEPTION_VALUES}
     138    * @return true if {@code vehicleType} is currently set as exception in this
     139    * model.
     140    * @exception IllegalArgumentException thrown if {@code vehicleType} isn't a standard vehicle type
     141    */
     142    public boolean isVehicleException(String vehicleType) throws IllegalArgumentException{
     143        if (vehicleType == null) return false;
     144        if (!isStandardVehicleExceptionValue(vehicleType)) {
     145            throw new IllegalArgumentException(MessageFormat.format("vehicleType ''{0}'' isn''t a valid standard vehicle type", vehicleType));
     146        }
     147        vehicleType = vehicleType.trim().toLowerCase();
     148        return vehicleExceptions.contains(vehicleType);
     149    }
     150   
     151    /**
     152    * Sets the {@code vehicleType} as exception in this turn restriction.
     153    *
     154    * @param vehicleType one of the standard vehicle types from {@see #STANDARD_VEHICLE_EXCEPTION_VALUES}
     155    * @exception IllegalArgumentException thrown if {@code vehicleType} isn't a standard vehicle type
     156    */
     157    public void setVehicleException(String vehicleType) throws IllegalArgumentException{
     158        if (!isStandardVehicleExceptionValue(vehicleType)) {
     159            throw new IllegalArgumentException(MessageFormat.format("vehicleType ''{0}'' isn''t a valid standard vehicle type", vehicleType));
     160        }
     161        vehicleExceptions.add(vehicleType.trim().toLowerCase());
     162    }
     163   
     164
     165    /**
     166    * Sets or removes the {@code vehicleType} as exception in this turn restriction, depending
     167    * on whether {@code setOrRemove} is true or false, respectively.
     168    *
     169    * @param vehicleType one of the standard vehicle types from {@see #STANDARD_VEHICLE_EXCEPTION_VALUES}
     170    * @param setOrRemove if true, the exception is set; otherwise, it is removed
     171    * @exception IllegalArgumentException thrown if {@code vehicleType} isn't a standard vehicle type
     172    */
     173    public void setVehicleException(String vehicleType, boolean setOrRemove) throws IllegalArgumentException{
     174        if (setOrRemove){
     175            setVehicleException(vehicleType);
     176        } else {
     177            removeVehicleException(vehicleType);
     178        }
     179    }
     180   
     181    /**
     182    * Removes the {@code vehicleType} as exception in this turn restriction
     183    *
     184    * @param vehicleType one of the standard vehicle types from {@see #STANDARD_VEHICLE_EXCEPTION_VALUES}
     185    * @exception IllegalArgumentException thrown if {@code vehicleType} isn't a standard vehicle type
     186    */
     187    public void removeVehicleException(String vehicleType) throws IllegalArgumentException{
     188        if (!isStandardVehicleExceptionValue(vehicleType)) {
     189            throw new IllegalArgumentException(MessageFormat.format("vehicleType ''{0}'' isn''t a valid standard vehicle type", vehicleType));
     190        }
     191        vehicleExceptions.remove(vehicleType.trim().toLowerCase());
     192    }
     193
     194    @Override
     195    public int hashCode() {
     196        final int prime = 31;
     197        int result = 1;
     198        result = prime * result + getValue().hashCode();
     199        return result;
     200    }
     201
     202    @Override
     203    public boolean equals(Object obj) {
     204        if (this == obj)
     205            return true;
     206        if (obj == null)
     207            return false;
     208        if (getClass() != obj.getClass())
     209            return false;
     210        ExceptValueModel other = (ExceptValueModel) obj;
     211        return getValue().equals(other.getValue());
     212    }       
    213213}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/JosmSelectionListModel.java

    r20735 r23192  
    4040 */
    4141public class JosmSelectionListModel extends AbstractListModel implements EditLayerChangeListener, SelectionChangedListener, DataSetListener, PrimitiveIdListProvider{
    42         static private final Logger logger = Logger.getLogger(JosmSelectionListModel.class.getName());
    43        
     42    static private final Logger logger = Logger.getLogger(JosmSelectionListModel.class.getName());
     43   
    4444    private final List<OsmPrimitive> selection = new ArrayList<OsmPrimitive>();
    4545    private DefaultListSelectionModel selectionModel;
     
    5555     */
    5656    public JosmSelectionListModel(OsmDataLayer layer, DefaultListSelectionModel selectionModel) {
    57         CheckParameterUtil.ensureParameterNotNull(selectionModel, "selectionModel");
    58         CheckParameterUtil.ensureParameterNotNull(layer, "layer");
    59         this.layer = layer;
     57        CheckParameterUtil.ensureParameterNotNull(selectionModel, "selectionModel");
     58        CheckParameterUtil.ensureParameterNotNull(layer, "layer");
     59        this.layer = layer;
    6060        this.selectionModel = selectionModel;
    6161        setJOSMSelection(layer.data.getSelected());
     
    115115     */
    116116    public void setJOSMSelection(Collection<? extends OsmPrimitive> selection) {
    117         Collection<OsmPrimitive> sel = getSelected();
     117        Collection<OsmPrimitive> sel = getSelected();
    118118        this.selection.clear();
    119119        if (selection == null) {
     
    150150    public void editLayerChanged(OsmDataLayer oldLayer, OsmDataLayer newLayer) {
    151151        if (newLayer == null) {
    152                 // don't show a JOSM selection if we don't have a data layer
     152            // don't show a JOSM selection if we don't have a data layer
    153153            setJOSMSelection(null);
    154154        } else if (newLayer != layer){
    155                 // don't show a JOSM selection if this turn restriction editor doesn't
    156                 // manipulate data in the current data layer
    157                 setJOSMSelection(null);
     155            // don't show a JOSM selection if this turn restriction editor doesn't
     156            // manipulate data in the current data layer
     157            setJOSMSelection(null);
    158158        } else {
    159159            setJOSMSelection(newLayer.data.getSelected());
     
    165165    /* ------------------------------------------------------------------------ */
    166166    public void selectionChanged(Collection<? extends OsmPrimitive> newSelection) {
    167         // only update the JOSM selection if it is changed in the same data layer
    168         // this turn restriction editor is working on
    169         OsmDataLayer layer = Main.main.getEditLayer();
    170         if(layer == null) return;
    171         if (layer != this.layer) return;
     167        // only update the JOSM selection if it is changed in the same data layer
     168        // this turn restriction editor is working on
     169        OsmDataLayer layer = Main.main.getEditLayer();
     170        if(layer == null) return;
     171        if (layer != this.layer) return;
    172172        setJOSMSelection(newSelection);
    173173    }
     
    184184        if (event.getDataset() != layer.data) return;
    185185        // may influence the display name of primitives, update the data
    186         update(event.getPrimitives());
     186        update(event.getPrimitives());
    187187    }
    188188
     
    217217    /* interface PrimitiveIdListProvider                                        */
    218218    /* ------------------------------------------------------------------------ */
    219         public List<PrimitiveId> getSelectedPrimitiveIds() {
    220                 List<PrimitiveId> ret = new ArrayList<PrimitiveId>(getSelected().size());
    221                 for(int i=0; i< selection.size(); i++) {
    222                         if (selectionModel.isSelectedIndex(i)) {
    223                                 ret.add(selection.get(i).getPrimitiveId());
    224                         }
    225                 }
    226                 return ret;
    227         }
     219    public List<PrimitiveId> getSelectedPrimitiveIds() {
     220        List<PrimitiveId> ret = new ArrayList<PrimitiveId>(getSelected().size());
     221        for(int i=0; i< selection.size(); i++) {
     222            if (selectionModel.isSelectedIndex(i)) {
     223                ret.add(selection.get(i).getPrimitiveId());
     224            }
     225        }
     226        return ret;
     227    }
    228228}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/JosmSelectionPanel.java

    r20586 r23192  
    4242 */
    4343public class JosmSelectionPanel extends JPanel {
    44         /**  the list view */
    45         private JList lstSelection;
    46         /** the model managing the selection */
    47         private JosmSelectionListModel model;
    48        
    49         private CopyAction actCopy;
    50         private TransferHandler transferHandler;
    51        
    52         /**
    53         * builds the UI for the panel
    54         */
    55         protected void build(OsmDataLayer layer) {
    56                 setLayout(new BorderLayout());
    57                 DefaultListSelectionModel selectionModel = new DefaultListSelectionModel();
    58                 model = new JosmSelectionListModel(layer,selectionModel);
    59                 lstSelection = new JList(model);
    60                 lstSelection.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    61                 lstSelection.setSelectionModel(selectionModel);
    62                 lstSelection.setCellRenderer(new OsmPrimitivRenderer());
    63                 lstSelection.setTransferHandler(transferHandler = new JosmSelectionTransferHandler(model));
    64                 lstSelection.setDragEnabled(true);
    65                
    66                 add(new JScrollPane(lstSelection), BorderLayout.CENTER);
    67                 add(new JLabel(tr("Selection")), BorderLayout.NORTH);
    68                
    69                 setBorder(BorderFactory.createEmptyBorder(5,5,5,5));           
    70                 actCopy = new CopyAction();
    71                 lstSelection.addMouseListener(new PopupLauncher());
    72         }
    73        
    74         /**
    75         * Creates the JOSM selection panel for the selection in an OSM data layer
    76         *
    77         * @param layer the data layer. Must not be null.
    78         * @exception IllegalArgumentException thrown if {@code layer} is null
    79         */
    80         public JosmSelectionPanel(OsmDataLayer layer) throws IllegalArgumentException{
    81                 CheckParameterUtil.ensureParameterNotNull(layer, "layer");
    82                 build(layer);
    83         }
    84        
    85         /**
    86         * wires the UI as listener to global event sources
    87         */
    88         public void wireListeners() {
    89                 MapView.addEditLayerChangeListener(model);
    90                 DatasetEventManager.getInstance().addDatasetListener(model, FireMode.IN_EDT);
    91                 SelectionEventManager.getInstance().addSelectionListener(model, FireMode.IN_EDT_CONSOLIDATED);
    92         }
    93        
    94         /**
    95         * removes the UI as listener to global event sources
    96         */
    97         public void unwireListeners() {
    98                 MapView.removeEditLayerChangeListener(model);
    99                 DatasetEventManager.getInstance().removeDatasetListener(model);
    100                 SelectionEventManager.getInstance().removeSelectionListener(model);             
    101         }
    102        
    103         class PopupLauncher extends PopupMenuLauncher {
    104                 @Override
    105                 public void launch(MouseEvent evt) {
    106                         new PopupMenu().show(lstSelection, evt.getX(), evt.getY());
    107                 }               
    108         }
    109        
    110         class PopupMenu extends JPopupMenu {
    111                 public PopupMenu() {
    112                         JMenuItem item = add(actCopy);
    113                         item.setTransferHandler(transferHandler);
    114                         actCopy.setEnabled(!model.getSelected().isEmpty());
    115                 }
    116         }
     44    /**  the list view */
     45    private JList lstSelection;
     46    /** the model managing the selection */
     47    private JosmSelectionListModel model;
     48   
     49    private CopyAction actCopy;
     50    private TransferHandler transferHandler;
     51   
     52    /**
     53    * builds the UI for the panel
     54    */
     55    protected void build(OsmDataLayer layer) {
     56        setLayout(new BorderLayout());
     57        DefaultListSelectionModel selectionModel = new DefaultListSelectionModel();
     58        model = new JosmSelectionListModel(layer,selectionModel);
     59        lstSelection = new JList(model);
     60        lstSelection.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
     61        lstSelection.setSelectionModel(selectionModel);
     62        lstSelection.setCellRenderer(new OsmPrimitivRenderer());
     63        lstSelection.setTransferHandler(transferHandler = new JosmSelectionTransferHandler(model));
     64        lstSelection.setDragEnabled(true);
     65       
     66        add(new JScrollPane(lstSelection), BorderLayout.CENTER);
     67        add(new JLabel(tr("Selection")), BorderLayout.NORTH);
     68       
     69        setBorder(BorderFactory.createEmptyBorder(5,5,5,5));       
     70        actCopy = new CopyAction();
     71        lstSelection.addMouseListener(new PopupLauncher());
     72    }
     73   
     74    /**
     75    * Creates the JOSM selection panel for the selection in an OSM data layer
     76    *
     77    * @param layer the data layer. Must not be null.
     78    * @exception IllegalArgumentException thrown if {@code layer} is null
     79    */
     80    public JosmSelectionPanel(OsmDataLayer layer) throws IllegalArgumentException{
     81        CheckParameterUtil.ensureParameterNotNull(layer, "layer");
     82        build(layer);
     83    }
     84   
     85    /**
     86    * wires the UI as listener to global event sources
     87    */
     88    public void wireListeners() {
     89        MapView.addEditLayerChangeListener(model);
     90        DatasetEventManager.getInstance().addDatasetListener(model, FireMode.IN_EDT);
     91        SelectionEventManager.getInstance().addSelectionListener(model, FireMode.IN_EDT_CONSOLIDATED);
     92    }
     93   
     94    /**
     95    * removes the UI as listener to global event sources
     96    */
     97    public void unwireListeners() {
     98        MapView.removeEditLayerChangeListener(model);
     99        DatasetEventManager.getInstance().removeDatasetListener(model);
     100        SelectionEventManager.getInstance().removeSelectionListener(model);     
     101    }
     102   
     103    class PopupLauncher extends PopupMenuLauncher {
     104        @Override
     105        public void launch(MouseEvent evt) {
     106            new PopupMenu().show(lstSelection, evt.getX(), evt.getY());
     107        }       
     108    }
     109   
     110    class PopupMenu extends JPopupMenu {
     111        public PopupMenu() {
     112            JMenuItem item = add(actCopy);
     113            item.setTransferHandler(transferHandler);
     114            actCopy.setEnabled(!model.getSelected().isEmpty());
     115        }
     116    }
    117117
    118         class CopyAction extends AbstractAction {
    119                 private Action delegate;
    120                
    121                 public CopyAction(){
    122                         putValue(NAME, tr("Copy"));
    123                         putValue(SHORT_DESCRIPTION, tr("Copy to the clipboard"));
    124                         putValue(SMALL_ICON, ImageProvider.get("copy"));
    125                         putValue(ACCELERATOR_KEY, Shortcut.getCopyKeyStroke());
    126                         delegate = lstSelection.getActionMap().get("copy");
    127                 }
     118    class CopyAction extends AbstractAction {
     119        private Action delegate;
     120       
     121        public CopyAction(){
     122            putValue(NAME, tr("Copy"));
     123            putValue(SHORT_DESCRIPTION, tr("Copy to the clipboard"));
     124            putValue(SMALL_ICON, ImageProvider.get("copy"));
     125            putValue(ACCELERATOR_KEY, Shortcut.getCopyKeyStroke());
     126            delegate = lstSelection.getActionMap().get("copy");
     127        }
    128128
    129                 public void actionPerformed(ActionEvent e) {
    130                         delegate.actionPerformed(e);
    131                 }
    132         }
    133        
    134         static private class JosmSelectionTransferHandler extends PrimitiveIdListTransferHandler {
    135                 public JosmSelectionTransferHandler(PrimitiveIdListProvider provider) {
    136                         super(provider);
    137                 }
     129        public void actionPerformed(ActionEvent e) {
     130            delegate.actionPerformed(e);
     131        }
     132    }
     133   
     134    static private class JosmSelectionTransferHandler extends PrimitiveIdListTransferHandler {
     135        public JosmSelectionTransferHandler(PrimitiveIdListProvider provider) {
     136            super(provider);
     137        }
    138138
    139                 @Override
    140                 public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
    141                         // the JOSM selection list is read-only. Don't allow to drop or paste
    142                         // data on it
    143                         return false;
    144                 }
    145         }
     139        @Override
     140        public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
     141            // the JOSM selection list is read-only. Don't allow to drop or paste
     142            // data on it
     143            return false;
     144        }
     145    }
    146146}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/NavigationControler.java

    r20586 r23192  
    22
    33public interface NavigationControler {
    4         public enum BasicEditorFokusTargets {
    5                 RESTRICION_TYPE,
    6                 FROM,
    7                 TO,
    8                 VIA
    9         }       
    10         void gotoBasicEditor();
    11         void gotoAdvancedEditor();
    12         void gotoBasicEditor(BasicEditorFokusTargets focusTarget);     
     4    public enum BasicEditorFokusTargets {
     5        RESTRICION_TYPE,
     6        FROM,
     7        TO,
     8        VIA
     9    }   
     10    void gotoBasicEditor();
     11    void gotoAdvancedEditor();
     12    void gotoBasicEditor(BasicEditorFokusTargets focusTarget); 
    1313}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/RelationMemberColumnModel.java

    r20724 r23192  
    1414 */
    1515public class RelationMemberColumnModel extends DefaultTableColumnModel{
    16         protected void build() {
    17                 TableColumn col = new TableColumn();
    18                
    19                 // the role column
    20                 col.setHeaderValue(tr("Role"));
    21                 col.setResizable(true);
    22                  col.setPreferredWidth(100);   
    23                 col.setCellEditor(new MemberRoleCellEditor());
    24                 col.setCellRenderer(new RelationMemberRoleCellRenderer());
    25                 addColumn(col);
    26                
    27                   // column 1 - the member
    28               col = new TableColumn(1);
    29               col.setHeaderValue(tr("Refers to"));
    30               col.setResizable(true);
    31               col.setPreferredWidth(300);
    32               col.setCellRenderer(new RelationMemberTargetCellRenderer());
    33               addColumn(col);        
    34         }
    35        
    36         /**
    37         * Creates the column model with a given column selection model.
    38         *
    39         * @param colSelectionModel the column selection model. Must not be null.
    40         * @throws IllegalArgumentException thrown if {@code colSelectionModel} is null
    41         */
    42         public RelationMemberColumnModel(DefaultListSelectionModel colSelectionModel) throws IllegalArgumentException{
    43                 CheckParameterUtil.ensureParameterNotNull(colSelectionModel, "colSelectionModel");
    44                 setSelectionModel(colSelectionModel);
    45                 build();
    46         }
     16    protected void build() {
     17        TableColumn col = new TableColumn();
     18       
     19        // the role column
     20        col.setHeaderValue(tr("Role"));
     21        col.setResizable(true);
     22         col.setPreferredWidth(100);   
     23        col.setCellEditor(new MemberRoleCellEditor());
     24        col.setCellRenderer(new RelationMemberRoleCellRenderer());
     25        addColumn(col);
     26       
     27          // column 1 - the member
     28          col = new TableColumn(1);
     29          col.setHeaderValue(tr("Refers to"));
     30          col.setResizable(true);
     31          col.setPreferredWidth(300);
     32          col.setCellRenderer(new RelationMemberTargetCellRenderer());
     33          addColumn(col);        
     34    }
     35   
     36    /**
     37    * Creates the column model with a given column selection model.
     38    *
     39    * @param colSelectionModel the column selection model. Must not be null.
     40    * @throws IllegalArgumentException thrown if {@code colSelectionModel} is null
     41    */
     42    public RelationMemberColumnModel(DefaultListSelectionModel colSelectionModel) throws IllegalArgumentException{
     43        CheckParameterUtil.ensureParameterNotNull(colSelectionModel, "colSelectionModel");
     44        setSelectionModel(colSelectionModel);
     45        build();
     46    }
    4747}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/RelationMemberEditorModel.java

    r20724 r23192  
    2424import org.openstreetmap.josm.tools.CheckParameterUtil;
    2525
    26 public class RelationMemberEditorModel extends AbstractTableModel{     
    27         static private final Logger logger = Logger.getLogger(RelationMemberEditorModel.class.getName());
    28         private final ArrayList<RelationMemberModel> members = new ArrayList<RelationMemberModel>();
    29         private OsmDataLayer layer;
    30         private DefaultListSelectionModel rowSelectionModel;
    31         private DefaultListSelectionModel colSelectionModel;
    32        
    33         /**
    34         * Creates a new model in the context of an {@see OsmDataLayer}. Internally allocates
    35         * a row and a column selection model, see {@see #getRowSelectionModel()} and
    36         * {@see #getColSelectionModel()}.
    37         *
    38         * @param layer the data layer. Must not be null.
    39         * @exception IllegalArgumentException thrown if layer is null
    40         */
    41         public RelationMemberEditorModel(OsmDataLayer layer) throws IllegalArgumentException{
    42                 CheckParameterUtil.ensureParameterNotNull(layer, "layer");
    43                 this.layer = layer;
    44                 rowSelectionModel = new DefaultListSelectionModel();
    45                 colSelectionModel = new DefaultListSelectionModel();
    46         }
    47 
    48         /**
    49         *  Creates a new model in the context of an {@see OsmDataLayer}
    50        
    51         * @param layer layer the data layer. Must not be null.
    52         * @param rowSelectionModel the row selection model. Must not be null.
    53         * @param colSelectionModel the column selection model. Must not be null.
    54         * @throws IllegalArgumentException thrown if layer is null
    55         * @throws IllegalArgumentException thrown if rowSelectionModel is null
    56         * @throws IllegalArgumentException thrown if colSelectionModel is null
    57         */
    58         public RelationMemberEditorModel(OsmDataLayer layer, DefaultListSelectionModel rowSelectionModel, DefaultListSelectionModel colSelectionModel) throws IllegalArgumentException{
    59                 CheckParameterUtil.ensureParameterNotNull(layer, "layer");
    60                 CheckParameterUtil.ensureParameterNotNull(rowSelectionModel, "rowSelectionModel");
    61                 CheckParameterUtil.ensureParameterNotNull(colSelectionModel, "colSelectionModel");
    62                 this.layer = layer;
    63                 this.rowSelectionModel = rowSelectionModel;
    64                 this.colSelectionModel = colSelectionModel;
    65         }
    66 
    67         /**
    68         * Replies the row selection model used in this table model.
    69         *
    70         * @return the row selection model
    71         */
    72         public DefaultListSelectionModel getRowSelectionModel() {
    73                 return rowSelectionModel;
    74         }
    75        
    76         /**
    77         * Replies the column selection model used in this table model.
    78         *
    79         * @return the col selection model
    80         */
    81         public DefaultListSelectionModel getColSelectionModel() {
    82                 return colSelectionModel;
    83         }
    84        
    85         /**
    86         * Replies the set of {@see OsmPrimitive}s with the role {@code role}. If no
    87         * such primitives exists, the empty set is returned.
    88         *
    89         * @return the set of {@see OsmPrimitive}s with the role {@code role}
    90         */
    91         protected Set<OsmPrimitive> getPrimitivesWithRole(String role) {
    92                 HashSet<OsmPrimitive> ret = new HashSet<OsmPrimitive>();
    93                 for (RelationMemberModel rm: members){
    94                         if (rm.getRole().equals(role)){
    95                                 OsmPrimitive p = layer.data.getPrimitiveById(rm.getTarget());
    96                                 if (p != null){
    97                                         ret.add(p);
    98                                 }
    99                         }
    100                 }
    101                 return ret;
    102         }
    103        
    104         /**
    105         * Replies the list of {@see RelationMemberModel}s with the role {@code role}. If no
    106         * such primitives exists, the empty set is returned.
    107         *
    108         * @return the set of {@see RelationMemberModel}s with the role {@code role}
    109         */
    110         protected List<RelationMemberModel> getRelationMembersWithRole(String role) {
    111                 ArrayList<RelationMemberModel> ret = new ArrayList<RelationMemberModel>();
    112                 for (RelationMemberModel rm: members){
    113                         if (rm.getRole().equals(role)){
    114                                 ret.add(rm);
    115                         }
    116                 }
    117                 return ret;
    118         }
    119        
    120         /**
    121         * Removes all members with role {@code role}.
    122         *
    123         * @param role the role. Ignored if null.
    124         * @return true if the list of members was modified; false, otherwise
    125         */
    126         protected boolean removeMembersWithRole(String role){
    127                 if (role == null) return false;
    128                 boolean isChanged = false;
    129                 for(Iterator<RelationMemberModel> it = members.iterator(); it.hasNext(); ){
    130                         RelationMemberModel rm = it.next();
    131                         if (rm.getRole().equals(role)) {
    132                                 it.remove();
    133                                 isChanged = true;
    134                         }
    135                 }
    136                 return isChanged;
    137         }
    138                
    139         /**
    140         * Replies the set of {@see OsmPrimitive}s with the role 'from'. If no
    141         * such primitives exists, the empty set is returned.
    142         *
    143         * @return the set of {@see OsmPrimitive}s with the role 'from'
    144         */
    145         public Set<OsmPrimitive> getFromPrimitives() {
    146                 return getPrimitivesWithRole("from");           
    147         }
    148        
    149         /**
    150         * Replies the set of {@see OsmPrimitive}s with the role 'to'. If no
    151         * such primitives exists, the empty set is returned.
    152         *
    153         * @return the set of {@see OsmPrimitive}s with the role 'from'
    154         */
    155         public Set<OsmPrimitive> getToPrimitives() {
    156                 return getPrimitivesWithRole("to");
    157         }
    158        
    159         /**
    160         * Replies the list of 'via' objects in the order they occur in the
    161         * member list. Replies an empty list if no vias exist
    162         *
    163         * @return
    164         */
    165         public List<OsmPrimitive> getVias() {
    166                 ArrayList<OsmPrimitive> ret = new ArrayList<OsmPrimitive>();
    167                 for (RelationMemberModel rm: getRelationMembersWithRole("via")){
    168                         ret.add(layer.data.getPrimitiveById(rm.getTarget()));
    169                 }
    170                 return ret;
    171         }
    172        
    173         /**
    174         * Sets the list of vias. Removes all 'vias' if {@code vias} is null.
    175         *
    176         * null vias are skipped. A via must belong to the dataset of the layer in whose context
    177         * this editor is working, otherwise an {@see IllegalArgumentException} is thrown.
    178         *
    179         * @param vias the vias.
    180         * @exception IllegalArgumentException thrown if a via doesn't belong to the dataset of the layer
    181         * in whose context this editor is working
    182         */
    183         public void setVias(List<OsmPrimitive> vias) throws IllegalArgumentException{
    184                 boolean viasDeleted = removeMembersWithRole("via");
    185                 if (vias == null || vias.isEmpty()){
    186                         if (viasDeleted){
    187                                 fireTableDataChanged();
    188                         }
    189                         return;
    190                 }
    191                 // check vias
    192                 for (OsmPrimitive via: vias) {
    193                         if (via == null) continue;
    194                         if (via.getDataSet() == null || via.getDataSet() != layer.data){
    195                                 throw new IllegalArgumentException(MessageFormat.format("via object ''{0}'' must belong to dataset of layer ''{1}''", via.getDisplayName(DefaultNameFormatter.getInstance()), layer.getName()));
    196                         }
    197                 }
    198                 // add vias
    199                 for (OsmPrimitive via: vias) {
    200                         if (via == null) continue;
    201                         RelationMemberModel model = new RelationMemberModel("via", via);
    202                         members.add(model);
    203                 }
    204                 fireTableDataChanged();
    205         }
    206        
    207         /**
    208         * Sets the turn restriction member with role {@code role}. Removes all
    209         * members with role {@code role} if {@code id} is null.
    210         *
    211         * @param id the id
    212         * @return true if the model was modified; false, otherwise
    213         */
    214         protected boolean setPrimitiveWithRole(PrimitiveId id, String role){
    215                 if (id == null){
    216                         return removeMembersWithRole(role);
    217                 }
    218                
    219                 List<RelationMemberModel> fromMembers = getRelationMembersWithRole(role);
    220                 if (fromMembers.isEmpty()){
    221                         RelationMemberModel rm = new RelationMemberModel(role, id);
    222                         members.add(rm);
    223                         return true;
    224                 } else if (fromMembers.size() == 1){
    225                         RelationMemberModel rm = fromMembers.get(0);
    226                         if (!rm.getTarget().equals(id)){
    227                                 rm.setTarget(id);
    228                                 return true;
    229                         }
    230                         return false;
    231                 } else {
    232                         removeMembersWithRole(role);
    233                         RelationMemberModel rm = new RelationMemberModel(role, id);
    234                         members.add(rm);
    235                         return true;
    236                 }
    237         }
    238        
    239         /**
    240         * Sets the turn restriction member with role 'from'. Removes all
    241         * members with role 'from' if {@code id} is null.
    242         *
    243         * @param id the id
    244         */
    245         public void setFromPrimitive(PrimitiveId id){
    246                 if (setPrimitiveWithRole(id, "from")) {
    247                         fireTableDataChanged();
    248                 }
    249         }
    250        
    251         /**
    252         * Sets the turn restriction member with role 'to'. Removes all
    253         * members with role 'to' if {@code id} is null.
    254         *
    255         * @param id the id
    256         */
    257         public void setToPrimitive(PrimitiveId id){
    258                 if (setPrimitiveWithRole(id, "to")) {
    259                         fireTableDataChanged();
    260                 }
    261         }
    262        
    263         /**
    264         * Replies the set of {@see OsmPrimitive}s referred to by members in
    265         * this model.
    266         *
    267         * @return the set of {@see OsmPrimitive}s referred to by members in
    268         * this model.
    269         */
    270         public Set<OsmPrimitive> getMemberPrimitives() {
    271                 Set<OsmPrimitive> ret = new HashSet<OsmPrimitive>();
    272                 for (RelationMemberModel rm: members){
    273                         OsmPrimitive p = layer.data.getPrimitiveById(rm.getTarget());
    274                         if (p != null) ret.add(p);
    275                 }
    276                 return ret;
    277         }
    278        
    279         /**
    280         * Populates the model with the relation member of a turn restriction. Clears
    281         * the model if {@code tr} is null.
    282         *
    283         * @param tr the turn restriction
    284         */
    285         public void populate(Relation tr){
    286                 members.clear();
    287                 if (tr == null){
    288                         fireTableDataChanged();
    289                         return;
    290                 }
    291                 for(RelationMember rm: tr.getMembers()){
    292                         members.add(new RelationMemberModel(rm));
    293                 }
    294                 fireTableDataChanged();
    295         }
    296        
    297         /**
    298         * Replaces the member of turn restriction {@code tr} by the relation members currently
    299         * edited in this model.
    300         *
    301         * @param tr the turn restriction. Ignored if null.
    302         */
    303         public void applyTo(Relation tr){
    304                 if (tr == null) return;
    305                 List<RelationMember> newMembers = new ArrayList<RelationMember>();
    306                 for(RelationMemberModel model: members){
    307                         RelationMember rm = new RelationMember(model.getRole(), layer.data.getPrimitiveById(model.getTarget()));
    308                         newMembers.add(rm);
    309                 }
    310                 tr.setMembers(newMembers);
    311         }
    312        
    313         /**
    314         * Clears the roles of all relation members currently selected in the
    315         * table.
    316         */
    317         protected void clearSelectedRoles(){
    318                 for(int i=0; i < getRowCount();i++){
    319                         if (rowSelectionModel.isSelectedIndex(i)) {
    320                                 members.get(i).setRole("");
    321                         }
    322                 }               
    323         }
    324        
    325         /**
    326         * Removes the currently selected rows from the model
    327         */
    328         protected void removedSelectedMembers() {
    329                 for(int i=getRowCount()-1; i >= 0;i--){
    330                         if (rowSelectionModel.isSelectedIndex(i)) {
    331                                 members.remove(i);
    332                         }
    333                 }
    334         }
    335        
    336         /**
    337         * Deletes the current selection.
    338         *
    339         * If only cells in the first column are selected, the roles of the selected
    340         * members are reset to the empty string. Otherwise the selected members are
    341         * removed from the model.
    342         *
    343         */
    344         public void deleteSelected() {
    345                 if (colSelectionModel.isSelectedIndex(0) && !colSelectionModel.isSelectedIndex(1)) {
    346                         clearSelectedRoles();
    347                 } else if (rowSelectionModel.getMinSelectionIndex() >= 0){
    348                         removedSelectedMembers();
    349                 }
    350                 fireTableDataChanged();
    351         }
    352        
    353         protected List<Integer> getSelectedIndices() {
    354                 ArrayList<Integer> ret = new ArrayList<Integer>();
    355                 for(int i =0; i < members.size(); i++){
    356                         if (rowSelectionModel.isSelectedIndex(i))
    357                                 ret.add(i);
    358                 }
    359                 return ret;
    360         }
    361        
    362         public boolean canMoveUp() {
    363                 List<Integer> sel = getSelectedIndices();
    364                 if (sel.isEmpty()) return false;
    365                 return sel.get(0) > 0;
    366         }
    367        
    368         public boolean canMoveDown() {
    369                 List<Integer> sel = getSelectedIndices();
    370                 if (sel.isEmpty()) return false;
    371                 return sel.get(sel.size()-1) < members.size()-1;
    372         }
    373        
    374         public void moveUpSelected() {
    375                 if (!canMoveUp()) return;
    376                 List<Integer> sel = getSelectedIndices();
    377                 for (int idx: sel){
    378                         RelationMemberModel m = members.remove(idx);
    379                         members.add(idx-1, m);
    380                 }
    381                 fireTableDataChanged();
    382                 rowSelectionModel.clearSelection();
    383                 colSelectionModel.setSelectionInterval(0, 1);
    384                 for (int idx: sel){
    385                         rowSelectionModel.addSelectionInterval(idx-1, idx-1);
    386                 }
    387         }
    388        
    389         public void moveDownSelected() {
    390                 if (!canMoveDown()) return;
    391                 List<Integer> sel = getSelectedIndices();
    392                 for (int i = sel.size()-1; i>=0;i--){
    393                         int idx = sel.get(i);
    394                         RelationMemberModel m = members.remove(idx);
    395                         members.add(idx+1, m);
    396                 }
    397                 fireTableDataChanged();
    398                 rowSelectionModel.clearSelection();
    399                 colSelectionModel.setSelectionInterval(0, 1);
    400                 for (int idx: sel){
    401                         rowSelectionModel.addSelectionInterval(idx+1, idx+1);
    402                 }
    403         }
    404        
    405         /**
    406         * Inserts a list of new relation members with the empty role for the primitives
    407         * with id in {@code ids}. Inserts the new primitives at the position of the first
    408         * selected row. If no row is selected, at the end of the list.
    409         *
    410         *  null values are skipped. If there is an id for which there is no primitive in the context
    411         *  layer, if the primitive is deleted or invisible, an {@see IllegalArgumentException}
    412         *  is thrown and nothing is inserted.
    413         *
    414         * @param ids the list of ids. Ignored if null.
    415         * @throws IllegalArgumentException thrown if one of the ids can't be inserted
    416         */
    417         public void insertMembers(Collection<PrimitiveId> ids) throws IllegalArgumentException {
    418                 if (ids == null) return;       
    419                 ArrayList<RelationMemberModel> newMembers = new ArrayList<RelationMemberModel>();
    420                 for (PrimitiveId id: ids){
    421                         OsmPrimitive p = layer.data.getPrimitiveById(id);
    422                         if (p == null){
    423                                 throw new IllegalArgumentException(tr("Cannot find object with id ''{0}'' in layer ''{1}''", id.toString(), layer.getName()));
    424                         }
    425                         if (p.isDeleted() || ! p.isVisible()) {
    426                                 throw new IllegalArgumentException(tr("Cannot add object ''{0}'' as relation member because it is deleted or invisible in layer ''{1}''", p.getDisplayName(DefaultNameFormatter.getInstance()), layer.getName()));                             
    427                         }
    428                         newMembers.add(new RelationMemberModel("",id));
    429                 }
    430                 if (newMembers.isEmpty()) return;
    431                 int insertPos = rowSelectionModel.getMinSelectionIndex();
    432                 if ( insertPos >=0){
    433                         members.addAll(insertPos, newMembers);
    434                 } else {
    435                         members.addAll(newMembers);
    436                 }
    437                 fireTableDataChanged();
    438                 if (insertPos < 0) insertPos = 0;               
    439                 colSelectionModel.setSelectionInterval(0, 1); // select both columns
    440                 rowSelectionModel.setSelectionInterval(insertPos, insertPos + newMembers.size()-1);
    441         }
    442 
    443         public int getColumnCount() {
    444                 return 2;
    445         }
    446 
    447         public int getRowCount() {
    448                 if (members.size() > 0) return members.size();
    449                
    450                 // we display an empty row if the model is empty because otherwise
    451                 // we can't drag/drop into the empty table.
    452                 // FIXME: use JTable.setFillsViewportHeight(boolean) after the migration
    453                 // to Java 6.
    454                 return 1;
    455         }
    456 
    457         public Object getValueAt(int rowIndex, int columnIndex) {
    458                 if (members.size() == 0 && rowIndex == 0){
    459                         // we display an empty row if the model is empty because otherwise
    460                         // we can't drag/drop into the empty table.
    461                         // FIXME: use JTable.setFillsViewportHeight(boolean) after the migration
    462                         // to Java 6.
    463                         return null;
    464                 }
    465                 switch(columnIndex){
    466                 case 0: return members.get(rowIndex).getRole();
    467                 case 1: return layer.data.getPrimitiveById(members.get(rowIndex).getTarget());
    468                 }
    469                 return null;
    470         }
    471 
    472         @Override
    473         public boolean isCellEditable(int rowIndex, int columnIndex) {
    474                 // we display an empty row if the model is empty because otherwise
    475                 // we can't drag/drop into the empty table. This row isn't editable
    476                 // FIXME: use JTable.setFillsViewportHeight(boolean) after the migration
    477                 // to Java 6.
    478                 if (members.size() == 0 && rowIndex == 0) return false;
    479                
    480                 // otherwise only the column with the member roles is editable
    481                 return columnIndex == 0;
    482         }
    483 
    484         @Override
    485         public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
    486                 if (columnIndex !=0)return;
    487                 String role = (String)aValue;
    488                 RelationMemberModel model = members.get(rowIndex);
    489                 model.setRole(role);
    490                 fireTableCellUpdated(rowIndex, columnIndex);
    491         }
     26public class RelationMemberEditorModel extends AbstractTableModel{ 
     27    static private final Logger logger = Logger.getLogger(RelationMemberEditorModel.class.getName());
     28    private final ArrayList<RelationMemberModel> members = new ArrayList<RelationMemberModel>();
     29    private OsmDataLayer layer;
     30    private DefaultListSelectionModel rowSelectionModel;
     31    private DefaultListSelectionModel colSelectionModel;
     32   
     33    /**
     34    * Creates a new model in the context of an {@see OsmDataLayer}. Internally allocates
     35    * a row and a column selection model, see {@see #getRowSelectionModel()} and
     36    * {@see #getColSelectionModel()}.
     37    *
     38    * @param layer the data layer. Must not be null.
     39    * @exception IllegalArgumentException thrown if layer is null
     40    */
     41    public RelationMemberEditorModel(OsmDataLayer layer) throws IllegalArgumentException{
     42        CheckParameterUtil.ensureParameterNotNull(layer, "layer");
     43        this.layer = layer;
     44        rowSelectionModel = new DefaultListSelectionModel();
     45        colSelectionModel = new DefaultListSelectionModel();
     46    }
     47
     48    /**
     49    *  Creates a new model in the context of an {@see OsmDataLayer}
     50   
     51    * @param layer layer the data layer. Must not be null.
     52    * @param rowSelectionModel the row selection model. Must not be null.
     53    * @param colSelectionModel the column selection model. Must not be null.
     54    * @throws IllegalArgumentException thrown if layer is null
     55    * @throws IllegalArgumentException thrown if rowSelectionModel is null
     56    * @throws IllegalArgumentException thrown if colSelectionModel is null
     57    */
     58    public RelationMemberEditorModel(OsmDataLayer layer, DefaultListSelectionModel rowSelectionModel, DefaultListSelectionModel colSelectionModel) throws IllegalArgumentException{
     59        CheckParameterUtil.ensureParameterNotNull(layer, "layer");
     60        CheckParameterUtil.ensureParameterNotNull(rowSelectionModel, "rowSelectionModel");
     61        CheckParameterUtil.ensureParameterNotNull(colSelectionModel, "colSelectionModel");
     62        this.layer = layer;
     63        this.rowSelectionModel = rowSelectionModel;
     64        this.colSelectionModel = colSelectionModel;
     65    }
     66
     67    /**
     68    * Replies the row selection model used in this table model.
     69    *
     70    * @return the row selection model
     71    */
     72    public DefaultListSelectionModel getRowSelectionModel() {
     73        return rowSelectionModel;
     74    }
     75   
     76    /**
     77    * Replies the column selection model used in this table model.
     78    *
     79    * @return the col selection model
     80    */
     81    public DefaultListSelectionModel getColSelectionModel() {
     82        return colSelectionModel;
     83    }
     84   
     85    /**
     86    * Replies the set of {@see OsmPrimitive}s with the role {@code role}. If no
     87    * such primitives exists, the empty set is returned.
     88    *
     89    * @return the set of {@see OsmPrimitive}s with the role {@code role}
     90    */
     91    protected Set<OsmPrimitive> getPrimitivesWithRole(String role) {
     92        HashSet<OsmPrimitive> ret = new HashSet<OsmPrimitive>();
     93        for (RelationMemberModel rm: members){
     94            if (rm.getRole().equals(role)){
     95                OsmPrimitive p = layer.data.getPrimitiveById(rm.getTarget());
     96                if (p != null){
     97                    ret.add(p);
     98                }
     99            }
     100        }
     101        return ret;
     102    }
     103   
     104    /**
     105    * Replies the list of {@see RelationMemberModel}s with the role {@code role}. If no
     106    * such primitives exists, the empty set is returned.
     107    *
     108    * @return the set of {@see RelationMemberModel}s with the role {@code role}
     109    */
     110    protected List<RelationMemberModel> getRelationMembersWithRole(String role) {
     111        ArrayList<RelationMemberModel> ret = new ArrayList<RelationMemberModel>();
     112        for (RelationMemberModel rm: members){
     113            if (rm.getRole().equals(role)){
     114                ret.add(rm);
     115            }
     116        }
     117        return ret;
     118    }
     119   
     120    /**
     121    * Removes all members with role {@code role}.
     122    *
     123    * @param role the role. Ignored if null.
     124    * @return true if the list of members was modified; false, otherwise
     125    */
     126    protected boolean removeMembersWithRole(String role){
     127        if (role == null) return false;
     128        boolean isChanged = false;
     129        for(Iterator<RelationMemberModel> it = members.iterator(); it.hasNext(); ){
     130            RelationMemberModel rm = it.next();
     131            if (rm.getRole().equals(role)) {
     132                it.remove();
     133                isChanged = true;
     134            }
     135        }
     136        return isChanged;
     137    }
     138       
     139    /**
     140    * Replies the set of {@see OsmPrimitive}s with the role 'from'. If no
     141    * such primitives exists, the empty set is returned.
     142    *
     143    * @return the set of {@see OsmPrimitive}s with the role 'from'
     144    */
     145    public Set<OsmPrimitive> getFromPrimitives() {
     146        return getPrimitivesWithRole("from");       
     147    }
     148   
     149    /**
     150    * Replies the set of {@see OsmPrimitive}s with the role 'to'. If no
     151    * such primitives exists, the empty set is returned.
     152    *
     153    * @return the set of {@see OsmPrimitive}s with the role 'from'
     154    */
     155    public Set<OsmPrimitive> getToPrimitives() {
     156        return getPrimitivesWithRole("to");
     157    }
     158   
     159    /**
     160    * Replies the list of 'via' objects in the order they occur in the
     161    * member list. Replies an empty list if no vias exist
     162    *
     163    * @return
     164    */
     165    public List<OsmPrimitive> getVias() {
     166        ArrayList<OsmPrimitive> ret = new ArrayList<OsmPrimitive>();
     167        for (RelationMemberModel rm: getRelationMembersWithRole("via")){
     168            ret.add(layer.data.getPrimitiveById(rm.getTarget()));
     169        }
     170        return ret;
     171    }
     172   
     173    /**
     174    * Sets the list of vias. Removes all 'vias' if {@code vias} is null.
     175    *
     176    * null vias are skipped. A via must belong to the dataset of the layer in whose context
     177    * this editor is working, otherwise an {@see IllegalArgumentException} is thrown.
     178    *
     179    * @param vias the vias.
     180    * @exception IllegalArgumentException thrown if a via doesn't belong to the dataset of the layer
     181    * in whose context this editor is working
     182    */
     183    public void setVias(List<OsmPrimitive> vias) throws IllegalArgumentException{
     184        boolean viasDeleted = removeMembersWithRole("via");
     185        if (vias == null || vias.isEmpty()){
     186            if (viasDeleted){
     187                fireTableDataChanged();
     188            }
     189            return;
     190        }
     191        // check vias
     192        for (OsmPrimitive via: vias) {
     193            if (via == null) continue;
     194            if (via.getDataSet() == null || via.getDataSet() != layer.data){
     195                throw new IllegalArgumentException(MessageFormat.format("via object ''{0}'' must belong to dataset of layer ''{1}''", via.getDisplayName(DefaultNameFormatter.getInstance()), layer.getName()));
     196            }
     197        }
     198        // add vias
     199        for (OsmPrimitive via: vias) {
     200            if (via == null) continue;
     201            RelationMemberModel model = new RelationMemberModel("via", via);
     202            members.add(model);
     203        }
     204        fireTableDataChanged();
     205    }
     206   
     207    /**
     208    * Sets the turn restriction member with role {@code role}. Removes all
     209    * members with role {@code role} if {@code id} is null.
     210    *
     211    * @param id the id
     212    * @return true if the model was modified; false, otherwise
     213    */
     214    protected boolean setPrimitiveWithRole(PrimitiveId id, String role){
     215        if (id == null){
     216            return removeMembersWithRole(role);
     217        }
     218       
     219        List<RelationMemberModel> fromMembers = getRelationMembersWithRole(role);
     220        if (fromMembers.isEmpty()){
     221            RelationMemberModel rm = new RelationMemberModel(role, id);
     222            members.add(rm);
     223            return true;
     224        } else if (fromMembers.size() == 1){
     225            RelationMemberModel rm = fromMembers.get(0);
     226            if (!rm.getTarget().equals(id)){
     227                rm.setTarget(id);
     228                return true;
     229            }
     230            return false;
     231        } else {
     232            removeMembersWithRole(role);
     233            RelationMemberModel rm = new RelationMemberModel(role, id);
     234            members.add(rm);
     235            return true;
     236        }
     237    }
     238   
     239    /**
     240    * Sets the turn restriction member with role 'from'. Removes all
     241    * members with role 'from' if {@code id} is null.
     242    *
     243    * @param id the id
     244    */
     245    public void setFromPrimitive(PrimitiveId id){
     246        if (setPrimitiveWithRole(id, "from")) {
     247            fireTableDataChanged();
     248        }
     249    }
     250   
     251    /**
     252    * Sets the turn restriction member with role 'to'. Removes all
     253    * members with role 'to' if {@code id} is null.
     254    *
     255    * @param id the id
     256    */
     257    public void setToPrimitive(PrimitiveId id){
     258        if (setPrimitiveWithRole(id, "to")) {
     259            fireTableDataChanged();
     260        }
     261    }
     262   
     263    /**
     264    * Replies the set of {@see OsmPrimitive}s referred to by members in
     265    * this model.
     266    *
     267    * @return the set of {@see OsmPrimitive}s referred to by members in
     268    * this model.
     269    */
     270    public Set<OsmPrimitive> getMemberPrimitives() {
     271        Set<OsmPrimitive> ret = new HashSet<OsmPrimitive>();
     272        for (RelationMemberModel rm: members){
     273            OsmPrimitive p = layer.data.getPrimitiveById(rm.getTarget());
     274            if (p != null) ret.add(p);
     275        }
     276        return ret;
     277    }
     278   
     279    /**
     280    * Populates the model with the relation member of a turn restriction. Clears
     281    * the model if {@code tr} is null.
     282    *
     283    * @param tr the turn restriction
     284    */
     285    public void populate(Relation tr){
     286        members.clear();
     287        if (tr == null){
     288            fireTableDataChanged();
     289            return;
     290        }
     291        for(RelationMember rm: tr.getMembers()){
     292            members.add(new RelationMemberModel(rm));
     293        }
     294        fireTableDataChanged();
     295    }
     296   
     297    /**
     298    * Replaces the member of turn restriction {@code tr} by the relation members currently
     299    * edited in this model.
     300    *
     301    * @param tr the turn restriction. Ignored if null.
     302    */
     303    public void applyTo(Relation tr){
     304        if (tr == null) return;
     305        List<RelationMember> newMembers = new ArrayList<RelationMember>();
     306        for(RelationMemberModel model: members){
     307            RelationMember rm = new RelationMember(model.getRole(), layer.data.getPrimitiveById(model.getTarget()));
     308            newMembers.add(rm);
     309        }
     310        tr.setMembers(newMembers);
     311    }
     312   
     313    /**
     314    * Clears the roles of all relation members currently selected in the
     315    * table.
     316    */
     317    protected void clearSelectedRoles(){
     318        for(int i=0; i < getRowCount();i++){
     319            if (rowSelectionModel.isSelectedIndex(i)) {
     320                members.get(i).setRole("");
     321            }
     322        }       
     323    }
     324   
     325    /**
     326    * Removes the currently selected rows from the model
     327    */
     328    protected void removedSelectedMembers() {
     329        for(int i=getRowCount()-1; i >= 0;i--){
     330            if (rowSelectionModel.isSelectedIndex(i)) {
     331                members.remove(i);
     332            }
     333        }
     334    }
     335   
     336    /**
     337    * Deletes the current selection.
     338    *
     339    * If only cells in the first column are selected, the roles of the selected
     340    * members are reset to the empty string. Otherwise the selected members are
     341    * removed from the model.
     342    *
     343    */
     344    public void deleteSelected() {
     345        if (colSelectionModel.isSelectedIndex(0) && !colSelectionModel.isSelectedIndex(1)) {
     346            clearSelectedRoles();
     347        } else if (rowSelectionModel.getMinSelectionIndex() >= 0){
     348            removedSelectedMembers();
     349        }
     350        fireTableDataChanged();
     351    }
     352   
     353    protected List<Integer> getSelectedIndices() {
     354        ArrayList<Integer> ret = new ArrayList<Integer>();
     355        for(int i =0; i < members.size(); i++){
     356            if (rowSelectionModel.isSelectedIndex(i))
     357                ret.add(i);
     358        }
     359        return ret;
     360    }
     361   
     362    public boolean canMoveUp() {
     363        List<Integer> sel = getSelectedIndices();
     364        if (sel.isEmpty()) return false;
     365        return sel.get(0) > 0;
     366    }
     367   
     368    public boolean canMoveDown() {
     369        List<Integer> sel = getSelectedIndices();
     370        if (sel.isEmpty()) return false;
     371        return sel.get(sel.size()-1) < members.size()-1;
     372    }
     373   
     374    public void moveUpSelected() {
     375        if (!canMoveUp()) return;
     376        List<Integer> sel = getSelectedIndices();
     377        for (int idx: sel){
     378            RelationMemberModel m = members.remove(idx);
     379            members.add(idx-1, m);
     380        }
     381        fireTableDataChanged();
     382        rowSelectionModel.clearSelection();
     383        colSelectionModel.setSelectionInterval(0, 1);
     384        for (int idx: sel){
     385            rowSelectionModel.addSelectionInterval(idx-1, idx-1);
     386        }
     387    }
     388   
     389    public void moveDownSelected() {
     390        if (!canMoveDown()) return;
     391        List<Integer> sel = getSelectedIndices();
     392        for (int i = sel.size()-1; i>=0;i--){
     393            int idx = sel.get(i);
     394            RelationMemberModel m = members.remove(idx);
     395            members.add(idx+1, m);
     396        }
     397        fireTableDataChanged();
     398        rowSelectionModel.clearSelection();
     399        colSelectionModel.setSelectionInterval(0, 1);
     400        for (int idx: sel){
     401            rowSelectionModel.addSelectionInterval(idx+1, idx+1);
     402        }
     403    }
     404   
     405    /**
     406    * Inserts a list of new relation members with the empty role for the primitives
     407    * with id in {@code ids}. Inserts the new primitives at the position of the first
     408    * selected row. If no row is selected, at the end of the list.
     409    *
     410    *  null values are skipped. If there is an id for which there is no primitive in the context
     411    *  layer, if the primitive is deleted or invisible, an {@see IllegalArgumentException}
     412    *  is thrown and nothing is inserted.
     413    *
     414    * @param ids the list of ids. Ignored if null.
     415    * @throws IllegalArgumentException thrown if one of the ids can't be inserted
     416    */
     417    public void insertMembers(Collection<PrimitiveId> ids) throws IllegalArgumentException {
     418        if (ids == null) return;   
     419        ArrayList<RelationMemberModel> newMembers = new ArrayList<RelationMemberModel>();
     420        for (PrimitiveId id: ids){
     421            OsmPrimitive p = layer.data.getPrimitiveById(id);
     422            if (p == null){
     423                throw new IllegalArgumentException(tr("Cannot find object with id ''{0}'' in layer ''{1}''", id.toString(), layer.getName()));
     424            }
     425            if (p.isDeleted() || ! p.isVisible()) {
     426                throw new IllegalArgumentException(tr("Cannot add object ''{0}'' as relation member because it is deleted or invisible in layer ''{1}''", p.getDisplayName(DefaultNameFormatter.getInstance()), layer.getName()));             
     427            }
     428            newMembers.add(new RelationMemberModel("",id));
     429        }
     430        if (newMembers.isEmpty()) return;
     431        int insertPos = rowSelectionModel.getMinSelectionIndex();
     432        if ( insertPos >=0){
     433            members.addAll(insertPos, newMembers);
     434        } else {
     435            members.addAll(newMembers);
     436        }
     437        fireTableDataChanged();
     438        if (insertPos < 0) insertPos = 0;       
     439        colSelectionModel.setSelectionInterval(0, 1); // select both columns
     440        rowSelectionModel.setSelectionInterval(insertPos, insertPos + newMembers.size()-1);
     441    }
     442
     443    public int getColumnCount() {
     444        return 2;
     445    }
     446
     447    public int getRowCount() {
     448        if (members.size() > 0) return members.size();
     449       
     450        // we display an empty row if the model is empty because otherwise
     451        // we can't drag/drop into the empty table.
     452        // FIXME: use JTable.setFillsViewportHeight(boolean) after the migration
     453        // to Java 6.
     454        return 1;
     455    }
     456
     457    public Object getValueAt(int rowIndex, int columnIndex) {
     458        if (members.size() == 0 && rowIndex == 0){
     459            // we display an empty row if the model is empty because otherwise
     460            // we can't drag/drop into the empty table.
     461            // FIXME: use JTable.setFillsViewportHeight(boolean) after the migration
     462            // to Java 6.
     463            return null;
     464        }
     465        switch(columnIndex){
     466        case 0: return members.get(rowIndex).getRole();
     467        case 1: return layer.data.getPrimitiveById(members.get(rowIndex).getTarget());
     468        }
     469        return null;
     470    }
     471
     472    @Override
     473    public boolean isCellEditable(int rowIndex, int columnIndex) {
     474        // we display an empty row if the model is empty because otherwise
     475        // we can't drag/drop into the empty table. This row isn't editable
     476        // FIXME: use JTable.setFillsViewportHeight(boolean) after the migration
     477        // to Java 6.
     478        if (members.size() == 0 && rowIndex == 0) return false;
     479       
     480        // otherwise only the column with the member roles is editable
     481        return columnIndex == 0;
     482    }
     483
     484    @Override
     485    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
     486        if (columnIndex !=0)return;
     487        String role = (String)aValue;
     488        RelationMemberModel model = members.get(rowIndex);
     489        model.setRole(role);
     490        fireTableCellUpdated(rowIndex, columnIndex);
     491    }
    492492}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/RelationMemberModel.java

    r20527 r23192  
    1616 */
    1717public class RelationMemberModel implements Serializable{
    18         private String role;
    19         private SimplePrimitiveId target;
    20        
    21         /**
    22         * Creates a new relation member model
    23         *
    24         * @param role the member role. Reset to "" if null.
    25         * @param target the id of the target object. Must not be null.
    26         * @throws IllegalArgumentException thrown if {@code target} is null
    27         */
    28         public RelationMemberModel(String role, PrimitiveId target) throws IllegalArgumentException {
    29                 CheckParameterUtil.ensureParameterNotNull(target, "target");
    30                 this.role = role == null? "" : role;
    31                 this.target = new SimplePrimitiveId(target.getUniqueId(), target.getType());
    32         }
    33        
    34         /**
    35         * Creates a new relation member model from a relation member
    36         *
    37         * @param member the relation member. Must not be null.
    38         * @throws IllegalArgumentException thrown if {@code member} is null
    39         */
    40         public RelationMemberModel(RelationMember member) throws IllegalArgumentException{
    41                 CheckParameterUtil.ensureParameterNotNull(member, "member");
    42                 this.role = member.getRole();
    43                 setTarget(member.getMember().getPrimitiveId());
    44         }
     18    private String role;
     19    private SimplePrimitiveId target;
     20   
     21    /**
     22    * Creates a new relation member model
     23    *
     24    * @param role the member role. Reset to "" if null.
     25    * @param target the id of the target object. Must not be null.
     26    * @throws IllegalArgumentException thrown if {@code target} is null
     27    */
     28    public RelationMemberModel(String role, PrimitiveId target) throws IllegalArgumentException {
     29        CheckParameterUtil.ensureParameterNotNull(target, "target");
     30        this.role = role == null? "" : role;
     31        this.target = new SimplePrimitiveId(target.getUniqueId(), target.getType());
     32    }
     33   
     34    /**
     35    * Creates a new relation member model from a relation member
     36    *
     37    * @param member the relation member. Must not be null.
     38    * @throws IllegalArgumentException thrown if {@code member} is null
     39    */
     40    public RelationMemberModel(RelationMember member) throws IllegalArgumentException{
     41        CheckParameterUtil.ensureParameterNotNull(member, "member");
     42        this.role = member.getRole();
     43        setTarget(member.getMember().getPrimitiveId());
     44    }
    4545
    46         /**
    47         * Replies the current role in this model. Never null.
    48         *
    49         * @return the current role in this model
    50         */
    51         public String getRole() {
    52                 return role;
    53         }
     46    /**
     47    * Replies the current role in this model. Never null.
     48    *
     49    * @return the current role in this model
     50    */
     51    public String getRole() {
     52        return role;
     53    }
    5454
    55         /**
    56         * Sets the current role in this model.
    57         *
    58         * @param role the role. Reset to "" if null.
    59         */
    60         public void setRole(String role) {
    61                 this.role = role == null? "" : role;
    62         }
     55    /**
     56    * Sets the current role in this model.
     57    *
     58    * @param role the role. Reset to "" if null.
     59    */
     60    public void setRole(String role) {
     61        this.role = role == null? "" : role;
     62    }
    6363
    64         /**
    65         * Replies the id of the target object of this relation member.
    66         *
    67         * @return the id of the target object of this relation member.
    68         */
    69         public PrimitiveId getTarget() {
    70                 return target;
    71         }
     64    /**
     65    * Replies the id of the target object of this relation member.
     66    *
     67    * @return the id of the target object of this relation member.
     68    */
     69    public PrimitiveId getTarget() {
     70        return target;
     71    }
    7272
    73         /**
    74         * Sets the id of the target object. 
    75         *
    76         * @param target the id of the target object. Must not be null.
    77         * @throws IllegalArgumentException thrown if {@code target} is null
    78         */
    79         public void setTarget(PrimitiveId target) throws IllegalArgumentException{
    80                 CheckParameterUtil.ensureParameterNotNull(target, "target");
    81                 this.target = new SimplePrimitiveId(target.getUniqueId(), target.getType());
    82         }
    83        
    84         @Override
    85         public int hashCode() {
    86                 final int prime = 31;
    87                 int result = 1;
    88                 result = prime * result + ((role == null) ? 0 : role.hashCode());
    89                 result = prime * result + ((target == null) ? 0 : target.hashCode());
    90                 return result;
    91         }
     73    /**
     74    * Sets the id of the target object. 
     75    *
     76    * @param target the id of the target object. Must not be null.
     77    * @throws IllegalArgumentException thrown if {@code target} is null
     78    */
     79    public void setTarget(PrimitiveId target) throws IllegalArgumentException{
     80        CheckParameterUtil.ensureParameterNotNull(target, "target");
     81        this.target = new SimplePrimitiveId(target.getUniqueId(), target.getType());
     82    }
     83   
     84    @Override
     85    public int hashCode() {
     86        final int prime = 31;
     87        int result = 1;
     88        result = prime * result + ((role == null) ? 0 : role.hashCode());
     89        result = prime * result + ((target == null) ? 0 : target.hashCode());
     90        return result;
     91    }
    9292
    93         @Override
    94         public boolean equals(Object obj) {
    95                 if (this == obj)
    96                         return true;
    97                 if (obj == null)
    98                         return false;
    99                 if (getClass() != obj.getClass())
    100                         return false;
    101                 RelationMemberModel other = (RelationMemberModel) obj;
    102                 if (role == null) {
    103                         if (other.role != null)
    104                                 return false;
    105                 } else if (!role.equals(other.role))
    106                         return false;
    107                 if (target == null) {
    108                         if (other.target != null)
    109                                 return false;
    110                 } else if (!target.equals(other.target))
    111                         return false;
    112                 return true;
    113         }
     93    @Override
     94    public boolean equals(Object obj) {
     95        if (this == obj)
     96            return true;
     97        if (obj == null)
     98            return false;
     99        if (getClass() != obj.getClass())
     100            return false;
     101        RelationMemberModel other = (RelationMemberModel) obj;
     102        if (role == null) {
     103            if (other.role != null)
     104                return false;
     105        } else if (!role.equals(other.role))
     106            return false;
     107        if (target == null) {
     108            if (other.target != null)
     109                return false;
     110        } else if (!target.equals(other.target))
     111            return false;
     112        return true;
     113    }
    114114}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/RelationMemberRoleCellRenderer.java

    r20724 r23192  
    1010public class RelationMemberRoleCellRenderer extends DefaultTableCellRenderer{
    1111private JLabel mockCell;
    12        
    13         public RelationMemberRoleCellRenderer() {
    14                 mockCell = new JLabel();
    15                 mockCell.setText("");
    16                 mockCell.setOpaque(true);
    17         }
    18        
    19         public Component getTableCellRendererComponent(JTable table, Object value,
    20                         boolean isSelected, boolean hasFocus, int row, int column) {
    21                 if (value != null){
    22                         return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    23                 }
    24                
    25                 // FIXME: required to always draw a mock row, even if the table is empty.
    26                 // Otherwise, drag and drop onto the table fails.
    27                 // Replace with JTable.setFillsViewportHeight(boolean) after the migration
    28                 // to Java 6.
    29                 if (isSelected){
    30                         mockCell.setBackground(UIManager.getColor("Table.selectionBackground"));
    31                         mockCell.setForeground(UIManager.getColor("Table.selectionForeground"));
    32                 } else {
    33                         mockCell.setBackground(UIManager.getColor("Panel.background"));
    34                         mockCell.setForeground(UIManager.getColor("Panel.foreground"));
    35                 }               
    36                 return mockCell;
    37         }
     12   
     13    public RelationMemberRoleCellRenderer() {
     14        mockCell = new JLabel();
     15        mockCell.setText("");
     16        mockCell.setOpaque(true);
     17    }
     18   
     19    public Component getTableCellRendererComponent(JTable table, Object value,
     20            boolean isSelected, boolean hasFocus, int row, int column) {
     21        if (value != null){
     22            return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
     23        }
     24       
     25        // FIXME: required to always draw a mock row, even if the table is empty.
     26        // Otherwise, drag and drop onto the table fails.
     27        // Replace with JTable.setFillsViewportHeight(boolean) after the migration
     28        // to Java 6.
     29        if (isSelected){
     30            mockCell.setBackground(UIManager.getColor("Table.selectionBackground"));
     31            mockCell.setForeground(UIManager.getColor("Table.selectionForeground"));
     32        } else {
     33            mockCell.setBackground(UIManager.getColor("Panel.background"));
     34            mockCell.setForeground(UIManager.getColor("Panel.foreground"));
     35        }       
     36        return mockCell;
     37    }
    3838}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/RelationMemberTable.java

    r20675 r23192  
    4646 */
    4747public class RelationMemberTable extends JTable {
    48         static private final Logger logger = Logger.getLogger(RelationMemberTable.class.getName());
    49        
    50         private TurnRestrictionEditorModel model;
    51         private DeleteAction actDelete;
    52         private PasteAction actPaste;
    53         private MoveUpAction actMoveUp;
    54         private MoveDownAction actMoveDown;
    55         private TransferHandler transferHandler;
    56        
    57         public RelationMemberTable(TurnRestrictionEditorModel model) {
    58                 super(
    59                                 model.getRelationMemberEditorModel(),
    60                                 new RelationMemberColumnModel(model.getRelationMemberEditorModel().getColSelectionModel()),
    61                                 model.getRelationMemberEditorModel().getRowSelectionModel()
    62                 );
    63                 this.model = model;
    64                 setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
     48    static private final Logger logger = Logger.getLogger(RelationMemberTable.class.getName());
     49   
     50    private TurnRestrictionEditorModel model;
     51    private DeleteAction actDelete;
     52    private PasteAction actPaste;
     53    private MoveUpAction actMoveUp;
     54    private MoveDownAction actMoveDown;
     55    private TransferHandler transferHandler;
     56   
     57    public RelationMemberTable(TurnRestrictionEditorModel model) {
     58        super(
     59                model.getRelationMemberEditorModel(),
     60                new RelationMemberColumnModel(model.getRelationMemberEditorModel().getColSelectionModel()),
     61                model.getRelationMemberEditorModel().getRowSelectionModel()
     62        );
     63        this.model = model;
     64        setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    6565        setRowSelectionAllowed(true);
    6666        setColumnSelectionAllowed(true);
    6767
    68                 // register the popup menu launcher
    69                 addMouseListener(new TablePopupLauncher());
    70                
    71                 // transfer handling
    72                 setDragEnabled(true);
    73                 setTransferHandler(new RelationMemberTransferHandler());
    74                 setDropTarget(new RelationMemberTableDropTarget());
    75                
    76                 // initialize the delete action
    77                 //
    78                 actDelete = new DeleteAction();
    79                 model.getRelationMemberEditorModel().getRowSelectionModel().addListSelectionListener(actDelete);
    80                 registerKeyboardAction(actDelete, KeyStroke.getKeyStroke(KeyEvent.VK_DELETE,0), WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    81                
    82                 // initialize the paste action (will be used in the popup, the action map already includes
    83                 // the standard paste action for transfer handling)
    84                 actPaste = new PasteAction();
    85                
    86                 actMoveUp = new MoveUpAction();
    87                 model.getRelationMemberEditorModel().getRowSelectionModel().addListSelectionListener(actMoveUp);
    88                 registerKeyboardAction(actMoveUp,actMoveUp.getKeyStroke(), WHEN_FOCUSED);
    89                
    90                 actMoveDown = new MoveDownAction();
    91                 model.getRelationMemberEditorModel().getRowSelectionModel().addListSelectionListener(actMoveDown);
    92                 registerKeyboardAction(actMoveDown, actMoveDown.getKeyStroke(), WHEN_FOCUSED);
    93         }
    94 
    95         /**
    96         * The action for deleting the selected table cells
    97         *
    98         */
    99         class DeleteAction extends AbstractAction implements ListSelectionListener{
    100                 public DeleteAction() {
    101                         putValue(NAME, tr("Delete"));
    102                         putValue(SHORT_DESCRIPTION, tr("Clear the selected roles or delete the selected members"));
    103                         putValue(SMALL_ICON, ImageProvider.get("deletesmall"));
    104                         putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_DELETE,0));
    105                         updateEnabledState();
    106                 }
    107                
    108                 public void updateEnabledState() {
    109                         setEnabled(model.getRelationMemberEditorModel().getRowSelectionModel().getMinSelectionIndex()>=0);
    110                 }
    111 
    112                 public void actionPerformed(ActionEvent e) {
    113                         model.getRelationMemberEditorModel().deleteSelected();
    114                 }
    115 
    116                 public void valueChanged(ListSelectionEvent e) {
    117                         updateEnabledState();
    118                 }
    119         }       
    120        
    121         /**
    122         * The action for pasting into the relation member table
    123         *
    124         */
    125         class PasteAction extends AbstractAction{               
    126                 public PasteAction() {
    127                         putValue(NAME, tr("Paste"));
    128                         putValue(SHORT_DESCRIPTION, tr("Insert new relation members from object in the clipboard"));
    129                         putValue(SMALL_ICON, ImageProvider.get("paste"));
    130                         putValue(ACCELERATOR_KEY, Shortcut.getPasteKeyStroke());
    131                         updateEnabledState();
    132                 }
    133                
    134                 public void updateEnabledState() {
    135                         DataFlavor[] flavors = Toolkit.getDefaultToolkit().getSystemClipboard().getAvailableDataFlavors();
    136                         setEnabled(PrimitiveIdListTransferHandler.isSupportedFlavor(flavors));
    137                 }
    138 
    139                 public void actionPerformed(ActionEvent evt) {
    140                         // tried to delegate to 'paste' action in the action map of the
    141                         // table, but didn't work. Now duplicating the logic of importData(...) in
    142                         // the transfer handler.
    143                         //
    144                         Clipboard cp = Toolkit.getDefaultToolkit().getSystemClipboard();
    145                         if (!PrimitiveIdListTransferHandler.isSupportedFlavor(cp.getAvailableDataFlavors())) return;
    146                         try {
    147                                 List<PrimitiveId> ids;
    148                                 ids = (List<PrimitiveId>)cp.getData(PrimitiveIdTransferable.PRIMITIVE_ID_LIST_FLAVOR);
    149                                 try {
    150                                         model.getRelationMemberEditorModel().insertMembers(ids);
    151                                 } catch(IllegalArgumentException e){
    152                                         e.printStackTrace();
    153                                         // FIXME: provide user feedback
    154                                 }
    155                         } catch(IOException e){
    156                                 e.printStackTrace();
    157                         } catch(UnsupportedFlavorException e){
    158                                 e.printStackTrace();
    159                         }
    160                 }
    161         }       
    162 
    163         class MoveDownAction extends AbstractAction implements ListSelectionListener{   
    164                 private KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, KeyEvent.ALT_DOWN_MASK);
    165                 public MoveDownAction(){
    166                         putValue(NAME, tr("Move down"));
    167                         putValue(SHORT_DESCRIPTION, tr("Move the selected relation members down by one position"));
    168                         putValue(ACCELERATOR_KEY,keyStroke);
    169                         putValue(SMALL_ICON, ImageProvider.get("dialogs", "movedown"));
    170                         updateEnabledState();
    171                 }
    172                
    173                 public void actionPerformed(ActionEvent e) {
    174                         model.getRelationMemberEditorModel().moveDownSelected();
    175                 }
    176 
    177                 public void updateEnabledState(){
    178                         setEnabled(model.getRelationMemberEditorModel().canMoveDown());
    179                 }
    180                
    181                 public void valueChanged(ListSelectionEvent e) {
    182                         updateEnabledState();                   
    183                 }
    184                 public KeyStroke getKeyStroke() {
    185                         return keyStroke;
    186                 }
    187         }
    188        
    189         class MoveUpAction extends AbstractAction implements ListSelectionListener{
    190                 private KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_UP, KeyEvent.ALT_DOWN_MASK);
    191 
    192                 public MoveUpAction() {
    193                         putValue(NAME, tr("Move up"));
    194                         putValue(SHORT_DESCRIPTION, tr("Move the selected relation members up by one position"));
    195                         putValue(ACCELERATOR_KEY,keyStroke);
    196                         putValue(SMALL_ICON, ImageProvider.get("dialogs", "moveup"));
    197                         updateEnabledState();
    198                 }
    199                
    200                 public void actionPerformed(ActionEvent e) {
    201                         model.getRelationMemberEditorModel().moveUpSelected();
    202                 }
    203 
    204                 public void updateEnabledState(){
    205                         setEnabled(model.getRelationMemberEditorModel().canMoveUp());
    206                 }
    207                
    208                 public void valueChanged(ListSelectionEvent e) {
    209                         updateEnabledState();                   
    210                 }
    211                 public KeyStroke getKeyStroke() {
    212                         return keyStroke;
    213                 }
    214         }
    215        
    216         class TablePopupLauncher extends PopupMenuLauncher {
    217                 @Override
    218                 public void launch(MouseEvent evt) {
    219                         int row = rowAtPoint(evt.getPoint());
    220                         if (getSelectionModel().getMinSelectionIndex() < 0 && row >=0){
    221                                 getSelectionModel().setSelectionInterval(row, row);
    222                                 getColumnModel().getSelectionModel().setSelectionInterval(0, 1);
    223                         }
    224                         new PopupMenu().show(RelationMemberTable.this, evt.getX(), evt.getY());
    225                 }               
    226         }
    227        
    228         class PopupMenu extends JPopupMenu {
    229                 public PopupMenu() {
    230                         JMenuItem item = add(actPaste);
    231                         item.setTransferHandler(transferHandler);
    232                         actPaste.updateEnabledState();
    233                         addSeparator();
    234                         add(actDelete);
    235                         addSeparator();
    236                         add(actMoveUp);
    237                         add(actMoveDown);
    238                 }
    239         }
    240        
    241         /**
    242         * The transfer handler for the relation member table.
    243         *
    244         */
    245         class RelationMemberTransferHandler extends TransferHandler {
    246                
    247                 @Override
    248                 public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
    249                         return PrimitiveIdListTransferHandler.isSupportedFlavor(transferFlavors);
    250                 }
    251 
    252                 @Override
    253                 public boolean importData(JComponent comp, Transferable t) {
    254                         try {
    255                                 List<PrimitiveId> ids;
    256                                 ids = (List<PrimitiveId>)t.getTransferData(PrimitiveIdTransferable.PRIMITIVE_ID_LIST_FLAVOR);
    257                                 try {
    258                                         model.getRelationMemberEditorModel().insertMembers(ids);
    259                                 } catch(IllegalArgumentException e){
    260                                         e.printStackTrace();
    261                                         // FIXME: provide user feedback
    262                                         return false;
    263                                 }
    264                                 return true;
    265                         } catch(IOException e){
    266                                 e.printStackTrace();
    267                         } catch(UnsupportedFlavorException e){
    268                                 e.printStackTrace();
    269                         }
    270                         return false;
    271                 }
    272 
    273                 @Override
    274                 public int getSourceActions(JComponent c) {
    275                         return  COPY_OR_MOVE;
    276                 }
    277         }
    278        
    279         /**
    280         * A custom drop target for the relation member table. During dragging we need to
    281         * disable colum selection model. 
    282         *
    283         */
    284         class RelationMemberTableDropTarget extends DropTarget{         
    285                 private boolean dropAccepted = false;   
    286                
    287                 /**
    288                 * Replies true if {@code transferFlavors} includes the data flavor {@see PrimitiveIdTransferable#PRIMITIVE_ID_LIST_FLAVOR}.
    289 
    290                 * @param transferFlavors an array of transferFlavors
    291                 * @return
    292                 */
    293                 protected boolean isSupportedFlavor(DataFlavor[] transferFlavors) {
    294                         for (DataFlavor df: transferFlavors) {
    295                                 if (df.equals(PrimitiveIdTransferable.PRIMITIVE_ID_LIST_FLAVOR)) return true;
    296                         }
    297                         return false;
    298                 }               
    299                
    300                 public synchronized void dragEnter(DropTargetDragEvent dtde) {
    301                         if (isSupportedFlavor(dtde.getCurrentDataFlavors())) {
    302                                 if ((dtde.getSourceActions() & DnDConstants.ACTION_COPY_OR_MOVE) != 0){
    303                                         dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);             
    304                                         setColumnSelectionAllowed(false);
    305                                         dropAccepted  = true;
    306                                 } else {
    307                                         dtde.rejectDrag();
    308                                 }
    309                         } else {
    310                                 dtde.rejectDrag();
    311                         }
    312                 }
    313                
    314                 public synchronized void dragExit(DropTargetEvent dte) {
    315                         setColumnSelectionAllowed(true);
    316                         dropAccepted = false;
    317                 }
    318                
    319                 @Override
    320                 public synchronized void dragOver(DropTargetDragEvent dtde) {
    321                         int row = rowAtPoint(dtde.getLocation());
    322                         int selectedRow = getSelectionModel().getMinSelectionIndex();
    323                         if (row >= 0 && row != selectedRow){
    324                                 getSelectionModel().setSelectionInterval(row, row);
    325                         }                       
    326                 }
    327 
    328                 public synchronized void drop(DropTargetDropEvent dtde) {
    329                         try {
    330                                 if (!dropAccepted) return;
    331                                 if ((dtde.getSourceActions() & DnDConstants.ACTION_COPY_OR_MOVE) == 0) {
    332                                         return;
    333                                 }
    334                                 List<PrimitiveId> ids;
    335                                 ids = (List<PrimitiveId>)dtde.getTransferable().getTransferData(PrimitiveIdTransferable.PRIMITIVE_ID_LIST_FLAVOR);
    336                                 try {
    337                                         model.getRelationMemberEditorModel().insertMembers(ids);
    338                                 } catch(IllegalArgumentException e){
    339                                         e.printStackTrace();
    340                                         // FIXME: provide user feedback
    341                                 }
    342                         } catch(IOException e){
    343                                 e.printStackTrace();
    344                         } catch(UnsupportedFlavorException e){
    345                                 e.printStackTrace();
    346                         } finally {
    347                                 setColumnSelectionAllowed(true);
    348                         }
    349                 }
    350                
    351                 public synchronized void dropActionChanged(DropTargetDragEvent dtde) {
    352                         if ((dtde.getSourceActions() & DnDConstants.ACTION_COPY_OR_MOVE) == 0) {
    353                                 dtde.rejectDrag();
    354                         } else {
    355                                 dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
    356                         }
    357                 }
    358         }
     68        // register the popup menu launcher
     69        addMouseListener(new TablePopupLauncher());
     70       
     71        // transfer handling
     72        setDragEnabled(true);
     73        setTransferHandler(new RelationMemberTransferHandler());
     74        setDropTarget(new RelationMemberTableDropTarget());
     75       
     76        // initialize the delete action
     77        //
     78        actDelete = new DeleteAction();
     79        model.getRelationMemberEditorModel().getRowSelectionModel().addListSelectionListener(actDelete);
     80        registerKeyboardAction(actDelete, KeyStroke.getKeyStroke(KeyEvent.VK_DELETE,0), WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
     81       
     82        // initialize the paste action (will be used in the popup, the action map already includes
     83        // the standard paste action for transfer handling)
     84        actPaste = new PasteAction();
     85       
     86        actMoveUp = new MoveUpAction();
     87        model.getRelationMemberEditorModel().getRowSelectionModel().addListSelectionListener(actMoveUp);
     88        registerKeyboardAction(actMoveUp,actMoveUp.getKeyStroke(), WHEN_FOCUSED);
     89       
     90        actMoveDown = new MoveDownAction();
     91        model.getRelationMemberEditorModel().getRowSelectionModel().addListSelectionListener(actMoveDown);
     92        registerKeyboardAction(actMoveDown, actMoveDown.getKeyStroke(), WHEN_FOCUSED);
     93    }
     94
     95    /**
     96    * The action for deleting the selected table cells
     97    *
     98    */
     99    class DeleteAction extends AbstractAction implements ListSelectionListener{
     100        public DeleteAction() {
     101            putValue(NAME, tr("Delete"));
     102            putValue(SHORT_DESCRIPTION, tr("Clear the selected roles or delete the selected members"));
     103            putValue(SMALL_ICON, ImageProvider.get("deletesmall"));
     104            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_DELETE,0));
     105            updateEnabledState();
     106        }
     107       
     108        public void updateEnabledState() {
     109            setEnabled(model.getRelationMemberEditorModel().getRowSelectionModel().getMinSelectionIndex()>=0);
     110        }
     111
     112        public void actionPerformed(ActionEvent e) {
     113            model.getRelationMemberEditorModel().deleteSelected();
     114        }
     115
     116        public void valueChanged(ListSelectionEvent e) {
     117            updateEnabledState();
     118        }
     119    }   
     120   
     121    /**
     122    * The action for pasting into the relation member table
     123    *
     124    */
     125    class PasteAction extends AbstractAction{       
     126        public PasteAction() {
     127            putValue(NAME, tr("Paste"));
     128            putValue(SHORT_DESCRIPTION, tr("Insert new relation members from object in the clipboard"));
     129            putValue(SMALL_ICON, ImageProvider.get("paste"));
     130            putValue(ACCELERATOR_KEY, Shortcut.getPasteKeyStroke());
     131            updateEnabledState();
     132        }
     133       
     134        public void updateEnabledState() {
     135            DataFlavor[] flavors = Toolkit.getDefaultToolkit().getSystemClipboard().getAvailableDataFlavors();
     136            setEnabled(PrimitiveIdListTransferHandler.isSupportedFlavor(flavors));
     137        }
     138
     139        public void actionPerformed(ActionEvent evt) {
     140            // tried to delegate to 'paste' action in the action map of the
     141            // table, but didn't work. Now duplicating the logic of importData(...) in
     142            // the transfer handler.
     143            //
     144            Clipboard cp = Toolkit.getDefaultToolkit().getSystemClipboard();
     145            if (!PrimitiveIdListTransferHandler.isSupportedFlavor(cp.getAvailableDataFlavors())) return;
     146            try {
     147                List<PrimitiveId> ids;
     148                ids = (List<PrimitiveId>)cp.getData(PrimitiveIdTransferable.PRIMITIVE_ID_LIST_FLAVOR);
     149                try {
     150                    model.getRelationMemberEditorModel().insertMembers(ids);
     151                } catch(IllegalArgumentException e){
     152                    e.printStackTrace();
     153                    // FIXME: provide user feedback
     154                }
     155            } catch(IOException e){
     156                e.printStackTrace();
     157            } catch(UnsupportedFlavorException e){
     158                e.printStackTrace();
     159            }
     160        }
     161    }   
     162
     163    class MoveDownAction extends AbstractAction implements ListSelectionListener{   
     164        private KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, KeyEvent.ALT_DOWN_MASK);
     165        public MoveDownAction(){
     166            putValue(NAME, tr("Move down"));
     167            putValue(SHORT_DESCRIPTION, tr("Move the selected relation members down by one position"));
     168            putValue(ACCELERATOR_KEY,keyStroke);
     169            putValue(SMALL_ICON, ImageProvider.get("dialogs", "movedown"));
     170            updateEnabledState();
     171        }
     172       
     173        public void actionPerformed(ActionEvent e) {
     174            model.getRelationMemberEditorModel().moveDownSelected();
     175        }
     176
     177        public void updateEnabledState(){
     178            setEnabled(model.getRelationMemberEditorModel().canMoveDown());
     179        }
     180       
     181        public void valueChanged(ListSelectionEvent e) {
     182            updateEnabledState();           
     183        }
     184        public KeyStroke getKeyStroke() {
     185            return keyStroke;
     186        }
     187    }
     188   
     189    class MoveUpAction extends AbstractAction implements ListSelectionListener{
     190        private KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_UP, KeyEvent.ALT_DOWN_MASK);
     191
     192        public MoveUpAction() {
     193            putValue(NAME, tr("Move up"));
     194            putValue(SHORT_DESCRIPTION, tr("Move the selected relation members up by one position"));
     195            putValue(ACCELERATOR_KEY,keyStroke);
     196            putValue(SMALL_ICON, ImageProvider.get("dialogs", "moveup"));
     197            updateEnabledState();
     198        }
     199       
     200        public void actionPerformed(ActionEvent e) {
     201            model.getRelationMemberEditorModel().moveUpSelected();
     202        }
     203
     204        public void updateEnabledState(){
     205            setEnabled(model.getRelationMemberEditorModel().canMoveUp());
     206        }
     207       
     208        public void valueChanged(ListSelectionEvent e) {
     209            updateEnabledState();           
     210        }
     211        public KeyStroke getKeyStroke() {
     212            return keyStroke;
     213        }
     214    }
     215   
     216    class TablePopupLauncher extends PopupMenuLauncher {
     217        @Override
     218        public void launch(MouseEvent evt) {
     219            int row = rowAtPoint(evt.getPoint());
     220            if (getSelectionModel().getMinSelectionIndex() < 0 && row >=0){
     221                getSelectionModel().setSelectionInterval(row, row);
     222                getColumnModel().getSelectionModel().setSelectionInterval(0, 1);
     223            }
     224            new PopupMenu().show(RelationMemberTable.this, evt.getX(), evt.getY());
     225        }       
     226    }
     227   
     228    class PopupMenu extends JPopupMenu {
     229        public PopupMenu() {
     230            JMenuItem item = add(actPaste);
     231            item.setTransferHandler(transferHandler);
     232            actPaste.updateEnabledState();
     233            addSeparator();
     234            add(actDelete);
     235            addSeparator();
     236            add(actMoveUp);
     237            add(actMoveDown);
     238        }
     239    }
     240   
     241    /**
     242    * The transfer handler for the relation member table.
     243    *
     244    */
     245    class RelationMemberTransferHandler extends TransferHandler {
     246       
     247        @Override
     248        public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
     249            return PrimitiveIdListTransferHandler.isSupportedFlavor(transferFlavors);
     250        }
     251
     252        @Override
     253        public boolean importData(JComponent comp, Transferable t) {
     254            try {
     255                List<PrimitiveId> ids;
     256                ids = (List<PrimitiveId>)t.getTransferData(PrimitiveIdTransferable.PRIMITIVE_ID_LIST_FLAVOR);
     257                try {
     258                    model.getRelationMemberEditorModel().insertMembers(ids);
     259                } catch(IllegalArgumentException e){
     260                    e.printStackTrace();
     261                    // FIXME: provide user feedback
     262                    return false;
     263                }
     264                return true;
     265            } catch(IOException e){
     266                e.printStackTrace();
     267            } catch(UnsupportedFlavorException e){
     268                e.printStackTrace();
     269            }
     270            return false;
     271        }
     272
     273        @Override
     274        public int getSourceActions(JComponent c) {
     275            return  COPY_OR_MOVE;
     276        }
     277    }
     278   
     279    /**
     280    * A custom drop target for the relation member table. During dragging we need to
     281    * disable colum selection model. 
     282    *
     283    */
     284    class RelationMemberTableDropTarget extends DropTarget{     
     285        private boolean dropAccepted = false;   
     286       
     287        /**
     288        * Replies true if {@code transferFlavors} includes the data flavor {@see PrimitiveIdTransferable#PRIMITIVE_ID_LIST_FLAVOR}.
     289
     290        * @param transferFlavors an array of transferFlavors
     291        * @return
     292        */
     293        protected boolean isSupportedFlavor(DataFlavor[] transferFlavors) {
     294            for (DataFlavor df: transferFlavors) {
     295                if (df.equals(PrimitiveIdTransferable.PRIMITIVE_ID_LIST_FLAVOR)) return true;
     296            }
     297            return false;
     298        }       
     299       
     300        public synchronized void dragEnter(DropTargetDragEvent dtde) {
     301            if (isSupportedFlavor(dtde.getCurrentDataFlavors())) {
     302                if ((dtde.getSourceActions() & DnDConstants.ACTION_COPY_OR_MOVE) != 0){
     303                    dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);     
     304                    setColumnSelectionAllowed(false);
     305                    dropAccepted  = true;
     306                } else {
     307                    dtde.rejectDrag();
     308                }
     309            } else {
     310                dtde.rejectDrag();
     311            }
     312        }
     313       
     314        public synchronized void dragExit(DropTargetEvent dte) {
     315            setColumnSelectionAllowed(true);
     316            dropAccepted = false;
     317        }
     318       
     319        @Override
     320        public synchronized void dragOver(DropTargetDragEvent dtde) {
     321            int row = rowAtPoint(dtde.getLocation());
     322            int selectedRow = getSelectionModel().getMinSelectionIndex();
     323            if (row >= 0 && row != selectedRow){
     324                getSelectionModel().setSelectionInterval(row, row);
     325            }           
     326        }
     327
     328        public synchronized void drop(DropTargetDropEvent dtde) {
     329            try {
     330                if (!dropAccepted) return;
     331                if ((dtde.getSourceActions() & DnDConstants.ACTION_COPY_OR_MOVE) == 0) {
     332                    return;
     333                }
     334                List<PrimitiveId> ids;
     335                ids = (List<PrimitiveId>)dtde.getTransferable().getTransferData(PrimitiveIdTransferable.PRIMITIVE_ID_LIST_FLAVOR);
     336                try {
     337                    model.getRelationMemberEditorModel().insertMembers(ids);
     338                } catch(IllegalArgumentException e){
     339                    e.printStackTrace();
     340                    // FIXME: provide user feedback
     341                }
     342            } catch(IOException e){
     343                e.printStackTrace();
     344            } catch(UnsupportedFlavorException e){
     345                e.printStackTrace();
     346            } finally {
     347                setColumnSelectionAllowed(true);
     348            }
     349        }
     350       
     351        public synchronized void dropActionChanged(DropTargetDragEvent dtde) {
     352            if ((dtde.getSourceActions() & DnDConstants.ACTION_COPY_OR_MOVE) == 0) {
     353                dtde.rejectDrag();
     354            } else {
     355                dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
     356            }
     357        }
     358    }
    359359}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/RelationMemberTargetCellRenderer.java

    r20724 r23192  
    1111
    1212public class RelationMemberTargetCellRenderer extends OsmPrimitivRenderer{
    13         static private final Logger logger = Logger.getLogger(RelationMemberTargetCellRenderer.class.getName());
    14         private JLabel mockCell;
    15        
    16         public RelationMemberTargetCellRenderer() {
    17                 mockCell = new JLabel();
    18                 mockCell.setText("");
    19                 mockCell.setOpaque(true);
    20         }
    21        
    22         @Override
    23         public Component getTableCellRendererComponent(JTable table, Object value,
    24                         boolean isSelected, boolean hasFocus, int row, int column) {
    25                 if (value != null){
    26                         return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    27                 }
    28                
    29                 // FIXME: required to always draw a mock row, even if the table is empty.
    30                 // Otherwise, drag and drop onto the table fails.
    31                 // Replace with JTable.setFillsViewportHeight(boolean) after the migration
    32                 // to Java 6.
    33                 if (isSelected){
    34                         mockCell.setBackground(UIManager.getColor("Table.selectionBackground"));
    35                         mockCell.setForeground(UIManager.getColor("Table.selectionForeground"));
    36                 } else {
    37                         mockCell.setBackground(UIManager.getColor("Panel.background"));
    38                         mockCell.setForeground(UIManager.getColor("Panel.foreground"));
    39                 }               
    40                 return mockCell;               
    41         }
     13    static private final Logger logger = Logger.getLogger(RelationMemberTargetCellRenderer.class.getName());
     14    private JLabel mockCell;
     15   
     16    public RelationMemberTargetCellRenderer() {
     17        mockCell = new JLabel();
     18        mockCell.setText("");
     19        mockCell.setOpaque(true);
     20    }
     21   
     22    @Override
     23    public Component getTableCellRendererComponent(JTable table, Object value,
     24            boolean isSelected, boolean hasFocus, int row, int column) {
     25        if (value != null){
     26            return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
     27        }
     28       
     29        // FIXME: required to always draw a mock row, even if the table is empty.
     30        // Otherwise, drag and drop onto the table fails.
     31        // Replace with JTable.setFillsViewportHeight(boolean) after the migration
     32        // to Java 6.
     33        if (isSelected){
     34            mockCell.setBackground(UIManager.getColor("Table.selectionBackground"));
     35            mockCell.setForeground(UIManager.getColor("Table.selectionForeground"));
     36        } else {
     37            mockCell.setBackground(UIManager.getColor("Panel.background"));
     38            mockCell.setForeground(UIManager.getColor("Panel.foreground"));
     39        }       
     40        return mockCell;       
     41    }
    4242}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/TurnRestrictionComboBox.java

    r20666 r23192  
    99 */
    1010public class TurnRestrictionComboBox extends JComboBox{
    11        
    12         /**
    13         * Constructor
    14         *
    15         * @param model the combo box model. Must not be null.
    16         */
    17         public TurnRestrictionComboBox(TurnRestrictionComboBoxModel model){
    18                 super(model);
    19                 setEditable(false);
    20                 setRenderer(new TurnRestrictionTypeRenderer());
    21         }
    22        
    23         /**
    24         * Replies the turn restriction combo box model
    25         *
    26         * @return the turn restriction combo box model
    27         */
    28         public TurnRestrictionComboBoxModel getTurnRestrictionComboBoxModel() {
    29                 return (TurnRestrictionComboBoxModel)getModel();
    30         }
    31        
    32         /**
    33         * Initializes the set of icons used from the preference key
    34         * {@see PreferenceKeys#ROAD_SIGNS}.
    35         *
    36         * @param prefs the JOSM preferences
    37         */
    38         public void initIconSetFromPreferences(Preferences prefs){
    39                 TurnRestrictionTypeRenderer renderer = (TurnRestrictionTypeRenderer)getRenderer();
    40                 renderer.initIconSetFromPreferences(prefs);
    41                 repaint();
    42         }
     11   
     12    /**
     13    * Constructor
     14    *
     15    * @param model the combo box model. Must not be null.
     16    */
     17    public TurnRestrictionComboBox(TurnRestrictionComboBoxModel model){
     18        super(model);
     19        setEditable(false);
     20        setRenderer(new TurnRestrictionTypeRenderer());
     21    }
     22   
     23    /**
     24    * Replies the turn restriction combo box model
     25    *
     26    * @return the turn restriction combo box model
     27    */
     28    public TurnRestrictionComboBoxModel getTurnRestrictionComboBoxModel() {
     29        return (TurnRestrictionComboBoxModel)getModel();
     30    }
     31   
     32    /**
     33    * Initializes the set of icons used from the preference key
     34    * {@see PreferenceKeys#ROAD_SIGNS}.
     35    *
     36    * @param prefs the JOSM preferences
     37    */
     38    public void initIconSetFromPreferences(Preferences prefs){
     39        TurnRestrictionTypeRenderer renderer = (TurnRestrictionTypeRenderer)getRenderer();
     40        renderer.initIconSetFromPreferences(prefs);
     41        repaint();
     42    }
    4343}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/TurnRestrictionComboBoxModel.java

    r20606 r23192  
    2121 */
    2222public class TurnRestrictionComboBoxModel implements ComboBoxModel, Observer{
    23         static private final Logger logger = Logger.getLogger(TurnRestrictionComboBoxModel.class.getName());
    24        
    25         private TurnRestrictionEditorModel model;
    26         final private List<Object> values = new ArrayList<Object>();
    27         private String selectedTagValue = null;
    28         private final transient EventListenerList listeners = new EventListenerList();
    29        
    30         /**
    31         * Populates the model with the list of standard values. If the
    32         * data contains a non-standard value it is displayed in the combo
    33         * box as an additional element.
    34         */
    35         protected void populate() {
    36                 values.clear();
    37                 for (TurnRestrictionType type: TurnRestrictionType.values()) {
    38                         values.add(type);
    39                 }               
    40                
    41                 String tagValue = model.getRestrictionTagValue();
    42                 if (tagValue.trim().equals("")) {
    43                         selectedTagValue = null;
    44                 } else {
    45                         TurnRestrictionType type = TurnRestrictionType.fromTagValue(tagValue);
    46                         if (type == null) {
    47                                 values.add(0, tagValue);
    48                                 selectedTagValue = tagValue;
    49                         } else {
    50                                 selectedTagValue = type.getTagValue();
    51                         }
    52                 }
    53                 fireContentsChanged();
    54         }
    55        
    56         /**
    57         * Creates the combo box model.
    58         *
    59         * @param model the turn restriction editor model. Must not be null.
    60         */
    61         public TurnRestrictionComboBoxModel(TurnRestrictionEditorModel model){
    62                 CheckParameterUtil.ensureParameterNotNull(model, "model");
    63                 this.model = model;
    64                 model.addObserver(this);
    65                 populate();
    66         }
     23    static private final Logger logger = Logger.getLogger(TurnRestrictionComboBoxModel.class.getName());
     24   
     25    private TurnRestrictionEditorModel model;
     26    final private List<Object> values = new ArrayList<Object>();
     27    private String selectedTagValue = null;
     28    private final transient EventListenerList listeners = new EventListenerList();
     29   
     30    /**
     31    * Populates the model with the list of standard values. If the
     32    * data contains a non-standard value it is displayed in the combo
     33    * box as an additional element.
     34    */
     35    protected void populate() {
     36        values.clear();
     37        for (TurnRestrictionType type: TurnRestrictionType.values()) {
     38            values.add(type);
     39        }       
     40       
     41        String tagValue = model.getRestrictionTagValue();
     42        if (tagValue.trim().equals("")) {
     43            selectedTagValue = null;
     44        } else {
     45            TurnRestrictionType type = TurnRestrictionType.fromTagValue(tagValue);
     46            if (type == null) {
     47                values.add(0, tagValue);
     48                selectedTagValue = tagValue;
     49            } else {
     50                selectedTagValue = type.getTagValue();
     51            }
     52        }
     53        fireContentsChanged();
     54    }
     55   
     56    /**
     57    * Creates the combo box model.
     58    *
     59    * @param model the turn restriction editor model. Must not be null.
     60    */
     61    public TurnRestrictionComboBoxModel(TurnRestrictionEditorModel model){
     62        CheckParameterUtil.ensureParameterNotNull(model, "model");
     63        this.model = model;
     64        model.addObserver(this);
     65        populate();
     66    }
    6767
    68         public Object getSelectedItem() {
    69                 TurnRestrictionType type = TurnRestrictionType.fromTagValue(selectedTagValue);
    70                 if (type != null) return type;
    71                 return selectedTagValue;
    72         }
     68    public Object getSelectedItem() {
     69        TurnRestrictionType type = TurnRestrictionType.fromTagValue(selectedTagValue);
     70        if (type != null) return type;
     71        return selectedTagValue;
     72    }
    7373
    74         public void setSelectedItem(Object anItem) {
    75                 String tagValue = null;
    76                 if (anItem instanceof String) {
    77                         tagValue = (String)anItem;
    78                 } else if (anItem instanceof TurnRestrictionType){
    79                         tagValue = ((TurnRestrictionType)anItem).getTagValue();
    80                 }
    81                 model.setRestrictionTagValue(tagValue);
    82         }
     74    public void setSelectedItem(Object anItem) {
     75        String tagValue = null;
     76        if (anItem instanceof String) {
     77            tagValue = (String)anItem;
     78        } else if (anItem instanceof TurnRestrictionType){
     79            tagValue = ((TurnRestrictionType)anItem).getTagValue();
     80        }
     81        model.setRestrictionTagValue(tagValue);
     82    }
    8383
    84         public Object getElementAt(int index) {
    85                 return values.get(index);
    86         }
     84    public Object getElementAt(int index) {
     85        return values.get(index);
     86    }
    8787
    88         public int getSize() {
    89                 return values.size();
    90         }
    91        
    92         public void addListDataListener(ListDataListener l) {
    93                 listeners.add(ListDataListener.class, l);               
    94         }
    95        
    96         public void removeListDataListener(ListDataListener l) {
    97                 listeners.remove(ListDataListener.class, l);           
    98         }
    99        
    100         protected void fireContentsChanged() {
    101                 for(ListDataListener l: listeners.getListeners(ListDataListener.class)) {
    102                         l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, 0, getSize()));
    103                 }
    104         }
    105        
    106         /* ------------------------------------------------------------------------------------ */
    107         /* interface Observer                                                                   */
    108         /* ------------------------------------------------------------------------------------ */
    109         public void update(Observable o, Object arg) {         
    110                 String tagValue = model.getRestrictionTagValue();
    111                 if (tagValue == null && selectedTagValue != null) {
    112                         populate();
    113                 } else if (tagValue != null && selectedTagValue == null){
    114                         populate();
    115                 } else if (tagValue != null) {
    116                         if (!tagValue.equals(selectedTagValue)) {
    117                                 populate();
    118                         }
    119                 }
    120         }
     88    public int getSize() {
     89        return values.size();
     90    }
     91   
     92    public void addListDataListener(ListDataListener l) {
     93        listeners.add(ListDataListener.class, l);       
     94    }
     95   
     96    public void removeListDataListener(ListDataListener l) {
     97        listeners.remove(ListDataListener.class, l);       
     98    }
     99   
     100    protected void fireContentsChanged() {
     101        for(ListDataListener l: listeners.getListeners(ListDataListener.class)) {
     102            l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, 0, getSize()));
     103        }
     104    }
     105   
     106    /* ------------------------------------------------------------------------------------ */
     107    /* interface Observer                                                                   */
     108    /* ------------------------------------------------------------------------------------ */
     109    public void update(Observable o, Object arg) {     
     110        String tagValue = model.getRestrictionTagValue();
     111        if (tagValue == null && selectedTagValue != null) {
     112            populate();
     113        } else if (tagValue != null && selectedTagValue == null){
     114            populate();
     115        } else if (tagValue != null) {
     116            if (!tagValue.equals(selectedTagValue)) {
     117                populate();
     118            }
     119        }
     120    }
    121121}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/TurnRestrictionEditor.java

    r20916 r23192  
    5858
    5959public class TurnRestrictionEditor extends JDialog implements NavigationControler{
    60         final private static Logger logger = Logger.getLogger(TurnRestrictionEditor.class.getName());
    61        
     60    final private static Logger logger = Logger.getLogger(TurnRestrictionEditor.class.getName());
     61   
    6262    /** the property name for the current turn restriction
    6363     * @see #setRelation(Relation)
     
    8484    /** the data layer the turn restriction belongs to */
    8585    private OsmDataLayer layer;
    86        
     86   
    8787    private JosmSelectionPanel pnlJosmSelection;
    8888    private BasicEditorPanel pnlBasicEditor;
     
    114114     */
    115115    protected JPanel buildJOSMSelectionPanel() {
    116         pnlJosmSelection = new JosmSelectionPanel(layer);
    117         return pnlJosmSelection;
     116        pnlJosmSelection = new JosmSelectionPanel(layer);
     117        return pnlJosmSelection;
    118118    }
    119119   
     
    125125     */
    126126    protected JPanel buildEditorPanel() {
    127         JPanel pnl = new JPanel(new BorderLayout());
    128         tpEditors = new JTabbedPane();
    129         JScrollPane pane = new JScrollPane(pnlBasicEditor =new BasicEditorPanel(editorModel));
    130         pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    131         pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
    132         tpEditors.add(pane);
    133         tpEditors.setTitleAt(0, tr("Basic"));
    134         tpEditors.setToolTipTextAt(0, tr("Edit basic attributes of a turn restriction"));
    135        
    136         tpEditors.add(pnlAdvancedEditor = new AdvancedEditorPanel(editorModel));
    137         tpEditors.setTitleAt(1, tr("Advanced"));
    138         tpEditors.setToolTipTextAt(1, tr("Edit the raw tags and members of this turn restriction"));
    139        
    140         tpEditors.add(pnlIssuesView = new IssuesView(editorModel.getIssuesModel()));
    141         tpEditors.setTitleAt(2, tr("Errors/Warnings"));
    142         tpEditors.setToolTipTextAt(2, tr("Show errors and warnings related to this turn restriction"));
    143        
    144         pnl.add(tpEditors, BorderLayout.CENTER);
    145         return pnl;
     127        JPanel pnl = new JPanel(new BorderLayout());
     128        tpEditors = new JTabbedPane();
     129        JScrollPane pane = new JScrollPane(pnlBasicEditor =new BasicEditorPanel(editorModel));
     130        pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
     131        pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
     132        tpEditors.add(pane);
     133        tpEditors.setTitleAt(0, tr("Basic"));
     134        tpEditors.setToolTipTextAt(0, tr("Edit basic attributes of a turn restriction"));
     135       
     136        tpEditors.add(pnlAdvancedEditor = new AdvancedEditorPanel(editorModel));
     137        tpEditors.setTitleAt(1, tr("Advanced"));
     138        tpEditors.setToolTipTextAt(1, tr("Edit the raw tags and members of this turn restriction"));
     139       
     140        tpEditors.add(pnlIssuesView = new IssuesView(editorModel.getIssuesModel()));
     141        tpEditors.setTitleAt(2, tr("Errors/Warnings"));
     142        tpEditors.setToolTipTextAt(2, tr("Show errors and warnings related to this turn restriction"));
     143       
     144        pnl.add(tpEditors, BorderLayout.CENTER);
     145        return pnl;
    146146    }
    147147   
     
    153153     */
    154154    protected JPanel buildContentPanel() {
    155         JPanel pnl = new JPanel(new BorderLayout());
    156         final JSplitPane sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
    157         pnl.add(sp, BorderLayout.CENTER);
    158         sp.setLeftComponent(buildEditorPanel());
    159         sp.setRightComponent(buildJOSMSelectionPanel());
     155        JPanel pnl = new JPanel(new BorderLayout());
     156        final JSplitPane sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
     157        pnl.add(sp, BorderLayout.CENTER);
     158        sp.setLeftComponent(buildEditorPanel());
     159        sp.setRightComponent(buildJOSMSelectionPanel());
    160160        addWindowListener(new WindowAdapter() {
    161161            @Override
     
    167167        });
    168168
    169         return pnl;
     169        return pnl;
    170170    }
    171171   
     
    197197     * builds the UI
    198198     */
    199     protected void build() {           
    200         editorModel = new TurnRestrictionEditorModel(getLayer(), this);
    201         Container c = getContentPane();
    202         c.setLayout(new BorderLayout());
    203         c.add(buildToolBar(), BorderLayout.NORTH);
    204         c.add(buildContentPanel(), BorderLayout.CENTER);       
    205         c.add(buildOkCancelButtonPanel(), BorderLayout.SOUTH);
    206        
    207         editorModel.getIssuesModel().addObserver(new IssuesModelObserver());
    208         setSize(600,600);       
     199    protected void build() {       
     200        editorModel = new TurnRestrictionEditorModel(getLayer(), this);
     201        Container c = getContentPane();
     202        c.setLayout(new BorderLayout());
     203        c.add(buildToolBar(), BorderLayout.NORTH);
     204        c.add(buildContentPanel(), BorderLayout.CENTER);       
     205        c.add(buildOkCancelButtonPanel(), BorderLayout.SOUTH);
     206       
     207        editorModel.getIssuesModel().addObserver(new IssuesModelObserver());
     208        setSize(600,600);       
    209209    }   
    210        
    211         /**
     210   
     211    /**
    212212    * Creates a new turn restriction editor
    213213    *
     
    216216    * @throws IllegalArgumentException thrown if layer is null
    217217    */
    218         public TurnRestrictionEditor(Component owner, OsmDataLayer layer) {
    219                 this(owner, layer, null);
    220         }
    221        
    222         /**
     218    public TurnRestrictionEditor(Component owner, OsmDataLayer layer) {
     219        this(owner, layer, null);
     220    }
     221   
     222    /**
    223223     * Creates a new turn restriction editor
    224224     *
     
    229229     */
    230230    public TurnRestrictionEditor(Component owner, OsmDataLayer layer, Relation turnRestriction)  throws IllegalArgumentException{
    231         super(JOptionPane.getFrameForComponent(owner),false /* not modal */);
     231        super(JOptionPane.getFrameForComponent(owner),false /* not modal */);
    232232        CheckParameterUtil.ensureParameterNotNull(layer, "layer");
    233233        this.layer = layer;
     
    260260    protected void setTurnRestriction(Relation turnRestriction) {     
    261261        if (turnRestriction == null) {
    262                 editorModel.populate(new Relation());
     262            editorModel.populate(new Relation());
    263263        } else if (turnRestriction.getDataSet() == null || turnRestriction.getDataSet() == getLayer().data) {
    264                 editorModel.populate(turnRestriction);
     264            editorModel.populate(turnRestriction);
    265265        } else {
    266                 throw new IllegalArgumentException(MessageFormat.format("turnRestriction must belong to layer ''{0}''", getLayer().getName()));
     266            throw new IllegalArgumentException(MessageFormat.format("turnRestriction must belong to layer ''{0}''", getLayer().getName()));
    267267        }
    268268        setTurnRestrictionSnapshot(turnRestriction == null ? null : new Relation(turnRestriction));
     
    332332     */
    333333    public TurnRestrictionEditorModel getModel() {
    334         return editorModel;
     334        return editorModel;
    335335    }
    336336   
    337337    public void setVisible(boolean visible) {
    338         if (visible && ! isVisible()) {
    339                 pnlJosmSelection.wireListeners();
    340                 editorModel.registerAsEventListener();
    341                 Main.pref.addPreferenceChangeListener(this.preferenceChangeHandler = new PreferenceChangeHandler());
    342                 pnlBasicEditor.initIconSetFromPreferences(Main.pref);
    343         } else if (!visible && isVisible()) {
    344                 pnlJosmSelection.unwireListeners();
    345                 editorModel.unregisterAsEventListener();
    346                 Main.pref.removePreferenceChangeListener(preferenceChangeHandler);
    347         }
    348         super.setVisible(visible);
    349         if (!visible){
    350                 dispose();
    351         }
     338        if (visible && ! isVisible()) {
     339            pnlJosmSelection.wireListeners();
     340            editorModel.registerAsEventListener();
     341            Main.pref.addPreferenceChangeListener(this.preferenceChangeHandler = new PreferenceChangeHandler());
     342            pnlBasicEditor.initIconSetFromPreferences(Main.pref);
     343        } else if (!visible && isVisible()) {
     344            pnlJosmSelection.unwireListeners();
     345            editorModel.unregisterAsEventListener();
     346            Main.pref.removePreferenceChangeListener(preferenceChangeHandler);
     347        }
     348        super.setVisible(visible);
     349        if (!visible){
     350            dispose();
     351        }
    352352    }
    353353   
     
    371371    /* ----------------------------------------------------------------------- */
    372372    public void gotoBasicEditor() {
    373         tpEditors.setSelectedIndex(0);
    374         }
     373        tpEditors.setSelectedIndex(0);
     374    }
    375375
    376376    public void gotoAdvancedEditor() {
    377         tpEditors.setSelectedIndex(1);
    378         }
    379 
    380         public void gotoBasicEditor(BasicEditorFokusTargets focusTarget) {
    381                 tpEditors.setSelectedIndex(0);
    382                 pnlBasicEditor.requestFocusFor(focusTarget);
    383         }
    384 
    385         /**
     377        tpEditors.setSelectedIndex(1);
     378    }
     379
     380    public void gotoBasicEditor(BasicEditorFokusTargets focusTarget) {
     381        tpEditors.setSelectedIndex(0);
     382        pnlBasicEditor.requestFocusFor(focusTarget);
     383    }
     384
     385    /**
    386386     * The abstract base action for applying the updates of a turn restriction
    387387     * to the dataset.
    388388     */
    389     abstract class SavingAction extends AbstractAction {       
    390         protected boolean confirmSaveDespiteOfErrorsAndWarnings(){
    391                 int numErrors = editorModel.getIssuesModel().getNumErrors();
    392                 int numWarnings = editorModel.getIssuesModel().getNumWarnings();
    393                 if (numErrors + numWarnings == 0) return true;
    394                
    395                 StringBuffer sb = new StringBuffer();
    396                 sb.append("<html>");
    397                 sb.append(trn(
    398                                 "There is still an unresolved error or warning identified for this turn restriction. "
    399                                 + "You are recommended to resolve this issue first.",
    400                                   "There are still {0} errors and/or warnings identified for this turn restriction. "
    401                                 + "You are recommended to resolve these issues first.",
    402                                   numErrors + numWarnings,
    403                                   numErrors + numWarnings
    404                 ));
    405                 sb.append("<br>");
    406                 sb.append(tr("Do you want to save anyway?"));
    407                 ButtonSpec[] options = new ButtonSpec[] {
    408                                 new ButtonSpec(
    409                                                 tr("Yes, save anyway"),
    410                                                 ImageProvider.get("ok"),
    411                                                 tr("Save the turn restriction despite of errors and/or warnings"),
    412                                                 null // no specific help topic
    413                                 ),
    414                                 new ButtonSpec(
    415                                                 tr("No, resolve issues first"),
    416                                                 ImageProvider.get("cancel"),
    417                                                 tr("Cancel saving and start resolving pending issues first"),
    418                                                 null // no specific help topic
    419                                 )
    420                 };
    421                
    422                 int ret = HelpAwareOptionPane.showOptionDialog(
    423                                 JOptionPane.getFrameForComponent(TurnRestrictionEditor.this),
    424                                 sb.toString(),
    425                                 tr("Pending errors and warnings"),
    426                                 JOptionPane.WARNING_MESSAGE,
    427                                 null, // no special icon
    428                                 options,
    429                                 options[1], // cancel is default operation
    430                                 HelpUtil.ht("/Plugins/turnrestrictions#PendingErrorsAndWarnings")
    431                 );
    432                 return ret == 0 /* OK */;               
    433         }
    434        
    435         /**
    436         * Replies the list of relation members in {@code r} which refer to
    437         * a deleted or invisible primitives.
    438         *
    439         * @param r the relation
    440         * @return the list of relation members in {@code r} which refer to
    441         * a deleted or invisible member
    442         */
    443         protected List<RelationMember> getDeletedRelationMembers(Relation r) {
    444                 List<RelationMember> ret = new ArrayList<RelationMember>();
    445                 for(RelationMember rm: r.getMembers()) {
    446                         if (rm.getMember().isDeleted() || !rm.getMember().isVisible()) {
    447                                 ret.add(rm);
    448                         }
    449                 }
    450                 return ret;
    451         }
    452        
    453         /**
    454         * Removes all members referring to deleted or invisible primitives
    455         * from the turn restriction {@code tr}.
    456         *
    457         * @param tr  the turn restriction
    458         */
    459         protected void removeDeletedMembers(Relation tr) {
    460                 List<RelationMember> members = tr.getMembers();
    461                 for(Iterator<RelationMember> it = members.iterator(); it.hasNext();) {
    462                         RelationMember rm = it.next();
    463                         if (rm.getMember().isDeleted() || !rm.getMember().isVisible()) {
    464                                 it.remove();
    465                         }
    466                 }
    467                 tr.setMembers(members);
    468         }
    469        
    470         /**
    471         * Asks the user how to proceed if a turn restriction refers to deleted or invisible
    472         * primitives.
    473         *
    474         * If this method returns true the respective members should be removed and the turn
    475         * restriction should be saved anyway. If it replies false, the turn restriction must not
    476         * be saved. 
    477         *
    478         * @param deletedMembers the list of members referring to deleted or invisible primitives 
    479         * @return the confirmation
    480         */
    481         protected boolean confirmSaveTurnRestrictionWithDeletePrimitives(List<RelationMember> deletedMembers) {                                 
    482                 StringBuffer sb = new StringBuffer();
    483                 sb.append("<html>");
    484                 sb.append(trn("This turn restriction refers to an object which was deleted outside "
    485                            + "of this turn restriction editor:",
    486                            "This turn restriction refers to {0} which were deleted outside "
    487                            + "of this turn restriction editor:", deletedMembers.size(), deletedMembers.size()));
    488                 sb.append("<ul>");
    489                 for(RelationMember rm: deletedMembers){
    490                         sb.append("<li>");
    491                         if (!rm.getRole().equals("")) {
    492                                 sb.append(rm.getRole()).append(": ");
    493                         }
    494                         sb.append(rm.getMember().getDisplayName(DefaultNameFormatter.getInstance()));
    495                         sb.append("</li>");
    496                 }
    497                 sb.append(tr("Updates to this turn restriction can''t be saved unless deleted members are removed.<br>"
    498                                 + "How to you want to proceed?"));
    499                
    500                 ButtonSpec[] options = new ButtonSpec[] {
    501                                 new ButtonSpec(
    502                                         tr("Remove deleted members and save"),
    503                                         ImageProvider.get("OK"),
    504                                         tr("Remove deleted members and save"),
    505                                         null
    506                              ),
    507                                   new ButtonSpec(
    508                                                 tr("Cancel and return to editor"),
    509                                                 ImageProvider.get("cancel"),
    510                                                 tr("Cancel and return to editor"),
    511                                                 null
    512                                    )
    513                 };
    514                
    515                 int ret = HelpAwareOptionPane.showOptionDialog(
    516                                 TurnRestrictionEditor.this,
    517                                 sb.toString(),
    518                                 tr("Deleted members in turn restriction"),
    519                                 JOptionPane.WARNING_MESSAGE,
    520                                 null, // no special icon
    521                                 options,
    522                                 options[1], // cancel is default
    523                                 null // FIXME: provide help topic
    524                 );             
    525                 return ret == 0 /* OK button */;
    526         }
    527        
     389    abstract class SavingAction extends AbstractAction {       
     390        protected boolean confirmSaveDespiteOfErrorsAndWarnings(){
     391            int numErrors = editorModel.getIssuesModel().getNumErrors();
     392            int numWarnings = editorModel.getIssuesModel().getNumWarnings();
     393            if (numErrors + numWarnings == 0) return true;
     394           
     395            StringBuffer sb = new StringBuffer();
     396            sb.append("<html>");
     397            sb.append(trn(
     398                "There is still an unresolved error or warning identified for this turn restriction. "
     399                    + "You are recommended to resolve this issue first.",
     400                  "There are still {0} errors and/or warnings identified for this turn restriction. "
     401                    + "You are recommended to resolve these issues first.",
     402                  numErrors + numWarnings,
     403                  numErrors + numWarnings
     404            ));
     405            sb.append("<br>");
     406            sb.append(tr("Do you want to save anyway?"));
     407            ButtonSpec[] options = new ButtonSpec[] {
     408                    new ButtonSpec(
     409                            tr("Yes, save anyway"),
     410                            ImageProvider.get("ok"),
     411                            tr("Save the turn restriction despite of errors and/or warnings"),
     412                            null // no specific help topic
     413                    ),
     414                    new ButtonSpec(
     415                            tr("No, resolve issues first"),
     416                            ImageProvider.get("cancel"),
     417                            tr("Cancel saving and start resolving pending issues first"),
     418                            null // no specific help topic
     419                    )
     420            };
     421           
     422            int ret = HelpAwareOptionPane.showOptionDialog(
     423                    JOptionPane.getFrameForComponent(TurnRestrictionEditor.this),
     424                    sb.toString(),
     425                    tr("Pending errors and warnings"),
     426                    JOptionPane.WARNING_MESSAGE,
     427                    null, // no special icon
     428                    options,
     429                    options[1], // cancel is default operation
     430                    HelpUtil.ht("/Plugins/turnrestrictions#PendingErrorsAndWarnings")
     431            );
     432            return ret == 0 /* OK */;           
     433        }
     434       
     435        /**
     436        * Replies the list of relation members in {@code r} which refer to
     437        * a deleted or invisible primitives.
     438        *
     439        * @param r the relation
     440        * @return the list of relation members in {@code r} which refer to
     441        * a deleted or invisible member
     442        */
     443        protected List<RelationMember> getDeletedRelationMembers(Relation r) {
     444            List<RelationMember> ret = new ArrayList<RelationMember>();
     445            for(RelationMember rm: r.getMembers()) {
     446                if (rm.getMember().isDeleted() || !rm.getMember().isVisible()) {
     447                    ret.add(rm);
     448                }
     449            }
     450            return ret;
     451        }
     452       
     453        /**
     454        * Removes all members referring to deleted or invisible primitives
     455        * from the turn restriction {@code tr}.
     456        *
     457        * @param tr  the turn restriction
     458        */
     459        protected void removeDeletedMembers(Relation tr) {
     460            List<RelationMember> members = tr.getMembers();
     461            for(Iterator<RelationMember> it = members.iterator(); it.hasNext();) {
     462                RelationMember rm = it.next();
     463                if (rm.getMember().isDeleted() || !rm.getMember().isVisible()) {
     464                    it.remove();
     465                }
     466            }
     467            tr.setMembers(members);
     468        }
     469       
     470        /**
     471        * Asks the user how to proceed if a turn restriction refers to deleted or invisible
     472        * primitives.
     473        *
     474        * If this method returns true the respective members should be removed and the turn
     475        * restriction should be saved anyway. If it replies false, the turn restriction must not
     476        * be saved. 
     477        *
     478        * @param deletedMembers the list of members referring to deleted or invisible primitives 
     479        * @return the confirmation
     480        */
     481        protected boolean confirmSaveTurnRestrictionWithDeletePrimitives(List<RelationMember> deletedMembers) {                     
     482            StringBuffer sb = new StringBuffer();
     483            sb.append("<html>");
     484            sb.append(trn("This turn restriction refers to an object which was deleted outside "
     485                       + "of this turn restriction editor:",
     486                       "This turn restriction refers to {0} which were deleted outside "
     487                       + "of this turn restriction editor:", deletedMembers.size(), deletedMembers.size()));
     488            sb.append("<ul>");
     489            for(RelationMember rm: deletedMembers){
     490                sb.append("<li>");
     491                if (!rm.getRole().equals("")) {
     492                    sb.append(rm.getRole()).append(": ");
     493                }
     494                sb.append(rm.getMember().getDisplayName(DefaultNameFormatter.getInstance()));
     495                sb.append("</li>");
     496            }
     497            sb.append(tr("Updates to this turn restriction can''t be saved unless deleted members are removed.<br>"
     498                    + "How to you want to proceed?"));
     499           
     500            ButtonSpec[] options = new ButtonSpec[] {
     501                    new ButtonSpec(
     502                        tr("Remove deleted members and save"),
     503                        ImageProvider.get("OK"),
     504                        tr("Remove deleted members and save"),
     505                        null
     506                     ),
     507                      new ButtonSpec(
     508                            tr("Cancel and return to editor"),
     509                            ImageProvider.get("cancel"),
     510                            tr("Cancel and return to editor"),
     511                            null
     512                       )
     513            };
     514           
     515            int ret = HelpAwareOptionPane.showOptionDialog(
     516                    TurnRestrictionEditor.this,
     517                    sb.toString(),
     518                    tr("Deleted members in turn restriction"),
     519                    JOptionPane.WARNING_MESSAGE,
     520                    null, // no special icon
     521                    options,
     522                    options[1], // cancel is default
     523                    null // FIXME: provide help topic
     524            );         
     525            return ret == 0 /* OK button */;
     526        }
     527       
    528528        /**
    529529         * apply updates to a new turn restriction
    530530         */
    531         protected boolean applyNewTurnRestriction() {           
     531        protected boolean applyNewTurnRestriction() {           
    532532            Relation newTurnRestriction = new Relation();
    533533            editorModel.apply(newTurnRestriction);
     
    541541            List<RelationMember> deletedMembers = getDeletedRelationMembers(newTurnRestriction);
    542542            if (!deletedMembers.isEmpty()) {
    543                 if (!confirmSaveTurnRestrictionWithDeletePrimitives(deletedMembers)) {
    544                         return false;
    545                 }
    546                 removeDeletedMembers(newTurnRestriction);
     543                if (!confirmSaveTurnRestrictionWithDeletePrimitives(deletedMembers)) {
     544                    return false;
     545                }
     546                removeDeletedMembers(newTurnRestriction);
    547547            }
    548548           
     
    576576         * outside of the turn restriction editor.
    577577         */
    578         protected void applyExistingNonConflictingTurnRestriction() {           
     578        protected void applyExistingNonConflictingTurnRestriction() {           
    579579            if (getTurnRestriction().getDataSet() == null) {
    580                 editorModel.apply(getTurnRestriction());
    581                 Main.main.undoRedo.add(new AddCommand(getTurnRestriction()));
     580                editorModel.apply(getTurnRestriction());
     581                Main.main.undoRedo.add(new AddCommand(getTurnRestriction()));
    582582            } else {
    583                 Relation toUpdate = new Relation(getTurnRestriction());
     583                Relation toUpdate = new Relation(getTurnRestriction());
    584584                editorModel.apply(toUpdate);           
    585                 Main.main.undoRedo.add(new ChangeCommand(getTurnRestriction(), toUpdate));
     585                Main.main.undoRedo.add(new ChangeCommand(getTurnRestriction(), toUpdate));
    586586            }
    587587            // this will refresh the snapshot and update the dialog title
     
    646646
    647647        public void run() {
    648                 if (!confirmSaveDespiteOfErrorsAndWarnings()){
    649                         tpEditors.setSelectedIndex(2); // show the errors and warnings
    650                         return;
    651                 }
     648            if (!confirmSaveDespiteOfErrorsAndWarnings()){
     649                tpEditors.setSelectedIndex(2); // show the errors and warnings
     650                return;
     651            }
    652652            if (getTurnRestriction() == null) {
    653653                applyNewTurnRestriction();
     
    658658            editorModel.apply(toUpdate);
    659659            if (TurnRestrictionEditorModel.hasSameMembersAndTags(toUpdate, getTurnRestriction()))
    660                 // nothing to update
    661                 return;
     660                // nothing to update
     661                return;
    662662           
    663663            if (isDirtyTurnRestriction()) {
     
    689689
    690690        public void run() {
    691                 if (!confirmSaveDespiteOfErrorsAndWarnings()){
    692                         tpEditors.setSelectedIndex(2); // show the errors and warnings
    693                         return;
    694                 }
     691            if (!confirmSaveDespiteOfErrorsAndWarnings()){
     692                tpEditors.setSelectedIndex(2); // show the errors and warnings
     693                return;
     694            }
    695695            if (getTurnRestriction() == null) {
    696                 // it's a new turn restriction. Try to save it and close the dialog
     696                // it's a new turn restriction. Try to save it and close the dialog
    697697                if (applyNewTurnRestriction()) {
    698                         setVisible(false);
     698                    setVisible(false);
    699699                }
    700700                return;
     
    704704            editorModel.apply(toUpdate);
    705705            if (TurnRestrictionEditorModel.hasSameMembersAndTags(toUpdate, getTurnRestriction())){
    706                 // nothing to update
    707                 setVisible(false);
    708                 return;
     706                // nothing to update
     707                setVisible(false);
     708                return;
    709709            }
    710710           
    711711            if (isDirtyTurnRestriction()) {
    712                 // the turn restriction this editor is working on has changed outside
    713                 // of the editor.
     712                // the turn restriction this editor is working on has changed outside
     713                // of the editor.
    714714                if (confirmClosingBecauseOfDirtyState()) {
    715715                    if (getLayer().getConflicts().hasConflictForMy(getTurnRestriction())) {
     
    750750   
    751751    class DeleteAction extends AbstractAction implements PropertyChangeListener{
    752         public DeleteAction() {
    753                 putValue(NAME, tr("Delete"));
    754                 putValue(SHORT_DESCRIPTION, tr("Delete this turn restriction"));
    755                 putValue(SMALL_ICON, ImageProvider.get("dialogs", "delete"));
    756                 updateEnabledState();
    757         }
    758        
    759         protected void updateEnabledState() {                   
    760                 Relation tr = getTurnRestriction();
    761                 setEnabled(tr != null && tr.getDataSet() != null);
    762         }
    763 
    764         public void actionPerformed(ActionEvent e) {
    765                 Relation tr = getTurnRestriction();
    766                 if (tr == null || tr.getDataSet() == null) return;
    767                 org.openstreetmap.josm.actions.mapmode.DeleteAction.deleteRelation(
     752        public DeleteAction() {
     753            putValue(NAME, tr("Delete"));
     754            putValue(SHORT_DESCRIPTION, tr("Delete this turn restriction"));
     755            putValue(SMALL_ICON, ImageProvider.get("dialogs", "delete"));
     756            updateEnabledState();
     757        }
     758       
     759        protected void updateEnabledState() {           
     760            Relation tr = getTurnRestriction();
     761            setEnabled(tr != null && tr.getDataSet() != null);
     762        }
     763
     764        public void actionPerformed(ActionEvent e) {
     765            Relation tr = getTurnRestriction();
     766            if (tr == null || tr.getDataSet() == null) return;
     767            org.openstreetmap.josm.actions.mapmode.DeleteAction.deleteRelation(
    768768                    getLayer(),
    769769                    tr
    770770            );
    771                 setVisible(false);
    772                 }
    773 
    774                 public void propertyChange(PropertyChangeEvent evt) {
    775                         if (evt.getPropertyName().equals(TURN_RESTRICION_PROP)){
    776                                 updateEnabledState();
    777                         }
    778                 }
     771            setVisible(false);
     772        }
     773
     774        public void propertyChange(PropertyChangeEvent evt) {
     775            if (evt.getPropertyName().equals(TURN_RESTRICION_PROP)){
     776                updateEnabledState();
     777            }
     778        }
    779779    }
    780780   
    781781    class SelectAction extends AbstractAction implements PropertyChangeListener{
    782         public SelectAction() {
    783                 putValue(NAME, tr("Select"));
    784                 putValue(SHORT_DESCRIPTION, tr("Select this turn restriction"));
    785                 putValue(SMALL_ICON, ImageProvider.get("dialogs", "select"));
    786                 updateEnabledState();
    787         }
    788        
    789         protected void updateEnabledState() {
    790                 Relation tr = getTurnRestriction();
    791                 setEnabled(tr != null && tr.getDataSet() != null);
    792         }
    793 
    794         public void actionPerformed(ActionEvent e) {
    795                 Relation tr = getTurnRestriction();
    796                 if (tr == null || tr.getDataSet() == null) return;
    797                 getLayer().data.setSelected(tr);
    798                 }
    799 
    800                 public void propertyChange(PropertyChangeEvent evt) {
    801                         if (evt.getPropertyName().equals(TURN_RESTRICION_PROP)){
    802                                 updateEnabledState();
    803                         }
    804                 }
     782        public SelectAction() {
     783            putValue(NAME, tr("Select"));
     784            putValue(SHORT_DESCRIPTION, tr("Select this turn restriction"));
     785            putValue(SMALL_ICON, ImageProvider.get("dialogs", "select"));
     786            updateEnabledState();
     787        }
     788       
     789        protected void updateEnabledState() {
     790            Relation tr = getTurnRestriction();
     791            setEnabled(tr != null && tr.getDataSet() != null);
     792        }
     793
     794        public void actionPerformed(ActionEvent e) {
     795            Relation tr = getTurnRestriction();
     796            if (tr == null || tr.getDataSet() == null) return;
     797            getLayer().data.setSelected(tr);
     798        }
     799
     800        public void propertyChange(PropertyChangeEvent evt) {
     801            if (evt.getPropertyName().equals(TURN_RESTRICION_PROP)){
     802                updateEnabledState();
     803            }
     804        }
    805805    }
    806806   
    807807    class ZoomToAction extends AbstractAction implements PropertyChangeListener{
    808         public ZoomToAction() {
    809                 putValue(NAME, tr("Zoom to"));
    810                 putValue(SHORT_DESCRIPTION, tr("Activate the layer this turn restriction belongs to and zoom to it"));
    811                 putValue(SMALL_ICON, ImageProvider.get("dialogs/autoscale", "data"));
    812                 updateEnabledState();
    813         }
    814        
    815         protected void updateEnabledState() {
    816                 Relation tr = getTurnRestriction();
    817                 setEnabled(tr != null && tr.getDataSet() != null);
    818         }
    819 
    820         public void actionPerformed(ActionEvent e) {
    821                 if (Main.main.getActiveLayer() != getLayer()){
    822                         Main.map.mapView.setActiveLayer(getLayer());
    823                 }
    824                 Relation tr = getTurnRestriction();
    825                 if (tr == null || tr.getDataSet() == null) return;
    826                 getLayer().data.setSelected(tr);               
    827                 AutoScaleAction.zoomToSelection();
    828                 }
    829 
    830                 public void propertyChange(PropertyChangeEvent evt) {
    831                         if (evt.getPropertyName().equals(TURN_RESTRICION_PROP)){
    832                                 updateEnabledState();
    833                         }
    834                 }
     808        public ZoomToAction() {
     809            putValue(NAME, tr("Zoom to"));
     810            putValue(SHORT_DESCRIPTION, tr("Activate the layer this turn restriction belongs to and zoom to it"));
     811            putValue(SMALL_ICON, ImageProvider.get("dialogs/autoscale", "data"));
     812            updateEnabledState();
     813        }
     814       
     815        protected void updateEnabledState() {
     816            Relation tr = getTurnRestriction();
     817            setEnabled(tr != null && tr.getDataSet() != null);
     818        }
     819
     820        public void actionPerformed(ActionEvent e) {
     821            if (Main.main.getActiveLayer() != getLayer()){
     822                Main.map.mapView.setActiveLayer(getLayer());
     823            }
     824            Relation tr = getTurnRestriction();
     825            if (tr == null || tr.getDataSet() == null) return;
     826            getLayer().data.setSelected(tr);           
     827            AutoScaleAction.zoomToSelection();
     828        }
     829
     830        public void propertyChange(PropertyChangeEvent evt) {
     831            if (evt.getPropertyName().equals(TURN_RESTRICION_PROP)){
     832                updateEnabledState();
     833            }
     834        }
    835835    }
    836836   
    837837    class IssuesModelObserver implements Observer {
    838                 public void update(Observable o, Object arg) {
    839                         int numWarnings = editorModel.getIssuesModel().getNumWarnings();
    840                         int numErrors = editorModel.getIssuesModel().getNumErrors();
    841                         String warningText = null;
    842                         if (numWarnings > 0){
    843                                 warningText = trn("{0} warning", "{0} warnings", numWarnings, numWarnings);
    844                         }
    845                         String errorText = null;
    846                         if (numErrors > 0){
    847                                 errorText = trn("{0} error", "{0} errors", numErrors, numErrors);
    848                         }
    849                         String title = "";
    850                         if (errorText != null) {
    851                                 title += errorText;
    852                         }
    853                         if (warningText != null){
    854                                 if (title.length() > 0){
    855                                         title += "/";
    856                                 }
    857                                 title += warningText;
    858                         }
    859                         if (title.length() == 0){
    860                                 title = tr("no issues");
    861                         }
    862                         tpEditors.setTitleAt(2, title);
    863                         tpEditors.setEnabledAt(2, numWarnings + numErrors > 0);
    864                 }       
     838        public void update(Observable o, Object arg) {
     839            int numWarnings = editorModel.getIssuesModel().getNumWarnings();
     840            int numErrors = editorModel.getIssuesModel().getNumErrors();
     841            String warningText = null;
     842            if (numWarnings > 0){
     843                warningText = trn("{0} warning", "{0} warnings", numWarnings, numWarnings);
     844            }
     845            String errorText = null;
     846            if (numErrors > 0){
     847                errorText = trn("{0} error", "{0} errors", numErrors, numErrors);
     848            }
     849            String title = "";
     850            if (errorText != null) {
     851                title += errorText;
     852            }
     853            if (warningText != null){
     854                if (title.length() > 0){
     855                    title += "/";
     856                }
     857                title += warningText;
     858            }
     859            if (title.length() == 0){
     860                title = tr("no issues");
     861            }
     862            tpEditors.setTitleAt(2, title);
     863            tpEditors.setEnabledAt(2, numWarnings + numErrors > 0);
     864        }       
    865865    }
    866866   
     
    874874     *
    875875     */
    876     class PreferenceChangeHandler implements PreferenceChangedListener {       
    877         public void refreshIconSet() {
    878                 pnlBasicEditor.initIconSetFromPreferences(Main.pref);
    879         }
    880        
    881                 public void preferenceChanged(PreferenceChangeEvent evt) {                     
    882                         if (evt.getKey().equals(PreferenceKeys.ROAD_SIGNS)){
    883                                 refreshIconSet();
    884                         } else if (evt.getKey().equals(PreferenceKeys.SHOW_VIAS_IN_BASIC_EDITOR)) {
    885                                 pnlBasicEditor.initViasVisibilityFromPreferences(Main.pref);
    886                         }                       
    887                 }
     876    class PreferenceChangeHandler implements PreferenceChangedListener {       
     877        public void refreshIconSet() {
     878            pnlBasicEditor.initIconSetFromPreferences(Main.pref);
     879        }
     880       
     881        public void preferenceChanged(PreferenceChangeEvent evt) {         
     882            if (evt.getKey().equals(PreferenceKeys.ROAD_SIGNS)){
     883                refreshIconSet();
     884            } else if (evt.getKey().equals(PreferenceKeys.SHOW_VIAS_IN_BASIC_EDITOR)) {
     885                pnlBasicEditor.initViasVisibilityFromPreferences(Main.pref);
     886            }           
     887        }
    888888    }
    889889}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/TurnRestrictionEditorManager.java

    r20489 r23192  
    2323 */
    2424public class TurnRestrictionEditorManager extends WindowAdapter implements MapView.LayerChangeListener{
    25         static private final Logger logger = Logger.getLogger(TurnRestrictionEditorManager.class.getName());
     25    static private final Logger logger = Logger.getLogger(TurnRestrictionEditorManager.class.getName());
    2626
    2727    /** keeps track of open relation editors */
     
    5555
    5656        @Override
    57                 public int hashCode() {
    58                         final int prime = 31;
    59                         int result = 1;
    60                         result = prime * result + ((layer == null) ? 0 : layer.hashCode());
    61                         result = prime * result
    62                                         + ((primitiveId == null) ? 0 : primitiveId.hashCode());
    63                         return result;
    64                 }
    65 
    66                 @Override
    67                 public boolean equals(Object obj) {
    68                         if (this == obj)
    69                                 return true;
    70                         if (obj == null)
    71                                 return false;
    72                         if (getClass() != obj.getClass())
    73                                 return false;
    74                         DialogContext other = (DialogContext) obj;
    75                         if (layer == null) {
    76                                 if (other.layer != null)
    77                                         return false;
    78                         } else if (!layer.equals(other.layer))
    79                                 return false;
    80                         if (primitiveId == null) {
    81                                 if (other.primitiveId != null)
    82                                         return false;
    83                         } else if (!primitiveId.equals(other.primitiveId))
    84                                 return false;
    85                         return true;
    86                 }
    87 
    88                 public boolean matchesLayer(OsmDataLayer layer) {
     57        public int hashCode() {
     58            final int prime = 31;
     59            int result = 1;
     60            result = prime * result + ((layer == null) ? 0 : layer.hashCode());
     61            result = prime * result
     62                    + ((primitiveId == null) ? 0 : primitiveId.hashCode());
     63            return result;
     64        }
     65
     66        @Override
     67        public boolean equals(Object obj) {
     68            if (this == obj)
     69                return true;
     70            if (obj == null)
     71                return false;
     72            if (getClass() != obj.getClass())
     73                return false;
     74            DialogContext other = (DialogContext) obj;
     75            if (layer == null) {
     76                if (other.layer != null)
     77                    return false;
     78            } else if (!layer.equals(other.layer))
     79                return false;
     80            if (primitiveId == null) {
     81                if (other.primitiveId != null)
     82                    return false;
     83            } else if (!primitiveId.equals(other.primitiveId))
     84                return false;
     85            return true;
     86        }
     87
     88        public boolean matchesLayer(OsmDataLayer layer) {
    8989            if (layer == null) return false;
    9090            return this.layer.equals(layer);
     
    187187    @Override
    188188    public void windowClosed(WindowEvent e) {
    189         TurnRestrictionEditor editor = (TurnRestrictionEditor)e.getWindow();
     189        TurnRestrictionEditor editor = (TurnRestrictionEditor)e.getWindow();
    190190        DialogContext context = null;
    191191        for (DialogContext c : openDialogs.keySet()) {
     
    200200    }
    201201
    202         /**
     202    /**
    203203     * Positions an {@see TurnRestrictionEditor} centered on the screen
    204204     *
     
    286286            Entry<DialogContext,TurnRestrictionEditor> entry = it.next();
    287287            if (entry.getKey().matchesLayer(dataLayer)) {
    288                 TurnRestrictionEditor editor = entry.getValue();
     288                TurnRestrictionEditor editor = entry.getValue();
    289289                it.remove();
    290290                editor.setVisible(false);
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/TurnRestrictionEditorModel.java

    r20735 r23192  
    4040 */
    4141public class TurnRestrictionEditorModel extends Observable implements DataSetListener{
    42         static private final Logger logger = Logger.getLogger(TurnRestrictionEditorModel.class.getName());
    43        
    44         /**
    45         * Replies true if {@code tp1} and {@code tp2} have the same tags and
    46         * the same members
    47         *
    48         * @param tp1 a turn restriction. Must not be null.
    49         * @param tp2 a turn restriction . Must not be null.
    50         * @return true if {@code tp1} and {@code tp2} have the same tags and
    51         * the same members
    52         * @throws IllegalArgumentException thrown if {@code tp1} is null
    53         * @throws IllegalArgumentException thrown if {@code tp2} is null
    54         */
    55         static public boolean hasSameMembersAndTags(Relation tp1, Relation tp2) throws IllegalArgumentException {
    56                 CheckParameterUtil.ensureParameterNotNull(tp1, "tp1");
    57                 CheckParameterUtil.ensureParameterNotNull(tp2, "tp2");
    58                 if (!TagCollection.from(tp1).asSet().equals(TagCollection.from(tp2).asSet())) return false;
    59                 if (tp1.getMembersCount() != tp2.getMembersCount()) return false;
    60                 for(int i=0; i < tp1.getMembersCount();i++){
    61                         if (!tp1.getMember(i).equals(tp2.getMember(i))) return false;
    62                 }
    63                 return true;
    64         }
    65        
    66         private OsmDataLayer layer;
    67         private final TagEditorModel tagEditorModel = new TagEditorModel();
    68         private  RelationMemberEditorModel memberModel;
    69         private  IssuesModel issuesModel;
    70         private NavigationControler navigationControler;
    71        
    72         /**
    73         * Creates a model in the context of a {@see OsmDataLayer}
    74         *
    75         * @param layer the layer. Must not be null.
    76         * @param navigationControler control to direct the user to specific UI components. Must not be null
    77         * @throws IllegalArgumentException thrown if {@code layer} is null
    78         */
    79         public TurnRestrictionEditorModel(OsmDataLayer layer, NavigationControler navigationControler) throws IllegalArgumentException{
    80                 CheckParameterUtil.ensureParameterNotNull(layer, "layer");
    81                 CheckParameterUtil.ensureParameterNotNull(navigationControler, "navigationControler");
    82                 this.layer = layer;
    83                 this.navigationControler = navigationControler;
    84                 memberModel = new RelationMemberEditorModel(layer);
    85                 memberModel.addTableModelListener(new RelationMemberModelListener());
    86                 issuesModel = new IssuesModel(this);
    87                 addObserver(issuesModel);
    88                 tagEditorModel.addTableModelListener(new TagEditorModelObserver());
    89         }
    90        
    91         /**
    92         * Sets the way participating in the turn restriction in a given role.
    93         *
    94         * @param role the role. Must not be null. 
    95         * @param way the way which participates in the turn restriction in the respective role.
    96         * null, to remove the way with the given role.
    97         * @exception IllegalArgumentException thrown if role is null
    98         */
    99         public void setTurnRestrictionLeg(TurnRestrictionLegRole role, Way way) {
    100                 CheckParameterUtil.ensureParameterNotNull(role, "role");
    101                 switch(role){
    102                 case FROM:
    103                         memberModel.setFromPrimitive(way);
    104                         break;
    105                 case TO:
    106                         memberModel.setToPrimitive(way);
    107                         break;
    108                 }
    109         }       
    110                
    111         /**
    112         * Sets the way participating in the turn restriction in a given role.
    113         *
    114         * @param role the role. Must not be null. 
    115         * @param wayId the id of the way to set
    116         * @exception IllegalArgumentException thrown if role is null
    117         * @exception IllegalArgumentException thrown if wayId != null isn't the id of a way
    118         * @exception IllegalStateException thrown the no way with this id was found in the dataset
    119         */
    120         public void setTurnRestrictionLeg(TurnRestrictionLegRole role, PrimitiveId wayId) {
    121                 CheckParameterUtil.ensureParameterNotNull(role, "role");
    122                 if (wayId == null) {
    123                         setTurnRestrictionLeg(role, (Way)null);
    124                         return;
    125                 }
    126                 if (!wayId.getType().equals(OsmPrimitiveType.WAY)) {
    127                         throw new IllegalArgumentException(MessageFormat.format("parameter ''wayId'' of type {0} expected, got {1}", OsmPrimitiveType.WAY, wayId.getType()));
    128                 }
    129 
    130                 OsmPrimitive p = layer.data.getPrimitiveById(wayId);
    131                 if (p == null) {
    132                         throw new IllegalStateException(MessageFormat.format("didn''t find way with id {0} in layer ''{1}''", wayId, layer.getName()));                 
    133                 }
    134                 setTurnRestrictionLeg(role, (Way)p);
    135         }       
    136        
    137         /**
    138         * "Officially" a turn restriction should have exactly one member with
    139         * role {@see TurnRestrictionLegRole#FROM} and one member with role {@see TurnRestrictionLegRole#TO},
    140         * both referring to an OSM {@see Way}. In order to deals with turn restrictions where these
    141         * integrity constraints are violated, this model also supports relation with multiple or no
    142         * 'from' or 'to' members.
    143         *
    144         * Replies the turn restriction legs with role {@code role}. If no leg with this
    145         * role exists, an empty set is returned. If multiple legs exists, the set of referred
    146         * primitives is returned. 
    147         *
    148         * @param role the role. Must not be null.
    149         * @return the set of turn restriction legs with role {@code role}. The empty set, if
    150         * no such turn restriction leg exists
    151         * @throws IllegalArgumentException thrown if role is null
    152         */
    153         public Set<OsmPrimitive>getTurnRestrictionLeg(TurnRestrictionLegRole role){
    154                 CheckParameterUtil.ensureParameterNotNull(role, "role");
    155                 switch(role){
    156                 case FROM: return memberModel.getFromPrimitives();
    157                 case TO: return memberModel.getToPrimitives();
    158                 }
    159                 // should not happen
    160                 return null;
    161         }
    162        
    163         /**
    164         * Initializes the model from a relation representing a turn
    165         * restriction
    166         *
    167         * @param turnRestriction the turn restriction
    168         */
    169         protected void initFromTurnRestriction(Relation turnRestriction) {
    170                
    171                 // populate the member model
    172                 memberModel.populate(turnRestriction);
    173                
    174                 // make sure we have a restriction tag
    175                 TagCollection tags = TagCollection.from(turnRestriction);
    176                 tags.setUniqueForKey("type", "restriction");
    177                 tagEditorModel.initFromTags(tags);
    178                                
    179                 setChanged();
    180                 notifyObservers();
    181         }
    182        
    183         /**
    184         * Populates the turn restriction editor model with a turn restriction.
    185         * {@code turnRestriction} is an arbitrary relation. A tag type=restriction
    186         * isn't required. If it is missing, it is added here. {@code turnRestriction}
    187         * must not be null and it must belong to a dataset.
    188         *
    189         * @param turnRestriction the turn restriction
    190         * @throws IllegalArgumentException thrown if turnRestriction is null
    191         * @throws IllegalArgumentException thrown if turnRestriction doesn't belong to a dataset 
    192         */
    193         public void populate(Relation turnRestriction) {
    194                 CheckParameterUtil.ensureParameterNotNull(turnRestriction, "turnRestriction");
    195                 if (turnRestriction.getDataSet() != null && turnRestriction.getDataSet() != layer.data) {                       
    196                         throw new IllegalArgumentException(
    197                                 // don't translate - it's a technical message
    198                                 MessageFormat.format("turnRestriction {0} must not belong to a different dataset than the dataset of layer ''{1}''", turnRestriction.getId(), layer.getName())
    199                         );
    200                 }
    201                 initFromTurnRestriction(turnRestriction);
    202         }
    203        
    204        
    205         /**
    206         * Applies the current state in the model to a turn restriction
    207         *
    208         * @param turnRestriction the turn restriction. Must not be null.
    209         */
    210         public void apply(Relation turnRestriction) {
    211                 CheckParameterUtil.ensureParameterNotNull(turnRestriction, "turnRestriction");         
    212                 TagCollection tags = tagEditorModel.getTagCollection();
    213                 turnRestriction.removeAll();
    214                 tags.applyTo(turnRestriction);
    215                 memberModel.applyTo(turnRestriction);           
    216         }
    217        
    218         /**
    219         * Replies the current tag value for the tag <tt>restriction</tt>.
    220         * The empty tag, if there isn't a tag <tt>restriction</tt>. 
    221         *
    222         * @return the tag value
    223         */
    224         public String getRestrictionTagValue() {
    225                 TagCollection tags = tagEditorModel.getTagCollection();
    226                 if (!tags.hasTagsFor("restriction")) return "";
    227                 return tags.getJoinedValues("restriction");
    228         }
    229        
    230         /**
    231         * Sets the current value for the restriction tag. If {@code value} is
    232         * null or an empty string, the restriction tag is removed.
    233         *
    234         * @param value the value of the restriction tag
    235         */
    236         public void setRestrictionTagValue(String value){
    237                 if (value == null || value.trim().equals("")) {
    238                         tagEditorModel.delete("restriction");                   
    239                 } else {
    240                         TagModel  tm = tagEditorModel.get("restriction");
    241                         if (tm != null){
    242                                 tm.setValue(value);
    243                         } else {
    244                                 tagEditorModel.prepend(new TagModel("restriction", value.trim().toLowerCase()));
    245                         }
    246                 }
    247                 setChanged();
    248                 notifyObservers();
    249         }
    250        
    251         /**
    252         * Replies the list of 'via' objects. The return value is an
    253         * unmodifiable list.
    254        
    255         * @return the list of 'via' objects
    256         */
    257         public List<OsmPrimitive> getVias() {
    258                 return memberModel.getVias();
    259         }
    260        
    261         /**
    262         * Sets the list of vias for the edited turn restriction.
    263         *
    264         * If {@code vias} is null, all vias are removed. All primitives
    265         * in {@code vias} must be assigned to a dataset and the dataset
    266         * must be equal to the dataset of this editor model, see {@see #getDataSet()}
    267         *
    268         * null values in {@see vias} are skipped.
    269         *
    270         * @param vias the list of vias
    271         * @throws IllegalArgumentException thrown if one of the via objects belongs to the wrong dataset
    272         */
    273         public void setVias(List<OsmPrimitive> vias) throws IllegalArgumentException{
    274                 memberModel.setVias(vias);
    275         }
    276        
    277         /**
    278         * Replies the layer in whose context this editor is working
    279         *
    280         * @return the layer in whose context this editor is working
    281         */
    282         public OsmDataLayer getLayer() {
    283                 return layer;
    284         }
    285        
    286         /**
    287         * Registers this model with global event sources like {@see DatasetEventManager}
    288         */
    289         public void registerAsEventListener(){
    290                 DatasetEventManager.getInstance().addDatasetListener(this, FireMode.IN_EDT);
    291         }
    292        
    293         /**
    294         * Removes this model as listener from global event sources like  {@see DatasetEventManager}
    295         */
    296         public void unregisterAsEventListener() {
    297                 DatasetEventManager.getInstance().removeDatasetListener(this);
    298         }
    299        
    300         /**
    301         * Replies the tag  editor model
    302         *
    303         * @return the tag  editor model
    304         */
    305         public TagEditorModel getTagEditorModel() {
    306                 return tagEditorModel;
    307         }
    308        
    309         /**
    310         * Replies the editor model for the relation members
    311         *
    312         * @return the editor model for the relation members
    313         */
    314         public RelationMemberEditorModel getRelationMemberEditorModel() {
    315                 return memberModel;
    316         }
    317        
    318         /**
    319         * Replies the model for the open issues in this turn restriction
    320         * editor.
    321         *
    322         * @return the model for the open issues in this turn restriction
    323         * editor
    324         */
    325         public IssuesModel getIssuesModel() {
    326                 return issuesModel;
    327         }
    328        
    329         public NavigationControler getNavigationControler() {
    330                 return navigationControler;
    331         }
    332        
    333         /**
    334         * Replies the current value of the tag "except", or the empty string
    335         * if the tag doesn't exist.
    336         *
    337         * @return
    338         */
    339         public ExceptValueModel getExcept() {
    340                 TagModel tag = tagEditorModel.get("except");
    341                 if (tag == null) return new ExceptValueModel("");
    342                 return new ExceptValueModel(tag.getValue());
    343         }
    344        
    345         /**
    346         * Sets the current value of the tag "except". Removes the
    347         * tag is {@code value} is null or consists of white
    348         * space only.
    349         *
    350         * @param value the new value for 'except'
    351         */
    352         public void setExcept(ExceptValueModel value){
    353                 if (value == null || value.getValue().equals("")) {
    354                         if (tagEditorModel.get("except") != null){
    355                                 tagEditorModel.delete("except");
    356                                 setChanged();
    357                                 notifyObservers();                             
    358                         }
    359                         return;                 
    360                 }
    361                 TagModel tag = tagEditorModel.get("except");
    362                 if (tag == null) {
    363                         tagEditorModel.prepend(new TagModel("except", value.getValue()));
    364                         setChanged();
    365                         notifyObservers();
    366                 } else {
    367                         if (!tag.getValue().equals(value.getValue())) {
    368                                 tag.setValue(value.getValue().trim());
    369                                 setChanged();
    370                                 notifyObservers();
    371                         }
    372                 }               
    373         }
    374 
    375         /* ----------------------------------------------------------------------------------------- */
    376         /* interface DataSetListener                                                                 */
    377         /* ----------------------------------------------------------------------------------------- */
    378         protected boolean isAffectedByDataSetUpdate(DataSet ds, List<? extends OsmPrimitive> updatedPrimitives) {
    379                 if (ds != layer.data) return false;
    380                 if (updatedPrimitives == null || updatedPrimitives.isEmpty()) return false;
    381                 Set<OsmPrimitive> myPrimitives = memberModel.getMemberPrimitives();
    382                 int size1 = myPrimitives.size();
    383                 myPrimitives.retainAll(updatedPrimitives);
    384                 return size1 != myPrimitives.size();
    385         }
    386        
    387         public void dataChanged(DataChangedEvent event) {
    388                 // refresh the views
    389                 setChanged();
    390                 notifyObservers();             
    391         }
    392 
    393         public void nodeMoved(NodeMovedEvent event) {
    394                 // may affect the display name of node in the list of vias
    395                 if (isAffectedByDataSetUpdate(event.getDataset(), event.getPrimitives())) {
    396                         setChanged();
    397                         notifyObservers();
    398                 }
    399         }
    400 
    401         public void otherDatasetChange(AbstractDatasetChangedEvent event) {/* irrelevant in this context */}
    402 
    403         public void primtivesAdded(PrimitivesAddedEvent event) {/* irrelevant in this context */}
    404         public void primtivesRemoved(PrimitivesRemovedEvent event) {
    405                 // relevant for the state of this model but not handled here. When the
    406                 // state of this model is applied to the dataset we check whether the
    407                 // the turn restriction refers to deleted or invisible primitives
    408         }
    409 
    410         public void relationMembersChanged(RelationMembersChangedEvent event) {/* irrelevant in this context */}
    411         public void tagsChanged(TagsChangedEvent event) {
    412                 // may affect the display name of 'from', 'to' or 'via' elements
    413                 if (isAffectedByDataSetUpdate(event.getDataset(), event.getPrimitives())) {
    414                         setChanged();
    415                         notifyObservers();
    416                 }
    417         }
    418 
    419         public void wayNodesChanged(WayNodesChangedEvent event) {
    420                 // may affect the display name of 'from', 'to' or 'via' elements
    421                 if (isAffectedByDataSetUpdate(event.getDataset(), event.getPrimitives())) {
    422                         setChanged();
    423                         notifyObservers();
    424                 }               
    425         }       
    426        
    427         class RelationMemberModelListener implements TableModelListener {
    428                 public void tableChanged(TableModelEvent e) {
    429                         setChanged();
    430                         notifyObservers();
    431                 }               
    432         }
    433 
    434         /* ----------------------------------------------------------------------------------------- */
    435         /* inner classes                                                                             */
    436         /* ----------------------------------------------------------------------------------------- */
    437         class TagEditorModelObserver implements TableModelListener {
    438                 public void tableChanged(TableModelEvent e) {
    439                         setChanged();
    440                         notifyObservers();
    441                 }               
    442         }
     42    static private final Logger logger = Logger.getLogger(TurnRestrictionEditorModel.class.getName());
     43   
     44    /**
     45    * Replies true if {@code tp1} and {@code tp2} have the same tags and
     46    * the same members
     47    *
     48    * @param tp1 a turn restriction. Must not be null.
     49    * @param tp2 a turn restriction . Must not be null.
     50    * @return true if {@code tp1} and {@code tp2} have the same tags and
     51    * the same members
     52    * @throws IllegalArgumentException thrown if {@code tp1} is null
     53    * @throws IllegalArgumentException thrown if {@code tp2} is null
     54    */
     55    static public boolean hasSameMembersAndTags(Relation tp1, Relation tp2) throws IllegalArgumentException {
     56        CheckParameterUtil.ensureParameterNotNull(tp1, "tp1");
     57        CheckParameterUtil.ensureParameterNotNull(tp2, "tp2");
     58        if (!TagCollection.from(tp1).asSet().equals(TagCollection.from(tp2).asSet())) return false;
     59        if (tp1.getMembersCount() != tp2.getMembersCount()) return false;
     60        for(int i=0; i < tp1.getMembersCount();i++){
     61            if (!tp1.getMember(i).equals(tp2.getMember(i))) return false;
     62        }
     63        return true;
     64    }
     65   
     66    private OsmDataLayer layer;
     67    private final TagEditorModel tagEditorModel = new TagEditorModel();
     68    private  RelationMemberEditorModel memberModel;
     69    private  IssuesModel issuesModel;
     70    private NavigationControler navigationControler;
     71   
     72    /**
     73    * Creates a model in the context of a {@see OsmDataLayer}
     74    *
     75    * @param layer the layer. Must not be null.
     76    * @param navigationControler control to direct the user to specific UI components. Must not be null
     77    * @throws IllegalArgumentException thrown if {@code layer} is null
     78    */
     79    public TurnRestrictionEditorModel(OsmDataLayer layer, NavigationControler navigationControler) throws IllegalArgumentException{
     80        CheckParameterUtil.ensureParameterNotNull(layer, "layer");
     81        CheckParameterUtil.ensureParameterNotNull(navigationControler, "navigationControler");
     82        this.layer = layer;
     83        this.navigationControler = navigationControler;
     84        memberModel = new RelationMemberEditorModel(layer);
     85        memberModel.addTableModelListener(new RelationMemberModelListener());
     86        issuesModel = new IssuesModel(this);
     87        addObserver(issuesModel);
     88        tagEditorModel.addTableModelListener(new TagEditorModelObserver());
     89    }
     90   
     91    /**
     92    * Sets the way participating in the turn restriction in a given role.
     93    *
     94    * @param role the role. Must not be null. 
     95    * @param way the way which participates in the turn restriction in the respective role.
     96    * null, to remove the way with the given role.
     97    * @exception IllegalArgumentException thrown if role is null
     98    */
     99    public void setTurnRestrictionLeg(TurnRestrictionLegRole role, Way way) {
     100        CheckParameterUtil.ensureParameterNotNull(role, "role");
     101        switch(role){
     102        case FROM:
     103            memberModel.setFromPrimitive(way);
     104            break;
     105        case TO:
     106            memberModel.setToPrimitive(way);
     107            break;
     108        }
     109    }   
     110       
     111    /**
     112    * Sets the way participating in the turn restriction in a given role.
     113    *
     114    * @param role the role. Must not be null. 
     115    * @param wayId the id of the way to set
     116    * @exception IllegalArgumentException thrown if role is null
     117    * @exception IllegalArgumentException thrown if wayId != null isn't the id of a way
     118    * @exception IllegalStateException thrown the no way with this id was found in the dataset
     119    */
     120    public void setTurnRestrictionLeg(TurnRestrictionLegRole role, PrimitiveId wayId) {
     121        CheckParameterUtil.ensureParameterNotNull(role, "role");
     122        if (wayId == null) {
     123            setTurnRestrictionLeg(role, (Way)null);
     124            return;
     125        }
     126        if (!wayId.getType().equals(OsmPrimitiveType.WAY)) {
     127            throw new IllegalArgumentException(MessageFormat.format("parameter ''wayId'' of type {0} expected, got {1}", OsmPrimitiveType.WAY, wayId.getType()));
     128        }
     129
     130        OsmPrimitive p = layer.data.getPrimitiveById(wayId);
     131        if (p == null) {
     132            throw new IllegalStateException(MessageFormat.format("didn''t find way with id {0} in layer ''{1}''", wayId, layer.getName()));         
     133        }
     134        setTurnRestrictionLeg(role, (Way)p);
     135    }   
     136   
     137    /**
     138    * "Officially" a turn restriction should have exactly one member with
     139    * role {@see TurnRestrictionLegRole#FROM} and one member with role {@see TurnRestrictionLegRole#TO},
     140    * both referring to an OSM {@see Way}. In order to deals with turn restrictions where these
     141    * integrity constraints are violated, this model also supports relation with multiple or no
     142    * 'from' or 'to' members.
     143    *
     144    * Replies the turn restriction legs with role {@code role}. If no leg with this
     145    * role exists, an empty set is returned. If multiple legs exists, the set of referred
     146    * primitives is returned. 
     147    *
     148    * @param role the role. Must not be null.
     149    * @return the set of turn restriction legs with role {@code role}. The empty set, if
     150    * no such turn restriction leg exists
     151    * @throws IllegalArgumentException thrown if role is null
     152    */
     153    public Set<OsmPrimitive>getTurnRestrictionLeg(TurnRestrictionLegRole role){
     154        CheckParameterUtil.ensureParameterNotNull(role, "role");
     155        switch(role){
     156        case FROM: return memberModel.getFromPrimitives();
     157        case TO: return memberModel.getToPrimitives();
     158        }
     159        // should not happen
     160        return null;
     161    }
     162   
     163    /**
     164    * Initializes the model from a relation representing a turn
     165    * restriction
     166    *
     167    * @param turnRestriction the turn restriction
     168    */
     169    protected void initFromTurnRestriction(Relation turnRestriction) {
     170       
     171        // populate the member model
     172        memberModel.populate(turnRestriction);
     173       
     174        // make sure we have a restriction tag
     175        TagCollection tags = TagCollection.from(turnRestriction);
     176        tags.setUniqueForKey("type", "restriction");
     177        tagEditorModel.initFromTags(tags);
     178               
     179        setChanged();
     180        notifyObservers();
     181    }
     182   
     183    /**
     184    * Populates the turn restriction editor model with a turn restriction.
     185    * {@code turnRestriction} is an arbitrary relation. A tag type=restriction
     186    * isn't required. If it is missing, it is added here. {@code turnRestriction}
     187    * must not be null and it must belong to a dataset.
     188    *
     189    * @param turnRestriction the turn restriction
     190    * @throws IllegalArgumentException thrown if turnRestriction is null
     191    * @throws IllegalArgumentException thrown if turnRestriction doesn't belong to a dataset 
     192    */
     193    public void populate(Relation turnRestriction) {
     194        CheckParameterUtil.ensureParameterNotNull(turnRestriction, "turnRestriction");
     195        if (turnRestriction.getDataSet() != null && turnRestriction.getDataSet() != layer.data) {           
     196            throw new IllegalArgumentException(
     197                // don't translate - it's a technical message
     198                MessageFormat.format("turnRestriction {0} must not belong to a different dataset than the dataset of layer ''{1}''", turnRestriction.getId(), layer.getName())
     199            );
     200        }
     201        initFromTurnRestriction(turnRestriction);
     202    }
     203   
     204   
     205    /**
     206    * Applies the current state in the model to a turn restriction
     207    *
     208    * @param turnRestriction the turn restriction. Must not be null.
     209    */
     210    public void apply(Relation turnRestriction) {
     211        CheckParameterUtil.ensureParameterNotNull(turnRestriction, "turnRestriction");     
     212        TagCollection tags = tagEditorModel.getTagCollection();
     213        turnRestriction.removeAll();
     214        tags.applyTo(turnRestriction);
     215        memberModel.applyTo(turnRestriction);       
     216    }
     217   
     218    /**
     219    * Replies the current tag value for the tag <tt>restriction</tt>.
     220    * The empty tag, if there isn't a tag <tt>restriction</tt>. 
     221    *
     222    * @return the tag value
     223    */
     224    public String getRestrictionTagValue() {
     225        TagCollection tags = tagEditorModel.getTagCollection();
     226        if (!tags.hasTagsFor("restriction")) return "";
     227        return tags.getJoinedValues("restriction");
     228    }
     229   
     230    /**
     231    * Sets the current value for the restriction tag. If {@code value} is
     232    * null or an empty string, the restriction tag is removed.
     233    *
     234    * @param value the value of the restriction tag
     235    */
     236    public void setRestrictionTagValue(String value){
     237        if (value == null || value.trim().equals("")) {
     238            tagEditorModel.delete("restriction");           
     239        } else {
     240            TagModel  tm = tagEditorModel.get("restriction");
     241            if (tm != null){
     242                tm.setValue(value);
     243            } else {
     244                tagEditorModel.prepend(new TagModel("restriction", value.trim().toLowerCase()));
     245            }
     246        }
     247        setChanged();
     248        notifyObservers();
     249    }
     250   
     251    /**
     252    * Replies the list of 'via' objects. The return value is an
     253    * unmodifiable list.
     254   
     255    * @return the list of 'via' objects
     256    */
     257    public List<OsmPrimitive> getVias() {
     258        return memberModel.getVias();
     259    }
     260   
     261    /**
     262    * Sets the list of vias for the edited turn restriction.
     263    *
     264    * If {@code vias} is null, all vias are removed. All primitives
     265    * in {@code vias} must be assigned to a dataset and the dataset
     266    * must be equal to the dataset of this editor model, see {@see #getDataSet()}
     267    *
     268    * null values in {@see vias} are skipped.
     269    *
     270    * @param vias the list of vias
     271    * @throws IllegalArgumentException thrown if one of the via objects belongs to the wrong dataset
     272    */
     273    public void setVias(List<OsmPrimitive> vias) throws IllegalArgumentException{
     274        memberModel.setVias(vias);
     275    }
     276   
     277    /**
     278    * Replies the layer in whose context this editor is working
     279    *
     280    * @return the layer in whose context this editor is working
     281    */
     282    public OsmDataLayer getLayer() {
     283        return layer;
     284    }
     285   
     286    /**
     287    * Registers this model with global event sources like {@see DatasetEventManager}
     288    */
     289    public void registerAsEventListener(){
     290        DatasetEventManager.getInstance().addDatasetListener(this, FireMode.IN_EDT);
     291    }
     292   
     293    /**
     294    * Removes this model as listener from global event sources like  {@see DatasetEventManager}
     295    */
     296    public void unregisterAsEventListener() {
     297        DatasetEventManager.getInstance().removeDatasetListener(this);
     298    }
     299   
     300    /**
     301    * Replies the tag  editor model
     302    *
     303    * @return the tag  editor model
     304    */
     305    public TagEditorModel getTagEditorModel() {
     306        return tagEditorModel;
     307    }
     308   
     309    /**
     310    * Replies the editor model for the relation members
     311    *
     312    * @return the editor model for the relation members
     313    */
     314    public RelationMemberEditorModel getRelationMemberEditorModel() {
     315        return memberModel;
     316    }
     317   
     318    /**
     319    * Replies the model for the open issues in this turn restriction
     320    * editor.
     321    *
     322    * @return the model for the open issues in this turn restriction
     323    * editor
     324    */
     325    public IssuesModel getIssuesModel() {
     326        return issuesModel;
     327    }
     328   
     329    public NavigationControler getNavigationControler() {
     330        return navigationControler;
     331    }
     332   
     333    /**
     334    * Replies the current value of the tag "except", or the empty string
     335    * if the tag doesn't exist.
     336    *
     337    * @return
     338    */
     339    public ExceptValueModel getExcept() {
     340        TagModel tag = tagEditorModel.get("except");
     341        if (tag == null) return new ExceptValueModel("");
     342        return new ExceptValueModel(tag.getValue());
     343    }
     344   
     345    /**
     346    * Sets the current value of the tag "except". Removes the
     347    * tag is {@code value} is null or consists of white
     348    * space only.
     349    *
     350    * @param value the new value for 'except'
     351    */
     352    public void setExcept(ExceptValueModel value){
     353        if (value == null || value.getValue().equals("")) {
     354            if (tagEditorModel.get("except") != null){
     355                tagEditorModel.delete("except");
     356                setChanged();
     357                notifyObservers();             
     358            }
     359            return;         
     360        }
     361        TagModel tag = tagEditorModel.get("except");
     362        if (tag == null) {
     363            tagEditorModel.prepend(new TagModel("except", value.getValue()));
     364            setChanged();
     365            notifyObservers();
     366        } else {
     367            if (!tag.getValue().equals(value.getValue())) {
     368                tag.setValue(value.getValue().trim());
     369                setChanged();
     370                notifyObservers();
     371            }
     372        }       
     373    }
     374
     375    /* ----------------------------------------------------------------------------------------- */
     376    /* interface DataSetListener                                                                 */
     377    /* ----------------------------------------------------------------------------------------- */
     378    protected boolean isAffectedByDataSetUpdate(DataSet ds, List<? extends OsmPrimitive> updatedPrimitives) {
     379        if (ds != layer.data) return false;
     380        if (updatedPrimitives == null || updatedPrimitives.isEmpty()) return false;
     381        Set<OsmPrimitive> myPrimitives = memberModel.getMemberPrimitives();
     382        int size1 = myPrimitives.size();
     383        myPrimitives.retainAll(updatedPrimitives);
     384        return size1 != myPrimitives.size();
     385    }
     386   
     387    public void dataChanged(DataChangedEvent event) {
     388        // refresh the views
     389        setChanged();
     390        notifyObservers();     
     391    }
     392
     393    public void nodeMoved(NodeMovedEvent event) {
     394        // may affect the display name of node in the list of vias
     395        if (isAffectedByDataSetUpdate(event.getDataset(), event.getPrimitives())) {
     396            setChanged();
     397            notifyObservers();
     398        }
     399    }
     400
     401    public void otherDatasetChange(AbstractDatasetChangedEvent event) {/* irrelevant in this context */}
     402
     403    public void primtivesAdded(PrimitivesAddedEvent event) {/* irrelevant in this context */}
     404    public void primtivesRemoved(PrimitivesRemovedEvent event) {
     405        // relevant for the state of this model but not handled here. When the
     406        // state of this model is applied to the dataset we check whether the
     407        // the turn restriction refers to deleted or invisible primitives
     408    }
     409
     410    public void relationMembersChanged(RelationMembersChangedEvent event) {/* irrelevant in this context */}
     411    public void tagsChanged(TagsChangedEvent event) {
     412        // may affect the display name of 'from', 'to' or 'via' elements
     413        if (isAffectedByDataSetUpdate(event.getDataset(), event.getPrimitives())) {
     414            setChanged();
     415            notifyObservers();
     416        }
     417    }
     418
     419    public void wayNodesChanged(WayNodesChangedEvent event) {
     420        // may affect the display name of 'from', 'to' or 'via' elements
     421        if (isAffectedByDataSetUpdate(event.getDataset(), event.getPrimitives())) {
     422            setChanged();
     423            notifyObservers();
     424        }       
     425    }   
     426   
     427    class RelationMemberModelListener implements TableModelListener {
     428        public void tableChanged(TableModelEvent e) {
     429            setChanged();
     430            notifyObservers();
     431        }       
     432    }
     433
     434    /* ----------------------------------------------------------------------------------------- */
     435    /* inner classes                                                                             */
     436    /* ----------------------------------------------------------------------------------------- */
     437    class TagEditorModelObserver implements TableModelListener {
     438        public void tableChanged(TableModelEvent e) {
     439            setChanged();
     440            notifyObservers();
     441        }       
     442    }
    443443}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/TurnRestrictionLegEditor.java

    r20701 r23192  
    5555 */
    5656public class TurnRestrictionLegEditor extends JPanel implements Observer, PrimitiveIdListProvider {
    57         static private final Logger logger = Logger.getLogger(TurnRestrictionLegEditor.class.getName());
     57    static private final Logger logger = Logger.getLogger(TurnRestrictionLegEditor.class.getName());
    5858 
    59         private JLabel lblOsmObject;
    60         private final Set<OsmPrimitive> legs = new HashSet<OsmPrimitive>();
    61         private TurnRestrictionEditorModel model;
    62         private TurnRestrictionLegRole role;
    63         private DeleteAction actDelete;
    64         private CopyAction actCopy;
    65         private PasteAction actPaste;
    66         private TransferHandler transferHandler;
    67        
    68         /**
    69         * builds the UI
    70         */
    71         protected void build() {
    72                 setLayout(new BorderLayout());
    73                 add(lblOsmObject = new JLabel(), BorderLayout.CENTER);         
    74                 lblOsmObject.setOpaque(true);
    75                 lblOsmObject.setBorder(null);
    76                 setBorder(
    77                                 BorderFactory.createCompoundBorder(
    78                                                 BorderFactory.createEtchedBorder(),
    79                                                 BorderFactory.createEmptyBorder(1,1,1,1)
    80                                 )
    81                 );
    82                
    83                 JButton btn;
    84                 actDelete = new DeleteAction();
    85                 add(btn = new JButton(actDelete), BorderLayout.EAST);
    86                 btn.setFocusable(false);
    87                 btn.setText(null);
    88                 btn.setBorder(BorderFactory.createRaisedBevelBorder());
    89                                
    90                 // focus handling
    91                 FocusHandler fh  = new FocusHandler();
    92                 lblOsmObject.setFocusable(true);       
    93                 lblOsmObject.addFocusListener(fh);             
    94                 this.addFocusListener(fh);
    95 
    96                 // mouse event handling
    97                 MouseEventHandler meh = new MouseEventHandler();
    98                 lblOsmObject.addMouseListener(meh);
    99                 addMouseListener(meh);
    100                 lblOsmObject.addMouseListener(new PopupLauncher());
    101                
    102                 // enable DEL to remove the object from the turn restriction
    103                 registerKeyboardAction(actDelete,KeyStroke.getKeyStroke(KeyEvent.VK_DELETE,0) , JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    104 
    105                 getInputMap().put(Shortcut.getCopyKeyStroke(), TransferHandler.getCopyAction().getValue(Action.NAME));;
    106                 getInputMap().put(Shortcut.getPasteKeyStroke(), TransferHandler.getPasteAction().getValue(Action.NAME));;
    107                 getActionMap().put(TransferHandler.getCopyAction().getValue(Action.NAME), TransferHandler.getCopyAction());
    108                 getActionMap().put(TransferHandler.getPasteAction().getValue(Action.NAME), TransferHandler.getPasteAction());
    109                 lblOsmObject.setTransferHandler(transferHandler = new LegEditorTransferHandler(this));
    110                 lblOsmObject.addMouseMotionListener(new MouseMotionAdapter(){
    111                         @Override
    112                         public void mouseDragged(MouseEvent e) {
    113                                 JComponent c = (JComponent)e.getSource();
    114                                 TransferHandler th = c.getTransferHandler();
    115                                 th.exportAsDrag(c, e, TransferHandler.COPY);                           
    116                         }                                       
    117                 });
    118                 actCopy = new CopyAction();
    119                 actPaste = new PasteAction();
    120         }
    121        
    122         /**
    123         * Constructor
    124         *
    125         * @param model the model. Must not be null.
    126         * @param role the leg role of the leg this editor is editing. Must not be null.
    127         * @exception IllegalArgumentException thrown if model is null
    128         * @exception IllegalArgumentException thrown if role is null
    129         */
    130         public TurnRestrictionLegEditor(TurnRestrictionEditorModel model, TurnRestrictionLegRole role) {
    131                 CheckParameterUtil.ensureParameterNotNull(model, "model");
    132                 CheckParameterUtil.ensureParameterNotNull(role, "role");
    133                
    134                 this.model = model;
    135                 this.role = role;
    136                 build();
    137                 model.addObserver(this);
    138                 refresh();     
    139         }
    140 
    141         protected void refresh(){
    142                 legs.clear();
    143                 legs.addAll(model.getTurnRestrictionLeg(role));
    144                 if (legs.isEmpty()) {
    145                         lblOsmObject.setFont(UIManager.getFont("Label.font").deriveFont(Font.ITALIC));
    146                         lblOsmObject.setIcon(null);
    147                         lblOsmObject.setText(tr("please select a way"));
    148                         lblOsmObject.setToolTipText(null);
    149                 } else if (legs.size() == 1){
    150                         OsmPrimitive leg = legs.iterator().next();
    151                         lblOsmObject.setFont(UIManager.getFont("Label.font"));
    152                         lblOsmObject.setIcon(ImageProvider.get("data", "way"));
    153                         lblOsmObject.setText(leg.getDisplayName(DefaultNameFormatter.getInstance()));
    154                         lblOsmObject.setToolTipText(DefaultNameFormatter.getInstance().buildDefaultToolTip(leg));
    155                 } else {
    156                         lblOsmObject.setFont(UIManager.getFont("Label.font").deriveFont(Font.ITALIC));
    157                         lblOsmObject.setIcon(null);
    158                         lblOsmObject.setText(tr("multiple objects with role ''{0}''",this.role.getOsmRole()));
    159                         lblOsmObject.setToolTipText(null);                     
    160                 }
    161                 renderColors();
    162                 actDelete.updateEnabledState();
    163         }
    164        
    165         /**
    166         * Render the foreground and background color
    167         */
    168         protected void renderColors() {
    169                 if (lblOsmObject.hasFocus()) {
    170                         setBackground(UIManager.getColor("List.selectionBackground"));
    171                         setForeground(UIManager.getColor("List.selectionForeground"));
    172                         lblOsmObject.setBackground(UIManager.getColor("List.selectionBackground"));
    173                         lblOsmObject.setForeground(UIManager.getColor("List.selectionForeground"));
    174                 } else {
    175                         lblOsmObject.setBackground(UIManager.getColor("List.background"));
    176                         lblOsmObject.setForeground(UIManager.getColor("List.foreground"));
    177                 }
    178         }
    179        
    180         /**
    181         * Replies the model for this editor
    182         *
    183         * @return the model
    184         */
    185         public TurnRestrictionEditorModel getModel() {
    186                 return model;
    187         }
    188        
    189         /**
    190         * Replies the role of this editor
    191         *
    192         * @return the role
    193         */
    194         public TurnRestrictionLegRole getRole() {
    195                 return role;
    196         }               
    197        
    198         /* ----------------------------------------------------------------------------- */
    199         /* interface Observer                                                            */
    200         /* ----------------------------------------------------------------------------- */
    201         public void update(Observable o, Object arg) {
    202                 refresh();             
    203         }
    204        
    205         /* ----------------------------------------------------------------------------- */
    206         /* interface PrimitiveIdListProvider                                                            */
    207         /* ----------------------------------------------------------------------------- */
    208         public List<PrimitiveId> getSelectedPrimitiveIds() {
    209                 if (legs.size() == 1) {
    210                         return Collections.singletonList(legs.iterator().next().getPrimitiveId());
    211                 }
    212                 return Collections.emptyList();
    213         }
    214        
    215         /* ----------------------------------------------------------------------------- */
    216         /* inner classes                                                                 */
    217         /* ----------------------------------------------------------------------------- */     
    218         /**
    219         * Responds to focus change events 
    220         */
    221         class FocusHandler extends FocusAdapter {
    222                 @Override
    223                 public void focusGained(FocusEvent e) {
    224                         renderColors();
    225                 }
    226 
    227                 @Override
    228                 public void focusLost(FocusEvent e) {
    229                         renderColors();
    230                 }               
    231         }
    232        
    233         class MouseEventHandler extends MouseAdapter {
    234                 @Override
    235                 public void mouseClicked(MouseEvent e) {
    236                         lblOsmObject.requestFocusInWindow();
    237                 }               
    238         }
    239        
    240         /**
    241         * Deletes the way from the turn restriction
    242         */
    243         class DeleteAction extends AbstractAction {
    244                 public DeleteAction() {
    245                         putValue(SHORT_DESCRIPTION, tr("Delete from turn restriction"));
    246                         putValue(NAME, tr("Delete"));
    247                         putValue(SMALL_ICON, ImageProvider.get("deletesmall"));
    248                         putValue(ACCELERATOR_KEY,KeyStroke.getKeyStroke(KeyEvent.VK_DELETE,0));
    249                         updateEnabledState();
    250                 }
    251                
    252                 public void actionPerformed(ActionEvent e) {
    253                         model.setTurnRestrictionLeg(role, null);                       
    254                 }               
    255                
    256                 public void updateEnabledState() {
    257                         setEnabled(legs.size()>0);
    258                 }
    259         }
    260        
    261         /**
    262         * The transfer handler for Drag-and-Drop.
    263         */
    264         class LegEditorTransferHandler extends PrimitiveIdListTransferHandler {
    265                 Logger logger = Logger.getLogger(LegEditorTransferHandler.class.getName());
    266                
    267                 public LegEditorTransferHandler(PrimitiveIdListProvider provider){
    268                         super(provider);
    269                 }
    270 
    271                 @SuppressWarnings("unchecked")
    272                 @Override
    273                 public boolean importData(JComponent comp, Transferable t) {
    274                         try {
    275                                 List<PrimitiveId> ids = (List<PrimitiveId>)t.getTransferData(PrimitiveIdTransferable.PRIMITIVE_ID_LIST_FLAVOR);
    276                                 if (ids.size() !=1) {
    277                                         return false;
    278                                 }
    279                                 PrimitiveId id = ids.get(0);
    280                                 if (!id.getType().equals(OsmPrimitiveType.WAY)) return false;
    281                                 model.setTurnRestrictionLeg(role, id);
    282                                 return true;
    283                         } catch(IOException e) {
    284                                 // ignore
    285                                 return false;
    286                         } catch(UnsupportedFlavorException e) {
    287                                 // ignore
    288                                 return false;
    289                         }
    290                 }
    291 
    292                 @Override
    293                 protected Transferable createTransferable(JComponent c) {
    294                         if (legs.size() != 1) return null;
    295                         return super.createTransferable(c);
    296                 }
    297         }
    298        
    299         class PopupLauncher extends PopupMenuLauncher {
    300                 @Override
    301                 public void launch(MouseEvent evt) {
    302                         new PopupMenu().show(lblOsmObject, evt.getX(), evt.getY());
    303                 }               
    304         }
    305        
    306         class PopupMenu extends JPopupMenu {
    307                 public PopupMenu() {
    308                         actCopy.updateEnabledState();
    309                         JMenuItem item = add(actCopy);
    310                         item.setTransferHandler(transferHandler);
    311                         actPaste.updateEnabledState();
    312                         item = add(actPaste);                   
    313                         item.setTransferHandler(transferHandler);
    314                         addSeparator();
    315                         add(actDelete);
    316                 }
    317         }
    318        
    319         class CopyAction extends AbstractAction {
    320                 private Action delegate;
    321                
    322                 public CopyAction(){
    323                         putValue(NAME, tr("Copy"));
    324                         putValue(SHORT_DESCRIPTION, tr("Copy to the clipboard"));
    325                         putValue(SMALL_ICON, ImageProvider.get("copy"));
    326                         putValue(ACCELERATOR_KEY, Shortcut.getCopyKeyStroke());
    327                         delegate = TurnRestrictionLegEditor.this.getActionMap().get("copy");
    328                         updateEnabledState();
    329                 }
    330 
    331                 public void actionPerformed(ActionEvent e) {
    332                         delegate.actionPerformed(e);
    333                 }
    334                
    335                 public void updateEnabledState() {
    336                         setEnabled(legs.size() == 1);
    337                 }
    338         }
    339        
    340         class PasteAction extends AbstractAction {
    341                 private Action delegate;
    342                
    343                 public boolean canPaste() {
    344                         Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    345                         for (DataFlavor df: clipboard.getAvailableDataFlavors()) {
    346                                 if (df.equals(PrimitiveIdTransferable.PRIMITIVE_ID_LIST_FLAVOR)) return true;
    347                         }                       
    348                         // FIXME: check whether there are selected objects in the JOSM copy/paste buffer 
    349                         return false;
    350                 }
    351                
    352                 public PasteAction(){
    353                         putValue(NAME, tr("Paste"));
    354                         putValue(SHORT_DESCRIPTION, tr("Paste from the clipboard"));
    355                         putValue(SMALL_ICON, ImageProvider.get("paste"));
    356                         putValue(ACCELERATOR_KEY, Shortcut.getPasteKeyStroke());
    357                         delegate = TurnRestrictionLegEditor.this.getActionMap().get("paste");
    358                 }
    359                
    360                 public void updateEnabledState() {
    361                         setEnabled(canPaste());
    362                 }
    363 
    364                 public void actionPerformed(ActionEvent e) {
    365                         delegate.actionPerformed(e);                   
    366                 }
    367         }
     59    private JLabel lblOsmObject;
     60    private final Set<OsmPrimitive> legs = new HashSet<OsmPrimitive>();
     61    private TurnRestrictionEditorModel model;
     62    private TurnRestrictionLegRole role;
     63    private DeleteAction actDelete;
     64    private CopyAction actCopy;
     65    private PasteAction actPaste;
     66    private TransferHandler transferHandler;
     67   
     68    /**
     69    * builds the UI
     70    */
     71    protected void build() {
     72        setLayout(new BorderLayout());
     73        add(lblOsmObject = new JLabel(), BorderLayout.CENTER);     
     74        lblOsmObject.setOpaque(true);
     75        lblOsmObject.setBorder(null);
     76        setBorder(
     77                BorderFactory.createCompoundBorder(
     78                        BorderFactory.createEtchedBorder(),
     79                        BorderFactory.createEmptyBorder(1,1,1,1)
     80                )
     81        );
     82       
     83        JButton btn;
     84        actDelete = new DeleteAction();
     85        add(btn = new JButton(actDelete), BorderLayout.EAST);
     86        btn.setFocusable(false);
     87        btn.setText(null);
     88        btn.setBorder(BorderFactory.createRaisedBevelBorder());
     89               
     90        // focus handling
     91        FocusHandler fh  = new FocusHandler();
     92        lblOsmObject.setFocusable(true);   
     93        lblOsmObject.addFocusListener(fh);     
     94        this.addFocusListener(fh);
     95
     96        // mouse event handling
     97        MouseEventHandler meh = new MouseEventHandler();
     98        lblOsmObject.addMouseListener(meh);
     99        addMouseListener(meh);
     100        lblOsmObject.addMouseListener(new PopupLauncher());
     101       
     102        // enable DEL to remove the object from the turn restriction
     103        registerKeyboardAction(actDelete,KeyStroke.getKeyStroke(KeyEvent.VK_DELETE,0) , JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
     104
     105        getInputMap().put(Shortcut.getCopyKeyStroke(), TransferHandler.getCopyAction().getValue(Action.NAME));;
     106        getInputMap().put(Shortcut.getPasteKeyStroke(), TransferHandler.getPasteAction().getValue(Action.NAME));;
     107        getActionMap().put(TransferHandler.getCopyAction().getValue(Action.NAME), TransferHandler.getCopyAction());
     108        getActionMap().put(TransferHandler.getPasteAction().getValue(Action.NAME), TransferHandler.getPasteAction());
     109        lblOsmObject.setTransferHandler(transferHandler = new LegEditorTransferHandler(this));
     110        lblOsmObject.addMouseMotionListener(new MouseMotionAdapter(){
     111            @Override
     112            public void mouseDragged(MouseEvent e) {
     113                JComponent c = (JComponent)e.getSource();
     114                TransferHandler th = c.getTransferHandler();
     115                th.exportAsDrag(c, e, TransferHandler.COPY);               
     116            }                   
     117        });
     118        actCopy = new CopyAction();
     119        actPaste = new PasteAction();
     120    }
     121   
     122    /**
     123    * Constructor
     124    *
     125    * @param model the model. Must not be null.
     126    * @param role the leg role of the leg this editor is editing. Must not be null.
     127    * @exception IllegalArgumentException thrown if model is null
     128    * @exception IllegalArgumentException thrown if role is null
     129    */
     130    public TurnRestrictionLegEditor(TurnRestrictionEditorModel model, TurnRestrictionLegRole role) {
     131        CheckParameterUtil.ensureParameterNotNull(model, "model");
     132        CheckParameterUtil.ensureParameterNotNull(role, "role");
     133       
     134        this.model = model;
     135        this.role = role;
     136        build();
     137        model.addObserver(this);
     138        refresh(); 
     139    }
     140
     141    protected void refresh(){
     142        legs.clear();
     143        legs.addAll(model.getTurnRestrictionLeg(role));
     144        if (legs.isEmpty()) {
     145            lblOsmObject.setFont(UIManager.getFont("Label.font").deriveFont(Font.ITALIC));
     146            lblOsmObject.setIcon(null);
     147            lblOsmObject.setText(tr("please select a way"));
     148            lblOsmObject.setToolTipText(null);
     149        } else if (legs.size() == 1){
     150            OsmPrimitive leg = legs.iterator().next();
     151            lblOsmObject.setFont(UIManager.getFont("Label.font"));
     152            lblOsmObject.setIcon(ImageProvider.get("data", "way"));
     153            lblOsmObject.setText(leg.getDisplayName(DefaultNameFormatter.getInstance()));
     154            lblOsmObject.setToolTipText(DefaultNameFormatter.getInstance().buildDefaultToolTip(leg));
     155        } else {
     156            lblOsmObject.setFont(UIManager.getFont("Label.font").deriveFont(Font.ITALIC));
     157            lblOsmObject.setIcon(null);
     158            lblOsmObject.setText(tr("multiple objects with role ''{0}''",this.role.getOsmRole()));
     159            lblOsmObject.setToolTipText(null);         
     160        }
     161        renderColors();
     162        actDelete.updateEnabledState();
     163    }
     164   
     165    /**
     166    * Render the foreground and background color
     167    */
     168    protected void renderColors() {
     169        if (lblOsmObject.hasFocus()) {
     170            setBackground(UIManager.getColor("List.selectionBackground"));
     171            setForeground(UIManager.getColor("List.selectionForeground"));
     172            lblOsmObject.setBackground(UIManager.getColor("List.selectionBackground"));
     173            lblOsmObject.setForeground(UIManager.getColor("List.selectionForeground"));
     174        } else {
     175            lblOsmObject.setBackground(UIManager.getColor("List.background"));
     176            lblOsmObject.setForeground(UIManager.getColor("List.foreground"));
     177        }
     178    }
     179   
     180    /**
     181    * Replies the model for this editor
     182    *
     183    * @return the model
     184    */
     185    public TurnRestrictionEditorModel getModel() {
     186        return model;
     187    }
     188   
     189    /**
     190    * Replies the role of this editor
     191    *
     192    * @return the role
     193    */
     194    public TurnRestrictionLegRole getRole() {
     195        return role;
     196    }       
     197   
     198    /* ----------------------------------------------------------------------------- */
     199    /* interface Observer                                                            */
     200    /* ----------------------------------------------------------------------------- */
     201    public void update(Observable o, Object arg) {
     202        refresh();     
     203    }
     204   
     205    /* ----------------------------------------------------------------------------- */
     206    /* interface PrimitiveIdListProvider                                                            */
     207    /* ----------------------------------------------------------------------------- */
     208    public List<PrimitiveId> getSelectedPrimitiveIds() {
     209        if (legs.size() == 1) {
     210            return Collections.singletonList(legs.iterator().next().getPrimitiveId());
     211        }
     212        return Collections.emptyList();
     213    }
     214   
     215    /* ----------------------------------------------------------------------------- */
     216    /* inner classes                                                                 */
     217    /* ----------------------------------------------------------------------------- */
     218    /**
     219    * Responds to focus change events 
     220    */
     221    class FocusHandler extends FocusAdapter {
     222        @Override
     223        public void focusGained(FocusEvent e) {
     224            renderColors();
     225        }
     226
     227        @Override
     228        public void focusLost(FocusEvent e) {
     229            renderColors();
     230        }       
     231    }
     232   
     233    class MouseEventHandler extends MouseAdapter {
     234        @Override
     235        public void mouseClicked(MouseEvent e) {
     236            lblOsmObject.requestFocusInWindow();
     237        }       
     238    }
     239   
     240    /**
     241    * Deletes the way from the turn restriction
     242    */
     243    class DeleteAction extends AbstractAction {
     244        public DeleteAction() {
     245            putValue(SHORT_DESCRIPTION, tr("Delete from turn restriction"));
     246            putValue(NAME, tr("Delete"));
     247            putValue(SMALL_ICON, ImageProvider.get("deletesmall"));
     248            putValue(ACCELERATOR_KEY,KeyStroke.getKeyStroke(KeyEvent.VK_DELETE,0));
     249            updateEnabledState();
     250        }
     251       
     252        public void actionPerformed(ActionEvent e) {
     253            model.setTurnRestrictionLeg(role, null);           
     254        }       
     255       
     256        public void updateEnabledState() {
     257            setEnabled(legs.size()>0);
     258        }
     259    }
     260   
     261    /**
     262    * The transfer handler for Drag-and-Drop.
     263    */
     264    class LegEditorTransferHandler extends PrimitiveIdListTransferHandler {
     265        Logger logger = Logger.getLogger(LegEditorTransferHandler.class.getName());
     266       
     267        public LegEditorTransferHandler(PrimitiveIdListProvider provider){
     268            super(provider);
     269        }
     270
     271        @SuppressWarnings("unchecked")
     272        @Override
     273        public boolean importData(JComponent comp, Transferable t) {
     274            try {
     275                List<PrimitiveId> ids = (List<PrimitiveId>)t.getTransferData(PrimitiveIdTransferable.PRIMITIVE_ID_LIST_FLAVOR);
     276                if (ids.size() !=1) {
     277                    return false;
     278                }
     279                PrimitiveId id = ids.get(0);
     280                if (!id.getType().equals(OsmPrimitiveType.WAY)) return false;
     281                model.setTurnRestrictionLeg(role, id);
     282                return true;
     283            } catch(IOException e) {
     284                // ignore
     285                return false;
     286            } catch(UnsupportedFlavorException e) {
     287                // ignore
     288                return false;
     289            }
     290        }
     291
     292        @Override
     293        protected Transferable createTransferable(JComponent c) {
     294            if (legs.size() != 1) return null;
     295            return super.createTransferable(c);
     296        }
     297    }
     298   
     299    class PopupLauncher extends PopupMenuLauncher {
     300        @Override
     301        public void launch(MouseEvent evt) {
     302            new PopupMenu().show(lblOsmObject, evt.getX(), evt.getY());
     303        }       
     304    }
     305   
     306    class PopupMenu extends JPopupMenu {
     307        public PopupMenu() {
     308            actCopy.updateEnabledState();
     309            JMenuItem item = add(actCopy);
     310            item.setTransferHandler(transferHandler);
     311            actPaste.updateEnabledState();
     312            item = add(actPaste);           
     313            item.setTransferHandler(transferHandler);
     314            addSeparator();
     315            add(actDelete);
     316        }
     317    }
     318   
     319    class CopyAction extends AbstractAction {
     320        private Action delegate;
     321       
     322        public CopyAction(){
     323            putValue(NAME, tr("Copy"));
     324            putValue(SHORT_DESCRIPTION, tr("Copy to the clipboard"));
     325            putValue(SMALL_ICON, ImageProvider.get("copy"));
     326            putValue(ACCELERATOR_KEY, Shortcut.getCopyKeyStroke());
     327            delegate = TurnRestrictionLegEditor.this.getActionMap().get("copy");
     328            updateEnabledState();
     329        }
     330
     331        public void actionPerformed(ActionEvent e) {
     332            delegate.actionPerformed(e);
     333        }
     334       
     335        public void updateEnabledState() {
     336            setEnabled(legs.size() == 1);
     337        }
     338    }
     339   
     340    class PasteAction extends AbstractAction {
     341        private Action delegate;
     342       
     343        public boolean canPaste() {
     344            Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
     345            for (DataFlavor df: clipboard.getAvailableDataFlavors()) {
     346                if (df.equals(PrimitiveIdTransferable.PRIMITIVE_ID_LIST_FLAVOR)) return true;
     347            }           
     348            // FIXME: check whether there are selected objects in the JOSM copy/paste buffer 
     349            return false;
     350        }
     351       
     352        public PasteAction(){
     353            putValue(NAME, tr("Paste"));
     354            putValue(SHORT_DESCRIPTION, tr("Paste from the clipboard"));
     355            putValue(SMALL_ICON, ImageProvider.get("paste"));
     356            putValue(ACCELERATOR_KEY, Shortcut.getPasteKeyStroke());
     357            delegate = TurnRestrictionLegEditor.this.getActionMap().get("paste");
     358        }
     359       
     360        public void updateEnabledState() {
     361            setEnabled(canPaste());
     362        }
     363
     364        public void actionPerformed(ActionEvent e) {
     365            delegate.actionPerformed(e);           
     366        }
     367    }
    368368}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/TurnRestrictionLegRole.java

    r20622 r23192  
    44 * Enumerates the two roles a "leg" in a turn restriction can have.
    55 */
    6 public enum TurnRestrictionLegRole {   
    7         FROM("from"),
    8         TO("to");
    9        
    10         private String osmRoleName;
    11        
    12         private TurnRestrictionLegRole(String osmRoleName) {
    13                 this.osmRoleName = osmRoleName;
    14         }
    15        
    16         public String getOsmRole() {
    17                 return osmRoleName;
    18         }
     6public enum TurnRestrictionLegRole {   
     7    FROM("from"),
     8    TO("to");
     9   
     10    private String osmRoleName;
     11   
     12    private TurnRestrictionLegRole(String osmRoleName) {
     13        this.osmRoleName = osmRoleName;
     14    }
     15   
     16    public String getOsmRole() {
     17        return osmRoleName;
     18    }
    1919}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/TurnRestrictionSelectionPopupPanel.java

    r20606 r23192  
    5050 */
    5151public class TurnRestrictionSelectionPopupPanel extends JPanel{
    52         static private final Logger logger = Logger.getLogger(TurnRestrictionSelectionPopupPanel.class.getName());
    53 
    54         /** the parent popup */
    55         private Popup parentPopup;
    56         /** the button for creating a new turn restriction */
    57         private JButton btnNew;
    58         /** the table with the turn restrictions which can be edited */
    59         private JTable tblTurnRestrictions;     
    60         private OsmDataLayer layer;
    61        
    62        
    63        
    64         /**
    65         * Replies the collection of turn restrictions the primitives in {@code primitives}
    66         * currently participate in.
    67         *
    68         * @param primitives the collection of primitives. May be null.
    69         * @return the collection of "parent" turn restrictions.
    70         */
    71         static public Collection<Relation> getTurnRestrictionsParticipatingIn(Collection<OsmPrimitive> primitives){
    72                 HashSet<Relation> ret = new HashSet<Relation>();
    73                 if (primitives == null) return ret;
    74                 for (OsmPrimitive p: primitives){
    75                         if (p == null) continue;
    76                         if (p.isDeleted() || !p.isVisible()) continue;
    77                         for (OsmPrimitive parent: p.getReferrers()){
    78                                 if (!(parent instanceof Relation)) continue;
    79                                 String type = parent.get("type");
    80                                 if (type == null || ! type.equals("restriction")) continue;
    81                                 if (parent.isDeleted() || ! parent.isVisible()) continue;
    82                                 ret.add((Relation)parent);
    83                         }
    84                 }
    85                 return ret;
    86         }
    87        
    88         /**
    89         * Registers 1..9 shortcuts for the first 9 turn restrictions to
    90         * edit
    91         *
    92         * @param editCandiates the edit candidates
    93         */
    94         protected void registerEditShortcuts(Collection<Relation> editCandiates){
    95                 for(int i=1; i <= Math.min(editCandiates.size(),9);i++){
    96                         int vkey = 0;
    97                         switch(i){
    98                         case 1: vkey = KeyEvent.VK_1; break;
    99                         case 2: vkey = KeyEvent.VK_2; break;
    100                         case 3: vkey = KeyEvent.VK_3; break;
    101                         case 4: vkey = KeyEvent.VK_4; break;
    102                         case 5: vkey = KeyEvent.VK_5; break;
    103                         case 6: vkey = KeyEvent.VK_6; break;
    104                         case 7: vkey = KeyEvent.VK_7; break;
    105                         case 8: vkey = KeyEvent.VK_8; break;
    106                         case 9: vkey = KeyEvent.VK_9; break;
    107                         }
    108                         registerKeyboardAction(new EditTurnRestrictionAction(i-1), KeyStroke.getKeyStroke(vkey,0), WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    109                 }
    110         }
    111         /**
    112         * Builds the panel with the turn restrictions table
    113         *
    114         * @param editCandiates the list of edit candiates 
    115         * @return the panel
    116         */
    117         protected JPanel buildTurnRestrictionTablePanel(Collection<Relation> editCandiates) {
    118                 tblTurnRestrictions = new JTable(new TurnRestrictionTableModel(editCandiates), new TurnRestrictionTableColumnModel());
    119                 tblTurnRestrictions.setColumnSelectionAllowed(false);
    120                 tblTurnRestrictions.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    121                 TurnRestrictionCellRenderer renderer = new TurnRestrictionCellRenderer();
    122                 tblTurnRestrictions.setRowHeight((int)renderer.getPreferredSize().getHeight());
    123                
    124                 // create a scroll pane, remove the table header
    125                 JScrollPane pane = new JScrollPane(tblTurnRestrictions);
    126                 pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    127                 pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
    128                 tblTurnRestrictions.setTableHeader(null);
    129                 pane.setColumnHeaderView(null);
    130                
    131                 // respond to double click and ENTER
    132                 EditSelectedTurnRestrictionAction action = new EditSelectedTurnRestrictionAction();
    133                 tblTurnRestrictions.addMouseListener(action);
    134                 tblTurnRestrictions.registerKeyboardAction(action, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0), WHEN_FOCUSED);
    135                
    136                 tblTurnRestrictions.addFocusListener(new FocusHandler());
    137                
    138                 JPanel pnl = new JPanel(new BorderLayout());
    139                 pnl.add(pane, BorderLayout.CENTER);
    140                
    141                 pnl.setBackground(UIManager.getColor("Table.background"));
    142                 pane.setBackground(UIManager.getColor("Table.background"));
    143                 return pnl;             
    144         }
    145        
    146         /**
    147         * Builds the panel
    148         *
    149         * @param editCandiates the edit candidates
    150         */
    151         protected void build(Collection<Relation> editCandiates) {
    152                 setLayout(new BorderLayout());
    153                 add(btnNew = new JButton(new NewAction()), BorderLayout.NORTH);
    154                 btnNew.setFocusable(true);
    155                 btnNew.registerKeyboardAction(btnNew.getAction(), KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0), WHEN_FOCUSED);
    156                 registerKeyboardAction(new CloseAction(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0), WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    157                 registerKeyboardAction(btnNew.getAction(), KeyStroke.getKeyStroke(KeyEvent.VK_N,0), WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    158                
    159                 btnNew.addFocusListener(new FocusHandler());
    160                
    161                 if (editCandiates != null && ! editCandiates.isEmpty()) {
    162                         add(buildTurnRestrictionTablePanel(editCandiates), BorderLayout.CENTER);       
    163                         registerEditShortcuts(editCandiates);
    164                 }
    165                
    166                 setBackground(UIManager.getColor("Table.background"));         
    167         }
    168 
    169        
    170         /**
    171         * Creates the panel
    172         *
    173         * @param layer the reference OSM data layer. Must not be null.
    174         * @throws IllegalArgumentException thrown if {@code layer} is null
    175         */
    176         public TurnRestrictionSelectionPopupPanel(OsmDataLayer layer) throws IllegalArgumentException {
    177                 CheckParameterUtil.ensureParameterNotNull(layer, "layer");
    178                 this.layer = layer;
    179                 build(getTurnRestrictionsParticipatingIn(layer.data.getSelected()));
    180         }
    181        
    182         /**
    183         * Creates the panel
    184         *
    185         * @param layer the reference OSM data layer. Must not be null.
    186         * @param editCandidates a collection of turn restrictions as edit candidates. May be null.
    187         * @throws IllegalArgumentException thrown if {@code layer} is null
    188         */
    189         public TurnRestrictionSelectionPopupPanel(OsmDataLayer layer, Collection<Relation> editCandiates) {
    190                 CheckParameterUtil.ensureParameterNotNull(layer, "layer");
    191                 this.layer = layer;
    192                 build(editCandiates);
    193         }
    194        
    195         /**
    196         * Launches a popup with this panel as content
    197         */
    198         public void launch(){
    199                 PointerInfo info = MouseInfo.getPointerInfo();
    200                 Point pt = info.getLocation();
    201                 parentPopup = PopupFactory.getSharedInstance().getPopup(Main.map.mapView,this, pt.x, pt.y);
    202                 parentPopup.show();
    203                 btnNew.requestFocusInWindow();
    204         }
    205 
    206         @Override
    207         public Dimension getPreferredSize() {
    208                 int bestheight = (int)btnNew.getPreferredSize().getHeight()
    209                       + Math.min(2, tblTurnRestrictions.getRowCount()) * tblTurnRestrictions.getRowHeight()
    210                       + 5;
    211                 return new Dimension(300, bestheight);
    212         }
    213        
    214         /* --------------------------------------------------------------------------------------- */
    215         /* inner classes                                                                           */
    216         /* --------------------------------------------------------------------------------------- */
    217        
    218         private class NewAction extends AbstractAction {
    219                 public NewAction() {
    220                         putValue(NAME, tr("Create new turn restriction"));
    221                         putValue(SHORT_DESCRIPTION, tr("Launch the turn restriction editor to create a new turn restriction"));
    222                         putValue(SMALL_ICON, ImageProvider.get("new"));
    223                         putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_N, 0));
    224                 }
    225 
    226                 public void actionPerformed(ActionEvent e) {
    227                         Relation tr = new TurnRestrictionBuilder().buildFromSelection(layer);
    228                         TurnRestrictionEditor editor = new TurnRestrictionEditor(Main.map.mapView,layer,tr);
    229                         TurnRestrictionEditorManager.getInstance().positionOnScreen(editor);
    230                         TurnRestrictionEditorManager.getInstance().register(layer, tr, editor);
    231                         if (parentPopup != null){
    232                                 parentPopup.hide();
    233                         }
    234                         editor.setVisible(true);
    235                 }
    236         }
    237        
    238         abstract private  class AbstractEditTurnRestrictionAction extends AbstractAction {
    239                 protected void launchEditor(Relation tr){
    240                         TurnRestrictionEditorManager manager = TurnRestrictionEditorManager.getInstance();
    241                         TurnRestrictionEditor editor = manager.getEditorForRelation(layer, tr);
    242                         if (parentPopup != null){
    243                                 parentPopup.hide();
    244                         }
    245                         if (editor != null) {
    246                                 editor.setVisible(true);
    247                                 editor.toFront();
    248                         } else {
    249                                 editor = new TurnRestrictionEditor(Main.map.mapView, layer,tr);
    250                                 manager.positionOnScreen(editor);
    251                                 manager.register(layer, tr,editor);
    252                                 editor.setVisible(true);
    253                         }
    254                 }
    255         }
    256        
    257         private class EditTurnRestrictionAction extends AbstractEditTurnRestrictionAction {
    258                 private int idx;
    259                
    260                 public EditTurnRestrictionAction(int idx){
    261                         this.idx = idx;
    262                 }
    263                
    264                 public void actionPerformed(ActionEvent e) {
    265                         Relation tr = (Relation)tblTurnRestrictions.getModel().getValueAt(idx, 1);
    266                         launchEditor(tr);
    267                 }               
    268         }
    269        
    270         private class EditSelectedTurnRestrictionAction extends AbstractEditTurnRestrictionAction implements MouseListener{
    271                 public void editTurnRestrictionAtRow(int row){
    272                         if (row < 0) return;
    273                         Relation tr = (Relation)tblTurnRestrictions.getModel().getValueAt(row, 1);
    274                         launchEditor(tr);
    275                 }
    276                 public void actionPerformed(ActionEvent e) {
    277                         int row = tblTurnRestrictions.getSelectedRow();
    278                         editTurnRestrictionAtRow(row);
    279                 }
    280                 public void mouseClicked(MouseEvent e) {
    281                         if (!(SwingUtilities.isLeftMouseButton(e) && e.getClickCount() >= 2)) return;
    282                         int row = tblTurnRestrictions.rowAtPoint(e.getPoint());
    283                         if (row < 0) return;
    284                         editTurnRestrictionAtRow(row);                 
    285                 }
    286                 public void mouseEntered(MouseEvent e) {}
    287                 public void mouseExited(MouseEvent e) {}
    288                 public void mousePressed(MouseEvent e) {}
    289                 public void mouseReleased(MouseEvent e) {}
    290         }
    291        
    292         private class CloseAction extends AbstractAction {
    293                 public void actionPerformed(ActionEvent e) {
    294                         if (parentPopup != null){
    295                                 parentPopup.hide();
    296                         }
    297                 }               
    298         }
    299        
    300         private static class TurnRestrictionTableModel extends AbstractTableModel {
    301                 private final ArrayList<Relation> turnrestrictions = new ArrayList<Relation>();
    302 
    303                 public TurnRestrictionTableModel(Collection<Relation> turnrestrictions){
    304                         this.turnrestrictions.clear();
    305                         if (turnrestrictions != null){
    306                                 this.turnrestrictions.addAll(turnrestrictions);
    307                         }
    308                         fireTableDataChanged();
    309                 }
    310                
    311                 public int getRowCount() {
    312                         return turnrestrictions.size();
    313                 }
    314 
    315                 public int getColumnCount() {
    316                         return 2;
    317                 }
    318 
    319                 public Object getValueAt(int rowIndex, int columnIndex) {
    320                         switch(columnIndex){
    321                         case 0:
    322                                 if (rowIndex <=8 ) {
    323                                         return Integer.toString(rowIndex+1);
    324                                 } else {
    325                                         return "";
    326                                 }
    327                         case 1:
    328                                 return turnrestrictions.get(rowIndex);
    329                         }
    330                         // should not happen
    331                         return null;
    332                 }
    333         }
    334        
    335         private static class TurnRestrictionTableColumnModel extends DefaultTableColumnModel {         
    336                 public TurnRestrictionTableColumnModel() {                     
    337                         // the idx column
    338                         TableColumn col = new TableColumn(0);                   
    339                         col.setResizable(false);
    340                         col.setWidth(50);
    341                         addColumn(col);
    342                        
    343                         // the column displaying turn restrictions
    344                         col = new TableColumn(1);                       
    345                         col.setResizable(false);
    346                         col.setPreferredWidth(400);
    347                         col.setCellRenderer(new TurnRestrictionCellRenderer());
    348                         addColumn(col);                 
    349                 }
    350         }
    351        
    352         private class FocusHandler extends FocusAdapter {               
    353                 @Override
    354                 public void focusLost(FocusEvent e) {
    355                         // if we loose the focus to a component outside of the popup panel
    356                         // we hide the popup                   
    357                         if (e.getOppositeComponent() == null ||!SwingUtilities.isDescendingFrom(e.getOppositeComponent(), TurnRestrictionSelectionPopupPanel.this)) {
    358                                 if (parentPopup != null){
    359                                         parentPopup.hide();
    360                                 }
    361                         }
    362                 }
    363         }
     52    static private final Logger logger = Logger.getLogger(TurnRestrictionSelectionPopupPanel.class.getName());
     53
     54    /** the parent popup */
     55    private Popup parentPopup;
     56    /** the button for creating a new turn restriction */
     57    private JButton btnNew;
     58    /** the table with the turn restrictions which can be edited */
     59    private JTable tblTurnRestrictions;
     60    private OsmDataLayer layer;
     61   
     62   
     63   
     64    /**
     65    * Replies the collection of turn restrictions the primitives in {@code primitives}
     66    * currently participate in.
     67    *
     68    * @param primitives the collection of primitives. May be null.
     69    * @return the collection of "parent" turn restrictions.
     70    */
     71    static public Collection<Relation> getTurnRestrictionsParticipatingIn(Collection<OsmPrimitive> primitives){
     72        HashSet<Relation> ret = new HashSet<Relation>();
     73        if (primitives == null) return ret;
     74        for (OsmPrimitive p: primitives){
     75            if (p == null) continue;
     76            if (p.isDeleted() || !p.isVisible()) continue;
     77            for (OsmPrimitive parent: p.getReferrers()){
     78                if (!(parent instanceof Relation)) continue;
     79                String type = parent.get("type");
     80                if (type == null || ! type.equals("restriction")) continue;
     81                if (parent.isDeleted() || ! parent.isVisible()) continue;
     82                ret.add((Relation)parent);
     83            }
     84        }
     85        return ret;
     86    }
     87   
     88    /**
     89    * Registers 1..9 shortcuts for the first 9 turn restrictions to
     90    * edit
     91    *
     92    * @param editCandiates the edit candidates
     93    */
     94    protected void registerEditShortcuts(Collection<Relation> editCandiates){
     95        for(int i=1; i <= Math.min(editCandiates.size(),9);i++){
     96            int vkey = 0;
     97            switch(i){
     98            case 1: vkey = KeyEvent.VK_1; break;
     99            case 2: vkey = KeyEvent.VK_2; break;
     100            case 3: vkey = KeyEvent.VK_3; break;
     101            case 4: vkey = KeyEvent.VK_4; break;
     102            case 5: vkey = KeyEvent.VK_5; break;
     103            case 6: vkey = KeyEvent.VK_6; break;
     104            case 7: vkey = KeyEvent.VK_7; break;
     105            case 8: vkey = KeyEvent.VK_8; break;
     106            case 9: vkey = KeyEvent.VK_9; break;
     107            }
     108            registerKeyboardAction(new EditTurnRestrictionAction(i-1), KeyStroke.getKeyStroke(vkey,0), WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
     109        }
     110    }
     111    /**
     112    * Builds the panel with the turn restrictions table
     113    *
     114    * @param editCandiates the list of edit candiates 
     115    * @return the panel
     116    */
     117    protected JPanel buildTurnRestrictionTablePanel(Collection<Relation> editCandiates) {
     118        tblTurnRestrictions = new JTable(new TurnRestrictionTableModel(editCandiates), new TurnRestrictionTableColumnModel());
     119        tblTurnRestrictions.setColumnSelectionAllowed(false);
     120        tblTurnRestrictions.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
     121        TurnRestrictionCellRenderer renderer = new TurnRestrictionCellRenderer();
     122        tblTurnRestrictions.setRowHeight((int)renderer.getPreferredSize().getHeight());
     123       
     124        // create a scroll pane, remove the table header
     125        JScrollPane pane = new JScrollPane(tblTurnRestrictions);
     126        pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
     127        pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
     128        tblTurnRestrictions.setTableHeader(null);
     129        pane.setColumnHeaderView(null);
     130       
     131        // respond to double click and ENTER
     132        EditSelectedTurnRestrictionAction action = new EditSelectedTurnRestrictionAction();
     133        tblTurnRestrictions.addMouseListener(action);
     134        tblTurnRestrictions.registerKeyboardAction(action, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0), WHEN_FOCUSED);
     135       
     136        tblTurnRestrictions.addFocusListener(new FocusHandler());
     137       
     138        JPanel pnl = new JPanel(new BorderLayout());
     139        pnl.add(pane, BorderLayout.CENTER);
     140       
     141        pnl.setBackground(UIManager.getColor("Table.background"));
     142        pane.setBackground(UIManager.getColor("Table.background"));
     143        return pnl;     
     144    }
     145   
     146    /**
     147    * Builds the panel
     148    *
     149    * @param editCandiates the edit candidates
     150    */
     151    protected void build(Collection<Relation> editCandiates) {
     152        setLayout(new BorderLayout());
     153        add(btnNew = new JButton(new NewAction()), BorderLayout.NORTH);
     154        btnNew.setFocusable(true);
     155        btnNew.registerKeyboardAction(btnNew.getAction(), KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0), WHEN_FOCUSED);
     156        registerKeyboardAction(new CloseAction(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0), WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
     157        registerKeyboardAction(btnNew.getAction(), KeyStroke.getKeyStroke(KeyEvent.VK_N,0), WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
     158       
     159        btnNew.addFocusListener(new FocusHandler());
     160       
     161        if (editCandiates != null && ! editCandiates.isEmpty()) {
     162            add(buildTurnRestrictionTablePanel(editCandiates), BorderLayout.CENTER);   
     163            registerEditShortcuts(editCandiates);
     164        }
     165       
     166        setBackground(UIManager.getColor("Table.background"));     
     167    }
     168
     169   
     170    /**
     171    * Creates the panel
     172    *
     173    * @param layer the reference OSM data layer. Must not be null.
     174    * @throws IllegalArgumentException thrown if {@code layer} is null
     175    */
     176    public TurnRestrictionSelectionPopupPanel(OsmDataLayer layer) throws IllegalArgumentException {
     177        CheckParameterUtil.ensureParameterNotNull(layer, "layer");
     178        this.layer = layer;
     179        build(getTurnRestrictionsParticipatingIn(layer.data.getSelected()));
     180    }
     181   
     182    /**
     183    * Creates the panel
     184    *
     185    * @param layer the reference OSM data layer. Must not be null.
     186    * @param editCandidates a collection of turn restrictions as edit candidates. May be null.
     187    * @throws IllegalArgumentException thrown if {@code layer} is null
     188    */
     189    public TurnRestrictionSelectionPopupPanel(OsmDataLayer layer, Collection<Relation> editCandiates) {
     190        CheckParameterUtil.ensureParameterNotNull(layer, "layer");
     191        this.layer = layer;
     192        build(editCandiates);
     193    }
     194   
     195    /**
     196    * Launches a popup with this panel as content
     197    */
     198    public void launch(){
     199        PointerInfo info = MouseInfo.getPointerInfo();
     200        Point pt = info.getLocation();
     201        parentPopup = PopupFactory.getSharedInstance().getPopup(Main.map.mapView,this, pt.x, pt.y);
     202        parentPopup.show();
     203        btnNew.requestFocusInWindow();
     204    }
     205
     206    @Override
     207    public Dimension getPreferredSize() {
     208        int bestheight = (int)btnNew.getPreferredSize().getHeight()
     209              + Math.min(2, tblTurnRestrictions.getRowCount()) * tblTurnRestrictions.getRowHeight()
     210              + 5;
     211        return new Dimension(300, bestheight);
     212    }
     213   
     214    /* --------------------------------------------------------------------------------------- */
     215    /* inner classes                                                                           */
     216    /* --------------------------------------------------------------------------------------- */
     217   
     218    private class NewAction extends AbstractAction {
     219        public NewAction() {
     220            putValue(NAME, tr("Create new turn restriction"));
     221            putValue(SHORT_DESCRIPTION, tr("Launch the turn restriction editor to create a new turn restriction"));
     222            putValue(SMALL_ICON, ImageProvider.get("new"));
     223            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_N, 0));
     224        }
     225
     226        public void actionPerformed(ActionEvent e) {
     227            Relation tr = new TurnRestrictionBuilder().buildFromSelection(layer);
     228            TurnRestrictionEditor editor = new TurnRestrictionEditor(Main.map.mapView,layer,tr);
     229            TurnRestrictionEditorManager.getInstance().positionOnScreen(editor);
     230            TurnRestrictionEditorManager.getInstance().register(layer, tr, editor);
     231            if (parentPopup != null){
     232                parentPopup.hide();
     233            }
     234            editor.setVisible(true);
     235        }
     236    }
     237   
     238    abstract private  class AbstractEditTurnRestrictionAction extends AbstractAction {
     239        protected void launchEditor(Relation tr){
     240            TurnRestrictionEditorManager manager = TurnRestrictionEditorManager.getInstance();
     241            TurnRestrictionEditor editor = manager.getEditorForRelation(layer, tr);
     242            if (parentPopup != null){
     243                parentPopup.hide();
     244            }
     245            if (editor != null) {
     246                editor.setVisible(true);
     247                editor.toFront();
     248            } else {
     249                editor = new TurnRestrictionEditor(Main.map.mapView, layer,tr);
     250                manager.positionOnScreen(editor);
     251                manager.register(layer, tr,editor);
     252                editor.setVisible(true);
     253            }
     254        }
     255    }
     256   
     257    private class EditTurnRestrictionAction extends AbstractEditTurnRestrictionAction {
     258        private int idx;
     259       
     260        public EditTurnRestrictionAction(int idx){
     261            this.idx = idx;
     262        }
     263       
     264        public void actionPerformed(ActionEvent e) {
     265            Relation tr = (Relation)tblTurnRestrictions.getModel().getValueAt(idx, 1);
     266            launchEditor(tr);
     267        }       
     268    }
     269   
     270    private class EditSelectedTurnRestrictionAction extends AbstractEditTurnRestrictionAction implements MouseListener{
     271        public void editTurnRestrictionAtRow(int row){
     272            if (row < 0) return;
     273            Relation tr = (Relation)tblTurnRestrictions.getModel().getValueAt(row, 1);
     274            launchEditor(tr);
     275        }
     276        public void actionPerformed(ActionEvent e) {
     277            int row = tblTurnRestrictions.getSelectedRow();
     278            editTurnRestrictionAtRow(row);
     279        }
     280        public void mouseClicked(MouseEvent e) {
     281            if (!(SwingUtilities.isLeftMouseButton(e) && e.getClickCount() >= 2)) return;
     282            int row = tblTurnRestrictions.rowAtPoint(e.getPoint());
     283            if (row < 0) return;
     284            editTurnRestrictionAtRow(row);         
     285        }
     286        public void mouseEntered(MouseEvent e) {}
     287        public void mouseExited(MouseEvent e) {}
     288        public void mousePressed(MouseEvent e) {}
     289        public void mouseReleased(MouseEvent e) {}
     290    }
     291   
     292    private class CloseAction extends AbstractAction {
     293        public void actionPerformed(ActionEvent e) {
     294            if (parentPopup != null){
     295                parentPopup.hide();
     296            }
     297        }       
     298    }
     299   
     300    private static class TurnRestrictionTableModel extends AbstractTableModel {
     301        private final ArrayList<Relation> turnrestrictions = new ArrayList<Relation>();
     302
     303        public TurnRestrictionTableModel(Collection<Relation> turnrestrictions){
     304            this.turnrestrictions.clear();
     305            if (turnrestrictions != null){
     306                this.turnrestrictions.addAll(turnrestrictions);
     307            }
     308            fireTableDataChanged();
     309        }
     310       
     311        public int getRowCount() {
     312            return turnrestrictions.size();
     313        }
     314
     315        public int getColumnCount() {
     316            return 2;
     317        }
     318
     319        public Object getValueAt(int rowIndex, int columnIndex) {
     320            switch(columnIndex){
     321            case 0:
     322                if (rowIndex <=8 ) {
     323                    return Integer.toString(rowIndex+1);
     324                } else {
     325                    return "";
     326                }
     327            case 1:
     328                return turnrestrictions.get(rowIndex);
     329            }
     330            // should not happen
     331            return null;
     332        }
     333    }
     334   
     335    private static class TurnRestrictionTableColumnModel extends DefaultTableColumnModel {     
     336        public TurnRestrictionTableColumnModel() {         
     337            // the idx column
     338            TableColumn col = new TableColumn(0);           
     339            col.setResizable(false);
     340            col.setWidth(50);
     341            addColumn(col);
     342           
     343            // the column displaying turn restrictions
     344            col = new TableColumn(1);           
     345            col.setResizable(false);
     346            col.setPreferredWidth(400);
     347            col.setCellRenderer(new TurnRestrictionCellRenderer());
     348            addColumn(col);         
     349        }
     350    }
     351   
     352    private class FocusHandler extends FocusAdapter {       
     353        @Override
     354        public void focusLost(FocusEvent e) {
     355            // if we loose the focus to a component outside of the popup panel
     356            // we hide the popup           
     357            if (e.getOppositeComponent() == null ||!SwingUtilities.isDescendingFrom(e.getOppositeComponent(), TurnRestrictionSelectionPopupPanel.this)) {
     358                if (parentPopup != null){
     359                    parentPopup.hide();
     360                }
     361            }
     362        }
     363    }
    364364}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/TurnRestrictionType.java

    r20586 r23192  
    99 */
    1010public enum TurnRestrictionType {
    11         NO_RIGHT_TURN("no_right_turn", tr("No Right Turn")),
    12         NO_LEFT_TURN("no_left_turn", tr("No Left Turn")),
    13         NO_U_TURN("no_u_turn", tr("No U-Turn")),
    14         NO_STRAIGHT_ON("no_straight_on", tr("No Straight On")),
    15         ONLY_RIGHT_TURN("only_right_turn", tr("Only Right Turn")),
    16         ONLY_LEFT_TURN("only_left_turn", tr("Only Left Turn")),
    17         ONLY_STRAIGHT_ON("only_straight_on", tr("Only Straight On"));
    18        
    19         private String tagValue;
    20         private String displayName;
    21        
    22         TurnRestrictionType(String tagValue, String displayName) {
    23                 this.tagValue = tagValue;
    24                 this.displayName = displayName;
    25         }
    26        
    27         /**
    28         * Replies the tag value for a specific turn restriction type
    29         *
    30         * @return the tag value for a specific turn restriction type
    31         */
    32         public String getTagValue() {
    33                 return tagValue;
    34         }
    35        
    36         /**
    37         * Replies the localized display name for a turn restriction type
    38         */
    39         public String getDisplayName() {
    40                 return displayName;
    41         }       
    42        
    43         /**
    44         * Replies the enumeration value for a given tag value. null,
    45         * if {@code tagValue} is null or if there isnt an enumeration value
    46         * for this {@code tagValue}
    47        
    48         * @param tagValue the tag value, i.e. <tt>no_left_turn</tt>
    49         * @return the enumeration value
    50         */
    51         static public TurnRestrictionType fromTagValue(String tagValue) {
    52                 if (tagValue == null) return null;
    53                 for(TurnRestrictionType type: values()) {
    54                         if(type.getTagValue().equals(tagValue)) return type;
    55                 }
    56                 return null;
    57         }
     11    NO_RIGHT_TURN("no_right_turn", tr("No Right Turn")),
     12    NO_LEFT_TURN("no_left_turn", tr("No Left Turn")),
     13    NO_U_TURN("no_u_turn", tr("No U-Turn")),
     14    NO_STRAIGHT_ON("no_straight_on", tr("No Straight On")),
     15    ONLY_RIGHT_TURN("only_right_turn", tr("Only Right Turn")),
     16    ONLY_LEFT_TURN("only_left_turn", tr("Only Left Turn")),
     17    ONLY_STRAIGHT_ON("only_straight_on", tr("Only Straight On"));
     18   
     19    private String tagValue;
     20    private String displayName;
     21   
     22    TurnRestrictionType(String tagValue, String displayName) {
     23        this.tagValue = tagValue;
     24        this.displayName = displayName;
     25    }
     26   
     27    /**
     28    * Replies the tag value for a specific turn restriction type
     29    *
     30    * @return the tag value for a specific turn restriction type
     31    */
     32    public String getTagValue() {
     33        return tagValue;
     34    }
     35   
     36    /**
     37    * Replies the localized display name for a turn restriction type
     38    */
     39    public String getDisplayName() {
     40        return displayName;
     41    }   
     42   
     43    /**
     44    * Replies the enumeration value for a given tag value. null,
     45    * if {@code tagValue} is null or if there isnt an enumeration value
     46    * for this {@code tagValue}
     47   
     48    * @param tagValue the tag value, i.e. <tt>no_left_turn</tt>
     49    * @return the enumeration value
     50    */
     51    static public TurnRestrictionType fromTagValue(String tagValue) {
     52        if (tagValue == null) return null;
     53        for(TurnRestrictionType type: values()) {
     54            if(type.getTagValue().equals(tagValue)) return type;
     55        }
     56        return null;
     57    }
    5858
    59         /**
    60         * Replies true if {@code tagValue} is a standard restriction type.
    61         *
    62         * @param tagValue the tag value
    63         * @return true if {@code tagValue} is a standard restriction type
    64         */
    65         static public boolean isStandardTagValue(String tagValue){
    66                 return fromTagValue(tagValue) != null;
    67         }
     59    /**
     60    * Replies true if {@code tagValue} is a standard restriction type.
     61    *
     62    * @param tagValue the tag value
     63    * @return true if {@code tagValue} is a standard restriction type
     64    */
     65    static public boolean isStandardTagValue(String tagValue){
     66        return fromTagValue(tagValue) != null;
     67    }
    6868}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/TurnRestrictionTypeRenderer.java

    r20666 r23192  
    2020public class TurnRestrictionTypeRenderer extends JLabel implements ListCellRenderer{
    2121 
    22         final private Map<TurnRestrictionType, ImageIcon> icons = new HashMap<TurnRestrictionType, ImageIcon>();
    23         private String iconSet = "set-a";
    24        
    25         /**
    26         * Loads the image icons for the rendered turn restriction types
    27         */
    28         protected void loadImages() {
    29                 for(TurnRestrictionType type: TurnRestrictionType.values()) {
    30                         try {
    31                                 ImageIcon icon = new ImageIcon(ImageProvider.get("types/" + iconSet, type.getTagValue()).getImage().getScaledInstance(16, 16, Image.SCALE_SMOOTH));
    32                                 icons.put(type,icon);
    33                         } catch(Exception e){
    34                                 System.out.println(tr("Warning: failed to load icon for turn restriction type ''{0}''", type.getTagValue()));
    35                                 e.printStackTrace();                           
    36                         }
    37                 }
    38         }
    39        
    40         public TurnRestrictionTypeRenderer() {
    41                 setOpaque(true);
    42                 loadImages();
    43         }
    44        
    45         protected void renderColors(boolean isSelected){
    46                 if (isSelected){
    47                         setBackground(UIManager.getColor("List.selectionBackground"));
    48                         setForeground(UIManager.getColor("List.selectionForeground"));
    49                 } else {
    50                         setBackground(UIManager.getColor("List.background"));
    51                         setForeground(UIManager.getColor("List.foreground"));                   
    52                 }
    53         }
    54        
    55         /**
    56         * Initializes the set of icons used from the preference key
    57         * {@see PreferenceKeys#ROAD_SIGNS}.
    58         *
    59         * @param prefs the JOSM preferences
    60         */
    61         public void initIconSetFromPreferences(Preferences prefs){             
    62                 iconSet = prefs.get(PreferenceKeys.ROAD_SIGNS, "set-a");
    63                 iconSet = iconSet.trim().toLowerCase();
    64                 if (!iconSet.equals("set-a") && !iconSet.equals("set-b")) {
    65                         iconSet = "set-a";
    66                 }
    67                 loadImages();
    68         }
    69        
    70         public Component getListCellRendererComponent(JList list, Object value,
    71                         int index, boolean isSelected, boolean cellHasFocus) {
    72                
    73                 renderColors(isSelected);
    74                 if (value == null) {
    75                         setText(tr("please select a turn restriction type"));
    76                         setIcon(null);
    77                 } else if (value instanceof String){
    78                         setText((String)value);
    79                         setIcon(null); // FIXME: special icon for non-standard types?
    80                 } else if (value instanceof TurnRestrictionType){
    81                         TurnRestrictionType type = (TurnRestrictionType)value;
    82                         setText(type.getDisplayName());
    83                         setIcon(icons.get(type));
    84                 }
    85                 return this;
    86         }       
     22    final private Map<TurnRestrictionType, ImageIcon> icons = new HashMap<TurnRestrictionType, ImageIcon>();
     23    private String iconSet = "set-a";
     24   
     25    /**
     26    * Loads the image icons for the rendered turn restriction types
     27    */
     28    protected void loadImages() {
     29        for(TurnRestrictionType type: TurnRestrictionType.values()) {
     30            try {
     31                ImageIcon icon = new ImageIcon(ImageProvider.get("types/" + iconSet, type.getTagValue()).getImage().getScaledInstance(16, 16, Image.SCALE_SMOOTH));
     32                icons.put(type,icon);
     33            } catch(Exception e){
     34                System.out.println(tr("Warning: failed to load icon for turn restriction type ''{0}''", type.getTagValue()));
     35                e.printStackTrace();               
     36            }
     37        }
     38    }
     39   
     40    public TurnRestrictionTypeRenderer() {
     41        setOpaque(true);
     42        loadImages();
     43    }
     44   
     45    protected void renderColors(boolean isSelected){
     46        if (isSelected){
     47            setBackground(UIManager.getColor("List.selectionBackground"));
     48            setForeground(UIManager.getColor("List.selectionForeground"));
     49        } else {
     50            setBackground(UIManager.getColor("List.background"));
     51            setForeground(UIManager.getColor("List.foreground"));           
     52        }
     53    }
     54   
     55    /**
     56    * Initializes the set of icons used from the preference key
     57    * {@see PreferenceKeys#ROAD_SIGNS}.
     58    *
     59    * @param prefs the JOSM preferences
     60    */
     61    public void initIconSetFromPreferences(Preferences prefs){     
     62        iconSet = prefs.get(PreferenceKeys.ROAD_SIGNS, "set-a");
     63        iconSet = iconSet.trim().toLowerCase();
     64        if (!iconSet.equals("set-a") && !iconSet.equals("set-b")) {
     65            iconSet = "set-a";
     66        }
     67        loadImages();
     68    }
     69   
     70    public Component getListCellRendererComponent(JList list, Object value,
     71            int index, boolean isSelected, boolean cellHasFocus) {
     72       
     73        renderColors(isSelected);
     74        if (value == null) {
     75            setText(tr("please select a turn restriction type"));
     76            setIcon(null);
     77        } else if (value instanceof String){
     78            setText((String)value);
     79            setIcon(null); // FIXME: special icon for non-standard types?
     80        } else if (value instanceof TurnRestrictionType){
     81            TurnRestrictionType type = (TurnRestrictionType)value;
     82            setText(type.getDisplayName());
     83            setIcon(icons.get(type));
     84        }
     85        return this;
     86    }   
    8787}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/VehicleExceptionEditor.java

    r20648 r23192  
    3636 */
    3737public class VehicleExceptionEditor extends JPanel implements Observer{
    38         static private final Logger logger = Logger.getLogger(VehicleExceptionEditor.class.getName());
    39        
    40         private TurnRestrictionEditorModel model;
    41         private JCheckBox cbPsv;
    42         private JCheckBox cbBicyle;
    43         private JCheckBox cbHgv;
    44         private JCheckBox cbMotorcar;
    45         private JTextField tfNonStandardValue;
    46         private ButtonGroup bgStandardOrNonStandard;
    47         private JRadioButton rbStandardException;
    48         private JRadioButton rbNonStandardException;
    49         private JPanel pnlStandard;
    50         private JPanel pnlNonStandard;
    51         private ExceptValueModel exceptValue = new ExceptValueModel();
    52        
    53         private JPanel buildMessagePanel() {
    54                 JPanel pnl = new JPanel(new BorderLayout());
    55                 HtmlPanel msg = new HtmlPanel();
    56                 pnl.add(msg, BorderLayout.CENTER);
    57                 msg.setText(
    58                                 "<html><body>"
    59                                 + tr("Select the vehicle types this turn restriction is <strong>not</strong> applicable for.")
    60                                 + "</body></html>"
    61             );
    62                 return pnl;
    63         }
    64        
    65         private JPanel buildStandardInputPanel() {
    66                 if (pnlStandard != null)
    67                         return pnlStandard;
    68                
    69                 StandardVehicleTypeChangeListener changeHandler = new StandardVehicleTypeChangeListener();
    70                
    71                 GridBagConstraints gc = new GridBagConstraints();
    72                 gc.anchor = GridBagConstraints.NORTHWEST;
    73                 gc.fill = GridBagConstraints.HORIZONTAL;
    74                 gc.gridx = 0;
    75                 gc.gridy = 0;
    76                
    77                 pnlStandard = new JPanel(new GridBagLayout());
    78                 JLabel lbl;
    79                 cbPsv = new JCheckBox();
    80                 cbPsv.addItemListener(changeHandler);
    81                 lbl = new JLabel();
    82                 lbl.setText(tr("Public Service Vehicles"));
    83                 lbl.setToolTipText(tr("Public service vehicles like buses, tramways, etc."));
    84                 lbl.setIcon(ImageProvider.get("vehicle", "psv"));
    85                
    86                 gc.weightx = 0.0;
    87                 pnlStandard.add(cbPsv, gc);
    88                 gc.weightx = 1.0;
    89                 gc.gridx++;
    90                 pnlStandard.add(lbl, gc);
    91                
    92                 cbHgv = new JCheckBox();
    93                 cbHgv.addItemListener(changeHandler);
    94                 lbl = new JLabel();
    95                 lbl.setText(tr("Heavy Goods Vehicles"));
    96                 lbl.setIcon(ImageProvider.get("vehicle", "hgv"));
    97 
    98                 gc.weightx = 0.0;
    99                 gc.gridx++;
    100                 pnlStandard.add(cbHgv, gc);
    101                 gc.weightx = 1.0;
    102                 gc.gridx++;
    103                 pnlStandard.add(lbl, gc);
    104 
    105                 cbMotorcar = new JCheckBox();
    106                 cbMotorcar.addItemListener(changeHandler);
    107                 lbl = new JLabel();
    108                 lbl.setText(tr("Motorcars"));
    109                 lbl.setIcon(ImageProvider.get("vehicle", "motorcar"));
    110                
    111                 gc.weightx = 0.0;
    112                 gc.gridx = 0;
    113                 gc.gridy = 1;
    114                 pnlStandard.add(cbMotorcar, gc);
    115                 gc.weightx = 1.0;
    116                 gc.gridx++;
    117                 pnlStandard.add(lbl, gc);
    118                
    119                 cbBicyle = new JCheckBox();
    120                 cbBicyle.addItemListener(changeHandler);
    121                 lbl = new JLabel();
    122                 lbl.setText(tr("Bicycles"));
    123                 lbl.setIcon(ImageProvider.get("vehicle", "bicycle"));
    124                
    125 
    126                 gc.weightx = 0.0;
    127                 gc.gridx++;
    128                 pnlStandard.add(cbBicyle, gc);
    129                 gc.weightx = 1.0;
    130                 gc.gridx++;
    131                 pnlStandard.add(lbl, gc);
    132                
    133                 return pnlStandard;
    134         }
    135        
    136         private JPanel buildNonStandardInputPanel() {
    137                 if (pnlNonStandard != null)
    138                         return pnlNonStandard;
    139                 pnlNonStandard = new JPanel(new GridBagLayout());
    140                 GridBagConstraints gc = new GridBagConstraints();
    141                 gc.anchor = GridBagConstraints.NORTHWEST;
    142                 gc.fill = GridBagConstraints.HORIZONTAL;
    143                 gc.weightx = 0.0;
    144                 gc.insets = new Insets(0, 0, 4, 0);
    145                 gc.gridx = 0;
    146                 gc.gridy = 0;
    147                
    148                 pnlNonStandard.add(new JLabel(tr("Value:")), gc);
    149                 gc.gridx = 1;
    150                 gc.weightx = 1.0;
    151                 pnlNonStandard.add(tfNonStandardValue = new JTextField(), gc);
    152                 SelectAllOnFocusGainedDecorator.decorate(tfNonStandardValue);
    153                
    154                 NonStandardVehicleTypesHandler inputChangedHandler = new NonStandardVehicleTypesHandler();
    155                 tfNonStandardValue.addActionListener(inputChangedHandler);
    156                 tfNonStandardValue.addFocusListener(inputChangedHandler);
    157                 return pnlNonStandard;
    158         }
    159                
    160         /**
    161         * Builds the UI for entering standard values
    162         */
    163         protected void buildStandard() {
    164                 setLayout(new GridBagLayout());
    165                 GridBagConstraints gc = new GridBagConstraints();
    166                 gc.anchor = GridBagConstraints.NORTHWEST;
    167                 gc.fill = GridBagConstraints.HORIZONTAL;
    168                 gc.weightx = 1.0;
    169                 gc.gridx = 0;
    170                 gc.gridy = 0;
    171                 add(buildMessagePanel(), gc);
    172                
    173                 gc.gridy=1;
    174                 add(buildStandardInputPanel(), gc);             
    175         }
    176        
    177         /**
    178         * Builds the UI for entering either standard or non-standard values
    179         */
    180         protected void buildNonStandard() {
    181                 setLayout(new GridBagLayout());
    182                 GridBagConstraints gc = new GridBagConstraints();
    183                 gc.anchor = GridBagConstraints.NORTHWEST;
    184                 gc.fill = GridBagConstraints.HORIZONTAL;
    185                 gc.weightx = 1.0;
    186                 gc.gridx = 0;
    187                 gc.gridy = 0;
    188                 add(buildMessagePanel(), gc);
    189                                
    190                 gc.gridx=0;
    191                 gc.gridy=1;
    192                 gc.insets = new Insets(0,0,0,0);
    193                 add(rbStandardException = new JRadioButton(tr("Use standard exceptions")), gc);
    194 
    195                 gc.gridx=0;
    196                 gc.gridy=2;
    197                 gc.insets = new Insets(0, 20, 0,0);
    198                 add(buildStandardInputPanel(), gc);
    199 
    200                 gc.gridx=0;
    201                 gc.gridy=3;
    202                 gc.insets = new Insets(0,0,0,0);
    203                 add(rbNonStandardException = new JRadioButton(tr("Use non-standard exceptions")), gc);
    204 
    205                 gc.gridx=0;
    206                 gc.gridy=4;
    207                 gc.insets = new Insets(0, 20, 0,0);
    208                 add(buildNonStandardInputPanel(), gc);
    209                
    210                 bgStandardOrNonStandard = new ButtonGroup();
    211                 bgStandardOrNonStandard.add(rbNonStandardException);
    212                 bgStandardOrNonStandard.add(rbStandardException);
    213                
    214                 StandardNonStandardChangeHander changeHandler = new StandardNonStandardChangeHander();
    215                 rbNonStandardException.addItemListener(changeHandler);
    216                 rbStandardException.addItemListener(changeHandler);
    217         }
    218        
    219         protected void build() {
    220                 removeAll();
    221                 buildNonStandardInputPanel();
    222                 buildStandardInputPanel();
    223                 if (exceptValue.isStandard()){
    224                         buildStandard();
    225                 } else {
    226                         buildNonStandard();
    227                 }
    228                 init();
    229                 invalidate();
    230         }
    231        
    232         protected void init() {
    233                 cbPsv.setSelected(exceptValue.isVehicleException("psv"));
    234                 cbBicyle.setSelected(exceptValue.isVehicleException("bicycle"));
    235                 cbMotorcar.setSelected(exceptValue.isVehicleException("motorcar"));
    236                 cbHgv.setSelected(exceptValue.isVehicleException("hgv"));
    237                 if (!exceptValue.isStandard()){
    238                         rbNonStandardException.setSelected(true);
    239                         tfNonStandardValue.setText(exceptValue.getValue());
    240                         setEnabledNonStandardInputPanel(true);
    241                         setEnabledStandardInputPanel(false);
    242                 } else {
    243                         setEnabledNonStandardInputPanel(false);
    244                         setEnabledStandardInputPanel(true);
    245                 }
    246         }
    247        
    248         protected void setEnabledStandardInputPanel(boolean enabled) {
    249                 for (Component c: pnlStandard.getComponents()){
    250                         c.setEnabled(enabled);
    251                 }
    252         }
    253        
    254         protected void setEnabledNonStandardInputPanel(boolean enabled) {
    255                 for (Component c: pnlNonStandard.getComponents()){
    256                         c.setEnabled(enabled);
    257                 }
    258         }
    259 
    260        
    261         /**
    262         * Creates the editor
    263         *
    264         * @param model the editor model. Must not be null.
    265         * @throws IllegalArgumentException thrown if {@code model} is null
    266         */
    267         public VehicleExceptionEditor(TurnRestrictionEditorModel model) throws IllegalArgumentException {
    268                 CheckParameterUtil.ensureParameterNotNull(model, "model");
    269                 this.model = model;
    270                 build();
    271                 model.addObserver(this);
    272         }
    273        
    274         /* ------------------------------------------------------------------------------------ */
    275         /* interface Observer                                                                   */
    276         /* ------------------------------------------------------------------------------------ */
    277         public void update(Observable o, Object arg) {
    278                 if (!this.exceptValue.equals(model.getExcept())) {
    279                         this.exceptValue = model.getExcept();
    280                         build();
    281                 }
    282         }
    283 
    284         /* ------------------------------------------------------------------------------------ */
    285         /* inner classes                                                                        */
    286         /* ------------------------------------------------------------------------------------ */
    287         class StandardNonStandardChangeHander implements ItemListener {
    288                 public void itemStateChanged(ItemEvent e) {
    289                         if (rbNonStandardException.isSelected()){
    290                                 setEnabledNonStandardInputPanel(true);
    291                                 setEnabledStandardInputPanel(false);
    292                                 exceptValue.setStandard(false);
    293                         } else {
    294                                 setEnabledNonStandardInputPanel(false);
    295                                 setEnabledStandardInputPanel(true);
    296                                 exceptValue.setStandard(true);
    297                         }
    298                         model.setExcept(exceptValue);
    299                 }
    300         }
    301        
    302         class StandardVehicleTypeChangeListener implements ItemListener {
    303                 public void itemStateChanged(ItemEvent e) {
    304                         exceptValue.setVehicleException("bicycle", cbBicyle.isSelected());
    305                         exceptValue.setVehicleException("hgv", cbHgv.isSelected());
    306                         exceptValue.setVehicleException("psv", cbPsv.isSelected());
    307                         exceptValue.setVehicleException("motorcar", cbMotorcar.isSelected());
    308                         model.setExcept(exceptValue);
    309                 }
    310         }
    311        
    312         class NonStandardVehicleTypesHandler implements ActionListener, FocusListener {
    313                 public void persist() {
    314                         exceptValue.setValue(tfNonStandardValue.getText());
    315                         model.setExcept(exceptValue);
    316                 }
    317                
    318                 public void focusGained(FocusEvent e) {}
    319                 public void focusLost(FocusEvent e) {
    320                         persist();
    321                 }
    322 
    323                 public void actionPerformed(ActionEvent e) {
    324                         persist();                     
    325                 }
    326         }
     38    static private final Logger logger = Logger.getLogger(VehicleExceptionEditor.class.getName());
     39   
     40    private TurnRestrictionEditorModel model;
     41    private JCheckBox cbPsv;
     42    private JCheckBox cbBicyle;
     43    private JCheckBox cbHgv;
     44    private JCheckBox cbMotorcar;
     45    private JTextField tfNonStandardValue;
     46    private ButtonGroup bgStandardOrNonStandard;
     47    private JRadioButton rbStandardException;
     48    private JRadioButton rbNonStandardException;
     49    private JPanel pnlStandard;
     50    private JPanel pnlNonStandard;
     51    private ExceptValueModel exceptValue = new ExceptValueModel();
     52   
     53    private JPanel buildMessagePanel() {
     54        JPanel pnl = new JPanel(new BorderLayout());
     55        HtmlPanel msg = new HtmlPanel();
     56        pnl.add(msg, BorderLayout.CENTER);
     57        msg.setText(
     58                "<html><body>"
     59                + tr("Select the vehicle types this turn restriction is <strong>not</strong> applicable for.")
     60                + "</body></html>"
     61        );
     62        return pnl;
     63    }
     64   
     65    private JPanel buildStandardInputPanel() {
     66        if (pnlStandard != null)
     67            return pnlStandard;
     68       
     69        StandardVehicleTypeChangeListener changeHandler = new StandardVehicleTypeChangeListener();
     70       
     71        GridBagConstraints gc = new GridBagConstraints();
     72        gc.anchor = GridBagConstraints.NORTHWEST;
     73        gc.fill = GridBagConstraints.HORIZONTAL;
     74        gc.gridx = 0;
     75        gc.gridy = 0;
     76       
     77        pnlStandard = new JPanel(new GridBagLayout());
     78        JLabel lbl;
     79        cbPsv = new JCheckBox();
     80        cbPsv.addItemListener(changeHandler);
     81        lbl = new JLabel();
     82        lbl.setText(tr("Public Service Vehicles"));
     83        lbl.setToolTipText(tr("Public service vehicles like buses, tramways, etc."));
     84        lbl.setIcon(ImageProvider.get("vehicle", "psv"));
     85       
     86        gc.weightx = 0.0;
     87        pnlStandard.add(cbPsv, gc);
     88        gc.weightx = 1.0;
     89        gc.gridx++;
     90        pnlStandard.add(lbl, gc);
     91       
     92        cbHgv = new JCheckBox();
     93        cbHgv.addItemListener(changeHandler);
     94        lbl = new JLabel();
     95        lbl.setText(tr("Heavy Goods Vehicles"));
     96        lbl.setIcon(ImageProvider.get("vehicle", "hgv"));
     97
     98        gc.weightx = 0.0;
     99        gc.gridx++;
     100        pnlStandard.add(cbHgv, gc);
     101        gc.weightx = 1.0;
     102        gc.gridx++;
     103        pnlStandard.add(lbl, gc);
     104
     105        cbMotorcar = new JCheckBox();
     106        cbMotorcar.addItemListener(changeHandler);
     107        lbl = new JLabel();
     108        lbl.setText(tr("Motorcars"));
     109        lbl.setIcon(ImageProvider.get("vehicle", "motorcar"));
     110       
     111        gc.weightx = 0.0;
     112        gc.gridx = 0;
     113        gc.gridy = 1;
     114        pnlStandard.add(cbMotorcar, gc);
     115        gc.weightx = 1.0;
     116        gc.gridx++;
     117        pnlStandard.add(lbl, gc);
     118       
     119        cbBicyle = new JCheckBox();
     120        cbBicyle.addItemListener(changeHandler);
     121        lbl = new JLabel();
     122        lbl.setText(tr("Bicycles"));
     123        lbl.setIcon(ImageProvider.get("vehicle", "bicycle"));
     124       
     125
     126        gc.weightx = 0.0;
     127        gc.gridx++;
     128        pnlStandard.add(cbBicyle, gc);
     129        gc.weightx = 1.0;
     130        gc.gridx++;
     131        pnlStandard.add(lbl, gc);
     132       
     133        return pnlStandard;
     134    }
     135   
     136    private JPanel buildNonStandardInputPanel() {
     137        if (pnlNonStandard != null)
     138            return pnlNonStandard;
     139        pnlNonStandard = new JPanel(new GridBagLayout());
     140        GridBagConstraints gc = new GridBagConstraints();
     141        gc.anchor = GridBagConstraints.NORTHWEST;
     142        gc.fill = GridBagConstraints.HORIZONTAL;
     143        gc.weightx = 0.0;
     144        gc.insets = new Insets(0, 0, 4, 0);
     145        gc.gridx = 0;
     146        gc.gridy = 0;
     147       
     148        pnlNonStandard.add(new JLabel(tr("Value:")), gc);
     149        gc.gridx = 1;
     150        gc.weightx = 1.0;
     151        pnlNonStandard.add(tfNonStandardValue = new JTextField(), gc);
     152        SelectAllOnFocusGainedDecorator.decorate(tfNonStandardValue);
     153       
     154        NonStandardVehicleTypesHandler inputChangedHandler = new NonStandardVehicleTypesHandler();
     155        tfNonStandardValue.addActionListener(inputChangedHandler);
     156        tfNonStandardValue.addFocusListener(inputChangedHandler);
     157        return pnlNonStandard;
     158    }
     159       
     160    /**
     161    * Builds the UI for entering standard values
     162    */
     163    protected void buildStandard() {
     164        setLayout(new GridBagLayout());
     165        GridBagConstraints gc = new GridBagConstraints();
     166        gc.anchor = GridBagConstraints.NORTHWEST;
     167        gc.fill = GridBagConstraints.HORIZONTAL;
     168        gc.weightx = 1.0;
     169        gc.gridx = 0;
     170        gc.gridy = 0;
     171        add(buildMessagePanel(), gc);
     172       
     173        gc.gridy=1;
     174        add(buildStandardInputPanel(), gc);     
     175    }
     176   
     177    /**
     178    * Builds the UI for entering either standard or non-standard values
     179    */
     180    protected void buildNonStandard() {
     181        setLayout(new GridBagLayout());
     182        GridBagConstraints gc = new GridBagConstraints();
     183        gc.anchor = GridBagConstraints.NORTHWEST;
     184        gc.fill = GridBagConstraints.HORIZONTAL;
     185        gc.weightx = 1.0;
     186        gc.gridx = 0;
     187        gc.gridy = 0;
     188        add(buildMessagePanel(), gc);
     189               
     190        gc.gridx=0;
     191        gc.gridy=1;
     192        gc.insets = new Insets(0,0,0,0);
     193        add(rbStandardException = new JRadioButton(tr("Use standard exceptions")), gc);
     194
     195        gc.gridx=0;
     196        gc.gridy=2;
     197        gc.insets = new Insets(0, 20, 0,0);
     198        add(buildStandardInputPanel(), gc);
     199
     200        gc.gridx=0;
     201        gc.gridy=3;
     202        gc.insets = new Insets(0,0,0,0);
     203        add(rbNonStandardException = new JRadioButton(tr("Use non-standard exceptions")), gc);
     204
     205        gc.gridx=0;
     206        gc.gridy=4;
     207        gc.insets = new Insets(0, 20, 0,0);
     208        add(buildNonStandardInputPanel(), gc);
     209       
     210        bgStandardOrNonStandard = new ButtonGroup();
     211        bgStandardOrNonStandard.add(rbNonStandardException);
     212        bgStandardOrNonStandard.add(rbStandardException);
     213       
     214        StandardNonStandardChangeHander changeHandler = new StandardNonStandardChangeHander();
     215        rbNonStandardException.addItemListener(changeHandler);
     216        rbStandardException.addItemListener(changeHandler);
     217    }
     218   
     219    protected void build() {
     220        removeAll();
     221        buildNonStandardInputPanel();
     222        buildStandardInputPanel();
     223        if (exceptValue.isStandard()){
     224            buildStandard();
     225        } else {
     226            buildNonStandard();
     227        }
     228        init();
     229        invalidate();
     230    }
     231   
     232    protected void init() {
     233        cbPsv.setSelected(exceptValue.isVehicleException("psv"));
     234        cbBicyle.setSelected(exceptValue.isVehicleException("bicycle"));
     235        cbMotorcar.setSelected(exceptValue.isVehicleException("motorcar"));
     236        cbHgv.setSelected(exceptValue.isVehicleException("hgv"));
     237        if (!exceptValue.isStandard()){
     238            rbNonStandardException.setSelected(true);
     239            tfNonStandardValue.setText(exceptValue.getValue());
     240            setEnabledNonStandardInputPanel(true);
     241            setEnabledStandardInputPanel(false);
     242        } else {
     243            setEnabledNonStandardInputPanel(false);
     244            setEnabledStandardInputPanel(true);
     245        }
     246    }
     247   
     248    protected void setEnabledStandardInputPanel(boolean enabled) {
     249        for (Component c: pnlStandard.getComponents()){
     250            c.setEnabled(enabled);
     251        }
     252    }
     253   
     254    protected void setEnabledNonStandardInputPanel(boolean enabled) {
     255        for (Component c: pnlNonStandard.getComponents()){
     256            c.setEnabled(enabled);
     257        }
     258    }
     259
     260   
     261    /**
     262    * Creates the editor
     263    *
     264    * @param model the editor model. Must not be null.
     265    * @throws IllegalArgumentException thrown if {@code model} is null
     266    */
     267    public VehicleExceptionEditor(TurnRestrictionEditorModel model) throws IllegalArgumentException {
     268        CheckParameterUtil.ensureParameterNotNull(model, "model");
     269        this.model = model;
     270        build();
     271        model.addObserver(this);
     272    }
     273   
     274    /* ------------------------------------------------------------------------------------ */
     275    /* interface Observer                                                                   */
     276    /* ------------------------------------------------------------------------------------ */
     277    public void update(Observable o, Object arg) {
     278        if (!this.exceptValue.equals(model.getExcept())) {
     279            this.exceptValue = model.getExcept();
     280            build();
     281        }
     282    }
     283
     284    /* ------------------------------------------------------------------------------------ */
     285    /* inner classes                                                                        */
     286    /* ------------------------------------------------------------------------------------ */
     287    class StandardNonStandardChangeHander implements ItemListener {
     288        public void itemStateChanged(ItemEvent e) {
     289            if (rbNonStandardException.isSelected()){
     290                setEnabledNonStandardInputPanel(true);
     291                setEnabledStandardInputPanel(false);
     292                exceptValue.setStandard(false);
     293            } else {
     294                setEnabledNonStandardInputPanel(false);
     295                setEnabledStandardInputPanel(true);
     296                exceptValue.setStandard(true);
     297            }
     298            model.setExcept(exceptValue);
     299        }
     300    }
     301   
     302    class StandardVehicleTypeChangeListener implements ItemListener {
     303        public void itemStateChanged(ItemEvent e) {
     304            exceptValue.setVehicleException("bicycle", cbBicyle.isSelected());
     305            exceptValue.setVehicleException("hgv", cbHgv.isSelected());
     306            exceptValue.setVehicleException("psv", cbPsv.isSelected());
     307            exceptValue.setVehicleException("motorcar", cbMotorcar.isSelected());
     308            model.setExcept(exceptValue);
     309        }
     310    }
     311   
     312    class NonStandardVehicleTypesHandler implements ActionListener, FocusListener {
     313        public void persist() {
     314            exceptValue.setValue(tfNonStandardValue.getText());
     315            model.setExcept(exceptValue);
     316        }
     317       
     318        public void focusGained(FocusEvent e) {}
     319        public void focusLost(FocusEvent e) {
     320            persist();
     321        }
     322
     323        public void actionPerformed(ActionEvent e) {
     324            persist();         
     325        }
     326    }
    327327}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/ViaList.java

    r20489 r23192  
    4646 */
    4747public class ViaList extends JList{
    48        
    49         static private final Logger logger = Logger.getLogger(ViaList.class.getName());
    50 
    51         private ViaListModel model;
    52         private DeleteAction actDelete;
    53         private MoveUpAction actMoveUp;
    54         private MoveDownAction actMoveDown;
    55         private CopyAction actCopy;
    56         private PasteAction actPaste;
    57         private TransferHandler transferHandler;
    58        
    59         /**
    60         * Constructor
    61         *
    62         * @param model the via list model. Must not be null.
    63         * @param selectionModel the selection model. Must not be null.
    64         *
    65         */
    66         public ViaList(ViaListModel model, DefaultListSelectionModel selectionModel) {
    67                 super(model);
    68                 this.model = model;
    69                 setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    70                 setSelectionModel(selectionModel);
    71                 setCellRenderer(new OsmPrimitivRenderer());
    72                 setDragEnabled(true);           
    73                 setTransferHandler(transferHandler =new ViaListTransferHandler(model));
    74                 setVisibleRowCount(4);
    75                
    76                 actDelete = new DeleteAction();
    77                 selectionModel.addListSelectionListener(actDelete);
    78                 registerKeyboardAction(actDelete, KeyStroke.getKeyStroke(KeyEvent.VK_DELETE,0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    79                
    80                 actMoveDown = new MoveDownAction();
    81                 selectionModel.addListSelectionListener(actMoveDown);
    82                 registerKeyboardAction(actMoveDown, KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, KeyEvent.ALT_DOWN_MASK), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    83 
    84                 actMoveUp = new MoveUpAction();
    85                 selectionModel.addListSelectionListener(actMoveUp);
    86                 registerKeyboardAction(actMoveUp, KeyStroke.getKeyStroke(KeyEvent.VK_UP, KeyEvent.ALT_DOWN_MASK), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    87                
    88                 actCopy = new CopyAction();
    89                 actPaste = new PasteAction();
    90                 getSelectionModel().addListSelectionListener(actCopy);
    91        
    92                 addMouseListener(new ViaListPopupMenuLaucher());                       
    93         }
    94        
    95         /**
    96         * The transfer handler for Drag-and-Drop.
    97         */
    98         class ViaListTransferHandler extends PrimitiveIdListTransferHandler {
    99                 Logger logger = Logger.getLogger(ViaListTransferHandler.class.getName());
    100                
    101                 private boolean isViaListInDragOperation = false;
    102                 private List<Integer> selectedRowsMemento = null;
    103                
    104                 public ViaListTransferHandler(PrimitiveIdListProvider provider) {
    105                         super(provider);
    106                 }
    107 
    108                 @Override
    109                 public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
    110                         // a drag operation on itself is always allowed
    111                         if (isViaListInDragOperation) return true;
    112                         return isSupportedFlavor(transferFlavors);                     
    113                 }
    114 
    115                 @SuppressWarnings("unchecked")
    116                 @Override
    117                 public boolean importData(JComponent comp, Transferable t) {   
    118                         if (!isSupportedFlavor(t.getTransferDataFlavors())) return false;
    119                         if (isViaListInDragOperation) {
    120                                 // this is a drag operation on itself
    121                                 int targetRow = getSelectedIndex();
    122                                 if (targetRow <0) return true;
    123                                 model.moveVias(selectedRowsMemento, targetRow);                         
    124                         } else {
    125                                 // this is a drag operation from another component
    126                                 try {
    127                                         List<PrimitiveId> idsToAdd = (List<PrimitiveId>)t.getTransferData(PrimitiveIdTransferable.PRIMITIVE_ID_LIST_FLAVOR);
    128                                         model.insertVias(idsToAdd);
    129                                 } catch(IOException e){
    130                                         e.printStackTrace();
    131                                 } catch(UnsupportedFlavorException e){
    132                                         e.printStackTrace();
    133                                 }
    134                         }
    135                         return true;
    136                 }
    137 
    138                 @Override
    139                 protected void exportDone(JComponent source, Transferable data, int action) {
    140                         isViaListInDragOperation = false;
    141                         super.exportDone(source, data, action);
    142                 }
    143 
    144                 @Override
    145                 public void exportAsDrag(JComponent comp, InputEvent e, int action) {
    146                         isViaListInDragOperation = true;
    147                         selectedRowsMemento = model.getSelectedRows();
    148                         super.exportAsDrag(comp, e, action);
    149                 }               
    150         }       
    151        
    152         class DeleteAction extends AbstractAction implements ListSelectionListener {
    153                 public DeleteAction() {
    154                         putValue(NAME, tr("Remove"));
    155                         putValue(SMALL_ICON, ImageProvider.get("dialogs", "delete"));
    156                         putValue(SHORT_DESCRIPTION,tr("Remove the currently selected vias"));           
    157                         putValue(ACCELERATOR_KEY,KeyStroke.getKeyStroke(KeyEvent.VK_DELETE,0));                 
    158                         updateEnabledState();
    159                 }
    160                
    161                 public void valueChanged(ListSelectionEvent e) {
    162                         updateEnabledState();                   
    163                 }
    164                
    165                 public void updateEnabledState() {
    166                         setEnabled(getSelectedIndex() >= 0);
    167                 }
    168 
    169                 public void actionPerformed(ActionEvent e) {
    170                         model.removeSelectedVias();                     
    171                 }
    172         }
    173        
    174         class MoveDownAction extends AbstractAction implements ListSelectionListener{           
    175                 public MoveDownAction(){
    176                         putValue(NAME, tr("Move down"));
    177                         putValue(SHORT_DESCRIPTION, tr("Move the selected vias down by one position"));
    178                         putValue(ACCELERATOR_KEY,KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, KeyEvent.ALT_DOWN_MASK));
    179                         putValue(SMALL_ICON, ImageProvider.get("dialogs", "movedown"));
    180                         updateEnabledState();
    181                 }
    182                
    183                 public void actionPerformed(ActionEvent e) {
    184                         model.moveDown();
    185                 }
    186 
    187                 public void updateEnabledState(){
    188                         if (getSelectedIndex() < 0) {
    189                                 setEnabled(false);
    190                                 return;
    191                         }
    192                         setEnabled(getSelectionModel().getMaxSelectionIndex() < getModel().getSize() -1);
    193                 }
    194                
    195                 public void valueChanged(ListSelectionEvent e) {
    196                         updateEnabledState();                   
    197                 }
    198         }
    199        
    200         class MoveUpAction extends AbstractAction implements ListSelectionListener{             
    201                 public MoveUpAction() {
    202                         putValue(NAME, tr("Move up"));
    203                         putValue(SHORT_DESCRIPTION, tr("Move the selected vias up by one position"));
    204                         putValue(ACCELERATOR_KEY,KeyStroke.getKeyStroke(KeyEvent.VK_UP, KeyEvent.ALT_DOWN_MASK));
    205                         putValue(SMALL_ICON, ImageProvider.get("dialogs", "moveup"));
    206                         updateEnabledState();
    207                 }
    208                
    209                 public void actionPerformed(ActionEvent e) {
    210                         model.moveUp();
    211                 }
    212 
    213                 public void updateEnabledState(){
    214                         if (getSelectedIndex() < 0) {
    215                                 setEnabled(false);
    216                                 return;
    217                         }
    218                         setEnabled(getSelectionModel().getMinSelectionIndex() > 0);
    219                 }
    220                
    221                 public void valueChanged(ListSelectionEvent e) {
    222                         updateEnabledState();                   
    223                 }
    224         }
    225 
    226         class CopyAction extends AbstractAction implements ListSelectionListener {
    227                 private Action delegate;
    228                
    229                 public CopyAction(){
    230                         putValue(NAME, tr("Copy"));
    231                         putValue(SHORT_DESCRIPTION, tr("Copy the selected vias to the clipboard"));
    232                         putValue(SMALL_ICON, ImageProvider.get("copy"));
    233                         putValue(ACCELERATOR_KEY, Shortcut.getCopyKeyStroke());
    234                         delegate = ViaList.this.getActionMap().get("copy");
    235                 }
    236 
    237                 public void actionPerformed(ActionEvent e) {                   
    238                         delegate.actionPerformed(e);
    239                 }
    240 
    241                 protected void updateEnabledState() {
    242                         setEnabled(!model.getSelectedVias().isEmpty());
    243                 }
    244                
    245                 public void valueChanged(ListSelectionEvent e) {
    246                         updateEnabledState();
    247                 }
    248         }
    249        
    250         class PasteAction extends AbstractAction {
    251                 private Action delegate;
    252                
    253                 public boolean canPaste() {
    254                         Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    255                         for (DataFlavor df: clipboard.getAvailableDataFlavors()) {
    256                                 if (df.equals(PrimitiveIdTransferable.PRIMITIVE_ID_LIST_FLAVOR)) return true;
    257                         }                       
    258                         // FIXME: check whether there are selected objects in the JOSM copy/paste buffer 
    259                         return false;
    260                 }
    261                
    262                 public PasteAction(){
    263                         putValue(NAME, tr("Paste"));
    264                         putValue(SHORT_DESCRIPTION, tr("Insert 'via' objects from the clipboard"));
    265                         putValue(SMALL_ICON, ImageProvider.get("paste"));
    266                         putValue(ACCELERATOR_KEY, Shortcut.getPasteKeyStroke());
    267                         delegate = ViaList.this.getActionMap().get("paste");
    268                         updateEnabledState();
    269                 }
    270 
    271                 public void updateEnabledState() {
    272                         setEnabled(canPaste());
    273                 }
    274                
    275                 public void actionPerformed(ActionEvent e) {
    276                         delegate.actionPerformed(e);                   
    277                 }
    278         }
    279        
    280         class ViaListPopupMenu extends JPopupMenu {
    281                 public ViaListPopupMenu() {
    282                         JMenuItem item = add(actCopy);
    283                         item.setTransferHandler(transferHandler);                       
    284                         item = add(actPaste);
    285                         actPaste.updateEnabledState();
    286                         item.setTransferHandler(transferHandler);
    287                         addSeparator();
    288                         add(actDelete);
    289                         addSeparator();
    290                         add(actMoveUp);
    291                         add(actMoveDown);
    292                 }
    293         }
    294        
    295         class ViaListPopupMenuLaucher extends PopupMenuLauncher {
    296                 @Override
    297                 public void launch(MouseEvent evt) {
    298                         if (getSelectedIndex() <0) {
    299                                 int idx = locationToIndex(evt.getPoint());
    300                                 if (idx >=0) {
    301                                         setSelectedIndex(idx);
    302                                 }
    303                         }
    304                         new ViaListPopupMenu().show(ViaList.this, evt.getX(), evt.getY());
    305                 }               
    306         }       
     48   
     49    static private final Logger logger = Logger.getLogger(ViaList.class.getName());
     50
     51    private ViaListModel model;
     52    private DeleteAction actDelete;
     53    private MoveUpAction actMoveUp;
     54    private MoveDownAction actMoveDown;
     55    private CopyAction actCopy;
     56    private PasteAction actPaste;
     57    private TransferHandler transferHandler;
     58   
     59    /**
     60    * Constructor
     61    *
     62    * @param model the via list model. Must not be null.
     63    * @param selectionModel the selection model. Must not be null.
     64    *
     65    */
     66    public ViaList(ViaListModel model, DefaultListSelectionModel selectionModel) {
     67        super(model);
     68        this.model = model;
     69        setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
     70        setSelectionModel(selectionModel);
     71        setCellRenderer(new OsmPrimitivRenderer());
     72        setDragEnabled(true);       
     73        setTransferHandler(transferHandler =new ViaListTransferHandler(model));
     74        setVisibleRowCount(4);
     75       
     76        actDelete = new DeleteAction();
     77        selectionModel.addListSelectionListener(actDelete);
     78        registerKeyboardAction(actDelete, KeyStroke.getKeyStroke(KeyEvent.VK_DELETE,0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
     79       
     80        actMoveDown = new MoveDownAction();
     81        selectionModel.addListSelectionListener(actMoveDown);
     82        registerKeyboardAction(actMoveDown, KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, KeyEvent.ALT_DOWN_MASK), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
     83
     84        actMoveUp = new MoveUpAction();
     85        selectionModel.addListSelectionListener(actMoveUp);
     86        registerKeyboardAction(actMoveUp, KeyStroke.getKeyStroke(KeyEvent.VK_UP, KeyEvent.ALT_DOWN_MASK), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
     87       
     88        actCopy = new CopyAction();
     89        actPaste = new PasteAction();
     90        getSelectionModel().addListSelectionListener(actCopy);
     91       
     92        addMouseListener(new ViaListPopupMenuLaucher());           
     93    }
     94   
     95    /**
     96    * The transfer handler for Drag-and-Drop.
     97    */
     98    class ViaListTransferHandler extends PrimitiveIdListTransferHandler {
     99        Logger logger = Logger.getLogger(ViaListTransferHandler.class.getName());
     100       
     101        private boolean isViaListInDragOperation = false;
     102        private List<Integer> selectedRowsMemento = null;
     103       
     104        public ViaListTransferHandler(PrimitiveIdListProvider provider) {
     105            super(provider);
     106        }
     107
     108        @Override
     109        public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
     110            // a drag operation on itself is always allowed
     111            if (isViaListInDragOperation) return true;
     112            return isSupportedFlavor(transferFlavors);         
     113        }
     114
     115        @SuppressWarnings("unchecked")
     116        @Override
     117        public boolean importData(JComponent comp, Transferable t) {   
     118            if (!isSupportedFlavor(t.getTransferDataFlavors())) return false;
     119            if (isViaListInDragOperation) {
     120                // this is a drag operation on itself
     121                int targetRow = getSelectedIndex();
     122                if (targetRow <0) return true;
     123                model.moveVias(selectedRowsMemento, targetRow);             
     124            } else {
     125                // this is a drag operation from another component
     126                try {
     127                    List<PrimitiveId> idsToAdd = (List<PrimitiveId>)t.getTransferData(PrimitiveIdTransferable.PRIMITIVE_ID_LIST_FLAVOR);
     128                    model.insertVias(idsToAdd);
     129                } catch(IOException e){
     130                    e.printStackTrace();
     131                } catch(UnsupportedFlavorException e){
     132                    e.printStackTrace();
     133                }
     134            }
     135            return true;
     136        }
     137
     138        @Override
     139        protected void exportDone(JComponent source, Transferable data, int action) {
     140            isViaListInDragOperation = false;
     141            super.exportDone(source, data, action);
     142        }
     143
     144        @Override
     145        public void exportAsDrag(JComponent comp, InputEvent e, int action) {
     146            isViaListInDragOperation = true;
     147            selectedRowsMemento = model.getSelectedRows();
     148            super.exportAsDrag(comp, e, action);
     149        }       
     150    }   
     151   
     152    class DeleteAction extends AbstractAction implements ListSelectionListener {
     153        public DeleteAction() {
     154            putValue(NAME, tr("Remove"));
     155            putValue(SMALL_ICON, ImageProvider.get("dialogs", "delete"));
     156            putValue(SHORT_DESCRIPTION,tr("Remove the currently selected vias"));       
     157            putValue(ACCELERATOR_KEY,KeyStroke.getKeyStroke(KeyEvent.VK_DELETE,0));         
     158            updateEnabledState();
     159        }
     160       
     161        public void valueChanged(ListSelectionEvent e) {
     162            updateEnabledState();           
     163        }
     164       
     165        public void updateEnabledState() {
     166            setEnabled(getSelectedIndex() >= 0);
     167        }
     168
     169        public void actionPerformed(ActionEvent e) {
     170            model.removeSelectedVias();         
     171        }
     172    }
     173   
     174    class MoveDownAction extends AbstractAction implements ListSelectionListener{       
     175        public MoveDownAction(){
     176            putValue(NAME, tr("Move down"));
     177            putValue(SHORT_DESCRIPTION, tr("Move the selected vias down by one position"));
     178            putValue(ACCELERATOR_KEY,KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, KeyEvent.ALT_DOWN_MASK));
     179            putValue(SMALL_ICON, ImageProvider.get("dialogs", "movedown"));
     180            updateEnabledState();
     181        }
     182       
     183        public void actionPerformed(ActionEvent e) {
     184            model.moveDown();
     185        }
     186
     187        public void updateEnabledState(){
     188            if (getSelectedIndex() < 0) {
     189                setEnabled(false);
     190                return;
     191            }
     192            setEnabled(getSelectionModel().getMaxSelectionIndex() < getModel().getSize() -1);
     193        }
     194       
     195        public void valueChanged(ListSelectionEvent e) {
     196            updateEnabledState();           
     197        }
     198    }
     199   
     200    class MoveUpAction extends AbstractAction implements ListSelectionListener{     
     201        public MoveUpAction() {
     202            putValue(NAME, tr("Move up"));
     203            putValue(SHORT_DESCRIPTION, tr("Move the selected vias up by one position"));
     204            putValue(ACCELERATOR_KEY,KeyStroke.getKeyStroke(KeyEvent.VK_UP, KeyEvent.ALT_DOWN_MASK));
     205            putValue(SMALL_ICON, ImageProvider.get("dialogs", "moveup"));
     206            updateEnabledState();
     207        }
     208       
     209        public void actionPerformed(ActionEvent e) {
     210            model.moveUp();
     211        }
     212
     213        public void updateEnabledState(){
     214            if (getSelectedIndex() < 0) {
     215                setEnabled(false);
     216                return;
     217            }
     218            setEnabled(getSelectionModel().getMinSelectionIndex() > 0);
     219        }
     220       
     221        public void valueChanged(ListSelectionEvent e) {
     222            updateEnabledState();           
     223        }
     224    }
     225
     226    class CopyAction extends AbstractAction implements ListSelectionListener {
     227        private Action delegate;
     228       
     229        public CopyAction(){
     230            putValue(NAME, tr("Copy"));
     231            putValue(SHORT_DESCRIPTION, tr("Copy the selected vias to the clipboard"));
     232            putValue(SMALL_ICON, ImageProvider.get("copy"));
     233            putValue(ACCELERATOR_KEY, Shortcut.getCopyKeyStroke());
     234            delegate = ViaList.this.getActionMap().get("copy");
     235        }
     236
     237        public void actionPerformed(ActionEvent e) {           
     238            delegate.actionPerformed(e);
     239        }
     240
     241        protected void updateEnabledState() {
     242            setEnabled(!model.getSelectedVias().isEmpty());
     243        }
     244       
     245        public void valueChanged(ListSelectionEvent e) {
     246            updateEnabledState();
     247        }
     248    }
     249   
     250    class PasteAction extends AbstractAction {
     251        private Action delegate;
     252       
     253        public boolean canPaste() {
     254            Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
     255            for (DataFlavor df: clipboard.getAvailableDataFlavors()) {
     256                if (df.equals(PrimitiveIdTransferable.PRIMITIVE_ID_LIST_FLAVOR)) return true;
     257            }           
     258            // FIXME: check whether there are selected objects in the JOSM copy/paste buffer 
     259            return false;
     260        }
     261       
     262        public PasteAction(){
     263            putValue(NAME, tr("Paste"));
     264            putValue(SHORT_DESCRIPTION, tr("Insert 'via' objects from the clipboard"));
     265            putValue(SMALL_ICON, ImageProvider.get("paste"));
     266            putValue(ACCELERATOR_KEY, Shortcut.getPasteKeyStroke());
     267            delegate = ViaList.this.getActionMap().get("paste");
     268            updateEnabledState();
     269        }
     270
     271        public void updateEnabledState() {
     272            setEnabled(canPaste());
     273        }
     274       
     275        public void actionPerformed(ActionEvent e) {
     276            delegate.actionPerformed(e);           
     277        }
     278    }
     279   
     280    class ViaListPopupMenu extends JPopupMenu {
     281        public ViaListPopupMenu() {
     282            JMenuItem item = add(actCopy);
     283            item.setTransferHandler(transferHandler);           
     284            item = add(actPaste);
     285            actPaste.updateEnabledState();
     286            item.setTransferHandler(transferHandler);
     287            addSeparator();
     288            add(actDelete);
     289            addSeparator();
     290            add(actMoveUp);
     291            add(actMoveDown);
     292        }
     293    }
     294   
     295    class ViaListPopupMenuLaucher extends PopupMenuLauncher {
     296        @Override
     297        public void launch(MouseEvent evt) {
     298            if (getSelectedIndex() <0) {
     299                int idx = locationToIndex(evt.getPoint());
     300                if (idx >=0) {
     301                    setSelectedIndex(idx);
     302                }
     303            }
     304            new ViaListPopupMenu().show(ViaList.this, evt.getX(), evt.getY());
     305        }       
     306    }   
    307307}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/ViaListModel.java

    r20527 r23192  
    2323 */
    2424public class ViaListModel extends AbstractListModel implements PrimitiveIdListProvider, Observer{
    25         static private final Logger logger = Logger.getLogger(ViaListModel.class.getName());
    26        
    27         private DefaultListSelectionModel selectionModel;
    28         private final ArrayList<OsmPrimitive> vias = new ArrayList<OsmPrimitive>();
    29         private TurnRestrictionEditorModel model;
    30        
    31         /**
    32         * Constructor
    33         *
    34         * @param model the turn restriction editor model. Must not be null.
    35         * @param selectionModel the selection model. Must not be null.
    36         * @throws IllegalArgumentException thrown if model is null
    37         * @throws IllegalArgumentException thrown if selectionModel is null
    38         */
    39         public ViaListModel(TurnRestrictionEditorModel model, DefaultListSelectionModel selectionModel) {
    40                 CheckParameterUtil.ensureParameterNotNull(model, "model");
    41                 CheckParameterUtil.ensureParameterNotNull(selectionModel, "selectionModel");
    42                 this.model = model;
    43                 this.selectionModel = selectionModel;
    44                 model.addObserver(this);
    45                 refresh();
    46         }
    47 
    48         /**
    49         * Replies the list of currently selected vias
    50         *
    51         * @return the list of currently selected vias
    52         */
    53         public List<OsmPrimitive> getSelectedVias() {
    54                 ArrayList<OsmPrimitive> ret = new ArrayList<OsmPrimitive>();
    55                 for (int i=0; i < getSize(); i++) {
    56                         if (selectionModel.isSelectedIndex(i)) {
    57                                 ret.add(vias.get(i));
    58                         }
    59                 }
    60                 return ret;
    61         }
    62        
    63         /**
    64         * Sets the collection of currently selected vias
    65         *
    66         *  @param vias a collection of vias
    67         */
    68         public void setSelectedVias(Collection<OsmPrimitive> vias) {
    69                 selectionModel.clearSelection();
    70                 if (vias == null) return;
    71                 for(OsmPrimitive via: vias) {
    72                         int idx = this.vias.indexOf(via);
    73                         if (idx < 0) continue;
    74                         selectionModel.addSelectionInterval(idx, idx);
    75                 }
    76         }
    77        
    78         /**
    79         * Replies the list of selected rows
    80         *
    81         * @return the list of selected rows
    82         */
    83         public List<Integer> getSelectedRows() {
    84                 ArrayList<Integer> ret = new ArrayList<Integer>();
    85                 for (int i=0; i < getSize(); i++) {
    86                         if (selectionModel.isSelectedIndex(i)) {
    87                                 ret.add(i);
    88                         }
    89                 }
    90                 return ret;
    91         }
    92        
    93         protected List<Integer> moveUp(List<Integer> rows, int targetRow) {
    94                 List<Integer> ret = new ArrayList<Integer>(rows.size());
    95                 int delta = rows.get(0) - targetRow;
    96                 for(int row: rows) {
    97                         OsmPrimitive via = vias.remove(row);
    98                         vias.add(row - delta, via);
    99                         ret.add(row - delta);
    100                 }
    101                 return ret;
    102         }
    103        
    104         protected List<Integer>  moveDown(List<Integer> rows, int targetRow) {
    105                 List<Integer> ret = new ArrayList<Integer>(rows.size());
    106                 int delta = targetRow - rows.get(0);
    107                 for(int i = rows.size()-1; i >=0; i--) {
    108                         int row = rows.get(i);
    109                         OsmPrimitive via = vias.remove(row);
    110                         vias.add(row + delta, via);
    111                         ret.add(row + delta);
    112                 }
    113                 return ret;
    114         }
    115        
    116         public void moveVias(List<Integer> selectedRows, int targetRow){
    117                 if (selectedRows == null) return;
    118                 if (selectedRows.size() == 1){
    119                         int sourceRow = selectedRows.get(0);
    120                         if (sourceRow == targetRow) return;
    121                         OsmPrimitive via = vias.remove(sourceRow);
    122                         vias.add(targetRow, via);
    123                         fireContentsChanged(this, 0, getSize());
    124                         selectionModel.setSelectionInterval(targetRow, targetRow);
    125                         return;
    126                 }
    127                 int min = selectedRows.get(0);
    128                 int max = selectedRows.get(selectedRows.size()-1);
    129                 if (targetRow < min) {
    130                         selectedRows = moveUp(selectedRows, targetRow);
    131                 } else if (targetRow == min){
    132                         // do nothing
    133                 } else if (targetRow - min < getSize() - max){
    134                         int delta = Math.min(targetRow - min, getSize()-1 - max);
    135                         targetRow = min + delta;
    136                         if (targetRow > min) {
    137                                 selectedRows = moveDown(selectedRows, targetRow);
    138                         }
    139                 }
    140                 fireContentsChanged(this, 0, getSize());
    141                 selectionModel.clearSelection();
    142                 for(int row: selectedRows) {
    143                         selectionModel.addSelectionInterval(row, row);
    144                 }               
    145         }
    146        
    147         /**
    148         * Move the currently selected vias up by one position
    149         */
    150         public void moveUp() {
    151                 List<Integer> sel = getSelectedRows();
    152                 if (sel.isEmpty() || sel.get(0) == 0) return;
    153                 moveVias(sel, sel.get(0)-1);
    154         }
    155 
    156         /**
    157         * Move the currently selected vias down by one position
    158         */
    159         public void moveDown() {
    160                 List<Integer> sel = getSelectedRows();
    161                 if (sel.isEmpty() || sel.get(sel.size()-1) == getSize()-1) return;
    162                 moveVias(sel, sel.get(sel.size()-1)+1);
    163         }
    164        
    165         /**
    166         * Inserts a list of OSM objects given by OSM primitive ids.
    167         *
    168         * @param idsToInsert the ids of the objects to insert
    169         */
    170         public void insertVias(List<PrimitiveId> idsToInsert) {
    171                 if (idsToInsert == null) return;
    172                 List<OsmPrimitive> primitives = new ArrayList<OsmPrimitive>(idsToInsert.size());
    173                 DataSet ds = model.getLayer().data;
    174                 for(PrimitiveId id: idsToInsert){
    175                         OsmPrimitive p = ds.getPrimitiveById(id);
    176                         if (p == null){
    177                                 System.out.println(tr("Failed to retrieve OSM object with id {0} from dataset {1}. Cannot add it as ''via''.", id, ds));
    178                                 continue;
    179                         }
    180                         primitives.add(p);
    181                 }
    182                 int targetRow = Math.max(selectionModel.getMinSelectionIndex(),0);
    183                 List<OsmPrimitive> newVias = new ArrayList<OsmPrimitive>(vias);
    184                 newVias.addAll(targetRow, primitives);
    185                 model.setVias(newVias);
    186                 fireContentsChanged(this, 0, getSize());
    187                 selectionModel.clearSelection();
    188                 for(int i=targetRow; i< targetRow + primitives.size();i++) {
    189                         selectionModel.addSelectionInterval(i, i);
    190                 }                       
    191         }
    192 
    193         /**
    194         * Removes the currently selected vias
    195         */
    196         public void removeSelectedVias() {
    197                 ArrayList<OsmPrimitive> newVias = new ArrayList<OsmPrimitive>(vias);
    198                 int j = 0;
    199                 for(int i=0; i< getSize();i++){
    200                         if (!selectionModel.isSelectedIndex(i)) continue;
    201                         newVias.remove(i-j);
    202                         j++;
    203                 }
    204                 if (j == 0) return; // nothing selected, nothing deleted
    205                 model.setVias(newVias);
    206         }
    207        
    208         /**
    209         * Refreshes the list of 'vias' in this model with the current list of
    210         * vias from the turn restriction model.
    211         */
    212         protected void refresh() {
    213                 List<OsmPrimitive> sel = getSelectedVias();
    214                 vias.clear();
    215                 vias.addAll(model.getVias());           
    216                 fireContentsChanged(this, 0, getSize());
    217                 setSelectedVias(sel);
    218         }
    219 
    220         public Object getElementAt(int index) {
    221                 return vias.get(index);
    222         }
    223 
    224         public int getSize() {
    225                 return vias.size();
    226         }
    227        
    228         /* ----------------------------------------------------------------------- */
    229         /* interface PrimitiveIdListProvider                                       */
    230         /* ----------------------------------------------------------------------- */
    231         public List<PrimitiveId> getSelectedPrimitiveIds() {
    232                 ArrayList<PrimitiveId> ids = new ArrayList<PrimitiveId>();
    233                 for (OsmPrimitive p: getSelectedVias()) {
    234                         ids.add(p.getPrimitiveId());
    235                 }
    236                 return ids;
    237         }
    238 
    239         /* ----------------------------------------------------------------------- */
    240         /* interface Observer                                                      */
    241         /* ----------------------------------------------------------------------- */
    242         public void update(Observable o, Object arg) {
    243                 refresh();
    244         }       
     25    static private final Logger logger = Logger.getLogger(ViaListModel.class.getName());
     26   
     27    private DefaultListSelectionModel selectionModel;
     28    private final ArrayList<OsmPrimitive> vias = new ArrayList<OsmPrimitive>();
     29    private TurnRestrictionEditorModel model;
     30   
     31    /**
     32    * Constructor
     33    *
     34    * @param model the turn restriction editor model. Must not be null.
     35    * @param selectionModel the selection model. Must not be null.
     36    * @throws IllegalArgumentException thrown if model is null
     37    * @throws IllegalArgumentException thrown if selectionModel is null
     38    */
     39    public ViaListModel(TurnRestrictionEditorModel model, DefaultListSelectionModel selectionModel) {
     40        CheckParameterUtil.ensureParameterNotNull(model, "model");
     41        CheckParameterUtil.ensureParameterNotNull(selectionModel, "selectionModel");
     42        this.model = model;
     43        this.selectionModel = selectionModel;
     44        model.addObserver(this);
     45        refresh();
     46    }
     47
     48    /**
     49    * Replies the list of currently selected vias
     50    *
     51    * @return the list of currently selected vias
     52    */
     53    public List<OsmPrimitive> getSelectedVias() {
     54        ArrayList<OsmPrimitive> ret = new ArrayList<OsmPrimitive>();
     55        for (int i=0; i < getSize(); i++) {
     56            if (selectionModel.isSelectedIndex(i)) {
     57                ret.add(vias.get(i));
     58            }
     59        }
     60        return ret;
     61    }
     62   
     63    /**
     64    * Sets the collection of currently selected vias
     65    *
     66    *  @param vias a collection of vias
     67    */
     68    public void setSelectedVias(Collection<OsmPrimitive> vias) {
     69        selectionModel.clearSelection();
     70        if (vias == null) return;
     71        for(OsmPrimitive via: vias) {
     72            int idx = this.vias.indexOf(via);
     73            if (idx < 0) continue;
     74            selectionModel.addSelectionInterval(idx, idx);
     75        }
     76    }
     77   
     78    /**
     79    * Replies the list of selected rows
     80    *
     81    * @return the list of selected rows
     82    */
     83    public List<Integer> getSelectedRows() {
     84        ArrayList<Integer> ret = new ArrayList<Integer>();
     85        for (int i=0; i < getSize(); i++) {
     86            if (selectionModel.isSelectedIndex(i)) {
     87                ret.add(i);
     88            }
     89        }
     90        return ret;
     91    }
     92   
     93    protected List<Integer> moveUp(List<Integer> rows, int targetRow) {
     94        List<Integer> ret = new ArrayList<Integer>(rows.size());
     95        int delta = rows.get(0) - targetRow;
     96        for(int row: rows) {
     97            OsmPrimitive via = vias.remove(row);
     98            vias.add(row - delta, via);
     99            ret.add(row - delta);
     100        }
     101        return ret;
     102    }
     103   
     104    protected List<Integer>  moveDown(List<Integer> rows, int targetRow) {
     105        List<Integer> ret = new ArrayList<Integer>(rows.size());
     106        int delta = targetRow - rows.get(0);
     107        for(int i = rows.size()-1; i >=0; i--) {
     108            int row = rows.get(i);
     109            OsmPrimitive via = vias.remove(row);
     110            vias.add(row + delta, via);
     111            ret.add(row + delta);
     112        }
     113        return ret;
     114    }
     115   
     116    public void moveVias(List<Integer> selectedRows, int targetRow){
     117        if (selectedRows == null) return;
     118        if (selectedRows.size() == 1){
     119            int sourceRow = selectedRows.get(0);
     120            if (sourceRow == targetRow) return;
     121            OsmPrimitive via = vias.remove(sourceRow);
     122            vias.add(targetRow, via);
     123            fireContentsChanged(this, 0, getSize());
     124            selectionModel.setSelectionInterval(targetRow, targetRow);
     125            return;
     126        }
     127        int min = selectedRows.get(0);
     128        int max = selectedRows.get(selectedRows.size()-1);
     129        if (targetRow < min) {
     130            selectedRows = moveUp(selectedRows, targetRow);
     131        } else if (targetRow == min){
     132            // do nothing
     133        } else if (targetRow - min < getSize() - max){
     134            int delta = Math.min(targetRow - min, getSize()-1 - max);
     135            targetRow = min + delta;
     136            if (targetRow > min) {
     137                selectedRows = moveDown(selectedRows, targetRow);
     138            }
     139        }
     140        fireContentsChanged(this, 0, getSize());
     141        selectionModel.clearSelection();
     142        for(int row: selectedRows) {
     143            selectionModel.addSelectionInterval(row, row);
     144        }       
     145    }
     146   
     147    /**
     148    * Move the currently selected vias up by one position
     149    */
     150    public void moveUp() {
     151        List<Integer> sel = getSelectedRows();
     152        if (sel.isEmpty() || sel.get(0) == 0) return;
     153        moveVias(sel, sel.get(0)-1);
     154    }
     155
     156    /**
     157    * Move the currently selected vias down by one position
     158    */
     159    public void moveDown() {
     160        List<Integer> sel = getSelectedRows();
     161        if (sel.isEmpty() || sel.get(sel.size()-1) == getSize()-1) return;
     162        moveVias(sel, sel.get(sel.size()-1)+1);
     163    }
     164   
     165    /**
     166    * Inserts a list of OSM objects given by OSM primitive ids.
     167    *
     168    * @param idsToInsert the ids of the objects to insert
     169    */
     170    public void insertVias(List<PrimitiveId> idsToInsert) {
     171        if (idsToInsert == null) return;
     172        List<OsmPrimitive> primitives = new ArrayList<OsmPrimitive>(idsToInsert.size());
     173        DataSet ds = model.getLayer().data;
     174        for(PrimitiveId id: idsToInsert){
     175            OsmPrimitive p = ds.getPrimitiveById(id);
     176            if (p == null){
     177                System.out.println(tr("Failed to retrieve OSM object with id {0} from dataset {1}. Cannot add it as ''via''.", id, ds));
     178                continue;
     179            }
     180            primitives.add(p);
     181        }
     182        int targetRow = Math.max(selectionModel.getMinSelectionIndex(),0);
     183        List<OsmPrimitive> newVias = new ArrayList<OsmPrimitive>(vias);
     184        newVias.addAll(targetRow, primitives);
     185        model.setVias(newVias);
     186        fireContentsChanged(this, 0, getSize());
     187        selectionModel.clearSelection();
     188        for(int i=targetRow; i< targetRow + primitives.size();i++) {
     189            selectionModel.addSelectionInterval(i, i);
     190        }           
     191    }
     192
     193    /**
     194    * Removes the currently selected vias
     195    */
     196    public void removeSelectedVias() {
     197        ArrayList<OsmPrimitive> newVias = new ArrayList<OsmPrimitive>(vias);
     198        int j = 0;
     199        for(int i=0; i< getSize();i++){
     200            if (!selectionModel.isSelectedIndex(i)) continue;
     201            newVias.remove(i-j);
     202            j++;
     203        }
     204        if (j == 0) return; // nothing selected, nothing deleted
     205        model.setVias(newVias);
     206    }
     207   
     208    /**
     209    * Refreshes the list of 'vias' in this model with the current list of
     210    * vias from the turn restriction model.
     211    */
     212    protected void refresh() {
     213        List<OsmPrimitive> sel = getSelectedVias();
     214        vias.clear();
     215        vias.addAll(model.getVias());       
     216        fireContentsChanged(this, 0, getSize());
     217        setSelectedVias(sel);
     218    }
     219
     220    public Object getElementAt(int index) {
     221        return vias.get(index);
     222    }
     223
     224    public int getSize() {
     225        return vias.size();
     226    }
     227   
     228    /* ----------------------------------------------------------------------- */
     229    /* interface PrimitiveIdListProvider                                       */
     230    /* ----------------------------------------------------------------------- */
     231    public List<PrimitiveId> getSelectedPrimitiveIds() {
     232        ArrayList<PrimitiveId> ids = new ArrayList<PrimitiveId>();
     233        for (OsmPrimitive p: getSelectedVias()) {
     234            ids.add(p.getPrimitiveId());
     235        }
     236        return ids;
     237    }
     238
     239    /* ----------------------------------------------------------------------- */
     240    /* interface Observer                                                      */
     241    /* ----------------------------------------------------------------------- */
     242    public void update(Observable o, Object arg) {
     243        refresh();
     244    }   
    245245}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/list/AbstractTurnRestrictionsListView.java

    r20666 r23192  
    1515 */
    1616abstract class AbstractTurnRestrictionsListView extends JPanel {
    17         protected TurnRestrictionsListModel model;
    18         protected JList lstTurnRestrictions;
    19        
    20         public TurnRestrictionsListModel getModel(){
    21                 return model;
    22         }
    23        
    24         public JList getList() {
    25                 return lstTurnRestrictions;
    26         }
    27        
    28         public void addListSelectionListener(ListSelectionListener listener) {
    29                 lstTurnRestrictions.addListSelectionListener(listener);
    30         }
    31        
    32         public void removeListSelectionListener(ListSelectionListener listener) {
    33                 lstTurnRestrictions.addListSelectionListener(listener);
    34         }
    35        
    36         public void initIconSetFromPreferences(Preferences prefs){
    37                 TurnRestrictionCellRenderer renderer = (TurnRestrictionCellRenderer)lstTurnRestrictions.getCellRenderer();
    38                 renderer.initIconSetFromPreferences(prefs);
    39         }
     17    protected TurnRestrictionsListModel model;
     18    protected JList lstTurnRestrictions;
     19   
     20    public TurnRestrictionsListModel getModel(){
     21        return model;
     22    }
     23   
     24    public JList getList() {
     25        return lstTurnRestrictions;
     26    }
     27   
     28    public void addListSelectionListener(ListSelectionListener listener) {
     29        lstTurnRestrictions.addListSelectionListener(listener);
     30    }
     31   
     32    public void removeListSelectionListener(ListSelectionListener listener) {
     33        lstTurnRestrictions.addListSelectionListener(listener);
     34    }
     35   
     36    public void initIconSetFromPreferences(Preferences prefs){
     37        TurnRestrictionCellRenderer renderer = (TurnRestrictionCellRenderer)lstTurnRestrictions.getCellRenderer();
     38        renderer.initIconSetFromPreferences(prefs);
     39    }
    4040}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/list/TurnRestrictionCellRenderer.java

    r20701 r23192  
    4141 */
    4242public class TurnRestrictionCellRenderer extends JPanel implements ListCellRenderer, TableCellRenderer{
    43         static private final Logger logger = Logger.getLogger(TurnRestrictionCellRenderer.class.getName());
    44        
    45         /** the names of restriction types */
    46         static private Set<String> RESTRICTION_TYPES = new HashSet<String>(
    47                         Arrays.asList(new String[] {
    48                                         "no_left_turn",
    49                                         "no_right_turn",
    50                                         "no_straight_on",
    51                                         "no_u_turn",
    52                                         "only_left_turn",
    53                                         "only_right_turn",
    54                                         "only_straight_on"
    55                         })
    56         );
    57        
    58         /** components used to render the turn restriction */
    59         private JLabel icon;
    60         private JLabel from;
    61         private JLabel to;
    62         private String iconSet = "set-a";
    63        
    64         public TurnRestrictionCellRenderer() {
    65                 build();
    66         }
    67 
    68         /**
    69         * Replies true if {@code restrictionType} is a valid restriction
    70         * type.
    71         *
    72         * @param restrictionType the restriction type
    73         * @return true if {@code restrictionType} is a valid restriction
    74         * type
    75         */
    76         protected boolean isValidRestrictionType(String restrictionType) {
    77                 if (restrictionType == null) return false;
    78                 restrictionType = restrictionType.trim().toLowerCase();
    79                 return RESTRICTION_TYPES.contains(restrictionType);
    80         }
    81        
    82         /**
    83         * Builds the icon name for a given restriction type
    84         *
    85         * @param restrictionType the restriction type
    86         * @return the icon name
    87         */
    88         protected String buildImageName(String restrictionType) {
    89                 return "types/" + iconSet + "/" + restrictionType;
    90         }
    91        
    92         /**
    93         * Replies the icon for a given restriction type
    94         * @param restrictionType the restriction type
    95         * @return the icon
    96         */
    97         protected ImageIcon getIcon(String restrictionType) {
    98                 if (!isValidRestrictionType(restrictionType)) {
    99                         return ImageProvider.get("types", "non-standard-type");
    100                 }
    101                 return ImageProvider.get(buildImageName(restrictionType));
    102         }
    103         
    104         /**
    105         * Builds the UI used to render turn restrictions
    106         */
    107         protected void build() {
    108                 setLayout(new GridBagLayout());
    109                 GridBagConstraints gc = new GridBagConstraints();
    110                
    111                 // the turn restriction icon           
    112                 gc.fill = GridBagConstraints.HORIZONTAL;
    113                 gc.weightx = 0.0;
    114                 gc.gridheight = 2;
    115                 gc.anchor = GridBagConstraints.CENTER;
    116                 gc.insets = new Insets(0,0,2,2);
    117                 add(icon = new JLabel(), gc);
    118                
    119                
    120                 // the name of the way with role "from"
    121                 gc.anchor = GridBagConstraints.NORTHWEST;
    122                 gc.gridx = 1;
    123                 gc.gridheight = 1;
    124                 gc.weightx = 0.0;
    125                 add(new JMultilineLabel("<html><strong>" + trc("turnrestrictions","From:") + "</strong></html>"), gc);
    126                
    127                 gc.gridx = 2;
    128                 gc.weightx = 1.0;
    129                 add(from = new JLabel(), gc);
    130                
    131                 // the name of the way with role "to"
    132                 gc.anchor = GridBagConstraints.NORTHWEST;
    133                 gc.gridx = 1;
    134                 gc.gridy = 1;
    135                 gc.weightx = 0.0;
    136                 add(new JMultilineLabel("<html><strong>" + trc("turnrestriction", "To:")  + "</strong></html>"), gc);
    137                
    138                 gc.gridx = 2;
    139                 gc.weightx = 1.0;
    140                 add(to = new JLabel(), gc);
    141         }
    142 
    143         /**
    144         * Renders the icon for the turn restriction 
    145         *
    146         * @param tr the turn restriction
    147         */
    148         protected void renderIcon(Relation tr) {
    149                 String restrictionType = tr.get("restriction");
    150                 icon.setIcon(getIcon(restrictionType));
    151         }
    152 
    153         /**
    154         * Replies a way participating in this turn restriction in a given role
    155         *
    156         * @param tr the turn restriction
    157         * @param role the role (either "from" or "to")
    158         * @return the participating way; null, if no way is participating in this role
    159         */
    160         private Way getParticipatingWay(Relation tr, String role){
    161                 for(RelationMember rm: tr.getMembers()){
    162                         if (rm.getRole().trim().toLowerCase().equals(role) && rm.getType().equals(OsmPrimitiveType.WAY)) {
    163                                 return (Way)rm.getMember();
    164                         }
    165                 }
    166                 return null;
    167         }
    168        
    169         protected void renderFrom(Relation tr) {
    170                 Way from = getParticipatingWay(tr, "from");
    171                 if (from == null) {
    172                         // FIXME: render as warning/error (red background?)
    173                         this.from.setText(tr("no participating way with role ''from''"));
    174                         return;
    175                 }
    176                 this.from.setText(DefaultNameFormatter.getInstance().format(from));
    177         }
    178 
    179         protected void renderTo(Relation tr) {
    180                 Way to = getParticipatingWay(tr, "to");
    181                 if (to == null) {
    182                         // FIXME: render as warning/error (red background?)
    183                         this.to.setText(tr("no participating way with role ''to''"));
    184                         return;
    185                 }
    186                 this.to.setText(DefaultNameFormatter.getInstance().format(to));
    187         }
    188 
    189         /**
    190         * Renders the foreground and background color depending on whether
    191         * the turn restriction is selected
    192         *
    193         * @param isSelected true if the turn restriction is selected; false,
    194         * otherwise
    195         */
    196         protected void renderColor(boolean isSelected) {
    197                 Color bg;
    198                 Color fg;
    199                 if (isSelected) {
    200                         bg = UIManager.getColor("List.selectionBackground");
    201                         fg = UIManager.getColor("List.selectionForeground");
    202                 } else {
    203                         bg = UIManager.getColor("background");
    204                         fg = UIManager.getColor("foreground");
    205                 }
    206                 setBackground(bg);
    207                 this.icon.setBackground(bg);
    208                 this.from.setBackground(bg);
    209                 this.to.setBackground(bg);
    210                
    211                 setForeground(fg);
    212                 this.icon.setForeground(fg);
    213                 this.from.setForeground(fg);
    214                 this.to.setForeground(fg);
    215         }
    216 
    217         /**
    218         * Initializes the set of icons used from the preference key
    219         * {@see PreferenceKeys#ROAD_SIGNS}.
    220         *
    221         * @param prefs the JOSM preferences
    222         */
    223         public void initIconSetFromPreferences(Preferences prefs){
    224                
    225                 iconSet = prefs.get(PreferenceKeys.ROAD_SIGNS, "set-a");
    226                 iconSet = iconSet.trim().toLowerCase();
    227                 if (!iconSet.equals("set-a") && !iconSet.equals("set-b")) {
    228                         iconSet = "set-a";
    229                 }
    230         }
    231        
    232         /* ---------------------------------------------------------------------------------- */
    233         /* interface ListCellRenderer                                                         */
    234         /* ---------------------------------------------------------------------------------- */
    235         public Component getListCellRendererComponent(JList list, Object value,
    236                         int index, boolean isSelected, boolean cellHasFocus) {
    237 
    238                 renderColor(isSelected);
    239                 Relation tr = (Relation)value;
    240                 renderIcon(tr);
    241                 renderFrom(tr);
    242                 renderTo(tr);           
    243                 return this;
    244         }
    245 
    246         /* ---------------------------------------------------------------------------------- */
    247         /* interface TableCellRenderer                                                        */
    248         /* ---------------------------------------------------------------------------------- */
    249         public Component getTableCellRendererComponent(JTable table, Object value,
    250                         boolean isSelected, boolean hasFocus, int row, int column) {
    251                 renderColor(isSelected);               
    252                 Relation tr = (Relation)value;
    253                 renderIcon(tr);
    254                 renderFrom(tr);
    255                 renderTo(tr);           
    256                 return this;
    257         }       
     43    static private final Logger logger = Logger.getLogger(TurnRestrictionCellRenderer.class.getName());
     44   
     45    /** the names of restriction types */
     46    static private Set<String> RESTRICTION_TYPES = new HashSet<String>(
     47            Arrays.asList(new String[] {
     48                    "no_left_turn",
     49                    "no_right_turn",
     50                    "no_straight_on",
     51                    "no_u_turn",
     52                    "only_left_turn",
     53                    "only_right_turn",
     54                    "only_straight_on"
     55            })
     56    );
     57   
     58    /** components used to render the turn restriction */
     59    private JLabel icon;
     60    private JLabel from;
     61    private JLabel to;
     62    private String iconSet = "set-a";
     63   
     64    public TurnRestrictionCellRenderer() {
     65        build();
     66    }
     67
     68    /**
     69    * Replies true if {@code restrictionType} is a valid restriction
     70    * type.
     71    *
     72    * @param restrictionType the restriction type
     73    * @return true if {@code restrictionType} is a valid restriction
     74    * type
     75    */
     76    protected boolean isValidRestrictionType(String restrictionType) {
     77        if (restrictionType == null) return false;
     78        restrictionType = restrictionType.trim().toLowerCase();
     79        return RESTRICTION_TYPES.contains(restrictionType);
     80    }
     81   
     82    /**
     83    * Builds the icon name for a given restriction type
     84    *
     85    * @param restrictionType the restriction type
     86    * @return the icon name
     87    */
     88    protected String buildImageName(String restrictionType) {
     89        return "types/" + iconSet + "/" + restrictionType;
     90    }
     91   
     92    /**
     93    * Replies the icon for a given restriction type
     94    * @param restrictionType the restriction type
     95    * @return the icon
     96    */
     97    protected ImageIcon getIcon(String restrictionType) {
     98        if (!isValidRestrictionType(restrictionType)) {
     99            return ImageProvider.get("types", "non-standard-type");
     100        }
     101        return ImageProvider.get(buildImageName(restrictionType));
     102    }
     103    
     104    /**
     105    * Builds the UI used to render turn restrictions
     106    */
     107    protected void build() {
     108        setLayout(new GridBagLayout());
     109        GridBagConstraints gc = new GridBagConstraints();
     110       
     111        // the turn restriction icon       
     112        gc.fill = GridBagConstraints.HORIZONTAL;
     113        gc.weightx = 0.0;
     114        gc.gridheight = 2;
     115        gc.anchor = GridBagConstraints.CENTER;
     116        gc.insets = new Insets(0,0,2,2);
     117        add(icon = new JLabel(), gc);
     118       
     119       
     120        // the name of the way with role "from"
     121        gc.anchor = GridBagConstraints.NORTHWEST;
     122        gc.gridx = 1;
     123        gc.gridheight = 1;
     124        gc.weightx = 0.0;
     125        add(new JMultilineLabel("<html><strong>" + trc("turnrestrictions","From:") + "</strong></html>"), gc);
     126       
     127        gc.gridx = 2;
     128        gc.weightx = 1.0;
     129        add(from = new JLabel(), gc);
     130       
     131        // the name of the way with role "to"
     132        gc.anchor = GridBagConstraints.NORTHWEST;
     133        gc.gridx = 1;
     134        gc.gridy = 1;
     135        gc.weightx = 0.0;
     136        add(new JMultilineLabel("<html><strong>" + trc("turnrestriction", "To:")  + "</strong></html>"), gc);
     137       
     138        gc.gridx = 2;
     139        gc.weightx = 1.0;
     140        add(to = new JLabel(), gc);
     141    }
     142
     143    /**
     144    * Renders the icon for the turn restriction 
     145    *
     146    * @param tr the turn restriction
     147    */
     148    protected void renderIcon(Relation tr) {
     149        String restrictionType = tr.get("restriction");
     150        icon.setIcon(getIcon(restrictionType));
     151    }
     152
     153    /**
     154    * Replies a way participating in this turn restriction in a given role
     155    *
     156    * @param tr the turn restriction
     157    * @param role the role (either "from" or "to")
     158    * @return the participating way; null, if no way is participating in this role
     159    */
     160    private Way getParticipatingWay(Relation tr, String role){
     161        for(RelationMember rm: tr.getMembers()){
     162            if (rm.getRole().trim().toLowerCase().equals(role) && rm.getType().equals(OsmPrimitiveType.WAY)) {
     163                return (Way)rm.getMember();
     164            }
     165        }
     166        return null;
     167    }
     168   
     169    protected void renderFrom(Relation tr) {
     170        Way from = getParticipatingWay(tr, "from");
     171        if (from == null) {
     172            // FIXME: render as warning/error (red background?)
     173            this.from.setText(tr("no participating way with role ''from''"));
     174            return;
     175        }
     176        this.from.setText(DefaultNameFormatter.getInstance().format(from));
     177    }
     178
     179    protected void renderTo(Relation tr) {
     180        Way to = getParticipatingWay(tr, "to");
     181        if (to == null) {
     182            // FIXME: render as warning/error (red background?)
     183            this.to.setText(tr("no participating way with role ''to''"));
     184            return;
     185        }
     186        this.to.setText(DefaultNameFormatter.getInstance().format(to));
     187    }
     188
     189    /**
     190    * Renders the foreground and background color depending on whether
     191    * the turn restriction is selected
     192    *
     193    * @param isSelected true if the turn restriction is selected; false,
     194    * otherwise
     195    */
     196    protected void renderColor(boolean isSelected) {
     197        Color bg;
     198        Color fg;
     199        if (isSelected) {
     200            bg = UIManager.getColor("List.selectionBackground");
     201            fg = UIManager.getColor("List.selectionForeground");
     202        } else {
     203            bg = UIManager.getColor("background");
     204            fg = UIManager.getColor("foreground");
     205        }
     206        setBackground(bg);
     207        this.icon.setBackground(bg);
     208        this.from.setBackground(bg);
     209        this.to.setBackground(bg);
     210       
     211        setForeground(fg);
     212        this.icon.setForeground(fg);
     213        this.from.setForeground(fg);
     214        this.to.setForeground(fg);
     215    }
     216
     217    /**
     218    * Initializes the set of icons used from the preference key
     219    * {@see PreferenceKeys#ROAD_SIGNS}.
     220    *
     221    * @param prefs the JOSM preferences
     222    */
     223    public void initIconSetFromPreferences(Preferences prefs){
     224       
     225        iconSet = prefs.get(PreferenceKeys.ROAD_SIGNS, "set-a");
     226        iconSet = iconSet.trim().toLowerCase();
     227        if (!iconSet.equals("set-a") && !iconSet.equals("set-b")) {
     228            iconSet = "set-a";
     229        }
     230    }
     231   
     232    /* ---------------------------------------------------------------------------------- */
     233    /* interface ListCellRenderer                                                         */
     234    /* ---------------------------------------------------------------------------------- */
     235    public Component getListCellRendererComponent(JList list, Object value,
     236            int index, boolean isSelected, boolean cellHasFocus) {
     237
     238        renderColor(isSelected);
     239        Relation tr = (Relation)value;
     240        renderIcon(tr);
     241        renderFrom(tr);
     242        renderTo(tr);       
     243        return this;
     244    }
     245
     246    /* ---------------------------------------------------------------------------------- */
     247    /* interface TableCellRenderer                                                        */
     248    /* ---------------------------------------------------------------------------------- */
     249    public Component getTableCellRendererComponent(JTable table, Object value,
     250            boolean isSelected, boolean hasFocus, int row, int column) {
     251        renderColor(isSelected);       
     252        Relation tr = (Relation)value;
     253        renderIcon(tr);
     254        renderFrom(tr);
     255        renderTo(tr);       
     256        return this;
     257    }   
    258258}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/list/TurnRestrictionsInDatasetListModel.java

    r20489 r23192  
    3434 */
    3535public class TurnRestrictionsInDatasetListModel extends TurnRestrictionsListModel implements EditLayerChangeListener, DataSetListener {
    36         private static final Logger logger = Logger.getLogger(TurnRestrictionsInDatasetListModel.class.getName());
    37        
    38         public TurnRestrictionsInDatasetListModel(
    39                         DefaultListSelectionModel selectionModel) {
    40                 super(selectionModel);
    41         }
    42        
    43         /**
    44         * Filters the list of turn restrictions from a collection of OSM primitives.
    45         *
    46         * @param primitives the primitives
    47         * @return the list of turn restrictions
    48         */
    49         protected List<Relation> filterTurnRestrictions(Collection<? extends OsmPrimitive> primitives) {
    50                 List<Relation> ret = new LinkedList<Relation>();
    51                 if (primitives == null) return ret;
    52                 for(OsmPrimitive p: primitives){
    53                         if (!isTurnRestriction(p)) continue;
    54                         ret.add((Relation)p);
    55                 }
    56                 return ret;
    57         }
    58        
    59         /* --------------------------------------------------------------------------- */
    60         /* interface EditLayerChangeListener                                           */
    61         /* --------------------------------------------------------------------------- */
    62         public void editLayerChanged(OsmDataLayer oldLayer, OsmDataLayer newLayer) {
    63                 if (newLayer == null) {
    64                         setTurnRestrictions(null);
    65                         return;
    66                 }
    67                 List<Relation> turnRestrictions = new LinkedList<Relation>();
    68                 for (Relation r: newLayer.data.getRelations()) {
    69                         if (isValid(r) && isTurnRestriction(r)) {
    70                                 turnRestrictions.add(r);
    71                         }
    72                 }
    73                 setTurnRestrictions(turnRestrictions);
    74         }
    75        
    76         /* --------------------------------------------------------------------------- */
    77         /* interface DataSetListener                                                   */
    78         /* --------------------------------------------------------------------------- */       
    79         public void dataChanged(DataChangedEvent event) {               
    80                 OsmDataLayer layer = Main.map.mapView.getEditLayer();
    81                 if (layer == null) {
    82                         setTurnRestrictions(null);
    83                 } else {
    84                         List<Relation> turnRestrictions = filterTurnRestrictions(layer.data.getRelations());
    85                         setTurnRestrictions(turnRestrictions);
    86                 }
    87         }
     36    private static final Logger logger = Logger.getLogger(TurnRestrictionsInDatasetListModel.class.getName());
     37   
     38    public TurnRestrictionsInDatasetListModel(
     39            DefaultListSelectionModel selectionModel) {
     40        super(selectionModel);
     41    }
     42   
     43    /**
     44    * Filters the list of turn restrictions from a collection of OSM primitives.
     45    *
     46    * @param primitives the primitives
     47    * @return the list of turn restrictions
     48    */
     49    protected List<Relation> filterTurnRestrictions(Collection<? extends OsmPrimitive> primitives) {
     50        List<Relation> ret = new LinkedList<Relation>();
     51        if (primitives == null) return ret;
     52        for(OsmPrimitive p: primitives){
     53            if (!isTurnRestriction(p)) continue;
     54            ret.add((Relation)p);
     55        }
     56        return ret;
     57    }
     58   
     59    /* --------------------------------------------------------------------------- */
     60    /* interface EditLayerChangeListener                                           */
     61    /* --------------------------------------------------------------------------- */
     62    public void editLayerChanged(OsmDataLayer oldLayer, OsmDataLayer newLayer) {
     63        if (newLayer == null) {
     64            setTurnRestrictions(null);
     65            return;
     66        }
     67        List<Relation> turnRestrictions = new LinkedList<Relation>();
     68        for (Relation r: newLayer.data.getRelations()) {
     69            if (isValid(r) && isTurnRestriction(r)) {
     70                turnRestrictions.add(r);
     71            }
     72        }
     73        setTurnRestrictions(turnRestrictions);
     74    }
     75   
     76    /* --------------------------------------------------------------------------- */
     77    /* interface DataSetListener                                                   */
     78    /* --------------------------------------------------------------------------- */   
     79    public void dataChanged(DataChangedEvent event) {       
     80        OsmDataLayer layer = Main.map.mapView.getEditLayer();
     81        if (layer == null) {
     82            setTurnRestrictions(null);
     83        } else {
     84            List<Relation> turnRestrictions = filterTurnRestrictions(layer.data.getRelations());
     85            setTurnRestrictions(turnRestrictions);
     86        }
     87    }
    8888
    89         public void primtivesAdded(PrimitivesAddedEvent event) {
    90                 List<Relation> turnRestrictions = filterTurnRestrictions(event.getPrimitives());
    91                 if (!turnRestrictions.isEmpty()) {
    92                         addTurnRestrictions(turnRestrictions);
    93                 }
    94         }
     89    public void primtivesAdded(PrimitivesAddedEvent event) {
     90        List<Relation> turnRestrictions = filterTurnRestrictions(event.getPrimitives());
     91        if (!turnRestrictions.isEmpty()) {
     92            addTurnRestrictions(turnRestrictions);
     93        }
     94    }
    9595
    96         public void primtivesRemoved(PrimitivesRemovedEvent event) {
    97                 List<Relation> turnRestrictions = filterTurnRestrictions(event.getPrimitives());
    98                 if (!turnRestrictions.isEmpty()) {
    99                         removeTurnRestrictions(turnRestrictions);
    100                 }
    101         }
     96    public void primtivesRemoved(PrimitivesRemovedEvent event) {
     97        List<Relation> turnRestrictions = filterTurnRestrictions(event.getPrimitives());
     98        if (!turnRestrictions.isEmpty()) {
     99            removeTurnRestrictions(turnRestrictions);
     100        }
     101    }
    102102
    103         public void relationMembersChanged(RelationMembersChangedEvent event) {
    104                 List<Relation> turnRestrictions = filterTurnRestrictions(event.getPrimitives());
    105                 if (!turnRestrictions.isEmpty()) {
    106                         List<Relation> sel = getSelectedTurnRestrictions();
    107                         for(Relation tr: turnRestrictions) {   
    108                                 // enforce a repaint of the respective turn restriction
    109                                 int idx = getTurnRestrictionIndex(tr);
    110                                 fireContentsChanged(this, idx,idx);
    111                         }
    112                         setSelectedTurnRestrictions(sel);
    113                 }
    114         }
     103    public void relationMembersChanged(RelationMembersChangedEvent event) {
     104        List<Relation> turnRestrictions = filterTurnRestrictions(event.getPrimitives());
     105        if (!turnRestrictions.isEmpty()) {
     106            List<Relation> sel = getSelectedTurnRestrictions();
     107            for(Relation tr: turnRestrictions) {   
     108                // enforce a repaint of the respective turn restriction
     109                int idx = getTurnRestrictionIndex(tr);
     110                fireContentsChanged(this, idx,idx);
     111            }
     112            setSelectedTurnRestrictions(sel);
     113        }
     114    }
    115115
    116         public void tagsChanged(TagsChangedEvent event) {
    117                 List<Relation> turnRestrictions = filterTurnRestrictions(event.getPrimitives());
    118                 if (!turnRestrictions.isEmpty()) {
    119                         List<Relation> sel = getSelectedTurnRestrictions();
    120                         for(Relation tr: turnRestrictions) {   
    121                                 // enforce a repaint of the respective turn restriction
    122                                 int idx = getTurnRestrictionIndex(tr);
    123                                 fireContentsChanged(this, idx,idx);
    124                         }
    125                         setSelectedTurnRestrictions(sel);
    126                 }               
    127         }
     116    public void tagsChanged(TagsChangedEvent event) {
     117        List<Relation> turnRestrictions = filterTurnRestrictions(event.getPrimitives());
     118        if (!turnRestrictions.isEmpty()) {
     119            List<Relation> sel = getSelectedTurnRestrictions();
     120            for(Relation tr: turnRestrictions) {   
     121                // enforce a repaint of the respective turn restriction
     122                int idx = getTurnRestrictionIndex(tr);
     123                fireContentsChanged(this, idx,idx);
     124            }
     125            setSelectedTurnRestrictions(sel);
     126        }       
     127    }
    128128
    129         public void wayNodesChanged(WayNodesChangedEvent event) {/* ignore */}
    130         public void nodeMoved(NodeMovedEvent event) {/* ignore */}
    131         public void otherDatasetChange(AbstractDatasetChangedEvent event) {/* ignore */}
     129    public void wayNodesChanged(WayNodesChangedEvent event) {/* ignore */}
     130    public void nodeMoved(NodeMovedEvent event) {/* ignore */}
     131    public void otherDatasetChange(AbstractDatasetChangedEvent event) {/* ignore */}
    132132}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/list/TurnRestrictionsInDatasetView.java

    r20711 r23192  
    1818 * This is the view for the list of turn restrictions in the current data set.
    1919 */
    20 public class TurnRestrictionsInDatasetView extends AbstractTurnRestrictionsListView{   
    21         protected void build() {
    22                 DefaultListSelectionModel selectionModel = new DefaultListSelectionModel();
    23                 model = new TurnRestrictionsInDatasetListModel(selectionModel);
    24                 lstTurnRestrictions = new JList(model);
    25                 lstTurnRestrictions.setSelectionModel(selectionModel);
    26                 lstTurnRestrictions.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    27                 lstTurnRestrictions.setCellRenderer(new TurnRestrictionCellRenderer());
    28                
    29                 setLayout(new BorderLayout());
    30                 add(new JScrollPane(lstTurnRestrictions), BorderLayout.CENTER);
    31         }
     20public class TurnRestrictionsInDatasetView extends AbstractTurnRestrictionsListView{   
     21    protected void build() {
     22        DefaultListSelectionModel selectionModel = new DefaultListSelectionModel();
     23        model = new TurnRestrictionsInDatasetListModel(selectionModel);
     24        lstTurnRestrictions = new JList(model);
     25        lstTurnRestrictions.setSelectionModel(selectionModel);
     26        lstTurnRestrictions.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
     27        lstTurnRestrictions.setCellRenderer(new TurnRestrictionCellRenderer());
     28       
     29        setLayout(new BorderLayout());
     30        add(new JScrollPane(lstTurnRestrictions), BorderLayout.CENTER);
     31    }
    3232
    33         protected void registerAsListener() {
    34                 MapView.addEditLayerChangeListener((EditLayerChangeListener)model);
    35                 DatasetEventManager.getInstance().addDatasetListener((DataSetListener)model, FireMode.IN_EDT);
    36                 if (Main.main.getEditLayer() != null) {
    37                         model.setTurnRestrictions(Main.main.getEditLayer().data.getRelations());
    38                 }
    39         }
     33    protected void registerAsListener() {
     34        MapView.addEditLayerChangeListener((EditLayerChangeListener)model);
     35        DatasetEventManager.getInstance().addDatasetListener((DataSetListener)model, FireMode.IN_EDT);
     36        if (Main.main.getEditLayer() != null) {
     37            model.setTurnRestrictions(Main.main.getEditLayer().data.getRelations());
     38        }
     39    }
    4040
    41         protected void unregisterAsListener() {
    42                 MapView.removeEditLayerChangeListener((EditLayerChangeListener)model);
    43                 DatasetEventManager.getInstance().removeDatasetListener((DataSetListener)model);
    44         }
     41    protected void unregisterAsListener() {
     42        MapView.removeEditLayerChangeListener((EditLayerChangeListener)model);
     43        DatasetEventManager.getInstance().removeDatasetListener((DataSetListener)model);
     44    }
    4545
    46         public TurnRestrictionsInDatasetView() {
    47                 build();
    48         }
     46    public TurnRestrictionsInDatasetView() {
     47        build();
     48    }
    4949}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/list/TurnRestrictionsInSelectionListModel.java

    r20489 r23192  
    1919 */
    2020public class TurnRestrictionsInSelectionListModel extends TurnRestrictionsListModel implements EditLayerChangeListener, SelectionChangedListener {
    21         private static final Logger logger = Logger.getLogger(TurnRestrictionsInSelectionListModel.class.getName());
    22        
    23         public TurnRestrictionsInSelectionListModel(
    24                         DefaultListSelectionModel selectionModel) {
    25                 super(selectionModel);
    26         }
    27        
    28         /**
    29         * Initializes the model with the turn restrictions the primitives in
    30         * {@code selection} participate.
    31         *
    32         * @param selection the collection of selected primitives
    33         */
    34         public void initFromSelection(Collection<? extends OsmPrimitive> selection) {
    35                 Set<Relation> turnRestrictions = new HashSet<Relation>();
    36                 if (selection == null) return;
    37                 for (OsmPrimitive p: selection) {
    38                         for (OsmPrimitive parent: p.getReferrers()) {
    39                                 if (isTurnRestriction(parent))
    40                                         turnRestrictions.add((Relation)parent);
    41                         }
    42                 }
    43                 setTurnRestrictions(turnRestrictions);
    44         }
     21    private static final Logger logger = Logger.getLogger(TurnRestrictionsInSelectionListModel.class.getName());
     22   
     23    public TurnRestrictionsInSelectionListModel(
     24            DefaultListSelectionModel selectionModel) {
     25        super(selectionModel);
     26    }
     27   
     28    /**
     29    * Initializes the model with the turn restrictions the primitives in
     30    * {@code selection} participate.
     31    *
     32    * @param selection the collection of selected primitives
     33    */
     34    public void initFromSelection(Collection<? extends OsmPrimitive> selection) {
     35        Set<Relation> turnRestrictions = new HashSet<Relation>();
     36        if (selection == null) return;
     37        for (OsmPrimitive p: selection) {
     38            for (OsmPrimitive parent: p.getReferrers()) {
     39                if (isTurnRestriction(parent))
     40                    turnRestrictions.add((Relation)parent);
     41            }
     42        }
     43        setTurnRestrictions(turnRestrictions);
     44    }
    4545
    46         /* --------------------------------------------------------------------------- */
    47         /* interface EditLayerChangeListener                                           */
    48         /* --------------------------------------------------------------------------- */
    49         public void editLayerChanged(OsmDataLayer oldLayer, OsmDataLayer newLayer) {
    50                 if (newLayer == null) {
    51                         setTurnRestrictions(null);
    52                         return;
    53                 }
    54                 initFromSelection(newLayer.data.getSelected());
    55         }
    56        
    57         /* --------------------------------------------------------------------------- */
    58         /* interface SelectionChangedListener                                          */
    59         /* --------------------------------------------------------------------------- */       
    60         public void selectionChanged(Collection<? extends OsmPrimitive> newSelection) {
    61                 initFromSelection(newSelection);
    62         }
     46    /* --------------------------------------------------------------------------- */
     47    /* interface EditLayerChangeListener                                           */
     48    /* --------------------------------------------------------------------------- */
     49    public void editLayerChanged(OsmDataLayer oldLayer, OsmDataLayer newLayer) {
     50        if (newLayer == null) {
     51            setTurnRestrictions(null);
     52            return;
     53        }
     54        initFromSelection(newLayer.data.getSelected());
     55    }
     56   
     57    /* --------------------------------------------------------------------------- */
     58    /* interface SelectionChangedListener                                          */
     59    /* --------------------------------------------------------------------------- */   
     60    public void selectionChanged(Collection<? extends OsmPrimitive> newSelection) {
     61        initFromSelection(newSelection);
     62    }
    6363}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/list/TurnRestrictionsInSelectionView.java

    r20711 r23192  
    2424public class TurnRestrictionsInSelectionView extends AbstractTurnRestrictionsListView {
    2525
    26         protected void build() {
    27                 DefaultListSelectionModel selectionModel = new DefaultListSelectionModel();
    28                 model = new TurnRestrictionsInSelectionListModel(selectionModel);
    29                 lstTurnRestrictions = new JList(model);
    30                 lstTurnRestrictions.setSelectionModel(selectionModel);
    31                 lstTurnRestrictions.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    32                 lstTurnRestrictions.setCellRenderer(new TurnRestrictionCellRenderer());
    33                
    34                 setLayout(new BorderLayout());
    35                 add(new JScrollPane(lstTurnRestrictions), BorderLayout.CENTER);
    36         }
     26    protected void build() {
     27        DefaultListSelectionModel selectionModel = new DefaultListSelectionModel();
     28        model = new TurnRestrictionsInSelectionListModel(selectionModel);
     29        lstTurnRestrictions = new JList(model);
     30        lstTurnRestrictions.setSelectionModel(selectionModel);
     31        lstTurnRestrictions.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
     32        lstTurnRestrictions.setCellRenderer(new TurnRestrictionCellRenderer());
     33       
     34        setLayout(new BorderLayout());
     35        add(new JScrollPane(lstTurnRestrictions), BorderLayout.CENTER);
     36    }
    3737
    38         protected void registerAsListener() {
    39                 MapView.addEditLayerChangeListener((EditLayerChangeListener)model);
    40                 SelectionEventManager.getInstance().addSelectionListener((SelectionChangedListener)model, FireMode.IN_EDT_CONSOLIDATED);
    41                 TurnRestrictionsInSelectionListModel m = (TurnRestrictionsInSelectionListModel)model;
    42                 if (Main.main.getEditLayer() != null){
    43                         m.initFromSelection(Main.main.getEditLayer().data.getSelected());
    44                 } else {
    45                         m.initFromSelection(Collections.<OsmPrimitive>emptyList());
    46                 }
    47         }
     38    protected void registerAsListener() {
     39        MapView.addEditLayerChangeListener((EditLayerChangeListener)model);
     40        SelectionEventManager.getInstance().addSelectionListener((SelectionChangedListener)model, FireMode.IN_EDT_CONSOLIDATED);
     41        TurnRestrictionsInSelectionListModel m = (TurnRestrictionsInSelectionListModel)model;
     42        if (Main.main.getEditLayer() != null){
     43            m.initFromSelection(Main.main.getEditLayer().data.getSelected());
     44        } else {
     45            m.initFromSelection(Collections.<OsmPrimitive>emptyList());
     46        }
     47    }
    4848
    49         protected void unregisterAsListener() {
    50                 MapView.removeEditLayerChangeListener((EditLayerChangeListener)model);
    51                 SelectionEventManager.getInstance().removeSelectionListener((SelectionChangedListener)model);           
    52         }
     49    protected void unregisterAsListener() {
     50        MapView.removeEditLayerChangeListener((EditLayerChangeListener)model);
     51        SelectionEventManager.getInstance().removeSelectionListener((SelectionChangedListener)model);       
     52    }
    5353
    54         public TurnRestrictionsInSelectionView() {
    55                 build();
    56         }
     54    public TurnRestrictionsInSelectionView() {
     55        build();
     56    }
    5757}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/list/TurnRestrictionsListDialog.java

    r20735 r23192  
    5252 */
    5353public class TurnRestrictionsListDialog extends ToggleDialog{
    54         private static final Logger logger = Logger.getLogger(TurnRestrictionsListDialog.class.getName());
    55 
    56         /** checkbox for switching between the two list views */
    57         private JCheckBox cbInSelectionOnly;
    58         /** the view for the turn restrictions in the current data set */
    59         private TurnRestrictionsInDatasetView pnlTurnRestrictionsInDataSet;
    60         /** the view for the turn restrictions related to the current selection */
    61         private TurnRestrictionsInSelectionView pnlTurnRestrictionsInSelection;
    62        
    63         /** three actions */
    64         private NewAction actNew;
    65         private EditAction actEdit;
    66         private DeleteAction actDelete;
    67         private SelectSelectedTurnRestrictions actSelectSelectedTurnRestrictions;
    68         private ZoomToAction actZoomTo;
    69         private SwitchListViewHandler switchListViewHandler;
    70        
    71         private AbstractTurnRestrictionsListView currentListView = null;
    72        
    73         /** the main content panel in this toggle dialog */
    74         private JPanel pnlContent;
    75         private PreferenceChangeHandler preferenceChangeHandler;
    76        
    77         @Override
    78         public void showNotify() {
    79                 pnlTurnRestrictionsInDataSet.registerAsListener();             
    80                 pnlTurnRestrictionsInSelection.registerAsListener();
    81                 MapView.addEditLayerChangeListener(actNew);
    82                 actNew.updateEnabledState();
    83                 Main.pref.addPreferenceChangeListener(preferenceChangeHandler);
    84                 preferenceChangeHandler.refreshIconSet();
    85         }
    86 
    87         @Override
    88         public void hideNotify() {
    89                 pnlTurnRestrictionsInDataSet.unregisterAsListener();
    90                 pnlTurnRestrictionsInSelection.unregisterAsListener();
    91                 MapView.removeEditLayerChangeListener(actNew);
    92                 Main.pref.removePreferenceChangeListener(preferenceChangeHandler);
    93         }
    94 
    95         /**
    96         * Builds the panel with the checkbox for switching between the two
    97         * list views
    98         *
    99         * @return the panel
    100         */
    101         protected JPanel buildInSelectionOnlyTogglePanel(){
    102                 JPanel pnl = new JPanel(new FlowLayout(FlowLayout.LEFT,0,0));
    103                 pnl.setBorder(null);
    104                 pnl.add(cbInSelectionOnly = new JCheckBox(tr("Only participating in selection")));
    105                 cbInSelectionOnly.setToolTipText(tr(
    106                    "<html>Select to display turn restrictions related to object in the current selection only.<br>"
    107                 + "Deselect to display all turn restrictions in the current data set.</html>"));
    108                 return pnl;
    109         }
    110        
    111         /**
    112         * Builds the panel with the action buttons
    113         *
    114         * @return the panel
    115         */
    116         protected JPanel buildCommandPanel() {
    117                 JPanel pnl = new JPanel(new FlowLayout(FlowLayout.LEFT,0,0));
    118                 pnl.setBorder(null);
    119                 pnl.add(new SideButton(actNew = new NewAction(), false /* don't show the name */));
    120                 pnl.add(new SideButton(actEdit = new EditAction(), false /* don't show the name */));
    121                 pnl.add(new SideButton(actDelete = new DeleteAction(), false /* don't show the name */));
    122                
    123                 actSelectSelectedTurnRestrictions = new SelectSelectedTurnRestrictions();
    124                 actZoomTo = new ZoomToAction();
    125                 return pnl;
    126         }
    127        
    128         /**
    129         * Builds the UI
    130         */
    131         protected void build() {
    132                 pnlContent = new JPanel(new BorderLayout(0,0));
    133                 pnlContent.setBorder(null);
    134                 pnlContent.add(buildInSelectionOnlyTogglePanel(),  BorderLayout.NORTH);
    135                 pnlContent.add(buildCommandPanel(), BorderLayout.SOUTH);
    136                
    137                 add(pnlContent, BorderLayout.CENTER);
    138                
    139                 // create the two list views
    140                 pnlTurnRestrictionsInDataSet = new TurnRestrictionsInDatasetView();
    141                 pnlTurnRestrictionsInSelection = new TurnRestrictionsInSelectionView();
    142                
    143                 // wire the handler for switching between list views
    144                 switchListViewHandler = new SwitchListViewHandler();
    145                 switchListViewHandler.activateListView(pnlTurnRestrictionsInDataSet);
    146                 cbInSelectionOnly.addItemListener(switchListViewHandler);
    147                
    148                 // wire the popup menu launcher to the two turn restriction lists 
    149                 TurnRestrictionsPopupLauncher launcher = new TurnRestrictionsPopupLauncher();
    150                 pnlTurnRestrictionsInDataSet.getList().addMouseListener(launcher);
    151                 pnlTurnRestrictionsInSelection.getList().addMouseListener(launcher);
    152                
    153                 preferenceChangeHandler = new PreferenceChangeHandler();
    154                
    155         }
    156        
    157         /**
    158         * Constructor
    159         */
    160         public TurnRestrictionsListDialog() {
    161                 super(
    162                                 tr("Turn Restrictions"),
    163                                 "turnrestrictions",
    164                                 tr("Display and manage turn restrictions in the current data set"),
    165                                 null, // no shortcut
    166                                 150   // default height
    167                 );
    168                 build();
    169                 HelpUtil.setHelpContext(this, HelpUtil.ht("/Plugins/turnrestrictions#TurnRestrictionToggleDialog"));
    170         }       
    171        
    172         /**
    173         * Switches between the two list view.
    174         */
    175         class SwitchListViewHandler implements ItemListener {
    176                 public void activateListView(AbstractTurnRestrictionsListView view) {
    177                         if (currentListView != null) {
    178                                 currentListView.removeListSelectionListener(actEdit);
    179                                 currentListView.removeListSelectionListener(actDelete);
    180                                 currentListView.removeListSelectionListener(actSelectSelectedTurnRestrictions);
    181                                 currentListView.removeListSelectionListener(actZoomTo);
    182                                 pnlContent.remove(currentListView);
    183                         }
    184                         pnlContent.add(view,BorderLayout.CENTER);
    185                         currentListView = view;                                         
    186                         view.addListSelectionListener(actEdit);
    187                         view.addListSelectionListener(actDelete);
    188                         view.addListSelectionListener(actSelectSelectedTurnRestrictions);
    189                         view.addListSelectionListener(actZoomTo);
    190                         actEdit.updateEnabledState();
    191                         actDelete.updateEnabledState();
    192                         actSelectSelectedTurnRestrictions.updateEnabledState();
    193                         actZoomTo.updateEnabledState();
    194                         currentListView.revalidate();
    195                         currentListView.repaint();                     
    196                 }
    197 
    198                 public void itemStateChanged(ItemEvent e) {
    199                         switch(e.getStateChange()) {
    200                         case ItemEvent.SELECTED:
    201                                 activateListView(pnlTurnRestrictionsInSelection);
    202                                 break;
    203                                
    204                         case ItemEvent.DESELECTED:             
    205                                 activateListView(pnlTurnRestrictionsInDataSet);
    206                                 break;
    207                         }
    208                 }
    209         }
    210        
    211         /**
     54    private static final Logger logger = Logger.getLogger(TurnRestrictionsListDialog.class.getName());
     55
     56    /** checkbox for switching between the two list views */
     57    private JCheckBox cbInSelectionOnly;
     58    /** the view for the turn restrictions in the current data set */
     59    private TurnRestrictionsInDatasetView pnlTurnRestrictionsInDataSet;
     60    /** the view for the turn restrictions related to the current selection */
     61    private TurnRestrictionsInSelectionView pnlTurnRestrictionsInSelection;
     62   
     63    /** three actions */
     64    private NewAction actNew;
     65    private EditAction actEdit;
     66    private DeleteAction actDelete;
     67    private SelectSelectedTurnRestrictions actSelectSelectedTurnRestrictions;
     68    private ZoomToAction actZoomTo;
     69    private SwitchListViewHandler switchListViewHandler;
     70   
     71    private AbstractTurnRestrictionsListView currentListView = null;
     72   
     73    /** the main content panel in this toggle dialog */
     74    private JPanel pnlContent;
     75    private PreferenceChangeHandler preferenceChangeHandler;
     76   
     77    @Override
     78    public void showNotify() {
     79        pnlTurnRestrictionsInDataSet.registerAsListener();     
     80        pnlTurnRestrictionsInSelection.registerAsListener();
     81        MapView.addEditLayerChangeListener(actNew);
     82        actNew.updateEnabledState();
     83        Main.pref.addPreferenceChangeListener(preferenceChangeHandler);
     84        preferenceChangeHandler.refreshIconSet();
     85    }
     86
     87    @Override
     88    public void hideNotify() {
     89        pnlTurnRestrictionsInDataSet.unregisterAsListener();
     90        pnlTurnRestrictionsInSelection.unregisterAsListener();
     91        MapView.removeEditLayerChangeListener(actNew);
     92        Main.pref.removePreferenceChangeListener(preferenceChangeHandler);
     93    }
     94
     95    /**
     96    * Builds the panel with the checkbox for switching between the two
     97    * list views
     98    *
     99    * @return the panel
     100    */
     101    protected JPanel buildInSelectionOnlyTogglePanel(){
     102        JPanel pnl = new JPanel(new FlowLayout(FlowLayout.LEFT,0,0));
     103        pnl.setBorder(null);
     104        pnl.add(cbInSelectionOnly = new JCheckBox(tr("Only participating in selection")));
     105        cbInSelectionOnly.setToolTipText(tr(
     106           "<html>Select to display turn restrictions related to object in the current selection only.<br>"
     107        + "Deselect to display all turn restrictions in the current data set.</html>"));
     108        return pnl;
     109    }
     110   
     111    /**
     112    * Builds the panel with the action buttons
     113    *
     114    * @return the panel
     115    */
     116    protected JPanel buildCommandPanel() {
     117        JPanel pnl = new JPanel(new FlowLayout(FlowLayout.LEFT,0,0));
     118        pnl.setBorder(null);
     119        pnl.add(new SideButton(actNew = new NewAction(), false /* don't show the name */));
     120        pnl.add(new SideButton(actEdit = new EditAction(), false /* don't show the name */));
     121        pnl.add(new SideButton(actDelete = new DeleteAction(), false /* don't show the name */));
     122       
     123        actSelectSelectedTurnRestrictions = new SelectSelectedTurnRestrictions();
     124        actZoomTo = new ZoomToAction();
     125        return pnl;
     126    }
     127   
     128    /**
     129    * Builds the UI
     130    */
     131    protected void build() {
     132        pnlContent = new JPanel(new BorderLayout(0,0));
     133        pnlContent.setBorder(null);
     134        pnlContent.add(buildInSelectionOnlyTogglePanel(),  BorderLayout.NORTH);
     135        pnlContent.add(buildCommandPanel(), BorderLayout.SOUTH);
     136       
     137        add(pnlContent, BorderLayout.CENTER);
     138       
     139        // create the two list views
     140        pnlTurnRestrictionsInDataSet = new TurnRestrictionsInDatasetView();
     141        pnlTurnRestrictionsInSelection = new TurnRestrictionsInSelectionView();
     142       
     143        // wire the handler for switching between list views
     144        switchListViewHandler = new SwitchListViewHandler();
     145        switchListViewHandler.activateListView(pnlTurnRestrictionsInDataSet);
     146        cbInSelectionOnly.addItemListener(switchListViewHandler);
     147       
     148        // wire the popup menu launcher to the two turn restriction lists 
     149        TurnRestrictionsPopupLauncher launcher = new TurnRestrictionsPopupLauncher();
     150        pnlTurnRestrictionsInDataSet.getList().addMouseListener(launcher);
     151        pnlTurnRestrictionsInSelection.getList().addMouseListener(launcher);
     152       
     153        preferenceChangeHandler = new PreferenceChangeHandler();
     154       
     155    }
     156   
     157    /**
     158    * Constructor
     159    */
     160    public TurnRestrictionsListDialog() {
     161        super(
     162                tr("Turn Restrictions"),
     163                "turnrestrictions",
     164                tr("Display and manage turn restrictions in the current data set"),
     165                null, // no shortcut
     166                150   // default height
     167        );
     168        build();
     169        HelpUtil.setHelpContext(this, HelpUtil.ht("/Plugins/turnrestrictions#TurnRestrictionToggleDialog"));
     170    }   
     171   
     172    /**
     173    * Switches between the two list view.
     174    */
     175    class SwitchListViewHandler implements ItemListener {
     176        public void activateListView(AbstractTurnRestrictionsListView view) {
     177            if (currentListView != null) {
     178                currentListView.removeListSelectionListener(actEdit);
     179                currentListView.removeListSelectionListener(actDelete);
     180                currentListView.removeListSelectionListener(actSelectSelectedTurnRestrictions);
     181                currentListView.removeListSelectionListener(actZoomTo);
     182                pnlContent.remove(currentListView);
     183            }
     184            pnlContent.add(view,BorderLayout.CENTER);
     185            currentListView = view;                     
     186            view.addListSelectionListener(actEdit);
     187            view.addListSelectionListener(actDelete);
     188            view.addListSelectionListener(actSelectSelectedTurnRestrictions);
     189            view.addListSelectionListener(actZoomTo);
     190            actEdit.updateEnabledState();
     191            actDelete.updateEnabledState();
     192            actSelectSelectedTurnRestrictions.updateEnabledState();
     193            actZoomTo.updateEnabledState();
     194            currentListView.revalidate();
     195            currentListView.repaint();         
     196        }
     197
     198        public void itemStateChanged(ItemEvent e) {
     199            switch(e.getStateChange()) {
     200            case ItemEvent.SELECTED:
     201                activateListView(pnlTurnRestrictionsInSelection);
     202                break;
     203               
     204            case ItemEvent.DESELECTED:     
     205                activateListView(pnlTurnRestrictionsInDataSet);
     206                break;
     207            }
     208        }
     209    }
     210   
     211    /**
    212212     * The edit action
    213213     *
     
    231231        }
    232232
    233                 public void launchEditor(Relation toEdit) {
    234                         if (toEdit == null)
    235                                 return;
    236                         OsmDataLayer layer = Main.main.getEditLayer();
    237                         TurnRestrictionEditorManager manager = TurnRestrictionEditorManager.getInstance();
    238                         TurnRestrictionEditor editor = manager.getEditorForRelation(layer, toEdit);
    239                         if (editor != null) {
    240                                 editor.setVisible(true);
    241                                 editor.toFront();
    242                         } else {
    243                                 editor = new TurnRestrictionEditor(
    244                                                 TurnRestrictionsListDialog.this, layer,toEdit);
    245                                 manager.positionOnScreen(editor);
    246                                 manager.register(layer, toEdit,editor);
    247                                 editor.setVisible(true);
    248                         }
    249                 }
     233        public void launchEditor(Relation toEdit) {
     234            if (toEdit == null)
     235                return;
     236            OsmDataLayer layer = Main.main.getEditLayer();
     237            TurnRestrictionEditorManager manager = TurnRestrictionEditorManager.getInstance();
     238            TurnRestrictionEditor editor = manager.getEditorForRelation(layer, toEdit);
     239            if (editor != null) {
     240                editor.setVisible(true);
     241                editor.toFront();
     242            } else {
     243                editor = new TurnRestrictionEditor(
     244                        TurnRestrictionsListDialog.this, layer,toEdit);
     245                manager.positionOnScreen(editor);
     246                manager.register(layer, toEdit,editor);
     247                editor.setVisible(true);
     248            }
     249        }
    250250
    251251        public void actionPerformed(ActionEvent e) {
     
    258258
    259259        public void updateEnabledState() {
    260                 setEnabled(currentListView!= null && currentListView.getModel().getSelectedTurnRestrictions().size() == 1);
     260            setEnabled(currentListView!= null && currentListView.getModel().getSelectedTurnRestrictions().size() == 1);
    261261        }
    262262       
     
    298298       
    299299        public void updateEnabledState() {
    300                 setEnabled(currentListView != null && !currentListView.getModel().getSelectedTurnRestrictions().isEmpty());
     300            setEnabled(currentListView != null && !currentListView.getModel().getSelectedTurnRestrictions().isEmpty());
    301301        }
    302302
    303303        public void valueChanged(ListSelectionEvent e) {
    304                 updateEnabledState();
     304            updateEnabledState();
    305305        }
    306306    }
     
    319319
    320320        public void run() {
    321                 OsmDataLayer layer =  Main.main.getEditLayer();
    322                 if (layer == null) return;
    323                 Relation tr = new TurnRestrictionBuilder().buildFromSelection(layer);
    324                 TurnRestrictionEditor editor = new TurnRestrictionEditor(TurnRestrictionsListDialog.this, layer, tr);
     321            OsmDataLayer layer =  Main.main.getEditLayer();
     322            if (layer == null) return;
     323            Relation tr = new TurnRestrictionBuilder().buildFromSelection(layer);
     324            TurnRestrictionEditor editor = new TurnRestrictionEditor(TurnRestrictionsListDialog.this, layer, tr);
    325325             TurnRestrictionEditorManager.getInstance().positionOnScreen(editor);             
    326326             TurnRestrictionEditorManager.getInstance().register(layer, tr, editor);
     
    336336        }
    337337
    338                 public void editLayerChanged(OsmDataLayer oldLayer,
    339                                 OsmDataLayer newLayer) {
    340             updateEnabledState();
    341                 }
     338        public void editLayerChanged(OsmDataLayer oldLayer,
     339                OsmDataLayer newLayer) {
     340            updateEnabledState();
     341        }
    342342    }
    343343   
     
    367367       
    368368        public void updateEnabledState() {
    369                 setEnabled(currentListView != null && !currentListView.getModel().getSelectedTurnRestrictions().isEmpty());
     369            setEnabled(currentListView != null && !currentListView.getModel().getSelectedTurnRestrictions().isEmpty());
    370370        }
    371371
    372372        public void valueChanged(ListSelectionEvent e) {
    373                 updateEnabledState();
     373            updateEnabledState();
    374374        }
    375375    }
     
    401401       
    402402        public void updateEnabledState() {
    403                 setEnabled(currentListView != null && !currentListView.getModel().getSelectedTurnRestrictions().isEmpty());
     403            setEnabled(currentListView != null && !currentListView.getModel().getSelectedTurnRestrictions().isEmpty());
    404404        }
    405405
    406406        public void valueChanged(ListSelectionEvent e) {
    407                 updateEnabledState();
     407            updateEnabledState();
    408408        }
    409409    }
     
    448448     *
    449449     */
    450     class PreferenceChangeHandler implements PreferenceChangedListener {       
    451         public void refreshIconSet() {
    452                 pnlTurnRestrictionsInDataSet.initIconSetFromPreferences(Main.pref);
    453                         pnlTurnRestrictionsInSelection.initIconSetFromPreferences(Main.pref);
    454                         repaint();
    455         }
    456        
    457                 public void preferenceChanged(PreferenceChangeEvent evt) {                     
    458                         if (!evt.getKey().equals(PreferenceKeys.ROAD_SIGNS)) return;
    459                         refreshIconSet();
    460                 }
     450    class PreferenceChangeHandler implements PreferenceChangedListener {       
     451        public void refreshIconSet() {
     452            pnlTurnRestrictionsInDataSet.initIconSetFromPreferences(Main.pref);
     453            pnlTurnRestrictionsInSelection.initIconSetFromPreferences(Main.pref);
     454            repaint();
     455        }
     456       
     457        public void preferenceChanged(PreferenceChangeEvent evt) {         
     458            if (!evt.getKey().equals(PreferenceKeys.ROAD_SIGNS)) return;
     459            refreshIconSet();
     460        }
    461461    }
    462462}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/list/TurnRestrictionsListModel.java

    r20489 r23192  
    7373     */
    7474    protected boolean isTurnRestriction(OsmPrimitive primitive) {
    75         if (primitive == null) return false;
    76         if (! (primitive instanceof Relation)) return false;
    77         String type = primitive.get("type");
    78         if (type == null || ! type.equals("restriction")) return false;
    79         return true;
     75        if (primitive == null) return false;
     76        if (! (primitive instanceof Relation)) return false;
     77        String type = primitive.get("type");
     78        if (type == null || ! type.equals("restriction")) return false;
     79        return true;
    8080    }
    8181   
     
    122122                continue;
    123123            }
    124                         turnrestrictions.add(r);
    125                         added = true;
     124            turnrestrictions.add(r);
     125            added = true;
    126126        }
    127127        if (added) {
     
    143143        Set<Relation> removedTurnRestrictions = new HashSet<Relation>();
    144144        for (OsmPrimitive p: removedPrimitives) {
    145                 if (!isTurnRestriction(p)) continue;
     145            if (!isTurnRestriction(p)) continue;
    146146            removedTurnRestrictions.add((Relation)p);
    147147        }
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/preferences/PreferenceEditor.java

    r20675 r23192  
    3131 */
    3232public class PreferenceEditor extends JPanel implements PreferenceSetting{
    33        
    34         private PreferencesPanel pnlIconPreferences;
     33   
     34    private PreferencesPanel pnlIconPreferences;
    3535
    36         /**
    37         * builds the panel with the sponsoring information
    38         *
    39         * @return
    40         */
    41         protected JPanel buildCreditPanel() {
    42                 JPanel pnl = new JPanel(new GridBagLayout());
    43                 pnl.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
    44                 GridBagConstraints gc = new GridBagConstraints();
    45                 gc.anchor = GridBagConstraints.NORTHWEST;
    46                 gc.fill = GridBagConstraints.HORIZONTAL;
    47                 gc.insets = new Insets(0, 0,0, 5);
    48                 gc.weightx = 0.0;
    49                 JLabel lbl = new JLabel();
    50                 pnl.add(lbl, gc);
    51                 lbl.setIcon(ImageProvider.get("skobbler-logo"));
    52                
    53                 gc.gridx = 1;
    54                 gc.weightx = 1.0;
    55                 HtmlPanel msg  =new HtmlPanel();
    56                 msg.setText("<html><body>"
    57                                 + tr("Development of the turn restriction plugin was sponsored "
    58                                 + "by <a href=\"http://www.skobbler.de\">skobbler GmbH</a>.")
    59                                 +"</body></html>");
    60                 pnl.add(msg, gc);
    61                
    62                 // filler - grab remaining space
    63                 gc.gridy = 1;
    64                 gc.gridx = 0;
    65                 gc.gridwidth = 2;
    66                 gc.weightx = 1.0;
    67                 gc.weighty = 1.0;
    68                 pnl.add(new JPanel(), gc);
    69                
    70                 SkobblerUrlLauncher urlLauncher = new SkobblerUrlLauncher();
    71                 msg.getEditorPane().addHyperlinkListener(urlLauncher);
    72                 lbl.addMouseListener(urlLauncher);
    73                 return pnl;
    74         }
     36    /**
     37    * builds the panel with the sponsoring information
     38    *
     39    * @return
     40    */
     41    protected JPanel buildCreditPanel() {
     42        JPanel pnl = new JPanel(new GridBagLayout());
     43        pnl.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
     44        GridBagConstraints gc = new GridBagConstraints();
     45        gc.anchor = GridBagConstraints.NORTHWEST;
     46        gc.fill = GridBagConstraints.HORIZONTAL;
     47        gc.insets = new Insets(0, 0,0, 5);
     48        gc.weightx = 0.0;
     49        JLabel lbl = new JLabel();
     50        pnl.add(lbl, gc);
     51        lbl.setIcon(ImageProvider.get("skobbler-logo"));
     52       
     53        gc.gridx = 1;
     54        gc.weightx = 1.0;
     55        HtmlPanel msg  =new HtmlPanel();
     56        msg.setText("<html><body>"
     57                + tr("Development of the turn restriction plugin was sponsored "
     58                + "by <a href=\"http://www.skobbler.de\">skobbler GmbH</a>.")
     59                +"</body></html>");
     60        pnl.add(msg, gc);
     61       
     62        // filler - grab remaining space
     63        gc.gridy = 1;
     64        gc.gridx = 0;
     65        gc.gridwidth = 2;
     66        gc.weightx = 1.0;
     67        gc.weighty = 1.0;
     68        pnl.add(new JPanel(), gc);
     69       
     70        SkobblerUrlLauncher urlLauncher = new SkobblerUrlLauncher();
     71        msg.getEditorPane().addHyperlinkListener(urlLauncher);
     72        lbl.addMouseListener(urlLauncher);
     73        return pnl;
     74    }
    7575
    76         protected JPanel buildIconPreferencePanel() {
    77                 JPanel pnl = new JPanel(new BorderLayout());
    78                
    79                 pnlIconPreferences = new PreferencesPanel();
    80                 pnlIconPreferences.initFromPreferences(Main.pref);
    81                
    82                 JScrollPane sp = new JScrollPane(pnlIconPreferences);
    83                 sp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    84                 sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
    85                
    86                 pnl.add(sp, BorderLayout.CENTER);
    87                 return pnl;
    88         }
    89        
    90         protected void build() {
    91                 setLayout(new BorderLayout());
    92                 JTabbedPane tp = new JTabbedPane();
    93                 tp.add(buildIconPreferencePanel());
    94                 tp.add(buildCreditPanel());             
    95                 tp.setTitleAt(0, tr("Preferences"));
    96                 tp.setToolTipTextAt(0,tr("Configure the preferences for the turnrestrictions plugin"));
    97                 tp.setTitleAt(1, tr("Sponsor"));
    98                 add(tp, BorderLayout.CENTER);
    99         }
    100        
    101         public PreferenceEditor() {
    102                 build();
    103         }
    104        
    105         public void addGui(PreferenceTabbedPane gui) {
    106                 String description = tr("An OSM plugin for editing turn restrictions.");
    107                 JPanel tab = gui.createPreferenceTab("turnrestrictions", tr("Turn Restrictions"), description);
     76    protected JPanel buildIconPreferencePanel() {
     77        JPanel pnl = new JPanel(new BorderLayout());
     78       
     79        pnlIconPreferences = new PreferencesPanel();
     80        pnlIconPreferences.initFromPreferences(Main.pref);
     81       
     82        JScrollPane sp = new JScrollPane(pnlIconPreferences);
     83        sp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
     84        sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
     85       
     86        pnl.add(sp, BorderLayout.CENTER);
     87        return pnl;
     88    }
     89   
     90    protected void build() {
     91        setLayout(new BorderLayout());
     92        JTabbedPane tp = new JTabbedPane();
     93        tp.add(buildIconPreferencePanel());
     94        tp.add(buildCreditPanel());     
     95        tp.setTitleAt(0, tr("Preferences"));
     96        tp.setToolTipTextAt(0,tr("Configure the preferences for the turnrestrictions plugin"));
     97        tp.setTitleAt(1, tr("Sponsor"));
     98        add(tp, BorderLayout.CENTER);
     99    }
     100   
     101    public PreferenceEditor() {
     102        build();
     103    }
     104   
     105    public void addGui(PreferenceTabbedPane gui) {
     106        String description = tr("An OSM plugin for editing turn restrictions.");
     107        JPanel tab = gui.createPreferenceTab("turnrestrictions", tr("Turn Restrictions"), description);
    108108        tab.add(this, GBC.eol().fill(GBC.BOTH));
    109         }
     109    }
    110110
    111         public boolean ok() {
    112                 pnlIconPreferences.saveToPreferences(Main.pref);
    113                 return false;
    114         }
    115        
    116         /**
    117         * Launches an external browser with the sponsors home page
    118         */
    119         class SkobblerUrlLauncher extends MouseAdapter implements HyperlinkListener {
    120                 protected void launchBrowser() {
    121                         OpenBrowser.displayUrl("http://www.skobbler.de");
    122                 }
    123                
    124                 public void hyperlinkUpdate(HyperlinkEvent e) {
    125                         if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) {
    126                                 launchBrowser();
    127                         }
    128                 }
     111    public boolean ok() {
     112        pnlIconPreferences.saveToPreferences(Main.pref);
     113        return false;
     114    }
     115   
     116    /**
     117    * Launches an external browser with the sponsors home page
     118    */
     119    class SkobblerUrlLauncher extends MouseAdapter implements HyperlinkListener {
     120        protected void launchBrowser() {
     121            OpenBrowser.displayUrl("http://www.skobbler.de");
     122        }
     123       
     124        public void hyperlinkUpdate(HyperlinkEvent e) {
     125            if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) {
     126                launchBrowser();
     127            }
     128        }
    129129
    130                 @Override
    131                 public void mouseClicked(MouseEvent e) {
    132                         launchBrowser();
    133                 }
    134         }
     130        @Override
     131        public void mouseClicked(MouseEvent e) {
     132            launchBrowser();
     133        }
     134    }
    135135}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/preferences/PreferenceKeys.java

    r20701 r23192  
    99 */
    1010public interface PreferenceKeys {
    11         /**
    12         * Indicates which of two sets of road sign icons to use. Supported
    13         * values are:
    14         * <ul>
    15         *   <li><tt>set-a</tt> - the set of icons in the directory <tt>/images/types/set-a</tt></li>
    16         *   <li><tt>set-b</tt> - the set of icons in the directory <tt>/images/types/set-b</tt></li>
    17         * </ul>
    18         *
    19         */
    20         String ROAD_SIGNS = "turnrestrictions.road-signs";
    21        
    22         /**
    23         * Indicates whether the Basic Editor should include a widget for for displaying
    24         * and editing the via-objects of a turn restriction.
    25         *
    26         * Supported values are:
    27         * <ul>
    28         *   <li><tt>true</tt> - display the list of vias in the basic editor </li>
    29         *    <li><tt>false</tt> - don't display the list of vias in the basic editor </li>
    30         * </ul>
    31         */
    32         String SHOW_VIAS_IN_BASIC_EDITOR = "turnrestrictions.show-vias-in-basic-editor";
    33        
    34         /**
    35         * The shortcut which triggers creating a new or editing and existing turn
    36         * restriction. The value must be parseable by {@see KeyStroke#getKeyStroke(String)}.
    37         * If missing, the default value "ctrl shift T" is assumed.
    38         */
    39         String EDIT_SHORTCUT= "turnrestrictions.edit-shortcut";
     11    /**
     12    * Indicates which of two sets of road sign icons to use. Supported
     13    * values are:
     14    * <ul>
     15    *   <li><tt>set-a</tt> - the set of icons in the directory <tt>/images/types/set-a</tt></li>
     16    *   <li><tt>set-b</tt> - the set of icons in the directory <tt>/images/types/set-b</tt></li>
     17    * </ul>
     18    *
     19    */
     20    String ROAD_SIGNS = "turnrestrictions.road-signs";
     21   
     22    /**
     23    * Indicates whether the Basic Editor should include a widget for for displaying
     24    * and editing the via-objects of a turn restriction.
     25    *
     26    * Supported values are:
     27    * <ul>
     28    *   <li><tt>true</tt> - display the list of vias in the basic editor </li>
     29    *    <li><tt>false</tt> - don't display the list of vias in the basic editor </li>
     30    * </ul>
     31    */
     32    String SHOW_VIAS_IN_BASIC_EDITOR = "turnrestrictions.show-vias-in-basic-editor";
     33   
     34    /**
     35    * The shortcut which triggers creating a new or editing and existing turn
     36    * restriction. The value must be parseable by {@see KeyStroke#getKeyStroke(String)}.
     37    * If missing, the default value "ctrl shift T" is assumed.
     38    */
     39    String EDIT_SHORTCUT= "turnrestrictions.edit-shortcut";
    4040}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/preferences/PreferencesPanel.java

    r20701 r23192  
    3030 */
    3131public class PreferencesPanel extends VerticallyScrollablePanel {
    32         private static final Logger logger = Logger.getLogger(PreferencesPanel.class.getName());
    33         private JRadioButton rbSetA;
    34         private JRadioButton rbSetB;
    35         private ButtonGroup bgIconSet;
    36         private JCheckBox cbShowViaListInBasicEditor;
    37         private ShortcutPreferencePanel pnlShortcutPreference;
    38        
    39         protected JPanel buildShowViaListInBasicEditorPanel() {
    40                 JPanel pnl = new JPanel(new GridBagLayout());
    41                 GridBagConstraints gc = new GridBagConstraints();
    42                 gc.anchor = GridBagConstraints.NORTHWEST;
    43                 gc.fill = GridBagConstraints.HORIZONTAL;
    44                 gc.weightx = 1.0;
    45                 gc.gridx = 0;
    46                 gc.gridy = 0;
    47                
    48                 HtmlPanel msg = new HtmlPanel();
    49                 msg.setText("<html><body>"
    50                                 + tr("The Basic Editor can optionally display the list of via-objects "
    51                                         + "of a turn restriction. If enabled, one can edit them "
    52                                         + "in the Basic editor too. If disabled, editing of via-objects is "
    53                                         + "possible in the Advanced Editor only."
    54                                   )
    55                                 + "</body></html>"
    56             );
    57                 pnl.add(msg, gc);
    58                
    59                 gc.gridy++;
    60                 pnl.add(cbShowViaListInBasicEditor = new JCheckBox(tr("Display and edit list of via-objects in the Basic Editor")), gc);
    61                 return pnl;
    62         }
    63        
    64         /**
    65         * Builds the panel for the icon set "set-a"
    66         *
    67         * @return
    68         */
    69         protected JPanel buildSetAPanel() {
    70                 JPanel pnl = new JPanel(new GridBagLayout());;
    71                 GridBagConstraints gc = new GridBagConstraints();
    72                 gc.anchor = GridBagConstraints.NORTHWEST;
    73                 gc.fill = GridBagConstraints.HORIZONTAL;
    74                 gc.weightx = 1.0;
    75                 gc.gridx = 0;
    76                 gc.gridy = 0;
    77                
    78                 pnl.add(rbSetA = new JRadioButton(tr("Road signs - Set A")),gc);
    79                
    80                 JPanel icons = new JPanel(new FlowLayout(FlowLayout.LEFT));
    81                 for (TurnRestrictionType type: TurnRestrictionType.values()){
    82                         JLabel lbl = new JLabel();
    83                         icons.add(lbl);
    84                         lbl.setIcon(ImageProvider.get("types/set-a",type.getTagValue()));
    85                 }
    86                
    87                 gc.gridy = 1;
    88                 gc.insets = new Insets(0,20,0,0);
    89                 pnl.add(icons, gc);
    90                 return pnl;             
    91         }
    92        
    93         /**
    94         * Builds the panel for the icon set "set-b"
    95         *
    96         * @return
    97         */
    98         protected JPanel buildSetBPanel() {
    99                 JPanel pnl = new JPanel(new GridBagLayout());;
    100                 GridBagConstraints gc = new GridBagConstraints();
    101                 gc.anchor = GridBagConstraints.NORTHWEST;
    102                 gc.fill = GridBagConstraints.HORIZONTAL;
    103                 gc.weightx = 1.0;
    104                 gc.gridx = 0;
    105                 gc.gridy = 0;
    106                
    107                 pnl.add(rbSetB = new JRadioButton(tr("Road signs - Set B")),gc);
    108                
    109                 JPanel icons = new JPanel(new FlowLayout(FlowLayout.LEFT));
    110                 for (TurnRestrictionType type: TurnRestrictionType.values()){
    111                         JLabel lbl = new JLabel();
    112                         icons.add(lbl);
    113                         lbl.setIcon(ImageProvider.get("types/set-b",type.getTagValue()));
    114                 }
    115                
    116                 gc.gridy = 1;
    117                 gc.insets = new Insets(0,20,0,0);
    118                 pnl.add(icons, gc);
    119                 return pnl;             
    120         }
    121        
    122         /**
    123         * Builds the message panel at the top
    124         *
    125         * @return
    126         */
    127         protected JPanel buildMessagePanel() {
    128                 HtmlPanel pnl = new HtmlPanel();
    129                 pnl.setText(
    130                                 "<html><body>"
    131                           + tr("Please select the set of road sign icons to be used in the plugin.")
    132                           + "</body></html>"
    133                 );
    134                 return pnl;
    135         }
    136        
    137         /**
    138         * Builds the UI
    139         *
    140         * @return
    141         */
    142         protected void build() {                       
    143                 setLayout(new GridBagLayout());
    144                 GridBagConstraints gc = new GridBagConstraints();
    145                 gc.anchor = GridBagConstraints.NORTHWEST;
    146                 gc.fill = GridBagConstraints.HORIZONTAL;
    147                 gc.weightx = 1.0;
    148                 gc.gridx = 0;
    149                 gc.gridy = 0;
    150                
    151                 add(buildMessagePanel(), gc);
    152                 gc.gridy++;
    153                 add(buildSetAPanel(), gc);
    154                 gc.gridy++;
    155                 add(buildSetBPanel(), gc);
    156                 gc.gridy++;
    157                 add(new JSeparator(), gc);             
    158                 gc.gridy++;
    159                 add(buildShowViaListInBasicEditorPanel(), gc);
    160                 gc.gridy++;
    161                 add(new JSeparator(), gc);
    162                 gc.gridy++;
    163                 add(pnlShortcutPreference = new ShortcutPreferencePanel(), gc);
    164                
    165                 // filler - just grab remaining space
    166                 gc.gridy++;
    167                 gc.fill = GridBagConstraints.BOTH;
    168                 gc.weighty = 1.0;
    169                 add(new JPanel(), gc);         
    170                
    171                 bgIconSet = new ButtonGroup();
    172                 bgIconSet.add(rbSetA);
    173                 bgIconSet.add(rbSetB);
    174                
    175                 setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
    176         }
    177        
    178         /**
    179         * Initializes the UI from the current settings in the JOSM preferences
    180         * {@code prefs}
    181         *
    182         * @param prefs the preferences
    183         */
    184         public void initFromPreferences(Preferences prefs){
    185                 String set = prefs.get(PreferenceKeys.ROAD_SIGNS, "set-a");
    186                 set = set.trim().toLowerCase();
    187                 if (! set.equals("set-a") && ! set.equals("set-b")) {
    188                         System.out.println(tr("Warning: the preference with key ''{0}'' has an unsupported value ''{1}''. Assuming the default value ''set-a''.", PreferenceKeys.ROAD_SIGNS, set));
    189                         set = "set-a";
    190                 }
    191                 if (set.equals("set-a")){
    192                         rbSetA.setSelected(true);
    193                 } else {
    194                         rbSetB.setSelected(true);
    195                 }
    196                
    197                 boolean b = prefs.getBoolean(PreferenceKeys.SHOW_VIAS_IN_BASIC_EDITOR, false);
    198                 cbShowViaListInBasicEditor.setSelected(b);
    199                
    200                 pnlShortcutPreference.initFromPreferences(prefs);
    201         }
    202        
    203         /**
    204         * Saves the current settings to the JOSM preferences {@code prefs}.
    205         *
    206         * @param prefs the preferences
    207         */
    208         public void saveToPreferences(Preferences prefs){
    209                 String set = null;
    210                 if (rbSetA.isSelected()){
    211                         set = "set-a";
    212                 } else {
    213                         set = "set-b";
    214                 }
    215                 String oldSet = prefs.get(PreferenceKeys.ROAD_SIGNS, "set-a");         
    216                 if (!set.equals(oldSet)){
    217                         prefs.put(PreferenceKeys.ROAD_SIGNS, set);
    218                 }
    219                
    220                 boolean newValue = cbShowViaListInBasicEditor.isSelected();
    221                 boolean oldValue = prefs.getBoolean(PreferenceKeys.SHOW_VIAS_IN_BASIC_EDITOR, false);
    222                 if (newValue != oldValue){
    223                         prefs.put(PreferenceKeys.SHOW_VIAS_IN_BASIC_EDITOR, newValue);
    224                 }               
    225                
    226                 pnlShortcutPreference.saveToPreferences(prefs);
    227         }
    228        
    229         public PreferencesPanel() {
    230                 build();
    231         }       
     32    private static final Logger logger = Logger.getLogger(PreferencesPanel.class.getName());
     33    private JRadioButton rbSetA;
     34    private JRadioButton rbSetB;
     35    private ButtonGroup bgIconSet;
     36    private JCheckBox cbShowViaListInBasicEditor;
     37    private ShortcutPreferencePanel pnlShortcutPreference;
     38   
     39    protected JPanel buildShowViaListInBasicEditorPanel() {
     40        JPanel pnl = new JPanel(new GridBagLayout());
     41        GridBagConstraints gc = new GridBagConstraints();
     42        gc.anchor = GridBagConstraints.NORTHWEST;
     43        gc.fill = GridBagConstraints.HORIZONTAL;
     44        gc.weightx = 1.0;
     45        gc.gridx = 0;
     46        gc.gridy = 0;
     47       
     48        HtmlPanel msg = new HtmlPanel();
     49        msg.setText("<html><body>"
     50                + tr("The Basic Editor can optionally display the list of via-objects "
     51                    + "of a turn restriction. If enabled, one can edit them "
     52                    + "in the Basic editor too. If disabled, editing of via-objects is "
     53                    + "possible in the Advanced Editor only."
     54                  )
     55                + "</body></html>"
     56        );
     57        pnl.add(msg, gc);
     58       
     59        gc.gridy++;
     60        pnl.add(cbShowViaListInBasicEditor = new JCheckBox(tr("Display and edit list of via-objects in the Basic Editor")), gc);
     61        return pnl;
     62    }
     63   
     64    /**
     65    * Builds the panel for the icon set "set-a"
     66    *
     67    * @return
     68    */
     69    protected JPanel buildSetAPanel() {
     70        JPanel pnl = new JPanel(new GridBagLayout());;
     71        GridBagConstraints gc = new GridBagConstraints();
     72        gc.anchor = GridBagConstraints.NORTHWEST;
     73        gc.fill = GridBagConstraints.HORIZONTAL;
     74        gc.weightx = 1.0;
     75        gc.gridx = 0;
     76        gc.gridy = 0;
     77       
     78        pnl.add(rbSetA = new JRadioButton(tr("Road signs - Set A")),gc);
     79       
     80        JPanel icons = new JPanel(new FlowLayout(FlowLayout.LEFT));
     81        for (TurnRestrictionType type: TurnRestrictionType.values()){
     82            JLabel lbl = new JLabel();
     83            icons.add(lbl);
     84            lbl.setIcon(ImageProvider.get("types/set-a",type.getTagValue()));
     85        }
     86       
     87        gc.gridy = 1;
     88        gc.insets = new Insets(0,20,0,0);
     89        pnl.add(icons, gc);
     90        return pnl;     
     91    }
     92   
     93    /**
     94    * Builds the panel for the icon set "set-b"
     95    *
     96    * @return
     97    */
     98    protected JPanel buildSetBPanel() {
     99        JPanel pnl = new JPanel(new GridBagLayout());;
     100        GridBagConstraints gc = new GridBagConstraints();
     101        gc.anchor = GridBagConstraints.NORTHWEST;
     102        gc.fill = GridBagConstraints.HORIZONTAL;
     103        gc.weightx = 1.0;
     104        gc.gridx = 0;
     105        gc.gridy = 0;
     106       
     107        pnl.add(rbSetB = new JRadioButton(tr("Road signs - Set B")),gc);
     108       
     109        JPanel icons = new JPanel(new FlowLayout(FlowLayout.LEFT));
     110        for (TurnRestrictionType type: TurnRestrictionType.values()){
     111            JLabel lbl = new JLabel();
     112            icons.add(lbl);
     113            lbl.setIcon(ImageProvider.get("types/set-b",type.getTagValue()));
     114        }
     115       
     116        gc.gridy = 1;
     117        gc.insets = new Insets(0,20,0,0);
     118        pnl.add(icons, gc);
     119        return pnl;     
     120    }
     121   
     122    /**
     123    * Builds the message panel at the top
     124    *
     125    * @return
     126    */
     127    protected JPanel buildMessagePanel() {
     128        HtmlPanel pnl = new HtmlPanel();
     129        pnl.setText(
     130                "<html><body>"
     131              + tr("Please select the set of road sign icons to be used in the plugin.")
     132              + "</body></html>"
     133        );
     134        return pnl;
     135    }
     136   
     137    /**
     138    * Builds the UI
     139    *
     140    * @return
     141    */
     142    protected void build() {           
     143        setLayout(new GridBagLayout());
     144        GridBagConstraints gc = new GridBagConstraints();
     145        gc.anchor = GridBagConstraints.NORTHWEST;
     146        gc.fill = GridBagConstraints.HORIZONTAL;
     147        gc.weightx = 1.0;
     148        gc.gridx = 0;
     149        gc.gridy = 0;
     150       
     151        add(buildMessagePanel(), gc);
     152        gc.gridy++;
     153        add(buildSetAPanel(), gc);
     154        gc.gridy++;
     155        add(buildSetBPanel(), gc);
     156        gc.gridy++;
     157        add(new JSeparator(), gc);     
     158        gc.gridy++;
     159        add(buildShowViaListInBasicEditorPanel(), gc);
     160        gc.gridy++;
     161        add(new JSeparator(), gc);
     162        gc.gridy++;
     163        add(pnlShortcutPreference = new ShortcutPreferencePanel(), gc);
     164       
     165        // filler - just grab remaining space
     166        gc.gridy++;
     167        gc.fill = GridBagConstraints.BOTH;
     168        gc.weighty = 1.0;
     169        add(new JPanel(), gc);     
     170       
     171        bgIconSet = new ButtonGroup();
     172        bgIconSet.add(rbSetA);
     173        bgIconSet.add(rbSetB);
     174       
     175        setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
     176    }
     177   
     178    /**
     179    * Initializes the UI from the current settings in the JOSM preferences
     180    * {@code prefs}
     181    *
     182    * @param prefs the preferences
     183    */
     184    public void initFromPreferences(Preferences prefs){
     185        String set = prefs.get(PreferenceKeys.ROAD_SIGNS, "set-a");
     186        set = set.trim().toLowerCase();
     187        if (! set.equals("set-a") && ! set.equals("set-b")) {
     188            System.out.println(tr("Warning: the preference with key ''{0}'' has an unsupported value ''{1}''. Assuming the default value ''set-a''.", PreferenceKeys.ROAD_SIGNS, set));
     189            set = "set-a";
     190        }
     191        if (set.equals("set-a")){
     192            rbSetA.setSelected(true);
     193        } else {
     194            rbSetB.setSelected(true);
     195        }
     196       
     197        boolean b = prefs.getBoolean(PreferenceKeys.SHOW_VIAS_IN_BASIC_EDITOR, false);
     198        cbShowViaListInBasicEditor.setSelected(b);
     199       
     200        pnlShortcutPreference.initFromPreferences(prefs);
     201    }
     202   
     203    /**
     204    * Saves the current settings to the JOSM preferences {@code prefs}.
     205    *
     206    * @param prefs the preferences
     207    */
     208    public void saveToPreferences(Preferences prefs){
     209        String set = null;
     210        if (rbSetA.isSelected()){
     211            set = "set-a";
     212        } else {
     213            set = "set-b";
     214        }
     215        String oldSet = prefs.get(PreferenceKeys.ROAD_SIGNS, "set-a");     
     216        if (!set.equals(oldSet)){
     217            prefs.put(PreferenceKeys.ROAD_SIGNS, set);
     218        }
     219       
     220        boolean newValue = cbShowViaListInBasicEditor.isSelected();
     221        boolean oldValue = prefs.getBoolean(PreferenceKeys.SHOW_VIAS_IN_BASIC_EDITOR, false);
     222        if (newValue != oldValue){
     223            prefs.put(PreferenceKeys.SHOW_VIAS_IN_BASIC_EDITOR, newValue);
     224        }       
     225       
     226        pnlShortcutPreference.saveToPreferences(prefs);
     227    }
     228   
     229    public PreferencesPanel() {
     230        build();
     231    }   
    232232}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/preferences/ShortcutPreferencePanel.java

    r20701 r23192  
    3636 */
    3737public class ShortcutPreferencePanel extends JPanel {
    38        
    39         private JCheckBox cbCtrl;
    40         private JCheckBox cbAlt;
    41         private JCheckBox cbShift;
    42         private JCheckBox cbMeta;
    43         private JComboBox cmKeyCodes;
    44 
    45         protected JPanel buildMessagePanel() {
    46                 HtmlPanel pnl = new HtmlPanel();
    47                 pnl.setText("<html><body>"
    48                         + tr("Please configure the <strong>keyboard shortcut</strong> which triggers "
    49                                 + "creating/editing a turn restriction from the current JOSM selection.")
    50                         + "</body></html>"
    51                 );
    52                 return pnl;
    53         }
    54        
    55         protected JPanel buildShortCutConfigPanel() {
    56                 JPanel pnl = new JPanel(new GridBagLayout());
    57                 GridBagConstraints gc = new GridBagConstraints();
    58                 gc.anchor = GridBagConstraints.NORTHWEST;
    59                 gc.fill = GridBagConstraints.HORIZONTAL;
    60                 gc.weightx = 0.0;
    61                 gc.gridx = 0;
    62                 gc.gridy = 0;
    63                
    64                 pnl.add(new JLabel(trc("keyboard-key", "Key:")), gc);
    65                 gc.gridx++;
    66                 gc.gridwidth=4;
    67                 gc.weightx = 1.0;
    68                 pnl.add(cmKeyCodes = new JComboBox(new VKeyComboBoxModel()), gc);
    69                 cmKeyCodes.setRenderer(new VKeyCellRenderer());
    70                
    71                 gc.gridx = 0;
    72                 gc.gridy = 1;
    73                 gc.gridwidth = 1;
    74                 gc.weightx = 0.0;
    75                 pnl.add(new JLabel(trc("keyboard-modifiers", "Modifiers:")), gc);
    76        
    77                 gc.gridx++;
    78                 pnl.add(cbShift = new JCheckBox(trc("keyboard-modifiers", "Shift")), gc);
    79                 gc.gridx++;
    80                 pnl.add(cbCtrl = new JCheckBox(trc("keyboard-modifiers", "Ctrl")), gc);
    81                 gc.gridx++;
    82                 pnl.add(cbAlt = new JCheckBox(trc("keyboard-modifiers", "Alt")), gc);
    83                 gc.gridx++;
    84                 gc.weightx = 1.0;
    85                 pnl.add(cbMeta = new JCheckBox(trc("keyboard-modifiers", "Meta")), gc);
    86                
    87                 return pnl;
    88         }
    89        
    90         protected void build() {
    91                 setLayout(new GridBagLayout());
    92                 GridBagConstraints gc = new GridBagConstraints();
    93                 gc.anchor = GridBagConstraints.NORTHWEST;
    94                 gc.fill = GridBagConstraints.HORIZONTAL;
    95                 gc.weightx = 1.0;
    96                 gc.gridx = 0;
    97                 gc.gridy = 0;
    98                 add(buildMessagePanel(), gc);
    99                 gc.gridy++;
    100                 add(buildShortCutConfigPanel(), gc);
    101         }
    102        
    103         public ShortcutPreferencePanel() {
    104                 build();
    105         }
    106        
    107         public void initFromPreferences(Preferences pref){
    108                 String value = pref.get(PreferenceKeys.EDIT_SHORTCUT, "shift ctrl T");
    109                 KeyStroke key = KeyStroke.getKeyStroke(value);
    110                 if (key == null){
    111                         System.out.println(tr("Warning: illegal value ''{0}'' for preference key ''{1}''. Falling back to default value ''shift ctrl T''.", value, PreferenceKeys.EDIT_SHORTCUT));
    112                         key = KeyStroke.getKeyStroke("shift ctrl T");
    113                 }
    114                 cmKeyCodes.getModel().setSelectedItem(key.getKeyCode());
    115                 cbAlt.setSelected((key.getModifiers() & KeyEvent.ALT_DOWN_MASK) != 0);
    116                 cbCtrl.setSelected((key.getModifiers() & KeyEvent.CTRL_DOWN_MASK) != 0);
    117                 cbShift.setSelected((key.getModifiers() & KeyEvent.SHIFT_DOWN_MASK) != 0);
    118                 cbMeta.setSelected((key.getModifiers() & KeyEvent.META_DOWN_MASK) != 0);
    119         }
    120        
    121         public void saveToPreferences(Preferences pref){
    122                 Integer code  = (Integer)cmKeyCodes.getModel().getSelectedItem();
    123                 if (code == null) {
    124                         code = KeyEvent.VK_T;
    125                 }
    126                 int modifiers = 0;
    127                 if (cbAlt.isSelected()) modifiers |= KeyEvent.ALT_DOWN_MASK;
    128                 if (cbCtrl.isSelected()) modifiers |= KeyEvent.CTRL_DOWN_MASK;
    129                 if (cbShift.isSelected()) modifiers |= KeyEvent.SHIFT_DOWN_MASK;
    130                 if (cbMeta.isSelected()) modifiers |= KeyEvent.META_DOWN_MASK;         
    131                 KeyStroke ks = KeyStroke.getKeyStroke(code, modifiers);
    132                
    133                 pref.put(PreferenceKeys.EDIT_SHORTCUT, ks.toString());         
    134                 CreateOrEditTurnRestrictionAction.install(ks);
    135         }
    136        
    137         static private class VKeyComboBoxModel extends AbstractListModel implements ComboBoxModel {
    138                 private final ArrayList<Integer> keys = new ArrayList<Integer>();
    139                 private Integer selected = null;
    140 
    141                 public VKeyComboBoxModel() {
    142                         populate();
    143                 }
    144                
    145                 public void populate() {
    146                         for (Field f :KeyEvent.class.getFields()) {
    147                                 if (! Modifier.isStatic(f.getModifiers())) continue;
    148                                 if (! f.getName().startsWith("VK_")) continue;
    149                                 try {
    150                                         keys.add((Integer)f.get(null));
    151                                 } catch(IllegalAccessException e){
    152                                         // ignore
    153                                 }
    154                         }
    155                        
    156                         Collections.sort(keys, new KeyCodeComparator());
    157                 }
    158                
    159                 public Object getSelectedItem() {
    160                         return selected;
    161                 }
    162 
    163                 public void setSelectedItem(Object anItem) {
    164                         this.selected = (Integer)anItem;                       
    165                 }
    166 
    167                 public Object getElementAt(int index) {
    168                         return keys.get(index);
    169                 }
    170 
    171                 public int getSize() {
    172                         return keys.size();
    173                 }               
    174         }
    175        
    176         static private class VKeyCellRenderer extends JLabel implements ListCellRenderer {
    177                 public Component getListCellRendererComponent(JList list, Object value,
    178                                 int index, boolean isSelected, boolean cellHasFocus) {
    179                         if (isSelected) {
    180                                 setBackground(UIManager.getColor("ComboBox.selectionBackground"));
    181                                 setForeground(UIManager.getColor("ComboBox.selectionForeground"));
    182                         } else {
    183                                 setBackground(UIManager.getColor("ComboBox.background"));
    184                                 setForeground(UIManager.getColor("ComboBox.foreground"));
    185                         }
    186                         setText(KeyEvent.getKeyText((Integer)value));
    187                         return this;
    188                 }               
    189         }
    190        
    191         static private class KeyCodeComparator implements Comparator<Integer> {
    192                 private final static Map<Integer, String> keyNames = new HashMap<Integer, String>();
    193                
    194                 protected String keyName(Integer code){
    195                         String name = keyNames.get(code);
    196                         if (name == null){
    197                                 name = KeyEvent.getKeyText(code);
    198                                 keyNames.put(code, name);
    199                         }
    200                         return name;
    201                 }
    202                 /**
    203                 * Make sure single letter keys (A-Z, 0-9) are at the top of the list.
    204                 * Make sure function key F1-F19 are sorted numerically, not lexicografically.
    205                 *
    206                 */
    207                 public int compare(Integer kc1, Integer kc2) {
    208                         String n1 = keyName(kc1);
    209                         String n2 = keyName(kc2);
    210                         if (n1.length() == 1 && n2.length()==1){
    211                                 return n1.compareTo(n2);
    212                         } else if (n1.length() == 1){
    213                                 return -1;
    214                         } else if (n2.length() == 1){
    215                                 return 1;
    216                         } else if (n1.matches("F\\d+") && n2.matches("F\\d+")){
    217                                 int f1 = Integer.parseInt(n1.substring(1));
    218                                 int f2 = Integer.parseInt(n2.substring(1));
    219                                 return new Integer(f1).compareTo(f2);                           
    220                         } else {
    221                                 return n1.compareTo(n2);
    222                         }                               
    223                 }               
    224         }
     38   
     39    private JCheckBox cbCtrl;
     40    private JCheckBox cbAlt;
     41    private JCheckBox cbShift;
     42    private JCheckBox cbMeta;
     43    private JComboBox cmKeyCodes;
     44
     45    protected JPanel buildMessagePanel() {
     46        HtmlPanel pnl = new HtmlPanel();
     47        pnl.setText("<html><body>"
     48            + tr("Please configure the <strong>keyboard shortcut</strong> which triggers "
     49                + "creating/editing a turn restriction from the current JOSM selection.")
     50            + "</body></html>"
     51        );
     52        return pnl;
     53    }
     54   
     55    protected JPanel buildShortCutConfigPanel() {
     56        JPanel pnl = new JPanel(new GridBagLayout());
     57        GridBagConstraints gc = new GridBagConstraints();
     58        gc.anchor = GridBagConstraints.NORTHWEST;
     59        gc.fill = GridBagConstraints.HORIZONTAL;
     60        gc.weightx = 0.0;
     61        gc.gridx = 0;
     62        gc.gridy = 0;
     63       
     64        pnl.add(new JLabel(trc("keyboard-key", "Key:")), gc);
     65        gc.gridx++;
     66        gc.gridwidth=4;
     67        gc.weightx = 1.0;
     68        pnl.add(cmKeyCodes = new JComboBox(new VKeyComboBoxModel()), gc);
     69        cmKeyCodes.setRenderer(new VKeyCellRenderer());
     70       
     71        gc.gridx = 0;
     72        gc.gridy = 1;
     73        gc.gridwidth = 1;
     74        gc.weightx = 0.0;
     75        pnl.add(new JLabel(trc("keyboard-modifiers", "Modifiers:")), gc);
     76   
     77        gc.gridx++;
     78        pnl.add(cbShift = new JCheckBox(trc("keyboard-modifiers", "Shift")), gc);
     79        gc.gridx++;
     80        pnl.add(cbCtrl = new JCheckBox(trc("keyboard-modifiers", "Ctrl")), gc);
     81        gc.gridx++;
     82        pnl.add(cbAlt = new JCheckBox(trc("keyboard-modifiers", "Alt")), gc);
     83        gc.gridx++;
     84        gc.weightx = 1.0;
     85        pnl.add(cbMeta = new JCheckBox(trc("keyboard-modifiers", "Meta")), gc);
     86       
     87        return pnl;
     88    }
     89   
     90    protected void build() {
     91        setLayout(new GridBagLayout());
     92        GridBagConstraints gc = new GridBagConstraints();
     93        gc.anchor = GridBagConstraints.NORTHWEST;
     94        gc.fill = GridBagConstraints.HORIZONTAL;
     95        gc.weightx = 1.0;
     96        gc.gridx = 0;
     97        gc.gridy = 0;
     98        add(buildMessagePanel(), gc);
     99        gc.gridy++;
     100        add(buildShortCutConfigPanel(), gc);
     101    }
     102   
     103    public ShortcutPreferencePanel() {
     104        build();
     105    }
     106   
     107    public void initFromPreferences(Preferences pref){
     108        String value = pref.get(PreferenceKeys.EDIT_SHORTCUT, "shift ctrl T");
     109        KeyStroke key = KeyStroke.getKeyStroke(value);
     110        if (key == null){
     111            System.out.println(tr("Warning: illegal value ''{0}'' for preference key ''{1}''. Falling back to default value ''shift ctrl T''.", value, PreferenceKeys.EDIT_SHORTCUT));
     112            key = KeyStroke.getKeyStroke("shift ctrl T");
     113        }
     114        cmKeyCodes.getModel().setSelectedItem(key.getKeyCode());
     115        cbAlt.setSelected((key.getModifiers() & KeyEvent.ALT_DOWN_MASK) != 0);
     116        cbCtrl.setSelected((key.getModifiers() & KeyEvent.CTRL_DOWN_MASK) != 0);
     117        cbShift.setSelected((key.getModifiers() & KeyEvent.SHIFT_DOWN_MASK) != 0);
     118        cbMeta.setSelected((key.getModifiers() & KeyEvent.META_DOWN_MASK) != 0);
     119    }
     120   
     121    public void saveToPreferences(Preferences pref){
     122        Integer code  = (Integer)cmKeyCodes.getModel().getSelectedItem();
     123        if (code == null) {
     124            code = KeyEvent.VK_T;
     125        }
     126        int modifiers = 0;
     127        if (cbAlt.isSelected()) modifiers |= KeyEvent.ALT_DOWN_MASK;
     128        if (cbCtrl.isSelected()) modifiers |= KeyEvent.CTRL_DOWN_MASK;
     129        if (cbShift.isSelected()) modifiers |= KeyEvent.SHIFT_DOWN_MASK;
     130        if (cbMeta.isSelected()) modifiers |= KeyEvent.META_DOWN_MASK;     
     131        KeyStroke ks = KeyStroke.getKeyStroke(code, modifiers);
     132       
     133        pref.put(PreferenceKeys.EDIT_SHORTCUT, ks.toString());     
     134        CreateOrEditTurnRestrictionAction.install(ks);
     135    }
     136   
     137    static private class VKeyComboBoxModel extends AbstractListModel implements ComboBoxModel {
     138        private final ArrayList<Integer> keys = new ArrayList<Integer>();
     139        private Integer selected = null;
     140
     141        public VKeyComboBoxModel() {
     142            populate();
     143        }
     144       
     145        public void populate() {
     146            for (Field f :KeyEvent.class.getFields()) {
     147                if (! Modifier.isStatic(f.getModifiers())) continue;
     148                if (! f.getName().startsWith("VK_")) continue;
     149                try {
     150                    keys.add((Integer)f.get(null));
     151                } catch(IllegalAccessException e){
     152                    // ignore
     153                }
     154            }
     155           
     156            Collections.sort(keys, new KeyCodeComparator());
     157        }
     158       
     159        public Object getSelectedItem() {
     160            return selected;
     161        }
     162
     163        public void setSelectedItem(Object anItem) {
     164            this.selected = (Integer)anItem;           
     165        }
     166
     167        public Object getElementAt(int index) {
     168            return keys.get(index);
     169        }
     170
     171        public int getSize() {
     172            return keys.size();
     173        }       
     174    }
     175   
     176    static private class VKeyCellRenderer extends JLabel implements ListCellRenderer {
     177        public Component getListCellRendererComponent(JList list, Object value,
     178                int index, boolean isSelected, boolean cellHasFocus) {
     179            if (isSelected) {
     180                setBackground(UIManager.getColor("ComboBox.selectionBackground"));
     181                setForeground(UIManager.getColor("ComboBox.selectionForeground"));
     182            } else {
     183                setBackground(UIManager.getColor("ComboBox.background"));
     184                setForeground(UIManager.getColor("ComboBox.foreground"));
     185            }
     186            setText(KeyEvent.getKeyText((Integer)value));
     187            return this;
     188        }       
     189    }
     190   
     191    static private class KeyCodeComparator implements Comparator<Integer> {
     192        private final static Map<Integer, String> keyNames = new HashMap<Integer, String>();
     193       
     194        protected String keyName(Integer code){
     195            String name = keyNames.get(code);
     196            if (name == null){
     197                name = KeyEvent.getKeyText(code);
     198                keyNames.put(code, name);
     199            }
     200            return name;
     201        }
     202        /**
     203        * Make sure single letter keys (A-Z, 0-9) are at the top of the list.
     204        * Make sure function key F1-F19 are sorted numerically, not lexicografically.
     205        *
     206        */
     207        public int compare(Integer kc1, Integer kc2) {
     208            String n1 = keyName(kc1);
     209            String n2 = keyName(kc2);
     210            if (n1.length() == 1 && n2.length()==1){
     211                return n1.compareTo(n2);
     212            } else if (n1.length() == 1){
     213                return -1;
     214            } else if (n2.length() == 1){
     215                return 1;
     216            } else if (n1.matches("F\\d+") && n2.matches("F\\d+")){
     217                int f1 = Integer.parseInt(n1.substring(1));
     218                int f2 = Integer.parseInt(n2.substring(1));
     219                return new Integer(f1).compareTo(f2);               
     220            } else {
     221                return n1.compareTo(n2);
     222            }               
     223        }       
     224    }
    225225}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/qa/IdenticalTurnRestrictionLegsError.java

    r20701 r23192  
    1515 */
    1616public class IdenticalTurnRestrictionLegsError extends Issue{
    17         private OsmPrimitive leg;
    18        
    19         public IdenticalTurnRestrictionLegsError(IssuesModel parent, OsmPrimitive leg) {
    20                 super(parent, Severity.ERROR);
    21                 actions.add(new DeleteFromAction());
    22                 actions.add(new DeleteToAction());
    23                 actions.add(new FixInEditorAction());
    24                 this.leg = leg;
    25         }
     17    private OsmPrimitive leg;
     18   
     19    public IdenticalTurnRestrictionLegsError(IssuesModel parent, OsmPrimitive leg) {
     20        super(parent, Severity.ERROR);
     21        actions.add(new DeleteFromAction());
     22        actions.add(new DeleteToAction());
     23        actions.add(new FixInEditorAction());
     24        this.leg = leg;
     25    }
    2626
    27         @Override
    28         public String getText() {               
    29                 return tr("This turn restriction uses the OSM way <span class=\"object-name\">{0}</span> with role <tt>from</tt> <strong>and</strong> with role <tt>to</tt>. "
    30                                 + "In a turn restriction, the way with role <tt>from</tt> should be different from the way with role <tt>to</tt>, though.",
    31                                 leg.getDisplayName(DefaultNameFormatter.getInstance())
    32                                 );                             
    33         }
    34        
    35         class DeleteFromAction extends AbstractAction {
    36                 public DeleteFromAction() {
    37                         putValue(NAME, tr("Delete ''from''"));
    38                         putValue(SHORT_DESCRIPTION, tr("Removes the member with role ''from''"));
    39                 }
    40                 public void actionPerformed(ActionEvent e) {
    41                         getIssuesModel().getEditorModel().getRelationMemberEditorModel().setFromPrimitive(null);                       
    42                 }               
    43         }
    44        
    45         class DeleteToAction extends AbstractAction {
    46                 public DeleteToAction() {
    47                         putValue(NAME, tr("Delete ''to''"));
    48                         putValue(SHORT_DESCRIPTION, tr("Removes the member with role ''to''"));
    49                 }
    50                 public void actionPerformed(ActionEvent e) {
    51                         getIssuesModel().getEditorModel().getRelationMemberEditorModel().setToPrimitive(null);                 
    52                 }               
    53         }
    54        
    55         class FixInEditorAction extends AbstractAction {
    56                 public FixInEditorAction() {
    57                         putValue(NAME, tr("Fix in editor"));
    58                         putValue(SHORT_DESCRIPTION, tr("Go to Basic Editor and manually choose members with roles ''from'' and ''to''"));
    59                 }
    60                 public void actionPerformed(ActionEvent e) {
    61                         getIssuesModel().getNavigationControler().gotoBasicEditor();           
    62                 }               
    63         }
     27    @Override
     28    public String getText() {       
     29        return tr("This turn restriction uses the OSM way <span class=\"object-name\">{0}</span> with role <tt>from</tt> <strong>and</strong> with role <tt>to</tt>. "
     30                + "In a turn restriction, the way with role <tt>from</tt> should be different from the way with role <tt>to</tt>, though.",
     31                leg.getDisplayName(DefaultNameFormatter.getInstance())
     32                );             
     33    }
     34   
     35    class DeleteFromAction extends AbstractAction {
     36        public DeleteFromAction() {
     37            putValue(NAME, tr("Delete ''from''"));
     38            putValue(SHORT_DESCRIPTION, tr("Removes the member with role ''from''"));
     39        }
     40        public void actionPerformed(ActionEvent e) {
     41            getIssuesModel().getEditorModel().getRelationMemberEditorModel().setFromPrimitive(null);           
     42        }       
     43    }
     44   
     45    class DeleteToAction extends AbstractAction {
     46        public DeleteToAction() {
     47            putValue(NAME, tr("Delete ''to''"));
     48            putValue(SHORT_DESCRIPTION, tr("Removes the member with role ''to''"));
     49        }
     50        public void actionPerformed(ActionEvent e) {
     51            getIssuesModel().getEditorModel().getRelationMemberEditorModel().setToPrimitive(null);         
     52        }       
     53    }
     54   
     55    class FixInEditorAction extends AbstractAction {
     56        public FixInEditorAction() {
     57            putValue(NAME, tr("Fix in editor"));
     58            putValue(SHORT_DESCRIPTION, tr("Go to Basic Editor and manually choose members with roles ''from'' and ''to''"));
     59        }
     60        public void actionPerformed(ActionEvent e) {
     61            getIssuesModel().getNavigationControler().gotoBasicEditor();       
     62        }       
     63    }
    6464}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/qa/IllegalRestrictionTypeError.java

    r20622 r23192  
    1515 */
    1616public class IllegalRestrictionTypeError extends Issue{
    17         private String value;
    18        
    19         public IllegalRestrictionTypeError(IssuesModel parent, String value) {
    20                 super(parent, Severity.ERROR);
    21                 actions.add(new FixInEditorAction());
    22                 this.value = value;
    23         }
     17    private String value;
     18   
     19    public IllegalRestrictionTypeError(IssuesModel parent, String value) {
     20        super(parent, Severity.ERROR);
     21        actions.add(new FixInEditorAction());
     22        this.value = value;
     23    }
    2424
    25         @Override
    26         public String getText() {               
    27                 return tr("This turn restriction uses a non-standard restriction type <tt>{0}</tt> for the tag key <tt>restriction</tt>. "
    28                                 + "It is recommended to use standard values only. Please select one in the Basic editor.",
    29                                 value
    30                                 );                             
    31         }
    32        
    33         class FixInEditorAction extends AbstractAction {
    34                 public FixInEditorAction() {
    35                         putValue(NAME, tr("Fix in editor"));
    36                         putValue(SHORT_DESCRIPTION, tr("Go to Basic Editor and manually choose a turn restriction type"));
    37                 }
    38                 public void actionPerformed(ActionEvent e) {
    39                         getIssuesModel().getNavigationControler().gotoBasicEditor(NavigationControler.BasicEditorFokusTargets.RESTRICION_TYPE);                 
    40                 }               
    41         }
     25    @Override
     26    public String getText() {       
     27        return tr("This turn restriction uses a non-standard restriction type <tt>{0}</tt> for the tag key <tt>restriction</tt>. "
     28                + "It is recommended to use standard values only. Please select one in the Basic editor.",
     29                value
     30                );             
     31    }
     32   
     33    class FixInEditorAction extends AbstractAction {
     34        public FixInEditorAction() {
     35            putValue(NAME, tr("Fix in editor"));
     36            putValue(SHORT_DESCRIPTION, tr("Go to Basic Editor and manually choose a turn restriction type"));
     37        }
     38        public void actionPerformed(ActionEvent e) {
     39            getIssuesModel().getNavigationControler().gotoBasicEditor(NavigationControler.BasicEditorFokusTargets.RESTRICION_TYPE);         
     40        }       
     41    }
    4242}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/qa/IntersectionMissingAsViaError.java

    r20701 r23192  
    2020 */
    2121public class IntersectionMissingAsViaError extends Issue{
    22         private Way from;
    23         private Way to;
    24         private Node interesect;
    25        
    26         public IntersectionMissingAsViaError(IssuesModel parent, Way from, Way to, Node intersect) {
    27                 super(parent, Severity.ERROR);
    28                 this.from = from;
    29                 this.to = to;
    30                 this.interesect = intersect;
    31                 actions.add(new SetVia());
    32                 actions.add(new FixInEditorAction());
    33         }
     22    private Way from;
     23    private Way to;
     24    private Node interesect;
     25   
     26    public IntersectionMissingAsViaError(IssuesModel parent, Way from, Way to, Node intersect) {
     27        super(parent, Severity.ERROR);
     28        this.from = from;
     29        this.to = to;
     30        this.interesect = intersect;
     31        actions.add(new SetVia());
     32        actions.add(new FixInEditorAction());
     33    }
    3434
    35         @Override
    36         public String getText() {               
    37                 String msg = tr("The <strong>from</strong>-way <span class=\"object-name\">{0}</span> and the <strong>to</strong>-way <span class=\"object-name\">{1}</span> "
    38                        + "interesect at node <span class=\"object-name\">{2}</span> but <span class=\"object-name\">{2}</span> isn''t a <strong>via</strong>-object.<br> "
    39                        + "It is recommended to set <span class=\"object-name\">{2}</span> as unique <strong>via</strong>-object.",
    40                        this.from.getDisplayName(DefaultNameFormatter.getInstance()),
    41                        this.to.getDisplayName(DefaultNameFormatter.getInstance()),
    42                        this.interesect.getDisplayName(DefaultNameFormatter.getInstance())
    43                 );
    44                 return msg;
    45         }
    46        
    47         class SetVia extends AbstractAction {
    48                 public SetVia() {
    49                         putValue(NAME, tr("Set via-Object"));
    50                         putValue(SHORT_DESCRIPTION, tr("Replaces the currently configured via-objects with the node at the intersection"));
    51                 }
    52                 public void actionPerformed(ActionEvent e) {
    53                         getIssuesModel().getEditorModel().setVias(Collections.<OsmPrimitive>singletonList(interesect));                 
    54                 }               
    55         }
    56        
    57         class FixInEditorAction extends AbstractAction {
    58                 public FixInEditorAction() {
    59                         putValue(NAME, tr("Fix in editor"));
    60                         putValue(SHORT_DESCRIPTION, tr("Go to Basic Editor and manually fix the list of via-objects"));
    61                 }
    62                 public void actionPerformed(ActionEvent e) {
    63                         getIssuesModel().getNavigationControler().gotoBasicEditor(BasicEditorFokusTargets.VIA);
    64                 }               
    65         }
     35    @Override
     36    public String getText() {       
     37        String msg = tr("The <strong>from</strong>-way <span class=\"object-name\">{0}</span> and the <strong>to</strong>-way <span class=\"object-name\">{1}</span> "
     38               + "interesect at node <span class=\"object-name\">{2}</span> but <span class=\"object-name\">{2}</span> isn''t a <strong>via</strong>-object.<br> "
     39               + "It is recommended to set <span class=\"object-name\">{2}</span> as unique <strong>via</strong>-object.",
     40               this.from.getDisplayName(DefaultNameFormatter.getInstance()),
     41               this.to.getDisplayName(DefaultNameFormatter.getInstance()),
     42               this.interesect.getDisplayName(DefaultNameFormatter.getInstance())
     43        );
     44        return msg;
     45    }
     46   
     47    class SetVia extends AbstractAction {
     48        public SetVia() {
     49            putValue(NAME, tr("Set via-Object"));
     50            putValue(SHORT_DESCRIPTION, tr("Replaces the currently configured via-objects with the node at the intersection"));
     51        }
     52        public void actionPerformed(ActionEvent e) {
     53            getIssuesModel().getEditorModel().setVias(Collections.<OsmPrimitive>singletonList(interesect));         
     54        }       
     55    }
     56   
     57    class FixInEditorAction extends AbstractAction {
     58        public FixInEditorAction() {
     59            putValue(NAME, tr("Fix in editor"));
     60            putValue(SHORT_DESCRIPTION, tr("Go to Basic Editor and manually fix the list of via-objects"));
     61        }
     62        public void actionPerformed(ActionEvent e) {
     63            getIssuesModel().getNavigationControler().gotoBasicEditor(BasicEditorFokusTargets.VIA);
     64        }       
     65    }
    6666}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/qa/Issue.java

    r20622 r23192  
    1818 */
    1919abstract public class Issue {
    20         /** the parent model for this issue */
    21         protected IssuesModel parent;
    22         protected Severity severity;
    23         protected final ArrayList<Action> actions = new ArrayList<Action>();
    24        
    25         /**
    26         * Creates a new issue associated with a parent model. Severity is
    27         * initialized to {@see Severity#WARNING}.
    28         *
    29         * @param parent the parent model. Must not be null.
    30         * @throws IllegalArgumentException thrown if parent is null
    31         */
    32         public Issue(IssuesModel parent) throws IllegalArgumentException{
    33                 CheckParameterUtil.ensureParameterNotNull(parent, "parent");
    34                 this.parent = parent;
    35                 this.severity = Severity.WARNING;
    36         }
    37        
    38         /**
    39         * Creates a new issue of severity {@code severity} associated with
    40         * the parent model {@code parent}.
    41         *
    42         * @param parent the parent model. Must not be null.
    43         * @param severity the severity. Must not be null.
    44         * @throws IllegalArgumentException thrown if parent is null
    45         * @throws IllegalArgumentException thrown if severity is null
    46         */
    47         public Issue(IssuesModel parent, Severity severity){
    48                 CheckParameterUtil.ensureParameterNotNull(parent, "parent");
    49                 CheckParameterUtil.ensureParameterNotNull(severity, "severity");
    50                 this.parent = parent;
    51                 this.severity = severity;
    52         }
     20    /** the parent model for this issue */
     21    protected IssuesModel parent;
     22    protected Severity severity;
     23    protected final ArrayList<Action> actions = new ArrayList<Action>();
     24   
     25    /**
     26    * Creates a new issue associated with a parent model. Severity is
     27    * initialized to {@see Severity#WARNING}.
     28    *
     29    * @param parent the parent model. Must not be null.
     30    * @throws IllegalArgumentException thrown if parent is null
     31    */
     32    public Issue(IssuesModel parent) throws IllegalArgumentException{
     33        CheckParameterUtil.ensureParameterNotNull(parent, "parent");
     34        this.parent = parent;
     35        this.severity = Severity.WARNING;
     36    }
     37   
     38    /**
     39    * Creates a new issue of severity {@code severity} associated with
     40    * the parent model {@code parent}.
     41    *
     42    * @param parent the parent model. Must not be null.
     43    * @param severity the severity. Must not be null.
     44    * @throws IllegalArgumentException thrown if parent is null
     45    * @throws IllegalArgumentException thrown if severity is null
     46    */
     47    public Issue(IssuesModel parent, Severity severity){
     48        CheckParameterUtil.ensureParameterNotNull(parent, "parent");
     49        CheckParameterUtil.ensureParameterNotNull(severity, "severity");
     50        this.parent = parent;
     51        this.severity = severity;
     52    }
    5353
    54         /**
    55         * Replies the parent model this issue is associated with
    56         *
    57         * @return the parent model
    58         */
    59         public IssuesModel getIssuesModel() {
    60                 return parent;
    61         }
     54    /**
     55    * Replies the parent model this issue is associated with
     56    *
     57    * @return the parent model
     58    */
     59    public IssuesModel getIssuesModel() {
     60        return parent;
     61    }
    6262
    63         /**
    64         * Replies the severity of this issue
    65         *
    66         * @return the severity
    67         */
    68         public Severity getSeverity() {
    69                 return severity;
    70         }
     63    /**
     64    * Replies the severity of this issue
     65    *
     66    * @return the severity
     67    */
     68    public Severity getSeverity() {
     69        return severity;
     70    }
    7171
    72         /**
    73         * Sets the severity of this issue.
    74         *
    75         * @param severity the severity. Must not be null.
    76         * @throws IllegalArgumentException thrown if severity is null
    77         */
    78         public void setSeverity(Severity severity) throws IllegalArgumentException {
    79                 CheckParameterUtil.ensureParameterNotNull(severity, "severity");
    80                 this.severity = severity;
    81         }
     72    /**
     73    * Sets the severity of this issue.
     74    *
     75    * @param severity the severity. Must not be null.
     76    * @throws IllegalArgumentException thrown if severity is null
     77    */
     78    public void setSeverity(Severity severity) throws IllegalArgumentException {
     79        CheckParameterUtil.ensureParameterNotNull(severity, "severity");
     80        this.severity = severity;
     81    }
    8282
    83         /**
    84         * Replies the HTML formatted description of the issue. The text should neither include
    85         * the &lt;html&gt;, nor the &lt;body&gt; tag. 
    86         *
    87         * @return the HTML formatted description of the issue.
    88         */
    89         public abstract String getText();
    90        
    91         /**
    92         * Replies a list of actions which can be applied to this issue in order to fix
    93         * it. The default implementation replies an empty list.
    94         *
    95         * @return a list of action
    96         */
    97         public List<Action> getActions() {
    98                 return Collections.unmodifiableList(actions);
    99         }
     83    /**
     84    * Replies the HTML formatted description of the issue. The text should neither include
     85    * the &lt;html&gt;, nor the &lt;body&gt; tag. 
     86    *
     87    * @return the HTML formatted description of the issue.
     88    */
     89    public abstract String getText();
     90   
     91    /**
     92    * Replies a list of actions which can be applied to this issue in order to fix
     93    * it. The default implementation replies an empty list.
     94    *
     95    * @return a list of action
     96    */
     97    public List<Action> getActions() {
     98        return Collections.unmodifiableList(actions);
     99    }
    100100}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/qa/IssueView.java

    r20645 r23192  
    2626public class IssueView extends JPanel{
    2727
    28         private HtmlPanel pnlMessage;
    29         private JPanel pnlActions;
    30         private Issue issue;
    31         private JLabel lblIcon;
    32         private StyleSheet styleSheet;
    33        
    34         /**
     28    private HtmlPanel pnlMessage;
     29    private JPanel pnlActions;
     30    private Issue issue;
     31    private JLabel lblIcon;
     32    private StyleSheet styleSheet;
     33   
     34    /**
    3535     * Builds the style sheet used in the internal help browser
    3636     *
     
    4343        ss.addRule(".object-name {background-color:rgb(240,240,240); color: blue;}");
    4444    }
    45        
    46         protected void build() {
    47                 setLayout(new GridBagLayout());
    48                 setBackground(Color.WHITE);
    49                 setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 1));
    50                
    51                 // add the icon for the severity
    52                 GridBagConstraints gc = new GridBagConstraints();
    53                 gc.anchor = GridBagConstraints.NORTHWEST;
    54                 gc.fill = GridBagConstraints.VERTICAL;
    55                 gc.gridheight = 2;
    56                 gc.weightx = 0.0;
    57                 gc.weighty = 1.0;
    58                 gc.gridx = 0;
    59                 gc.gridy = 0;
    60                 gc.insets = new Insets(2,2,2,2);
    61                 add(lblIcon = new JLabel(), gc);
    62                 lblIcon.setVerticalAlignment(SwingConstants.TOP);
    63                 lblIcon.setHorizontalAlignment(SwingConstants.CENTER);
    64                 lblIcon.setBorder(BorderFactory.createEmptyBorder(2,2,2,2));
     45   
     46    protected void build() {
     47        setLayout(new GridBagLayout());
     48        setBackground(Color.WHITE);
     49        setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 1));
     50       
     51        // add the icon for the severity
     52        GridBagConstraints gc = new GridBagConstraints();
     53        gc.anchor = GridBagConstraints.NORTHWEST;
     54        gc.fill = GridBagConstraints.VERTICAL;
     55        gc.gridheight = 2;
     56        gc.weightx = 0.0;
     57        gc.weighty = 1.0;
     58        gc.gridx = 0;
     59        gc.gridy = 0;
     60        gc.insets = new Insets(2,2,2,2);
     61        add(lblIcon = new JLabel(), gc);
     62        lblIcon.setVerticalAlignment(SwingConstants.TOP);
     63        lblIcon.setHorizontalAlignment(SwingConstants.CENTER);
     64        lblIcon.setBorder(BorderFactory.createEmptyBorder(2,2,2,2));
    6565
    66                 // add the html panel with the issue description
    67                 gc.insets = new Insets(0,0,0,0);
    68                 gc.anchor = GridBagConstraints.NORTHWEST;
    69                 gc.fill = GridBagConstraints.BOTH;
    70                 gc.gridx = 1;
    71                 gc.gridy = 0;
    72                 gc.gridheight = 1;
    73                 gc.weightx = 1.0;
    74                 gc.weighty = 1.0;
    75                 add(pnlMessage = new HtmlPanel(), gc);
    76                 initStyleSheet(pnlMessage);
    77                 pnlMessage.setBackground(Color.white);
    78                 pnlMessage.setText("<html><body>" + issue.getText() + "</html></bod>");
     66        // add the html panel with the issue description
     67        gc.insets = new Insets(0,0,0,0);
     68        gc.anchor = GridBagConstraints.NORTHWEST;
     69        gc.fill = GridBagConstraints.BOTH;
     70        gc.gridx = 1;
     71        gc.gridy = 0;
     72        gc.gridheight = 1;
     73        gc.weightx = 1.0;
     74        gc.weighty = 1.0;
     75        add(pnlMessage = new HtmlPanel(), gc);
     76        initStyleSheet(pnlMessage);
     77        pnlMessage.setBackground(Color.white);
     78        pnlMessage.setText("<html><body>" + issue.getText() + "</html></bod>");
    7979
    80                
    81                 // if there are any actions available to resolve the issue, add a panel with action buttons
    82                 if (!issue.getActions().isEmpty()) {
    83                         pnlActions = new JPanel(new FlowLayout(FlowLayout.LEFT));
    84                         pnlActions.setBackground(Color.WHITE);
    85                         for (Action action: issue.getActions()){
    86                                 JButton btn = new JButton(action);
    87                                 pnlActions.add(btn);                           
    88                         }
    89                        
    90                         gc.gridx = 1;                   
    91                         gc.gridy = 1;                   
    92                         gc.fill = GridBagConstraints.HORIZONTAL;
    93                         gc.weighty = 0.0;
    94                         add(pnlActions,gc);
    95                 }       
    96                
    97                 // set the severity icon
    98                 switch(issue.getSeverity()){
    99                 case WARNING:
    100                         lblIcon.setIcon(ImageProvider.get("warning-small"));
    101                         break;
    102                 case ERROR:
    103                         lblIcon.setIcon(ImageProvider.get("error"));
    104                         break;
    105                 }               
    106         }
    107        
    108         /**
    109         * Creates an issue view for an issue.
    110         *
    111         * @param issue the issue. Must not be null.
    112         * @throws IllegalArgumentException thrown if issue is null.
    113         */
    114         public IssueView(Issue issue) throws IllegalArgumentException{
    115                 CheckParameterUtil.ensureParameterNotNull(issue, "issue");
    116                 this.issue = issue;
    117                 build();               
    118         }
     80       
     81        // if there are any actions available to resolve the issue, add a panel with action buttons
     82        if (!issue.getActions().isEmpty()) {
     83            pnlActions = new JPanel(new FlowLayout(FlowLayout.LEFT));
     84            pnlActions.setBackground(Color.WHITE);
     85            for (Action action: issue.getActions()){
     86                JButton btn = new JButton(action);
     87                pnlActions.add(btn);               
     88            }
     89           
     90            gc.gridx = 1;           
     91            gc.gridy = 1;           
     92            gc.fill = GridBagConstraints.HORIZONTAL;
     93            gc.weighty = 0.0;
     94            add(pnlActions,gc);
     95        }   
     96       
     97        // set the severity icon
     98        switch(issue.getSeverity()){
     99        case WARNING:
     100            lblIcon.setIcon(ImageProvider.get("warning-small"));
     101            break;
     102        case ERROR:
     103            lblIcon.setIcon(ImageProvider.get("error"));
     104            break;
     105        }       
     106    }
     107   
     108    /**
     109    * Creates an issue view for an issue.
     110    *
     111    * @param issue the issue. Must not be null.
     112    * @throws IllegalArgumentException thrown if issue is null.
     113    */
     114    public IssueView(Issue issue) throws IllegalArgumentException{
     115        CheckParameterUtil.ensureParameterNotNull(issue, "issue");
     116        this.issue = issue;
     117        build();       
     118    }
    119119
    120         @Override
    121         public Dimension getMinimumSize() {
    122                 return super.getPreferredSize();
    123         }
     120    @Override
     121    public Dimension getMinimumSize() {
     122        return super.getPreferredSize();
     123    }
    124124}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/qa/IssuesModel.java

    r20724 r23192  
    3131 */
    3232public class IssuesModel extends Observable implements Observer{
    33         private final ArrayList<Issue> issues = new ArrayList<Issue>();
    34         private TurnRestrictionEditorModel editorModel;
    35        
    36         /**
    37         * Creates the model
    38         *
    39         * {@code controler} is used in resolution actions for issues in
    40         * this model to direct the user to a specific input field in one
    41         * of the editor tabs in order to fix an issue.
    42         *
    43         * @param editorModel the editor model. Must not be null.
    44         * @throws IllegalArgumentException thrown if controler is null
    45         */
    46         public IssuesModel(TurnRestrictionEditorModel editorModel) throws IllegalArgumentException{
    47                 CheckParameterUtil.ensureParameterNotNull(editorModel, "editorModel");
    48                 this.editorModel = editorModel;
    49                 this.editorModel.addObserver(this);
    50         }
    51        
    52         /**
    53         * Populates the model with a list of issues. Just clears the model
    54         * if {@code issues} is null or empty.
    55         *
    56         * @param issues the list of issues.
    57         */
    58         public void populate(List<Issue> issues){
    59                 this.issues.clear();
    60                 if (issues != null){
    61                         this.issues.addAll(issues);
    62                 }
    63                 setChanged();
    64                 notifyObservers();
    65         }
    66        
    67         /**
    68         * Replies the (unmodifiable) list of issues in this model.
    69         *
    70         * @return the (unmodifiable) list of issues in this model.
    71         */
    72         public List<Issue> getIssues() {
    73                 return Collections.unmodifiableList(issues);
    74         }
    75        
    76         /**
    77         * Replies the turn restriction editor model
    78         *
    79         * @return
    80         */
    81         public TurnRestrictionEditorModel getEditorModel() {
    82                 return editorModel;
    83         }
    84        
    85         /**
    86         * Populates this model with issues derived from the state of the
    87         * turn restriction editor model. If {@code editorModel} is null, the
    88         * list of issues is cleared.
    89         *
    90         * @param editorModel the editor model.
    91         */
    92         public void populate() {
    93                 issues.clear();
    94                 if (editorModel != null) {
    95                         checkTags(editorModel);
    96                         checkFromLeg(editorModel);
    97                         checkToLeg(editorModel);
    98                         checkFromAndToEquals(editorModel);
    99                         checkVias(editorModel);
    100                 }
    101                 setChanged();
    102                 notifyObservers();
    103         }
    104        
    105         /**
    106         * Checks whether there are required tags missing.
    107         *
    108         * @param editorModel
    109         */
    110         protected void checkTags(TurnRestrictionEditorModel editorModel) {
    111                 TagEditorModel tagEditorModel = editorModel.getTagEditorModel();
    112                 TagModel tag = tagEditorModel.get("type");
    113                
    114                 // missing marker tag for a turn restriction
    115                 if (tag == null || ! tag.getValue().trim().equals("restriction")) {
    116                         issues.add(new RequiredTagMissingError(this, "type", "restriction"));
    117                 }
    118                
    119                 // missing or illegal restriction type ?
    120                 tag = tagEditorModel.get("restriction");
    121                 if (tag == null) {
    122                         issues.add(new MissingRestrictionTypeError(this));
    123                 } else if (!TurnRestrictionType.isStandardTagValue(tag.getValue())) {
    124                         issues.add(new IllegalRestrictionTypeError(this, tag.getValue()));
    125                 }
    126 
    127                 // non-standard value for the 'except' tag?
    128                 ExceptValueModel except = getEditorModel().getExcept();
    129                 if (!except.isStandard()) {
    130                         issues.add(new NonStandardExceptWarning(this, except));
    131                 }
    132         }
    133        
    134         /**
    135         * Checks various data integrity restriction for the relation member with
    136         * role 'from'.
    137         *
    138         */
    139         protected void checkFromLeg(TurnRestrictionEditorModel editorModel) {
    140                 Set<OsmPrimitive> froms = editorModel.getTurnRestrictionLeg(TurnRestrictionLegRole.FROM);
    141                 if (froms.isEmpty()){
    142                         issues.add(new MissingTurnRestrictionLegError(this, TurnRestrictionLegRole.FROM));
    143                         return;
    144                 } else if (froms.size() > 1){
    145                         issues.add(new MultipleTurnRestrictionLegError(this, TurnRestrictionLegRole.FROM, froms.size()));
    146                         return;
    147                 }
    148                 OsmPrimitive p = froms.iterator().next();
    149                 if (! (p instanceof Way)) {
    150                         issues.add(new WrongTurnRestrictionLegTypeError(this, TurnRestrictionLegRole.FROM, p));
    151                 }
    152         }
    153        
    154         /**
    155         * Checks various data integrity restriction for the relation member with
    156         * role 'to'.
    157         *
    158         */
    159         protected void checkToLeg(TurnRestrictionEditorModel editorModel) {
    160                 Set<OsmPrimitive> toLegs = editorModel.getTurnRestrictionLeg(TurnRestrictionLegRole.TO);
    161                 if (toLegs.isEmpty()){
    162                         issues.add(new MissingTurnRestrictionLegError(this, TurnRestrictionLegRole.TO));
    163                         return;
    164                 } else if (toLegs.size() > 1){
    165                         issues.add(new MultipleTurnRestrictionLegError(this, TurnRestrictionLegRole.TO, toLegs.size()));
    166                         return;
    167                 }
    168                 OsmPrimitive p = toLegs.iterator().next();
    169                 if (! (p instanceof Way)) {
    170                         issues.add(new WrongTurnRestrictionLegTypeError(this, TurnRestrictionLegRole.TO, p));
    171                 }
    172         }
    173        
    174         /**
    175         * Creates an issue if this turn restriction has identical 'from' and to'.
    176         *
    177         * @param editorModel
    178         */
    179         protected void checkFromAndToEquals(TurnRestrictionEditorModel editorModel){
    180                 Set<OsmPrimitive> toLegs = editorModel.getTurnRestrictionLeg(TurnRestrictionLegRole.TO);
    181                 Set<OsmPrimitive> fromLegs = editorModel.getTurnRestrictionLeg(TurnRestrictionLegRole.FROM);
    182                 if (toLegs.size() != 1 || fromLegs.size() != 1) return;
    183                
    184                 OsmPrimitive from = fromLegs.iterator().next();
    185                 OsmPrimitive to = toLegs.iterator().next();
    186                
    187                 if (! (from instanceof Way)) return;
    188                 if (! (to instanceof Way)) return;
    189                 if (from.equals(to) && ! "no_u_turn".equals(editorModel.getRestrictionTagValue())){
    190                         // identical from and to allowed for "no_u_turn" only
    191                         //
    192                         issues.add(new IdenticalTurnRestrictionLegsError(this, from));
    193                 }               
    194         }
    195        
    196         protected Node getNodeAtIntersection(Way from, Way to){
    197                 Set<Node> fromNodes = new HashSet<Node>(from.getNodes());
    198                 fromNodes.retainAll(to.getNodes());
    199                 if (fromNodes.size() == 1){
    200                         return fromNodes.iterator().next();
    201                 } else {
    202                         return null;
    203                 }
    204         }
    205        
    206         /**
    207         * Checks the 'via' members in the turn restriction
    208         *
    209         * @param editorModel the editor model
    210         */
    211         protected void checkVias(TurnRestrictionEditorModel editorModel){
    212                 Set<OsmPrimitive> toLegs = editorModel.getTurnRestrictionLeg(TurnRestrictionLegRole.TO);
    213                 Set<OsmPrimitive> fromLegs = editorModel.getTurnRestrictionLeg(TurnRestrictionLegRole.FROM);
    214                 // we only check vias if 'to' and 'from' are already OK
    215                 if (toLegs.size() != 1 || fromLegs.size() != 1) return;
    216                 if (! (toLegs.iterator().next() instanceof Way)) return;
    217                 if (! (fromLegs.iterator().next() instanceof Way)) return;
    218                
    219                 Way from = (Way)fromLegs.iterator().next();
    220                 Way to = (Way)toLegs.iterator().next();
    221                 Node intersect = getNodeAtIntersection(from, to);
    222                 if (intersect != null){
    223                         if (!editorModel.getVias().contains(intersect)) {
    224                                 issues.add(new IntersectionMissingAsViaError(this, from, to, intersect));
    225                         }
    226                 }
    227                
    228                 // 'from' intersects with 'to' - should be split 
    229                 if (intersect != null && from.getNode(0) != intersect && from.getNode(from.getNodesCount()-1) != intersect){
    230                         issues.add(new TurnRestrictionLegSplitRequiredError(this, TurnRestrictionLegRole.FROM, from, to, intersect));
    231                 }
    232                 // 'to' intersects with 'from' - should be split
    233                 if (intersect != null && to.getNode(0) != intersect && to.getNode(to.getNodesCount()-1) != intersect){
    234                         issues.add(new TurnRestrictionLegSplitRequiredError(this, TurnRestrictionLegRole.TO, from, to, intersect));
    235                 }               
    236         }
    237        
    238         public NavigationControler getNavigationControler() {
    239                 return editorModel.getNavigationControler();
    240         }
    241        
    242         public int getNumWarnings() {
    243                 int ret = 0;
    244                 for (Issue issue: issues){
    245                         if (issue.getSeverity().equals(Severity.WARNING)) ret++;
    246                 }
    247                 return ret;
    248         }
    249 
    250         public int getNumErrors() {
    251                 int ret = 0;
    252                 for (Issue issue: issues){
    253                         if (issue.getSeverity().equals(Severity.ERROR)) ret++;
    254                 }
    255                 return ret;
    256         }
    257 
    258         /* ------------------------------------------------------------------------------------- */
    259         /* interface Observer                                                                    */
    260         /* ------------------------------------------------------------------------------------- */
    261         public void update(Observable o, Object arg) {
    262                 populate();             
    263         }
     33    private final ArrayList<Issue> issues = new ArrayList<Issue>();
     34    private TurnRestrictionEditorModel editorModel;
     35   
     36    /**
     37    * Creates the model
     38    *
     39    * {@code controler} is used in resolution actions for issues in
     40    * this model to direct the user to a specific input field in one
     41    * of the editor tabs in order to fix an issue.
     42    *
     43    * @param editorModel the editor model. Must not be null.
     44    * @throws IllegalArgumentException thrown if controler is null
     45    */
     46    public IssuesModel(TurnRestrictionEditorModel editorModel) throws IllegalArgumentException{
     47        CheckParameterUtil.ensureParameterNotNull(editorModel, "editorModel");
     48        this.editorModel = editorModel;
     49        this.editorModel.addObserver(this);
     50    }
     51   
     52    /**
     53    * Populates the model with a list of issues. Just clears the model
     54    * if {@code issues} is null or empty.
     55    *
     56    * @param issues the list of issues.
     57    */
     58    public void populate(List<Issue> issues){
     59        this.issues.clear();
     60        if (issues != null){
     61            this.issues.addAll(issues);
     62        }
     63        setChanged();
     64        notifyObservers();
     65    }
     66   
     67    /**
     68    * Replies the (unmodifiable) list of issues in this model.
     69    *
     70    * @return the (unmodifiable) list of issues in this model.
     71    */
     72    public List<Issue> getIssues() {
     73        return Collections.unmodifiableList(issues);
     74    }
     75   
     76    /**
     77    * Replies the turn restriction editor model
     78    *
     79    * @return
     80    */
     81    public TurnRestrictionEditorModel getEditorModel() {
     82        return editorModel;
     83    }
     84   
     85    /**
     86    * Populates this model with issues derived from the state of the
     87    * turn restriction editor model. If {@code editorModel} is null, the
     88    * list of issues is cleared.
     89    *
     90    * @param editorModel the editor model.
     91    */
     92    public void populate() {
     93        issues.clear();
     94        if (editorModel != null) {
     95            checkTags(editorModel);
     96            checkFromLeg(editorModel);
     97            checkToLeg(editorModel);
     98            checkFromAndToEquals(editorModel);
     99            checkVias(editorModel);
     100        }
     101        setChanged();
     102        notifyObservers();
     103    }
     104   
     105    /**
     106    * Checks whether there are required tags missing.
     107    *
     108    * @param editorModel
     109    */
     110    protected void checkTags(TurnRestrictionEditorModel editorModel) {
     111        TagEditorModel tagEditorModel = editorModel.getTagEditorModel();
     112        TagModel tag = tagEditorModel.get("type");
     113       
     114        // missing marker tag for a turn restriction
     115        if (tag == null || ! tag.getValue().trim().equals("restriction")) {
     116            issues.add(new RequiredTagMissingError(this, "type", "restriction"));
     117        }
     118       
     119        // missing or illegal restriction type ?
     120        tag = tagEditorModel.get("restriction");
     121        if (tag == null) {
     122            issues.add(new MissingRestrictionTypeError(this));
     123        } else if (!TurnRestrictionType.isStandardTagValue(tag.getValue())) {
     124            issues.add(new IllegalRestrictionTypeError(this, tag.getValue()));
     125        }
     126
     127        // non-standard value for the 'except' tag?
     128        ExceptValueModel except = getEditorModel().getExcept();
     129        if (!except.isStandard()) {
     130            issues.add(new NonStandardExceptWarning(this, except));
     131        }
     132    }
     133   
     134    /**
     135    * Checks various data integrity restriction for the relation member with
     136    * role 'from'.
     137    *
     138    */
     139    protected void checkFromLeg(TurnRestrictionEditorModel editorModel) {
     140        Set<OsmPrimitive> froms = editorModel.getTurnRestrictionLeg(TurnRestrictionLegRole.FROM);
     141        if (froms.isEmpty()){
     142            issues.add(new MissingTurnRestrictionLegError(this, TurnRestrictionLegRole.FROM));
     143            return;
     144        } else if (froms.size() > 1){
     145            issues.add(new MultipleTurnRestrictionLegError(this, TurnRestrictionLegRole.FROM, froms.size()));
     146            return;
     147        }
     148        OsmPrimitive p = froms.iterator().next();
     149        if (! (p instanceof Way)) {
     150            issues.add(new WrongTurnRestrictionLegTypeError(this, TurnRestrictionLegRole.FROM, p));
     151        }
     152    }
     153   
     154    /**
     155    * Checks various data integrity restriction for the relation member with
     156    * role 'to'.
     157    *
     158    */
     159    protected void checkToLeg(TurnRestrictionEditorModel editorModel) {
     160        Set<OsmPrimitive> toLegs = editorModel.getTurnRestrictionLeg(TurnRestrictionLegRole.TO);
     161        if (toLegs.isEmpty()){
     162            issues.add(new MissingTurnRestrictionLegError(this, TurnRestrictionLegRole.TO));
     163            return;
     164        } else if (toLegs.size() > 1){
     165            issues.add(new MultipleTurnRestrictionLegError(this, TurnRestrictionLegRole.TO, toLegs.size()));
     166            return;
     167        }
     168        OsmPrimitive p = toLegs.iterator().next();
     169        if (! (p instanceof Way)) {
     170            issues.add(new WrongTurnRestrictionLegTypeError(this, TurnRestrictionLegRole.TO, p));
     171        }
     172    }
     173   
     174    /**
     175    * Creates an issue if this turn restriction has identical 'from' and to'.
     176    *
     177    * @param editorModel
     178    */
     179    protected void checkFromAndToEquals(TurnRestrictionEditorModel editorModel){
     180        Set<OsmPrimitive> toLegs = editorModel.getTurnRestrictionLeg(TurnRestrictionLegRole.TO);
     181        Set<OsmPrimitive> fromLegs = editorModel.getTurnRestrictionLeg(TurnRestrictionLegRole.FROM);
     182        if (toLegs.size() != 1 || fromLegs.size() != 1) return;
     183       
     184        OsmPrimitive from = fromLegs.iterator().next();
     185        OsmPrimitive to = toLegs.iterator().next();
     186       
     187        if (! (from instanceof Way)) return;
     188        if (! (to instanceof Way)) return;
     189        if (from.equals(to) && ! "no_u_turn".equals(editorModel.getRestrictionTagValue())){
     190            // identical from and to allowed for "no_u_turn" only
     191            //
     192            issues.add(new IdenticalTurnRestrictionLegsError(this, from));
     193        }       
     194    }
     195   
     196    protected Node getNodeAtIntersection(Way from, Way to){
     197        Set<Node> fromNodes = new HashSet<Node>(from.getNodes());
     198        fromNodes.retainAll(to.getNodes());
     199        if (fromNodes.size() == 1){
     200            return fromNodes.iterator().next();
     201        } else {
     202            return null;
     203        }
     204    }
     205   
     206    /**
     207    * Checks the 'via' members in the turn restriction
     208    *
     209    * @param editorModel the editor model
     210    */
     211    protected void checkVias(TurnRestrictionEditorModel editorModel){
     212        Set<OsmPrimitive> toLegs = editorModel.getTurnRestrictionLeg(TurnRestrictionLegRole.TO);
     213        Set<OsmPrimitive> fromLegs = editorModel.getTurnRestrictionLeg(TurnRestrictionLegRole.FROM);
     214        // we only check vias if 'to' and 'from' are already OK
     215        if (toLegs.size() != 1 || fromLegs.size() != 1) return;
     216        if (! (toLegs.iterator().next() instanceof Way)) return;
     217        if (! (fromLegs.iterator().next() instanceof Way)) return;
     218       
     219        Way from = (Way)fromLegs.iterator().next();
     220        Way to = (Way)toLegs.iterator().next();
     221        Node intersect = getNodeAtIntersection(from, to);
     222        if (intersect != null){
     223            if (!editorModel.getVias().contains(intersect)) {
     224                issues.add(new IntersectionMissingAsViaError(this, from, to, intersect));
     225            }
     226        }
     227       
     228        // 'from' intersects with 'to' - should be split 
     229        if (intersect != null && from.getNode(0) != intersect && from.getNode(from.getNodesCount()-1) != intersect){
     230            issues.add(new TurnRestrictionLegSplitRequiredError(this, TurnRestrictionLegRole.FROM, from, to, intersect));
     231        }
     232        // 'to' intersects with 'from' - should be split
     233        if (intersect != null && to.getNode(0) != intersect && to.getNode(to.getNodesCount()-1) != intersect){
     234            issues.add(new TurnRestrictionLegSplitRequiredError(this, TurnRestrictionLegRole.TO, from, to, intersect));
     235        }       
     236    }
     237   
     238    public NavigationControler getNavigationControler() {
     239        return editorModel.getNavigationControler();
     240    }
     241   
     242    public int getNumWarnings() {
     243        int ret = 0;
     244        for (Issue issue: issues){
     245            if (issue.getSeverity().equals(Severity.WARNING)) ret++;
     246        }
     247        return ret;
     248    }
     249
     250    public int getNumErrors() {
     251        int ret = 0;
     252        for (Issue issue: issues){
     253            if (issue.getSeverity().equals(Severity.ERROR)) ret++;
     254        }
     255        return ret;
     256    }
     257
     258    /* ------------------------------------------------------------------------------------- */
     259    /* interface Observer                                                                    */
     260    /* ------------------------------------------------------------------------------------- */
     261    public void update(Observable o, Object arg) {
     262        populate();     
     263    }
    264264}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/qa/IssuesView.java

    r20735 r23192  
    1717 */
    1818public class IssuesView extends VerticallyScrollablePanel implements Observer{
    19         static private final Logger logger = Logger.getLogger(IssuesView.class.getName());
    20        
    21         /** the issues model */
    22         private IssuesModel model;
    23        
    24         protected void build(){
    25                 setLayout(new GridBagLayout());
    26         }
    27        
    28         /**
    29         * Creates the view
    30         *
    31         * @param model the model. Must not be null.
    32         * @exception IllegalArgumentException thrown if model is null
    33         */
    34         public IssuesView(IssuesModel model) throws IllegalArgumentException{
    35                 CheckParameterUtil.ensureParameterNotNull(model, "model");
    36                 this.model = model;
    37                 model.addObserver(this);
    38                 build();
    39                 HelpUtil.setHelpContext(this, HelpUtil.ht("/Plugins/turnrestrictions#ErrorsAndWarnings"));
    40         }
    41        
    42         /**
    43         * Refreshes the view with the current state in the model
    44         */
    45         public void refresh() {
    46                 removeAll();
    47                 if (! model.getIssues().isEmpty()){
    48                         GridBagConstraints gc = new GridBagConstraints();
    49                         gc.anchor = GridBagConstraints.NORTHWEST;
    50                         gc.fill = GridBagConstraints.HORIZONTAL;
    51                         gc.weightx = 1.0;
    52                         gc.weighty = 0.0;
    53                         gc.gridx = 0;
    54                         gc.gridy = 0;
    55                         for (Issue issue: model.getIssues()){
    56                                 add(new IssueView(issue), gc);
    57                                 gc.gridy++;
    58                         }
    59                         // filler - grabs remaining space
    60                         gc.weighty = 1.0;                       
    61                         add(new JPanel(), gc);
    62                 }
    63                 invalidate();
    64         }
     19    static private final Logger logger = Logger.getLogger(IssuesView.class.getName());
     20   
     21    /** the issues model */
     22    private IssuesModel model;
     23   
     24    protected void build(){
     25        setLayout(new GridBagLayout());
     26    }
     27   
     28    /**
     29    * Creates the view
     30    *
     31    * @param model the model. Must not be null.
     32    * @exception IllegalArgumentException thrown if model is null
     33    */
     34    public IssuesView(IssuesModel model) throws IllegalArgumentException{
     35        CheckParameterUtil.ensureParameterNotNull(model, "model");
     36        this.model = model;
     37        model.addObserver(this);
     38        build();
     39        HelpUtil.setHelpContext(this, HelpUtil.ht("/Plugins/turnrestrictions#ErrorsAndWarnings"));
     40    }
     41   
     42    /**
     43    * Refreshes the view with the current state in the model
     44    */
     45    public void refresh() {
     46        removeAll();
     47        if (! model.getIssues().isEmpty()){
     48            GridBagConstraints gc = new GridBagConstraints();
     49            gc.anchor = GridBagConstraints.NORTHWEST;
     50            gc.fill = GridBagConstraints.HORIZONTAL;
     51            gc.weightx = 1.0;
     52            gc.weighty = 0.0;
     53            gc.gridx = 0;
     54            gc.gridy = 0;
     55            for (Issue issue: model.getIssues()){
     56                add(new IssueView(issue), gc);
     57                gc.gridy++;
     58            }
     59            // filler - grabs remaining space
     60            gc.weighty = 1.0;           
     61            add(new JPanel(), gc);
     62        }
     63        invalidate();
     64    }
    6565
    66         /* ------------------------------------------------------------------------------- */
    67         /* interface Observer                                                              */
    68         /* ------------------------------------------------------------------------------- */
    69         public void update(Observable o, Object arg) {
    70                 refresh();             
    71         }
     66    /* ------------------------------------------------------------------------------- */
     67    /* interface Observer                                                              */
     68    /* ------------------------------------------------------------------------------- */
     69    public void update(Observable o, Object arg) {
     70        refresh();     
     71    }
    7272}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/qa/MissingRestrictionTypeError.java

    r20586 r23192  
    1515 */
    1616public class MissingRestrictionTypeError extends Issue{
    17        
    18         public MissingRestrictionTypeError(IssuesModel parent) {
    19                 super(parent, Severity.ERROR);
    20                 actions.add(new FixInEditorAction());
    21         }
     17   
     18    public MissingRestrictionTypeError(IssuesModel parent) {
     19        super(parent, Severity.ERROR);
     20        actions.add(new FixInEditorAction());
     21    }
    2222
    23         @Override
    24         public String getText() {
    25                 return tr("A turn restriction must declare the type of restriction. Please select a type in the Basic Editor.");                               
    26         }
    27        
    28         class FixInEditorAction extends AbstractAction {
    29                 public FixInEditorAction() {
    30                         putValue(NAME, tr("Fix in editor"));
    31                         putValue(SHORT_DESCRIPTION, tr("Go to Basic Editor and manually choose a turn restriction type"));
    32                 }
    33                 public void actionPerformed(ActionEvent e) {
    34                         getIssuesModel().getNavigationControler().gotoBasicEditor(NavigationControler.BasicEditorFokusTargets.RESTRICION_TYPE);                 
    35                 }               
    36         }
     23    @Override
     24    public String getText() {
     25        return tr("A turn restriction must declare the type of restriction. Please select a type in the Basic Editor.");               
     26    }
     27   
     28    class FixInEditorAction extends AbstractAction {
     29        public FixInEditorAction() {
     30            putValue(NAME, tr("Fix in editor"));
     31            putValue(SHORT_DESCRIPTION, tr("Go to Basic Editor and manually choose a turn restriction type"));
     32        }
     33        public void actionPerformed(ActionEvent e) {
     34            getIssuesModel().getNavigationControler().gotoBasicEditor(NavigationControler.BasicEditorFokusTargets.RESTRICION_TYPE);         
     35        }       
     36    }
    3737}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/qa/MissingTurnRestrictionLegError.java

    r20633 r23192  
    1515 */
    1616public class MissingTurnRestrictionLegError extends Issue {
    17         private TurnRestrictionLegRole role;
     17    private TurnRestrictionLegRole role;
    1818
    19         /**
    20         * Creates the issue.
    21         *
    22         * @param parent the parent model
    23         * @param role the role of the missing way
    24         */
    25         public MissingTurnRestrictionLegError(IssuesModel parent, TurnRestrictionLegRole role) {
    26                 super(parent, Severity.ERROR);
    27                 this.role = role;
    28                 actions.add(new FixAction());
    29         }
     19    /**
     20    * Creates the issue.
     21    *
     22    * @param parent the parent model
     23    * @param role the role of the missing way
     24    */
     25    public MissingTurnRestrictionLegError(IssuesModel parent, TurnRestrictionLegRole role) {
     26        super(parent, Severity.ERROR);
     27        this.role = role;
     28        actions.add(new FixAction());
     29    }
    3030
    31         @Override
    32         public String getText() {
    33                 String msg = "";
    34                 switch(role){
    35                 case FROM:
    36                         msg = tr("An OSM way with role <tt>from</tt> is required in a turn restriction.");
    37                         break;
    38                 case TO:
    39                         msg = tr("An OSM way with role <tt>to</tt> is required in a turn restriction.");
    40                         break;
    41                 }
    42                 msg += " " + tr("Please go to the Basic editor and manually choose an OSM way.");
    43                 return msg;
    44         }
     31    @Override
     32    public String getText() {
     33        String msg = "";
     34        switch(role){
     35        case FROM:
     36            msg = tr("An OSM way with role <tt>from</tt> is required in a turn restriction.");
     37            break;
     38        case TO:
     39            msg = tr("An OSM way with role <tt>to</tt> is required in a turn restriction.");
     40            break;
     41        }
     42        msg += " " + tr("Please go to the Basic editor and manually choose an OSM way.");
     43        return msg;
     44    }
    4545
    46         class FixAction extends AbstractAction {
    47                 public FixAction() {
    48                         putValue(NAME, tr("Add in editor"));
    49                         switch(role){
    50                         case FROM:
    51                                 putValue(SHORT_DESCRIPTION, tr("Add an OSM way with role ''from''"));
    52                                 break;
    53                         case TO:
    54                                 putValue(SHORT_DESCRIPTION, tr("Add an OSM way with role ''to''"));
    55                                 break;                         
    56                         }                       
    57                 }
    58                 public void actionPerformed(ActionEvent e) {
    59                         switch(role){
    60                         case FROM:
    61                                 getIssuesModel().getNavigationControler().gotoBasicEditor(FROM);
    62                                 break;
    63                         case TO:
    64                                 getIssuesModel().getNavigationControler().gotoBasicEditor(TO);
    65                                 break;                         
    66                         }                       
    67                 }               
    68         }
     46    class FixAction extends AbstractAction {
     47        public FixAction() {
     48            putValue(NAME, tr("Add in editor"));
     49            switch(role){
     50            case FROM:
     51                putValue(SHORT_DESCRIPTION, tr("Add an OSM way with role ''from''"));
     52                break;
     53            case TO:
     54                putValue(SHORT_DESCRIPTION, tr("Add an OSM way with role ''to''"));
     55                break;             
     56            }           
     57        }
     58        public void actionPerformed(ActionEvent e) {
     59            switch(role){
     60            case FROM:
     61                getIssuesModel().getNavigationControler().gotoBasicEditor(FROM);
     62                break;
     63            case TO:
     64                getIssuesModel().getNavigationControler().gotoBasicEditor(TO);
     65                break;             
     66            }           
     67        }       
     68    }
    6969}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/qa/MultipleTurnRestrictionLegError.java

    r20701 r23192  
    1414 */
    1515public class MultipleTurnRestrictionLegError extends Issue {
    16         private TurnRestrictionLegRole role;
    17         private int numLegs;
    18        
    19         /**
    20         * Create the issue
    21         *
    22         * @param parent the parent model
    23         * @param role the role of the turn restriction leg with multiple entries
    24         * @param numLegs the number of legs
    25         */
    26         public MultipleTurnRestrictionLegError(IssuesModel parent, TurnRestrictionLegRole role, int numLegs) {
    27                 super(parent, Severity.ERROR);
    28                 this.role = role;
    29                 this.numLegs = numLegs;
    30                 actions.add(new FixAction());
    31         }
     16    private TurnRestrictionLegRole role;
     17    private int numLegs;
     18   
     19    /**
     20    * Create the issue
     21    *
     22    * @param parent the parent model
     23    * @param role the role of the turn restriction leg with multiple entries
     24    * @param numLegs the number of legs
     25    */
     26    public MultipleTurnRestrictionLegError(IssuesModel parent, TurnRestrictionLegRole role, int numLegs) {
     27        super(parent, Severity.ERROR);
     28        this.role = role;
     29        this.numLegs = numLegs;
     30        actions.add(new FixAction());
     31    }
    3232
    33         @Override
    34         public String getText() {
    35                 switch(role){
    36                 case FROM: 
    37                         return tr("A turn restriction requires exactly one way with role <tt>from</tt>. "
    38                                 + "This turn restriction has {0} ways in this role. Please remove "
    39                                 + "{1} of them.",
    40                                 numLegs,
    41                                 numLegs -1
    42                         );
    43                 case TO:
    44                         return tr("A turn restriction requires exactly one way with role <tt>to</tt>. "
    45                                         + "This turn restriction has {0} ways in this role. Please remove "
    46                                         + "{1} of them.",
    47                                         numLegs,
    48                                         numLegs -1
    49                                 );
    50                 }
    51                 return "";
    52         }
     33    @Override
     34    public String getText() {
     35        switch(role){
     36        case FROM: 
     37            return tr("A turn restriction requires exactly one way with role <tt>from</tt>. "
     38                + "This turn restriction has {0} ways in this role. Please remove "
     39                + "{1} of them.",
     40                numLegs,
     41                numLegs -1
     42            );
     43        case TO:
     44            return tr("A turn restriction requires exactly one way with role <tt>to</tt>. "
     45                    + "This turn restriction has {0} ways in this role. Please remove "
     46                    + "{1} of them.",
     47                    numLegs,
     48                    numLegs -1
     49                );
     50        }
     51        return "";
     52    }
    5353
    54         class FixAction extends AbstractAction {
    55                 public FixAction() {
    56                         putValue(NAME, tr("Fix in editor"));
    57                         putValue(SHORT_DESCRIPTION, tr("Go to the Advanced Editor and remove the members"));
    58                 }
    59                 public void actionPerformed(ActionEvent e) {
    60                         getIssuesModel().getNavigationControler().gotoAdvancedEditor();
    61                 }               
    62         }
     54    class FixAction extends AbstractAction {
     55        public FixAction() {
     56            putValue(NAME, tr("Fix in editor"));
     57            putValue(SHORT_DESCRIPTION, tr("Go to the Advanced Editor and remove the members"));
     58        }
     59        public void actionPerformed(ActionEvent e) {
     60            getIssuesModel().getNavigationControler().gotoAdvancedEditor();
     61        }       
     62    }
    6363}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/qa/NonStandardExceptWarning.java

    r20586 r23192  
    1414 */
    1515public class NonStandardExceptWarning extends Issue{
    16         private ExceptValueModel value;
    17         public NonStandardExceptWarning(IssuesModel parent, ExceptValueModel value) {
    18                 super(parent, Severity.WARNING);
    19                 actions.add(new FixInEditorAction());
    20                 this.value  = value;
    21         }
     16    private ExceptValueModel value;
     17    public NonStandardExceptWarning(IssuesModel parent, ExceptValueModel value) {
     18        super(parent, Severity.WARNING);
     19        actions.add(new FixInEditorAction());
     20        this.value  = value;
     21    }
    2222
    23         @Override
    24         public String getText() {               
    25                 return tr("The tag <tt>except</tt> has the non-standard value <tt>{0}</tt>. "
    26                                 + "It is recommended to use standard values for <tt>except</tt> only.",
    27                                 value.getValue()
    28                                 );                             
    29         }
    30        
    31         class FixInEditorAction extends AbstractAction {
    32                 public FixInEditorAction() {
    33                         putValue(NAME, tr("Fix in editor"));
    34                         putValue(SHORT_DESCRIPTION, tr("Go to Basic Editor and select standard vehicle type based exceptions"));
    35                 }
    36                 public void actionPerformed(ActionEvent e) {
    37                         getIssuesModel().getNavigationControler().gotoBasicEditor();           
    38                 }               
    39         }
     23    @Override
     24    public String getText() {       
     25        return tr("The tag <tt>except</tt> has the non-standard value <tt>{0}</tt>. "
     26                + "It is recommended to use standard values for <tt>except</tt> only.",
     27                value.getValue()
     28                );             
     29    }
     30   
     31    class FixInEditorAction extends AbstractAction {
     32        public FixInEditorAction() {
     33            putValue(NAME, tr("Fix in editor"));
     34            putValue(SHORT_DESCRIPTION, tr("Go to Basic Editor and select standard vehicle type based exceptions"));
     35        }
     36        public void actionPerformed(ActionEvent e) {
     37            getIssuesModel().getNavigationControler().gotoBasicEditor();       
     38        }       
     39    }
    4040}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/qa/RequiredTagMissingError.java

    r20586 r23192  
    1515 */
    1616public class RequiredTagMissingError extends Issue {
    17         static private final Logger logger = Logger.getLogger(RequiredTagMissingError.class.getName());
    18         private String tagKey;
    19         private String tagValue;
    20        
    21         /**
    22         * Create the issue
    23         *
    24         * @param parent the issues model
    25         * @param tagKey the tag key
    26         * @param tagValue the tag value
    27         */
    28         public RequiredTagMissingError(IssuesModel parent, String tagKey, String tagValue) {
    29                 super(parent, Severity.ERROR);
    30                 this.tagKey = tagKey;
    31                 this.tagValue = tagValue;
    32                 actions.add(new AddTagAction());
    33         }
     17    static private final Logger logger = Logger.getLogger(RequiredTagMissingError.class.getName());
     18    private String tagKey;
     19    private String tagValue;
     20   
     21    /**
     22    * Create the issue
     23    *
     24    * @param parent the issues model
     25    * @param tagKey the tag key
     26    * @param tagValue the tag value
     27    */
     28    public RequiredTagMissingError(IssuesModel parent, String tagKey, String tagValue) {
     29        super(parent, Severity.ERROR);
     30        this.tagKey = tagKey;
     31        this.tagValue = tagValue;
     32        actions.add(new AddTagAction());
     33    }
    3434
    35         @Override
    36         public String getText() {       
    37                 return tr("The required tag <tt>{0}={1}</tt> is missing.",                             
    38                                 this.tagKey,
    39                                 this.tagValue
    40                 );
    41         }
     35    @Override
     36    public String getText() {   
     37        return tr("The required tag <tt>{0}={1}</tt> is missing.",             
     38                this.tagKey,
     39                this.tagValue
     40        );
     41    }
    4242
    43         private class AddTagAction extends AbstractAction {
    44                 public AddTagAction(){
    45                         putValue(NAME,tr("Add missing tag"));
    46                         putValue(SHORT_DESCRIPTION, tr("Add the missing tag {0}={1}", tagKey, tagValue));               
    47                 }
    48                
    49                 public void actionPerformed(ActionEvent e) {
    50                         TagEditorModel model = getIssuesModel().getEditorModel().getTagEditorModel();
    51                         TagModel t = model.get(tagKey);
    52                         if (t == null){
    53                                 t = new TagModel(tagKey, tagValue);
    54                                 model.prepend(t);
    55                         }                       
    56                 }               
    57         }
     43    private class AddTagAction extends AbstractAction {
     44        public AddTagAction(){
     45            putValue(NAME,tr("Add missing tag"));
     46            putValue(SHORT_DESCRIPTION, tr("Add the missing tag {0}={1}", tagKey, tagValue));       
     47        }
     48       
     49        public void actionPerformed(ActionEvent e) {
     50            TagEditorModel model = getIssuesModel().getEditorModel().getTagEditorModel();
     51            TagModel t = model.get(tagKey);
     52            if (t == null){
     53                t = new TagModel(tagKey, tagValue);
     54                model.prepend(t);
     55            }           
     56        }       
     57    }
    5858}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/qa/Severity.java

    r20586 r23192  
    22
    33public enum Severity {
    4         WARNING,
    5         ERROR
     4    WARNING,
     5    ERROR
    66}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/qa/TurnRestrictionLegSplitRequiredError.java

    r22477 r23192  
    2323 */
    2424public class TurnRestrictionLegSplitRequiredError extends Issue{
    25         private TurnRestrictionLegRole role;
    26         private Way from;
    27         private Way to;
    28         private Node interesect;
     25    private TurnRestrictionLegRole role;
     26    private Way from;
     27    private Way to;
     28    private Node interesect;
    2929
    30         /**
    31         * Create the issue
    32         *
    33         * @param parent the parent model
    34         * @param role the role of the way which should be splitted
    35         * @param from the way with role 'from'
    36         * @param to the way with role 'to'
    37         * @param interesect the node at the intersection
    38         */
    39         public TurnRestrictionLegSplitRequiredError(IssuesModel parent, TurnRestrictionLegRole role, Way from, Way to, Node intersect) {
    40                 super(parent, Severity.ERROR);
    41                 this.role = role;
    42                 this.from = from;
    43                 this.to = to;
    44                 this.interesect = intersect;
    45                 actions.add(new SplitAction());
    46         }
     30    /**
     31    * Create the issue
     32    *
     33    * @param parent the parent model
     34    * @param role the role of the way which should be splitted
     35    * @param from the way with role 'from'
     36    * @param to the way with role 'to'
     37    * @param interesect the node at the intersection
     38    */
     39    public TurnRestrictionLegSplitRequiredError(IssuesModel parent, TurnRestrictionLegRole role, Way from, Way to, Node intersect) {
     40        super(parent, Severity.ERROR);
     41        this.role = role;
     42        this.from = from;
     43        this.to = to;
     44        this.interesect = intersect;
     45        actions.add(new SplitAction());
     46    }
    4747
    48         @Override
    49         public String getText() {
    50                 String msg = null;
    51                 switch(role){
    52                 case FROM:
    53                         msg = tr("The OSM way <span class=\"object-name\">{0}</span> with role <tt>{1}</tt> should be split "
    54                                 + "at node <span class=\"object-name\">{2}</span> where it connects to way <span class=\"object-name\">{3}</span>.",
    55                                 from.getDisplayName(DefaultNameFormatter.getInstance()),
    56                                 role.getOsmRole(),
    57                                 interesect.getDisplayName(DefaultNameFormatter.getInstance()),
    58                                 to.getDisplayName(DefaultNameFormatter.getInstance())
    59                         );
    60                         break;
    61                 case TO:
    62                         msg = tr("The OSM way <span class=\"object-name\">{0}</span> with role <tt>{1}</tt> should be split "
    63                                         + "at node <span class=\"object-name\">{2}</span> where it connects to way <span class=\"object-name\">{3}</span>.",
    64                                         to.getDisplayName(DefaultNameFormatter.getInstance()),
    65                                         role.getOsmRole(),
    66                                         interesect.getDisplayName(DefaultNameFormatter.getInstance()),
    67                                         from.getDisplayName(DefaultNameFormatter.getInstance())
    68                                 );
    69                         break;
    70                 }
    71                 return msg;
    72         }
     48    @Override
     49    public String getText() {
     50        String msg = null;
     51        switch(role){
     52        case FROM:
     53            msg = tr("The OSM way <span class=\"object-name\">{0}</span> with role <tt>{1}</tt> should be split "
     54                + "at node <span class=\"object-name\">{2}</span> where it connects to way <span class=\"object-name\">{3}</span>.",
     55                from.getDisplayName(DefaultNameFormatter.getInstance()),
     56                role.getOsmRole(),
     57                interesect.getDisplayName(DefaultNameFormatter.getInstance()),
     58                to.getDisplayName(DefaultNameFormatter.getInstance())
     59            );
     60            break;
     61        case TO:
     62            msg = tr("The OSM way <span class=\"object-name\">{0}</span> with role <tt>{1}</tt> should be split "
     63                    + "at node <span class=\"object-name\">{2}</span> where it connects to way <span class=\"object-name\">{3}</span>.",
     64                    to.getDisplayName(DefaultNameFormatter.getInstance()),
     65                    role.getOsmRole(),
     66                    interesect.getDisplayName(DefaultNameFormatter.getInstance()),
     67                    from.getDisplayName(DefaultNameFormatter.getInstance())
     68                );
     69            break;
     70        }
     71        return msg;
     72    }
    7373
    74         class SplitAction extends AbstractAction {
    75                 public SplitAction() {
    76                         putValue(NAME, tr("Split now"));
    77                         putValue(SHORT_DESCRIPTION, tr("Splits the way"));
    78                 }
    79                 public void actionPerformed(ActionEvent e) {
    80                         Way way = null;
    81                         switch(role){
    82                         case FROM: way = from; break;
    83                         case TO: way = to; break;
    84                         }
    85                         SplitWayResult result = SplitWayAction.split(
    86                                         parent.getEditorModel().getLayer(),
    87                                         way,
    88                                         Collections.singletonList(interesect),
    89                                         Collections.<OsmPrimitive>emptyList()
    90                         );
    91                         if (result != null){
    92                                 Main.main.undoRedo.add(result.getCommand());
    93                         }
    94                 }
    95         }
     74    class SplitAction extends AbstractAction {
     75        public SplitAction() {
     76            putValue(NAME, tr("Split now"));
     77            putValue(SHORT_DESCRIPTION, tr("Splits the way"));
     78        }
     79        public void actionPerformed(ActionEvent e) {
     80            Way way = null;
     81            switch(role){
     82            case FROM: way = from; break;
     83            case TO: way = to; break;
     84            }
     85            SplitWayResult result = SplitWayAction.split(
     86                    parent.getEditorModel().getLayer(),
     87                    way,
     88                    Collections.singletonList(interesect),
     89                    Collections.<OsmPrimitive>emptyList()
     90            );
     91            if (result != null){
     92                Main.main.undoRedo.add(result.getCommand());
     93            }
     94        }
     95    }
    9696}
  • applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/qa/WrongTurnRestrictionLegTypeError.java

    r20622 r23192  
    1919 */
    2020public class WrongTurnRestrictionLegTypeError extends Issue {
    21         private TurnRestrictionLegRole role;
    22         private OsmPrimitive leg;
     21    private TurnRestrictionLegRole role;
     22    private OsmPrimitive leg;
    2323
    24         /**
    25         * Create the issue
    26         *
    27         * @param parent the parent model
    28         * @param role the role of the turn restriction leg
    29         * @param leg the leg
    30         */
    31         public WrongTurnRestrictionLegTypeError(IssuesModel parent, TurnRestrictionLegRole role, OsmPrimitive leg) {
    32                 super(parent, Severity.ERROR);
    33                 this.role = role;
    34                 this.leg = leg;
    35                 actions.add(new DeleteAction());
    36                 actions.add(new FixInEditorAction());
    37         }
     24    /**
     25    * Create the issue
     26    *
     27    * @param parent the parent model
     28    * @param role the role of the turn restriction leg
     29    * @param leg the leg
     30    */
     31    public WrongTurnRestrictionLegTypeError(IssuesModel parent, TurnRestrictionLegRole role, OsmPrimitive leg) {
     32        super(parent, Severity.ERROR);
     33        this.role = role;
     34        this.leg = leg;
     35        actions.add(new DeleteAction());
     36        actions.add(new FixInEditorAction());
     37    }
    3838
    39         @Override
    40         public String getText() {               
    41                 String msg = null;
    42                 switch(leg.getType()){
    43                 case NODE:
    44                         msg = tr(
    45                                 "This turn restriction uses the OSM node <span class=\"object-name\">{0}</span> as member with role <tt>{1}</tt>.",
    46                                 leg.getDisplayName(DefaultNameFormatter.getInstance()),
    47                                 role.toString()
    48                         );
    49                         break;
    50                 case RELATION:
    51                         msg = tr("This turn restriction uses the OSM relation <span class=\"object-name\">{0}</span> as member with role <tt>{1}</tt>.",
    52                                         leg.getDisplayName(DefaultNameFormatter.getInstance()),
    53                                         role.toString()
    54                                 );                             
    55                         break;                 
    56                 }
    57                 return msg + " " + tr("An OSM way is required instead.");
    58         }
     39    @Override
     40    public String getText() {       
     41        String msg = null;
     42        switch(leg.getType()){
     43        case NODE:
     44            msg = tr(
     45                "This turn restriction uses the OSM node <span class=\"object-name\">{0}</span> as member with role <tt>{1}</tt>.",
     46                leg.getDisplayName(DefaultNameFormatter.getInstance()),
     47                role.toString()
     48            );
     49            break;
     50        case RELATION:
     51            msg = tr("This turn restriction uses the OSM relation <span class=\"object-name\">{0}</span> as member with role <tt>{1}</tt>.",
     52                    leg.getDisplayName(DefaultNameFormatter.getInstance()),
     53                    role.toString()
     54                );             
     55            break;         
     56        }
     57        return msg + " " + tr("An OSM way is required instead.");
     58    }
    5959
    60         class DeleteAction extends AbstractAction {
    61                 public DeleteAction() {
    62                         putValue(NAME, tr("Delete"));
    63                         putValue(SHORT_DESCRIPTION, tr("Delete the member from the turn restriction"));
    64                 }
    65                 public void actionPerformed(ActionEvent e) {
    66                         RelationMemberEditorModel model = getIssuesModel().getEditorModel().getRelationMemberEditorModel();
    67                         switch(role){
    68                         case FROM:
    69                                 model.setFromPrimitive(null);
    70                                 break;
    71                         case TO:
    72                                 model.setToPrimitive(null);
    73                                 break;
    74                         }
    75                 }               
    76         }
    77        
    78         class FixInEditorAction extends AbstractAction {
    79                 public FixInEditorAction() {
    80                         putValue(NAME, tr("Fix in editor"));
    81                         putValue(SHORT_DESCRIPTION, tr("Change to the Basic Editor and select an OSM way"));
    82                 }
    83                 public void actionPerformed(ActionEvent e) {
    84                         NavigationControler controler = getIssuesModel().getNavigationControler();
    85                         switch(role){
    86                         case FROM:
    87                                 controler.gotoBasicEditor(BasicEditorFokusTargets.FROM);
    88                                 break;
    89                         case TO:
    90                                 controler.gotoBasicEditor(BasicEditorFokusTargets.TO);
    91                                 break;
    92                         }
    93                 }               
    94         }
     60    class DeleteAction extends AbstractAction {
     61        public DeleteAction() {
     62            putValue(NAME, tr("Delete"));
     63            putValue(SHORT_DESCRIPTION, tr("Delete the member from the turn restriction"));
     64        }
     65        public void actionPerformed(ActionEvent e) {
     66            RelationMemberEditorModel model = getIssuesModel().getEditorModel().getRelationMemberEditorModel();
     67            switch(role){
     68            case FROM:
     69                model.setFromPrimitive(null);
     70                break;
     71            case TO:
     72                model.setToPrimitive(null);
     73                break;
     74            }
     75        }       
     76    }
     77   
     78    class FixInEditorAction extends AbstractAction {
     79        public FixInEditorAction() {
     80            putValue(NAME, tr("Fix in editor"));
     81            putValue(SHORT_DESCRIPTION, tr("Change to the Basic Editor and select an OSM way"));
     82        }
     83        public void actionPerformed(ActionEvent e) {
     84            NavigationControler controler = getIssuesModel().getNavigationControler();
     85            switch(role){
     86            case FROM:
     87                controler.gotoBasicEditor(BasicEditorFokusTargets.FROM);
     88                break;
     89            case TO:
     90                controler.gotoBasicEditor(BasicEditorFokusTargets.TO);
     91                break;
     92            }
     93        }       
     94    }
    9595}
  • applications/editors/josm/plugins/turnrestrictions/test/org/openstreetmap/josm/plugins/turnrestrictions/editor/BasicEditorPanelTest.java

    r20586 r23192  
    1515public class BasicEditorPanelTest extends JFrame {
    1616
    17         private TurnRestrictionEditorModel model;
    18         private DataSet ds;
    19        
    20         public BasicEditorPanelTest() {
    21                 ds = new DataSet();
    22                 OsmDataLayer layer =new OsmDataLayer(ds, "test",null);
    23                 // mock a controler
    24                 NavigationControler controler = new NavigationControler() {
    25                         public void gotoAdvancedEditor() {
    26                         }
     17    private TurnRestrictionEditorModel model;
     18    private DataSet ds;
     19   
     20    public BasicEditorPanelTest() {
     21        ds = new DataSet();
     22        OsmDataLayer layer =new OsmDataLayer(ds, "test",null);
     23        // mock a controler
     24        NavigationControler controler = new NavigationControler() {
     25            public void gotoAdvancedEditor() {
     26            }
    2727
    28                         public void gotoBasicEditor() {
    29                         }
     28            public void gotoBasicEditor() {
     29            }
    3030
    31                         public void gotoBasicEditor(BasicEditorFokusTargets focusTarget) {
    32                         }                       
    33                 };
    34                 model = new TurnRestrictionEditorModel(layer, controler);
    35                
    36                 BasicEditorPanel panel = new BasicEditorPanel(model);
    37                
    38                 Container c = getContentPane();
    39                 c.setLayout(new BorderLayout());
    40                 c.add(panel, BorderLayout.CENTER);             
    41                 setSize(600,600);
    42                 setDefaultCloseOperation(EXIT_ON_CLOSE);
    43         }
    44        
    45        
    46         static public void main(String args[]) {
    47                 new BasicEditorPanelTest().setVisible(true);
    48         }
     31            public void gotoBasicEditor(BasicEditorFokusTargets focusTarget) {
     32            }           
     33        };
     34        model = new TurnRestrictionEditorModel(layer, controler);
     35       
     36        BasicEditorPanel panel = new BasicEditorPanel(model);
     37       
     38        Container c = getContentPane();
     39        c.setLayout(new BorderLayout());
     40        c.add(panel, BorderLayout.CENTER);     
     41        setSize(600,600);
     42        setDefaultCloseOperation(EXIT_ON_CLOSE);
     43    }
     44   
     45   
     46    static public void main(String args[]) {
     47        new BasicEditorPanelTest().setVisible(true);
     48    }
    4949}
  • applications/editors/josm/plugins/turnrestrictions/test/org/openstreetmap/josm/plugins/turnrestrictions/editor/TurnRestrictionComboBoxTest.java

    r20606 r23192  
    1616 */
    1717public class TurnRestrictionComboBoxTest extends JFrame {
    18        
    19         private TurnRestrictionEditorModel model;
    20         private DataSet ds = new DataSet();
    21        
    22         protected void build() {
    23                 ds = new DataSet();
    24                 OsmDataLayer layer =new OsmDataLayer(ds, "test",null);
    25                 // mock a controler
    26                 NavigationControler controler = new NavigationControler() {
    27                         public void gotoAdvancedEditor() {
    28                         }
     18   
     19    private TurnRestrictionEditorModel model;
     20    private DataSet ds = new DataSet();
     21   
     22    protected void build() {
     23        ds = new DataSet();
     24        OsmDataLayer layer =new OsmDataLayer(ds, "test",null);
     25        // mock a controler
     26        NavigationControler controler = new NavigationControler() {
     27            public void gotoAdvancedEditor() {
     28            }
    2929
    30                         public void gotoBasicEditor() {
    31                         }
     30            public void gotoBasicEditor() {
     31            }
    3232
    33                         public void gotoBasicEditor(BasicEditorFokusTargets focusTarget) {
    34                         }                       
    35                 };
    36                 model = new TurnRestrictionEditorModel(layer, controler);
    37                
    38                 Container c = getContentPane();
    39                 c.setLayout(new GridBagLayout());
    40                 GridBagConstraints gc = new GridBagConstraints();
    41                 gc.anchor = GridBagConstraints.NORTHWEST;
    42                 gc.fill = GridBagConstraints.HORIZONTAL;
    43                 gc.weightx = 1.0;
    44                
    45                 TurnRestrictionComboBox cb = new TurnRestrictionComboBox(
    46                                 new TurnRestrictionComboBoxModel(model)
    47                 );
    48                 add(cb, gc);           
    49         }
    50        
    51         public TurnRestrictionComboBoxTest() {
    52                 build();
    53                 setSize(600,600);
    54                 setDefaultCloseOperation(EXIT_ON_CLOSE);
    55         }
    56        
    57         public static void main(String args[]) {
    58                 new TurnRestrictionComboBoxTest().setVisible(true);
    59         }
     33            public void gotoBasicEditor(BasicEditorFokusTargets focusTarget) {
     34            }           
     35        };
     36        model = new TurnRestrictionEditorModel(layer, controler);
     37       
     38        Container c = getContentPane();
     39        c.setLayout(new GridBagLayout());
     40        GridBagConstraints gc = new GridBagConstraints();
     41        gc.anchor = GridBagConstraints.NORTHWEST;
     42        gc.fill = GridBagConstraints.HORIZONTAL;
     43        gc.weightx = 1.0;
     44       
     45        TurnRestrictionComboBox cb = new TurnRestrictionComboBox(
     46                new TurnRestrictionComboBoxModel(model)
     47        );
     48        add(cb, gc);       
     49    }
     50   
     51    public TurnRestrictionComboBoxTest() {
     52        build();
     53        setSize(600,600);
     54        setDefaultCloseOperation(EXIT_ON_CLOSE);
     55    }
     56   
     57    public static void main(String args[]) {
     58        new TurnRestrictionComboBoxTest().setVisible(true);
     59    }
    6060
    6161}
  • applications/editors/josm/plugins/turnrestrictions/test/org/openstreetmap/josm/plugins/turnrestrictions/editor/TurnRestrictionEditorTest.java

    r20606 r23192  
    1010 */
    1111public class TurnRestrictionEditorTest extends JFrame {
    12        
    13         public TurnRestrictionEditorTest() {
    14                 setSize(10,10);
    15                 TurnRestrictionEditor editor = new TurnRestrictionEditor(this, new OsmDataLayer(new DataSet(), "test", null));
    16                 editor.setSize(600,600);
    17                 editor.setVisible(true);
    18                
    19                 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    20         }
    21        
    22         static public void main(String args[]) {
    23                 new TurnRestrictionEditorTest().setVisible(true);
    24         }
     12   
     13    public TurnRestrictionEditorTest() {
     14        setSize(10,10);
     15        TurnRestrictionEditor editor = new TurnRestrictionEditor(this, new OsmDataLayer(new DataSet(), "test", null));
     16        editor.setSize(600,600);
     17        editor.setVisible(true);
     18       
     19        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     20    }
     21   
     22    static public void main(String args[]) {
     23        new TurnRestrictionEditorTest().setVisible(true);
     24    }
    2525}
  • applications/editors/josm/plugins/turnrestrictions/test/org/openstreetmap/josm/plugins/turnrestrictions/editor/TurnRestrictionLegEditorTest.java

    r20606 r23192  
    3434 */
    3535public class TurnRestrictionLegEditorTest extends JFrame {
    36        
    37         private JTextArea taTest;
    38         private TurnRestrictionLegEditor editor;
    39         private TurnRestrictionEditorModel model;
    40         private JList lstObjects;
    41         private DefaultListModel listModel;
    42         private DataSet dataSet;
    43        
    44        
    45         protected JPanel buildLegEditorPanel() {
    46                 DataSet ds = new DataSet();
    47                 OsmDataLayer layer =new OsmDataLayer(ds, "test",null);
    48                 // mock a controler
    49                 NavigationControler controler = new NavigationControler() {
    50                         public void gotoAdvancedEditor() {
    51                         }
     36   
     37    private JTextArea taTest;
     38    private TurnRestrictionLegEditor editor;
     39    private TurnRestrictionEditorModel model;
     40    private JList lstObjects;
     41    private DefaultListModel listModel;
     42    private DataSet dataSet;
     43   
     44   
     45    protected JPanel buildLegEditorPanel() {
     46        DataSet ds = new DataSet();
     47        OsmDataLayer layer =new OsmDataLayer(ds, "test",null);
     48        // mock a controler
     49        NavigationControler controler = new NavigationControler() {
     50            public void gotoAdvancedEditor() {
     51            }
    5252
    53                         public void gotoBasicEditor() {
    54                         }
     53            public void gotoBasicEditor() {
     54            }
    5555
    56                         public void gotoBasicEditor(BasicEditorFokusTargets focusTarget) {
    57                         }                       
    58                 };
    59                 JPanel pnl = new JPanel(new GridBagLayout());
    60                 GridBagConstraints gc = new GridBagConstraints();
    61                 gc.anchor = GridBagConstraints.NORTHWEST;
    62                 gc.fill = GridBagConstraints.HORIZONTAL;
    63                 gc.weightx = 0.0;               
    64                 pnl.add(new JLabel("From"), gc);
    65                
    66                 gc.weightx = 1.0;
    67                 gc.gridx = 1;
    68                 model = new TurnRestrictionEditorModel(layer, controler);
    69                 dataSet = new DataSet();
    70                 model.populate(new Relation());
    71                 pnl.add(editor = new TurnRestrictionLegEditor(model, TurnRestrictionLegRole.FROM), gc);
    72                
    73                 return pnl;
    74         }
    75        
    76         protected JPanel buildObjectListPanel() {
    77                 JPanel pnl = new JPanel(new BorderLayout());
    78                 listModel = new DefaultListModel();
    79                 pnl.add(new JScrollPane(lstObjects = new JList(listModel)), BorderLayout.CENTER);
    80                 lstObjects.setCellRenderer(new OsmPrimitivRenderer());         
    81                
    82                 PrimitiveIdListProvider provider = new PrimitiveIdListProvider() {                     
    83                         public List<PrimitiveId> getSelectedPrimitiveIds() {
    84                                 List<PrimitiveId> ret = new ArrayList<PrimitiveId>();
    85                                 int [] sel = lstObjects.getSelectedIndices();
    86                                 for (int i: sel){
    87                                         ret.add(((OsmPrimitive)lstObjects.getModel().getElementAt(i)).getPrimitiveId());
    88                                 }
    89                                 return ret;
    90                         }
    91                 };
    92                
    93                 lstObjects.setTransferHandler(new PrimitiveIdListTransferHandler(provider));
    94                 lstObjects.setDragEnabled(true);
    95                 return pnl;
    96         }
    97        
    98         protected void build() {
    99                 Container c = getContentPane();
    100                 c.setLayout(new GridBagLayout());
    101                
    102                 GridBagConstraints gc = new GridBagConstraints();
    103                 gc.anchor = GridBagConstraints.NORTHWEST;
    104                 gc.fill = GridBagConstraints.HORIZONTAL;       
    105                 gc.insets = new Insets(20, 0, 20, 0);
    106                 gc.weightx = 1.0;               
    107                 gc.weighty = 0.0;
    108                 add(buildLegEditorPanel(), gc);
    109                
    110                 gc.gridy = 1;
    111                 gc.weightx = 1.0;
    112                 gc.weighty = 1.0;
    113                 gc.fill = GridBagConstraints.BOTH;
    114                 add(buildObjectListPanel(), gc);
    115                 setSize(600,600);       
    116         }
    117        
    118         protected void initForTest1() {
    119                 Way w = new Way(1);
    120                 w.put("name", "way-1");
    121                
    122                 editor.getModel().setTurnRestrictionLeg(TurnRestrictionLegRole.FROM, w);
    123         }
    124        
    125         protected void initForTest2() {
    126                 Way w = new Way(1);
    127                 w.put("name", "way-1");         
    128                 dataSet.addPrimitive(w);
    129                 editor.getModel().setTurnRestrictionLeg(TurnRestrictionLegRole.FROM, w);
    130                
    131                 Node n = new Node(new LatLon(1,1));
    132                 n.setOsmId(1, 1);
    133                 n.put("name", "node.1");
    134                 dataSet.addPrimitive(n);
    135                 listModel.addElement(n);
    136                
    137                 w = new Way();
    138                 w.setOsmId(2,1);
    139                 w.put("name", "way.1");
    140                 dataSet.addPrimitive(w);
    141                 listModel.addElement(w);
    142                
    143                 Relation r = new Relation();
    144                 r.setOsmId(3,1);
    145                 r.put("name", "relation.1");
    146                 dataSet.addPrimitive(r);
    147                 listModel.addElement(r);
    148         }
     56            public void gotoBasicEditor(BasicEditorFokusTargets focusTarget) {
     57            }           
     58        };
     59        JPanel pnl = new JPanel(new GridBagLayout());
     60        GridBagConstraints gc = new GridBagConstraints();
     61        gc.anchor = GridBagConstraints.NORTHWEST;
     62        gc.fill = GridBagConstraints.HORIZONTAL;
     63        gc.weightx = 0.0;       
     64        pnl.add(new JLabel("From"), gc);
     65       
     66        gc.weightx = 1.0;
     67        gc.gridx = 1;
     68        model = new TurnRestrictionEditorModel(layer, controler);
     69        dataSet = new DataSet();
     70        model.populate(new Relation());
     71        pnl.add(editor = new TurnRestrictionLegEditor(model, TurnRestrictionLegRole.FROM), gc);
     72       
     73        return pnl;
     74    }
     75   
     76    protected JPanel buildObjectListPanel() {
     77        JPanel pnl = new JPanel(new BorderLayout());
     78        listModel = new DefaultListModel();
     79        pnl.add(new JScrollPane(lstObjects = new JList(listModel)), BorderLayout.CENTER);
     80        lstObjects.setCellRenderer(new OsmPrimitivRenderer());     
     81       
     82        PrimitiveIdListProvider provider = new PrimitiveIdListProvider() {         
     83            public List<PrimitiveId> getSelectedPrimitiveIds() {
     84                List<PrimitiveId> ret = new ArrayList<PrimitiveId>();
     85                int [] sel = lstObjects.getSelectedIndices();
     86                for (int i: sel){
     87                    ret.add(((OsmPrimitive)lstObjects.getModel().getElementAt(i)).getPrimitiveId());
     88                }
     89                return ret;
     90            }
     91        };
     92       
     93        lstObjects.setTransferHandler(new PrimitiveIdListTransferHandler(provider));
     94        lstObjects.setDragEnabled(true);
     95        return pnl;
     96    }
     97   
     98    protected void build() {
     99        Container c = getContentPane();
     100        c.setLayout(new GridBagLayout());
     101       
     102        GridBagConstraints gc = new GridBagConstraints();
     103        gc.anchor = GridBagConstraints.NORTHWEST;
     104        gc.fill = GridBagConstraints.HORIZONTAL;   
     105        gc.insets = new Insets(20, 0, 20, 0);
     106        gc.weightx = 1.0;       
     107        gc.weighty = 0.0;
     108        add(buildLegEditorPanel(), gc);
     109       
     110        gc.gridy = 1;
     111        gc.weightx = 1.0;
     112        gc.weighty = 1.0;
     113        gc.fill = GridBagConstraints.BOTH;
     114        add(buildObjectListPanel(), gc);
     115        setSize(600,600);   
     116    }
     117   
     118    protected void initForTest1() {
     119        Way w = new Way(1);
     120        w.put("name", "way-1");
     121       
     122        editor.getModel().setTurnRestrictionLeg(TurnRestrictionLegRole.FROM, w);
     123    }
     124   
     125    protected void initForTest2() {
     126        Way w = new Way(1);
     127        w.put("name", "way-1");     
     128        dataSet.addPrimitive(w);
     129        editor.getModel().setTurnRestrictionLeg(TurnRestrictionLegRole.FROM, w);
     130       
     131        Node n = new Node(new LatLon(1,1));
     132        n.setOsmId(1, 1);
     133        n.put("name", "node.1");
     134        dataSet.addPrimitive(n);
     135        listModel.addElement(n);
     136       
     137        w = new Way();
     138        w.setOsmId(2,1);
     139        w.put("name", "way.1");
     140        dataSet.addPrimitive(w);
     141        listModel.addElement(w);
     142       
     143        Relation r = new Relation();
     144        r.setOsmId(3,1);
     145        r.put("name", "relation.1");
     146        dataSet.addPrimitive(r);
     147        listModel.addElement(r);
     148    }
    149149
    150         public TurnRestrictionLegEditorTest(){
    151                 build();
    152                 initForTest2();
    153         }
    154        
    155         static public void main(String args[]) {
    156                 new TurnRestrictionLegEditorTest().setVisible(true);
    157         }
     150    public TurnRestrictionLegEditorTest(){
     151        build();
     152        initForTest2();
     153    }
     154   
     155    static public void main(String args[]) {
     156        new TurnRestrictionLegEditorTest().setVisible(true);
     157    }
    158158}
  • applications/editors/josm/plugins/turnrestrictions/test/org/openstreetmap/josm/plugins/turnrestrictions/editor/VehicleExceptionEditorTest.java

    r20606 r23192  
    1515 */
    1616public class VehicleExceptionEditorTest extends JFrame {
    17         TurnRestrictionEditorModel model;
    18         OsmDataLayer layer;
    19         VehicleExceptionEditor editor;
    20        
    21         protected void build() {
    22                 Container c = getContentPane();
    23                 c.setLayout(new BorderLayout());
    24                 layer = new OsmDataLayer(new DataSet(), "test", null);
     17    TurnRestrictionEditorModel model;
     18    OsmDataLayer layer;
     19    VehicleExceptionEditor editor;
     20   
     21    protected void build() {
     22        Container c = getContentPane();
     23        c.setLayout(new BorderLayout());
     24        layer = new OsmDataLayer(new DataSet(), "test", null);
    2525
    26                 model = new TurnRestrictionEditorModel(layer, new MockNavigationControler());           
    27                 editor = new VehicleExceptionEditor(model);
    28                 c.add(editor, BorderLayout.CENTER);
    29                
    30                 model.getTagEditorModel().add(new TagModel("except", "non-standard-value"));
    31         }
    32        
    33         public VehicleExceptionEditorTest(){
    34                 build();
    35                 setDefaultCloseOperation(EXIT_ON_CLOSE);
    36                 setSize(500,500);               
    37         }
    38        
    39         public static void main(String args[]){
    40                 new VehicleExceptionEditorTest().setVisible(true);
    41         }
    42        
    43         static private class MockNavigationControler implements NavigationControler{
     26        model = new TurnRestrictionEditorModel(layer, new MockNavigationControler());       
     27        editor = new VehicleExceptionEditor(model);
     28        c.add(editor, BorderLayout.CENTER);
     29       
     30        model.getTagEditorModel().add(new TagModel("except", "non-standard-value"));
     31    }
     32   
     33    public VehicleExceptionEditorTest(){
     34        build();
     35        setDefaultCloseOperation(EXIT_ON_CLOSE);
     36        setSize(500,500);       
     37    }
     38   
     39    public static void main(String args[]){
     40        new VehicleExceptionEditorTest().setVisible(true);
     41    }
     42   
     43    static private class MockNavigationControler implements NavigationControler{
    4444
    45                 public void gotoAdvancedEditor() {
    46                         // TODO Auto-generated method stub
    47                        
    48                 }
     45        public void gotoAdvancedEditor() {
     46            // TODO Auto-generated method stub
     47           
     48        }
    4949
    50                 public void gotoBasicEditor() {
    51                         // TODO Auto-generated method stub
    52                        
    53                 }
     50        public void gotoBasicEditor() {
     51            // TODO Auto-generated method stub
     52           
     53        }
    5454
    55                 public void gotoBasicEditor(BasicEditorFokusTargets focusTarget) {
    56                         // TODO Auto-generated method stub
    57                        
    58                 }
    59         }
     55        public void gotoBasicEditor(BasicEditorFokusTargets focusTarget) {
     56            // TODO Auto-generated method stub
     57           
     58        }
     59    }
    6060}
  • applications/editors/josm/plugins/turnrestrictions/test/org/openstreetmap/josm/plugins/turnrestrictions/editor/ViaListTest.java

    r20606 r23192  
    2222 */
    2323public class ViaListTest  extends JFrame{
    24        
    25         private ViaList lstVias;
    26         private TurnRestrictionEditorModel model;
    27         private JList lstJOSMSelection;
    28        
    29        
    30         protected void build() {
    31                 DataSet ds = new DataSet();
    32                 OsmDataLayer layer =new OsmDataLayer(ds, "test",null);
    33                 // mock a controler
    34                 NavigationControler controler = new NavigationControler() {
    35                         public void gotoAdvancedEditor() {
    36                         }
     24   
     25    private ViaList lstVias;
     26    private TurnRestrictionEditorModel model;
     27    private JList lstJOSMSelection;
     28   
     29   
     30    protected void build() {
     31        DataSet ds = new DataSet();
     32        OsmDataLayer layer =new OsmDataLayer(ds, "test",null);
     33        // mock a controler
     34        NavigationControler controler = new NavigationControler() {
     35            public void gotoAdvancedEditor() {
     36            }
    3737
    38                         public void gotoBasicEditor() {
    39                         }
     38            public void gotoBasicEditor() {
     39            }
    4040
    41                         public void gotoBasicEditor(BasicEditorFokusTargets focusTarget) {
    42                         }                       
    43                 };
    44                 model = new TurnRestrictionEditorModel(layer, controler);
    45                 Container c = getContentPane();
    46                
    47                 c.setLayout(new GridBagLayout());
    48                 GridBagConstraints gc = new GridBagConstraints();
    49                 gc.anchor = GridBagConstraints.NORTHWEST;
    50                 gc.insets = new Insets(5,5,5,20);
    51                 gc.fill = GridBagConstraints.BOTH;
    52                 gc.weightx = 0.5;
    53                 gc.weighty = 1.0;
    54                
    55                 DefaultListSelectionModel selectionModel = new DefaultListSelectionModel();
    56                 c.add(lstVias = new ViaList(new ViaListModel(model, selectionModel), selectionModel), gc);
    57                
    58                 gc.gridx = 1;
    59                 c.add(lstJOSMSelection = new JList(), gc);
    60                
    61                 setSize(600,600);               
    62                 setDefaultCloseOperation(EXIT_ON_CLOSE);
    63         }
    64        
    65         protected void initTest1() {
    66                 DataSet ds = new DataSet();
    67                 Relation r = new Relation();
    68                 Node n;
    69                 for (int i = 1; i<10; i++){
    70                         n = new Node(new LatLon(i,i)); 
    71                         n.put("name", "node." + i);
    72                         ds.addPrimitive(n);
    73                         r.addMember(new RelationMember("via",n));
    74                 }               
    75                 model.populate(r);
    76         }
    77        
    78         public ViaListTest() {
    79                 build();               
    80                 initTest1();
    81         }
    82        
    83         static public void main(String args[]) {
    84                 new ViaListTest().setVisible(true);
    85         }
     41            public void gotoBasicEditor(BasicEditorFokusTargets focusTarget) {
     42            }           
     43        };
     44        model = new TurnRestrictionEditorModel(layer, controler);
     45        Container c = getContentPane();
     46       
     47        c.setLayout(new GridBagLayout());
     48        GridBagConstraints gc = new GridBagConstraints();
     49        gc.anchor = GridBagConstraints.NORTHWEST;
     50        gc.insets = new Insets(5,5,5,20);
     51        gc.fill = GridBagConstraints.BOTH;
     52        gc.weightx = 0.5;
     53        gc.weighty = 1.0;
     54       
     55        DefaultListSelectionModel selectionModel = new DefaultListSelectionModel();
     56        c.add(lstVias = new ViaList(new ViaListModel(model, selectionModel), selectionModel), gc);
     57       
     58        gc.gridx = 1;
     59        c.add(lstJOSMSelection = new JList(), gc);
     60       
     61        setSize(600,600);       
     62        setDefaultCloseOperation(EXIT_ON_CLOSE);
     63    }
     64   
     65    protected void initTest1() {
     66        DataSet ds = new DataSet();
     67        Relation r = new Relation();
     68        Node n;
     69        for (int i = 1; i<10; i++){
     70            n = new Node(new LatLon(i,i)); 
     71            n.put("name", "node." + i);
     72            ds.addPrimitive(n);
     73            r.addMember(new RelationMember("via",n));
     74        }       
     75        model.populate(r);
     76    }
     77   
     78    public ViaListTest() {
     79        build();       
     80        initTest1();
     81    }
     82   
     83    static public void main(String args[]) {
     84        new ViaListTest().setVisible(true);
     85    }
    8686}
  • applications/editors/josm/plugins/turnrestrictions/test/org/openstreetmap/josm/plugins/turnrestrictions/qa/IssuesViewTest.java

    r20606 r23192  
    1919 */
    2020public class IssuesViewTest extends JFrame {
    21         private IssuesModel model;
    22        
    23         protected void build() {
    24                 Container c = getContentPane();
    25                 c.setLayout(new GridBagLayout());
    26                 // mock a controler
    27                 NavigationControler controler = new NavigationControler() {
    28                         public void gotoAdvancedEditor() {
    29                         }
     21    private IssuesModel model;
     22   
     23    protected void build() {
     24        Container c = getContentPane();
     25        c.setLayout(new GridBagLayout());
     26        // mock a controler
     27        NavigationControler controler = new NavigationControler() {
     28            public void gotoAdvancedEditor() {
     29            }
    3030
    31                         public void gotoBasicEditor() {
    32                         }
     31            public void gotoBasicEditor() {
     32            }
    3333
    34                         public void gotoBasicEditor(BasicEditorFokusTargets focusTarget) {
    35                         }                       
    36                 };
    37                 OsmDataLayer layer = new OsmDataLayer(new DataSet(), "test", null);
    38                 TurnRestrictionEditorModel editorModel = new TurnRestrictionEditorModel(layer, controler);
    39                 model = new IssuesModel(editorModel);
    40                 GridBagConstraints gc = new GridBagConstraints();
    41                 gc.anchor = GridBagConstraints.NORTHWEST;
    42                 gc.fill = GridBagConstraints.BOTH;
    43                 gc.weightx = 1.0;
    44                 gc.weighty = 1.0;
    45                 JScrollPane pane = new JScrollPane(new IssuesView(model));
    46                 pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    47                 pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
    48                 c.add(pane, gc);
    49                
    50                 List<Issue> issues = new ArrayList<Issue>();
    51                 issues.add(new RequiredTagMissingError(model, "type", "restriction"));
    52                 issues.add(new MissingRestrictionTypeError(model));
    53                 model.populate(issues);
    54         }
    55        
    56         public IssuesViewTest() {
    57                 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    58                 setSize(400,600);
    59                 build();
    60         }
    61        
    62         public static void main(String args[]) {
    63                 new IssuesViewTest().setVisible(true);
    64         }
     34            public void gotoBasicEditor(BasicEditorFokusTargets focusTarget) {
     35            }           
     36        };
     37        OsmDataLayer layer = new OsmDataLayer(new DataSet(), "test", null);
     38        TurnRestrictionEditorModel editorModel = new TurnRestrictionEditorModel(layer, controler);
     39        model = new IssuesModel(editorModel);
     40        GridBagConstraints gc = new GridBagConstraints();
     41        gc.anchor = GridBagConstraints.NORTHWEST;
     42        gc.fill = GridBagConstraints.BOTH;
     43        gc.weightx = 1.0;
     44        gc.weighty = 1.0;
     45        JScrollPane pane = new JScrollPane(new IssuesView(model));
     46        pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
     47        pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
     48        c.add(pane, gc);
     49       
     50        List<Issue> issues = new ArrayList<Issue>();
     51        issues.add(new RequiredTagMissingError(model, "type", "restriction"));
     52        issues.add(new MissingRestrictionTypeError(model));
     53        model.populate(issues);
     54    }
     55   
     56    public IssuesViewTest() {
     57        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     58        setSize(400,600);
     59        build();
     60    }
     61   
     62    public static void main(String args[]) {
     63        new IssuesViewTest().setVisible(true);
     64    }
    6565}
  • applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/OSMValidatorPlugin.java

    r21616 r23192  
    111111     */
    112112    public OSMValidatorPlugin(PluginInformation info) {
    113         super(info);
     113        super(info);
    114114        checkPluginDir();
    115115        initializeGridDetail();
     
    175175            MapView.addLayerChangeListener(this);
    176176        } else
    177                 MapView.removeLayerChangeListener(this);
     177            MapView.removeLayerChangeListener(this);
    178178        if (newFrame != null) {
    179                 UploadAction.registerUploadHook(uploadHook = new ValidateUploadHook(this));
     179            UploadAction.registerUploadHook(uploadHook = new ValidateUploadHook(this));
    180180        } else {
    181                 UploadAction.unregisterUploadHook(uploadHook);
    182                 uploadHook = null;
     181            UploadAction.unregisterUploadHook(uploadHook);
     182            uploadHook = null;
    183183        }
    184184    }
     
    280280                e.printStackTrace();
    281281                JOptionPane.showMessageDialog(Main.parent,
    282                                 tr("Error initializing test {0}:\n {1}", test.getClass()
     282                        tr("Error initializing test {0}:\n {1}", test.getClass()
    283283                        .getSimpleName(), e),
    284284                        tr("Error"),
     
    306306
    307307    public void layerRemoved(Layer oldLayer) {
    308         if (oldLayer == errorLayer) {
    309                 errorLayer = null;
    310                 return;
    311         }
     308        if (oldLayer == errorLayer) {
     309            errorLayer = null;
     310            return;
     311        }
    312312        layerErrors.remove(oldLayer);
    313313        if (Main.map.mapView.getLayersOfType(OsmDataLayer.class).isEmpty()) {
    314                 if (errorLayer != null) {
    315                         Main.map.mapView.removeLayer(errorLayer);
    316                 }
     314            if (errorLayer != null) {
     315                Main.map.mapView.removeLayer(errorLayer);
     316            }
    317317        }
    318318    }
  • applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/PreferenceEditor.java

    r20828 r23192  
    2222/**
    2323 * Preference settings for the validator plugin
    24  * 
     24 *
    2525 * @author frsantos
    2626 */
     
    5252    /**
    5353     * The preferences key for enabling the permanent filtering
    54      * of the displayed errors in the tree regarding the current selection 
     54     * of the displayed errors in the tree regarding the current selection
    5555     */
    5656    public static final String PREF_FILTER_BY_SELECTION = PREFIX + ".selectionFilter";
  • applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/tests/Coastlines.java

    r20828 r23192  
    4747    public void startTest(ProgressMonitor monitor)
    4848    {
    49         super.startTest(monitor);
     49        super.startTest(monitor);
    5050
    5151        OsmDataLayer layer = Main.map.mapView.getEditLayer();
  • applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/tests/CrossingWays.java

    r20828 r23192  
    5353    public void startTest(ProgressMonitor monitor)
    5454    {
    55         super.startTest(monitor);
     55        super.startTest(monitor);
    5656        cellSegments = new HashMap<Point2D,List<ExtendedSegment>>(1000);
    5757        errorSegments = new HashSet<WaySegment>();
     
    6262    public void endTest()
    6363    {
    64         super.endTest();
     64        super.endTest();
    6565        cellSegments = null;
    6666        errorSegments = null;
  • applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/tests/DuplicateWay.java

    r22714 r23192  
    7070    public void startTest(ProgressMonitor monitor)
    7171    {
    72         super.startTest(monitor);
     72        super.startTest(monitor);
    7373        ways = new Bag<WayPair, OsmPrimitive>(1000);
    7474    }
     
    7777    public void endTest()
    7878    {
    79         super.endTest();
     79        super.endTest();
    8080        for(List<OsmPrimitive> duplicated : ways.values() )
    8181        {
  • applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/tests/DuplicatedWayNodes.java

    r20828 r23192  
    5050        for (Node n : w.getNodes()) {
    5151            if (lastN == null) {
    52                 wnew.addNode(n);
     52                wnew.addNode(n);
    5353            } else if (n == lastN) {
    5454                // Skip this node
    5555            } else {
    56                 wnew.addNode(n);
     56                wnew.addNode(n);
    5757            }
    5858            lastN = n;
  • applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/tests/NameMismatch.java

    r20828 r23192  
    7474                tr("A name is missing, even though name:* exists."),
    7575                                     NAME_MISSING, p));
    76             return;
    77         }
     76        return;
     77    }
    7878
    7979        if (names.contains(name)) return;
  • applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/tests/OverlappingWays.java

    r20828 r23192  
    5252    public void startTest(ProgressMonitor monitor)
    5353    {
    54         super.startTest(monitor);
     54        super.startTest(monitor);
    5555        nodePairs = new Bag<Pair<Node,Node>, WaySegment>(1000);
    5656    }
  • applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/tests/SimilarNamedWays.java

    r20828 r23192  
    4444    public void startTest(ProgressMonitor monitor)
    4545    {
    46         super.startTest(monitor);
     46        super.startTest(monitor);
    4747        cellWays = new HashMap<Point2D,List<Way>>(1000);
    4848        errorWays = new Bag<Way, Way>();
  • applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/tests/WronglyOrderedWays.java

    r20828 r23192  
    4040    public void startTest(ProgressMonitor monitor)
    4141    {
    42         super.startTest(monitor);
     42        super.startTest(monitor);
    4343        _errorWays = new Bag<Way, Way>();
    4444    }
  • applications/editors/josm/plugins/waypoint_search/src/org/openstreetmap/josm/plugins/waypointSearch/SelectWaypointDialog.java

    r23190 r23192  
    6363   
    6464   
    65         public void updateSearchResults(){
    66                 String searchfor = "";
    67                 listModel.clear();
    68                 SearchResultObjectCache.clear();
    69                 if (!first_time_search) {
    70                         searchfor = searchPattern.getText();
    71                 }
    72                 for (Iterator<Marker> i = engine.searchGpxWaypoints(searchfor).iterator(); i.hasNext();) {
    73                         Marker marker = i.next();
    74                         listModel.addElement(marker.getText());
    75                         SearchResultObjectCache.add(marker);
    76                 }
    77         }
     65    public void updateSearchResults(){
     66        String searchfor = "";
     67        listModel.clear();
     68        SearchResultObjectCache.clear();
     69        if (!first_time_search) {
     70            searchfor = searchPattern.getText();
     71        }
     72        for (Iterator<Marker> i = engine.searchGpxWaypoints(searchfor).iterator(); i.hasNext();) {
     73            Marker marker = i.next();
     74            listModel.addElement(marker.getText());
     75            SearchResultObjectCache.add(marker);
     76        }
     77    }
    7878   
    7979
     
    9191
    9292
    93         @Override
    94         public void keyTyped(KeyEvent arg0) {
    95                 first_time_search = false;
    96         }
     93    @Override
     94    public void keyTyped(KeyEvent arg0) {
     95        first_time_search = false;
     96    }
    9797
    9898
  • applications/editors/josm/plugins/waypoint_search/src/org/openstreetmap/josm/plugins/waypointSearch/WaypointSearchPlugin.java

    r23190 r23192  
    2929    }
    3030
    31        
    32         @Override
    33         public void layerAdded(Layer newLayer) {
    34                 //add dialog
    35                 if (Main.map.getToggleDialog(SelectWaypointDialog.class)==null) {
    36                         Main.map.addToggleDialog(waypointDialog);
    37                 }
    38                 //update search
    39                 if (engine.gpxLayersExist()) {
    40                         waypointDialog.updateSearchResults();
    41                 }
    42         }
     31   
     32    @Override
     33    public void layerAdded(Layer newLayer) {
     34        //add dialog
     35        if (Main.map.getToggleDialog(SelectWaypointDialog.class)==null) {
     36            Main.map.addToggleDialog(waypointDialog);
     37        }
     38        //update search
     39        if (engine.gpxLayersExist()) {
     40            waypointDialog.updateSearchResults();
     41        }
     42    }
    4343
    4444
Note: See TracChangeset for help on using the changeset viewer.