Ticket #8442: 8442.patch

File 8442.patch, 40.9 KB (added by Don-vip, 13 years ago)
  • src/CommandLine/CommandLine.java

     
    3737import java.io.PrintWriter;
    3838import java.util.ArrayList;
    3939import java.util.Collection;
    40 import java.util.HashMap;
    4140import java.util.List;
    4241
    4342import javax.swing.JMenu;
     
    5049import org.openstreetmap.josm.data.imagery.ImageryInfo;
    5150import org.openstreetmap.josm.data.osm.BBox;
    5251import org.openstreetmap.josm.data.osm.DataSet;
    53 import org.openstreetmap.josm.data.osm.Node;
    5452import org.openstreetmap.josm.data.osm.OsmPrimitive;
    55 import org.openstreetmap.josm.data.osm.Relation;
    56 import org.openstreetmap.josm.data.osm.Way;
    5753import org.openstreetmap.josm.gui.MainMenu;
    5854import org.openstreetmap.josm.gui.MapFrame;
    5955import org.openstreetmap.josm.gui.PleaseWaitRunnable;
     
    6763import org.openstreetmap.josm.plugins.PluginInformation;
    6864
    6965public class CommandLine extends Plugin {
    70         protected JTextField textField;
    71         protected JTextField historyField;
    72         private String prefix;
    73         private Mode mode;
    74         private ArrayList<Command> commands;
    75         private JMenu commandMenu;
    76         protected Command currentCommand;
    77         protected String commandSymbol;
    78         protected History history;
    79         protected MapFrame currentMapFrame;
    80         protected MapMode previousMode;
     66    protected JTextField textField;
     67    protected JTextField historyField;
     68    private String prefix;
     69    private Mode mode;
     70    private ArrayList<Command> commands;
     71    private JMenu commandMenu;
     72    protected Command currentCommand;
     73    protected String commandSymbol;
     74    protected History history;
     75    protected MapFrame currentMapFrame;
     76    protected MapMode previousMode;
    8177
    82         static final String pluginDir = Main.pref.getPluginsDirectory().getAbsolutePath() + "/CommandLine/";
     78    static final String pluginDir = Main.pref.getPluginsDirectory().getAbsolutePath() + "/CommandLine/";
    8379
    84         public CommandLine(PluginInformation info) {
    85                 super(info);
    86                 commandSymbol = ": ";
    87                 history = new History(100);
    88                 historyField = new JTextField();
    89                 textField = new JTextField() {
    90                         @Override
    91                         protected void processKeyEvent(KeyEvent e) {
    92                                 if (e.getID() == KeyEvent.KEY_PRESSED) {
    93                                         String text = textField.getText();
    94                                         int code = e.getKeyCode();
    95                                         if (code == KeyEvent.VK_ENTER) {
    96                                                 String commandText = textField.getText().substring(prefix.length());
    97                                                 switch (mode) {
    98                                                 case IDLE:
    99                                                         if (commandText.isEmpty()) {
    100                                                                 commandText = history.getLastItem();
    101                                                         }
    102                                                         else {
    103                                                                 history.addItem(commandText);
    104                                                         }
    105                                                         Command command = findCommand(commandText, true);
    106                                                         if (command != null) {
    107                                                                 startCommand(command);
    108                                                         }
    109                                                         else
    110                                                                 setMode(Mode.IDLE);
    111                                                         break;
    112                                                 case SELECTION:
    113                                                         if (currentMapFrame.mapMode instanceof WayAction || currentMapFrame.mapMode instanceof NodeAction || currentMapFrame.mapMode instanceof RelationAction || currentMapFrame.mapMode instanceof AnyAction) {
    114                                                                 Collection<OsmPrimitive> selected = Main.main.getCurrentDataSet().getSelected();
    115                                                                 if (selected.size() > 0)
    116                                                                         loadParameter(selected, true);
    117                                                         }
    118                                                         else {
    119                                                                 loadParameter(commandText, currentCommand.parameters.get(currentCommand.currentParameterNum).maxInstances == 1);
    120                                                         }
    121                                                         break;
    122                                                 case ADJUSTMENT:
    123                                                         break;
    124                                                 }
    125                                                 e.consume();
    126                                         }
    127                                         else if (code == KeyEvent.VK_UP) {
    128                                                 textField.setText(prefix + history.getPrevItem());
    129                                                 e.consume();
    130                                         }
    131                                         else if (code == KeyEvent.VK_DOWN) {
    132                                                 textField.setText(prefix + history.getNextItem());
    133                                                 e.consume();
    134                                         }
    135                                         else if (code == KeyEvent.VK_BACK_SPACE || code == KeyEvent.VK_LEFT) {
    136                                                 if (textField.getCaretPosition() <= prefix.length())
    137                                                         e.consume();
    138                                         }
    139                                         else if (code == KeyEvent.VK_HOME) {
    140                                                 setCaretPosition(prefix.length());
    141                                                 e.consume();
    142                                         }
    143                                         else if (code == KeyEvent.VK_ESCAPE) {
    144                                                 if (textField.getText().length() == prefix.length() && mode == Mode.IDLE)
    145                                                         deactivate();
    146                                                 else
    147                                                         endInput();
    148                                                 e.consume();
    149                                         }
    150                                         else if (code == KeyEvent.VK_DELETE || code == KeyEvent.VK_RIGHT || code == KeyEvent.VK_END) {
    151                                         }
    152                                         else {
    153                                                 e.consume();
    154                                         }
    155                                         if (textField.getCaretPosition() < prefix.length() || (textField.getSelectionStart() < prefix.length() && textField.getSelectionStart() > 0) )
    156                                                 e.consume();
    157                                 }
    158                                 if (e.getID() == KeyEvent.KEY_TYPED)
    159                                         if (textField.getCaretPosition() < prefix.length() || (textField.getSelectionStart() < prefix.length() && textField.getSelectionStart() > 0) )
    160                                                 e.consume();
    161                                 super.processKeyEvent(e);
    162                                 if (textField.getText().length() < prefix.length()) { // Safe
    163                                         setMode(mode);
    164                                 }
    165                                 if (e.getID() == KeyEvent.KEY_TYPED) {
    166                                         if (e.getKeyChar() > 'A' && e.getKeyChar() < 'z') {
    167                                                 Command command = findCommand(textField.getText().substring(prefix.length()), false);
    168                                                 if (command != null) {
    169                                                         int currentPos = textField.getSelectionStart() == 0 ? textField.getCaretPosition() : textField.getSelectionStart();
    170                                                         textField.setText(prefix + command.name);
    171                                                         textField.setCaretPosition(currentPos);
    172                                                         textField.select(currentPos, prefix.length() + command.name.length());
    173                                                 }
    174                                         }
    175                                 }
    176                         }
    177                         @Override
    178                         protected void processMouseEvent(MouseEvent e) {
    179                                 super.processMouseEvent(e);
    180                                 if (e.getButton() == MouseEvent.BUTTON1 && e.getID() == MouseEvent.MOUSE_RELEASED) {
    181                                         if (textField.getSelectionStart() > 0 && textField.getSelectionStart() < prefix.length())
    182                                                 textField.setSelectionStart(prefix.length());
    183                                         else if (textField.getCaretPosition() < prefix.length())
    184                                                 textField.setCaretPosition(prefix.length());
    185                                 }
    186                         }
    187                 };
     80    @SuppressWarnings("serial")
     81    public CommandLine(PluginInformation info) {
     82        super(info);
     83        commandSymbol = ": ";
     84        history = new History(100);
     85        historyField = new JTextField();
     86        textField = new JTextField() {
     87            @Override
     88            protected void processKeyEvent(KeyEvent e) {
     89                if (e.getID() == KeyEvent.KEY_PRESSED) {
     90                    //String text = textField.getText();
     91                    int code = e.getKeyCode();
     92                    if (code == KeyEvent.VK_ENTER) {
     93                        String commandText = textField.getText().substring(prefix.length());
     94                        switch (mode) {
     95                        case IDLE:
     96                            if (commandText.isEmpty()) {
     97                                commandText = history.getLastItem();
     98                            }
     99                            else {
     100                                history.addItem(commandText);
     101                            }
     102                            Command command = findCommand(commandText, true);
     103                            if (command != null) {
     104                                startCommand(command);
     105                            }
     106                            else
     107                                setMode(Mode.IDLE);
     108                            break;
     109                        case SELECTION:
     110                            if (currentMapFrame.mapMode instanceof WayAction || currentMapFrame.mapMode instanceof NodeAction || currentMapFrame.mapMode instanceof RelationAction || currentMapFrame.mapMode instanceof AnyAction) {
     111                                Collection<OsmPrimitive> selected = Main.main.getCurrentDataSet().getSelected();
     112                                if (selected.size() > 0)
     113                                    loadParameter(selected, true);
     114                            }
     115                            else {
     116                                loadParameter(commandText, currentCommand.parameters.get(currentCommand.currentParameterNum).maxInstances == 1);
     117                            }
     118                            break;
     119                        case ADJUSTMENT:
     120                            break;
     121                        }
     122                        e.consume();
     123                    }
     124                    else if (code == KeyEvent.VK_UP) {
     125                        textField.setText(prefix + history.getPrevItem());
     126                        e.consume();
     127                    }
     128                    else if (code == KeyEvent.VK_DOWN) {
     129                        textField.setText(prefix + history.getNextItem());
     130                        e.consume();
     131                    }
     132                    else if (code == KeyEvent.VK_BACK_SPACE || code == KeyEvent.VK_LEFT) {
     133                        if (textField.getCaretPosition() <= prefix.length())
     134                            e.consume();
     135                    }
     136                    else if (code == KeyEvent.VK_HOME) {
     137                        setCaretPosition(prefix.length());
     138                        e.consume();
     139                    }
     140                    else if (code == KeyEvent.VK_ESCAPE) {
     141                        if (textField.getText().length() == prefix.length() && mode == Mode.IDLE)
     142                            deactivate();
     143                        else
     144                            endInput();
     145                        e.consume();
     146                    }
     147                    else if (code == KeyEvent.VK_DELETE || code == KeyEvent.VK_RIGHT || code == KeyEvent.VK_END) {
     148                    }
     149                    else {
     150                        e.consume();
     151                    }
     152                    if (textField.getCaretPosition() < prefix.length() || (textField.getSelectionStart() < prefix.length() && textField.getSelectionStart() > 0) )
     153                        e.consume();
     154                }
     155                if (e.getID() == KeyEvent.KEY_TYPED)
     156                    if (textField.getCaretPosition() < prefix.length() || (textField.getSelectionStart() < prefix.length() && textField.getSelectionStart() > 0) )
     157                        e.consume();
     158                super.processKeyEvent(e);
     159                if (textField.getText().length() < prefix.length()) { // Safe
     160                    setMode(mode);
     161                }
     162                if (e.getID() == KeyEvent.KEY_TYPED) {
     163                    if (e.getKeyChar() > 'A' && e.getKeyChar() < 'z') {
     164                        Command command = findCommand(textField.getText().substring(prefix.length()), false);
     165                        if (command != null) {
     166                            int currentPos = textField.getSelectionStart() == 0 ? textField.getCaretPosition() : textField.getSelectionStart();
     167                            textField.setText(prefix + command.name);
     168                            textField.setCaretPosition(currentPos);
     169                            textField.select(currentPos, prefix.length() + command.name.length());
     170                        }
     171                    }
     172                }
     173            }
     174            @Override
     175            protected void processMouseEvent(MouseEvent e) {
     176                super.processMouseEvent(e);
     177                if (e.getButton() == MouseEvent.BUTTON1 && e.getID() == MouseEvent.MOUSE_RELEASED) {
     178                    if (textField.getSelectionStart() > 0 && textField.getSelectionStart() < prefix.length())
     179                        textField.setSelectionStart(prefix.length());
     180                    else if (textField.getCaretPosition() < prefix.length())
     181                        textField.setCaretPosition(prefix.length());
     182                }
     183            }
     184        };
    188185
    189                 if ( Main.main.menu != null ) {
    190                         commandMenu = Main.main.menu.addMenu(marktr("Commands") , KeyEvent.VK_M, Main.main.menu.defaultMenuPos, ht("/Plugin/CommandLine"));
    191                         MainMenu.add(Main.main.menu.toolsMenu, new CommandLineAction(this));
    192                 }
    193                 loadCommands();
    194                 setMode(Mode.IDLE);
    195         }
     186        if ( Main.main.menu != null ) {
     187            commandMenu = Main.main.menu.addMenu(marktr("Commands") , KeyEvent.VK_M, Main.main.menu.defaultMenuPos, ht("/Plugin/CommandLine"));
     188            MainMenu.add(Main.main.menu.toolsMenu, new CommandLineAction(this));
     189        }
     190        loadCommands();
     191        setMode(Mode.IDLE);
     192    }
    196193
    197         public void startCommand(String commandName) {
    198                 Command command = findCommand(commandName, true);
    199                 if (command != null) {
    200                         startCommand(command);
    201                 }
    202         }
     194    public void startCommand(String commandName) {
     195        Command command = findCommand(commandName, true);
     196        if (command != null) {
     197            startCommand(command);
     198        }
     199    }
    203200
    204         protected void startCommand(Command command) {
    205                 if (Main.map == null)
    206                         return;
    207                 DataSet ds = Main.main.getCurrentDataSet();
    208                 if (ds == null)
    209                         return;
    210                 currentCommand = command;
    211                 currentCommand.resetLoading();
    212                 parseSelection(ds.getSelected());
    213                 if (!(Main.map.mapMode instanceof AnyAction || Main.map.mapMode instanceof DummyAction || Main.map.mapMode instanceof LengthAction || Main.map.mapMode instanceof NodeAction || Main.map.mapMode instanceof PointAction || Main.map.mapMode instanceof RelationAction || Main.map.mapMode instanceof WayAction)) {
    214                         previousMode = Main.map.mapMode;
    215                 }
    216                 if (currentCommand.currentParameterNum < currentCommand.parameters.size())
    217                         setMode(Mode.SELECTION);
    218                 else
    219                         runTool();
    220         }
     201    protected void startCommand(Command command) {
     202        if (Main.map == null)
     203            return;
     204        DataSet ds = Main.main.getCurrentDataSet();
     205        if (ds == null)
     206            return;
     207        currentCommand = command;
     208        currentCommand.resetLoading();
     209        parseSelection(ds.getSelected());
     210        if (!(Main.map.mapMode instanceof AnyAction || Main.map.mapMode instanceof DummyAction || Main.map.mapMode instanceof LengthAction || Main.map.mapMode instanceof NodeAction || Main.map.mapMode instanceof PointAction || Main.map.mapMode instanceof RelationAction || Main.map.mapMode instanceof WayAction)) {
     211            previousMode = Main.map.mapMode;
     212        }
     213        if (currentCommand.currentParameterNum < currentCommand.parameters.size())
     214            setMode(Mode.SELECTION);
     215        else
     216            runTool();
     217    }
    221218
    222         @Override
    223         public void mapFrameInitialized(MapFrame oldFrame, MapFrame newFrame)
    224         {
    225                 currentMapFrame = newFrame;
    226                 if (oldFrame == null && newFrame != null) {
    227                         JToolBar tb = new JToolBar();
    228                         tb.setLayout(new BorderLayout());
    229                         tb.setFloatable(false);
    230                         tb.setOrientation(JToolBar.HORIZONTAL);
    231                         tb.add(historyField, BorderLayout.NORTH);
    232                         tb.add(textField, BorderLayout.SOUTH);
    233                         currentMapFrame.add(tb, BorderLayout.NORTH);
    234                         printHistory("Loaded CommandLine, version " + getPluginInformation().version);
    235                 }
    236         }
     219    @Override
     220    public void mapFrameInitialized(MapFrame oldFrame, MapFrame newFrame)
     221    {
     222        currentMapFrame = newFrame;
     223        if (oldFrame == null && newFrame != null) {
     224            JToolBar tb = new JToolBar();
     225            tb.setLayout(new BorderLayout());
     226            tb.setFloatable(false);
     227            tb.setOrientation(JToolBar.HORIZONTAL);
     228            tb.add(historyField, BorderLayout.NORTH);
     229            tb.add(textField, BorderLayout.SOUTH);
     230            currentMapFrame.add(tb, BorderLayout.NORTH);
     231            printHistory("Loaded CommandLine, version " + getPluginInformation().version);
     232        }
     233    }
    237234
    238         protected void printHistory(String text) {
    239                 historyField.setText(text);
    240         }
     235    protected void printHistory(String text) {
     236        historyField.setText(text);
     237    }
    241238
    242         private void loadCommands() {
    243                 commands = (new Loader(getPluginDir())).load();
    244                 for (Command command : commands) {
    245                         commandMenu.add(new CommandAction(command, this));
    246                 }
    247         }
     239    private void loadCommands() {
     240        commands = (new Loader(getPluginDir())).load();
     241        for (Command command : commands) {
     242            commandMenu.add(new CommandAction(command, this));
     243        }
     244    }
    248245
    249         private Command findCommand(String text, boolean strict) {
    250                 for (int i = 0; i < commands.size(); i++) {
    251                         if (strict) {
    252                                 if ( commands.get(i).name.equalsIgnoreCase(text) ) {
    253                                         return commands.get(i);
    254                                 }
    255                         }
    256                         else {
    257                                 if ( commands.get(i).name.toLowerCase().startsWith( text.toLowerCase() ) && text.length() > 1 ) {
    258                                         return commands.get(i);
    259                                 }
    260                         }
    261                 }
    262                 return null;
    263         }
     246    private Command findCommand(String text, boolean strict) {
     247        for (int i = 0; i < commands.size(); i++) {
     248            if (strict) {
     249                if ( commands.get(i).name.equalsIgnoreCase(text) ) {
     250                    return commands.get(i);
     251                }
     252            }
     253            else {
     254                if ( commands.get(i).name.toLowerCase().startsWith( text.toLowerCase() ) && text.length() > 1 ) {
     255                    return commands.get(i);
     256                }
     257            }
     258        }
     259        return null;
     260    }
    264261
    265         protected void setMode(Mode targetMode) {
    266                 DataSet currentDataSet = Main.main.getCurrentDataSet();
    267                 if (currentDataSet != null) {
    268                         currentDataSet.clearSelection();
    269                         Main.map.mapView.repaint();
    270                 }
    271                 if (targetMode == Mode.IDLE) {
    272                         mode = Mode.IDLE;
    273                         currentCommand = null;
    274                         prefix = tr("Command") + commandSymbol;
    275                         textField.setText(prefix);
    276                 }
    277                 else if (targetMode == Mode.SELECTION) {
    278                         mode = Mode.SELECTION;
    279                         Parameter currentParameter = currentCommand.parameters.get(currentCommand.currentParameterNum);
    280                         prefix = tr(currentParameter.description == null ? currentParameter.name : currentParameter.description);
    281                         if (currentParameter.getRawValue() instanceof Relay)
    282                                 prefix = prefix + " (" + ((Relay)(currentParameter.getRawValue())).getOptionsString() + ")";
    283                         prefix += commandSymbol;
    284                         String value = currentParameter.getValue();
    285                         textField.setText(prefix + value);
    286                         Type currentType = currentParameter.type;
    287                         MapMode action = null;
    288                         switch (currentType) {
    289                         case POINT:
    290                                 action = new PointAction(currentMapFrame, this);
    291                                 break;
    292                         case WAY:
    293                                 action = new WayAction(currentMapFrame, this);
    294                                 break;
    295                         case NODE:
    296                                 action = new NodeAction(currentMapFrame, this);
    297                                 break;
    298                         case RELATION:
    299                                 action = new RelationAction(currentMapFrame, this);
    300                                 break;
    301                         case ANY:
    302                                 action = new AnyAction(currentMapFrame, this);
    303                                 break;
    304                         case LENGTH:
    305                                 action = new LengthAction(currentMapFrame, this);
    306                                 break;
    307                         case USERNAME:
    308                                 loadParameter(Main.pref.get("osm-server.username", null), true);
    309                                 action = new DummyAction(currentMapFrame, this);
    310                                 break;
    311                         case IMAGERYURL:
    312                                 Layer layer = Main.map.mapView.getActiveLayer();
    313                                 if (layer != null) {
    314                                         if (layer instanceof ImageryLayer) {
    315                                         }
    316                                         else {
    317                                                 List<ImageryLayer> imageryLayers = Main.map.mapView.getLayersOfType(ImageryLayer.class);
    318                                                 if (imageryLayers.size() == 1) {
    319                                                         layer = imageryLayers.get(0);
    320                                                 }
    321                                                 else {
    322                                                         endInput();
    323                                                         return;
    324                                                 }
    325                                         }
    326                                 }
    327                                 ImageryInfo info = ((ImageryLayer)layer).getInfo();
    328                                 String url = info.getUrl();
    329                                 String itype = info.getImageryType().getUrlString();
    330                                 loadParameter((url.equals("") ? itype : url), true);
    331                                 action = new DummyAction(currentMapFrame, this);
    332                                 break;
    333                         case IMAGERYOFFSET:
    334                                 Layer olayer = Main.map.mapView.getActiveLayer();
    335                                 if (olayer != null) {
    336                                         if (olayer instanceof ImageryLayer) {
    337                                         }
    338                                         else {
    339                                                 List<ImageryLayer> imageryLayers = Main.map.mapView.getLayersOfType(ImageryLayer.class);
    340                                                 if (imageryLayers.size() == 1) {
    341                                                         olayer = imageryLayers.get(0);
    342                                                 }
    343                                                 else {
    344                                                         endInput();
    345                                                         return;
    346                                                 }
    347                                         }
    348                                 }
    349                                 loadParameter((String.valueOf(((ImageryLayer)olayer).getDx()) + "," + String.valueOf(((ImageryLayer)olayer).getDy())), true);
    350                                 action = new DummyAction(currentMapFrame, this);
    351                                 break;
    352                         default:
    353                                 action = new DummyAction(currentMapFrame, this);
    354                                 break;
    355                         }
    356                         currentMapFrame.selectMapMode(action);
    357                         activate();
    358                         textField.select(prefix.length(), textField.getText().length());
    359                 }
    360                 else if (targetMode == Mode.PROCESSING) {
    361                         mode = Mode.PROCESSING;
    362                         prefix = tr("Processing...");
    363                         textField.setText(prefix);
    364                         Main.map.mapView.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    365                 }
    366         }
     262    protected void setMode(Mode targetMode) {
     263        DataSet currentDataSet = Main.main.getCurrentDataSet();
     264        if (currentDataSet != null) {
     265            currentDataSet.clearSelection();
     266            Main.map.mapView.repaint();
     267        }
     268        if (targetMode == Mode.IDLE) {
     269            mode = Mode.IDLE;
     270            currentCommand = null;
     271            prefix = tr("Command") + commandSymbol;
     272            textField.setText(prefix);
     273        }
     274        else if (targetMode == Mode.SELECTION) {
     275            mode = Mode.SELECTION;
     276            Parameter currentParameter = currentCommand.parameters.get(currentCommand.currentParameterNum);
     277            prefix = tr(currentParameter.description == null ? currentParameter.name : currentParameter.description);
     278            if (currentParameter.getRawValue() instanceof Relay)
     279                prefix = prefix + " (" + ((Relay)(currentParameter.getRawValue())).getOptionsString() + ")";
     280            prefix += commandSymbol;
     281            String value = currentParameter.getValue();
     282            textField.setText(prefix + value);
     283            Type currentType = currentParameter.type;
     284            MapMode action = null;
     285            switch (currentType) {
     286            case POINT:
     287                action = new PointAction(currentMapFrame, this);
     288                break;
     289            case WAY:
     290                action = new WayAction(currentMapFrame, this);
     291                break;
     292            case NODE:
     293                action = new NodeAction(currentMapFrame, this);
     294                break;
     295            case RELATION:
     296                action = new RelationAction(currentMapFrame, this);
     297                break;
     298            case ANY:
     299                action = new AnyAction(currentMapFrame, this);
     300                break;
     301            case LENGTH:
     302                action = new LengthAction(currentMapFrame, this);
     303                break;
     304            case USERNAME:
     305                loadParameter(Main.pref.get("osm-server.username", null), true);
     306                action = new DummyAction(currentMapFrame, this);
     307                break;
     308            case IMAGERYURL:
     309                Layer layer = Main.map.mapView.getActiveLayer();
     310                if (layer != null) {
     311                    if (layer instanceof ImageryLayer) {
     312                    }
     313                    else {
     314                        List<ImageryLayer> imageryLayers = Main.map.mapView.getLayersOfType(ImageryLayer.class);
     315                        if (imageryLayers.size() == 1) {
     316                            layer = imageryLayers.get(0);
     317                        }
     318                        else {
     319                            endInput();
     320                            return;
     321                        }
     322                    }
     323                }
     324                ImageryInfo info = ((ImageryLayer)layer).getInfo();
     325                String url = info.getUrl();
     326                String itype = info.getImageryType().getUrlString();
     327                loadParameter((url.equals("") ? itype : url), true);
     328                action = new DummyAction(currentMapFrame, this);
     329                break;
     330            case IMAGERYOFFSET:
     331                Layer olayer = Main.map.mapView.getActiveLayer();
     332                if (olayer != null) {
     333                    if (olayer instanceof ImageryLayer) {
     334                    }
     335                    else {
     336                        List<ImageryLayer> imageryLayers = Main.map.mapView.getLayersOfType(ImageryLayer.class);
     337                        if (imageryLayers.size() == 1) {
     338                            olayer = imageryLayers.get(0);
     339                        }
     340                        else {
     341                            endInput();
     342                            return;
     343                        }
     344                    }
     345                }
     346                loadParameter((String.valueOf(((ImageryLayer)olayer).getDx()) + "," + String.valueOf(((ImageryLayer)olayer).getDy())), true);
     347                action = new DummyAction(currentMapFrame, this);
     348                break;
     349            default:
     350                action = new DummyAction(currentMapFrame, this);
     351                break;
     352            }
     353            currentMapFrame.selectMapMode(action);
     354            activate();
     355            textField.select(prefix.length(), textField.getText().length());
     356        }
     357        else if (targetMode == Mode.PROCESSING) {
     358            mode = Mode.PROCESSING;
     359            prefix = tr("Processing...");
     360            textField.setText(prefix);
     361            Main.map.mapView.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
     362        }
     363    }
    367364
    368         public void activate() {
    369                 textField.requestFocus();
    370                 textField.setCaretPosition(textField.getText().length());
    371         }
     365    public void activate() {
     366        textField.requestFocus();
     367        textField.setCaretPosition(textField.getText().length());
     368    }
    372369
    373         public void deactivate() {
    374                 Main.map.mapView.requestFocus();
    375         }
     370    public void deactivate() {
     371        Main.map.mapView.requestFocus();
     372    }
    376373
    377         public void abortInput() {
    378                 printHistory(tr("Aborted") + ".");
    379                 endInput();
    380         }
     374    public void abortInput() {
     375        printHistory(tr("Aborted") + ".");
     376        endInput();
     377    }
    381378
    382         public void endInput() {
    383                 setMode(Mode.IDLE);
    384                 Main.map.selectMapMode(previousMode);
    385                 Main.map.mapView.repaint();
    386         }
     379    public void endInput() {
     380        setMode(Mode.IDLE);
     381        Main.map.selectMapMode(previousMode);
     382        Main.map.mapView.repaint();
     383    }
    387384
    388         public void loadParameter(Object obj, boolean next) {
    389                 if (currentCommand.loadObject(obj)) {
    390                         if (currentCommand.hasNextParameter()) {
    391                                 if (next) {
    392                                         Parameter currentParameter = currentCommand.parameters.get(currentCommand.currentParameterNum);
    393                                         String prefix = tr(currentParameter.description == null ? currentParameter.name : currentParameter.description);
    394                                         prefix += commandSymbol;
    395                                         String value = currentParameter.getValue();
    396                                         printHistory(prefix + value);
    397                                         currentCommand.nextParameter();
    398                                         setMode(Mode.SELECTION);
    399                                 }
    400                         }
    401                         else {
    402                                 runTool();
    403                         }
    404                 }
    405                 else {
    406                         System.out.println("Invalid argument");
    407                         endInput();
    408                 }
    409         }
     385    public void loadParameter(Object obj, boolean next) {
     386        if (currentCommand.loadObject(obj)) {
     387            if (currentCommand.hasNextParameter()) {
     388                if (next) {
     389                    Parameter currentParameter = currentCommand.parameters.get(currentCommand.currentParameterNum);
     390                    String prefix = tr(currentParameter.description == null ? currentParameter.name : currentParameter.description);
     391                    prefix += commandSymbol;
     392                    String value = currentParameter.getValue();
     393                    printHistory(prefix + value);
     394                    currentCommand.nextParameter();
     395                    setMode(Mode.SELECTION);
     396                }
     397            }
     398            else {
     399                runTool();
     400            }
     401        }
     402        else {
     403            System.out.println("Invalid argument");
     404            endInput();
     405        }
     406    }
    410407
    411         private void parseSelection(Collection<OsmPrimitive> selection) {
    412                 boolean ok = false;
    413                 for (OsmPrimitive obj : selection) {
    414                         ok = currentCommand.loadObject(obj);
    415                         if (!ok)
    416                                 break;
    417                 }
    418                 if (ok) {
    419                         currentCommand.nextParameter();
    420                 }
    421                 else {
    422                         currentCommand.resetLoading();
    423                 }
    424                 //System.out.println("Selected before " + String.valueOf(currentCommand.currentParameterNum) + "\n");
    425         }
     408    private void parseSelection(Collection<OsmPrimitive> selection) {
     409        boolean ok = false;
     410        for (OsmPrimitive obj : selection) {
     411            ok = currentCommand.loadObject(obj);
     412            if (!ok)
     413                break;
     414        }
     415        if (ok) {
     416            currentCommand.nextParameter();
     417        }
     418        else {
     419            currentCommand.resetLoading();
     420        }
     421        //System.out.println("Selected before " + String.valueOf(currentCommand.currentParameterNum) + "\n");
     422    }
    426423
    427         private class ToolProcess {
    428                 public Process process;
    429                 public volatile boolean running;
    430         }
     424    private class ToolProcess {
     425        public Process process;
     426        public volatile boolean running;
     427    }
    431428
    432         // Thanks to Upliner
    433         public void runTool() {
    434                 setMode(Mode.PROCESSING);
    435                 String commandToRun = currentCommand.run;
    436                 final boolean tracks = currentCommand.tracks;
    437                 final ArrayList<Parameter> parameters = currentCommand.parameters;
     429    // Thanks to Upliner
     430    public void runTool() {
     431        setMode(Mode.PROCESSING);
     432        String commandToRun = currentCommand.run;
     433        final boolean tracks = currentCommand.tracks;
     434        final ArrayList<Parameter> parameters = currentCommand.parameters;
    438435
    439                 for (Parameter parameter : currentCommand.parameters) {
    440                         commandToRun = commandToRun.replace("{" + parameter.name + "}", parameter.getValue());
    441                 }
    442                 for (Parameter parameter : currentCommand.optParameters) {
    443                         commandToRun = commandToRun.replace("{" + parameter.name + "}", parameter.getValue());
    444                 }
    445                 String[] listToRun = commandToRun.split(" ");
     436        for (Parameter parameter : currentCommand.parameters) {
     437            commandToRun = commandToRun.replace("{" + parameter.name + "}", parameter.getValue());
     438        }
     439        for (Parameter parameter : currentCommand.optParameters) {
     440            commandToRun = commandToRun.replace("{" + parameter.name + "}", parameter.getValue());
     441        }
     442        String[] listToRun = commandToRun.split(" ");
    446443
    447                 // create the process
    448                 final Object syncObj = new Object();
     444        // create the process
     445        final Object syncObj = new Object();
    449446
    450                 ProcessBuilder builder;
    451                 builder = new ProcessBuilder(listToRun);
    452                 builder.directory(new File(getPluginDir()));
     447        ProcessBuilder builder;
     448        builder = new ProcessBuilder(listToRun);
     449        builder.directory(new File(getPluginDir()));
    453450
    454                 final StringBuilder debugstr = new StringBuilder();
     451        final StringBuilder debugstr = new StringBuilder();
    455452
    456                 // debug: print resulting cmdline
    457                 for (String s : builder.command())
    458                         debugstr.append(s + " ");
    459                 debugstr.append("\n");
    460                 System.out.print(debugstr.toString());
     453        // debug: print resulting cmdline
     454        for (String s : builder.command())
     455            debugstr.append(s + " ");
     456        debugstr.append("\n");
     457        System.out.print(debugstr.toString());
    461458
    462                 final ToolProcess tp = new ToolProcess();
    463                 try {
    464                         tp.process = builder.start();
    465                 } catch (final IOException e) {
    466                         e.printStackTrace();
    467                         synchronized (debugstr) {
    468                                 System.out.print(
    469                                                 tr("Error executing the script: ") +
    470                                                 debugstr.toString() + e.getMessage() + "\n" + e.getStackTrace());
    471                         }
    472                         return;
    473                 }
    474                 tp.running = true;
     459        final ToolProcess tp = new ToolProcess();
     460        try {
     461            tp.process = builder.start();
     462        } catch (final IOException e) {
     463            e.printStackTrace();
     464            synchronized (debugstr) {
     465                System.out.print(
     466                        tr("Error executing the script: ") +
     467                        debugstr.toString() + e.getMessage() + "\n" + e.getStackTrace());
     468            }
     469            return;
     470        }
     471        tp.running = true;
    475472
    476                 // redirect child process's stderr to JOSM stderr
    477                 new Thread(new Runnable() {
    478                         @Override
    479                         public void run() {
    480                                 try {
    481                                         byte[] buffer = new byte[1024];
    482                                         InputStream errStream = tp.process.getErrorStream();
    483                                         int len;
    484                                         while ((len = errStream.read(buffer)) > 0) {
    485                                                 synchronized (debugstr) {
    486                                                         debugstr.append(new String(buffer, 0, len));
    487                                                 }
    488                                                 System.err.write(buffer, 0, len);
    489                                         }
    490                                 } catch (IOException e) {
    491                                 }
    492                         }
    493                 }).start();
     473        // redirect child process's stderr to JOSM stderr
     474        new Thread(new Runnable() {
     475            @Override
     476            public void run() {
     477                try {
     478                    byte[] buffer = new byte[1024];
     479                    InputStream errStream = tp.process.getErrorStream();
     480                    int len;
     481                    while ((len = errStream.read(buffer)) > 0) {
     482                        synchronized (debugstr) {
     483                            debugstr.append(new String(buffer, 0, len));
     484                        }
     485                        System.err.write(buffer, 0, len);
     486                    }
     487                } catch (IOException e) {
     488                }
     489            }
     490        }).start();
    494491
    495                 // Write stdin stream
    496                 Thread osmWriteThread = new Thread(new Runnable() {
    497                         @Override
    498                         public void run() {
    499                                 BBox bbox = null;
    500                                 final OutputStream outputStream = tp.process.getOutputStream();
    501                                 PrintWriter printWriter = null;
    502                                 try { printWriter = new PrintWriter(new OutputStreamWriter(outputStream, "utf-8")); }
    503                                 catch (Exception e) {e.printStackTrace();}
    504                                 final OsmWriter osmWriter = OsmWriterFactory.createOsmWriter(printWriter, true, null);
    505                                 Collection<OsmPrimitive> refObjects = currentCommand.getDepsObjects();
    506                                 Collection<OsmPrimitive> pObjects;
    507                                 osmWriter.header();
    508                                 for (OsmPrimitive primitive : refObjects) {
    509                                         if (primitive instanceof Node)
    510                                                 osmWriter.visit((Node)primitive);
    511                                         else if (primitive instanceof Way)
    512                                                 osmWriter.visit((Way)primitive);
    513                                         else if (primitive instanceof Relation)
    514                                                 osmWriter.visit((Relation)primitive);
    515                                         if (bbox == null)
    516                                                 bbox = new BBox(primitive.getBBox());
    517                                         else
    518                                                 bbox.addPrimitive(primitive, 0.0);
    519                                 }
    520                                 osmWriter.footer();
    521                                 osmWriter.flush();
    522                                 for (Parameter parameter : parameters) {
    523                                         if (!parameter.isOsm())
    524                                                 continue;
    525                                         osmWriter.header();
    526                                         pObjects = parameter.getParameterObjects();
    527                                         for (OsmPrimitive primitive : pObjects) {
    528                                                 if (primitive instanceof Node)
    529                                                         osmWriter.visit((Node)primitive);
    530                                                 else if (primitive instanceof Way)
    531                                                         osmWriter.visit((Way)primitive);
    532                                                 else if (primitive instanceof Relation)
    533                                                         osmWriter.visit((Relation)primitive);
    534                                                 if (bbox == null)
    535                                                         bbox = new BBox(primitive.getBBox());
    536                                                 else
    537                                                         bbox.addPrimitive(primitive, 0.0);
    538                                         }
    539                                         osmWriter.footer();
    540                                         osmWriter.flush();
    541                                 }
    542                                 if (tracks) {
    543                                         final GpxWriter gpxWriter = new GpxWriter(printWriter);
    544                                         GpxFilter gpxFilter = new GpxFilter();
    545                                         gpxFilter.initBboxFilter(bbox);
    546                                         List<GpxLayer> gpxLayers = Main.map.mapView.getLayersOfType(GpxLayer.class);
    547                                         for (GpxLayer gpxLayer : gpxLayers) {
    548                                                 gpxFilter.addGpxData(gpxLayer.data);
    549                                         }
    550                                         gpxWriter.write(gpxFilter.getGpxData());
    551                                 }
    552                                 osmWriter.close();
    553                                 synchronized (syncObj) {
    554                                         tp.running = false;
    555                                         syncObj.notifyAll();
    556                                 }
    557                         }
     492        // Write stdin stream
     493        Thread osmWriteThread = new Thread(new Runnable() {
     494            @Override
     495            public void run() {
     496                BBox bbox = null;
     497                final OutputStream outputStream = tp.process.getOutputStream();
     498                PrintWriter printWriter = null;
     499                try { printWriter = new PrintWriter(new OutputStreamWriter(outputStream, "utf-8")); }
     500                catch (Exception e) {e.printStackTrace();}
     501                final OsmWriter osmWriter = OsmWriterFactory.createOsmWriter(printWriter, true, null);
     502                Collection<OsmPrimitive> refObjects = currentCommand.getDepsObjects();
     503                Collection<OsmPrimitive> pObjects;
     504                osmWriter.header();
     505                DataSet ds = new DataSet();
     506                for (OsmPrimitive primitive : refObjects) {
     507                    ds.addPrimitive(primitive);
     508                    if (bbox == null)
     509                        bbox = new BBox(primitive.getBBox());
     510                    else
     511                        bbox.addPrimitive(primitive, 0.0);
     512                }
     513                for (Parameter parameter : parameters) {
     514                    if (!parameter.isOsm())
     515                        continue;
     516                    pObjects = parameter.getParameterObjects();
     517                    for (OsmPrimitive primitive : pObjects) {
     518                        ds.addPrimitive(primitive);
     519                        if (bbox == null)
     520                            bbox = new BBox(primitive.getBBox());
     521                        else
     522                            bbox.addPrimitive(primitive, 0.0);
     523                    }
     524                }
     525                osmWriter.writeContent(ds);
     526                osmWriter.footer();
     527                osmWriter.flush();
     528                if (tracks) {
     529                    final GpxWriter gpxWriter = new GpxWriter(printWriter);
     530                    GpxFilter gpxFilter = new GpxFilter();
     531                    gpxFilter.initBboxFilter(bbox);
     532                    List<GpxLayer> gpxLayers = Main.map.mapView.getLayersOfType(GpxLayer.class);
     533                    for (GpxLayer gpxLayer : gpxLayers) {
     534                        gpxFilter.addGpxData(gpxLayer.data);
     535                    }
     536                    gpxWriter.write(gpxFilter.getGpxData());
     537                }
     538                osmWriter.close();
     539                synchronized (syncObj) {
     540                    tp.running = false;
     541                    syncObj.notifyAll();
     542                }
     543            }
    558544
    559                 });
     545        });
    560546
    561                 // Read stdout stream
    562                 final OsmToCmd osmToCmd = new OsmToCmd(this, Main.main.getCurrentDataSet());
    563                 Thread osmParseThread = new Thread(new Runnable() {
    564                         @Override
    565                         public void run() {
    566                                 try {
    567                                         String commandName = currentCommand.name;
    568                                         HashMap<Long, Long> inexiDMap = new HashMap<Long, Long>();
    569                                         final InputStream inputStream = tp.process.getInputStream();
    570                                         osmToCmd.parseStream(inputStream);
    571                                         final List<org.openstreetmap.josm.command.Command> cmdlist = osmToCmd.getCommandList();
    572                                         if (!cmdlist.isEmpty()) {
    573                                                 SequenceCommand cmd = new SequenceCommand(commandName, cmdlist);
    574                                                 Main.main.undoRedo.add(cmd);
    575                                         }
    576                                 }
    577                                 catch (Exception e) {}
    578                                 finally {
    579                                         synchronized (syncObj) {
    580                                                 tp.running = false;
    581                                                 syncObj.notifyAll();
    582                                         }
    583                                 }
    584                         }
     547        // Read stdout stream
     548        final OsmToCmd osmToCmd = new OsmToCmd(this, Main.main.getCurrentDataSet());
     549        Thread osmParseThread = new Thread(new Runnable() {
     550            @Override
     551            public void run() {
     552                try {
     553                    String commandName = currentCommand.name;
     554                    //HashMap<Long, Long> inexiDMap = new HashMap<Long, Long>();
     555                    final InputStream inputStream = tp.process.getInputStream();
     556                    osmToCmd.parseStream(inputStream);
     557                    final List<org.openstreetmap.josm.command.Command> cmdlist = osmToCmd.getCommandList();
     558                    if (!cmdlist.isEmpty()) {
     559                        SequenceCommand cmd = new SequenceCommand(commandName, cmdlist);
     560                        Main.main.undoRedo.add(cmd);
     561                    }
     562                }
     563                catch (Exception e) {}
     564                finally {
     565                    synchronized (syncObj) {
     566                        tp.running = false;
     567                        syncObj.notifyAll();
     568                    }
     569                }
     570            }
    585571
    586                 });
     572        });
    587573
    588                 osmParseThread.start();
    589                 osmWriteThread.start();
     574        osmParseThread.start();
     575        osmWriteThread.start();
    590576
    591                 synchronized (syncObj) {
    592                         try {
    593                                 syncObj.wait(10000);
    594                         } catch (InterruptedException e) {
    595                         }
    596                 }
    597                 if (tp.running) {
    598                         new Thread(new PleaseWaitRunnable(currentCommand.name) {
    599                                 @Override
    600                                 protected void realRun() {
    601                                         try {
    602                                                 progressMonitor.indeterminateSubTask(null);
    603                                                 synchronized (syncObj) {
    604                                                         if (tp.running)
    605                                                                 syncObj.wait();
    606                                                 }
    607                                         } catch (InterruptedException e) {
    608                                         }
    609                                 }
     577        synchronized (syncObj) {
     578            try {
     579                syncObj.wait(10000);
     580            } catch (InterruptedException e) {
     581            }
     582        }
     583        if (tp.running) {
     584            new Thread(new PleaseWaitRunnable(currentCommand.name) {
     585                @Override
     586                protected void realRun() {
     587                    try {
     588                        progressMonitor.indeterminateSubTask(null);
     589                        synchronized (syncObj) {
     590                            if (tp.running)
     591                                syncObj.wait();
     592                        }
     593                    } catch (InterruptedException e) {
     594                    }
     595                }
    610596
    611                                 @Override
    612                                 protected void cancel() {
    613                                         synchronized (syncObj) {
    614                                                 tp.running = false;
    615                                                 tp.process.destroy();
    616                                                 syncObj.notifyAll();
    617                                                 endInput();
    618                                         }
    619                                 }
     597                @Override
     598                protected void cancel() {
     599                    synchronized (syncObj) {
     600                        tp.running = false;
     601                        tp.process.destroy();
     602                        syncObj.notifyAll();
     603                        endInput();
     604                    }
     605                }
    620606
    621                                 @Override
    622                                 protected void finish() {
    623                                 }
    624                         }).start();
    625                 }
    626                 endInput();
    627         }
     607                @Override
     608                protected void finish() {
     609                }
     610            }).start();
     611        }
     612        endInput();
     613    }
    628614}