001package jmri.jmrit.roster; 002 003import com.fasterxml.jackson.databind.util.StdDateFormat; 004 005import java.awt.HeadlessException; 006import java.awt.Image; 007import java.io.File; 008import java.io.FileNotFoundException; 009import java.io.IOException; 010import java.io.Writer; 011import java.text.*; 012import java.util.*; 013 014import javax.annotation.CheckForNull; 015import javax.annotation.Nonnull; 016import javax.swing.ImageIcon; 017import javax.swing.JLabel; 018 019import jmri.BasicRosterEntry; 020import jmri.DccLocoAddress; 021import jmri.InstanceManager; 022import jmri.LocoAddress; 023import jmri.beans.ArbitraryBean; 024import jmri.jmrit.roster.rostergroup.RosterGroup; 025import jmri.jmrit.symbolicprog.CvTableModel; 026import jmri.jmrit.symbolicprog.VariableTableModel; 027import jmri.util.FileUtil; 028import jmri.util.StringUtil; 029import jmri.util.davidflanagan.HardcopyWriter; 030import jmri.util.jdom.LocaleSelector; 031import jmri.util.swing.JmriJOptionPane; 032 033import org.jdom2.Attribute; 034import org.jdom2.Element; 035import org.jdom2.JDOMException; 036 037/** 038 * RosterEntry represents a single element in a locomotive roster, including 039 * information on how to locate it from decoder information. 040 * <p> 041 * The RosterEntry is the central place to find information about a locomotive's 042 * configuration, including CV and "programming variable" information. 043 * RosterEntry handles persistence through the LocoFile class. Creating a 044 * RosterEntry does not necessarily read the corresponding file (which might not 045 * even exist), please see readFile(), writeFile() member functions. 046 * <p> 047 * All the data attributes have a content, not null. FileName, however, is 048 * special. A null value for it indicates that no physical file is (yet) 049 * associated with this entry. 050 * <p> 051 * When the filePath attribute is non-null, the user has decided to organize the 052 * roster into directories. 053 * <p> 054 * Each entry can have one or more "Attributes" associated with it. These are 055 * (key, value) pairs. The key has to be unique, and currently both objects have 056 * to be Strings. 057 * <p> 058 * All properties, including the "Attributes", are bound. 059 * 060 * @author Bob Jacobsen Copyright (C) 2001, 2002, 2004, 2005, 2009 061 * @author Dennis Miller Copyright 2004 062 * @author Egbert Broerse Copyright (C) 2018 063 * @author Dave Heap Copyright (C) 2019 064 * @see jmri.jmrit.roster.LocoFile 065 */ 066public class RosterEntry extends ArbitraryBean implements RosterObject, BasicRosterEntry { 067 068 // identifiers for property change events and some XML elements 069 public static final String ID = "id"; // NOI18N 070 public static final String FILENAME = "filename"; // NOI18N 071 public static final String ROADNAME = "roadname"; // NOI18N 072 public static final String MFG = "mfg"; // NOI18N 073 public static final String MODEL = "model"; // NOI18N 074 public static final String OWNER = "owner"; // NOI18N 075 public static final String DCC_ADDRESS = "dccaddress"; // NOI18N 076 public static final String LONG_ADDRESS = "longaddress"; // NOI18N 077 public static final String PROTOCOL = "protocol"; // NOI18N 078 public static final String COMMENT = "comment"; // NOI18N 079 public static final String DECODER_MODEL = "decodermodel"; // NOI18N 080 public static final String DECODER_DEVELOPERID = "developerID"; // NOI18N 081 public static final String DECODER_MANUFACTURERID = "manufacturerID"; // NOI18N 082 public static final String DECODER_PRODUCTID = "productID"; // NOI18N 083 public static final String DECODER_FAMILY = "decoderfamily"; // NOI18N 084 public static final String DECODER_COMMENT = "decodercomment"; // NOI18N 085 public static final String DECODER_MAXFNNUM = "decodermaxFnNum"; // NOI18N 086 public static final String DEFAULT_MAXFNNUM = "28"; // NOI18N 087 public static final String IMAGE_FILE_PATH = "imagefilepath"; // NOI18N 088 public static final String ICON_FILE_PATH = "iconfilepath"; // NOI18N 089 public static final String URL = "url"; // NOI18N 090 public static final String DATE_UPDATED = "dateupdated"; // NOI18N 091 public static final String FUNCTION_IMAGE = "functionImage"; // NOI18N 092 public static final String FUNCTION_LABEL = "functionlabel"; // NOI18N 093 public static final String FUNCTION_LOCKABLE = "functionLockable"; // NOI18N 094 public static final String FUNCTION_SELECTED_IMAGE = "functionSelectedImage"; // NOI18N 095 public static final String ATTRIBUTE_UPDATED = "attributeUpdated:"; // NOI18N 096 public static final String ATTRIBUTE_DELETED = "attributeDeleted"; // NOI18N 097 public static final String MAX_SPEED = "maxSpeed"; // NOI18N 098 public static final String SHUNTING_FUNCTION = "IsShuntingOn"; // NOI18N 099 public static final String SPEED_PROFILE = "speedprofile"; // NOI18N 100 public static final String SOUND_LABEL = "soundlabel"; // NOI18N 101 public static final String ATTRIBUTE_OPERATING_DURATION = "OperatingDuration"; // NOI18N 102 public static final String ATTRIBUTE_LAST_OPERATED = "LastOperated"; // NOI18N 103 104 // members to remember all the info 105 protected String _fileName = null; 106 107 protected String _id = ""; 108 protected String _roadName = ""; 109 protected String _roadNumber = ""; 110 protected String _mfg = ""; 111 protected String _owner = ""; 112 protected String _model = ""; 113 protected String _dccAddress = "3"; 114 protected LocoAddress.Protocol _protocol = LocoAddress.Protocol.DCC_SHORT; 115 protected String _comment = ""; 116 protected String _decoderModel = ""; 117 protected String _decoderFamily = ""; 118 protected String _decoderComment = ""; 119 protected String _maxFnNum = DEFAULT_MAXFNNUM; 120 protected String _dateUpdated = ""; 121 protected Date dateModified = null; 122 protected int _maxSpeedPCT = 100; 123 protected String _developerID = ""; 124 protected String _manufacturerID = ""; 125 protected String _productID = ""; 126 127 /** 128 * Get the highest valid Fn key number for this roster entry. 129 * <dl> 130 * <dt>The default value (28) can be overridden by a "maxFnNum" attribute in 131 * the "model" element of a decoder definition file</dt> 132 * <dd><ul> 133 * <li>A European standard (RCN-212) extends NMRA S9.2.1 up to F68.</li> 134 * <li>ESU LokSound 5 already uses up to F31.</li> 135 * </ul></dd> 136 * </dl> 137 * 138 * @return the highest function number (Fn) supported by this roster entry. 139 * 140 * @see "http://normen.railcommunity.de/RCN-212.pdf" 141 */ 142 public int getMaxFnNumAsInt() { 143 return Integer.parseInt(getMaxFnNum()); 144 } 145 146 protected Map<Integer, String> functionLabels; 147 protected Map<Integer, String> soundLabels; 148 protected Map<Integer, String> functionSelectedImages; 149 protected Map<Integer, String> functionImages; 150 protected Map<Integer, Boolean> functionLockables; 151 protected Map<Integer, Boolean> functionVisibles; 152 protected String _isShuntingOn = ""; 153 154 protected final TreeMap<String, String> attributePairs = new TreeMap<>(); 155 156 protected String _imageFilePath = null; 157 protected String _iconFilePath = null; 158 protected String _URL = ""; 159 160 protected RosterSpeedProfile _sp = null; 161 162 /** 163 * Construct a blank object. 164 */ 165 public RosterEntry() { 166 functionLabels = Collections.synchronizedMap(new HashMap<>()); 167 soundLabels = Collections.synchronizedMap(new HashMap<>()); 168 functionSelectedImages = Collections.synchronizedMap(new HashMap<>()); 169 functionImages = Collections.synchronizedMap(new HashMap<>()); 170 functionLockables = Collections.synchronizedMap(new HashMap<>()); 171 } 172 173 /** 174 * Constructor based on a given file name. 175 * 176 * @param fileName xml file name for the user's Roster entry 177 */ 178 public RosterEntry(String fileName) { 179 this(); 180 _fileName = fileName; 181 } 182 183 /** 184 * Constructor based on a given RosterEntry object and name/ID. 185 * 186 * @param pEntry RosterEntry object 187 * @param pID unique name/ID for the roster entry 188 */ 189 public RosterEntry(RosterEntry pEntry, String pID) { 190 this(); 191 // The ID is different for this element 192 _id = pID; 193 194 // The filename is not set here, rather later 195 _fileName = null; 196 197 // All other items are copied 198 _roadName = pEntry._roadName; 199 _roadNumber = pEntry._roadNumber; 200 _mfg = pEntry._mfg; 201 _model = pEntry._model; 202 _dccAddress = pEntry._dccAddress; 203 _protocol = pEntry._protocol; 204 _comment = pEntry._comment; 205 _decoderModel = pEntry._decoderModel; 206 _decoderFamily = pEntry._decoderFamily; 207 _developerID = pEntry._developerID; 208 _manufacturerID = pEntry._manufacturerID; 209 _productID = pEntry._productID; 210 _decoderComment = pEntry._decoderComment; 211 _owner = pEntry._owner; 212 _imageFilePath = pEntry._imageFilePath; 213 _iconFilePath = pEntry._iconFilePath; 214 _URL = pEntry._URL; 215 _maxSpeedPCT = pEntry._maxSpeedPCT; 216 _isShuntingOn = pEntry._isShuntingOn; 217 218 if (pEntry.functionLabels != null) { 219 pEntry.functionLabels.forEach((key, value) -> { 220 if (value != null) { 221 functionLabels.put(key, value); 222 } 223 }); 224 } 225 if (pEntry.soundLabels != null) { 226 pEntry.soundLabels.forEach((key, value) -> { 227 if (value != null) { 228 soundLabels.put(key, value); 229 } 230 }); 231 } 232 if (pEntry.functionSelectedImages != null) { 233 pEntry.functionSelectedImages.forEach((key, value) -> { 234 if (value != null) { 235 functionSelectedImages.put(key, value); 236 } 237 }); 238 } 239 if (pEntry.functionImages != null) { 240 pEntry.functionImages.forEach((key, value) -> { 241 if (value != null) { 242 functionImages.put(key, value); 243 } 244 }); 245 } 246 if (pEntry.functionLockables != null) { 247 pEntry.functionLockables.forEach((key, value) -> { 248 if (value != null) { 249 functionLockables.put(key, value); 250 } 251 }); 252 } 253 } 254 255 /** 256 * Set the roster ID for this roster entry. 257 * 258 * @param s new ID 259 */ 260 public void setId(String s) { 261 String oldID = _id; 262 _id = s; 263 if (oldID == null || !oldID.equals(s)) { 264 firePropertyChange(RosterEntry.ID, oldID, s); 265 } 266 } 267 268 @Override 269 public String getId() { 270 return _id; 271 } 272 273 /** 274 * Set the file name for this roster entry. 275 * 276 * @param s the new roster entry file name 277 */ 278 public void setFileName(String s) { 279 String oldName = _fileName; 280 _fileName = s; 281 firePropertyChange(RosterEntry.FILENAME, oldName, s); 282 } 283 284 public String getFileName() { 285 return _fileName; 286 } 287 288 public String getPathName() { 289 return Roster.getDefault().getRosterFilesLocation() + _fileName; 290 } 291 292 /** 293 * Ensure the entry has a valid filename. 294 * <p> 295 * If none exists, create one based on the ID string. Does _not_ enforce any 296 * particular naming; you have to check separately for {@literal "<none>"} 297 * or whatever your convention is for indicating an invalid name. Does 298 * replace the space, period, colon, slash and backslash characters so that 299 * the filename will be generally usable. 300 */ 301 public void ensureFilenameExists() { 302 // if there isn't a filename, store using the id 303 if (getFileName() == null || getFileName().isEmpty()) { 304 305 String newFilename = Roster.makeValidFilename(getId()); 306 307 // we don't want to overwrite a file that exists, whether or not 308 // it's in the roster 309 File testFile = new File(Roster.getDefault().getRosterFilesLocation() + newFilename); 310 int count = 0; 311 String oldFilename = newFilename; 312 while (testFile.exists()) { 313 // oops - change filename and try again 314 newFilename = oldFilename.substring(0, oldFilename.length() - 4) + count + ".xml"; 315 count++; 316 log.debug("try to use {} as filename instead of {}", newFilename, oldFilename); 317 testFile = new File(Roster.getDefault().getRosterFilesLocation() + newFilename); 318 } 319 setFileName(newFilename); 320 log.debug("new filename: {}", getFileName()); 321 } 322 } 323 324 public void setRoadName(String s) { 325 String old = _roadName; 326 _roadName = s; 327 firePropertyChange(RosterEntry.ROADNAME, old, s); 328 } 329 330 public String getRoadName() { 331 return _roadName; 332 } 333 334 public void setRoadNumber(String s) { 335 String old = _roadNumber; 336 _roadNumber = s; 337 firePropertyChange(RosterEntry.ROADNAME, old, s); 338 } 339 340 public String getRoadNumber() { 341 return _roadNumber; 342 } 343 344 public void setMfg(String s) { 345 String old = _mfg; 346 _mfg = s; 347 firePropertyChange(RosterEntry.MFG, old, s); 348 } 349 350 public String getMfg() { 351 return _mfg; 352 } 353 354 public void setModel(String s) { 355 String old = _model; 356 _model = s; 357 firePropertyChange(RosterEntry.MODEL, old, s); 358 } 359 360 public String getModel() { 361 return _model; 362 } 363 364 public void setOwner(String s) { 365 String old = _owner; 366 _owner = s; 367 firePropertyChange(RosterEntry.OWNER, old, s); 368 } 369 370 public String getOwner() { 371 if (_owner.isEmpty()) { 372 RosterConfigManager manager = InstanceManager.getNullableDefault(RosterConfigManager.class); 373 if (manager != null) { 374 _owner = manager.getDefaultOwner(); 375 } 376 } 377 return _owner; 378 } 379 380 public void setDccAddress(String s) { 381 String old = _dccAddress; 382 _dccAddress = s; 383 firePropertyChange(RosterEntry.DCC_ADDRESS, old, s); 384 } 385 386 @Override 387 public String getDccAddress() { 388 return _dccAddress; 389 } 390 391 public void setLongAddress(boolean b) { 392 boolean old = false; 393 if (_protocol == LocoAddress.Protocol.DCC_LONG) { 394 old = true; 395 } 396 if (b) { 397 _protocol = LocoAddress.Protocol.DCC_LONG; 398 } else { 399 _protocol = LocoAddress.Protocol.DCC_SHORT; 400 } 401 firePropertyChange(RosterEntry.LONG_ADDRESS, old, b); 402 } 403 404 public RosterSpeedProfile getSpeedProfile() { 405 return _sp; 406 } 407 408 public void setSpeedProfile(RosterSpeedProfile sp) { 409 if (sp.getRosterEntry() != this) { 410 log.error("Attempting to set a speed profile against the wrong roster entry"); 411 return; 412 } 413 RosterSpeedProfile old = this._sp; 414 _sp = sp; 415 this.firePropertyChange(RosterEntry.SPEED_PROFILE, old, this._sp); 416 } 417 418 @Override 419 public boolean isLongAddress() { 420 return _protocol == LocoAddress.Protocol.DCC_LONG; 421 } 422 423 public void setProtocol(LocoAddress.Protocol protocol) { 424 LocoAddress.Protocol old = _protocol; 425 _protocol = protocol; 426 firePropertyChange(RosterEntry.PROTOCOL, old, _protocol); 427 } 428 429 public LocoAddress.Protocol getProtocol() { 430 return _protocol; 431 } 432 433 public String getProtocolAsString() { 434 return _protocol.getPeopleName(); 435 } 436 437 public void setComment(String s) { 438 String old = _comment; 439 _comment = s; 440 firePropertyChange(RosterEntry.COMMENT, old, s); 441 } 442 443 public String getComment() { 444 return _comment; 445 } 446 447 public void setDecoderModel(String s) { 448 String old = _decoderModel; 449 _decoderModel = s; 450 firePropertyChange(RosterEntry.DECODER_MODEL, old, s); 451 } 452 453 public String getDecoderModel() { 454 return _decoderModel; 455 } 456 457 public void setDeveloperID(String s) { 458 String old = _developerID; 459 _developerID = s; 460 firePropertyChange(DECODER_DEVELOPERID, old, s); 461 } 462 463 public String getDeveloperID() { 464 return _developerID; 465 } 466 467 public void setManufacturerID(String s) { 468 String old = _manufacturerID; 469 _manufacturerID = s; 470 firePropertyChange(DECODER_MANUFACTURERID, old, s); 471 } 472 473 public String getManufacturerID() { 474 return _manufacturerID; 475 } 476 477 public void setProductID(String s) { 478 String old = _productID; 479 if (s == null) {s="";} 480 _productID = s; 481 firePropertyChange(DECODER_PRODUCTID, old, s); 482 } 483 484 public String getProductID() { 485 return _productID; 486 } 487 488 public void setDecoderFamily(String s) { 489 String old = _decoderFamily; 490 _decoderFamily = s; 491 firePropertyChange(RosterEntry.DECODER_FAMILY, old, s); 492 } 493 494 public String getDecoderFamily() { 495 return _decoderFamily; 496 } 497 498 public void setDecoderComment(String s) { 499 String old = _decoderComment; 500 _decoderComment = s; 501 firePropertyChange(RosterEntry.DECODER_COMMENT, old, s); 502 } 503 504 public String getDecoderComment() { 505 return _decoderComment; 506 } 507 508 public void setMaxFnNum(String s) { 509 String old = _maxFnNum; 510 _maxFnNum = s; 511 firePropertyChange(RosterEntry.DECODER_MAXFNNUM, old, s); 512 } 513 514 public String getMaxFnNum() { 515 return _maxFnNum; 516 } 517 518 @Override 519 public DccLocoAddress getDccLocoAddress() { 520 int n; 521 try { 522 n = Integer.parseInt(getDccAddress()); 523 } catch (NumberFormatException e) { 524 log.error("Illegal format for DCC address roster entry: \"{}\" value: \"{}\"", getId(), getDccAddress()); 525 n = 0; 526 } 527 return new DccLocoAddress(n, _protocol); 528 } 529 530 public void setImagePath(String s) { 531 String old = _imageFilePath; 532 _imageFilePath = s; 533 firePropertyChange(RosterEntry.IMAGE_FILE_PATH, old, s); 534 } 535 536 public String getImagePath() { 537 return _imageFilePath; 538 } 539 540 public void setIconPath(String s) { 541 String old = _iconFilePath; 542 _iconFilePath = s; 543 firePropertyChange(RosterEntry.ICON_FILE_PATH, old, s); 544 } 545 546 public String getIconPath() { 547 return _iconFilePath; 548 } 549 550 public void setShuntingFunction(String fn) { 551 String old = this._isShuntingOn; 552 _isShuntingOn = fn; 553 this.firePropertyChange(RosterEntry.SHUNTING_FUNCTION, old, this._isShuntingOn); 554 } 555 556 @Override 557 public String getShuntingFunction() { 558 return _isShuntingOn; 559 } 560 561 public void setURL(String s) { 562 String old = _URL; 563 _URL = s; 564 firePropertyChange(RosterEntry.URL, old, s); 565 } 566 567 public String getURL() { 568 return _URL; 569 } 570 571 public void setDateModified(@Nonnull Date date) { 572 Date old = this.dateModified; 573 this.dateModified = date; 574 this.firePropertyChange(RosterEntry.DATE_UPDATED, old, date); 575 } 576 577 /** 578 * Set the date modified given a string representing a date. 579 * <p> 580 * Tries ISO 8601 and the current Java defaults as formats for parsing a 581 * date. 582 * 583 * @param date the string to parse into a date 584 * @throws ParseException if the date cannot be parsed 585 */ 586 public void setDateModified(@Nonnull String date) throws ParseException { 587 try { 588 // parse using ISO 8601 date format(s) 589 setDateModified(new StdDateFormat().parse(date)); 590 } catch (ParseException ex) { 591 log.debug("ParseException in setDateModified ISO attempt: \"{}\"", date); 592 // next, try parse using defaults since thats how it was saved if saved 593 // by earlier versions of JMRI 594 try { 595 setDateModified(DateFormat.getDateTimeInstance().parse(date)); 596 } catch (ParseException ex2) { 597 // then try with a specific format to handle e.g. "Apr 1, 2016 9:13:36 AM" 598 DateFormat customFmt = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a"); 599 try { 600 setDateModified(customFmt.parse(date)); 601 } catch (ParseException ex3) { 602 // then try with a specific format to handle e.g. "01-Oct-2016 9:13:36" 603 customFmt = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss"); 604 setDateModified(customFmt.parse(date)); 605 } 606 } 607 } catch (IllegalArgumentException ex2) { 608 // warn that there's perhaps something wrong with the classpath 609 log.error( 610 "IllegalArgumentException in RosterEntry.setDateModified - this may indicate a problem with the classpath, specifically multiple copies of the 'jackson` library. See release notes"); 611 // parse using defaults since thats how it was saved if saved 612 // by earlier versions of JMRI 613 this.setDateModified(DateFormat.getDateTimeInstance().parse(date)); 614 } 615 } 616 617 @CheckForNull 618 public Date getDateModified() { 619 return this.dateModified; 620 } 621 622 /** 623 * Set the date last updated. 624 * 625 * @param s the string to parse into a date 626 */ 627 protected void setDateUpdated(String s) { 628 String old = _dateUpdated; 629 _dateUpdated = s; 630 try { 631 this.setDateModified(s); 632 } catch (ParseException ex) { 633 log.warn("Unable to parse \"{}\" as a date in roster entry \"{}\".", s, getId()); 634 // property change is fired by setDateModified if s parses as a date 635 firePropertyChange(RosterEntry.DATE_UPDATED, old, s); 636 } 637 } 638 639 /** 640 * Get the date this entry was last modified. Returns the value of 641 * {@link #getDateModified()} in ISO 8601 format if that is not null, 642 * otherwise returns the raw value for the last modified date from the XML 643 * file for the roster entry. 644 * <p> 645 * Use getDateModified() if control over formatting is required 646 * 647 * @return the string representation of the date last modified 648 */ 649 public String getDateUpdated() { 650 Date date = this.getDateModified(); 651 if (date == null) { 652 return _dateUpdated; 653 } else { 654 return new StdDateFormat().format(date); 655 } 656 } 657 658 //openCounter is used purely to indicate if the roster entry has been opened in an editing mode. 659 int openCounter = 0; 660 661 @Override 662 public void setOpen(boolean boo) { 663 if (boo) { 664 openCounter++; 665 } else { 666 openCounter--; 667 } 668 if (openCounter < 0) { 669 openCounter = 0; 670 } 671 } 672 673 @Override 674 public boolean isOpen() { 675 return openCounter != 0; 676 } 677 678 /** 679 * Construct this Entry from XML. 680 * <p> 681 * This member has to remain synchronized with the detailed schema in 682 * xml/schema/locomotive-config.xsd. 683 * 684 * @param e Locomotive XML element 685 */ 686 public RosterEntry(Element e) { 687 functionLabels = Collections.synchronizedMap(new HashMap<>()); 688 soundLabels = Collections.synchronizedMap(new HashMap<>()); 689 functionSelectedImages = Collections.synchronizedMap(new HashMap<>()); 690 functionImages = Collections.synchronizedMap(new HashMap<>()); 691 functionLockables = Collections.synchronizedMap(new HashMap<>()); 692 if (log.isDebugEnabled()) { 693 log.debug("ctor from element {}", e); 694 } 695 Attribute a; 696 if ((a = e.getAttribute("id")) != null) { 697 _id = a.getValue(); 698 } else { 699 log.warn("no id attribute in locomotive element when reading roster"); 700 } 701 if ((a = e.getAttribute("fileName")) != null) { 702 _fileName = a.getValue(); 703 } 704 if ((a = e.getAttribute("roadName")) != null) { 705 _roadName = a.getValue(); 706 } 707 if ((a = e.getAttribute("roadNumber")) != null) { 708 _roadNumber = a.getValue(); 709 } 710 if ((a = e.getAttribute("owner")) != null) { 711 _owner = a.getValue(); 712 } 713 if ((a = e.getAttribute("mfg")) != null) { 714 _mfg = a.getValue(); 715 } 716 if ((a = e.getAttribute("model")) != null) { 717 _model = a.getValue(); 718 } 719 if ((a = e.getAttribute("dccAddress")) != null) { 720 _dccAddress = a.getValue(); 721 } 722 723 // file path was saved without default xml config path 724 if ((a = e.getAttribute("imageFilePath")) != null && !a.getValue().isEmpty()) { 725 try { 726 if (FileUtil.getFile(a.getValue()).isFile()) { 727 _imageFilePath = FileUtil.getAbsoluteFilename(a.getValue()); 728 } 729 } catch (FileNotFoundException ex) { 730 try { 731 if (FileUtil.getFile(FileUtil.getUserResourcePath() + a.getValue()).isFile()) { 732 _imageFilePath = FileUtil.getUserResourcePath() + a.getValue(); 733 } 734 } catch (FileNotFoundException ex1) { 735 _imageFilePath = null; 736 } 737 } 738 } 739 if ((a = e.getAttribute("iconFilePath")) != null && !a.getValue().isEmpty()) { 740 try { 741 if (FileUtil.getFile(a.getValue()).isFile()) { 742 _iconFilePath = FileUtil.getAbsoluteFilename(a.getValue()); 743 } 744 } catch (FileNotFoundException ex) { 745 try { 746 if (FileUtil.getFile(FileUtil.getUserResourcePath() + a.getValue()).isFile()) { 747 _iconFilePath = FileUtil.getUserResourcePath() + a.getValue(); 748 } 749 } catch (FileNotFoundException ex1) { 750 _iconFilePath = null; 751 } 752 } 753 } 754 if ((a = e.getAttribute("URL")) != null) { 755 _URL = a.getValue(); 756 } 757 if ((a = e.getAttribute(RosterEntry.SHUNTING_FUNCTION)) != null) { 758 _isShuntingOn = a.getValue(); 759 } 760 if ((a = e.getAttribute(RosterEntry.MAX_SPEED)) != null) { 761 _maxSpeedPCT = Integer.parseInt(a.getValue()); 762 } 763 764 if ((a = e.getAttribute(DECODER_DEVELOPERID)) != null) { 765 _developerID = a.getValue(); 766 } 767 768 if ((a = e.getAttribute(DECODER_MANUFACTURERID)) != null) { 769 _manufacturerID = a.getValue(); 770 } 771 772 if ((a = e.getAttribute(DECODER_PRODUCTID)) != null) { 773 _productID = a.getValue(); 774 } 775 776 Element e3; 777 if ((e3 = e.getChild("dateUpdated")) != null) { 778 this.setDateUpdated(e3.getText()); 779 } 780 if ((e3 = e.getChild("locoaddress")) != null) { 781 DccLocoAddress la = (DccLocoAddress) ((new jmri.configurexml.LocoAddressXml()).getAddress(e3)); 782 if (la != null) { 783 _dccAddress = "" + la.getNumber(); 784 _protocol = la.getProtocol(); 785 } else { 786 _dccAddress = ""; 787 _protocol = LocoAddress.Protocol.DCC_SHORT; 788 } 789 } else {// Did not find "locoaddress" element carrying the short/long, probably 790 // because this is an older-format file, so try to use system default. 791 // This is generally the best we can do without parsing the decoder file now 792 // but may give the wrong answer in some cases (low value long addresses on NCE) 793 794 jmri.ThrottleManager tf = jmri.InstanceManager.getNullableDefault(jmri.ThrottleManager.class); 795 int address; 796 try { 797 address = Integer.parseInt(_dccAddress); 798 } catch (NumberFormatException e2) { 799 address = 3; 800 } // ignore, accepting the default value 801 if (tf != null && tf.canBeLongAddress(address) && !tf.canBeShortAddress(address)) { 802 // if it has to be long, handle that 803 _protocol = LocoAddress.Protocol.DCC_LONG; 804 } else if (tf != null && !tf.canBeLongAddress(address) && tf.canBeShortAddress(address)) { 805 // if it has to be short, handle that 806 _protocol = LocoAddress.Protocol.DCC_SHORT; 807 } else { 808 // else guess short address 809 // These people should resave their roster, so we'll warn them 810 warnShortLong(_id); 811 _protocol = LocoAddress.Protocol.DCC_SHORT; 812 813 } 814 } 815 if ((a = e.getAttribute("comment")) != null) { 816 _comment = a.getValue(); 817 } 818 Element d = e.getChild("decoder"); 819 if (d != null) { 820 if ((a = d.getAttribute("model")) != null) { 821 _decoderModel = a.getValue(); 822 } 823 if ((a = d.getAttribute("family")) != null) { 824 _decoderFamily = a.getValue(); 825 } 826 if ((a = d.getAttribute(DECODER_DEVELOPERID)) != null) { 827 _developerID = a.getValue(); 828 } 829 if ((a = d.getAttribute(DECODER_MANUFACTURERID)) != null) { 830 _manufacturerID = a.getValue(); 831 } 832 if ((a = d.getAttribute(DECODER_PRODUCTID)) != null) { 833 _productID = a.getValue(); 834 } 835 if ((a = d.getAttribute("comment")) != null) { 836 _decoderComment = a.getValue(); 837 } 838 if ((a = d.getAttribute("maxFnNum")) != null) { 839 _maxFnNum = a.getValue(); 840 } 841 } 842 843 loadFunctions(e.getChild("functionlabels"), "RosterEntry"); 844 loadSounds(e.getChild("soundlabels"), "RosterEntry"); 845 loadAttributes(e.getChild("attributepairs")); 846 847 if (e.getChild(RosterEntry.SPEED_PROFILE) != null) { 848 _sp = new RosterSpeedProfile(this); 849 _sp.load(e.getChild(RosterEntry.SPEED_PROFILE)); 850 } 851 852 } 853 854 boolean loadedOnce = false; 855 856 /** 857 * Load function names from a JDOM element. 858 * <p> 859 * Does not change values that are already present! 860 * 861 * @param e3 the XML element containing functions 862 */ 863 public void loadFunctions(Element e3) { 864 this.loadFunctions(e3, "family"); 865 } 866 867 /** 868 * Loads function names from a JDOM element. Does not change values that are 869 * already present! 870 * 871 * @param e3 the XML element containing the functions 872 * @param source "family" if source is the decoder definition, or "model" if 873 * source is the roster entry itself 874 */ 875 public void loadFunctions(Element e3, String source) { 876 /* 877 * Load flag once, means that when the roster entry is edited only the 878 * first set of function labels are displayed ie those saved in the 879 * roster file, rather than those being left blank rather than being 880 * over-written by the defaults linked to the decoder def 881 */ 882 if (loadedOnce) { 883 return; 884 } 885 if (e3 != null) { 886 // load function names 887 List<Element> l = e3.getChildren(RosterEntry.FUNCTION_LABEL); 888 for (Element fn : l) { 889 int num = Integer.parseInt(fn.getAttribute("num").getValue()); 890 String lock = fn.getAttribute("lockable").getValue(); 891 String val = LocaleSelector.getAttribute(fn, "text"); 892 if (val == null) { 893 val = fn.getText(); 894 } 895 if ((this.getFunctionLabel(num) == null) || (source.equalsIgnoreCase("model"))) { 896 this.setFunctionLabel(num, val); 897 this.setFunctionLockable(num, lock.equals("true")); 898 Attribute a; 899 if ((a = fn.getAttribute("functionImage")) != null && !a.getValue().isEmpty()) { 900 try { 901 if (FileUtil.getFile(a.getValue()).isFile()) { 902 this.setFunctionImage(num, FileUtil.getAbsoluteFilename(a.getValue())); 903 } 904 } catch (FileNotFoundException ex) { 905 try { 906 if (FileUtil.getFile(FileUtil.getUserResourcePath() + a.getValue()).isFile()) { 907 this.setFunctionImage(num, FileUtil.getUserResourcePath() + a.getValue()); 908 } 909 } catch (FileNotFoundException ex1) { 910 this.setFunctionImage(num, null); 911 } 912 } 913 } 914 if ((a = fn.getAttribute("functionImageSelected")) != null && !a.getValue().isEmpty()) { 915 try { 916 if (FileUtil.getFile(a.getValue()).isFile()) { 917 this.setFunctionSelectedImage(num, FileUtil.getAbsoluteFilename(a.getValue())); 918 } 919 } catch (FileNotFoundException ex) { 920 try { 921 if (FileUtil.getFile(FileUtil.getUserResourcePath() + a.getValue()).isFile()) { 922 this.setFunctionSelectedImage(num, FileUtil.getUserResourcePath() + a.getValue()); 923 } 924 } catch (FileNotFoundException ex1) { 925 this.setFunctionSelectedImage(num, null); 926 } 927 } 928 } 929 } 930 } 931 } 932 if (source.equalsIgnoreCase("RosterEntry")) { 933 loadedOnce = true; 934 } 935 } 936 937 boolean soundLoadedOnce = false; 938 939 /** 940 * Loads sound names from a JDOM element. Does not change values that are 941 * already present! 942 * 943 * @param e3 the XML element containing sound names 944 * @param source "family" if source is the decoder definition, or "model" if 945 * source is the roster entry itself 946 */ 947 public void loadSounds(Element e3, String source) { 948 /* 949 * Load flag once, means that when the roster entry is edited only the 950 * first set of sound labels are displayed ie those saved in the roster 951 * file, rather than those being left blank rather than being 952 * over-written by the defaults linked to the decoder def 953 */ 954 if (soundLoadedOnce) { 955 return; 956 } 957 if (e3 != null) { 958 // load sound names 959 List<Element> l = e3.getChildren(RosterEntry.SOUND_LABEL); 960 for (Element fn : l) { 961 int num = Integer.parseInt(fn.getAttribute("num").getValue()); 962 String val = LocaleSelector.getAttribute(fn, "text"); 963 if (val == null) { 964 val = fn.getText(); 965 } 966 if ((this.getSoundLabel(num) == null) || (source.equalsIgnoreCase("model"))) { 967 this.setSoundLabel(num, val); 968 } 969 } 970 } 971 if (source.equalsIgnoreCase("RosterEntry")) { 972 soundLoadedOnce = true; 973 } 974 } 975 976 /** 977 * Load attribute key/value pairs from a JDOM element. 978 * 979 * @param e3 XML element containing roster entry attributes 980 */ 981 public void loadAttributes(Element e3) { 982 if (e3 != null) { 983 List<Element> l = e3.getChildren("keyvaluepair"); 984 for (Element fn : l) { 985 String key = fn.getChild("key").getText(); 986 String value = fn.getChild("value").getText(); 987 this.putAttribute(key, value); 988 } 989 } 990 } 991 992 /** 993 * Set the label for a specific function. 994 * 995 * @param fn function number, starting with 0 996 * @param label the label to use 997 */ 998 public void setFunctionLabel(int fn, String label) { 999 if (functionLabels == null) { 1000 functionLabels = Collections.synchronizedMap(new HashMap<>()); 1001 } 1002 String old = functionLabels.get(fn); 1003 functionLabels.put(fn, label); 1004 this.firePropertyChange(RosterEntry.FUNCTION_LABEL + fn, old, label); 1005 } 1006 1007 /** 1008 * If a label has been defined for a specific function, return it, otherwise 1009 * return null. 1010 * 1011 * @param fn function number, starting with 0 1012 * @return function label or null if not defined 1013 */ 1014 public String getFunctionLabel(int fn) { 1015 if (functionLabels == null) { 1016 return null; 1017 } 1018 return functionLabels.get(fn); 1019 } 1020 1021 /** 1022 * Define label for a specific sound. 1023 * 1024 * @param fn sound number, starting with 0 1025 * @param label display label for the sound function 1026 */ 1027 public void setSoundLabel(int fn, String label) { 1028 if (soundLabels == null) { 1029 soundLabels = Collections.synchronizedMap(new HashMap<>()); 1030 } 1031 String old = soundLabels.get(fn); 1032 soundLabels.put(fn, label); 1033 this.firePropertyChange(RosterEntry.SOUND_LABEL + fn, old, label); 1034 } 1035 1036 /** 1037 * If a label has been defined for a specific sound, return it, otherwise 1038 * return null. 1039 * 1040 * @param fn sound number, starting with 0 1041 * @return sound label or null 1042 */ 1043 public String getSoundLabel(int fn) { 1044 if (soundLabels == null) { 1045 return null; 1046 } 1047 return soundLabels.get(fn); 1048 } 1049 1050 public void setFunctionImage(int fn, String s) { 1051 if (functionImages == null) { 1052 functionImages = Collections.synchronizedMap(new HashMap<>()); 1053 } 1054 String old = functionImages.get(fn); 1055 functionImages.put(fn, s); 1056 firePropertyChange(RosterEntry.FUNCTION_IMAGE + fn, old, s); 1057 } 1058 1059 public String getFunctionImage(int fn) { 1060 if (functionImages == null) { 1061 return null; 1062 } 1063 return functionImages.get(fn); 1064 } 1065 1066 public void setFunctionSelectedImage(int fn, String s) { 1067 if (functionSelectedImages == null) { 1068 functionSelectedImages = Collections.synchronizedMap(new HashMap<>()); 1069 } 1070 String old = functionSelectedImages.get(fn); 1071 functionSelectedImages.put(fn, s); 1072 firePropertyChange(RosterEntry.FUNCTION_SELECTED_IMAGE + fn, old, s); 1073 } 1074 1075 public String getFunctionSelectedImage(int fn) { 1076 if (functionSelectedImages == null) { 1077 return null; 1078 } 1079 return functionSelectedImages.get(fn); 1080 } 1081 1082 /** 1083 * Define whether a specific function is lockable. 1084 * 1085 * @param fn function number, starting with 0 1086 * @param lockable true if function is continuous; false if momentary 1087 */ 1088 public void setFunctionLockable(int fn, boolean lockable) { 1089 if (functionLockables == null) { 1090 functionLockables = Collections.synchronizedMap(new HashMap<>()); 1091 functionLockables.put(fn, true); 1092 } 1093 boolean old = ((functionLockables.get(fn) != null) ? functionLockables.get(fn) : true); 1094 functionLockables.put(fn, lockable); 1095 this.firePropertyChange(RosterEntry.FUNCTION_LOCKABLE + fn, old, lockable); 1096 } 1097 1098 /** 1099 * Return the lockable/latchable state of a specific function. Defaults to true. 1100 * 1101 * @param fn function number, starting with 0 1102 * @return true if function is lockable/latchable 1103 */ 1104 public boolean getFunctionLockable(int fn) { 1105 if (functionLockables == null) { 1106 return true; 1107 } 1108 return ((functionLockables.get(fn) != null) ? functionLockables.get(fn) : true); 1109 } 1110 1111 /** 1112 * Define whether a specific function button is visible. 1113 * 1114 * @param fn function number, starting with 0 1115 * @param visible true if function button is visible; false to hide 1116 */ 1117 public void setFunctionVisible(int fn, boolean visible) { 1118 if (functionVisibles == null) { 1119 functionVisibles = Collections.synchronizedMap(new HashMap<>()); 1120 functionVisibles.put(fn, true); 1121 } 1122 boolean old = ((functionVisibles.get(fn) != null) ? functionVisibles.get(fn) : true); 1123 functionVisibles.put(fn, visible); 1124 this.firePropertyChange(RosterEntry.FUNCTION_LOCKABLE + fn, old, visible); 1125 } 1126 1127 /** 1128 * Return the UI visibility of a specific function button. Defaults to true. 1129 * 1130 * @param fn function number, starting with 0 1131 * @return true if function button is visible 1132 */ 1133 public boolean getFunctionVisible(int fn) { 1134 if (functionVisibles == null) { 1135 return true; 1136 } 1137 return ((functionVisibles.get(fn) != null) ? functionVisibles.get(fn) : true); 1138 } 1139 1140 @Override 1141 public void putAttribute(String key, String value) { 1142 String oldValue = getAttribute(key); 1143 attributePairs.put(key, value); 1144 firePropertyChange(RosterEntry.ATTRIBUTE_UPDATED + key, oldValue, value); 1145 } 1146 1147 @Override 1148 public String getAttribute(String key) { 1149 return attributePairs.get(key); 1150 } 1151 1152 @Override 1153 public void deleteAttribute(String key) { 1154 if (attributePairs.containsKey(key)) { 1155 attributePairs.remove(key); 1156 firePropertyChange(RosterEntry.ATTRIBUTE_DELETED, key, null); 1157 } 1158 } 1159 1160 /** 1161 * Provide access to the set of attributes. 1162 * <p> 1163 * This is directly backed access, so e.g. removing an item from this Set 1164 * removes it from the RosterEntry too. 1165 * 1166 * @return a set of attribute keys 1167 */ 1168 public java.util.Set<String> getAttributes() { 1169 return attributePairs.keySet(); 1170 } 1171 1172 @Override 1173 public String[] getAttributeList() { 1174 return attributePairs.keySet().toArray(new String[attributePairs.size()]); 1175 } 1176 1177 /** 1178 * List the roster groups this entry is a member of, returning existing 1179 * {@link jmri.jmrit.roster.rostergroup.RosterGroup}s from the default 1180 * {@link jmri.jmrit.roster.Roster} if they exist. 1181 * 1182 * @return list of roster groups 1183 */ 1184 public List<RosterGroup> getGroups() { 1185 return this.getGroups(Roster.getDefault()); 1186 } 1187 1188 /** 1189 * List the roster groups this entry is a member of, returning existing 1190 * {@link jmri.jmrit.roster.rostergroup.RosterGroup}s from the specified 1191 * {@link jmri.jmrit.roster.Roster} if they exist. 1192 * 1193 * @param roster the roster to get matching groups from 1194 * @return list of roster groups 1195 */ 1196 public List<RosterGroup> getGroups(Roster roster) { 1197 List<RosterGroup> groups = new ArrayList<>(); 1198 if (!this.getAttributes().isEmpty()) { 1199 for (String attribute : this.getAttributes()) { 1200 if (attribute.startsWith(Roster.ROSTER_GROUP_PREFIX)) { 1201 String name = attribute.substring(Roster.ROSTER_GROUP_PREFIX.length()); 1202 if (roster.getRosterGroups().containsKey(name)) { 1203 groups.add(roster.getRosterGroups().get(name)); 1204 } else { 1205 groups.add(new RosterGroup(name)); 1206 } 1207 } 1208 } 1209 } 1210 return groups; 1211 } 1212 1213 @Override 1214 public int getMaxSpeedPCT() { 1215 return _maxSpeedPCT; 1216 } 1217 1218 public void setMaxSpeedPCT(int maxSpeedPCT) { 1219 int old = this._maxSpeedPCT; 1220 _maxSpeedPCT = maxSpeedPCT; 1221 this.firePropertyChange(RosterEntry.MAX_SPEED, old, this._maxSpeedPCT); 1222 } 1223 1224 /** 1225 * Warn user that the roster entry needs to be resaved. 1226 * 1227 * @param id roster ID to warn about 1228 */ 1229 protected void warnShortLong(String id) { 1230 log.warn("Roster entry \"{}\" should be saved again to store the short/long address value", id); 1231 } 1232 1233 /** 1234 * Create an XML element to represent this Entry. 1235 * <p> 1236 * This member has to remain synchronized with the detailed schema in 1237 * xml/schema/locomotive-config.xsd. 1238 * 1239 * @return Contents in a JDOM Element 1240 */ 1241 @Override 1242 public Element store() { 1243 Element e = new Element("locomotive"); 1244 e.setAttribute("id", getId()); 1245 e.setAttribute("fileName", getFileName()); 1246 e.setAttribute("roadNumber", getRoadNumber()); 1247 e.setAttribute("roadName", getRoadName()); 1248 e.setAttribute("mfg", getMfg()); 1249 e.setAttribute("owner", getOwner()); 1250 e.setAttribute("model", getModel()); 1251 e.setAttribute("dccAddress", getDccAddress()); 1252 //e.setAttribute("protocol", "" + getProtocol()); 1253 e.setAttribute("comment", getComment()); 1254 e.setAttribute(DECODER_DEVELOPERID, getDeveloperID()); 1255 e.setAttribute(DECODER_MANUFACTURERID, getManufacturerID()); 1256 e.setAttribute(DECODER_PRODUCTID, getProductID()); 1257 e.setAttribute(RosterEntry.MAX_SPEED, (Integer.toString(getMaxSpeedPCT()))); 1258 // file path are saved without default xml config path 1259 e.setAttribute("imageFilePath", 1260 (this.getImagePath() != null) ? FileUtil.getPortableFilename(this.getImagePath()) : ""); 1261 e.setAttribute("iconFilePath", 1262 (this.getIconPath() != null) ? FileUtil.getPortableFilename(this.getIconPath()) : ""); 1263 e.setAttribute("URL", getURL()); 1264 e.setAttribute(RosterEntry.SHUNTING_FUNCTION, getShuntingFunction()); 1265 if (_dateUpdated.isEmpty()) { 1266 // set date updated to now if never set previously 1267 this.changeDateUpdated(); 1268 } 1269 e.addContent(new Element("dateUpdated").addContent(this.getDateUpdated())); 1270 Element d = new Element("decoder"); 1271 d.setAttribute("model", getDecoderModel()); 1272 d.setAttribute("family", getDecoderFamily()); 1273 d.setAttribute("comment", getDecoderComment()); 1274 d.setAttribute("maxFnNum", getMaxFnNum()); 1275 1276 e.addContent(d); 1277 if (_dccAddress.isEmpty()) { 1278 e.addContent((new jmri.configurexml.LocoAddressXml()).store(null)); // store a null address 1279 } else { 1280 e.addContent((new jmri.configurexml.LocoAddressXml()) 1281 .store(new DccLocoAddress(Integer.parseInt(_dccAddress), _protocol))); 1282 } 1283 1284 if (functionLabels != null) { 1285 Element s = new Element("functionlabels"); 1286 1287 // loop to copy non-null elements 1288 functionLabels.forEach((key, value) -> { 1289 if (value != null && !value.isEmpty()) { 1290 Element fne = new Element(RosterEntry.FUNCTION_LABEL); 1291 fne.setAttribute("num", "" + key); 1292 fne.setAttribute("lockable", getFunctionLockable(key) ? "true" : "false"); 1293 fne.setAttribute("functionImage", 1294 (getFunctionImage(key) != null) ? FileUtil.getPortableFilename(getFunctionImage(key)) : ""); 1295 fne.setAttribute("functionImageSelected", (getFunctionSelectedImage(key) != null) 1296 ? FileUtil.getPortableFilename(getFunctionSelectedImage(key)) : ""); 1297 fne.addContent(value); 1298 s.addContent(fne); 1299 } 1300 }); 1301 e.addContent(s); 1302 } 1303 1304 if (soundLabels != null) { 1305 Element s = new Element("soundlabels"); 1306 1307 // loop to copy non-null elements 1308 soundLabels.forEach((key, value) -> { 1309 if (value != null && !value.isEmpty()) { 1310 Element fne = new Element(RosterEntry.SOUND_LABEL); 1311 fne.setAttribute("num", "" + key); 1312 fne.addContent(value); 1313 s.addContent(fne); 1314 } 1315 }); 1316 e.addContent(s); 1317 } 1318 1319 if (!getAttributes().isEmpty()) { 1320 d = new Element("attributepairs"); 1321 for (String key : getAttributes()) { 1322 d.addContent(new Element("keyvaluepair") 1323 .addContent(new Element("key") 1324 .addContent(key)) 1325 .addContent(new Element("value") 1326 .addContent(getAttribute(key)))); 1327 } 1328 e.addContent(d); 1329 } 1330 if (_sp != null) { 1331 _sp.store(e); 1332 } 1333 return e; 1334 } 1335 1336 @Override 1337 public String titleString() { 1338 return getId(); 1339 } 1340 1341 @Override 1342 public String toString() { 1343 String out = "[RosterEntry: " 1344 + _id 1345 + " " 1346 + (_fileName != null ? _fileName : "<null>") 1347 + " " 1348 + _roadName 1349 + " " 1350 + _roadNumber 1351 + " " 1352 + _mfg 1353 + " " 1354 + _owner 1355 + " " 1356 + _model 1357 + " " 1358 + _dccAddress 1359 + " " 1360 + _comment 1361 + " " 1362 + _decoderModel 1363 + " " 1364 + _decoderFamily 1365 + " " 1366 + _developerID 1367 + " " 1368 + _manufacturerID 1369 + " " 1370 + _productID 1371 + " " 1372 + _decoderComment 1373 + "]"; 1374 return out; 1375 } 1376 1377 /** 1378 * Write the contents of this RosterEntry back to a file, preserving all 1379 * existing decoder CV content. 1380 * <p> 1381 * This writes the file back in place, with the same decoder-specific 1382 * content. 1383 */ 1384 public void updateFile() { 1385 LocoFile df = new LocoFile(); 1386 1387 String fullFilename = Roster.getDefault().getRosterFilesLocation() + getFileName(); 1388 1389 // read in the content 1390 try { 1391 mRootElement = df.rootFromName(fullFilename); 1392 } catch (JDOMException 1393 | IOException e) { 1394 log.error("Exception while loading loco XML file: {} exception", getFileName(), e); 1395 } 1396 1397 try { 1398 File f = new File(fullFilename); 1399 // do backup 1400 df.makeBackupFile(Roster.getDefault().getRosterFilesLocation() + getFileName()); 1401 1402 // and finally write the file 1403 df.writeFile(f, mRootElement, this.store()); 1404 1405 } catch (Exception e) { 1406 log.error("error during locomotive file output", e); 1407 try { 1408 JmriJOptionPane.showMessageDialog(null, 1409 Bundle.getMessage("ErrorSavingText") + "\n" 1410 + e.getMessage(), 1411 Bundle.getMessage("ErrorSavingTitle"), 1412 JmriJOptionPane.ERROR_MESSAGE); 1413 } catch (HeadlessException he) { 1414 // silently ignore inability to display dialog 1415 } 1416 } 1417 } 1418 1419 /** 1420 * Write the contents of this RosterEntry to a file. 1421 * <p> 1422 * Information on the contents is passed through the parameters, as the 1423 * actual XML creation is done in the LocoFile class. 1424 * 1425 * @param cvModel CV contents to include in file 1426 * @param variableModel Variable contents to include in file 1427 * 1428 */ 1429 public void writeFile(CvTableModel cvModel, VariableTableModel variableModel) { 1430 LocoFile df = new LocoFile(); 1431 1432 // do I/O 1433 FileUtil.createDirectory(Roster.getDefault().getRosterFilesLocation()); 1434 1435 try { 1436 String fullFilename = Roster.getDefault().getRosterFilesLocation() + getFileName(); 1437 File f = new File(fullFilename); 1438 // do backup 1439 df.makeBackupFile(Roster.getDefault().getRosterFilesLocation() + getFileName()); 1440 1441 // changed 1442 changeDateUpdated(); 1443 1444 // and finally write the file 1445 df.writeFile(f, cvModel, variableModel, this); 1446 1447 } catch (Exception e) { 1448 log.error("error during locomotive file output", e); 1449 try { 1450 JmriJOptionPane.showMessageDialog(null, 1451 Bundle.getMessage("ErrorSavingText") + "\n" 1452 + e.getMessage(), 1453 Bundle.getMessage("ErrorSavingTitle"), 1454 JmriJOptionPane.ERROR_MESSAGE); 1455 } catch (HeadlessException he) { 1456 // silently ignore inability to display dialog 1457 } 1458 } 1459 } 1460 1461 /** 1462 * Mark the date updated, e.g. from storing this roster entry. 1463 */ 1464 public void changeDateUpdated() { 1465 // used to create formatted string of now using defaults 1466 this.setDateModified(new Date()); 1467 } 1468 1469 /** 1470 * Store the root element of the JDOM tree representing this RosterEntry. 1471 */ 1472 private Element mRootElement = null; 1473 1474 /** 1475 * Load pre-existing Variable and CvTableModel object with the contents of 1476 * this entry. 1477 * 1478 * @param varModel the variable model to load 1479 * @param cvModel CV contents to load 1480 */ 1481 public void loadCvModel(VariableTableModel varModel, CvTableModel cvModel) { 1482 if (cvModel == null) { 1483 log.error("loadCvModel must be given a non-null argument"); 1484 return; 1485 } 1486 if (mRootElement == null) { 1487 log.error("loadCvModel called before readFile() succeeded"); 1488 return; 1489 } 1490 try { 1491 if (varModel != null) { 1492 LocoFile.loadVariableModel(mRootElement.getChild("locomotive"), varModel); 1493 } 1494 1495 LocoFile.loadCvModel(mRootElement.getChild("locomotive"), cvModel, getManufacturerID(), getDecoderFamily()); 1496 } catch (Exception ex) { 1497 log.error("Error reading roster entry", ex); 1498 try { 1499 JmriJOptionPane.showMessageDialog(null, 1500 Bundle.getMessage("ErrorReadingText") + "\n" + _fileName, 1501 Bundle.getMessage("ErrorReadingTitle"), 1502 JmriJOptionPane.ERROR_MESSAGE); 1503 } catch (HeadlessException he) { 1504 // silently ignore inability to display dialog 1505 } 1506 } 1507 } 1508 1509 /** 1510 * Ultra compact list view of roster entries. Shows text from fields as 1511 * initially visible in the Roster frame table. 1512 * <p> 1513 * Header is created in 1514 * {@link PrintListAction#actionPerformed(java.awt.event.ActionEvent)} so 1515 * keep column widths identical with values of colWidth below. 1516 * 1517 * @param w writer providing output 1518 */ 1519 public void printEntryLine(HardcopyWriter w) { 1520 // no image 1521 // @see #printEntryDetails(w); 1522 1523 try { 1524 //int textSpace = w.getCharactersPerLine() - 1; // could be used to truncate line. 1525 // for now, text just flows to next line 1526 String thisText; 1527 String thisLine = ""; 1528 1529 // start each entry on a new line 1530 w.write(newLine, 0, 1); 1531 1532 int colWidth = 15; 1533 // roster entry ID (not the filname) 1534 if (_id != null) { 1535 thisText = String.format("%-" + colWidth + "s", _id.substring(0, Math.min(_id.length(), colWidth))); // %- = left align 1536 log.debug("thisText = |{}|, length = {}", thisText, thisText.length()); 1537 } else { 1538 thisText = String.format("%-" + colWidth + "s", "<null>"); 1539 } 1540 thisLine += thisText; 1541 colWidth = 6; 1542 // _dccAddress 1543 thisLine += StringUtil.padString(_dccAddress, colWidth); 1544 colWidth = 6; 1545 // _roadName 1546 thisLine += StringUtil.padString(_roadName, colWidth); 1547 colWidth = 6; 1548 // _roadNumber 1549 thisLine += StringUtil.padString(_roadNumber, colWidth); 1550 colWidth = 6; 1551 // _mfg 1552 thisLine += StringUtil.padString(_mfg, colWidth); 1553 colWidth = 10; 1554 // _model 1555 thisLine += StringUtil.padString(_model, colWidth); 1556 colWidth = 10; 1557 // _decoderModel 1558 thisLine += StringUtil.padString(_decoderModel, colWidth); 1559 colWidth = 12; 1560 // _protocol (type) 1561 thisLine += StringUtil.padString(_protocol.toString(), colWidth); 1562 colWidth = 6; 1563 // _owner 1564 thisLine += StringUtil.padString(_owner, colWidth); 1565 colWidth = 10; 1566 1567 // dateModified (type) 1568 if (dateModified != null) { 1569 DateFormat.getDateTimeInstance().format(dateModified); 1570 thisText = String.format("%-" + colWidth + "s", 1571 dateModified.toString().substring(0, Math.min(dateModified.toString().length(), colWidth))); 1572 thisLine += thisText; 1573 } 1574 // don't include comment and decoder family 1575 1576 w.write(thisLine); 1577 // extra whitespace line after each entry would miss goal of a compact listing 1578 // w.write(newLine, 0, 1); 1579 } catch (IOException e) { 1580 log.error("Error printing RosterEntry: ", e); 1581 } 1582 } 1583 1584 public void printEntry(HardcopyWriter w) { 1585 if (getIconPath() != null) { 1586 ImageIcon icon = new ImageIcon(getIconPath()); 1587 // We use an ImageIcon because it's guaranteed to have been loaded when ctor is complete. 1588 // We set the imagesize to 150x150 pixels 1589 int imagesize = 150; 1590 1591 Image img = icon.getImage(); 1592 int width = img.getWidth(null); 1593 int height = img.getHeight(null); 1594 double widthratio = (double) width / imagesize; 1595 double heightratio = (double) height / imagesize; 1596 double ratio = Math.max(widthratio, heightratio); 1597 width = (int) (width / ratio); 1598 height = (int) (height / ratio); 1599 Image newImg = img.getScaledInstance(width, height, java.awt.Image.SCALE_SMOOTH); 1600 1601 ImageIcon newIcon = new ImageIcon(newImg); 1602 w.writeNoScale(newIcon.getImage(), new JLabel(newIcon)); 1603 // Work out the number of line approx that the image takes up. 1604 // We might need to pad some areas of the roster out, so that things 1605 // look correct and text doesn't overflow into the image. 1606 blanks = (newImg.getHeight(null) - w.getLineAscent()) / w.getLineHeight(); 1607 textSpaceWithIcon 1608 = w.getCharactersPerLine() - ((newImg.getWidth(null) / w.getCharWidth())) - indentWidth - 1; 1609 1610 } 1611 printEntryDetails(w); 1612 } 1613 1614 private int blanks = 0; 1615 private int textSpaceWithIcon = 0; 1616 String indent = " "; 1617 int indentWidth = indent.length(); 1618 String newLine = "\n"; 1619 1620 /** 1621 * Print the roster information. 1622 * <p> 1623 * Updated to allow for multiline comment and decoder comment fields. 1624 * Separate write statements for text and line feeds to work around the 1625 * HardcopyWriter bug that misplaces borders. 1626 * 1627 * @param w the HardcopyWriter used to print 1628 */ 1629 public void printEntryDetails(Writer w) { 1630 if (!(w instanceof HardcopyWriter)) { 1631 throw new IllegalArgumentException("No HardcopyWriter instance passed"); 1632 } 1633 int linesAdded = -1; 1634 String title; 1635 String leftMargin = " "; // 3 spaces in front of legend labels 1636 int labelColumn = 19; // pad remaining spaces for legend using fixed width font, forms "%-19s" in line 1637 try { 1638 HardcopyWriter ww = (HardcopyWriter) w; 1639 int textSpace = ww.getCharactersPerLine() - indentWidth - 1; 1640 title = String.format("%-" + labelColumn + "s", 1641 (Bundle.getMessage("MakeLabel", Bundle.getMessage("FieldID")))); // I18N ID: 1642 if ((textSpaceWithIcon != 0) && (linesAdded < blanks)) { 1643 linesAdded = writeWrappedComment(w, _id, leftMargin + title, textSpaceWithIcon) + linesAdded; 1644 } else { 1645 linesAdded = writeWrappedComment(w, _id, leftMargin + title, textSpace) + linesAdded; 1646 } 1647 title = String.format("%-" + labelColumn + "s", 1648 (Bundle.getMessage("MakeLabel", Bundle.getMessage("FieldFilename")))); // I18N Filename: 1649 if ((textSpaceWithIcon != 0) && (linesAdded < blanks)) { 1650 linesAdded = writeWrappedComment(w, _fileName != null ? _fileName : "<null>", leftMargin + title, 1651 textSpaceWithIcon) + linesAdded; 1652 } else { 1653 linesAdded = writeWrappedComment(w, _fileName != null ? _fileName : "<null>", leftMargin + title, 1654 textSpace) + linesAdded; 1655 } 1656 1657 if (!(_roadName.isEmpty())) { 1658 title = String.format("%-" + labelColumn + "s", 1659 (Bundle.getMessage("MakeLabel", Bundle.getMessage("FieldRoadName")))); // I18N Road name: 1660 if ((textSpaceWithIcon != 0) && (linesAdded < blanks)) { 1661 linesAdded = writeWrappedComment(w, _roadName, leftMargin + title, textSpaceWithIcon) + linesAdded; 1662 } else { 1663 linesAdded = writeWrappedComment(w, _roadName, leftMargin + title, textSpace) + linesAdded; 1664 } 1665 } 1666 if (!(_roadNumber.isEmpty())) { 1667 title = String.format("%-" + labelColumn + "s", 1668 (Bundle.getMessage("MakeLabel", Bundle.getMessage("FieldRoadNumber")))); // I18N Road number: 1669 1670 if ((textSpaceWithIcon != 0) && (linesAdded < blanks)) { 1671 linesAdded 1672 = writeWrappedComment(w, _roadNumber, leftMargin + title, textSpaceWithIcon) + linesAdded; 1673 } else { 1674 linesAdded = writeWrappedComment(w, _roadNumber, leftMargin + title, textSpace) + linesAdded; 1675 } 1676 } 1677 if (!(_mfg.isEmpty())) { 1678 title = String.format("%-" + labelColumn + "s", 1679 (Bundle.getMessage("MakeLabel", Bundle.getMessage("FieldManufacturer")))); // I18N Manufacturer: 1680 1681 if ((textSpaceWithIcon != 0) && (linesAdded < blanks)) { 1682 linesAdded = writeWrappedComment(w, _mfg, leftMargin + title, textSpaceWithIcon) + linesAdded; 1683 } else { 1684 linesAdded = writeWrappedComment(w, _mfg, leftMargin + title, textSpace) + linesAdded; 1685 } 1686 } 1687 if (!(_owner.isEmpty())) { 1688 title = String.format("%-" + labelColumn + "s", 1689 (Bundle.getMessage("MakeLabel", Bundle.getMessage("FieldOwner")))); // I18N Owner: 1690 1691 if ((textSpaceWithIcon != 0) && (linesAdded < blanks)) { 1692 linesAdded = writeWrappedComment(w, _owner, leftMargin + title, textSpaceWithIcon) + linesAdded; 1693 } else { 1694 linesAdded = writeWrappedComment(w, _owner, leftMargin + title, textSpace) + linesAdded; 1695 } 1696 } 1697 if (!(_model.isEmpty())) { 1698 title = String.format("%-" + labelColumn + "s", 1699 (Bundle.getMessage("MakeLabel", Bundle.getMessage("FieldModel")))); // I18N Model: 1700 if ((textSpaceWithIcon != 0) && (linesAdded < blanks)) { 1701 linesAdded = writeWrappedComment(w, _model, leftMargin + title, textSpaceWithIcon) + linesAdded; 1702 } else { 1703 linesAdded = writeWrappedComment(w, _model, leftMargin + title, textSpace) + linesAdded; 1704 } 1705 } 1706 if (!(_dccAddress.isEmpty())) { 1707 w.write(newLine, 0, 1); 1708 title = String.format("%-" + labelColumn + "s", 1709 (Bundle.getMessage("MakeLabel", Bundle.getMessage("FieldDCCAddress")))); // I18N DCC Address: 1710 String s = leftMargin + title + _dccAddress; 1711 w.write(s, 0, s.length()); 1712 linesAdded++; 1713 } 1714 1715 // If there is a comment field, then wrap it using the new wrapCommment() 1716 // method and print it 1717 if (!(_comment.isEmpty())) { 1718 //Because the text will fill the width if the roster entry has an icon 1719 //then we need to add some blank lines to prevent the comment text going 1720 //through the picture. 1721 for (int i = 0; i < (blanks - linesAdded); i++) { 1722 w.write(newLine, 0, 1); 1723 } 1724 //As we have added the blank lines to pad out the comment we will 1725 //reset the number of blanks to 0. 1726 if (blanks != 0) { 1727 blanks = 0; 1728 } 1729 title = String.format("%-" + labelColumn + "s", 1730 (Bundle.getMessage("MakeLabel", Bundle.getMessage("FieldComment")))); // I18N Comment: 1731 linesAdded = writeWrappedComment(w, _comment, leftMargin + title, textSpace) + linesAdded; 1732 } 1733 if (!(_decoderModel.isEmpty())) { 1734 title = String.format("%-" + labelColumn + "s", 1735 (Bundle.getMessage("MakeLabel", Bundle.getMessage("FieldDecoderModel")))); // I18N Decoder Model: 1736 if ((textSpaceWithIcon != 0) && (linesAdded < blanks)) { 1737 linesAdded 1738 = writeWrappedComment(w, _decoderModel, leftMargin + title, textSpaceWithIcon) + linesAdded; 1739 } else { 1740 linesAdded = writeWrappedComment(w, _decoderModel, leftMargin + title, textSpace) + linesAdded; 1741 } 1742 } 1743 if (!(_decoderFamily.isEmpty())) { 1744 title = String.format("%-" + labelColumn + "s", 1745 (Bundle.getMessage("MakeLabel", Bundle.getMessage("FieldDecoderFamily")))); // I18N Decoder Family: 1746 if ((textSpaceWithIcon != 0) && (linesAdded < blanks)) { 1747 linesAdded 1748 = writeWrappedComment(w, _decoderFamily, leftMargin + title, textSpaceWithIcon) + linesAdded; 1749 } else { 1750 linesAdded = writeWrappedComment(w, _decoderFamily, leftMargin + title, textSpace) + linesAdded; 1751 } 1752 } 1753 1754 //If there is a decoderComment field, need to wrap it 1755 if (!(_decoderComment.isEmpty())) { 1756 //Because the text will fill the width if the roster entry has an icon 1757 //then we need to add some blank lines to prevent the comment text going 1758 //through the picture. 1759 for (int i = 0; i < (blanks - linesAdded); i++) { 1760 w.write(newLine, 0, 1); 1761 } 1762 //As we have added the blank lines to pad out the comment we will 1763 //reset the number of blanks to 0. 1764 if (blanks != 0) { 1765 blanks = 0; 1766 } 1767 title = String.format("%-" + labelColumn + "s", 1768 (Bundle.getMessage("MakeLabel", Bundle.getMessage("FieldDecoderComment")))); // I18N Decoder Comment: 1769 linesAdded = writeWrappedComment(w, _decoderComment, leftMargin + title, textSpace) + linesAdded; 1770 } 1771 w.write(newLine, 0, 1); 1772 for (int i = -1; i < (blanks - linesAdded); i++) { 1773 w.write(newLine, 0, 1); 1774 } 1775 } catch (IOException e) { 1776 log.error("Error printing RosterEntry", e); 1777 } 1778 } 1779 1780 private int writeWrappedComment(Writer w, String text, String title, int textSpace) { 1781 Vector<String> commentVector = wrapComment(text, textSpace); 1782 1783 //Now have a vector of text pieces and line feeds that will all 1784 //fit in the allowed space. Print each piece, prefixing the first one 1785 //with the label and indenting any remaining. 1786 String s; 1787 int k = 0; 1788 try { 1789 w.write(newLine, 0, 1); 1790 s = title + commentVector.elementAt(k); 1791 w.write(s, 0, s.length()); 1792 k++; 1793 while (k < commentVector.size()) { 1794 String token = commentVector.elementAt(k); 1795 if (!token.equals("\n")) { 1796 s = indent + token; 1797 } else { 1798 s = token; 1799 } 1800 w.write(s, 0, s.length()); 1801 k++; 1802 } 1803 } catch (IOException e) { 1804 log.error("Error printing RosterEntry", e); 1805 } 1806 return k; 1807 } 1808 1809 /** 1810 * Line wrap a comment. 1811 * 1812 * @param comment the comment to wrap at word boundaries 1813 * @param textSpace the width of the space to print 1814 * 1815 * @return comment wrapped to fit given width 1816 */ 1817 public Vector<String> wrapComment(String comment, int textSpace) { 1818 //Tokenize the string using \n to separate the text on mulitple lines 1819 //and create a vector to hold the processed text pieces 1820 StringTokenizer commentTokens = new StringTokenizer(comment, "\n", true); 1821 Vector<String> textVector = new Vector<>(commentTokens.countTokens()); 1822 while (commentTokens.hasMoreTokens()) { 1823 String commentToken = commentTokens.nextToken(); 1824 int startIndex = 0; 1825 int endIndex; 1826 //Check each token to see if it needs to have a line wrap. 1827 //Get a piece of the token, either the size of the allowed space or 1828 //a shorter piece if there isn't enough text to fill the space 1829 if (commentToken.length() < startIndex + textSpace) { 1830 //the piece will fit so extract it and put it in the vector 1831 textVector.addElement(commentToken); 1832 } else { 1833 //Piece too long to fit. Extract a piece the size of the textSpace 1834 //and check for farthest right space for word wrapping. 1835 log.debug("token: /{}/", commentToken); 1836 1837 while (startIndex < commentToken.length()) { 1838 String tokenPiece = commentToken.substring(startIndex, startIndex + textSpace); 1839 if (log.isDebugEnabled()) { 1840 log.debug("loop: /{}/ {}", tokenPiece, tokenPiece.lastIndexOf(" ")); 1841 } 1842 if (tokenPiece.lastIndexOf(" ") == -1) { 1843 //If no spaces, put the whole piece in the vector and add a line feed, then 1844 //increment the startIndex to reposition for extracting next piece 1845 textVector.addElement(tokenPiece); 1846 textVector.addElement(newLine); 1847 startIndex += textSpace; 1848 } else { 1849 //If there is at least one space, extract up to and including the 1850 //last space and put in the vector as well as a line feed 1851 endIndex = tokenPiece.lastIndexOf(" ") + 1; 1852 log.debug("tokenPiece /{}/ {} {}", tokenPiece, startIndex, endIndex); 1853 1854 textVector.addElement(tokenPiece.substring(0, endIndex)); 1855 textVector.addElement(newLine); 1856 startIndex += endIndex; 1857 } 1858 //Check the remaining piece to see if it fits - startIndex now points 1859 //to the start of the next piece 1860 if (commentToken.substring(startIndex).length() < textSpace) { 1861 //It will fit so just insert it, otherwise will cycle through the 1862 //while loop and the checks above will take care of the remainder. 1863 //Line feed is not required as this is the last part of the token. 1864 textVector.addElement(commentToken.substring(startIndex)); 1865 startIndex += textSpace; 1866 } 1867 } 1868 } 1869 } 1870 return textVector; 1871 } 1872 1873 /** 1874 * Read a file containing the contents of this RosterEntry. 1875 * <p> 1876 * This has to be done before a call to loadCvModel, for example. 1877 */ 1878 public void readFile() { 1879 if (getFileName() == null) { 1880 log.warn("readFile invoked with null filename"); 1881 return; 1882 } else { 1883 log.debug("readFile invoked with filename {}", getFileName()); 1884 } 1885 1886 LocoFile lf = new LocoFile(); // used as a temporary 1887 String file = Roster.getDefault().getRosterFilesLocation() + getFileName(); 1888 if (!(new File(file).exists())) { 1889 // try without prefix 1890 file = getFileName(); 1891 } 1892 try { 1893 mRootElement = lf.rootFromName(file); 1894 } catch (JDOMException | IOException e) { 1895 log.error("Exception while loading loco XML file: {} from {}", getFileName(), file, e); 1896 } 1897 } 1898 1899 /** 1900 * Create a RosterEntry from a file. 1901 * 1902 * @param file The file containing the RosterEntry 1903 * @return a new RosterEntry 1904 * @throws JDOMException if unable to parse file 1905 * @throws IOException if unable to read file 1906 */ 1907 public static RosterEntry fromFile(@Nonnull File file) throws JDOMException, IOException { 1908 Element loco = (new LocoFile()).rootFromFile(file).getChild("locomotive"); 1909 if (loco == null) { 1910 throw new JDOMException("missing expected element"); 1911 } 1912 RosterEntry re = new RosterEntry(loco); 1913 re.setFileName(file.getName()); 1914 return re; 1915 } 1916 1917 @Override 1918 public String getDisplayName() { 1919 if (this.getRoadName() != null && !this.getRoadName().isEmpty()) { // NOI18N 1920 return Bundle.getMessage("RosterEntryDisplayName", this.getDccAddress(), this.getRoadName(), 1921 this.getRoadNumber()); // NOI18N 1922 } else { 1923 return Bundle.getMessage("RosterEntryDisplayName", this.getDccAddress(), this.getId(), ""); // NOI18N 1924 } 1925 } 1926 1927 private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(RosterEntry.class); 1928 1929}