/**
   * Prompts the user with a list of WMS layers which can be adjusted
   *
   * @param adjustableLayers the list of adjustable layers
   * @return the selected layer; null, if no layer was selected
   */
  protected Layer askAdjustLayer(List<? extends Layer> adjustableLayers) {
    if (adjustableLayers.size() == 0) return null;
    if (adjustableLayers.size() == 1) return adjustableLayers.get(0);
    JComboBox<Layer> layerList = new JComboBox<>();
    layerList.setRenderer(new LayerListCellRenderer());
    layerList.setModel(new DefaultComboBoxModel<>(adjustableLayers.toArray(new Layer[0])));
    layerList.setSelectedIndex(0);

    JPanel pnl = new JPanel();
    pnl.setLayout(new GridBagLayout());
    pnl.add(new JLabel(tr("Please select the imagery layer to adjust.")), GBC.eol());
    pnl.add(layerList, GBC.eol());

    ExtendedDialog diag =
        new ExtendedDialog(
            Main.parent,
            tr("Select imagery layer"),
            new String[] {tr("Start adjusting"), tr("Cancel")});
    diag.setContent(pnl);
    diag.setButtonIcons(new String[] {"mapmode/adjustimg", "cancel"});
    diag.showDialog();
    int decision = diag.getValue();
    if (decision != 1) return null;
    Layer adjustLayer = (Layer) layerList.getSelectedItem();
    return adjustLayer;
  }
  public void addGui(final DownloadDialog gui) {
    buildDownloadAreaInputFields();
    final JPanel dlg = new JPanel(new GridBagLayout());

    tfOsmUrl.getDocument().addDocumentListener(new OsmUrlRefresher());

    // select content on receiving focus. this seems to be the default in the
    // windows look+feel but not for others. needs invokeLater to avoid strange
    // side effects that will cancel out the newly made selection otherwise.
    tfOsmUrl.addFocusListener(new SelectAllOnFocusHandler(tfOsmUrl));
    tfOsmUrl.setLineWrap(true);
    tfOsmUrl.setBorder(latlon[0].getBorder());

    dlg.add(new JLabel(tr("min lat")), GBC.std().insets(10, 20, 5, 0));
    dlg.add(latlon[0], GBC.std().insets(0, 20, 0, 0));
    dlg.add(new JLabel(tr("min lon")), GBC.std().insets(10, 20, 5, 0));
    dlg.add(latlon[1], GBC.eol().insets(0, 20, 0, 0));
    dlg.add(new JLabel(tr("max lat")), GBC.std().insets(10, 0, 5, 0));
    dlg.add(latlon[2], GBC.std());
    dlg.add(new JLabel(tr("max lon")), GBC.std().insets(10, 0, 5, 0));
    dlg.add(latlon[3], GBC.eol());

    dlg.add(
        new JLabel(
            tr("URL from www.openstreetmap.org (you can paste an URL here to download the area)")),
        GBC.eol().insets(10, 20, 5, 0));
    dlg.add(tfOsmUrl, GBC.eop().insets(10, 0, 5, 0).fill());
    tfOsmUrl.addMouseListener(
        new MouseAdapter() {
          @Override
          public void mousePressed(MouseEvent e) {
            checkPopup(e);
          }

          @Override
          public void mouseClicked(MouseEvent e) {
            checkPopup(e);
          }

          @Override
          public void mouseReleased(MouseEvent e) {
            checkPopup(e);
          }

          private void checkPopup(MouseEvent e) {
            if (e.isPopupTrigger()) {
              OsmUrlPopup popup = new OsmUrlPopup();
              popup.show(tfOsmUrl, e.getX(), e.getY());
            }
          }
        });
    dlg.add(showUrl, GBC.eop().insets(10, 0, 5, 5));
    showUrl.setEditable(false);
    showUrl.setBackground(dlg.getBackground());
    showUrl.addFocusListener(new SelectAllOnFocusHandler(showUrl));

    gui.addDownloadAreaSelector(dlg, tr("Bounding Box"));
    this.parent = gui;
  }
Ejemplo n.º 3
0
    protected void buildPanel() {
      setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
      add(
          new JLabel(preferenceSetting.getTitle()),
          GBC.eol().insets(0, 5, 0, 10).anchor(GBC.NORTHWEST));

      JLabel descLabel = new JLabel("<html>" + preferenceSetting.getDescription() + "</html>");
      descLabel.setFont(descLabel.getFont().deriveFont(Font.ITALIC));
      add(descLabel, GBC.eol().insets(5, 0, 5, 20).fill(GBC.HORIZONTAL));
    }
Ejemplo n.º 4
0
  private Component buildSettingsPanel() {
    final JPanel p = new JPanel(new GridBagLayout());
    p.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

    addSettingsSection(p, tr("Common Settings"), commonSettings);
    addSettingsSection(p, tr("WMS Settings"), wmsSettings, GBC.eol().fill(GBC.HORIZONTAL));
    addSettingsSection(p, tr("TMS Settings"), tmsSettings, GBC.eol().fill(GBC.HORIZONTAL));

    p.add(new JPanel(), GBC.eol().fill(GBC.BOTH));
    return GuiHelper.setDefaultIncrement(new JScrollPane(p));
  }
Ejemplo n.º 5
0
    private void build() {
      filter = new JosmTextField(30);
      filter.setColumns(10);
      filter.getDocument().addDocumentListener(this);

      selectionList = new JList<>(data.toArray(new String[0]));
      selectionList.setModel(model = new ProjectionCodeListModel());
      JScrollPane scroll = new JScrollPane(selectionList);
      scroll.setPreferredSize(new Dimension(200, 214));

      this.setLayout(new GridBagLayout());
      this.add(filter, GBC.eol().weight(1.0, 0.0));
      this.add(scroll, GBC.eol());
    }
Ejemplo n.º 6
0
  protected JPanel buildSearchPanel() {
    JPanel lpanel = new JPanel(new GridLayout(2, 2));
    JPanel panel = new JPanel(new GridBagLayout());

    lpanel.add(new JLabel(tr("Choose the server for searching:")));
    lpanel.add(server);
    String s = Main.pref.get("namefinder.server", SERVERS[0].name);
    for (int i = 0; i < SERVERS.length; ++i) {
      if (SERVERS[i].name.equals(s)) {
        server.setSelectedIndex(i);
      }
    }
    lpanel.add(new JLabel(tr("Enter a place name to search for:")));

    cbSearchExpression = new HistoryComboBox();
    cbSearchExpression.setToolTipText(tr("Enter a place name to search for"));
    List<String> cmtHistory =
        new LinkedList<>(Main.pref.getCollection(HISTORY_KEY, new LinkedList<String>()));
    Collections.reverse(cmtHistory);
    cbSearchExpression.setPossibleItems(cmtHistory);
    lpanel.add(cbSearchExpression);

    panel.add(lpanel, GBC.std().fill(GBC.HORIZONTAL).insets(5, 5, 0, 5));
    SearchAction searchAction = new SearchAction();
    JButton btnSearch = new JButton(searchAction);
    cbSearchExpression.getEditorComponent().getDocument().addDocumentListener(searchAction);
    cbSearchExpression.getEditorComponent().addActionListener(searchAction);

    panel.add(btnSearch, GBC.eol().insets(5, 5, 0, 5));

    return panel;
  }
Ejemplo n.º 7
0
  @Override
  protected final JPanel build() {
    JPanel p = new JPanel(new GridBagLayout());
    p.add(new JLabel(tr("Key: {0}", entry.getKey())), GBC.eol().insets(0, 0, 5, 0));
    ListSettingTableModel listModel = new ListSettingTableModel();
    JTable table = new JTable(listModel);
    table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
    table.setTableHeader(null);

    DefaultCellEditor editor = new DefaultCellEditor(new JosmTextField());
    editor.setClickCountToStart(1);
    table.setDefaultEditor(table.getColumnClass(0), editor);

    JScrollPane pane = new JScrollPane(table);
    p.add(pane, GBC.eol().insets(5, 10, 0, 0).fill());
    return p;
  }
Ejemplo n.º 8
0
 private static void addSettingsSection(final JPanel p, String name, JPanel section, GBC gbc) {
   final JLabel lbl = new JLabel(name);
   lbl.setFont(lbl.getFont().deriveFont(Font.BOLD));
   lbl.setLabelFor(section);
   p.add(lbl, GBC.std());
   p.add(new JSeparator(), GBC.eol().fill(GBC.HORIZONTAL).insets(5, 0, 0, 0));
   p.add(section, gbc.insets(20, 5, 0, 10));
 }
Ejemplo n.º 9
0
    /**
     * Constructs a new {@code OffsetBookmarksPanel}.
     *
     * @param gui the preferences tab pane
     */
    OffsetBookmarksPanel(final PreferenceTabbedPane gui) {
      super(new GridBagLayout());
      final JTable list =
          new JTable(model) {
            @Override
            public String getToolTipText(MouseEvent e) {
              java.awt.Point p = e.getPoint();
              return model.getValueAt(rowAtPoint(p), columnAtPoint(p)).toString();
            }
          };
      JScrollPane scroll = new JScrollPane(list);
      add(scroll, GBC.eol().fill(GridBagConstraints.BOTH));
      scroll.setPreferredSize(new Dimension(200, 200));

      TableColumnModel mod = list.getColumnModel();
      mod.getColumn(0).setPreferredWidth(150);
      mod.getColumn(1).setPreferredWidth(200);
      mod.getColumn(2).setPreferredWidth(300);
      mod.getColumn(3).setPreferredWidth(150);
      mod.getColumn(4).setPreferredWidth(150);

      JPanel buttonPanel = new JPanel(new FlowLayout());

      JButton add = new JButton(tr("Add"));
      buttonPanel.add(add, GBC.std().insets(0, 5, 0, 0));
      add.addActionListener(
          e -> model.addRow(new OffsetBookmark(Main.getProjection().toCode(), "", "", 0, 0)));

      JButton delete = new JButton(tr("Delete"));
      buttonPanel.add(delete, GBC.std().insets(0, 5, 0, 0));
      delete.addActionListener(
          e -> {
            if (list.getSelectedRow() == -1) {
              JOptionPane.showMessageDialog(gui, tr("Please select the row to delete."));
            } else {
              Integer i;
              while ((i = list.getSelectedRow()) != -1) {
                model.removeRow(i);
              }
            }
          });

      add(buttonPanel, GBC.eol());
    }
Ejemplo n.º 10
0
  protected Layer askTargetLayer(List<Layer> targetLayers) {
    JosmComboBox layerList = new JosmComboBox(targetLayers.toArray());
    layerList.setRenderer(new LayerListCellRenderer());
    layerList.setSelectedIndex(0);

    JPanel pnl = new JPanel(new GridBagLayout());
    pnl.add(new JLabel(tr("Please select the target layer.")), GBC.eol());
    pnl.add(layerList, GBC.eol());

    ExtendedDialog ed =
        new ExtendedDialog(
            Main.parent, tr("Select target layer"), new String[] {tr("Merge"), tr("Cancel")});
    ed.setButtonIcons(new String[] {"dialogs/mergedown", "cancel"});
    ed.setContent(pnl);
    ed.showDialog();
    if (ed.getValue() != 1) return null;

    Layer targetLayer = (Layer) layerList.getSelectedItem();
    return targetLayer;
  }
Ejemplo n.º 11
0
  /**
   * Allow the tester to manage its own preferences
   *
   * @param testPanel The panel to add any preferences component
   */
  public void addGui(JPanel testPanel) {
    checkEnabled = new JCheckBox(name, enabled);
    checkEnabled.setToolTipText(description);
    testPanel.add(checkEnabled, GBC.std());

    GBC a = GBC.eol();
    a.anchor = GridBagConstraints.EAST;
    checkBeforeUpload = new JCheckBox();
    checkBeforeUpload.setSelected(testBeforeUpload);
    testPanel.add(checkBeforeUpload, a);
  }
Ejemplo n.º 12
0
 /**
  * Area "a" contains the hull that we would like to download data for. however we can only
  * download rectangles, so the following is an attempt at finding a number of rectangles to
  * download.
  *
  * <p>The idea is simply: Start out with the full bounding box. If it is too large, then split it
  * in half and repeat recursively for each half until you arrive at something small enough to
  * download. The algorithm is improved by always using the intersection between the rectangle and
  * the actual desired area. For example, if you have a track that goes like this: +----+ | /| | /
  * | | / | |/ | +----+ then we would first look at downloading the whole rectangle (assume it's
  * too big), after that we split it in half (upper and lower half), but we donot request the full
  * upper and lower rectangle, only the part of the upper/lower rectangle that actually has
  * something in it.
  *
  * <p>This functions calculates the rectangles, asks the user to continue and downloads the areas
  * if applicable.
  */
 protected static void confirmAndDownloadAreas(
     Area a,
     double max_area,
     boolean osmDownload,
     boolean gpxDownload,
     String title,
     ProgressMonitor progressMonitor) {
   List<Rectangle2D> toDownload = new ArrayList<Rectangle2D>();
   addToDownload(a, a.getBounds(), toDownload, max_area);
   if (toDownload.isEmpty()) {
     return;
   }
   JPanel msg = new JPanel(new GridBagLayout());
   msg.add(
       new JLabel(
           tr(
               "<html>This action will require {0} individual<br>"
                   + "download requests. Do you wish<br>to continue?</html>",
               toDownload.size())),
       GBC.eol());
   if (JOptionPane.OK_OPTION
       != JOptionPane.showConfirmDialog(
           Main.parent, msg, title, JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE)) {
     return;
   }
   final PleaseWaitProgressMonitor monitor = new PleaseWaitProgressMonitor(tr("Download data"));
   final Future<?> future =
       new DownloadTaskList().download(false, toDownload, osmDownload, gpxDownload, monitor);
   Main.worker.submit(
       new Runnable() {
         @Override
         public void run() {
           try {
             future.get();
           } catch (Exception e) {
             e.printStackTrace();
             return;
           }
           monitor.close();
         }
       });
 }
Ejemplo n.º 13
0
  @Override
  public Object getInfoComponent() {
    final DataCountVisitor counter = new DataCountVisitor();
    for (final OsmPrimitive osm : data.allPrimitives()) osm.visit(counter);
    final JPanel p = new JPanel(new GridBagLayout());
    p.add(new JLabel(tr("{0} consists of:", name)), GBC.eol());
    for (int i = 0; i < counter.normal.length; ++i) {
      String s =
          counter.normal[i]
              + " "
              + trn(counter.names[i], counter.names[i] + "s", counter.normal[i]);
      if (counter.deleted[i] > 0) s += tr(" ({0} deleted.)", counter.deleted[i]);
      p.add(
          new JLabel(s, ImageProvider.get("data", counter.names[i]), JLabel.HORIZONTAL),
          GBC.eop().insets(15, 0, 0, 0));
    }
    p.add(new JLabel(tr("API version: {0}", (data.version != null) ? data.version : tr("unset"))));

    return p;
  }
Ejemplo n.º 14
0
  /** Creates cache content panel */
  public CacheContentsPanel() {
    super(new GridBagLayout());
    CacheAccess<String, BufferedImageCacheEntry> cache = TMSLayer.getCache();
    add(
        new JLabel(tr("TMS cache, total cache size: {0} bytes", getCacheSize(cache))),
        GBC.eol().insets(5, 5, 0, 0));
    add(new JScrollPane(getTableForCache(cache)), GBC.eol().fill(GBC.BOTH));

    cache = WMSLayer.getCache();
    add(
        new JLabel(tr("WMS cache, total cache size: {0} bytes", getCacheSize(cache))),
        GBC.eol().insets(5, 5, 0, 0));
    add(new JScrollPane(getTableForCache(cache)), GBC.eol().fill(GBC.BOTH));

    cache = WMTSLayer.getCache();
    add(
        new JLabel(tr("WMTS cache, total cache size: {0} bytes", getCacheSize(cache))),
        GBC.eol().insets(5, 5, 0, 0));

    add(new JScrollPane(getTableForCache(cache)), GBC.eol().fill(GBC.BOTH));

    executor.shutdown();
  }
Ejemplo n.º 15
0
  @Override
  public JPanel getExportPanel() {
    final JPanel p = new JPanel(new GridBagLayout());
    JPanel topRow = new JPanel(new GridBagLayout());
    export = new JCheckBox();
    export.setSelected(true);
    final JLabel lbl = new JLabel(layer.getName(), layer.getIcon(), SwingConstants.LEFT);
    lbl.setToolTipText(layer.getToolTipText());

    JLabel lblData = new JLabel(tr("Data:"));
    /* I18n: Refer to a OSM data file in session file */ link = new JRadioButton(tr("local file"));
    link.putClientProperty("actionname", "link");
    link.setToolTipText(tr("Link to a OSM data file on your local disk."));
    /* I18n: Include OSM data in session file */ include = new JRadioButton(tr("include"));
    include.setToolTipText(tr("Include OSM data in the .joz session file."));
    include.putClientProperty("actionname", "include");
    ButtonGroup group = new ButtonGroup();
    group.add(link);
    group.add(include);

    JPanel cardLink = new JPanel(new GridBagLayout());
    final File file = layer.getAssociatedFile();
    final LayerSaveAction saveAction = new LayerSaveAction();
    final JButton save = new JButton(saveAction);
    if (file != null) {
      JosmTextField tf = new JosmTextField();
      tf.setText(file.getPath());
      tf.setEditable(false);
      cardLink.add(tf, GBC.std());
      save.setMargin(new Insets(0, 0, 0, 0));
      cardLink.add(save, GBC.eol().insets(2, 0, 0, 0));
    } else {
      cardLink.add(new JLabel(tr("No file association")), GBC.eol());
    }

    JPanel cardInclude = new JPanel(new GridBagLayout());
    JLabel lblIncl = new JLabel(tr("OSM data will be included in the session file."));
    lblIncl.setFont(lblIncl.getFont().deriveFont(Font.PLAIN));
    cardInclude.add(lblIncl, GBC.eol().fill(GBC.HORIZONTAL));

    final CardLayout cl = new CardLayout();
    final JPanel cards = new JPanel(cl);
    cards.add(cardLink, "link");
    cards.add(cardInclude, "include");

    if (file != null) {
      link.setSelected(true);
    } else {
      link.setEnabled(false);
      link.setToolTipText(tr("No file association"));
      include.setSelected(true);
      cl.show(cards, "include");
    }

    link.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            cl.show(cards, "link");
          }
        });
    include.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            cl.show(cards, "include");
          }
        });

    topRow.add(export, GBC.std());
    topRow.add(lbl, GBC.std());
    topRow.add(GBC.glue(1, 0), GBC.std().fill(GBC.HORIZONTAL));
    p.add(topRow, GBC.eol().fill(GBC.HORIZONTAL));
    p.add(lblData, GBC.std().insets(10, 0, 0, 0));
    p.add(link, GBC.std());
    p.add(include, GBC.eol());
    p.add(cards, GBC.eol().insets(15, 0, 3, 3));

    export.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.DESELECTED) {
              GuiHelper.setEnabledRec(p, false);
              export.setEnabled(true);
            } else {
              GuiHelper.setEnabledRec(p, true);
              save.setEnabled(saveAction.isEnabled());
              link.setEnabled(file != null);
            }
          }
        });
    return p;
  }
Ejemplo n.º 16
0
 @Override
 public void addGui(PreferenceTabbedPane gui) {
   gui.createPreferenceTab(this).add(getTabPane(), GBC.eol().fill(GBC.BOTH));
 }
Ejemplo n.º 17
0
  private JPanel buildPanel(boolean modified) {
    JPanel pnl = new JPanel(new GridBagLayout());

    pnl.add(Box.createRigidArea(new Dimension(400, 0)), GBC.eol().fill(GBC.HORIZONTAL));

    pnl.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    pnl.add(
        new JLabel(
            "<html>"
                + tr(
                    "This operation makes JOSM forget the selected objects.<br> "
                        + "They will be removed from the layer, but <i>not</i> deleted<br> "
                        + "on the server when uploading.")
                + "</html>",
            ImageProvider.get("purge"),
            JLabel.LEFT),
        GBC.eol().fill(GBC.HORIZONTAL));

    if (!toPurgeAdditionally.isEmpty()) {
      pnl.add(new JSeparator(), GBC.eol().fill(GBC.HORIZONTAL).insets(0, 5, 0, 5));
      pnl.add(
          new JLabel(
              "<html>"
                  + tr(
                      "The following dependent objects will be purged<br> "
                          + "in addition to the selected objects:")
                  + "</html>",
              ImageProvider.get("warning-small"),
              JLabel.LEFT),
          GBC.eol().fill(GBC.HORIZONTAL));

      Collections.sort(
          toPurgeAdditionally,
          new Comparator<OsmPrimitive>() {
            public int compare(OsmPrimitive o1, OsmPrimitive o2) {
              int type = o2.getType().compareTo(o1.getType());
              if (type != 0) return type;
              return (Long.valueOf(o1.getUniqueId())).compareTo(o2.getUniqueId());
            }
          });
      JList list = new JList(toPurgeAdditionally.toArray(new OsmPrimitive[0]));
      /* force selection to be active for all entries */
      list.setCellRenderer(
          new OsmPrimitivRenderer() {
            @Override
            public Component getListCellRendererComponent(
                JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
              return super.getListCellRendererComponent(list, value, index, true, false);
            }
          });
      JScrollPane scroll = new JScrollPane(list);
      scroll.setPreferredSize(new Dimension(250, 300));
      scroll.setMinimumSize(new Dimension(250, 300));
      pnl.add(scroll, GBC.std().fill(GBC.VERTICAL).weight(0.0, 1.0));

      JButton addToSelection =
          new JButton(
              new AbstractAction() {
                {
                  putValue(SHORT_DESCRIPTION, tr("Add to selection"));
                  putValue(SMALL_ICON, ImageProvider.get("dialogs", "select"));
                }

                public void actionPerformed(ActionEvent e) {
                  layer.data.addSelected(toPurgeAdditionally);
                }
              });
      addToSelection.setMargin(new Insets(0, 0, 0, 0));
      pnl.add(addToSelection, GBC.eol().anchor(GBC.SOUTHWEST).weight(1.0, 1.0).insets(2, 0, 0, 3));
    }

    if (modified) {
      pnl.add(new JSeparator(), GBC.eol().fill(GBC.HORIZONTAL).insets(0, 5, 0, 5));
      pnl.add(
          new JLabel(
              "<html>"
                  + tr(
                      "Some of the objects are modified.<br> "
                          + "Proceed, if these changes should be discarded."
                          + "</html>"),
              ImageProvider.get("warning-small"),
              JLabel.LEFT),
          GBC.eol().fill(GBC.HORIZONTAL));
    }

    cbClearUndoRedo = new JCheckBox(tr("Clear Undo/Redo buffer"));
    cbClearUndoRedo.setSelected(Main.pref.getBoolean("purge.clear_undo_redo", false));

    pnl.add(new JSeparator(), GBC.eol().fill(GBC.HORIZONTAL).insets(0, 5, 0, 5));
    pnl.add(cbClearUndoRedo, GBC.eol());
    return pnl;
  }
Ejemplo n.º 18
0
  protected Collection<Command> applyCorrections(
      Map<OsmPrimitive, List<TagCorrection>> tagCorrectionsMap,
      Map<OsmPrimitive, List<RoleCorrection>> roleCorrectionMap,
      String description)
      throws UserCancelException {

    if (!tagCorrectionsMap.isEmpty() || !roleCorrectionMap.isEmpty()) {
      Collection<Command> commands = new ArrayList<Command>();
      Map<OsmPrimitive, TagCorrectionTable> tagTableMap =
          new HashMap<OsmPrimitive, TagCorrectionTable>();
      Map<OsmPrimitive, RoleCorrectionTable> roleTableMap =
          new HashMap<OsmPrimitive, RoleCorrectionTable>();

      final JPanel p = new JPanel(new GridBagLayout());

      final JMultilineLabel label1 = new JMultilineLabel(description);
      label1.setMaxWidth(600);
      p.add(label1, GBC.eop().anchor(GBC.CENTER));

      final JMultilineLabel label2 =
          new JMultilineLabel(tr("Please select which changes you want to apply."));
      label2.setMaxWidth(600);
      p.add(label2, GBC.eop().anchor(GBC.CENTER));

      for (Entry<OsmPrimitive, List<TagCorrection>> entry : tagCorrectionsMap.entrySet()) {
        final OsmPrimitive primitive = entry.getKey();
        final List<TagCorrection> tagCorrections = entry.getValue();

        if (tagCorrections.isEmpty()) {
          continue;
        }

        final JLabel propertiesLabel = new JLabel(tr("Tags of "));
        p.add(propertiesLabel, GBC.std());

        final JLabel primitiveLabel =
            new JLabel(
                primitive.getDisplayName(DefaultNameFormatter.getInstance()) + ":",
                ImageProvider.get(primitive.getDisplayType()),
                JLabel.LEFT);
        p.add(primitiveLabel, GBC.eol());

        final TagCorrectionTable table = new TagCorrectionTable(tagCorrections);
        final JScrollPane scrollPane = new JScrollPane(table);
        p.add(scrollPane, GBC.eop().fill(GBC.HORIZONTAL));

        tagTableMap.put(primitive, table);
      }

      for (Entry<OsmPrimitive, List<RoleCorrection>> entry : roleCorrectionMap.entrySet()) {
        final OsmPrimitive primitive = entry.getKey();
        final List<RoleCorrection> roleCorrections = entry.getValue();

        if (roleCorrections.isEmpty()) {
          continue;
        }

        final JLabel rolesLabel = new JLabel(tr("Roles in relations referring to"));
        p.add(rolesLabel, GBC.std());

        final JLabel primitiveLabel =
            new JLabel(
                primitive.getDisplayName(DefaultNameFormatter.getInstance()),
                ImageProvider.get(primitive.getDisplayType()),
                JLabel.LEFT);
        p.add(primitiveLabel, GBC.eol());

        final RoleCorrectionTable table = new RoleCorrectionTable(roleCorrections);
        final JScrollPane scrollPane = new JScrollPane(table);
        p.add(scrollPane, GBC.eop().fill(GBC.HORIZONTAL));

        roleTableMap.put(primitive, table);
      }

      int answer =
          JOptionPane.showOptionDialog(
              Main.parent,
              p,
              tr("Automatic tag correction"),
              JOptionPane.YES_NO_CANCEL_OPTION,
              JOptionPane.PLAIN_MESSAGE,
              null,
              applicationOptions,
              applicationOptions[0]);

      if (answer == JOptionPane.YES_OPTION) {
        for (Entry<OsmPrimitive, List<TagCorrection>> entry : tagCorrectionsMap.entrySet()) {
          List<TagCorrection> tagCorrections = entry.getValue();
          OsmPrimitive primitive = entry.getKey();

          // create the clone
          OsmPrimitive clone = null;
          if (primitive instanceof Way) {
            clone = new Way((Way) primitive);
          } else if (primitive instanceof Node) {
            clone = new Node((Node) primitive);
          } else if (primitive instanceof Relation) {
            clone = new Relation((Relation) primitive);
          } else throw new AssertionError();

          // use this structure to remember keys that have been set already so that
          // they're not dropped by a later step
          Set<String> keysChanged = new HashSet<String>();

          // apply all changes to this clone
          for (int i = 0; i < tagCorrections.size(); i++) {
            if (tagTableMap.get(primitive).getCorrectionTableModel().getApply(i)) {
              TagCorrection tagCorrection = tagCorrections.get(i);
              if (tagCorrection.isKeyChanged() && !keysChanged.contains(tagCorrection.oldKey)) {
                clone.remove(tagCorrection.oldKey);
              }
              clone.put(tagCorrection.newKey, tagCorrection.newValue);
              keysChanged.add(tagCorrection.newKey);
            }
          }

          // save the clone
          if (!keysChanged.isEmpty()) {
            commands.add(new ChangeCommand(primitive, clone));
          }
        }
        for (Entry<OsmPrimitive, List<RoleCorrection>> entry : roleCorrectionMap.entrySet()) {
          OsmPrimitive primitive = entry.getKey();
          List<RoleCorrection> roleCorrections = entry.getValue();

          for (int i = 0; i < roleCorrections.size(); i++) {
            RoleCorrection roleCorrection = roleCorrections.get(i);
            if (roleTableMap.get(primitive).getCorrectionTableModel().getApply(i)) {
              commands.add(
                  new ChangeRelationMemberRoleCommand(
                      roleCorrection.relation, roleCorrection.position, roleCorrection.newRole));
            }
          }
        }
      } else if (answer != JOptionPane.NO_OPTION) throw new UserCancelException();
      return commands;
    }

    return Collections.emptyList();
  }
Ejemplo n.º 19
0
  public AddWMSLayerPanel() {
    JPanel wmsFetchPanel = new JPanel(new GridBagLayout());
    menuName = new JTextField(40);
    menuName.setText(tr("Unnamed WMS Layer"));
    final JTextArea serviceUrl = new JTextArea(3, 40);
    serviceUrl.setLineWrap(true);
    serviceUrl.setText("http://sample.com/wms?");
    wmsFetchPanel.add(new JLabel(tr("Menu Name")), GBC.std().insets(0, 0, 5, 0));
    wmsFetchPanel.add(menuName, GBC.eop().insets(5, 0, 0, 0).fill(GridBagConstraints.HORIZONTAL));
    wmsFetchPanel.add(new JLabel(tr("Service URL")), GBC.std().insets(0, 0, 5, 0));
    JScrollPane scrollPane =
        new JScrollPane(
            serviceUrl,
            JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    wmsFetchPanel.add(scrollPane, GBC.eop().insets(5, 0, 0, 0));
    JButton getLayersButton = new JButton(tr("Get Layers"));
    getLayersButton.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            Cursor beforeCursor = getCursor();
            try {
              setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
              attemptGetCapabilities(serviceUrl.getText());
            } finally {
              setCursor(beforeCursor);
            }
          }
        });
    wmsFetchPanel.add(getLayersButton, GBC.eop().anchor(GridBagConstraints.EAST));

    treeRootNode = new DefaultMutableTreeNode();
    treeData = new DefaultTreeModel(treeRootNode);
    layerTree = new JTree(treeData);
    layerTree.setCellRenderer(new LayerTreeCellRenderer());
    layerTree.addTreeSelectionListener(
        new TreeSelectionListener() {

          @Override
          public void valueChanged(TreeSelectionEvent e) {
            TreePath[] selectionRows = layerTree.getSelectionPaths();
            if (selectionRows == null) {
              showBoundsButton.setEnabled(false);
              selectedLayer = null;
              return;
            }

            selectedLayers = new LinkedList<LayerDetails>();
            for (TreePath i : selectionRows) {
              Object userObject =
                  ((DefaultMutableTreeNode) i.getLastPathComponent()).getUserObject();
              if (userObject instanceof LayerDetails) {
                LayerDetails detail = (LayerDetails) userObject;
                if (!detail.isSupported()) {
                  layerTree.removeSelectionPath(i);
                  if (!previouslyShownUnsupportedCrsError) {
                    JOptionPane.showMessageDialog(
                        null,
                        tr(
                            "That layer does not support any of JOSM's projections,\n"
                                + "so you can not use it. This message will not show again."),
                        tr("WMS Error"),
                        JOptionPane.ERROR_MESSAGE);
                    previouslyShownUnsupportedCrsError = true;
                  }
                } else if (detail.ident != null) {
                  selectedLayers.add(detail);
                }
              }
            }

            if (!selectedLayers.isEmpty()) {
              resultingLayerField.setText(buildGetMapUrl());

              if (selectedLayers.size() == 1) {
                showBoundsButton.setEnabled(true);
                selectedLayer = selectedLayers.get(0);
              }
            } else {
              showBoundsButton.setEnabled(false);
              selectedLayer = null;
            }
          }
        });
    wmsFetchPanel.add(
        new JScrollPane(layerTree),
        GBC.eop().insets(5, 0, 0, 0).fill(GridBagConstraints.HORIZONTAL));

    JPanel layerManipulationButtons = new JPanel();
    showBoundsButton = new JButton(tr("Show Bounds"));
    showBoundsButton.setEnabled(false);
    showBoundsButton.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            if (selectedLayer.bounds != null) {
              SlippyMapBBoxChooser mapPanel = new SlippyMapBBoxChooser();
              mapPanel.setBoundingBox(selectedLayer.bounds);
              JOptionPane.showMessageDialog(
                  null, mapPanel, tr("Show Bounds"), JOptionPane.PLAIN_MESSAGE);
            } else {
              JOptionPane.showMessageDialog(
                  null,
                  tr("No bounding box was found for this layer."),
                  tr("WMS Error"),
                  JOptionPane.ERROR_MESSAGE);
            }
          }
        });
    layerManipulationButtons.add(showBoundsButton);

    wmsFetchPanel.add(layerManipulationButtons, GBC.eol().insets(0, 0, 5, 0));
    wmsFetchPanel.add(new JLabel(tr("WMS URL")), GBC.std().insets(0, 0, 5, 0));
    resultingLayerField = new JTextArea(3, 40);
    resultingLayerField.setLineWrap(true);
    wmsFetchPanel.add(
        new JScrollPane(
            resultingLayerField,
            JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER),
        GBC.eop().insets(5, 0, 0, 0).fill(GridBagConstraints.HORIZONTAL));

    add(wmsFetchPanel);
  }
Ejemplo n.º 20
0
    @Override
    public void actionPerformed(ActionEvent arg0) {

      long diff = delta + Math.round(timezone * 60 * 60);

      double diffInH = (double) diff / (60 * 60); // hours

      // Find day difference
      final int dayOffset = (int) Math.round(diffInH / 24); // days
      double tmz = diff - dayOffset * 24 * 60 * 60L; // seconds

      // In hours, rounded to two decimal places
      tmz = (double) Math.round(tmz * 100 / (60 * 60)) / 100;

      // Due to imprecise clocks we might get a "+3:28" timezone, which should obviously be 3:30
      // with
      // -2 minutes offset. This determines the real timezone and finds offset.
      double fixTimezone = (double) Math.round(tmz * 2) / 2; // hours, rounded to one decimal place
      int offset =
          (int) Math.round(diff - fixTimezone * 60 * 60) - dayOffset * 24 * 60 * 60; // seconds

      // Info Labels
      final JLabel lblMatches = new JLabel();

      // Timezone Slider
      // The slider allows to switch timezon from -12:00 to 12:00 in 30 minutes steps. Therefore the
      // range is -24 to 24.
      final JLabel lblTimezone = new JLabel();
      final JSlider sldTimezone = new JSlider(-24, 24, 0);
      sldTimezone.setPaintLabels(true);
      Dictionary<Integer, JLabel> labelTable = new Hashtable<>();
      // CHECKSTYLE.OFF: ParenPad
      labelTable.put(-24, new JLabel("-12:00"));
      labelTable.put(-12, new JLabel("-6:00"));
      labelTable.put(0, new JLabel("0:00"));
      labelTable.put(12, new JLabel("6:00"));
      labelTable.put(24, new JLabel("12:00"));
      // CHECKSTYLE.ON: ParenPad
      sldTimezone.setLabelTable(labelTable);

      // Minutes Slider
      final JLabel lblMinutes = new JLabel();
      final JSlider sldMinutes = new JSlider(-15, 15, 0);
      sldMinutes.setPaintLabels(true);
      sldMinutes.setMajorTickSpacing(5);

      // Seconds slider
      final JLabel lblSeconds = new JLabel();
      final JSlider sldSeconds = new JSlider(-60, 60, 0);
      sldSeconds.setPaintLabels(true);
      sldSeconds.setMajorTickSpacing(30);

      // This is called whenever one of the sliders is moved.
      // It updates the labels and also calls the "match photos" code
      class SliderListener implements ChangeListener {
        @Override
        public void stateChanged(ChangeEvent e) {
          // parse slider position into real timezone
          double tz = Math.abs(sldTimezone.getValue());
          String zone =
              tz % 2 == 0 ? (int) Math.floor(tz / 2) + ":00" : (int) Math.floor(tz / 2) + ":30";
          if (sldTimezone.getValue() < 0) {
            zone = '-' + zone;
          }

          lblTimezone.setText(tr("Timezone: {0}", zone));
          lblMinutes.setText(tr("Minutes: {0}", sldMinutes.getValue()));
          lblSeconds.setText(tr("Seconds: {0}", sldSeconds.getValue()));

          try {
            timezone = parseTimezone(zone);
          } catch (ParseException pe) {
            throw new RuntimeException(pe);
          }
          delta = sldMinutes.getValue() * 60 + sldSeconds.getValue();

          tfTimezone.getDocument().removeDocumentListener(statusBarUpdater);
          tfOffset.getDocument().removeDocumentListener(statusBarUpdater);

          tfTimezone.setText(formatTimezone(timezone));
          tfOffset.setText(
              Long.toString(
                  delta + 24 * 60 * 60L * dayOffset)); // add the day offset to the offset field

          tfTimezone.getDocument().addDocumentListener(statusBarUpdater);
          tfOffset.getDocument().addDocumentListener(statusBarUpdater);

          lblMatches.setText(
              statusBarText.getText()
                  + "<br>"
                  + trn(
                      "(Time difference of {0} day)",
                      "Time difference of {0} days", Math.abs(dayOffset), Math.abs(dayOffset)));

          statusBarUpdater.updateStatusBar();
          yLayer.updateBufferAndRepaint();
        }
      }

      // Put everything together
      JPanel p = new JPanel(new GridBagLayout());
      p.setPreferredSize(new Dimension(400, 230));
      p.add(lblMatches, GBC.eol().fill());
      p.add(lblTimezone, GBC.eol().fill());
      p.add(sldTimezone, GBC.eol().fill().insets(0, 0, 0, 10));
      p.add(lblMinutes, GBC.eol().fill());
      p.add(sldMinutes, GBC.eol().fill().insets(0, 0, 0, 10));
      p.add(lblSeconds, GBC.eol().fill());
      p.add(sldSeconds, GBC.eol().fill());

      // If there's an error in the calculation the found values
      // will be off range for the sliders. Catch this error
      // and inform the user about it.
      try {
        sldTimezone.setValue((int) (fixTimezone * 2));
        sldMinutes.setValue(offset / 60);
        sldSeconds.setValue(offset % 60);
      } catch (Exception e) {
        JOptionPane.showMessageDialog(
            Main.parent,
            tr(
                "An error occurred while trying to match the photos to the GPX track."
                    + " You can adjust the sliders to manually match the photos."),
            tr("Matching photos to track failed"),
            JOptionPane.WARNING_MESSAGE);
      }

      // Call the sliderListener once manually so labels get adjusted
      new SliderListener().stateChanged(null);
      // Listeners added here, otherwise it tries to match three times
      // (when setting the default values)
      sldTimezone.addChangeListener(new SliderListener());
      sldMinutes.addChangeListener(new SliderListener());
      sldSeconds.addChangeListener(new SliderListener());

      // There is no way to cancel this dialog, all changes get applied
      // immediately. Therefore "Close" is marked with an "OK" icon.
      // Settings are only saved temporarily to the layer.
      new ExtendedDialog(Main.parent, tr("Adjust timezone and offset"), new String[] {tr("Close")})
          .setContent(p)
          .setButtonIcons(new String[] {"ok"})
          .showDialog();
    }
Ejemplo n.º 21
0
  private static void buildHints(JPanel right, HistoryComboBox hcbSearchString) {
    right.add(
        new SearchKeywordRow(hcbSearchString)
            .addTitle(tr("basic examples"))
            .addKeyword(tr("Baker Street"), null, tr("''Baker'' and ''Street'' in any key"))
            .addKeyword(tr("\"Baker Street\""), "\"\"", tr("''Baker Street'' in any key")),
        GBC.eol());
    right.add(
        new SearchKeywordRow(hcbSearchString)
            .addTitle(tr("basics"))
            .addKeyword(
                "<i>key</i>:<i>valuefragment</i>",
                null,
                tr("''valuefragment'' anywhere in ''key''"),
                "name:str matches name=Bakerstreet")
            .addKeyword(
                "-<i>key</i>:<i>valuefragment</i>",
                null,
                tr("''valuefragment'' nowhere in ''key''"))
            .addKeyword("<i>key</i>=<i>value</i>", null, tr("''key'' with exactly ''value''"))
            .addKeyword("<i>key</i>=*", null, tr("''key'' with any value"))
            .addKeyword("*=<i>value</i>", null, tr("''value'' in any key"))
            .addKeyword("<i>key</i>=", null, tr("matches if ''key'' exists"))
            .addKeyword(
                "<i>key</i>><i>value</i>",
                null,
                tr("matches if ''key'' is greater than ''value'' (analogously, less than)"))
            .addKeyword(
                "\"key\"=\"value\"",
                "\"\"=\"\"",
                tr(
                    "to quote operators.<br>Within quoted strings the <b>\"</b> and <b>\\</b> characters need to be escaped "
                        + "by a preceding <b>\\</b> (e.g. <b>\\\"</b> and <b>\\\\</b>)."),
                "\"addr:street\""),
        GBC.eol());
    right.add(
        new SearchKeywordRow(hcbSearchString)
            .addTitle(tr("combinators"))
            .addKeyword(
                "<i>expr</i> <i>expr</i>",
                null,
                tr("logical and (both expressions have to be satisfied)"))
            .addKeyword(
                "<i>expr</i> | <i>expr</i>",
                "| ",
                tr("logical or (at least one expression has to be satisfied)"))
            .addKeyword(
                "<i>expr</i> OR <i>expr</i>",
                "OR ",
                tr("logical or (at least one expression has to be satisfied)"))
            .addKeyword("-<i>expr</i>", null, tr("logical not"))
            .addKeyword("(<i>expr</i>)", "()", tr("use parenthesis to group expressions")),
        GBC.eol());

    if (Main.pref.getBoolean("expert", false)) {
      right.add(
          new SearchKeywordRow(hcbSearchString)
              .addTitle(tr("objects"))
              .addKeyword("type:node", "type:node ", tr("all ways"))
              .addKeyword("type:way", "type:way ", tr("all ways"))
              .addKeyword("type:relation", "type:relation ", tr("all relations"))
              .addKeyword("closed", "closed ", tr("all closed ways"))
              .addKeyword("untagged", "untagged ", tr("object without useful tags")),
          GBC.eol());
      right.add(
          new SearchKeywordRow(hcbSearchString)
              .addTitle(tr("metadata"))
              .addKeyword("user:"******"user:"******"objects changed by user", "user:anonymous"))
              .addKeyword("id:", "id:", tr("objects with given ID"), "id:0 (new objects)")
              .addKeyword(
                  "version:",
                  "version:",
                  tr("objects with given version"),
                  "version:0 (objects without an assigned version)")
              .addKeyword(
                  "changeset:",
                  "changeset:",
                  tr("objects with given changeset ID"),
                  "changeset:0 (objects without an assigned changeset)")
              .addKeyword(
                  "timestamp:",
                  "timestamp:",
                  tr("objects with last modification timestamp within range"),
                  "timestamp:2012/",
                  "timestamp:2008/2011-02-04T12"),
          GBC.eol());
      right.add(
          new SearchKeywordRow(hcbSearchString)
              .addTitle(tr("properties"))
              .addKeyword(
                  "nodes:<i>20-</i>",
                  "nodes:",
                  tr("ways with at least 20 nodes, or relations containing at least 20 nodes"))
              .addKeyword(
                  "ways:<i>3-</i>",
                  "ways:",
                  tr(
                      "nodes with at least 3 referring ways, or relations containing at least 3 ways"))
              .addKeyword("tags:<i>5-10</i>", "tags:", tr("objects having 5 to 10 tags"))
              .addKeyword("role:", "role:", tr("objects with given role in a relation"))
              .addKeyword(
                  "areasize:<i>-100</i>",
                  "areasize:",
                  tr("closed ways with an area of 100 m\u00b2"))
              .addKeyword(
                  "waylength:<i>200-</i>", "waylength:", tr("ways with a length of 200 m or more")),
          GBC.eol());
      right.add(
          new SearchKeywordRow(hcbSearchString)
              .addTitle(tr("state"))
              .addKeyword("modified", "modified ", tr("all modified objects"))
              .addKeyword("new", "new ", tr("all new objects"))
              .addKeyword("selected", "selected ", tr("all selected objects"))
              .addKeyword("incomplete", "incomplete ", tr("all incomplete objects")),
          GBC.eol());
      right.add(
          new SearchKeywordRow(hcbSearchString)
              .addTitle(tr("related objects"))
              .addKeyword(
                  "child <i>expr</i>",
                  "child ",
                  tr("all children of objects matching the expression"),
                  "child building")
              .addKeyword(
                  "parent <i>expr</i>",
                  "parent ",
                  tr("all parents of objects matching the expression"),
                  "parent bus_stop")
              .addKeyword(
                  "hasRole:<i>stop</i>",
                  "hasRole:",
                  tr("relation containing a member of role <i>stop</i>"))
              .addKeyword(
                  "role:<i>stop</i>",
                  "role:",
                  tr("objects being part of a relation as role <i>stop</i>"))
              .addKeyword(
                  "nth:<i>7</i>",
                  "nth:",
                  tr("n-th member of relation and/or n-th node of way"),
                  "nth:5 (child type:relation)",
                  "nth:-1")
              .addKeyword(
                  "nth%:<i>7</i>",
                  "nth%:",
                  tr("every n-th member of relation and/or every n-th node of way"),
                  "nth%:100 (child waterway)"),
          GBC.eol());
      right.add(
          new SearchKeywordRow(hcbSearchString)
              .addTitle(tr("view"))
              .addKeyword("inview", "inview ", tr("objects in current view"))
              .addKeyword(
                  "allinview",
                  "allinview ",
                  tr("objects (and all its way nodes / relation members) in current view"))
              .addKeyword("indownloadedarea", "indownloadedarea ", tr("objects in downloaded area"))
              .addKeyword(
                  "allindownloadedarea",
                  "allindownloadedarea ",
                  tr("objects (and all its way nodes / relation members) in downloaded area")),
          GBC.eol());
    }
  }
Ejemplo n.º 22
0
 /** Add component @param c on top of MapView */
 public void addTopPanel(Component c) {
   leftPanel.add(c, GBC.eol().fill(GBC.HORIZONTAL), leftPanel.getComponentCount() - 1);
   leftPanel.doLayout();
   c.doLayout();
 }
Ejemplo n.º 23
0
 private static void addSettingsSection(final JPanel p, String name, JPanel section) {
   addSettingsSection(p, name, section, GBC.eol());
 }
Ejemplo n.º 24
0
    @Override
    public void addGui(PreferenceTabbedPane gui) {
      actionsTree.setCellRenderer(
          new DefaultTreeCellRenderer() {
            @Override
            public Component getTreeCellRendererComponent(
                JTree tree,
                Object value,
                boolean sel,
                boolean expanded,
                boolean leaf,
                int row,
                boolean hasFocus) {
              DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
              JLabel comp =
                  (JLabel)
                      super.getTreeCellRendererComponent(
                          tree, value, sel, expanded, leaf, row, hasFocus);
              if (node.getUserObject() == null) {
                comp.setText(tr("Separator"));
                comp.setIcon(ImageProvider.get("preferences/separator"));
              } else if (node.getUserObject() instanceof Action) {
                Action action = (Action) node.getUserObject();
                comp.setText((String) action.getValue(Action.NAME));
                comp.setIcon((Icon) action.getValue(Action.SMALL_ICON));
              }
              return comp;
            }
          });

      ListCellRenderer renderer =
          new DefaultListCellRenderer() {
            @Override
            public Component getListCellRendererComponent(
                JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
              String s;
              Icon i;
              ActionDefinition action = (ActionDefinition) value;
              if (!action.isSeparator()) {
                s = action.getDisplayName();
                i = action.getDisplayIcon();
              } else {
                i = ImageProvider.get("preferences/separator");
                s = tr("Separator");
              }
              JLabel l =
                  (JLabel)
                      super.getListCellRendererComponent(list, s, index, isSelected, cellHasFocus);
              l.setIcon(i);
              return l;
            }
          };
      selectedList.setCellRenderer(renderer);
      selectedList.addListSelectionListener(
          new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
              boolean sel = selectedList.getSelectedIndex() != -1;
              if (sel) {
                actionsTree.clearSelection();
                ActionDefinition action =
                    (ActionDefinition) selected.get(selectedList.getSelectedIndex());
                actionParametersModel.setCurrentAction(action);
                actionParametersPanel.setVisible(actionParametersModel.getRowCount() > 0);
              }
              updateEnabledState();
            }
          });

      selectedList.setDragEnabled(true);
      selectedList.setTransferHandler(
          new TransferHandler() {
            @Override
            protected Transferable createTransferable(JComponent c) {
              List<ActionDefinition> actions = new ArrayList<ActionDefinition>();
              for (Object o : ((JList) c).getSelectedValues()) {
                actions.add((ActionDefinition) o);
              }
              return new ActionTransferable(actions);
            }

            @Override
            public int getSourceActions(JComponent c) {
              return TransferHandler.MOVE;
            }

            @Override
            public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
              for (DataFlavor f : transferFlavors) {
                if (ACTION_FLAVOR.equals(f)) return true;
              }
              return false;
            }

            @Override
            public void exportAsDrag(JComponent comp, InputEvent e, int action) {
              super.exportAsDrag(comp, e, action);
              movingComponent = "list";
            }

            @Override
            public boolean importData(JComponent comp, Transferable t) {
              try {
                int dropIndex = selectedList.locationToIndex(selectedList.getMousePosition(true));
                List<?> draggedData = (List<?>) t.getTransferData(ACTION_FLAVOR);

                Object leadItem = dropIndex >= 0 ? selected.elementAt(dropIndex) : null;
                int dataLength = draggedData.size();

                if (leadItem != null) {
                  for (Object o : draggedData) {
                    if (leadItem.equals(o)) return false;
                  }
                }

                int dragLeadIndex = -1;
                boolean localDrop = "list".equals(movingComponent);

                if (localDrop) {
                  dragLeadIndex = selected.indexOf(draggedData.get(0));
                  for (Object o : draggedData) {
                    selected.removeElement(o);
                  }
                }
                int[] indices = new int[dataLength];

                if (localDrop) {
                  int adjustedLeadIndex = selected.indexOf(leadItem);
                  int insertionAdjustment = dragLeadIndex <= adjustedLeadIndex ? 1 : 0;
                  for (int i = 0; i < dataLength; i++) {
                    selected.insertElementAt(
                        draggedData.get(i), adjustedLeadIndex + insertionAdjustment + i);
                    indices[i] = adjustedLeadIndex + insertionAdjustment + i;
                  }
                } else {
                  for (int i = 0; i < dataLength; i++) {
                    selected.add(dropIndex, draggedData.get(i));
                    indices[i] = dropIndex + i;
                  }
                }
                selectedList.clearSelection();
                selectedList.setSelectedIndices(indices);
                movingComponent = "";
                return true;
              } catch (Exception e) {
                e.printStackTrace();
              }
              return false;
            }

            @Override
            protected void exportDone(JComponent source, Transferable data, int action) {
              if (movingComponent.equals("list")) {
                try {
                  List<?> draggedData = (List<?>) data.getTransferData(ACTION_FLAVOR);
                  boolean localDrop = selected.contains(draggedData.get(0));
                  if (localDrop) {
                    int[] indices = selectedList.getSelectedIndices();
                    Arrays.sort(indices);
                    for (int i = indices.length - 1; i >= 0; i--) {
                      selected.remove(indices[i]);
                    }
                  }
                } catch (Exception e) {
                  e.printStackTrace();
                }
                movingComponent = "";
              }
            }
          });

      actionsTree.setTransferHandler(
          new TransferHandler() {
            private static final long serialVersionUID = 1L;

            @Override
            public int getSourceActions(JComponent c) {
              return TransferHandler.MOVE;
            }

            @Override
            protected void exportDone(JComponent source, Transferable data, int action) {}

            @Override
            protected Transferable createTransferable(JComponent c) {
              TreePath[] paths = actionsTree.getSelectionPaths();
              List<ActionDefinition> dragActions = new ArrayList<ActionDefinition>();
              for (TreePath path : paths) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
                Object obj = node.getUserObject();
                if (obj == null) {
                  dragActions.add(ActionDefinition.getSeparator());
                } else if (obj instanceof Action) {
                  dragActions.add(new ActionDefinition((Action) obj));
                }
              }
              return new ActionTransferable(dragActions);
            }
          });
      actionsTree.setDragEnabled(true);
      actionsTree
          .getSelectionModel()
          .addTreeSelectionListener(
              new TreeSelectionListener() {
                @Override
                public void valueChanged(TreeSelectionEvent e) {
                  updateEnabledState();
                }
              });

      final JPanel left = new JPanel(new GridBagLayout());
      left.add(new JLabel(tr("Toolbar")), GBC.eol());
      left.add(new JScrollPane(selectedList), GBC.std().fill(GBC.BOTH));

      final JPanel right = new JPanel(new GridBagLayout());
      right.add(new JLabel(tr("Available")), GBC.eol());
      right.add(new JScrollPane(actionsTree), GBC.eol().fill(GBC.BOTH));

      final JPanel buttons = new JPanel(new GridLayout(6, 1));
      buttons.add(upButton = createButton("up"));
      buttons.add(addButton = createButton("<"));
      buttons.add(removeButton = createButton(">"));
      buttons.add(downButton = createButton("down"));
      updateEnabledState();

      final JPanel p = new JPanel();
      p.setLayout(
          new LayoutManager() {
            @Override
            public void addLayoutComponent(String name, Component comp) {}

            @Override
            public void removeLayoutComponent(Component comp) {}

            @Override
            public Dimension minimumLayoutSize(Container parent) {
              Dimension l = left.getMinimumSize();
              Dimension r = right.getMinimumSize();
              Dimension b = buttons.getMinimumSize();
              return new Dimension(
                  l.width + b.width + 10 + r.width, l.height + b.height + 10 + r.height);
            }

            @Override
            public Dimension preferredLayoutSize(Container parent) {
              Dimension l = new Dimension(200, 200); // left.getPreferredSize();
              Dimension r = new Dimension(200, 200); // right.getPreferredSize();
              return new Dimension(
                  l.width + r.width + 10 + buttons.getPreferredSize().width,
                  Math.max(l.height, r.height));
            }

            @Override
            public void layoutContainer(Container parent) {
              Dimension d = p.getSize();
              Dimension b = buttons.getPreferredSize();
              int width = (d.width - 10 - b.width) / 2;
              left.setBounds(new Rectangle(0, 0, width, d.height));
              right.setBounds(new Rectangle(width + 10 + b.width, 0, width, d.height));
              buttons.setBounds(
                  new Rectangle(width + 5, d.height / 2 - b.height / 2, b.width, b.height));
            }
          });
      p.add(left);
      p.add(buttons);
      p.add(right);

      actionParametersPanel = new JPanel(new GridBagLayout());
      actionParametersPanel.add(
          new JLabel(tr("Action parameters")), GBC.eol().insets(0, 10, 0, 20));
      actionParametersTable.getColumnModel().getColumn(0).setHeaderValue(tr("Parameter name"));
      actionParametersTable.getColumnModel().getColumn(1).setHeaderValue(tr("Parameter value"));
      actionParametersPanel.add(
          actionParametersTable.getTableHeader(), GBC.eol().fill(GBC.HORIZONTAL));
      actionParametersPanel.add(
          actionParametersTable, GBC.eol().fill(GBC.BOTH).insets(0, 0, 0, 10));
      actionParametersPanel.setVisible(false);

      JPanel panel = gui.createPreferenceTab(this);
      panel.add(p, GBC.eol().fill(GBC.BOTH));
      panel.add(actionParametersPanel, GBC.eol().fill(GBC.HORIZONTAL));
      selected.removeAllElements();
      for (ActionDefinition actionDefinition : getDefinedActions()) {
        selected.addElement(actionDefinition);
      }
    }
Ejemplo n.º 25
0
  protected final JPanel buildMainPanel() {
    JPanel pnl = new JPanel();
    pnl.setLayout(new GridBagLayout());

    // adding the download tasks
    pnl.add(new JLabel(tr("Data Sources and Types:")), GBC.std().insets(5, 5, 1, 5));
    cbDownloadOsmData = new JCheckBox(tr("OpenStreetMap data"), true);
    cbDownloadOsmData.setToolTipText(
        tr("Select to download OSM data in the selected download area."));
    pnl.add(cbDownloadOsmData, GBC.std().insets(1, 5, 1, 5));
    cbDownloadGpxData = new JCheckBox(tr("Raw GPS data"));
    cbDownloadGpxData.setToolTipText(
        tr("Select to download GPS traces in the selected download area."));
    pnl.add(cbDownloadGpxData, GBC.eol().insets(5, 5, 1, 5));

    // hook for subclasses
    buildMainPanelAboveDownloadSelections(pnl);

    slippyMapChooser = new SlippyMapChooser();

    // predefined download selections
    downloadSelections.add(slippyMapChooser);
    downloadSelections.add(new BookmarkSelection());
    downloadSelections.add(new BoundingBoxSelection());
    downloadSelections.add(new PlaceSelection());
    downloadSelections.add(new TileSelection());

    // add selections from plugins
    PluginHandler.addDownloadSelection(downloadSelections);

    // now everybody may add their tab to the tabbed pane
    // (not done right away to allow plugins to remove one of
    // the default selectors!)
    for (DownloadSelection s : downloadSelections) {
      s.addGui(this);
    }

    pnl.add(tpDownloadAreaSelectors, GBC.eol().fill());

    try {
      tpDownloadAreaSelectors.setSelectedIndex(Main.pref.getInteger("download.tab", 0));
    } catch (Exception ex) {
      Main.pref.putInteger("download.tab", 0);
    }

    Font labelFont = sizeCheck.getFont();
    sizeCheck.setFont(labelFont.deriveFont(Font.PLAIN, labelFont.getSize()));

    cbNewLayer = new JCheckBox(tr("Download as new layer"));
    cbNewLayer.setToolTipText(
        tr(
            "<html>Select to download data into a new data layer.<br>"
                + "Unselect to download into the currently active data layer.</html>"));

    cbStartup = new JCheckBox(tr("Open this dialog on startup"));
    cbStartup.setToolTipText(
        tr(
            "<html>Autostart ''Download from OSM'' dialog every time JOSM is started.<br>You can open it manually from File menu or toolbar.</html>"));
    cbStartup.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            Main.pref.put("download.autorun", cbStartup.isSelected());
          }
        });

    pnl.add(cbNewLayer, GBC.std().anchor(GBC.WEST).insets(5, 5, 5, 5));
    pnl.add(cbStartup, GBC.std().anchor(GBC.WEST).insets(15, 5, 5, 5));

    pnl.add(sizeCheck, GBC.eol().anchor(GBC.EAST).insets(5, 5, 5, 2));

    if (!ExpertToggleAction.isExpert()) {
      JLabel infoLabel =
          new JLabel(
              tr(
                  "Use left click&drag to select area, arrows or right mouse button to scroll map, wheel or +/- to zoom."));
      pnl.add(infoLabel, GBC.eol().anchor(GBC.SOUTH).insets(0, 0, 0, 0));
    }
    return pnl;
  }
Ejemplo n.º 26
0
  /**
   * @param stylesPreferencesKey the preferences key with the list of active style sources
   *     (filenames and URLs)
   * @param iconsPreferenceKey the preference key with the list of icon sources (can be null)
   * @param availableStylesUrl the URL to the list of available style sources
   */
  public StyleSourceEditor(
      String stylesPreferencesKey, String iconsPreferenceKey, final String availableStylesUrl) {

    DefaultListSelectionModel selectionModel = new DefaultListSelectionModel();
    tblActiveStyles = new JTable(activeStylesModel = new ActiveStylesModel(selectionModel));
    tblActiveStyles.putClientProperty("terminateEditOnFocusLost", true);
    tblActiveStyles.setSelectionModel(selectionModel);
    tblActiveStyles.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    tblActiveStyles.setTableHeader(null);
    tblActiveStyles.getColumnModel().getColumn(0).setCellEditor(new FileOrUrlCellEditor());
    tblActiveStyles.setRowHeight(20);
    activeStylesModel.setActiveStyles(Main.pref.getCollection(stylesPreferencesKey, null));

    selectionModel = new DefaultListSelectionModel();
    lstAvailableStyles =
        new JList(availableStylesModel = new AvailableStylesListModel(selectionModel));
    lstAvailableStyles.setSelectionModel(selectionModel);
    lstAvailableStyles.setCellRenderer(new StyleSourceCellRenderer());
    // availableStylesModel.setStyleSources(reloadAvailableStyles(availableStylesUrl));
    this.availableStylesUrl = availableStylesUrl;

    this.pref = stylesPreferencesKey;
    this.iconpref = iconsPreferenceKey;

    JButton iconadd = null;
    JButton iconedit = null;
    JButton icondelete = null;

    if (iconsPreferenceKey != null) {
      selectionModel = new DefaultListSelectionModel();
      tblIconPaths = new JTable(iconPathsModel = new IconPathTableModel(selectionModel));
      tblIconPaths.setSelectionModel(selectionModel);
      tblIconPaths.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
      tblIconPaths.setTableHeader(null);
      tblIconPaths.getColumnModel().getColumn(0).setCellEditor(new FileOrUrlCellEditor());
      tblIconPaths.setRowHeight(20);
      iconPathsModel.setIconPaths(Main.pref.getCollection(iconsPreferenceKey, null));

      iconadd = new JButton(new NewIconPathAction());

      EditIconPathAction editIconPathAction = new EditIconPathAction();
      tblIconPaths.getSelectionModel().addListSelectionListener(editIconPathAction);
      iconedit = new JButton(editIconPathAction);

      RemoveIconPathAction removeIconPathAction = new RemoveIconPathAction();
      tblIconPaths.getSelectionModel().addListSelectionListener(removeIconPathAction);
      icondelete = new JButton(removeIconPathAction);
      tblIconPaths
          .getInputMap(JComponent.WHEN_FOCUSED)
          .put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), "delete");
      tblIconPaths.getActionMap().put("delete", removeIconPathAction);
    }

    JButton add = new JButton(new NewActiveStyleAction());

    EditActiveStyleAction editActiveStyleAction = new EditActiveStyleAction();
    tblActiveStyles.getSelectionModel().addListSelectionListener(editActiveStyleAction);
    JButton edit = new JButton(editActiveStyleAction);

    RemoveActiveStylesAction removeActiveStylesAction = new RemoveActiveStylesAction();
    tblActiveStyles.getSelectionModel().addListSelectionListener(removeActiveStylesAction);
    tblActiveStyles
        .getInputMap(JComponent.WHEN_FOCUSED)
        .put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), "delete");
    tblActiveStyles.getActionMap().put("delete", removeActiveStylesAction);
    JButton delete = new JButton(removeActiveStylesAction);

    ActivateStylesAction activateStylesAction = new ActivateStylesAction();
    lstAvailableStyles.addListSelectionListener(activateStylesAction);
    JButton copy = new JButton(activateStylesAction);

    JButton update = new JButton(new ReloadStylesAction(availableStylesUrl));

    setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
    setLayout(new GridBagLayout());
    add(new JLabel(tr("Active styles")), GBC.eol().insets(5, 5, 5, 0));
    JScrollPane sp;
    add(sp = new JScrollPane(tblActiveStyles), GBC.eol().insets(5, 0, 5, 0).fill(GBC.BOTH));
    sp.setColumnHeaderView(null);
    JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
    add(buttonPanel, GBC.eol().insets(5, 0, 5, 5).fill(GBC.HORIZONTAL));
    buttonPanel.add(add, GBC.std().insets(0, 5, 0, 0));
    buttonPanel.add(edit, GBC.std().insets(5, 5, 5, 0));
    buttonPanel.add(delete, GBC.std().insets(0, 5, 5, 0));
    buttonPanel.add(copy, GBC.std().insets(0, 5, 5, 0));
    add(
        new JLabel(tr("Available styles (from {0})", availableStylesUrl)),
        GBC.eol().insets(5, 5, 5, 0));
    add(new JScrollPane(lstAvailableStyles), GBC.eol().insets(5, 0, 5, 0).fill(GBC.BOTH));
    buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
    add(buttonPanel, GBC.eol().insets(5, 0, 5, 5).fill(GBC.HORIZONTAL));
    buttonPanel.add(update, GBC.std().insets(0, 5, 0, 0));
    if (tblIconPaths != null) {
      add(new JLabel(tr("Icon paths")), GBC.eol().insets(5, -5, 5, 0));
      add(sp = new JScrollPane(tblIconPaths), GBC.eol().insets(5, 0, 5, 0).fill(GBC.BOTH));
      sp.setColumnHeaderView(null);
      buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
      add(buttonPanel, GBC.eol().insets(5, 0, 5, 5).fill(GBC.HORIZONTAL));
      buttonPanel.add(iconadd);
      buttonPanel.add(iconedit);
      buttonPanel.add(icondelete);
    }
  }
Ejemplo n.º 27
0
  @Override
  public void actionPerformed(ActionEvent arg0) {
    // Construct the list of loaded GPX tracks
    Collection<Layer> layerLst = Main.map.mapView.getAllLayers();
    GpxDataWrapper defaultItem = null;
    for (Layer cur : layerLst) {
      if (cur instanceof GpxLayer) {
        GpxLayer curGpx = (GpxLayer) cur;
        GpxDataWrapper gdw =
            new GpxDataWrapper(curGpx.getName(), curGpx.data, curGpx.data.storageFile);
        gpxLst.add(gdw);
        if (cur == yLayer.gpxLayer) {
          defaultItem = gdw;
        }
      }
    }
    for (GpxData data : loadedGpxData) {
      gpxLst.add(new GpxDataWrapper(data.storageFile.getName(), data, data.storageFile));
    }

    if (gpxLst.isEmpty()) {
      gpxLst.add(new GpxDataWrapper(tr("<No GPX track loaded yet>"), null, null));
    }

    JPanel panelCb = new JPanel();

    panelCb.add(new JLabel(tr("GPX track: ")));

    cbGpx = new JosmComboBox<>(gpxLst.toArray(new GpxDataWrapper[0]));
    if (defaultItem != null) {
      cbGpx.setSelectedItem(defaultItem);
    }
    cbGpx.addActionListener(statusBarUpdaterWithRepaint);
    panelCb.add(cbGpx);

    JButton buttonOpen = new JButton(tr("Open another GPX trace"));
    buttonOpen.addActionListener(new LoadGpxDataActionListener());
    panelCb.add(buttonOpen);

    JPanel panelTf = new JPanel(new GridBagLayout());

    String prefTimezone = Main.pref.get("geoimage.timezone", "0:00");
    if (prefTimezone == null) {
      prefTimezone = "0:00";
    }
    try {
      timezone = parseTimezone(prefTimezone);
    } catch (ParseException e) {
      timezone = 0;
    }

    tfTimezone = new JosmTextField(10);
    tfTimezone.setText(formatTimezone(timezone));

    try {
      delta = parseOffset(Main.pref.get("geoimage.delta", "0"));
    } catch (ParseException e) {
      delta = 0;
    }
    delta = delta / 1000; // milliseconds -> seconds

    tfOffset = new JosmTextField(10);
    tfOffset.setText(Long.toString(delta));

    JButton buttonViewGpsPhoto =
        new JButton(
            tr("<html>Use photo of an accurate clock,<br>" + "e.g. GPS receiver display</html>"));
    buttonViewGpsPhoto.setIcon(ImageProvider.get("clock"));
    buttonViewGpsPhoto.addActionListener(new SetOffsetActionListener());

    JButton buttonAutoGuess = new JButton(tr("Auto-Guess"));
    buttonAutoGuess.setToolTipText(tr("Matches first photo with first gpx point"));
    buttonAutoGuess.addActionListener(new AutoGuessActionListener());

    JButton buttonAdjust = new JButton(tr("Manual adjust"));
    buttonAdjust.addActionListener(new AdjustActionListener());

    JLabel labelPosition = new JLabel(tr("Override position for: "));

    int numAll = getSortedImgList(true, true).size();
    int numExif = numAll - getSortedImgList(false, true).size();
    int numTagged = numAll - getSortedImgList(true, false).size();

    cbExifImg =
        new JCheckBox(tr("Images with geo location in exif data ({0}/{1})", numExif, numAll));
    cbExifImg.setEnabled(numExif != 0);

    cbTaggedImg =
        new JCheckBox(tr("Images that are already tagged ({0}/{1})", numTagged, numAll), true);
    cbTaggedImg.setEnabled(numTagged != 0);

    labelPosition.setEnabled(cbExifImg.isEnabled() || cbTaggedImg.isEnabled());

    boolean ticked = yLayer.thumbsLoaded || Main.pref.getBoolean("geoimage.showThumbs", false);
    cbShowThumbs = new JCheckBox(tr("Show Thumbnail images on the map"), ticked);
    cbShowThumbs.setEnabled(!yLayer.thumbsLoaded);

    int y = 0;
    GBC gbc = GBC.eol();
    gbc.gridx = 0;
    gbc.gridy = y++;
    panelTf.add(panelCb, gbc);

    gbc = GBC.eol().fill(GBC.HORIZONTAL).insets(0, 0, 0, 12);
    gbc.gridx = 0;
    gbc.gridy = y++;
    panelTf.add(new JSeparator(SwingConstants.HORIZONTAL), gbc);

    gbc = GBC.std();
    gbc.gridx = 0;
    gbc.gridy = y;
    panelTf.add(new JLabel(tr("Timezone: ")), gbc);

    gbc = GBC.std().fill(GBC.HORIZONTAL);
    gbc.gridx = 1;
    gbc.gridy = y++;
    gbc.weightx = 1.;
    panelTf.add(tfTimezone, gbc);

    gbc = GBC.std();
    gbc.gridx = 0;
    gbc.gridy = y;
    panelTf.add(new JLabel(tr("Offset:")), gbc);

    gbc = GBC.std().fill(GBC.HORIZONTAL);
    gbc.gridx = 1;
    gbc.gridy = y++;
    gbc.weightx = 1.;
    panelTf.add(tfOffset, gbc);

    gbc = GBC.std().insets(5, 5, 5, 5);
    gbc.gridx = 2;
    gbc.gridy = y - 2;
    gbc.gridheight = 2;
    gbc.gridwidth = 2;
    gbc.fill = GridBagConstraints.BOTH;
    gbc.weightx = 0.5;
    panelTf.add(buttonViewGpsPhoto, gbc);

    gbc = GBC.std().fill(GBC.BOTH).insets(5, 5, 5, 5);
    gbc.gridx = 2;
    gbc.gridy = y++;
    gbc.weightx = 0.5;
    panelTf.add(buttonAutoGuess, gbc);

    gbc.gridx = 3;
    panelTf.add(buttonAdjust, gbc);

    gbc = GBC.eol().fill(GBC.HORIZONTAL).insets(0, 12, 0, 0);
    gbc.gridx = 0;
    gbc.gridy = y++;
    panelTf.add(new JSeparator(SwingConstants.HORIZONTAL), gbc);

    gbc = GBC.eol();
    gbc.gridx = 0;
    gbc.gridy = y++;
    panelTf.add(labelPosition, gbc);

    gbc = GBC.eol();
    gbc.gridx = 1;
    gbc.gridy = y++;
    panelTf.add(cbExifImg, gbc);

    gbc = GBC.eol();
    gbc.gridx = 1;
    gbc.gridy = y++;
    panelTf.add(cbTaggedImg, gbc);

    gbc = GBC.eol();
    gbc.gridx = 0;
    gbc.gridy = y++;
    panelTf.add(cbShowThumbs, gbc);

    final JPanel statusBar = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
    statusBar.setBorder(BorderFactory.createLoweredBevelBorder());
    statusBarText = new JLabel(" ");
    statusBarText.setFont(statusBarText.getFont().deriveFont(8));
    statusBar.add(statusBarText);

    tfTimezone.addFocusListener(repaintTheMap);
    tfOffset.addFocusListener(repaintTheMap);

    tfTimezone.getDocument().addDocumentListener(statusBarUpdater);
    tfOffset.getDocument().addDocumentListener(statusBarUpdater);
    cbExifImg.addItemListener(statusBarUpdaterWithRepaint);
    cbTaggedImg.addItemListener(statusBarUpdaterWithRepaint);

    statusBarUpdater.updateStatusBar();

    outerPanel = new JPanel(new BorderLayout());
    outerPanel.add(statusBar, BorderLayout.PAGE_END);

    if (!GraphicsEnvironment.isHeadless()) {
      syncDialog =
          new ExtendedDialog(
              Main.parent,
              tr("Correlate images with GPX track"),
              new String[] {tr("Correlate"), tr("Cancel")},
              false);
      syncDialog.setContent(panelTf, false);
      syncDialog.setButtonIcons(new String[] {"ok", "cancel"});
      syncDialog.setupDialog();
      outerPanel.add(syncDialog.getContentPane(), BorderLayout.PAGE_START);
      syncDialog.setContentPane(outerPanel);
      syncDialog.pack();
      syncDialog.addWindowListener(new SyncDialogWindowListener());
      syncDialog.showDialog();
    }
  }
Ejemplo n.º 28
0
    /**
     * Constructs a new {@code ImageryProvidersPanel}.
     *
     * @param gui The parent preference tab pane
     * @param layerInfoArg The list of imagery entries to display
     */
    public ImageryProvidersPanel(final PreferenceTabbedPane gui, ImageryLayerInfo layerInfoArg) {
      super(new GridBagLayout());
      this.gui = gui;
      this.layerInfo = layerInfoArg;
      this.activeModel = new ImageryLayerTableModel();

      activeTable =
          new JTable(activeModel) {
            @Override
            public String getToolTipText(MouseEvent e) {
              java.awt.Point p = e.getPoint();
              return activeModel.getValueAt(rowAtPoint(p), columnAtPoint(p)).toString();
            }
          };
      activeTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);

      defaultModel = new ImageryDefaultLayerTableModel();
      defaultTable = new JTable(defaultModel);

      defaultModel.addTableModelListener(e -> activeTable.repaint());
      activeModel.addTableModelListener(e -> defaultTable.repaint());

      TableColumnModel mod = defaultTable.getColumnModel();
      mod.getColumn(2).setPreferredWidth(800);
      mod.getColumn(2).setCellRenderer(new ImageryURLTableCellRenderer(layerInfo.getLayers()));
      mod.getColumn(1).setPreferredWidth(400);
      mod.getColumn(1).setCellRenderer(new ImageryNameTableCellRenderer());
      mod.getColumn(0).setPreferredWidth(50);

      mod = activeTable.getColumnModel();
      mod.getColumn(1).setPreferredWidth(800);
      mod.getColumn(1)
          .setCellRenderer(new ImageryURLTableCellRenderer(layerInfo.getDefaultLayers()));
      mod.getColumn(0).setPreferredWidth(200);

      RemoveEntryAction remove = new RemoveEntryAction();
      activeTable.getSelectionModel().addListSelectionListener(remove);

      add(new JLabel(tr("Available default entries:")), GBC.eol().insets(5, 5, 0, 0));
      // Add default item list
      JScrollPane scrolldef = new JScrollPane(defaultTable);
      scrolldef.setPreferredSize(new Dimension(200, 200));
      add(
          scrolldef,
          GBC.std()
              .insets(0, 5, 0, 0)
              .fill(GridBagConstraints.BOTH)
              .weight(1.0, 0.6)
              .insets(5, 0, 0, 0));

      // Add default item map
      defaultMap = new JMapViewer();
      defaultMap.setTileSource(new OsmTileSource.Mapnik()); // for attribution
      defaultMap.addMouseListener(
          new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
              if (e.getButton() == MouseEvent.BUTTON1) {
                defaultMap.getAttribution().handleAttribution(e.getPoint(), true);
              }
            }
          });
      defaultMap.setZoomContolsVisible(false);
      defaultMap.setMinimumSize(new Dimension(100, 200));
      add(
          defaultMap,
          GBC.std()
              .insets(5, 5, 0, 0)
              .fill(GridBagConstraints.BOTH)
              .weight(0.33, 0.6)
              .insets(5, 0, 0, 0));

      defaultTableListener = new DefListSelectionListener();
      defaultTable.getSelectionModel().addListSelectionListener(defaultTableListener);

      defaultToolbar = new JToolBar(JToolBar.VERTICAL);
      defaultToolbar.setFloatable(false);
      defaultToolbar.setBorderPainted(false);
      defaultToolbar.setOpaque(false);
      defaultToolbar.add(new ReloadAction());
      add(defaultToolbar, GBC.eol().anchor(GBC.SOUTH).insets(0, 0, 5, 0));

      ActivateAction activate = new ActivateAction();
      defaultTable.getSelectionModel().addListSelectionListener(activate);
      JButton btnActivate = new JButton(activate);

      middleToolbar = new JToolBar(JToolBar.HORIZONTAL);
      middleToolbar.setFloatable(false);
      middleToolbar.setBorderPainted(false);
      middleToolbar.setOpaque(false);
      middleToolbar.add(btnActivate);
      add(middleToolbar, GBC.eol().anchor(GBC.CENTER).insets(5, 15, 5, 0));

      add(Box.createHorizontalGlue(), GBC.eol().fill(GridBagConstraints.HORIZONTAL));

      add(new JLabel(tr("Selected entries:")), GBC.eol().insets(5, 0, 0, 0));
      JScrollPane scroll = new JScrollPane(activeTable);
      add(
          scroll,
          GBC.std()
              .fill(GridBagConstraints.BOTH)
              .span(GridBagConstraints.RELATIVE)
              .weight(1.0, 0.4)
              .insets(5, 0, 0, 5));
      scroll.setPreferredSize(new Dimension(200, 200));

      activeToolbar = new JToolBar(JToolBar.VERTICAL);
      activeToolbar.setFloatable(false);
      activeToolbar.setBorderPainted(false);
      activeToolbar.setOpaque(false);
      activeToolbar.add(new NewEntryAction(ImageryInfo.ImageryType.WMS));
      activeToolbar.add(new NewEntryAction(ImageryInfo.ImageryType.TMS));
      activeToolbar.add(new NewEntryAction(ImageryInfo.ImageryType.WMTS));
      // activeToolbar.add(edit); TODO
      activeToolbar.add(remove);
      add(activeToolbar, GBC.eol().anchor(GBC.NORTH).insets(0, 0, 5, 5));
    }
Ejemplo n.º 29
0
  /** Constructs a new {@code AddWMSLayerPanel}. */
  public AddWMSLayerPanel() {

    add(new JLabel(tr("1. Enter service URL")), GBC.eol());
    add(rawUrl, GBC.eol().fill());
    rawUrl.setLineWrap(true);
    JButton getLayers = new JButton(tr("Get layers"));
    add(getLayers, GBC.eop().fill());

    add(new JLabel(tr("2. Select layers")), GBC.eol());
    add(endpoint, GBC.eol().fill());
    add(new JScrollPane(tree.getLayerTree()), GBC.eol().fill().weight(1, 100));

    showBounds.setEnabled(false);
    add(new JScrollPane(showBounds), GBC.eop().fill());

    add(new JLabel(tr("3. Select image format")), GBC.eol());
    add(formats, GBC.eol().fill());

    add(wmsInstruction = new JLabel(tr("4. Verify generated WMS URL")), GBC.eol());
    add(wmsUrl, GBC.eop().fill());
    wmsUrl.setLineWrap(true);

    add(new JLabel(tr("5. Enter name for this layer")), GBC.eol());
    add(name, GBC.eop().fill());

    getLayers.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            try {
              wms.attemptGetCapabilities(rawUrl.getText());
              tree.updateTree(wms);
              formats.setModel(new DefaultComboBoxModel(wms.getFormats().toArray()));
            } catch (MalformedURLException ex) {
              JOptionPane.showMessageDialog(
                  getParent(),
                  tr("Invalid service URL."),
                  tr("WMS Error"),
                  JOptionPane.ERROR_MESSAGE);
            } catch (IOException ex) {
              JOptionPane.showMessageDialog(
                  getParent(),
                  tr("Could not retrieve WMS layer list."),
                  tr("WMS Error"),
                  JOptionPane.ERROR_MESSAGE);
            } catch (WMSImagery.WMSGetCapabilitiesException ex) {
              JOptionPane.showMessageDialog(
                  getParent(),
                  tr("Could not parse WMS layer list."),
                  tr("WMS Error"),
                  JOptionPane.ERROR_MESSAGE);
              System.err.println("Could not parse WMS layer list. Incoming data:");
              System.err.println(ex.getIncomingData());
            }
          }
        });

    endpoint.addItemListener(
        new ItemListener() {
          @Override
          public void itemStateChanged(ItemEvent e) {
            tree.getLayerTree().setEnabled(!endpoint.isSelected());
            showBounds.setEnabled(!endpoint.isSelected());
            wmsInstruction.setEnabled(!endpoint.isSelected());
            formats.setEnabled(!endpoint.isSelected());
            wmsUrl.setEnabled(!endpoint.isSelected());
            if (endpoint.isSelected()) {
              URL url = wms.getServiceUrl();
              if (url != null) {
                name.setText(url.getHost());
              }
            } else {
              onLayerSelectionChanged();
            }
          }
        });

    tree.getLayerTree()
        .addPropertyChangeListener(
            "selectedLayers",
            new PropertyChangeListener() {
              @Override
              public void propertyChange(PropertyChangeEvent evt) {
                onLayerSelectionChanged();
              }
            });

    formats.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            onLayerSelectionChanged();
          }
        });

    showBounds.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            if (tree.getSelectedLayers().get(0).bounds != null) {
              SlippyMapBBoxChooser mapPanel = new SlippyMapBBoxChooser();
              mapPanel.setBoundingBox(tree.getSelectedLayers().get(0).bounds);
              JOptionPane.showMessageDialog(
                  null, mapPanel, tr("Show Bounds"), JOptionPane.PLAIN_MESSAGE);
            } else {
              JOptionPane.showMessageDialog(
                  null,
                  tr("No bounding box was found for this layer."),
                  tr("WMS Error"),
                  JOptionPane.ERROR_MESSAGE);
            }
          }
        });

    registerValidableComponent(endpoint);
    registerValidableComponent(rawUrl);
    registerValidableComponent(wmsUrl);
  }
Ejemplo n.º 30
0
  public static SearchSetting showSearchDialog(SearchSetting initialValues) {
    if (initialValues == null) {
      initialValues = new SearchSetting();
    }
    // -- prepare the combo box with the search expressions
    //
    JLabel label =
        new JLabel(initialValues instanceof Filter ? tr("Filter string:") : tr("Search string:"));
    final HistoryComboBox hcbSearchString = new HistoryComboBox();
    final String tooltip = tr("Enter the search expression");
    hcbSearchString.setText(initialValues.text);
    hcbSearchString.setToolTipText(tooltip);
    // we have to reverse the history, because ComboBoxHistory will reverse it again in addElement()
    //
    List<String> searchExpressionHistory = getSearchExpressionHistory();
    Collections.reverse(searchExpressionHistory);
    hcbSearchString.setPossibleItems(searchExpressionHistory);
    hcbSearchString.setPreferredSize(new Dimension(40, hcbSearchString.getPreferredSize().height));
    label.setLabelFor(hcbSearchString);

    JRadioButton replace =
        new JRadioButton(tr("replace selection"), initialValues.mode == SearchMode.replace);
    JRadioButton add =
        new JRadioButton(tr("add to selection"), initialValues.mode == SearchMode.add);
    JRadioButton remove =
        new JRadioButton(tr("remove from selection"), initialValues.mode == SearchMode.remove);
    JRadioButton inSelection =
        new JRadioButton(tr("find in selection"), initialValues.mode == SearchMode.in_selection);
    ButtonGroup bg = new ButtonGroup();
    bg.add(replace);
    bg.add(add);
    bg.add(remove);
    bg.add(inSelection);

    final JCheckBox caseSensitive =
        new JCheckBox(tr("case sensitive"), initialValues.caseSensitive);
    JCheckBox allElements = new JCheckBox(tr("all objects"), initialValues.allElements);
    allElements.setToolTipText(tr("Also include incomplete and deleted objects in search."));
    final JRadioButton standardSearch =
        new JRadioButton(tr("standard"), !initialValues.regexSearch && !initialValues.mapCSSSearch);
    final JRadioButton regexSearch =
        new JRadioButton(tr("regular expression"), initialValues.regexSearch);
    final JRadioButton mapCSSSearch =
        new JRadioButton(tr("MapCSS selector"), initialValues.mapCSSSearch);
    final JCheckBox addOnToolbar = new JCheckBox(tr("add toolbar button"), false);
    final ButtonGroup bg2 = new ButtonGroup();
    bg2.add(standardSearch);
    bg2.add(regexSearch);
    bg2.add(mapCSSSearch);

    JPanel top = new JPanel(new GridBagLayout());
    top.add(label, GBC.std().insets(0, 0, 5, 0));
    top.add(hcbSearchString, GBC.eol().fill(GBC.HORIZONTAL));
    JPanel left = new JPanel(new GridBagLayout());
    left.add(replace, GBC.eol());
    left.add(add, GBC.eol());
    left.add(remove, GBC.eol());
    left.add(inSelection, GBC.eop());
    left.add(caseSensitive, GBC.eol());
    if (Main.pref.getBoolean("expert", false)) {
      left.add(allElements, GBC.eol());
      left.add(addOnToolbar, GBC.eop());
      left.add(standardSearch, GBC.eol());
      left.add(regexSearch, GBC.eol());
      left.add(mapCSSSearch, GBC.eol());
    }

    final JPanel right;
    right = new JPanel(new GridBagLayout());
    buildHints(right, hcbSearchString);

    final JTextComponent editorComponent = hcbSearchString.getEditorComponent();
    editorComponent
        .getDocument()
        .addDocumentListener(
            new AbstractTextComponentValidator(editorComponent) {

              @Override
              public void validate() {
                if (!isValid()) {
                  feedbackInvalid(tr("Invalid search expression"));
                } else {
                  feedbackValid(tooltip);
                }
              }

              @Override
              public boolean isValid() {
                try {
                  SearchSetting ss = new SearchSetting();
                  ss.text = hcbSearchString.getText();
                  ss.caseSensitive = caseSensitive.isSelected();
                  ss.regexSearch = regexSearch.isSelected();
                  ss.mapCSSSearch = mapCSSSearch.isSelected();
                  SearchCompiler.compile(ss);
                  return true;
                } catch (ParseError | MapCSSException e) {
                  return false;
                }
              }
            });

    final JPanel p = new JPanel(new GridBagLayout());
    p.add(top, GBC.eol().fill(GBC.HORIZONTAL).insets(5, 5, 5, 0));
    p.add(left, GBC.std().anchor(GBC.NORTH).insets(5, 10, 10, 0));
    p.add(right, GBC.eol());
    ExtendedDialog dialog =
        new ExtendedDialog(
            Main.parent,
            initialValues instanceof Filter ? tr("Filter") : tr("Search"),
            new String[] {
              initialValues instanceof Filter ? tr("Submit filter") : tr("Start Search"),
              tr("Cancel")
            }) {
          @Override
          protected void buttonAction(int buttonIndex, ActionEvent evt) {
            if (buttonIndex == 0) {
              try {
                SearchSetting ss = new SearchSetting();
                ss.text = hcbSearchString.getText();
                ss.caseSensitive = caseSensitive.isSelected();
                ss.regexSearch = regexSearch.isSelected();
                ss.mapCSSSearch = mapCSSSearch.isSelected();
                SearchCompiler.compile(ss);
                super.buttonAction(buttonIndex, evt);
              } catch (ParseError e) {
                Main.debug(e);
                JOptionPane.showMessageDialog(
                    Main.parent,
                    tr("Search expression is not valid: \n\n {0}", e.getMessage()),
                    tr("Invalid search expression"),
                    JOptionPane.ERROR_MESSAGE);
              }
            } else {
              super.buttonAction(buttonIndex, evt);
            }
          }
        };
    dialog.setButtonIcons(new String[] {"dialogs/search", "cancel"});
    dialog.configureContextsensitiveHelp("/Action/Search", true /* show help button */);
    dialog.setContent(p);
    dialog.showDialog();
    int result = dialog.getValue();

    if (result != 1) return null;

    // User pressed OK - let's perform the search
    SearchMode mode =
        replace.isSelected()
            ? SearchAction.SearchMode.replace
            : (add.isSelected()
                ? SearchAction.SearchMode.add
                : (remove.isSelected()
                    ? SearchAction.SearchMode.remove
                    : SearchAction.SearchMode.in_selection));
    initialValues.text = hcbSearchString.getText();
    initialValues.mode = mode;
    initialValues.caseSensitive = caseSensitive.isSelected();
    initialValues.allElements = allElements.isSelected();
    initialValues.regexSearch = regexSearch.isSelected();
    initialValues.mapCSSSearch = mapCSSSearch.isSelected();

    if (addOnToolbar.isSelected()) {
      ToolbarPreferences.ActionDefinition aDef =
          new ToolbarPreferences.ActionDefinition(Main.main.menu.search);
      aDef.getParameters().put(SEARCH_EXPRESSION, initialValues);
      // Display search expression as tooltip instead of generic one
      aDef.setName(Utils.shortenString(initialValues.text, MAX_LENGTH_SEARCH_EXPRESSION_DISPLAY));
      // parametrized action definition is now composed
      ActionParser actionParser = new ToolbarPreferences.ActionParser(null);
      String res = actionParser.saveAction(aDef);

      // add custom search button to toolbar preferences
      Main.toolbar.addCustomButton(res, -1, false);
    }
    return initialValues;
  }