Welcome to mirror list, hosted at ThFree Co, Russian Federation.

PublicServerListFragment.java « servers « mumla « lublin « se « java « main « src « app - gitlab.com/quite/mumla.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: b753a910efc59be3bb1388949a64a6e395d71795 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
/*
 * Copyright (C) 2014 Andrew Comminos
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package se.lublin.mumla.servers;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import se.lublin.humla.model.Server;
import se.lublin.mumla.R;
import se.lublin.mumla.Settings;
import se.lublin.mumla.db.DatabaseProvider;
import se.lublin.mumla.db.MumlaDatabase;
import se.lublin.mumla.db.PublicServer;

/**
 * Displays a list of public servers that can be connected to, sorted, and favourited.
 * @author morlunk
 *
 */
public class PublicServerListFragment extends Fragment implements OnItemClickListener, PublicServerAdapter.PublicServerAdapterMenuListener {
    
    private FavouriteServerListFragment.ServerConnectHandler mConnectHandler;
    private DatabaseProvider mDatabaseProvider;
    private List<PublicServer> mServers;
    private GridView mServerGrid;
    private ProgressBar mServerProgress;
    private PublicServerAdapter mServerAdapter;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setHasOptionsMenu(true);
    }
    
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        
        try {
            mConnectHandler = (FavouriteServerListFragment.ServerConnectHandler)activity;
            mDatabaseProvider = (DatabaseProvider) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()+" must implement ServerConnectHandler and DatabaseProvider!");
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        fillPublicList();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_public_server_list, container, false);
        mServerGrid = (GridView) view.findViewById(R.id.server_list_grid);
        mServerGrid.setOnItemClickListener(this);
        if(mServerAdapter != null)
            mServerGrid.setAdapter(mServerAdapter);
        mServerProgress = (ProgressBar) view.findViewById(R.id.serverProgress);
        mServerProgress.setVisibility(mServerAdapter == null ? View.VISIBLE : View.GONE);
        return view;
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        menu.findItem(R.id.menu_match_server).setVisible(VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB); // Executors only supported on Honeycomb +
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.fragment_public_server_list, menu);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (isFilled()) {
            switch(item.getItemId()) {
                case R.id.menu_match_server:
                    showMatchDialog();
                    break;
                case R.id.menu_sort_server_item:
                    showSortDialog();
                    return true;
                case R.id.menu_search_server_item:
                    showFilterDialog();
                    return true;
            }
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void favouriteServer(final Server server) {
        final Settings settings = Settings.getInstance(getActivity());
        final EditText usernameField = new EditText(getActivity());
        usernameField.setHint(settings.getDefaultUsername());
        AlertDialog.Builder adb = new AlertDialog.Builder(getActivity());
        adb.setTitle(R.string.addFavorite);
        adb.setView(usernameField);
        adb.setPositiveButton(R.string.add, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if(usernameField.getText().length() > 0) {
                    server.setUsername(usernameField.getText().toString());
                } else {
                    server.setUsername(settings.getDefaultUsername());
                }
                MumlaDatabase database = mDatabaseProvider.getDatabase();
                database.addServer(server);
            }
        });
        adb.setNegativeButton(android.R.string.cancel, null);
        adb.show();
    }
    
    public void setServers(List<PublicServer> servers) {
        mServers = servers;
        mServerProgress.setVisibility(View.GONE);
        mServerAdapter = new PublicServerAdapter(getActivity(), servers, this);
        mServerGrid.setAdapter(mServerAdapter);
    }
    
    public boolean isFilled() {
        return mServerAdapter != null;
    }

    private void showMatchDialog() {
        AlertDialog.Builder adb = new AlertDialog.Builder(getActivity());
        adb.setTitle(R.string.server_match);
        adb.setMessage(R.string.server_match_description);
        adb.setPositiveButton(R.string.search, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                findOptimalServer();
            }
        });
        adb.setNegativeButton(android.R.string.cancel, null);
        adb.show();
    }

    private void findOptimalServer() {
        MatchServerTask matchServerTask = new MatchServerTask();
        matchServerTask.execute(Locale.getDefault().getCountry());
    }

    private void showSortDialog() {
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(getActivity());
        alertBuilder.setTitle(R.string.sortBy);
        alertBuilder.setItems(new String[] { getString(R.string.name), getString(R.string.country)}, new SortClickListener());
        alertBuilder.show();
    }
    
    private void showFilterDialog() {
        View dialogView = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.dialog_server_search, null);
        final EditText nameText = (EditText) dialogView.findViewById(R.id.server_search_name);
        final EditText countryText = (EditText) dialogView.findViewById(R.id.server_search_country);
                
        final AlertDialog dlg = new AlertDialog.Builder(getActivity()).
            setTitle(R.string.search).
            setView(dialogView).
            setPositiveButton(R.string.search, new DialogInterface.OnClickListener() {
                public void onClick(final DialogInterface dialog, final int which)
                {
                    String queryName = nameText.getText().toString().toUpperCase(Locale.US);
                    String queryCountry = countryText.getText().toString().toUpperCase(Locale.US);
                    mServerAdapter.filter(queryName, queryCountry);
                    dialog.dismiss();
                }
            }).create();
        
        nameText.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        nameText.setOnEditorActionListener(new OnEditorActionListener() {
            @Override
            public boolean onEditorAction(final TextView v, final int actionId, final KeyEvent event)
            {
                String queryName = nameText.getText().toString().toUpperCase(Locale.US);
                String queryCountry = countryText.getText().toString().toUpperCase(Locale.US);
                mServerAdapter.filter(queryName, queryCountry);
                dlg.dismiss();
                return true;
            }
        });
        
        countryText.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        countryText.setOnEditorActionListener(new OnEditorActionListener() {
            @Override
            public boolean onEditorAction(final TextView v, final int actionId, final KeyEvent event)
            {
                String queryName = nameText.getText().toString().toUpperCase(Locale.US);
                String queryCountry = countryText.getText().toString().toUpperCase(Locale.US);
                mServerAdapter.filter(queryName, queryCountry);
                dlg.dismiss();
                return true;
            }
        });
        
        // Show keyboard automatically
        nameText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    dlg.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
                }
            }
        });
        
        dlg.show();
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        mConnectHandler.connectToPublicServer(mServerAdapter.getItem(arg2));
    }

    private void fillPublicList() {
        new PublicServerFetchTask() {
            protected void onPostExecute(List<PublicServer> result) {
                super.onPostExecute(result);

                if (result == null) {
                    // Handle error
                    Toast.makeText(getActivity(), R.string.error_fetching_servers, Toast.LENGTH_SHORT).show();
                    return;
                }

                if(isVisible()) // Prevents NPEs when fragment is detached.
                    setServers(result);
            };
        }.execute();
    }

    private class SortClickListener implements DialogInterface.OnClickListener {

        private static final int SORT_NAME = 0;
        private static final int SORT_COUNTRY = 1;
        
        private Comparator<PublicServer> nameComparator = new Comparator<PublicServer>() {
            @Override
            public int compare(PublicServer lhs, PublicServer rhs) {
                return lhs.getName().compareTo(rhs.getName());
            }
        };

        private Comparator<PublicServer> countryComparator = new Comparator<PublicServer>() {
            @Override
            public int compare(PublicServer lhs, PublicServer rhs) {
                if(rhs.getCountry() == null) return -1;
                else if(lhs.getCountry() == null) return 1;
                return lhs.getCountry().compareTo(rhs.getCountry());
            }
        };
        
        
        @Override
        public void onClick(DialogInterface dialog, int which) {
            ArrayAdapter<PublicServer> arrayAdapter = mServerAdapter;
            if(which == SORT_NAME) {
                arrayAdapter.sort(nameComparator);
            } else if(which == SORT_COUNTRY) {
                arrayAdapter.sort(countryComparator);
            }
        }
    }

    /**
     * Finds an empty server in the user's country code with low latency.
     * By default, it will show a ProgressDialog while it performs this and an AlertDialog allowing the user to connect.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private class MatchServerTask extends AsyncTask<String, Void, ServerInfoResponse> {

        /**
         * Query until we find up to SEARCH_RANGE empty servers that meet the zero user and location requirements.
         * Once we have that, then we'll sort them based on latency.
         * TODO make this a user-changeable option.
         */
        public static final int SEARCH_RANGE = 20;

        private Comparator<ServerInfoResponse> mLatencyComparator = new Comparator<ServerInfoResponse>() {
            @Override
            public int compare(ServerInfoResponse lhs, ServerInfoResponse rhs) {
                return lhs.getLatency() == rhs.getLatency() ? 0 :
                        lhs.getLatency() < rhs.getLatency() ? -1 : 1;
            }
        };

        private class MatchServerInfoTask extends ServerInfoTask {
            @Override
            protected void onPostExecute(ServerInfoResponse serverInfoResponse) {
                mResponseCount++;
                if(serverInfoResponse == null) {
                    // TODO handle bad responses
                } else if(serverInfoResponse.getCurrentUsers() == 0 &&
                        serverInfoResponse.getVersion() == se.lublin.humla.Constants.PROTOCOL_VERSION) {
                    mGoodResponses.add(serverInfoResponse);
                }

                // Once we have a good sample of results, shut down the ping threads.
                if(mResponseCount >= mResponsesToSend) {
                    synchronized (mLock) {
                        mLock.notify();
                    }
                    mPingExecutor.shutdownNow();
                }
            }

        }

        private ExecutorService mPingExecutor = Executors.newFixedThreadPool(5); // Run 5 concurrent pings at a time
        private Object mLock = new Object();

        private List<ServerInfoResponse> mGoodResponses = Collections.synchronizedList(new ArrayList<ServerInfoResponse>());
        private volatile int mResponseCount = 0;
        private int mResponsesToSend = SEARCH_RANGE;

        private ProgressDialog mProgressDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgressDialog = ProgressDialog.show(getActivity(), null, getString(R.string.server_match_progress));
            mProgressDialog.setCancelable(true);
            mProgressDialog.setCanceledOnTouchOutside(true);
            mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    cancel(true);
                }
            });
        }

        // TODO? suppress for the executeOnExecutor() below
        @SuppressLint("WrongThread")
        @Override
        protected ServerInfoResponse doInBackground(String... params) {
            final String country = params.length > 0 ? params[0] : null; // If a country is provided, search within country

            Collection<PublicServer> servers;
            if(country != null) {
                servers = new LinkedList<PublicServer>();
                for (PublicServer server : mServers) {
                    if (country.equals(server.getCountryCode())) {
                        servers.add(server);
                    }
                }
            } else {
                servers = mServers;
            }

            // For countries with 0 servers, immediately return null.
            if(servers.size() == 0)
                return null;

            // If there are less servers than the value of our range, deal with it.
            mResponsesToSend = Math.min(SEARCH_RANGE, servers.size());

            Iterator iterator = servers.iterator();
            while(iterator.hasNext() && mGoodResponses.size() < mResponsesToSend) {
                PublicServer server = (PublicServer) iterator.next();
                new MatchServerInfoTask().executeOnExecutor(mPingExecutor, server);
            }
            try {
                synchronized (mLock) {
                    mLock.wait();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            Collections.sort(mGoodResponses, mLatencyComparator);

            if(mGoodResponses.size() > 0)
                return mGoodResponses.get(0);
            else
                return null;
        }

        @Override
        protected void onPostExecute(ServerInfoResponse response) {
            super.onPostExecute(response);
            final PublicServer publicServer = response == null ? null : (PublicServer) response.getServer();
            mProgressDialog.hide();

            AlertDialog.Builder adb = new AlertDialog.Builder(getActivity());
            if(publicServer != null) {
                adb.setTitle(R.string.server_match_found);
                adb.setMessage(getString(R.string.server_match_info,
                        publicServer.getName(),
                        publicServer.getHost(),
                        publicServer.getPort(),
                        response.getCurrentUsers(),
                        response.getMaximumUsers(),
                        response.getVersionString(),
                        publicServer.getCountry(),
                        response.getLatency()));
                adb.setPositiveButton(R.string.connect, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mConnectHandler.connectToPublicServer(publicServer);
                    }
                });
            } else {
                adb.setTitle(R.string.server_match_not_found);
                adb.setMessage(R.string.server_match_expand_country);
                adb.setPositiveButton(R.string.expand, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        MatchServerTask matchTask = new MatchServerTask();
                        matchTask.execute();
                    }
                });
            }
            adb.setNegativeButton(android.R.string.cancel, null);
            adb.show();
        }
    }
}