Ignore:
Timestamp:
2016-07-03T21:26:31+02:00 (8 years ago)
Author:
donvip
Message:

checkstyle

Location:
applications/editors/josm/plugins/geochat
Files:
3 added
12 edited

Legend:

Unmodified
Added
Removed
  • applications/editors/josm/plugins/geochat/.project

    r32286 r32544  
    1616                        </arguments>
    1717                </buildCommand>
     18                <buildCommand>
     19                        <name>net.sf.eclipsecs.core.CheckstyleBuilder</name>
     20                        <arguments>
     21                        </arguments>
     22                </buildCommand>
    1823        </buildSpec>
    1924        <natures>
    2025                <nature>org.eclipse.jdt.core.javanature</nature>
     26                <nature>net.sf.eclipsecs.core.CheckstyleNature</nature>
    2127        </natures>
    2228</projectDescription>
  • applications/editors/josm/plugins/geochat/build.xml

    r31923 r32544  
    55    <property name="commit.message" value="[josm_geochat] copypaste from keyboard, font size advanced parameters"/>
    66    <!-- enter the *lowest* JOSM version this plugin is currently compatible with -->
    7     <property name="plugin.main.version" value="7001"/>
     7    <property name="plugin.main.version" value="10420"/>
    88
    99    <property name="plugin.author" value="Ilya Zverev"/>
  • applications/editors/josm/plugins/geochat/src/geochat/ChatMessage.java

    r29854 r32544  
    1 // License: WTFPL
     1// License: WTFPL. For details, see LICENSE file.
    22package geochat;
    33
    44import java.util.Date;
     5
    56import org.openstreetmap.josm.data.coor.LatLon;
    67
    78/**
    89 * One message.
    9  * 
     10 *
    1011 * @author zverik
    1112 */
     
    2021    private boolean incoming;
    2122
    22     public ChatMessage( long id, LatLon pos, String author, boolean incoming, String message, Date time ) {
     23    public ChatMessage(long id, LatLon pos, String author, boolean incoming, String message, Date time) {
    2324        this.id = id;
    2425        this.author = author;
     
    3132    }
    3233
    33     public void setRecipient( String recipient ) {
     34    public void setRecipient(String recipient) {
    3435        this.recipient = recipient;
    3536    }
    3637
    37     public void setPrivate( boolean priv ) {
     38    public void setPrivate(boolean priv) {
    3839        this.priv = priv;
    3940    }
    40    
     41
    4142    public String getAuthor() {
    4243        return author;
     
    6162        return message;
    6263    }
    63    
     64
    6465    public boolean isPrivate() {
    6566        return priv;
     
    9697    }
    9798
     99    @Override
    98100    public int compareTo(ChatMessage o) {
    99101        long otherId = o.id;
  • applications/editors/josm/plugins/geochat/src/geochat/ChatPaneManager.java

    r30737 r32544  
    1 // License: WTFPL
     1// License: WTFPL. For details, see LICENSE file.
    22package geochat;
     3
     4import static org.openstreetmap.josm.tools.I18n.tr;
    35
    46import java.awt.Color;
    57import java.awt.Component;
    68import java.awt.Font;
    7 import java.util.*;
    8 import javax.swing.*;
     9import java.util.ArrayList;
     10import java.util.HashMap;
     11import java.util.List;
     12import java.util.Map;
     13
     14import javax.swing.JLabel;
     15import javax.swing.JScrollPane;
     16import javax.swing.JTabbedPane;
     17import javax.swing.JTextPane;
    918import javax.swing.event.ChangeEvent;
    1019import javax.swing.event.ChangeListener;
    11 import javax.swing.text.*;
     20import javax.swing.text.BadLocationException;
     21import javax.swing.text.Document;
     22import javax.swing.text.SimpleAttributeSet;
     23import javax.swing.text.StyleConstants;
     24
    1225import org.openstreetmap.josm.Main;
    1326import org.openstreetmap.josm.gui.util.GuiHelper;
    14 import static org.openstreetmap.josm.tools.I18n.tr;
    1527
    1628/**
     
    2638    private boolean collapsed;
    2739
    28     public ChatPaneManager( GeoChatPanel panel, JTabbedPane tabs ) {
     40    ChatPaneManager(GeoChatPanel panel, JTabbedPane tabs) {
    2941        this.panel = panel;
    3042        this.tabs = tabs;
     
    3345        createChatPane(null);
    3446        tabs.addChangeListener(new ChangeListener() {
    35             public void stateChanged( ChangeEvent e ) {
     47            @Override
     48            public void stateChanged(ChangeEvent e) {
    3649                updateActiveTabStatus();
    3750            }
     
    3952    }
    4053
    41     public void setCollapsed( boolean collapsed ) {
     54    public void setCollapsed(boolean collapsed) {
    4255        this.collapsed = collapsed;
    4356        updateActiveTabStatus();
    4457    }
    4558
    46     public boolean hasUser( String user ) {
     59    public boolean hasUser(String user) {
    4760        return chatPanes.containsKey(user == null ? PUBLIC_PANE : user);
    4861    }
     
    5467    public int getNotifyLevel() {
    5568        int alarm = 0;
    56         for( ChatPane entry : chatPanes.values() ) {
    57             if( entry.notify > alarm )
     69        for (ChatPane entry : chatPanes.values()) {
     70            if (entry.notify > alarm)
    5871                alarm = entry.notify;
    5972        }
     
    6275
    6376    public void updateActiveTabStatus() {
    64         if( tabs.getSelectedIndex() >= 0 )
    65             ((ChatTabTitleComponent)tabs.getTabComponentAt(tabs.getSelectedIndex())).updateAlarm();
    66     }
    67 
    68     public void notify( String user, int alarmLevel ) {
    69         if( alarmLevel <= 0 || !hasUser(user) )
     77        if (tabs.getSelectedIndex() >= 0)
     78            ((ChatTabTitleComponent) tabs.getTabComponentAt(tabs.getSelectedIndex())).updateAlarm();
     79    }
     80
     81    public void notify(String user, int alarmLevel) {
     82        if (alarmLevel <= 0 || !hasUser(user))
    7083            return;
    7184        ChatPane entry = chatPanes.get(user == null ? PUBLIC_PANE : user);
    7285        entry.notify = alarmLevel;
    7386        int idx = tabs.indexOfComponent(entry.component);
    74         if( idx >= 0 )
    75             ((ChatTabTitleComponent)tabs.getTabComponentAt(idx)).updateAlarm();
     87        if (idx >= 0)
     88            ((ChatTabTitleComponent) tabs.getTabComponentAt(idx)).updateAlarm();
    7689    }
    7790
     
    8194    private static Color COLOR_ATTENTION = new Color(0, 0, 192);
    8295
    83     private void addLineToChatPane( String userName, String line, final int messageType ) {
    84         if( line.length() == 0 )
     96    private void addLineToChatPane(String userName, String line, final int messageType) {
     97        if (line.length() == 0)
    8598            return;
    86         if( !chatPanes.containsKey(userName) )
     99        if (!chatPanes.containsKey(userName))
    87100            createChatPane(userName);
    88101        final String nline = line.startsWith("\n") ? line : "\n" + line;
    89102        final JTextPane thepane = chatPanes.get(userName).pane;
    90103        GuiHelper.runInEDT(new Runnable() {
     104            @Override
    91105            public void run() {
    92106                Document doc = thepane.getDocument();
    93107                try {
    94108                    SimpleAttributeSet attrs = null;
    95                     if( messageType != MESSAGE_TYPE_DEFAULT ) {
     109                    if (messageType != MESSAGE_TYPE_DEFAULT) {
    96110                        attrs = new SimpleAttributeSet();
    97                         if( messageType == MESSAGE_TYPE_INFORMATION )
     111                        if (messageType == MESSAGE_TYPE_INFORMATION)
    98112                            StyleConstants.setItalic(attrs, true);
    99                         else if( messageType == MESSAGE_TYPE_ATTENTION )
     113                        else if (messageType == MESSAGE_TYPE_ATTENTION)
    100114                            StyleConstants.setForeground(attrs, COLOR_ATTENTION);
    101115                    }
    102116                    doc.insertString(doc.getLength(), nline, attrs);
    103                 } catch( BadLocationException ex ) {
    104                     // whatever
     117                } catch (BadLocationException ex) {
     118                    Main.warn(ex);
    105119                }
    106120                thepane.setCaretPosition(doc.getLength());
     
    109123    }
    110124
    111     public void addLineToChatPane( String userName, String line ) {
     125    public void addLineToChatPane(String userName, String line) {
    112126        addLineToChatPane(userName, line, MESSAGE_TYPE_DEFAULT);
    113127    }
    114128
    115     public void addLineToPublic( String line ) {
     129    public void addLineToPublic(String line) {
    116130        addLineToChatPane(PUBLIC_PANE, line);
    117131    }
    118132
    119     public void addLineToPublic( String line, int messageType ) {
     133    public void addLineToPublic(String line, int messageType) {
    120134        addLineToChatPane(PUBLIC_PANE, line, messageType);
    121135    }
     
    125139    }
    126140
    127     public void clearChatPane( String userName) {
    128         if( userName == null || userName.equals(PUBLIC_PANE) )
     141    public void clearChatPane(String userName) {
     142        if (userName == null || userName.equals(PUBLIC_PANE))
    129143            clearPublicChatPane();
    130144        else
     
    136150    }
    137151
    138     public ChatPane createChatPane( String userName ) {
     152    public ChatPane createChatPane(String userName) {
    139153        JTextPane chatPane = new JTextPane();
    140154        chatPane.setEditable(false);
    141155        Font font = chatPane.getFont();
    142156        float size = Main.pref.getInteger("geochat.fontsize", -1);
    143         if( size < 6 )
     157        if (size < 6)
    144158            size += font.getSize2D();
    145159        chatPane.setFont(font.deriveFont(size));
    146 //        DefaultCaret caret = (DefaultCaret)chatPane.getCaret(); // does not work
    147 //        caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
     160        //        DefaultCaret caret = (DefaultCaret)chatPane.getCaret(); // does not work
     161        //        caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
    148162        JScrollPane scrollPane = new JScrollPane(chatPane, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    149163        chatPane.addMouseListener(new GeoChatPopupAdapter(panel));
     
    169183    public String getActiveChatPane() {
    170184        Component c = tabs.getSelectedComponent();
    171         if( c == null )
     185        if (c == null)
    172186            return null;
    173         for( String user : chatPanes.keySet() )
    174             if( c.equals(chatPanes.get(user).component) )
     187        for (String user : chatPanes.keySet()) {
     188            if (c.equals(chatPanes.get(user).component))
    175189                return user;
     190        }
    176191        return null;
    177192    }
     
    182197    }
    183198
    184     public void closeChatPane( String user ) {
    185         if( user == null || user.equals(PUBLIC_PANE) || !chatPanes.containsKey(user) )
     199    public void closeChatPane(String user) {
     200        if (user == null || user.equals(PUBLIC_PANE) || !chatPanes.containsKey(user))
    186201            return;
    187202        tabs.remove(chatPanes.get(user).component);
     
    191206    public void closeSelectedPrivatePane() {
    192207        String pane = getRecipient();
    193         if( pane != null )
     208        if (pane != null)
    194209            closeChatPane(pane);
    195210    }
     
    197212    public void closePrivateChatPanes() {
    198213        List<String> entries = new ArrayList<>(chatPanes.keySet());
    199         for( String user : entries )
    200             if( !user.equals(PUBLIC_PANE) )
     214        for (String user : entries) {
     215            if (!user.equals(PUBLIC_PANE))
    201216                closeChatPane(user);
    202     }
    203    
     217        }
     218    }
     219
    204220    public boolean hasSelectedText() {
    205221        String user = getActiveChatPane();
    206         if( user != null ) {
     222        if (user != null) {
    207223            JTextPane pane = chatPanes.get(user).pane;
    208224            return pane.getSelectedText() != null;
     
    213229    public void copySelectedText() {
    214230        String user = getActiveChatPane();
    215         if( user != null )
     231        if (user != null)
    216232            chatPanes.get(user).pane.copy();
    217233    }
    218    
    219234
    220235    private class ChatTabTitleComponent extends JLabel {
    221236        private ChatPane entry;
    222237
    223         public ChatTabTitleComponent( ChatPane entry ) {
     238        ChatTabTitleComponent(ChatPane entry) {
    224239            super(entry.isPublic ? tr("Public") : entry.userName);
    225240            this.entry = entry;
     
    230245
    231246        public void updateAlarm() {
    232             if( normalFont == null ) {
     247            if (normalFont == null) {
    233248                // prepare cached fonts
    234249                normalFont = getFont().deriveFont(Font.PLAIN);
    235250                boldFont = getFont().deriveFont(Font.BOLD);
    236251            }
    237             if( entry.notify > 0 && !collapsed && tabs.getSelectedIndex() == tabs.indexOfComponent(entry.component) )
     252            if (entry.notify > 0 && !collapsed && tabs.getSelectedIndex() == tabs.indexOfComponent(entry.component))
    238253                entry.notify = 0;
    239254            setFont(entry.notify > 0 ? boldFont : normalFont);
  • applications/editors/josm/plugins/geochat/src/geochat/ChatServerConnection.java

    r30737 r32544  
    1 // License: WTFPL
     1// License: WTFPL. For details, see LICENSE file.
    22package geochat;
    33
     
    2727/**
    2828 * This class holds all the chat data and periodically polls the server.
    29  * 
     29 *
    3030 * @author zverik
    3131 */
    32 class ChatServerConnection {
     32final class ChatServerConnection {
    3333    public static final String TOKEN_PREFIX = "=";
    3434    private static final String TOKEN_PATTERN = "^[a-zA-Z0-9]{10}$";
    35    
     35
    3636    private int userId;
    3737    private String userName;
     
    4747        new Thread(requestThread).start();
    4848    }
    49    
     49
    5050    public static ChatServerConnection getInstance() {
    51         if( instance == null )
     51        if (instance == null)
    5252            instance = new ChatServerConnection();
    5353        return instance;
    5454    }
    5555
    56     public void addListener( ChatServerConnectionListener listener ) {
     56    public void addListener(ChatServerConnectionListener listener) {
    5757        listeners.add(listener);
    5858    }
    5959
    60     public void removeListener( ChatServerConnectionListener listener ) {
     60    public void removeListener(ChatServerConnectionListener listener) {
    6161        listeners.remove(listener);
    6262    }
     
    8585     * Does not autologin, if userName is null, obviously.
    8686     */
    87     public void autoLogin( final String userName ) {
     87    public void autoLogin(final String userName) {
    8888        final int uid = Main.pref.getInteger("geochat.lastuid", 0);
    89         if( uid <= 0 ) {
    90             if( userName != null && userName.length() > 1 )
     89        if (uid <= 0) {
     90            if (userName != null && userName.length() > 1)
    9191                login(userName);
    9292        } else {
    9393            String query = "whoami&uid=" + uid;
    9494            JsonQueryUtil.queryAsync(query, new JsonQueryCallback() {
    95                 public void processJson( JsonObject json ) {
    96                     if( json != null && json.get("name") != null )
     95                @Override
     96                public void processJson(JsonObject json) {
     97                    if (json != null && json.get("name") != null)
    9798                        login(uid, json.getString("name"));
    98                     else if( userName != null && userName.length() > 1 )
     99                    else if (userName != null && userName.length() > 1)
    99100                        login(userName);
    100101                }
     
    107108     * If two seconds have passed, stops the waiting. Doesn't wait if userName is empty.
    108109     */
    109     public void autoLoginWithDelay( final String userName ) {
    110         if( userName == null || userName.length() == 0 ) {
     110    public void autoLoginWithDelay(final String userName) {
     111        if (userName == null || userName.length() == 0) {
    111112            checkLogin();
    112113            return;
    113114        }
    114115        new Thread(new Runnable() {
     116            @Override
    115117            public void run() {
    116118                try {
    117119                    int cnt = 10;
    118                     while( getPosition() == null && cnt-- > 0 )
     120                    while (getPosition() == null && cnt-- > 0) {
    119121                        Thread.sleep(200);
    120                 } catch( InterruptedException e ) {}
     122                    }
     123                } catch (InterruptedException e) {
     124                    Main.warn(e);
     125                }
    121126                autoLogin(userName);
    122127            }
     
    124129    }
    125130
    126     public void login( final String userName ) {
    127         if( userName == null )
     131    public void login(final String userName) {
     132        if (userName == null)
    128133            throw new IllegalArgumentException("userName is null");
    129134        LatLon pos = getPosition();
    130         if( pos == null ) {
     135        if (pos == null) {
    131136            fireLoginFailed("Zoom level is too low");
    132137            return;
    133138        }
    134139        String token = userName.startsWith(TOKEN_PREFIX) ? userName.substring(TOKEN_PREFIX.length()) : null;
    135         if( token != null && !token.matches(TOKEN_PATTERN) ) {
     140        if (token != null && !token.matches(TOKEN_PATTERN)) {
    136141            fireLoginFailed("Incorrect token format");
    137142            return;
     
    141146            String nameAttr = token != null ? "&token=" + token : "&name=" + URLEncoder.encode(userName, "UTF-8");
    142147            String query = "register&lat=" + pos.latToString(CoordinateFormat.DECIMAL_DEGREES)
    143                     + "&lon=" + pos.lonToString(CoordinateFormat.DECIMAL_DEGREES)
    144                     + nameAttr;
     148            + "&lon=" + pos.lonToString(CoordinateFormat.DECIMAL_DEGREES)
     149            + nameAttr;
    145150            JsonQueryUtil.queryAsync(query, new JsonQueryCallback() {
    146                 public void processJson( JsonObject json ) {
    147                     if( json == null )
     151                @Override
     152                public void processJson(JsonObject json) {
     153                    if (json == null)
    148154                        fireLoginFailed(tr("Could not get server response, check logs"));
    149                     else if( json.get("error") != null )
     155                    else if (json.get("error") != null)
    150156                        fireLoginFailed(tr("Failed to login as {0}:", userName) + "\n" + json.getString("error"));
    151                     else if( json.get("uid") == null)
     157                    else if (json.get("uid") == null)
    152158                        fireLoginFailed(tr("The server did not return user ID"));
    153159                    else {
     
    157163                }
    158164            });
    159         } catch( UnsupportedEncodingException e ) {
    160             // wut
    161         }
    162     }
    163 
    164     private void login( int userId, String userName ) {
     165        } catch (UnsupportedEncodingException e) {
     166            Main.error(e);
     167        }
     168    }
     169
     170    private void login(int userId, String userName) {
    165171        this.userId = userId;
    166172        this.userName = userName;
    167173        Main.pref.putInteger("geochat.lastuid", userId);
    168         for( ChatServerConnectionListener listener : listeners )
     174        for (ChatServerConnectionListener listener : listeners) {
    169175            listener.loggedIn(userName);
     176        }
    170177    }
    171178
     
    174181        ChatServerConnection.this.userName = null;
    175182        Main.pref.put("geochat.lastuid", null);
    176         for( ChatServerConnectionListener listener : listeners )
     183        for (ChatServerConnectionListener listener : listeners) {
    177184            listener.notLoggedIn(null);
    178     }
    179 
    180     private void fireLoginFailed( String reason ) {
    181         for( ChatServerConnectionListener listener : listeners )
     185        }
     186    }
     187
     188    private void fireLoginFailed(String reason) {
     189        for (ChatServerConnectionListener listener : listeners) {
    182190            listener.notLoggedIn(reason);
     191        }
    183192    }
    184193
     
    187196     */
    188197    public void logout() {
    189         if( !isLoggedIn() )
     198        if (!isLoggedIn())
    190199            return;
    191200        String query = "logout&uid=" + userId;
    192201        JsonQueryUtil.queryAsync(query, new JsonQueryCallback() {
    193             public void processJson( JsonObject json ) {
    194                 if( json != null && json.get("message") != null) {
     202            @Override
     203            public void processJson(JsonObject json) {
     204                if (json != null && json.get("message") != null) {
    195205                    logoutIntl();
    196206                }
     
    204214     */
    205215    public void bruteLogout() throws IOException {
    206         if( isLoggedIn() )
     216        if (isLoggedIn())
    207217            JsonQueryUtil.query("logout&uid=" + userId);
    208218    }
    209219
    210     private void fireMessageFailed( String reason ) {
    211         for( ChatServerConnectionListener listener : listeners )
     220    private void fireMessageFailed(String reason) {
     221        for (ChatServerConnectionListener listener : listeners) {
    212222            listener.messageSendFailed(reason);
     223        }
    213224    }
    214225
     
    218229     * @see #postMessage(java.lang.String, java.lang.String)
    219230     */
    220     public void postMessage( String message ) {
     231    public void postMessage(String message) {
    221232        postMessage(message, null);
    222233    }
     
    228239     * @param targetUser null if sending to everyone, name of user otherwise.
    229240     */
    230     public void postMessage( String message, String targetUser ) {
    231         if( !isLoggedIn() ) {
     241    public void postMessage(String message, String targetUser) {
     242        if (!isLoggedIn()) {
    232243            fireMessageFailed("Not logged in");
    233244            return;
    234245        }
    235246        LatLon pos = getPosition();
    236         if( pos == null ) {
     247        if (pos == null) {
    237248            fireMessageFailed("Zoom level is too low");
    238249            return;
     
    240251        try {
    241252            String query = "post&lat=" + pos.latToString(CoordinateFormat.DECIMAL_DEGREES)
    242                     + "&lon=" + pos.lonToString(CoordinateFormat.DECIMAL_DEGREES)
    243                     + "&uid=" + userId
    244                     + "&message=" + URLEncoder.encode(message, "UTF8");
    245             if( targetUser != null && targetUser.length() > 0)
    246                     query += "&to=" + URLEncoder.encode(targetUser, "UTF8");
     253            + "&lon=" + pos.lonToString(CoordinateFormat.DECIMAL_DEGREES)
     254            + "&uid=" + userId
     255            + "&message=" + URLEncoder.encode(message, "UTF8");
     256            if (targetUser != null && targetUser.length() > 0)
     257                query += "&to=" + URLEncoder.encode(targetUser, "UTF8");
    247258            JsonQueryUtil.queryAsync(query, new JsonQueryCallback() {
    248                 public void processJson( JsonObject json ) {
    249                     if( json == null )
     259                @Override
     260                public void processJson(JsonObject json) {
     261                    if (json == null)
    250262                        fireMessageFailed(tr("Could not get server response, check logs"));
    251                     else if( json.get("error") != null )
     263                    else if (json.get("error") != null)
    252264                        fireMessageFailed(json.getString("error"));
    253265                }
    254266            });
    255         } catch( UnsupportedEncodingException e ) {
    256             // wut
    257         }
    258     }
    259    
     267        } catch (UnsupportedEncodingException e) {
     268            Main.error(e);
     269        }
     270    }
     271
    260272    /**
    261273     * Returns current coordinates or null if there is no map, or zoom is too low.
    262274     */
    263275    private static LatLon getPosition() {
    264         if( Main.map == null || Main.map.mapView == null )
     276        if (Main.map == null || Main.map.mapView == null)
    265277            return null;
    266         if( getCurrentZoom() < 10 )
     278        if (getCurrentZoom() < 10)
    267279            return null;
    268280        Projection proj = Main.getProjection();
     
    271283
    272284    // Following three methods were snatched from TMSLayer
    273     private static double latToTileY( double lat, int zoom ) {
     285    private static double latToTileY(double lat, int zoom) {
    274286        double l = lat / 180 * Math.PI;
    275287        double pf = Math.log(Math.tan(l) + (1 / Math.cos(l)));
     
    277289    }
    278290
    279     private static double lonToTileX( double lon, int zoom ) {
     291    private static double lonToTileX(double lon, int zoom) {
    280292        return Math.pow(2.0, zoom - 3) * (lon + 180.0) / 45.0;
    281293    }
    282294
    283295    public static int getCurrentZoom() {
    284         if( Main.map == null || Main.map.mapView == null ) {
     296        if (Main.map == null || Main.map.mapView == null) {
    285297            return 1;
    286298        }
     
    295307        int screenPixels = mv.getWidth() * mv.getHeight();
    296308        double tilePixels = Math.abs((y2 - y1) * (x2 - x1) * 256 * 256);
    297         if( screenPixels == 0 || tilePixels == 0 ) {
     309        if (screenPixels == 0 || tilePixels == 0) {
    298310            return 1;
    299311        }
    300312        double factor = screenPixels / tilePixels;
    301313        double result = Math.log(factor) / Math.log(2) / 2 + 1;
    302         int intResult = (int)Math.floor(result);
     314        int intResult = (int) Math.floor(result);
    303315        return intResult;
    304316    }
     
    312324        private boolean stopping = false;
    313325
     326        @Override
    314327        public void run() {
    315 //            lastId = Main.pref.getLong("geochat.lastid", 0);
     328            //            lastId = Main.pref.getLong("geochat.lastid", 0);
    316329            int interval = Main.pref.getInteger("geochat.interval", 2);
    317             while( !stopping ) {
     330            while (!stopping) {
    318331                process();
    319332                try {
    320333                    Thread.sleep(interval * 1000);
    321                 } catch( InterruptedException e ) {
     334                } catch (InterruptedException e) {
    322335                    stopping = true;
    323336                }
     
    330343
    331344        public void process() {
    332             if( !isLoggedIn() ) {
     345            if (!isLoggedIn()) {
    333346                fireStatusChanged(false);
    334347                return;
     
    336349
    337350            LatLon pos = getPosition();
    338             if( pos == null ) {
     351            if (pos == null) {
    339352                fireStatusChanged(false);
    340353                return;
    341354            }
    342355            fireStatusChanged(true);
    343            
     356
    344357            final boolean needReset;
    345358            final boolean needFullReset = lastUserId != userId;
    346             if( needFullReset || (lastPosition != null && pos.greatCircleDistance(lastPosition) > MAX_JUMP) ) {
     359            if (needFullReset || (lastPosition != null && pos.greatCircleDistance(lastPosition) > MAX_JUMP)) {
    347360                // reset messages
    348361                lastId = 0;
    349 //                Main.pref.put("geochat.lastid", null);
     362                //                Main.pref.put("geochat.lastid", null);
    350363                needReset = true;
    351364            } else
     
    353366            lastUserId = userId;
    354367            lastPosition = pos;
    355            
     368
    356369            String query = "get&lat=" + pos.latToString(CoordinateFormat.DECIMAL_DEGREES)
    357                     + "&lon=" + pos.lonToString(CoordinateFormat.DECIMAL_DEGREES)
    358                     + "&uid=" + userId + "&last=" + lastId;
     370            + "&lon=" + pos.lonToString(CoordinateFormat.DECIMAL_DEGREES)
     371            + "&uid=" + userId + "&last=" + lastId;
    359372            JsonObject json;
    360373            try {
    361374                json = JsonQueryUtil.query(query);
    362             } catch( IOException ex ) {
     375            } catch (IOException ex) {
    363376                json = null; // ?
    364377            }
    365             if( json == null ) {
     378            if (json == null) {
    366379                // do nothing?
    367 //              fireLoginFailed(tr("Could not get server response, check logs"));
    368 //              logoutIntl(); // todo: uncomment?
    369             } else if( json.get("error") != null) {
     380                //              fireLoginFailed(tr("Could not get server response, check logs"));
     381                //              logoutIntl(); // todo: uncomment?
     382            } else if (json.get("error") != null) {
    370383                fireLoginFailed(tr("Failed to get messages as {0}:", userName) + "\n" + json.getString("error"));
    371384                logoutIntl();
    372385            } else {
    373                 if( json.get("users") != null) {
     386                if (json.get("users") != null) {
    374387                    Map<String, LatLon> users = parseUsers(json.getJsonArray("users"));
    375                     for( ChatServerConnectionListener listener : listeners )
     388                    for (ChatServerConnectionListener listener : listeners) {
    376389                        listener.updateUsers(users);
    377                 }
    378                 if( json.get("messages") != null) {
     390                    }
     391                }
     392                if (json.get("messages") != null) {
    379393                    List<ChatMessage> messages = parseMessages(json.getJsonArray("messages"), false);
    380                     for( ChatMessage m : messages )
    381                         if( m.getId() > lastId )
     394                    for (ChatMessage m : messages) {
     395                        if (m.getId() > lastId)
    382396                            lastId = m.getId();
    383                     for( ChatServerConnectionListener listener : listeners )
     397                    }
     398                    for (ChatServerConnectionListener listener : listeners) {
    384399                        listener.receivedMessages(needReset, messages);
    385                 }
    386                 if( json.get("private") != null) {
     400                    }
     401                }
     402                if (json.get("private") != null) {
    387403                    List<ChatMessage> messages = parseMessages(json.getJsonArray("private"), true);
    388                     for( ChatMessage m : messages )
    389                         if( m.getId() > lastId )
     404                    for (ChatMessage m : messages) {
     405                        if (m.getId() > lastId)
    390406                            lastId = m.getId();
    391                     for( ChatServerConnectionListener listener : listeners )
     407                    }
     408                    for (ChatServerConnectionListener listener : listeners) {
    392409                        listener.receivedPrivateMessages(needFullReset, messages);
    393                 }
    394             }
    395 //                    if( lastId > 0 && Main.pref.getBoolean("geochat.store.lastid", true) )
    396 //                        Main.pref.putLong("geochat.lastid", lastId);
    397         }
    398 
    399         private List<ChatMessage> parseMessages( JsonArray messages, boolean priv ) {
     410                    }
     411                }
     412            }
     413            //                    if (lastId > 0 && Main.pref.getBoolean("geochat.store.lastid", true) )
     414            //                        Main.pref.putLong("geochat.lastid", lastId);
     415        }
     416
     417        private List<ChatMessage> parseMessages(JsonArray messages, boolean priv) {
    400418            List<ChatMessage> result = new ArrayList<>();
    401             for( int i = 0; i < messages.size(); i++ ) {
     419            for (int i = 0; i < messages.size(); i++) {
    402420                try {
    403                         JsonObject msg = messages.getJsonObject(i);
     421                    JsonObject msg = messages.getJsonObject(i);
    404422                    long id = Long.parseLong(msg.getString("id"));
    405423                    double lat = Double.parseDouble(msg.getString("lat"));
     
    412430                            incoming, message, new Date(timeStamp * 1000));
    413431                    cm.setPrivate(priv);
    414                     if( msg.get("recipient") != null && !incoming )
     432                    if (msg.get("recipient") != null && !incoming)
    415433                        cm.setRecipient(msg.getString("recipient"));
    416434                    result.add(cm);
    417                 } catch( JsonException e ) {
    418                     // do nothing, just skip this message
     435                } catch (JsonException e) {
     436                    Main.trace(e);
    419437                }
    420438            }
     
    422440        }
    423441
    424         private Map<String, LatLon> parseUsers( JsonArray users ) {
     442        private Map<String, LatLon> parseUsers(JsonArray users) {
    425443            Map<String, LatLon> result = new HashMap<>();
    426             for( int i = 0; i < users.size(); i++ ) {
     444            for (int i = 0; i < users.size(); i++) {
    427445                try {
    428                         JsonObject user = users.getJsonObject(i);
     446                    JsonObject user = users.getJsonObject(i);
    429447                    String name = user.getString("user");
    430448                    double lat = Double.parseDouble(user.getString("lat"));
    431449                    double lon = Double.parseDouble(user.getString("lon"));
    432450                    result.put(name, new LatLon(lat, lon));
    433                 } catch( JsonException e ) {
    434                     // do nothing, just skip this user
     451                } catch (JsonException e) {
     452                    Main.trace(e);
    435453                }
    436454            }
     
    438456        }
    439457
    440         private void fireStatusChanged( boolean newStatus ) {
    441             if( newStatus == lastStatus )
     458        private void fireStatusChanged(boolean newStatus) {
     459            if (newStatus == lastStatus)
    442460                return;
    443461            lastStatus = newStatus;
    444             for( ChatServerConnectionListener listener : listeners )
     462            for (ChatServerConnectionListener listener : listeners) {
    445463                listener.statusChanged(newStatus);
     464            }
    446465        }
    447466    }
  • applications/editors/josm/plugins/geochat/src/geochat/ChatServerConnectionListener.java

    r29584 r32544  
    1 // License: WTFPL
     1// License: WTFPL. For details, see LICENSE file.
    22package geochat;
    33
    4 import java.util.*;
     4import java.util.List;
     5import java.util.Map;
     6
    57import org.openstreetmap.josm.data.coor.LatLon;
    68
     
    1517     * @param userName Name of the logged in user.
    1618     */
    17     void loggedIn( String userName );
    18    
     19    void loggedIn(String userName);
     20
    1921    /**
    2022     * User tried to log in, but failed.
    2123     * @param reason Why. <tt>null</tt> if it is intended logout.
    2224     */
    23     void notLoggedIn( String reason );
     25    void notLoggedIn(String reason);
    2426
    2527    /**
     
    2729     * @param reason Why.
    2830     */
    29     void messageSendFailed( String reason );
     31    void messageSendFailed(String reason);
    3032
    3133    /**
     
    3335     * @param active Is the chat active.
    3436     */
    35     void statusChanged( boolean active );
     37    void statusChanged(boolean active);
    3638
    3739    /**
     
    3941     * @param users a hash of user names and coordinates.
    4042     */
    41     void updateUsers( Map<String, LatLon> users );
     43    void updateUsers(Map<String, LatLon> users);
    4244
    4345    /**
     
    4648     * @param messages new messages array.
    4749     */
    48     void receivedMessages( boolean replace, List<ChatMessage> messages );
     50    void receivedMessages(boolean replace, List<ChatMessage> messages);
    4951
    5052    /**
     
    5557     * @param messages list of new private messages.
    5658     */
    57     void receivedPrivateMessages( boolean replace, List<ChatMessage> messages );
     59    void receivedPrivateMessages(boolean replace, List<ChatMessage> messages);
    5860}
  • applications/editors/josm/plugins/geochat/src/geochat/GeoChatPanel.java

    r30737 r32544  
    1 // License: WTFPL
     1// License: WTFPL. For details, see LICENSE file.
    22package geochat;
    33
    4 import java.awt.*;
    5 import java.awt.event.*;
     4import static org.openstreetmap.josm.tools.I18n.tr;
     5import static org.openstreetmap.josm.tools.I18n.trn;
     6
     7import java.awt.AlphaComposite;
     8import java.awt.BorderLayout;
     9import java.awt.Color;
     10import java.awt.Composite;
     11import java.awt.Dimension;
     12import java.awt.Font;
     13import java.awt.FontMetrics;
     14import java.awt.Graphics2D;
     15import java.awt.GridBagConstraints;
     16import java.awt.GridBagLayout;
     17import java.awt.Point;
     18import java.awt.RenderingHints;
     19import java.awt.event.ActionEvent;
     20import java.awt.event.ActionListener;
    621import java.io.IOException;
    722import java.text.SimpleDateFormat;
    8 import java.util.*;
    923import java.util.List;
    10 import javax.swing.*;
     24import java.util.Map;
     25import java.util.TreeMap;
     26
     27import javax.swing.JButton;
     28import javax.swing.JCheckBox;
     29import javax.swing.JComponent;
     30import javax.swing.JLabel;
     31import javax.swing.JPanel;
     32import javax.swing.JTabbedPane;
     33import javax.swing.JTextField;
     34import javax.swing.SwingConstants;
     35
    1136import org.openstreetmap.josm.Main;
    1237import org.openstreetmap.josm.data.Bounds;
    1338import org.openstreetmap.josm.data.coor.LatLon;
    14 import org.openstreetmap.josm.gui.*;
     39import org.openstreetmap.josm.gui.JosmUserIdentityManager;
     40import org.openstreetmap.josm.gui.MapView;
     41import org.openstreetmap.josm.gui.Notification;
    1542import org.openstreetmap.josm.gui.dialogs.ToggleDialog;
    1643import org.openstreetmap.josm.gui.layer.MapViewPaintable;
    1744import org.openstreetmap.josm.gui.util.GuiHelper;
    1845import org.openstreetmap.josm.tools.GBC;
    19 import static org.openstreetmap.josm.tools.I18n.tr;
    20 import static org.openstreetmap.josm.tools.I18n.trn;
    2146
    2247/**
     
    3661    ChatPaneManager chatPanes;
    3762    boolean userLayerActive;
    38    
     63
    3964    public GeoChatPanel() {
    4065        super(tr("GeoChat"), "geochat", tr("Open GeoChat panel"), null, 200, true);
     
    4873        input = new JPanelTextField() {
    4974            @Override
    50             protected void processEnter( String text ) {
     75            protected void processEnter(String text) {
    5176                connection.postMessage(text, chatPanes.getRecipient());
    5277            }
    5378
    5479            @Override
    55             protected String autoComplete( String word, boolean atStart ) {
     80            protected String autoComplete(String word, boolean atStart) {
    5681                return autoCompleteUser(word, atStart);
    5782            }
    5883        };
    59        
     84
    6085        String defaultUserName = constructUserName();
    6186        loginPanel = createLoginPanel(defaultUserName);
     
    76101    private String constructUserName() {
    77102        String userName = Main.pref.get("geochat.username", null); // so the default is null
    78         if( userName == null )
     103        if (userName == null)
    79104            userName = JosmUserIdentityManager.getInstance().getUserName();
    80         if( userName == null )
     105        if (userName == null)
    81106            userName = "";
    82         if( userName.contains("@") )
     107        if (userName.contains("@"))
    83108            userName = userName.substring(0, userName.indexOf('@'));
    84109        userName = userName.replace(' ', '_');
     
    86111    }
    87112
    88     private JPanel createLoginPanel( String defaultUserName ) {
     113    private JPanel createLoginPanel(String defaultUserName) {
    89114        final JTextField nameField = new JPanelTextField() {
    90115            @Override
    91             protected void processEnter( String text ) {
     116            protected void processEnter(String text) {
    92117                connection.login(text);
    93118            }
     
    98123        loginButton.addActionListener(new ActionListener() {
    99124            @Override
    100             public void actionPerformed( ActionEvent e ) {
     125            public void actionPerformed(ActionEvent e) {
    101126                connection.login(nameField.getText());
    102127            }
     
    107132        autoLoginBox.addActionListener(new ActionListener() {
    108133            @Override
    109             public void actionPerformed( ActionEvent e ) {
     134            public void actionPerformed(ActionEvent e) {
    110135                Main.pref.put("geochat.autologin", autoLoginBox.isSelected());
    111136            }
     
    126151    public void destroy() {
    127152        try {
    128             if( Main.pref.getBoolean("geochat.logout.on.close", true) ) {
     153            if (Main.pref.getBoolean("geochat.logout.on.close", true)) {
    129154                connection.removeListener(this);
    130155                connection.bruteLogout();
    131156            }
    132         } catch( IOException e ) {
     157        } catch (IOException e) {
    133158            Main.warn("Failed to logout from geochat server: " + e.getMessage());
    134159        }
     
    136161    }
    137162
    138     private String autoCompleteUser( String word, boolean atStart ) {
     163    private String autoCompleteUser(String word, boolean atStart) {
    139164        String result = null;
    140165        boolean singleUser = true;
    141         for( String user : users.keySet() ) {
    142             if( user.startsWith(word) ) {
    143                 if( result == null )
     166        for (String user : users.keySet()) {
     167            if (user.startsWith(word)) {
     168                if (result == null)
    144169                    result = user;
    145170                else {
    146171                    singleUser = false;
    147172                    int i = word.length();
    148                     while( i < result.length() && i < user.length() && result.charAt(i) == user.charAt(i) )
     173                    while (i < result.length() && i < user.length() && result.charAt(i) == user.charAt(i)) {
    149174                        i++;
    150                     if( i < result.length() )
     175                    }
     176                    if (i < result.length())
    151177                        result = result.substring(0, i);
    152178                }
     
    161187     */
    162188    @Override
    163     public void paint( Graphics2D g, MapView mv, Bounds bbox ) {
    164         Graphics2D g2d = (Graphics2D)g.create();
     189    public void paint(Graphics2D g, MapView mv, Bounds bbox) {
     190        Graphics2D g2d = (Graphics2D) g.create();
    165191        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    166192        Composite ac04 = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.4f);
     
    171197        FontMetrics fm = g2d.getFontMetrics();
    172198
    173         for( String user : users.keySet() ) {
     199        for (String user : users.keySet()) {
    174200            int stringWidth = fm.stringWidth(user);
    175201            int radius = stringWidth / 2 + 10;
     
    193219    protected void updateTitleAlarm() {
    194220        int alarmLevel = connection.isLoggedIn() ? chatPanes.getNotifyLevel() : 0;
    195         if( !isDialogInCollapsedView() && alarmLevel > 1 )
     221        if (!isDialogInCollapsedView() && alarmLevel > 1)
    196222            alarmLevel = 1;
    197223
    198224        String comment;
    199         if( connection.isLoggedIn() ) {
     225        if (connection.isLoggedIn()) {
    200226            comment = trn("{0} user", "{0} users", users.size() + 1, users.size() + 1);
    201227        } else {
     
    204230
    205231        String title = tr("GeoChat");
    206         if( comment != null )
     232        if (comment != null)
    207233            title = title + " (" + comment + ")";
    208234        final String alarm = (alarmLevel <= 0 ? "" : alarmLevel == 1 ? "* " : "!!! ") + title;
     
    219245     */
    220246    @Override
    221     protected void setIsCollapsed( boolean val ) {
     247    protected void setIsCollapsed(boolean val) {
    222248        super.setIsCollapsed(val);
    223249        chatPanes.setCollapsed(val);
     
    228254
    229255    @Override
    230     public void loggedIn( String userName ) {
     256    public void loggedIn(String userName) {
    231257        Main.pref.put("geochat.username", userName);
    232         if( gcPanel.getComponentCount() == 1 ) {
     258        if (gcPanel.getComponentCount() == 1) {
    233259            GuiHelper.runInEDTAndWait(new Runnable() {
    234260                @Override
     
    244270
    245271    @Override
    246     public void notLoggedIn( final String reason ) {
    247         if( reason != null ) {
     272    public void notLoggedIn(final String reason) {
     273        if (reason != null) {
    248274            GuiHelper.runInEDT(new Runnable() {
    249275                @Override
     
    254280        } else {
    255281            // regular logout
    256             if( gcPanel.getComponentCount() > 1 ) {
     282            if (gcPanel.getComponentCount() > 1) {
    257283                gcPanel.removeAll();
    258284                gcPanel.add(loginPanel, BorderLayout.CENTER);
     
    263289
    264290    @Override
    265     public void messageSendFailed( final String reason ) {
     291    public void messageSendFailed(final String reason) {
    266292        GuiHelper.runInEDT(new Runnable() {
    267293            @Override
     
    273299
    274300    @Override
    275     public void statusChanged( boolean active ) {
     301    public void statusChanged(boolean active) {
    276302        // only the public tab, because private chats don't rely on coordinates
    277303        tabs.setComponentAt(0, active ? chatPanes.getPublicChatComponent() : noData);
     
    280306
    281307    @Override
    282     public void updateUsers( Map<String, LatLon> newUsers ) {
    283         for( String uname : this.users.keySet() ) {
    284             if( !newUsers.containsKey(uname) )
     308    public void updateUsers(Map<String, LatLon> newUsers) {
     309        for (String uname : this.users.keySet()) {
     310            if (!newUsers.containsKey(uname))
    285311                chatPanes.addLineToPublic(tr("User {0} has left", uname), ChatPaneManager.MESSAGE_TYPE_INFORMATION);
    286312        }
    287         for( String uname : newUsers.keySet() ) {
    288             if( !this.users.containsKey(uname) )
     313        for (String uname : newUsers.keySet()) {
     314            if (!this.users.containsKey(uname))
    289315                chatPanes.addLineToPublic(tr("User {0} is mapping nearby", uname), ChatPaneManager.MESSAGE_TYPE_INFORMATION);
    290316        }
    291317        this.users = newUsers;
    292318        updateTitleAlarm();
    293         if( userLayerActive && Main.map.mapView != null )
     319        if (userLayerActive && Main.map.mapView != null)
    294320            Main.map.mapView.repaint();
    295321    }
     
    297323    private final SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm");
    298324
    299     private void formatMessage( StringBuilder sb, ChatMessage msg ) {
     325    private void formatMessage(StringBuilder sb, ChatMessage msg) {
    300326        sb.append("\n");
    301327        sb.append('[').append(TIME_FORMAT.format(msg.getTime())).append("] ");
     
    304330
    305331    @Override
    306     public void receivedMessages( boolean replace, List<ChatMessage> messages ) {
    307         if( replace )
     332    public void receivedMessages(boolean replace, List<ChatMessage> messages) {
     333        if (replace)
    308334            chatPanes.clearPublicChatPane();
    309         if( !messages.isEmpty() ) {
     335        if (!messages.isEmpty()) {
    310336            int alarm = 0;
    311337            StringBuilder sb = new StringBuilder();
    312             for( ChatMessage msg : messages ) {
     338            for (ChatMessage msg : messages) {
    313339                boolean important = msg.isIncoming() && containsName(msg.getMessage());
    314                 if( msg.isIncoming() && alarm < 2 ) {
     340                if (msg.isIncoming() && alarm < 2) {
    315341                    alarm = important ? 2 : 1;
    316342                }
    317                 if( important ) {
     343                if (important) {
    318344                    // add buffer, then add current line with italic, then clear buffer
    319345                    chatPanes.addLineToPublic(sb.toString());
     
    326352            }
    327353            chatPanes.addLineToPublic(sb.toString());
    328             if( alarm > 0 )
     354            if (alarm > 0)
    329355                chatPanes.notify(null, alarm);
    330356        }
    331         if( replace )
     357        if (replace)
    332358            showNearbyUsers();
    333359    }
    334360
    335361    private void showNearbyUsers() {
    336         if( !users.isEmpty() ) {
     362        if (!users.isEmpty()) {
    337363            StringBuilder sb = new StringBuilder(tr("Users mapping nearby:"));
    338364            boolean first = true;
    339             for( String user : users.keySet() ) {
     365            for (String user : users.keySet()) {
    340366                sb.append(first ? " " : ", ");
    341367                sb.append(user);
     
    345371    }
    346372
    347     private boolean containsName( String message ) {
     373    private boolean containsName(String message) {
    348374        String userName = connection.getUserName();
    349375        int length = userName.length();
    350376        int i = message.indexOf(userName);
    351         while( i >= 0 ) {
    352             if( (i == 0 || !Character.isJavaIdentifierPart(message.charAt(i - 1)))
    353                     && (i + length >= message.length() || !Character.isJavaIdentifierPart(message.charAt(i + length))) )
     377        while (i >= 0) {
     378            if ((i == 0 || !Character.isJavaIdentifierPart(message.charAt(i - 1)))
     379                    && (i + length >= message.length() || !Character.isJavaIdentifierPart(message.charAt(i + length))))
    354380                return true;
    355381            i = message.indexOf(userName, i + 1);
     
    359385
    360386    @Override
    361     public void receivedPrivateMessages( boolean replace, List<ChatMessage> messages ) {
    362         if( replace )
     387    public void receivedPrivateMessages(boolean replace, List<ChatMessage> messages) {
     388        if (replace)
    363389            chatPanes.closePrivateChatPanes();
    364         for( ChatMessage msg : messages ) {
     390        for (ChatMessage msg : messages) {
    365391            StringBuilder sb = new StringBuilder();
    366392            formatMessage(sb, msg);
    367393            chatPanes.addLineToChatPane(msg.isIncoming() ? msg.getAuthor() : msg.getRecipient(), sb.toString());
    368             if( msg.isIncoming() )
     394            if (msg.isIncoming())
    369395                chatPanes.notify(msg.getAuthor(), 2);
    370396        }
  • applications/editors/josm/plugins/geochat/src/geochat/GeoChatPlugin.java

    r29584 r32544  
    1 // License: WTFPL
     1// License: WTFPL. For details, see LICENSE file.
    22package geochat;
    33
     
    88/**
    99 * Create chat panel.
    10  * 
     10 *
    1111 * @author zverik
    1212 */
    1313public class GeoChatPlugin extends Plugin {
    14     public GeoChatPlugin( PluginInformation info ) {
     14    public GeoChatPlugin(PluginInformation info) {
    1515        super(info);
    1616    }
    17    
     17
    1818    @Override
    19     public void mapFrameInitialized( MapFrame oldFrame, MapFrame newFrame ) {
    20         if( oldFrame == null && newFrame != null ) {
     19    public void mapFrameInitialized(MapFrame oldFrame, MapFrame newFrame) {
     20        if (oldFrame == null && newFrame != null) {
    2121            newFrame.addToggleDialog(new GeoChatPanel());
    2222        }
  • applications/editors/josm/plugins/geochat/src/geochat/GeoChatPopupAdapter.java

    r29584 r32544  
    1 // License: WTFPL
     1// License: WTFPL. For details, see LICENSE file.
    22package geochat;
     3
     4import static org.openstreetmap.josm.tools.I18n.tr;
    35
    46import java.awt.event.ActionEvent;
    57import java.awt.event.MouseAdapter;
    68import java.awt.event.MouseEvent;
    7 import javax.swing.*;
     9
     10import javax.swing.AbstractAction;
     11import javax.swing.JCheckBoxMenuItem;
     12import javax.swing.JMenu;
     13import javax.swing.JPopupMenu;
     14
    815import org.openstreetmap.josm.Main;
    9 import static org.openstreetmap.josm.tools.I18n.tr;
    1016
    1117/**
     
    1622    private GeoChatPanel panel;
    1723
    18     public GeoChatPopupAdapter( GeoChatPanel panel ) {
     24    GeoChatPopupAdapter(GeoChatPanel panel) {
    1925        this.panel = panel;
    2026    }
    2127
    2228    @Override
    23     public void mousePressed( MouseEvent e ) {
     29    public void mousePressed(MouseEvent e) {
    2430        check(e);
    2531    }
    2632
    2733    @Override
    28     public void mouseReleased( MouseEvent e ) {
     34    public void mouseReleased(MouseEvent e) {
    2935        check(e);
    3036    }
    3137
    32     private void check( MouseEvent e ) {
    33         if( e.isPopupTrigger() ) {
     38    private void check(MouseEvent e) {
     39        if (e.isPopupTrigger()) {
    3440            createPopupMenu().show(e.getComponent(), e.getX(), e.getY());
    3541        }
     
    3844    private JPopupMenu createPopupMenu() {
    3945        JMenu userMenu = new JMenu(tr("Private chat"));
    40         for( String user : panel.users.keySet() ) {
    41             if( !panel.chatPanes.hasUser(user) )
     46        for (String user : panel.users.keySet()) {
     47            if (!panel.chatPanes.hasUser(user))
    4248                userMenu.add(new PrivateChatAction(user));
    4349        }
    4450
    4551        JPopupMenu menu = new JPopupMenu();
    46         if( panel.chatPanes.hasSelectedText() )
     52        if (panel.chatPanes.hasSelectedText())
    4753            menu.add(new CopyTextAction());
    4854        menu.add(new JCheckBoxMenuItem(new ToggleUserLayerAction()));
    49         if( userMenu.getItemCount() > 0 )
     55        if (userMenu.getItemCount() > 0)
    5056            menu.add(userMenu);
    51         if( panel.chatPanes.getRecipient() != null )
     57        if (panel.chatPanes.getRecipient() != null)
    5258            menu.add(new CloseTabAction());
    53 //        menu.add(new ClearPaneAction());
    5459        menu.add(new LogoutAction());
    5560        return menu;
     
    5964        private String userName;
    6065
    61         public PrivateChatAction( String userName ) {
     66        PrivateChatAction(String userName) {
    6267            super(userName);
    6368            this.userName = userName;
    6469        }
    6570
    66         public void actionPerformed( ActionEvent e ) {
    67             if( !panel.chatPanes.hasUser(userName) ) {
     71        @Override
     72        public void actionPerformed(ActionEvent e) {
     73            if (!panel.chatPanes.hasUser(userName)) {
    6874                panel.chatPanes.createChatPane(userName);
    6975            }
     
    7278
    7379    private class CloseTabAction extends AbstractAction {
    74         public CloseTabAction() {
     80        CloseTabAction() {
    7581            super(tr("Close tab"));
    76 //            putValue(SMALL_ICON, ImageProvider.get("help"));
    7782        }
    7883
    79         public void actionPerformed( ActionEvent e ) {
     84        @Override
     85        public void actionPerformed(ActionEvent e) {
    8086            panel.chatPanes.closeSelectedPrivatePane();
    8187        }
     
    8389
    8490    private class LogoutAction extends AbstractAction {
    85         public LogoutAction() {
     91        LogoutAction() {
    8692            super(tr("Logout"));
    87 //            putValue(SMALL_ICON, ImageProvider.get("help"));
     93            //            putValue(SMALL_ICON, ImageProvider.get("help"));
    8894        }
    8995
    90         public void actionPerformed( ActionEvent e ) {
     96        @Override
     97        public void actionPerformed(ActionEvent e) {
    9198            panel.logout();
    9299        }
     
    94101
    95102    private class ClearPaneAction extends AbstractAction {
    96         public ClearPaneAction() {
     103        ClearPaneAction() {
    97104            super(tr("Clear log"));
    98 //            putValue(SMALL_ICON, ImageProvider.get("help"));
    99105        }
    100106
    101         public void actionPerformed( ActionEvent e ) {
     107        @Override
     108        public void actionPerformed(ActionEvent e) {
    102109            panel.chatPanes.clearActiveChatPane();
    103110        }
     
    105112
    106113    private class ToggleUserLayerAction extends AbstractAction {
    107         public ToggleUserLayerAction() {
     114        ToggleUserLayerAction() {
    108115            super(tr("Show users on map"));
    109 //            putValue(SMALL_ICON, ImageProvider.get("help"));
    110116            putValue(SELECTED_KEY, Boolean.valueOf(panel.userLayerActive));
    111117        }
    112118
    113         public void actionPerformed( ActionEvent e ) {
    114             if( Main.map == null || Main.map.mapView == null )
     119        @Override
     120        public void actionPerformed(ActionEvent e) {
     121            if (Main.map == null || Main.map.mapView == null)
    115122                return;
    116123            boolean wasAdded = Main.map.mapView.addTemporaryLayer(panel);
    117             if( !wasAdded )
     124            if (!wasAdded)
    118125                Main.map.mapView.removeTemporaryLayer(panel);
    119126            panel.userLayerActive = wasAdded;
     
    124131
    125132    private class CopyTextAction extends AbstractAction {
    126         public CopyTextAction() {
     133        CopyTextAction() {
    127134            super(tr("Copy"));
    128 //            putValue(SMALL_ICON, ImageProvider.get("help"));
    129135        }
    130136
    131         public void actionPerformed( ActionEvent e ) {
     137        @Override
     138        public void actionPerformed(ActionEvent e) {
    132139            panel.chatPanes.copySelectedText();
    133140        }
  • applications/editors/josm/plugins/geochat/src/geochat/JPanelTextField.java

    r29588 r32544  
    1 // License: WTFPL
     1// License: WTFPL. For details, see LICENSE file.
    22package geochat;
     3
     4import static org.openstreetmap.josm.tools.I18n.tr;
    35
    46import java.awt.KeyboardFocusManager;
     
    68import java.awt.event.KeyEvent;
    79import java.util.HashSet;
    8 import javax.swing.*;
     10
     11import javax.swing.JComponent;
     12import javax.swing.JMenuItem;
     13import javax.swing.JPopupMenu;
     14import javax.swing.JTextField;
     15import javax.swing.KeyStroke;
    916import javax.swing.text.DefaultEditorKit;
     17
    1018import org.openstreetmap.josm.Main;
    1119import org.openstreetmap.josm.gui.widgets.PopupMenuLauncher;
    12 import static org.openstreetmap.josm.tools.I18n.tr;
    1320
    1421/**
     
    1926 */
    2027public class JPanelTextField extends JTextField {
    21    
     28
    2229    public JPanelTextField() {
    2330        setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, new HashSet<KeyStroke>());
     
    3643    }
    3744
    38     private JMenuItem createMenuItem( String action, String label ) {
     45    private JMenuItem createMenuItem(String action, String label) {
    3946        JMenuItem item = new JMenuItem(getActionMap().get(action));
    4047        item.setText(label);
     
    4451    // list of "standard" OS keys for JTextFiels = cursor moving, selection, copy/paste
    4552    private final KeyStroke[] standardKeys;
    46     private static final int MODIFIERS_MASK = InputEvent.META_DOWN_MASK | InputEvent.CTRL_DOWN_MASK | InputEvent.ALT_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK;
     53    private static final int MODIFIERS_MASK =
     54            InputEvent.META_DOWN_MASK | InputEvent.CTRL_DOWN_MASK | InputEvent.ALT_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK;
    4755
    4856    @Override
    49     protected void processKeyEvent( KeyEvent e ) {
    50         if( e.getID() == KeyEvent.KEY_PRESSED ) {
     57    protected void processKeyEvent(KeyEvent e) {
     58        if (e.getID() == KeyEvent.KEY_PRESSED) {
    5159            int code = e.getKeyCode();
    52             if( code == KeyEvent.VK_ENTER ) {
     60            if (code == KeyEvent.VK_ENTER) {
    5361                String text = getText();
    54                 if( text.length() > 0 ) {
     62                if (text.length() > 0) {
    5563                    processEnter(text);
    5664                    setText("");
    5765                }
    58             } else if( code == KeyEvent.VK_TAB ) {
     66            } else if (code == KeyEvent.VK_TAB) {
    5967                String text = getText();
    6068                int caret = getCaretPosition();
    6169                int start = caret - 1;
    62                 while( start >= 0 && Character.isJavaIdentifierPart(text.charAt(start)) )
     70                while (start >= 0 && Character.isJavaIdentifierPart(text.charAt(start))) {
    6371                    start--;
     72                }
    6473                start++;
    65                 if( start < caret ) {
     74                if (start < caret) {
    6675                    String word = text.substring(start, caret);
    6776                    String complete = word == null ? null : autoComplete(word, start == 0);
    68                     if( complete != null && !complete.equals(word) ) {
     77                    if (complete != null && !complete.equals(word)) {
    6978                        StringBuilder sb = new StringBuilder();
    70                         if( start > 0 )
     79                        if (start > 0)
    7180                            sb.append(text.substring(0, start));
    7281                        sb.append(complete);
    73                         if( caret < text.length() )
     82                        if (caret < text.length())
    7483                            sb.append(text.substring(caret));
    7584                        setText(sb.toString());
     
    7786                    }
    7887                }
    79             } else if( code == KeyEvent.VK_ESCAPE ) {
    80                 if( Main.map != null && Main.map.mapView != null )
     88            } else if (code == KeyEvent.VK_ESCAPE) {
     89                if (Main.map != null && Main.map.mapView != null)
    8190                    Main.map.mapView.requestFocus();
    82             } 
     91            }
    8392
    8493            boolean keyIsStandard = false;
    8594            for (KeyStroke ks: standardKeys) {
    86                 if (code == ks.getKeyCode() && 
    87                        (e.getModifiersEx() & MODIFIERS_MASK) == (ks.getModifiers() & MODIFIERS_MASK)) {
     95                if (code == ks.getKeyCode() &&
     96                        (e.getModifiersEx() & MODIFIERS_MASK) == (ks.getModifiers() & MODIFIERS_MASK)) {
    8897                    keyIsStandard = true;
    8998                    break;
     
    91100            }
    92101            // Do not pass other events to JOSM
    93             if( !keyIsStandard ) {
     102            if (!keyIsStandard) {
    94103                e.consume();
    95104            }
     
    100109    /**
    101110     * Process VK_ENTER. Override this to submit the text.
    102      * 
     111     *
    103112     * @param text Contents of the text field.
    104113     */
    105     protected void processEnter( String text ) { }
     114    protected void processEnter(String text) { }
    106115
    107116    /**
     
    110119     * @return The whole word.
    111120     */
    112     protected String autoComplete( String word, boolean atStart ) {
     121    protected String autoComplete(String word, boolean atStart) {
    113122        return word;
    114123    }
  • applications/editors/josm/plugins/geochat/src/geochat/JsonQueryCallback.java

    r30234 r32544  
    1 // License: WTFPL
     1// License: WTFPL. For details, see LICENSE file.
    22package geochat;
    33
     
    1717     * @param json JSON parsed response or null if the query was unsuccessful.
    1818     */
    19     void processJson( JsonObject json );
     19    void processJson(JsonObject json);
    2020}
  • applications/editors/josm/plugins/geochat/src/geochat/JsonQueryUtil.java

    r30234 r32544  
    1 // License: WTFPL
     1// License: WTFPL. For details, see LICENSE file.
    22package geochat;
    33
     
    2020 * @author zverik
    2121 */
    22 public class JsonQueryUtil implements Runnable {
     22public final class JsonQueryUtil implements Runnable {
    2323
    2424    /**
     
    2828     * @throws IOException There was a problem connecting to the server or parsing JSON.
    2929     */
    30     public static JsonObject query( String query ) throws IOException {
     30    public static JsonObject query(String query) throws IOException {
    3131        try {
    3232            String serverURL = Main.pref.get("geochat.server", "http://zverik.dev.openstreetmap.org/osmochat.php?action=");
    3333            URL url = new URL(serverURL + query);
    34 //            System.out.println("GeoChat URL = " + url.toString());
    35             HttpURLConnection connection = (HttpURLConnection)url.openConnection();
     34            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    3635            connection.connect();
    37             if( connection.getResponseCode() != 200 ) {
     36            if (connection.getResponseCode() != 200) {
    3837                throw new IOException("HTTP Response code " + connection.getResponseCode() + " (" + connection.getResponseMessage() + ")");
    3938            }
    4039            InputStream inp = connection.getInputStream();
    41             if( inp == null )
     40            if (inp == null)
    4241                throw new IOException("Empty response");
    4342            try {
    4443                return Json.createReader(inp).readObject();
    45             } catch( JsonException e ) {
     44            } catch (JsonException e) {
    4645                throw new IOException("Failed to parse JSON: " + e.getMessage());
    4746            } finally {
    4847                connection.disconnect();
    4948            }
    50         } catch( MalformedURLException ex ) {
     49        } catch (MalformedURLException ex) {
    5150            throw new IOException("Malformed URL: " + ex.getMessage());
    5251        }
     
    6059    private JsonQueryUtil() {}
    6160
    62     private JsonQueryUtil( String query, JsonQueryCallback callback ) {
     61    private JsonQueryUtil(String query, JsonQueryCallback callback) {
    6362        this.query = query;
    6463        this.callback = callback;
     
    7069     * @param callback Callback listener to process the JSON response.
    7170     */
    72     public static void queryAsync( String query, JsonQueryCallback callback ) {
     71    public static void queryAsync(String query, JsonQueryCallback callback) {
    7372        Main.worker.submit(new JsonQueryUtil(query, callback));
    7473    }
    7574
    7675    private void doRealRun() {
    77         JsonObject obj;
     76        JsonObject obj;
    7877        try {
    7978            obj = query(query);
    80         } catch( IOException e ) {
     79        } catch (IOException e) {
    8180            Main.warn(e.getClass().getName() + " while connecting to a chat server: " + e.getMessage());
    8281            obj = null;
    8382        }
    84         if( callback != null )
     83        if (callback != null)
    8584            callback.processJson(obj);
    8685    }
    8786
     87    @Override
    8888    public void run() {
    89         if( EventQueue.isDispatchThread() ) {
     89        if (EventQueue.isDispatchThread()) {
    9090            new Thread(new Runnable() {
     91                @Override
    9192                public void run() {
    9293                    doRealRun();
Note: See TracChangeset for help on using the changeset viewer.