Beispiel #1
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;
  }
Beispiel #2
0
 public static GBC std(int x, int y) {
   GBC c = new GBC();
   c.anchor = WEST;
   c.gridx = x;
   c.gridy = y;
   return c;
 }
  /**
   * 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;
  }
 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));
 }
Beispiel #5
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));
    }
  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));
  }
Beispiel #7
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);
  }
 @Override
 public Component getExportPanel() {
   final JPanel p = 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());
   p.add(export, GBC.std());
   p.add(lbl, GBC.std());
   p.add(GBC.glue(1, 0), GBC.std().fill(GBC.HORIZONTAL));
   return p;
 }
    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());
    }
Beispiel #10
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;
  }
    /**
     * 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());
    }
Beispiel #12
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;
  }
Beispiel #13
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;
  }
  /**
   * builds the button row
   *
   * @return the panel with the button row
   */
  protected JPanel buildButtonRow() {
    JPanel pnl = new JPanel(new GridBagLayout());

    model.addPropertyChangeListener(saveAndProceedAction);
    pnl.add(saveAndProceedActionButton, GBC.std(0, 0).insets(5, 5, 0, 0).fill(GBC.HORIZONTAL));

    pnl.add(new JButton(saveSessionAction), GBC.std(1, 0).insets(5, 5, 5, 0).fill(GBC.HORIZONTAL));

    model.addPropertyChangeListener(discardAndProceedAction);
    pnl.add(
        new JButton(discardAndProceedAction),
        GBC.std(0, 1).insets(5, 5, 0, 5).fill(GBC.HORIZONTAL));

    pnl.add(new JButton(cancelAction), GBC.std(1, 1).insets(5, 5, 5, 5).fill(GBC.HORIZONTAL));

    JPanel pnl2 = new JPanel(new BorderLayout());
    pnl2.add(pnlUploadLayers, BorderLayout.CENTER);
    model.addPropertyChangeListener(pnlUploadLayers);
    pnl2.add(pnl, BorderLayout.SOUTH);
    return pnl2;
  }
 @Override
 public void addGui(final PreferenceTabbedPane gui) {
   JPanel p = gui.createPreferenceTab(this);
   JTabbedPane pane = getTabPane();
   layerInfo = new ImageryLayerInfo(ImageryLayerInfo.instance);
   imageryProviders = new ImageryProvidersPanel(gui, layerInfo);
   pane.addTab(tr("Imagery providers"), imageryProviders);
   pane.addTab(tr("Settings"), buildSettingsPanel());
   pane.addTab(tr("Offset bookmarks"), new OffsetBookmarksPanel(gui));
   pane.addTab(tr("Cache contents"), new CacheContentsPanel());
   loadSettings();
   p.add(pane, GBC.std().fill(GBC.BOTH));
 }
Beispiel #16
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();
         }
       });
 }
  /** 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();
  }
    /**
     * 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));
    }
Beispiel #19
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();
    }
Beispiel #20
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();
    }
  }
  /**
   * @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);
    }
  }
Beispiel #22
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;
  }
Beispiel #23
0
  @Override
  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());

    final JButton btnClear = new JButton(tr("Clear textarea"));
    btnClear.addMouseListener(
        new MouseAdapter() {
          @Override
          public void mouseClicked(MouseEvent arg0) {
            tfOsmUrl.setText("");
          }
        });
    dlg.add(btnClear, GBC.eol().insets(10, 20, 0, 0));

    dlg.add(
        new JLabel(
            tr("URL from www.openstreetmap.org (you can paste an URL here to download the area)")),
        GBC.eol().insets(10, 5, 5, 0));
    dlg.add(tfOsmUrl, GBC.eop().insets(10, 0, 5, 0).fill());
    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;
  }
Beispiel #24
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);
  }
Beispiel #25
0
 /**
  * Create the constraint for the last elements on a line.
  *
  * @return A constraint which indicates the last item on a line.
  */
 public static GBC eol() {
   GBC c = std();
   c.gridwidth = REMAINDER;
   return c;
 }
Beispiel #26
0
 /**
  * Create a standard constraint (which is not the last).
  *
  * @return A standard constraint with no filling.
  */
 public static GBC std() {
   GBC c = new GBC();
   c.anchor = WEST;
   return c;
 }
Beispiel #27
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;
  }
Beispiel #28
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();
  }
Beispiel #29
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;
  }
 private static void addSettingsSection(final JPanel p, String name, JPanel section) {
   addSettingsSection(p, name, section, GBC.eol());
 }