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 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
|
package tim.prune.function.settings;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.TimeZone;
import java.util.TreeSet;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import tim.prune.App;
import tim.prune.DataSubscriber;
import tim.prune.GenericFunction;
import tim.prune.I18nManager;
import tim.prune.UpdateMessageBroker;
import tim.prune.config.Config;
import tim.prune.gui.CombinedListAndModel;
import tim.prune.gui.GuiGridLayout;
/**
* Class to provide the gui for selecting an alternative timezone
*/
public class SelectTimezoneFunction extends GenericFunction
{
/** Arraylist of timezone infos */
private ArrayList<TimezoneDetails> _zoneInfo;
/** Dialog */
private JDialog _dialog = null;
/** Radio button to select system timezone instead of using listboxes */
private JRadioButton _systemRadio = null;
/** Radio button to select timezone using listboxes */
private JRadioButton _customRadio = null;
/** Array of list boxes */
private CombinedListAndModel[] _listBoxes = null;
/** Label for selected zone */
private JLabel _selectedZoneLabel = null;
/** Label for offset of selected zone */
private JLabel _selectedOffsetLabel = null;
/** OK button for finishing */
private JButton _okButton = null;
private static final int LIST_REGIONS = 0;
private static final int LIST_OFFSETS = 1;
private static final int LIST_GROUPS = 2;
private static final int LIST_NAMES = 3;
/**
* Inner class for listening to list clicks
*/
class ListListener implements ListSelectionListener
{
private int _key = 0;
/** Constructor */
ListListener(int inKey) {_key = inKey;}
/** Listen for selection changes */
public void valueChanged(ListSelectionEvent inEvent) {
if (!inEvent.getValueIsAdjusting()) {
processListClick(_key);
}
}
}
/** Inner class to hold categorisation info for a timezone */
private static class TimezoneDetails
{
public String _id;
public String _region;
public int _offset;
public String _group;
public String _name;
}
/**
* Constructor
* @param inApp App object
*/
public SelectTimezoneFunction(App inApp)
{
super(inApp);
}
/** Get the name key */
public String getNameKey() {
return "function.selecttimezone";
}
/**
* Begin the function
*/
public void begin()
{
if (_dialog == null)
{
_dialog = new JDialog(_parentFrame, getName(), true);
_dialog.setLocationRelativeTo(_parentFrame);
_dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
_dialog.getContentPane().add(makeDialogComponents());
_dialog.pack();
}
collectTimezoneInfo();
_systemRadio.setText(I18nManager.getText("dialog.settimezone.system") + " ("
+ TimeZone.getDefault().getID() + ")");
// Set up dialog according to current config
String selectedTimezone = getConfig().getConfigString(Config.KEY_TIMEZONE_ID);
if (selectedTimezone == null || selectedTimezone.equals(""))
{
_systemRadio.setSelected(true);
}
else
{
_customRadio.setSelected(true);
}
_dialog.setVisible(true);
}
/**
* Create dialog components
* @return Panel containing all gui elements in dialog
*/
private Component makeDialogComponents()
{
JPanel dialogPanel = new JPanel();
dialogPanel.setLayout(new BorderLayout(5, 5));
// Listener for radio buttons
ActionListener radioListener = e -> {
radioSelected(_systemRadio.isSelected());
};
FocusListener radioFocusListener = new FocusAdapter() {
public void focusGained(FocusEvent inEvent) {
radioSelected(_systemRadio.isSelected());
}
};
// Panel at top
JPanel topPanel = new JPanel();
topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.Y_AXIS));
JLabel topLabel = new JLabel(I18nManager.getText("dialog.settimezone.intro"));
topLabel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
topPanel.add(topLabel);
_systemRadio = new JRadioButton(I18nManager.getText("dialog.settimezone.system"));
_systemRadio.addActionListener(radioListener);
_systemRadio.addFocusListener(radioFocusListener);
topPanel.add(_systemRadio);
_customRadio = new JRadioButton(I18nManager.getText("dialog.settimezone.custom"));
_customRadio.addActionListener(radioListener);
_customRadio.addFocusListener(radioFocusListener);
topPanel.add(_customRadio);
ButtonGroup radioGroup = new ButtonGroup();
radioGroup.add(_systemRadio); radioGroup.add(_customRadio);
dialogPanel.add(topPanel, BorderLayout.NORTH);
// Main panel with box layout, list Panel with four lists in a grid
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
JPanel listsPanel = new JPanel();
listsPanel.setLayout(new GridLayout(1, 4));
_listBoxes = new CombinedListAndModel[4];
// First list for regions
_listBoxes[LIST_REGIONS] = new CombinedListAndModel(0);
// Add listener for list selection changes
_listBoxes[LIST_REGIONS].addListSelectionListener(new ListListener(LIST_REGIONS));
JScrollPane scrollPane = new JScrollPane(_listBoxes[LIST_REGIONS]);
scrollPane.setPreferredSize(new Dimension(100, 200));
scrollPane.setMinimumSize(new Dimension(100, 200));
scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
listsPanel.add(scrollPane);
// second list for offsets
_listBoxes[LIST_OFFSETS] = new CombinedListAndModel(1);
_listBoxes[LIST_OFFSETS].setMaxNumEntries(24);
_listBoxes[LIST_OFFSETS].addListSelectionListener(new ListListener(LIST_OFFSETS));
scrollPane = new JScrollPane(_listBoxes[LIST_OFFSETS]);
scrollPane.setPreferredSize(new Dimension(100, 200));
scrollPane.setMinimumSize(new Dimension(100, 200));
scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
listsPanel.add(scrollPane);
// third list for groups
_listBoxes[LIST_GROUPS] = new CombinedListAndModel(2);
_listBoxes[LIST_GROUPS].setMaxNumEntries(20);
_listBoxes[LIST_GROUPS].addListSelectionListener(new ListListener(LIST_GROUPS));
scrollPane = new JScrollPane(_listBoxes[LIST_GROUPS]);
scrollPane.setPreferredSize(new Dimension(100, 200));
scrollPane.setMinimumSize(new Dimension(100, 200));
scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
listsPanel.add(scrollPane);
// fourth list for names
_listBoxes[LIST_NAMES] = new CombinedListAndModel(3);
_listBoxes[LIST_NAMES].setMaxNumEntries(20);
_listBoxes[LIST_NAMES].addListSelectionListener(new ListListener(LIST_NAMES));
scrollPane = new JScrollPane(_listBoxes[LIST_NAMES]);
scrollPane.setPreferredSize(new Dimension(100, 200));
scrollPane.setMinimumSize(new Dimension(100, 200));
scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
listsPanel.add(scrollPane);
mainPanel.add(listsPanel);
// Details labels underneath lists - description and offset
JPanel detailsPanel = new JPanel();
GuiGridLayout grid = new GuiGridLayout(detailsPanel);
grid.add(new JLabel(I18nManager.getText("dialog.settimezone.selectedzone") + " :"));
_selectedZoneLabel = new JLabel("");
grid.add(_selectedZoneLabel);
grid.add(new JLabel(I18nManager.getText("dialog.settimezone.offsetfromutc") + " :"));
_selectedOffsetLabel = new JLabel("");
grid.add(_selectedOffsetLabel);
mainPanel.add(detailsPanel);
dialogPanel.add(mainPanel, BorderLayout.CENTER);
// close window if escape pressed
KeyAdapter escListener = new KeyAdapter() {
public void keyReleased(KeyEvent inE) {
if (inE.getKeyCode() == KeyEvent.VK_ESCAPE) {
_dialog.dispose();
}
}
};
_listBoxes[LIST_REGIONS].addKeyListener(escListener);
_listBoxes[LIST_OFFSETS].addKeyListener(escListener);
// button panel at bottom
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
// OK button
_okButton = new JButton(I18nManager.getText("button.ok"));
_okButton.addActionListener(e -> finishSelectTimezone());
buttonPanel.add(_okButton);
_okButton.addKeyListener(escListener);
// Cancel button
JButton cancelButton = new JButton(I18nManager.getText("button.cancel"));
cancelButton.addActionListener(e -> _dialog.dispose());
cancelButton.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent inE) {
if (inE.getKeyCode() == KeyEvent.VK_ESCAPE) {_dialog.dispose();}
}
});
buttonPanel.add(cancelButton);
dialogPanel.add(buttonPanel, BorderLayout.SOUTH);
return dialogPanel;
}
/**
* React to changes in the radio buttons
* @param inUseSystem true for system, false for custom
*/
private void radioSelected(boolean inUseSystem)
{
for (CombinedListAndModel listBox : _listBoxes)
{
if (inUseSystem) {
listBox.clear();
}
listBox.setEnabled(!inUseSystem);
}
if (!inUseSystem)
{
populateTimezoneRegions();
populateTimezoneOffsets(null);
preselectTimezone(getConfig().getConfigString(Config.KEY_TIMEZONE_ID));
}
showTimezoneDetails();
}
/**
* React to a selection change on one of our lists
* @param inKey key of list which was clicked
*/
private void processListClick(int inKey)
{
final boolean offsetSelected = _listBoxes[LIST_OFFSETS].getSelectedItem() != null;
final boolean groupSelected = _listBoxes[LIST_GROUPS].getSelectedItem() != null;
// Update offsets?
if (inKey == LIST_REGIONS)
{
populateTimezoneOffsets(_listBoxes[LIST_REGIONS].getSelectedItem());
}
// Update groups?
if (inKey == LIST_OFFSETS
|| (inKey == LIST_REGIONS && !offsetSelected))
{
populateTimezoneGroups(_listBoxes[LIST_REGIONS].getSelectedItem(), _listBoxes[LIST_OFFSETS].getSelectedItem());
}
// Update names?
if (inKey == LIST_GROUPS
|| (inKey <= LIST_OFFSETS && !groupSelected))
{
populateTimezoneNames(_listBoxes[LIST_REGIONS].getSelectedItem(), _listBoxes[LIST_OFFSETS].getSelectedItem(),
_listBoxes[LIST_GROUPS].getSelectedItem());
}
// Show the details of the selected timezone
showTimezoneDetails();
}
/**
* Use the system information to populate the list of available timezones
*/
private void collectTimezoneInfo()
{
_zoneInfo = new ArrayList<TimezoneDetails>();
for (String id : TimeZone.getAvailableIDs())
{
String region = getRegion(id);
if (region != null)
{
TimeZone tz = TimeZone.getTimeZone(id);
TimezoneDetails details = new TimezoneDetails();
details._id = id;
details._region = region;
details._offset = tz.getOffset(System.currentTimeMillis()) / 1000 / 60;
details._group = tz.getDisplayName();
details._name = getNameWithoutRegion(id);
_zoneInfo.add(details);
}
}
}
/**
* Populate the timezone regions into the region list
*/
private void populateTimezoneRegions()
{
_listBoxes[LIST_REGIONS].clear();
TreeSet<String> regions = new TreeSet<String>();
for (TimezoneDetails currZone : _zoneInfo)
{
regions.add(currZone._region);
}
for (String region : regions)
{
_listBoxes[LIST_REGIONS].addItem(region);
}
}
/**
* Extract the timezone region from the id
*/
private static String getRegion(String inId)
{
final int slashPos = (inId == null ? -1 : inId.indexOf('/'));
if (slashPos > 0)
{
return inId.substring(0, slashPos);
}
return null;
}
/**
* Populate the second listbox with the offsets for the given region
* @param inRegion selected region, or null if none selected
*/
private void populateTimezoneOffsets(String inRegion)
{
_listBoxes[LIST_OFFSETS].clear();
TreeSet<Integer> offsetsinMinutes = new TreeSet<Integer>();
for (TimezoneDetails currZone : _zoneInfo)
{
String region = currZone._region;
if (inRegion == null || region.equals(inRegion))
{
offsetsinMinutes.add(currZone._offset);
}
}
for (Integer offset : offsetsinMinutes)
{
_listBoxes[LIST_OFFSETS].addItem(makeOffsetString(offset));
}
}
/**
* @return String containing offset for display
*/
private static String makeOffsetString(int inOffsetInMinutes)
{
if (inOffsetInMinutes == 0) return "0";
final boolean isWholeHours = (inOffsetInMinutes % 60) == 0;
if (isWholeHours)
{
return (inOffsetInMinutes > 0 ? "+" : "") + (inOffsetInMinutes / 60);
}
final double numHours = inOffsetInMinutes / 60.0;
return (inOffsetInMinutes > 0 ? "+" : "") + numHours;
}
/**
* Populate the group list using the specified region and offset
* @param inRegion selected region (if any) from the first list
* @param inOffset selected offset (if any) from the second list
*/
private void populateTimezoneGroups(String inRegion, String inOffset)
{
_listBoxes[LIST_GROUPS].clear();
// Convert given offset string (in hours) into numeric offset (in minutes)
final int offsetMins = convertToMinutes(inOffset);
TreeSet<String> zoneGroups = new TreeSet<String>();
for (TimezoneDetails currZone : _zoneInfo)
{
if (inRegion == null || currZone._region.equals(inRegion))
{
if (offsetMins == -1 || offsetMins == currZone._offset)
{
zoneGroups.add(currZone._group);
}
}
}
// If the region and offset were given, then list is unlimited
_listBoxes[LIST_GROUPS].setUnlimited(inRegion != null && inOffset != null);
// Add all the found names to the listbox
for (String group : zoneGroups)
{
_listBoxes[LIST_GROUPS].addItem(group);
}
}
/**
* Populate the group list using the specified region, offset and group
* @param inRegion selected region (if any) from the first list
* @param inOffset selected offset (if any) from the second list
* @param inGroup selected group (if any) from the third list
*/
private void populateTimezoneNames(String inRegion, String inOffset, String inGroup)
{
CombinedListAndModel nameList = _listBoxes[LIST_NAMES];
nameList.clear();
// Convert given offset string (in hours) into numeric offset (in minutes)
final int offsetMins = convertToMinutes(inOffset);
TreeSet<String> zoneNames = new TreeSet<String>();
for (TimezoneDetails currZone : _zoneInfo)
{
if ((inRegion == null || currZone._region.equals(inRegion))
&& (offsetMins == -1 || currZone._offset == offsetMins)
&& (inGroup == null || currZone._group.equals(inGroup)))
{
zoneNames.add(currZone._name);
}
}
// If the region and offset were given, then list is unlimited
nameList.setUnlimited(inRegion != null && inOffset != null);
// Add all the found names to the listbox
for (String name : zoneNames)
{
nameList.addItem(name);
}
}
/**
* Convert the given String from hours to minutes
* @param inOffsetInHours String from listbox in +/- hours
* @return offset in minutes, or -1
*/
private static int convertToMinutes(String inOffsetInHours)
{
try {
return (int) (60 * Double.parseDouble(inOffsetInHours));
}
catch (NumberFormatException | NullPointerException nfe) {
return -1;
}
}
/**
* Remove the timezone region from the id to just leave the name after the slash
*/
private static String getNameWithoutRegion(String inId)
{
final int slashPos = (inId == null ? -1 : inId.indexOf('/'));
if (slashPos > 0) {
return inId.substring(slashPos + 1);
}
return null;
}
/**
* Get the selected timezone, or null if none selected
*/
private TimeZone getSelectedTimezone()
{
if (_systemRadio.isSelected()) {
return TimeZone.getDefault();
}
String chosenRegion = _listBoxes[LIST_REGIONS].getSelectedItem();
// Convert given offset string (in hours) into numeric offset (in minutes)
final int offsetMins = convertToMinutes(_listBoxes[LIST_OFFSETS].getSelectedItem());
String chosenGroup = _listBoxes[LIST_GROUPS].getSelectedItem();
String chosenName = _listBoxes[LIST_NAMES].getSelectedItem();
TreeSet<String> zoneIds = new TreeSet<String>();
for (TimezoneDetails currZone : _zoneInfo)
{
if ((chosenRegion == null || currZone._region.equals(chosenRegion))
&& (offsetMins == -1 || currZone._offset == offsetMins)
&& (chosenGroup == null || currZone._group.equals(chosenGroup))
&& (chosenName == null || currZone._name.equals(chosenName)))
{
zoneIds.add(currZone._id);
if (zoneIds.size() > 1) {
break; // exit loop now, we've got too many
}
}
}
// Should have exactly one result now
if (zoneIds.size() == 1)
{
return TimeZone.getTimeZone(zoneIds.first());
}
// none selected (yet)
return null;
}
/**
* Show the details of the selected timezone
*/
private void showTimezoneDetails()
{
TimeZone selectedTimezone = getSelectedTimezone();
if (selectedTimezone == null)
{
// Clear details labels
_selectedZoneLabel.setText("");
_selectedOffsetLabel.setText("");
}
else
{
// Fill results in labels
String desc = selectedTimezone.getID() + " - " + selectedTimezone.getDisplayName();
_selectedZoneLabel.setText(desc);
String offsets = getOffsetDescription(selectedTimezone);
_selectedOffsetLabel.setText(offsets);
}
_okButton.setEnabled(selectedTimezone != null);
}
/**
* @param inTimezone selected timezone
* @return String describing the time offset(s) of this zone including winter/summer time
*/
private static String getOffsetDescription(TimeZone inTimezone)
{
if (inTimezone == null) {
return "";
}
TreeSet<Integer> offsetsinMinutes = new TreeSet<Integer>();
long testTimeMillis = System.currentTimeMillis();
final long testPeriodInMillis = 1000L * 60 * 60 * 24 * 30 * 2;
for (int i=0; i<5; i++)
{
offsetsinMinutes.add(inTimezone.getOffset(testTimeMillis) / 1000 / 60);
testTimeMillis += testPeriodInMillis;
}
// Make String describing the sorted set
StringBuilder builder = new StringBuilder();
for (Integer offset : offsetsinMinutes)
{
if (builder.length() > 0) {
builder.append(" / ");
}
builder.append(makeOffsetString(offset));
}
return builder.toString();
}
/**
* On entry to the dialog, select the items in each listbox
* according to the given preselected timezone id
* @param zoneId id of zone to select
*/
private void preselectTimezone(String zoneId)
{
TimeZone tz = (zoneId == null ? TimeZone.getDefault() : TimeZone.getTimeZone(zoneId));
if (tz != null)
{
_listBoxes[LIST_REGIONS].selectItem(getRegion(zoneId));
_listBoxes[LIST_OFFSETS].selectItem(makeOffsetString(tz.getOffset(System.currentTimeMillis()) / 1000 / 60));
_listBoxes[LIST_GROUPS].selectItem(tz.getDisplayName());
_listBoxes[LIST_NAMES].selectItem(getNameWithoutRegion(zoneId));
}
}
/**
* Finish the dialog by setting the config according to the selected zone
*/
private void finishSelectTimezone()
{
TimeZone selectedTimezone = getSelectedTimezone();
if (_systemRadio.isSelected() || selectedTimezone == null)
{
// Clear config, use default system timezone instead
getConfig().setConfigString(Config.KEY_TIMEZONE_ID, null);
}
else
{
// Get selected timezone, set in config
getConfig().setConfigString(Config.KEY_TIMEZONE_ID, selectedTimezone.getID());
}
_dialog.dispose();
// Make sure listeners know to update themselves
UpdateMessageBroker.informSubscribers(DataSubscriber.UNITS_CHANGED);
}
}
|