file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
CurrentList.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/CurrentList.java
package net.joshuad.hypnos; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.ConcurrentModificationException; import java.util.LinkedHashSet; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.collections.transformation.FilteredList; import javafx.collections.transformation.SortedList; import net.joshuad.hypnos.audio.AudioSystem; import net.joshuad.hypnos.audio.AudioSystem.RepeatMode; import net.joshuad.hypnos.audio.AudioSystem.ShuffleMode; import net.joshuad.hypnos.fxui.ThrottledTrackFilter; import net.joshuad.hypnos.library.Album; import net.joshuad.hypnos.library.Artist; import net.joshuad.hypnos.library.Playlist; import net.joshuad.hypnos.library.Track; public class CurrentList { private static final Logger LOGGER = Logger.getLogger( CurrentList.class.getName() ); public enum Mode { ARTIST, ALBUM, ALBUM_REORDERED, PLAYLIST, PLAYLIST_UNSAVED, EMPTY; } public enum DefaultShuffleMode { SEQUENTIAL, SHUFFLE, NO_CHANGE } public enum DefaultRepeatMode { PLAY_ONCE, REPEAT, NO_CHANGE } Mode mode = Mode.EMPTY; final List <Album> currentAlbums = new ArrayList <Album> (); Playlist currentPlaylist; Artist currentArtist; private final ObservableList <CurrentListTrack> items = FXCollections.observableArrayList(); private final FilteredList <CurrentListTrack> currentListFiltered = new FilteredList <CurrentListTrack>( items, p -> true ); private final SortedList <CurrentListTrack> currentListSorted = new SortedList <CurrentListTrack>( currentListFiltered ); private SortedList <CurrentListTrack> currentListSortedNoFilter; private final List <CurrentListListener> listeners = new ArrayList<CurrentListListener> (); ThrottledTrackFilter currentListTableFilter; private AudioSystem audioSystem; private Queue queue; private DefaultShuffleMode albumShuffleMode = DefaultShuffleMode.SEQUENTIAL; private DefaultShuffleMode trackShuffleMode = DefaultShuffleMode.NO_CHANGE; private DefaultShuffleMode playlistShuffleMode = DefaultShuffleMode.SHUFFLE; private DefaultRepeatMode albumRepeatMode = DefaultRepeatMode.PLAY_ONCE; private DefaultRepeatMode trackRepeatMode = DefaultRepeatMode.NO_CHANGE; private DefaultRepeatMode playlistRepeatMode = DefaultRepeatMode.REPEAT; List <Thread> noLoadThreads = new ArrayList <Thread> (); transient private boolean hasUnsavedData = true; private boolean allowAlbumReload = true; //Allow the album to be reloaded if the disk is changed //usually enabled, but disabled for the current list after restarting hypnos public CurrentList ( AudioSystem audioSystem, Queue queue ) { this.queue = queue; this.audioSystem = audioSystem; currentListTableFilter = new ThrottledTrackFilter ( currentListFiltered ); startListWatcher(); items.addListener( (ListChangeListener.Change<? extends Track> change) -> { hasUnsavedData = true; }); } public boolean hasUnsavedData() { return hasUnsavedData; } public void setHasUnsavedData( boolean b ) { hasUnsavedData = b; } public boolean allowAlbumReload () { return allowAlbumReload; } public void addNoLoadThread ( Thread t ) { noLoadThreads.add ( t ); } private boolean onBadThread() { for ( Thread t : noLoadThreads ) { if ( t == Thread.currentThread() ) { return true; } } return false; } public void doThreadAware( Runnable runMe ) { if ( onBadThread() ) { Thread loaderThread = new Thread ( runMe ); loaderThread.setName( "Short Off-FX Thread" ); loaderThread.setDaemon( true ); loaderThread.start(); } else { runMe.run(); } } private void startListWatcher() { Thread watcher = new Thread( () -> { while ( true ) { try { for ( CurrentListTrack track : items ) { boolean isMissing = !Utils.isMusicFile( track.getPath() ); if ( !isMissing && track.isMissingFile() ) { track.setIsMissingFile ( false ); } else if ( isMissing && !track.isMissingFile() ) { track.setIsMissingFile ( true ); } if ( track.needsUpdateFromDisk() ) { try { track.update(); } catch ( Exception e ) { //No need to log anything, UI should show it } } } } catch ( ConcurrentModificationException e ) { //If the list is edited, stop what we're doing and start up again later. } try { Thread.sleep ( 250 ); } catch ( InterruptedException e ) { LOGGER.log ( Level.INFO, "Interrupted while sleeping in current list watcher.", e ); } } }); watcher.setName( "Current List Watcher" ); watcher.setDaemon( true ); watcher.start(); } public void addListener ( CurrentListListener listener ) { if ( listener == null ) { LOGGER.log( Level.INFO, "Null player listener was attempted to be added, ignoring.", new NullPointerException() ); } else if ( listeners.contains( listener ) ) { LOGGER.log( Level.INFO, "Duplicate listener was attempted to be added, ignoring.", new Exception() ); } else { listeners.add( listener ); } } public ObservableList<CurrentListTrack> getItems() { return items; } public void setMode ( Mode mode ) { this.mode = mode; notifyListenersStateChanged(); } public CurrentListState getState () { return new CurrentListState ( new ArrayList<CurrentListTrack>( items ), currentArtist, currentAlbums, currentPlaylist, mode ); } public void setDefaultAlbumShuffleMode ( DefaultShuffleMode mode ) { this.albumShuffleMode = mode; } public void setDefaultTrackShuffleMode ( DefaultShuffleMode mode ) { this.trackShuffleMode = mode; } public void setDefaultPlaylistShuffleMode ( DefaultShuffleMode mode ) { this.playlistShuffleMode = mode; } public void setDefaultAlbumRepeatMode ( DefaultRepeatMode mode ) { this.albumRepeatMode = mode; } public void setDefaultTrackRepeatMode ( DefaultRepeatMode mode ) { this.trackRepeatMode = mode; } public void setDefaultPlaylistRepeatMode ( DefaultRepeatMode mode ) { this.playlistRepeatMode = mode; } public DefaultShuffleMode getDefaultTrackShuffleMode () { return trackShuffleMode; } public DefaultShuffleMode getDefaultAlbumShuffleMode () { return albumShuffleMode; } public DefaultShuffleMode getDefaultPlaylistShuffleMode () { return playlistShuffleMode; } public DefaultRepeatMode getDefaultTrackRepeatMode () { return trackRepeatMode; } public DefaultRepeatMode getDefaultAlbumRepeatMode () { return albumRepeatMode; } public DefaultRepeatMode getDefaultPlaylistRepeatMode () { return playlistRepeatMode; } public void setState( CurrentListState state ) { items.clear(); items.addAll( state.getItems() ); currentAlbums.clear(); currentAlbums.addAll( state.getAlbums() ); currentPlaylist = state.getPlaylist(); currentArtist = state.getArtist(); mode = state.getMode(); notifyListenersStateChanged(); allowAlbumReload = false; } public Playlist getCurrentPlaylist () { return currentPlaylist; } public void shuffleList () { Collections.shuffle( items ); listReordered(); } public void shuffleItems ( List<Integer> input ) { List<CurrentListTrack> shuffleMe = new ArrayList<CurrentListTrack> (); List<Integer> itemIndices = new ArrayList<Integer> ( input ); for ( int index : itemIndices ) { shuffleMe.add( items.get( index ) ); } Collections.shuffle( shuffleMe ); for ( int index : itemIndices ) { items.set( index, shuffleMe.remove( 0 ) ); } listReordered(); } public void clearList() { if ( items.size() > 0 ) { listCleared(); } items.clear(); } public void removeTracksAtIndices ( List <Integer> indices ) { Runnable runMe = new Runnable() { public void run() { List <Integer> indicesToBeRemoved = new ArrayList <>(); for ( int index : indices ) { indicesToBeRemoved.add( currentListFiltered.getSourceIndex( currentListSorted.getSourceIndex( index ) ) ); } indicesToBeRemoved.sort( Comparator.reverseOrder() ); boolean changed = false; for ( Integer index : indicesToBeRemoved ) { CurrentListTrack removed = items.remove( index.intValue() ); if ( !changed && removed != null ) changed = true; } if ( changed ) { if ( items.size() == 0 ) { listCleared(); currentPlaylist = null; } else { tracksRemoved(); } } } }; doThreadAware ( runMe ); } public void moveTracks ( List<Integer> fromLocations, int toLocation ) { if ( fromLocations == null ) { LOGGER.log( Level.INFO, "Recieved a null list, ignoring request.", new NullPointerException() ); return; } if ( fromLocations.size() == 0 ) { LOGGER.log( Level.INFO, "Recieved an empty list, ignoring request.", new Exception() ); return; } ArrayList <CurrentListTrack> tracksToMove = new ArrayList <CurrentListTrack> ( fromLocations.size() ); for ( int index : fromLocations ) { if ( index >= 0 && index < items.size() ) { tracksToMove.add( items.get( index ) ); } } for ( int k = fromLocations.size() - 1; k >= 0; k-- ) { int index = fromLocations.get( k ).intValue(); if ( index >= 0 && index < items.size() ) { items.remove ( index ); } } if ( tracksToMove.size() > 0 ) { if ( toLocation > items.size() ) toLocation = items.size(); items.addAll( toLocation, tracksToMove ); listReordered(); } } public void setTrack ( String location ) { setTracksPathList ( Arrays.asList( Paths.get( location ) ) ); } public void setTrack ( Path path ) { setTracksPathList ( Arrays.asList( path ) ); } public void setTrack ( Track track ) { setTracksPathList ( Arrays.asList( track.getPath() ) ); } public void setTracks ( List <? extends Track> tracks ) { setTracks ( tracks, true ); } public void setTracks ( List <? extends Track> tracks, boolean clearQueue ) { clearList(); if ( clearQueue ) queue.clear(); this.currentListTableFilter.setFilter( "", false ); audioSystem.getUI().setCurrentListFilterText( "" ); appendTracks ( tracks ); } public void setTracksPathList ( List <Path> paths ) { setTracksPathList ( paths, null ); } public void setTracksPathList ( List <Path> paths, Runnable afterLoad ) { clearList(); queue.clear(); appendTracksPathList ( paths, afterLoad ); } public void appendTrack ( String location ) { appendTracksPathList ( Arrays.asList( Paths.get( location ) ) ); } public void appendTrack ( Path path ) { appendTracksPathList ( Arrays.asList( path ) ); } public void appendTrack ( Track track ) { insertTracks ( items.size(), Arrays.asList( track ) ); } public void appendTracks ( List <? extends Track> tracks ) { insertTracks ( items.size(), tracks ); } public void appendTracksPathList ( List <Path> paths ) { insertTrackPathList ( items.size(), paths, null ); } public void appendTracksPathList ( List <Path> paths, Runnable afterLoad ) { insertTrackPathList ( items.size(), paths, afterLoad ); } public void insertTracks ( int index, List<? extends Track> tracks ) { if ( tracks == null || tracks.size() <= 0 ) { LOGGER.log( Level.INFO, "Recieved a null or empty track list. No tracks loaded.", new Exception() ); return; } boolean startedEmpty = items.isEmpty(); List <CurrentListTrack> addMe = new ArrayList <CurrentListTrack> ( tracks.size() ); for ( Track track : tracks ) { addMe.add( new CurrentListTrack ( track ) ); } int targetIndex = index; synchronized ( items ) { if ( index < 0 ) { LOGGER.log( Level.INFO, "Asked to insert tracks at: " + index + ", inserting at 0 instead.", new Exception() ); targetIndex = 0; } else if ( index > items.size() ) { LOGGER.log( Level.INFO, "Asked to insert tracks past the end of current list. Inserting at end instead.", new Exception() ); targetIndex = items.size(); } } int tracksAdded = 0; for ( CurrentListTrack track : addMe ) { addItem ( targetIndex, track ); targetIndex++; tracksAdded++; } if ( tracksAdded > 0 ) { if ( startedEmpty ) { tracksSet(); } else { tracksAdded(); } } } public void insertTrackPathList ( int index, List<Path> paths ) { insertTrackPathList ( index, paths, null ); } public void insertTrackPathList ( int index, List <Path> paths, Runnable doAfterLoad ) { Runnable runMe = new Runnable() { public void run() { boolean startedEmpty = items.isEmpty(); if ( paths == null || paths.size() <= 0 ) { LOGGER.log( Level.INFO, "Recieved a null or empty track list. No tracks loaded.", new NullPointerException() ); return; } int targetIndex = index; synchronized ( items ) { if ( index < 0 ) { LOGGER.log( Level.INFO, "Asked to insert tracks at: " + index + ", inserting at 0 instead.", new Exception() ); targetIndex = 0; } else if ( index > items.size() ) { LOGGER.log( Level.INFO, "Asked to insert tracks past the end of current list. Inserting at end instead.", new Exception() ); targetIndex = items.size() - 1; } } int tracksAdded = 0; for ( Path path : paths ) { try { addItem ( targetIndex, new CurrentListTrack ( path ) ); targetIndex++; tracksAdded++; } catch ( Exception e ) { LOGGER.log( Level.INFO, "Couldn't load track: " + path.toString() + ". Skipping.", e ); } } if ( tracksAdded > 0 ) { if ( startedEmpty ) { tracksSet(); } else { tracksAdded(); } } //TODO: This is really bad practice, but it works for now. Refactor //This fixes two problems -- red rows in current list not being white after deleting and D&D //and the table not refreshing after drag & drop of folder //TODO: Is this still a problem or did new library fix it? Hypnos.getUI().refreshCurrentList(); if ( doAfterLoad != null ) { doAfterLoad.run(); } } }; doThreadAware ( runMe ); } private void addItem ( int index, CurrentListTrack track ) { if ( track == null ) return; synchronized ( items ) { int targetIndex = index; if ( index < 0 ) { LOGGER.log( Level.INFO, "Asked to insert tracks at: " + index + ", inserting at 0 instead.", new Exception() ); targetIndex = 0; } else if ( index > items.size() ) { LOGGER.log( Level.INFO, "Asked to insert tracks past the end of current list. Inserting at end instead.", new Exception() ); targetIndex = items.size() - 1; } items.add( targetIndex, track ); } } public void appendAlbum ( Album album ) { appendAlbums ( Arrays.asList( album ) ); } public void appendAlbums ( List<Album> albums ) { insertAlbums ( items.size(), albums ); } public void insertAlbums ( final int index, List<Album> albums ) { Runnable runMe = new Runnable() { public void run() { int targetIndex = index > items.size() ? items.size() : index; boolean insertedAtEnd = ( targetIndex == items.size() ); boolean startedEmpty = false; Mode startMode = mode; if ( items.size() == 0 ) startedEmpty = true; List<Track> addMe = new ArrayList<Track> (); for ( Album album : albums ) { if ( album != null ) { addMe.addAll( album.getTracks() ); } } insertTracks ( targetIndex, addMe ); if ( startedEmpty ) { albumsSet ( albums ); } else if ( startMode == Mode.ALBUM || startMode == Mode.ALBUM_REORDERED ) { boolean startedReordered = ( startMode == Mode.ALBUM_REORDERED ); List<Album> fullAlbumList = new ArrayList<Album> ( currentAlbums ); fullAlbumList.addAll ( albums ); albumsSet ( fullAlbumList ); if ( startedReordered && mode == Mode.ALBUM ) { mode = Mode.ALBUM_REORDERED; } if ( targetIndex != 0 && !insertedAtEnd ) { listReordered(); } } } }; doThreadAware ( runMe ); } public void setAlbum ( Album album, boolean clearQueue ) { setAlbums ( Arrays.asList( album ), clearQueue ); } public void setAlbum ( Album album ) { setAlbums ( Arrays.asList( album ) ); } public void setAlbums ( List<Album> albums ) { setAlbums ( albums, true ); } public void setAlbums ( List<Album> albums, boolean clearQueue ) { List <Track> addMe = new ArrayList <Track> (); List <Album> missing = new ArrayList <Album> (); for ( Album album : albums ) { if ( album == null ) { continue; } else if ( !Files.isDirectory ( album.getPath() ) ) { missing.add( album ); } else { addMe.addAll ( album.getTracks() ); } } setTracks ( addMe, clearQueue ); albumsSet ( albums ); if ( missing.size() > 0 ) { Hypnos.warnUserAlbumsMissing ( missing ); } } public void appendPlaylist ( Playlist playlist ) { boolean setAsPlaylist = false; if ( items.size() == 0 ) setAsPlaylist = true; appendTracks ( playlist.getTracks() ); if ( setAsPlaylist ) { currentPlaylist = playlist; playlistsSet ( Arrays.asList( playlist ) ); } } public void appendPlaylists ( List<Playlist> playlists ) { boolean startedEmpty = false; if ( items.size() == 0 ) startedEmpty = true; int playlistsAdded = 0; Playlist lastPlaylist = null; for ( Playlist playlist : playlists ) { if ( playlist != null ) { appendTracks ( playlist.getTracks() ); lastPlaylist = playlist; playlistsAdded++; } } if ( startedEmpty && playlistsAdded == 1 ) { currentPlaylist = lastPlaylist; } if ( startedEmpty ) { playlistsSet ( playlists ); } } public void insertPlaylists ( int index, List<Playlist> playlists ) { Runnable runMe = new Runnable() { public void run() { int targetIndex = index > items.size() ? items.size() : index; boolean startedEmpty = false; if ( items.size() == 0 ) startedEmpty = true; List<Track> addMe = new ArrayList<Track> (); for ( Playlist playlist : playlists ) { if ( playlist != null ) { addMe.addAll( playlist.getTracks() ); } } insertTracks ( targetIndex, addMe ); if ( startedEmpty ) { playlistsSet ( playlists ); } else { tracksAdded(); } } }; doThreadAware ( runMe ); } public void setPlaylist ( Playlist playlist ) { setPlaylists ( Arrays.asList( playlist ) ); } public void setPlaylists ( List<Playlist> playlists ) { List <Track> addMe = new ArrayList <Track> (); int playlistsAdded = 0; Playlist playlistAdded = null; for ( Playlist playlist : playlists ) { if ( playlist != null ) { addMe.addAll ( playlist.getTracks() ); playlistsAdded++; playlistAdded = playlist; } } setTracks ( addMe ); if ( playlistsAdded == 1 ) { currentPlaylist = playlistAdded; } playlistsSet ( playlists ); } public void notifyListenersStateChanged() { CurrentListState state = getState(); for ( CurrentListListener listener : listeners ) { listener.stateChanged ( state ); } allowAlbumReload = true; } public void albumsSet ( List <Album> input ) { if ( input == null ) { mode = Mode.EMPTY; currentAlbums.clear(); currentPlaylist = null; LOGGER.log( Level.INFO, "Recieved an null album list.", new NullPointerException() ); notifyListenersStateChanged(); return; } ArrayList<Album> albums = new ArrayList<Album> ( input ); albums.removeIf( Objects::isNull ); if ( albums.size() == 0 ) { mode = Mode.EMPTY; currentAlbums.clear(); currentPlaylist = null; notifyListenersStateChanged(); return; } else if ( albums.size() == 1 ) { mode = Mode.ALBUM; updateDefaultModes(); currentAlbums.clear(); currentAlbums.addAll( albums ); notifyListenersStateChanged(); return; } else { boolean initialized = false; String simpleTitle = "", year = "", artist = ""; boolean differentBaseAlbums = false; for ( int k = 0; k < albums.size(); k++ ) { Album album = albums.get( k ); if ( !initialized ) { simpleTitle = album.getAlbumTitle(); year = album.getYear(); artist = album.getAlbumArtist(); initialized = true; } else { if ( !album.getAlbumTitle().equals( simpleTitle ) || !album.getAlbumArtist().equals( artist ) || !album.getYear().equals( year ) ){ differentBaseAlbums = true; } } } if ( !initialized ) { mode = Mode.EMPTY; currentAlbums.clear(); currentPlaylist = null; notifyListenersStateChanged(); return; } else if ( differentBaseAlbums ) { mode = Mode.PLAYLIST_UNSAVED; updateDefaultModes(); currentAlbums.clear(); currentPlaylist = null; notifyListenersStateChanged(); return; } else { mode = Mode.ALBUM; updateDefaultModes(); currentAlbums.clear(); currentAlbums.addAll( albums ); notifyListenersStateChanged(); return; } } } //TODO: these nested case statements are ugly private void updateDefaultModes() { DefaultShuffleMode shuffleTarget; DefaultRepeatMode repeatTarget; switch ( mode ) { case ALBUM: case ALBUM_REORDERED: shuffleTarget = albumShuffleMode; repeatTarget = albumRepeatMode; break; case PLAYLIST: switch ( getCurrentPlaylist().getShuffleMode() ) { case SEQUENTIAL: shuffleTarget = DefaultShuffleMode.SEQUENTIAL; break; case SHUFFLE: shuffleTarget = DefaultShuffleMode.SHUFFLE; break; case USE_DEFAULT: default: shuffleTarget = playlistShuffleMode; break; } switch ( getCurrentPlaylist().getRepeatMode() ) { case PLAY_ONCE: repeatTarget = DefaultRepeatMode.PLAY_ONCE; break; case REPEAT: repeatTarget = DefaultRepeatMode.REPEAT; break; case USE_DEFAULT: default: repeatTarget = playlistRepeatMode; break; } break; case PLAYLIST_UNSAVED: case EMPTY: default: shuffleTarget = trackShuffleMode; repeatTarget = trackRepeatMode; break; } switch ( shuffleTarget ) { case NO_CHANGE: //Do nothing break; case SEQUENTIAL: audioSystem.setShuffleMode( ShuffleMode.SEQUENTIAL ); break; case SHUFFLE: audioSystem.setShuffleMode( ShuffleMode.SHUFFLE ); break; } switch ( repeatTarget ) { case NO_CHANGE: //Do nothing break; case PLAY_ONCE: audioSystem.setRepeatMode( RepeatMode.PLAY_ONCE ); break; case REPEAT: audioSystem.setRepeatMode( RepeatMode.REPEAT ); break; } } public void playlistsSet ( List <Playlist> playlists ) { if ( playlists == null ) { mode = Mode.EMPTY; currentAlbums.clear(); currentPlaylist = null; LOGGER.log( Level.INFO, "Recieved an null playlist list.", new NullPointerException() ); notifyListenersStateChanged(); return; } playlists.removeIf( Objects::isNull ); if ( playlists.size() == 0 ) { mode = Mode.EMPTY; currentAlbums.clear(); currentPlaylist = null; notifyListenersStateChanged(); return; } else if ( playlists.size() >= 1 ) { mode = Mode.PLAYLIST; currentPlaylist = playlists.get( 0 ); updateDefaultModes(); currentAlbums.clear(); notifyListenersStateChanged(); return; } } public void artistSet () { mode = Mode.ARTIST; updateDefaultModes(); currentAlbums.clear(); currentPlaylist = null; notifyListenersStateChanged(); } public void tracksSet () { mode = Mode.PLAYLIST_UNSAVED; updateDefaultModes(); currentAlbums.clear(); currentPlaylist = null; notifyListenersStateChanged(); } public void tracksAdded () { if ( mode == Mode.ARTIST ) { mode = Mode.PLAYLIST_UNSAVED; } else if ( mode == Mode.PLAYLIST ) { if ( currentPlaylist.getTracks().equals( items ) ) { mode = Mode.PLAYLIST; } else { mode = Mode.PLAYLIST_UNSAVED; } } else if ( mode == Mode.ALBUM || mode == Mode.ALBUM_REORDERED ) { mode = Mode.PLAYLIST_UNSAVED; } notifyListenersStateChanged(); } public void tracksRemoved () { if ( mode == Mode.ARTIST ) { mode = Mode.PLAYLIST_UNSAVED; } else if ( mode == Mode.PLAYLIST ) { mode = Mode.PLAYLIST_UNSAVED; } else if ( mode == Mode.ALBUM ) { mode = Mode.PLAYLIST_UNSAVED; this.currentAlbums.clear(); } notifyListenersStateChanged(); } public void listCleared () { currentAlbums.clear(); mode = Mode.EMPTY; notifyListenersStateChanged(); } public void listReordered () { if ( mode == Mode.ARTIST ) { mode = Mode.PLAYLIST_UNSAVED; } else if ( mode == Mode.ALBUM ) { mode = Mode.ALBUM_REORDERED; } else if ( mode == Mode.PLAYLIST ) { if ( currentPlaylist != null && items.equals( currentPlaylist.getTracks() ) ) { mode = Mode.PLAYLIST; } else { mode = Mode.PLAYLIST_UNSAVED; } } notifyListenersStateChanged(); } public void setAndPlayAlbum ( Album album ) { setAndPlayAlbums( Arrays.asList( album ) ); } public void setAndPlayAlbums ( List <Album> albums ) { setAlbums( albums ); audioSystem.next( false ); for ( Album album : albums ) { Hypnos.getLibrary().requestRescan ( album.getPath() ); } } public void setAndPlayPlaylist ( Playlist playlist ) { setAndPlayPlaylists( Arrays.asList( playlist ) ); } public void setAndPlayPlaylists ( List <Playlist> playlists ) { setPlaylists( playlists ); audioSystem.next( false ); } public FilteredList <CurrentListTrack> getFilteredItems () { return currentListFiltered; } public SortedList <CurrentListTrack> getSortedItems () { return currentListSorted; } public List <CurrentListTrack> getSortedItemsNoFilter () { if ( currentListSortedNoFilter == null ) { //REFACTOR: This is the right way to do this, but it's really bad in terms of module independence //Fix it at some point. currentListSortedNoFilter = new SortedList <CurrentListTrack> ( items ); currentListSortedNoFilter.comparatorProperty().bind( Hypnos.getUI().getCurrentListPane().currentListTable.comparatorProperty() ); } return currentListSortedNoFilter; } public void setItemsToSortedOrder() { items.setAll( new ArrayList<CurrentListTrack> ( getSortedItemsNoFilter () ) ); } public void setFilter ( String newValue ) { currentListTableFilter.setFilter( newValue, false ); } public void insertArtists ( int targetIndex, ObservableList <Artist> artists ) { List<Track> tracks = new ArrayList<> (); for ( Artist artist : artists ) { tracks.addAll( artist.getAllTracks() ); } insertTracks ( targetIndex, tracks ); } public void setAndPlayArtists ( List <Artist> artists ) { List<Track> tracks = new ArrayList<> (); for ( Artist artist : artists ) { tracks.addAll( artist.getAllTracks() ); } setTracks ( tracks ); audioSystem.next( false ); } public void appendArtists ( List <Artist> artists ) { boolean startedEmpty = items.isEmpty(); for ( Artist artist : artists ) { appendTracks ( artist.getAllTracks() ); } if ( startedEmpty && artists.size() == 1 && !items.isEmpty() ) { this.currentArtist = artists.get( 0 ); artistSet(); } } public void setAndPlayArtist ( Artist artist ) { setTracks ( artist.getAllTracks() ); audioSystem.next( false ); if ( !items.isEmpty() ) { this.currentArtist = artist; artistSet(); } } public void appendArtist ( Artist artist ) { boolean startedEmpty = items.isEmpty(); appendTracks ( artist.getAllTracks() ); if ( startedEmpty && !items.isEmpty() ) { this.currentArtist = artist; artistSet(); } } public void removeDuplicates() { Set<CurrentListTrack> nonDuplicateSet = new LinkedHashSet<> ( items ); boolean sameSize = ( items.size() == nonDuplicateSet.size() ); items.clear( ); items.addAll( nonDuplicateSet ); if ( !sameSize ) { tracksRemoved(); } } }
28,354
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
CurrentListState.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/CurrentListState.java
package net.joshuad.hypnos; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import net.joshuad.hypnos.CurrentList.Mode; import net.joshuad.hypnos.Hypnos.OS; import net.joshuad.hypnos.library.Album; import net.joshuad.hypnos.library.Artist; import net.joshuad.hypnos.library.Playlist; public class CurrentListState implements Serializable { private static final long serialVersionUID = 1L; private Mode mode; private Artist artist; private Playlist playlist; private List<Album> albums; private List<CurrentListTrack> tracks; public CurrentListState ( List<CurrentListTrack> tracks, Artist artist, List<Album> albums, Playlist playlist, Mode mode ) { if ( tracks == null ) { this.tracks = null; } else { this.tracks = new ArrayList<CurrentListTrack> ( tracks ); } if ( albums == null ) { this.albums = null; } else { this.albums = new ArrayList<Album> ( albums ); } this.artist = artist; this.playlist = playlist; this.mode = mode; } public Mode getMode() { return mode; } public Playlist getPlaylist() { return playlist; } public List<Album> getAlbums() { return Collections.unmodifiableList( albums ); } public Artist getArtist() { return artist; } public List<CurrentListTrack> getItems() { return Collections.unmodifiableList( tracks ); } public String getDisplayString() { String retMe = ""; if ( mode == Mode.ARTIST ) { retMe = "Artist - " + artist.getName(); } else if ( mode == Mode.ALBUM || mode == Mode.ALBUM_REORDERED ) { if ( albums.size() == 0 ) { } else if ( albums.size() == 1 ) { Album album = albums.get( 0 ); retMe = "Album: " + album.getAlbumArtist() + " - " + album.getYear() + " - " + album.getFullAlbumTitle(); } else { Album album = albums.get( 0 ); retMe ="Album: " + album.getAlbumArtist() + " - " + album.getYear() + " - " + album.getAlbumTitle(); } if ( mode == Mode.ALBUM_REORDERED ) { if ( Hypnos.getOS() == OS.WIN_XP || Hypnos.getOS() == OS.WIN_VISTA || Hypnos.getOS() == OS.WIN_7 ) { retMe += " *"; } else { retMe += " 🔀"; } } } else if ( mode == Mode.PLAYLIST || mode == Mode.PLAYLIST_UNSAVED ) { if ( playlist != null ) { retMe = "Playlist: " + playlist.getName(); } else { retMe = "Playlist: New"; } if ( mode == Mode.PLAYLIST_UNSAVED ) { retMe += " *"; } } return retMe; } }
2,501
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
Hypnos.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/Hypnos.java
package net.joshuad.hypnos; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLDecoder; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.EnumMap; import java.util.Enumeration; import java.util.List; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.Manifest; import java.util.logging.ConsoleHandler; import java.util.logging.FileHandler; import java.util.logging.Formatter; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import javafx.application.Application; import javafx.application.Platform; import javafx.stage.Stage; import net.joshuad.hypnos.Persister.Setting; import net.joshuad.hypnos.audio.AudioSystem; import net.joshuad.hypnos.audio.AudioSystem.StopReason; import net.joshuad.hypnos.fxui.FXUI; import net.joshuad.hypnos.hotkeys.GlobalHotkeys; import net.joshuad.hypnos.hotkeys.GlobalHotkeys.Hotkey; import net.joshuad.hypnos.library.Album; import net.joshuad.hypnos.library.Library; import net.joshuad.hypnos.library.Playlist; import net.joshuad.hypnos.library.Track; import net.joshuad.hypnos.library.Library.LoaderSpeed; public class Hypnos extends Application { private static final Logger LOGGER = Logger.getLogger( Hypnos.class.getName() ); public enum ExitCode { NORMAL, UNKNOWN_ERROR, AUDIO_ERROR, UNSUPPORTED_OS } public enum OS { WIN_XP ( "Windows XP" ), WIN_VISTA ( "Windows Vista" ), WIN_7 ( "Windows 7" ), WIN_8 ( "Windows 8" ), WIN_10 ( "Windows 10" ), WIN_UNKNOWN ( "Windows Unknown" ), OSX ( "Mac OSX" ), NIX ( "Linux/Unix" ), UNKNOWN ( "Unknown" ); private String displayName; OS ( String displayName ) { this.displayName = displayName; } public String getDisplayName () { return displayName; } public boolean isWindows() { switch ( this ) { case WIN_10: case WIN_7: case WIN_8: case WIN_UNKNOWN: case WIN_VISTA: case WIN_XP: return true; case NIX: case OSX: case UNKNOWN: default: return false; } } public boolean isOSX() { switch ( this ) { case OSX: return true; case WIN_10: case WIN_7: case WIN_8: case WIN_UNKNOWN: case WIN_VISTA: case WIN_XP: case NIX: case UNKNOWN: default: return false; } } public boolean isLinux() { switch ( this ) { case NIX: return true; case WIN_10: case WIN_7: case WIN_8: case WIN_UNKNOWN: case WIN_VISTA: case WIN_XP: case UNKNOWN: case OSX: default: return false; } } } private static OS os = OS.UNKNOWN; private static String build; private static String version; private static String buildDate; private static Path rootDirectory; private static Path configDirectory; private static Path logFile, logFileBackup, logFileBackup2; private static boolean isStandalone = false; private static boolean isDeveloping = false; private static boolean disableGlobalHotkeysRequestedByProperties = false; private static Persister persister; private static AudioSystem audioSystem; private static FXUI ui; private static Library library; private static GlobalHotkeys globalHotkeys; private static PrintStream originalOut; private static PrintStream originalErr; private static LoaderSpeed loaderSpeed = LoaderSpeed.HIGH; private static ByteArrayOutputStream logBuffer; //Used to store log info until log file is initialized private static Formatter logFormat = new Formatter() { SimpleDateFormat dateFormat = new SimpleDateFormat ( "MMM d, yyyy HH:mm:ss aaa" ); public String format ( LogRecord record ) { String exceptionMessage = ""; if ( record.getThrown() != null ) { StringWriter sw = new StringWriter(); record.getThrown().printStackTrace( new PrintWriter( sw ) ); exceptionMessage = "\n" + sw.toString(); } String retMe = dateFormat.format( new Date ( record.getMillis() ) ) + " " + record.getLoggerName() + " " + record.getSourceMethodName() + System.lineSeparator() + record.getLevel() + ": " + record.getMessage() + exceptionMessage + System.lineSeparator() + System.lineSeparator(); return retMe; } }; public static OS getOS() { return os; } public static String getVersion() { return version; } public static String getBuild() { return build; } public static String getBuildDate() { return buildDate; } public static boolean isStandalone() { return isStandalone; } public static boolean isDeveloping() { return isDeveloping; } public static Path getRootDirectory() { return rootDirectory; } public static Path getConfigDirectory() { return configDirectory; } public static Path getLogFile() { return logFile; } public static Path getLogFileBackup() { return logFileBackup; } public static Persister getPersister() { return persister; } public static Library getLibrary() { return library; } public static FXUI getUI() { return ui; } public static LoaderSpeed getLoaderSpeed ( ) { return loaderSpeed; } public static void setLoaderSpeed ( LoaderSpeed speed ) { loaderSpeed = speed; ui.setLoaderSpeedDisplay ( speed ); } private static void startLogToBuffer() { originalOut = System.out; originalErr = System.err; logBuffer = new ByteArrayOutputStream(); System.setOut( new PrintStream ( logBuffer ) ); System.setErr( new PrintStream ( logBuffer ) ); Logger.getLogger( "" ).getHandlers()[0].setFormatter( logFormat ); } private void parseSystemProperties() { isStandalone = Boolean.getBoolean( "hypnos.standalone" ); isDeveloping = Boolean.getBoolean( "hypnos.developing" ); disableGlobalHotkeysRequestedByProperties = Boolean.getBoolean( "hypnos.disableglobalhotkeys" ); if ( isStandalone ) LOGGER.info ( "Running as standalone - requested by system properties set at program launch" ); if ( isDeveloping ) LOGGER.info ( "Running on development port - requested by system properties set at program launch" ); if ( disableGlobalHotkeysRequestedByProperties ) LOGGER.info ( "Global hotkeys disabled - requested by system properties set at program launch" ); } private void determineOS() { String osString = System.getProperty( "os.name" ).toLowerCase(); if ( osString.indexOf( "win" ) >= 0 ) { if ( osString.indexOf( "xp" ) >= 0 ) { os = OS.WIN_XP; } else if ( osString.indexOf( "vista" ) >= 0 ) { os = OS.WIN_VISTA; } else if ( osString.indexOf( "7" ) >= 0 ) { os = OS.WIN_7; } else if ( osString.indexOf( "8" ) >= 0 ) { os = OS.WIN_8; } else if ( osString.indexOf( "10" ) >= 0 ) { os = OS.WIN_10; } else { os = OS.WIN_UNKNOWN; } } else if ( osString.indexOf( "nix" ) >= 0 || osString.indexOf( "linux" ) >= 0 ) { os = OS.NIX; } else if ( osString.indexOf( "mac" ) >= 0 ) { os = OS.OSX; } else { os = OS.UNKNOWN; } LOGGER.info ( "Operating System: " + os.getDisplayName() ); } public String determineVersionInfo () { @SuppressWarnings("rawtypes") Enumeration resEnum; try { resEnum = Thread.currentThread().getContextClassLoader().getResources( JarFile.MANIFEST_NAME ); while ( resEnum.hasMoreElements() ) { try { URL url = (URL) resEnum.nextElement(); if ( url.getFile().toLowerCase().contains( "hypnos" ) ) { try ( InputStream is = url.openStream(); ) { if ( is != null ) { Manifest manifest = new Manifest( is ); Attributes mainAttribs = manifest.getMainAttributes(); if ( mainAttribs.getValue( "Hypnos" ) != null ) { version = mainAttribs.getValue( "Implementation-Version" ); build = mainAttribs.getValue ( "Build-Number" ); buildDate = mainAttribs.getValue ( "Build-Date" ); LOGGER.info ( "Version: " + version + ", Build: " + build + ", Build Date: " + buildDate ); } } } } } catch ( Exception e ) { // Silently ignore wrong manifests on classpath? } } } catch ( Exception e1 ) { // Silently ignore wrong manifests on classpath? } return null; } private void setupRootDirectory () { String path = FXUI.class.getProtectionDomain().getCodeSource().getLocation().getPath(); try { String decodedPath = URLDecoder.decode(path, "UTF-8"); decodedPath = decodedPath.replaceFirst("^/(.:/)", "$1"); rootDirectory = Paths.get( decodedPath ).getParent(); } catch ( UnsupportedEncodingException e ) { rootDirectory = Paths.get( path ).getParent(); } } private void setupConfigDirectory () { // PENDING: We might want to make a few fall-throughs if these locations don't exist. String home = System.getProperty( "user.home" ); if ( Hypnos.isStandalone() ) { configDirectory = getRootDirectory().resolve( "config" ); } else { final String x = File.separator; switch ( getOS() ) { case NIX: configDirectory = Paths.get( home + x + ".config/hypnos" ); break; case OSX: configDirectory = Paths.get( home + x + "Preferences" + x + "Hypnos" ); break; case WIN_10: configDirectory = Paths.get( home + x + "AppData" + x + "Local" + x + "Hypnos" ); break; case WIN_7: configDirectory = Paths.get( home + x + "AppData" + x + "Local" + x + "Hypnos" ); break; case WIN_8: configDirectory = Paths.get( home + x + "AppData" + x + "Local" + x + "Hypnos" ); break; case WIN_UNKNOWN: configDirectory = Paths.get( home + x + "AppData" + x + "Local" + x + "Hypnos" ); break; case WIN_VISTA: configDirectory = Paths.get( home + x + "AppData" + x + "Local" + x + "Hypnos" ); break; case WIN_XP: //Do nothing, windows XP not supported //configDirectory = Paths.get( home + x + "Local Settings" + x + "Application Data" + x + "Hypnos" ); break; case UNKNOWN: //Fall through default: configDirectory = Paths.get( home + x + ".hypnos" ); break; } } File configDirectory = Hypnos.getConfigDirectory().toFile(); if ( !configDirectory.exists() ) { LOGGER.info( "Config directory doesn't exist, creating: " + Hypnos.getConfigDirectory() ); try { configDirectory.mkdirs(); } catch ( Exception e ) { String message = "Unable to create config directory, data will not be saved.\n" + Hypnos.getConfigDirectory(); LOGGER.info( message ); ///TODO: Some version of a deferred ui.notifyUserError( message ); } } else if ( !configDirectory.isDirectory() ) { String message = "There is a file where the config directory should be, data will not be saved.\n" + Hypnos.getConfigDirectory(); LOGGER.info( message ); ///TODO: Some version of a deferred ui.notifyUserError( message ); } else if ( !configDirectory.canWrite() ) { String message = "Cannot write to config directory, data will not be saved.\n" + Hypnos.getConfigDirectory(); LOGGER.info( message ); ///TODO: Some version of a deferred ui.notifyUserError( message ); } } private void setupLogFile() { logFile = configDirectory.resolve( "hypnos.log" ); logFileBackup = configDirectory.resolve( "hypnos.log.1" ); logFileBackup2 = configDirectory.resolve( "hypnos.log.2" ); if ( Files.exists( logFileBackup ) ) { try { Files.move( logFileBackup, logFileBackup2, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE ); } catch ( Exception e ) { LOGGER.log ( Level.WARNING, "Unable to create 2nd backup logfile", e ); } } if ( Files.exists( logFile ) ) { try { Files.move( logFile, logFileBackup, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE ); } catch ( Exception e ) { LOGGER.log ( Level.WARNING, "Unable to create 1st backup logfile", e ); } } try { logFile.toFile().createNewFile(); } catch ( Exception e ) { LOGGER.log ( Level.WARNING, "Unable to create logfile", e ); } try { PrintWriter logOut = new PrintWriter ( new FileOutputStream ( logFile.toFile(), false ) ); String logBufferS = logBuffer.toString(); logOut.print( logBufferS ); originalErr.print ( logBufferS ); logOut.close(); } catch ( Exception e ) { LOGGER.log ( Level.WARNING, "Unable to write initial log entries to log file", e ); } try { //Remove the existing console handler Logger.getLogger( "" ).removeHandler( Logger.getLogger( "" ).getHandlers()[0] ); //restore system out and system err, but put all of them to the err channel System.setOut( originalErr ); System.setErr( originalErr ); //Add a file handler to output to logFile FileHandler fileHandler = new FileHandler( logFile.toString(), true ); fileHandler.setFormatter( logFormat ); Logger.getLogger( "" ).addHandler( fileHandler ); //Create console output ConsoleHandler consoleHandler = new ConsoleHandler(); consoleHandler.setFormatter( logFormat ); Logger.getLogger( "" ).addHandler( consoleHandler ); } catch ( IOException e ) { LOGGER.log( Level.WARNING, "Unable to setup file handler for logger.", e ); } } public static boolean globalHotkeysDisabled() { //TODO: ask hotkeys, don't keep a value in Hypnos return disableGlobalHotkeysRequestedByProperties; } public static void doHotkeyAction ( Hotkey hotkey ) { Platform.runLater( () -> { //TODO: Should this runLater() be around everything or just show_hide_ui? switch ( hotkey ) { case NEXT: audioSystem.next(); break; case PLAY: audioSystem.play(); break; case PREVIOUS: audioSystem.previous(); break; case SHOW_HIDE_UI: ui.toggleHidden(); break; case SKIP_BACK: long target = audioSystem.getPositionMS() - 5000 ; if ( target < 0 ) target = 0; audioSystem.seekMS( target ); break; case SKIP_FORWARD: audioSystem.seekMS( audioSystem.getPositionMS() + 5000 ); break; case STOP: audioSystem.stop( StopReason.USER_REQUESTED ); break; case TOGGLE_MUTE: audioSystem.toggleMute(); break; case PLAY_PAUSE: audioSystem.togglePlayPause(); break; case TOGGLE_REPEAT: audioSystem.toggleRepeatMode(); break; case TOGGLE_SHUFFLE: audioSystem.toggleShuffleMode(); break; case VOLUME_DOWN: audioSystem.decrementVolume(); break; case VOLUME_UP: audioSystem.incrementVolume(); break; default: break; } }); } public static void warnUserPlaylistsNotSaved ( ArrayList <Playlist> errors ) { ui.warnUserPlaylistsNotSaved ( errors ); } public static void warnUserAlbumsMissing ( List <Album> missing ) { ui.warnUserAlbumsMissing ( missing ); } private long setTracksLastTime = 0; public void applyCLICommands ( List <SocketCommand> commands ) { ArrayList<Path> tracksToPlay = new ArrayList<Path>(); for ( SocketCommand command : commands ) { if ( command.getType() == SocketCommand.CommandType.SET_TRACKS ) { for ( File file : (List<File>) command.getObject() ) { if ( file.isDirectory() ) { tracksToPlay.addAll( Utils.getAllTracksInDirectory( file.toPath() ) ); } else if ( Utils.isPlaylistFile( file.toPath() ) ) { //TODO: It's kind of lame to load the tracks here just to discard them and load them again a few seconds later //Maybe modify loadPlaylist so i can just ask for the specified paths, without loading tag data Playlist playlist = Playlist.loadPlaylist( file.toPath() ); for ( Track track : playlist.getTracks() ) { tracksToPlay.add( track.getPath() ); } } else if ( Utils.isMusicFile( file.toPath() ) ) { tracksToPlay.add( file.toPath() ); } else { LOGGER.log( Level.INFO, "Recived non-music, non-playlist file, ignoring: " + file, new Exception() ); } } } } if ( tracksToPlay.size() > 0 ) { if ( System.currentTimeMillis() - setTracksLastTime > 2000 ) { Platform.runLater( () -> { audioSystem.getCurrentList().setTracksPathList( tracksToPlay, new Runnable() { @Override public void run() { audioSystem.next( false ); } } ); }); } else { Platform.runLater( () -> { audioSystem.getCurrentList().appendTracksPathList ( tracksToPlay ); }); } setTracksLastTime = System.currentTimeMillis(); } for ( SocketCommand command : commands ) { if ( command.getType() == SocketCommand.CommandType.CONTROL ) { int action = (Integer)command.getObject(); Platform.runLater( () -> { switch ( action ) { case SocketCommand.NEXT: audioSystem.next(); break; case SocketCommand.PREVIOUS: audioSystem.previous(); break; case SocketCommand.PAUSE: audioSystem.pause(); break; case SocketCommand.PLAY: audioSystem.unpause(); break; case SocketCommand.TOGGLE_PAUSE: audioSystem.togglePause(); break; case SocketCommand.STOP: audioSystem.stop( StopReason.USER_REQUESTED ); break; case SocketCommand.TOGGLE_MINIMIZED: ui.toggleMinimized(); break; case SocketCommand.VOLUME_DOWN: audioSystem.decrementVolume(); break; case SocketCommand.VOLUME_UP: audioSystem.incrementVolume(); break; case SocketCommand.SEEK_BACK: long target = audioSystem.getPositionMS() - 5000 ; if ( target < 0 ) target = 0; audioSystem.seekMS( target ); break; case SocketCommand.SEEK_FORWARD: audioSystem.seekMS( audioSystem.getPositionMS() + 5000 ); break; case SocketCommand.SHOW: ui.restoreWindow(); break; } }); } } } public static void exit ( ExitCode exitCode ) { Platform.runLater( () -> ui.getMainStage().hide() ); if ( globalHotkeys != null ) { globalHotkeys.prepareToExit(); } ui.getTrayIcon().prepareToExit(); if ( audioSystem != null && ui != null ) { EnumMap <Setting, ? extends Object> fromAudioSystem = audioSystem.getSettings(); EnumMap <Setting, ? extends Object> fromUI = ui.getSettings(); audioSystem.stop ( StopReason.USER_REQUESTED ); audioSystem.releaseResources(); persister.saveAllData( fromAudioSystem, fromUI ); } System.exit ( exitCode.ordinal() ); } @Override public void stop () { exit ( ExitCode.NORMAL ); } @Override public void start ( Stage stage ) { long baseStartTime = System.currentTimeMillis(); String loadTimeMessage = "Load Time Breakdown\n"; try { long thisTaskStart = System.currentTimeMillis(); startLogToBuffer(); loadTimeMessage += "- Start Log to Buffer: " + (System.currentTimeMillis() - thisTaskStart + "\n"); thisTaskStart = System.currentTimeMillis(); thisTaskStart = System.currentTimeMillis(); parseSystemProperties(); loadTimeMessage += "- Parse System Properties: " + (System.currentTimeMillis() - thisTaskStart + "\n"); thisTaskStart = System.currentTimeMillis(); thisTaskStart = System.currentTimeMillis(); determineOS(); loadTimeMessage += "- Determine OS " + (System.currentTimeMillis() - thisTaskStart + "\n"); thisTaskStart = System.currentTimeMillis(); thisTaskStart = System.currentTimeMillis(); setupRootDirectory(); loadTimeMessage += "- Setup Root Directory: " + (System.currentTimeMillis() - thisTaskStart + "\n"); thisTaskStart = System.currentTimeMillis(); thisTaskStart = System.currentTimeMillis(); setupConfigDirectory(); loadTimeMessage += "- Setup Config Directory: " + (System.currentTimeMillis() - thisTaskStart + "\n"); thisTaskStart = System.currentTimeMillis(); thisTaskStart = System.currentTimeMillis(); determineVersionInfo(); loadTimeMessage += "- Read Version Info: " + (System.currentTimeMillis() - thisTaskStart + "\n"); thisTaskStart = System.currentTimeMillis(); thisTaskStart = System.currentTimeMillis(); String[] args = getParameters().getRaw().toArray ( new String[0] ); CLIParser parser = new CLIParser( ); ArrayList <SocketCommand> commands = parser.parseCommands( args ); loadTimeMessage += "- Parse Args: " + (System.currentTimeMillis() - thisTaskStart + "\n"); thisTaskStart = System.currentTimeMillis(); thisTaskStart = System.currentTimeMillis(); SingleInstanceController singleInstanceController = new SingleInstanceController(); if ( singleInstanceController.isFirstInstance() ) { thisTaskStart = System.currentTimeMillis(); setupLogFile(); loadTimeMessage += "- Setup Log File: " + (System.currentTimeMillis() - thisTaskStart + "\n"); thisTaskStart = System.currentTimeMillis(); thisTaskStart = System.currentTimeMillis(); library = new Library(); loadTimeMessage += "- Initialize Library: " + (System.currentTimeMillis() - thisTaskStart + "\n"); thisTaskStart = System.currentTimeMillis(); thisTaskStart = System.currentTimeMillis(); audioSystem = new AudioSystem(); loadTimeMessage += "- Initialize Audio System: " + (System.currentTimeMillis() - thisTaskStart + "\n"); thisTaskStart = System.currentTimeMillis(); thisTaskStart = System.currentTimeMillis(); globalHotkeys = new GlobalHotkeys( getOS(), disableGlobalHotkeysRequestedByProperties ); globalHotkeys.addListener( Hypnos::doHotkeyAction ); loadTimeMessage += "- Initialize Hotkeys: " + (System.currentTimeMillis() - thisTaskStart + "\n"); thisTaskStart = System.currentTimeMillis(); thisTaskStart = System.currentTimeMillis(); ui = new FXUI ( stage, library, audioSystem, globalHotkeys ); audioSystem.setUI ( ui ); library.setAudioSystem ( audioSystem ); loadTimeMessage += "- Initialize FX UI: " + (System.currentTimeMillis() - thisTaskStart + "\n"); thisTaskStart = System.currentTimeMillis(); thisTaskStart = System.currentTimeMillis(); persister = new Persister ( ui, library, audioSystem, globalHotkeys ); loadTimeMessage += "- Initialize Persister: " + (System.currentTimeMillis() - thisTaskStart + "\n"); thisTaskStart = System.currentTimeMillis(); switch ( getOS() ) { case NIX: case OSX: { EnumMap <Setting, String> pendingSettings = persister.loadSettingsFromDisk(); persister.loadCurrentList(); ui.applySettingsBeforeWindowShown( pendingSettings ); if ( pendingSettings.containsKey( Setting.LOADER_SPEED ) ) { Hypnos.setLoaderSpeed( LoaderSpeed.valueOf( pendingSettings.get( Setting.LOADER_SPEED ) ) ); pendingSettings.remove( Setting.LOADER_SPEED ); } else { Hypnos.setLoaderSpeed(LoaderSpeed.HIGH); } ui.setLibraryLabelsToLoading(); ui.showMainWindow(); Thread finishLoadingThread = new Thread ( () -> { Platform.runLater( () -> { ui.applySettingsAfterWindowShown( pendingSettings ); persister.logUnusedSettings ( pendingSettings ); }); boolean sourcesLoaded = persister.loadRoots(); if ( sourcesLoaded ) { persister.loadAlbumsAndTracks(); } audioSystem.applySettings ( pendingSettings ); persister.loadQueue(); audioSystem.linkQueueToCurrentList(); persister.loadHistory(); persister.loadPlaylists(); persister.loadHotkeys(); Platform.runLater( () -> ui.getLibraryPane().updatePlaceholders() ); ui.refreshHotkeyList(); applyCLICommands( commands ); singleInstanceController.startCLICommandListener ( this ); library.setUI( ui ); library.startThreads(); LOGGER.info( "Hypnos finished loading." ); UpdateChecker updater = new UpdateChecker(); boolean updateAvailable = updater.updateAvailable(); if ( updateAvailable ) LOGGER.info( "Updates available" ); ui.setUpdateAvailable ( updateAvailable ); try { Thread.sleep ( 2000 ); } catch ( InterruptedException e ) {} ui.fixTables(); } ); finishLoadingThread.setName ( "Hypnos Load Finisher for Nix" ); finishLoadingThread.setDaemon( false ); finishLoadingThread.start(); } break; case UNKNOWN: case WIN_10: case WIN_7: case WIN_8: case WIN_UNKNOWN: case WIN_VISTA:{ thisTaskStart = System.currentTimeMillis(); EnumMap <Setting, String> pendingSettings = persister.loadSettingsFromDisk(); loadTimeMessage += "- Read Settings from Disk: " + (System.currentTimeMillis() - thisTaskStart + "\n"); thisTaskStart = System.currentTimeMillis(); thisTaskStart = System.currentTimeMillis(); persister.loadCurrentList(); loadTimeMessage += "- Read Current List from Disk " + (System.currentTimeMillis() - thisTaskStart + "\n"); thisTaskStart = System.currentTimeMillis(); thisTaskStart = System.currentTimeMillis(); audioSystem.applySettings ( pendingSettings ); if ( pendingSettings.containsKey( Setting.LOADER_SPEED ) ) { Hypnos.setLoaderSpeed( LoaderSpeed.valueOf( pendingSettings.get( Setting.LOADER_SPEED ) ) ); pendingSettings.remove( Setting.LOADER_SPEED ); } else { Hypnos.setLoaderSpeed(LoaderSpeed.HIGH); } ui.applySettingsBeforeWindowShown( pendingSettings ); ui.applySettingsAfterWindowShown( pendingSettings ); persister.logUnusedSettings ( pendingSettings ); loadTimeMessage += "- Apply Settings: " + (System.currentTimeMillis() - thisTaskStart + "\n"); thisTaskStart = System.currentTimeMillis(); boolean sourcesLoaded = persister.loadRoots(); if ( sourcesLoaded ) { persister.loadAlbumsAndTracks(); } loadTimeMessage += "- Load Albums and Tracks: " + (System.currentTimeMillis() - thisTaskStart + "\n"); thisTaskStart = System.currentTimeMillis(); persister.loadQueue(); loadTimeMessage += "- Load Queue from Disk: " + (System.currentTimeMillis() - thisTaskStart + "\n"); thisTaskStart = System.currentTimeMillis(); audioSystem.linkQueueToCurrentList(); loadTimeMessage += "- Link Queue to current list: " + (System.currentTimeMillis() - thisTaskStart + "\n"); thisTaskStart = System.currentTimeMillis(); persister.loadHistory(); loadTimeMessage += "- Load History: " + (System.currentTimeMillis() - thisTaskStart + "\n"); thisTaskStart = System.currentTimeMillis(); persister.loadPlaylists(); loadTimeMessage += "- Load Playlists: " + (System.currentTimeMillis() - thisTaskStart + "\n"); thisTaskStart = System.currentTimeMillis(); persister.loadHotkeys(); loadTimeMessage += "- Load Hotkeys: " + (System.currentTimeMillis() - thisTaskStart + "\n"); thisTaskStart = System.currentTimeMillis(); applyCLICommands( commands ); singleInstanceController.startCLICommandListener ( this ); loadTimeMessage += "- Apply CLI Commands: " + (System.currentTimeMillis() - thisTaskStart + "\n"); thisTaskStart = System.currentTimeMillis(); library.setUI( ui ); library.startThreads(); persister.startThread(); loadTimeMessage += "- Start background threads: " + (System.currentTimeMillis() - thisTaskStart + "\n"); thisTaskStart = System.currentTimeMillis(); ui.showMainWindow(); loadTimeMessage += "- Show UI: " + (System.currentTimeMillis() - thisTaskStart + "\n"); thisTaskStart = System.currentTimeMillis(); ui.getLibraryPane().updatePlaceholders(); ui.fixTables(); ui.settingsWindow.refreshHotkeyFields(); loadTimeMessage += "- Post show UI fixes: " + (System.currentTimeMillis() - thisTaskStart + "\n"); loadTimeMessage += "Total Load Time: " + (System.currentTimeMillis() - baseStartTime); LOGGER.info(loadTimeMessage); LOGGER.info( "Hypnos finished loading." ); UpdateChecker updater = new UpdateChecker(); if ( updater.updateAvailable() ) { LOGGER.info( "Updates available" ); } } break; case WIN_XP: default: { LOGGER.log(Level.SEVERE, "Operating System not supported, exiting."); exit(ExitCode.UNSUPPORTED_OS); } } } else { boolean gotResponse = singleInstanceController.sendCommandsThroughSocket( commands ); if ( commands.size() > 0 ) { originalOut.println ( "Commands sent to currently running Hypnos." ); } else if ( gotResponse ) { singleInstanceController.sendCommandsThroughSocket( Arrays.asList( new SocketCommand ( SocketCommand.CommandType.CONTROL, SocketCommand.SHOW ) )); originalOut.println ( "Hypnos is already running, brought to front." ); } else { FXUI.notifyUserHypnosNonResponsive(); } System.exit ( 0 ); //We don't use Hypnos.exit here intentionally. } } catch ( Exception e ) { LOGGER.log( Level.SEVERE, e.getClass() + ": Exception caught at top level of Hypnos. Exiting.", e ); exit ( ExitCode.UNKNOWN_ERROR ); } } public static void main ( String[] args ) { launch( args ); //This calls start() } }
29,850
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
PreviousStack.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/PreviousStack.java
package net.joshuad.hypnos; import java.util.ArrayList; import java.util.List; import net.joshuad.hypnos.library.Track; /* * Guarantees: * - No null tracks in the stack * - It's impossible for the same track to appear twice or more consecutively. */ public class PreviousStack { private static final int MAX_PREVIOUS_NEXT_STACK_SIZE = 1000; private final ArrayList <Track> stack = new ArrayList <Track>( MAX_PREVIOUS_NEXT_STACK_SIZE ); public synchronized void addToStack ( Track track ) { synchronized ( stack ) { if ( track == null ) return; if ( stack.size() > 0 && track.equals( stack.get( 0 ) ) ) return; while ( stack.size() >= MAX_PREVIOUS_NEXT_STACK_SIZE ) { stack.remove( stack.size() - 1 ); } stack.add( 0, track ); } } public synchronized Track removePreviousTrack ( Track currentTrack ) { if ( stack.isEmpty() ) return null; Track retMe = stack.remove( 0 ); if ( retMe.equals( currentTrack ) ) { if ( stack.isEmpty() ) { return null; } else { retMe = stack.remove( 0 ); } } return retMe; } public int size() { return stack.size(); } public boolean isEmpty () { return stack.isEmpty(); } public List<Track> subList ( int fromIndex, int toIndex ) { return stack.subList( fromIndex, toIndex ); } public List<Track> getData () { return stack; } }
1,384
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
CurrentListTrack.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/CurrentListTrack.java
package net.joshuad.hypnos; import java.io.IOException; import java.io.ObjectInputStream; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleObjectProperty; import net.joshuad.hypnos.library.Track; public class CurrentListTrack extends Track { @SuppressWarnings("unused") private static final Logger LOGGER = Logger.getLogger(CurrentListTrack.class.getName()); private static final long serialVersionUID = 1L; private boolean isCurrentTrack = false; private boolean lastCurrentListTrack = false; private List<Integer> queueIndex = new ArrayList<Integer>(); private transient BooleanProperty fileIsMissing = new SimpleBooleanProperty(false); private transient ObjectProperty<CurrentListTrackState> displayState = new SimpleObjectProperty<CurrentListTrackState>(new CurrentListTrackState(isCurrentTrack, queueIndex)); private boolean needsUpdateFromDisk = false; public CurrentListTrack(Path source) { super(source, false); } public CurrentListTrack(Track source) { super(source); needsUpdateFromDisk = true; } public boolean needsUpdateFromDisk() { return needsUpdateFromDisk; } public void setNeedsUpdateFromDisk(boolean needsUpdate) { this.needsUpdateFromDisk = needsUpdate; } public void update() { refreshTagData(); needsUpdateFromDisk = false; } public void setIsCurrentTrack(boolean isCurrentTrack) { this.isCurrentTrack = isCurrentTrack; updateDisplayState(); } public boolean getIsCurrentTrack() { return isCurrentTrack; } public void setIsLastCurrentListTrack(boolean last) { this.lastCurrentListTrack = last; } public boolean isLastCurrentListTrack() { return lastCurrentListTrack; } public List<Integer> getQueueIndices() { return queueIndex; } public void clearQueueIndex() { queueIndex.clear(); updateDisplayState(); } public void addQueueIndex(Integer index) { queueIndex.add(index); updateDisplayState(); } public BooleanProperty fileIsMissingProperty() { return fileIsMissing; } public boolean isMissingFile() { return fileIsMissing.getValue(); } public void setIsMissingFile(boolean missing) { fileIsMissing.set(missing); if (missing) { setIsCurrentTrack(false); } } private void updateDisplayState() { displayState.setValue(new CurrentListTrackState(isCurrentTrack, queueIndex)); } public ObjectProperty<CurrentListTrackState> displayStateProperty() { return displayState; } @Override public void refreshTagData() { super.refreshTagData(); for (Track track : Hypnos.getLibrary().getTrackData()) { if (track.equals(this)) { track.refreshTagData(); if(track.getAlbum() != null) { track.getAlbum().updateData(); } this.setAlbum(track.getAlbum()); } } } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); fileIsMissing = new SimpleBooleanProperty(false); queueIndex = new ArrayList<Integer>(); displayState = new SimpleObjectProperty<CurrentListTrackState>(new CurrentListTrackState(isCurrentTrack, queueIndex)); } }
3,302
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
HypnosURLS.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/HypnosURLS.java
package net.joshuad.hypnos; public class HypnosURLS { //TODO: Move the other urls to here. Settings window has a lot of them, maybe all? public static final String HELP_INOTIFY = "http://hypnosplayer.org/help/linux-inotify-count"; public static final String DDG_IMAGE_SEARCH = "https://duckduckgo.com/?iax=images&ia=images&q="; public static final String DDG_SEARCH = "https://duckduckgo.com/?q="; public static String getDDGSearchURL(String searchTerms) { return DDG_SEARCH + searchTerms.replaceAll(" ", "+"); } }
530
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
MultiFileImageTagPair.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/MultiFileImageTagPair.java
package net.joshuad.hypnos; import java.util.Arrays; import java.util.logging.Level; import java.util.logging.Logger; public class MultiFileImageTagPair { private static transient final Logger LOGGER = Logger.getLogger( MultiFileImageTagPair.class.getName() ); public static final byte[] MULTI_VALUE = new byte[] { 1, 3, 5, 8, 13, 21, 34, 55, 89 }; public enum ImageFieldKey { ALBUM_FRONT, ARTIST, ALBUM_OTHER, ALBUM_MEDIA, ARTIST_LEAD, ARTIST_ILLUSTRATION, ARTIST_LOGO; public static ImageFieldKey getKeyFromTagIndex ( int index ) { if ( index == 3 ) return ALBUM_FRONT; if ( index == 0 ) return ALBUM_OTHER; if ( index == 6 ) return ALBUM_MEDIA; if ( index == 8 ) return ARTIST; if ( index == 7 ) return ARTIST_LEAD; if ( index == 12 ) return ARTIST_ILLUSTRATION; if ( index == 13 ) return ARTIST_LOGO; return null; } public static int getIndexFromKey ( ImageFieldKey key ) { switch ( key ) { case ALBUM_FRONT: return 3; case ALBUM_OTHER: return 0; case ALBUM_MEDIA: return 6; case ARTIST: return 8; case ARTIST_LEAD: return 7; case ARTIST_ILLUSTRATION: return 12; case ARTIST_LOGO: return 13; default: return -1; //Tis can never happen } } } private ImageFieldKey key; private byte[] imageData; boolean multiValue = false; boolean imageDataChanged = false; public MultiFileImageTagPair ( ImageFieldKey key, byte[] imageData ) { this.key = key; this.imageData = imageData; } public void setImageData ( byte[] imageData ) { imageDataChanged = true; this.imageData = imageData; multiValue = false; } public void anotherFileValue ( byte[] newImageData ) { if ( !Arrays.equals( imageData, newImageData ) ) { multiValue = true; } } public boolean isMultiValue () { return multiValue; } public boolean imageDataChanged() { return imageDataChanged; } public String getTagName () { switch ( key ) { case ALBUM_FRONT: return "COVER"; case ALBUM_MEDIA: return "MEDIA"; case ALBUM_OTHER: return "ALBUM OTHER"; case ARTIST: return "ARTIST"; case ARTIST_ILLUSTRATION: return "ARTIST ILLUSTRATION"; case ARTIST_LEAD: return "ARTIST LEAD"; case ARTIST_LOGO: return "ARTIST LOGO"; default: LOGGER.log ( Level.WARNING, "This should never happen. Key type: " + key.name(), new Exception() ); return "NO NAME"; } } public ImageFieldKey getKey() { return key; } public byte[] getImageData () { if ( multiValue ) { return MULTI_VALUE; } else { return imageData; } } }
2,580
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
CurrentListTrackState.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/CurrentListTrackState.java
package net.joshuad.hypnos; import java.util.List; public class CurrentListTrackState { private boolean isCurrentTrack = false; private List <Integer> queueIndices; public CurrentListTrackState ( boolean isCurrentTrack, List <Integer> queueIndices ) { this.isCurrentTrack = isCurrentTrack; this.queueIndices = queueIndices; } public List <Integer> getQueueIndices () { return queueIndices; } public boolean getIsCurrentTrack () { return isCurrentTrack; } }
483
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
CurrentListListener.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/CurrentListListener.java
package net.joshuad.hypnos; public interface CurrentListListener { public void stateChanged ( CurrentListState state ); }
125
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
Utils.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/Utils.java
package net.joshuad.hypnos; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.DirectoryStream; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; import net.joshuad.hypnos.library.Track; import net.joshuad.hypnos.library.Track.Format; public class Utils { private static transient final Logger LOGGER = Logger.getLogger(Utils.class.getName()); private static String[] imageExtStrings = new String[] { "jpg", "jpeg", "png", "gif" }; private static String[] playlistExtStrings = new String[] { "m3u" }; public static final DirectoryStream.Filter<Path> musicFileFilter = new DirectoryStream.Filter<Path>() { @Override public boolean accept(Path entry) throws IOException { return isMusicFile(entry); } }; public static boolean hasImageExtension(String url) { String testExtension = url.substring(url.lastIndexOf(".") + 1).toLowerCase(); for (String imageExtension : imageExtStrings) { if (imageExtension.toLowerCase().equals(testExtension)) { return true; } } return false; } public static boolean isChildOf(Path potentialChild, Path parent) { parent = parent.normalize().toAbsolutePath(); Path test = potentialChild.getParent(); while (test != null) { if (test.equals(parent)) { return true; } test = test.getParent(); } return false; } public static boolean isImageFile(File testFile) { return isImageFile(testFile.toPath()); } public static boolean isImageFile(Path testFile) { String fileName = testFile.getFileName().toString(); if (!Files.exists(testFile)) { return false; } else if (!Files.isRegularFile(testFile)) { return false; } else if (fileName.lastIndexOf(".") == -1 || fileName.lastIndexOf(".") == 0) { return false; } return hasImageExtension(fileName); } public static String toReleaseTitleCase(String input) { if (input.equalsIgnoreCase("EP")) { return "EP"; } else { StringBuilder titleCase = new StringBuilder(); boolean nextTitleCase = true; for (char c : input.toCharArray()) { if (Character.isSpaceChar(c)) { nextTitleCase = true; } else if (nextTitleCase) { c = Character.toTitleCase(c); nextTitleCase = false; } titleCase.append(c); } return titleCase.toString(); } } public static boolean isMusicFile(String testFile) { return isMusicFile(Paths.get(testFile)); } public static boolean isMusicFile(Path testFile) { if (testFile == null) { LOGGER.log(Level.INFO, "Asked if a null path was a music file, returning false.", new NullPointerException()); return false; } String fileName = testFile.getFileName().toString(); if (!Files.exists(testFile)) { return false; } else if (!Files.isRegularFile(testFile)) { return false; } else if (fileName.lastIndexOf(".") == -1 || fileName.lastIndexOf(".") == 0) { return false; } else if (fileName.startsWith("._")) { return false; } String testExtension = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); Format format = Format.getFormat(testExtension); return format != null; } public static boolean isPlaylistFile(Path testFile) { String fileName = testFile.getFileName().toString(); if (!Files.exists(testFile)) { return false; } else if (!Files.isRegularFile(testFile)) { return false; } else if (fileName.lastIndexOf(".") == -1 || fileName.lastIndexOf(".") == 0) { return false; } String testExtension = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); for (String playlistExtension : playlistExtStrings) { if (playlistExtension.toLowerCase().equals(testExtension)) { return true; } } return false; } public static String getFileExtension(Path path) { return getFileExtension(path.toFile()); } public static String getFileExtension(File file) { String name = file.getName(); try { return name.substring(name.lastIndexOf(".") + 1); } catch (Exception e) { return ""; } } public static String getLengthDisplay(int lengthSeconds) { boolean negative = lengthSeconds < 0; lengthSeconds = Math.abs(lengthSeconds); int hours = lengthSeconds / 3600; int minutes = (lengthSeconds % 3600) / 60; int seconds = lengthSeconds % 60; if (hours > 0) { return String.format((negative ? "-" : "") + "%d:%02d:%02d", hours, minutes, seconds); } else { return String.format((negative ? "-" : "") + "%d:%02d", minutes, seconds); } } public static ArrayList<CurrentListTrack> convertTrackList(List<Track> tracks) { ArrayList<CurrentListTrack> retMe = new ArrayList<CurrentListTrack>(tracks.size()); for (Track track : tracks) { if (track instanceof CurrentListTrack) { retMe.add((CurrentListTrack) track); } else { retMe.add(new CurrentListTrack(track)); } } return retMe; } public static ArrayList<Track> convertCurrentTrackList(List<CurrentListTrack> tracks) { ArrayList<Track> retMe = new ArrayList<Track>(tracks.size()); for (CurrentListTrack track : tracks) { retMe.add((Track) track); } return retMe; } public static String prepareArtistForCompare(String string) { return string.toLowerCase().replaceAll(" & ", " and ").replaceAll("&", " and ").replaceAll(" \\+ ", " and ") .replaceAll("\\+", " and ").replaceAll(" ", " ").replaceAll(" the ", "").replaceAll("^the ", "") .replaceAll(", the$", "").replaceAll("-", " ").replaceAll("\\.", "").replaceAll("_", " "); } public static String prepareAlbumForCompare(String string) { return string.toLowerCase(); } public static ArrayList<Path> getAllTracksInDirectory(Path startingDirectory) { TrackFinder finder = new TrackFinder(); try { Files.walkFileTree(startingDirectory, finder); return finder.trackPaths; } catch (Exception e) { LOGGER.log(Level.WARNING, "Read error while traversing directory, some files may not have been loaded: " + startingDirectory.toString(), e); } return new ArrayList<Path>(); } public static boolean saveImageToDisk(Path location, byte[] buffer) { if (location == null) { return false; } InputStream in = new ByteArrayInputStream(buffer); try { BufferedImage bImage = ImageIO.read(in); ImageIO.write(bImage, "png", location.toFile()); return true; } catch (Exception e) { LOGGER.log(Level.WARNING, "Unable to save image to location: " + location, e); } return false; } } class TrackFinder extends SimpleFileVisitor<Path> { ArrayList<Path> trackPaths = new ArrayList<Path>(); ArrayList<Path> addMe = new ArrayList<Path>(); @Override public FileVisitResult visitFile(Path path, BasicFileAttributes attr) { boolean isMusicFile = Utils.isMusicFile(path); if (isMusicFile) { addMe.add(path); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) { Collections.sort(addMe); trackPaths.addAll(addMe); addMe.clear(); return FileVisitResult.CONTINUE; } public FileVisitResult visitFileFailed(Path file, IOException exc) { return FileVisitResult.CONTINUE; } }
7,480
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
Queue.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/Queue.java
package net.joshuad.hypnos; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import net.joshuad.hypnos.library.Album; import net.joshuad.hypnos.library.Artist; import net.joshuad.hypnos.library.Playlist; import net.joshuad.hypnos.library.Track; public class Queue { private static final Logger LOGGER = Logger.getLogger( Queue.class.getName() ); final private ObservableList <Track> queue = FXCollections.observableArrayList ( new ArrayList <Track>() ); transient private boolean hasUnsavedData = true; public Queue() { queue.addListener( (ListChangeListener.Change<? extends Track> change) -> { hasUnsavedData = true; }); } public boolean hasUnsavedData() { return hasUnsavedData; } public void setHasUnsavedData( boolean b ) { hasUnsavedData = b; } public synchronized void queueTrack ( Track track ) { queueTrack ( queue.size(), track ); } public synchronized void queueTrack ( int index, Track track ) { if ( index < 0 ) { LOGGER.log ( Level.INFO, "Asked to add a track at index: " + index + ", adding at 0 instead.", new Exception() ); index = 0; } if ( index > queue.size() ) { LOGGER.log ( Level.INFO, "Asked to add a track at index: " + index + ", which is beyond the end of the queue. Adding at the end instead.", new Exception() ); index = queue.size(); } queue.add( index, track ); updateQueueIndexes(); } public synchronized void queueAllAlbums ( List<? extends Album> albums ) { for ( Album album : albums ) { queueAllTracks( album.getTracks() ); } } public synchronized void queueAllAlbums ( List<? extends Album> albums, int index ) { List <Track> tracks = new ArrayList <Track> (); for ( Album album : albums ) { tracks.addAll ( album.getTracks() ); } queueAllTracks( tracks, index ); } public synchronized void queueAllPlaylists ( List<? extends Playlist> playlists ) { for ( Playlist playlist : playlists ) { queueAllTracks ( playlist.getTracks() ); } } public synchronized void queueAllPlaylists ( List<? extends Playlist> playlists, int index ) { List <Track> tracks = new ArrayList <Track> (); for ( Playlist playlist : playlists ) { tracks.addAll ( playlist.getTracks() ); } queueAllTracks( tracks, index ); } public synchronized void queueAllTracks ( List<? extends Track> tracks ) { for ( Track track : tracks ) { queueTrack ( track ); } } public synchronized void queueAllTracks ( List<? extends Track> tracks, int index ) { if ( index < 0 ) { LOGGER.log ( Level.INFO, "Asked to add a tracks at index: " + index + ", adding at 0 instead.", new Exception() ); index = 0; } if ( index > queue.size() ) { LOGGER.log ( Level.INFO, "Asked to add a tracks at index: " + index + ", which is beyond the end of the queue. Adding at the end instead.", new Exception() ); index = queue.size(); } for ( int k = 0; k < tracks.size(); k++ ) { queueTrack ( index + k, tracks.get ( k ) ); } } public synchronized void updateQueueIndexes () { updateQueueIndexes ( new ArrayList<Track> () ); } public synchronized void updateQueueIndexes( Track removedTrack ) { updateQueueIndexes ( Arrays.asList( removedTrack ) ); } public synchronized void updateQueueIndexes( List<Track> removedTracks ) { for ( Track removedTrack : removedTracks ) { if ( removedTrack != null && removedTrack instanceof CurrentListTrack ) { ((CurrentListTrack)removedTrack).clearQueueIndex(); } } for ( int k = 0; k < queue.size(); k++ ) { if ( queue.get( k ) instanceof CurrentListTrack ) { CurrentListTrack track = (CurrentListTrack)queue.get( k ); track.clearQueueIndex(); } } for ( int k = 0; k < queue.size(); k++ ) { if ( queue.get( k ) instanceof CurrentListTrack ) { CurrentListTrack track = (CurrentListTrack)queue.get( k ); track.addQueueIndex( k + 1 ); } } } public synchronized Track get ( int index ) { return queue.get( index ); } public synchronized int size () { return queue.size(); } public synchronized void remove ( int index ) { if ( index >= 0 && index < queue.size() ) { Track removedTrack = queue.remove( index ); updateQueueIndexes( removedTrack ); } } public synchronized boolean hasNext() { return ( !queue.isEmpty() ); } public synchronized boolean isEmpty() { return queue.isEmpty(); } public synchronized Track getNextTrack ( ) { if ( queue.isEmpty() ) { return null; } Track nextTrack = queue.remove ( 0 ); updateQueueIndexes( nextTrack ); return nextTrack; } public synchronized ObservableList<Track> getData() { return queue; } public void clear() { for ( Track removedTrack : queue ) { if ( removedTrack != null && removedTrack instanceof CurrentListTrack ) { ((CurrentListTrack)removedTrack).clearQueueIndex(); } } queue.clear(); } public void queueAllArtists ( ObservableList <Artist> artists, int index ) { List<Track> tracks = new ArrayList<> (); for ( Artist artist : artists ) { tracks.addAll( artist.getAllTracks() ); } queueAllTracks ( tracks, index ); } public void queueAllArtists ( List <Artist> artists ) { List<Track> tracks = new ArrayList<> (); for ( Artist artist : artists ) { tracks.addAll( artist.getAllTracks() ); } queueAllTracks ( tracks ); } }
5,601
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
SocketCommand.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/SocketCommand.java
package net.joshuad.hypnos; import java.io.Serializable; public class SocketCommand implements Serializable { private static final long serialVersionUID = 1L; public enum CommandType { CONTROL, SET_TRACKS } //REFACTOR: Maybe change these to enums public static final int NEXT = 0; public static final int PREVIOUS = 1; public static final int PAUSE = 2; public static final int PLAY = 3; public static final int TOGGLE_PAUSE = 4; public static final int STOP = 5; public static final int TOGGLE_MINIMIZED = 6; public static final int VOLUME_DOWN = 7; public static final int VOLUME_UP = 8; public static final int SEEK_FORWARD = 9; public static final int SEEK_BACK = 10; public static final int SHOW = 11; public static final int RECEIPT_ACKNOWLEDGED = 12; private CommandType type; private Object object; public SocketCommand ( CommandType type, Object object ) { this.type = type; this.object = object; } public CommandType getType () { return type; } public Object getObject() { return object; } }
1,047
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
Persister.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/Persister.java
package net.joshuad.hypnos; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.PrintWriter; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.Arrays; import java.util.EnumMap; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import net.joshuad.hypnos.audio.AudioSystem; import net.joshuad.hypnos.fxui.FXUI; import net.joshuad.hypnos.hotkeys.GlobalHotkeys; import net.joshuad.hypnos.hotkeys.GlobalHotkeys.Hotkey; import net.joshuad.hypnos.library.Album; import net.joshuad.hypnos.library.Library; import net.joshuad.hypnos.library.MusicRoot; import net.joshuad.hypnos.library.Playlist; import net.joshuad.hypnos.library.Track; import net.joshuad.hypnos.hotkeys.HotkeyState; public class Persister { private static final Logger LOGGER = Logger.getLogger( Persister.class.getName() ); private static final int SAVE_ALL_INTERVAL = 10000; public enum Setting { SHUFFLE, REPEAT, HIDE_ALBUM_TRACKS, WINDOW_MAXIMIZED, PRIMARY_SPLIT_PERCENT, ART_CURRENT_SPLIT_PERCENT, ART_SPLIT_PERCENT, WINDOW_X_POSITION, WINDOW_Y_POSITION, WINDOW_WIDTH, WINDOW_HEIGHT, TRACK, TRACK_POSITION, TRACK_NUMBER, VOLUME, PROMPT_BEFORE_OVERWRITE, SHOW_INOTIFY_ERROR_POPUP, SHOW_UPDATE_AVAILABLE_IN_MAIN_WINDOW, SHOW_SYSTEM_TRAY_ICON, CLOSE_TO_SYSTEM_TRAY, MINIMIZE_TO_SYSTEM_TRAY, THEME, LOADER_SPEED, DEFAULT_SHUFFLE_ALBUMS, DEFAULT_SHUFFLE_TRACKS, DEFAULT_SHUFFLE_PLAYLISTS, DEFAULT_REPEAT_ALBUMS, DEFAULT_REPEAT_TRACKS, DEFAULT_REPEAT_PLAYLISTS, AR_TABLE_ARTIST_COLUMN_SHOW, AR_TABLE_ALBUMS_COLUMN_SHOW, AR_TABLE_TRACKS_COLUMN_SHOW, AR_TABLE_LENGTH_COLUMN_SHOW, AL_TABLE_ARTIST_COLUMN_SHOW, AL_TABLE_YEAR_COLUMN_SHOW, AL_TABLE_ALBUM_COLUMN_SHOW, AL_TABLE_ADDED_COLUMN_SHOW, TR_TABLE_ARTIST_COLUMN_SHOW, TR_TABLE_NUMBER_COLUMN_SHOW, TR_TABLE_TITLE_COLUMN_SHOW, TR_TABLE_ALBUM_COLUMN_SHOW, TR_TABLE_LENGTH_COLUMN_SHOW, PL_TABLE_PLAYLIST_COLUMN_SHOW, PL_TABLE_TRACKS_COLUMN_SHOW, PL_TABLE_LENGTH_COLUMN_SHOW, CL_TABLE_PLAYING_COLUMN_SHOW, CL_TABLE_NUMBER_COLUMN_SHOW, CL_TABLE_ARTIST_COLUMN_SHOW, CL_TABLE_YEAR_COLUMN_SHOW, CL_TABLE_ALBUM_COLUMN_SHOW, CL_TABLE_TITLE_COLUMN_SHOW, CL_TABLE_LENGTH_COLUMN_SHOW, AR_TABLE_ARTIST_COLUMN_WIDTH, AR_TABLE_ALBUMS_COLUMN_WIDTH, AR_TABLE_TRACKS_COLUMN_WIDTH, AR_TABLE_LENGTH_COLUMN_WIDTH, AL_TABLE_ARTIST_COLUMN_WIDTH, AL_TABLE_YEAR_COLUMN_WIDTH, AL_TABLE_ALBUM_COLUMN_WIDTH, AL_TABLE_ADDED_COLUMN_WIDTH, TR_TABLE_ARTIST_COLUMN_WIDTH, TR_TABLE_NUMBER_COLUMN_WIDTH, TR_TABLE_TITLE_COLUMN_WIDTH, TR_TABLE_ALBUM_COLUMN_WIDTH, TR_TABLE_LENGTH_COLUMN_WIDTH, PL_TABLE_PLAYLIST_COLUMN_WIDTH, PL_TABLE_TRACKS_COLUMN_WIDTH, PL_TABLE_LENGTH_COLUMN_WIDTH, CL_TABLE_PLAYING_COLUMN_WIDTH, CL_TABLE_NUMBER_COLUMN_WIDTH, CL_TABLE_ARTIST_COLUMN_WIDTH, CL_TABLE_YEAR_COLUMN_WIDTH, CL_TABLE_ALBUM_COLUMN_WIDTH, CL_TABLE_TITLE_COLUMN_WIDTH, CL_TABLE_LENGTH_COLUMN_WIDTH, LIBRARY_TAB_ARTISTS_VISIBLE, LIBRARY_TAB_ALBUMS_VISIBLE, LIBRARY_TAB_TRACKS_VISIBLE, LIBRARY_TAB_PLAYLISTS_VISIBLE, LIBRARY_TAB, //Library Tab has to come after visible toggle //This is dumb, but column order has to come before sort order in this list //so column order is applied first, so it doesn't mess up sort order. ARTIST_COLUMN_ORDER, ARTIST_SORT_ORDER, ALBUM_COLUMN_ORDER, ALBUM_SORT_ORDER, TRACK_COLUMN_ORDER, TRACK_SORT_ORDER, PLAYLIST_COLUMN_ORDER, PLAYLIST_SORT_ORDER, CL_COLUMN_ORDER, CL_SORT_ORDER, LASTFM_USERNAME, LASTFM_PASSWORD_MD5, LASTFM_SCROBBLE_ON_PLAY, LASTFM_SCROBBLE_TIME, SHOW_LASTFM_IN_UI, ; } private File sourcesFile; private File playlistsDirectory; private File currentFile; private File queueFile; private File historyFile; private File dataFile; private File settingsFile; private File hotkeysFile; private FXUI ui; private AudioSystem audioSystem; private Library library; private GlobalHotkeys hotkeys; public Persister ( FXUI ui, Library library, AudioSystem audioSystem, GlobalHotkeys hotkeys ) { this.ui = ui; this.audioSystem = audioSystem; this.library = library; this.hotkeys = hotkeys; File configDirectory = Hypnos.getConfigDirectory().toFile(); sourcesFile = new File( configDirectory + File.separator + "sources" ); playlistsDirectory = new File( configDirectory + File.separator + "playlists" ); currentFile = new File( configDirectory + File.separator + "current" ); queueFile = new File( configDirectory + File.separator + "queue" ); historyFile = new File( configDirectory + File.separator + "history" ); dataFile = new File( configDirectory + File.separator + "data" ); settingsFile = new File( configDirectory + File.separator + "settings" ); hotkeysFile = new File( configDirectory + File.separator + "hotkeys" ); createNecessaryFolders(); } private void createNecessaryFolders () { if ( playlistsDirectory.exists() && !playlistsDirectory.isDirectory() ) { try { Files.delete( playlistsDirectory.toPath() ); LOGGER.info( "Playlists directory location existed but was not a directory. Removed: " + playlistsDirectory.toString() ); } catch ( IOException e ) { ui.notifyUserError( "Playlist directory (" + playlistsDirectory + ") exists but is not a directory.\n\nPlaylist data will not be saved." ); LOGGER.warning( "Playlists directory exists but is a normal file, and I can't remove it." + " Playlist data may be lost after program is terminated." + playlistsDirectory.toString() ); } } if ( !playlistsDirectory.exists() ) { boolean playlistDirCreated = playlistsDirectory.mkdirs(); if ( playlistDirCreated ) { LOGGER.info( "Playlist directory did not exist. Created: " + playlistsDirectory.toString() ); } else { ui.notifyUserError( "Cannot create playlist directory (" + playlistsDirectory + ").\n\nPlaylist data will not be saved." ); LOGGER.warning( "Cannot create playlists directory. Playlist data may be lost after program is terminated." + playlistsDirectory.toString() ); } } } public void saveAllData( EnumMap <Setting, ? extends Object> fromAudioSystem, EnumMap <Setting, ? extends Object> fromUI ) { createNecessaryFolders(); saveAlbumsAndTracks(); saveRoots(); saveCurrentList(); saveQueue(); saveHistory(); saveLibraryPlaylists(); saveSettings( fromAudioSystem, fromUI ); saveHotkeys(); } public void saveSettings () { EnumMap <Setting, ? extends Object> fromAudioSystem = audioSystem.getSettings(); EnumMap <Setting, ? extends Object> fromUI = ui.getSettings(); saveSettings ( fromAudioSystem, fromUI ); } public boolean loadRoots () { try ( ObjectInputStream rootsIn = new ObjectInputStream( new FileInputStream( sourcesFile ) ); ) { ArrayList <MusicRoot> musicRoots = (ArrayList <MusicRoot>) rootsIn.readObject(); library.setMusicRootsOnInitialLoad( musicRoots ); return true; } catch ( Exception e ) { LOGGER.log( Level.INFO, "Unable to read library directory list from disk, continuing.", e); } return false; } public void loadCurrentList() { try ( ObjectInputStream dataIn = new ObjectInputStream( new FileInputStream( currentFile ) ) ) { audioSystem.getCurrentList().setState ( (CurrentListState)dataIn.readObject() ); audioSystem.getCurrentList().setHasUnsavedData( false ); } catch ( Exception e ) { try ( ObjectInputStream dataIn = new ObjectInputStream( new GZIPInputStream( new FileInputStream( currentFile ) ) ) ) { audioSystem.getCurrentList().setState ( (CurrentListState)dataIn.readObject() ); audioSystem.getCurrentList().setHasUnsavedData( false ); } catch ( Exception e2 ) { LOGGER.log( Level.INFO, "Unable to read library data from disk, continuing.", e2 ); } } } public void loadQueue () { try ( ObjectInputStream queueIn = new ObjectInputStream( new FileInputStream( queueFile ) ); ) { audioSystem.getQueue().queueAllTracks( (ArrayList <Track>) queueIn.readObject() ); audioSystem.getQueue().setHasUnsavedData( false ); } catch ( Exception e ) { LOGGER.log( Level.INFO, "Unable to read queue data from disk, continuing.", e ); } } public void loadHistory () { try ( ObjectInputStream historyIn = new ObjectInputStream( new FileInputStream( historyFile ) ); ) { audioSystem.getHistory().setData( (ArrayList <Track>) historyIn.readObject() ); audioSystem.getHistory().setHasUnsavedData( false ); } catch ( Exception e ) { LOGGER.log( Level.INFO, "Unable to read history from disk, continuing.", e ); } } public void loadHotkeys () { try ( ObjectInputStream hotkeysIn = new ObjectInputStream( new FileInputStream( hotkeysFile ) ); ) { hotkeys.setMap( (EnumMap <Hotkey, HotkeyState>) hotkeysIn.readObject() ); hotkeys.setHasUnsavedData( false ); } catch ( Exception e ) { LOGGER.log( Level.INFO, "Unable to read hotkeys from disk, continuing.", e ); } } public void loadAlbumsAndTracks () { try ( ObjectInputStream dataIn = new ObjectInputStream( new GZIPInputStream( new FileInputStream( dataFile ) ) ) ) { ArrayList <Album> albums = (ArrayList <Album>) dataIn.readObject(); ArrayList <Track> tracks = (ArrayList <Track>) dataIn.readObject(); library.setDataOnInitialLoad ( tracks, albums ); if ( audioSystem.getCurrentTrack() != null ) { for ( Track track : library.getTrackData() ) { if ( track.equals(audioSystem.getCurrentTrack()) ) { audioSystem.getCurrentTrack().setAlbum(track.getAlbum()); } } } } catch ( Exception e ) { LOGGER.log( Level.INFO, "Unable to read library data from disk, continuing.", e ); } } public void loadPlaylists () { try ( DirectoryStream <Path> stream = Files.newDirectoryStream( playlistsDirectory.toPath() ); ) { List<Playlist> playlists = new ArrayList<>(); for ( Path child : stream ) { Playlist playlist = Playlist.loadPlaylist( child ); if ( playlist != null ) { playlist.setHasUnsavedData( false ); playlists.add( playlist ); library.linkPlaylistToLibrary(playlist); } } library.setDataOnInitialLoad( playlists ); } catch ( IOException e ) { LOGGER.log( Level.WARNING, "Unable to load playlists from disk.", e ); } } public void saveRoots () { File tempSourcesFile = new File ( sourcesFile.toString() + ".temp" ); try ( ObjectOutputStream sourcesOut = new ObjectOutputStream( new FileOutputStream( tempSourcesFile ) ); ) { sourcesOut.writeObject( new ArrayList <MusicRoot> ( library.getMusicRootData() ) ); sourcesOut.flush(); sourcesOut.close(); Files.move( tempSourcesFile.toPath(), sourcesFile.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to save library source directory list to disk, continuing.", e ); } } public void saveCurrentList () { if ( !audioSystem.getCurrentList().hasUnsavedData() ) return; File tempCurrentFile = new File ( currentFile.toString() + ".temp" ); if ( audioSystem.getCurrentList().getState().getItems().size() < 500 ) { try ( ObjectOutputStream currentListOut = new ObjectOutputStream( new FileOutputStream( tempCurrentFile ) ) ) { currentListOut.writeObject( audioSystem.getCurrentList().getState() ); currentListOut.flush(); currentListOut.close(); Files.move( tempCurrentFile.toPath(), currentFile.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE ); audioSystem.getCurrentList().setHasUnsavedData( false ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to save current list data to disk, continuing.", e ); } } else { try ( GZIPOutputStream currentListOut = new GZIPOutputStream( new BufferedOutputStream( new FileOutputStream( tempCurrentFile ) ) ); ) { ByteArrayOutputStream byteWriter = new ByteArrayOutputStream(); ObjectOutputStream bytesOut = new ObjectOutputStream( byteWriter ); bytesOut.writeObject( audioSystem.getCurrentList().getState() ); currentListOut.write( byteWriter.toByteArray() ); currentListOut.flush(); currentListOut.close(); Files.move( tempCurrentFile.toPath(), currentFile.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE ); audioSystem.getCurrentList().setHasUnsavedData( false ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to save current list data to disk, continuing.", e ); } } } public void saveQueue () { if ( !audioSystem.getQueue().hasUnsavedData() ) { return; } File tempQueueFile = new File ( queueFile.toString() + ".temp" ); try ( ObjectOutputStream queueListOut = new ObjectOutputStream( new FileOutputStream( tempQueueFile ) ) ) { queueListOut.writeObject( new ArrayList <Track>( audioSystem.getQueue().getData() ) ); queueListOut.flush(); queueListOut.close(); Files.move( tempQueueFile.toPath(), queueFile.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE ); audioSystem.getQueue().setHasUnsavedData( false ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to save queue to disk, continuing.", e ); } } public void saveHistory () { if ( !audioSystem.getHistory().hasUnsavedData() ) return; File tempHistoryFile = new File ( historyFile.toString() + ".temp" ); try ( ObjectOutputStream historyListOut = new ObjectOutputStream( new FileOutputStream( tempHistoryFile ) ) ) { historyListOut.writeObject( new ArrayList <Track>( audioSystem.getHistory().getItems() ) ); historyListOut.flush(); historyListOut.close(); Files.move( tempHistoryFile.toPath(), historyFile.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE ); audioSystem.getHistory().setHasUnsavedData( false ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to save history to disk, continuing.", e ); } } public void saveHotkeys () { if ( !hotkeys.hasUnsavedData() ) return; File tempHotkeysFile = new File ( hotkeysFile.toString() + ".temp" ); try ( ObjectOutputStream hotkeysOut = new ObjectOutputStream( new FileOutputStream( tempHotkeysFile ) ) ) { hotkeysOut.writeObject( hotkeys.getMap() ); hotkeysOut.flush(); hotkeysOut.close(); Files.move( tempHotkeysFile.toPath(), hotkeysFile.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE ); hotkeys.setHasUnsavedData( false ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to save hotkeys to disk, continuing.", e ); } } public void saveAlbumsAndTracks () { /* * Some notes for future Josh (2017/05/14): * 1. For some reason, keepingthe ByteArrayOutputStream in the middle * makes things take ~2/3 the amount of time. * 2. I tried removing tracks that have albums (since they're being * written twice) but it didn't create any savings. I guess compression * is handling that. * 3. I didn't try regular zip. GZIP was easier. */ File tempDataFile = new File ( dataFile.toString() + ".temp" ); try ( GZIPOutputStream compressedOut = new GZIPOutputStream( new BufferedOutputStream( new FileOutputStream( tempDataFile ) ) ); ) { ByteArrayOutputStream byteWriter = new ByteArrayOutputStream(); ObjectOutputStream bytesOut = new ObjectOutputStream( byteWriter ); bytesOut.writeObject( new ArrayList <Album>( Arrays.asList( library.getAlbumData().toArray( new Album [ library.getAlbumData().size() ] ) ) ) ); bytesOut.writeObject( new ArrayList <Track>( Arrays.asList( library.getTrackData().toArray( new Track [ library.getTrackData().size() ] ) ) ) ); compressedOut.write( byteWriter.toByteArray() ); compressedOut.flush(); compressedOut.close(); Files.move( tempDataFile.toPath(), dataFile.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to save library data to disk, continuing.", e ); } } public void saveLibraryPlaylists () { ArrayList <Playlist> playlists = new ArrayList <> ( library.getPlaylistData() ); ArrayList <Playlist> errors = new ArrayList <> (); for ( Playlist playlist : playlists ) { if ( playlist == null ) { LOGGER.log( Level.INFO, "Found a null playlist in library.playlists, ignoring.", new NullPointerException() ); continue; } if ( !playlist.hasUnsavedData() ) continue; try { saveLibaryPlaylist ( playlist ); } catch ( IOException e ) { LOGGER.log ( Level.WARNING, "Unable to save library playlist " + playlist.getName(), e ); errors.add( playlist ); } } if ( errors.size() > 0 ) { Hypnos.warnUserPlaylistsNotSaved ( errors ); } } public void deletePlaylistFile ( Playlist playlist ) { deletePlaylistFile ( playlist.getBaseFilename() ); } public void deletePlaylistFile ( String basename ) { Path targetFile = playlistsDirectory.toPath().resolve ( basename + ".m3u" ); try { Files.deleteIfExists( targetFile ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to delete playlist file: " + targetFile, e ); } } //Assumptions: playlist != null, playlist.name is not null or empty, and no playlists in library have the same name. private void saveLibaryPlaylist ( Playlist playlist ) throws IOException { String baseFileName = playlist.getBaseFilename(); Path targetFile = playlistsDirectory.toPath().resolve ( baseFileName + ".m3u" ); Path backupFile = playlistsDirectory.toPath().resolve ( baseFileName + ".m3u.backup" ); Path tempFile = playlistsDirectory.toPath().resolve ( baseFileName + ".m3u.temp" ); boolean savedToTemp = false; try { playlist.saveAs( tempFile.toFile() ); savedToTemp = true; } catch ( IOException e ) { savedToTemp = false; LOGGER.log( Level.INFO, "Unable to write to a temp file, so I will try writing directly to the playlist file." + "Your data will be saved in a backup file first. If this process is interrupted, you may need to manually " + "recover the data from the backup file.", e ); if ( Files.exists( targetFile ) ) { try { Files.move( targetFile, backupFile, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE ); } catch ( IOException e2 ) { LOGGER.log( Level.INFO, "Unable to move existing playlist file to backup location (" + backupFile.toString() + ") will continue trying to save current playlist, overwriting the existing file.", e2 ); } } } try { boolean movedFromTemp = false; if ( savedToTemp ) { try { Files.move( tempFile, targetFile, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE ); movedFromTemp = true; } catch ( IOException e ) { movedFromTemp = false; } } if ( !movedFromTemp ) { playlist.saveAs( targetFile.toFile() ); } } catch ( IOException e ) { LOGGER.log( Level.WARNING, "Unable to save playlist to file: " + targetFile.toString() + ".", e ); throw e; } finally { Files.deleteIfExists( tempFile ); } playlist.setHasUnsavedData( false ); } public void saveSettings ( EnumMap <Setting, ? extends Object> fromAudioSystem, EnumMap <Setting, ? extends Object> fromUI ) { File tempSettingsFile = new File ( settingsFile.toString() + ".temp" ); try ( FileWriter fileWriter = new FileWriter( tempSettingsFile ); ) { PrintWriter settingsOut = new PrintWriter( new BufferedWriter( fileWriter ) ); fromAudioSystem.forEach( ( key, value ) -> { String valueOut = value == null ? "null" : value.toString(); settingsOut.printf( "%s: %s%s", key, valueOut, System.lineSeparator() ); } ); fromUI.forEach( ( key, value ) -> { String valueOut = value == null ? "null" : value.toString(); settingsOut.printf( "%s: %s%s", key, valueOut, System.lineSeparator() ); } ); settingsOut.printf( "%s: %s%s", Setting.LOADER_SPEED, Hypnos.getLoaderSpeed(), System.lineSeparator() ); settingsOut.flush(); settingsOut.close(); Files.move( tempSettingsFile.toPath(), settingsFile.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to save settings to disk, continuing.", e ); } } public EnumMap <Setting, String> loadSettingsFromDisk () { EnumMap <Setting, String> settings = new EnumMap <Setting, String>( Setting.class ); try ( FileReader fileReader = new FileReader( settingsFile ) ) { BufferedReader settingsIn = new BufferedReader( fileReader ); for ( String line; (line = settingsIn.readLine()) != null; ) { Setting setting; try { setting = Setting.valueOf( line.split( ":\\s+" )[0] ); } catch ( IllegalArgumentException e ) { LOGGER.log( Level.INFO, "Found invalid setting: " + line.split( ":\\s+" )[0] + ", ignoring.", e ); continue; } String value = ""; try { value = line.split( ":\\s+" )[1]; } catch ( ArrayIndexOutOfBoundsException e ) { //Do nothing, some settings can be empty } settings.put ( setting, value ); } } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to read settings from disk, continuing.", e ); } return settings; } public void logUnusedSettings ( EnumMap <Setting, String> pendingSettings ) { if ( pendingSettings.size() == 0 ) return; String message = ""; for ( Setting setting : pendingSettings.keySet() ) { if ( message.length() > 0 ) message += "\n"; message += setting.toString() + ": " + pendingSettings.get( setting ); } LOGGER.log ( Level.INFO, "Some settings were read from disk but not applied:\n" + message ); } public void startThread() { Thread persisterThread = new Thread() { public void run() { long lastSaveTime = System.currentTimeMillis(); while ( true ) { if ( System.currentTimeMillis() - lastSaveTime > SAVE_ALL_INTERVAL ) { createNecessaryFolders(); if ( library.dataNeedsToBeSavedToDisk() ) { saveAlbumsAndTracks(); library.setDataNeedsToBeSavedToDisk( false ); } saveRoots(); saveCurrentList(); saveQueue(); saveHistory(); saveLibraryPlaylists(); saveHotkeys(); //there's no easy way to check if settings changed right now, so we just don't bother //it's not a big deal if they are lost due to a crash. They are saved on close //persister.saveSettings(); lastSaveTime = System.currentTimeMillis(); } try { Thread.sleep( 100 ); } catch (InterruptedException e) { LOGGER.log( Level.INFO, "Persister thread interrupted, ignoring.", e ); } } } }; persisterThread.setName( "Persister Thread" ); persisterThread.start(); } public Path getPlaylistDirectory() { return this.playlistsDirectory.toPath(); } }
23,591
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
History.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/History.java
package net.joshuad.hypnos; import java.util.ArrayList; import java.util.List; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import net.joshuad.hypnos.library.Track; public class History { private static final int MAX_HISTORY_SIZE = 1000; private final ObservableList <Track> history = FXCollections.observableArrayList( new ArrayList <Track>(MAX_HISTORY_SIZE) ); private transient boolean hasUnsavedData = true; public History() { history.addListener( (ListChangeListener.Change<? extends Track> change) -> { hasUnsavedData = true; }); } public boolean hasUnsavedData() { return hasUnsavedData; } public void setHasUnsavedData( boolean b ) { hasUnsavedData = b; } public void trackPlayed ( Track track ) { if ( track == null ) return; if ( history.size() == 0 || !track.equals( history.get( 0 ) ) ) { while ( history.size() >= MAX_HISTORY_SIZE ) { history.remove( history.size() - 1 ); } history.add( 0, track ); } } public ObservableList <Track> getItems() { return history; } public void setData ( List <Track> data ) { history.clear(); history.addAll( data ); } public Track getLastTrack () { if ( history.size() >= 0 ) { return history.get( 0 ); } else { return null; } } }
1,359
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
WindowsGlobalHotkeys.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/hotkeys/WindowsGlobalHotkeys.java
package net.joshuad.hypnos.hotkeys; import java.io.IOException; import java.util.HashMap; import java.util.logging.Level; import java.util.logging.Logger; import com.melloware.jintellitype.JIntellitype; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import net.joshuad.hypnos.Hypnos; import net.joshuad.hypnos.hotkeys.GlobalHotkeys.Hotkey; public class WindowsGlobalHotkeys extends SystemHotkeys { private static final Logger LOGGER = Logger.getLogger( WindowsGlobalHotkeys.class.getName() ); private static final int LAST_KEY_PRESS_EXPIRES_IN_MS = 50; GlobalHotkeys parent; Object lock = new Object(); int lastIntellitypeCommand = -1; long lastIntellitypePressedMS = 0; String lastIntellitypeName = ""; public WindowsGlobalHotkeys( GlobalHotkeys parent ) throws HotkeyException { this.parent = parent; try { String location = Hypnos.getRootDirectory().resolve( "lib\\win\\jintellitype\\JIntellitype-64.dll" ) .toFile().getCanonicalFile().toString(); JIntellitype.setLibraryLocation( location ); JIntellitype.getInstance().addHotKeyListener( ( int hotkeyID ) -> { if ( hotkeyID >= 0 && hotkeyID < Hotkey.values().length ) { Hotkey hotkey = Hotkey.values() [ hotkeyID ]; parent.systemHotkeyEventHappened ( hotkey ); } }); JIntellitype.getInstance().addIntellitypeListener( ( int command ) -> { recordLastCommand ( command ); for ( Hotkey hotkey : parent.getMap().keySet() ) { HotkeyState registeredHotkeyState = parent.getMap().get( hotkey ); if ( registeredHotkeyState instanceof IntellitypeHotkeyState ) { IntellitypeHotkeyState registeredIntellitypeHotkeyState = (IntellitypeHotkeyState)registeredHotkeyState; if ( command == registeredIntellitypeHotkeyState.getIntellitypeCommand() ) { parent.systemHotkeyEventHappened ( hotkey ); } } } }); } catch ( IOException | RuntimeException e ) { throw new HotkeyException( "Unable to load Hotkey Library for Windows: " + e ); } } @Override protected HotkeyState createJustPressedState( KeyEvent keyEvent ) { synchronized ( lock ) { if ( System.currentTimeMillis() - LAST_KEY_PRESS_EXPIRES_IN_MS < lastIntellitypePressedMS ) { return null; } HotkeyState retMe = new IntellitypeHotkeyState ( keyEvent, lastIntellitypeCommand, lastIntellitypeName ); return retMe; } } private void recordLastCommand ( int aCommand ) { synchronized ( lock ) { lastIntellitypeCommand = aCommand; lastIntellitypePressedMS = System.currentTimeMillis(); switch (aCommand) { case JIntellitype.APPCOMMAND_BROWSER_BACKWARD: lastIntellitypeName = "Browser Back"; break; case JIntellitype.APPCOMMAND_BROWSER_FAVOURITES: lastIntellitypeName = "Browser Favorites"; break; case JIntellitype.APPCOMMAND_BROWSER_FORWARD: lastIntellitypeName = "Browser Forward"; break; case JIntellitype.APPCOMMAND_BROWSER_HOME: lastIntellitypeName = "Browser Home"; break; case JIntellitype.APPCOMMAND_BROWSER_REFRESH: lastIntellitypeName = "Browser Refresh"; break; case JIntellitype.APPCOMMAND_BROWSER_SEARCH: lastIntellitypeName = "Browser Search"; break; case JIntellitype.APPCOMMAND_BROWSER_STOP: lastIntellitypeName = "Browser Stop"; break; case JIntellitype.APPCOMMAND_LAUNCH_APP1: lastIntellitypeName = "Launch App 1"; break; case JIntellitype.APPCOMMAND_LAUNCH_APP2: lastIntellitypeName = "Launch App 2"; break; case JIntellitype.APPCOMMAND_LAUNCH_MAIL: lastIntellitypeName = "Launch Mail"; break; case JIntellitype.APPCOMMAND_MEDIA_NEXTTRACK: lastIntellitypeName = "Next"; break; case JIntellitype.APPCOMMAND_MEDIA_PLAY_PAUSE: lastIntellitypeName = "Play/Pause"; break; case JIntellitype.APPCOMMAND_MEDIA_PREVIOUSTRACK: lastIntellitypeName = "Previous"; break; case JIntellitype.APPCOMMAND_MEDIA_STOP: lastIntellitypeName = "Stop"; break; case JIntellitype.APPCOMMAND_VOLUME_DOWN: lastIntellitypeName = "Volume Down"; break; case JIntellitype.APPCOMMAND_VOLUME_UP: lastIntellitypeName = "Volume Up"; break; case JIntellitype.APPCOMMAND_VOLUME_MUTE: lastIntellitypeName = "Volume Mute"; break; default: lastIntellitypeCommand = -1; lastIntellitypePressedMS = 0; LOGGER.log( Level.INFO, "Undefined INTELLITYPE message caught " + Integer.toString( aCommand ), new Exception() ); break; } } } @Override boolean registerHotkey ( Hotkey hotkey, HotkeyState state ) { int mod = 0; if ( state.isMetaDown() ) mod += JIntellitype.MOD_WIN; if ( state.isAltDown() ) mod += JIntellitype.MOD_ALT; if ( state.isControlDown() ) mod += JIntellitype.MOD_CONTROL; if ( state.isShiftDown() ) mod += JIntellitype.MOD_SHIFT; if ( state instanceof IntellitypeHotkeyState ) { return true; } else { int keyCode = keyCodeToAWTKeyEvent ( state.getCode() ); JIntellitype.getInstance().registerHotKey( hotkey.ordinal(), mod, keyCode ); } return true; } @Override void unregisterHotkey ( Hotkey hotkey ) { JIntellitype.getInstance().unregisterHotKey( hotkey.ordinal() ); } public static int keyCodeToAWTKeyEvent ( KeyCode code ) { return keycodetoAWTMap.get( code ); } private static HashMap<KeyCode, Integer> keycodetoAWTMap = new HashMap<>(); { keycodetoAWTMap.put( KeyCode.ENTER, 13 ); keycodetoAWTMap.put( KeyCode.BACK_SPACE, java.awt.event.KeyEvent.VK_BACK_SPACE ); keycodetoAWTMap.put( KeyCode.TAB, java.awt.event.KeyEvent.VK_TAB ); keycodetoAWTMap.put( KeyCode.CANCEL, java.awt.event.KeyEvent.VK_CANCEL ); keycodetoAWTMap.put( KeyCode.CLEAR, java.awt.event.KeyEvent.VK_CLEAR ); keycodetoAWTMap.put( KeyCode.PAUSE, java.awt.event.KeyEvent.VK_PAUSE ); keycodetoAWTMap.put( KeyCode.CAPS, java.awt.event.KeyEvent.VK_CAPS_LOCK ); keycodetoAWTMap.put( KeyCode.ESCAPE, java.awt.event.KeyEvent.VK_ESCAPE ); keycodetoAWTMap.put( KeyCode.SPACE, java.awt.event.KeyEvent.VK_SPACE ); keycodetoAWTMap.put( KeyCode.PAGE_UP, java.awt.event.KeyEvent.VK_PAGE_UP ); keycodetoAWTMap.put( KeyCode.PAGE_DOWN, java.awt.event.KeyEvent.VK_PAGE_DOWN ); keycodetoAWTMap.put( KeyCode.END, java.awt.event.KeyEvent.VK_END ); keycodetoAWTMap.put( KeyCode.HOME, java.awt.event.KeyEvent.VK_HOME ); keycodetoAWTMap.put( KeyCode.LEFT, java.awt.event.KeyEvent.VK_LEFT ); keycodetoAWTMap.put( KeyCode.UP, java.awt.event.KeyEvent.VK_UP ); keycodetoAWTMap.put( KeyCode.RIGHT, java.awt.event.KeyEvent.VK_RIGHT ); keycodetoAWTMap.put( KeyCode.DOWN, java.awt.event.KeyEvent.VK_DOWN ); keycodetoAWTMap.put( KeyCode.COMMA, 188 ); keycodetoAWTMap.put( KeyCode.MINUS, 109 ); keycodetoAWTMap.put( KeyCode.PERIOD, 110 ); keycodetoAWTMap.put( KeyCode.SLASH, 191 ); keycodetoAWTMap.put( KeyCode.BACK_QUOTE, 192); keycodetoAWTMap.put( KeyCode.DIGIT0, java.awt.event.KeyEvent.VK_0 ); keycodetoAWTMap.put( KeyCode.DIGIT1, java.awt.event.KeyEvent.VK_1 ); keycodetoAWTMap.put( KeyCode.DIGIT2, java.awt.event.KeyEvent.VK_2 ); keycodetoAWTMap.put( KeyCode.DIGIT3, java.awt.event.KeyEvent.VK_3 ); keycodetoAWTMap.put( KeyCode.DIGIT4, java.awt.event.KeyEvent.VK_4 ); keycodetoAWTMap.put( KeyCode.DIGIT5, java.awt.event.KeyEvent.VK_5 ); keycodetoAWTMap.put( KeyCode.DIGIT6, java.awt.event.KeyEvent.VK_6 ); keycodetoAWTMap.put( KeyCode.DIGIT7, java.awt.event.KeyEvent.VK_7 ); keycodetoAWTMap.put( KeyCode.DIGIT8, java.awt.event.KeyEvent.VK_8 ); keycodetoAWTMap.put( KeyCode.DIGIT9, java.awt.event.KeyEvent.VK_9 ); keycodetoAWTMap.put( KeyCode.SEMICOLON, 186 ); keycodetoAWTMap.put( KeyCode.EQUALS, 187 ); keycodetoAWTMap.put( KeyCode.A, java.awt.event.KeyEvent.VK_A ); keycodetoAWTMap.put( KeyCode.B, java.awt.event.KeyEvent.VK_B ); keycodetoAWTMap.put( KeyCode.C, java.awt.event.KeyEvent.VK_C ); keycodetoAWTMap.put( KeyCode.D, java.awt.event.KeyEvent.VK_D ); keycodetoAWTMap.put( KeyCode.E, java.awt.event.KeyEvent.VK_E ); keycodetoAWTMap.put( KeyCode.F, java.awt.event.KeyEvent.VK_F ); keycodetoAWTMap.put( KeyCode.G, java.awt.event.KeyEvent.VK_G ); keycodetoAWTMap.put( KeyCode.H, java.awt.event.KeyEvent.VK_H ); keycodetoAWTMap.put( KeyCode.I, java.awt.event.KeyEvent.VK_I ); keycodetoAWTMap.put( KeyCode.J, java.awt.event.KeyEvent.VK_J ); keycodetoAWTMap.put( KeyCode.K, java.awt.event.KeyEvent.VK_K ); keycodetoAWTMap.put( KeyCode.L, java.awt.event.KeyEvent.VK_L ); keycodetoAWTMap.put( KeyCode.M, java.awt.event.KeyEvent.VK_M ); keycodetoAWTMap.put( KeyCode.N, java.awt.event.KeyEvent.VK_N ); keycodetoAWTMap.put( KeyCode.O, java.awt.event.KeyEvent.VK_O ); keycodetoAWTMap.put( KeyCode.P, java.awt.event.KeyEvent.VK_P ); keycodetoAWTMap.put( KeyCode.Q, java.awt.event.KeyEvent.VK_Q ); keycodetoAWTMap.put( KeyCode.R, java.awt.event.KeyEvent.VK_R ); keycodetoAWTMap.put( KeyCode.S, java.awt.event.KeyEvent.VK_S ); keycodetoAWTMap.put( KeyCode.T, java.awt.event.KeyEvent.VK_T ); keycodetoAWTMap.put( KeyCode.U, java.awt.event.KeyEvent.VK_U ); keycodetoAWTMap.put( KeyCode.V, java.awt.event.KeyEvent.VK_V ); keycodetoAWTMap.put( KeyCode.W, java.awt.event.KeyEvent.VK_W ); keycodetoAWTMap.put( KeyCode.X, java.awt.event.KeyEvent.VK_X ); keycodetoAWTMap.put( KeyCode.Y, java.awt.event.KeyEvent.VK_Y ); keycodetoAWTMap.put( KeyCode.Z, java.awt.event.KeyEvent.VK_Z ); keycodetoAWTMap.put( KeyCode.OPEN_BRACKET, 219 ); keycodetoAWTMap.put( KeyCode.BACK_SLASH, 220 ); keycodetoAWTMap.put( KeyCode.CLOSE_BRACKET, 221 ); keycodetoAWTMap.put( KeyCode.NUMPAD0, java.awt.event.KeyEvent.VK_NUMPAD0 ); keycodetoAWTMap.put( KeyCode.NUMPAD1, java.awt.event.KeyEvent.VK_NUMPAD1 ); keycodetoAWTMap.put( KeyCode.NUMPAD2, java.awt.event.KeyEvent.VK_NUMPAD2 ); keycodetoAWTMap.put( KeyCode.NUMPAD3, java.awt.event.KeyEvent.VK_NUMPAD3 ); keycodetoAWTMap.put( KeyCode.NUMPAD4, java.awt.event.KeyEvent.VK_NUMPAD4 ); keycodetoAWTMap.put( KeyCode.NUMPAD5, java.awt.event.KeyEvent.VK_NUMPAD5 ); keycodetoAWTMap.put( KeyCode.NUMPAD6, java.awt.event.KeyEvent.VK_NUMPAD6 ); keycodetoAWTMap.put( KeyCode.NUMPAD7, java.awt.event.KeyEvent.VK_NUMPAD7 ); keycodetoAWTMap.put( KeyCode.NUMPAD8, java.awt.event.KeyEvent.VK_NUMPAD8 ); keycodetoAWTMap.put( KeyCode.NUMPAD9, java.awt.event.KeyEvent.VK_NUMPAD9 ); keycodetoAWTMap.put( KeyCode.MULTIPLY, java.awt.event.KeyEvent.VK_MULTIPLY ); keycodetoAWTMap.put( KeyCode.ADD, java.awt.event.KeyEvent.VK_ADD ); keycodetoAWTMap.put( KeyCode.SEPARATOR, java.awt.event.KeyEvent.VK_SEPARATOR ); keycodetoAWTMap.put( KeyCode.SUBTRACT, java.awt.event.KeyEvent.VK_SUBTRACT ); keycodetoAWTMap.put( KeyCode.DECIMAL, java.awt.event.KeyEvent.VK_DECIMAL ); keycodetoAWTMap.put( KeyCode.DIVIDE, java.awt.event.KeyEvent.VK_DIVIDE ); keycodetoAWTMap.put( KeyCode.DELETE, 46 ); keycodetoAWTMap.put( KeyCode.NUM_LOCK, java.awt.event.KeyEvent.VK_NUM_LOCK ); keycodetoAWTMap.put( KeyCode.SCROLL_LOCK, java.awt.event.KeyEvent.VK_SCROLL_LOCK ); keycodetoAWTMap.put( KeyCode.F1, java.awt.event.KeyEvent.VK_F1 ); keycodetoAWTMap.put( KeyCode.F2, java.awt.event.KeyEvent.VK_F2 ); keycodetoAWTMap.put( KeyCode.F3, java.awt.event.KeyEvent.VK_F3 ); keycodetoAWTMap.put( KeyCode.F4, java.awt.event.KeyEvent.VK_F4 ); keycodetoAWTMap.put( KeyCode.F5, java.awt.event.KeyEvent.VK_F5 ); keycodetoAWTMap.put( KeyCode.F6, java.awt.event.KeyEvent.VK_F6 ); keycodetoAWTMap.put( KeyCode.F7, java.awt.event.KeyEvent.VK_F7 ); keycodetoAWTMap.put( KeyCode.F8, java.awt.event.KeyEvent.VK_F8 ); keycodetoAWTMap.put( KeyCode.F9, java.awt.event.KeyEvent.VK_F9 ); keycodetoAWTMap.put( KeyCode.F10, java.awt.event.KeyEvent.VK_F10 ); keycodetoAWTMap.put( KeyCode.F11, java.awt.event.KeyEvent.VK_F11 ); keycodetoAWTMap.put( KeyCode.F12, java.awt.event.KeyEvent.VK_F12 ); keycodetoAWTMap.put( KeyCode.F13, java.awt.event.KeyEvent.VK_F13 ); keycodetoAWTMap.put( KeyCode.F14, java.awt.event.KeyEvent.VK_F14 ); keycodetoAWTMap.put( KeyCode.F15, java.awt.event.KeyEvent.VK_F15 ); keycodetoAWTMap.put( KeyCode.F16, java.awt.event.KeyEvent.VK_F16 ); keycodetoAWTMap.put( KeyCode.F17, java.awt.event.KeyEvent.VK_F17 ); keycodetoAWTMap.put( KeyCode.F18, java.awt.event.KeyEvent.VK_F18 ); keycodetoAWTMap.put( KeyCode.F19, java.awt.event.KeyEvent.VK_F19 ); keycodetoAWTMap.put( KeyCode.F20, java.awt.event.KeyEvent.VK_F20 ); keycodetoAWTMap.put( KeyCode.F21, java.awt.event.KeyEvent.VK_F21 ); keycodetoAWTMap.put( KeyCode.F22, java.awt.event.KeyEvent.VK_F22 ); keycodetoAWTMap.put( KeyCode.F23, java.awt.event.KeyEvent.VK_F23 ); keycodetoAWTMap.put( KeyCode.F24, java.awt.event.KeyEvent.VK_F24 ); keycodetoAWTMap.put( KeyCode.PRINTSCREEN, 44 ); keycodetoAWTMap.put( KeyCode.INSERT, 45 ); keycodetoAWTMap.put( KeyCode.HELP, 47 ); keycodetoAWTMap.put( KeyCode.META, java.awt.event.KeyEvent.VK_META ); keycodetoAWTMap.put( KeyCode.BACK_QUOTE, java.awt.event.KeyEvent.VK_BACK_QUOTE ); keycodetoAWTMap.put( KeyCode.QUOTE, java.awt.event.KeyEvent.VK_QUOTE ); keycodetoAWTMap.put( KeyCode.KP_UP, java.awt.event.KeyEvent.VK_KP_UP ); keycodetoAWTMap.put( KeyCode.KP_DOWN, java.awt.event.KeyEvent.VK_KP_DOWN ); keycodetoAWTMap.put( KeyCode.KP_LEFT, java.awt.event.KeyEvent.VK_KP_LEFT ); keycodetoAWTMap.put( KeyCode.KP_RIGHT, java.awt.event.KeyEvent.VK_KP_RIGHT ); keycodetoAWTMap.put( KeyCode.DEAD_GRAVE, java.awt.event.KeyEvent.VK_DEAD_GRAVE ); keycodetoAWTMap.put( KeyCode.DEAD_ACUTE, java.awt.event.KeyEvent.VK_DEAD_ACUTE ); keycodetoAWTMap.put( KeyCode.DEAD_CIRCUMFLEX, java.awt.event.KeyEvent.VK_DEAD_CIRCUMFLEX ); keycodetoAWTMap.put( KeyCode.DEAD_TILDE, java.awt.event.KeyEvent.VK_DEAD_TILDE ); keycodetoAWTMap.put( KeyCode.DEAD_MACRON, java.awt.event.KeyEvent.VK_DEAD_MACRON ); keycodetoAWTMap.put( KeyCode.DEAD_BREVE, java.awt.event.KeyEvent.VK_DEAD_BREVE ); keycodetoAWTMap.put( KeyCode.DEAD_ABOVEDOT, java.awt.event.KeyEvent.VK_DEAD_ABOVEDOT ); keycodetoAWTMap.put( KeyCode.DEAD_DIAERESIS, java.awt.event.KeyEvent.VK_DEAD_DIAERESIS ); keycodetoAWTMap.put( KeyCode.DEAD_ABOVERING, java.awt.event.KeyEvent.VK_DEAD_ABOVERING ); keycodetoAWTMap.put( KeyCode.DEAD_DOUBLEACUTE, java.awt.event.KeyEvent.VK_DEAD_DOUBLEACUTE ); keycodetoAWTMap.put( KeyCode.DEAD_CARON, java.awt.event.KeyEvent.VK_DEAD_CARON ); keycodetoAWTMap.put( KeyCode.DEAD_CEDILLA, java.awt.event.KeyEvent.VK_DEAD_CEDILLA ); keycodetoAWTMap.put( KeyCode.DEAD_OGONEK, java.awt.event.KeyEvent.VK_DEAD_OGONEK ); keycodetoAWTMap.put( KeyCode.DEAD_IOTA, java.awt.event.KeyEvent.VK_DEAD_IOTA ); keycodetoAWTMap.put( KeyCode.DEAD_VOICED_SOUND, java.awt.event.KeyEvent.VK_DEAD_VOICED_SOUND ); keycodetoAWTMap.put( KeyCode.DEAD_SEMIVOICED_SOUND, java.awt.event.KeyEvent.VK_DEAD_SEMIVOICED_SOUND ); keycodetoAWTMap.put( KeyCode.AMPERSAND, java.awt.event.KeyEvent.VK_AMPERSAND ); keycodetoAWTMap.put( KeyCode.ASTERISK, java.awt.event.KeyEvent.VK_ASTERISK ); keycodetoAWTMap.put( KeyCode.QUOTEDBL, java.awt.event.KeyEvent.VK_QUOTEDBL ); keycodetoAWTMap.put( KeyCode.LESS, java.awt.event.KeyEvent.VK_LESS ); keycodetoAWTMap.put( KeyCode.GREATER, java.awt.event.KeyEvent.VK_GREATER ); keycodetoAWTMap.put( KeyCode.BRACELEFT, java.awt.event.KeyEvent.VK_BRACELEFT ); keycodetoAWTMap.put( KeyCode.BRACERIGHT, java.awt.event.KeyEvent.VK_BRACERIGHT ); keycodetoAWTMap.put( KeyCode.AT, java.awt.event.KeyEvent.VK_AT ); keycodetoAWTMap.put( KeyCode.COLON, java.awt.event.KeyEvent.VK_COLON ); keycodetoAWTMap.put( KeyCode.CIRCUMFLEX, java.awt.event.KeyEvent.VK_CIRCUMFLEX ); keycodetoAWTMap.put( KeyCode.DOLLAR, java.awt.event.KeyEvent.VK_DOLLAR ); keycodetoAWTMap.put( KeyCode.EURO_SIGN, java.awt.event.KeyEvent.VK_EURO_SIGN ); keycodetoAWTMap.put( KeyCode.EXCLAMATION_MARK, java.awt.event.KeyEvent.VK_EXCLAMATION_MARK ); keycodetoAWTMap.put( KeyCode.INVERTED_EXCLAMATION_MARK, java.awt.event.KeyEvent.VK_INVERTED_EXCLAMATION_MARK ); keycodetoAWTMap.put( KeyCode.LEFT_PARENTHESIS, java.awt.event.KeyEvent.VK_LEFT_PARENTHESIS ); keycodetoAWTMap.put( KeyCode.NUMBER_SIGN, java.awt.event.KeyEvent.VK_NUMBER_SIGN ); keycodetoAWTMap.put( KeyCode.PLUS, java.awt.event.KeyEvent.VK_PLUS ); keycodetoAWTMap.put( KeyCode.RIGHT_PARENTHESIS, java.awt.event.KeyEvent.VK_RIGHT_PARENTHESIS ); keycodetoAWTMap.put( KeyCode.UNDERSCORE, java.awt.event.KeyEvent.VK_UNDERSCORE ); keycodetoAWTMap.put( KeyCode.CONTEXT_MENU, java.awt.event.KeyEvent.VK_CONTEXT_MENU ); keycodetoAWTMap.put( KeyCode.FINAL, java.awt.event.KeyEvent.VK_FINAL ); keycodetoAWTMap.put( KeyCode.CONVERT, java.awt.event.KeyEvent.VK_CONVERT ); keycodetoAWTMap.put( KeyCode.NONCONVERT, java.awt.event.KeyEvent.VK_NONCONVERT ); keycodetoAWTMap.put( KeyCode.ACCEPT, java.awt.event.KeyEvent.VK_ACCEPT ); keycodetoAWTMap.put( KeyCode.MODECHANGE, java.awt.event.KeyEvent.VK_MODECHANGE ); keycodetoAWTMap.put( KeyCode.KANA, java.awt.event.KeyEvent.VK_KANA ); keycodetoAWTMap.put( KeyCode.KANJI, java.awt.event.KeyEvent.VK_KANJI ); keycodetoAWTMap.put( KeyCode.ALPHANUMERIC, java.awt.event.KeyEvent.VK_ALPHANUMERIC ); keycodetoAWTMap.put( KeyCode.KATAKANA, java.awt.event.KeyEvent.VK_KATAKANA ); keycodetoAWTMap.put( KeyCode.HIRAGANA, java.awt.event.KeyEvent.VK_HIRAGANA ); keycodetoAWTMap.put( KeyCode.FULL_WIDTH, java.awt.event.KeyEvent.VK_FULL_WIDTH ); keycodetoAWTMap.put( KeyCode.HALF_WIDTH, java.awt.event.KeyEvent.VK_HALF_WIDTH ); keycodetoAWTMap.put( KeyCode.ROMAN_CHARACTERS, java.awt.event.KeyEvent.VK_ROMAN_CHARACTERS ); keycodetoAWTMap.put( KeyCode.ALL_CANDIDATES, java.awt.event.KeyEvent.VK_ALL_CANDIDATES ); keycodetoAWTMap.put( KeyCode.PREVIOUS_CANDIDATE, java.awt.event.KeyEvent.VK_PREVIOUS_CANDIDATE ); keycodetoAWTMap.put( KeyCode.CODE_INPUT, java.awt.event.KeyEvent.VK_CODE_INPUT ); keycodetoAWTMap.put( KeyCode.JAPANESE_KATAKANA, java.awt.event.KeyEvent.VK_JAPANESE_KATAKANA ); keycodetoAWTMap.put( KeyCode.JAPANESE_HIRAGANA, java.awt.event.KeyEvent.VK_JAPANESE_HIRAGANA ); keycodetoAWTMap.put( KeyCode.JAPANESE_ROMAN, java.awt.event.KeyEvent.VK_JAPANESE_ROMAN ); keycodetoAWTMap.put( KeyCode.KANA_LOCK, java.awt.event.KeyEvent.VK_KANA_LOCK ); keycodetoAWTMap.put( KeyCode.INPUT_METHOD_ON_OFF, java.awt.event.KeyEvent.VK_INPUT_METHOD_ON_OFF ); keycodetoAWTMap.put( KeyCode.CUT, java.awt.event.KeyEvent.VK_CUT ); keycodetoAWTMap.put( KeyCode.COPY, java.awt.event.KeyEvent.VK_COPY ); keycodetoAWTMap.put( KeyCode.PASTE, java.awt.event.KeyEvent.VK_PASTE ); keycodetoAWTMap.put( KeyCode.UNDO, java.awt.event.KeyEvent.VK_UNDO ); keycodetoAWTMap.put( KeyCode.AGAIN, java.awt.event.KeyEvent.VK_AGAIN ); keycodetoAWTMap.put( KeyCode.FIND, java.awt.event.KeyEvent.VK_FIND ); keycodetoAWTMap.put( KeyCode.PROPS, java.awt.event.KeyEvent.VK_PROPS ); keycodetoAWTMap.put( KeyCode.STOP, java.awt.event.KeyEvent.VK_STOP ); keycodetoAWTMap.put( KeyCode.COMPOSE, java.awt.event.KeyEvent.VK_COMPOSE ); keycodetoAWTMap.put( KeyCode.ALT_GRAPH, java.awt.event.KeyEvent.VK_ALT_GRAPH ); keycodetoAWTMap.put( KeyCode.BEGIN, java.awt.event.KeyEvent.VK_BEGIN ); keycodetoAWTMap.put( KeyCode.UNDEFINED, -1 ); } }
19,107
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
HotkeyState.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/hotkeys/HotkeyState.java
package net.joshuad.hypnos.hotkeys; import java.io.Serializable; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; public class HotkeyState implements Serializable { private static final long serialVersionUID = 1L; private KeyCode keyCode; private boolean isShiftDown; private boolean isControlDown; private boolean isAltDown; private boolean isMetaDown; public HotkeyState ( KeyCode keyCode, boolean shiftDown, boolean controlDown, boolean altDown, boolean metaDown ) { this.keyCode = keyCode; this.isShiftDown = shiftDown; this.isControlDown = controlDown; this.isAltDown = altDown; this.isMetaDown = metaDown; } public HotkeyState ( KeyEvent event ) { keyCode = event.getCode(); isShiftDown = event.isShiftDown(); isControlDown = event.isControlDown(); isAltDown = event.isAltDown(); isMetaDown = event.isMetaDown(); } public static String getDisplayText ( KeyEvent event ) { return new HotkeyState ( event ).getDisplayText(); } public KeyCode getCode() { return keyCode; } public boolean isShiftDown() { return isShiftDown; } public boolean isControlDown() { return isControlDown; } public boolean isAltDown() { return isAltDown; } public boolean isMetaDown() { return isMetaDown; } public String getDisplayText ( ) { String shortcut = ""; if ( isControlDown() ) shortcut += "Ctrl + "; if ( isAltDown() ) shortcut += "Alt + "; if ( isShiftDown() ) shortcut += "Shift + "; if ( isMetaDown() ) shortcut += "Meta + "; if ( keyCode != KeyCode.CONTROL && keyCode != KeyCode.ALT && keyCode != KeyCode.SHIFT && keyCode != KeyCode.META && keyCode != KeyCode.ALT_GRAPH && keyCode != KeyCode.WINDOWS && keyCode != KeyCode.ESCAPE ) { shortcut += keyCode.getName(); } return shortcut; } public boolean equals ( Object compareTo ) { if ( !(compareTo instanceof HotkeyState) ) return false; HotkeyState compareState = (HotkeyState)compareTo; if ( !getCode().equals( compareState.getCode() ) ) return false; if ( isShiftDown() != compareState.isShiftDown() ) return false; if ( isControlDown() != compareState.isControlDown() ) return false; if ( isAltDown() != compareState.isAltDown() ) return false; if ( isMetaDown() != compareState.isMetaDown() ) return false; return true; } }
2,334
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
GlobalHotkeyListener.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/hotkeys/GlobalHotkeyListener.java
package net.joshuad.hypnos.hotkeys; import net.joshuad.hypnos.hotkeys.GlobalHotkeys.Hotkey; public interface GlobalHotkeyListener { public void hotkeyPressed ( Hotkey hotkey ); }
185
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
LinuxGlobalHotkeys.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/hotkeys/LinuxGlobalHotkeys.java
package net.joshuad.hypnos.hotkeys; import java.io.IOException; import javafx.scene.input.KeyEvent; import jxgrabkey.HotkeyConflictException; import jxgrabkey.JXGrabKey; import jxgrabkey.X11KeysymDefinitions; import jxgrabkey.X11MaskDefinitions; import net.joshuad.hypnos.Hypnos; import net.joshuad.hypnos.hotkeys.GlobalHotkeys.Hotkey; public class LinuxGlobalHotkeys extends SystemHotkeys { public LinuxGlobalHotkeys ( GlobalHotkeys parent ) throws HotkeyException { try { System.load( Hypnos.getRootDirectory().resolve( "lib/nix/libJXGrabKey.so" ).toFile().getCanonicalPath() ); } catch ( IOException e ) { throw new HotkeyException ( "Unable to load Hotkey Library for Linux: " + e ); } JXGrabKey.getInstance().addHotkeyListener( ( int hotkeyID ) -> { if ( hotkeyID >= 0 && hotkeyID < Hotkey.values().length ) { Hotkey hotkey = Hotkey.values() [ hotkeyID ]; parent.systemHotkeyEventHappened ( hotkey ); } }); } @Override void unregisterHotkey( Hotkey hotkey ) { JXGrabKey.getInstance().unregisterHotKey ( hotkey.ordinal() ); } @Override boolean registerHotkey ( Hotkey hotkey, HotkeyState keystate ) { int hotkeyID = hotkey.ordinal(); int key = X11KeysymDefinitions.fxKeyToX11Keysym ( keystate.getCode() ); int mask = X11MaskDefinitions.fxKeyStateToX11Mask ( keystate ); if ( key == X11KeysymDefinitions.ERROR ) return false; try { JXGrabKey.getInstance().registerX11Hotkey( hotkeyID, mask, key ); } catch ( HotkeyConflictException e ) { return false; } return true; } @Override protected HotkeyState createJustPressedState( KeyEvent keyEvent ) { return null; } }
1,658
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
SystemHotkeys.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/hotkeys/SystemHotkeys.java
package net.joshuad.hypnos.hotkeys; import javafx.scene.input.KeyEvent; import net.joshuad.hypnos.hotkeys.GlobalHotkeys.Hotkey; public abstract class SystemHotkeys { abstract void unregisterHotkey ( Hotkey key ); abstract boolean registerHotkey ( Hotkey hotkey, HotkeyState event ); protected abstract HotkeyState createJustPressedState( KeyEvent keyEvent ); }
366
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
HotkeyException.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/hotkeys/HotkeyException.java
package net.joshuad.hypnos.hotkeys; public class HotkeyException extends Exception { private static final long serialVersionUID = 1L; private String message; public HotkeyException ( String message ) { this.message = message; } public String getMessage() { return message; } }
296
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
DummyGlobalHotkeys.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/hotkeys/DummyGlobalHotkeys.java
package net.joshuad.hypnos.hotkeys; import javafx.scene.input.KeyEvent; import net.joshuad.hypnos.hotkeys.GlobalHotkeys.Hotkey; public class DummyGlobalHotkeys extends SystemHotkeys { public DummyGlobalHotkeys( GlobalHotkeys parent ) {} @Override public boolean registerHotkey ( Hotkey hotkey, HotkeyState event ) { return false; } @Override void unregisterHotkey ( Hotkey key ) {} @Override protected HotkeyState createJustPressedState(KeyEvent keyEvent) { return null; } }
498
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
GlobalHotkeys.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/hotkeys/GlobalHotkeys.java
package net.joshuad.hypnos.hotkeys; import java.util.ArrayList; import java.util.EnumMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javafx.scene.input.KeyEvent; import net.joshuad.hypnos.Hypnos.OS; public class GlobalHotkeys { private static transient final Logger LOGGER = Logger.getLogger( GlobalHotkeys.class.getName() ); public enum Hotkey { PREVIOUS ( "Previous" ), NEXT ( "Next" ), PLAY_PAUSE ( "Play / Pause" ), PLAY ( "Play" ), STOP ( "Stop" ), VOLUME_UP ( "Volume Up" ), VOLUME_DOWN ( "Volume Down" ), TOGGLE_MUTE ( "Mute / Unmute" ), TOGGLE_SHUFFLE ( "Toggle Shuffle" ), TOGGLE_REPEAT ( "Toggle Repeat" ), SHOW_HIDE_UI ( "Show / Hide Main Window" ), SKIP_FORWARD ( "Forward 5 Seconds" ), SKIP_BACK ( "Back 5 Seconds" ); private String label; Hotkey ( String label ) { this.label = label; } public String getLabel () { return label; } } List<GlobalHotkeyListener> listeners = new ArrayList<>(); Map <Hotkey, HotkeyState> hotkeyMap = new EnumMap <> ( Hotkey.class ); private boolean disabled = false; boolean hasUnsavedData = false; private boolean inEditMode = false; private SystemHotkeys system; public GlobalHotkeys( OS operatingSystem, boolean disabled ) { this.disabled = disabled; this.hasUnsavedData = true; try { switch ( operatingSystem ) { case NIX: system = new LinuxGlobalHotkeys( this ); break; case OSX: throw new HotkeyException ( "OSX does not currently support hotkeys." ); case WIN_10: case WIN_7: case WIN_8: case WIN_UNKNOWN: case WIN_VISTA: system = new WindowsGlobalHotkeys( this ); break; case WIN_XP: throw new HotkeyException ( "Windows XP not supported by Hypnos." ); case UNKNOWN: default: throw new HotkeyException ( "Cannot recognize operating system." ); } } catch ( HotkeyException e ) { system = new DummyGlobalHotkeys ( this ); disabled = true; LOGGER.log( Level.WARNING, "Unable to setup global hotkeys, they will be disabled for this session." + e ); } } public void addListener ( GlobalHotkeyListener listener ) { listeners.add ( listener ); } public boolean hasUnsavedData () { return hasUnsavedData; } public void setHasUnsavedData ( boolean b ) { hasUnsavedData = b; } public boolean isDisabled() { return disabled || system instanceof DummyGlobalHotkeys; } public String getReasonDisabled() { if ( disabled ) { return "Disabled at launch"; } else if ( system instanceof DummyGlobalHotkeys ) { return "Global Hotkeys not currently supported by Hypnos for your Operating System."; } else { return ""; } } public boolean registerFXHotkey ( Hotkey hotkey, KeyEvent event ) { if ( isDisabled() ) return false; return registerHotkey ( hotkey, new HotkeyState ( event ) ); } public boolean registerHotkey ( Hotkey hotkey, HotkeyState keystate ) { if ( isDisabled() ) return false; if ( keystate == null ) return false; for ( Hotkey existingKey : hotkeyMap.keySet() ) { if ( keystate.equals( hotkeyMap.get( existingKey ) ) ) { clearHotkey ( existingKey ); } } boolean result = system.registerHotkey ( hotkey, keystate ); if ( inEditMode ) { system.unregisterHotkey ( hotkey ); } if ( result ) { hotkeyMap.put( hotkey, keystate ); hasUnsavedData = true; } return result; } public void beginEditMode() { if ( isDisabled() ) return; if ( !inEditMode ) { for ( Hotkey hotkey : hotkeyMap.keySet() ) { system.unregisterHotkey ( hotkey ); } inEditMode = true; } } public void endEditMode() { if ( isDisabled() ) return; if ( inEditMode ) { for ( Hotkey hotkey : hotkeyMap.keySet() ) { system.registerHotkey ( hotkey, hotkeyMap.get( hotkey ) ); } inEditMode = false; } } public void prepareToExit() { for ( Hotkey hotkey : hotkeyMap.keySet() ) { system.unregisterHotkey ( hotkey ); } } public void clearAllHotkeys() { if ( isDisabled() ) return; for ( Hotkey hotkey : hotkeyMap.keySet() ) { clearHotkey ( hotkey ); } } public void clearHotkey ( Hotkey key ) { if ( isDisabled() ) return; if ( key == null ) return; hotkeyMap.remove( key ); hasUnsavedData = true; system.unregisterHotkey ( key ); } public Map <Hotkey, HotkeyState> getMap() { return hotkeyMap; } public void setMap ( EnumMap <Hotkey, HotkeyState> map ) { this.hotkeyMap = map; if ( isDisabled() ) return; for ( Hotkey hotkey : map.keySet() ) { registerHotkey ( hotkey, map.get( hotkey ) ); } } public String getDisplayText ( Hotkey hotkey ) { HotkeyState state = hotkeyMap.get( hotkey ); if ( state == null ) { return ""; } else { return hotkeyMap.get( hotkey ).getDisplayText( ); } } void systemHotkeyEventHappened ( Hotkey hotkey ) { if ( isDisabled() || inEditMode ) return; for ( GlobalHotkeyListener listener : listeners ) { listener.hotkeyPressed ( hotkey ); } } public HotkeyState createJustPressedState ( KeyEvent keyEvent ) { return system.createJustPressedState ( keyEvent ); } }
5,192
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
IntellitypeHotkeyState.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/hotkeys/IntellitypeHotkeyState.java
package net.joshuad.hypnos.hotkeys; import javafx.scene.input.KeyEvent; public class IntellitypeHotkeyState extends HotkeyState { private static final long serialVersionUID = 1L; private int intellitypeCommand = -1; private String name; public IntellitypeHotkeyState ( KeyEvent event, int intellitypeCommand, String name ) { super ( null, event.isShiftDown(), event.isControlDown(), event.isAltDown(), event.isMetaDown() ); this.intellitypeCommand = intellitypeCommand; this.name = name; } public int getIntellitypeCommand () { return intellitypeCommand; } @Override public String getDisplayText ( ) { String shortcut = ""; if ( isControlDown() ) shortcut += "Ctrl + "; if ( isAltDown() ) shortcut += "Alt + "; if ( isShiftDown() ) shortcut += "Shift + "; if ( isMetaDown() ) shortcut += "Meta + "; shortcut += name; return shortcut; } public boolean equals ( Object compareTo ) { if ( !(compareTo instanceof IntellitypeHotkeyState) ) return false; IntellitypeHotkeyState compareState = (IntellitypeHotkeyState)compareTo; if ( getIntellitypeCommand() != compareState.getIntellitypeCommand() ) return false; if ( isShiftDown() != compareState.isShiftDown() ) return false; if ( isControlDown() != compareState.isControlDown() ) return false; if ( isAltDown() != compareState.isAltDown() ) return false; if ( isMetaDown() != compareState.isMetaDown() ) return false; return true; } }
1,460
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
NativeTrayIcon.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/trayicon/NativeTrayIcon.java
package net.joshuad.hypnos.trayicon; public abstract class NativeTrayIcon { public abstract void show(); public abstract void hide(); protected abstract void prepareToExit(); }
183
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
TrayIcon.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/trayicon/TrayIcon.java
package net.joshuad.hypnos.trayicon; import java.util.logging.Level; import java.util.logging.Logger; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import net.joshuad.hypnos.Hypnos; import net.joshuad.hypnos.audio.AudioSystem; import net.joshuad.hypnos.fxui.FXUI; public class TrayIcon { private static final Logger LOGGER = Logger.getLogger( TrayIcon.class.getName() ); private NativeTrayIcon nativeTrayIcon; private BooleanProperty systemTraySupported = new SimpleBooleanProperty ( true ); public TrayIcon ( FXUI ui, AudioSystem audioSystem ) { switch ( Hypnos.getOS() ) { case NIX: try { nativeTrayIcon = new LinuxTrayIcon( ui, audioSystem ); nativeTrayIcon.hide(); } catch ( Exception | UnsatisfiedLinkError e ) { LOGGER.log( Level.INFO, "Unable to initialize linux tray icon.", e ); nativeTrayIcon = null; } break; case OSX: case WIN_10: case WIN_7: case WIN_8: case WIN_UNKNOWN: case WIN_VISTA: nativeTrayIcon = new WindowsTrayIcon( ui, audioSystem ); break; case WIN_XP: //Do nothing, windows xp not supported case UNKNOWN: default: } systemTraySupported.set( nativeTrayIcon != null ); } public boolean isSupported() { return systemTraySupported.get(); } public BooleanProperty systemTraySupportedProperty() { return systemTraySupported; } public void show() { if ( nativeTrayIcon != null ) { nativeTrayIcon.show(); } } public void hide() { if ( nativeTrayIcon != null ) { nativeTrayIcon.hide(); } } public void prepareToExit() { if ( nativeTrayIcon != null ) { nativeTrayIcon.prepareToExit(); } } }
1,717
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
WindowsTrayIcon.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/trayicon/WindowsTrayIcon.java
package net.joshuad.hypnos.trayicon; import java.util.logging.Level; import java.util.logging.Logger; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Tray; import org.eclipse.swt.widgets.TrayItem; import net.joshuad.hypnos.Hypnos; import net.joshuad.hypnos.Hypnos.ExitCode; import net.joshuad.hypnos.audio.AudioSystem; import net.joshuad.hypnos.audio.AudioSystem.RepeatMode; import net.joshuad.hypnos.audio.AudioSystem.ShuffleMode; import net.joshuad.hypnos.audio.AudioSystem.StopReason; import net.joshuad.hypnos.audio.PlayerListener; import net.joshuad.hypnos.fxui.FXUI; import net.joshuad.hypnos.library.Track; public class WindowsTrayIcon extends NativeTrayIcon implements PlayerListener { private static final Logger LOGGER = Logger.getLogger( WindowsTrayIcon.class.getName() ); private FXUI ui; private Display swtDisplay; private TrayItem trayIcon; private Shell shell; private Menu menu; private MenuItem play; private Object lock = new Object(); private boolean hideTrayIconRequested = false; private boolean showTrayIconRequested = false; private boolean exitRequested = false; private boolean setTextToPlay = false; private boolean setTextToPause = false; private boolean setTextToUnmute = false; private boolean setTextToMute = false; private boolean setTextToHide = false; private boolean setTextToShow =false; public WindowsTrayIcon ( FXUI ui, AudioSystem audioSystem ) { this.ui = ui; Thread t = new Thread (() -> { swtDisplay = new Display(); shell = new Shell( swtDisplay ); menu = new Menu( shell, SWT.POP_UP ); MenuItem toggleShow = new MenuItem( menu, SWT.PUSH ); toggleShow.setText( "Hide" ); toggleShow.addListener( SWT.Selection, (Event e) -> { ui.toggleHidden(); }); ui.getMainStage().showingProperty().addListener( ( obs, wasShowing, isShowing ) -> { synchronized ( lock ) { if ( isShowing ) { setTextToHide = true; setTextToShow = false; } else { setTextToHide = false; setTextToShow = true; } } }); new MenuItem( menu, SWT.SEPARATOR ); play = new MenuItem( menu, SWT.PUSH ); play.setText( "Play" ); play.addListener( SWT.Selection, (Event e) -> { audioSystem.togglePlayPause(); }); MenuItem next = new MenuItem( menu, SWT.PUSH ); next.setText( "Next" ); next.addListener( SWT.Selection, (Event e) -> { audioSystem.next(); }); MenuItem previous = new MenuItem( menu, SWT.PUSH ); previous.setText( "Previous" ); previous.addListener( SWT.Selection, (Event e) -> { audioSystem.previous(); }); MenuItem stop = new MenuItem( menu, SWT.PUSH ); stop.setText( "Stop" ); stop.addListener( SWT.Selection, (Event e) -> { audioSystem.stop( StopReason.USER_REQUESTED ); }); MenuItem toggleMute = new MenuItem( menu, SWT.PUSH ); toggleMute.setText( audioSystem.getVolumePercent() == 0 ? "Unmute" : "Mute" ); toggleMute.addListener( SWT.Selection, (Event e) -> { audioSystem.toggleMute(); }); new MenuItem( menu, SWT.SEPARATOR ); MenuItem quit = new MenuItem( menu, SWT.PUSH ); quit.setText( "Quit" ); quit.addListener( SWT.Selection, (Event e) -> { if ( trayIcon != null ) { trayIcon.setVisible ( false ); } swtDisplay.dispose(); Hypnos.exit( ExitCode.NORMAL ); }); while ( !shell.isDisposed() ) { synchronized ( lock ) { if ( showTrayIconRequested ) { if ( trayIcon == null ) { initializeTrayIcon(); } trayIcon.setVisible ( true ); showTrayIconRequested = false; } if ( hideTrayIconRequested ) { if ( trayIcon != null ) { trayIcon.setVisible ( false ); } hideTrayIconRequested = false; } if ( setTextToPlay ) { play.setText( "Play" ); setTextToPlay = false; } if ( setTextToPause ) { play.setText( "Pause" ); setTextToPause = false; } if ( setTextToUnmute ) { toggleMute.setText( "Unmute" ); setTextToUnmute = false; } if ( setTextToMute ) { toggleMute.setText( "Mute" ); setTextToMute = false; } if ( setTextToShow ) { toggleShow.setText( "Show" ); setTextToShow = false; } if ( setTextToHide ) { toggleShow.setText( "Hide" ); setTextToHide = false; } } if ( !swtDisplay.readAndDispatch() ) { try { Thread.sleep( 25 ); } catch (InterruptedException e1) { LOGGER.log ( Level.INFO, "Interrupted during swt sleep loop", e1 ); } } if ( exitRequested ) { if ( trayIcon != null ) { trayIcon.setVisible ( false ); } swtDisplay.dispose(); } } }); t.setDaemon( true ); t.setName("SWT Tray Icon Thread"); t.start(); audioSystem.addPlayerListener( this ); } public void initializeTrayIcon () { Tray tray = shell.getDisplay().getSystemTray(); trayIcon = new TrayItem( tray, SWT.NONE ); trayIcon.setImage( new Image( swtDisplay, Hypnos.getRootDirectory().resolve( "resources/icon.png" ).toString() ) ); trayIcon.addListener( SWT.Selection, (Event event) -> { ui.toggleHidden(); }); trayIcon.addListener( SWT.MenuDetect, (Event event) -> { menu.setVisible( true ); }); } @Override public void show() { showTrayIconRequested = true; } @Override public void hide() { hideTrayIconRequested = true; } @Override protected void prepareToExit() { exitRequested = true; } @Override public void playerStopped(Track track, StopReason reason) { synchronized ( lock ) { setTextToPlay = true; setTextToPause = false; } } @Override public void playerStarted(Track track) { synchronized ( lock ) { setTextToPlay = false; setTextToPause = true; } } @Override public void playerPaused() { synchronized ( lock ) { setTextToPlay = true; setTextToPause = false; } } @Override public void playerUnpaused() { synchronized ( lock ) { setTextToPlay = false; setTextToPause = true; } } @Override public void playerVolumeChanged(double newVolumePercent) { synchronized ( lock ) { if ( newVolumePercent == 0 ) { setTextToUnmute = true; setTextToMute = false; } else { setTextToUnmute = false; setTextToMute = true; } } } @Override public void playerShuffleModeChanged(ShuffleMode newMode) {} @Override public void playerRepeatModeChanged(RepeatMode newMode) {} @Override public void playerPositionChanged(int positionMS, int lengthMS) {} /* private Image toIcon ( Image image, int size ) { ImageData data = image.getImageData().scaledTo( size, size ); for (int x = 0; x < data.width; x++ ) { for ( int y = 0; y < data.height; y++ ) { data.setPixel( x, y, 0x333333 ); } } return new Image ( swtDisplay, data ); } Image previousImage = new Image( swtDisplay, Hypnos.getRootDirectory().resolve( "resources/previous.png" ).toString() ); previousImage = toIcon ( previousImage, 14 ); Image stopImage = new Image( swtDisplay, Hypnos.getRootDirectory().resolve( "resources/stop.png" ).toString() ); stopImage = toIcon ( stopImage, 14 ); Image nextImage = new Image( swtDisplay, Hypnos.getRootDirectory().resolve( "resources/next.png" ).toString() ); nextImage = toIcon ( nextImage, 14 ); Image pauseImage = new Image( swtDisplay, Hypnos.getRootDirectory().resolve( "resources/pause.png" ).toString() ); pauseImage = toIcon ( pauseImage, 14 ); Image playImage = new Image( swtDisplay, Hypnos.getRootDirectory().resolve( "resources/play.png" ).toString() ); playImage = toIcon ( playImage, 14 ); Image muteImage = new Image( swtDisplay, Hypnos.getRootDirectory().resolve( "resources/vol-0.png" ).toString() ); muteImage = toIcon ( muteImage, 14 ); Image unuteImage = new Image( swtDisplay, Hypnos.getRootDirectory().resolve( "resources/vol-3.png" ).toString() ); unuteImage = toIcon ( unuteImage, 14 ); Image quitImage = new Image( swtDisplay, Hypnos.getRootDirectory().resolve( "resources/clear.png" ).toString() ); quitImage = toIcon ( quitImage, 14 ); */ }
8,413
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
LinuxTrayIcon.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/trayicon/LinuxTrayIcon.java
package net.joshuad.hypnos.trayicon; import java.io.IOException; import net.joshuad.hypnos.Hypnos; import net.joshuad.hypnos.Hypnos.ExitCode; import net.joshuad.hypnos.audio.AudioSystem; import net.joshuad.hypnos.audio.AudioSystem.StopReason; import net.joshuad.hypnos.fxui.FXUI; public class LinuxTrayIcon extends NativeTrayIcon { private native void initTrayIcon ( String iconLocation ); private native void showTrayIcon (); private native void hideTrayIcon (); private boolean doneInit = true; private boolean exitRequested = false; private boolean toggleUIRequested = false; private boolean playRequested = false; private boolean pauseRequested = false; private boolean previousRequested = false; private boolean nextRequested = false; private boolean stopRequested = false; private boolean muteRequested = false; private FXUI ui; private AudioSystem audioSystem; public LinuxTrayIcon ( FXUI ui, AudioSystem audioSystem ) throws IOException { this.ui = ui; this.audioSystem = audioSystem; System.load ( Hypnos.getRootDirectory().resolve( "lib/nix/tray_icon_jni64.so" ).toFile().getCanonicalPath() ); Thread gtkThread = new Thread( () -> { initTrayIcon( Hypnos.getRootDirectory().resolve( "resources/icon.png" ).toFile().getAbsoluteFile().toString() ); }); gtkThread.setName( "GTK Tray Icon Thread" ); gtkThread.setDaemon( true ); doneInit = false; gtkThread.start(); int pauseTime = 0; while ( !doneInit && pauseTime < 1000 ) { try { pauseTime += 5; Thread.sleep( 5 ); } catch ( InterruptedException e ) { } } if ( !doneInit ) { throw new IOException ( "Unable to init tray icon. Aborted after 1 second." ); } Thread enacterThread = new Thread( () -> { while ( true ) { if ( exitRequested ) Hypnos.exit( ExitCode.NORMAL ); if ( toggleUIRequested ) ui.toggleHidden(); if ( playRequested ) audioSystem.play(); if ( pauseRequested ) audioSystem.pause(); if ( previousRequested ) audioSystem.previous(); if ( nextRequested ) audioSystem.next(); if ( stopRequested ) audioSystem.stop( StopReason.USER_REQUESTED ); if ( muteRequested ) audioSystem.toggleMute(); exitRequested = false; toggleUIRequested = false; playRequested = false; pauseRequested = false; previousRequested = false; nextRequested = false; stopRequested = false; muteRequested = false; try { Thread.sleep( 25 ); } catch ( InterruptedException e ) { } } } ); enacterThread.setName( "Enacter thread for GTK requests" ); enacterThread.setDaemon( true ); enacterThread.start(); } @Override public void show () { showTrayIcon(); } @Override public void hide () { hideTrayIcon(); } void jni_doneInit () { doneInit = true; } void jni_requestExit () { exitRequested = true; } void jni_requestToggleUI () { toggleUIRequested = true; } void jni_requestPlay () { playRequested = true; } void jni_requestPause () { pauseRequested = true; } void jni_requestPrevious () { previousRequested = true; } void jni_requestNext () { nextRequested = true; } void jni_requestStop () { stopRequested = true; } void jni_requestMute () { muteRequested = true; } @Override protected void prepareToExit() { // TODO Auto-generated method stub } }
3,394
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
LastFM.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/lastfm/LastFM.java
package net.joshuad.hypnos.lastfm; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; import de.umass.lastfm.Authenticator; import de.umass.lastfm.Caller; import de.umass.lastfm.Result; import de.umass.lastfm.Session; import de.umass.lastfm.Track; import de.umass.lastfm.User; import de.umass.lastfm.scrobble.ScrobbleResult; import de.umass.util.StringUtilities; import net.joshuad.hypnos.Hypnos; public class LastFM { public enum LovedState { TRUE, FALSE, NOT_SET, CANNOT_GET_DATA }; private String key = "accf97169875efd9a189520ee542c1f6"; private String secret = "534851bcd3b6441dc91c9c970c766666"; private String username = ""; private String password = ""; private Session session; private boolean triedConnectWithTheseCredentials = true; private boolean notifiedUserOfFailedAttempt = false; StringBuffer log = new StringBuffer(); SimpleDateFormat timeStampFormat = new SimpleDateFormat( "yyyy/MM/dd hh:mm:ss aaa" ); public LastFM() { Logger logger = Logger.getLogger( Caller.class.getPackage().getName() ); logger.setLevel( Level.OFF ); Caller.getInstance().setUserAgent( "hypnos-music-player" ); } public void setPassword ( String password ) { if ( password == null ) { password = ""; } else if ( !StringUtilities.isMD5 ( password ) ) { password = StringUtilities.md5 ( password ); } this.password = password; triedConnectWithTheseCredentials = false; } public void setUsername ( String username ) { if ( username == null ) { username = ""; } this.username = username; triedConnectWithTheseCredentials = false; } public void setCredentials( String username, String password ) { setUsername ( username ); setPassword ( password ); } public void connect () { session = Authenticator.getMobileSession( username, password, key, secret ); if ( session == null ) { log.append ( "Unable to connect to lastfm. Check your username, password, and internet connection.\n" ); } else { log.append ( "Successfully connected to lastfm.\n" ); } triedConnectWithTheseCredentials = true; } public void disconnectAndForgetCredentials() { setCredentials ( "", "" ); if ( session == null ) { log.append ( "Not connected. Credentials forgotten.\n" ); } else { session = null; log.append ( "Disconnected and credentials forgotten.\n" ); } } //This should be called after any attempted write to lastfm public void notifyUserIfNeeded( boolean success ) { if ( success ) { notifiedUserOfFailedAttempt = false; } else if ( !success && !notifiedUserOfFailedAttempt ) { Hypnos.getUI().notifyUserError( "Unable to connect to lastfm.\n\n" + "Check your internet connection, username, and password.\n\n" + "(This popup won't appear again this session.)" ); notifiedUserOfFailedAttempt = true; } } public void scrobbleTrack ( net.joshuad.hypnos.library.Track track ) { String timeStamp = timeStampFormat.format( new Date ( System.currentTimeMillis() ) ); if ( track == null ) { log.append ( "[" + timeStamp + "] Asked to scrobble a null track, ignoring.\n" ); return; } String artist = track.getArtist(); String title = track.getTitle(); if ( !triedConnectWithTheseCredentials ) connect(); if ( session == null ) { log.append( "[" + timeStamp + "] Invalid session, unable to scrobble: " + artist + " - " + title + "\n" ); notifyUserIfNeeded( false ); return; } log.append( "[" + timeStamp + "] Attempting to Scrobble: " + artist + " - " + title + " ... " ); int now = (int) (System.currentTimeMillis() / 1000); ScrobbleResult result = Track.scrobble( artist, title, now, session ); boolean success = result.isSuccessful() && !result.isIgnored(); log.append ( success ? "success!" : "failed." ); log.append ( "\n" ); notifyUserIfNeeded( success ); return; } public void loveTrack ( net.joshuad.hypnos.library.Track track ) { String timeStamp = timeStampFormat.format( new Date ( System.currentTimeMillis() ) ); if ( track == null ) { log.append ( "[" + timeStamp + "] Asked to love a null track, ignoring.\n" ); return; } String artist = track.getArtist(); String title = track.getTitle(); if ( !triedConnectWithTheseCredentials ) connect(); if ( session == null ) { log.append( "[" + timeStamp + "] Invalid session, unable to love: " + artist + " - " + title + "\n" ); notifyUserIfNeeded( false ); return; } log.append( "[" + timeStamp + "] Attempting to Love: " + artist + " - " + title + " ... " ); Result result = Track.love( artist, title, session ); boolean success = result.isSuccessful(); if ( success ) track.setLovedState ( LovedState.TRUE ); log.append ( success ? "success!" : "failed - " + result.getErrorMessage() ); log.append ( "\n" ); notifyUserIfNeeded( success ); } public void unloveTrack ( net.joshuad.hypnos.library.Track track ) { String timeStamp = timeStampFormat.format( new Date ( System.currentTimeMillis() ) ); if ( track == null ) { log.append ( "[" + timeStamp + "] Asked to unlove a null track, ignoring.\n" ); return; } String artist = track.getArtist(); String title = track.getTitle(); if ( !triedConnectWithTheseCredentials ) connect(); if ( session == null ) { log.append( "[" + timeStamp + "] Invalid session, unable to unlove: " + artist + " - " + title + "\n" ); notifyUserIfNeeded( false ); return; } log.append( "[" + timeStamp + "] Attempting to Unlove: " + artist + " - " + title + " ... " ); Result result = Track.unlove( artist, title, session ); boolean success = result.isSuccessful(); if ( success ) track.setLovedState ( LovedState.FALSE ); log.append ( success ? "success!" : "failed - " + result.getErrorMessage() ); log.append ( "\n" ); if ( success ) notifiedUserOfFailedAttempt = false; } public LovedState isLoved ( net.joshuad.hypnos.library.Track track, boolean fromCache ) { if ( track == null ) return LovedState.FALSE; if ( fromCache && track.getLovedState() != LovedState.NOT_SET ) return track.getLovedState(); String artist = track.getArtist(); String title = track.getTitle(); if ( artist == null || title == null ) { return LovedState.FALSE; } if ( !triedConnectWithTheseCredentials ) connect(); String timeStamp = timeStampFormat.format( new Date ( System.currentTimeMillis() ) ); if ( session == null ) { log.append( "[" + timeStamp + "] Invalid session, cannot check if loved: " + artist + " - " + title + "\n" ); track.setLovedState( LovedState.CANNOT_GET_DATA ); return LovedState.CANNOT_GET_DATA; } Collection<Track> lovedTracks = User.getLovedTracks( session.getUsername(), key ).getPageResults(); for ( Track test : lovedTracks ) { if ( test.getArtist().toLowerCase().equals( artist.toLowerCase() ) && test.getName().toLowerCase().equals( title.toLowerCase() ) ) { track.setLovedState( LovedState.TRUE ); return LovedState.TRUE; } } track.setLovedState( LovedState.FALSE ); return LovedState.FALSE; } public void toggleLoveTrack ( net.joshuad.hypnos.library.Track track ) { switch ( isLoved ( track, false ) ) { case FALSE: loveTrack( track ); break; case TRUE: unloveTrack( track ); break; case CANNOT_GET_DATA: notifyUserIfNeeded( false ); break; case NOT_SET: //This should be impossible. break; } } public StringBuffer getLog () { return log; } public String getUsername() { return username; } public String getPasswordMD5() { return password; } }
7,757
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
VLCAudioPlayer.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/audio/VLCAudioPlayer.java
package net.joshuad.hypnos.audio; import java.io.File; import java.nio.file.Files; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import com.sun.jna.NativeLibrary; import net.joshuad.hypnos.Hypnos; import net.joshuad.hypnos.Hypnos.ExitCode; import net.joshuad.hypnos.audio.AudioSystem.StopReason; import net.joshuad.hypnos.fxui.FXUI; import net.joshuad.hypnos.library.Track; import uk.co.caprica.vlcj.binding.internal.libvlc_state_t; import uk.co.caprica.vlcj.component.AudioMediaPlayerComponent; import uk.co.caprica.vlcj.player.MediaPlayer; import uk.co.caprica.vlcj.player.MediaPlayerEventAdapter; import uk.co.caprica.vlcj.runtime.RuntimeUtil; public class VLCAudioPlayer { private static final Logger LOGGER = Logger.getLogger( VLCAudioPlayer.class.getName() ); public enum PlayState { STOPPED, PAUSED, PLAYING; } PlayState state = PlayState.STOPPED; AudioSystem controller; Track currentTrack = null; private AudioMediaPlayerComponent vlcComponent; private MediaPlayer mediaPlayer; private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); private Runnable notifyFinished = new Runnable () { public void run() { controller.playerStopped( currentTrack, StopReason.TRACK_FINISHED ); } }; private int currentVolume = 100; public VLCAudioPlayer( AudioSystem controller ) { this.controller = controller; String nativeVLCLibPath = ""; switch ( Hypnos.getOS() ) { case NIX: nativeVLCLibPath = Hypnos.getRootDirectory().resolve( "lib/nix/vlc/" ).toAbsolutePath().toString(); break; case OSX: nativeVLCLibPath = Hypnos.getRootDirectory().resolve( "lib/osx/vlc" ).toAbsolutePath().toString(); break; case UNKNOWN: break; case WIN_10: case WIN_7: case WIN_8: case WIN_UNKNOWN: case WIN_VISTA: nativeVLCLibPath = Hypnos.getRootDirectory().resolve( "lib/win/vlc" ).toAbsolutePath().toString(); break; case WIN_XP: //Do nothing, Windows XP not supported default: LOGGER.log( Level.SEVERE, "Cannot determine OS, unable to load native VLC libraries. Exiting." ); Hypnos.exit( ExitCode.UNSUPPORTED_OS ); break; } try { NativeLibrary.addSearchPath( RuntimeUtil.getLibVlcLibraryName(), nativeVLCLibPath ); vlcComponent = new AudioMediaPlayerComponent(); mediaPlayer = vlcComponent.getMediaPlayer(); } catch ( Exception e ) { LOGGER.log( Level.SEVERE, "Unable to load VLC libaries.", e ); FXUI.notifyUserVLCLibraryError(); Hypnos.exit( ExitCode.AUDIO_ERROR ); } mediaPlayer.addMediaPlayerEventListener(new MediaPlayerEventAdapter() { public void finished ( MediaPlayer player ) { scheduler.schedule( notifyFinished, 50, TimeUnit.MILLISECONDS ); } //Can do either timeChanged or positionChanged, don't do both (duplicative) public void timeChanged ( MediaPlayer player, long newTime ) { updateControllerTrackPosition(); } public void backward ( MediaPlayer player ) { updateControllerTrackPosition(); } public void forward ( MediaPlayer player ) { updateControllerTrackPosition(); } public void paused ( MediaPlayer player ) { controller.playerPaused(); } public void playing ( MediaPlayer player ) { controller.playerStarted( currentTrack ); } }); } private void updateControllerTrackPosition() { if ( currentTrack != null ) { int lengthMS = currentTrack.getLengthS() * 1000; double positionPercent = mediaPlayer.getPosition(); int timeElapsedMS = (int)( lengthMS * positionPercent ); controller.playerTrackPositionChanged ( currentTrack, timeElapsedMS, lengthMS ); } } public void requestTogglePause() { mediaPlayer.setPause( vlcComponent.getMediaPlayer().isPlaying() ); } public void requestUnpause() { mediaPlayer.setPause( false ); } public void requestPause() { mediaPlayer.setPause( true ); } public void requestStop() { mediaPlayer.stop(); currentTrack = null; } public void requestPlayTrack( Track track, boolean startPaused ) { String targetFile = track.getPath().toString(); if ( !Files.isRegularFile( track.getPath() ) || !Files.exists( track.getPath() ) ) { scheduler.schedule( notifyFinished, 50, TimeUnit.MILLISECONDS ); return; } //Address this bug: https://github.com/caprica/vlcj/issues/645 switch ( Hypnos.getOS() ) { case NIX: case OSX: case UNKNOWN: default: break; case WIN_10: case WIN_7: case WIN_8: case WIN_UNKNOWN: case WIN_VISTA: //Assumes filename is an absolute file location. targetFile = new File( targetFile ).toURI().toASCIIString().replaceFirst( "file:/", "file:///" ); break; case WIN_XP: //Do nothing, windows XP not supported break; } mediaPlayer.playMedia( targetFile ); scheduler.schedule( new Runnable() { public void run() { mediaPlayer.setVolume( currentVolume ); } }, 100, TimeUnit.MILLISECONDS ); currentTrack = track; if ( startPaused ) { mediaPlayer.setPause( true ); } } //VLC accepts 0 ... 200 as range for volume public void requestVolumePercent ( double volumePercent ) { //TODO: allow up to 200% volume, maybe. VLC supports it. if ( volumePercent < 0 ) { LOGGER.log( Level.INFO, "Volume requested to be turned down below 0. Setting to 0 instead.", new Exception() ); volumePercent = 0; } if ( volumePercent > 1 ) { LOGGER.log( Level.INFO, "Volume requested to be more than 1 (i.e. 100%). Setting to 1 instead.", new Exception() ); volumePercent = 1; } int vlcValue = (int)(volumePercent * 100f); if ( vlcValue != currentVolume ) { currentVolume = vlcValue; if ( !isStopped() ) { mediaPlayer.setVolume( vlcValue ); } controller.volumeChanged ( currentVolume/100f ); } } public double getVolumePercent () { int vlcVolume = currentVolume; double hypnosVolume = ((double)vlcVolume)/100; return hypnosVolume; } public Track getTrack() { return currentTrack; } public void requestSeekPercent ( double seekPercent ) { mediaPlayer.setPosition( (float)seekPercent ); updateControllerTrackPosition(); } public long getPositionMS() { int lengthMS = currentTrack.getLengthS() * 1000; double positionPercent = mediaPlayer.getPosition(); long timeElapsedMS = (long)(lengthMS * positionPercent); return timeElapsedMS; } public void requestIncrementMS ( int diffMS ) { mediaPlayer.setTime( getPositionMS() + diffMS ); updateControllerTrackPosition(); } public void requestSeekMS ( long seekMS ) { mediaPlayer.setTime( seekMS ); updateControllerTrackPosition(); } public PlayState getState() { if ( isStopped() ) return PlayState.STOPPED; else if ( isPaused() ) return PlayState.PAUSED; else return PlayState.PLAYING; } public boolean isStopped () { return currentTrack == null; } public boolean isPaused () { return mediaPlayer.getMediaState() == libvlc_state_t.libvlc_Paused; } public boolean isPlaying() { return mediaPlayer.getMediaState() == libvlc_state_t.libvlc_Playing; } public void releaseResources() { mediaPlayer.release(); } }
7,315
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
PlayerListener.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/audio/PlayerListener.java
package net.joshuad.hypnos.audio; import net.joshuad.hypnos.audio.AudioSystem.RepeatMode; import net.joshuad.hypnos.audio.AudioSystem.ShuffleMode; import net.joshuad.hypnos.audio.AudioSystem.StopReason; import net.joshuad.hypnos.library.Track; public interface PlayerListener { public void playerPositionChanged ( int positionMS, int lengthMS ); public void playerStopped ( Track track, StopReason reason ); public void playerStarted ( Track track ); public void playerPaused (); public void playerUnpaused (); public void playerVolumeChanged ( double newVolumePercent ); public void playerShuffleModeChanged ( ShuffleMode newMode ); public void playerRepeatModeChanged ( RepeatMode newMode ); }
707
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
AudioSystem.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/audio/AudioSystem.java
package net.joshuad.hypnos.audio; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.EnumMap; import java.util.List; import java.util.ListIterator; import java.util.Random; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import javafx.beans.property.BooleanProperty; import javafx.beans.property.DoubleProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleDoubleProperty; import net.joshuad.hypnos.CurrentList; import net.joshuad.hypnos.CurrentListTrack; import net.joshuad.hypnos.History; import net.joshuad.hypnos.Hypnos; import net.joshuad.hypnos.Persister; import net.joshuad.hypnos.PreviousStack; import net.joshuad.hypnos.Queue; import net.joshuad.hypnos.fxui.FXUI; import net.joshuad.hypnos.lastfm.LastFM; import net.joshuad.hypnos.library.Playlist; import net.joshuad.hypnos.library.Track; import net.joshuad.hypnos.Persister.Setting; public class AudioSystem { private static final Logger LOGGER = Logger.getLogger( AudioSystem.class.getName() ); public enum StopReason { TRACK_FINISHED, USER_REQUESTED, END_OF_CURRENT_LIST, EMPTY_LIST, WRITING_TO_TAG, UNABLE_TO_START_TRACK, ERROR } public enum ShuffleMode { SEQUENTIAL ( "⇉" ), SHUFFLE ( "🔀" ); String symbol; ShuffleMode ( String symbol ) { this.symbol = symbol; } public String getSymbol () { return symbol; } } public enum RepeatMode { PLAY_ONCE ( "⇥" ), REPEAT ( "🔁" ), REPEAT_ONE_TRACK ( "🔂" ); String symbol; RepeatMode ( String symbol ) { this.symbol = symbol; } public String getSymbol () { return symbol; } } private ShuffleMode shuffleMode = ShuffleMode.SEQUENTIAL; private RepeatMode repeatMode = RepeatMode.PLAY_ONCE; private Vector<PlayerListener> playerListeners = new Vector<PlayerListener> (); private Random randomGenerator = new Random(); private int shuffleTracksPlayedCounter = 0; private final VLCAudioPlayer player; private final Queue queue; private final History history; private final PreviousStack previousStack; private final CurrentList currentList; private final LastFM lastFM; private Double unmutedVolume = null; private final BooleanProperty lastFMDoScrobble = new SimpleBooleanProperty ( false ); private boolean scrobbledThisTrack = false; private final DoubleProperty lastFMScrobbleTime = new SimpleDoubleProperty ( 0 ); private FXUI ui; public AudioSystem () { player = new VLCAudioPlayer ( this ); queue = new Queue(); history = new History(); previousStack = new PreviousStack(); currentList = new CurrentList( this, queue ); lastFM = new LastFM(); } public void setUI ( FXUI ui ) { this.ui = ui; } public void unpause () { player.requestUnpause(); } public void pause () { player.requestPause(); } public void togglePlayPause () { if ( player.isStopped() ) { play(); } else { togglePause(); } } public void togglePause () { player.requestTogglePause(); } public void play () { switch ( player.getState() ) { case PAUSED: player.requestUnpause(); break; case PLAYING: this.playTrack( player.getTrack(), false ); break; case STOPPED: next( false ); break; } } public void stop ( StopReason reason ) { Track stoppedTrack = player.getTrack(); player.requestStop(); for ( CurrentListTrack track : currentList.getItems() ) { track.setIsCurrentTrack( false ); track.setIsLastCurrentListTrack( false ); } notifyListenersStopped( stoppedTrack, reason ); shuffleTracksPlayedCounter = 0; } public void releaseResources() { player.releaseResources(); } public void previous ( ) { boolean startPaused = player.isPaused() || player.isStopped(); previous ( startPaused ); } public void previous ( boolean startPaused ) { if ( player.isPlaying() || player.isPaused() ) { if ( player.getPositionMS() >= 5000 ) { playTrack ( player.getTrack(), player.isPaused(), false ); return; } } Track previousTrack = null; int previousStackSize = previousStack.size(); while ( !previousStack.isEmpty() && previousTrack == null ) { Track candidate = previousStack.removePreviousTrack( player.getTrack() ); if ( currentList.getItems().contains( candidate ) ) { previousTrack = candidate; } } int previousStackSizeDifference = previousStackSize - previousStack.size(); shuffleTracksPlayedCounter -= previousStackSizeDifference; if ( previousTrack != null ) { playTrack ( previousTrack, startPaused, true ); } else if ( repeatMode == RepeatMode.PLAY_ONCE || repeatMode == RepeatMode.REPEAT_ONE_TRACK ) { shuffleTracksPlayedCounter = 1; Track previousTrackInList = null; for ( CurrentListTrack track : currentList.getItems() ) { if ( track.getIsCurrentTrack() ) { if ( previousTrackInList != null ) { playTrack( previousTrackInList, startPaused, false ); } else { playTrack( track, startPaused, false ); } break; } else { previousTrackInList = track; } } } else if ( repeatMode == RepeatMode.REPEAT ) { Track previousTrackInList = null; for ( CurrentListTrack track : currentList.getItems() ) { if ( track.getIsCurrentTrack() ) { if ( previousTrackInList != null ) { playTrack( previousTrackInList, startPaused, false ); } else { playTrack( currentList.getItems().get( currentList.getItems().size() - 1 ), startPaused, false ); } break; } else { previousTrackInList = track; } } } } public void next() { boolean startPaused = player.isPaused() || player.isStopped(); next ( startPaused ); } public void next ( boolean startPaused ) { List<CurrentListTrack> items = currentList.getSortedItemsNoFilter(); if ( queue.hasNext() ) { playTrack( queue.getNextTrack(), startPaused ); } else if ( items.size() == 0 ) { stop ( StopReason.EMPTY_LIST ); return; } else if ( repeatMode == RepeatMode.REPEAT_ONE_TRACK ) { playTrack ( history.getLastTrack() ); } else if ( shuffleMode == ShuffleMode.SEQUENTIAL ) { ListIterator <CurrentListTrack> currentListIterator = items.listIterator(); boolean didSomething = false; while ( currentListIterator.hasNext() ) { if ( currentListIterator.next().isLastCurrentListTrack() ) { if ( currentListIterator.hasNext() ) { playTrack( currentListIterator.next(), startPaused ); didSomething = true; } else if ( repeatMode == RepeatMode.PLAY_ONCE ) { shuffleTracksPlayedCounter = 1; stop( StopReason.END_OF_CURRENT_LIST ); didSomething = true; } else if ( items.size() <= 0 ) { stop( StopReason.EMPTY_LIST ); didSomething = true; } else if ( repeatMode == RepeatMode.REPEAT && items.size() > 0 ) { playTrack( items.get( 0 ), startPaused ); didSomething = true; } break; } } if ( !didSomething ) { if ( items.size() > 0 ) { playTrack ( items.get( 0 ), startPaused ); } } } else if ( shuffleMode == ShuffleMode.SHUFFLE ) { if ( repeatMode == RepeatMode.REPEAT ) { shuffleTracksPlayedCounter = 1; int currentListSize = items.size(); int collisionWindowSize = currentListSize / 3; int permittedRetries = 3; boolean foundMatch = false; int retryCount = 0; Track playMe; List <Track> collisionWindow; if ( previousStack.size() >= collisionWindowSize ) { collisionWindow = previousStack.subList( 0, collisionWindowSize ); } else { collisionWindow = previousStack.getData(); } do { playMe = items.get( randomGenerator.nextInt( items.size() ) ); if ( !collisionWindow.contains( playMe ) ) { foundMatch = true; } else { ++retryCount; } } while ( !foundMatch && retryCount < permittedRetries ); playTrack( playMe, startPaused ); } else { if ( shuffleTracksPlayedCounter < items.size() ) { List <Track> alreadyPlayed = previousStack.subList( 0, shuffleTracksPlayedCounter ); ArrayList <Track> viableTracks = new ArrayList <Track>( items ); viableTracks.removeAll( alreadyPlayed ); Track playMe = viableTracks.get( randomGenerator.nextInt( viableTracks.size() ) ); playTrack( playMe, startPaused ); ++shuffleTracksPlayedCounter; } else { stop( StopReason.END_OF_CURRENT_LIST ); } } } } public int getCurrentTrackIndex() { for ( int k = 0 ; k < currentList.getItems().size(); k++ ) { if ( currentList.getItems().get( k ).getIsCurrentTrack() ) { return k; } } return -1; } public void setShuffleMode ( ShuffleMode newMode ) { this.shuffleMode = newMode; notifyListenersShuffleModeChanged ( shuffleMode ); } public ShuffleMode getShuffleMode() { return shuffleMode; } public void toggleShuffleMode() { if ( shuffleMode == ShuffleMode.SEQUENTIAL ) { shuffleMode = ShuffleMode.SHUFFLE; } else { shuffleMode = ShuffleMode.SEQUENTIAL; } notifyListenersShuffleModeChanged ( shuffleMode ); } public void setRepeatMode ( RepeatMode newMode ) { this.repeatMode = newMode; notifyListenersRepeatModeChanged ( newMode ); } public RepeatMode getRepeatMode() { return repeatMode; } public void toggleRepeatMode() { if ( repeatMode == RepeatMode.PLAY_ONCE ) { repeatMode = RepeatMode.REPEAT; } else if ( repeatMode == RepeatMode.REPEAT ) { repeatMode = RepeatMode.REPEAT_ONE_TRACK; } else { repeatMode = RepeatMode.PLAY_ONCE; } notifyListenersRepeatModeChanged ( repeatMode ); } public History getHistory () { return history; } public Queue getQueue() { return queue; } public CurrentList getCurrentList() { return currentList; } public Track getCurrentTrack() { return player.getTrack(); } public Playlist getCurrentPlaylist () { return currentList.getCurrentPlaylist(); } public void shuffleList() { currentList.shuffleList( ); } public void seekPercent ( double percent ) { player.requestSeekPercent( percent ); } public void skipMS ( int diffMS ) { player.requestIncrementMS ( diffMS ); } public void seekMS ( long ms ) { player.requestSeekMS( ms ); } public long getPositionMS() { return player.getPositionMS(); } public void setVolumePercent ( double percent ) { player.requestVolumePercent( percent ); } public double getVolumePercent () { return player.getVolumePercent(); } public void decrementVolume () { double target = player.getVolumePercent() - .05; if ( target < 0 ) target = 0; player.requestVolumePercent( target ); } public void incrementVolume () { double target = player.getVolumePercent() + .05; if ( target > 1 ) target = 1; player.requestVolumePercent( target ); } public boolean isPlaying () { return player.isPlaying(); } public boolean isPaused() { return player.isPaused(); } public boolean isStopped () { return player.isStopped(); } public EnumMap <Persister.Setting, String> getSettings () { EnumMap <Persister.Setting, String> retMe = new EnumMap <Persister.Setting, String> ( Persister.Setting.class ); if ( !player.isStopped() ) { if ( player.getTrack() != null ) { retMe.put ( Setting.TRACK, player.getTrack().getPath().toString() ); } retMe.put ( Setting.TRACK_POSITION, Long.toString( player.getPositionMS() ) ); retMe.put ( Setting.TRACK_NUMBER, Integer.toString ( getCurrentTrackIndex() ) ); } retMe.put ( Setting.SHUFFLE, getShuffleMode().toString() ); retMe.put ( Setting.REPEAT, getRepeatMode().toString() ); retMe.put ( Setting.VOLUME, Double.toString( player.getVolumePercent() ) ); retMe.put ( Setting.DEFAULT_SHUFFLE_TRACKS, currentList.getDefaultTrackShuffleMode().toString() ); retMe.put ( Setting.DEFAULT_SHUFFLE_ALBUMS, currentList.getDefaultAlbumShuffleMode().toString() ); retMe.put ( Setting.DEFAULT_SHUFFLE_PLAYLISTS, currentList.getDefaultPlaylistShuffleMode().toString() ); retMe.put ( Setting.DEFAULT_REPEAT_TRACKS, currentList.getDefaultTrackRepeatMode().toString() ); retMe.put ( Setting.DEFAULT_REPEAT_ALBUMS, currentList.getDefaultAlbumRepeatMode().toString() ); retMe.put ( Setting.DEFAULT_REPEAT_PLAYLISTS, currentList.getDefaultPlaylistRepeatMode().toString() ); retMe.put( Setting.LASTFM_USERNAME, lastFM.getUsername() ); retMe.put( Setting.LASTFM_PASSWORD_MD5, lastFM.getPasswordMD5() ); retMe.put( Setting.LASTFM_SCROBBLE_ON_PLAY, lastFMDoScrobble.getValue().toString() ); retMe.put( Setting.LASTFM_SCROBBLE_TIME, this.lastFMScrobbleTime.getValue().toString() ); return retMe; } @SuppressWarnings("incomplete-switch") public void applySettings ( EnumMap <Persister.Setting, String> settings ) { settings.forEach( ( setting, value )-> { try { switch ( setting ) { case TRACK: Path trackPath = Paths.get( value ); Track track = new Track ( trackPath, false ); ui.trackSelected( track ); playTrack( track, true ); settings.remove ( setting ); //NOTE: track.album is set in Persister.loadAlbumsAndTracks() break; case TRACK_POSITION: seekMS( Long.parseLong( value ) ); settings.remove ( setting ); playerTrackPositionChanged ( player.getTrack(), (int)Long.parseLong( value ), player.getTrack().getLengthS() * 1000 ); break; case SHUFFLE: setShuffleMode ( AudioSystem.ShuffleMode.valueOf( value ) ); settings.remove ( setting ); break; case REPEAT: setRepeatMode ( AudioSystem.RepeatMode.valueOf( value ) ); settings.remove ( setting ); break; case VOLUME: setVolumePercent( Double.valueOf ( value ) ); Hypnos.getUI().playerVolumeChanged ( Double.valueOf ( value ) ); //TODO: this is kind of a hack. settings.remove ( setting ); break; case TRACK_NUMBER: try { int tracklistNumber = Integer.parseInt( value ); if ( tracklistNumber != -1 ) { getCurrentList().getItems().get( tracklistNumber ).setIsCurrentTrack( true ); } } catch ( Exception e ) { LOGGER.log( Level.INFO, "Error loading current list track number: ", e ); } settings.remove ( setting ); break; case DEFAULT_REPEAT_ALBUMS: getCurrentList().setDefaultAlbumRepeatMode( CurrentList.DefaultRepeatMode.valueOf( value ) ); settings.remove ( setting ); break; case DEFAULT_REPEAT_PLAYLISTS: getCurrentList().setDefaultPlaylistRepeatMode( CurrentList.DefaultRepeatMode.valueOf( value ) ); settings.remove ( setting ); break; case DEFAULT_REPEAT_TRACKS: getCurrentList().setDefaultTrackRepeatMode( CurrentList.DefaultRepeatMode.valueOf( value ) ); settings.remove ( setting ); break; case DEFAULT_SHUFFLE_ALBUMS: getCurrentList().setDefaultAlbumShuffleMode( CurrentList.DefaultShuffleMode.valueOf( value ) ); settings.remove ( setting ); break; case DEFAULT_SHUFFLE_PLAYLISTS: getCurrentList().setDefaultPlaylistShuffleMode( CurrentList.DefaultShuffleMode.valueOf( value ) ); settings.remove ( setting ); break; case DEFAULT_SHUFFLE_TRACKS: getCurrentList().setDefaultTrackShuffleMode( CurrentList.DefaultShuffleMode.valueOf( value ) ); settings.remove ( setting ); break; case LASTFM_USERNAME: lastFM.setUsername ( value ); settings.remove ( setting ); break; case LASTFM_PASSWORD_MD5: lastFM.setPassword ( value ); settings.remove ( setting ); break; case LASTFM_SCROBBLE_ON_PLAY: this.lastFMDoScrobble.setValue( Boolean.valueOf( value ) ); settings.remove ( setting ); break; case LASTFM_SCROBBLE_TIME: this.lastFMScrobbleTime.setValue( Double.valueOf( value ) ); settings.remove( setting ); break; } } catch ( Exception e ) { LOGGER.log( Level.INFO, "Unable to apply setting: " + setting + " to UI.", e ); } }); } //Manage Listeners public void addPlayerListener ( PlayerListener listener ) { if ( listener != null ) { playerListeners.add( listener ); } else { LOGGER.log( Level.INFO, "Null player listener was attempted to be added, ignoring.", new NullPointerException() ); } } private void notifyListenersPositionChanged ( Track track, int positionMS, int lengthMS ) { for ( PlayerListener listener : playerListeners ) { listener.playerPositionChanged( positionMS, lengthMS ); } if ( !scrobbledThisTrack && lastFMDoScrobble.getValue() ) { if ( positionMS / (double)lengthMS >= this.lastFMScrobbleTime.get() ) { lastFM.scrobbleTrack( track ); scrobbledThisTrack = true; } } } private void notifyListenersStopped ( Track track, StopReason reason ) { for ( PlayerListener listener : playerListeners ) { listener.playerStopped( track, reason ); } if ( !scrobbledThisTrack && lastFMDoScrobble.getValue() && reason == StopReason.TRACK_FINISHED && track != null ) { lastFM.scrobbleTrack( track ); scrobbledThisTrack = true; } } private void notifyListenersStarted ( Track track ) { scrobbledThisTrack = false; for ( PlayerListener listener : playerListeners ) { listener.playerStarted( track ); } } private void notifyListenersPaused () { for ( PlayerListener listener : playerListeners ) { listener.playerPaused(); } } private void notifyListenersUnpaused () { for ( PlayerListener listener : playerListeners ) { listener.playerUnpaused( ); } } private void notifyListenersVolumeChanged ( double newVolumePercent ) { for ( PlayerListener listener : playerListeners ) { listener.playerVolumeChanged( newVolumePercent ); } } private void notifyListenersShuffleModeChanged ( ShuffleMode newMode ) { for ( PlayerListener listener : playerListeners ) { listener.playerShuffleModeChanged( newMode ); } } private void notifyListenersRepeatModeChanged ( RepeatMode newMode ) { for ( PlayerListener listener : playerListeners ) { listener.playerRepeatModeChanged( newMode ); } } //REFACTOR: Make these a listener interface, and add this object as a listener to player? private int consecutiveFailedToStartCount = 0; void playerStopped ( Track track, StopReason reason ) { if ( reason == StopReason.TRACK_FINISHED ) { next ( false ); consecutiveFailedToStartCount = 0; } else if ( reason == StopReason.UNABLE_TO_START_TRACK ) { consecutiveFailedToStartCount++; if ( consecutiveFailedToStartCount <= currentList.getSortedItems().size() ) { next ( false ); } } notifyListenersStopped ( track, reason ); } void playerPaused () { notifyListenersPaused(); } void playerUnpaused () { notifyListenersUnpaused(); } void volumeChanged ( double volumePercentRequested ) { notifyListenersVolumeChanged ( volumePercentRequested ); } void playerStarted ( Track track ) { notifyListenersStarted( track ); } void playerTrackPositionChanged ( Track track, int positionMS, int lengthMS ) { notifyListenersPositionChanged ( track, positionMS, lengthMS ); } public void playTrack ( Track track ) { playTrack ( track, false ); } public void playTrack ( Track track, boolean startPaused ) { playTrack ( track, startPaused, true ); } public void playTrack ( Track track, boolean startPaused, boolean addToPreviousNextStack ) { player.requestPlayTrack( track, startPaused ); for ( CurrentListTrack listTrack : currentList.getItems() ) { listTrack.setIsCurrentTrack( false ); } if ( track instanceof CurrentListTrack ) { for ( CurrentListTrack listTrack : currentList.getItems() ) { listTrack.setIsLastCurrentListTrack( false ); } ((CurrentListTrack)track).setIsCurrentTrack( true ); ((CurrentListTrack)track).setIsLastCurrentListTrack( true ); } if ( addToPreviousNextStack ) { previousStack.addToStack ( track ); } history.trackPlayed( track ); } public void playItems ( List <Track> items ) { //REFACTOR: maybe break this into two separate functions and have the UI determine whether to set tracks or just play if ( items.size() == 1 ) { playTrack ( items.get( 0 ) ); } else if ( items.size() > 1 ) { currentList.setTracks( items ); next ( false ); } } //Used after program loads to get everything linked back up properly. public void linkQueueToCurrentList () { for ( CurrentListTrack track : currentList.getItems() ) { for ( int index : track.getQueueIndices() ) { if ( index < queue.size() ) { queue.getData().set( index - 1, track ); } else { LOGGER.log( Level.INFO, "Current list had a queue index beyond the length of the queue. Removing.", new Exception() ); track.getQueueIndices().remove( Integer.valueOf ( index ) ); } } } } public void toggleMute () { if ( player.getVolumePercent() == 0 ) { if ( unmutedVolume != null ) { player.requestVolumePercent( unmutedVolume ); unmutedVolume = null; } else { player.requestVolumePercent( 1 ); } } else { unmutedVolume = player.getVolumePercent(); player.requestVolumePercent( 0 ); } } public LastFM getLastFM () { return lastFM; } public BooleanProperty doLastFMScrobbleProperty() { return lastFMDoScrobble; } public boolean doLastFMScrobble() { return lastFMDoScrobble.getValue(); } public void setScrobbleTime( double value ) { lastFMScrobbleTime.set( value ); } public DoubleProperty scrobbleTimeProperty () { return lastFMScrobbleTime; } public FXUI getUI () { return ui; } }
21,810
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
MusicRoot.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/library/MusicRoot.java
package net.joshuad.hypnos.library; import java.io.File; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.nio.file.Files; import java.nio.file.Path; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; public class MusicRoot implements Serializable { private static final long serialVersionUID = 1L; private File file; private boolean needsInitialScan = true; private transient boolean needsRescan = false; @SuppressWarnings("unused") private boolean failedScan = false; //TODO: Show this in the UI @SuppressWarnings("unused") private transient boolean hadInotifyError = false; //TODO: Show this in the UI private transient BooleanProperty isValidSearchLocation = new SimpleBooleanProperty ( true ); public MusicRoot ( Path path ) { this.file = path.toFile(); } public Path getPath() { return file.toPath(); } public void setNeedsInitialScan( boolean needsInitialScan ) { this.needsInitialScan = needsInitialScan; } public boolean needsInitialScan() { return needsInitialScan; } public void setNeedsRescan( boolean needsRescan ) { this.needsRescan = needsRescan; } public boolean needsRescan() { return needsRescan; } public void setHadInotifyError( boolean hadError ) { this.hadInotifyError = hadError; } @Override public boolean equals ( Object other ) { if ( !( other instanceof MusicRoot ) ) { return false; } MusicRoot otherLocation = (MusicRoot)other; return file.toPath().equals( otherLocation.getPath() ); } public BooleanProperty validSearchLocationProperty() { return isValidSearchLocation; } public void recheckValidity() { boolean newValue = true; if ( !Files.exists( getPath() ) || !Files.isDirectory( getPath() ) || !Files.isReadable( getPath() ) ) { newValue = false; } if ( isValidSearchLocation.get() != newValue ) { isValidSearchLocation.setValue( newValue ); } } private void readObject ( ObjectInputStream in ) throws IOException, ClassNotFoundException { in.defaultReadObject(); isValidSearchLocation = new SimpleBooleanProperty ( true ); } public void setFailedScan(boolean failed) { this.failedScan = failed; } }
2,323
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
Track.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/library/Track.java
package net.joshuad.hypnos.library; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.nio.channels.ClosedByInterruptException; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import org.jaudiotagger.audio.AudioFile; import org.jaudiotagger.audio.AudioFileIO; import org.jaudiotagger.audio.AudioHeader; import org.jaudiotagger.audio.exceptions.CannotReadException; import org.jaudiotagger.audio.exceptions.InvalidAudioFrameException; import org.jaudiotagger.audio.exceptions.ReadOnlyFileException; import org.jaudiotagger.tag.FieldKey; import org.jaudiotagger.tag.Tag; import org.jaudiotagger.tag.TagException; import org.jaudiotagger.tag.TagField; import org.jaudiotagger.tag.id3.ID3v1Tag; import org.jaudiotagger.tag.id3.ID3v23Tag; import org.jaudiotagger.tag.images.Artwork; import org.jaudiotagger.tag.images.StandardArtwork; import javafx.beans.property.IntegerProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.embed.swing.SwingFXUtils; import javafx.scene.image.Image; import net.joshuad.hypnos.Hypnos; import net.joshuad.hypnos.MultiFileImageTagPair; import net.joshuad.hypnos.MultiFileImageTagPair.ImageFieldKey; import net.joshuad.hypnos.MultiFileTextTagPair; import net.joshuad.hypnos.Utils; import net.joshuad.hypnos.audio.AudioSystem; import net.joshuad.hypnos.audio.AudioSystem.StopReason; import net.joshuad.hypnos.lastfm.LastFM.LovedState; import net.joshuad.hypnos.library.TagError.TagErrorType; public class Track implements Serializable, AlbumInfoSource { private static transient final Logger LOGGER = Logger.getLogger( Track.class.getName() ); private static final long serialVersionUID = 1L; public static final int NO_TRACK_NUMBER = -885533; public enum Format { FLAC ( "flac" ), MP3 ( "mp3" ), OGG ( "ogg" ), ALAC ( "alac" ), WAV ( "wav" ), M4A ( "m4a" ), M4B ( "m4b" ), M4R ( "m4r" ), AAC ( "AAC" ), AIFF ( "aiff" ), AC3 ( "ac3" ), AMR ( "amr" ), AU ( "au" ), MKA ( "mka" ), RA ( "ra" ), VOC ( "voc" ), WMA ( "wma" ); final String extension; Format ( String extension ) { this.extension = extension; } public String getExtension () { return extension; } public static Format getFormat ( String extension ) { extension = extension.replaceAll( "^\\.", "" ); for ( Format format : Format.values() ) { if ( format.getExtension().equalsIgnoreCase( extension ) ) { return format; } } return null; } } public enum ArtistTagImagePriority { GENERAL ( 0 ), ALBUM ( 1 ), TRACK ( 2 ); private int value; ArtistTagImagePriority ( int value ) { this.value = value; } public int getValue() { return value; } }; private int length = 0; private File trackFile; private boolean isLossless = false; private long bitRate = -1; private int sampleRate = -1; private boolean isVBR = false; private String encodingType = ""; private String format = ""; private Album album = null; private transient StringProperty artist; private transient StringProperty albumArtist; private transient StringProperty title; private transient StringProperty albumTitle; private transient StringProperty date; private transient StringProperty originalDate; private transient IntegerProperty trackNumber; private transient StringProperty discSubtitle; private transient IntegerProperty discNumber; private transient IntegerProperty discCount; private transient StringProperty releaseType; private Vector <TagError> tagErrors; private transient LovedState lovedState; private boolean logTagErrors; private static final DirectoryStream.Filter<Path> imageFileFilter = new DirectoryStream.Filter<Path>() { @Override public boolean accept ( Path entry ) throws IOException { return Utils.isImageFile ( entry ); } }; public Track ( Path trackPath ) { this (trackPath, false); } public Track ( Path trackPath, boolean logTagErrors ) { initializeTransientFields(); this.trackFile = trackPath.toFile(); if ( trackFile == null ) { LOGGER.log(Level.WARNING, "Null path track", new Exception()); } this.logTagErrors = logTagErrors; refreshTagData(); } public Track ( Track track ) { initializeTransientFields(); setData ( track ); } public void setData ( Track track ) { this.length = track.length; this.trackFile = track.trackFile; this.album = track.album; this.artist.set(track.artist.get()); this.title.set(track.title.get()); this.albumTitle.set(track.albumTitle.get()); this.date.set(track.date.get()); this.originalDate.set(track.originalDate.get()); this.trackNumber.set(track.trackNumber.get()); this.discSubtitle.set(track.discSubtitle.get()); this.discNumber.set(track.discNumber.get()); this.discCount.set(track.discCount.get()); this.releaseType.set(track.releaseType.get()); this.isLossless = track.isLossless; this.bitRate = track.bitRate; this.sampleRate = track.sampleRate; this.isVBR = track.isVBR; this.encodingType = track.encodingType; this.format = track.format; this.tagErrors.clear(); this.tagErrors.addAll(track.tagErrors); this.logTagErrors = track.logTagErrors; } public void setAlbum( Album album ) { this.album = album; } public Album getAlbum() { return album; } public List <TagError> getTagErrors () { return tagErrors; } public void refreshTagData() { Tag tag = null; Logger.getLogger( "org.jaudiotagger" ).setLevel( Level.OFF ); try { AudioFile audioFile = getAudioFile(); AudioHeader audioHeader = audioFile.getAudioHeader(); length = audioHeader.getTrackLength(); tag = audioFile.getTag(); isLossless = audioHeader.isLossless(); bitRate = audioHeader.getBitRateAsNumber(); sampleRate = audioHeader.getSampleRateAsNumber(); isVBR = audioHeader.isVariableBitRate(); encodingType = audioHeader.getEncodingType(); format = audioHeader.getFormat(); Hypnos.getLibrary().removeTagErrors(tagErrors); tagErrors.clear(); parseArtist( tag ); parseTitle( tag ); parseAlbum( tag ); parseDate( tag ); parseTrackNumber( tag ); parseDiscInfo( tag ); parseReleaseType( tag ); } catch ( Exception e ) { tagErrors.add( new TagError ( TagErrorType.CANNOT_READ_TAG, this ) ); } parseFileName(); if(this.logTagErrors) { Hypnos.getLibrary().addTagErrors(tagErrors); } } private AudioFile getAudioFile() throws IOException, CannotReadException, TagException, ReadOnlyFileException, InvalidAudioFrameException { int i = trackFile.toString().lastIndexOf('.'); String extension = ""; if( i > 0 ) { extension = trackFile.toString().substring(i+1).toLowerCase(); } if ( extension.matches( Format.AAC.getExtension() ) || extension.matches( Format.M4R.getExtension() ) ) { return AudioFileIO.readAs( trackFile, "m4a" ); } else { return AudioFileIO.read( trackFile ); } } private void parseFileName () { //TODO: Look at parsing track number from file name too String filenameArtist = ""; String filenameYear = ""; String filenameAlbum = ""; String filenameTitle = ""; try { filenameArtist = trackFile.toPath().getParent().getParent().getFileName().toString(); } catch ( Exception e ) { //No need to log this } try { String parentName = trackFile.toPath().getParent().getFileName().toString(); String[] parentParts = parentName.split( " - " ); if ( parentParts.length == 1 ) { if ( album != null ) { filenameAlbum = parentParts [ 0 ]; } else { filenameArtist = parentParts [ 0 ]; } } else if ( parentParts.length == 2 ) { if ( parentParts [ 0 ].matches( "^[0-9]{4}[a-zA-Z]{0,1}" ) ) { filenameYear = parentParts [ 0 ]; filenameAlbum = parentParts [ 1 ]; } else if ( parentParts [ 1 ].matches( "^[0-9]{4}[a-zA-Z]{0,1}" ) ) { filenameYear = parentParts [ 1 ]; filenameAlbum = parentParts [ 0 ]; } else { filenameAlbum = parentName; } } //TODO: parse track number filenameTitle = trackFile.toPath().getFileName().toString(); filenameTitle = filenameTitle.replaceAll(" - ", "").replaceAll(filenameArtist, "").replaceAll(filenameAlbum, "") .replaceAll(filenameYear, ""); } catch ( Exception e ) { //PENDING: We get an exception with albums that have [] and maybe {} in their directory structure } //TODO: Add some error checking, only do this if we're pretty sure it's good. if ( artist.get().equals( "" ) && !filenameArtist.equals( "" ) ) { artist.set(filenameArtist); } if ( albumArtist.get().equals( "" ) && !filenameArtist.equals( "" ) ) { albumArtist.set(filenameArtist); } if ( albumTitle.get().equals( "" ) && !filenameAlbum.equals( "" ) ) { albumTitle.set(filenameAlbum); } if ( date.get().equals( "" ) && !filenameYear.equals( "" ) ) { date.set(filenameYear); } if ( title.get().equals( "" ) && !filenameTitle.equals( "" ) ) { title.set(filenameTitle); } } private void parseArtist( Tag tag ) { // Do we want to do antyhing with FieldKey.ARTISTS or .ALBUM_ARTISTS or .ALBUM_ARTIST_SORT? if ( tag != null ) { albumArtist.set(tag.getFirst ( FieldKey.ALBUM_ARTIST )); artist.set(tag.getFirst ( FieldKey.ARTIST )); } if ( albumArtist.get().equals( "" ) ) { albumArtist.set(artist.get()); } if ( artist.get().equals( "" ) ) { tagErrors.add( new TagError ( TagErrorType.MISSING_ARTIST, this ) ); } } private void parseTitle ( Tag tag ) { if ( tag != null ) { title.set(tag.getFirst ( FieldKey.TITLE )); try { if ( title.get().equals( "" ) ) { tagErrors.add( new TagError ( TagErrorType.MISSING_TITLE, this ) ); title.set(tag.getFirst( FieldKey.TITLE_SORT )); } } catch ( UnsupportedOperationException e ) { //No problem, it doesn't exist for this file format } } } private void parseAlbum ( Tag tag ) { if ( tag != null ) { albumTitle.set(tag.getFirst ( FieldKey.ALBUM )); try { if ( albumTitle.get().equals( "" ) ) { tagErrors.add( new TagError ( TagErrorType.MISSING_ALBUM, this ) ); albumTitle.set(tag.getFirst( FieldKey.ALBUM_SORT )); } } catch ( UnsupportedOperationException e ) {} } } private void parseDate ( Tag tag ) { if ( tag != null ) { try { originalDate.set(tag.getFirst ( FieldKey.ORIGINAL_YEAR )); } catch ( UnsupportedOperationException e ) { //Do nothing } try { date.set(tag.getFirst( FieldKey.YEAR )); } catch ( UnsupportedOperationException e ) { //Do nothing } } if ( date.get().equals( "" ) ) { tagErrors.add( new TagError ( TagErrorType.MISSING_DATE, this ) ); } } private void parseTrackNumber( Tag tag ) { if ( tag != null ) { String rawText = tag.getFirst ( FieldKey.TRACK ); String rawNoWhiteSpace = rawText.replaceAll("\\s+",""); try { if ( rawText.matches( "^[0-9]+$" ) ) { // 0, 01, 1010, 2134141, etc. trackNumber.set(Integer.parseInt( rawText )); } else if ( rawNoWhiteSpace.matches( "^[0-9]+$" ) ) { trackNumber.set(Integer.parseInt( rawNoWhiteSpace )); tagErrors.add( new TagError ( TagErrorType.TRACK_NUMBER_EXCESS_WHITESPACE, this ) ); } else if ( rawText.matches("^[0-9]+/.*") ) { trackNumber.set(Integer.parseInt( rawText.split("/")[0] )); tagErrors.add( new TagError ( TagErrorType.TRACK_NUMBER_HAS_DISC, this ) ); } else if ( rawNoWhiteSpace.matches("^[0-9]+/.*") ) { trackNumber.set(Integer.parseInt( rawNoWhiteSpace.split("/")[0] )); tagErrors.add( new TagError ( TagErrorType.TRACK_NUMBER_HAS_DISC, this ) ); } else { throw new NumberFormatException(); } } catch ( NumberFormatException e ) { if ( ! rawNoWhiteSpace.equals( "" ) ) { tagErrors.add( new TagError ( TagErrorType.TRACK_NUMBER_INVALID_FORMAT, this, rawText ) ); } } } } private void parseDiscInfo ( Tag tag ) { if ( tag != null ) { try { discSubtitle.set(tag.getFirst ( FieldKey.DISC_SUBTITLE )); } catch ( UnsupportedOperationException e ) { //No problem, it doesn't exist for this file format } try { discCount.set(Integer.valueOf( tag.getFirst ( FieldKey.DISC_TOTAL ) )); } catch ( NumberFormatException e ) { if ( ! tag.getFirst ( FieldKey.DISC_TOTAL ).equals( "" ) ) { tagErrors.add( new TagError ( TagErrorType.DISC_COUNT_INVALID_FORMAT, this , tag.getFirst ( FieldKey.DISC_TOTAL ) ) ); } } catch ( UnsupportedOperationException e ) { //No problem, it doesn't exist for this file format } String rawText = ""; String rawNoWhiteSpace = ""; try { rawText = tag.getFirst ( FieldKey.DISC_NO ); rawNoWhiteSpace = rawText.replaceAll("\\s+",""); if ( rawText.matches( "^[0-9]+$" ) ) { // 0, 01, 1010, 2134141, etc. discNumber.set(Integer.parseInt( rawText )); } else if ( rawNoWhiteSpace.matches( "^[0-9]+$" ) ) { discNumber.set(Integer.parseInt( rawNoWhiteSpace )); tagErrors.add( new TagError ( TagErrorType.DISC_NUMBER_EXCESS_WHITESPACE, this ) ); } else if ( rawText.matches("^[0-9]+/.*") ) {//if matches 23/<whatever> discNumber.set(Integer.parseInt( rawText.split("/")[0] )); if ( discCount == null ) { discCount.set(Integer.parseInt( rawText.split("/")[1] )); } tagErrors.add( new TagError ( TagErrorType.DISC_NUMBER_HAS_TRACK, this ) ); } else if ( rawNoWhiteSpace.matches("^[0-9]+/.*") ) { //if matches 23/<whatever> discNumber.set(Integer.parseInt( rawNoWhiteSpace.split("/")[0] )); if ( discCount == null ) { discCount.set(Integer.parseInt( rawNoWhiteSpace.split("/")[1] )); } tagErrors.add( new TagError ( TagErrorType.DISC_NUMBER_HAS_TRACK, this ) ); } else { throw new NumberFormatException(); } } catch ( NumberFormatException e ) { if ( ! rawNoWhiteSpace.equals( "" ) ) { tagErrors.add( new TagError ( TagErrorType.DISC_NUMBER_INVALID_FORMAT, this, rawText ) ); } } catch ( UnsupportedOperationException e ) { //No problem, it doesn't exist for this file format } } } private void parseReleaseType ( Tag tag ) { if ( tag != null ) { try { releaseType.set(tag.getFirst ( FieldKey.MUSICBRAINZ_RELEASE_TYPE )); } catch ( UnsupportedOperationException e ) { //No problem, it doesn't exist for this file format } } } public String getArtist () { return artist.get(); } public String getAlbumArtist() { return albumArtist.get(); } public String getYear () { if ( !originalDate.get().isEmpty() ) { return originalDate.get(); } else { return date.get(); } } public String getAlbumTitle () { return albumTitle.get(); } public String getFullAlbumTitle () { String retMe = albumTitle.get(); if ( discSubtitle != null && !discSubtitle.get().equals( "" ) ) { retMe += " (" + discSubtitle + ")"; } else if ( discCount != null && discCount.get() > 1 ) { if ( discNumber != null ) retMe += " (Disc " + discNumber + ")"; } else if ( discNumber != null && discNumber.get() > 1 ) { retMe += " (Disc " + discNumber + ")"; } if ( releaseType.get() != null && !releaseType.get().equals("") && !releaseType.get().matches( "(?i:album)" ) ) { retMe += " [" + Utils.toReleaseTitleCase( releaseType.get() ) + "]"; } return retMe; } public Integer getDiscNumber() { return discNumber.get(); } public Integer getDiscCount() { return discCount.get(); } public String getReleaseType () { if ( releaseType.get() != null && !releaseType.get().matches( "(?i:album)" ) ) { return Utils.toReleaseTitleCase( releaseType.get() ); } else { return null; } } public String getDiscSubtitle () { return discSubtitle.get(); } public StringProperty getTitleProperty() { return title; } public StringProperty getArtistProperty() { return artist; } public StringProperty getAlbumArtistProperty() { return albumArtist; } public StringProperty getAlbumTitleProperty() { return albumTitle; } public IntegerProperty getTrackNumberProperty() { return trackNumber; } public String getTitle () { return title.get(); } public Integer getTrackNumber () { return trackNumber.get(); } public int getLengthS () { return length; } public Path getPath() { return trackFile.toPath(); } public String getFilename() { return trackFile.getName(); } public String getLengthDisplay () { return Utils.getLengthDisplay( getLengthS () ); } public String getShortEncodingString() { if ( encodingType.toLowerCase().matches( "mp3" ) ) { if ( isVBR ) { return "MP3 VBR"; } else { return "MP3 " + bitRate; } } else if ( encodingType.toLowerCase().matches( "flac" ) ) { return encodingType; } else if ( encodingType.toLowerCase().matches( "aac" ) ) { if ( isVBR ) { return "AAC VBR"; } else { return "AAC " + bitRate; } } else { return encodingType; } } public boolean equals( Object o ) { if ( !( o instanceof Track ) ) return false; Track compareTo = (Track) o; return ( compareTo.getPath().toAbsolutePath().equals( getPath().toAbsolutePath() ) ); } public int hashCode() { return getPath().hashCode(); } // TODO: It's not clear to me any more that these methods belong in this class. public static void saveArtistImageToTag ( File file, Path imagePath, ArtistTagImagePriority priority, boolean overwriteAll, AudioSystem audioSystem ) { try { byte[] imageBuffer = Files.readAllBytes( imagePath ); saveImageToID3 ( file, imageBuffer, 8, priority, overwriteAll, audioSystem ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to read image data from file" + imagePath, e ); } } public static void saveArtistImageToTag ( File file, byte[] buffer, ArtistTagImagePriority priority, boolean overwriteAll, AudioSystem audioSystem ) { saveImageToID3 ( file, buffer, 8, priority, overwriteAll, audioSystem ); } public static void saveAlbumImageToTag ( File file, byte[] buffer, AudioSystem audioSystem ) { saveImageToID3 ( file, buffer, 3, null, true, audioSystem ); } private static void deleteImageFromID3 ( File file, int type, AudioSystem audioSystem ) { try { AudioFile audioFile = AudioFileIO.read( file ); Tag tag = audioFile.getTag(); if ( tag instanceof ID3v1Tag ) { tag = new ID3v23Tag ( (ID3v1Tag)tag ); } tag.deleteField( FieldKey.CUSTOM4 ); List <Artwork> artworkList = tag.getArtworkList(); tag.deleteArtworkField(); for ( Artwork artwork : artworkList ) { if ( artwork.getPictureType() != type ) { tag.addField( artwork ); } } boolean pausedPlayer = false; long currentPositionMS = 0; Track currentTrack = null; if ( audioSystem.getCurrentTrack() != null && audioSystem.getCurrentTrack().getPath().equals( file.toPath() ) && audioSystem.isPlaying() ) { currentPositionMS = audioSystem.getPositionMS(); currentTrack = audioSystem.getCurrentTrack(); audioSystem.stop( StopReason.WRITING_TO_TAG ); pausedPlayer = true; } audioFile.setTag( tag ); AudioFileIO.write( audioFile ); if ( pausedPlayer ) { audioSystem.playTrack( currentTrack, true ); audioSystem.seekMS( currentPositionMS ); audioSystem.unpause(); } } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to delete image from tag: " + file, e ); } } private static void saveImageToID3 ( File file, byte[] buffer, int type, ArtistTagImagePriority priority, boolean overwriteAll, AudioSystem audioSystem ) { try { AudioFile audioFile = AudioFileIO.read( file ); Tag tag = audioFile.getTag(); if ( tag instanceof ID3v1Tag ) { tag = new ID3v23Tag ( (ID3v1Tag)tag ); } if ( priority != null && !overwriteAll ) { Integer currentPriority = null; try { currentPriority = ArtistTagImagePriority.valueOf( tag.getFirst( FieldKey.CUSTOM4 ) ).getValue(); } catch ( Exception e ) { currentPriority = null; } if ( currentPriority != null && currentPriority > priority.getValue() ) { LOGGER.log( Level.INFO, file.getName() + ": Not overwriting tag. Selected priority (" + priority.getValue() + ") " + "is less than current priority (" + currentPriority + ").", new Exception() ); return; } } List <Artwork> artworkList = tag.getArtworkList(); tag.deleteArtworkField(); for ( Artwork artwork : artworkList ) { if ( artwork.getPictureType() != type ) { tag.addField( artwork ); } } Artwork artwork = new StandardArtwork(); artwork.setBinaryData( buffer ); artwork.setPictureType( type ); tag.addField( artwork ); if ( priority != null ) { tag.deleteField( FieldKey.CUSTOM4 ); tag.addField( FieldKey.CUSTOM4, priority.toString() ); } boolean pausedPlayer = false; long currentPositionMS = 0; Track currentTrack = null; if ( audioSystem.getCurrentTrack() != null && audioSystem.getCurrentTrack().getPath().equals( file.toPath() ) && audioSystem.isPlaying() ) { currentPositionMS = audioSystem.getPositionMS(); currentTrack = audioSystem.getCurrentTrack(); audioSystem.stop( StopReason.WRITING_TO_TAG ); pausedPlayer = true; } audioFile.setTag( tag ); AudioFileIO.write( audioFile ); if ( pausedPlayer ) { audioSystem.playTrack( currentTrack, true ); audioSystem.seekMS( currentPositionMS ); audioSystem.unpause(); } } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to write image to tag: " + file, e ); } } public void setAndSaveAlbumImage ( Path imagePath, AudioSystem audioSystem ) { try { byte[] imageBuffer = Files.readAllBytes( imagePath ); setAndSaveAlbumImage ( imageBuffer, audioSystem ); } catch ( IOException e ) { LOGGER.log( Level.WARNING, "Unable to read image data from image file (" + imagePath + ") can't set album image for track: " + getPath(), e ); } } public void setAndSaveAlbumImage ( byte[] buffer, AudioSystem audioSystem ) { if ( buffer.length < 8 ) { return; //png signature is length 8, so might as well use that as an absolute minimum } saveAlbumImageToTag ( getPath().toFile(), buffer, audioSystem ); if ( album != null ) { String extension = null; if ( buffer[0] == (byte)0xFF && buffer[1] == (byte)0xD8 ) { extension = ".jpg"; } else if ( buffer[0] == (byte)0x89 && buffer[1] == (byte)0x50 && buffer[2] == (byte)0x4e && buffer[3] == (byte)0x47 && buffer[4] == (byte)0x0d && buffer[5] == (byte)0x0A && buffer[6] == (byte)0x1A && buffer[7] == (byte)0x0A ) { extension = ".png"; } if ( extension == null ) { LOGGER.log( Level.INFO, "Invalid image file type, not saving.", new Exception() ); } Path copyTo = album.getPath().resolve( "front" + extension ); try { Files.deleteIfExists( album.getPath().resolve( "front.png" ) ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to delete previous album cover: " + album.getPath().resolve( "front.png" ), e ); } try ( FileOutputStream fos = new FileOutputStream ( copyTo.toFile() ) ) { fos.write( buffer ); fos.close(); } catch ( IOException e ) { LOGGER.log( Level.WARNING, "Unable to write album image to disk: " + copyTo, e ); } Thread updaterThread = new Thread ( () -> { List <Path> tracks = Utils.getAllTracksInDirectory ( album.getPath() ); for ( Path track : tracks ) { if ( !track.toAbsolutePath().equals( getPath().toAbsolutePath() ) ) { saveAlbumImageToTag ( track.toFile(), buffer, audioSystem ); } } }); updaterThread.setName ( "Album Image Tag Writer" ); updaterThread.setDaemon( true ); updaterThread.start(); } } private Path getPreferredAlbumCoverPath () { if ( this.getPath().getParent() != null ) { ArrayList <Path> preferredFiles = new ArrayList <Path> (); preferredFiles.add( Paths.get ( this.getPath().getParent().toString(), "front.png" ) ); preferredFiles.add( Paths.get ( this.getPath().getParent().toString(), "front.jpg" ) ); preferredFiles.add( Paths.get ( this.getPath().getParent().toString(), "cover.png" ) ); preferredFiles.add( Paths.get ( this.getPath().getParent().toString(), "cover.jpg" ) ); preferredFiles.add( Paths.get ( this.getPath().getParent().toString(), "album.png" ) ); preferredFiles.add( Paths.get ( this.getPath().getParent().toString(), "album.jpg" ) ); for ( Path test : preferredFiles ) { if ( Files.exists( test ) && Files.isRegularFile( test ) ) { return test; } } } return null; } private Path getSecondaryAlbumCoverPath () { if ( album != null ) { if ( this.getPath().getParent() != null ) { ArrayList<Path> otherFiles = new ArrayList<Path>(); try { DirectoryStream <Path> albumDirectoryStream = Files.newDirectoryStream ( this.getPath().getParent(), imageFileFilter ); for ( Path imagePath : albumDirectoryStream ) { if ( !imagePath.toString().toLowerCase().matches( ".*artist\\.\\w{3,6}$" ) ) { otherFiles.add( imagePath ); } } } catch ( Exception e ) { LOGGER.log( Level.INFO, "Unable to get directory listing: " + this.getPath().getParent(), e ); } for ( Path test : otherFiles ) { if ( Files.exists( test ) && Files.isRegularFile( test ) ) { return test; } } } } return null; } public Image getAlbumCoverImage ( ) { //Get the tag cover image //then look to folder for key files //then look at tag for any other suitable images //then take any image file from the album folder. if ( !Files.exists( getPath() ) ) { LOGGER.log( Level.INFO, "Track file does not exist: " + getPath(), new Exception() ); return null; } List<Artwork> artworkList = null; try { artworkList = getAudioFile().getTag().getArtworkList(); //This line can throw a NPE } catch ( Exception e ) { //Do nothing, there is no artwork in this file, no big deal. } if ( artworkList != null ) { try { artworkList = getAudioFile().getTag().getArtworkList(); if ( artworkList != null ) { for ( Artwork artwork : artworkList ) { if ( artwork.getPictureType() == 3 ) { //see ID3 specification for why 3 Image coverImage = SwingFXUtils.toFXImage((BufferedImage) artwork.getImage(), null); if ( coverImage != null ) return coverImage; } } } } catch ( ClosedByInterruptException e ) { return null; } catch ( Exception e ) { LOGGER.log( Level.INFO, "Unable to load album image from tag for file: " + getFilename(), e ); } } Path bestPath = getPreferredAlbumCoverPath (); if ( bestPath != null ) { return new Image( bestPath.toUri().toString() ); } artworkList = null; try { artworkList = getAudioFile().getTag().getArtworkList(); //This line can throw a NPE } catch ( Exception e ) { //Do nothing, there is no artwork in this file, no big deal. } try { if ( artworkList != null ) { for ( Artwork artwork : artworkList ) { if ( artwork.getPictureType() == 0 ) { Image otherImage = SwingFXUtils.toFXImage((BufferedImage) artwork.getImage(), null); if ( otherImage != null ) return otherImage; } else if ( artwork.getPictureType() == 6 ) { Image mediaImage = SwingFXUtils.toFXImage((BufferedImage) artwork.getImage(), null); if ( mediaImage != null ) return mediaImage; } } } } catch ( ClosedByInterruptException e ) { return null; } catch ( Exception e ) { LOGGER.log( Level.INFO, "Unable to load album image from tag for file: " + getFilename(), e ); } Path otherPaths = getSecondaryAlbumCoverPath (); if ( otherPaths != null ) { return new Image( otherPaths.toUri().toString() ); } return null; } private ArtistTagImagePriority tagImagePriority() { try { TagField tagImagePriority = getAudioFile().getTag().getFirstField( FieldKey.CUSTOM4 ); return ArtistTagImagePriority.valueOf( tagImagePriority.toString() ); } catch ( Exception e ) { return null; } } private Image getTagArtistImage () { try { List<Artwork> artworkList = getAudioFile().getTag().getArtworkList(); if ( artworkList != null ) { for ( Artwork artwork : artworkList ) { if ( artwork.getPictureType() == 8 ) { Image artistImage = SwingFXUtils.toFXImage((BufferedImage) artwork.getImage(), null); if ( artistImage != null ) return artistImage; } } } } catch ( Exception e ) { LOGGER.log( Level.INFO, "Unable to load artist image from tag for file: " + getFilename(), e ); } return null; } public Image getArtistImage ( ) { if ( tagImagePriority() == ArtistTagImagePriority.TRACK ) { Image tagArtistImage = getTagArtistImage(); if ( tagArtistImage != null ) return tagArtistImage; } if ( this.getPath().getParent() != null ) { Path targetPath = this.getPath().toAbsolutePath(); ArrayList <Path> possibleFiles = new ArrayList <Path> (); possibleFiles.add( Paths.get ( targetPath.getParent().toString(), "artist.png" ) ); possibleFiles.add( Paths.get ( targetPath.getParent().toString(), "artist.jpg" ) ); if ( this.getPath().getParent().getParent() != null ) { possibleFiles.add( Paths.get ( targetPath.getParent().getParent().toString(), "artist.png" ) ); possibleFiles.add( Paths.get ( targetPath.getParent().getParent().toString(), "artist.jpg" ) ); } for ( Path test : possibleFiles ) { if ( Files.exists( test ) && Files.isRegularFile( test ) ) { return new Image( test.toUri().toString() ); } } } if ( tagImagePriority() == ArtistTagImagePriority.ALBUM ) { Image tagArtistImage = getTagArtistImage(); if ( tagArtistImage != null ) return tagArtistImage; } List<Artwork> artworkList = null; try { artworkList = getAudioFile().getTag().getArtworkList(); //This line can throw a NPE } catch ( Exception e ) { //Do nothing, there is no artwork in this file, no big deal. } try { if ( artworkList != null ) { for ( Artwork artwork : artworkList ) { if ( artwork.getPictureType() == 7 ) { Image leadArtistImage = SwingFXUtils.toFXImage( (BufferedImage) artwork.getImage(), null ); if ( leadArtistImage != null ) { return leadArtistImage; } } else if ( artwork.getPictureType() == 8 ) { Image artistImage = SwingFXUtils.toFXImage((BufferedImage) artwork.getImage(), null); if ( artistImage != null ) { return artistImage; } } else if ( artwork.getPictureType() == 12 ) { Image writerImage = SwingFXUtils.toFXImage( (BufferedImage) artwork.getImage(), null ); if ( writerImage != null ) { return writerImage; } } else if ( artwork.getPictureType() == 13 ) { Image logoImage = SwingFXUtils.toFXImage( (BufferedImage) artwork.getImage(), null ); if ( logoImage != null ) { return logoImage; } } } } } catch ( ClosedByInterruptException e ) { return null; } catch ( Exception e ) { LOGGER.log( Level.INFO, "Error when trying to load tag images for file" + getPath(), e ); } return null; } public void updateTagsAndSave ( List<MultiFileTextTagPair> textTagPairs, List<MultiFileImageTagPair> imageTagPairs, AudioSystem audioSystem ) { try { AudioFile audioFile = AudioFileIO.read( getPath().toFile() ); Tag tag = audioFile.getTag(); if ( tag == null ) { tag = audioFile.createDefaultTag(); } else if ( tag instanceof ID3v1Tag ) { tag = new ID3v23Tag ( (ID3v1Tag)tag ); } for ( MultiFileTextTagPair tagPair : textTagPairs ) { if ( !tagPair.isMultiValue() ) { if ( tagPair.getValue().equals( "" ) ) { tag.deleteField( tagPair.getKey() ); } else { tag.setField( tagPair.getKey(), tagPair.getValue() ); } } } audioFile.setTag( tag ); AudioFileIO.write( audioFile ); for ( MultiFileImageTagPair tagPair : imageTagPairs ) { if ( !tagPair.isMultiValue() && tagPair.imageDataChanged() ) { if ( tagPair.getImageData() == null ) { deleteImageFromID3 ( getPath().toFile(), ImageFieldKey.getIndexFromKey( tagPair.getKey() ), audioSystem ); } else { saveImageToID3 ( getPath().toFile(), tagPair.getImageData(), ImageFieldKey.getIndexFromKey( tagPair.getKey() ), ArtistTagImagePriority.TRACK, true, audioSystem ); } } } refreshTagData(); if(getAlbum() != null) { getAlbum().updateData(); } } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to save updated tag.", e ); } } private void writeObject ( ObjectOutputStream out ) throws IOException { out.defaultWriteObject(); out.writeObject(artist.get()); out.writeObject(albumArtist.get()); out.writeObject(title.get()); out.writeObject(albumTitle.get()); out.writeObject(date.get()); out.writeObject(originalDate.get()); out.writeInt(trackNumber.get()); out.writeObject(discSubtitle.get()); out.writeInt(discNumber.get()); out.writeInt(discCount.get()); out.writeObject(releaseType.get()); } private void readObject ( ObjectInputStream in ) throws IOException, ClassNotFoundException { initializeTransientFields(); in.defaultReadObject(); artist.set((String)in.readObject()); albumArtist.set((String)in.readObject()); title.set((String)in.readObject()); albumTitle.set((String)in.readObject()); date.set((String)in.readObject()); originalDate.set((String)in.readObject()); trackNumber.set(in.readInt()); discSubtitle.set((String)in.readObject()); discNumber.set(in.readInt()); discCount.set(in.readInt()); releaseType.set((String)in.readObject()); } public LovedState getLovedState () { return lovedState; } public void setLovedState ( LovedState state ) { this.lovedState = state; } private void initializeTransientFields() { artist = new SimpleStringProperty(""); albumArtist = new SimpleStringProperty(""); title = new SimpleStringProperty(""); albumTitle = new SimpleStringProperty(""); date = new SimpleStringProperty(""); originalDate = new SimpleStringProperty(""); trackNumber = new SimpleIntegerProperty(NO_TRACK_NUMBER); discSubtitle = new SimpleStringProperty(""); discNumber = new SimpleIntegerProperty(); discCount = new SimpleIntegerProperty(); releaseType = new SimpleStringProperty(""); tagErrors = new Vector <TagError> (); lovedState = LovedState.NOT_SET; } }
35,808
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
TagError.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/library/TagError.java
package net.joshuad.hypnos.library; import java.io.Serializable; import java.nio.file.Path; public class TagError implements Serializable { private static final long serialVersionUID = 1L; public enum TagErrorType { MISSING_ARTIST ( "No artist name" ), MISSING_TITLE ( "No track title" ), MISSING_ALBUM ( "No album title" ), MISSING_DATE ( "No date." ), TRACK_NUMBER_EXCESS_WHITESPACE ( "Track # has excess whitespace" ), TRACK_NUMBER_HAS_DISC ( "Track # in N/N format" ), TRACK_NUMBER_INVALID_FORMAT ( "Track # format invalid" ), DISC_COUNT_INVALID_FORMAT ( "Disc count format invalid" ), DISC_NUMBER_EXCESS_WHITESPACE ( "Disc # has excess whitespace" ), DISC_NUMBER_HAS_TRACK ( "Disc # in N/N format" ), DISC_NUMBER_INVALID_FORMAT ( "Disc # format invalid" ), CANNOT_READ_TAG ( "Unable to read tag." ); private String message; private TagErrorType ( String message ) { this.message = message; } public String getMessage () { return message; } } private TagErrorType type; private Track track; private String moreInfo; public TagError ( TagErrorType type, Track track ) { this.type = type; this.track = track; } public TagError ( TagErrorType type, Track track, String moreInfo ) { this ( type, track ); this.moreInfo = moreInfo; } public Path getPath() { return track.getPath(); } public String getFolderDisplay() { return getPath().getParent().toString(); } public String getFilenameDisplay() { return getPath().getFileName().toString(); } public String getMessage() { if ( moreInfo == null ) { return type.getMessage(); } else { return type.getMessage() + ": " + moreInfo ; } } public Track getTrack() { return track; } }
1,744
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
LibraryScanLogger.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/library/LibraryScanLogger.java
package net.joshuad.hypnos.library; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.nio.charset.StandardCharsets; public class LibraryScanLogger { private final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); private final PrintStream ps = new PrintStream(buffer, true, StandardCharsets.UTF_8); public synchronized void println(String string) { ps.println(string); } public synchronized String dumpBuffer() { String retMe = new String(buffer.toByteArray(), StandardCharsets.UTF_8); buffer.reset(); return retMe; } }
596
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
DiskReader.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/library/DiskReader.java
package net.joshuad.hypnos.library; import java.io.IOException; import java.nio.file.FileVisitOption; import java.nio.file.FileVisitResult; import java.nio.file.FileVisitor; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.lang3.exception.ExceptionUtils; import me.xdrop.fuzzywuzzy.FuzzySearch; import net.joshuad.hypnos.Hypnos; import net.joshuad.hypnos.Utils; import net.joshuad.hypnos.fxui.FXUI; class DiskReader implements FileVisitor<Path> { private static final Logger LOGGER = Logger.getLogger(DiskReader.class.getName()); public enum ScanMode { INITIAL_SCAN("Scanning "), RESCAN("Rescanning "); private final String statusPrefix; ScanMode(String statusPrefix) { this.statusPrefix = statusPrefix; } public String getStatusPrefix() { return statusPrefix; } } private FileTreeNode currentDirectoryNode = null; private boolean interrupted = false; private boolean interruptRequested = false; private long directoriesVisited = 0; private long directoriesToScan = 1; private Path currentRootPath = null; private ScanMode scanMode = ScanMode.INITIAL_SCAN; private Library library; private FXUI ui; LibraryLoader loader; LibraryScanLogger scanLogger; DiskReader(Library library, LibraryLoader loader, LibraryScanLogger scanLogger) { this.loader = loader; this.library = library; this.scanLogger = scanLogger; } void setUI(FXUI ui) { this.ui = ui; } void interrupt() { interruptRequested = true; } private void resetState() { currentDirectoryNode = null; interrupted = false; interruptRequested = false; directoriesVisited = 0; directoriesToScan = 1; currentRootPath = null; scanMode = ScanMode.INITIAL_SCAN; } // TODO: make sure we're not already scanning, if so throw an error void scanMusicRoot(MusicRoot musicRoot, ScanMode scanMode) { resetState(); this.scanMode = scanMode; scanLogger.println("[DiskReader] " + scanMode.statusPrefix + " root: " + musicRoot.getPath().toString()); try { directoriesToScan = LibraryLoader.getDirectoryCount(musicRoot.getPath()); currentRootPath = musicRoot.getPath(); ui.setLibraryLoaderStatus(scanMode.getStatusPrefix() + " " + currentRootPath.toString() + "...", 0, this); library.getDiskWatcher().watchAll(musicRoot.getPath()); if (scanMode == ScanMode.INITIAL_SCAN) { musicRoot.setNeedsRescan(false); } Files.walkFileTree(musicRoot.getPath(), EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, this); switch (scanMode) { case INITIAL_SCAN: musicRoot.setNeedsInitialScan(interrupted); break; case RESCAN: musicRoot.setNeedsRescan(interrupted); break; } } catch (Exception e) { scanLogger.println("[DiskReader] Scan failed or incomplete for path, giving up: " + musicRoot.getPath()); scanLogger.println(ExceptionUtils.getStackTrace(e)); musicRoot.setNeedsRescan(false); musicRoot.setFailedScan(true); } if (ui != null) { ui.setLibraryLoaderStatusToStandby(this); } } // TODO: make sure we're not already scanning, if so throw an error void updatePath(Path path) { resetState(); this.scanMode = ScanMode.RESCAN; directoriesToScan = LibraryLoader.getDirectoryCount(path); currentRootPath = path; library.getDiskWatcher().watchAll(path); try { Files.walkFileTree(path, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, this); } catch (Exception e) { scanLogger.println("[DiskReader] Scan failed or incomplete for path, giving up: " + path); scanLogger.println(ExceptionUtils.getStackTrace(e)); List<MusicRoot> roots = new ArrayList<>(library.getMusicRootData()); for (MusicRoot root : roots) { if (Utils.isChildOf(path, root.getPath())) { root.setFailedScan(true); } } } if (ui != null) { ui.setLibraryLoaderStatusToStandby(this); } } private final List<Track> tracksInCurrentDirectory = new ArrayList<>(); @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { if (interruptRequested) { interrupted = true; return FileVisitResult.TERMINATE; } FileTreeNode directoryNode = new FileTreeNode(dir, currentDirectoryNode); if (currentDirectoryNode != null) { currentDirectoryNode.addChild(directoryNode); } currentDirectoryNode = directoryNode; if (ui != null) { ui.setLibraryLoaderStatus(scanMode.getStatusPrefix() + " " + currentRootPath.toString() + "...", directoriesVisited / (double) directoriesToScan, this); } tracksInCurrentDirectory.clear(); for ( Track libraryTrack : library.getTrackData() ) { if ( libraryTrack.getPath().startsWith(dir) ) { tracksInCurrentDirectory.add(libraryTrack); } } switch(Hypnos.getLoaderSpeed()) { case HIGH: default: break; case MED: try { Thread.sleep(10); } catch (InterruptedException e) { LOGGER.log(Level.INFO, "Interrupted during sleep in disk watcher, if this persists the loader speed may be ignored.", e); } break; case LOW: try { Thread.sleep(50); } catch (InterruptedException e) { LOGGER.log(Level.INFO, "Interrupted during sleep in disk watcher, if this persists the loader speed may be ignored.", e); } break; } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path filePath, BasicFileAttributes attr) { loader.pathUpdated(filePath); if (Utils.isMusicFile(filePath)) { Track track = null; for (Track libraryTrack : tracksInCurrentDirectory) { if (libraryTrack.getPath().equals(filePath)) { track = libraryTrack; break; } } if (track == null) { track = new Track(filePath, true); library.addTrack(track); } else { track.refreshTagData(); } currentDirectoryNode.addChild(new FileTreeNode(filePath, currentDirectoryNode, track)); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exception) throws IOException { directoriesVisited++; loader.pathUpdated(dir); if (isAlbum(currentDirectoryNode, scanLogger)) { List<Track> tracks = new ArrayList<>(); for (FileTreeNode child : currentDirectoryNode.getChildren()) { if (child.getTrack() != null) { tracks.add(child.getTrack()); } } Album album = null; for(Album libraryAlbum : library.getAlbumData()) { if(libraryAlbum.getPath().equals(currentDirectoryNode.getPath())) { album = libraryAlbum; } } if(album == null ) { album = new Album(currentDirectoryNode.getPath(), tracks); scanLogger.println("[DiskReader] Loading new album: " + album.getAlbumArtist() + " - " + album.getAlbumTitle()); library.addAlbum(album); } else { album.setTracks(tracks); scanLogger.println("[DiskReader] Updating album: " + album.getAlbumArtist() + " - " + album.getAlbumTitle()); } currentDirectoryNode.setAlbum(album); } else { library.notAnAlbum(currentDirectoryNode.getPath()); } if (currentDirectoryNode.getParent() != null) { currentDirectoryNode = currentDirectoryNode.getParent(); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exception) throws IOException { LOGGER.log(Level.INFO, "Unable to scan" + file, exception); return FileVisitResult.CONTINUE; } public boolean isRescanning() { return scanMode == ScanMode.RESCAN; } static boolean isAlbum(FileTreeNode node, LibraryScanLogger libraryLog) { if (!Files.isDirectory(node.getPath())) { libraryLog.println( "[LibraryLoader] Album rejected, not a directory: " + node.getPath() ); return false; } String albumName = null; String artistName = null; int childTrackCount = 0; for (FileTreeNode child : node.getChildren()) { if (child.getAlbum() != null) { libraryLog.println( "[LibraryLoader] Album rejected, subdirectory is an album: " + node.getPath() ); return false; } if (child.getArtist() != null) { libraryLog.println( "[LibraryLoader] Album rejected, no artist specified: " + node.getPath() ); return false; } if (child.getTrack() != null) { childTrackCount++; if (albumName == null) { albumName = Utils.prepareAlbumForCompare(child.getTrack().getAlbumTitle()); artistName = Utils.prepareArtistForCompare(child.getTrack().getAlbumArtist()); } else { // We usually use weighted ratio, but that can return 0 for album names like () // even if the strings are identical. // In that case, we switch to straight ratio, which doesn't have this problem int albumMatchPercent = FuzzySearch.weightedRatio(albumName, Utils.prepareAlbumForCompare(child.getTrack().getAlbumTitle())); if (albumMatchPercent == 0) albumMatchPercent = FuzzySearch.ratio(albumName, Utils.prepareAlbumForCompare(child.getTrack().getAlbumTitle())); if (albumMatchPercent < 90) { libraryLog.println( "[LibraryLoader] Album rejected, album name in tags too different: " + node.getPath() ); return false; } int artistMatchPercent = FuzzySearch.weightedRatio(artistName, Utils.prepareArtistForCompare(child.getTrack().getAlbumArtist())); if (artistMatchPercent == 0) albumMatchPercent = FuzzySearch.ratio(artistName, Utils.prepareAlbumForCompare(child.getTrack().getAlbumArtist())); if (artistMatchPercent < 90) { libraryLog.println( "[LibraryLoader] Album rejected, artist name in tags too different: " + node.getPath() ); return false; } } } } if (childTrackCount == 0) { libraryLog.println( "[LibraryLoader] Album rejected, no tracks: " + node.getPath() ); return false; } return true; } }
10,261
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
LibraryLoader.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/library/LibraryLoader.java
package net.joshuad.hypnos.library; import java.nio.file.FileVisitOption; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import net.joshuad.hypnos.Utils; import net.joshuad.hypnos.fxui.FXUI; class LibraryLoader { private static final Logger LOGGER = Logger.getLogger(LibraryLoader.class.getName()); private final ArrayList<Path> pathsToUpdate = new ArrayList<>(); private boolean clearOrphansAndMissing = false; private boolean musicRootRemoved = false; private Thread loaderThread; private Library library; private DiskReader diskReader; private LibraryScanLogger scanLogger; private FXUI ui; public LibraryLoader(Library library, LibraryScanLogger scanLogger) { this.library = library; this.scanLogger = scanLogger; this.diskReader = new DiskReader(library, this, scanLogger); setupLoaderThread(); } public void setUI(FXUI ui) { this.ui = ui; diskReader.setUI(ui); } public void start() { if (!loaderThread.isAlive()) { loaderThread.start(); } else { LOGGER.log(Level.INFO, "Disk Scanner thread asked to start, but it's already running, request ignored.", new Exception()); } } void requestClearOrphans() { this.clearOrphansAndMissing = true; } public void queueUpdatePath(Path path) { if (!pathsToUpdate.contains(path)) { pathsToUpdate.add(path); } } private long lastOrphanClearMS = 0; private void setupLoaderThread() { loaderThread = new Thread() { public void run() { while (true) { try { for (MusicRoot root : library.getMusicRootData()) { root.recheckValidity(); } if (System.currentTimeMillis() - lastOrphanClearMS > 5000) { clearOrphansAndMissing = true; } if (clearOrphansAndMissing || musicRootRemoved) { String message = musicRootRemoved ? "Removing Items..." : ""; musicRootRemoved = false; clearOrphansAndMissing = false; lastOrphanClearMS = System.currentTimeMillis(); clearOrphans(message); clearMissing(); if (!message.isBlank()) { ui.setLibraryLoaderStatusToStandby(null); } musicRootRemoved = false; } List<MusicRoot> libraryRoots = new ArrayList<>(library.getMusicRootData()); for (MusicRoot root : libraryRoots) { if (root.needsInitialScan()) { diskReader.scanMusicRoot(root, DiskReader.ScanMode.INITIAL_SCAN); } } libraryRoots = new ArrayList<>(library.getMusicRootData()); for (MusicRoot root : libraryRoots) { if (root.needsRescan()) { diskReader.scanMusicRoot(root, DiskReader.ScanMode.RESCAN); } } if (!pathsToUpdate.isEmpty()) { synchronized (pathsToUpdate) { Path pathToUpdate = pathsToUpdate.remove(0).toAbsolutePath(); updateLibraryAtPath(pathToUpdate); } } library.getDiskWatcher().processWatcherEvents(); try { Thread.sleep(50); } catch (InterruptedException e) { } } catch (Exception e) { LOGGER.log(Level.INFO, "Caught an unhandled exception in loader loop, continuing.", e); } } } }; loaderThread.setName("Library Loader"); loaderThread.setDaemon(true); } public void updateLibraryAtPath(Path path) { path = path.toAbsolutePath(); if (!Files.exists(path)) { List<Track> tracksToRemove = new ArrayList<>(); for (Track track : library.getTrackData()) { if (track.getPath().toAbsolutePath().startsWith(path)) { tracksToRemove.add(track); } } for (Track track : tracksToRemove) { scanLogger.println("[LibraryLoader] Removing track data from track list: " + track.getPath()); library.removeTrack(track); } List<Album> albumsToRemove = new ArrayList<>(); for (Album album : library.getAlbumData()) { if (album.getPath().toAbsolutePath().startsWith(path)) { albumsToRemove.add(album); } } for (Album album : albumsToRemove) { scanLogger.println("[LibraryLoader] Removing album data from album list: " + path); library.removeAlbum(album); library.getDiskWatcher().stopWatching(album.getPath()); } } else if (Utils.isMusicFile(path)) { Track existingTrackAtPath = null; for (Track track : library.getTrackData()) { if (track.getPath().equals(path)) { existingTrackAtPath = track; break; } } if (existingTrackAtPath != null) { scanLogger.println("[LibraryLoader] Updating track data at: " + path); existingTrackAtPath.refreshTagData(); // This will make sure that any existing album gets updated, and if the // album has been destroyed on disk, it is removed from our library pathsToUpdate.add(existingTrackAtPath.getPath().getParent()); library.requestRegenerateArtists(); } else { scanLogger.println("[LibraryLoader] new track found at: " + path); Track newTrack = new Track(path, true); library.getTrackData().remove(newTrack); } } else if (Files.isDirectory(path)) { scanLogger.println("[LibraryLoader] Doing directory rescan at: " + path); List<Path> childrenOfPath = new ArrayList<>(); for (Path futureUpdate : pathsToUpdate) { if (Utils.isChildOf(futureUpdate, path)) { childrenOfPath.add(futureUpdate); scanLogger.println("[LibraryLoader] - Removing future scan, its a child: " + path); } } pathsToUpdate.removeAll(childrenOfPath); diskReader.updatePath(path); } } static long getDirectoryCount(Path dir) { long retMe = 5000; try { retMe = Files.walk(dir, FileVisitOption.FOLLOW_LINKS).parallel().filter(p -> p.toFile().isDirectory()).count(); } catch (Exception e) { LOGGER.log(Level.INFO, "Unable to count subdirectories, loader status bar will not be accurate", e); } return retMe; } private void clearMissing() { List<Album> removeMeAlbums = new ArrayList<>(); for (Album album : library.getAlbumData()) { if(!Files.isDirectory(album.getPath())) { removeMeAlbums.add(album); } } for (Album album : removeMeAlbums) { library.removeAlbum(album); scanLogger.println( "[LibraryLoader] Album pruned, directory missing from disk: " + album.getPath() ); //No need to remove tracks from the album, they'll be removed below } List<Track> removeMeTracks = new ArrayList<>(); for (Track track : library.getTrackData()) { if(!Files.isRegularFile(track.getPath())) { removeMeTracks.add(track); } } for (Track track : removeMeTracks) { library.removeTrack(track); scanLogger.println( "[LibraryLoader] Track pruned, file missing from disk: " + track.getPath() ); } } private void clearOrphans(String message) { int totalCount = library.getAlbumData().size() + library.getTrackData().size() + 10; //10 for the removal time int currentCount = 0; List<Album> removeMeAlbums = new ArrayList<>(); for (Album album : library.getAlbumData()) { currentCount++; if(!message.isBlank()) { ui.setLibraryLoaderStatus(message, currentCount/(double)totalCount, this); } boolean hasRoot = false; for (MusicRoot root : library.getMusicRootData()) { if (Utils.isChildOf(album.getPath(), root.getPath())) { hasRoot = true; break; } if(album.getPath().equals(root.getPath())) { hasRoot = true; break; } } if (!hasRoot) { removeMeAlbums.add(album); } } for (Album album : removeMeAlbums) { library.removeAlbum(album); //No need to remove tracks from the album, they'll be removed below scanLogger.println( "[LibraryLoader] Orphan album pruned, no root: " + album.getPath() ); } List<Track> removeMeTracks = new ArrayList<>(); for (Track track : library.getTrackData()) { currentCount++; if(!message.isBlank()) { ui.setLibraryLoaderStatus(message, currentCount/(double)totalCount, this); } boolean hasRoot = false; for (MusicRoot root : library.getMusicRootData()) { if (Utils.isChildOf(track.getPath(), root.getPath())) { hasRoot = true; break; } } if (!hasRoot) { removeMeTracks.add(track); } } for (Track track : removeMeTracks) { library.removeTrack(track); scanLogger.println( "[LibraryLoader] Orphan track pruned, no root: " + track.getPath() ); } } public void removeMusicRoot(MusicRoot musicRoot) { diskReader.interrupt(); requestClearOrphans(); } void interruptDiskReader() { diskReader.interrupt(); } public void setMusicRootRemoved(boolean b) { musicRootRemoved = b; } void pathUpdated(Path path) { pathsToUpdate.remove(path); } }
8,886
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
AlbumInfoSource.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/library/AlbumInfoSource.java
package net.joshuad.hypnos.library; public interface AlbumInfoSource { public String getAlbumTitle(); public String getFullAlbumTitle(); public String getReleaseType(); public String getDiscSubtitle(); public Integer getDiscCount(); public Integer getDiscNumber(); }
274
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
Album.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/library/Album.java
package net.joshuad.hypnos.library; import java.io.File; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javafx.beans.InvalidationListener; import javafx.beans.Observable; import javafx.beans.property.IntegerProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.image.Image; public class Album implements Serializable, AlbumInfoSource { private static transient final Logger LOGGER = Logger.getLogger(Album.class.getName()); private static final long serialVersionUID = 2L; private File directory; private transient ObservableList<Track> tracks; private transient StringProperty albumArtistProperty; private transient StringProperty yearProperty; private transient StringProperty albumTitleProperty; private transient StringProperty fullAlbumTitleProperty; private transient StringProperty dateAddedStringProperty; private transient IntegerProperty discNumberProperty; private transient IntegerProperty discCountProperty; private transient StringProperty releaseTypeProperty; private transient StringProperty discSubtitleProperty; private void initializeTransientFields() { tracks = FXCollections.observableArrayList(); this.tracks.addListener(new InvalidationListener() { @Override public void invalidated(Observable arg0) { updateData(); } }); albumArtistProperty = new SimpleStringProperty(""); yearProperty = new SimpleStringProperty(""); albumTitleProperty = new SimpleStringProperty(""); fullAlbumTitleProperty = new SimpleStringProperty(""); dateAddedStringProperty = new SimpleStringProperty(""); discNumberProperty = new SimpleIntegerProperty(); discCountProperty = new SimpleIntegerProperty(); releaseTypeProperty = new SimpleStringProperty(""); discSubtitleProperty = new SimpleStringProperty(""); } public Album(Path albumDirectory, List<Track> tracks) { initializeTransientFields(); this.directory = albumDirectory.toFile(); setTracks(tracks); } public void setTracks(List<Track> tracks) { this.tracks.setAll(tracks); for (Track track : tracks) { track.setAlbum(this); } } public void updateData() { albumArtistProperty.set(tracks.get(0).getAlbumArtist()); if (tracks.get(0).getYear().length() > 4) { yearProperty.set(tracks.get(0).getYear().substring(0, 4)); } else { yearProperty.set(tracks.get(0).getYear()); } albumTitleProperty.set(tracks.get(0).getAlbumTitle()); fullAlbumTitleProperty.set(tracks.get(0).getFullAlbumTitle()); discNumberProperty.set(tracks.get(0).getDiscNumber()); discCountProperty.set(tracks.get(0).getDiscCount()); releaseTypeProperty.set(tracks.get(0).getReleaseType()); discSubtitleProperty.set(tracks.get(0).getDiscSubtitle()); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); try { long creationMS = Files.readAttributes(directory.toPath(), BasicFileAttributes.class).creationTime().toMillis(); dateAddedStringProperty.setValue(sdf.format(new Date(creationMS))); } catch (IOException e) { dateAddedStringProperty.setValue(sdf.format(new Date())); LOGGER.log(Level.INFO, "Unable to determine file creation time for album, assuming it is very old." + directory.toString(), e); } } public StringProperty getAlbumArtistProperty() { return albumArtistProperty; } public StringProperty getYearProperty() { return yearProperty; } public StringProperty getAlbumTitleProperty() { return albumTitleProperty; } public StringProperty getFullAlbumTitleProperty() { return fullAlbumTitleProperty; } public StringProperty getDateAddedStringProperty() { return dateAddedStringProperty; } public IntegerProperty getDiscNumberProperty() { return discNumberProperty; } public IntegerProperty getDiscCountProperty() { return discCountProperty; } public StringProperty getReleaseTypeProperty() { return releaseTypeProperty; } public StringProperty getDiscSubtitleProperty() { return discSubtitleProperty; } public String getAlbumArtist() { return albumArtistProperty.get(); } public String getYear() { return yearProperty.get(); } public String getAlbumTitle() { return albumTitleProperty.get(); } public String getFullAlbumTitle() { return fullAlbumTitleProperty.get(); } public Integer getDiscNumber() { return discNumberProperty.get(); } public Integer getDiscCount() { return discCountProperty.get(); } public String getReleaseType() { return releaseTypeProperty.get(); } public String getDiscSubtitle() { return discSubtitleProperty.get(); } public Path getPath() { return directory.toPath(); } public ObservableList<Track> getTracks() { return tracks; } @Override public boolean equals(Object e) { if (!(e instanceof Album)) { return false; } Album compareTo = (Album) e; return compareTo.getPath().toAbsolutePath().equals(this.getPath().toAbsolutePath()); } public Image getAlbumCoverImage() { for (Track track : tracks) { if (track.getAlbumCoverImage() != null) { return track.getAlbumCoverImage(); } } return null; } public Image getAlbumArtistImage() { for (Track track : tracks) { if (track.getAlbumCoverImage() != null) { return track.getArtistImage(); } } return null; } private void writeObject ( ObjectOutputStream out ) throws IOException { out.defaultWriteObject(); out.writeObject(new ArrayList<Track>(tracks)); } private void readObject ( ObjectInputStream in ) throws IOException, ClassNotFoundException { initializeTransientFields(); in.defaultReadObject(); tracks.addAll((ArrayList<Track>)in.readObject()); updateData(); } }
6,361
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
Playlist.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/library/Playlist.java
package net.joshuad.hypnos.library; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Serializable; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import net.joshuad.hypnos.Hypnos; import net.joshuad.hypnos.Utils; public class Playlist implements Serializable { private static final Logger LOGGER = Logger.getLogger(Playlist.class.getName()); private static final long serialVersionUID = 1L; public enum PlaylistShuffleMode { USE_DEFAULT, SEQUENTIAL, SHUFFLE, } public enum PlaylistRepeatMode { USE_DEFAULT, PLAY_ONCE, REPEAT } private transient ObservableList<Track> tracks = FXCollections.observableArrayList(); private transient boolean hasUnsavedData = true; private String name; private PlaylistShuffleMode shuffleMode = PlaylistShuffleMode.USE_DEFAULT; private PlaylistRepeatMode repeatMode = PlaylistRepeatMode.USE_DEFAULT; public Playlist(String name) { this(name, new ArrayList<Track>()); tracks.addListener((ListChangeListener.Change<? extends Track> change) -> { hasUnsavedData = true; }); } @Override public boolean equals(Object test) { if (test == null) { return false; } if (!(test instanceof Playlist)) { return false; } Playlist testPlaylist = (Playlist) test; return testPlaylist.name.equals(name); } public boolean hasUnsavedData() { return hasUnsavedData; } public void setHasUnsavedData(boolean b) { hasUnsavedData = b; } public Playlist(String name, List<Track> tracks) { if (name == null || name.length() == 0) { name = Hypnos.getLibrary().getUniquePlaylistName(); } setTracks(tracks); this.name = name; } public static List<Path> getTrackPaths(Path playlistPath) { List<Path> retMe = new ArrayList<Path>(); if (playlistPath.toString().toLowerCase().endsWith(".m3u")) { try (FileInputStream fileInput = new FileInputStream(playlistPath.toFile());) { BufferedReader m3uIn = new BufferedReader(new InputStreamReader(fileInput, "UTF8")); for (String line; (line = m3uIn.readLine()) != null;) { if (line.isEmpty()) { // Do nothing } else if (!line.startsWith("#")) { retMe.add(Paths.get(line)); } } } catch (Exception e) { LOGGER.log(Level.INFO, "Error reading playlist file: " + playlistPath, e); } } else { LOGGER.log(Level.INFO, "Asked to load a playlist that doesn't have a playlist extension, ignoring.", new Exception()); } return retMe; } public static Playlist loadPlaylist(Path path) { if (path.toString().toLowerCase().endsWith(".m3u")) { Playlist playlist = new Playlist(path.getFileName().toString()); try (FileInputStream fileInput = new FileInputStream(path.toFile());) { BufferedReader m3uIn = new BufferedReader(new InputStreamReader(fileInput, "UTF8")); for (String line; (line = m3uIn.readLine()) != null; /**/ ) { try { if (line.startsWith("#Name:")) { String name = line.split(":")[1].trim(); playlist.setName(name); } else if (line.startsWith("#RepeatMode:")) { PlaylistRepeatMode repeatMode = PlaylistRepeatMode.valueOf(line.split(":")[1].trim()); playlist.setRepeatMode(repeatMode); } else if (line.startsWith("#ShuffleMode:")) { PlaylistShuffleMode repeatMode = PlaylistShuffleMode.valueOf(line.split(":")[1].trim()); playlist.setShuffleMode(repeatMode); } else if (line.isEmpty()) { // Do nothing } else if (!line.startsWith("#")) { playlist.addTrack(new Track(Paths.get(line))); } } catch (Exception e) { LOGGER.info("Error parsing line in playlist: " + path.toString() + "\n\tLine: " + line); } } } catch (Exception e) { LOGGER.log(Level.INFO, "Error reading playlist file: " + path, e); return null; } return playlist; } return null; } public String getName() { return name; } public void setName(String newName) { this.name = newName; } public PlaylistRepeatMode getRepeatMode() { return repeatMode; } public void setRepeatMode(PlaylistRepeatMode repeatMode) { if (this.repeatMode != repeatMode) { this.repeatMode = repeatMode; hasUnsavedData = true; } } public PlaylistShuffleMode getShuffleMode() { return shuffleMode; } public void setShuffleMode(PlaylistShuffleMode shuffleMode) { if (this.shuffleMode != shuffleMode) { this.shuffleMode = shuffleMode; hasUnsavedData = true; } } public int getLength() { int retMe = 0; for (Track track : tracks) { if (track != null) { retMe += track.getLengthS(); } } return retMe; } public String getLengthDisplay() { return Utils.getLengthDisplay(getLength()); } public int getSongCount() { return tracks.size(); } public ObservableList<Track> getTracks() { return tracks; } public void setData(Playlist playlist) { tracks.clear(); tracks.addAll(playlist.tracks); name = playlist.name; shuffleMode = playlist.shuffleMode; repeatMode = playlist.repeatMode; hasUnsavedData = true; } public void setTracks(List<Track> newTracks) { if (tracks == null) { tracks.clear(); } else { tracks.clear(); tracks.addAll(newTracks); } } public void addTrack(Track track) { tracks.add(track); } public void addTracks(ArrayList<Track> addMe) { tracks.addAll(addMe); } public void saveAs(File file) throws IOException { if (file == null) { throw new IOException("Null file specified."); } try (FileOutputStream fileOut = new FileOutputStream(file)) { PrintWriter playlistOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(fileOut, "UTF8"))); playlistOut.println("#EXTM3U"); playlistOut.printf("#Name: %s%s", getName(), System.lineSeparator()); playlistOut.printf("#RepeatMode: %s%s", getRepeatMode(), System.lineSeparator()); playlistOut.printf("#ShuffleMode: %s%s", getShuffleMode(), System.lineSeparator()); playlistOut.printf("%s", System.lineSeparator()); for (Track track : getTracks()) { playlistOut.printf("#EXTINF:%d,%s - %s%s", track.getLengthS(), track.getArtist(), track.getTitle(), System.lineSeparator()); playlistOut.println(track.getPath().toString()); playlistOut.println(); } playlistOut.flush(); } } public String getBaseFilename() { String fileSafeName = getName().replaceAll("\\W+", ""); if (fileSafeName.length() > 12) { fileSafeName = fileSafeName.substring(0, 12); } String baseFileName = fileSafeName + getName().hashCode(); return baseFileName; } private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeObject(tracks.toArray(new Track[tracks.size()])); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); tracks = FXCollections.observableArrayList((Track[])in.readObject()); } }
7,631
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
Library.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/library/Library.java
package net.joshuad.hypnos.library; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import javafx.beans.InvalidationListener; import javafx.beans.Observable; import javafx.collections.ObservableList; import javafx.collections.transformation.FilteredList; import javafx.collections.transformation.SortedList; import me.xdrop.fuzzywuzzy.FuzzySearch; import net.joshuad.hypnos.AlphanumComparator; import net.joshuad.hypnos.Utils; import net.joshuad.hypnos.audio.AudioSystem; import net.joshuad.hypnos.fxui.FXUI; public class Library { private static final Logger LOGGER = Logger.getLogger(Library.class.getName()); public enum LoaderSpeed { LOW, MED, HIGH } // These are all three representations of the same data. Add stuff to the // Observable List, the other two can't accept add. private final CachedList<Track> tracks = new CachedList<>(); private final FilteredList<Track> tracksFiltered = new FilteredList<>(tracks.getDisplayItems(), p -> true); private final SortedList<Track> tracksSorted = new SortedList<>(tracksFiltered); private final CachedList<Album> albums = new CachedList<>(); private final FilteredList<Album> albumsFiltered = new FilteredList<>(albums.getDisplayItems(), p -> true); private final SortedList<Album> albumsSorted = new SortedList<>(albumsFiltered); private final CachedList<Artist> artists = new CachedList<>(); private final FilteredList<Artist> artistsFiltered = new FilteredList<>(artists.getDisplayItems(), p -> true); private final SortedList<Artist> artistsSorted = new SortedList<>(artistsFiltered); private final CachedList<Playlist> playlists = new CachedList<>(); private final FilteredList<Playlist> playlistsFiltered = new FilteredList<>(playlists.getDisplayItems(), p -> true); private final SortedList<Playlist> playlistsSorted = new SortedList<>(playlistsFiltered); private final CachedList<TagError> tagErrors = new CachedList<>(); private final FilteredList<TagError> tagErrorsFiltered = new FilteredList<>(tagErrors.getDisplayItems(), p -> true); private final SortedList<TagError> tagErrorsSorted = new SortedList<>(tagErrorsFiltered); private final CachedList<MusicRoot> musicRoots = new CachedList<>(); private AudioSystem audioSystem; private final LibraryLoader loader; private final DiskWatcher diskWatcher; private final LibraryScanLogger scanLogger = new LibraryScanLogger(); private boolean dataNeedsToBeSavedToDisk = false; private boolean upkeepNeeded = false; private final Object doUpkeepFlagLock = new Object(); public Library() { diskWatcher = new DiskWatcher(this, scanLogger); loader = new LibraryLoader(this, scanLogger); InvalidationListener invalidationListener = new InvalidationListener() { @Override public void invalidated(Observable arg0) { dataNeedsToBeSavedToDisk = true; synchronized (doUpkeepFlagLock) { upkeepNeeded = true; } } }; tracks.addListenerToBase(invalidationListener); albums.addListenerToBase(invalidationListener); Thread artistGeneratorThread = new Thread() { @Override public void run() { while (true) { boolean doUpkeep = false; synchronized (doUpkeepFlagLock) { doUpkeep = upkeepNeeded; upkeepNeeded = false; } if (doUpkeep) { scanLogger.println("[Library] Changes to library were made, regenerating artist list"); artists.getItemsCopy().setAll(generateArtists()); relinkPlaylistsToLibrary(); relinkCurrentListToLibrary(); } try { Thread.sleep(2000); } catch (InterruptedException e) { LOGGER.log(Level.INFO, "Sleep interupted during wait period.", e); } } } }; artistGeneratorThread.setName("Artist Generator"); artistGeneratorThread.setDaemon(true); artistGeneratorThread.start(); } public void setUI(FXUI ui) { loader.setUI(ui); diskWatcher.setUI(ui); } public boolean dataNeedsToBeSavedToDisk() { return dataNeedsToBeSavedToDisk; } public SortedList<Playlist> getPlaylistsSorted() { return playlistsSorted; } public ObservableList<Playlist> getPlaylistData() { return playlists.getItemsCopy(); } public ObservableList<Playlist> getPlaylistsDisplayCache() { return playlists.getDisplayItems(); } public ObservableList<MusicRoot> getMusicRootData() { return musicRoots.getItemsCopy(); } public ObservableList<MusicRoot> getMusicRootDisplayCache() { return musicRoots.getDisplayItems(); } public FilteredList<Playlist> getPlaylistsFiltered() { return playlistsFiltered; } public SortedList<Album> getAlbumsSorted() { return albumsSorted; } public FilteredList<Album> getAlbumsFiltered() { return albumsFiltered; } public ObservableList<Track> getTrackData() { return tracks.getItemsCopy(); } public ObservableList<Track> getTrackDisplayCache() { return tracks.getDisplayItems(); } public ObservableList<Album> getAlbumData() { return albums.getItemsCopy(); } public ObservableList<Album> getAlbumDisplayCache() { return albums.getDisplayItems(); } public ObservableList<Artist> getArtistData() { return artists.getItemsCopy(); } public ObservableList<Artist> getArtistDisplayCache() { return artists.getDisplayItems(); } public SortedList<Track> getTracksSorted() { return tracksSorted; } public FilteredList<Track> getTracksFiltered() { return tracksFiltered; } public SortedList<Artist> getArtistsSorted() { return artistsSorted; } public FilteredList<Artist> getArtistsFiltered() { return artistsFiltered; } public SortedList<TagError> getTagErrorsSorted() { return tagErrorsSorted; } public void requestRescan(Path path) { loader.queueUpdatePath(path); } public void requestRescan(List<Album> albums) { for (Album album : albums) { requestRescan(album.getPath()); } } public void setMusicRootsOnInitialLoad(List<MusicRoot> roots) { for (MusicRoot musicRoot : roots) { musicRoot.setNeedsRescan(true); } musicRoots.getItemsCopy().setAll(roots); } public void setDataOnInitialLoad(List<Playlist> playlists) { this.playlists.setDataOnInitialLoad(playlists); } public void setDataOnInitialLoad(List<Track> tracks, List<Album> albums) { this.tracks.setDataOnInitialLoad(tracks); this.albums.setDataOnInitialLoad(albums); this.artists.setDataOnInitialLoad(generateArtists()); List<TagError> errors = new ArrayList<>(); for(Track track : tracks) { errors.addAll(track.getTagErrors()); } this.tagErrors.setDataOnInitialLoad(errors); } public void addMusicRoot(Path path) { for (MusicRoot root : musicRoots.getItemsCopy()) { if(root.getPath().equals(path)) { return; } } musicRoots.addItem(new MusicRoot(path), true); } public void removeMusicRoot(MusicRoot musicRoot) { loader.interruptDiskReader(); musicRoots.remove(musicRoot, true); loader.setMusicRootRemoved(true); } public void removePlaylist(Playlist playlist) { playlists.remove(playlist, true); } public void addPlaylist(Playlist playlist) { playlists.addItem(playlist, true); } public String getUniquePlaylistName() { return getUniquePlaylistName("New Playlist"); } public void startThreads() { loader.start(); } public LibraryScanLogger getScanLogger() { return scanLogger; } public String getUniquePlaylistName(String base) { String name = base; int number = 0; while (true) { boolean foundMatch = false; for (Playlist playlist : playlists.getItemsCopy()) { if (playlist.getName().toLowerCase().equals(name.toLowerCase())) { foundMatch = true; } } if (foundMatch) { number++; name = base + " " + number; } else { break; } } return name; } private List<Artist> generateArtists() { List<Artist> newArtistList = new ArrayList<>(); List<Album> libraryAlbums = new ArrayList<>(albums.getItemsCopy()); Album[] albumArray = libraryAlbums.toArray(new Album[libraryAlbums.size()]); AlphanumComparator comparator = new AlphanumComparator(AlphanumComparator.CaseHandling.CASE_INSENSITIVE); Arrays.sort(albumArray, Comparator.comparing(Album::getAlbumArtist, comparator)); Artist lastArtist = null; for (Album album : albumArray) { if (album.getAlbumArtist().isBlank()) { continue; } if (lastArtist != null && lastArtist.getName().equals(album.getAlbumArtist())) { lastArtist.addAlbum(album); } else { Artist artist = null; for (Artist test : newArtistList) { if (test.getName().equalsIgnoreCase(album.getAlbumArtist())) { artist = test; break; } } if (artist == null) { artist = new Artist(album.getAlbumArtist()); newArtistList.add(artist); } artist.addAlbum(album); lastArtist = artist; } } List<Track> looseTracks = new ArrayList<>(); for (Track track : tracks.getItemsCopy()) { if (track.getAlbum() == null) { looseTracks.add(track); } } Track[] trackArray = looseTracks.toArray(new Track[looseTracks.size()]); Arrays.sort(trackArray, Comparator.comparing(Track::getAlbumArtist, comparator)); lastArtist = null; for (Track track : trackArray) { if (track.getAlbumArtist().isBlank()) continue; if (lastArtist != null && lastArtist.getName().equals(track.getAlbumArtist())) { lastArtist.addLooseTrack(track); } else { Artist artist = null; for (Artist test : newArtistList) { if (test.getName().equalsIgnoreCase(track.getAlbumArtist())) { artist = test; break; } } if (artist == null) { artist = new Artist(track.getAlbumArtist()); newArtistList.add(artist); } artist.addLooseTrack(track); lastArtist = artist; } } return newArtistList; } LibraryLoader getLoader() { return loader; } DiskWatcher getDiskWatcher() { return diskWatcher; } public void setDataNeedsToBeSavedToDisk(boolean b) { this.dataNeedsToBeSavedToDisk = b; } void addTrack(Track track) { tracks.addItem(track); for (TagError error : track.getTagErrors()) { tagErrors.addItem(error); } } void removeTrack(Track track) { tracks.remove(track); for (TagError error : track.getTagErrors()) { tagErrors.remove(error); } } void addAlbum(Album album) { albums.addItem(album); } void notAnAlbum(Path path) { for (Album album : albums.getItemsCopy()) { if (album.getPath().equals(path)) { albums.remove(album); break; } } } void removeAlbum(Album album) { albums.remove(album); } void requestRegenerateArtists() { upkeepNeeded = true; } public boolean isArtistDirectory(Path path) { String directoryName = Utils.prepareArtistForCompare(path.getFileName().toString()); List<Album> albumsInPath = new ArrayList<>(); for (Album album : albums.getItemsCopy()) { if (album.getPath().getParent().equals(path)) { albumsInPath.add(album); } } List<Track> tracksInPath = new ArrayList<>(); for (Track track : tracks.getItemsCopy()) { if (track.getPath().getParent().equals(path) && track.getAlbum() == null) { tracksInPath.add(track); } } if(albumsInPath.size() == 0 && tracksInPath.size() == 0) { return false; } for (Album album : albumsInPath) { try { int matchPercent = FuzzySearch.weightedRatio(directoryName, Utils.prepareArtistForCompare(album.getAlbumArtist())); if (matchPercent < 90) { return false; } } catch (Exception e) { continue; } } for (Track track : tracksInPath) { try { int matchPercent = FuzzySearch.weightedRatio(directoryName, Utils.prepareArtistForCompare(track.getAlbumArtist())); if (matchPercent < 90) { return false; } } catch (Exception e) { continue; } } return true; } private void relinkCurrentListToLibrary() { for (int k = 0; k < audioSystem.getCurrentList().getItems().size(); k++ ) { boolean foundInLibrary = false; for (Track libraryTrack : tracks.getItemsCopy()) { if (libraryTrack.equals(audioSystem.getCurrentList().getItems().get(k))) { audioSystem.getCurrentList().getItems().get(k).setData(libraryTrack); foundInLibrary = true; } } if(!foundInLibrary) { audioSystem.getCurrentList().getItems().get(k).setAlbum(null); } } } private void relinkPlaylistsToLibrary() { for (Playlist playlist : playlists.getItemsCopy()) { linkPlaylistToLibrary(playlist); } } public void linkPlaylistToLibrary(Playlist playlist) { for (int k = 0; k < playlist.getTracks().size(); k++ ) { boolean foundInLibrary = false; for (Track libraryTrack : tracks.getItemsCopy()) { if (libraryTrack.equals(playlist.getTracks().get(k))) { playlist.getTracks().set(k, libraryTrack); foundInLibrary = true; } } if(!foundInLibrary) { playlist.getTracks().get(k).setAlbum(null); } } } public void setAudioSystem(AudioSystem audioSystem) { this.audioSystem = audioSystem; } public void removeTagErrors(Vector<TagError> errors) { for (TagError error : errors) { tagErrors.remove(error); } } public void addTagErrors(Vector<TagError> errors) { for (TagError error : errors) { tagErrors.addItem(error); } } }
13,753
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
DiskWatcher.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/library/DiskWatcher.java
package net.joshuad.hypnos.library; import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.FileVisitOption; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.StandardWatchEventKinds; import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.nio.file.attribute.BasicFileAttributes; import java.util.EnumSet; import java.util.HashMap; import java.util.Vector; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import net.joshuad.hypnos.Hypnos; import net.joshuad.hypnos.HypnosURLS; import net.joshuad.hypnos.fxui.FXUI; import net.joshuad.hypnos.Hypnos.OS; class DiskWatcher { private static final Logger LOGGER = Logger.getLogger( DiskWatcher.class.getName() ); private WatchService watcher; private final HashMap<WatchKey, Path> keys = new HashMap<WatchKey, Path>(); private DelayedUpdateThread delayedUpdater; private FXUI ui; private LibraryScanLogger scanLogger; DiskWatcher( Library library, LibraryScanLogger scanLogger ) { this.scanLogger = scanLogger; delayedUpdater = new DelayedUpdateThread( library ); try { watcher = FileSystems.getDefault().newWatchService(); delayedUpdater.start(); } catch ( IOException e ) { String message = "Unable to initialize file watcher, changes to file system while running won't be detected"; LOGGER.log( Level.WARNING, message, e ); ui.notifyUserError( message ); } } void setUI ( FXUI ui ) { this.ui = ui; } void stopWatching( Path path ) { //TODO: Should we stop watching recursively? for( WatchKey key : keys.keySet() ) { if( keys.get( key ).equals( path ) ) { scanLogger.println( "[Watcher] stopping watch on: " + path.toString() ); key.cancel(); } } } void watchAll( final Path path ) { watchAll( path, null ); } void watchAll( final MusicRoot musicRoot ) { watchAll( musicRoot.getPath(), null ); } void watchAll( final Path path, final MusicRoot musicRoot ) { /* Note: in my testing, this takes less than a few seconds to run, depending on folder count */ try { Files.walkFileTree( path, EnumSet.of( FileVisitOption.FOLLOW_LINKS ), Integer.MAX_VALUE, new SimpleFileVisitor <Path>() { @Override public FileVisitResult preVisitDirectory ( Path dir, BasicFileAttributes attrs ) throws IOException { if ( !keys.containsValue( dir ) ) { WatchKey key = dir.register( watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY ); keys.put( key, dir ); } return FileVisitResult.CONTINUE; } } ); } catch ( IOException e ) { if ( Hypnos.getOS() == OS.NIX && e.getMessage().matches( ".*inotify.*" ) ) { if ( ui != null ) { ui.notifyUserLinuxInotifyIssue(); } LOGGER.log( Level.INFO, e.getMessage() + "\nUnable to watch directory for changes: " + musicRoot.getPath().toString() + "\nSee here for how to fix this error on linux: " + HypnosURLS.HELP_INOTIFY ); if ( musicRoot != null ) { musicRoot.setHadInotifyError( true ); } } else { LOGGER.log( Level.INFO, e.getMessage() + "\nUnable to watch directory for changes: " + musicRoot.getPath().toString(), e ); } } } boolean processWatcherEvents () { WatchKey key; try { key = watcher.poll( 250, TimeUnit.MILLISECONDS ); } catch ( InterruptedException e ) { return false; } Path directory = keys.get( key ); if ( directory == null ) { return false; } for ( WatchEvent <?> event : key.pollEvents() ) { WatchEvent.Kind<?> eventKind = event.kind(); WatchEvent <Path> watchEvent = (WatchEvent<Path>)event; Path child = directory.resolve( watchEvent.context() ); if ( eventKind == StandardWatchEventKinds.ENTRY_CREATE ) { scanLogger.println( "[Watcher] Heard create: " + child ); delayedUpdater.addUpdateItem( child ); } else if ( eventKind == StandardWatchEventKinds.ENTRY_DELETE ) { scanLogger.println( "[Watcher] heard delete: " + child ); delayedUpdater.addUpdateItem( child ); } else if ( eventKind == StandardWatchEventKinds.ENTRY_MODIFY ) { scanLogger.println( "[Watcher] heard modify: " + child ); delayedUpdater.addUpdateItem( child ); } else if ( eventKind == StandardWatchEventKinds.OVERFLOW ) { //TODO: Think about how to handle this } boolean valid = key.reset(); if ( !valid ) { keys.remove( key ); } } return true; } } class DelayedUpdateThread extends Thread { private final Logger LOGGER = Logger.getLogger( DelayedUpdateThread.class.getName() ); public final int DELAY_LENGTH_MS = 3000; public int counter = DELAY_LENGTH_MS; Vector <Path> updateItems = new Vector <Path> (); Library library; public DelayedUpdateThread ( Library library ) { this.library = library; setDaemon( true ); setName ( "Library Update Delayer" ); } public void run() { while ( true ) { long startSleepTime = System.currentTimeMillis(); try { Thread.sleep ( 50 ); } catch ( InterruptedException e ) { LOGGER.log ( Level.INFO, "Sleep interupted during wait period.", e ); } long sleepTime = System.currentTimeMillis() - startSleepTime; if ( counter > 0 ) { counter -= sleepTime; } else { Vector <Path> copyUpdateItems = new Vector<Path> ( updateItems ); for ( Path location : copyUpdateItems ) { library.getLoader().queueUpdatePath ( location ); updateItems.remove( location ); } } } } public void addUpdateItem ( Path location ) { counter = DELAY_LENGTH_MS; if ( !updateItems.contains( location ) ) { updateItems.add ( location ); } } };
6,059
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
FileTreeNode.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/library/FileTreeNode.java
package net.joshuad.hypnos.library; import java.io.File; import java.io.Serializable; import java.nio.file.Path; import java.util.LinkedHashSet; import java.util.Set; class FileTreeNode implements Serializable { private static final long serialVersionUID = 1L; private final FileTreeNode parent; private final File file; private final Set<FileTreeNode> children = new LinkedHashSet<> (); private Track track; private Album album; private Artist artist; FileTreeNode ( Path path, FileTreeNode parent ) { this.file = path.toFile(); this.parent = parent; } FileTreeNode(Path filePath, FileTreeNode parent, Track track) { this ( filePath, parent ); this.track = track; } FileTreeNode getParent() { return parent; } Path getPath() { return file.toPath(); } void addChild ( FileTreeNode child ) { children.add( child ); } Set<FileTreeNode> getChildren() { return children; } Track getTrack() { return track; } void setAlbum( Album album ) { this.album = album; } Album getAlbum() { return album; } void setArtist( Artist artist ) { this.artist = artist; } Artist getArtist() { return artist; } }
1,238
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
Artist.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/library/Artist.java
package net.joshuad.hypnos.library; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javafx.beans.InvalidationListener; import javafx.beans.Observable; import javafx.beans.binding.Bindings; import javafx.beans.property.IntegerProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; public class Artist implements Serializable { private static final long serialVersionUID = 1L; //This values are only used and accurate during serialization. Don't read and write to them. private List <Album> albumsForSerialization = new ArrayList<>(); private List <Track> looseTracksForSerialization = new ArrayList<>(); private transient ObservableList <Album> albums = FXCollections.observableArrayList(); private transient ObservableList <Track> looseTracks = FXCollections.observableArrayList(); private transient StringProperty name = new SimpleStringProperty(""); private transient IntegerProperty trackCount = new SimpleIntegerProperty(); { //This is a hack because Track and Album don't use Observable Values albums.addListener( ( Observable obs ) -> trackCount.set( getAllTracks().size() ) ); looseTracks.addListener( ( Observable obs ) -> trackCount.set( getAllTracks().size() ) ); }; private transient IntegerProperty albumCount = new SimpleIntegerProperty(); { albumCount.bind( Bindings.size( albums ) ); } private transient IntegerProperty totalLength = new SimpleIntegerProperty ( 0 ); { //This is a hack because Track and Album don't use Observable Values InvalidationListener listener = ( Observable obs ) -> recalculateTotalLength(); albums.addListener( listener ); looseTracks.addListener( listener ); }; private void recalculateTotalLength () { int lengthS = 0; for ( Track track : getAllTracks() ) { lengthS += track.getLengthS(); } totalLength.setValue( lengthS ); } public Artist ( String name ) { this.name.set(name); } public Artist ( String name, List<Album> albums, List<Track> looseTracks ) { this.name.set(name); albums.addAll( albums ); looseTracks.addAll( looseTracks ); } public String getName() { return name.get(); } public StringProperty nameProperty() { return name; } public IntegerProperty lengthProperty() { return totalLength; } public IntegerProperty albumCountProperty() { return albumCount; } public IntegerProperty trackCountProperty() { return trackCount; } public int getTrackCount() { return trackCount.get(); } public List<Track> getAllTracks() { List<Track> retMe = new ArrayList<>(); for ( Album album : albums ) { retMe.addAll ( album.getTracks() ); } retMe.addAll( looseTracks ); return retMe; } public boolean equals ( Object object ) { if ( ! ( object instanceof Artist ) ) { return false; } return ( ((Artist)object).getName().equals ( getName() ) ); } public void addAlbum ( Album album ) { if ( albums.contains( album ) ) { albums.remove( album ); } //TODO: error checking maybe? albums.add ( album ); } public void addLooseTrack ( Track track ) { looseTracks.add ( track ); } public void removeAlbum ( Album removeMe ) { albums.remove( removeMe ); } public void removeTrack ( Track removeMe ) { looseTracks.remove ( removeMe ); } public List <Album> getAlbums () { return new ArrayList<Album> ( albums ); } private void writeObject ( ObjectOutputStream out ) throws IOException { albumsForSerialization.clear(); albumsForSerialization.addAll( albums ); looseTracksForSerialization.clear(); looseTracksForSerialization.addAll( looseTracks ); out.defaultWriteObject(); } private void readObject ( ObjectInputStream in ) throws IOException, ClassNotFoundException { in.defaultReadObject(); trackCount = new SimpleIntegerProperty(); albumCount = new SimpleIntegerProperty(); totalLength = new SimpleIntegerProperty(); name = new SimpleStringProperty(); albums = FXCollections.observableArrayList( albumsForSerialization ); looseTracks = FXCollections.observableArrayList( looseTracksForSerialization ); albumCount.set( albums.size() ); trackCount.set( getAllTracks().size() ); recalculateTotalLength(); } }
4,655
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
CachedList.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/library/CachedList.java
package net.joshuad.hypnos.library; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Platform; import javafx.beans.InvalidationListener; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; public class CachedList<T> { private static final Logger LOGGER = Logger.getLogger(CachedList.class.getName()); ObservableList<T> items = FXCollections.observableArrayList(new ArrayList<T>()); Lock itemsLock = new ReentrantLock(); ObservableList<T> displayCache = FXCollections .synchronizedObservableList(FXCollections.observableArrayList(new ArrayList<T>())); List<Action<T>> pendingChanges = new ArrayList<>(); boolean runLaterPending = false; public CachedList() { items.addListener(new ListChangeListener<T>() { @Override public void onChanged(Change<? extends T> change) { while (change.next()) { if (change.wasPermutated()) { for (int i = change.getFrom(); i < change.getTo(); ++i) { //I don't care about order, ignoring } } else if (change.wasUpdated()) { // do nothing, this is handled automatically } else { for (T removedItem : change.getRemoved()) { pendingChanges.add(new Action<T>(Action.ChangeType.REMOVE, removedItem)); } for (T addedItem : change.getAddedSubList()) { pendingChanges.add(new Action<T>(Action.ChangeType.ADD, addedItem)); } } } } }); Thread changeExecutor = new Thread() { @Override public void run() { while (true) { if (!runLaterPending) { pushChanges(); } try { Thread.sleep(100); } catch (InterruptedException e) { LOGGER.log(Level.INFO, "Sleep interupted during wait period.", e); } } } }; changeExecutor.setDaemon(true); changeExecutor.setName("Library to UI updater"); changeExecutor.start(); } public void remove(T removeMe) { remove(removeMe, false); } public void remove(T removeMe, boolean fxThreadPermitted) { if(!fxThreadPermitted && Platform.isFxApplicationThread()) { LOGGER.log( Level.WARNING, "Modifying the base list while on UI Thread. This is likely a bug, but trying to continue.", new Exception() ); } if(removeMe == null) { LOGGER.log(Level.WARNING, "Asked to remove a null item from list, ignoring.", new Exception()); return; } try { itemsLock.lock(); items.remove(removeMe); } finally { itemsLock.unlock(); } } public void addItem(T addMe) { addItem(addMe, false); } public void addItem(T addMe, boolean fxThreadPermitted) { if(!fxThreadPermitted && Platform.isFxApplicationThread()) { LOGGER.log(Level.INFO, "Modifying the base list while on UI Thread. This is likely a bug, but trying to continue.", new Exception() ); } if(addMe == null) { LOGGER.log(Level.WARNING, "Asked to add a null item to list, ignoring.", new NullPointerException() ); return; } try { itemsLock.lock(); items.add(addMe); } finally { itemsLock.unlock(); } } //TODO: Can i just make this public List<T> getItems() {return items;}? I think so public ObservableList<T> getItemsCopy() { try { itemsLock.lock(); ObservableList<T> retMe = FXCollections.observableList(items); return retMe; } finally { itemsLock.unlock(); } } public ObservableList<T> getDisplayItems() { if(!Platform.isFxApplicationThread()) { LOGGER.log(Level.INFO, "Asked for display items while not on FX thread, this is likely a bug, but continuing.", new Exception() ); } return displayCache; } private void pushChanges() { if (!pendingChanges.isEmpty()) { runLaterPending = true; Platform.runLater(() -> { long startTime = System.currentTimeMillis(); boolean locked = false; try { if (itemsLock.tryLock(200, TimeUnit.MILLISECONDS)) { locked = true; while (pendingChanges.size() > 0 && System.currentTimeMillis() - startTime < 400) { Action<T> action = pendingChanges.remove(0); switch (action.getType()) { case ADD: displayCache.add(action.getItem()); break; case REMOVE: displayCache.remove(action.getItem()); break; case UPDATE: break; default: break; } } } } catch (Exception e) { LOGGER.log(Level.INFO, "Exception while trying to acquire lock, continuing.", e); } finally { runLaterPending = false; if (locked) { itemsLock.unlock(); } } }); } } public void addListenerToBase(InvalidationListener listener) { items.addListener(listener); } public void setDataOnInitialLoad(List<T> initialItems) { items.addAll(initialItems); displayCache.addAll(initialItems); pendingChanges.clear(); } } class Action<T> { public enum ChangeType { ADD, REMOVE, UPDATE }; T item; ChangeType type; public Action(ChangeType type, T item) { this.item = item; this.type = type; } public T getItem() { return item; } public ChangeType getType() { return type; } }
5,567
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
LibraryPlaylistPane.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/fxui/LibraryPlaylistPane.java
package net.joshuad.hypnos.fxui; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.text.Normalizer; import java.util.ArrayList; import java.util.Arrays; import java.util.EnumMap; import java.util.List; import java.util.Optional; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Platform; import javafx.collections.ListChangeListener; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.CheckMenuItem; import javafx.scene.control.ContextMenu; import javafx.scene.control.Label; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.scene.control.RadioMenuItem; import javafx.scene.control.SelectionMode; import javafx.scene.control.TableColumn; import javafx.scene.control.TableRow; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.ToggleGroup; import javafx.scene.control.Tooltip; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.TableColumn.SortType; import javafx.scene.control.TableView.ResizeFeatures; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.effect.ColorAdjust; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.ClipboardContent; import javafx.scene.input.Dragboard; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseButton; import javafx.scene.input.TransferMode; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.text.TextAlignment; import net.joshuad.hypnos.AlphanumComparator; import net.joshuad.hypnos.Hypnos; import net.joshuad.hypnos.Persister; import net.joshuad.hypnos.Utils; import net.joshuad.hypnos.AlphanumComparator.CaseHandling; import net.joshuad.hypnos.Persister.Setting; import net.joshuad.hypnos.audio.AudioSystem; import net.joshuad.hypnos.fxui.DraggedTrackContainer.DragSource; import net.joshuad.hypnos.library.Library; import net.joshuad.hypnos.library.Playlist; import net.joshuad.hypnos.library.Track; import net.joshuad.hypnos.library.Playlist.PlaylistRepeatMode; import net.joshuad.hypnos.library.Playlist.PlaylistShuffleMode; public class LibraryPlaylistPane extends BorderPane { private static final Logger LOGGER = Logger.getLogger( LibraryPlaylistPane.class.getName() ); private FXUI ui; private AudioSystem audioSystem; private Library library; TableView <Playlist> playlistTable; HBox FilterPane; ContextMenu columnSelectorMenu; TableColumn<Playlist, String> nameColumn, lengthColumn; TableColumn<Playlist, Integer> tracksColumn; Label emptyLabel = new Label( "You haven't created any playlists, make a playlist on the right and click the save button." ); Label filteredLabel = new Label( "No playlists match." ); Label noColumnsLabel = new Label( "All columns hidden." ); Label loadingLabel = new Label( "Loading..." ); TextField filterBox; private ImageView addSourceImage, filterClearImage; public LibraryPlaylistPane ( FXUI ui, AudioSystem audioSystem, Library library ) { this.library = library; this.audioSystem = audioSystem; this.ui = ui; setupPlaylistFilterPane(); setupPlaylistTable(); resetTableSettingsToDefault(); FilterPane.prefWidthProperty().bind( this.widthProperty() ); this.setTop( FilterPane ); this.setCenter( playlistTable ); library.getPlaylistsSorted().addListener( new ListChangeListener<Playlist>() { @Override public void onChanged(Change<? extends Playlist> arg0) { updatePlaceholders(); } }); nameColumn.visibleProperty().addListener( e -> updatePlaceholders() ); lengthColumn.visibleProperty().addListener( e -> updatePlaceholders() ); tracksColumn.visibleProperty().addListener( e -> updatePlaceholders() ); resetTableSettingsToDefault(); } public void updatePlaceholders() { Platform.runLater( () -> { boolean someVisible = false; for ( TableColumn<?,?> column : playlistTable.getColumns() ) { if ( column.isVisible() ) { someVisible = true; break; } } if ( !someVisible ) { playlistTable.setPlaceholder( noColumnsLabel ); } else if ( library.getPlaylistsDisplayCache().isEmpty() ) { if ( playlistTable.getPlaceholder() != emptyLabel ) { playlistTable.setPlaceholder( emptyLabel ); } } else { if ( !playlistTable.getPlaceholder().equals( filteredLabel ) ) { playlistTable.setPlaceholder( filteredLabel ); } } }); } public void setupPlaylistFilterPane () { FilterPane = new HBox(); filterBox = new TextField(); filterBox.setPrefWidth( 500000 ); filterBox.textProperty().addListener( ( observable, oldValue, newValue ) -> { Platform.runLater( () -> { library.getPlaylistsFiltered().setPredicate( playlist -> { if ( newValue == null || newValue.isEmpty() ) { return true; } String[] lowerCaseFilterTokens = newValue.toLowerCase().split( "\\s+" ); ArrayList <String> matchableText = new ArrayList <String>(); matchableText.add( Normalizer.normalize( playlist.getName(), Normalizer.Form.NFD ).replaceAll( "[^\\p{ASCII}]", "" ).toLowerCase() ); matchableText.add( playlist.getName().toLowerCase() ); for ( String token : lowerCaseFilterTokens ) { boolean tokenMatches = false; for ( String test : matchableText ) { if ( test.contains( token ) ) { tokenMatches = true; } } if ( !tokenMatches ) { return false; } } return true; }); }); }); filterBox.setOnKeyPressed( ( KeyEvent event ) -> { if ( event.getCode() == KeyCode.ESCAPE ) { filterBox.clear(); if ( filterBox.getText().length() > 0 ) { filterBox.clear(); } else { playlistTable.requestFocus(); } event.consume(); } else if ( event.getCode() == KeyCode.DOWN ) { playlistTable.requestFocus(); playlistTable.getSelectionModel().select( playlistTable.getSelectionModel().getFocusedIndex() ); } else if ( event.getCode() == KeyCode.ENTER && !event.isAltDown() && !event.isShiftDown() && !event.isControlDown() && !event.isMetaDown() ) { event.consume(); Playlist playMe = playlistTable.getSelectionModel().getSelectedItem(); if( playMe == null ) playlistTable.getItems().get( 0 ); audioSystem.getCurrentList().setAndPlayPlaylist( playMe ); } else if ( event.getCode() == KeyCode.ENTER && event.isShiftDown() && !event.isAltDown() && !event.isControlDown() && !event.isMetaDown() ) { event.consume(); Playlist playMe = playlistTable.getSelectionModel().getSelectedItem(); if( playMe == null ) playlistTable.getItems().get( 0 ); audioSystem.getQueue().queueAllPlaylists( Arrays.asList( playMe ) ); } else if ( event.getCode() == KeyCode.ENTER && event.isControlDown() && !event.isAltDown() && !event.isShiftDown() && !event.isMetaDown() ) { event.consume(); Playlist playMe = playlistTable.getSelectionModel().getSelectedItem(); if( playMe == null ) playlistTable.getItems().get( 0 ); audioSystem.getCurrentList().appendPlaylist( playMe ); } }); double width = 33; float height = Hypnos.getOS().isWindows() ? 28 : 26; filterBox.setPrefHeight( height ); String addLocation = "resources/add.png"; String clearLocation = "resources/clear.png"; try { double currentListControlsButtonFitWidth = 15; double currentListControlsButtonFitHeight = 15; Image image = new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( addLocation ).toFile() ) ); addSourceImage = new ImageView ( image ); addSourceImage.setFitWidth( currentListControlsButtonFitWidth ); addSourceImage.setFitHeight( currentListControlsButtonFitHeight ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to load add icon: " + addLocation, e ); } try { Image clearImage = new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( clearLocation ).toFile() ) ); filterClearImage = new ImageView ( clearImage ); filterClearImage.setFitWidth( 12 ); filterClearImage.setFitHeight( 12 ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to load clear icon: " + clearLocation, e ); } Button libraryButton = new Button( ); libraryButton.setGraphic ( addSourceImage ); libraryButton.setMinSize( width, height ); libraryButton.setPrefSize( width, height ); libraryButton.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent e ) { if ( ui.libraryLocationWindow.isShowing() ) { ui.libraryLocationWindow.hide(); } else { ui.libraryLocationWindow.show(); } } }); Button clearButton = new Button ( ); clearButton.setGraphic( filterClearImage ); clearButton.setMinSize( width, height ); clearButton.setPrefSize( width, height ); clearButton.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent e ) { filterBox.setText( "" ); } }); libraryButton.setTooltip( new Tooltip( "Add or Remove Music Folders" ) ); filterBox.setTooltip ( new Tooltip ( "Filter/Search playlists" ) ); clearButton.setTooltip( new Tooltip( "Clear the filter text" ) ); FilterPane.getChildren().addAll( libraryButton, filterBox, clearButton ); } public void resetTableSettingsToDefault() { nameColumn.setVisible( true ); lengthColumn.setVisible( true ); tracksColumn.setVisible( true ); playlistTable.getColumns().remove( nameColumn ); playlistTable.getColumns().add( nameColumn ); playlistTable.getColumns().remove( lengthColumn ); playlistTable.getColumns().add( lengthColumn ); playlistTable.getColumns().remove( tracksColumn ); playlistTable.getColumns().add( tracksColumn ); playlistTable.getSortOrder().clear(); nameColumn.setSortType( SortType.ASCENDING ); tracksColumn.setSortType( SortType.ASCENDING ); lengthColumn.setSortType( SortType.ASCENDING ); nameColumn.setPrefWidth( 100 ); tracksColumn.setPrefWidth( 90 ); lengthColumn.setPrefWidth( 90 ); playlistTable.getColumnResizePolicy().call(new ResizeFeatures<Playlist> ( playlistTable, null, 0d ) ); } public void setupPlaylistTable () { nameColumn = new TableColumn<Playlist, String>( "Playlist" ); lengthColumn = new TableColumn<Playlist, String>( "Length" ); tracksColumn = new TableColumn<Playlist, Integer>( "Tracks" ); lengthColumn.setComparator( new AlphanumComparator( CaseHandling.CASE_INSENSITIVE ) ); //TODO: Are these the right types? Integer/String look wrong. nameColumn.setCellValueFactory( new PropertyValueFactory <Playlist, String>( "Name" ) ); lengthColumn.setCellValueFactory( new PropertyValueFactory <Playlist, String>( "LengthDisplay" ) ); tracksColumn.setCellValueFactory( new PropertyValueFactory <Playlist, Integer>( "SongCount" ) ); columnSelectorMenu = new ContextMenu (); CheckMenuItem nameMenuItem = new CheckMenuItem ( "Show Name Column" ); CheckMenuItem tracksMenuItem = new CheckMenuItem ( "Show Tracks Column" ); CheckMenuItem lengthMenuItem = new CheckMenuItem ( "Show Length Column" ); MenuItem defaultMenuItem = new MenuItem ( "Reset to Default View" ); nameMenuItem.setSelected( true ); tracksMenuItem.setSelected( true ); lengthMenuItem.setSelected( true ); columnSelectorMenu.getItems().addAll( nameMenuItem, tracksMenuItem, lengthMenuItem, defaultMenuItem ); nameColumn.setContextMenu( columnSelectorMenu ); tracksColumn.setContextMenu( columnSelectorMenu ); lengthColumn.setContextMenu( columnSelectorMenu ); nameMenuItem.selectedProperty().bindBidirectional( nameColumn.visibleProperty() ); tracksMenuItem.selectedProperty().bindBidirectional( tracksColumn.visibleProperty() ); lengthMenuItem.selectedProperty().bindBidirectional( lengthColumn.visibleProperty() ); defaultMenuItem.setOnAction( ( e ) -> this.resetTableSettingsToDefault() ); playlistTable = new TableView<Playlist>(); playlistTable.getColumns().addAll( nameColumn, tracksColumn, lengthColumn ); playlistTable.setEditable( false ); playlistTable.getSelectionModel().setSelectionMode( SelectionMode.MULTIPLE ); playlistTable.setItems( library.getPlaylistsSorted() ); library.getPlaylistsSorted().comparatorProperty().bind( playlistTable.comparatorProperty() ); HypnosResizePolicy resizePolicy = new HypnosResizePolicy(); playlistTable.setColumnResizePolicy( resizePolicy ); resizePolicy.registerFixedWidthColumns( tracksColumn, lengthColumn ); emptyLabel.setWrapText( true ); emptyLabel.setTextAlignment( TextAlignment.CENTER ); emptyLabel.setPadding( new Insets( 20, 10, 20, 10 ) ); playlistTable.setPlaceholder( emptyLabel ); MenuItem playMenuItem = new MenuItem( "Play" ); MenuItem appendMenuItem = new MenuItem( "Append" ); MenuItem playNextMenuItem = new MenuItem( "Play Next" ); MenuItem enqueueMenuItem = new MenuItem( "Enqueue" ); MenuItem renameMenuItem = new MenuItem( "Rename" ); MenuItem infoMenuItem = new MenuItem( "Track List" ); MenuItem goToFolderItem = new MenuItem( "Go to Folder" ); MenuItem exportM3UMenuItem = new MenuItem( "Export as M3U" ); MenuItem exportFolderMenuItem = new MenuItem ( "Export as Folder" ); MenuItem removeMenuItem = new MenuItem( "Remove" ); RadioMenuItem shuffleNoChange = new RadioMenuItem ( "Use Default" ); RadioMenuItem shuffleSequential = new RadioMenuItem ( "Sequential" ); RadioMenuItem shuffleShuffle = new RadioMenuItem ( "Shuffle" ); Menu shuffleMode = new Menu ( "Shuffle Mode" ); shuffleMode.getItems().addAll( shuffleNoChange, shuffleSequential, shuffleShuffle ); ToggleGroup shuffleGroup = new ToggleGroup(); shuffleNoChange.setToggleGroup( shuffleGroup ); shuffleSequential.setToggleGroup( shuffleGroup ); shuffleShuffle.setToggleGroup( shuffleGroup ); shuffleGroup.selectedToggleProperty().addListener( ( observale, oldValue, newValue ) -> { PlaylistShuffleMode targetMode; if ( newValue.equals( shuffleSequential ) ) { targetMode = PlaylistShuffleMode.SEQUENTIAL; } else if ( newValue.equals( shuffleShuffle ) ) { targetMode = PlaylistShuffleMode.SHUFFLE; } else { targetMode = PlaylistShuffleMode.USE_DEFAULT; } playlistTable.getSelectionModel().getSelectedItem().setShuffleMode( targetMode ); }); RadioMenuItem repeatNoChange = new RadioMenuItem ( "Use Default" ); RadioMenuItem repeatPlayOnce = new RadioMenuItem ( "Play Once" ); RadioMenuItem repeatRepeat = new RadioMenuItem ( "Repeat" ); Menu repeatMode = new Menu ( "Repeat Mode" ); repeatMode.getItems().addAll( repeatNoChange, repeatPlayOnce, repeatRepeat ); ToggleGroup repeatGroup = new ToggleGroup(); repeatNoChange.setToggleGroup( repeatGroup ); repeatPlayOnce.setToggleGroup( repeatGroup ); repeatRepeat.setToggleGroup( repeatGroup ); shuffleGroup.selectedToggleProperty().addListener( ( observable, oldValue, newValue ) -> { PlaylistShuffleMode targetMode; if ( newValue.equals( shuffleSequential ) ) { targetMode = PlaylistShuffleMode.SEQUENTIAL; } else if ( newValue.equals( shuffleShuffle ) ) { targetMode = PlaylistShuffleMode.SHUFFLE; } else { targetMode = PlaylistShuffleMode.USE_DEFAULT; } playlistTable.getSelectionModel().getSelectedItem().setShuffleMode( targetMode ); }); repeatGroup.selectedToggleProperty().addListener( ( observable, oldValue, newValue ) -> { PlaylistRepeatMode targetMode; if ( newValue.equals( repeatPlayOnce ) ) { targetMode = PlaylistRepeatMode.PLAY_ONCE; } else if ( newValue.equals( repeatRepeat ) ) { targetMode = PlaylistRepeatMode.REPEAT; } else { targetMode = PlaylistRepeatMode.USE_DEFAULT; } playlistTable.getSelectionModel().getSelectedItem().setRepeatMode( targetMode ); }); ContextMenu contextMenu = new ContextMenu(); contextMenu.getItems().addAll( playMenuItem, appendMenuItem, playNextMenuItem, enqueueMenuItem, shuffleMode, repeatMode, renameMenuItem, infoMenuItem, goToFolderItem, exportM3UMenuItem, exportFolderMenuItem, removeMenuItem ); playMenuItem.setOnAction( ( ActionEvent event ) -> { if ( ui.okToReplaceCurrentList() ) { audioSystem.getCurrentList().setAndPlayPlaylists( playlistTable.getSelectionModel().getSelectedItems() ); } }); appendMenuItem.setOnAction( ( ActionEvent event ) -> { audioSystem.getCurrentList().appendPlaylists( playlistTable.getSelectionModel().getSelectedItems() ); }); playNextMenuItem.setOnAction( ( ActionEvent event ) -> { audioSystem.getQueue().queueAllPlaylists( playlistTable.getSelectionModel().getSelectedItems(), 0 ); }); enqueueMenuItem.setOnAction( ( ActionEvent event ) -> { audioSystem.getQueue().queueAllPlaylists( playlistTable.getSelectionModel().getSelectedItems() ); }); renameMenuItem.setOnAction( ( ActionEvent event ) -> { ui.promptAndRenamePlaylist ( playlistTable.getSelectionModel().getSelectedItem() ); }); infoMenuItem.setOnAction( ( ActionEvent event ) -> { ui.playlistInfoWindow.setPlaylist ( playlistTable.getSelectionModel().getSelectedItem() ); ui.playlistInfoWindow.show(); }); goToFolderItem.setOnAction( ( ActionEvent event ) -> { ui.openFileBrowser(Hypnos.getPersister().getPlaylistDirectory()); }); exportM3UMenuItem.setOnAction( ( ActionEvent event ) -> { File targetFile = ui.promptUserForPlaylistFile(); if ( targetFile == null ) { return; } Playlist saveMe = playlistTable.getSelectionModel().getSelectedItem(); if ( saveMe == null ) { return; } try { saveMe.saveAs( targetFile ); } catch ( IOException e1 ) { ui.alertUser ( AlertType.ERROR, "Warning", "Unable to save playlist.", "Unable to save the playlist to the specified location" ); } }); exportFolderMenuItem.setOnAction( ( ActionEvent event ) -> { List<Track> exportMe = playlistTable.getSelectionModel().getSelectedItem().getTracks(); ui.exportPopup.export( exportMe ); }); removeMenuItem.setOnAction( ( ActionEvent event ) -> { List <Playlist> deleteMe = playlistTable.getSelectionModel().getSelectedItems(); if ( deleteMe.size() == 0 ) return; Alert alert = new Alert( AlertType.CONFIRMATION ); ui.applyCurrentTheme( alert ); FXUI.setAlertWindowIcon( alert ); double x = ui.mainStage.getX() + ui.mainStage.getWidth() / 2 - 220; //It'd be nice to use alert.getWidth() / 2, but it's NAN now. double y = ui.mainStage.getY() + ui.mainStage.getHeight() / 2 - 50; alert.setX( x ); alert.setY( y ); alert.setTitle( "Confirm" ); alert.setHeaderText( "Delete Playlist Requested" ); String text = "Are you sure you want to delete theses playlists?\n"; int count = 0; for ( Playlist playlist : deleteMe ) { text += "\n " + playlist.getName(); count++; if ( count > 6 ) { text += "\n <... and more>"; break; } }; alert.setContentText( text ); Optional <ButtonType> result = alert.showAndWait(); if ( result.get() == ButtonType.OK ) { for ( Playlist playlist : playlistTable.getSelectionModel().getSelectedItems() ) { library.removePlaylist( playlist ); Hypnos.getPersister().deletePlaylistFile(playlist); } playlistTable.getSelectionModel().clearSelection(); } }); playlistTable.getSelectionModel().selectedItemProperty().addListener( ( obs, oldSelection, newSelection ) -> { if (newSelection != null) { ui.playlistInfoWindow.setPlaylist( newSelection ); } }); playlistTable.setOnKeyPressed( ( KeyEvent e ) -> { if ( e.getCode() == KeyCode.ESCAPE ) { if ( filterBox.getText().length() > 0 ) { filterBox.clear(); Platform.runLater( ()-> playlistTable.scrollTo( playlistTable.getSelectionModel().getSelectedItem() ) ); } else { playlistTable.getSelectionModel().clearSelection(); } } else if ( e.getCode() == KeyCode.F2 && !e.isAltDown() && !e.isControlDown() && !e.isMetaDown() && !e.isShiftDown() ) { renameMenuItem.fire(); } else if ( e.getCode() == KeyCode.F3 && !e.isAltDown() && !e.isControlDown() && !e.isMetaDown() && !e.isShiftDown() ) { infoMenuItem.fire(); } else if ( e.getCode() == KeyCode.Q && !e.isAltDown() && !e.isControlDown() && !e.isMetaDown() && !e.isShiftDown() ) { enqueueMenuItem.fire(); } else if ( e.getCode() == KeyCode.Q && e.isShiftDown() && !e.isAltDown() && !e.isControlDown() && !e.isMetaDown() ) { playNextMenuItem.fire(); } else if ( e.getCode() == KeyCode.ENTER && !e.isAltDown() && !e.isControlDown() && !e.isMetaDown() && !e.isShiftDown() ) { playMenuItem.fire(); } else if ( e.getCode() == KeyCode.ENTER && e.isShiftDown() && !e.isAltDown() && !e.isControlDown() && !e.isMetaDown() ) { audioSystem.getCurrentList().insertPlaylists ( 0, playlistTable.getSelectionModel().getSelectedItems() ); } else if ( e.getCode() == KeyCode.ENTER && e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { appendMenuItem.fire(); } else if ( e.getCode() == KeyCode.DELETE && !e.isAltDown() && !e.isControlDown() && !e.isMetaDown() && !e.isShiftDown() ) { removeMenuItem.fire(); } else if ( e.getCode() == KeyCode.UP ) { if ( playlistTable.getSelectionModel().getSelectedIndex() == 0 ) { filterBox.requestFocus(); } } }); playlistTable.setOnDragOver( event -> { Dragboard db = event.getDragboard(); if ( db.hasFiles() ) { //REFACTOR: I can check for file extensions... event.acceptTransferModes( TransferMode.COPY ); event.consume(); } }); playlistTable.setOnDragDropped( event -> { Dragboard db = event.getDragboard(); if ( db.hasFiles() ) { ArrayList <Playlist> playlistsToAdd = new ArrayList <Playlist> (); for ( File file : db.getFiles() ) { Path droppedPath = Paths.get( file.getAbsolutePath() ); if ( Utils.isPlaylistFile ( droppedPath ) ) { Playlist playlist = Playlist.loadPlaylist( droppedPath ); if ( playlist != null ) { playlistsToAdd.add( playlist ); } } } for ( Playlist playlist : playlistsToAdd ) { library.addPlaylist( playlist ); } event.setDropCompleted( true ); event.consume(); } }); playlistTable.setRowFactory( tv -> { TableRow <Playlist> row = new TableRow <>(); row.itemProperty().addListener( (obs, oldValue, newValue ) -> { if ( newValue != null ) { row.setContextMenu( contextMenu ); } else { row.setContextMenu( null ); } }); row.setOnMouseClicked( event -> { if ( event.getClickCount() == 2 && !row.isEmpty() ) { boolean doOverwrite = ui.okToReplaceCurrentList(); if ( doOverwrite ) { audioSystem.getCurrentList().setAndPlayPlaylist( row.getItem() ); } } else if ( event.getButton() == MouseButton.SECONDARY ) { Playlist playlist = playlistTable.getSelectionModel().getSelectedItem(); if ( playlist != null ) { switch ( playlist.getShuffleMode() ) { case SEQUENTIAL: shuffleGroup.selectToggle( shuffleSequential ); break; case SHUFFLE: shuffleGroup.selectToggle( shuffleShuffle ); break; case USE_DEFAULT: shuffleGroup.selectToggle( shuffleNoChange ); break; default: break; } switch ( playlist.getRepeatMode() ) { case PLAY_ONCE: repeatGroup.selectToggle ( repeatPlayOnce ); break; case REPEAT: repeatGroup.selectToggle ( repeatRepeat ); break; case USE_DEFAULT: repeatGroup.selectToggle ( repeatNoChange ); break; default: break; } } } }); row.setOnDragDetected( event -> { if ( !row.isEmpty() ) { List <Playlist> selectedPlaylists = playlistTable.getSelectionModel().getSelectedItems(); List <Track> tracks = new ArrayList <Track> (); List <Playlist> serializableList = new ArrayList<Playlist> ( selectedPlaylists ); for ( Playlist playlist : selectedPlaylists ) { tracks.addAll ( playlist.getTracks() ); } DraggedTrackContainer dragObject = new DraggedTrackContainer( null, tracks, null, serializableList, null, DragSource.PLAYLIST_LIST ); Dragboard db = row.startDragAndDrop( TransferMode.COPY ); db.setDragView( row.snapshot( null, null ) ); ClipboardContent cc = new ClipboardContent(); cc.put( FXUI.DRAGGED_TRACKS, dragObject ); db.setContent( cc ); event.consume(); } }); row.setOnDragOver( event -> { Dragboard db = event.getDragboard(); if ( db.hasContent( FXUI.DRAGGED_TRACKS ) ) { if ( !row.isEmpty() ) { event.acceptTransferModes( TransferMode.COPY ); event.consume(); } } else if ( db.hasFiles() ) { //REFACTOR: I can check for file extensions... event.acceptTransferModes( TransferMode.COPY ); event.consume(); } }); row.setOnDragDropped( event -> { Dragboard db = event.getDragboard(); if ( db.hasContent( FXUI.DRAGGED_TRACKS ) ) { if ( !row.isEmpty() ) { DraggedTrackContainer container = (DraggedTrackContainer) db.getContent( FXUI.DRAGGED_TRACKS ); Playlist playlist = row.getItem(); ui.addToPlaylist( container.getTracks(), playlist ); playlistTable.refresh(); event.setDropCompleted( true ); event.consume(); } } else if ( db.hasFiles() ) { ArrayList <Playlist> playlistsToAdd = new ArrayList <Playlist> (); for ( File file : db.getFiles() ) { Path droppedPath = Paths.get( file.getAbsolutePath() ); if ( Utils.isPlaylistFile ( droppedPath ) ) { Playlist playlist = Playlist.loadPlaylist( droppedPath ); if ( playlist != null ) { playlistsToAdd.add( playlist ); } } } for ( Playlist playlist : playlistsToAdd ) { library.addPlaylist( playlist ); } event.setDropCompleted( true ); event.consume(); } }); return row; }); } public void applyDarkTheme ( ColorAdjust buttonColor ) { if ( filterClearImage != null ) filterClearImage.setEffect( buttonColor ); if ( addSourceImage != null ) addSourceImage.setEffect( buttonColor ); } public void applyLightTheme () { if ( filterClearImage != null ) filterClearImage.setEffect( ui.lightThemeButtonEffect ); if ( addSourceImage != null ) addSourceImage.setEffect( ui.lightThemeButtonEffect ); } @SuppressWarnings("incomplete-switch") public void applySettingsBeforeWindowShown ( EnumMap<Persister.Setting, String> settings ) { settings.forEach( ( setting, value )-> { try { switch ( setting ) { case PL_TABLE_PLAYLIST_COLUMN_SHOW: nameColumn.setVisible( Boolean.valueOf ( value ) ); settings.remove ( setting ); break; case PL_TABLE_TRACKS_COLUMN_SHOW: tracksColumn.setVisible( Boolean.valueOf ( value ) ); settings.remove ( setting ); break; case PL_TABLE_LENGTH_COLUMN_SHOW: lengthColumn.setVisible( Boolean.valueOf ( value ) ); settings.remove ( setting ); break; case PL_TABLE_PLAYLIST_COLUMN_WIDTH: nameColumn.setPrefWidth( Double.valueOf( value ) ); settings.remove ( setting ); break; case PL_TABLE_TRACKS_COLUMN_WIDTH: tracksColumn.setPrefWidth( Double.valueOf( value ) ); settings.remove ( setting ); break; case PL_TABLE_LENGTH_COLUMN_WIDTH: lengthColumn.setPrefWidth( Double.valueOf( value ) ); settings.remove ( setting ); break; case PLAYLIST_COLUMN_ORDER: { String[] order = value.split( " " ); int newIndex = 0; for ( String columnName : order ) { try { if ( columnName.equals( "name" ) ) { playlistTable.getColumns().remove( nameColumn ); playlistTable.getColumns().add( newIndex, nameColumn ); } else if ( columnName.equals( "tracks" ) ) { playlistTable.getColumns().remove( tracksColumn ); playlistTable.getColumns().add( newIndex, tracksColumn ); } else if ( columnName.equals( "length" ) ) { playlistTable.getColumns().remove( lengthColumn ); playlistTable.getColumns().add( newIndex, lengthColumn ); } newIndex++; } catch ( Exception e ) { LOGGER.log( Level.INFO, "Unable to set album table column order: '" + value + "'", e ); } } settings.remove ( setting ); break; } case PLAYLIST_SORT_ORDER: { playlistTable.getSortOrder().clear(); if ( !value.equals( "" ) ) { String[] order = value.split( " " ); for ( String fullValue : order ) { try { String columnName = fullValue.split( "-" )[0]; SortType sortType = SortType.valueOf( fullValue.split( "-" )[1] ); if ( columnName.equals( "name" ) ) { playlistTable.getSortOrder().add( nameColumn ); nameColumn.setSortType( sortType ); } else if ( columnName.equals( "tracks" ) ) { playlistTable.getSortOrder().add( tracksColumn ); tracksColumn.setSortType( sortType ); } else if ( columnName.equals( "length" ) ) { playlistTable.getSortOrder().add( lengthColumn ); lengthColumn.setSortType( sortType ); } } catch ( Exception e ) { LOGGER.log( Level.INFO, "Unable to set album table sort order: '" + value + "'", e ); } } } settings.remove ( setting ); break; } } } catch ( Exception e ) { LOGGER.log( Level.INFO, "Unable to apply setting: " + setting + " to UI.", e ); } }); } public EnumMap<Persister.Setting, ? extends Object> getSettings () { EnumMap <Persister.Setting, Object> retMe = new EnumMap <Persister.Setting, Object> ( Persister.Setting.class ); String playlistColumnOrderValue = ""; for ( TableColumn<Playlist, ?> column : playlistTable.getColumns() ) { if ( column == this.nameColumn ) { playlistColumnOrderValue += "name "; } else if ( column == this.tracksColumn ) { playlistColumnOrderValue += "tracks "; } else if ( column == this.lengthColumn ) { playlistColumnOrderValue += "length "; } } retMe.put ( Setting.PLAYLIST_COLUMN_ORDER, playlistColumnOrderValue ); String playlistSortValue = ""; for ( TableColumn<Playlist, ?> column : playlistTable.getSortOrder() ) { if ( column == this.nameColumn ) { playlistSortValue += "name-" + nameColumn.getSortType() + " "; } else if ( column == this.tracksColumn ) { playlistSortValue += "tracks-" + tracksColumn.getSortType() + " "; } else if ( column == this.lengthColumn ) { playlistSortValue += "length-" + lengthColumn.getSortType() + " "; } } retMe.put ( Setting.PLAYLIST_SORT_ORDER, playlistSortValue ); retMe.put ( Setting.PL_TABLE_PLAYLIST_COLUMN_SHOW, nameColumn.isVisible() ); retMe.put ( Setting.PL_TABLE_TRACKS_COLUMN_SHOW, tracksColumn.isVisible() ); retMe.put ( Setting.PL_TABLE_LENGTH_COLUMN_SHOW, lengthColumn.isVisible() ); retMe.put ( Setting.PL_TABLE_PLAYLIST_COLUMN_WIDTH, nameColumn.getPrefWidth() ); retMe.put ( Setting.PL_TABLE_TRACKS_COLUMN_WIDTH, tracksColumn.getPrefWidth() ); retMe.put ( Setting.PL_TABLE_LENGTH_COLUMN_WIDTH, lengthColumn.getPrefWidth() ); return retMe; } public void focusFilter() { playlistTable.requestFocus(); filterBox.requestFocus(); playlistTable.getSelectionModel().clearSelection(); } }
32,870
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
ThrottledTrackFilter.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/fxui/ThrottledTrackFilter.java
package net.joshuad.hypnos.fxui; import java.text.Normalizer; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Platform; import javafx.collections.transformation.FilteredList; import net.joshuad.hypnos.library.Track; public class ThrottledTrackFilter { private static final Logger LOGGER = Logger.getLogger(ThrottledTrackFilter.class.getName()); private String requestedFilter = ""; private boolean requestedHideAlbumTracks = false; private long timeRequestMadeMS = 0; private Thread filterThread; private boolean interruptFiltering = false; private String currentAppliedFilter = ""; private boolean currentAppliedHideAlbumTracks = false; private FilteredList <? extends Track> filteredList; public ThrottledTrackFilter ( FilteredList <? extends Track> filteredList ) { this.filteredList = filteredList; filterThread = new Thread ( () -> { while ( true ) { String filter = requestedFilter; boolean hide = requestedHideAlbumTracks; if ( !filter.equals( currentAppliedFilter ) || hide != currentAppliedHideAlbumTracks ) { if ( System.currentTimeMillis() >= timeRequestMadeMS + 100 ) { interruptFiltering = false; Platform.runLater(()->setPredicate( filter, hide )); currentAppliedFilter = filter; currentAppliedHideAlbumTracks = hide; } } try { Thread.sleep( 25 ); } catch ( InterruptedException e ) {} } }); filterThread.setName( "Throttled Track Filter" ); filterThread.setDaemon( true ); filterThread.start(); } public void setFilter ( String filter, boolean hideAlbumTracks ) { if ( filter == null ) filter = ""; timeRequestMadeMS = System.currentTimeMillis(); this.requestedFilter = filter; this.requestedHideAlbumTracks = hideAlbumTracks; interruptFiltering = true; } private void setPredicate ( String filterText, boolean hideAlbumTracks ) { try { filteredList.setPredicate( ( Track track ) -> { try { if ( track.getAlbum() != null && hideAlbumTracks ) return false; if ( interruptFiltering ) return true; if ( filterText.isEmpty() ) return true; ArrayList <String> matchableText = new ArrayList <String>(); matchableText.add( track.getArtist().toLowerCase() ); matchableText.add( track.getTitle().toLowerCase() ); matchableText.add( track.getFullAlbumTitle().toLowerCase() ); if ( track.getArtist().matches( ".*[^\\p{ASCII}]+.*" ) ) { matchableText.add( Normalizer.normalize( track.getArtist(), Normalizer.Form.NFD ) .replaceAll( "[^\\p{ASCII}]", "" ).toLowerCase() ); } if ( track.getTitle().matches( ".*[^\\p{ASCII}]+.*" ) ) { matchableText.add( Normalizer.normalize( track.getTitle(), Normalizer.Form.NFD ) .replaceAll( "[^\\p{ASCII}]", "" ).toLowerCase() ); } if ( track.getFullAlbumTitle().matches( ".*[^\\p{ASCII}]+.*" ) ) { matchableText.add( Normalizer.normalize( track.getFullAlbumTitle(), Normalizer.Form.NFD ) .replaceAll( "[^\\p{ASCII}]", "" ).toLowerCase() ); } String[] lowerCaseFilterTokens = filterText.toLowerCase().split( "\\s+" ); for ( String token : lowerCaseFilterTokens ) { boolean tokenMatches = false; for ( String test : matchableText ) { if ( test.contains( token ) ) { tokenMatches = true; } } if ( !tokenMatches ) { return false; } } }catch(ArrayIndexOutOfBoundsException ae) { //This happens if you filter a list while scanning, and then clear the filter. //It doesn't seem to matter at all, so I'm just ignoring it for now. }catch(Exception e) { LOGGER.log(Level.INFO, "Exception caught, ignored.", e); } return true; }); } catch ( Exception e ) { LOGGER.log(Level.INFO, "Caught Exception: " + e ); } } }
3,966
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
StretchedTabPane.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/fxui/StretchedTabPane.java
package net.joshuad.hypnos.fxui; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.ListChangeListener; import javafx.geometry.Side; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; /* Copyright "Cameron Tauxe": http://stackoverflow.com/questions/31051756/javafx-tab-fit-full-size-of-header */ public class StretchedTabPane extends TabPane { public StretchedTabPane() { super(); setUpChangeListeners(); } public StretchedTabPane(Tab... tabs) { super(tabs); setUpChangeListeners(); } public void fixTabs () { Side side = getSide(); int numTabs = getTabs().size(); if (numTabs != 0) { if (side == Side.LEFT|| side == Side.RIGHT) { setTabMinWidth(heightProperty().intValue() / numTabs - (20)); setTabMaxWidth(heightProperty().intValue() / numTabs - (20)); } if (side == Side.BOTTOM || side == Side.TOP) { setTabMinWidth(widthProperty().intValue() / numTabs - (20)); setTabMaxWidth(widthProperty().intValue() / numTabs - (20)); } } } private void setUpChangeListeners() { widthProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue<? extends Number> value, Number oldWidth, Number newWidth) { Side side = getSide(); int numTabs = getTabs().size(); if ((side == Side.BOTTOM || side == Side.TOP) && numTabs != 0) { setTabMinWidth(newWidth.intValue() / numTabs - (23)); setTabMaxWidth(newWidth.intValue() / numTabs - (23)); } } }); heightProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue<? extends Number> value, Number oldHeight, Number newHeight) { Side side = getSide(); int numTabs = getTabs().size(); if ((side == Side.LEFT || side == Side.RIGHT) && numTabs != 0) { setTabMinWidth(newHeight.intValue() / numTabs - (23)); setTabMaxWidth(newHeight.intValue() / numTabs - (23)); } } }); getTabs().addListener(new ListChangeListener<Tab>() { public void onChanged(ListChangeListener.Change<? extends Tab> change){ Side side = getSide(); int numTabs = getTabs().size(); if (numTabs != 0) { if (side == Side.LEFT|| side == Side.RIGHT) { setTabMinWidth(heightProperty().intValue() / numTabs - (20)); setTabMaxWidth(heightProperty().intValue() / numTabs - (20)); } if (side == Side.BOTTOM || side == Side.TOP) { setTabMinWidth(widthProperty().intValue() / numTabs - (20)); setTabMaxWidth(widthProperty().intValue() / numTabs - (20)); } } } }); } }
3,139
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
LyricsWindow.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/fxui/LyricsWindow.java
package net.joshuad.hypnos.fxui; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Hyperlink; import javafx.scene.control.Label; import javafx.scene.control.TextArea; import javafx.scene.control.Tooltip; import javafx.scene.image.Image; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.Priority; import javafx.scene.layout.Region; import javafx.scene.layout.VBox; import javafx.scene.text.TextAlignment; import javafx.stage.Modality; import javafx.stage.Stage; import net.joshuad.hypnos.Hypnos; import net.joshuad.hypnos.HypnosURLS; import net.joshuad.hypnos.library.Track; import net.joshuad.hypnos.lyrics.Lyrics; import net.joshuad.hypnos.lyrics.LyricsFetcher; public class LyricsWindow extends Stage { private static final Logger LOGGER = Logger.getLogger( LyricsWindow.class.getName() ); private LyricsFetcher lyricsParser = new LyricsFetcher(); private TextArea lyricsArea = new TextArea(); private Label headerLabel = new Label ( "" ); private Hyperlink sourceHyperlink = new Hyperlink ( "" ); private Tooltip sourceTooltip = new Tooltip ( "" ); private Label sourceLabel = new Label ( "Source:" ); private String sourceURL = null; private Button searchWebButton = new Button( "Search on Web" ); private Track track; public LyricsWindow ( FXUI ui ) { super(); initModality( Modality.NONE ); initOwner( ui.getMainStage() ); setTitle( "Lyrics" ); setWidth( 600 ); setHeight( 700 ); Pane root = new Pane(); Scene scene = new Scene( root ); VBox lyricsPane = new VBox(); lyricsPane.setAlignment( Pos.CENTER ); lyricsPane.setPadding( new Insets ( 10 ) ); headerLabel.setPadding( new Insets ( 0, 0, 10, 0 ) ); headerLabel.setWrapText( true ); headerLabel.setTextAlignment( TextAlignment.CENTER ); headerLabel.setStyle( "-fx-font-size: 16px; -fx-font-weight: bold" ); lyricsPane.getChildren().add( headerLabel ); lyricsArea.setEditable( false ); lyricsArea.setWrapText( true ); lyricsArea.getStyleClass().add( "lyricsTextArea" ); lyricsArea.setStyle("-fx-focus-color: transparent; -fx-faint-focus-color: transparent"); lyricsArea.getStyleClass().add( "lyrics" ); lyricsPane.getChildren().add( lyricsArea ); sourceHyperlink.setVisited( true ); sourceHyperlink.setTooltip( sourceTooltip ); sourceHyperlink.setVisible( false ); sourceHyperlink.setOnAction( ( ActionEvent e ) -> { if ( sourceURL != null && !sourceURL.isEmpty() ) { ui.openWebBrowser( sourceURL ); } }); try { getIcons().add( new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( "resources" + File.separator + "icon.png" ).toFile() ) ) ); } catch ( FileNotFoundException e ) { LOGGER.log( Level.WARNING, "Unable to load program icon: resources/icon.png", e ); } searchWebButton.setOnAction( ( ActionEvent e ) -> { String searchSlug = null; if ( track != null ) { searchSlug = "lyrics " + track.getAlbumArtist() + " " + track.getTitle(); ui.openWebBrowser(HypnosURLS.getDDGSearchURL(searchSlug)); } }); sourceLabel.setVisible( false ); Region spring = new Region(); HBox.setHgrow(spring, Priority.ALWAYS); HBox sourceBox = new HBox(); sourceBox.getChildren().addAll ( sourceLabel, sourceHyperlink, spring, searchWebButton ); sourceBox.setAlignment( Pos.CENTER ); lyricsPane.getChildren().add( sourceBox ); lyricsArea.prefHeightProperty().bind( lyricsPane.heightProperty().subtract( headerLabel.heightProperty() ) ); lyricsArea.prefWidthProperty().bind( lyricsPane.widthProperty() ); lyricsPane.prefWidthProperty().bind( root.widthProperty() ); lyricsPane.prefHeightProperty().bind( root.heightProperty() ); root.getChildren().add( lyricsPane ); setScene( scene ); scene.addEventFilter( KeyEvent.KEY_PRESSED, new EventHandler <KeyEvent>() { @Override public void handle ( KeyEvent e ) { if ( e.getCode() == KeyCode.ESCAPE && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() && !e.isAltDown() ) { hide(); e.consume(); } } }); } public void setTrack ( Track track ) { this.track = track; if ( track == null ) { return; } headerLabel.setText( track.getArtist() + " - " + track.getTitle() ); lyricsArea.setText( "loading..." ); sourceHyperlink.setVisible( false ); sourceLabel.setVisible( false ); Thread lyricThread = new Thread () { public void run() { Lyrics lyrics = lyricsParser.get( track ); Platform.runLater( () -> { if ( !lyrics.hadScrapeError() ) { lyricsArea.setText( lyrics.getLyrics() ); sourceHyperlink.setText( lyrics.getSite().getName() ); sourceURL = lyrics.getSourceURL(); sourceTooltip.setText( lyrics.getSourceURL() ); sourceHyperlink.setVisible( true ); sourceLabel.setVisible( true ); } else { lyricsArea.setText( "Unable to load lyrics for this song." ); sourceURL = ""; } }); } }; lyricThread.setDaemon( true ); lyricThread.setName( "Lyric Fetcher" ); lyricThread.start(); } }
5,497
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
Transport.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/fxui/Transport.java
package net.joshuad.hypnos.fxui; import java.io.FileInputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.ListChangeListener; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.control.ContentDisplay; import javafx.scene.control.ContextMenu; import javafx.scene.control.Hyperlink; import javafx.scene.control.Label; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.scene.control.Slider; import javafx.scene.control.Tooltip; import javafx.scene.effect.ColorAdjust; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.ClipboardContent; import javafx.scene.input.Dragboard; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.input.ScrollEvent; import javafx.scene.input.TransferMode; import javafx.scene.layout.Border; import javafx.scene.layout.BorderPane; import javafx.scene.layout.BorderStroke; import javafx.scene.layout.BorderStrokeStyle; import javafx.scene.layout.BorderWidths; import javafx.scene.layout.CornerRadii; import javafx.scene.layout.HBox; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.text.TextAlignment; import net.joshuad.hypnos.CurrentListTrack; import net.joshuad.hypnos.Hypnos; import net.joshuad.hypnos.Utils; import net.joshuad.hypnos.audio.AudioSystem; import net.joshuad.hypnos.audio.AudioSystem.StopReason; import net.joshuad.hypnos.fxui.DraggedTrackContainer.DragSource; import net.joshuad.hypnos.lastfm.LastFM.LovedState; import net.joshuad.hypnos.library.Playlist; import net.joshuad.hypnos.library.Track; public class Transport extends VBox { private static final Logger LOGGER = Logger.getLogger( Transport.class.getName() ); ImageView playImage, pauseImage, stopImage, nextImage, previousImage, loveImage; Image playImageSource, pauseImageSource; ImageView settingsImage; ImageView[] volumeImages = new ImageView[ 4 ]; Button togglePlayButton, previousButton, nextButton, stopButton, loveButton; Button showSettingsButton; Hyperlink updateAvailableButton; Label timeElapsedLabel = new Label( "" ); Label timeRemainingLabel = new Label( "" ); Button currentTrackButton; Tooltip currentTrackTooltip; Slider trackPositionSlider; Slider volumeSlider; Button volumeMuteButton; boolean sliderMouseHeld; HBox volumePane; ColorAdjust lightThemeButtonEffect = new ColorAdjust(); { lightThemeButtonEffect.setBrightness( -.75d ); lightThemeButtonEffect.setHue( 0 ); lightThemeButtonEffect.setSaturation( 0 ); } ColorAdjust lightThemeButtonsHover = new ColorAdjust(); { lightThemeButtonsHover.setBrightness( -.5d ); lightThemeButtonsHover.setSaturation( .7d ); lightThemeButtonsHover.setHue( -.875d ); } ColorAdjust darkThemeButtonEffect = new ColorAdjust(); { darkThemeButtonEffect.setBrightness( -.4d ); darkThemeButtonEffect.setHue( 0 ); darkThemeButtonEffect.setSaturation( 0 ); } ColorAdjust darkThemeButtonsHover = new ColorAdjust(); { darkThemeButtonsHover.setBrightness( -.2d ); darkThemeButtonsHover.setSaturation( .4d ); darkThemeButtonsHover.setHue( -.75d ); } ColorAdjust darkThemeLovedEffect = new ColorAdjust(); { darkThemeLovedEffect.setBrightness( -.4d ); darkThemeLovedEffect.setHue( .15d ); darkThemeLovedEffect.setSaturation( .75d ); } ColorAdjust darkThemeNotLovedEffect = new ColorAdjust(); { darkThemeNotLovedEffect.setBrightness( -.4d ); darkThemeNotLovedEffect.setHue( 0 ); darkThemeNotLovedEffect.setSaturation( 0 ); } ColorAdjust lightThemeLovedEffect = new ColorAdjust(); { lightThemeLovedEffect.setBrightness( -.1d ); lightThemeLovedEffect.setHue( .0d ); lightThemeLovedEffect.setSaturation( .6d ); } ColorAdjust lightThemeNotLovedEffect = new ColorAdjust(); { lightThemeNotLovedEffect.setBrightness( -.3d ); lightThemeNotLovedEffect.setHue( -0d ); lightThemeNotLovedEffect.setSaturation( .0d ); } Border loveBorder = new Border ( new BorderStroke ( Color.TRANSPARENT, BorderStrokeStyle.NONE, new CornerRadii ( 5 ), BorderWidths.DEFAULT )); Border loveBorderHover = new Border ( new BorderStroke ( Color.GREY, BorderStrokeStyle.DOTTED, new CornerRadii ( 5 ), BorderWidths.DEFAULT )); FXUI ui; AudioSystem audioSystem; public Transport( FXUI ui, AudioSystem audioSystem ) { this.ui = ui; this.audioSystem = audioSystem; loadImages(); togglePlayButton = new Button ( "" ); togglePlayButton.setGraphic( playImage ); togglePlayButton.setPrefSize( 42, 35 ); togglePlayButton.setMinSize( 42, 35 ); togglePlayButton.setMaxSize( 42, 35 ); togglePlayButton.setTooltip( new Tooltip( "Toggle Play/Pause" ) ); previousButton = new Button ( "" ); previousButton.setGraphic( previousImage ); previousButton.setPrefSize( 42, 35 ); previousButton.setMinSize( 42, 35 ); previousButton.setMaxSize( 42, 35 ); previousButton.setTooltip( new Tooltip( "Previous Track" ) ); nextButton = new Button ( "" ); nextButton.setGraphic( nextImage ); nextButton.setPrefSize( 42, 35 ); nextButton.setMinSize( 42, 35 ); nextButton.setMaxSize( 42, 35 ); nextButton.setTooltip( new Tooltip( "Next Track" ) ); stopButton = new Button ( "" ); stopButton.setGraphic( stopImage ); stopButton.setPrefSize( 42, 35 ); stopButton.setMinSize( 42, 35 ); stopButton.setMaxSize( 42, 35 ); stopButton.setTooltip( new Tooltip( "Stop" ) ); previousButton.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent e ) { ui.previousRequested(); } } ); nextButton.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent e ) { audioSystem.next(); } }); stopButton.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent e ) { audioSystem.stop( StopReason.USER_REQUESTED ); } } ); togglePlayButton.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent e ) { if ( audioSystem.isStopped() ) { if ( ui.getCurrentListPane().currentListTable.getItems().size() != 0 ) { CurrentListTrack selectedItem = ui.getCurrentListPane().currentListTable.getSelectionModel().getSelectedItem(); if ( selectedItem != null ) { audioSystem.playTrack( selectedItem ); } else { audioSystem.next( false ); } } } else { audioSystem.togglePause(); } } } ); loveButton = new Button( ); loveButton.setTooltip( new Tooltip( "Love on LastFM" ) ); loveButton.setVisible( false ); loveButton.setManaged( false ); loveButton.getStyleClass().add( "loveButton" ); loveButton.setPadding( new Insets ( 0, 10, 0, 10 ) ); loveButton.visibleProperty().bindBidirectional( ui.showLastFMWidgets ); loveButton.setBorder( loveBorder ); ui.showLastFMWidgets.addListener( ( observable, oldValue, newValue ) -> { loveButton.setManaged( newValue ); if ( audioSystem.isStopped() ) loveButton.setGraphic( null ); else loveButton.setGraphic( loveImage ); updateLovedIndicator( false ); }); loveButton.setOnAction( ( ActionEvent e ) -> { boolean currentlyLoved = false; if ( loveImage.getEffect() == darkThemeLovedEffect || loveImage.getEffect() == lightThemeLovedEffect ) { currentlyLoved = true; } if ( currentlyLoved ) { loveImage.setEffect ( ui.isDarkTheme() ? darkThemeNotLovedEffect : lightThemeNotLovedEffect ); } else { loveImage.setEffect ( ui.isDarkTheme() ? darkThemeLovedEffect : lightThemeLovedEffect ); } Thread taskThread = new Thread (() -> { audioSystem.getLastFM().toggleLoveTrack( audioSystem.getCurrentTrack() ); Platform.runLater( () -> updateLovedIndicator( false ) ); }); taskThread.setDaemon( true ); taskThread.start(); }); loveButton.hoverProperty().addListener( ( observable, oldValue, newValue ) -> { loveButton.setBorder( newValue ? loveBorderHover : loveBorder ); }); timeElapsedLabel = new Label( "" ); timeRemainingLabel = new Label( "" ); timeElapsedLabel.setMinWidth( 65 ); timeElapsedLabel.setContentDisplay( ContentDisplay.RIGHT ); timeElapsedLabel.setTextAlignment( TextAlignment.RIGHT ); timeElapsedLabel.setAlignment( Pos.CENTER_RIGHT ); timeElapsedLabel.setTooltip( new Tooltip ( "Time Elapsed" ) ); timeRemainingLabel.setMinWidth( 65 ); timeRemainingLabel.setTooltip( new Tooltip ( "Time Remaining" ) ); trackPositionSlider = new Slider(); trackPositionSlider.setMin( 0 ); trackPositionSlider.setMax( 1000 ); trackPositionSlider.setValue( 0 ); trackPositionSlider.setMaxWidth( 600 ); trackPositionSlider.setMinWidth( 200 ); trackPositionSlider.setPrefWidth( 400 ); trackPositionSlider.setStyle( "-fx-font-size: 18px" ); trackPositionSlider.setTooltip( new Tooltip ( "Change Track Position" ) ); trackPositionSlider.valueChangingProperty().addListener( new ChangeListener <Boolean>() { public void changed ( ObservableValue <? extends Boolean> obs, Boolean wasChanging, Boolean isNowChanging ) { if ( !isNowChanging ) { audioSystem.seekPercent( trackPositionSlider.getValue() / trackPositionSlider.getMax() ); } } }); trackPositionSlider.setOnMousePressed( ( MouseEvent e ) -> { sliderMouseHeld = true; }); trackPositionSlider.setOnMouseReleased( ( MouseEvent e ) -> { sliderMouseHeld = false; audioSystem.seekPercent( trackPositionSlider.getValue() / trackPositionSlider.getMax() ); }); volumeMuteButton = new Button ( ); volumeMuteButton.setGraphic( volumeImages[3] ); volumeMuteButton.getStyleClass().add( "volumeLabel" ); volumeMuteButton.setPadding( new Insets ( 0, 5, 0, 5 ) ); volumeMuteButton.getStyleClass().add( "volumeButton" ); volumeMuteButton.setTooltip( new Tooltip ( "Toggle Mute" ) ); volumeMuteButton.setOnAction( e -> audioSystem.toggleMute() ); volumeMuteButton.hoverProperty().addListener( ( obserable, oldValue, newValue ) -> { for ( ImageView volumeImage : volumeImages ) { applyHover ( volumeImage, newValue ); } }); volumeSlider = new Slider(); volumeSlider.setMin( 0 ); volumeSlider.setMax( 100 ); volumeSlider.setValue( 100 ); volumeSlider.setPrefWidth( 130 ); volumeSlider.setMinWidth( 80 ); volumeSlider.setTooltip( new Tooltip ( "Control Volume" ) ); volumeSlider.setPadding( new Insets ( 0, 10, 0, 0 ) ); EventHandler<MouseEvent> volumeSliderHandler = new EventHandler<MouseEvent> () { @Override public void handle ( MouseEvent event ) { double min = volumeSlider.getMin(); double max = volumeSlider.getMax(); double percent = (volumeSlider.getValue() - min) / (max - min); audioSystem.setVolumePercent( percent ); //Note: this works because min is 0 } }; EventHandler<ScrollEvent> volumeSliderScrollHandler = new EventHandler<ScrollEvent> () { @Override public void handle ( ScrollEvent event ) { if ( event.getDeltaY() < 0 ) { audioSystem.decrementVolume(); } else if ( event.getDeltaY() > 0 ) { audioSystem.incrementVolume(); } } }; volumeMuteButton.setOnScroll ( volumeSliderScrollHandler ); volumeSlider.setOnMouseDragged ( volumeSliderHandler ); volumeSlider.setOnMouseClicked ( volumeSliderHandler ); volumeSlider.setOnScroll( volumeSliderScrollHandler ); volumePane = new HBox(); volumePane.getChildren().addAll( volumeMuteButton, volumeSlider ); volumePane.setAlignment( Pos.CENTER ); volumePane.setSpacing( 5 ); HBox positionSliderPane = new HBox(); positionSliderPane.getChildren().addAll( timeElapsedLabel, trackPositionSlider, timeRemainingLabel ); positionSliderPane.setAlignment( Pos.CENTER ); positionSliderPane.setSpacing( 5 ); HBox trackControls = new HBox(); trackControls.getChildren().addAll( previousButton, togglePlayButton, stopButton, nextButton ); trackControls.setPadding( new Insets( 5 ) ); trackControls.setSpacing( 5 ); HBox controls = new HBox(); controls.getChildren().addAll( trackControls, positionSliderPane, volumePane ); controls.setSpacing( 10 ); controls.setAlignment( Pos.CENTER ); showSettingsButton = new Button ( ); showSettingsButton.setGraphic( settingsImage ); showSettingsButton.getStyleClass().add( "settingsButton" ); showSettingsButton.setTooltip( new Tooltip( "Configuration and Information" ) ); showSettingsButton.setOnAction ( e -> { if ( ui.settingsWindow.isShowing() ) { ui.settingsWindow.hide(); } else { ui.settingsWindow.show(); } } ); showSettingsButton.hoverProperty().addListener( ( obserable, oldValue, newValue ) -> { applyHover ( settingsImage, newValue ); }); updateAvailableButton = new Hyperlink ( "!" ); updateAvailableButton.getStyleClass().add( "updateButton" ); updateAvailableButton.setTooltip( new Tooltip( "An Update is Available!" ) ); updateAvailableButton.setOnAction ( event -> ui.openWebBrowser( "http://hypnosplayer.org" ) ); //switch ( Hypnos.getOS() ) { // case WIN_10: case WIN_7: case WIN_8: case WIN_UNKNOWN: case WIN_VISTA: case WIN_XP: showSettingsButton.setPadding( new Insets ( 7, 5, 0, 5 ) ); updateAvailableButton.setPadding( new Insets ( 7, 5, 5, 0 ) ); // break; // case NIX: case OSX: case UNKNOWN: // showSettingsButton.setPadding( new Insets ( 0, 5, 0, 5 ) ); // updateAvailableButton.setPadding( new Insets ( 5, 5, 5, 0 ) ); // break; //} //Make it not take up space when it is not visible. updateAvailableButton.managedProperty().bind( updateAvailableButton.visibleProperty() ); updateAvailableButton.visibleProperty().bind( ui.updateAvailableProperty().and( ui.showUpdateAvailableInUIProperty() ) ); HBox settingsBox = new HBox(); settingsBox.getChildren().addAll( showSettingsButton, updateAvailableButton ); Label settingsWidthPadding = new Label ( "" ); //settingsWidthPadding.prefWidthProperty().bind( settingsBox.widthProperty() ); BorderPane playingTrackInfo = new BorderPane(); currentTrackButton = new Button( "" ); currentTrackButton.setPadding( new Insets ( 10, 0, 0, 0 ) ); currentTrackButton.getStyleClass().add( "trackName" ); HBox currentTrackBox = new HBox(); currentTrackBox.setAlignment( Pos.BOTTOM_CENTER ); currentTrackBox.getChildren().addAll( currentTrackButton, loveButton ); playingTrackInfo.setCenter( currentTrackBox ); playingTrackInfo.setRight( settingsBox ); playingTrackInfo.setLeft( settingsWidthPadding ); settingsWidthPadding.minWidthProperty().bind( settingsBox.widthProperty() ); currentTrackButton.setOnMouseClicked( ( MouseEvent event ) -> { if ( event.getButton() == MouseButton.PRIMARY && event.isControlDown() ) { ui.goToAlbumOfTrack(audioSystem.getCurrentTrack()); } else if ( event.getButton() == MouseButton.PRIMARY && event.isAltDown() ) { ui.goToArtistOfTrack(audioSystem.getCurrentTrack()); } else if ( event.getButton() == MouseButton.PRIMARY ) { ui.selectCurrentTrack(); } }); currentTrackTooltip = new Tooltip ( "" ); currentTrackButton.setTooltip( currentTrackTooltip ); currentTrackButton.setOnDragDetected( event -> { if ( audioSystem.getCurrentTrack() != null ) { ArrayList <Track> tracks = new ArrayList<> ( Arrays.asList( audioSystem.getCurrentTrack() ) ); DraggedTrackContainer dragObject = new DraggedTrackContainer( null, tracks, null, null, null, DragSource.CURRENT_TRACK ); Dragboard db = currentTrackButton.startDragAndDrop( TransferMode.COPY ); db.setDragView( currentTrackButton.snapshot( null, null ) ); ClipboardContent cc = new ClipboardContent(); cc.put( FXUI.DRAGGED_TRACKS, dragObject ); db.setContent( cc ); event.consume(); } }); MenuItem playMenuItem = new MenuItem( "Play" ); MenuItem appendMenuItem = new MenuItem( "Append" ); MenuItem playNextMenuItem = new MenuItem( "Play Next" ); MenuItem enqueueMenuItem = new MenuItem( "Enqueue" ); MenuItem editTagMenuItem = new MenuItem( "Edit Tag(s)" ); MenuItem infoMenuItem = new MenuItem( "Info" ); MenuItem lyricsMenuItem = new MenuItem( "Lyrics" ); MenuItem goToAlbumMenuItem = new MenuItem( "Go to Album" ); MenuItem browseMenuItem = new MenuItem( "Browse Folder" ); Menu addToPlaylistMenuItem = new Menu( "Add to Playlist" ); MenuItem newPlaylistButton = new MenuItem( "<New>" ); addToPlaylistMenuItem.getItems().add( newPlaylistButton ); newPlaylistButton.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent e ) { Track current = audioSystem.getCurrentTrack(); if ( current != null ) { ui.promptAndSavePlaylist ( Arrays.asList( current ) ); } } }); EventHandler<ActionEvent> addToPlaylistHandler = new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { Playlist playlist = (Playlist) ((MenuItem) event.getSource()).getUserData(); Track currentTrack = audioSystem.getCurrentTrack(); if ( currentTrack != null && playlist != null ) { ui.addToPlaylist ( Arrays.asList( currentTrack ), playlist ); } } }; ui.library.getPlaylistsSorted().addListener( ( ListChangeListener.Change <? extends Playlist> change ) -> { ui.updatePlaylistMenuItems( addToPlaylistMenuItem.getItems(), addToPlaylistHandler ); } ); ui.updatePlaylistMenuItems( addToPlaylistMenuItem.getItems(), addToPlaylistHandler ); playMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { Track currentTrack = audioSystem.getCurrentTrack(); if ( currentTrack != null ) { audioSystem.playTrack( currentTrack ); } } }); appendMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { Track currentTrack = audioSystem.getCurrentTrack(); if ( currentTrack != null ) { audioSystem.getCurrentList().appendTrack ( currentTrack ); } } }); playNextMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { Track currentTrack = audioSystem.getCurrentTrack(); if ( currentTrack != null ) { audioSystem.getQueue().queueTrack( 0, currentTrack ); } } }); enqueueMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { Track currentTrack = audioSystem.getCurrentTrack(); if ( currentTrack != null ) { audioSystem.getQueue().queueTrack( currentTrack ); } } }); editTagMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { Track currentTrack = audioSystem.getCurrentTrack(); if ( currentTrack != null ) { ui.tagWindow.setTracks( Arrays.asList( currentTrack ), null ); ui.tagWindow.show(); } } }); infoMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { Track currentTrack = audioSystem.getCurrentTrack(); if ( currentTrack != null ) { ui.trackInfoWindow.setTrack( currentTrack ); ui.trackInfoWindow.show(); } } }); lyricsMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { ui.lyricsWindow.setTrack( audioSystem.getCurrentTrack() ); ui.lyricsWindow.show(); } }); goToAlbumMenuItem.setOnAction( ( event ) -> { ui.goToAlbumOfTrack ( audioSystem.getCurrentTrack() ); }); browseMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { ui.openFileBrowser( audioSystem.getCurrentTrack().getPath() ); } }); Menu lastFMMenu = new Menu( "LastFM" ); MenuItem loveMenuItem = new MenuItem ( "Love" ); MenuItem unloveMenuItem = new MenuItem ( "Unlove" ); MenuItem scrobbleMenuItem = new MenuItem ( "Scrobble" ); lastFMMenu.getItems().addAll ( loveMenuItem, unloveMenuItem, scrobbleMenuItem ); lastFMMenu.setVisible ( false ); lastFMMenu.visibleProperty().bind( ui.showLastFMWidgets ); loveMenuItem.setOnAction( ( event ) -> { ui.audioSystem.getLastFM().loveTrack( ui.audioSystem.getCurrentTrack() ); }); unloveMenuItem.setOnAction( ( event ) -> { ui.audioSystem.getLastFM().unloveTrack( ui.audioSystem.getCurrentTrack() ); }); scrobbleMenuItem.setOnAction( ( event ) -> { ui.audioSystem.getLastFM().scrobbleTrack( ui.audioSystem.getCurrentTrack() ); }); ContextMenu currentTrackButtonMenu = new ContextMenu(); currentTrackButtonMenu.getItems().addAll( playMenuItem, appendMenuItem, playNextMenuItem, enqueueMenuItem, editTagMenuItem, infoMenuItem, lyricsMenuItem, goToAlbumMenuItem, browseMenuItem, addToPlaylistMenuItem, lastFMMenu ); currentTrackButton.setContextMenu( currentTrackButtonMenu ); getChildren().add( playingTrackInfo ); getChildren().add( controls ); setPadding( new Insets( 0, 0, 10, 0 ) ); setSpacing( 5 ); setId( "transport" ); } private void updateLovedIndicator( boolean fromCache ) { LovedState loved = audioSystem.getLastFM().isLoved( audioSystem.getCurrentTrack(), fromCache ); if ( loved == LovedState.TRUE ) { loveImage.setEffect ( ui.isDarkTheme() ? darkThemeLovedEffect : lightThemeLovedEffect ); } else { loveImage.setEffect ( ui.isDarkTheme() ? darkThemeNotLovedEffect : lightThemeNotLovedEffect ); } } private void applyHover ( ImageView image, Boolean hasHover ) { if ( hasHover ) { image.setEffect ( ui.isDarkTheme() ? darkThemeButtonsHover : lightThemeButtonsHover ); } else { image.setEffect ( ui.isDarkTheme() ? darkThemeButtonEffect : lightThemeButtonEffect ); } } private void loadImages() { double volFitWidth = 55 * .52; double volFitHeight = 45 * .52; try { volumeImages[0] = new ImageView ( new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( "resources/vol-0.png" ).toFile() ) ) ); volumeImages[0].setFitWidth( volFitWidth ); volumeImages[0].setFitHeight( volFitHeight ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to load play icon: resources/vol-0.png", e ); } try { volumeImages[1] = new ImageView ( new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( "resources/vol-1.png" ).toFile() ) ) ); volumeImages[1].setFitWidth( volFitWidth ); volumeImages[1].setFitHeight( volFitHeight ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to load play icon: resources/vol-1.png", e ); } try { volumeImages[2] = new ImageView ( new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( "resources/vol-2.png" ).toFile() ) ) ); volumeImages[2].setFitWidth( volFitWidth ); volumeImages[2].setFitHeight( volFitHeight ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to load play icon: resources/vol-2.png", e ); } try { volumeImages[3] = new ImageView ( new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( "resources/vol-3.png" ).toFile() ) ) ); volumeImages[3].setFitWidth( volFitWidth ); volumeImages[3].setFitHeight( volFitHeight ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to load play icon: resources/vol-3.png", e ); } try { settingsImage = new ImageView ( new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( "resources/config.png" ).toFile() ) ) ); settingsImage.setFitWidth( 24 ); settingsImage.setFitHeight( 24 ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to load play icon: resources/config.png", e ); } playImage = null; try { playImageSource = new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( "resources/play.png" ).toFile() ) ); playImage = new ImageView ( playImageSource ); playImage.setFitHeight( 18 ); playImage.setFitWidth( 18 ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to load play icon: resources/play.png", e ); } pauseImage = null; try { pauseImageSource = new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( "resources/pause.png" ).toFile() ) ); pauseImage = new ImageView ( pauseImageSource ); pauseImage.setFitHeight( 18 ); pauseImage.setFitWidth( 18 ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to load pause icon: resources/pause.png", e ); } previousImage = null; try { previousImage = new ImageView ( new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( "resources/previous.png" ).toFile() ) ) ); previousImage.setFitHeight( 18 ); previousImage.setFitWidth( 18 ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to load previous icon: resources/previous.png", e ); } nextImage = null; try { nextImage = new ImageView ( new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( "resources/next.png" ).toFile() ) ) ); nextImage.setFitHeight( 18 ); nextImage.setFitWidth( 18 ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to load previous icon: resources/next.png", e ); } stopImage = null; try { stopImage = new ImageView ( new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( "resources/stop.png" ).toFile() ) ) ); stopImage.setFitHeight( 18 ); stopImage.setFitWidth( 18 ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to load previous icon: resources/stop.png", e ); } loveImage = null; try { Image loveImageSource = new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( "resources/love.png" ).toFile() ) ); loveImage = new ImageView ( loveImageSource ); loveImage.setFitHeight( 14 ); loveImage.setFitWidth( 14 ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to load play icon: resources/love.png", e ); } } public void applyDarkTheme () { if ( stopImage != null ) stopImage.setEffect( darkThemeButtonEffect ); if ( nextImage != null ) nextImage.setEffect( darkThemeButtonEffect ); if ( previousImage != null ) previousImage.setEffect( darkThemeButtonEffect ); if ( pauseImage != null ) pauseImage.setEffect( darkThemeButtonEffect ); if ( playImage != null ) playImage.setEffect( darkThemeButtonEffect ); if ( settingsImage != null ) settingsImage.setEffect( darkThemeButtonEffect ); for ( int k = 0; k < volumeImages.length; k++ ) { if ( volumeImages[k] != null ) volumeImages[k].setEffect( darkThemeButtonEffect ); } updateLovedIndicator( true ); } public void applyLightTheme() { if ( stopImage != null ) stopImage.setEffect( lightThemeButtonEffect ); if ( nextImage != null ) nextImage.setEffect( lightThemeButtonEffect ); if ( previousImage != null ) previousImage.setEffect( lightThemeButtonEffect ); if ( pauseImage != null ) pauseImage.setEffect( lightThemeButtonEffect ); if ( playImage != null ) playImage.setEffect( lightThemeButtonEffect ); if ( settingsImage != null ) settingsImage.setEffect( lightThemeButtonEffect ); for ( int k = 0; k < volumeImages.length; k++ ) { if ( volumeImages[k] != null ) volumeImages[k].setEffect( lightThemeButtonEffect ); } updateLovedIndicator( true ); } public void update ( int timeElapsedS, int timeRemainingS, double percent ) { Platform.runLater( new Runnable() { public void run () { if ( audioSystem.isPlaying() || audioSystem.isPaused() ) { if ( !trackPositionSlider.isValueChanging() && !sliderMouseHeld ) { trackPositionSlider.setValue( (trackPositionSlider.getMax() - trackPositionSlider.getMin()) * percent + trackPositionSlider.getMin() ); } timeElapsedLabel.setText( Utils.getLengthDisplay( timeElapsedS ) ); timeRemainingLabel.setText( Utils.getLengthDisplay( -timeRemainingS ) ); } else if ( audioSystem.isStopped() ) { ui.getCurrentListPane().currentListTable.refresh(); togglePlayButton.setGraphic( playImage ); trackPositionSlider.setValue( 0 ); timeElapsedLabel.setText( "" ); timeRemainingLabel.setText( "" ); currentTrackButton.setText( "" ); loveButton.setText( "" ); currentTrackTooltip.setText( "No current track." ); StackPane thumb = (StackPane) trackPositionSlider.lookup( ".thumb" ); thumb.setVisible( false ); } } }); } //@Override public void playerVolumeChanged ( double newVolumePercent ) { Platform.runLater( () -> { double min = volumeSlider.getMin(); double max = volumeSlider.getMax(); volumeSlider.setValue( newVolumePercent * ( max - min ) ); if ( newVolumePercent == 0 ) { volumeMuteButton.setGraphic( volumeImages[0] ); } else if ( newVolumePercent > 0 && newVolumePercent <= .33f ) { volumeMuteButton.setGraphic( volumeImages[1] ); } else if ( newVolumePercent > .33f && newVolumePercent <= .66f ) { volumeMuteButton.setGraphic( volumeImages[2] ); } else if ( newVolumePercent > .66f ) { volumeMuteButton.setGraphic( volumeImages[3] ); } }); } public ColorAdjust getDarkThemeButtonAdjust () { return darkThemeButtonEffect; } public void doAfterShowProcessing () { StackPane thumb = (StackPane) trackPositionSlider.lookup( ".thumb" ); thumb.setVisible( false ); } public void playerStarted ( Track track ) { Runnable runMe = () -> { StackPane thumb = (StackPane) trackPositionSlider.lookup( ".thumb" ); thumb.setVisible( true ); currentTrackButton.setText( track.getArtist() + " - " + track.getTitle() ); currentTrackTooltip.setText( "Album: " + track.getAlbumTitle() + "\n" + "Year: " + track.getYear() + "\n" + "Length: " + Utils.getLengthDisplay( track.getLengthS() ) + "\n" + "Encoding: " + track.getShortEncodingString() ); togglePlayButton.setGraphic( pauseImage ); if ( ui.showLastFMWidgets.get() ) { loveButton.setGraphic( loveImage ); Thread taskThread = new Thread (() -> { //Load the data to cache now, so we can access it quickly w/ Platform call audioSystem.getLastFM().isLoved( audioSystem.getCurrentTrack(), false ); Platform.runLater( () -> updateLovedIndicator( true ) ); }); taskThread.setDaemon( true ); taskThread.start(); } }; if ( Platform.isFxApplicationThread() ) { runMe.run(); } else { Platform.runLater( runMe ); } } public void playerStopped ( Track track, StopReason reason ) { Runnable runMe = () -> { update ( 0, 0, 0 ); //values don't matter. volumeSlider.setDisable( false ); volumeMuteButton.setDisable( false ); if ( ui.showLastFMWidgets.get() ) loveButton.setGraphic( null ); }; if ( Platform.isFxApplicationThread() ) { runMe.run(); } else { Platform.runLater( runMe ); } } }
31,288
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
SettingsWindow.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/fxui/SettingsWindow.java
package net.joshuad.hypnos.fxui; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.EnumMap; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.HPos; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.ChoiceBox; import javafx.scene.control.ContextMenu; import javafx.scene.control.Hyperlink; import javafx.scene.control.Label; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.scene.control.PasswordField; import javafx.scene.control.SelectionMode; import javafx.scene.control.Slider; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.control.TableColumn; import javafx.scene.control.TableRow; import javafx.scene.control.TableView; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.control.Toggle; import javafx.scene.control.ToggleButton; import javafx.scene.control.ToggleGroup; import javafx.scene.control.Tooltip; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.ClipboardContent; import javafx.scene.input.Dragboard; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.TransferMode; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.scene.text.TextAlignment; import javafx.stage.FileChooser; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.stage.WindowEvent; import javafx.util.Duration; import net.joshuad.hypnos.CurrentList.DefaultRepeatMode; import net.joshuad.hypnos.CurrentList.DefaultShuffleMode; import net.joshuad.hypnos.Hypnos; import net.joshuad.hypnos.hotkeys.GlobalHotkeys; import net.joshuad.hypnos.hotkeys.GlobalHotkeys.Hotkey; import net.joshuad.hypnos.library.Library; import net.joshuad.hypnos.library.Playlist; import net.joshuad.hypnos.library.TagError; import net.joshuad.hypnos.library.Track; import net.joshuad.hypnos.hotkeys.HotkeyState; import net.joshuad.hypnos.audio.AudioSystem; import net.joshuad.hypnos.fxui.DraggedTrackContainer.DragSource; public class SettingsWindow extends Stage { private static final Logger LOGGER = Logger.getLogger( SettingsWindow.class.getName() ); private FXUI ui; private Library library; private GlobalHotkeys hotkeys; private AudioSystem audioSystem; private TabPane tabPane; private Tab globalHotkeysTab; private EnumMap <Hotkey, TextField> hotkeyFields = new EnumMap <Hotkey, TextField> ( Hotkey.class ); private ChoiceBox <String> albumShuffleChoices; private ChoiceBox <String> albumRepeatChoices; private ChoiceBox <String> trackShuffleChoices; private ChoiceBox <String> trackRepeatChoices; private ChoiceBox <String> playlistShuffleChoices; private ChoiceBox <String> playlistRepeatChoices; private TextField userInput; private PasswordField passwordInput; private ToggleButton lightTheme, darkTheme; private ToggleGroup themeToggleGroup; private Hyperlink updateLink; private TableView <TagError> tagTable; private List <TextField> globalHotkeyFields = new ArrayList<> (); SettingsWindow( FXUI ui, Library library, GlobalHotkeys hotkeys, AudioSystem audioSystem ) { super(); this.ui = ui; this.library = library; this.hotkeys = hotkeys; this.audioSystem = audioSystem; initModality( Modality.NONE ); initOwner( ui.getMainStage() ); setWidth ( 700 ); setHeight ( 650 ); setTitle( "Config and Info" ); Pane root = new Pane(); Scene scene = new Scene( root ); tabPane = new TabPane(); Tab settingsTab = setupSettingsTab( root, ui ); globalHotkeysTab = setupGlobalHotkeysTab( root ); if ( hotkeys.isDisabled() ) { globalHotkeysTab.setDisable( true ); globalHotkeysTab.setTooltip( new Tooltip ( hotkeys.getReasonDisabled() ) ); } Tab hotkeysTab = setupHotkeysTab( root ); Tab logTab = setupLogTab( root ); Tab tagTab = setupTagTab( root ); Tab lastFMTab = setupLastFMTab( root ); Tab aboutTab = setupAboutTab( root ); tabPane.getTabs().addAll( settingsTab, hotkeysTab, globalHotkeysTab, logTab, tagTab, lastFMTab, aboutTab ); tabPane.getSelectionModel().selectedItemProperty().addListener( new ChangeListener<Tab>() { @Override public void changed(ObservableValue<? extends Tab> observable, Tab oldValue, Tab newValue) { if ( newValue == globalHotkeysTab ) { hotkeys.beginEditMode(); } else if ( oldValue == globalHotkeysTab ) { hotkeys.endEditMode(); } } } ); this.showingProperty().addListener( ( obs, previousValue, isNowShowing ) -> { if ( isNowShowing ) { if ( tabPane.getSelectionModel().getSelectedItem() == globalHotkeysTab ) { hotkeys.beginEditMode(); } } else { hotkeys.endEditMode(); } }); tabPane.prefWidthProperty().bind( root.widthProperty() ); tabPane.prefHeightProperty().bind( root.heightProperty() ); VBox primaryPane = new VBox(); primaryPane.getChildren().addAll( tabPane ); root.getChildren().add( primaryPane ); setScene( scene ); refreshHotkeyFields(); setOnCloseRequest ( ( WindowEvent event ) -> { Hypnos.getPersister().saveHotkeys(); Hypnos.getPersister().saveSettings(); }); try { getIcons().add( new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( "resources" + File.separator + "icon.png" ).toFile() ) ) ); } catch ( FileNotFoundException e ) { LOGGER.log( Level.WARNING, "Unable to load program icon: resources/icon.png", new NullPointerException() ); } this.setOnShowing( ( event ) -> { String username = audioSystem.getLastFM().getUsername(); String passwordMD5 = audioSystem.getLastFM().getPasswordMD5(); if ( !username.isBlank( ) ) { userInput.setText( username ); passwordInput.setText( passwordMD5 ); } }); scene.addEventFilter( KeyEvent.KEY_PRESSED, new EventHandler <KeyEvent>() { @Override public void handle ( KeyEvent e ) { if ( e.getCode() == KeyCode.ESCAPE ) { boolean editingGlobalHotkey = false; for ( TextField field : globalHotkeyFields ) { if ( field.isFocused() ) { editingGlobalHotkey = true; } } if ( !editingGlobalHotkey ) { close(); e.consume(); } } } }); } private Tab setupHotkeysTab ( Pane root ) { Tab hotkeyTab = new Tab ( "Hotkeys" ); hotkeyTab.setClosable( false ); VBox hotkeyPane = new VBox(); hotkeyTab.setContent( hotkeyPane ); hotkeyPane.setAlignment( Pos.CENTER ); hotkeyPane.setPadding( new Insets ( 10 ) ); Label headerLabel = new Label ( "Hotkeys" ); headerLabel.setPadding( new Insets ( 0, 0, 10, 0 ) ); headerLabel.setWrapText( true ); headerLabel.setTextAlignment( TextAlignment.CENTER ); headerLabel.setStyle( "-fx-font-size: 20px; -fx-font-weight: bold" ); hotkeyPane.getChildren().add( headerLabel ); TextArea hotkeyView = new TextArea(); hotkeyView.setEditable( false ); hotkeyView.prefHeightProperty().bind( root.heightProperty() ); hotkeyView.setWrapText( false ); hotkeyView.getStyleClass().add( "monospaced" ); hotkeyView.setText( hotkeyText ); hotkeyPane.getChildren().addAll( hotkeyView ); return hotkeyTab; } private Tab setupGlobalHotkeysTab ( Pane root ) { GridPane globalContent = new GridPane(); globalContent.setAlignment( Pos.TOP_CENTER ); globalContent.setPadding( new Insets ( 10 ) ); globalContent.setVgap( 2 ); Tab hotkeysTab = new Tab ( "Global Hotkeys" ); hotkeysTab.setClosable( false ); hotkeysTab.setContent( globalContent ); int row = 0; Label headerLabel = new Label ( "Global Hotkeys" ); headerLabel.setPadding( new Insets ( 0, 0, 10, 0 ) ); headerLabel.setWrapText( true ); headerLabel.setTextAlignment( TextAlignment.CENTER ); headerLabel.setStyle( "-fx-alignment: center; -fx-font-size: 20px; -fx-font-weight: bold" ); globalContent.add( headerLabel, 0, row, 2, 1 ); GridPane.setHalignment( headerLabel, HPos.CENTER ); row++; Label descriptionLabel = new Label ( "These hotkeys will also work when Hypnos is minimized or out of focus." ); descriptionLabel.setPadding( new Insets ( 0, 0, 20, 0 ) ); descriptionLabel.setWrapText( true ); descriptionLabel.setTextAlignment( TextAlignment.CENTER ); globalContent.add( descriptionLabel, 0, row, 2, 1 ); GridPane.setHalignment( descriptionLabel, HPos.CENTER ); row++; for ( Hotkey hotkey : Hotkey.values() ) { Label label = new Label ( hotkey.getLabel() ); GridPane.setHalignment( label, HPos.RIGHT ); label.setPadding( new Insets ( 0, 20, 0, 0 ) ); TextField field = new TextField (); field.setStyle( "-fx-alignment: center" ); //TODO: Put this in the stylesheet field.setPrefWidth( 200 ); globalHotkeyFields.add ( field ); field.setOnKeyPressed( ( KeyEvent keyEvent ) -> { String hotkeyText = HotkeyState.getDisplayText( keyEvent ); if ( keyEvent.getCode().equals ( KeyCode.UNDEFINED ) ) { //Do nothing, it's handled during key release } else if ( keyEvent.getCode().equals( KeyCode.ESCAPE ) ) { field.setText( "" ); hotkeys.clearHotkey ( hotkey ); } else if ( keyEvent.getCode().isModifierKey() ) { field.setText( hotkeyText ); hotkeys.clearHotkey ( hotkey ); } else if ( keyEvent.getCode().equals( KeyCode.TAB ) ) { //Do nothing, javafx automatically focus cycles } else { boolean registered = hotkeys.registerFXHotkey( hotkey, keyEvent ); if ( registered ) { field.setText( hotkeyText ); refreshHotkeyFields(); } } field.positionCaret( hotkeyText.length() ); keyEvent.consume(); }); field.addEventFilter(KeyEvent.KEY_TYPED, new EventHandler<KeyEvent>() { @Override public void handle(KeyEvent event) { event.consume(); } }); field.focusedProperty().addListener( ( obs, oldVal, newVal ) -> { //This fixes a particular bug on linux //Have a hotkey (meta + X) registered with another program, then press //1. Meta, 2. X, 3. Release Meta, 4. Release X. // If you do that, you'll get the key area frozen at Meta + refreshHotkeyFields(); //TODO: on linux I could use stop this to show a "registered with system already" thing //not sure if it'll work on configurations other than xubuntu } ); field.setOnKeyReleased( ( KeyEvent keyEvent ) -> { if ( keyEvent.getCode().equals ( KeyCode.UNDEFINED ) ) { HotkeyState state = hotkeys.createJustPressedState ( keyEvent ); boolean registered = hotkeys.registerHotkey( hotkey, state ); if ( registered ) { field.setText( state.getDisplayText() ); refreshHotkeyFields(); } } refreshHotkeyFields(); field.positionCaret( 0 ); }); globalContent.add( label, 0, row ); globalContent.add( field, 1, row ); hotkeyFields.put( hotkey, field ); row++; } Label clearHotkeyLabel = new Label ( "(Use ESC to erase a global hotkey)" ); clearHotkeyLabel.setPadding( new Insets ( 20, 0, 20, 0 ) ); clearHotkeyLabel.setWrapText( true ); clearHotkeyLabel.setTextAlignment( TextAlignment.CENTER ); globalContent.add( clearHotkeyLabel, 0, row, 2, 1 ); GridPane.setHalignment( clearHotkeyLabel, HPos.CENTER ); row++; if ( Hypnos.globalHotkeysDisabled() ) { Label disabledNote = new Label ( "Hotkeys are currently disabled by system. See the log for more info." ); globalContent.add( disabledNote, 0, row, 2, 1 ); disabledNote.setPadding( new Insets ( 0, 0, 20, 0 ) ); GridPane.setHalignment( disabledNote, HPos.CENTER ); row++; } return hotkeysTab; } public void updateSettingsBeforeWindowShown() { switch ( audioSystem.getCurrentList().getDefaultTrackRepeatMode() ) { case NO_CHANGE: trackRepeatChoices.getSelectionModel().select( 0 ); break; case PLAY_ONCE: trackRepeatChoices.getSelectionModel().select( 1 ); break; case REPEAT: trackRepeatChoices.getSelectionModel().select( 2 ); break; } switch ( audioSystem.getCurrentList().getDefaultAlbumRepeatMode() ) { case NO_CHANGE: albumRepeatChoices.getSelectionModel().select( 0 ); break; case PLAY_ONCE: albumRepeatChoices.getSelectionModel().select( 1 ); break; case REPEAT: albumRepeatChoices.getSelectionModel().select( 2 ); break; } switch ( audioSystem.getCurrentList().getDefaultPlaylistRepeatMode() ) { case NO_CHANGE: playlistRepeatChoices.getSelectionModel().select( 0 ); break; case PLAY_ONCE: playlistRepeatChoices.getSelectionModel().select( 1 ); break; case REPEAT: playlistRepeatChoices.getSelectionModel().select( 2 ); break; } switch ( audioSystem.getCurrentList().getDefaultTrackShuffleMode() ) { case NO_CHANGE: trackShuffleChoices.getSelectionModel().select( 0 ); break; case SEQUENTIAL: trackShuffleChoices.getSelectionModel().select( 1 ); break; case SHUFFLE: trackShuffleChoices.getSelectionModel().select( 2 ); break; } switch ( audioSystem.getCurrentList().getDefaultAlbumShuffleMode() ) { case NO_CHANGE: albumShuffleChoices.getSelectionModel().select( 0 ); break; case SEQUENTIAL: albumShuffleChoices.getSelectionModel().select( 1 ); break; case SHUFFLE: albumShuffleChoices.getSelectionModel().select( 2 ); break; } switch ( audioSystem.getCurrentList().getDefaultPlaylistShuffleMode() ) { case NO_CHANGE: playlistShuffleChoices.getSelectionModel().select( 0 ); break; case SEQUENTIAL: playlistShuffleChoices.getSelectionModel().select( 1 ); break; case SHUFFLE: playlistShuffleChoices.getSelectionModel().select( 2 ); break; } if ( ui.isDarkTheme() ) { themeToggleGroup.selectToggle( darkTheme ); } else { themeToggleGroup.selectToggle( lightTheme ); } } public void refreshHotkeyFields() { for ( Hotkey key : Hotkey.values() ) { TextField field = hotkeyFields.get( key ); if ( field == null ) continue; field.setText( hotkeys.getDisplayText( key ) ); } } private Tab setupSettingsTab ( Pane root, FXUI ui ) { Tab settingsTab = new Tab ( "Settings" ); settingsTab.setClosable( false ); VBox settingsPane = new VBox( 20 ); settingsTab.setContent ( settingsPane ); settingsPane.setAlignment( Pos.TOP_CENTER ); settingsPane.setPadding( new Insets ( 10 ) ); Label headerLabel = new Label ( "Settings" ); headerLabel.setPadding( new Insets ( 0, 0, 10, 0 ) ); headerLabel.setWrapText( true ); headerLabel.setTextAlignment( TextAlignment.CENTER ); headerLabel.setStyle( "-fx-font-size: 20px; -fx-font-weight: bold" ); settingsPane.getChildren().add( headerLabel ); Insets labelInsets = new Insets ( 10, 10, 10, 10 ); Insets checkBoxInsets = new Insets ( 10, 10, 10, 10 ); Label themeLabel = new Label ( "Theme: " ); themeLabel.setPadding( labelInsets ); lightTheme = new ToggleButton ( "Light" ); darkTheme = new ToggleButton ( "Dark" ); themeToggleGroup = new ToggleGroup(); lightTheme.setToggleGroup( themeToggleGroup ); darkTheme.setToggleGroup( themeToggleGroup ); lightTheme.setPrefWidth( 150 ); darkTheme.setPrefWidth( 150 ); lightTheme.setSelected( true ); themeToggleGroup.selectedToggleProperty().addListener( new ChangeListener <Toggle>() { public void changed ( ObservableValue <? extends Toggle> oldValue, Toggle toggle, Toggle newValue ) { if ( newValue == null ) { //Do nothing } else if ( newValue == lightTheme ) { ui.applyLightTheme(); } else if ( newValue == darkTheme ) { ui.applyDarkTheme(); } } }); HBox themeBox = new HBox(); themeBox.setAlignment( Pos.TOP_CENTER ); themeBox.getChildren().addAll( themeLabel, lightTheme, darkTheme ); Label warnLabel = new Label ( "Warn before erasing unsaved playlists" ); warnLabel.setPadding( labelInsets ); CheckBox warnCheckBox = new CheckBox (); warnCheckBox.setPadding( checkBoxInsets ); warnCheckBox.selectedProperty().bindBidirectional( ui.promptBeforeOverwriteProperty() ); HBox warnBox = new HBox(); warnBox.setAlignment( Pos.TOP_CENTER ); warnBox.getChildren().addAll( warnCheckBox, warnLabel ); Label updateInUILabel = new Label ( "Show update available notification in main window" ); updateInUILabel.setPadding( labelInsets ); CheckBox updateInUICheckBox = new CheckBox (); updateInUICheckBox.setPadding( checkBoxInsets ); updateInUICheckBox.selectedProperty().bindBidirectional( ui.showUpdateAvailableInUIProperty() ); HBox updateInUIBox = new HBox(); updateInUIBox.setAlignment( Pos.TOP_CENTER ); updateInUIBox.getChildren().addAll( updateInUICheckBox, updateInUILabel ); GridPane shuffleGrid = new GridPane(); shuffleGrid.setPadding( new Insets ( 0, 0, 0, 0 ) ); shuffleGrid.setHgap( 15 ); shuffleGrid.setVgap( 5 ); int row = 0; Label shuffleLabel = new Label ( "Shuffle" ); GridPane.setHalignment( shuffleLabel, HPos.CENTER ); shuffleGrid.add( shuffleLabel, 1, row ); Label repeatLabel = new Label ( "Repeat" ); GridPane.setHalignment( repeatLabel, HPos.CENTER ); shuffleGrid.add( repeatLabel, 2, row ); row++; final ObservableList<String> shuffleOptions = FXCollections.observableArrayList( "No Change", "Sequential", "Shuffle" ); final ObservableList<String> repeatOptions = FXCollections.observableArrayList( "No Change", "Play Once", "Repeat" ); Label albumsLabel = new Label ( "Default setting for albums:" ); GridPane.setHalignment( albumsLabel, HPos.RIGHT ); shuffleGrid.add ( albumsLabel, 0, row ); albumShuffleChoices = new ChoiceBox <String>( shuffleOptions ); shuffleGrid.add ( albumShuffleChoices, 1, row ); albumShuffleChoices.getSelectionModel().select( 1 ); albumShuffleChoices.getSelectionModel().selectedIndexProperty().addListener( new ChangeListener<Number>() { @Override public void changed ( ObservableValue <? extends Number> observableValue, Number oldValue, Number newValue ) { switch ( newValue.intValue() ) { case 0: audioSystem.getCurrentList().setDefaultAlbumShuffleMode ( DefaultShuffleMode.NO_CHANGE ); break; case 1: audioSystem.getCurrentList().setDefaultAlbumShuffleMode ( DefaultShuffleMode.SEQUENTIAL ); break; case 2: audioSystem.getCurrentList().setDefaultAlbumShuffleMode ( DefaultShuffleMode.SHUFFLE ); break; } } }); albumRepeatChoices = new ChoiceBox <String>( repeatOptions ); shuffleGrid.add ( albumRepeatChoices, 2, row ); albumRepeatChoices.getSelectionModel().select( 1 ); albumRepeatChoices.getSelectionModel().selectedIndexProperty().addListener( new ChangeListener<Number>() { @Override public void changed ( ObservableValue <? extends Number> observableValue, Number oldValue, Number newValue ) { switch ( newValue.intValue() ) { case 0: audioSystem.getCurrentList().setDefaultAlbumRepeatMode( DefaultRepeatMode.NO_CHANGE ); break; case 1: audioSystem.getCurrentList().setDefaultAlbumRepeatMode ( DefaultRepeatMode.PLAY_ONCE ); break; case 2: audioSystem.getCurrentList().setDefaultAlbumRepeatMode ( DefaultRepeatMode.REPEAT ); break; } } }); row++; Label trackLabel = new Label ( "Default setting for tracks:" ); GridPane.setHalignment( trackLabel, HPos.RIGHT ); shuffleGrid.add ( trackLabel, 0, row ); trackShuffleChoices = new ChoiceBox <String>( shuffleOptions ); shuffleGrid.add ( trackShuffleChoices, 1, row ); trackShuffleChoices.getSelectionModel().select( 0 ); trackShuffleChoices.getSelectionModel().selectedIndexProperty().addListener( new ChangeListener<Number>() { @Override public void changed ( ObservableValue <? extends Number> observableValue, Number oldValue, Number newValue ) { switch ( newValue.intValue() ) { case 0: audioSystem.getCurrentList().setDefaultTrackShuffleMode( DefaultShuffleMode.NO_CHANGE ); break; case 1: audioSystem.getCurrentList().setDefaultTrackShuffleMode ( DefaultShuffleMode.SEQUENTIAL ); break; case 2: audioSystem.getCurrentList().setDefaultTrackShuffleMode ( DefaultShuffleMode.SHUFFLE ); break; } } }); trackRepeatChoices = new ChoiceBox <String>( repeatOptions ); shuffleGrid.add ( trackRepeatChoices, 2, row ); trackRepeatChoices.getSelectionModel().select( 0 ); trackRepeatChoices.getSelectionModel().selectedIndexProperty().addListener( new ChangeListener<Number>() { @Override public void changed ( ObservableValue <? extends Number> observableValue, Number oldValue, Number newValue ) { switch ( newValue.intValue() ) { case 0: audioSystem.getCurrentList().setDefaultTrackRepeatMode( DefaultRepeatMode.NO_CHANGE ); break; case 1: audioSystem.getCurrentList().setDefaultTrackRepeatMode ( DefaultRepeatMode.PLAY_ONCE ); break; case 2: audioSystem.getCurrentList().setDefaultTrackRepeatMode ( DefaultRepeatMode.REPEAT ); break; } } }); row++; Label playlistLabel = new Label ( "Default setting for playlists:" ); GridPane.setHalignment( playlistLabel, HPos.RIGHT ); shuffleGrid.add ( playlistLabel, 0, row ); playlistShuffleChoices = new ChoiceBox <String>( shuffleOptions ); shuffleGrid.add ( playlistShuffleChoices, 1, row ); playlistShuffleChoices.getSelectionModel().select( 2 ); playlistShuffleChoices.getSelectionModel().selectedIndexProperty().addListener( new ChangeListener<Number>() { @Override public void changed ( ObservableValue <? extends Number> observableValue, Number oldValue, Number newValue ) { switch ( newValue.intValue() ) { case 0: audioSystem.getCurrentList().setDefaultPlaylistShuffleMode( DefaultShuffleMode.NO_CHANGE ); break; case 1: audioSystem.getCurrentList().setDefaultPlaylistShuffleMode ( DefaultShuffleMode.SEQUENTIAL ); break; case 2: audioSystem.getCurrentList().setDefaultPlaylistShuffleMode ( DefaultShuffleMode.SHUFFLE ); break; } } }); playlistRepeatChoices = new ChoiceBox <String>( repeatOptions ); shuffleGrid.add ( playlistRepeatChoices, 2, row ); playlistRepeatChoices.getSelectionModel().select( 2 ); playlistRepeatChoices.getSelectionModel().selectedIndexProperty().addListener( new ChangeListener<Number>() { @Override public void changed ( ObservableValue <? extends Number> observableValue, Number oldValue, Number newValue ) { switch ( newValue.intValue() ) { case 0: audioSystem.getCurrentList().setDefaultPlaylistRepeatMode( DefaultRepeatMode.NO_CHANGE ); break; case 1: audioSystem.getCurrentList().setDefaultPlaylistRepeatMode ( DefaultRepeatMode.PLAY_ONCE ); break; case 2: audioSystem.getCurrentList().setDefaultPlaylistRepeatMode ( DefaultRepeatMode.REPEAT ); break; } } }); albumShuffleChoices.getStyleClass().add("shuffleRepeatChoices"); albumRepeatChoices.getStyleClass().add("shuffleRepeatChoices"); trackShuffleChoices.getStyleClass().add("shuffleRepeatChoices"); trackRepeatChoices.getStyleClass().add("shuffleRepeatChoices"); playlistShuffleChoices.getStyleClass().add("shuffleRepeatChoices"); playlistRepeatChoices.getStyleClass().add("shuffleRepeatChoices"); row++; shuffleGrid.setAlignment( Pos.TOP_CENTER ); Label showSystemTrayLabel = new Label ( "Show in System Tray" ); showSystemTrayLabel.setPadding( labelInsets ); CheckBox showSystemTrayCheckBox = new CheckBox (); showSystemTrayCheckBox.setPadding( checkBoxInsets ); showSystemTrayCheckBox.selectedProperty().bindBidirectional( ui.showSystemTrayProperty() ); Label closeToTrayLabel = new Label ( "Close to System Tray" ); closeToTrayLabel.setPadding( labelInsets ); CheckBox closeToTrayCheckBox = new CheckBox (); closeToTrayCheckBox.setPadding( checkBoxInsets ); closeToTrayCheckBox.selectedProperty().bindBidirectional( ui.closeToSystemTrayProperty() ); Label minToTrayLabel = new Label ( "Minimize to System Tray" ); minToTrayLabel.setPadding( labelInsets ); CheckBox minToTrayCheckBox = new CheckBox (); minToTrayCheckBox.setPadding( checkBoxInsets ); minToTrayCheckBox.selectedProperty().bindBidirectional( ui.minimizeToSystemTrayProperty() ); if ( ui.getTrayIcon().systemTraySupportedProperty().get() ) { ui.showSystemTrayProperty().addListener( ( ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue ) -> { if ( newValue ) { closeToTrayLabel.setDisable( false ); closeToTrayCheckBox.setDisable( false ); minToTrayLabel.setDisable( false ); minToTrayCheckBox.setDisable( false ); } else { closeToTrayLabel.setDisable( true ); closeToTrayCheckBox.setSelected( false ); closeToTrayCheckBox.setDisable( true ); minToTrayLabel.setDisable( true ); minToTrayCheckBox.setSelected( false ); minToTrayCheckBox.setDisable( true ); } }); if ( ui.showSystemTrayProperty().get() ) { closeToTrayLabel.setDisable( false ); closeToTrayCheckBox.setDisable( false ); minToTrayLabel.setDisable( false ); minToTrayCheckBox.setDisable( false ); } else { closeToTrayLabel.setDisable( true ); closeToTrayCheckBox.setSelected( false ); closeToTrayCheckBox.setDisable( true ); minToTrayLabel.setDisable( true ); minToTrayCheckBox.setSelected( false ); minToTrayCheckBox.setDisable( true ); } } HBox systemTrayBox = new HBox(); systemTrayBox.setAlignment( Pos.TOP_CENTER ); systemTrayBox.getChildren().addAll( showSystemTrayCheckBox, showSystemTrayLabel, minToTrayCheckBox, minToTrayLabel, closeToTrayCheckBox, closeToTrayLabel ); //We create this container so we can disable systemTrayBox but still have a tooltip on it HBox systemTrayBoxContainer = new HBox(); systemTrayBoxContainer.setAlignment( Pos.TOP_CENTER ); systemTrayBoxContainer.getChildren().add( systemTrayBox ); settingsPane.getChildren().addAll( shuffleGrid, themeBox, warnBox, updateInUIBox, systemTrayBoxContainer ); if ( !ui.getTrayIcon().isSupported() ) { systemTrayBox.setDisable( true ); Tooltip.install( systemTrayBoxContainer, new Tooltip ( "System Tray not supported for your desktop environment, sorry!" ) ); } return settingsTab; } private Tab setupLogTab( Pane root ) { Tab logTab = new Tab ( "Log" ); logTab.setClosable( false ); VBox logPane = new VBox(); logTab.setContent( logPane ); logPane.setAlignment( Pos.CENTER ); logPane.setPadding( new Insets( 10 ) ); Label headerLabel = new Label( "Log" ); headerLabel.setPadding( new Insets( 0, 0, 10, 0 ) ); headerLabel.setWrapText( true ); headerLabel.setTextAlignment( TextAlignment.CENTER ); headerLabel.setStyle( "-fx-font-size: 20px; -fx-font-weight: bold" ); logPane.getChildren().add( headerLabel ); TextArea logView = new TextArea(); logView.setEditable( false ); logView.prefHeightProperty().bind( root.heightProperty() ); logView.getStyleClass().add( "monospaced" ); logView.setWrapText( true ); Thread logReader = new Thread( () -> { try ( BufferedReader reader = new BufferedReader( new FileReader( Hypnos.getLogFile().toFile() ) ); ){ while ( true ) { String line = reader.readLine(); if ( line == null ) { try { Thread.sleep( 500 ); } catch ( InterruptedException ie ) { } } else { Platform.runLater( () -> { logView.appendText( line + "\n" ); }); } } } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to link log window to log file.", e ); } }); logReader.setName( "Log UI Text Loader" ); logReader.setDaemon( true ); logReader.start(); Button exportButton = new Button ( "Export Log File" ); exportButton.setOnAction( ( ActionEvent event ) -> { FileChooser fileChooser = new FileChooser(); FileChooser.ExtensionFilter fileExtensions = new FileChooser.ExtensionFilter( "Log Files", Arrays.asList( "*.log", "*.txt" ) ); fileChooser.getExtensionFilters().add( fileExtensions ); fileChooser.setTitle( "Export Log File" ); fileChooser.setInitialFileName( "hypnos.log" ); File targetFile = fileChooser.showSaveDialog( this ); if ( targetFile == null ) return; if ( !targetFile.toString().toLowerCase().endsWith(".log") && !targetFile.toString().toLowerCase().endsWith(".txt") ) { targetFile = targetFile.toPath().resolveSibling ( targetFile.getName() + ".log" ).toFile(); } try { Files.copy( Hypnos.getLogFile(), targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING ); } catch ( Exception ex ) { ui.notifyUserError ( ex.getClass().getCanonicalName() + ": Unable to export log file." ); LOGGER.log( Level.WARNING, "Unable to export log file.", ex ); } }); Button previousLog = new Button ( "View Last Log" ); previousLog.setOnAction( e -> ui.openFileNatively ( Hypnos.getLogFileBackup() ) ); HBox controlBox = new HBox(); controlBox.setAlignment( Pos.TOP_CENTER ); controlBox.getChildren().addAll( exportButton, previousLog ); controlBox.setPadding( new Insets ( 5, 0, 0, 0 ) ); logPane.getChildren().addAll( logView, controlBox ); return logTab; } private Tab setupTagTab ( Pane root ) { Tab tab = new Tab ( "Tags" ); tab.setClosable( false ); VBox pane = new VBox(); tab.setContent ( pane ); pane.setAlignment( Pos.TOP_CENTER ); pane.setPadding( new Insets ( 10 ) ); Label headerLabel = new Label ( "Tag Errors" ); headerLabel.setPadding( new Insets ( 0, 0, 10, 0 ) ); headerLabel.setWrapText( true ); headerLabel.setTextAlignment( TextAlignment.CENTER ); headerLabel.setStyle( "-fx-font-size: 20px; -fx-font-weight: bold" ); pane.getChildren().add( headerLabel ); TableColumn<TagError, String> pathColumn = new TableColumn<TagError, String> ( "Location" ); TableColumn<TagError, String> filenameColumn = new TableColumn<TagError, String> ( "Filename" ); TableColumn<TagError, String> messageColumn = new TableColumn<TagError, String> ( "Error Message" ); pathColumn.setCellValueFactory( new PropertyValueFactory <TagError, String>( "FolderDisplay" ) ); filenameColumn.setCellValueFactory( new PropertyValueFactory <TagError, String>( "FilenameDisplay" ) ); messageColumn.setCellValueFactory( new PropertyValueFactory <TagError, String>( "Message" ) ); pathColumn.setMaxWidth( 30000 ); filenameColumn.setMaxWidth ( 40000 ); messageColumn.setMaxWidth( 30000 ); pathColumn.setReorderable( false ); filenameColumn.setReorderable ( false ); messageColumn.setReorderable( false ); tagTable = new TableView <TagError> (); tagTable.getColumns().addAll( pathColumn, filenameColumn, messageColumn ); tagTable.getSortOrder().addAll( pathColumn, messageColumn, filenameColumn ); tagTable.setPlaceholder( new Label( "There are no tag errors." ) ); library.getTagErrorsSorted().comparatorProperty().bind( tagTable.comparatorProperty() ); tagTable.setEditable( false ); tagTable.getSelectionModel().setSelectionMode( SelectionMode.MULTIPLE ); tagTable.setColumnResizePolicy( TableView.CONSTRAINED_RESIZE_POLICY ); tagTable.setItems( library.getTagErrorsSorted() ); tagTable.prefWidthProperty().bind( pane.widthProperty() ); tagTable.prefHeightProperty().bind( pane.heightProperty() ); tagTable.getSelectionModel().selectedItemProperty().addListener( ( obs, oldSelection, newSelection ) -> { if ( newSelection != null ) { ui.trackSelected ( newSelection.getTrack() ); } }); Menu lastFMMenu = new Menu( "LastFM" ); MenuItem loveMenuItem = new MenuItem ( "Love" ); MenuItem unloveMenuItem = new MenuItem ( "Unlove" ); MenuItem scrobbleMenuItem = new MenuItem ( "Scrobble" ); lastFMMenu.getItems().addAll ( loveMenuItem, unloveMenuItem, scrobbleMenuItem ); lastFMMenu.setVisible ( false ); lastFMMenu.visibleProperty().bind( ui.showLastFMWidgets ); loveMenuItem.setOnAction( ( event ) -> { ui.audioSystem.getLastFM().loveTrack( tagTable.getSelectionModel().getSelectedItem().getTrack() ); }); unloveMenuItem.setOnAction( ( event ) -> { ui.audioSystem.getLastFM().unloveTrack( tagTable.getSelectionModel().getSelectedItem().getTrack() ); }); scrobbleMenuItem.setOnAction( ( event ) -> { ui.audioSystem.getLastFM().scrobbleTrack( tagTable.getSelectionModel().getSelectedItem().getTrack() ); }); ContextMenu contextMenu = new ContextMenu(); MenuItem playMenuItem = new MenuItem( "Play" ); MenuItem playNextMenuItem = new MenuItem( "Play Next" ); MenuItem appendMenuItem = new MenuItem( "Append" ); MenuItem enqueueMenuItem = new MenuItem( "Enqueue" ); MenuItem editTagMenuItem = new MenuItem( "Edit Tag(s)" ); MenuItem infoMenuItem = new MenuItem( "Info" ); MenuItem lyricsMenuItem = new MenuItem( "Lyrics" ); MenuItem goToAlbumMenuItem = new MenuItem( "Go to Album" ); MenuItem browseMenuItem = new MenuItem( "Browse Folder" ); Menu addToPlaylistMenuItem = new Menu( "Add to Playlist" ); contextMenu.getItems().addAll( playMenuItem, playNextMenuItem, appendMenuItem, enqueueMenuItem, editTagMenuItem, infoMenuItem, lyricsMenuItem, goToAlbumMenuItem, browseMenuItem, addToPlaylistMenuItem, lastFMMenu ); MenuItem newPlaylistButton = new MenuItem( "<New>" ); addToPlaylistMenuItem.getItems().add( newPlaylistButton ); newPlaylistButton.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent e ) { List <Track> tracks = new ArrayList <Track> (); for ( TagError error : tagTable.getSelectionModel().getSelectedItems() ) { tracks.add( error.getTrack() ); } ui.promptAndSavePlaylist ( tracks ); } }); EventHandler<ActionEvent> addToPlaylistHandler = new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { List <Track> tracks = new ArrayList <Track> (); for ( TagError error : tagTable.getSelectionModel().getSelectedItems() ) { tracks.add( error.getTrack() ); } Playlist playlist = (Playlist) ((MenuItem) event.getSource()).getUserData(); ui.addToPlaylist ( tracks, playlist ); } }; library.getPlaylistsSorted().addListener( ( ListChangeListener.Change <? extends Playlist> change ) -> { ui.updatePlaylistMenuItems( addToPlaylistMenuItem.getItems(), addToPlaylistHandler ); } ); ui.updatePlaylistMenuItems( addToPlaylistMenuItem.getItems(), addToPlaylistHandler ); playMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { List <Track> tracks = new ArrayList <Track> (); for ( TagError error : tagTable.getSelectionModel().getSelectedItems() ) { tracks.add( error.getTrack() ); } if ( tracks.size() == 1 ) { audioSystem.playItems( tracks ); } else if ( tracks.size() > 1 ) { if ( ui.okToReplaceCurrentList() ) { audioSystem.playItems( tracks ); } } } }); playNextMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { List <Track> tracks = new ArrayList <Track> (); for ( TagError error : tagTable.getSelectionModel().getSelectedItems() ) { tracks.add( error.getTrack() ); } if ( tracks.size() == 1 ) { audioSystem.getQueue().queueAllTracks( tracks, 0 ); } } }); appendMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { List <Track> tracks = new ArrayList <Track> (); for ( TagError error : tagTable.getSelectionModel().getSelectedItems() ) { tracks.add( error.getTrack() ); } audioSystem.getCurrentList().appendTracks ( tracks ); } }); enqueueMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { List <Track> tracks = new ArrayList <Track> (); for ( TagError error : tagTable.getSelectionModel().getSelectedItems() ) { tracks.add( error.getTrack() ); } audioSystem.getQueue().queueAllTracks( tracks ); } }); editTagMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { List <Track> tracks = new ArrayList <Track> (); for ( TagError error : tagTable.getSelectionModel().getSelectedItems() ) { if ( error != null ) { tracks.add( error.getTrack() ); } } ui.tagWindow.setTracks( tracks, null ); ui.tagWindow.show(); } }); infoMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { ui.trackInfoWindow.setTrack( tagTable.getSelectionModel().getSelectedItem().getTrack() ); ui.trackInfoWindow.show(); } }); lyricsMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { ui.lyricsWindow.setTrack( tagTable.getSelectionModel().getSelectedItem().getTrack() ); ui.lyricsWindow.show(); } }); goToAlbumMenuItem.setOnAction( ( event ) -> { ui.goToAlbumOfTrack ( tagTable.getSelectionModel().getSelectedItem().getTrack() ); }); browseMenuItem.setOnAction( new EventHandler <ActionEvent>() { // PENDING: This is the better way, once openjdk and openjfx supports // it: getHostServices().showDocument(file.toURI().toString()); @Override public void handle ( ActionEvent event ) { ui.openFileBrowser( tagTable.getSelectionModel().getSelectedItem().getPath() ); } }); tagTable.setOnKeyPressed( ( KeyEvent e ) -> { if ( e.getCode() == KeyCode.ESCAPE && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { tagTable.getSelectionModel().clearSelection(); } else if ( e.getCode() == KeyCode.L && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { lyricsMenuItem.fire(); } else if ( e.getCode() == KeyCode.Q && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { enqueueMenuItem.fire(); } else if ( e.getCode() == KeyCode.G && e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { goToAlbumMenuItem.fire(); } else if ( e.getCode() == KeyCode.Q && e.isShiftDown() && !e.isAltDown() && !e.isControlDown() && !e.isMetaDown() ) { playNextMenuItem.fire(); } else if ( e.getCode() == KeyCode.F2 && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { editTagMenuItem.fire(); } else if ( e.getCode() == KeyCode.F3 && !e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { infoMenuItem.fire(); e.consume(); } else if ( e.getCode() == KeyCode.F4 && !e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { browseMenuItem.fire(); e.consume(); } else if ( e.getCode() == KeyCode.ENTER && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { playMenuItem.fire(); e.consume(); } else if ( e.getCode() == KeyCode.ENTER && e.isShiftDown() && !e.isAltDown() && !e.isControlDown() && !e.isMetaDown() ) { List <TagError> errors = tagTable.getSelectionModel().getSelectedItems(); List <Track> tracks = new ArrayList<> (); for ( TagError error : errors ) tracks.add ( error.getTrack() ); ui.audioSystem.getCurrentList().insertTracks( 0, tracks ); e.consume(); } else if ( e.getCode() == KeyCode.ENTER && e.isControlDown() && !e.isShiftDown() && !e.isAltDown() && !e.isMetaDown() ) { appendMenuItem.fire(); e.consume(); } }); tagTable.setRowFactory( tv -> { TableRow <TagError> row = new TableRow <>(); row.itemProperty().addListener( (obs, oldValue, newValue ) -> { if ( newValue != null ) { row.setContextMenu( contextMenu ); } else { row.setContextMenu( null ); } }); row.setOnContextMenuRequested( event -> { goToAlbumMenuItem.setDisable( row.getItem().getTrack().getAlbum() == null ); }); row.setOnMouseClicked( event -> { if ( event.getClickCount() == 2 && (!row.isEmpty()) ) { ui.tagWindow.setTracks( Arrays.asList ( row.getItem().getTrack() ), null ); ui.tagWindow.show(); } }); row.setOnDragDetected( event -> { if ( !row.isEmpty() ) { ArrayList <Integer> indices = new ArrayList <Integer>( tagTable.getSelectionModel().getSelectedIndices() ); ArrayList <Track> tracks = new ArrayList <Track>( ); for ( Integer index : indices ) { TagError error = tagTable.getItems().get( index ); if ( error != null ) { tracks.add( error.getTrack() ); } } DraggedTrackContainer dragObject = new DraggedTrackContainer( indices, tracks, null, null, null, DragSource.TAG_ERROR_LIST ); Dragboard db = row.startDragAndDrop( TransferMode.COPY ); db.setDragView( row.snapshot( null, null ) ); ClipboardContent cc = new ClipboardContent(); cc.put( FXUI.DRAGGED_TRACKS, dragObject ); db.setContent( cc ); event.consume(); } }); return row; }); pane.getChildren().addAll( tagTable ); return tab; } private Tab setupLastFMTab( Pane root ) { Label headerLabel = new Label( "LastFM" ); headerLabel.setPadding( new Insets( 0, 0, 10, 0 ) ); headerLabel.setWrapText( true ); headerLabel.setTextAlignment( TextAlignment.CENTER ); headerLabel.setStyle( "-fx-font-size: 20px; -fx-font-weight: bold" ); userInput = new TextField(); passwordInput = new PasswordField(); CheckBox scrobbleCheckbox = new CheckBox(); CheckBox showInUICheckbox = new CheckBox(); Label scrobbleLabel = new Label ( "Scrobble Automatically:" ); Label scrobbleTime = new Label ( "At Beginning" ); Label showInUILabel = new Label ( "Show LastFM in UI:" ); scrobbleLabel.setPadding( new Insets ( 0, 0, 0, 60 ) ); scrobbleTime.setPadding( new Insets ( 0, 0, 0, 60 ) ); showInUILabel.setPadding( new Insets ( 0, 0, 0, 60 ) ); Slider scrobbleTimeSlider = new Slider ( 0, 1, 0 ); scrobbleTimeSlider.setMajorTickUnit( .25 ); scrobbleTimeSlider.setMinorTickCount( 0 ); scrobbleTimeSlider.valueProperty().addListener( (observable, oldValue, newValue) -> { if ( newValue.doubleValue() == 0 ) { scrobbleTime.setText( "At Beginning" ); audioSystem.setScrobbleTime ( 0 ); } else if ( newValue.doubleValue() == 1 ) { scrobbleTime.setText( "After Finish" ); audioSystem.setScrobbleTime ( 1d ); } else { scrobbleTime.setText( "After playing " + new DecimalFormat( "##%").format ( newValue.doubleValue() ) ); audioSystem.setScrobbleTime ( newValue.doubleValue() ); } }); scrobbleCheckbox.selectedProperty().bindBidirectional( audioSystem.doLastFMScrobbleProperty() ); showInUICheckbox.selectedProperty().bindBidirectional( ui.showLastFMWidgets ); scrobbleTimeSlider.valueProperty().bindBidirectional( audioSystem.scrobbleTimeProperty() ); Button connectButton = new Button( "Connect" ); connectButton.setOnAction( (ActionEvent e) -> { audioSystem.getLastFM().setCredentials( userInput.getText(), passwordInput.getText() ); audioSystem.getLastFM().connect(); }); Button disconnectButton = new Button( "Disconnect" ); disconnectButton.setOnAction( (ActionEvent e) -> { audioSystem.getLastFM().disconnectAndForgetCredentials(); userInput.clear(); passwordInput.clear(); }); HBox connectPane = new HBox(); connectPane.setAlignment( Pos.CENTER ); connectPane.getChildren().addAll( connectButton, disconnectButton ); GridPane.setHalignment( connectPane, HPos.CENTER ); GridPane loginPane = new GridPane(); loginPane.setHgap( 5 ); loginPane.setVgap( 5 ); loginPane.add( new Label ( "Username:"), 0, 0 ); loginPane.add( userInput, 1, 0 ); loginPane.add( new Label ( "Password:"), 0, 1 ); loginPane.add( passwordInput, 1, 1 ); loginPane.add( connectPane, 0, 2, 2, 1 ); loginPane.add( showInUILabel, 2, 0 ); loginPane.add( showInUICheckbox, 3, 0 ); loginPane.add( scrobbleLabel, 2, 1 ); loginPane.add( scrobbleCheckbox, 3, 1 ); loginPane.add( scrobbleTime, 2, 2 ); loginPane.add( scrobbleTimeSlider, 3, 2 ); TextArea logView = new TextArea(); logView.setEditable( false ); logView.setWrapText( true ); logView.prefHeightProperty().bind( root.heightProperty() ); logView.prefWidthProperty().bind( root.widthProperty() ); logView.getStyleClass().add( "monospaced" ); Timeline lastFMUpdater = new Timeline(); lastFMUpdater.setCycleCount( Timeline.INDEFINITE ); KeyFrame updateFrame = new KeyFrame( Duration.millis(1000), ae -> { String string = audioSystem.getLastFM().getLog().toString(); if ( !string.equals( logView.getText() ) ) { logView.setText( string ); } }); lastFMUpdater.getKeyFrames().add( updateFrame ); lastFMUpdater.play(); Tab lastFMTab = new Tab ( "LastFM" ); lastFMTab.setClosable( false ); VBox logPane = new VBox(); logPane.setAlignment( Pos.TOP_CENTER ); lastFMTab.setContent( logPane ); logPane.setPadding( new Insets( 10 ) ); logPane.setSpacing( 20 ); logPane.prefHeightProperty().bind( root.heightProperty() ); logPane.prefWidthProperty().bind( root.widthProperty() ); Hyperlink lastFMLink = new Hyperlink ( "last.fm" ); lastFMLink.setStyle( "-fx-text-fill: #0A95C8" ); lastFMLink.setOnAction( e-> ui.openWebBrowser( "http://last.fm" ) ); logPane.getChildren().addAll( headerLabel, loginPane, logView, lastFMLink ); return lastFMTab; } private Tab setupAboutTab ( Pane root ) { Tab aboutTab = new Tab ( "About" ); aboutTab.setClosable( false ); VBox aboutPane = new VBox(); aboutTab.setContent( aboutPane ); aboutPane.setStyle( "-fx-background-color: wheat" ); aboutPane.getStyleClass().add( "aboutPaneBack" ); aboutPane.setAlignment( Pos.CENTER ); Label name = new Label ( "Hypnos Music Player" ); name.setStyle( "-fx-font-size: 36px; -fx-text-fill: #020202" ); name.getStyleClass().add( "aboutPaneText" ); String url = "http://www.hypnosplayer.org"; Hyperlink website = new Hyperlink ( url ); website.setTooltip( new Tooltip ( url ) ); website.setOnAction( event -> ui.openWebBrowser( url ) ); website.setStyle( "-fx-font-size: 20px; -fx-text-fill: #0A95C8" ); aboutPane.getStyleClass().add( "aboutPaneURL" ); String labelString = Hypnos.getVersion() + ", Build: " + Hypnos.getBuild() + "\n" + Hypnos.getBuildDate() ; Label versionNumber = new Label ( labelString ); versionNumber.setTextAlignment( TextAlignment.CENTER ); versionNumber.setStyle( "-fx-font-size: 16px; -fx-text-fill: #020202" ); versionNumber.setPadding( new Insets ( 0, 0, 20, 0 ) ); versionNumber.getStyleClass().add( "aboutPaneText" ); Image image = null; try { image = new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( "resources" + File.separator + "icon.png" ).toFile() ) ); } catch ( Exception e1 ) { LOGGER.log( Level.INFO, "Unable to load hypnos icon for settings -> about tab.", e1 ); } ImageView logo = new ImageView( image ); logo.setFitWidth( 200 ); logo.setPreserveRatio( true ); logo.setSmooth( true ); logo.setCache( true ); HBox authorBox = new HBox(); authorBox.setAlignment( Pos.CENTER ); authorBox.setPadding ( new Insets ( 20, 0, 0, 0 ) ); authorBox.setStyle( "-fx-font-size: 16px; -fx-background-color: transparent;" ); Label authorLabel = new Label ( "Author:" ); authorLabel.getStyleClass().add( "aboutPaneText" ); authorLabel.setStyle( "-fx-text-fill: #020202" ); Hyperlink authorLink = new Hyperlink ( "Joshua Hartwell" ); String authorURL = "http://joshuad.net"; authorLink.setTooltip( new Tooltip ( authorURL ) ); authorLink.setStyle( "-fx-text-fill: #0A95C8" ); authorLink.setOnAction( ( ActionEvent e ) -> { ui.openWebBrowser( authorURL ); }); authorLink.getStyleClass().add( "aboutPaneURL" ); authorBox.getChildren().addAll( authorLabel, authorLink ); HBox sourceBox = new HBox(); sourceBox.setStyle( "-fx-background-color: transparent" ); sourceBox.setAlignment( Pos.CENTER ); sourceBox.setStyle( "-fx-background-color: transparent" ); Label sourceLabel = new Label ( "Source Code:" ); sourceLabel.setStyle( "-fx-text-fill: #020202" ); sourceLabel.getStyleClass().add( "aboutPaneText" ); Hyperlink sourceLink = new Hyperlink ( "GitHub" ); sourceLink.getStyleClass().add( "aboutPaneURL" ); String githubURL = "https://github.com/JoshuaD84/HypnosMusicPlayer"; sourceLink.setTooltip( new Tooltip ( githubURL ) ); sourceLink.setStyle( "-fx-text-fill: #0A95C8" ); sourceLink.setOnAction( ( ActionEvent e ) -> { ui.openWebBrowser( githubURL ); }); sourceBox.getChildren().addAll( sourceLabel, sourceLink ); HBox licenseBox = new HBox(); licenseBox.setStyle( "-fx-background-color: transparent" ); licenseBox.setAlignment( Pos.CENTER ); Label licenseLabel = new Label ( "License:" ); licenseLabel.setStyle( "-fx-text-fill: #020202" ); licenseLabel.getStyleClass().add( "aboutPaneText" ); Hyperlink licenseLink = new Hyperlink ( "GNU GPLv3" ); licenseLink.setStyle( "-fx-text-fill: #0A95C8" ); licenseLink.getStyleClass().add( "aboutPaneURL" ); String gplurl = "https://www.gnu.org/licenses/gpl-3.0-standalone.html"; licenseLink.setTooltip ( new Tooltip ( gplurl ) ); licenseLink.setOnAction( ( ActionEvent e ) -> { ui.openWebBrowser( gplurl ); }); licenseBox.getChildren().addAll( licenseLabel, licenseLink ); HBox bugBox = new HBox(); bugBox.setStyle( "-fx-background-color: transparent" ); bugBox.setAlignment( Pos.CENTER ); Label bugLabel = new Label ( "Report a Bug:" ); bugLabel.setStyle( "-fx-text-fill: #020202" ); bugLabel.getStyleClass().add( "aboutPaneText" ); Hyperlink bugGitLink = new Hyperlink ( "on GitHub" ); bugGitLink.setStyle( "-fx-text-fill: #0A95C8" ); bugGitLink.getStyleClass().add( "aboutPaneURL" ); String bugGitHubURL = "https://github.com/JoshuaD84/HypnosMusicPlayer/issues"; bugGitLink.setTooltip ( new Tooltip ( bugGitHubURL ) ); bugGitLink.setOnAction( ( ActionEvent e ) -> { ui.openWebBrowser( bugGitHubURL ); }); bugBox.getChildren().addAll( bugLabel, bugGitLink ); String updateURL = "http://hypnosplayer.org"; updateLink = new Hyperlink ( "Update Available!" ); updateLink.setStyle( "-fx-font-size: 20px; -fx-text-fill: #0A95C8" ); updateLink.getStyleClass().add( "aboutPaneURL" ); updateLink.setPadding( new Insets ( 15, 0, 0, 0 ) ); updateLink.setVisible ( false ); updateLink.setOnAction( e -> ui.openWebBrowser( updateURL ) ); updateLink.setTooltip ( new Tooltip ( updateURL ) ); updateLink.visibleProperty().bind( ui.updateAvailableProperty() ); aboutPane.getChildren().addAll ( name, website, versionNumber, logo, authorBox, sourceBox, licenseBox, bugBox, updateLink ); return aboutTab; } private String hotkeyText = "Main Window\n" + " Back 5 seconds Numpad 1\n" + " Stop Numpad 2\n" + " Forward 5 seconds Numpad 3\n" + " Previous Numpad 4\n" + " Play / Pause Numpad 5\n" + " Next Numpad 6\n" + " Volume Down Numpad 7\n" + " Mute / Unmute Numpad 8\n" + " Volume Up Numpad 9\n" + " Toggle Shuffle Mode S\n" + " Toggle Repeat Mode R\n" + " Show Lyrics on Current Track Shift + L\n" + " Toggle Library Collapsed Ctrl + L\n" + " Toggle Artwork Collapsed Ctrl + ;\n" + " Show Queue Ctrl + Q\n" + " Show History Ctrl + H\n" + " Show Config Ctrl + P\n" + " Save Current List as Playlist Ctrl + S\n" + " Open files Ctrl + O\n" + " Export Current List as Playlist Ctrl + E\n" + " Filter the Current List F\n" + " Filter the First Tab in Library 1 or Ctrl + 1\n" + " Filter the Second Tab in Library 2 or Ctrl + 2\n" + " Filter the Third Tab in Library 3 or Ctrl + 3\n" + " Filter the Fourth Tab in Library 4 or Ctrl + 4\n" + " Filter whichever table has focus Ctrl + F\n" + "\n" + "Playlists, Albums, Tracks\n" + " Queue Item Q\n" + " play next (front of queue) Shift + Q\n" + " Tag Editor / Rename Playlist F2\n" + " Track List / Info F3\n" + " File System Browser F4\n" + " Play Selected Item(s) Enter\n" + " Append Item to current list Ctrl + Enter\n" + " Prepend to current List Shift + Enter\n" + "\n" + "Playlist Library\n" + " Delete selected Playlists Del\n" + "\n" + "Any Track\n" + " Show Lyrics L\n" + " Select the track's album in library Ctrl + G\n" + "\n" + "All Tables\n" + " Deselect Esc\n" + "\n" + "Filter Text Boxes\n" + " Clear Filter Esc\n" + "\n" + "Current List\n" + " Delete selected Tracks Del\n" + " Crop to selected Tracks Shift + Del\n" + "\n" + "Tag Window\n" + " Save and Previous Ctrl + Right\n" + " Save and Next Ctrl + Left\n" + "\n" + "Popup Windows\n" + " Close Window Esc"; }
55,597
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
EditOnClickCell.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/fxui/EditOnClickCell.java
package net.joshuad.hypnos.fxui; import javafx.application.Platform; import javafx.event.Event; import javafx.scene.control.ContentDisplay; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.scene.control.TableColumn.CellEditEvent; import javafx.scene.control.TablePosition; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.util.StringConverter; public class EditOnClickCell<S, T> extends TableCell<S, T> { private final TextField textField = new TextField(); private final StringConverter<T> converter; public EditOnClickCell(StringConverter<T> converter) { textField.setMaxHeight(5); textField.setPrefHeight(5); this.converter = converter; itemProperty().addListener((obx, oldItem, newItem) -> { setText(converter.toString(newItem)); }); setGraphic(textField); setContentDisplay(ContentDisplay.TEXT_ONLY); Platform.runLater(() -> { getTableView().setOnKeyPressed(event -> { TablePosition<T, ?> pos = getTableView().getFocusModel().getFocusedCell(); if (pos != null && event.getCode().isLetterKey() || event.getCode().isDigitKey()) { beginEditing(); } }); getTableView().getSelectionModel().selectedItemProperty().addListener((obs, oldSelection, newSelection) -> { if (newSelection != null) { beginEditing(); } }); }); textField.setOnAction(evt -> { commitEdit(this.converter.fromString(textField.getText())); }); textField.focusedProperty().addListener((obs, wasFocused, isNowFocused) -> { if (!isNowFocused) { commitEdit((T)textField.getText()); setText(textField.getText()); cancelEdit(); } }); textField.addEventFilter(KeyEvent.KEY_PRESSED, event -> { if (event.getCode() == KeyCode.ESCAPE) { textField.setText(converter.toString(getItem())); cancelEdit(); event.consume(); } else if (event.getCode() == KeyCode.UP || (event.getCode() == KeyCode.TAB && event.isShiftDown())) { commitEdit((T)textField.getText()); cancelEdit(); getTableView().getSelectionModel().selectAboveCell(); event.consume(); } else if (event.getCode() == KeyCode.DOWN || (event.getCode() == KeyCode.TAB && !event.isShiftDown())) { commitEdit((T)textField.getText()); this.cancelEdit(); getTableView().getSelectionModel().selectBelowCell(); event.consume(); } }); } private void beginEditing() { int row = getTableView().getSelectionModel().getSelectedCells().get(0).getRow(); TableColumn<S, ?> column = getTableView().getColumns().get(1); Platform.runLater(() -> { getTableView().edit(row, column); textField.selectAll(); }); } public static final StringConverter<String> IDENTITY_CONVERTER = new StringConverter<String>() { @Override public String toString(String object) { if ( object == null ) return ""; else return object; } @Override public String fromString(String string) { if ( string == null ) return ""; else return string; } }; public static <S> EditOnClickCell<S, String> createStringEditCell() { return new EditOnClickCell<S, String>(IDENTITY_CONVERTER); } @Override public void startEdit() { super.startEdit(); textField.setText(converter.toString(getItem())); setContentDisplay(ContentDisplay.GRAPHIC_ONLY); textField.requestFocus(); } @Override public void cancelEdit() { super.cancelEdit(); setContentDisplay(ContentDisplay.TEXT_ONLY); } @Override public void commitEdit(T item) { // This block is necessary to support commit on losing focus, because the // baked-in mechanism // sets our editing state to false before we can intercept the loss of focus. // The default commitEdit(...) method simply bails if we are not editing... if (!isEditing() && !item.equals(getItem())) { TableView<S> table = getTableView(); if (table != null) { TableColumn<S, T> column = getTableColumn(); CellEditEvent<S, T> event = new CellEditEvent<>(table, new TablePosition<S, T>(table, getIndex(), column), TableColumn.editCommitEvent(), item); Event.fireEvent(column, event); } } super.commitEdit(item); setContentDisplay(ContentDisplay.TEXT_ONLY); } }
4,398
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
ArtistInfoWindow.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/fxui/ArtistInfoWindow.java
package net.joshuad.hypnos.fxui; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.ContextMenu; import javafx.scene.control.Label; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.scene.control.SelectionMode; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.scene.control.TableRow; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.ClipboardContent; import javafx.scene.input.Dragboard; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.TransferMode; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.stage.Modality; import javafx.stage.Stage; import net.joshuad.hypnos.Utils; import net.joshuad.hypnos.audio.AudioSystem; import net.joshuad.hypnos.fxui.DraggedTrackContainer.DragSource; import net.joshuad.hypnos.library.Album; import net.joshuad.hypnos.library.Artist; import net.joshuad.hypnos.library.Library; import net.joshuad.hypnos.library.Playlist; import net.joshuad.hypnos.library.Track; public class ArtistInfoWindow extends Stage { private static final Logger LOGGER = Logger.getLogger( ArtistInfoWindow.class.getName() ); Artist artist; TableView <Track> trackTable; TextField locationField; FXUI ui; Library library; AudioSystem audioSystem; public ArtistInfoWindow( FXUI ui, Library library, AudioSystem audioSystem ) { super(); this.ui = ui; this.library = library; this.audioSystem = audioSystem; this.initModality( Modality.NONE ); this.initOwner( ui.getMainStage() ); this.setTitle( "Album Info" ); this.setWidth( 600 ); this.setHeight( 400 ); Pane root = new Pane(); Scene scene = new Scene( root ); VBox primaryPane = new VBox(); setupPlaylistTable( primaryPane ); primaryPane.prefWidthProperty().bind( root.widthProperty() ); primaryPane.prefHeightProperty().bind( root.heightProperty() ); primaryPane.getChildren().addAll( trackTable ); root.getChildren().add( primaryPane ); setScene( scene ); scene.addEventFilter( KeyEvent.KEY_PRESSED, new EventHandler <KeyEvent>() { @Override public void handle ( KeyEvent e ) { if ( e.getCode() == KeyCode.ESCAPE && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() && !e.isAltDown() ) { hide(); e.consume(); } } }); } public void setArtist ( Artist artist ) { this.artist = artist; if ( artist != null ) { trackTable.setItems( FXCollections.observableArrayList ( artist.getAllTracks() ) ); this.setTitle( "Artist: " + artist.getName() ); } } private void setupPlaylistTable ( VBox primaryPane ) { TableColumn<Track, String> albumColumn = new TableColumn<Track, String>( "Album" ); TableColumn<Track, Integer> trackNumberColumn = new TableColumn<Track, Integer>( "#" ); TableColumn<Track, String> titleColumn = new TableColumn<Track, String>( "Title" ); TableColumn<Track, Integer> lengthColumn = new TableColumn<Track, Integer>( "Length" ); trackNumberColumn.setMaxWidth( 70000 ); albumColumn.setMaxWidth( 400000 ); titleColumn.setMaxWidth( 500000 ); lengthColumn.setMaxWidth( 90000 ); trackNumberColumn.setEditable( false ); albumColumn.setEditable( false ); titleColumn.setEditable( false ); lengthColumn.setEditable( false ); trackNumberColumn.setReorderable( false ); albumColumn.setReorderable( false ); titleColumn.setReorderable( false ); lengthColumn.setReorderable( false ); trackNumberColumn.setCellValueFactory( new PropertyValueFactory <Track, Integer>( "trackNumber" ) ); albumColumn.setCellValueFactory( new PropertyValueFactory <Track, String>( "AlbumTitle" ) ); titleColumn.setCellValueFactory( new PropertyValueFactory <Track, String>( "Title" ) ); lengthColumn.setCellValueFactory( new PropertyValueFactory <Track, Integer>( "LengthDisplay" ) ); trackNumberColumn.setCellFactory( column -> { return new TableCell <Track, Integer>() { @Override protected void updateItem ( Integer value, boolean empty ) { super.updateItem( value, empty ); if ( value == null || value.equals( Track.NO_TRACK_NUMBER ) || empty ) { setText( null ); setStyle( "" ); } else { setText( value.toString() ); } } }; }); trackTable = new TableView<Track> (); trackTable.getColumns().addAll( albumColumn, trackNumberColumn, titleColumn, lengthColumn ); trackTable.setColumnResizePolicy( TableView.CONSTRAINED_RESIZE_POLICY ); trackTable.setEditable( true ); trackTable.getSelectionModel().setSelectionMode( SelectionMode.MULTIPLE ); trackTable.prefWidthProperty().bind( primaryPane.widthProperty() ); trackTable.prefHeightProperty().bind( primaryPane.heightProperty() ); trackTable.setPlaceholder( new Label( "Empty Playlist." ) ); trackTable.setOnDragOver( event -> { Dragboard db = event.getDragboard(); if ( db.hasContent( FXUI.DRAGGED_TRACKS ) || db.hasFiles() ) { event.acceptTransferModes( TransferMode.COPY ); event.consume(); } } ); trackTable.getSelectionModel().selectedItemProperty().addListener( ( obs, oldSelection, newSelection ) -> { ui.trackSelected ( newSelection ); }); trackTable.setOnDragDropped( event -> { Dragboard db = event.getDragboard(); if ( db.hasContent( FXUI.DRAGGED_TRACKS ) ) { DraggedTrackContainer container = (DraggedTrackContainer) db.getContent( FXUI.DRAGGED_TRACKS ); switch ( container.getSource() ) { case PLAYLIST_LIST: { if ( container.getPlaylists() == null ) { LOGGER.log ( Level.INFO, "Recieved null data from playlist list, ignoring.", new NullPointerException() ); } else { List <Track> tracksToCopy = new ArrayList<Track>(); for ( Playlist playlist : container.getPlaylists() ) { if ( playlist == null ) { LOGGER.log ( Level.INFO, "Recieved null playlist from playlist list, ignoring.", new NullPointerException() ); } else { tracksToCopy.addAll( playlist.getTracks() ); } } trackTable.getItems().addAll ( tracksToCopy ); } } break; case ALBUM_LIST: { if ( container.getAlbums() == null ) { LOGGER.log ( Level.INFO, "Recieved null data from playlist list, ignoring.", new NullPointerException() ); } else { List <Track> tracksToCopy = new ArrayList<Track>(); for ( Album album : container.getAlbums() ) { if ( album == null ) { LOGGER.log ( Level.INFO, "Null album dropped in playlist window, ignoring.", new NullPointerException() ); } else { tracksToCopy.addAll( album.getTracks() ); } } trackTable.getItems().addAll ( tracksToCopy ); } } break; case ARTIST_LIST: case TRACK_LIST: case ALBUM_INFO: case HISTORY: case CURRENT_LIST: case TAG_ERROR_LIST: case QUEUE: case CURRENT_TRACK: { List <Track> tracksToCopy = container.getTracks(); trackTable.getItems().addAll( tracksToCopy ); } break; case PLAYLIST_INFO: { //Not possible; table is currently empty } break; } event.setDropCompleted( true ); event.consume(); } else if ( db.hasFiles() ) { ArrayList <Path> pathsToAdd = new ArrayList<Path> (); for ( File file : db.getFiles() ) { Path droppedPath = Paths.get( file.getAbsolutePath() ); if ( Utils.isMusicFile( droppedPath ) ) { pathsToAdd.add( droppedPath ); } else if ( Files.isDirectory( droppedPath ) ) { pathsToAdd.addAll( Utils.getAllTracksInDirectory( droppedPath ) ); } else if ( Utils.isPlaylistFile ( droppedPath ) ) { List<Path> paths = Playlist.getTrackPaths( droppedPath ); pathsToAdd.addAll( paths ); } } ArrayList <Track> tracksToAdd = new ArrayList<Track> ( pathsToAdd.size() ); for ( Path path : pathsToAdd ) { tracksToAdd.add( new Track ( path ) ); } if ( !tracksToAdd.isEmpty() ) { trackTable.getItems().addAll( tracksToAdd ); } event.setDropCompleted( true ); event.consume(); } } ); Menu lastFMMenu = new Menu( "LastFM" ); MenuItem loveMenuItem = new MenuItem ( "Love" ); MenuItem unloveMenuItem = new MenuItem ( "Unlove" ); MenuItem scrobbleMenuItem = new MenuItem ( "Scrobble" ); lastFMMenu.getItems().addAll ( loveMenuItem, unloveMenuItem, scrobbleMenuItem ); lastFMMenu.setVisible ( false ); lastFMMenu.visibleProperty().bind( ui.showLastFMWidgets ); loveMenuItem.setOnAction( ( event ) -> { ui.audioSystem.getLastFM().loveTrack( trackTable.getSelectionModel().getSelectedItem() ); }); unloveMenuItem.setOnAction( ( event ) -> { ui.audioSystem.getLastFM().unloveTrack( trackTable.getSelectionModel().getSelectedItem() ); }); scrobbleMenuItem.setOnAction( ( event ) -> { ui.audioSystem.getLastFM().scrobbleTrack( trackTable.getSelectionModel().getSelectedItem() ); }); ContextMenu contextMenu = new ContextMenu(); MenuItem playMenuItem = new MenuItem( "Play" ); MenuItem appendMenuItem = new MenuItem( "Append" ); MenuItem playNextMenuItem = new MenuItem( "Play Next" ); MenuItem enqueueMenuItem = new MenuItem( "Enqueue" ); MenuItem editTagMenuItem = new MenuItem( "Edit Tag(s)" ); MenuItem infoMenuItem = new MenuItem( "Info" ); MenuItem lyricsMenuItem = new MenuItem( "Lyrics" ); MenuItem goToAlbumMenuItem = new MenuItem( "Go to Album" ); MenuItem browseMenuItem = new MenuItem( "Browse Folder" ); Menu addToPlaylistMenuItem = new Menu( "Add to Playlist" ); contextMenu.getItems().addAll ( playMenuItem, appendMenuItem, playNextMenuItem, enqueueMenuItem, editTagMenuItem, infoMenuItem, lyricsMenuItem, goToAlbumMenuItem, browseMenuItem, addToPlaylistMenuItem, lastFMMenu ); MenuItem newPlaylistButton = new MenuItem( "<New>" ); addToPlaylistMenuItem.getItems().add( newPlaylistButton ); newPlaylistButton.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent e ) { ui.promptAndSavePlaylist ( new ArrayList <Track> ( trackTable.getSelectionModel().getSelectedItems() ) ); } }); EventHandler <ActionEvent> addToPlaylistHandler = new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { Playlist playlist = (Playlist) ((MenuItem) event.getSource()).getUserData(); ui.addToPlaylist ( trackTable.getSelectionModel().getSelectedItems(), playlist ); } }; library.getPlaylistsSorted().addListener( ( ListChangeListener.Change <? extends Playlist> change ) -> { ui.updatePlaylistMenuItems( addToPlaylistMenuItem.getItems(), addToPlaylistHandler ); }); ui.updatePlaylistMenuItems( addToPlaylistMenuItem.getItems(), addToPlaylistHandler ); trackTable.setOnKeyPressed( ( KeyEvent e ) -> { if ( e.getCode() == KeyCode.ESCAPE && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { trackTable.getSelectionModel().clearSelection(); } else if ( e.getCode() == KeyCode.Q && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { enqueueMenuItem.fire(); } else if ( e.getCode() == KeyCode.Q && e.isShiftDown() && !e.isAltDown() && !e.isControlDown() && !e.isMetaDown() ) { playNextMenuItem.fire(); } else if ( e.getCode() == KeyCode.F2 && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { editTagMenuItem.fire(); } else if ( e.getCode() == KeyCode.F3 && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { infoMenuItem.fire(); } else if ( e.getCode() == KeyCode.F3 && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { infoMenuItem.fire(); } else if ( e.getCode() == KeyCode.F4 && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { ui.openFileBrowser( trackTable.getSelectionModel().getSelectedItem().getPath() ); } else if ( e.getCode() == KeyCode.L && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { lyricsMenuItem.fire(); } else if ( e.getCode() == KeyCode.ENTER && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { playMenuItem.fire(); } else if ( e.getCode() == KeyCode.ENTER && e.isShiftDown() && !e.isAltDown() && !e.isControlDown() && !e.isMetaDown() ) { audioSystem.getCurrentList().insertTracks( 0, trackTable.getSelectionModel().getSelectedItems() ); } else if ( e.getCode() == KeyCode.ENTER && e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { appendMenuItem.fire(); } }); playNextMenuItem.setOnAction( event -> { audioSystem.getQueue().queueAllTracks( trackTable.getSelectionModel().getSelectedItems(), 0 ); }); enqueueMenuItem.setOnAction( event -> { audioSystem.getQueue().queueAllTracks( trackTable.getSelectionModel().getSelectedItems() ); }); infoMenuItem.setOnAction( event -> { ui.trackInfoWindow.setTrack( trackTable.getSelectionModel().getSelectedItem() ); ui.trackInfoWindow.show(); }); lyricsMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { ui.lyricsWindow.setTrack( trackTable.getSelectionModel().getSelectedItem() ); ui.lyricsWindow.show(); } }); goToAlbumMenuItem.setOnAction( ( event ) -> { ui.goToAlbumOfTrack ( trackTable.getSelectionModel().getSelectedItem() ); }); browseMenuItem.setOnAction( event -> { ui.openFileBrowser( trackTable.getSelectionModel().getSelectedItem().getPath() ); }); editTagMenuItem.setOnAction( event -> { ui.tagWindow.setTracks( (List<Track>)(List<?>)trackTable.getSelectionModel().getSelectedItems(), null ); ui.tagWindow.show(); }); appendMenuItem.setOnAction( event -> { ui.getCurrentListPane().currentListTable.getItems().addAll( Utils.convertTrackList( trackTable.getSelectionModel().getSelectedItems() ) ); }); playMenuItem.setOnAction( event -> { List <Track> selectedItems = new ArrayList<Track> ( trackTable.getSelectionModel().getSelectedItems() ); if ( selectedItems.size() == 1 ) { audioSystem.playItems( selectedItems ); } else if ( selectedItems.size() > 1 ) { if ( ui.okToReplaceCurrentList() ) { audioSystem.playItems( selectedItems ); } } }); trackTable.setRowFactory( tv -> { TableRow <Track> row = new TableRow <>(); row.itemProperty().addListener( (obs, oldValue, newValue ) -> { if ( newValue != null ) { row.setContextMenu( contextMenu ); } else { row.setContextMenu( null ); } }); row.setOnContextMenuRequested( event -> { goToAlbumMenuItem.setDisable( row.getItem().getAlbum() == null ); }); row.setOnMouseClicked( event -> { if ( event.getClickCount() == 2 && (!row.isEmpty()) ) { audioSystem.playTrack( row.getItem() ); } } ); row.setOnDragDetected( event -> { if ( !row.isEmpty() ) { ArrayList <Integer> indices = new ArrayList <Integer>( trackTable.getSelectionModel().getSelectedIndices() ); ArrayList <Track> tracks = new ArrayList <Track>( trackTable.getSelectionModel().getSelectedItems() ); DraggedTrackContainer dragObject = new DraggedTrackContainer( indices, tracks, null, null, null, DragSource.PLAYLIST_INFO ); Dragboard db = row.startDragAndDrop( TransferMode.COPY ); db.setDragView( row.snapshot( null, null ) ); ClipboardContent cc = new ClipboardContent(); cc.put( FXUI.DRAGGED_TRACKS, dragObject ); db.setContent( cc ); event.consume(); } }); return row; }); } }
16,320
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
LibraryAlbumPane.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/fxui/LibraryAlbumPane.java
package net.joshuad.hypnos.fxui; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.EnumMap; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.jaudiotagger.tag.FieldKey; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.scene.control.Button; import javafx.scene.control.CheckMenuItem; import javafx.scene.control.ContextMenu; import javafx.scene.control.Label; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.scene.control.SelectionMode; import javafx.scene.control.TableColumn; import javafx.scene.control.TableRow; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.Tooltip; import javafx.scene.control.TableColumn.SortType; import javafx.scene.control.TableView.ResizeFeatures; import javafx.scene.effect.ColorAdjust; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.ClipboardContent; import javafx.scene.input.Dragboard; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.TransferMode; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.text.TextAlignment; import net.joshuad.hypnos.AlphanumComparator; import net.joshuad.hypnos.Hypnos; import net.joshuad.hypnos.Persister; import net.joshuad.hypnos.AlphanumComparator.CaseHandling; import net.joshuad.hypnos.Persister.Setting; import net.joshuad.hypnos.audio.AudioSystem; import net.joshuad.hypnos.fxui.DraggedTrackContainer.DragSource; import net.joshuad.hypnos.library.Album; import net.joshuad.hypnos.library.Library; import net.joshuad.hypnos.library.Playlist; import net.joshuad.hypnos.library.Track; public class LibraryAlbumPane extends BorderPane { private static final Logger LOGGER = Logger.getLogger( LibraryArtistPane.class.getName() ); private FXUI ui; private AudioSystem audioSystem; private Library library; private HBox filterPane; TextField filterBox; TableView<Album> albumTable; //TODO: are these all actually strings? TableColumn<Album, String> artistColumn, yearColumn, addedDateColumn, albumColumn; ContextMenu columnSelectorMenu; Label emptyListLabel = new Label( "No albums loaded. To add to your library, click on the + button or drop folders here." ); Label filteredListLabel = new Label( "No albums match." ); Label noColumnsLabel = new Label( "All columns hidden." ); Label loadingListLabel = new Label( "Loading..." ); private ThrottledAlbumFilter tableFilter; private ImageView addSourceImage, filterClearImage; public LibraryAlbumPane ( FXUI ui, AudioSystem audioSystem, Library library ) { this.ui = ui; this.audioSystem = audioSystem; this.library = library; setupFilterPane(); setupTable(); filterPane.prefWidthProperty().bind( filterPane.widthProperty() ); setTop( filterPane ); setCenter( albumTable ); library.getAlbumsSorted().addListener( new ListChangeListener<Album>() { @Override public void onChanged(Change<? extends Album> arg0) { updatePlaceholders(); } }); artistColumn.visibleProperty().addListener( e -> updatePlaceholders() ); yearColumn.visibleProperty().addListener( e -> updatePlaceholders() ); addedDateColumn.visibleProperty().addListener( e -> updatePlaceholders() ); albumColumn.visibleProperty().addListener( e -> updatePlaceholders() ); resetTableSettingsToDefault(); } public void updatePlaceholders() { Platform.runLater( () -> { boolean someVisible = false; for ( TableColumn<?,?> column : albumTable.getColumns() ) { if ( column.isVisible() ) { someVisible = true; break; } } if ( !someVisible ) { albumTable.setPlaceholder( noColumnsLabel ); } else if ( library.getAlbumDisplayCache().isEmpty() ) { if ( albumTable.getPlaceholder() != emptyListLabel ) { albumTable.setPlaceholder( emptyListLabel ); } } else { if ( !albumTable.getPlaceholder().equals( filteredListLabel ) ) { albumTable.setPlaceholder( filteredListLabel ); } } }); } public void resetTableSettingsToDefault() { artistColumn.setVisible( true ); addedDateColumn.setVisible( false ); yearColumn.setVisible( true ); albumColumn.setVisible( true ); albumTable.getColumns().remove( artistColumn ); albumTable.getColumns().add( artistColumn ); albumTable.getColumns().remove( yearColumn ); albumTable.getColumns().add( yearColumn ); albumTable.getColumns().remove( addedDateColumn ); albumTable.getColumns().add( addedDateColumn ); albumTable.getColumns().remove( albumColumn ); albumTable.getColumns().add( albumColumn ); //Note: setSortType needs to be called before getSortOrder().add artistColumn.setSortType( SortType.ASCENDING ); albumColumn.setSortType( SortType.ASCENDING ); yearColumn.setSortType( SortType.ASCENDING ); addedDateColumn.setSortType( SortType.ASCENDING ); albumTable.getSortOrder().clear(); albumTable.getSortOrder().add( artistColumn ); albumTable.getSortOrder().add( yearColumn ); albumTable.getSortOrder().add( albumColumn ); artistColumn.setPrefWidth( 100 ); yearColumn.setPrefWidth( 60 ); albumColumn.setPrefWidth( 100 ); addedDateColumn.setPrefWidth ( 90 ); albumTable.getColumnResizePolicy().call( new ResizeFeatures<Album> ( albumTable, null, 0d ) ); updatePlaceholders(); } public void setupTable () { artistColumn = new TableColumn<Album, String>( "Artist" ); yearColumn = new TableColumn<Album, String>( "Year" ); albumColumn = new TableColumn<Album, String>( "Album" ); addedDateColumn = new TableColumn<Album, String> ( "Added" ); artistColumn.setComparator( new AlphanumComparator( CaseHandling.CASE_INSENSITIVE ) ); albumColumn.setComparator( new AlphanumComparator( CaseHandling.CASE_INSENSITIVE ) ); artistColumn.setCellValueFactory( cellData -> cellData.getValue().getAlbumArtistProperty() ); yearColumn.setCellValueFactory( cellData -> cellData.getValue().getYearProperty() ); albumColumn.setCellValueFactory( cellData -> cellData.getValue().getFullAlbumTitleProperty() ); addedDateColumn.setCellValueFactory( cellData -> cellData.getValue().getDateAddedStringProperty() ); albumColumn.setCellFactory( e -> new FormattedAlbumCell<> () ); columnSelectorMenu = new ContextMenu (); CheckMenuItem artistMenuItem = new CheckMenuItem ( "Show Artist Column" ); CheckMenuItem yearMenuItem = new CheckMenuItem ( "Show Year Column" ); CheckMenuItem albumMenuItem = new CheckMenuItem ( "Show Album Column" ); CheckMenuItem dateAddedMenuItem = new CheckMenuItem ( "Show Added Column" ); MenuItem defaultMenuItem = new MenuItem ( "Reset to Default View" ); artistMenuItem.setSelected( true ); yearMenuItem.setSelected( true ); albumMenuItem.setSelected( true ); dateAddedMenuItem.setSelected( false ); columnSelectorMenu.getItems().addAll( artistMenuItem, yearMenuItem, dateAddedMenuItem, albumMenuItem, defaultMenuItem ); artistColumn.setContextMenu( columnSelectorMenu ); yearColumn.setContextMenu( columnSelectorMenu ); albumColumn.setContextMenu( columnSelectorMenu ); addedDateColumn.setContextMenu( columnSelectorMenu ); artistMenuItem.selectedProperty().bindBidirectional( artistColumn.visibleProperty() ); yearMenuItem.selectedProperty().bindBidirectional( yearColumn.visibleProperty() ); albumMenuItem.selectedProperty().bindBidirectional( albumColumn.visibleProperty() ); dateAddedMenuItem.selectedProperty().bindBidirectional( addedDateColumn.visibleProperty() ); defaultMenuItem.setOnAction( e -> this.resetTableSettingsToDefault() ); albumTable = new TableView<Album>(); albumTable.getColumns().addAll( artistColumn, yearColumn, addedDateColumn, albumColumn ); albumTable.setEditable( false ); albumTable.setItems( library.getAlbumsSorted() ); albumTable.getSelectionModel().setSelectionMode( SelectionMode.MULTIPLE ); library.getAlbumsSorted().comparatorProperty().bind( albumTable.comparatorProperty() ); HypnosResizePolicy resizePolicy = new HypnosResizePolicy(); albumTable.setColumnResizePolicy( resizePolicy ); resizePolicy.registerFixedWidthColumns( yearColumn ); resizePolicy.registerFixedWidthColumns( addedDateColumn ); emptyListLabel.setPadding( new Insets( 20, 10, 20, 10 ) ); emptyListLabel.setWrapText( true ); emptyListLabel.setTextAlignment( TextAlignment.CENTER ); filteredListLabel.setPadding( new Insets( 20, 10, 20, 10 ) ); filteredListLabel.setWrapText( true ); filteredListLabel.setTextAlignment( TextAlignment.CENTER ); albumTable.setPlaceholder( emptyListLabel ); ContextMenu contextMenu = new ContextMenu(); MenuItem playMenuItem = new MenuItem( "Play" ); MenuItem appendMenuItem = new MenuItem( "Append" ); MenuItem playNextMenuItem = new MenuItem( "Play Next" ); MenuItem enqueueMenuItem = new MenuItem( "Enqueue" ); MenuItem editTagMenuItem = new MenuItem( "Edit Tag(s)" ); MenuItem sortByNewestMenuItem = new MenuItem ( "Sort by Add Date" ); MenuItem rescanMenuItem = new MenuItem ( "Rescan" ); MenuItem browseMenuItem = new MenuItem( "Browse Folder" ); Menu addToPlaylistMenuItem = new Menu( "Add to Playlist" ); MenuItem infoMenuItem = new MenuItem( "Track List" ); albumTable.setOnKeyPressed( ( KeyEvent e ) -> { if ( e.getCode() == KeyCode.ESCAPE && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { if ( filterBox.getText().length() > 0 ) { filterBox.clear(); Platform.runLater( ()-> albumTable.scrollTo( albumTable.getSelectionModel().getSelectedItem() ) ); } else { albumTable.getSelectionModel().clearSelection(); } } else if ( e.getCode() == KeyCode.Q && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { enqueueMenuItem.fire(); } else if ( e.getCode() == KeyCode.Q && e.isShiftDown() && !e.isAltDown() && !e.isControlDown() && !e.isMetaDown() ) { playNextMenuItem.fire(); } else if ( e.getCode() == KeyCode.F2 && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { editTagMenuItem.fire(); } else if ( e.getCode() == KeyCode.F3 && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { infoMenuItem.fire(); } else if ( e.getCode() == KeyCode.F4 && !e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { browseMenuItem.fire(); e.consume(); } else if ( e.getCode() == KeyCode.ENTER && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { playMenuItem.fire(); } else if ( e.getCode() == KeyCode.ENTER && e.isShiftDown() && !e.isAltDown() && !e.isControlDown() && !e.isMetaDown() ) { audioSystem.getCurrentList().insertAlbums( 0, albumTable.getSelectionModel().getSelectedItems() ); } else if ( e.getCode() == KeyCode.ENTER && e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { appendMenuItem.fire(); } else if ( e.getCode() == KeyCode.UP ) { if ( albumTable.getSelectionModel().getSelectedIndex() == 0 ) { filterBox.requestFocus(); } } }); contextMenu.getItems().addAll( playMenuItem, appendMenuItem, playNextMenuItem, enqueueMenuItem, editTagMenuItem, infoMenuItem, sortByNewestMenuItem, rescanMenuItem, browseMenuItem, addToPlaylistMenuItem ); MenuItem newPlaylistButton = new MenuItem( "<New>" ); addToPlaylistMenuItem.getItems().add( newPlaylistButton ); newPlaylistButton.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent e ) { ObservableList <Album> selectedAlbums = albumTable.getSelectionModel().getSelectedItems(); ArrayList <Track> tracks = new ArrayList <Track> (); for ( Album album : selectedAlbums ) { tracks.addAll( album.getTracks() ); } ui.promptAndSavePlaylist ( tracks ); } }); EventHandler<ActionEvent> addToPlaylistHandler = new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { Playlist playlist = (Playlist) ((MenuItem) event.getSource()).getUserData(); ArrayList <Album> albums = new ArrayList <Album> ( albumTable.getSelectionModel().getSelectedItems() ); ArrayList <Track> tracksToAdd = new ArrayList <Track> (); for ( Album album : albums ) { tracksToAdd.addAll( album.getTracks() ); } ui.addToPlaylist ( tracksToAdd, playlist ); } }; library.getPlaylistsSorted().addListener( ( ListChangeListener.Change <? extends Playlist> change ) -> { ui.updatePlaylistMenuItems( addToPlaylistMenuItem.getItems(), addToPlaylistHandler ); } ); ui.updatePlaylistMenuItems( addToPlaylistMenuItem.getItems(), addToPlaylistHandler ); playMenuItem.setOnAction( event -> { if ( ui.okToReplaceCurrentList() ) { List <Album> playMe = albumTable.getSelectionModel().getSelectedItems(); audioSystem.getCurrentList().setAndPlayAlbums( playMe ); } }); appendMenuItem.setOnAction( event -> { audioSystem.getCurrentList().appendAlbums( albumTable.getSelectionModel().getSelectedItems() ); }); playNextMenuItem.setOnAction( event -> { audioSystem.getQueue().queueAllAlbums( albumTable.getSelectionModel().getSelectedItems(), 0 ); }); enqueueMenuItem.setOnAction( event -> { audioSystem.getQueue().queueAllAlbums( albumTable.getSelectionModel().getSelectedItems() ); }); sortByNewestMenuItem.setOnAction( event -> { albumTable.getSortOrder().clear(); addedDateColumn.setSortType( SortType.DESCENDING ); albumTable.getSortOrder().add( addedDateColumn ); }); editTagMenuItem.setOnAction( event -> { List<Album> albums = albumTable.getSelectionModel().getSelectedItems(); ArrayList<Track> editMe = new ArrayList<Track>(); for ( Album album : albums ) { if ( album != null ) { editMe.addAll( album.getTracks() ); } } ui.tagWindow.setTracks( editMe, albums, FieldKey.TRACK, FieldKey.TITLE ); ui.tagWindow.show(); }); infoMenuItem.setOnAction( event -> { ui.albumInfoWindow.setAlbum( albumTable.getSelectionModel().getSelectedItem() ); ui.albumInfoWindow.show(); }); rescanMenuItem.setOnAction( event -> { library.requestRescan( albumTable.getSelectionModel().getSelectedItems() ); }); browseMenuItem.setOnAction( event -> { ui.openFileBrowser ( albumTable.getSelectionModel().getSelectedItem().getPath() ); }); albumTable.setOnDragOver( event -> { Dragboard db = event.getDragboard(); if ( db.hasFiles() ) { event.acceptTransferModes( TransferMode.COPY ); event.consume(); } }); albumTable.setOnDragDropped( event -> { Dragboard db = event.getDragboard(); if ( db.hasFiles() ) { List <File> files = db.getFiles(); for ( File file : files ) { library.addMusicRoot( file.toPath() ); } event.setDropCompleted( true ); event.consume(); } }); albumTable.getSelectionModel().selectedItemProperty().addListener( ( obs, oldSelection, newSelection ) -> { if ( newSelection != null ) { ui.albumSelected ( newSelection ); } else if ( audioSystem.getCurrentTrack() != null ) { ui.trackSelected ( audioSystem.getCurrentTrack() ); } else { //Do nothing, leave the old artwork there. We can set to null if we like that better //I don't think so though } }); albumTable.setRowFactory( tv -> { TableRow <Album> row = new TableRow <>(); row.itemProperty().addListener( (obs, oldValue, newValue ) -> { if ( newValue != null ) { row.setContextMenu( contextMenu ); } else { row.setContextMenu( null ); } }); row.setOnMouseClicked( event -> { if ( event.getClickCount() == 2 && (!row.isEmpty()) ) { if ( ui.okToReplaceCurrentList() ) { audioSystem.getCurrentList().setAndPlayAlbum( row.getItem() ); } } } ); row.setOnDragOver( event -> { Dragboard db = event.getDragboard(); if ( db.hasFiles() ) { event.acceptTransferModes( TransferMode.COPY ); event.consume(); } }); row.setOnDragDropped( event -> { Dragboard db = event.getDragboard(); if ( db.hasFiles() ) { List <File> files = db.getFiles(); for ( File file : files ) { library.addMusicRoot( file.toPath() ); } event.setDropCompleted( true ); event.consume(); } }); row.setOnDragDetected( event -> { if ( !row.isEmpty() ) { ArrayList <Album> albums = new ArrayList <Album>( albumTable.getSelectionModel().getSelectedItems() ); ArrayList <Track> tracks = new ArrayList <Track> (); for ( Album album : albums ) { if ( album != null ) { tracks.addAll( album.getTracks() ); } } DraggedTrackContainer dragObject = new DraggedTrackContainer( null, tracks, albums, null, null, DragSource.ALBUM_LIST ); Dragboard db = row.startDragAndDrop( TransferMode.COPY ); db.setDragView( row.snapshot( null, null ) ); ClipboardContent cc = new ClipboardContent(); cc.put( FXUI.DRAGGED_TRACKS, dragObject ); db.setContent( cc ); event.consume(); } }); return row; }); } public void setupFilterPane () { tableFilter = new ThrottledAlbumFilter ( library.getAlbumsFiltered() ); filterPane = new HBox(); filterBox = new TextField(); filterBox.setPrefWidth( 500000 ); filterBox.textProperty().addListener( new ChangeListener <String> () { @Override public void changed ( ObservableValue <? extends String> observable, String oldValue, String newValue ) { tableFilter.setFilter( newValue ); } }); filterBox.setOnKeyPressed( ( KeyEvent event ) -> { if ( event.getCode() == KeyCode.ESCAPE ) { event.consume(); if ( filterBox.getText().length() > 0 ) { filterBox.clear(); } else { albumTable.requestFocus(); } } else if ( event.getCode() == KeyCode.DOWN ) { event.consume(); albumTable.requestFocus(); albumTable.getSelectionModel().select( albumTable.getSelectionModel().getFocusedIndex() ); } else if ( event.getCode() == KeyCode.ENTER && !event.isAltDown() && !event.isShiftDown() && !event.isControlDown() && !event.isMetaDown() ) { event.consume(); Album playMe = albumTable.getSelectionModel().getSelectedItem(); if( playMe == null ) albumTable.getItems().get( 0 ); audioSystem.getCurrentList().setAndPlayAlbum( playMe ); } else if ( event.getCode() == KeyCode.ENTER && event.isShiftDown() && !event.isAltDown() && !event.isControlDown() && !event.isMetaDown() ) { event.consume(); Album playMe = albumTable.getSelectionModel().getSelectedItem(); if( playMe == null ) albumTable.getItems().get( 0 ); audioSystem.getQueue().queueAllAlbums( Arrays.asList( playMe ) ); } else if ( event.getCode() == KeyCode.ENTER && event.isControlDown() && !event.isAltDown() && !event.isShiftDown() && !event.isMetaDown() ) { event.consume(); Album playMe = albumTable.getSelectionModel().getSelectedItem(); if( playMe == null ) albumTable.getItems().get( 0 ); audioSystem.getCurrentList().appendAlbum( playMe ); } }); float width = 33; float height = Hypnos.getOS().isWindows() ? 28 : 26; filterBox.setPrefHeight( height ); String addLocation = "resources/add.png"; String clearLocation = "resources/clear.png"; try { double currentListControlsButtonFitWidth = 15; double currentListControlsButtonFitHeight = 15; Image image = new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( addLocation ).toFile() ) ); addSourceImage = new ImageView ( image ); addSourceImage.setFitWidth( currentListControlsButtonFitWidth ); addSourceImage.setFitHeight( currentListControlsButtonFitHeight ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to load add icon: " + addLocation, e ); } try { Image clearImage = new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( clearLocation ).toFile() ) ); filterClearImage = new ImageView ( clearImage ); filterClearImage.setFitWidth( 12 ); filterClearImage.setFitHeight( 12 ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to load clear icon: " + clearLocation, e ); } Button libraryButton = new Button( ); libraryButton.setGraphic( addSourceImage ); libraryButton.setMinSize( width, height ); libraryButton.setPrefSize( width, height ); libraryButton.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent e ) { if ( ui.libraryLocationWindow.isShowing() ) { ui.libraryLocationWindow.hide(); } else { ui.libraryLocationWindow.show(); } } } ); Button clearButton = new Button( ); clearButton.setGraphic( filterClearImage ); clearButton.setMinSize( width, height ); clearButton.setPrefSize( width, height ); clearButton.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent e ) { filterBox.setText( "" ); } }); libraryButton.setTooltip( new Tooltip( "Add or Remove Music Folders" ) ); filterBox.setTooltip ( new Tooltip ( "Filter/Search albums" ) ); clearButton.setTooltip( new Tooltip( "Clear the filter text" ) ); filterPane.getChildren().addAll( libraryButton, filterBox, clearButton ); } public void applyDarkTheme ( ColorAdjust buttonColor ) { if ( filterClearImage != null ) filterClearImage.setEffect( buttonColor ); if ( addSourceImage != null ) addSourceImage.setEffect( buttonColor ); } public void applyLightTheme () { if ( filterClearImage != null ) filterClearImage.setEffect( ui.lightThemeButtonEffect ); if ( addSourceImage != null ) addSourceImage.setEffect( ui.lightThemeButtonEffect ); } @SuppressWarnings("incomplete-switch") public void applySettingsBeforeWindowShown ( EnumMap<Persister.Setting, String> settings ) { settings.forEach( ( setting, value )-> { try { switch ( setting ) { case AL_TABLE_ARTIST_COLUMN_SHOW: artistColumn.setVisible( Boolean.valueOf ( value ) ); settings.remove ( setting ); break; case AL_TABLE_YEAR_COLUMN_SHOW: yearColumn.setVisible( Boolean.valueOf ( value ) ); settings.remove ( setting ); break; case AL_TABLE_ALBUM_COLUMN_SHOW: albumColumn.setVisible( Boolean.valueOf ( value ) ); settings.remove ( setting ); break; case AL_TABLE_ADDED_COLUMN_SHOW: addedDateColumn.setVisible( Boolean.valueOf ( value ) ); settings.remove ( setting ); break; case AL_TABLE_ARTIST_COLUMN_WIDTH: artistColumn.setPrefWidth( Double.valueOf( value ) ); settings.remove ( setting ); break; case AL_TABLE_YEAR_COLUMN_WIDTH: yearColumn.setPrefWidth( Double.valueOf( value ) ); settings.remove ( setting ); break; case AL_TABLE_ADDED_COLUMN_WIDTH: addedDateColumn.setPrefWidth( Double.valueOf( value ) ); settings.remove ( setting ); break; case AL_TABLE_ALBUM_COLUMN_WIDTH: albumColumn.setPrefWidth( Double.valueOf( value ) ); settings.remove ( setting ); break; case ALBUM_COLUMN_ORDER: { String[] order = value.split( " " ); int newIndex = 0; for ( String columnName : order ) { try { if ( columnName.equals( "artist" ) ) { albumTable.getColumns().remove( artistColumn ); albumTable.getColumns().add( newIndex, artistColumn ); } else if ( columnName.equals( "year" ) ) { albumTable.getColumns().remove( yearColumn ); albumTable.getColumns().add( newIndex, yearColumn ); } else if ( columnName.equals( "album" ) ) { albumTable.getColumns().remove( albumColumn ); albumTable.getColumns().add( newIndex, albumColumn ); } else if ( columnName.equals( "added" ) ) { albumTable.getColumns().remove( addedDateColumn ); albumTable.getColumns().add( newIndex, addedDateColumn ); } newIndex++; } catch ( Exception e ) { LOGGER.log( Level.INFO, "Unable to set album table column order: '" + value + "'", e ); } } settings.remove ( setting ); break; } case ALBUM_SORT_ORDER: { albumTable.getSortOrder().clear(); if ( !value.equals( "" ) ) { String[] order = value.split( " " ); for ( String fullValue : order ) { try { String columnName = fullValue.split( "-" )[0]; SortType sortType = SortType.valueOf( fullValue.split( "-" )[1] ); if ( columnName.equals( "artist" ) ) { albumTable.getSortOrder().add( artistColumn ); artistColumn.setSortType( sortType ); } else if ( columnName.equals( "year" ) ) { albumTable.getSortOrder().add( yearColumn ); yearColumn.setSortType( sortType ); } else if ( columnName.equals( "album" ) ) { albumTable.getSortOrder().add( albumColumn ); albumColumn.setSortType( sortType ); } else if ( columnName.equals( "added" ) ) { albumTable.getSortOrder().add( addedDateColumn ); addedDateColumn.setSortType( sortType ); } } catch ( Exception e ) { LOGGER.log( Level.INFO, "Unable to set album table sort order: '" + value + "'", e ); } } } settings.remove ( setting ); break; } } } catch ( Exception e ) { LOGGER.log( Level.INFO, "Unable to apply setting: " + setting + " to UI.", e ); } }); } public EnumMap<Persister.Setting, ? extends Object> getSettings () { EnumMap <Persister.Setting, Object> retMe = new EnumMap <Persister.Setting, Object> ( Persister.Setting.class ); String albumColumnOrderValue = ""; for ( TableColumn<Album, ?> column : albumTable.getColumns() ) { if ( column == artistColumn ) { albumColumnOrderValue += "artist "; } else if ( column == yearColumn ) { albumColumnOrderValue += "year "; } else if ( column == addedDateColumn ) { albumColumnOrderValue += "added "; } else if ( column == albumColumn ) { albumColumnOrderValue += "album "; } } retMe.put ( Setting.ALBUM_COLUMN_ORDER, albumColumnOrderValue ); String albumSortValue = ""; for ( TableColumn<Album, ?> column : albumTable.getSortOrder() ) { if ( column == artistColumn ) { albumSortValue += "artist-" + artistColumn.getSortType() + " "; } else if ( column == yearColumn ) { albumSortValue += "year-" + yearColumn.getSortType() + " "; } else if ( column == albumColumn ) { albumSortValue += "album-" + albumColumn.getSortType() + " "; } else if ( column == this.addedDateColumn ) { albumSortValue += "added-" + addedDateColumn.getSortType() + " "; } } retMe.put ( Setting.ALBUM_SORT_ORDER, albumSortValue ); retMe.put ( Setting.AL_TABLE_ARTIST_COLUMN_SHOW, artistColumn.isVisible() ); retMe.put ( Setting.AL_TABLE_YEAR_COLUMN_SHOW, yearColumn.isVisible() ); retMe.put ( Setting.AL_TABLE_ALBUM_COLUMN_SHOW, albumColumn.isVisible() ); retMe.put ( Setting.AL_TABLE_ADDED_COLUMN_SHOW, addedDateColumn.isVisible() ); retMe.put ( Setting.AL_TABLE_ARTIST_COLUMN_WIDTH, artistColumn.getPrefWidth() ); retMe.put ( Setting.AL_TABLE_YEAR_COLUMN_WIDTH, yearColumn.getPrefWidth() ); retMe.put ( Setting.AL_TABLE_ADDED_COLUMN_WIDTH, addedDateColumn.getPrefWidth() ); retMe.put ( Setting.AL_TABLE_ALBUM_COLUMN_WIDTH, albumColumn.getPrefWidth() ); return retMe; } public void focusFilter() { albumTable.requestFocus(); filterBox.requestFocus(); albumTable.getSelectionModel().clearSelection(); } }
29,050
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
ArtistImageSaveDialog.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/fxui/ArtistImageSaveDialog.java
package net.joshuad.hypnos.fxui; import java.io.File; import java.io.FileInputStream; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javafx.event.ActionEvent; import javafx.geometry.Insets; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.Modality; import javafx.stage.Stage; import net.joshuad.hypnos.Hypnos; public class ArtistImageSaveDialog extends Stage { private static final Logger LOGGER = Logger.getLogger( ArtistImageSaveDialog.class.getName() ); public enum Choice { ALL, ALBUM, TRACK, CANCEL } private Choice selectedChoice = Choice.CANCEL; CheckBox override; public ArtistImageSaveDialog ( Stage mainStage, List <Choice> choices ) { super( ); Group root = new Group(); Scene scene = new Scene( root ); VBox primaryPane = new VBox(); this.setResizable( false ); try { Image icon = new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( "resources" + File.separator + "icon.png" ).toFile() ) ); getIcons().add( icon ); } catch ( Exception e ) { LOGGER.log ( Level.INFO, "Unable to set icon on Artist Image Save Dialog.", e ); } primaryPane.setPadding( new Insets ( 10, 10, 10, 10 ) ); primaryPane.setSpacing( 20 ); setTitle( "Set Artist Image" ); initModality ( Modality.APPLICATION_MODAL ); double x = mainStage.getX() + mainStage.getWidth() / 2 - 200; double y = mainStage.getY() + mainStage.getHeight() / 2 - 100; setX ( x ); setY ( y ); HBox info = new HBox(); info.setPadding( new Insets ( 20, 0, 0, 0 ) ); Label infoLabel = new Label ( "How do you want to set the artist image? More specific fields have higher priority." ); info.getChildren().addAll( infoLabel ); HBox controls = new HBox(); override = new CheckBox ( "Overwrite all existing artist tag images" ); override.setPadding( new Insets ( 0, 0, 0, 0 ) ); controls.getChildren().addAll( override ); HBox buttons = new HBox(); buttons.setPadding( new Insets ( 10, 10, 10, 10 ) ); buttons.setSpacing( 10 ); Button all = new Button ( "All albums by this artist" ); Button album = new Button ( "This album only" ); Button track = new Button ( "This track only" ); Button cancel = new Button ( "Cancel" ); buttons.getChildren().addAll( all, album, track, cancel ); if ( !choices.contains( Choice.ALL ) ) { all.setDisable( true ); } if ( !choices.contains( Choice.ALBUM ) ) { album.setDisable( true ); } if ( !choices.contains( Choice.TRACK ) ) { track.setDisable( true ); } primaryPane.getChildren().addAll( info, controls, buttons ); root.getChildren().add( primaryPane ); setScene( scene ); all.setOnAction( ( ActionEvent e ) -> { selectedChoice = Choice.ALL; close(); }); album.setOnAction( ( ActionEvent e ) -> { selectedChoice = Choice.ALBUM; close(); }); track.setOnAction( ( ActionEvent e ) -> { selectedChoice = Choice.TRACK; close(); }); cancel.setOnAction( ( ActionEvent e ) -> { selectedChoice = Choice.CANCEL; close(); }); } public Choice getSelectedChoice () { return selectedChoice; } public boolean getOverwriteAllSelected() { return override.isSelected(); } }
3,474
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
HypnosResizePolicy.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/fxui/HypnosResizePolicy.java
package net.joshuad.hypnos.fxui; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.Vector; import javafx.geometry.Orientation; import javafx.scene.Node; import javafx.scene.control.ScrollBar; import javafx.scene.control.TableColumn; import javafx.scene.control.TableColumnBase; import javafx.scene.control.TableView; import javafx.util.Callback; /* Summary: * Min-width, Max-width, and not-resizable are respected absolutely. These take precedence over all other constraints * * total width of columns tries to be the width of the table. i.e. columns fill the table, but not past 100%. * * Programmer can register "fixed width" columns so that they tend not to change size when the table is resized but the user can directly resize them * * When the entire table's size is changed, the excess space is shared on a ratio basis between non-fixed-width, resizable columns * * When the user manually resizes columns, use that new size as the pref width for the columns * * If a single column is manually resized, the delta is shared on a ratio basis between non-fixed-width columns, but only columns the resized column's right side * * If all of the columns are set to fixed-size or no-resize, extra space is given to / taken from all fixed width columns proportionally * * If all of the columns are no-resize, then the columns will not fill the table's width exactly (except, of course, at one coincidental size). * * Finally, following the guidelines above, extra space is given to columns that aren't at their pref width and need that type of space * (negative or positive) on a proportional basis first. */ @SuppressWarnings({ "rawtypes" }) public class HypnosResizePolicy implements Callback <TableView.ResizeFeatures, Boolean> { Vector <TableColumn<?, ?>> fixedWidthColumns = new Vector <TableColumn<?, ?>> (); public void registerFixedWidthColumns ( TableColumn <?, ?> ... addMe ) { fixedWidthColumns.addAll ( Arrays.asList ( addMe ) ); } public void unregisterFixedWidthColumn ( TableColumn <?, ?> column ) { fixedWidthColumns.remove ( column ); } @Override public Boolean call ( TableView.ResizeFeatures feature ) { TableView table = feature.getTable(); if ( table == null || table.getWidth() == 0 ) return false; TableColumn columnToResize = feature.getColumn(); List <TableColumn> columns = table.getVisibleLeafColumns(); //There seem to be two modes: Either the entire table is resized, or the user is resizing a single column //This boolean will soon tell us know which mode we're in. boolean singleColumnResizeMode = false; double targetDelta = feature.getDelta(); if ( columnToResize != null && columnToResize.isResizable() ) { //Now we know we're in the mode where a single column is being resized. singleColumnResizeMode = true; //We want to grow that column by targetDelta, but making sure we stay within the bounds of min and max. double targetWidth = columnToResize.getWidth() + feature.getDelta(); if ( targetWidth >= columnToResize.getMaxWidth() ) targetWidth = columnToResize.getMaxWidth(); else if ( targetWidth <= columnToResize.getMinWidth() ) targetWidth = columnToResize.getMinWidth(); targetDelta = targetWidth - columnToResize.getWidth(); } double spaceToDistribute = calculateSpaceAvailable ( table ) - targetDelta; if ( Math.abs ( spaceToDistribute ) < 1 ) return false; //First we try to distribute the space to columns that aren't at their pref width //but always obeying not-resizable, min-width, and max-width //The space is distributed on a ratio basis, so columns that want to be bigger grow faster, etc. List <TableColumn> columnsNotAtPref = new ArrayList<> (); for ( TableColumn column : columns ) { boolean resizeThisColumn = false; //Choose to resize columns that aren't at their pref width and need the type of space we have (negative or positive) to get there //We do this pref - width > 1 thing instead of pref > width because very small differences don't matter //but they cause a bug where the column widths jump around wildly. if ( spaceToDistribute > 0 && column.getPrefWidth() - column.getWidth() > 1 ) resizeThisColumn = true; if ( spaceToDistribute < 0 && column.getWidth() - column.getPrefWidth() > 1 ) resizeThisColumn = true; //but never resize columns that aren't resizable, are the current manul resizing column //or are to the left of the current manual resize column if ( !column.isResizable() ) resizeThisColumn = false; if ( singleColumnResizeMode && column == columnToResize ) resizeThisColumn = false; if ( singleColumnResizeMode && columns.indexOf( column ) < columns.indexOf( columnToResize ) ) resizeThisColumn = false; if ( resizeThisColumn ) { columnsNotAtPref.add( column ); } } distributeSpaceRatioToPref ( columnsNotAtPref, spaceToDistribute ); //See how much space we have left after distributing to satisfy preferences. spaceToDistribute = calculateSpaceAvailable ( table ) - targetDelta; if ( Math.abs( spaceToDistribute ) >= 1 ) { //Now we distribute remaining space across the rest of the columns, excluding as follows: List <TableColumn> columnsToReceiveSpace = new ArrayList <> (); for ( TableColumn column : columns ) { boolean resizeThisColumn = true; //Never resize columns that aren't resizable if ( !column.isResizable() ) resizeThisColumn = false; //Never make columns more narrow than their min width if ( spaceToDistribute < 0 && column.getWidth() <= column.getMinWidth() ) resizeThisColumn = false; //Never make columns wider than their max width if ( spaceToDistribute > 0 && column.getWidth() >= column.getMaxWidth() ) resizeThisColumn = false; //If the extra space is the result of an individual column being resized, don't include that column //when distributing the extra space if ( singleColumnResizeMode && column == columnToResize ) resizeThisColumn = false; //Exclude fixed-width columns, for now. We may add them back in later if needed. if ( fixedWidthColumns.contains( column ) ) resizeThisColumn = false; //Exclude columns to the left of the resized column in the case of a single column manual resize if ( singleColumnResizeMode && columns.indexOf( column ) < columns.indexOf( columnToResize ) ) resizeThisColumn = false; if ( resizeThisColumn ) { columnsToReceiveSpace.add( column ); } } if ( columnsToReceiveSpace.size() == 0 ) { if ( singleColumnResizeMode ) { //If there are no eligible columns and we're doing a manual resize, we can break our fixed-width exclusion // and distribute the space to only the first fixed-width column to the right, this time allowing fixedWidth columns to be changed. for ( int k = columns.indexOf( columnToResize ) + 1 ; k < columns.size() ; k++ ) { TableColumn candidate = columns.get( k ); boolean resizeThisColumn = true; //Never resize columns that aren't resizable if ( !candidate.isResizable() ) resizeThisColumn = false; //Never make columns more narrow than their min width if ( spaceToDistribute < 0 && candidate.getWidth() <= candidate.getMinWidth() ) resizeThisColumn = false; //Never make columns wider than their max width if ( spaceToDistribute > 0 && candidate.getWidth() >= candidate.getMaxWidth() ) resizeThisColumn = false; if ( resizeThisColumn ) { columnsToReceiveSpace.add ( candidate ); //We only want one column, so we break after we find one. break; } } } else { //If we're in full table resize mode and all of the columns are set to fixed-size or no-resize, //extra space is given to / taken from all fixed width columns proportionally for ( TableColumn column : columns ) { if ( fixedWidthColumns.contains( column ) && column.isResizable() ) { columnsToReceiveSpace.add( column ); } } } } //Now we distribute the space amongst all eligible columns. It is still possible for there to be no eligible columns, in that case, nothing happens. distributeSpaceRatio ( columnsToReceiveSpace, spaceToDistribute ); } if ( singleColumnResizeMode ) { //Now if the user is manually resizing one column, we adjust that column's width to include whatever space we made / destroyed //with the above operations. //I found it is better to do this at the end when the actual space create/destroyed is known, rather than doing at the top and then //trying to get that much space from the other columns. Sometimes the other columns resist, and this creates a much smoother user experience. setColumnWidth( columnToResize, columnToResize.getWidth() + calculateSpaceAvailable ( table ) ); //If it's a manual resize, set pref-widths to these user specified widths. //The user manually set them now, so they like this size. Try to respect them on next resize. for ( TableColumn column : columns ) { column.setPrefWidth( column.getWidth() ); } } return true; } private void distributeSpaceRatioToPref ( List<TableColumn> columns, double spaceToDistribute ) { double spaceWanted = 0; for ( TableColumn column : columns ) spaceWanted += column.getPrefWidth() - column.getWidth(); if ( spaceWanted < spaceToDistribute ) { for ( TableColumn column : columns ) { double targetWidth = column.getPrefWidth(); if ( targetWidth >= column.getMaxWidth() ) targetWidth = column.getMaxWidth(); else if ( targetWidth <= column.getMinWidth() ) targetWidth = column.getMinWidth(); setColumnWidth( column, targetWidth ); } } else { for ( TableColumn column : columns ) { double targetWidth = column.getWidth() + spaceToDistribute * ( column.getPrefWidth() / spaceWanted ); if ( targetWidth >= column.getMaxWidth() ) targetWidth = column.getMaxWidth(); else if ( targetWidth <= column.getMinWidth() ) targetWidth = column.getMinWidth(); setColumnWidth( column, targetWidth ); } } } private void distributeSpaceRatio ( List<TableColumn> columns, double space ) { double totalWidth = 0; for ( TableColumn column : columns ) totalWidth += column.getWidth(); for ( TableColumn column : columns ) { double targetWidth = column.getWidth() + space * ( column.getWidth() / totalWidth ); if ( targetWidth >= column.getMaxWidth() ) targetWidth = column.getMaxWidth(); else if ( targetWidth <= column.getMinWidth() ) targetWidth = column.getMinWidth(); setColumnWidth( column, targetWidth ); } } private void setColumnWidth ( TableColumn column, double targetWidth ) { try { Method method = TableColumnBase.class.getDeclaredMethod( "doSetWidth", double.class ); method.setAccessible( true ); method.invoke( column, targetWidth ); } catch ( NoSuchMethodException | InvocationTargetException | IllegalAccessException e ) { e.printStackTrace(); } } private double calculateSpaceAvailable ( TableView table ) { List <TableColumn> columns = table.getVisibleLeafColumns(); double spaceToDistribute = table.getWidth() - getScrollbarWidth ( table ) - 4; //That -4 is annoying. I'm sure there's a way to actually get that value //See thread here: https://stackoverflow.com/questions/47852175/how-to-spread-the-total-width-amongst-all-columns-on-table-construction //Which is also implemented below in calculateSpaceAvailableNew //Unfortunately, that solution didn't work on manual resizes. for ( TableColumn column : columns ) spaceToDistribute -= column.getWidth(); return spaceToDistribute; } private double getScrollbarWidth ( TableView table ) { double scrollBarWidth = 0; Set <Node> nodes = table.lookupAll( ".scroll-bar" ); for ( final Node node : nodes ) { if ( node instanceof ScrollBar ) { ScrollBar sb = (ScrollBar) node; if ( sb.getOrientation() == Orientation.VERTICAL ) { if ( sb.isVisible() ) { scrollBarWidth = sb.getWidth(); } } } } return scrollBarWidth; } /*private double calculateSpaceAvailableNew ( TableView table ) { Region region = null; Set<Node> nodes = table.lookupAll(".clipped-container"); for (Node node : nodes) { if (node instanceof Region) { region = (Region) node; } } return region.getWidth(); }*/ }
12,648
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
ExportPlaylistPopup.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/fxui/ExportPlaylistPopup.java
package net.joshuad.hypnos.fxui; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.Optional; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Platform; import javafx.scene.Group; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.ProgressBar; import javafx.scene.control.Alert; import javafx.scene.control.ButtonBar; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.ButtonType; import javafx.scene.control.DialogPane; import javafx.scene.image.Image; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.stage.Modality; import javafx.stage.Stage; import net.joshuad.hypnos.Hypnos; import net.joshuad.hypnos.Utils; import net.joshuad.hypnos.library.Track; public class ExportPlaylistPopup extends Stage { private static final Logger LOGGER = Logger.getLogger( ExportPlaylistPopup.class.getName() ); FXUI ui; private final ProgressBar progressBar; private final Label label; private boolean doingExport = false; private boolean stopRequested = false; public ExportPlaylistPopup ( FXUI ui ) { super(); this.ui = ui; Pane root = new Pane(); Scene scene = new Scene( root ); VBox primaryPane = new VBox(); initModality( Modality.NONE ); initOwner( ui.getMainStage() ); setTitle( "Export Tracks" ); try { getIcons().add( new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( "resources" + File.separator + "icon.png" ).toFile() ) ) ); } catch ( FileNotFoundException e ) { LOGGER.log(Level.WARNING, "Unable to load program icon: resources" + File.separator + "icon.png", e ); } progressBar = new ProgressBar(); progressBar.setPrefWidth( 400 ); progressBar.setPrefHeight( 40 ); label = new Label ( "" ); primaryPane.getChildren().addAll( progressBar, label ); root.getChildren().add( primaryPane ); setScene( scene ); sizeToScene(); setResizable( false ); setOnCloseRequest( event -> { if ( doingExport ) { Optional<ButtonType> choice = confirmCancel(); if ( choice.isPresent() && choice.get() == ButtonType.YES ) { stopRequested = true; hide(); } } else { hide(); } }); } public void export ( List <Track> tracks ) { if ( doingExport ) { Platform.runLater( ()-> { ui.notifyUserError( "Currently exporting, please cancel that task or wait for it to finish." ); }); return; } doingExport = true; stopRequested = false; progressBar.progressProperty().set( 0 ); File targetFile = ui.promptUserForFolder(); if ( targetFile == null ) { doingExport = false; return; } Path targetFolder = targetFile.toPath(); this.show(); Runnable exportRunnable = ()-> { if ( !Files.isDirectory( targetFolder ) ) { Platform.runLater( ()-> { ui.alertUser( AlertType.WARNING, "Unable to Copy the following files:", "Unable to Copy Files", "Destination is not a folder" ); }); return; } String error = ""; int playlistIndex = 1; for ( Track track : tracks ) { if ( stopRequested ) break; String number = String.format( "%02d", playlistIndex ); String extension = Utils.getFileExtension( track.getPath() ); String name = track.getArtist() + " - " + track.getTitle(); String fullName = number + " - " + name + "." + extension; Path targetOut = targetFolder.resolve( fullName ); Platform.runLater( ()-> label.setText( "Exporting: " + fullName ) ); try { Files.copy( track.getPath(), targetOut ); } catch ( FileAlreadyExistsException ex ) { if ( !error.equals( "" ) ) error += "\n\n"; error += "File already exists, not overwritten: " + targetOut; } catch ( IOException ex ) { if ( !error.equals( "" ) ) error += "\n\n"; error += "Unable to save file (" + ex.getMessage() + "): " + targetOut; } playlistIndex++; progressBar.progressProperty().setValue( playlistIndex / (double)tracks.size() ); } if ( !error.equals( "" ) ) { final String finalError = error; Platform.runLater( ()-> { ui.alertUser( AlertType.WARNING, "Unable to Copy the following files:", "Unable to Copy Files", finalError ); }); } doingExport = false; }; Thread t = new Thread ( exportRunnable ); t.setDaemon( true ); t.start(); } private Optional <ButtonType> confirmCancel () { Alert alert = new Alert( AlertType.CONFIRMATION ); double x = getX() + getWidth() / 2 - 220; //It'd be nice to use alert.getWidth() / 2, but it's NAN now. double y = getY() + getHeight() / 2 - 50; alert.setX( x ); alert.setY( y ); alert.setDialogPane( new DialogPane() { protected Node createDetailsButton () { return new Pane(); } @Override protected Node createButtonBar () { //This lets me specify my own button order below ButtonBar node = (ButtonBar) super.createButtonBar(); node.setButtonOrder( ButtonBar.BUTTON_ORDER_NONE ); return node; } }); FXUI.setAlertWindowIcon ( alert ); ui.applyCurrentTheme ( alert ); alert.getDialogPane().getButtonTypes().addAll( ButtonType.YES, ButtonType.NO, ButtonType.CANCEL ); alert.getDialogPane().setContentText( "Cancel Export?" ); alert.getDialogPane().setExpandableContent( new Group() ); alert.getDialogPane().setExpanded( false ); alert.getDialogPane().setGraphic( alert.getDialogPane().getGraphic() ); alert.setTitle( "Cancel Export?" ); alert.setHeaderText( null ); return alert.showAndWait(); } }
5,808
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
ImagesPanel.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/fxui/ImagesPanel.java
package net.joshuad.hypnos.fxui; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.ByteBuffer; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; import javafx.application.Platform; import javafx.beans.property.SimpleBooleanProperty; import javafx.collections.ListChangeListener; import javafx.embed.swing.SwingFXUtils; import javafx.event.ActionEvent; import javafx.scene.control.ContextMenu; import javafx.scene.control.Label; import javafx.scene.control.MenuItem; import javafx.scene.control.SplitPane; import javafx.scene.image.Image; import javafx.scene.input.ContextMenuEvent; import javafx.scene.input.DataFormat; import javafx.scene.input.Dragboard; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.input.TransferMode; import javafx.scene.layout.BorderPane; import javafx.stage.FileChooser; import net.joshuad.hypnos.CurrentListTrack; import net.joshuad.hypnos.Hypnos; import net.joshuad.hypnos.HypnosURLS; import net.joshuad.hypnos.Utils; import net.joshuad.hypnos.audio.AudioSystem; import net.joshuad.hypnos.audio.AudioSystem.RepeatMode; import net.joshuad.hypnos.audio.AudioSystem.ShuffleMode; import net.joshuad.hypnos.audio.AudioSystem.StopReason; import net.joshuad.hypnos.library.Album; import net.joshuad.hypnos.library.Artist; import net.joshuad.hypnos.library.Library; import net.joshuad.hypnos.library.Track; import net.joshuad.hypnos.library.Track.ArtistTagImagePriority; import net.joshuad.hypnos.audio.PlayerListener; public class ImagesPanel extends SplitPane implements PlayerListener { static final DataFormat textContentFormat = DataFormat.lookupMimeType( "text/plain" ); private static final Logger LOGGER = Logger.getLogger( ImagesPanel.class.getName() ); ResizableImageView albumImage; ResizableImageView artistImage; BorderPane albumImagePane; BorderPane artistImagePane; Track currentImagesTrack = null; Album currentImagesAlbum = null; FXUI ui; AudioSystem audioSystem; Library library; public ImagesPanel( FXUI ui, AudioSystem audioSystem, Library library ) { this.ui = ui; this.library = library; this.audioSystem = audioSystem; setupAlbumImage(); setupArtistImage(); getItems().addAll( albumImagePane, artistImagePane ); startImageLoaderThread(); audioSystem.addPlayerListener ( this ); audioSystem.getCurrentList().getItems().addListener ( new ListChangeListener<CurrentListTrack> () { @Override public void onChanged ( Change <? extends CurrentListTrack> arg0 ) { if ( audioSystem.getCurrentList().getItems().size() == 0 ) { currentListCleared(); } } } ); } private void setupAlbumImage () { ContextMenu menu = new ContextMenu(); MenuItem setImage = new MenuItem ( "Set Album Image" ); MenuItem exportImage = new MenuItem ( "Export Album Image" ); MenuItem searchForAlbumImage = new MenuItem ( "Search for Album Image" ); Label dragAndDropLabel = new Label ( "Drop Album Image Here" ); dragAndDropLabel.getStyleClass().add( "dragAndDropLabel" ); menu.getItems().addAll( setImage, exportImage, searchForAlbumImage ); setImage.setOnAction( ( ActionEvent event ) -> { Track track = currentImagesTrack; if ( track == null ) return; FileChooser fileChooser = new FileChooser(); FileChooser.ExtensionFilter fileExtensions = new FileChooser.ExtensionFilter( "Image Files", Arrays.asList( "*.jpg", "*.jpeg", "*.png" ) ); fileChooser.getExtensionFilters().add( fileExtensions ); fileChooser.setTitle( "Set Album Image" ); File targetFile = fileChooser.showOpenDialog( ui.getMainStage() ); if ( targetFile == null ) return; track.setAndSaveAlbumImage ( targetFile.toPath(), audioSystem ); setImages ( currentImagesTrack ); //We set it to current because it might've changed since we assigned Track track. }); searchForAlbumImage.setOnAction( ( ActionEvent event ) -> { String artist = null; String album = null; if ( currentImagesTrack != null ) { artist = currentImagesTrack.getArtist(); album = currentImagesTrack.getAlbumTitle(); } else if ( currentImagesAlbum != null ) { artist = currentImagesAlbum.getAlbumArtist(); album = currentImagesTrack.getAlbumTitle(); } if ( artist != null && album != null ) { artist = artist.replaceAll( "&", "and" ); album = album.replaceAll( "&", "and" ); ui.openWebBrowser( HypnosURLS.DDG_IMAGE_SEARCH + artist + "+" + album ); } }); exportImage.setOnAction( ( ActionEvent event ) -> { Track track = currentImagesTrack; if ( track == null ) return; FileChooser fileChooser = new FileChooser(); FileChooser.ExtensionFilter fileExtensions = new FileChooser.ExtensionFilter( "Image Files", Arrays.asList( "*.png" ) ); fileChooser.getExtensionFilters().add( fileExtensions ); fileChooser.setTitle( "Export Album Image" ); fileChooser.setInitialFileName( "album.png" ); File targetFile = fileChooser.showSaveDialog( ui.getMainStage() ); if ( targetFile == null ) return; if ( !targetFile.toString().toLowerCase().endsWith(".png") ) { targetFile = targetFile.toPath().resolveSibling ( targetFile.getName() + ".png" ).toFile(); } try { BufferedImage bImage = SwingFXUtils.fromFXImage( albumImage.getImage(), null ); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); ImageIO.write( bImage, "png", byteStream ); byte[] imageBytes = byteStream.toByteArray(); byteStream.close(); Utils.saveImageToDisk( targetFile.toPath(), imageBytes ); } catch ( IOException e ) { ui.notifyUserError ( "Unable to export image. See log for more information." ); LOGGER.log( Level.WARNING, "Unable to export album image.", e ); } }); albumImagePane = new BorderPane(); albumImagePane.setMinWidth( 0 ); albumImagePane.getStyleClass().add( "artpane" ); albumImagePane.setOnContextMenuRequested( ( ContextMenuEvent e ) -> { boolean disableMenus = ( currentImagesTrack == null ); setImage.setDisable( disableMenus ); exportImage.setDisable( disableMenus ); searchForAlbumImage.setDisable( disableMenus ); menu.show( albumImagePane, e.getScreenX(), e.getScreenY() ); }); albumImagePane.addEventHandler( MouseEvent.MOUSE_PRESSED, ( MouseEvent e ) -> { menu.hide(); }); albumImagePane.setOnMouseClicked( event -> { if ( event.getButton() == MouseButton.PRIMARY ) { ui.goToAlbumOfTrack(this.currentImagesTrack); } }); albumImagePane.setOnDragOver( event -> { event.acceptTransferModes( TransferMode.COPY ); event.consume(); }); albumImagePane.setOnDragEntered ( event -> { albumImagePane.getChildren().clear( ); albumImagePane.setCenter( dragAndDropLabel ); }); albumImagePane.setOnDragExited( event -> { albumImagePane.getChildren().clear( ); albumImagePane.setCenter( albumImage ); }); albumImagePane.setOnDragDone( event -> { albumImagePane.getChildren().clear( ); albumImagePane.setCenter( albumImage ); }); albumImagePane.setOnDragDropped( event -> { event.setDropCompleted( true ); event.consume(); Track track = currentImagesTrack; if ( track == null ) return; Dragboard db = event.getDragboard(); if ( db.hasFiles() ) { List <File> files = db.getFiles(); for ( File file : files ) { if ( Utils.isImageFile( file ) ) { try { track.setAndSaveAlbumImage ( file.toPath(), audioSystem ); break; } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to set album image from file: " + file.toString(), e ); } } } setImages ( currentImagesTrack ); } else { byte[] buffer = getImageBytesFromDragboard( db ); if ( buffer != null ) { track.setAndSaveAlbumImage( buffer, audioSystem ); } else { String url = ""; if ( db.getContentTypes().contains( textContentFormat ) ) { url = (String)db.getContent( textContentFormat ) + "\n\n"; } String message = "Cannot save image from dropped source.\n\n" + url + "Try saving the image to disk and dragging from disk rather than web."; LOGGER.log( Level.WARNING, message.replaceAll( "\n\n", " " ), new NullPointerException() ); ui.notifyUserError( message ); } setImages ( currentImagesTrack ); } }); } private Track requestedTrack; private Album requestedAlbum; private void startImageLoaderThread() { Thread imageLoader = new Thread() { public void run() { while ( true ) { if ( requestedTrack != null ) { Track loadMeTrack = requestedTrack; Album loadMeAlbum = requestedAlbum; requestedTrack = null; requestedAlbum = null; Image albumImage = loadMeTrack.getAlbumCoverImage(); Image artistImage = loadMeTrack.getArtistImage(); SimpleBooleanProperty imagesDisplayed = new SimpleBooleanProperty ( false ); Platform.runLater( () -> { setAlbumImage( albumImage ); setArtistImage( artistImage ); currentImagesTrack = loadMeTrack; currentImagesAlbum = loadMeAlbum; imagesDisplayed.setValue( true ); }); while ( !imagesDisplayed.getValue() ) { try { Thread.sleep ( 10 ); } catch ( InterruptedException e ) {} } } try { Thread.sleep ( 100 ); } catch ( InterruptedException e ) {} } } }; imageLoader.setName ( "Image Panel Loader" ); imageLoader.setDaemon( true ); imageLoader.start(); } private void setupArtistImage () { ContextMenu menu = new ContextMenu(); MenuItem setArtistImage = new MenuItem ( "Set Artist Image" ); MenuItem setAlbumArtistImage = new MenuItem ( "Set Artist Image for this Album" ); MenuItem setTrackArtistImage = new MenuItem ( "Set Artist Image for this Track" ); MenuItem exportImage = new MenuItem ( "Export Image" ); MenuItem searchForArtistImage = new MenuItem ( "Search for Artist Image" ); menu.getItems().addAll( setArtistImage, setAlbumArtistImage, setTrackArtistImage, exportImage, searchForArtistImage ); artistImagePane = new BorderPane(); artistImagePane.setMinWidth( 0 ); artistImagePane.getStyleClass().add( "artpane" ); Label dragAndDropLabel = new Label ( "Drop Artist Image Here" ); dragAndDropLabel.getStyleClass().add( "dragAndDropLabel" ); searchForArtistImage.setOnAction( ( ActionEvent event ) -> { String artist = null; String year = null; if ( currentImagesTrack != null ) { artist = currentImagesTrack.getArtist(); year = currentImagesTrack.getYear(); } else if ( currentImagesAlbum != null ) { artist = currentImagesAlbum.getAlbumArtist(); year = currentImagesTrack.getYear(); } if ( artist != null && year != null ) { artist = artist.replaceAll( "&", "and" ); year = year.replaceAll( "&", "and" ); ui.openWebBrowser( HypnosURLS.DDG_IMAGE_SEARCH + artist + "+" + year ); } }); artistImagePane.setOnContextMenuRequested( ( ContextMenuEvent e ) -> { boolean disableAllMenus = false; boolean disableAlbum = true; boolean disableArtist = true; if ( currentImagesTrack == null ) { disableAllMenus = true; } else if ( currentImagesTrack.getAlbum() != null ) { disableAlbum = false; if ( library.isArtistDirectory( currentImagesTrack.getAlbum().getPath().getParent() ) ) { disableArtist = false; } } setTrackArtistImage.setDisable( disableAllMenus ); searchForArtistImage.setDisable ( disableAllMenus ); setAlbumArtistImage.setDisable( disableAllMenus || disableAlbum ); setArtistImage.setDisable( disableAllMenus || disableArtist ); exportImage.setDisable( disableAllMenus ); menu.show( artistImagePane, e.getScreenX(), e.getScreenY() ); }); artistImagePane.setOnMouseClicked( event -> { if ( event.getButton() == MouseButton.PRIMARY ) { ui.goToArtistOfTrack(this.currentImagesTrack); } }); exportImage.setOnAction( ( ActionEvent event ) -> { Track track = currentImagesTrack; if ( track == null ) return; FileChooser fileChooser = new FileChooser(); FileChooser.ExtensionFilter fileExtensions = new FileChooser.ExtensionFilter( "Image Files", Arrays.asList( "*.png" ) ); fileChooser.getExtensionFilters().add( fileExtensions ); fileChooser.setTitle( "Export Artist Image" ); fileChooser.setInitialFileName( "artist.png" ); File targetFile = fileChooser.showSaveDialog( ui.getMainStage() ); if ( targetFile == null ) return; if ( !targetFile.toString().toLowerCase().endsWith(".png") ) { targetFile = targetFile.toPath().resolveSibling ( targetFile.getName() + ".png" ).toFile(); } try { BufferedImage bImage = SwingFXUtils.fromFXImage( artistImage.getImage(), null ); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); ImageIO.write( bImage, "png", byteStream ); byte[] imageBytes = byteStream.toByteArray(); byteStream.close(); Utils.saveImageToDisk( targetFile.toPath(), imageBytes ); } catch ( IOException e ) { ui.notifyUserError ( e.getClass().getCanonicalName() + ": Unable to export image. See log for more information." ); LOGGER.log( Level.WARNING, "Unable to export artist image.", e ); } }); FileChooser fileChooser = new FileChooser(); FileChooser.ExtensionFilter fileExtensions = new FileChooser.ExtensionFilter( "Image Files", Arrays.asList( "*.jpg", "*.jpeg", "*.png" ) ); fileChooser.getExtensionFilters().add( fileExtensions ); fileChooser.setTitle( "Set Artist Image" ); setTrackArtistImage.setOnAction( ( ActionEvent e ) -> { Track track = currentImagesTrack; if ( track == null ) return; File imageFile = fileChooser.showOpenDialog( ui.getMainStage() ); if ( imageFile == null ) return; Track.saveArtistImageToTag ( track.getPath().toFile(), imageFile.toPath(), ArtistTagImagePriority.TRACK, false, audioSystem ); setImages ( currentImagesTrack ); }); setAlbumArtistImage.setOnAction( ( ActionEvent e ) -> { Track track = currentImagesTrack; if ( track == null ) return; File imageFile = fileChooser.showOpenDialog( ui.getMainStage() ); if ( imageFile == null ) return; try { byte[] buffer = Files.readAllBytes( imageFile.toPath() ); //REFACTOR: put this code in a function, it's duplciated below. if ( track.getAlbum() == null ) return; Path albumPath = track.getAlbum().getPath(); Utils.saveImageToDisk( albumPath.resolve( "artist.png" ), buffer ); setImages ( currentImagesTrack ); Thread workerThread = new Thread ( () -> { try ( DirectoryStream <Path> stream = Files.newDirectoryStream( albumPath ) ) { for ( Path child : stream ) { if ( Utils.isMusicFile( child ) ) { Track.saveArtistImageToTag ( child.toFile(), buffer, ArtistTagImagePriority.ALBUM, false, audioSystem ); } } } catch ( IOException e3 ) { LOGGER.log( Level.WARNING, "Unable to get directory listing, artist tags not updated for album: " + albumPath, e3 ); } Platform.runLater( () -> setImages ( currentImagesTrack ) ); }); workerThread.setName ( "Album Artist Image Tag Saver" ); workerThread.setDaemon( true ); workerThread.start(); } catch ( Exception e2 ) { LOGGER.log( Level.WARNING, "Unable to load image data from file: " + imageFile, e2 ); } }); setArtistImage.setOnAction( ( ActionEvent e ) -> { Track track = currentImagesTrack; if ( track == null ) return; File imageFile = fileChooser.showOpenDialog( ui.getMainStage() ); if ( imageFile == null ) return; try { byte[] buffer = Files.readAllBytes( imageFile.toPath() ); //REFACTOR: put this code in a function, it's duplicated below. if ( !library.isArtistDirectory( currentImagesTrack.getAlbum().getPath().getParent() ) ) return; Path artistPath = track.getAlbum().getPath().getParent(); Utils.saveImageToDisk( artistPath.resolve( "artist.png" ), buffer ); setImages ( currentImagesTrack ); Thread workerThread = new Thread ( () -> { try ( DirectoryStream <Path> stream = Files.newDirectoryStream( artistPath ) ) { for ( Path child : stream ) { if ( Utils.isMusicFile( child ) ) { Track.saveArtistImageToTag ( child.toFile(), buffer, ArtistTagImagePriority.GENERAL, false, audioSystem ); } } } catch ( IOException e3 ) { LOGGER.log( Level.WARNING, "Unable to get directory listing, artist tags not updated for album: " + artistPath, e3 ); } Platform.runLater( () -> setImages ( currentImagesTrack ) ); }); workerThread.setName ( "Album Artist Image Tag Saver" ); workerThread.setDaemon( true ); workerThread.start(); } catch ( Exception e2 ) { LOGGER.log( Level.WARNING, "Unable to load image data from file: " + imageFile, e2 ); } }); artistImagePane.addEventHandler( MouseEvent.MOUSE_PRESSED, ( MouseEvent e ) -> { menu.hide(); }); artistImagePane.setOnDragOver( event -> { event.acceptTransferModes( TransferMode.COPY ); event.consume(); }); artistImagePane.setOnDragEntered ( event -> { artistImagePane.getChildren().clear( ); artistImagePane.setCenter( dragAndDropLabel ); }); artistImagePane.setOnDragExited( event -> { artistImagePane.getChildren().clear( ); artistImagePane.setCenter( artistImage ); }); artistImagePane.setOnDragDone( event -> { artistImagePane.getChildren().clear( ); artistImagePane.setCenter( artistImage ); }); artistImagePane.setOnDragDropped( event -> { Track track = currentImagesTrack; if ( track == null ) return; Dragboard db = event.getDragboard(); if ( db.hasFiles() ) { List <File> files = db.getFiles(); for ( File file : files ) { if ( Utils.isImageFile( file ) ) { try { byte[] buffer = Files.readAllBytes( file.toPath() ); promptAndSaveArtistImage ( buffer ); break; } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to set artist image from file: " + file.toString(), e ); } } } } else { byte[] buffer = getImageBytesFromDragboard( db ); if ( buffer != null ) { promptAndSaveArtistImage ( buffer ); } else { String url = ""; if ( db.getContentTypes().contains( textContentFormat ) ) { url = (String)db.getContent( textContentFormat ) + "\n\n"; } String message = "Cannot pull image from dropped source.\n\n" + url + "Try saving the image to disk and dragging from disk rather than web."; LOGGER.log( Level.WARNING, message.replaceAll( "\n\n", " " ), new NullPointerException() ); ui.notifyUserError( message ); } } event.setDropCompleted( true ); event.consume(); }); } private void promptAndSaveArtistImage ( byte[] buffer ) { Track targetTrack = currentImagesTrack; if ( targetTrack != null ) { Path albumPath = targetTrack.getAlbum().getPath(); Path artistPath = null; if ( albumPath != null && library.isArtistDirectory( albumPath.getParent() ) ) { artistPath = albumPath.getParent(); } List <ArtistImageSaveDialog.Choice> choices = new ArrayList<>(); if ( artistPath != null ) { choices.add ( ArtistImageSaveDialog.Choice.ALL ); } if ( albumPath != null ) { choices.add ( ArtistImageSaveDialog.Choice.ALBUM ); } if ( currentImagesAlbum == null ) { choices.add ( ArtistImageSaveDialog.Choice.TRACK ); } ArtistImageSaveDialog prompt = new ArtistImageSaveDialog ( ui.getMainStage(), choices ); //TODO: Make this part of ArtistImageSaveDialog String darkSheet = ui.fileToStylesheetString( ui.darkStylesheet ); if ( darkSheet == null ) { LOGGER.log( Level.INFO, "Unable to load dark style sheet, alert will not look right." + ui.darkStylesheet.toString(), new NullPointerException() ); } else { if ( ui.isDarkTheme() ) { prompt.getScene().getStylesheets().add( darkSheet ); } else { prompt.getScene().getStylesheets().remove( darkSheet ); } } prompt.showAndWait(); ArtistImageSaveDialog.Choice choice = prompt.getSelectedChoice(); boolean overwriteAll = prompt.getOverwriteAllSelected(); switch ( choice ) { case CANCEL: break; case ALL: Utils.saveImageToDisk( artistPath.resolve( "artist.png" ), buffer ); setImages ( currentImagesTrack ); //PENDING: What about ID3 tags? Set them only if they're not already set? break; case ALBUM: //REFACTOR: put this code in a function, it's duplicated above. Utils.saveImageToDisk( albumPath.resolve( "artist.png" ), buffer ); setImages ( currentImagesTrack ); Thread workerThread = new Thread ( () -> { try ( DirectoryStream <Path> stream = Files.newDirectoryStream( albumPath ) ) { for ( Path child : stream ) { if ( Utils.isMusicFile( child ) ) { Track.saveArtistImageToTag ( child.toFile(), buffer, ArtistTagImagePriority.ALBUM, overwriteAll, audioSystem ); } } } catch ( IOException e ) { LOGGER.log( Level.WARNING, "Unable to list files in directory, artist tags not updated for album: " + albumPath, e ); } Platform.runLater( () -> setImages ( currentImagesTrack ) ); }); workerThread.setName ( "Artist Image Tag Saver" ); workerThread.setDaemon( true ); workerThread.start(); break; case TRACK: Track.saveArtistImageToTag ( targetTrack.getPath().toFile(), buffer, ArtistTagImagePriority.TRACK, overwriteAll, audioSystem ); setImages ( currentImagesTrack ); break; } } } private void setImages ( Track track ) { setImages ( track, null ); } private void setImages ( Album album ) { if ( album.getTracks() != null && album.getTracks().size() > 0 ) { setImages ( album.getTracks().get( 0 ), album ); } } private void setImages ( Artist artist ) { if ( artist.getAllTracks().size() > 0 ) { setImages ( artist.getAllTracks().get( 0 ) ); } } private void clearImages() { requestedTrack = null; requestedAlbum = null; currentImagesTrack = null; currentImagesAlbum = null; Platform.runLater( () -> { setAlbumImage ( null ); setArtistImage ( null ); }); } private void setImages ( Track track, Album album ) { if ( track != null && Files.exists( track.getPath() ) ) { requestedTrack = track; requestedAlbum = album; } else if ( track == null && currentImagesTrack != null ) { setImages ( currentImagesTrack ); } else { requestedTrack = null; requestedAlbum = null; currentImagesTrack = null; currentImagesAlbum = null; setAlbumImage ( null ); setArtistImage ( null ); } } private void setAlbumImage ( Image image ) { if ( image == null ) { albumImagePane.setCenter( null ); } else { try { albumImage = new ResizableImageView( image ); albumImage.setSmooth(true); albumImage.setCache(true); albumImage.setPreserveRatio( true ); albumImagePane.setCenter( albumImage ); } catch ( Exception e ) { albumImagePane.setCenter( null ); } } } private void setArtistImage ( Image image ) { try { artistImage = new ResizableImageView( image ); artistImage.setSmooth(true); artistImage.setCache(true); artistImage.setPreserveRatio( true ); artistImagePane.setCenter( artistImage ); } catch ( Exception e ) { artistImagePane.setCenter( null ); } } private byte[] getImageBytesFromDragboard ( Dragboard db ) { byte[] retMe = null; if ( db.getContentTypes().contains( textContentFormat ) ) { URL url; try { String file = (String) db.getContent( textContentFormat ); file = file.replaceAll( "\\?.*$", "" );//Get rid of everything after ? in a url, because who cares about arguments if ( Utils.hasImageExtension( file ) ) { url = new URL( file ); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try ( InputStream is = url.openStream () ) { byte[] byteChunk = new byte [ 4096 ]; int n; while ( (n = is.read( byteChunk )) > 0 ) { baos.write( byteChunk, 0, n ); } retMe = baos.toByteArray(); } catch ( IOException e ) { LOGGER.log( Level.WARNING, "Unable to pull image from internet (" + db.getContent( textContentFormat ) + ")", e ); } } else { LOGGER.log( Level.INFO, "Received drop of a non-image file, ignored: " + db.getContent( textContentFormat ), new Exception() ); } } catch ( MalformedURLException e1 ) { LOGGER.log( Level.INFO, "Unable to parse url: " + db.getContent( textContentFormat ), e1 ); } } if ( retMe == null ) { DataFormat byteBufferFormat = null; for ( DataFormat format : db.getContentTypes() ) { //Stupidly, DataFormat.lookupMimeType( "application/octet-stream" ) does not work. //But this does. if ( "application/octet-stream".equals( format.getIdentifiers().toArray()[0] ) ) { byteBufferFormat = format; } } if ( byteBufferFormat != null ) { retMe = ((ByteBuffer)db.getContent( byteBufferFormat )).array(); if ( retMe.length < 100 ) retMe = null; //This is a hack. } retMe = ((ByteBuffer)db.getContent( byteBufferFormat )).array(); } return retMe; } public void libraryCleared () { Platform.runLater(() -> { if ( audioSystem.getCurrentList().getItems().isEmpty() ) { if ( audioSystem.isPlaying() ) { setImages ( audioSystem.getCurrentTrack() ); } else { clearImages(); } } }); } public void currentListCleared() { if ( Hypnos.getLibrary().getAlbumData().isEmpty() && Hypnos.getLibrary().getTrackData().isEmpty() ) { if ( audioSystem.isPlaying() ) { setImages ( audioSystem.getCurrentTrack() ); } else { clearImages(); } } } public void trackSelected ( Track selected ) { setImages ( selected ); } public void albumSelected ( Album selected ) { setImages ( selected ); } public void artistSelected ( Artist artist ) { setImages ( artist ); } @Override public void playerStopped ( Track track, StopReason reason ) { if ( audioSystem.getCurrentList().getItems().isEmpty() && Hypnos.getLibrary().getAlbumData().isEmpty() && Hypnos.getLibrary().getTrackData().isEmpty() ) { clearImages(); } } @Override public void playerStarted ( Track track ) { setImages( track ); } @Override public void playerUnpaused () { setImages( audioSystem.getCurrentTrack() ); } @Override public void playerPositionChanged ( int positionMS, int lengthMS ) {} @Override public void playerPaused () {} @Override public void playerVolumeChanged ( double newVolumePercent ) {} @Override public void playerShuffleModeChanged ( ShuffleMode newMode ) {} @Override public void playerRepeatModeChanged ( RepeatMode newMode ) {} public void refreshImages () { setImages ( currentImagesTrack, currentImagesAlbum ); } public Track getCurrentImagesTrack () { return currentImagesTrack; } }
27,759
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
InfoFilterHybrid.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/fxui/InfoFilterHybrid.java
package net.joshuad.hypnos.fxui; import java.io.FileInputStream; import java.util.logging.Level; import java.util.logging.Logger; import javafx.beans.property.StringProperty; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.effect.ColorAdjust; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import net.joshuad.hypnos.Hypnos; public class InfoFilterHybrid extends BorderPane { private static final Logger LOGGER = Logger.getLogger( LibraryArtistPane.class.getName() ); private Label info; private TextField filter; private HBox filterBox; private Button clearButton; private boolean hasHover = false; private boolean editing = false; private boolean hasFocus = false; private boolean switchOnHover = false; private boolean registeredSceneFilter = false; private ImageView filterClearImage; //Used for the text box and for the associated filtered tableview private EventHandler <? super KeyEvent> textBoxKeyFilter = ( KeyEvent e ) -> { if ( e.getCode() == KeyCode.ESCAPE ) { if ( getText().length() > 0 ) { e.consume(); clearFilterText(); } else { e.consume(); stopEditing(); } } }; private EventHandler <KeyEvent> tableKeyFilter = ( KeyEvent e ) -> { if ( e.getCode() == KeyCode.ESCAPE ) { stopEditing(); e.consume(); } }; public InfoFilterHybrid( FXUI ui ) { super(); info = new Label ( ); filter = new TextField (); clearButton = new Button (); clearButton.setMinSize ( 33, 26 ); try { Image clearImage = new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( "resources/clear.png" ).toFile() ) ); filterClearImage = new ImageView ( clearImage ); filterClearImage.setFitWidth( 12 ); filterClearImage.setFitHeight( 12 ); clearButton.setGraphic( filterClearImage ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to load clear icon: resources/clear.png", e ); clearButton.setText( "X" ); //TODO: Do this in other places that have a clear button or an add button, why not? } clearButton.setOnAction( ( ActionEvent e ) -> { stopEditing(); }); filterBox = new HBox(); filterBox.getChildren().addAll( filter, clearButton ); filter.prefWidthProperty().bind( filterBox.widthProperty().subtract( clearButton.widthProperty() ) ); //info.setPrefHeight( 30 ); info.setAlignment( Pos.CENTER ); //filter.setPrefHeight( 30 ); filter.addEventFilter( KeyEvent.KEY_PRESSED, textBoxKeyFilter ); setCenter ( info ); hoverProperty().addListener( ( observable, hadHover, hasHover ) -> { this.hasHover = hasHover; updateDisplay(); }); focusedProperty().addListener( ( observable, hadFocus, hasFocus ) -> { this.hasFocus = hasFocus; updateDisplay(); }); layoutBoundsProperty().addListener( ( observable, wasVisible, isVisible ) -> { //We have to do this now instead of in the constructor because the scene is null //during construction. This may not be the best place, but it works for me. if ( !registeredSceneFilter ) { registeredSceneFilter = true; this.getScene().addEventFilter( MouseEvent.MOUSE_CLICKED, evt -> { if ( !inHierarchy( evt.getPickResult().getIntersectedNode(), this ) ) { mouseClickedSomewhereElse(); } }); } }); setOnMouseClicked ( ( MouseEvent e ) -> beginEditing() ); filter.setOnMouseClicked ( ( MouseEvent e ) -> beginEditing() ); info.setOnMouseClicked ( ( MouseEvent e ) -> beginEditing() ); } public void applyButtonColorAdjust ( ColorAdjust buttonColor ) { if ( filterClearImage != null ) filterClearImage.setEffect( buttonColor ); } public String getText () { return filter.getText(); } public void setText ( String string ) { if ( string == null ) string = ""; filter.setText( string ); editing = false; updateDisplay(); } public void clearFilterText() { filter.clear(); updateDisplay(); } public void setInfoText ( String text ) { info.setText( text ); } public boolean isFilterMode() { if ( getCenter() == filter ) return true; else return false; } public void beginEditing() { editing = true; updateDisplay(); this.requestFocus(); filter.requestFocus(); } public void stopEditing() { editing = false; hasHover = false; hasFocus = false; filter.clear(); updateDisplay(); info.requestFocus(); } public StringProperty textProperty() { return filter.textProperty(); } private void updateDisplay() { if ( ( hasHover && switchOnHover ) || editing || hasFocus || filter.getText().length() > 0 ) { setCenter( filterBox ); } else { setCenter( info ); } } public TextField getFilter() { return filter; } public void mouseClickedSomewhereElse() { if ( filter.getText().length() == 0 ) editing = false; hasFocus = false; updateDisplay(); } public boolean inHierarchy( Node node, Node potentialHierarchyElement ) { if (potentialHierarchyElement == null) { return true; } while (node != null) { if (node == potentialHierarchyElement) { return true; } node = node.getParent(); } return false; } public void setFilteredTable ( TableView <?> table ) { if ( table != null ) { table.removeEventFilter( KeyEvent.KEY_PRESSED, tableKeyFilter ); } table.addEventFilter( KeyEvent.KEY_PRESSED, tableKeyFilter ); } }
5,845
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
TrackFieldPair.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/fxui/TrackFieldPair.java
package net.joshuad.hypnos.fxui; public class TrackFieldPair { String label; Object value; public TrackFieldPair ( String label, Object value ) { this.label = label; this.value = value; } public String getLabel() { return label; } public Object getValue() { return value; } }
300
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
DraggedTrackContainer.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/fxui/DraggedTrackContainer.java
package net.joshuad.hypnos.fxui; import java.io.Serializable; import java.util.List; import net.joshuad.hypnos.library.Album; import net.joshuad.hypnos.library.Artist; import net.joshuad.hypnos.library.Playlist; import net.joshuad.hypnos.library.Track; public class DraggedTrackContainer implements Serializable { private static final long serialVersionUID = 1L; public enum DragSource { CURRENT_LIST, ARTIST_LIST, ALBUM_LIST, TRACK_LIST, PLAYLIST_LIST, TAG_ERROR_LIST, PLAYLIST_INFO, ALBUM_INFO, QUEUE, HISTORY, CURRENT_TRACK } private List<Track> tracks; private List<Integer> indices; private List<Album> albums; private List<Artist> artists; private List<Playlist> playlists; private DragSource source; public DraggedTrackContainer( List<Integer> indices, List<Track> tracks, List<Album> albums, List<Playlist> playlists, List<Artist> artists, DragSource source ) { this.indices = indices; this.source = source; this.tracks = tracks; this.albums = albums; this.artists = artists; this.playlists = playlists; } public List<Integer> getIndices() { return indices; } public DragSource getSource() { return source; } public List<Artist> getArtists() { return artists; } public List<Track> getTracks() { return tracks; } public List<Album> getAlbums() { return albums; } public List<Playlist> getPlaylists() { return playlists; } }
1,427
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
AlbumInfoWindow.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/fxui/AlbumInfoWindow.java
package net.joshuad.hypnos.fxui; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javafx.collections.ListChangeListener; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ContextMenu; import javafx.scene.control.Label; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.scene.control.SelectionMode; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.scene.control.TableRow; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.image.Image; import javafx.scene.input.ClipboardContent; import javafx.scene.input.Dragboard; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.TransferMode; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.Priority; import javafx.scene.layout.VBox; import javafx.stage.Modality; import javafx.stage.Stage; import net.joshuad.hypnos.Hypnos; import net.joshuad.hypnos.Utils; import net.joshuad.hypnos.audio.AudioSystem; import net.joshuad.hypnos.fxui.DraggedTrackContainer.DragSource; import net.joshuad.hypnos.library.Album; import net.joshuad.hypnos.library.Library; import net.joshuad.hypnos.library.Playlist; import net.joshuad.hypnos.library.Track; public class AlbumInfoWindow extends Stage { private static final Logger LOGGER = Logger.getLogger( AlbumInfoWindow.class.getName() ); Album album; TableView <Track> trackTable; TextField locationField; FXUI ui; AudioSystem audioSystem; Library library; Button browseButton; public AlbumInfoWindow( FXUI ui, Library library, AudioSystem audioSystem ) { super(); this.ui = ui; this.library = library; this.audioSystem = audioSystem; this.initModality( Modality.NONE ); this.initOwner( ui.getMainStage() ); this.setTitle( "Album Info" ); this.setWidth( 700 ); Pane root = new Pane(); Scene scene = new Scene( root ); VBox primaryPane = new VBox(); try { getIcons().add( new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( "resources" + File.separator + "icon.png" ).toFile() ) ) ); } catch ( FileNotFoundException e ) { LOGGER.log( Level.WARNING, "Unable to load program icon: resources/icon.png", e ); } setupAlbumTable( primaryPane ); Label label = new Label ( "Location: " ); label.setAlignment( Pos.CENTER_RIGHT ); locationField = new TextField(); locationField.setEditable( false ); locationField.setMaxWidth( Double.MAX_VALUE ); HBox.setHgrow( locationField, Priority.ALWAYS ); browseButton = new Button( "Browse" ); browseButton.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { ui.openFileBrowser( album.getPath() ); } }); HBox locationBox = new HBox(); locationBox.getChildren().addAll( label, locationField, browseButton ); label.prefHeightProperty().bind( locationBox.heightProperty() ); locationBox.prefWidthProperty().bind( primaryPane.widthProperty() ); primaryPane.getChildren().addAll( locationBox, trackTable ); primaryPane.prefWidthProperty().bind( root.widthProperty() ); primaryPane.prefHeightProperty().bind( root.heightProperty() ); setWidth ( 700 ); setHeight ( 500 ); root.getChildren().add( primaryPane ); setScene( scene ); scene.addEventFilter( KeyEvent.KEY_PRESSED, new EventHandler <KeyEvent>() { @Override public void handle ( KeyEvent e ) { if ( e.getCode() == KeyCode.ESCAPE && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() && !e.isAltDown() ) { hide(); e.consume(); } } }); } public void setAlbum ( Album album ) { this.album = album; trackTable.setItems( album.getTracks() ); locationField.setText( album.getPath().toString() ); } private void setupAlbumTable ( VBox primaryPane ) { TableColumn<Track, Integer> trackNumberColumn = new TableColumn<Track, Integer>( "#" ); TableColumn<Track, String> titleColumn = new TableColumn<Track, String>( "Title" ); TableColumn<Track, Integer> lengthColumn = new TableColumn<Track, Integer>( "Length" ); TableColumn<Track, String> fileColumn = new TableColumn<Track, String>( "Filename" ); TableColumn<Track, String> encodingColumn = new TableColumn<Track, String>( "Encoding" ); trackNumberColumn.setMaxWidth( 70000 ); titleColumn.setMaxWidth( 500000 ); lengthColumn.setMaxWidth( 90000 ); fileColumn.setMaxWidth( 500000 ); encodingColumn.setMaxWidth( 180000 ); trackNumberColumn.setEditable( false ); titleColumn.setEditable( false ); lengthColumn.setEditable( false ); fileColumn.setEditable( false ); encodingColumn.setEditable( false ); trackNumberColumn.setReorderable( false ); titleColumn.setReorderable( false ); lengthColumn.setReorderable( false ); fileColumn.setReorderable( false ); encodingColumn.setReorderable( false ); trackNumberColumn.setCellValueFactory( new PropertyValueFactory <Track, Integer>( "trackNumber" ) ); titleColumn.setCellValueFactory( new PropertyValueFactory <Track, String>( "Title" ) ); lengthColumn.setCellValueFactory( new PropertyValueFactory <Track, Integer>( "LengthDisplay" ) ); fileColumn.setCellValueFactory( new PropertyValueFactory <Track, String>( "Filename" ) ); encodingColumn.setCellValueFactory( new PropertyValueFactory <Track, String>( "ShortEncodingString" ) ); trackNumberColumn.setCellFactory( column -> { return new TableCell <Track, Integer>() { @Override protected void updateItem ( Integer value, boolean empty ) { super.updateItem( value, empty ); if ( value == null || value.equals( Track.NO_TRACK_NUMBER ) || empty ) { setText( null ); setStyle( "" ); } else { setText( value.toString() ); } } }; } ); trackTable = new TableView<Track> (); trackTable.getColumns().addAll( trackNumberColumn, titleColumn, lengthColumn, fileColumn, encodingColumn ); trackTable.setColumnResizePolicy( TableView.CONSTRAINED_RESIZE_POLICY ); trackTable.setEditable( true ); trackTable.getSelectionModel().setSelectionMode( SelectionMode.MULTIPLE ); trackTable.getSelectionModel().selectedItemProperty().addListener( ( obs, oldSelection, newSelection ) -> { ui.trackSelected ( newSelection ); }); trackTable.prefWidthProperty().bind( primaryPane.widthProperty() ); trackTable.prefHeightProperty().bind( primaryPane.heightProperty() ); Menu lastFMMenu = new Menu( "LastFM" ); MenuItem loveMenuItem = new MenuItem ( "Love" ); MenuItem unloveMenuItem = new MenuItem ( "Unlove" ); MenuItem scrobbleMenuItem = new MenuItem ( "Scrobble" ); lastFMMenu.getItems().addAll ( loveMenuItem, unloveMenuItem, scrobbleMenuItem ); lastFMMenu.setVisible ( false ); lastFMMenu.visibleProperty().bind( ui.showLastFMWidgets ); loveMenuItem.setOnAction( ( event ) -> { ui.audioSystem.getLastFM().loveTrack( trackTable.getSelectionModel().getSelectedItem() ); }); unloveMenuItem.setOnAction( ( event ) -> { ui.audioSystem.getLastFM().unloveTrack( trackTable.getSelectionModel().getSelectedItem() ); }); scrobbleMenuItem.setOnAction( ( event ) -> { ui.audioSystem.getLastFM().scrobbleTrack( trackTable.getSelectionModel().getSelectedItem() ); }); ContextMenu contextMenu = new ContextMenu(); MenuItem playMenuItem = new MenuItem( "Play" ); MenuItem appendMenuItem = new MenuItem( "Append" ); MenuItem playNextMenuItem = new MenuItem( "Play Next" ); MenuItem enqueueMenuItem = new MenuItem( "Enqueue" ); MenuItem editTagMenuItem = new MenuItem( "Edit Tag(s)" ); MenuItem infoMenuItem = new MenuItem( "Info" ); MenuItem lyricsMenuItem = new MenuItem( "Lyrics" ); Menu addToPlaylistMenuItem = new Menu( "Add to Playlist" ); contextMenu.getItems().addAll ( playMenuItem, appendMenuItem, playNextMenuItem, enqueueMenuItem, editTagMenuItem, infoMenuItem, lyricsMenuItem, addToPlaylistMenuItem, lastFMMenu ); MenuItem newPlaylistButton = new MenuItem( "<New>" ); addToPlaylistMenuItem.getItems().add( newPlaylistButton ); newPlaylistButton.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent e ) { ui.promptAndSavePlaylist ( new ArrayList <Track> ( trackTable.getSelectionModel().getSelectedItems() ) ); } }); EventHandler <ActionEvent> addToPlaylistHandler = new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { Playlist playlist = (Playlist) ((MenuItem) event.getSource()).getUserData(); ui.addToPlaylist ( trackTable.getSelectionModel().getSelectedItems(), playlist ); } }; library.getPlaylistsSorted().addListener( ( ListChangeListener.Change <? extends Playlist> change ) -> { ui.updatePlaylistMenuItems( addToPlaylistMenuItem.getItems(), addToPlaylistHandler ); }); ui.updatePlaylistMenuItems( addToPlaylistMenuItem.getItems(), addToPlaylistHandler ); playNextMenuItem.setOnAction( event -> { audioSystem.getQueue().queueAllTracks( trackTable.getSelectionModel().getSelectedItems(), 0 ); }); enqueueMenuItem.setOnAction( event -> { audioSystem.getQueue().queueAllTracks( trackTable.getSelectionModel().getSelectedItems() ); }); editTagMenuItem.setOnAction( event -> { ui.tagWindow.setTracks( (List<Track>)(List<?>)trackTable.getSelectionModel().getSelectedItems(), null ); ui.tagWindow.show(); }); appendMenuItem.setOnAction( event -> { audioSystem.getCurrentList().appendTracks ( trackTable.getSelectionModel().getSelectedItems() ); }); infoMenuItem.setOnAction( event -> { ui.trackInfoWindow.setTrack( trackTable.getSelectionModel().getSelectedItem() ); ui.trackInfoWindow.show(); }); lyricsMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { ui.lyricsWindow.setTrack( trackTable.getSelectionModel().getSelectedItem() ); ui.lyricsWindow.show(); } }); playMenuItem.setOnAction( event -> { List <Track> selectedItems = new ArrayList<Track> ( trackTable.getSelectionModel().getSelectedItems() ); if ( selectedItems.size() == 1 ) { if (Utils.isMusicFile(selectedItems.get(0).getPath()) ) { audioSystem.playTrack( selectedItems.get(0) ); } else { ui.notifyUserError("Error reading track from disk, cannot play: " + selectedItems.get(0).getPath()); } } else if ( selectedItems.size() > 1 ) { if ( ui.okToReplaceCurrentList() ) { audioSystem.playItems( selectedItems ); } } }); trackTable.setOnKeyPressed( ( KeyEvent e ) -> { if ( e.getCode() == KeyCode.ESCAPE && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { trackTable.getSelectionModel().clearSelection(); } else if ( e.getCode() == KeyCode.Q && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { enqueueMenuItem.fire(); } else if ( e.getCode() == KeyCode.Q && e.isShiftDown() && !e.isAltDown() && !e.isControlDown() && !e.isMetaDown() ) { playNextMenuItem.fire(); } else if ( e.getCode() == KeyCode.F2 && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { editTagMenuItem.fire(); } else if ( e.getCode() == KeyCode.F3 && !e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { infoMenuItem.fire(); e.consume(); } else if ( e.getCode() == KeyCode.F4 && !e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { browseButton.fire(); e.consume(); } else if ( e.getCode() == KeyCode.L && !e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { lyricsMenuItem.fire(); e.consume(); } else if ( e.getCode() == KeyCode.ENTER && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { playMenuItem.fire(); } else if ( e.getCode() == KeyCode.ENTER && e.isShiftDown() && !e.isAltDown() && !e.isControlDown() && !e.isMetaDown() ) { audioSystem.getCurrentList().insertTracks( 0, trackTable.getSelectionModel().getSelectedItems() ); } else if ( e.getCode() == KeyCode.ENTER && e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { appendMenuItem.fire(); } }); trackTable.setRowFactory( tv -> { TableRow <Track> row = new TableRow <>(); row.itemProperty().addListener( (obs, oldValue, newValue ) -> { if ( newValue != null ) { row.setContextMenu( contextMenu ); } else { row.setContextMenu( null ); } }); row.setOnMouseClicked( event -> { if ( event.getClickCount() == 2 && (!row.isEmpty()) ) { if (Utils.isMusicFile(row.getItem().getPath()) ) { audioSystem.playTrack( row.getItem(), false ); } else { ui.notifyUserError("Error reading track from disk, cannot play: " + row.getItem().getPath() ); } } } ); row.setOnDragDetected( event -> { if ( !row.isEmpty() ) { ArrayList <Integer> indices = new ArrayList <Integer>( trackTable.getSelectionModel().getSelectedIndices() ); ArrayList <Track> tracks = new ArrayList <Track>( trackTable.getSelectionModel().getSelectedItems() ); DraggedTrackContainer dragObject = new DraggedTrackContainer( indices, tracks, null, null, null, DragSource.ALBUM_INFO ); Dragboard db = row.startDragAndDrop( TransferMode.COPY ); db.setDragView( row.snapshot( null, null ) ); ClipboardContent cc = new ClipboardContent(); cc.put( FXUI.DRAGGED_TRACKS, dragObject ); db.setContent( cc ); event.consume(); } }); return row; }); } }
14,103
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
ThrottledArtistFilter.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/fxui/ThrottledArtistFilter.java
package net.joshuad.hypnos.fxui; import java.text.Normalizer; import java.util.ArrayList; import javafx.application.Platform; import javafx.collections.transformation.FilteredList; import net.joshuad.hypnos.library.Artist; public class ThrottledArtistFilter { private String requestedFilter = ""; private long timeRequestMadeMS = 0; private Thread filterThread; private boolean interruptFiltering = false; private String currentAppliedFilter = ""; private FilteredList <? extends Artist> filteredList; public ThrottledArtistFilter ( FilteredList <? extends Artist> filteredList ) { this.filteredList = filteredList; filterThread = new Thread ( () -> { while ( true ) { String filter = requestedFilter; if ( !filter.equals( currentAppliedFilter ) ) { if ( System.currentTimeMillis() >= timeRequestMadeMS + 100 ) { interruptFiltering = false; Platform.runLater(()->setPredicate( filter )); currentAppliedFilter = filter; } } try { Thread.sleep( 25 ); } catch ( InterruptedException e ) {} } }); filterThread.setName( "Throttled Track Filter" ); filterThread.setDaemon( true ); filterThread.start(); } public void setFilter ( String filter ) { if ( filter == null ) filter = ""; timeRequestMadeMS = System.currentTimeMillis(); this.requestedFilter = filter; interruptFiltering = true; } private void setPredicate ( String filterText ) { filteredList.setPredicate( ( Artist artist ) -> { if ( interruptFiltering ) return true; if ( filterText.isEmpty() ) return true; ArrayList <String> matchableText = new ArrayList <String>(); matchableText.add( artist.getName().toLowerCase() ); if ( artist.getName().matches( ".*[^\\p{ASCII}]+.*" ) ) { matchableText.add( Normalizer.normalize( artist.getName(), Normalizer.Form.NFD ) .replaceAll( "[^\\p{ASCII}]", "" ).toLowerCase() ); } String[] lowerCaseFilterTokens = filterText.toLowerCase().split( "\\s+" ); for ( String token : lowerCaseFilterTokens ) { boolean tokenMatches = false; for ( String test : matchableText ) { if ( test.contains( token ) ) { tokenMatches = true; } } if ( !tokenMatches ) { return false; } } return true; }); } }
2,293
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
HistoryWindow.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/fxui/HistoryWindow.java
package net.joshuad.hypnos.fxui; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javafx.beans.property.ReadOnlyObjectWrapper; import javafx.beans.value.ObservableValue; import javafx.collections.ListChangeListener; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.ContextMenu; import javafx.scene.control.Label; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.scene.control.SelectionMode; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.scene.control.TableRow; import javafx.scene.control.TableView; import javafx.scene.control.TableColumn.CellDataFeatures; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.image.Image; import javafx.scene.input.ClipboardContent; import javafx.scene.input.Dragboard; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.TransferMode; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.scene.text.TextAlignment; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.util.Callback; import net.joshuad.hypnos.Hypnos; import net.joshuad.hypnos.audio.AudioSystem; import net.joshuad.hypnos.fxui.DraggedTrackContainer.DragSource; import net.joshuad.hypnos.library.Library; import net.joshuad.hypnos.library.Playlist; import net.joshuad.hypnos.library.Track; public class HistoryWindow extends Stage { private static final Logger LOGGER = Logger.getLogger( HistoryWindow.class.getName() ); private TableView <Track> historyTable; public HistoryWindow ( FXUI ui, Library library, AudioSystem audioSystem ) { super(); initModality( Modality.NONE ); initOwner( ui.getMainStage() ); setTitle( "History" ); setWidth( 600 ); setHeight( 400 ); try { getIcons().add( new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( "resources" + File.separator + "icon.png" ).toFile() ) ) ); } catch ( FileNotFoundException e ) { LOGGER.log( Level.WARNING, "Unable to load program icon: resources/icon.png", e ); } Pane root = new Pane(); Scene scene = new Scene( root ); VBox primaryPane = new VBox(); historyTable = new TableView<Track>(); Label emptyLabel = new Label( "History is empty." ); emptyLabel.setPadding( new Insets( 20, 10, 20, 10 ) ); emptyLabel.setWrapText( true ); emptyLabel.setTextAlignment( TextAlignment.CENTER ); historyTable.getSelectionModel().selectedItemProperty().addListener( ( obs, oldSelection, newSelection ) -> { ui.trackSelected ( newSelection ); }); historyTable.setColumnResizePolicy( TableView.CONSTRAINED_RESIZE_POLICY ); historyTable.setPlaceholder( emptyLabel ); historyTable.setItems( audioSystem.getHistory().getItems() ); historyTable.getSelectionModel().setSelectionMode( SelectionMode.MULTIPLE ); TableColumn<Track, Integer> numberColumn = new TableColumn<Track, Integer>( "#" ); TableColumn<Track, String> artistColumn = new TableColumn<Track, String>( "Artist" ); TableColumn<Track, String> albumColumn = new TableColumn<Track, String>( "Album" ); TableColumn<Track, String> titleColumn = new TableColumn<Track, String>( "Title" ); numberColumn.setMaxWidth( 10000 ); artistColumn.setMaxWidth( 30000 ); albumColumn.setMaxWidth ( 30000 ); titleColumn.setMaxWidth ( 30000 ); Menu lastFMMenu = new Menu( "LastFM" ); MenuItem loveMenuItem = new MenuItem ( "Love" ); MenuItem unloveMenuItem = new MenuItem ( "Unlove" ); MenuItem scrobbleMenuItem = new MenuItem ( "Scrobble" ); lastFMMenu.getItems().addAll ( loveMenuItem, unloveMenuItem, scrobbleMenuItem ); lastFMMenu.setVisible ( false ); lastFMMenu.visibleProperty().bind( ui.showLastFMWidgets ); loveMenuItem.setOnAction( ( event ) -> { audioSystem.getLastFM().loveTrack( historyTable.getSelectionModel().getSelectedItem() ); }); unloveMenuItem.setOnAction( ( event ) -> { audioSystem.getLastFM().unloveTrack( historyTable.getSelectionModel().getSelectedItem() ); }); scrobbleMenuItem.setOnAction( ( event ) -> { audioSystem.getLastFM().scrobbleTrack( historyTable.getSelectionModel().getSelectedItem() ); }); ContextMenu contextMenu = new ContextMenu(); MenuItem playMenuItem = new MenuItem( "Play" ); MenuItem appendMenuItem = new MenuItem( "Append" ); MenuItem playNextMenuItem = new MenuItem( "Play Next" ); MenuItem enqueueMenuItem = new MenuItem( "Enqueue" ); MenuItem editTagMenuItem = new MenuItem( "Edit Tag(s)" ); MenuItem infoMenuItem = new MenuItem( "Info" ); MenuItem lyricsMenuItem = new MenuItem( "Lyrics" ); MenuItem goToAlbumMenuItem = new MenuItem( "Go to Album" ); MenuItem browseMenuItem = new MenuItem( "Browse Folder" ); Menu addToPlaylistMenuItem = new Menu( "Add to Playlist" ); MenuItem removeMenuItem = new MenuItem( "Remove from History" ); contextMenu.getItems().addAll( playMenuItem, appendMenuItem, playNextMenuItem, enqueueMenuItem, editTagMenuItem, infoMenuItem, lyricsMenuItem, goToAlbumMenuItem, browseMenuItem, addToPlaylistMenuItem, lastFMMenu, removeMenuItem ); MenuItem newPlaylistButton = new MenuItem( "<New>" ); historyTable.setOnKeyPressed( ( KeyEvent e ) -> { if ( e.getCode() == KeyCode.ESCAPE && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { if ( historyTable.getSelectionModel().getSelectedItems().size() > 0 ) { historyTable.getSelectionModel().clearSelection(); e.consume(); } else { this.hide(); } } else if ( e.getCode() == KeyCode.Q && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { enqueueMenuItem.fire(); e.consume(); } else if ( e.getCode() == KeyCode.G && e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { goToAlbumMenuItem.fire(); } else if ( e.getCode() == KeyCode.Q && e.isShiftDown() && !e.isAltDown() && !e.isControlDown() && !e.isMetaDown() ) { playNextMenuItem.fire(); e.consume(); } else if ( e.getCode() == KeyCode.F2 && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { editTagMenuItem.fire(); e.consume(); } else if ( e.getCode() == KeyCode.F3 && !e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { infoMenuItem.fire(); e.consume(); } else if ( e.getCode() == KeyCode.F4 && !e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { browseMenuItem.fire(); e.consume(); } else if ( e.getCode() == KeyCode.L && !e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { lyricsMenuItem.fire(); e.consume(); } else if ( e.getCode() == KeyCode.ENTER && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { playMenuItem.fire(); e.consume(); } else if ( e.getCode() == KeyCode.ENTER && e.isShiftDown() && !e.isAltDown() && !e.isControlDown() && !e.isMetaDown() ) { audioSystem.getCurrentList().insertTracks( 0, historyTable.getSelectionModel().getSelectedItems() ); } else if ( e.getCode() == KeyCode.ENTER && e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { appendMenuItem.fire(); e.consume(); } else if ( e.getCode() == KeyCode.DELETE && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { removeMenuItem.fire(); e.consume(); } }); historyTable.setRowFactory( tv -> { TableRow <Track> row = new TableRow <>(); row.itemProperty().addListener( (obs, oldValue, newValue ) -> { if ( newValue != null ) { row.setContextMenu( contextMenu ); } else { row.setContextMenu( null ); } }); row.setOnContextMenuRequested( event -> { goToAlbumMenuItem.setDisable( row.getItem().getAlbum() == null ); }); row.setOnMouseClicked( event -> { if ( event.getClickCount() == 2 && (!row.isEmpty()) ) { audioSystem.playTrack( row.getItem(), false ); } }); row.setOnDragDetected( event -> { if ( !row.isEmpty() ) { ArrayList <Integer> indices = new ArrayList <Integer>( historyTable.getSelectionModel().getSelectedIndices() ); ArrayList <Track> tracks = new ArrayList <Track>( historyTable.getSelectionModel().getSelectedItems() ); DraggedTrackContainer dragObject = new DraggedTrackContainer( indices, tracks, null, null, null, DragSource.HISTORY ); Dragboard db = row.startDragAndDrop( TransferMode.COPY ); db.setDragView( row.snapshot( null, null ) ); ClipboardContent cc = new ClipboardContent(); cc.put( FXUI.DRAGGED_TRACKS, dragObject ); db.setContent( cc ); event.consume(); } } ); return row; }); addToPlaylistMenuItem.getItems().add( newPlaylistButton ); newPlaylistButton.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent e ) { ui.promptAndSavePlaylist ( historyTable.getSelectionModel().getSelectedItems() ); } }); EventHandler<ActionEvent> addToPlaylistHandler = new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { Playlist playlist = (Playlist) ((MenuItem) event.getSource()).getUserData(); ui.addToPlaylist ( historyTable.getSelectionModel().getSelectedItems(), playlist ); } }; library.getPlaylistsSorted().addListener( ( ListChangeListener.Change <? extends Playlist> change ) -> { ui.updatePlaylistMenuItems( addToPlaylistMenuItem.getItems(), addToPlaylistHandler ); }); ui.updatePlaylistMenuItems( addToPlaylistMenuItem.getItems(), addToPlaylistHandler ); playMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { List <Track> selectedItems = new ArrayList<Track> ( historyTable.getSelectionModel().getSelectedItems() ); if ( selectedItems.size() == 1 ) { audioSystem.playItems( selectedItems ); } else if ( selectedItems.size() > 1 ) { if ( ui.okToReplaceCurrentList() ) { audioSystem.playItems( selectedItems ); } } } }); playNextMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { audioSystem.getQueue().queueAllTracks( historyTable.getSelectionModel().getSelectedItems(), 0 ); } }); enqueueMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { audioSystem.getQueue().queueAllTracks( historyTable.getSelectionModel().getSelectedItems() ); } }); infoMenuItem.setOnAction( event -> { ui.trackInfoWindow.setTrack( historyTable.getSelectionModel().getSelectedItem() ); ui.trackInfoWindow.show(); }); lyricsMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { ui.lyricsWindow.setTrack( historyTable.getSelectionModel().getSelectedItem() ); ui.lyricsWindow.show(); } }); appendMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { audioSystem.getCurrentList().appendTracks ( historyTable.getSelectionModel().getSelectedItems() ); } }); editTagMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { List<Track> tracks = historyTable.getSelectionModel().getSelectedItems(); ui.tagWindow.setTracks( tracks, null ); ui.tagWindow.show(); } }); removeMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { synchronized ( historyTable.getItems() ) { List<Integer> selectedIndices = historyTable.getSelectionModel().getSelectedIndices(); ArrayList<Integer> removeMeIndices = new ArrayList<Integer> ( selectedIndices ); for ( int k = removeMeIndices.size() - 1; k >= 0 ; k-- ) { //REFACTOR: probably put the remove code somewhere else. historyTable.getItems().remove( removeMeIndices.get( k ).intValue() ); } } } }); goToAlbumMenuItem.setOnAction( ( event ) -> { ui.goToAlbumOfTrack ( historyTable.getSelectionModel().getSelectedItem() ); }); browseMenuItem.setOnAction( new EventHandler <ActionEvent>() { // PENDING: This is the better way, once openjdk and openjfx supports // it: getHostServices().showDocument(file.toURI().toString()); @Override public void handle ( ActionEvent event ) { ui.openFileBrowser( historyTable.getSelectionModel().getSelectedItem().getPath() ); } }); numberColumn.setCellValueFactory( new Callback <CellDataFeatures <Track, Integer>, ObservableValue <Integer>>() { @Override public ObservableValue <Integer> call ( CellDataFeatures <Track, Integer> p ) { return new ReadOnlyObjectWrapper <Integer>( p.getValue(), "number" ); } }); numberColumn.setCellFactory( new Callback <TableColumn <Track, Integer>, TableCell <Track, Integer>>() { @Override public TableCell <Track, Integer> call ( TableColumn <Track, Integer> param ) { return new TableCell <Track, Integer>() { @Override protected void updateItem ( Integer item, boolean empty ) { super.updateItem( item, empty ); if ( this.getTableRow() != null && item != null ) { setText( this.getTableRow().getIndex() + 1 + "" ); } else { setText( "" ); } } }; } }); numberColumn.setSortable(false); artistColumn.setSortable(false); albumColumn.setSortable(false); titleColumn.setSortable(false); artistColumn.setCellValueFactory( new PropertyValueFactory <Track, String>( "Artist" ) ); titleColumn.setCellValueFactory( new PropertyValueFactory <Track, String>( "Title" ) ); albumColumn.setCellValueFactory( new PropertyValueFactory <Track, String>( "FullAlbumTitle" ) ); historyTable.getColumns().addAll( numberColumn, artistColumn, albumColumn, titleColumn ); historyTable.prefWidthProperty().bind( root.widthProperty() ); historyTable.prefHeightProperty().bind( root.heightProperty() ); primaryPane.getChildren().addAll( historyTable ); root.getChildren().add( primaryPane ); setScene( scene ); } }
14,642
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
ResizableImageView.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/fxui/ResizableImageView.java
package net.joshuad.hypnos.fxui; import javafx.scene.image.Image; import javafx.scene.image.ImageView; class ResizableImageView extends ImageView { ResizableImageView ( Image image ) { super ( image ); setPreserveRatio( true ); } @Override public double minWidth(double height) { return 100; } @Override public double prefWidth(double height) { Image I = getImage(); if (I == null) { return minWidth(height); } return I.getWidth(); } @Override public double maxWidth(double height) { return 10000; } @Override public double minHeight(double width) { return 0; } @Override public double prefHeight(double width) { Image I = getImage(); if (I == null) { return minHeight(width); } return I.getHeight(); } @Override public double maxHeight(double width) { return 10000; } @Override public boolean isResizable() { return true; } @Override public void resize(double width, double height) { setFitWidth(width); setFitHeight(height); } }
1,007
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
ProgressIndicatorBar.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/fxui/ProgressIndicatorBar.java
package net.joshuad.hypnos.fxui; import javafx.geometry.Pos; import javafx.scene.control.Label; import javafx.scene.control.ProgressBar; import javafx.scene.layout.StackPane; class ProgressIndicatorBar extends StackPane { final private ProgressBar bar = new ProgressBar(); final private Label text = new Label(); ProgressIndicatorBar ( ) { bar.maxWidthProperty().bind( this.prefWidthProperty() ); text.maxWidthProperty().bind( this.prefWidthProperty() ); text.setAlignment( Pos.CENTER ); StackPane.setAlignment( text, Pos.CENTER ); bar.setMinHeight( 30 ); bar.setMaxHeight( 30 ); bar.setPrefHeight( 30 ); bar.setProgress( 0 ); text.setText ( "" ); text.getStyleClass().add( "progress-indicator-text" ); getChildren().setAll( bar, text ); } public void setStatus ( String message, double percent ) { text.setText( message ); bar.setProgress( percent ); } }
899
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
FXUI.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/fxui/FXUI.java
package net.joshuad.hypnos.fxui; import java.awt.Desktop; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.Field; import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.EnumMap; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.SwingUtilities; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.application.Platform; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Orientation; import javafx.geometry.Rectangle2D; import javafx.scene.Group; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.ButtonBar; import javafx.scene.control.ButtonType; import javafx.scene.control.CheckBox; import javafx.scene.control.DialogPane; import javafx.scene.control.Hyperlink; import javafx.scene.control.Label; import javafx.scene.control.MenuItem; import javafx.scene.control.SplitPane; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.scene.control.TextArea; import javafx.scene.control.TextInputDialog; import javafx.scene.control.Tooltip; import javafx.scene.control.Alert.AlertType; import javafx.scene.effect.ColorAdjust; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.DataFormat; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Region; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import javafx.stage.DirectoryChooser; import javafx.stage.FileChooser; import javafx.stage.Stage; import javafx.stage.WindowEvent; import javafx.util.Callback; import javafx.util.Duration; import net.joshuad.hypnos.CurrentList; import net.joshuad.hypnos.CurrentList.Mode; import net.joshuad.hypnos.Hypnos.ExitCode; import net.joshuad.hypnos.CurrentListState; import net.joshuad.hypnos.CurrentListTrack; import net.joshuad.hypnos.Hypnos; import net.joshuad.hypnos.HypnosURLS; import net.joshuad.hypnos.Persister; import net.joshuad.hypnos.Utils; import net.joshuad.hypnos.Persister.Setting; import net.joshuad.hypnos.audio.AudioSystem; import net.joshuad.hypnos.audio.PlayerListener; import net.joshuad.hypnos.audio.AudioSystem.RepeatMode; import net.joshuad.hypnos.audio.AudioSystem.ShuffleMode; import net.joshuad.hypnos.audio.AudioSystem.StopReason; import net.joshuad.hypnos.hotkeys.GlobalHotkeys; import net.joshuad.hypnos.library.Album; import net.joshuad.hypnos.library.Artist; import net.joshuad.hypnos.library.Library; import net.joshuad.hypnos.library.Playlist; import net.joshuad.hypnos.library.Track; import net.joshuad.hypnos.library.Library.LoaderSpeed; import net.joshuad.hypnos.trayicon.TrayIcon; public class FXUI implements PlayerListener { private static final Logger LOGGER = Logger.getLogger( FXUI.class.getName() ); public static final DataFormat DRAGGED_TRACKS = new DataFormat( "application/hypnos-java-track" ); public final String PROGRAM_NAME = "Hypnos"; SplitPane primarySplitPane; SplitPane currentListSplitPane; private ImagesPanel artSplitPane; private LibraryPane libraryPane; private CurrentListPane currentListPane; Image warningAlertImageSource; Transport transport; Scene scene; Stage mainStage; QueueWindow queueWindow; TagWindow tagWindow; ArtistInfoWindow artistInfoWindow; PlaylistInfoWindow playlistInfoWindow; AlbumInfoWindow albumInfoWindow; MusicRootWindow libraryLocationWindow; HistoryWindow historyWindow; public SettingsWindow settingsWindow; TrackInfoWindow trackInfoWindow; LyricsWindow lyricsWindow; ExportPlaylistPopup exportPopup; TrayIcon trayIcon; LibraryLogWindow libraryLogWindow; final AudioSystem audioSystem; final Library library; private double windowedWidth = 1024; private double windowedHeight = 768; private double windowedX = 50; private double windowedY = 50; public File darkStylesheet; private File baseStylesheet; private boolean isDarkTheme = false; private double primarySplitPaneDefault = .35d; private double currentListSplitPaneDefault = .75d; private double artSplitPaneDefault = .5001d;// For some reason .5 puts it at like .3. private Double currentListSplitPaneRestoredPosition = null; private Double primarySplitPaneRestoredPosition = null; private ColorAdjust darkThemeButtonEffect = new ColorAdjust(); { darkThemeButtonEffect.setBrightness( -.3d ); } ColorAdjust lightThemeButtonEffect = new ColorAdjust(); { lightThemeButtonEffect.setBrightness( -.75d ); lightThemeButtonEffect.setHue( 0 ); lightThemeButtonEffect.setSaturation( 0 ); } //TODO: these don't really belong in the UI, but we don't have a better place atm. private SimpleBooleanProperty promptBeforeOverwrite = new SimpleBooleanProperty ( true ); private SimpleBooleanProperty showSystemTray = new SimpleBooleanProperty ( false ); private SimpleBooleanProperty closeToSystemTray = new SimpleBooleanProperty ( false ); private SimpleBooleanProperty minimizeToSystemTray = new SimpleBooleanProperty ( false ); private SimpleBooleanProperty showINotifyPopup = new SimpleBooleanProperty ( true ); private SimpleBooleanProperty showUpdateAvailableInUI = new SimpleBooleanProperty ( true ); private SimpleBooleanProperty updateAvailable = new SimpleBooleanProperty ( false ); SimpleBooleanProperty showLastFMWidgets = new SimpleBooleanProperty ( false ); boolean doPlaylistSaveWarning = true; private double currentListSplitPanePosition = -1; public FXUI ( Stage stage, Library library, AudioSystem audioSystem, GlobalHotkeys hotkeys ) { mainStage = stage; this.library = library; this.audioSystem = audioSystem; audioSystem.getCurrentList().addNoLoadThread( Thread.currentThread() ); scene = new Scene( new Group(), windowedWidth, windowedHeight ); baseStylesheet = new File ( Hypnos.getRootDirectory() + File.separator + "resources" + File.separator + "style.css" ); darkStylesheet = new File ( Hypnos.getRootDirectory() + File.separator + "resources" + File.separator + "style-dark.css" ); try { mainStage.getIcons().add( new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( "resources" + File.separator + "icon.png" ).toFile() ) ) ); } catch ( FileNotFoundException e ) { LOGGER.warning( "Unable to load program icon: resources/icon.png" ); } loadImages(); trayIcon = new TrayIcon ( this, audioSystem ); showSystemTray.addListener( ( ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue ) -> { if ( newValue ) { trayIcon.show(); } else { trayIcon.hide(); } }); libraryPane = new LibraryPane( this, audioSystem, library ); transport = new Transport( this, audioSystem ); artSplitPane = new ImagesPanel ( this, audioSystem, library ); currentListPane = new CurrentListPane( this, audioSystem, library ); libraryLocationWindow = new MusicRootWindow ( this, mainStage, library ); tagWindow = new TagWindow ( this, audioSystem ); queueWindow = new QueueWindow ( this, library, audioSystem, tagWindow ); albumInfoWindow = new AlbumInfoWindow ( this, library, audioSystem ); playlistInfoWindow = new PlaylistInfoWindow ( this, library, audioSystem ); artistInfoWindow = new ArtistInfoWindow ( this, library, audioSystem ); historyWindow = new HistoryWindow ( this, library, audioSystem ); settingsWindow = new SettingsWindow ( this, library, hotkeys, audioSystem ); trackInfoWindow = new TrackInfoWindow ( this ); lyricsWindow = new LyricsWindow ( this ); exportPopup = new ExportPlaylistPopup ( this ); libraryLogWindow = new LibraryLogWindow ( this, library ); setupNativeStylesheet(); applyBaseTheme(); applyDarkTheme(); currentListSplitPane = new SplitPane(); currentListSplitPane.setOrientation( Orientation.VERTICAL ); currentListSplitPane.getItems().addAll( currentListPane, artSplitPane ); artSplitPane.setMinWidth( 0 ); primarySplitPane = new SplitPane(); primarySplitPane.getItems().addAll( libraryPane, currentListSplitPane ); final BorderPane primaryContainer = new BorderPane(); primaryContainer.prefWidthProperty().bind( scene.widthProperty() ); primaryContainer.prefHeightProperty().bind( scene.heightProperty() ); primaryContainer.setPadding( new Insets( 0 ) ); primaryContainer.setCenter( primarySplitPane ); primaryContainer.setTop( transport ); SplitPane.setResizableWithParent( libraryPane, Boolean.FALSE ); SplitPane.setResizableWithParent( artSplitPane, Boolean.FALSE ); SplitPane.setResizableWithParent( currentListSplitPane, Boolean.FALSE ); SplitPane.setResizableWithParent( primarySplitPane, Boolean.FALSE ); SplitPane.setResizableWithParent( currentListPane, Boolean.FALSE ); mainStage.setTitle( ( Hypnos.isDeveloping() ? "Dev - " : "" ) + PROGRAM_NAME ); ((Group) scene.getRoot()).getChildren().addAll( primaryContainer ); mainStage.setScene( scene ); ChangeListener<Number> windowSizeListener = new ChangeListener<Number> () { @Override public void changed ( ObservableValue<? extends Number> observable, Number oldValue, Number newValue ) { if ( !mainStage.isMaximized() ) { windowedWidth = mainStage.getWidth(); windowedHeight = mainStage.getHeight(); windowedX = mainStage.getX(); windowedY = mainStage.getY(); } } }; primaryContainer.setOnKeyPressed( ( KeyEvent e ) -> { if ( e.getCode() == KeyCode.S && e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { e.consume(); currentListPane.saveMenuItem.fire(); } else if ( e.getCode() == KeyCode.E && e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { e.consume(); currentListPane.exportToM3U.fire(); } else if ( e.getCode() == KeyCode.O && e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { e.consume(); currentListPane.loadMenuItem.fire(); } else if ( e.getCode() == KeyCode.P && e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { e.consume(); settingsWindow.show(); } else if ( e.getCode() == KeyCode.DIGIT1 // With or without control && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { e.consume(); setLibraryCollapsed( false ); libraryPane.selectPane( 0 ); Platform.runLater( () -> libraryPane.focusFilterOfCurrentTab() ); } else if ( e.getCode() == KeyCode.DIGIT2 // With or without control && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { e.consume(); setLibraryCollapsed( false ); libraryPane.selectPane( 1 ); Platform.runLater( () -> libraryPane.focusFilterOfCurrentTab() ); } else if ( e.getCode() == KeyCode.DIGIT3 // With or without control && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { e.consume(); setLibraryCollapsed( false ); libraryPane.selectPane( 2 ); Platform.runLater( () -> libraryPane.focusFilterOfCurrentTab() ); } else if ( e.getCode() == KeyCode.DIGIT4 // With or without control && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { e.consume(); setLibraryCollapsed( false ); libraryPane.selectPane( 3 ); Platform.runLater( () -> libraryPane.focusFilterOfCurrentTab() ); } else if ( e.getCode() == KeyCode.F && !e.isControlDown() && !e.isShiftDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { e.consume(); //We put it in runlater to keep the key from being passed down to the filter box Platform.runLater( () -> { currentListPane.infoLabelAndFilter.beginEditing(); currentListPane.currentListTable.getSelectionModel().clearSelection(); }); } else if ( e.getCode() == KeyCode.F && e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { e.consume(); boolean libraryPaneHasFocus = false; Node focusedNode = scene.focusOwnerProperty().get(); Node parent = focusedNode.getParent(); while ( parent != null ) { if ( parent == libraryPane ) { libraryPaneHasFocus = true; break; } parent = parent.getParent(); } if ( libraryPaneHasFocus ) { libraryPane.focusFilterOfCurrentTab(); } else { //We put it in runlater to keep the key from being passed down to the filter box Platform.runLater( () -> { currentListPane.infoLabelAndFilter.beginEditing(); currentListPane.currentListTable.getSelectionModel().clearSelection(); }); } } else if ( e.getCode() == KeyCode.R && !e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { e.consume(); currentListPane.toggleRepeatButton.fire(); } else if ( e.getCode() == KeyCode.S && !e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { e.consume(); currentListPane.toggleShuffleButton.fire(); } else if ( e.getCode() == KeyCode.H && e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { e.consume(); historyWindow.show(); } else if ( e.getCode() == KeyCode.Q && e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { e.consume(); queueWindow.show(); } else if ( e.getCode() == KeyCode.L && e.isShiftDown() && !e.isAltDown() && !e.isControlDown() && !e.isMetaDown() ) { if ( !libraryPane.trackPane.filterBox.isFocused() && !libraryPane.albumPane.filterBox.isFocused() && !libraryPane.playlistPane.filterBox.isFocused() ) { e.consume(); lyricsWindow.setTrack( audioSystem.getCurrentTrack() ); lyricsWindow.show(); } } else if ( e.getCode() == KeyCode.L && e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { e.consume(); toggleLibraryCollapsed(); } else if ( e.getCode() == KeyCode.SEMICOLON && e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { e.consume(); toggleArtPaneCollapsed(); } else if ( ( e.getCode() == KeyCode.NUMPAD1 || e.getCode() == KeyCode.KP_UP ) && !e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { e.consume(); audioSystem.skipMS( -5000 ); } else if ( ( e.getCode() == KeyCode.NUMPAD2 || e.getCode() == KeyCode.KP_DOWN ) && !e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { e.consume(); transport.stopButton.fire(); } else if ( ( e.getCode() == KeyCode.NUMPAD3 || e.getCode() == KeyCode.KP_RIGHT ) && !e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { e.consume(); audioSystem.skipMS( 5000 ); } else if ( ( e.getCode() == KeyCode.NUMPAD4 || e.getCode() == KeyCode.KP_LEFT ) && !e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { e.consume(); transport.previousButton.fire(); } else if ( ( e.getCode() == KeyCode.NUMPAD5 || e.getCode() == KeyCode.KP_UP ) && !e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { e.consume(); transport.togglePlayButton.fire(); } else if ( ( e.getCode() == KeyCode.NUMPAD6 || e.getCode() == KeyCode.KP_DOWN ) && !e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { e.consume(); transport.nextButton.fire(); } else if ( ( e.getCode() == KeyCode.NUMPAD7 || e.getCode() == KeyCode.KP_RIGHT ) && !e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { e.consume(); audioSystem.decrementVolume(); } else if ( ( e.getCode() == KeyCode.NUMPAD8 || e.getCode() == KeyCode.KP_LEFT ) && !e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { e.consume(); transport.volumeMuteButton.fire(); } else if ( ( e.getCode() == KeyCode.NUMPAD9 || e.getCode() == KeyCode.KP_LEFT ) && !e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { e.consume(); audioSystem.incrementVolume(); } }); Runnable setDefaultDividerPositions = () -> { primarySplitPane.setDividerPositions( primarySplitPaneDefault ); currentListSplitPane.setDividerPositions( currentListSplitPaneDefault ); artSplitPane.setDividerPositions( artSplitPaneDefault ); }; if ( Hypnos.getOS().isLinux() ) { Platform.runLater( setDefaultDividerPositions ); } else { setDefaultDividerPositions.run(); } mainStage.widthProperty().addListener( windowSizeListener ); mainStage.heightProperty().addListener( windowSizeListener ); Platform.setImplicitExit( false ); mainStage.setOnCloseRequest( (WindowEvent t) -> { if ( closeToSystemTray.get() && trayIcon.isSupported() ) { hideMainWindow(); } else { mainStage.hide(); Hypnos.exit( ExitCode.NORMAL ); } }); mainStage.iconifiedProperty().addListener( ( obs, oldValue, newValue ) -> { if ( newValue && trayIcon.isSupported() && minimizeToSystemTray.get() ) { hideMainWindow(); } }); audioSystem.addPlayerListener ( this ); } private void setupNativeStylesheet() { Path stylesheet; switch ( Hypnos.getOS() ) { case OSX: stylesheet = Hypnos.getRootDirectory().resolve( "resources/style-osx.css" ); case WIN_10: case WIN_7: case WIN_8: case WIN_UNKNOWN: case WIN_VISTA: case WIN_XP: case UNKNOWN: stylesheet = Hypnos.getRootDirectory().resolve( "resources/style-win.css" ); break; case NIX: default: stylesheet = Hypnos.getRootDirectory().resolve( "resources/style-nix.css" ); break; } String fontSheet = fileToStylesheetString( stylesheet.toFile() ); if ( fontSheet == null ) { LOGGER.log( Level.WARNING, "Unable to load native stylesheet, hypnos will not look right." + stylesheet.toString(), new NullPointerException() ); return; } scene.getStylesheets().add( fontSheet ); libraryLocationWindow.getScene().getStylesheets().add( fontSheet ); settingsWindow.getScene().getStylesheets().add( fontSheet ); queueWindow.getScene().getStylesheets().add( fontSheet ); tagWindow.getScene().getStylesheets().add( fontSheet ); playlistInfoWindow.getScene().getStylesheets().add( fontSheet ); artistInfoWindow.getScene().getStylesheets().add( fontSheet ); albumInfoWindow.getScene().getStylesheets().add( fontSheet ); libraryLogWindow.getScene().getStylesheets().add( fontSheet ); historyWindow.getScene().getStylesheets().add( fontSheet ); trackInfoWindow.getScene().getStylesheets().add( fontSheet ); lyricsWindow.getScene().getStylesheets().add( fontSheet ); exportPopup.getScene().getStylesheets().add( fontSheet ); } private void loadImages() { try { warningAlertImageSource = new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( "resources/alert-warning.png" ).toFile() ) ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to load warning alert icon: resources/alert-warning.png", e ); } } public String fileToStylesheetString ( File stylesheetFile ) { try { return stylesheetFile.toURI().toURL().toString(); } catch ( Exception e ) { return null; } } public void applyBaseTheme() { String baseSheet = fileToStylesheetString( baseStylesheet ); if ( baseSheet == null ) { LOGGER.log( Level.WARNING, "Unable to load base style sheet hypnos will not look right." + baseStylesheet.toString(), new NullPointerException() ); return; } scene.getStylesheets().add( baseSheet ); libraryLocationWindow.getScene().getStylesheets().add( baseSheet ); settingsWindow.getScene().getStylesheets().add( baseSheet ); queueWindow.getScene().getStylesheets().add( baseSheet ); tagWindow.getScene().getStylesheets().add( baseSheet ); playlistInfoWindow.getScene().getStylesheets().add( baseSheet ); artistInfoWindow.getScene().getStylesheets().add( baseSheet ); albumInfoWindow.getScene().getStylesheets().add( baseSheet ); libraryLogWindow.getScene().getStylesheets().add( baseSheet ); historyWindow.getScene().getStylesheets().add( baseSheet ); trackInfoWindow.getScene().getStylesheets().add( baseSheet ); lyricsWindow.getScene().getStylesheets().add( baseSheet ); exportPopup.getScene().getStylesheets().add( baseSheet ); } public void applyDarkTheme() { if ( !isDarkTheme ) { String darkSheet = fileToStylesheetString( darkStylesheet ); if ( darkSheet == null ) { LOGGER.log( Level.WARNING, "Unable to load dark style sheet hypnos will not look right." + darkStylesheet.toString(), new NullPointerException() ); return; } isDarkTheme = true; scene.getStylesheets().add( darkSheet ); libraryLocationWindow.getScene().getStylesheets().add( darkSheet ); queueWindow.getScene().getStylesheets().add( darkSheet ); tagWindow.getScene().getStylesheets().add( darkSheet ); playlistInfoWindow.getScene().getStylesheets().add( darkSheet ); artistInfoWindow.getScene().getStylesheets().add( darkSheet ); albumInfoWindow.getScene().getStylesheets().add( darkSheet ); libraryLogWindow.getScene().getStylesheets().add( darkSheet ); historyWindow.getScene().getStylesheets().add( darkSheet ); settingsWindow.getScene().getStylesheets().add( darkSheet ); trackInfoWindow.getScene().getStylesheets().add( darkSheet ); lyricsWindow.getScene().getStylesheets().add( darkSheet ); exportPopup.getScene().getStylesheets().add( darkSheet ); transport.applyDarkTheme(); libraryPane.applyDarkTheme( darkThemeButtonEffect ); currentListPane.applyDarkTheme ( darkThemeButtonEffect ); } } public void applyLightTheme() { isDarkTheme = false; String darkSheet = fileToStylesheetString( darkStylesheet ); if ( darkSheet == null ) { LOGGER.log( Level.WARNING, "Unable to load dark style sheet, hypnos will not look right." + darkStylesheet.toString(), new NullPointerException() ); return; } scene.getStylesheets().remove( darkSheet ); libraryLocationWindow.getScene().getStylesheets().remove( darkSheet ); settingsWindow.getScene().getStylesheets().remove( darkSheet ); queueWindow.getScene().getStylesheets().remove( darkSheet ); tagWindow.getScene().getStylesheets().remove( darkSheet ); playlistInfoWindow.getScene().getStylesheets().remove( darkSheet ); artistInfoWindow.getScene().getStylesheets().remove( darkSheet ); albumInfoWindow.getScene().getStylesheets().remove( darkSheet ); libraryLogWindow.getScene().getStylesheets().remove( darkSheet ); historyWindow.getScene().getStylesheets().remove( darkSheet ); trackInfoWindow.getScene().getStylesheets().remove( darkSheet ); lyricsWindow.getScene().getStylesheets().remove( darkSheet ); exportPopup.getScene().getStylesheets().remove( darkSheet ); transport.applyLightTheme(); libraryPane.applyLightTheme(); currentListPane.applyLightTheme(); } public boolean isDarkTheme() { return isDarkTheme; } //REFACTOR: Does this function need to exist? void removeFromCurrentList ( List<Integer> removeMe ) { if ( !removeMe.isEmpty() ) { audioSystem.getCurrentList().removeTracksAtIndices ( removeMe ); } } public void previousRequested() { if ( audioSystem.isStopped() ) { currentListPane.currentListTable.getSelectionModel().clearAndSelect( currentListPane.currentListTable.getSelectionModel().getSelectedIndex() - 1 ); } else { audioSystem.previous(); } } public Track getSelectedTrack () { return currentListPane.currentListTable.getSelectionModel().getSelectedItem(); } public ObservableList <CurrentListTrack> getSelectedTracks () { return currentListPane.currentListTable.getSelectionModel().getSelectedItems(); } public void setSelectedTracks ( List <CurrentListTrack> selectMe ) { currentListPane.currentListTable.getSelectionModel().clearSelection(); if ( selectMe != null ) { for ( CurrentListTrack track : selectMe ) { currentListPane.currentListTable.getSelectionModel().select( track ); } } } public void updateTransport ( int timeElapsedS, int timeRemainingS, double percent ) { transport.update ( timeElapsedS, timeRemainingS, percent ); } public void toggleMinimized() { Platform.runLater( () -> { if ( !mainStage.isShowing() ) { restoreWindow(); } else if ( mainStage.isIconified() ) { mainStage.setIconified( false ); mainStage.toFront(); } else { mainStage.setIconified( true ); } }); } public void restoreWindow() { if ( !mainStage.isShowing() ) { mainStage.setIconified( false ); mainStage.show(); currentListSplitPane.setDividerPosition( 0, currentListSplitPanePosition ); } mainStage.setIconified( false ); mainStage.toFront(); } public void hideMainWindow() { switch ( Hypnos.getOS() ) { case NIX: currentListSplitPanePosition = currentListSplitPane.getDividerPositions()[0]; mainStage.hide(); break; case WIN_10: case WIN_7: case WIN_8: case WIN_UNKNOWN: case WIN_VISTA: currentListSplitPanePosition = currentListSplitPane.getDividerPositions()[0]; mainStage.setIconified( false ); mainStage.hide(); break; case WIN_XP: default: break; } } public void toggleHidden() { Platform.runLater(() -> { if ( closeToSystemTray.get() ) { if ( mainStage.isIconified() ) { mainStage.setIconified( false ); } else if ( !mainStage.isShowing() ) { restoreWindow(); } else { mainStage.setIconified( false ); //This is necessary for at least windows, seems good to keep it for every system hideMainWindow(); } } else { toggleMinimized(); } }); } public void updatePlaylistMenuItems ( ObservableList <MenuItem> items, EventHandler <ActionEvent> eventHandler ) { items.remove( 1, items.size() ); for ( Playlist playlist : library.getPlaylistData() ) { MenuItem newItem = new MenuItem( playlist.getName() ); newItem.setUserData( playlist ); newItem.setOnAction( eventHandler ); items.add( newItem ); } } public void selectCurrentTrack () { Track current = audioSystem.getCurrentTrack(); selectTrackOnCurrentList ( current ); } public void selectTrackOnCurrentList ( Track selectMe ) { if ( selectMe != null ) { synchronized ( currentListPane.currentListTable.getItems() ) { int itemIndex = currentListPane.currentListTable.getItems().indexOf( selectMe ); if ( itemIndex != -1 && itemIndex < currentListPane.currentListTable.getItems().size() ) { currentListPane.currentListTable.requestFocus(); currentListPane.currentListTable.getSelectionModel().clearAndSelect( itemIndex ); currentListPane.currentListTable.getFocusModel().focus( itemIndex ); currentListPane.currentListTable.scrollTo( itemIndex ); } } artSplitPane.trackSelected( selectMe ); } } //REFACTOR: This function probably belongs in Library public void addToPlaylist ( List <Track> tracks, Playlist playlist ) { playlist.getTracks().addAll( tracks ); libraryPane.playlistPane.playlistTable.refresh(); //TODO: playlist.equals ( playlist ) instead of name .equals ( name ) ? if ( audioSystem.getCurrentPlaylist() != null && audioSystem.getCurrentPlaylist().getName().equals( playlist.getName() ) ) { audioSystem.getCurrentList().appendTracks( tracks ); } } public BooleanProperty promptBeforeOverwriteProperty ( ) { return promptBeforeOverwrite; } public BooleanProperty closeToSystemTrayProperty ( ) { return closeToSystemTray; } public BooleanProperty minimizeToSystemTrayProperty ( ) { return minimizeToSystemTray; } public BooleanProperty showSystemTrayProperty ( ) { return showSystemTray; } public BooleanProperty showUpdateAvailableInUIProperty ( ) { return showUpdateAvailableInUI; } public BooleanProperty updateAvailableProperty ( ) { return updateAvailable; } public boolean okToReplaceCurrentList () { if ( audioSystem.getCurrentList().getState().getMode() != CurrentList.Mode.PLAYLIST_UNSAVED ) { return true; } if ( !promptBeforeOverwrite.getValue() ) { return true; } Alert alert = new Alert( AlertType.CONFIRMATION ); double x = mainStage.getX() + mainStage.getWidth() / 2 - 220; //It'd be nice to use alert.getWidth() / 2, but it's NAN now. double y = mainStage.getY() + mainStage.getHeight() / 2 - 50; alert.setX( x ); alert.setY( y ); alert.setDialogPane( new DialogPane() { @Override protected Node createDetailsButton () { CheckBox optOut = new CheckBox(); optOut.setPadding( new Insets ( 0, 20, 0, 0 ) ); optOut.setText( "Do not ask again" ); optOut.setOnAction( e -> { promptBeforeOverwrite.set( !optOut.isSelected() ); }); return optOut; } @Override protected Node createButtonBar () { //This lets me specify my own button order below ButtonBar node = (ButtonBar) super.createButtonBar(); node.setButtonOrder( ButtonBar.BUTTON_ORDER_NONE ); return node; } }); if ( warningAlertImageSource != null ) { ImageView warningImage = new ImageView ( warningAlertImageSource ); if ( isDarkTheme() ) { warningImage.setEffect( darkThemeButtonEffect ); } else { warningImage.setEffect( lightThemeButtonEffect ); } warningImage.setFitHeight( 50 ); warningImage.setFitWidth( 50 ); alert.setGraphic( warningImage ); } setAlertWindowIcon ( alert ); applyCurrentTheme ( alert ); alert.getDialogPane().getButtonTypes().addAll( ButtonType.YES, ButtonType.NO, ButtonType.CANCEL ); alert.getDialogPane().setContentText( "You have an unsaved playlist, do you wish to save it?" ); alert.getDialogPane().setExpandableContent( new Group() ); alert.getDialogPane().setExpanded( false ); alert.getDialogPane().setGraphic( alert.getDialogPane().getGraphic() ); alert.setTitle( "Save Unsaved Playlist" ); alert.setHeaderText( null ); Optional <ButtonType> result = alert.showAndWait(); if ( result.isPresent() ) { if ( result.get() == ButtonType.NO ) { return true; } else if (result.get() == ButtonType.YES ) { return promptAndSavePlaylist ( Utils.convertCurrentTrackList( audioSystem.getCurrentList().getItems() ) ); } else { return false; } } return false; } public boolean promptAndSavePlaylist ( List <Track> tracks ) { //REFACTOR: This should probably be refactored into promptForPlaylistName and <something>.savePlaylist( name, items ) String defaultName = ""; if ( audioSystem.getCurrentPlaylist() != null ) { defaultName = audioSystem.getCurrentPlaylist().getName(); } TextInputDialog dialog = new TextInputDialog( defaultName ); applyCurrentTheme ( dialog ); setDialogIcon ( dialog ); dialog.setX( mainStage.getX() + mainStage.getWidth() / 2 - 150 ); dialog.setY( mainStage.getY() + mainStage.getHeight() / 2 - 100 ); dialog.setTitle( "Save Playlist" ); dialog.setHeaderText( null ); Optional <String> result = dialog.showAndWait(); if ( result.isPresent() ) { String enteredName = result.get().trim(); Playlist updatedPlaylist = null; for ( Playlist test : library.getPlaylistData() ) { if ( test.getName().equals( enteredName ) ) { test.setTracks( tracks ); updatedPlaylist = test; libraryPane.playlistPane.playlistTable.refresh(); break; } } if ( updatedPlaylist == null ) { updatedPlaylist = new Playlist( enteredName, new ArrayList <Track> ( tracks ) ); library.addPlaylist ( updatedPlaylist ); } CurrentListState state = audioSystem.getCurrentList().getState(); CurrentListState newState; if ( state.getMode() == Mode.PLAYLIST || state.getMode() == Mode.PLAYLIST_UNSAVED ) { newState = new CurrentListState ( state.getItems(), state.getArtist(), state.getAlbums(), updatedPlaylist, CurrentList.Mode.PLAYLIST ); } else { newState = new CurrentListState ( state.getItems(), state.getArtist(), state.getAlbums(), null, state.getMode() ); } audioSystem.getCurrentList().setState( newState ); return true; } return false; } public void promptAndRenamePlaylist ( Playlist playlist ) { TextInputDialog dialog = new TextInputDialog( playlist.getName() ); dialog.setX( mainStage.getX() + mainStage.getWidth() / 2 - 150 ); dialog.setY( mainStage.getY() + mainStage.getHeight() / 2 - 100 ); dialog.setTitle( "Rename Playlist" ); dialog.setHeaderText( null ); applyCurrentTheme( dialog ); setDialogIcon( dialog ); Optional <String> result = dialog.showAndWait(); if ( result.isPresent() ) { String enteredName = result.get().trim(); renamePlaylist ( playlist, enteredName ); } } public void renamePlaylist ( Playlist playlist, String rawName ) { String oldFileBasename = playlist.getBaseFilename(); library.removePlaylist( playlist ); playlist.setName ( rawName ); playlist.setHasUnsavedData ( true ); library.addPlaylist ( playlist ); libraryPane.playlistPane.playlistTable.refresh(); Hypnos.getPersister().saveLibraryPlaylists(); Hypnos.getPersister().deletePlaylistFile( oldFileBasename ); } public void openFileBrowser ( Path path ) { // PENDING: This is the better way once openjdk and openjfx supports it: // getHostServices().showDocument(file.toURI().toString()); if ( !Files.isDirectory( path ) ) path = path.getParent(); final File showMe = path.toFile(); SwingUtilities.invokeLater( new Runnable() { public void run () { try { Desktop.getDesktop().browse( showMe.toURI() ); } catch ( IOException e ) { notifyUserError( "Unable to open native file browser." ); LOGGER.log( Level.INFO, "Unable to open native file browser.", e ); } } }); } public void openFileNatively ( Path logFileBackup ) { // PENDING: This is the better way once openjdk and openjfx supports it: // getHostServices().showDocument(file.toURI().toString()); SwingUtilities.invokeLater( new Runnable() { public void run () { try { Desktop.getDesktop().open( logFileBackup.toFile() ); } catch ( IOException e ) { notifyUserError( "Unable to open native file file viewer for:\n" + logFileBackup ); LOGGER.log( Level.INFO, "Unable to open native file viewer.", e ); } } }); } private void hackTooltipStartTiming() { try { Tooltip tooltip = new Tooltip (); Field fieldBehavior = tooltip.getClass().getDeclaredField("BEHAVIOR"); fieldBehavior.setAccessible(true); Object objBehavior = fieldBehavior.get(tooltip); Field fieldTimer = objBehavior.getClass().getDeclaredField("activationTimer"); fieldTimer.setAccessible(true); Timeline objTimer = (Timeline) fieldTimer.get(objBehavior); objTimer.getKeyFrames().clear(); objTimer.getKeyFrames().add(new KeyFrame(new Duration(350))); } catch ( Exception e ) { LOGGER.log( Level.INFO, "Unable accelerate tooltip popup speed.", e ); } } public void setLoaderSpeedDisplay ( LoaderSpeed speed ) { this.libraryLocationWindow.setLoaderSpeedDisplay ( speed ); } public double getPrimarySplitPercent() { return primarySplitPane.getDividerPositions()[0]; } //TODO: probably rename this public void runThreadSafe( Runnable runMe ) { if ( Platform.isFxApplicationThread() ) { runMe.run(); } else { Platform.runLater( runMe ); } } public double getCurrentListSplitPercent() { return currentListSplitPane.getDividerPositions()[0]; } public double getArtSplitPercent() { return artSplitPane.getDividerPositions()[0]; } public boolean isMaximized () { return mainStage.isMaximized(); } public static void notifyUserHypnosNonResponsive() { Alert alert = new Alert ( AlertType.INFORMATION ); setAlertWindowIcon ( alert ); alert.setTitle( "Error" ); alert.setHeaderText( "Unable to Launch Hypnos" ); alert.setContentText( "A Hypnos process is running, but it has become non-responsive. " + "Please end the existing process and then relaunch Hypnos." ); alert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE); GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); int width = gd.getDisplayMode().getWidth(); int height = gd.getDisplayMode().getHeight(); //NOTE: I can't get the alert's width and height yet, so i just have to eyeball it. Hopefully this is good. alert.setX ( width / 2 - 320 / 2 ); alert.setY ( height / 2 - 300 / 2 ); alert.showAndWait(); } public static void notifyUserVLCLibraryError() { Alert alert = new Alert ( AlertType.INFORMATION ); setAlertWindowIcon ( alert ); alert.setTitle( "Information" ); alert.setHeaderText( "Unable to launch Hypnos" ); String message = "Hypnos's libraries have been removed or corrupted. Please reinstall hypnos."; alert.setContentText( message ); alert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE); GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); int width = gd.getDisplayMode().getWidth(); int height = gd.getDisplayMode().getHeight(); //NOTE: I can't get the alert's width and height yet, so i just have to eyeball it. Hopefully this is good. alert.setX ( width / 2 - 320 / 2 ); alert.setY ( height / 2 - 300 / 2 ); alert.showAndWait(); } public static void setAlertWindowIcon ( Alert alert ) { Stage stage = (Stage) alert.getDialogPane().getScene().getWindow(); try { Image icon = new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( "resources" + File.separator + "icon.png" ).toFile() ) ); stage.getIcons().add( icon ); } catch ( Exception e ) { LOGGER.log ( Level.INFO, "Unable to set icon on alert.", e ); } } public static void setDialogIcon ( TextInputDialog dialog ) { Stage stage = (Stage) dialog.getDialogPane().getScene().getWindow(); try { Image icon = new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( "resources" + File.separator + "icon.png" ).toFile() ) ); stage.getIcons().add( icon ); } catch ( Exception e ) { LOGGER.log ( Level.INFO, "Unable to set icon on alert.", e ); } } public void applyCurrentTheme ( Alert alert ) { String darkSheet = fileToStylesheetString( darkStylesheet ); if ( darkSheet == null ) { LOGGER.log( Level.INFO, "Unable to load dark style sheet, alert will not look right." + darkStylesheet.toString(), new NullPointerException() ); return; } if ( isDarkTheme() ) { ((Stage) alert.getDialogPane().getScene().getWindow()).getScene().getStylesheets().add( darkSheet ); } else { ((Stage) alert.getDialogPane().getScene().getWindow()).getScene().getStylesheets().remove( darkSheet ); } } public void applyCurrentTheme ( TextInputDialog dialog ) { String darkSheet = fileToStylesheetString( darkStylesheet ); if ( darkSheet == null ) { LOGGER.log( Level.INFO, "Unable to load dark style sheet, input dialog will not look right." + darkStylesheet.toString(), new NullPointerException() ); return; } if ( isDarkTheme() ) { ((Stage) dialog.getDialogPane().getScene().getWindow()).getScene().getStylesheets().add( darkSheet ); } else { ((Stage) dialog.getDialogPane().getScene().getWindow()).getScene().getStylesheets().remove( darkSheet ); } } public void notifyUserError ( String message ) { Platform.runLater( () -> { Alert alert = new Alert ( AlertType.ERROR ); setAlertWindowIcon( alert ); applyCurrentTheme( alert ); alert.setTitle( "Error" ); alert.setContentText( message ); alert.getDialogPane().setMinHeight( Region.USE_PREF_SIZE ); alert.showAndWait(); }); } public void showMainWindow() { Rectangle2D screenSize = javafx.stage.Screen.getPrimary().getVisualBounds(); if ( !mainStage.isMaximized() && mainStage.getWidth() > screenSize.getWidth() ) { mainStage.setWidth( screenSize.getWidth() * .8f ); } if ( !mainStage.isMaximized() && mainStage.getHeight() > screenSize.getHeight() ) { mainStage.setHeight( screenSize.getHeight() * .8f ); } mainStage.show(); //PENDING: This is where I get a crash with oracle's java 9, no info and can't catch it. // This stuff has to be done after show transport.doAfterShowProcessing(); libraryPane.doAfterShowProcessing(); Node blankCurrentlistHeader = currentListPane.currentListTable.lookup(".column-header-background"); blankCurrentlistHeader.setOnContextMenuRequested ( event -> currentListPane.currentListColumnSelectorMenu.show( blankCurrentlistHeader, event.getScreenX(), event.getScreenY() ) ); Set<Node> dividers = primarySplitPane.lookupAll(".split-pane-divider"); for ( Node divider : dividers ) { if ( divider.getParent() == currentListSplitPane ) { divider.setOnMouseClicked ( ( e ) -> { if ( e.getClickCount() == 2 ) { toggleArtPaneCollapsed(); } }); } else if ( divider.getParent() == primarySplitPane ) { divider.setOnMouseClicked ( ( e ) -> { if ( e.getClickCount() == 2 ) { toggleLibraryCollapsed(); } }); } else if ( divider.getParent() == artSplitPane ) { divider.setOnMouseClicked ( ( e ) -> { if ( e.getClickCount() == 2 ) { artSplitPane.setDividerPosition( 0, .5f ); } }); } } SplitPane.setResizableWithParent( artSplitPane, Boolean.FALSE ); SplitPane.setResizableWithParent( currentListSplitPane, Boolean.FALSE ); SplitPane.setResizableWithParent( primarySplitPane, Boolean.FALSE ); hackTooltipStartTiming(); Platform.runLater( () -> { //This is a bad hack to give the album /track pane data time to load try { Thread.sleep ( 100 ); } catch ( InterruptedException e ) { //Do nothing } }); } public void toggleArtPaneCollapsed() { setArtPaneCollapsed( !isArtPaneCollapsed() ); } public boolean isArtPaneCollapsed() { return currentListSplitPane.getDividerPositions()[0] >= .99d; } public void setArtPaneCollapsed( boolean target ) { if( target ) { currentListSplitPaneRestoredPosition = currentListSplitPane.getDividerPositions()[0]; currentListSplitPane.setDividerPosition( 0, 1 ); } else { if ( currentListSplitPaneRestoredPosition != null ) { currentListSplitPane.setDividerPosition( 0, currentListSplitPaneRestoredPosition ); currentListSplitPaneRestoredPosition = null; } else if ( currentListSplitPane.getDividerPositions()[0] >= .99d ) { currentListSplitPane.setDividerPosition( 0, currentListSplitPaneDefault ); } } } public void toggleLibraryCollapsed() { setLibraryCollapsed( !isLibraryCollapsed() ); } public void setLibraryCollapsed( boolean target ) { if ( target ) { primarySplitPaneRestoredPosition = primarySplitPane.getDividerPositions()[0]; primarySplitPane.setDividerPosition( 0, 0 ); } else { if ( primarySplitPaneRestoredPosition != null ) { primarySplitPane.setDividerPosition( 0, primarySplitPaneRestoredPosition ); primarySplitPaneRestoredPosition = null; } else if ( primarySplitPane.getDividerPositions()[0] <= .01d ) { primarySplitPane.setDividerPosition( 0, primarySplitPaneDefault ); } } } public boolean isLibraryCollapsed() { return primarySplitPane.getDividerPositions()[0] <= .01d; } public void fixTables() { Platform.runLater( () -> { libraryPane.albumPane.albumTable.refresh(); libraryPane.playlistPane.playlistTable.refresh(); libraryPane.trackPane.trackTable.refresh(); libraryPane.artistPane.artistTable.refresh(); }); } public EnumMap <Persister.Setting, ? extends Object> getSettings () { EnumMap <Persister.Setting, Object> retMe = new EnumMap <Persister.Setting, Object> ( Persister.Setting.class ); boolean isMaximized = isMaximized(); retMe.put ( Setting.WINDOW_MAXIMIZED, isMaximized ); String theme = isDarkTheme ? "Dark" : "Light"; if ( isMaximized ) { retMe.put ( Setting.WINDOW_X_POSITION, windowedX ); retMe.put ( Setting.WINDOW_Y_POSITION, windowedY ); retMe.put ( Setting.WINDOW_WIDTH, windowedWidth ); retMe.put ( Setting.WINDOW_HEIGHT, windowedHeight ); } else { retMe.put ( Setting.WINDOW_X_POSITION, mainStage.getX() ); retMe.put ( Setting.WINDOW_Y_POSITION, mainStage.getY() ); retMe.put ( Setting.WINDOW_WIDTH, mainStage.getWidth() ); retMe.put ( Setting.WINDOW_HEIGHT, mainStage.getHeight() ); } retMe.put ( Setting.PRIMARY_SPLIT_PERCENT, getPrimarySplitPercent() ); retMe.put ( Setting.ART_CURRENT_SPLIT_PERCENT, getCurrentListSplitPercent() ); retMe.put ( Setting.ART_SPLIT_PERCENT, getArtSplitPercent() ); retMe.put ( Setting.PROMPT_BEFORE_OVERWRITE, promptBeforeOverwrite.getValue() ); retMe.put ( Setting.SHOW_SYSTEM_TRAY_ICON, showSystemTray.getValue() ); retMe.put ( Setting.CLOSE_TO_SYSTEM_TRAY, closeToSystemTray.getValue() ); retMe.put ( Setting.MINIMIZE_TO_SYSTEM_TRAY, minimizeToSystemTray.getValue() ); retMe.put ( Setting.SHOW_INOTIFY_ERROR_POPUP, showINotifyPopup.getValue() ); retMe.put ( Setting.SHOW_UPDATE_AVAILABLE_IN_MAIN_WINDOW, showUpdateAvailableInUI.getValue() ); retMe.put ( Setting.THEME, theme ); retMe.put ( Setting.SHOW_LASTFM_IN_UI, showLastFMWidgets.getValue().toString() ); EnumMap <Persister.Setting, ? extends Object> librarySettings = libraryPane.getSettings(); for ( Persister.Setting setting : librarySettings.keySet() ) { retMe.put( setting, librarySettings.get( setting ) ); } EnumMap <Persister.Setting, ? extends Object> currentListSettings = currentListPane.getSettings(); for ( Persister.Setting setting : currentListSettings.keySet() ) { retMe.put( setting, currentListSettings.get( setting ) ); } return retMe; } public void refreshQueueList() { queueWindow.refresh(); } public void refreshImages() { artSplitPane.refreshImages (); } public void refreshCurrentList () { for ( CurrentListTrack track : currentListPane.currentListTable.getItems() ) { try { track.refreshTagData(); } catch ( Exception e ) { track.setIsMissingFile( true ); //TODO: Do we want to make another flag or rename isMissingFile? } } currentListPane.currentListTable.refresh(); } public void refreshArtistTable () { libraryPane.artistPane.artistTable.refresh(); } public void refreshAlbumTable () { libraryPane.albumPane.albumTable.refresh(); } public void refreshTrackTable () { libraryPane.trackPane.trackTable.refresh(); } public void applySettingsAfterWindowShown ( EnumMap<Persister.Setting, String> settings ) { libraryPane.applySettingsAfterWindowShown( settings ); } @SuppressWarnings("incomplete-switch") public void applySettingsBeforeWindowShown( EnumMap<Persister.Setting, String> settings ) { settings.forEach( ( setting, value )-> { try { switch ( setting ) { case WINDOW_X_POSITION: double xPosition = Math.max( Double.valueOf( value ) , 0 ); mainStage.setX( xPosition ); settings.remove ( setting ); break; case WINDOW_Y_POSITION: double yPosition = Math.max( Double.valueOf( value ) , 0 ); mainStage.setY( yPosition ); settings.remove ( setting ); break; case WINDOW_WIDTH: mainStage.setWidth( Double.valueOf( value ) ); settings.remove ( setting ); break; case WINDOW_HEIGHT: mainStage.setHeight( Double.valueOf( value ) ); settings.remove ( setting ); break; case WINDOW_MAXIMIZED: mainStage.setMaximized( Boolean.valueOf( value ) ); settings.remove ( setting ); break; case PRIMARY_SPLIT_PERCENT: switch ( Hypnos.getOS() ) { case NIX: Platform.runLater ( () -> primarySplitPane.setDividerPosition( 0, Double.valueOf ( value ) ) ); break; default: primarySplitPane.setDividerPosition( 0, Double.valueOf ( value ) ); break; } settings.remove ( setting ); break; case ART_CURRENT_SPLIT_PERCENT: switch ( Hypnos.getOS() ) { case NIX: Platform.runLater ( () -> currentListSplitPane.setDividerPosition( 0, Double.valueOf ( value ) ) ); break; default: currentListSplitPane.setDividerPosition( 0, Double.valueOf ( value ) ); break; } settings.remove ( setting ); break; case ART_SPLIT_PERCENT: switch ( Hypnos.getOS() ) { case NIX: Platform.runLater ( () -> artSplitPane.setDividerPosition( 0, Double.valueOf ( value ) ) ); break; default: artSplitPane.setDividerPosition( 0, Double.valueOf ( value ) ); break; } settings.remove ( setting ); break; case SHOW_SYSTEM_TRAY_ICON: showSystemTray.setValue( Boolean.valueOf( value ) ); settings.remove ( setting ); break; case CLOSE_TO_SYSTEM_TRAY: closeToSystemTray.setValue( Boolean.valueOf( value ) ); settings.remove ( setting ); break; case MINIMIZE_TO_SYSTEM_TRAY: minimizeToSystemTray.setValue( Boolean.valueOf( value ) ); settings.remove ( setting ); break; case PROMPT_BEFORE_OVERWRITE: promptBeforeOverwrite.setValue( Boolean.valueOf( value ) ); settings.remove ( setting ); break; case SHOW_INOTIFY_ERROR_POPUP: showINotifyPopup.setValue( Boolean.valueOf( value ) ); settings.remove ( setting ); break; case SHOW_UPDATE_AVAILABLE_IN_MAIN_WINDOW: showUpdateAvailableInUI.setValue( Boolean.valueOf( value ) ); settings.remove ( setting ); break; case THEME: if ( value.equalsIgnoreCase( "dark" ) ) { applyDarkTheme(); } else { applyLightTheme(); } settings.remove ( setting ); break; case SHOW_LASTFM_IN_UI: this.showLastFMWidgets.set( Boolean.valueOf( value ) ); settings.remove( setting ); break; } } catch ( Exception e ) { LOGGER.log( Level.INFO, "Unable to apply setting: " + setting + " to UI.", e ); } }); libraryPane.applySettingsBeforeWindowShown( settings ); currentListPane.applySettingsBeforeWindowShown( settings ); settingsWindow.updateSettingsBeforeWindowShown(); } public Stage getMainStage () { return mainStage; } @Override public void playerPositionChanged ( int positionMS, int lengthMS ) { Platform.runLater( () -> { int timeElapsedS = positionMS / 1000; int timeRemainingS = ( lengthMS / 1000 ) - timeElapsedS; double percent = positionMS / (double)lengthMS; updateTransport( timeElapsedS, timeRemainingS, percent ); }); } @Override public void playerStopped ( Track track, StopReason reason ) { transport.playerStopped ( track, reason ); } @Override public void playerStarted ( Track track ) { Platform.runLater( () -> { transport.playerStarted ( track ); currentListPane.currentListTable.refresh(); }); } @Override public void playerPaused () { Platform.runLater( () -> { transport.togglePlayButton.setGraphic( transport.playImage ); currentListPane.currentListTable.refresh(); //To get the play/pause image to update. }); } @Override public void playerUnpaused () { Platform.runLater( () -> { transport.togglePlayButton.setGraphic( transport.pauseImage ); currentListPane.currentListTable.refresh();//To get the play/pause image to update. }); } @Override public void playerVolumeChanged ( double newVolumePercent ) { transport.playerVolumeChanged( newVolumePercent ); } @Override public void playerShuffleModeChanged ( ShuffleMode newMode ) { Platform.runLater( () -> { currentListPane.updateShuffleButtonImages(); }); } @Override public void playerRepeatModeChanged ( RepeatMode newMode ) { Platform.runLater( () -> { currentListPane.updateRepeatButtonImages(); }); } public void libraryCleared() { artSplitPane.libraryCleared(); } public void refreshHotkeyList () { settingsWindow.refreshHotkeyFields(); } public void warnUserPlaylistsNotSaved ( List <Playlist> errors ) { if ( doPlaylistSaveWarning ) { Platform.runLater( () -> { doPlaylistSaveWarning = false; Alert alert = new Alert( AlertType.ERROR ); double x = mainStage.getX() + mainStage.getWidth() / 2 - 220; //It'd be nice to use alert.getWidth() / 2, but it's NAN now. double y = mainStage.getY() + mainStage.getHeight() / 2 - 50; setAlertWindowIcon( alert ); applyCurrentTheme( alert ); alert.setX( x ); alert.setY( y ); alert.setTitle( "Warning" ); alert.setHeaderText( "Unable to save playlists." ); String message = "Unable to save the following playlists to the default playlist directory. " + "You may want to manually export them before exiting, so your data is not lost.\n"; for ( Playlist playlist : errors ) { if ( playlist != null ) { message += "\n" + playlist.getName(); } } Text text = new Text( message ); text.setWrappingWidth(500); text.getStyleClass().add( "alert-text" ); HBox holder = new HBox(); holder.getChildren().add( text ); holder.setPadding( new Insets ( 10, 10, 10, 10 ) ); alert.getDialogPane().setContent( holder ); alert.showAndWait(); }); } } public void warnUserAlbumsMissing ( List <Album> missing ) { Platform.runLater( () -> { Alert alert = new Alert( AlertType.ERROR ); double x = mainStage.getX() + mainStage.getWidth() / 2 - 220; //It'd be nice to use alert.getWidth() / 2, but it's NAN now. double y = mainStage.getY() + mainStage.getHeight() / 2 - 50; alert.setX( x ); alert.setY( y ); setAlertWindowIcon( alert ); applyCurrentTheme( alert ); alert.setTitle( "Unable to load Albums" ); alert.setHeaderText( "Albums have been deleted or moved." ); String message = "Unable to load the following albums because the folder is missing. If you recently moved or renamed the folder " + "hypnos will find and load the new location soon (as long as its in your library load path)."; for ( Album album : missing ) { if ( album != null ) { message += "\n\n" + album.getPath(); } } Text text = new Text( message ); text.setWrappingWidth(500); text.getStyleClass().add( "alert-text" ); HBox holder = new HBox(); holder.getChildren().add( text ); holder.setPadding( new Insets ( 10, 10, 10, 10 ) ); alert.getDialogPane().setContent( holder ); alert.showAndWait(); }); } public File promptUserForPlaylistFile() { FileChooser fileChooser = new FileChooser(); FileChooser.ExtensionFilter fileExtensions = new FileChooser.ExtensionFilter( "M3U Playlists", Arrays.asList( "*.m3u" ) ); fileChooser.getExtensionFilters().add( fileExtensions ); fileChooser.setTitle( "Export Playlist" ); fileChooser.setInitialFileName( "new-playlist.m3u" ); File targetFile = fileChooser.showSaveDialog( mainStage ); return targetFile; } public File promptUserForFolder() { DirectoryChooser dirChooser = new DirectoryChooser(); dirChooser.setTitle( "Export Playlist As Folder" ); File targetFile = dirChooser.showDialog( mainStage ); return targetFile; } public void alertUser ( AlertType type, String title, String header, String content ) { Alert alert = new Alert( type ); alert.getDialogPane().applyCss(); double x = mainStage.getX() + mainStage.getWidth() / 2 - 220; //It'd be nice to use alert.getWidth() / 2, but it's NAN now. double y = mainStage.getY() + mainStage.getHeight() / 2 - 50; alert.setX( x ); alert.setY( y ); alert.setTitle( title ); alert.setHeaderText( header ); setAlertWindowIcon ( alert ); applyCurrentTheme ( alert ); TextArea textArea = new TextArea(); textArea.setEditable( false ); textArea.setWrapText( true ); textArea.setText( content ); alert.getDialogPane().setContent( textArea ); alert.showAndWait(); } public Track getCurrentImagesTrack() { return artSplitPane.getCurrentImagesTrack(); } public void openWebBrowser ( String url ) { switch ( Hypnos.getOS() ) { case NIX: { try { new ProcessBuilder("x-www-browser", url ).start(); } catch ( Exception e ) { LOGGER.log( Level.INFO, "Unable to open web browser.", e ); } break; } case OSX: { Runtime rt = Runtime.getRuntime(); try { rt.exec("open " + url); } catch ( Exception e ) { LOGGER.log( Level.INFO, "Unable to open web browser.", e ); } break; } case WIN_10: case WIN_7: case WIN_8: case WIN_UNKNOWN: case WIN_VISTA: case UNKNOWN: { try { Desktop.getDesktop().browse( new URI ( url ) ); } catch ( Exception e ) { try { Runtime rt = Runtime.getRuntime(); rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } catch ( Exception e2 ) { LOGGER.log( Level.INFO, "Unable to open web browser.", e ); } } break; } case WIN_XP: //Do nothing, Win XP not supported break; } } public void setUpdateAvailable ( boolean updateAvailable ) { this.updateAvailable.setValue( updateAvailable ); } public void goToAlbumOfTrack ( Track track ) { Album album = track.getAlbum(); if ( album == null ) { LOGGER.log(Level.INFO, "Requested to 'go to album' of a track that is not part of an album, ignoring.", new NullPointerException() ); return; } libraryPane.clearAlbumFilter(); libraryPane.albumPane.albumTable.getSelectionModel().clearSelection(); libraryPane.albumPane.albumTable.getSelectionModel().select( album ); libraryPane.albumPane.albumTable.requestFocus(); libraryPane.albumPane.albumTable.scrollTo( album ); libraryPane.setAlbumsVisible( true ); if ( isLibraryCollapsed() ) setLibraryCollapsed( false ); libraryPane.showAndSelectAlbumTab(); } public void goToArtistOfTrack ( Track track ) { if ( track == null ) { LOGGER.log(Level.INFO, "Requested to 'go to artist' of a track that is null, ignoring.", new NullPointerException() ); return; } Artist artist = null; for ( Artist libraryArtist : library.getArtistData() ) { if ( libraryArtist.getName().matches(track.getAlbumArtist()) ) { artist = libraryArtist; break; } } if ( artist == null ) { LOGGER.log(Level.INFO, "Requested to 'go to artist' of a track that is not part of an album, ignoring.", new NullPointerException() ); return; } libraryPane.clearArtistFilter(); libraryPane.artistPane.artistTable.getSelectionModel().clearSelection(); libraryPane.artistPane.artistTable.getSelectionModel().select( artist ); libraryPane.artistPane.artistTable.requestFocus(); libraryPane.artistPane.artistTable.scrollTo( artist ); libraryPane.setArtistsVisible ( true ); if ( isLibraryCollapsed() ) setLibraryCollapsed( false ); libraryPane.showAndSelectArtistTab(); } public void setLibraryLabelsToLoading () { libraryPane.setLabelsToLoading(); } public void trackSelected ( Track newSelection ) { artSplitPane.trackSelected( newSelection ); if ( lyricsWindow.isShowing() ) { lyricsWindow.setTrack( newSelection ); } if ( trackInfoWindow.isShowing() ) { trackInfoWindow.setTrack( newSelection ); } } public void albumSelected ( Album album ) { artSplitPane.albumSelected( album ); if ( albumInfoWindow.isShowing() ) { albumInfoWindow.setAlbum( album ); } } public void artistSelected ( Artist artist ) { artSplitPane.artistSelected( artist ); if ( artistInfoWindow.isShowing() ) { artistInfoWindow.setArtist( artist ); } } public LibraryPane getLibraryPane () { return libraryPane; } public CurrentListPane getCurrentListPane () { return currentListPane; } public void setCurrentListFilterText ( String string ) { currentListPane.infoLabelAndFilter.setText ( string ); } /* Give it a source for the UI change so only that source can set it to standby * Avoiding overlapping modifications issues w/ threads terminating after other ones start */ private Object statusSource = null; public void setLibraryLoaderStatus ( String message, double percentDone, Object source ) { Platform.runLater( () -> { this.libraryLocationWindow.setLoaderStatus ( message, percentDone ); statusSource = source; }); } //The programmer can send a null source in if he wants to force a standby status public void setLibraryLoaderStatusToStandby ( Object source ) { if ( statusSource == null || source == null || statusSource == source ) { Platform.runLater( () -> { this.libraryLocationWindow.setLibraryLoaderStatusToStandby ( ); }); } } public void notifyUserLinuxInotifyIssue () { if ( showINotifyPopup.get() ) { Platform.runLater( () -> { Alert alert = new Alert( AlertType.WARNING ); double x = mainStage.getX() + mainStage.getWidth() / 2 - 220; //It'd be nice to use alert.getWidth() / 2, but it's NAN now. double y = mainStage.getY() + mainStage.getHeight() / 2 - 50; alert.setX( x ); alert.setY( y ); alert.setDialogPane( new DialogPane() { @Override protected Node createDetailsButton () { CheckBox optOut = new CheckBox(); optOut.setPadding( new Insets ( 0, 20, 0, 0 ) ); optOut.setText( "Do not show popup again" ); optOut.setOnAction( e -> { showINotifyPopup.set( !optOut.isSelected() ); }); return optOut; } }); if ( warningAlertImageSource != null ) { ImageView warningImage = new ImageView ( warningAlertImageSource ); if ( isDarkTheme() ) { warningImage.setEffect( darkThemeButtonEffect ); } else { warningImage.setEffect( lightThemeButtonEffect ); } warningImage.setFitHeight( 50 ); warningImage.setFitWidth( 50 ); alert.setGraphic( warningImage ); } setAlertWindowIcon ( alert ); applyCurrentTheme ( alert ); alert.getDialogPane().getButtonTypes().addAll( ButtonType.OK ); Label message = new Label ( "Hypnos is unable to watch for changes in some library\n" + "directories due to system defined Linux inotify count\n" + "limitations.\n\n" + "This error is non-fatal: your full library will be\n" + "rescanned each time Hypnos is started, so any changes\n" + "will be included in Hypnos's library eventually. However\n" + "you will not get real-time updates when the file system\n" + "changes.\n\n" + "If you would like real time updates (which are kind of nice)\n" + "You can adjust this limit by editing your sysctl.conf file.\n\n" ); Hyperlink link = new Hyperlink ( "Click here for detailed instructions." ); link.setOnAction( e -> { openWebBrowser( HypnosURLS.HELP_INOTIFY ); } ); VBox content = new VBox(); content.getChildren().addAll ( message, link ); alert.getDialogPane().setContent( content ); alert.getDialogPane().setExpandableContent( new Group() ); alert.getDialogPane().setExpanded( false ); alert.getDialogPane().setGraphic( alert.getDialogPane().getGraphic() ); alert.setTitle( "Unable to Watch for Changes" ); alert.setHeaderText( null ); Optional <ButtonType> result = alert.showAndWait(); if ( result.isPresent() ) { return; } return; }); } } public TrayIcon getTrayIcon () { return trayIcon; } } class LineNumbersCellFactory<T, E> implements Callback<TableColumn<T, E>, TableCell<T, E>> { @Override public TableCell<T, E> call(TableColumn<T, E> param) { return new TableCell<T, E>() { @Override protected void updateItem(E item, boolean empty) { super.updateItem(item, empty); if (!empty) { setText(this.getTableRow().getIndex() + 1 + ""); } else { setText(""); } } }; } } class FixedOrderButtonDialog extends DialogPane { @Override protected Node createButtonBar () { ButtonBar node = (ButtonBar) super.createButtonBar(); node.setButtonOrder( ButtonBar.BUTTON_ORDER_NONE ); return node; } }
65,038
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
LibraryTrackPane.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/fxui/LibraryTrackPane.java
package net.joshuad.hypnos.fxui; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.EnumMap; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.ListChangeListener; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.CheckMenuItem; import javafx.scene.control.ContextMenu; import javafx.scene.control.Label; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.scene.control.SelectionMode; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.Tooltip; import javafx.scene.control.TableColumn.SortType; import javafx.scene.control.TableRow; import javafx.scene.control.TableView.ResizeFeatures; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.effect.ColorAdjust; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.ClipboardContent; import javafx.scene.input.Dragboard; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.TransferMode; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.text.TextAlignment; import net.joshuad.hypnos.AlphanumComparator; import net.joshuad.hypnos.Hypnos; import net.joshuad.hypnos.Persister; import net.joshuad.hypnos.AlphanumComparator.CaseHandling; import net.joshuad.hypnos.Persister.Setting; import net.joshuad.hypnos.audio.AudioSystem; import net.joshuad.hypnos.fxui.DraggedTrackContainer.DragSource; import net.joshuad.hypnos.library.Library; import net.joshuad.hypnos.library.Playlist; import net.joshuad.hypnos.library.Track; public class LibraryTrackPane extends BorderPane { private static final Logger LOGGER = Logger.getLogger( LibraryTrackPane.class.getName() ); private FXUI ui; private AudioSystem audioSystem; private Library library; CheckBox filterAlbumsCheckBox; ThrottledTrackFilter tableFilter; TextField filterBox; HBox filterPane; ContextMenu columnSelectorMenu; TableView <Track> trackTable; TableColumn<Track, String> artistColumn, lengthColumn, albumColumn, titleColumn; TableColumn<Track, Number> numberColumn; Label filteredListLabel = new Label( "No tracks match." ); Label loadingListLabel = new Label( "Loading..." ); Label noColumnsLabel = new Label( "All columns hidden." ); Label emptyListLabel = new Label( "No tracks loaded. To add to your library, click on the + button or drop folders here." ); private ImageView addSourceImage, filterClearImage; public LibraryTrackPane ( FXUI ui, AudioSystem audioSystem, Library library ) { this.library = library; this.audioSystem = audioSystem; this.ui = ui; setupCheckBox(); setupTrackFilterPane(); setupTrackTable(); resetTableSettingsToDefault(); filterPane.prefWidthProperty().bind( widthProperty() ); setTop( filterPane ); setCenter( trackTable ); library.getTracksSorted().addListener( new ListChangeListener<Track>() { @Override public void onChanged(Change<? extends Track> arg0) { updatePlaceholders(); } }); artistColumn.visibleProperty().addListener( e -> updatePlaceholders() ); lengthColumn.visibleProperty().addListener( e -> updatePlaceholders() ); albumColumn.visibleProperty().addListener( e -> updatePlaceholders() ); titleColumn.visibleProperty().addListener( e -> updatePlaceholders() ); numberColumn.visibleProperty().addListener( e -> updatePlaceholders() ); resetTableSettingsToDefault(); } public void updatePlaceholders() { Platform.runLater( () -> { boolean someVisible = false; for ( TableColumn<?,?> column : trackTable.getColumns() ) { if ( column.isVisible() ) { someVisible = true; break; } } if ( !someVisible ) { trackTable.setPlaceholder( noColumnsLabel ); } else if ( library.getTrackDisplayCache().isEmpty() ) { if ( trackTable.getPlaceholder() != emptyListLabel ) { trackTable.setPlaceholder( emptyListLabel ); } } else { if ( !trackTable.getPlaceholder().equals( filteredListLabel ) ) { trackTable.setPlaceholder( filteredListLabel ); } } }); } public void setupCheckBox() { filterAlbumsCheckBox = new CheckBox( "" ); filterAlbumsCheckBox.selectedProperty().addListener( new ChangeListener <Boolean> () { @Override public void changed( ObservableValue <? extends Boolean> observable, Boolean oldValue, Boolean newValue ) { tableFilter.setFilter( filterBox.getText(), newValue ); } }); filterAlbumsCheckBox.getStyleClass().add ( "filterAlbumsCheckBox" ); filterAlbumsCheckBox.setTooltip( new Tooltip( "Only show tracks not in albums" ) ); } public void setupTrackFilterPane () { tableFilter = new ThrottledTrackFilter ( library.getTracksFiltered() ); filterPane = new HBox(); filterBox = new TextField(); filterBox.setPrefWidth( 500000 ); filterBox.textProperty().addListener( new ChangeListener <String> () { @Override public void changed ( ObservableValue <? extends String> observable, String oldValue, String newValue ) { tableFilter.setFilter( newValue, filterAlbumsCheckBox.isSelected() ); } }); filterBox.setOnKeyPressed( ( KeyEvent event ) -> { if ( event.getCode() == KeyCode.ESCAPE ) { filterBox.clear(); if ( filterBox.getText().length() > 0 ) { filterBox.clear(); } else { trackTable.requestFocus(); } event.consume(); } else if ( event.getCode() == KeyCode.DOWN ) { trackTable.requestFocus(); trackTable.getSelectionModel().select( trackTable.getSelectionModel().getFocusedIndex() ); } else if ( event.getCode() == KeyCode.ENTER && !event.isAltDown() && !event.isShiftDown() && !event.isControlDown() && !event.isMetaDown() ) { event.consume(); Track playMe = trackTable.getSelectionModel().getSelectedItem(); if( playMe != null ) { audioSystem.playTrack( playMe ); } } else if ( event.getCode() == KeyCode.ENTER && event.isShiftDown() && !event.isAltDown() && !event.isControlDown() && !event.isMetaDown() ) { event.consume(); Track playMe = trackTable.getSelectionModel().getSelectedItem(); if( playMe != null ) { audioSystem.getQueue().queueTrack( playMe ); } } else if ( event.getCode() == KeyCode.ENTER && event.isControlDown() && !event.isAltDown() && !event.isShiftDown() && !event.isMetaDown() ) { event.consume(); Track playMe = trackTable.getSelectionModel().getSelectedItem(); if( playMe != null ) { audioSystem.getCurrentList().appendTrack( playMe ); } } }); double width = 33; float height = Hypnos.getOS().isWindows() ? 28 : 26; filterBox.setPrefHeight( height ); String addLocation = "resources/add.png"; String clearLocation = "resources/clear.png"; try { double currentListControlsButtonFitWidth = 15; double currentListControlsButtonFitHeight = 15; Image image = new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( addLocation ).toFile() ) ); addSourceImage = new ImageView ( image ); addSourceImage.setFitWidth( currentListControlsButtonFitWidth ); addSourceImage.setFitHeight( currentListControlsButtonFitHeight ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to load add icon: " + addLocation, e ); } try { Image clearImage = new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( clearLocation ).toFile() ) ); filterClearImage = new ImageView ( clearImage ); filterClearImage.setFitWidth( 12 ); filterClearImage.setFitHeight( 12 ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to load clear icon: " + clearLocation, e ); } Button libraryButton = new Button( ); libraryButton.setGraphic( addSourceImage ); libraryButton.setMinSize( width, height ); libraryButton.setPrefSize( width, height ); libraryButton.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent e ) { if ( ui.libraryLocationWindow.isShowing() ) { ui.libraryLocationWindow.hide(); } else { ui.libraryLocationWindow.show(); } } } ); Button clearButton = new Button ( ); clearButton.setGraphic( filterClearImage ); clearButton.setMinSize( width, height ); clearButton.setPrefSize( width, height ); clearButton.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent e ) { filterBox.setText( "" ); } }); libraryButton.setTooltip( new Tooltip( "Add or Remove Music Folders" ) ); filterBox.setTooltip ( new Tooltip ( "Filter/Search tracks" ) ); clearButton.setTooltip( new Tooltip( "Clear the filter text" ) ); HBox checkBoxMargins = new HBox(); checkBoxMargins.setPadding( new Insets ( 4, 0, 0, 6 ) ); checkBoxMargins.getChildren().add( filterAlbumsCheckBox ); filterPane.getChildren().addAll( libraryButton, filterBox, clearButton, checkBoxMargins ); } public void setupTrackTable () { artistColumn = new TableColumn<Track, String>( "Artist" ); lengthColumn = new TableColumn<Track, String>( "Length" ); numberColumn = new TableColumn<Track, Number>( "#" ); albumColumn = new TableColumn<Track, String>( "Album" ); titleColumn = new TableColumn<Track, String>( "Title" ); artistColumn.setComparator( new AlphanumComparator( CaseHandling.CASE_INSENSITIVE ) ); //titleColumn.setComparator( new AlphanumComparator( CaseHandling.CASE_INSENSITIVE ) ); lengthColumn.setComparator( new AlphanumComparator( CaseHandling.CASE_INSENSITIVE ) ); artistColumn.setCellValueFactory( cellData -> cellData.getValue().getArtistProperty() ); titleColumn.setCellValueFactory( cellData -> cellData.getValue().getTitleProperty() ); lengthColumn.setCellValueFactory( new PropertyValueFactory <Track, String>( "LengthDisplay" ) ); numberColumn.setCellValueFactory( cellData -> cellData.getValue().getTrackNumberProperty() ); albumColumn.setCellValueFactory( cellData -> cellData.getValue().getAlbumTitleProperty() ); artistColumn.setSortType( TableColumn.SortType.ASCENDING ); numberColumn.setCellFactory( column -> { return new TableCell <Track, Number>() { @Override protected void updateItem ( Number value, boolean empty ) { super.updateItem( value, empty ); if ( value == null || value.equals( Track.NO_TRACK_NUMBER ) || empty ) { setText( null ); } else { setText( value.toString() ); } } }; } ); columnSelectorMenu = new ContextMenu (); CheckMenuItem artistMenuItem = new CheckMenuItem ( "Show Artist Column" ); CheckMenuItem albumMenuItem = new CheckMenuItem ( "Show Album Column" ); CheckMenuItem numberMenuItem = new CheckMenuItem ( "Show Track # Column" ); CheckMenuItem titleMenuItem = new CheckMenuItem ( "Show Title Column" ); CheckMenuItem lengthMenuItem = new CheckMenuItem ( "Show Length Column" ); MenuItem defaultMenuItem = new MenuItem ( "Reset to Default View" ); artistMenuItem.setSelected( true ); albumMenuItem.setSelected( true ); numberMenuItem.setSelected( true ); titleMenuItem.setSelected( true ); lengthMenuItem.setSelected( true ); columnSelectorMenu.getItems().addAll( artistMenuItem, albumMenuItem, numberMenuItem, titleMenuItem, lengthMenuItem, defaultMenuItem ); artistColumn.setContextMenu( columnSelectorMenu ); albumColumn.setContextMenu( columnSelectorMenu ); titleColumn.setContextMenu( columnSelectorMenu ); numberColumn.setContextMenu( columnSelectorMenu ); lengthColumn.setContextMenu( columnSelectorMenu ); artistMenuItem.selectedProperty().bindBidirectional( artistColumn.visibleProperty() ); albumMenuItem.selectedProperty().bindBidirectional( albumColumn.visibleProperty() ); numberMenuItem.selectedProperty().bindBidirectional( numberColumn.visibleProperty() ); titleMenuItem.selectedProperty().bindBidirectional( titleColumn.visibleProperty() ); lengthMenuItem.selectedProperty().bindBidirectional( lengthColumn.visibleProperty() ); defaultMenuItem.setOnAction( ( e ) -> this.resetTableSettingsToDefault() ); trackTable = new TableView<Track>(); trackTable.getColumns().addAll( artistColumn, albumColumn, numberColumn, titleColumn, lengthColumn ); trackTable.setEditable( false ); trackTable.setItems( library.getTracksSorted() ); library.getTracksSorted().comparatorProperty().bind( trackTable.comparatorProperty() ); trackTable.getSelectionModel().clearSelection(); HypnosResizePolicy resizePolicy = new HypnosResizePolicy(); trackTable.setColumnResizePolicy( resizePolicy ); resizePolicy.registerFixedWidthColumns( numberColumn, lengthColumn ); emptyListLabel.setPadding( new Insets( 20, 10, 20, 10 ) ); emptyListLabel.setWrapText( true ); emptyListLabel.setTextAlignment( TextAlignment.CENTER ); trackTable.setPlaceholder( emptyListLabel ); trackTable.getSelectionModel().setSelectionMode( SelectionMode.MULTIPLE ); Menu lastFMMenu = new Menu( "LastFM" ); MenuItem loveMenuItem = new MenuItem ( "Love" ); MenuItem unloveMenuItem = new MenuItem ( "Unlove" ); MenuItem scrobbleMenuItem = new MenuItem ( "Scrobble" ); lastFMMenu.getItems().addAll ( loveMenuItem, unloveMenuItem, scrobbleMenuItem ); lastFMMenu.setVisible ( false ); lastFMMenu.visibleProperty().bind( ui.showLastFMWidgets ); loveMenuItem.setOnAction( ( event ) -> { ui.audioSystem.getLastFM().loveTrack( trackTable.getSelectionModel().getSelectedItem() ); }); unloveMenuItem.setOnAction( ( event ) -> { ui.audioSystem.getLastFM().unloveTrack( trackTable.getSelectionModel().getSelectedItem() ); }); scrobbleMenuItem.setOnAction( ( event ) -> { ui.audioSystem.getLastFM().scrobbleTrack( trackTable.getSelectionModel().getSelectedItem() ); }); ContextMenu trackContextMenu = new ContextMenu(); MenuItem playMenuItem = new MenuItem( "Play" ); MenuItem playNextMenuItem = new MenuItem( "Play Next" ); MenuItem appendMenuItem = new MenuItem( "Append" ); MenuItem enqueueMenuItem = new MenuItem( "Enqueue" ); MenuItem editTagMenuItem = new MenuItem( "Edit Tag(s)" ); MenuItem infoMenuItem = new MenuItem( "Info" ); MenuItem lyricsMenuItem = new MenuItem( "Lyrics" ); MenuItem goToAlbumMenuItem = new MenuItem( "Go to Album" ); MenuItem browseMenuItem = new MenuItem( "Browse Folder" ); Menu addToPlaylistMenuItem = new Menu( "Add to Playlist" ); trackContextMenu.getItems().addAll ( playMenuItem, playNextMenuItem, appendMenuItem, enqueueMenuItem, editTagMenuItem, infoMenuItem, lyricsMenuItem, goToAlbumMenuItem, browseMenuItem, addToPlaylistMenuItem, lastFMMenu ); MenuItem newPlaylistButton = new MenuItem( "<New>" ); addToPlaylistMenuItem.getItems().add( newPlaylistButton ); newPlaylistButton.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent e ) { ui.promptAndSavePlaylist ( trackTable.getSelectionModel().getSelectedItems() ); } }); EventHandler<ActionEvent> addToPlaylistHandler = new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { Playlist playlist = (Playlist) ((MenuItem) event.getSource()).getUserData(); ui.addToPlaylist ( trackTable.getSelectionModel().getSelectedItems(), playlist ); } }; library.getPlaylistsSorted().addListener( ( ListChangeListener.Change <? extends Playlist> change ) -> { ui.updatePlaylistMenuItems( addToPlaylistMenuItem.getItems(), addToPlaylistHandler ); } ); ui.updatePlaylistMenuItems( addToPlaylistMenuItem.getItems(), addToPlaylistHandler ); playMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { List <Track> selectedItems = new ArrayList <> ( trackTable.getSelectionModel().getSelectedItems() ); if ( selectedItems.size() == 1 ) { audioSystem.playItems( selectedItems ); } else if ( selectedItems.size() > 1 ) { if ( ui.okToReplaceCurrentList() ) { audioSystem.playItems( selectedItems ); } } } }); appendMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { audioSystem.getCurrentList().appendTracks ( trackTable.getSelectionModel().getSelectedItems() ); } }); playNextMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { audioSystem.getQueue().queueAllTracks( trackTable.getSelectionModel().getSelectedItems(), 0 ); } }); enqueueMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { audioSystem.getQueue().queueAllTracks( trackTable.getSelectionModel().getSelectedItems() ); } }); editTagMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { List<Track> tracks = trackTable.getSelectionModel().getSelectedItems(); ui.tagWindow.setTracks( tracks, null ); ui.tagWindow.show(); } }); infoMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { ui.trackInfoWindow.setTrack( trackTable.getSelectionModel().getSelectedItem() ); ui.trackInfoWindow.show(); } }); lyricsMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { ui.lyricsWindow.setTrack( trackTable.getSelectionModel().getSelectedItem() ); ui.lyricsWindow.show(); } }); goToAlbumMenuItem.setOnAction( ( event ) -> { ui.goToAlbumOfTrack ( trackTable.getSelectionModel().getSelectedItem() ); }); browseMenuItem.setOnAction( new EventHandler <ActionEvent>() { // PENDING: This is the better way, once openjdk and openjfx supports // it: getHostServices().showDocument(file.toURI().toString()); @Override public void handle ( ActionEvent event ) { ui.openFileBrowser ( trackTable.getSelectionModel().getSelectedItem().getPath() ); } }); trackTable.setOnKeyPressed( ( KeyEvent e ) -> { if ( e.getCode() == KeyCode.ESCAPE && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { if ( filterBox.getText().length() > 0 ) { filterBox.clear(); Platform.runLater( ()-> trackTable.scrollTo( trackTable.getSelectionModel().getSelectedItem() ) ); } else { trackTable.getSelectionModel().clearSelection(); } } else if ( e.getCode() == KeyCode.L && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { lyricsMenuItem.fire(); } else if ( e.getCode() == KeyCode.Q && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { enqueueMenuItem.fire(); } else if ( e.getCode() == KeyCode.Q && e.isShiftDown() && !e.isAltDown() && !e.isControlDown() && !e.isMetaDown() ) { playNextMenuItem.fire(); } else if ( e.getCode() == KeyCode.G && e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { goToAlbumMenuItem.fire(); } else if ( e.getCode() == KeyCode.F2 && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { editTagMenuItem.fire(); } else if ( e.getCode() == KeyCode.F3 && !e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { infoMenuItem.fire(); e.consume(); } else if ( e.getCode() == KeyCode.F4 && !e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { browseMenuItem.fire(); e.consume(); } else if ( e.getCode() == KeyCode.ENTER && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { playMenuItem.fire(); e.consume(); } else if ( e.getCode() == KeyCode.ENTER && e.isShiftDown() && !e.isAltDown() && !e.isControlDown() && !e.isMetaDown() ) { audioSystem.getCurrentList().insertTracks( 0, trackTable.getSelectionModel().getSelectedItems() ); e.consume(); } else if ( e.getCode() == KeyCode.ENTER && e.isControlDown() && !e.isShiftDown() && !e.isAltDown() && !e.isMetaDown() ) { appendMenuItem.fire(); e.consume(); } else if ( e.getCode() == KeyCode.UP ) { if ( trackTable.getSelectionModel().getSelectedIndex() == 0 ) { filterBox.requestFocus(); } } }); trackTable.getSelectionModel().selectedItemProperty().addListener( ( obs, oldSelection, newSelection ) -> { if (newSelection != null) { ui.trackSelected ( newSelection ); } else if ( audioSystem.getCurrentTrack() != null ) { ui.trackSelected ( audioSystem.getCurrentTrack() ); } else { //Do nothing, leave the old artwork there. We can set to null if we like that better, //I don't think so though } }); trackTable.setOnDragOver( event -> { Dragboard db = event.getDragboard(); if ( db.hasFiles() ) { event.acceptTransferModes( TransferMode.COPY ); event.consume(); } }); trackTable.setOnDragDropped( event -> { Dragboard db = event.getDragboard(); if ( db.hasFiles() ) { List <File> files = db.getFiles(); for ( File file : files ) { library.addMusicRoot( file.toPath() ); } event.setDropCompleted( true ); event.consume(); } }); trackTable.setRowFactory( tv -> { TableRow <Track> row = new TableRow <>(); row.itemProperty().addListener( (obs, oldValue, newValue ) -> { if ( newValue != null ) { row.setContextMenu( trackContextMenu ); } else { row.setContextMenu( null ); } }); row.setOnMouseClicked( event -> { if ( event.getClickCount() == 2 && (!row.isEmpty()) ) { audioSystem.playTrack( row.getItem(), false ); } }); row.setOnContextMenuRequested( event -> { goToAlbumMenuItem.setDisable( row.getItem().getAlbum() == null ); }); row.setOnDragOver( event -> { Dragboard db = event.getDragboard(); if ( db.hasFiles() ) { event.acceptTransferModes( TransferMode.COPY ); event.consume(); } }); row.setOnDragDropped( event -> { Dragboard db = event.getDragboard(); if ( db.hasFiles() ) { List <File> files = db.getFiles(); for ( File file : files ) { library.addMusicRoot( file.toPath() ); } event.setDropCompleted( true ); event.consume(); } }); row.setOnDragDetected( event -> { if ( !row.isEmpty() ) { ArrayList <Integer> indices = new ArrayList <Integer>( trackTable.getSelectionModel().getSelectedIndices() ); ArrayList <Track> tracks = new ArrayList <Track>( trackTable.getSelectionModel().getSelectedItems() ); DraggedTrackContainer dragObject = new DraggedTrackContainer( indices, tracks, null, null, null, DragSource.TRACK_LIST ); Dragboard db = row.startDragAndDrop( TransferMode.COPY ); db.setDragView( row.snapshot( null, null ) ); ClipboardContent cc = new ClipboardContent(); cc.put( FXUI.DRAGGED_TRACKS, dragObject ); db.setContent( cc ); event.consume(); } }); return row; } ); } public void resetTableSettingsToDefault() { artistColumn.setVisible( true ); lengthColumn.setVisible( false ); numberColumn.setVisible( true ); albumColumn.setVisible( true ); titleColumn.setVisible( true ); trackTable.getColumns().remove( artistColumn ); trackTable.getColumns().add( artistColumn ); trackTable.getColumns().remove( albumColumn ); trackTable.getColumns().add( albumColumn ); trackTable.getColumns().remove( numberColumn ); trackTable.getColumns().add( numberColumn ); trackTable.getColumns().remove( titleColumn ); trackTable.getColumns().add( titleColumn ); trackTable.getColumns().remove( lengthColumn ); trackTable.getColumns().add( lengthColumn ); trackTable.getSortOrder().clear(); artistColumn.setSortType( SortType.ASCENDING ); albumColumn.setSortType( SortType.ASCENDING ); numberColumn.setSortType( SortType.ASCENDING ); trackTable.getSortOrder().add( artistColumn ); trackTable.getSortOrder().add( albumColumn ); trackTable.getSortOrder().add( numberColumn ); artistColumn.setPrefWidth( 100 ); numberColumn.setPrefWidth( 40 ); albumColumn.setPrefWidth( 100 ); lengthColumn.setPrefWidth( 60 ); titleColumn.setPrefWidth( 100 ); trackTable.getColumnResizePolicy().call(new ResizeFeatures<Track> ( trackTable, null, 0d ) ); } @SuppressWarnings("incomplete-switch") public void applySettingsBeforeWindowShown ( EnumMap<Persister.Setting, String> settings ) { settings.forEach( ( setting, value )-> { try { switch ( setting ) { case HIDE_ALBUM_TRACKS: ui.runThreadSafe ( () -> filterAlbumsCheckBox.setSelected( Boolean.valueOf ( value ) ) ); settings.remove ( setting ); break; case TR_TABLE_ARTIST_COLUMN_SHOW: artistColumn.setVisible( Boolean.valueOf ( value ) ); settings.remove ( setting ); break; case TR_TABLE_NUMBER_COLUMN_SHOW: numberColumn.setVisible( Boolean.valueOf ( value ) ); settings.remove ( setting ); break; case TR_TABLE_TITLE_COLUMN_SHOW: titleColumn.setVisible( Boolean.valueOf ( value ) ); settings.remove ( setting ); break; case TR_TABLE_ALBUM_COLUMN_SHOW: albumColumn.setVisible( Boolean.valueOf ( value ) ); settings.remove ( setting ); break; case TR_TABLE_LENGTH_COLUMN_SHOW: lengthColumn.setVisible( Boolean.valueOf ( value ) ); settings.remove ( setting ); break; case TR_TABLE_ARTIST_COLUMN_WIDTH: artistColumn.setPrefWidth( Double.valueOf( value ) ); settings.remove ( setting ); break; case TR_TABLE_NUMBER_COLUMN_WIDTH: numberColumn.setPrefWidth( Double.valueOf( value ) ); settings.remove ( setting ); break; case TR_TABLE_TITLE_COLUMN_WIDTH: titleColumn.setPrefWidth( Double.valueOf( value ) ); settings.remove ( setting ); break; case TR_TABLE_ALBUM_COLUMN_WIDTH: albumColumn.setPrefWidth( Double.valueOf( value ) ); settings.remove ( setting ); break; case TR_TABLE_LENGTH_COLUMN_WIDTH: lengthColumn.setPrefWidth( Double.valueOf( value ) ); settings.remove ( setting ); break; case TRACK_COLUMN_ORDER: { String[] order = value.split( " " ); int newIndex = 0; for ( String columnName : order ) { try { if ( columnName.equals( "artist" ) ) { trackTable.getColumns().remove( artistColumn ); trackTable.getColumns().add( newIndex, artistColumn ); } else if ( columnName.equals( "length" ) ) { trackTable.getColumns().remove( lengthColumn ); trackTable.getColumns().add( newIndex, lengthColumn ); } else if ( columnName.equals( "number" ) ) { trackTable.getColumns().remove( numberColumn ); trackTable.getColumns().add( newIndex, numberColumn ); } else if ( columnName.equals( "album" ) ) { trackTable.getColumns().remove( albumColumn ); trackTable.getColumns().add( newIndex, albumColumn ); } else if ( columnName.equals( "title" ) ) { trackTable.getColumns().remove( titleColumn ); trackTable.getColumns().add( newIndex, titleColumn ); } newIndex++; } catch ( Exception e ) { LOGGER.log( Level.INFO, "Unable to set album table column order: '" + value + "'", e ); } } settings.remove ( setting ); break; } case TRACK_SORT_ORDER: { trackTable.getSortOrder().clear(); if ( !value.equals( "" ) ) { String[] order = value.split( " " ); for ( String fullValue : order ) { try { String columnName = fullValue.split( "-" )[0]; SortType sortType = SortType.valueOf( fullValue.split( "-" )[1] ); if ( columnName.equals( "artist" ) ) { trackTable.getSortOrder().add( artistColumn ); artistColumn.setSortType( sortType ); } else if ( columnName.equals( "length" ) ) { trackTable.getSortOrder().add( lengthColumn ); lengthColumn.setSortType( sortType ); } else if ( columnName.equals( "number" ) ) { trackTable.getSortOrder().add( numberColumn ); numberColumn.setSortType( sortType ); } else if ( columnName.equals( "album" ) ) { trackTable.getSortOrder().add( albumColumn ); albumColumn.setSortType( sortType ); } else if ( columnName.equals( "title" ) ) { trackTable.getSortOrder().add( titleColumn ); titleColumn.setSortType( sortType ); } } catch ( Exception e ) { LOGGER.log( Level.INFO, "Unable to set album table sort order: '" + value + "'", e ); } } } settings.remove ( setting ); break; } } } catch ( Exception e ) { LOGGER.log( Level.INFO, "Unable to apply setting: " + setting + " to UI.", e ); } }); } public void applyDarkTheme ( ColorAdjust buttonColor ) { if ( filterClearImage != null ) filterClearImage.setEffect( buttonColor ); if ( addSourceImage != null ) addSourceImage.setEffect( buttonColor ); } public void applyLightTheme () { if ( filterClearImage != null ) filterClearImage.setEffect( ui.lightThemeButtonEffect ); if ( addSourceImage != null ) addSourceImage.setEffect( ui.lightThemeButtonEffect ); } public EnumMap<Persister.Setting, ? extends Object> getSettings () { EnumMap <Persister.Setting, Object> retMe = new EnumMap <Persister.Setting, Object> ( Persister.Setting.class ); String trackColumnOrderValue = ""; for ( TableColumn<Track, ?> column : trackTable.getColumns() ) { if ( column == artistColumn ) { trackColumnOrderValue += "artist "; } else if ( column == lengthColumn ) { trackColumnOrderValue += "length "; } else if ( column == numberColumn ) { trackColumnOrderValue += "number "; } else if ( column == albumColumn ) { trackColumnOrderValue += "album "; } else if ( column == titleColumn ) { trackColumnOrderValue += "title "; } } retMe.put ( Setting.TRACK_COLUMN_ORDER, trackColumnOrderValue ); String trackSortValue = ""; for ( TableColumn<Track, ?> column : trackTable.getSortOrder() ) { if ( column == artistColumn ) { trackSortValue += "artist-" + artistColumn.getSortType() + " "; } else if ( column == lengthColumn ) { trackSortValue += "length-" + lengthColumn.getSortType() + " "; } else if ( column == numberColumn ) { trackSortValue += "number-" + numberColumn.getSortType() + " "; } else if ( column == albumColumn ) { trackSortValue += "album-" + albumColumn.getSortType() + " "; } else if ( column == titleColumn ) { trackSortValue += "title-" + titleColumn.getSortType() + " "; } } retMe.put ( Setting.TRACK_SORT_ORDER, trackSortValue ); retMe.put ( Setting.TR_TABLE_ARTIST_COLUMN_SHOW, artistColumn.isVisible() ); retMe.put ( Setting.TR_TABLE_NUMBER_COLUMN_SHOW, numberColumn.isVisible() ); retMe.put ( Setting.TR_TABLE_TITLE_COLUMN_SHOW, titleColumn.isVisible() ); retMe.put ( Setting.TR_TABLE_ALBUM_COLUMN_SHOW, albumColumn.isVisible() ); retMe.put ( Setting.TR_TABLE_LENGTH_COLUMN_SHOW, lengthColumn.isVisible() ); retMe.put ( Setting.TR_TABLE_ARTIST_COLUMN_WIDTH, artistColumn.getPrefWidth() ); retMe.put ( Setting.TR_TABLE_NUMBER_COLUMN_WIDTH, numberColumn.getPrefWidth() ); retMe.put ( Setting.TR_TABLE_TITLE_COLUMN_WIDTH, titleColumn.getPrefWidth() ); retMe.put ( Setting.TR_TABLE_ALBUM_COLUMN_WIDTH, albumColumn.getPrefWidth() ); retMe.put ( Setting.TR_TABLE_LENGTH_COLUMN_WIDTH, lengthColumn.getPrefWidth() ); retMe.put ( Setting.HIDE_ALBUM_TRACKS, filterAlbumsCheckBox.isSelected() ); return retMe; } public void focusFilter() { trackTable.requestFocus(); filterBox.requestFocus(); trackTable.getSelectionModel().clearSelection(); } }
33,436
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
LibraryPane.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/fxui/LibraryPane.java
package net.joshuad.hypnos.fxui; import java.util.ArrayList; import java.util.EnumMap; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.scene.Node; import javafx.scene.control.CheckMenuItem; import javafx.scene.control.ContextMenu; import javafx.scene.control.TableView; import javafx.scene.control.ToggleButton; import javafx.scene.control.ToggleGroup; import javafx.scene.control.Tooltip; import javafx.scene.effect.ColorAdjust; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import net.joshuad.hypnos.Persister; import net.joshuad.hypnos.audio.AudioSystem; import net.joshuad.hypnos.library.Library; import net.joshuad.hypnos.Persister.Setting; public class LibraryPane extends BorderPane { private static final Logger LOGGER = Logger.getLogger( LibraryPane.class.getName() ); FXUI ui; AudioSystem audioSystem; Library library; LibraryArtistPane artistPane; LibraryAlbumPane albumPane; LibraryTrackPane trackPane; LibraryPlaylistPane playlistPane; ContextMenu tabMenu; CheckMenuItem showArtists, showAlbums, showTracks, showPlaylists; ToggleGroup buttonGroup; ToggleButton artistsButton, albumsButton, tracksButton, playlistsButton; HBox buttonBox; public LibraryPane ( FXUI ui, AudioSystem audioSystem, Library library ) { this.ui = ui; this.audioSystem = audioSystem; this.library = library; artistPane = new LibraryArtistPane ( ui, audioSystem, library ); albumPane = new LibraryAlbumPane ( ui, audioSystem, library ); trackPane = new LibraryTrackPane ( ui, audioSystem, library ); playlistPane = new LibraryPlaylistPane ( ui, audioSystem, library ); tabMenu = new ContextMenu(); showArtists = new CheckMenuItem ( "Artists" ); showAlbums = new CheckMenuItem ( "Albums" ); showTracks = new CheckMenuItem ( "Tracks" ); showPlaylists = new CheckMenuItem ( "Playlists" ); tabMenu.getItems().addAll( showArtists, showAlbums, showTracks, showPlaylists ); showArtists.setSelected( true ); showAlbums.setSelected( true ); showTracks.setSelected( true ); showPlaylists.setSelected( true ); showArtists.selectedProperty().addListener( ( observable, oldValue, newValue ) -> { setArtistsVisible ( newValue ); }); showAlbums.selectedProperty().addListener( ( observable, oldValue, newValue ) -> { setAlbumsVisible ( newValue ); }); showTracks.selectedProperty().addListener( ( observable, oldValue, newValue ) -> { setTracksVisible ( newValue ); }); showPlaylists.selectedProperty().addListener( ( observable, oldValue, newValue ) -> { setPlaylistsVisible ( newValue ); }); artistsButton = new ToggleButton( "Artists" ); albumsButton = new ToggleButton( "Albums" ); tracksButton = new ToggleButton( "Tracks" ); playlistsButton = new ToggleButton( "Playlists" ); artistsButton.setContextMenu( tabMenu ); albumsButton.setContextMenu( tabMenu ); tracksButton.setContextMenu( tabMenu ); playlistsButton.setContextMenu( tabMenu ); artistsButton.setPrefHeight( 32 ); albumsButton.setPrefHeight( 32 ); tracksButton.setPrefHeight( 32 ); playlistsButton.setPrefHeight( 32 ); artistsButton.setOnAction( e -> { setCenter( artistPane ); artistsButton.setSelected ( true ); }); albumsButton.setOnAction( e -> { setCenter( albumPane ); albumsButton.setSelected ( true ); } ); tracksButton.setOnAction( e -> { setCenter( trackPane ); tracksButton.setSelected ( true ); } ); playlistsButton.setOnAction( e -> { setCenter( playlistPane ); playlistsButton.setSelected ( true ); } ); buttonGroup = new ToggleGroup(); artistsButton.setToggleGroup( buttonGroup ); albumsButton.setToggleGroup( buttonGroup ); tracksButton.setToggleGroup( buttonGroup ); playlistsButton.setToggleGroup( buttonGroup ); artistsButton.setPrefWidth ( 1000000 ); albumsButton.setPrefWidth ( 1000000 ); tracksButton.setPrefWidth ( 1000000 ); playlistsButton.setPrefWidth ( 1000000 ); artistsButton.setMinWidth ( 0 ); albumsButton.setMinWidth ( 0 ); tracksButton.setMinWidth ( 0 ); playlistsButton.setMinWidth ( 0 ); setupTooltip ( artistsButton, library.getArtistDisplayCache(), "Artist Count: " ); setupTooltip ( albumsButton, library.getAlbumDisplayCache(), "Album Count: " ); setupTooltip ( tracksButton, library.getTrackDisplayCache(), "Track Count: " ); setupTooltip ( playlistsButton, library.getPlaylistsDisplayCache(), "Playlist Count: " ); buttonBox = new HBox(); buttonBox.getChildren().addAll( artistsButton, albumsButton, tracksButton, playlistsButton ); buttonBox.maxWidthProperty().bind( this.widthProperty().subtract( 1 ) ); artistsButton.fire(); setBottom ( buttonBox ); setMinWidth( 0 ); } private void setupTooltip ( ToggleButton button, ObservableList<? extends Object> list, String text ) { Tooltip tooltip = new Tooltip ( text + list.size() ); button.setTooltip( tooltip ); list.addListener( new ListChangeListener<Object> () { @Override public void onChanged ( Change <? extends Object> changed ) { tooltip.setText( text + list.size() ); } }); } private void fixButtonOrder() { List<Node> buttons = new ArrayList<Node> ( buttonBox.getChildren() ); List<Node> reorderedButtons = new ArrayList<> ( buttons.size() ); if ( buttons.contains( artistsButton ) ) { reorderedButtons.add( artistsButton ); } if ( buttons.contains( albumsButton ) ) { reorderedButtons.add( albumsButton ); } if ( buttons.contains( tracksButton ) ) { reorderedButtons.add( tracksButton ); } if ( buttons.contains( playlistsButton ) ) { reorderedButtons.add( playlistsButton ); } buttonBox.getChildren().remove( artistsButton ); buttonBox.getChildren().remove( albumsButton ); buttonBox.getChildren().remove( tracksButton ); buttonBox.getChildren().remove( playlistsButton ); buttonBox.getChildren().addAll( reorderedButtons ); } public void setArtistsVisible ( boolean makeVisible ) { if ( makeVisible ) { if ( !buttonBox.getChildren().contains( artistsButton ) ) { buttonBox.getChildren().add( artistsButton ); showArtists.setSelected( true ); fixButtonOrder(); artistsButton.fire(); artistsButton.requestFocus(); } } else { if ( buttonBox.getChildren().size() >= 2 ) { buttonBox.getChildren().remove( artistsButton ); fixButtonOrder(); showArtists.setSelected( false ); //TODO: I kind of hate this solution, but it is what I could find. Thread delayedAction = new Thread ( () -> { try { Thread.sleep ( 50 ); } catch (InterruptedException e) {} Platform.runLater( ()-> ((ToggleButton)buttonBox.getChildren().get( 0 )).fire() ); }); delayedAction.start(); } else { showArtists.setSelected( true ); } } } public void setAlbumsVisible ( boolean visible ) { if ( visible ) { if ( !buttonBox.getChildren().contains( albumsButton ) ) { buttonBox.getChildren().add( albumsButton ); albumsButton.fire(); showAlbums.setSelected( true ); fixButtonOrder(); albumsButton.fire(); albumsButton.requestFocus(); } } else { if ( buttonBox.getChildren().size() >= 2 ) { buttonBox.getChildren().remove( albumsButton ); showAlbums.setSelected( false ); fixButtonOrder(); //TODO: I kind of hate this solution, but it is what I could find. Thread delayedAction = new Thread ( () -> { try { Thread.sleep ( 50 ); } catch (InterruptedException e) {} Platform.runLater( ()-> ((ToggleButton)buttonBox.getChildren().get( 0 )).fire() ); }); delayedAction.start(); } } } public void setTracksVisible ( boolean visible ) { if ( visible ) { if ( !buttonBox.getChildren().contains( tracksButton ) ) { buttonBox.getChildren().add( tracksButton ); showTracks.setSelected( true ); fixButtonOrder(); tracksButton.fire(); tracksButton.requestFocus(); } } else { if ( buttonBox.getChildren().size() >= 2 ) { buttonBox.getChildren().remove( tracksButton ); showTracks.setSelected( false ); fixButtonOrder(); //TODO: I kind of hate this solution, but it is what I could find. Thread delayedAction = new Thread ( () -> { try { Thread.sleep ( 50 ); } catch (InterruptedException e) {} Platform.runLater( ()-> ((ToggleButton)buttonBox.getChildren().get( 0 )).fire() ); }); delayedAction.start(); } } } public void setPlaylistsVisible ( boolean visible ) { if ( visible ) { if ( !buttonBox.getChildren().contains( playlistsButton ) ) { buttonBox.getChildren().add( playlistsButton ); showPlaylists.setSelected( true ); fixButtonOrder(); playlistsButton.fire(); playlistsButton.requestFocus(); } } else { if ( buttonBox.getChildren().size() >= 2 ) { buttonBox.getChildren().remove( playlistsButton ); showPlaylists.setSelected( false ); fixButtonOrder(); //TODO: I kind of hate this solution, but it is what I could find. Thread delayedAction = new Thread ( () -> { try { Thread.sleep ( 50 ); } catch (InterruptedException e) {} Platform.runLater( ()-> ((ToggleButton)buttonBox.getChildren().get( 0 )).fire() ); }); delayedAction.start(); } } } /* Begin: These three methods go together */ private boolean attachEmptySelectorMenu( TableView<?> table, ContextMenu menu ) { Node blankHeader = table.lookup(".column-header-background"); if ( blankHeader != null ) { blankHeader.setOnContextMenuRequested ( event -> menu.show( blankHeader, event.getScreenX(), event.getScreenY() )); return true; } else { return false; } } private void attachEmptySelectorMenuLater( Pane pane, TableView<?> table, ContextMenu menu ) { final ChangeListener<Node> listener = new ChangeListener<Node>() { @Override public void changed ( ObservableValue< ? extends Node> obs, Node oldCenter, Node newCenter ) { if ( newCenter == pane ) { Thread runMe = new Thread( () -> { try { Thread.sleep( 50 ); } catch (InterruptedException e) {} Platform.runLater( () -> { attachEmptySelectorMenu ( table, menu ); centerProperty().removeListener( this ); }); }); runMe.start(); } } }; this.centerProperty().addListener( listener ); } private void setupEmptyTableHeaderConextMenu ( Pane pane, TableView<?> table, ContextMenu menu ) { boolean artistAttached = attachEmptySelectorMenu ( table, menu ); if ( !artistAttached ) { attachEmptySelectorMenuLater ( pane, table, menu ); } } /* End: These three methods go together */ public void doAfterShowProcessing () { setupEmptyTableHeaderConextMenu ( artistPane, artistPane.artistTable, artistPane.columnSelectorMenu ); setupEmptyTableHeaderConextMenu ( albumPane, albumPane.albumTable, albumPane.columnSelectorMenu ); setupEmptyTableHeaderConextMenu ( trackPane, trackPane.trackTable, trackPane.columnSelectorMenu ); setupEmptyTableHeaderConextMenu ( playlistPane, playlistPane.playlistTable, playlistPane.columnSelectorMenu ); } public void applyDarkTheme ( ColorAdjust buttonColor ) { artistPane.applyDarkTheme ( buttonColor ); albumPane.applyDarkTheme( buttonColor ); trackPane.applyDarkTheme( buttonColor ); playlistPane.applyDarkTheme( buttonColor ); } public void applyLightTheme () { artistPane.applyLightTheme(); albumPane.applyLightTheme(); trackPane.applyLightTheme(); playlistPane.applyLightTheme(); } public void focusFilterOfCurrentTab () { if( buttonGroup.getSelectedToggle() == artistsButton ) { artistPane.focusFilter(); } else if( buttonGroup.getSelectedToggle() == albumsButton ) { albumPane.focusFilter(); } else if( buttonGroup.getSelectedToggle() == tracksButton ) { trackPane.focusFilter(); } else if( buttonGroup.getSelectedToggle() == playlistsButton ) { playlistPane.focusFilter(); } } @SuppressWarnings("incomplete-switch") public void applySettingsBeforeWindowShown ( EnumMap<Persister.Setting, String> settings ) { settings.forEach( ( setting, value )-> { try { switch ( setting ) { } } catch ( Exception e ) { LOGGER.log( Level.INFO, "Unable to apply setting: " + setting + " to UI.", e ); } }); artistPane.applySettingsBeforeWindowShown ( settings ); albumPane.applySettingsBeforeWindowShown ( settings ); trackPane.applySettingsBeforeWindowShown ( settings ); playlistPane.applySettingsBeforeWindowShown ( settings ); } @SuppressWarnings("incomplete-switch") public void applySettingsAfterWindowShown ( EnumMap <Setting, String> settings ) { settings.forEach( ( setting, value )-> { try { switch ( setting ) { case LIBRARY_TAB_ARTISTS_VISIBLE: showArtists.setSelected ( Boolean.valueOf ( value ) ); settings.remove ( setting ); break; case LIBRARY_TAB_ALBUMS_VISIBLE: showAlbums.setSelected ( Boolean.valueOf ( value ) ); settings.remove ( setting ); break; case LIBRARY_TAB_TRACKS_VISIBLE: showTracks.setSelected ( Boolean.valueOf ( value ) ); settings.remove ( setting ); break; case LIBRARY_TAB_PLAYLISTS_VISIBLE: showPlaylists.setSelected ( Boolean.valueOf ( value ) ); settings.remove ( setting ); break; case LIBRARY_TAB: ToggleButton selectMe = (ToggleButton)buttonBox.getChildren().get ( Integer.valueOf ( value ) ); selectMe.fire(); settings.remove ( setting ); break; } } catch ( Exception e ) { LOGGER.log( Level.INFO, "Unable to apply setting: " + setting + " to UI.", e ); } }); } public EnumMap<Persister.Setting, ? extends Object> getSettings () { EnumMap <Persister.Setting, Object> retMe = new EnumMap <Persister.Setting, Object> ( Persister.Setting.class ); retMe.put ( Setting.LIBRARY_TAB, buttonBox.getChildren().indexOf( (ToggleButton)buttonGroup.getSelectedToggle() ) ); retMe.put ( Setting.LIBRARY_TAB_ARTISTS_VISIBLE, buttonBox.getChildren().contains( artistsButton ) ); retMe.put ( Setting.LIBRARY_TAB_ALBUMS_VISIBLE, buttonBox.getChildren().contains( albumsButton ) ); retMe.put ( Setting.LIBRARY_TAB_TRACKS_VISIBLE, buttonBox.getChildren().contains( tracksButton ) ); retMe.put ( Setting.LIBRARY_TAB_PLAYLISTS_VISIBLE, buttonBox.getChildren().contains( playlistsButton ) ); EnumMap <Persister.Setting, ? extends Object> artistTabSettings = artistPane.getSettings(); for ( Persister.Setting setting : artistTabSettings.keySet() ) { retMe.put( setting, artistTabSettings.get( setting ) ); } EnumMap <Persister.Setting, ? extends Object> albumTabSettings = albumPane.getSettings(); for ( Persister.Setting setting : albumTabSettings.keySet() ) { retMe.put( setting, albumTabSettings.get( setting ) ); } EnumMap <Persister.Setting, ? extends Object> trackTabSettings = trackPane.getSettings(); for ( Persister.Setting setting : trackTabSettings.keySet() ) { retMe.put( setting, trackTabSettings.get( setting ) ); } EnumMap <Persister.Setting, ? extends Object> playlistTabSettings = playlistPane.getSettings(); for ( Persister.Setting setting : playlistTabSettings.keySet() ) { retMe.put( setting, playlistTabSettings.get( setting ) ); } return retMe; } public void setLabelsToLoading () { //TODO: Clean this up it's all twisted artistPane.artistTable.setPlaceholder( artistPane.loadingListLabel ); albumPane.albumTable.setPlaceholder( albumPane.loadingListLabel ); trackPane.trackTable.setPlaceholder( trackPane.loadingListLabel ); playlistPane.playlistTable.setPlaceholder( playlistPane.loadingLabel ); } public void clearAlbumFilter () { //TODO: clean this up albumPane.filterBox.setText( "" ); } public void clearArtistFilter () { //TODO: clean this up artistPane.filterBox.setText( "" ); } public void selectPane(int i) { List<Node> children = buttonBox.getChildren(); if ( i >= 0 && i < children.size() ) { ToggleButton button = (ToggleButton)children.get( i ); if ( button != null ) { button.fire(); } } } public void showAndSelectAlbumTab() { albumsButton.fire(); } public void showAndSelectArtistTab() { artistsButton.fire(); } public void updatePlaceholders() { artistPane.updatePlaceholders(); albumPane.updatePlaceholders(); trackPane.updatePlaceholders(); playlistPane.updatePlaceholders(); } }
16,879
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
TagWindow.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/fxui/TagWindow.java
package net.joshuad.hypnos.fxui; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.file.Files; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; import org.jaudiotagger.audio.AudioFile; import org.jaudiotagger.audio.AudioFileIO; import org.jaudiotagger.tag.FieldKey; import org.jaudiotagger.tag.KeyNotFoundException; import org.jaudiotagger.tag.Tag; import org.jaudiotagger.tag.images.Artwork; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.scene.control.TableColumn.CellEditEvent; import javafx.scene.control.TableRow; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.Priority; import javafx.scene.layout.VBox; import javafx.scene.text.TextAlignment; import javafx.stage.FileChooser; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.util.Callback; import net.joshuad.hypnos.CurrentListTrack; import net.joshuad.hypnos.Hypnos; import net.joshuad.hypnos.MultiFileImageTagPair; import net.joshuad.hypnos.MultiFileTextTagPair; import net.joshuad.hypnos.Utils; import net.joshuad.hypnos.audio.AudioSystem; import net.joshuad.hypnos.MultiFileImageTagPair.ImageFieldKey; import net.joshuad.hypnos.library.Album; import net.joshuad.hypnos.library.Track; @SuppressWarnings("rawtypes") public class TagWindow extends Stage { private static transient final Logger LOGGER = Logger.getLogger( TagWindow.class.getName() ); List<Track> tracks; List<Album> albums; List <FieldKey> supportedTextTags = Arrays.asList ( FieldKey.ARTIST, FieldKey.ALBUM_ARTIST, FieldKey.TITLE, FieldKey.ALBUM, FieldKey.YEAR, FieldKey.ORIGINAL_YEAR, FieldKey.TRACK, FieldKey.DISC_SUBTITLE, FieldKey.DISC_NO, FieldKey.DISC_TOTAL, FieldKey.MUSICBRAINZ_RELEASE_TYPE //TODO: Think about TITLE_SORT, ALBUM_SORT, ORIGINAL_YEAR -- we read them. ); List <FieldKey> hiddenTextTagsList = Arrays.asList( ); final ObservableList <MultiFileTextTagPair> textTagPairs = FXCollections.observableArrayList(); final ObservableList <MultiFileImageTagPair> imageTagPairs = FXCollections.observableArrayList(); BorderPane controlPanel = new BorderPane(); TableColumn<MultiFileTextTagPair, String> textTagColumn; TableColumn<MultiFileTextTagPair, String> textValueColumn; TableColumn imageTagColumn; TableColumn imageValueColumn; TableColumn imageDeleteColumn; Button previousButton; Button nextButton; private TextField locationField; private HBox locationBox; private FXUI ui; AudioSystem audioSystem; public TagWindow( FXUI ui, AudioSystem audioSystem ) { super(); this.ui = ui; this.audioSystem = audioSystem; this.initModality( Modality.NONE ); this.initOwner( ui.getMainStage() ); this.setTitle( "Tag Editor" ); this.setWidth( 600 ); this.setHeight ( 500 ); Pane root = new Pane(); Scene scene = new Scene( root ); try { getIcons().add( new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( "resources" + File.separator + "icon.png" ).toFile() ) ) ); } catch ( FileNotFoundException e ) { LOGGER.log( Level.WARNING, "Unable to load program icon: resources/icon.png", e ); } VBox textTagPane = new VBox(); textTagColumn = new TableColumn<>( "Tag" ); textValueColumn = new TableColumn<>( "Value" ); textTagColumn.setStyle( "-fx-alignment: CENTER-RIGHT; -fx-font-weight: bold; -fx-padding: 0 10 0 0; "); textTagColumn.setMaxWidth( 350000 ); textValueColumn.setMaxWidth( 650000 ); textValueColumn.setEditable( true ); textTagColumn.setCellValueFactory( new PropertyValueFactory <MultiFileTextTagPair, String>( "TagName" ) ); textValueColumn.setCellValueFactory( new PropertyValueFactory <MultiFileTextTagPair, String>( "Value" ) ); textValueColumn.setCellFactory(c -> EditOnClickCell.createStringEditCell()); textValueColumn.setOnEditCommit( new EventHandler <CellEditEvent <MultiFileTextTagPair, String>>() { @Override public void handle ( CellEditEvent <MultiFileTextTagPair, String> t ) { ((MultiFileTextTagPair) t.getTableView().getItems().get( t.getTablePosition().getRow() )).setValue( t.getNewValue() ); } }); textTagColumn.setSortable( false ); textValueColumn.setSortable( false ); textTagColumn.setReorderable( false ); textValueColumn.setReorderable( false ); TableView <MultiFileTextTagPair> textTagTable = new TableView<MultiFileTextTagPair> (); textTagTable.setItems ( textTagPairs ); textTagTable.getColumns().addAll( textTagColumn, textValueColumn ); textTagTable.setColumnResizePolicy( TableView.CONSTRAINED_RESIZE_POLICY ); textTagTable.setEditable( true ); textTagPane.getChildren().addAll( textTagTable ); textTagTable.prefHeightProperty().bind( textTagPane.heightProperty() ); textTagTable.prefWidthProperty().bind( textTagPane.widthProperty() ); VBox imageTagPane = new VBox(); imageTagColumn = new TableColumn( "Tag" ); imageValueColumn = new TableColumn( "Image" ); imageDeleteColumn = new TableColumn ( "Delete" ); imageTagColumn.setReorderable( false ); imageValueColumn.setReorderable( false ); imageDeleteColumn.setReorderable( false ); imageTagColumn.setStyle( "-fx-alignment: CENTER-RIGHT; -fx-font-weight: bold; -fx-padding: 0 10 0 0; "); imageValueColumn.setStyle( "-fx-alignment: CENTER;"); imageTagColumn.setMaxWidth( 300000 ); imageValueColumn.setMaxWidth( 450000 ); imageDeleteColumn.setMaxWidth( 250000 ); imageTagColumn.setCellValueFactory( new PropertyValueFactory <MultiFileTextTagPair, String>( "TagName" ) ); imageValueColumn.setCellValueFactory( new PropertyValueFactory <MultiFileTextTagPair, byte[]>( "ImageData" ) ); imageTagColumn.setSortable( false ); imageValueColumn.setSortable( false ); imageDeleteColumn.setSortable ( false ); imageValueColumn.setCellFactory( new Callback <TableColumn <MultiFileTextTagPair, byte[]>, TableCell <MultiFileTextTagPair, byte[]>> () { @Override public TableCell <MultiFileTextTagPair, byte[]> call ( TableColumn <MultiFileTextTagPair, byte[]> param ) { TableCell <MultiFileTextTagPair, byte[]> cell = new TableCell <MultiFileTextTagPair, byte[]>() { @Override public void updateItem ( byte[] imageData, boolean empty ) { this.setWrapText( true ); this.setTextAlignment( TextAlignment.CENTER ); if ( imageData == MultiFileImageTagPair.MULTI_VALUE ) { setGraphic( null ); setText ( "Multiple Values" ); } else if ( imageData != null ) { ImageView imageview = new ImageView( new Image( new ByteArrayInputStream( imageData ) ) ); imageview.setFitHeight( 80 ); imageview.setFitWidth( 220 ); imageview.setSmooth( true ); imageview.setCache( true ); imageview.setPreserveRatio( true ); setGraphic( imageview ); setText ( null ); } else if ( !empty ) { setGraphic ( null ); setText ( "No images of this type are embedded in this tag. Hypnos may be reading images from the album or artist folder." ); } else { setGraphic ( null ); setText ( null ); } } }; return cell; } }); Callback <TableColumn <MultiFileImageTagPair, Void>, TableCell <MultiFileImageTagPair, Void>> deleteCellFactory = new Callback <TableColumn <MultiFileImageTagPair, Void>, TableCell <MultiFileImageTagPair, Void>>() { @Override public TableCell call ( final TableColumn <MultiFileImageTagPair, Void> param ) { final TableCell <MultiFileImageTagPair, Void> cell = new TableCell <MultiFileImageTagPair, Void>() { final Button changeButton = new Button( "Set" ); final Button exportButton = new Button( "Export" ); final Button deleteButton = new Button( "Delete" ); final VBox box = new VBox(); { box.getChildren().addAll( changeButton, exportButton, deleteButton ); setGraphic( box ); box.setAlignment( Pos.CENTER ); box.setStyle("-fx-background-color: rgba(0, 0, 0, 0);"); box.setPadding( new Insets ( 10, 0, 10, 0 ) ); changeButton.setMinWidth ( 100 ); deleteButton.setMinWidth ( 100 ); exportButton.setMinWidth ( 100 ); changeButton.setOnAction ( event -> { FileChooser fileChooser = new FileChooser(); FileChooser.ExtensionFilter fileExtensions = new FileChooser.ExtensionFilter( "Image Files", Arrays.asList( "*.jpg", "*.jpeg", "*.png" ) ); fileChooser.getExtensionFilters().add( fileExtensions ); fileChooser.setTitle( "Set Image" ); File targetFile = fileChooser.showOpenDialog( ui.mainStage ); if ( targetFile == null ) return; try { byte[] imageBuffer = Files.readAllBytes( targetFile.toPath() ); ((MultiFileImageTagPair)this.getTableRow().getItem()).setImageData( imageBuffer ); this.getTableRow().getTableView().refresh(); } catch ( IOException e ) { LOGGER.log( Level.WARNING, "Unable to read image data from file: " + targetFile, new NullPointerException() ); } } ); exportButton.setOnAction ( event -> { byte[] data = ((MultiFileImageTagPair)this.getTableRow().getItem()).getImageData(); if ( data != null ) { FileChooser fileChooser = new FileChooser(); FileChooser.ExtensionFilter fileExtensions = new FileChooser.ExtensionFilter( "Image Files", Arrays.asList( "*.png" ) ); fileChooser.getExtensionFilters().add( fileExtensions ); fileChooser.setTitle( "Export Image" ); fileChooser.setInitialFileName( "image.png" ); File targetFile = fileChooser.showSaveDialog( ui.mainStage ); if ( targetFile == null ) return; if ( !targetFile.toString().toLowerCase().endsWith(".png") ) { targetFile = targetFile.toPath().resolveSibling ( targetFile.getName() + ".png" ).toFile(); } try { BufferedImage bImage = ImageIO.read( new ByteArrayInputStream ( data ) ); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); ImageIO.write( bImage, "png", byteStream ); byte[] imageBytes = byteStream.toByteArray(); byteStream.close(); Utils.saveImageToDisk( targetFile.toPath(), imageBytes ); } catch ( IOException ex ) { ui.notifyUserError ( ex.getClass().getCanonicalName() + ": Unable to export image. See log for more information." ); LOGGER.log( Level.WARNING, "Unable to export image.", ex ); } } } ); deleteButton.setOnAction( event -> { ((MultiFileImageTagPair)this.getTableRow().getItem()).setImageData( null ); this.getTableRow().getTableView().refresh(); } ); } @Override public void updateItem ( Void item, boolean empty ) { super.updateItem( item, empty ); if ( empty ) { setGraphic( null ); setText( null ); } else { TableRow row = this.getTableRow(); if ( row != null ) { MultiFileImageTagPair pair = (MultiFileImageTagPair)this.getTableRow().getItem(); if ( pair != null ) { deleteButton.setDisable( pair.getImageData() == null ); exportButton.setDisable( pair.getImageData() == null ); if ( pair.getImageData() == MultiFileImageTagPair.MULTI_VALUE ) { changeButton.setText ( "Change" ); exportButton.setDisable( true ); } else if ( pair.getImageData() == null ) { changeButton.setText ( "Set" ); } else { changeButton.setText ( "Change" ); } } } setGraphic( box ); setText( null ); } } }; return cell; } }; imageDeleteColumn.setCellFactory( deleteCellFactory ); TableView <MultiFileImageTagPair> imageTagTable = new TableView<MultiFileImageTagPair> (); imageTagTable.setItems ( imageTagPairs ); imageTagTable.getColumns().addAll( imageTagColumn, imageValueColumn, imageDeleteColumn ); imageTagTable.setColumnResizePolicy( TableView.CONSTRAINED_RESIZE_POLICY ); imageTagTable.prefWidthProperty().bind( imageTagPane.widthProperty() ); imageTagPane.getChildren().add( imageTagTable ); imageTagTable.prefHeightProperty().bind( imageTagPane.heightProperty() ); imageTagTable.prefWidthProperty().bind( imageTagPane.widthProperty() ); setupControlPanel(); TabPane tabPane = new TabPane(); Tab textTab = new Tab( "Tags" ); Tab imagesTab = new Tab( "Images" ); tabPane.getTabs().addAll( textTab, imagesTab ); tabPane.setTabMinWidth( 100 ); textTab.setClosable( false ); imagesTab.setClosable ( false ); textTab.setContent( textTagPane ); textTagPane.prefWidthProperty().bind( tabPane.widthProperty() ); textTagPane.prefHeightProperty().bind( tabPane.heightProperty() ); imagesTab.setContent( imageTagPane ); imageTagPane.prefWidthProperty().bind( tabPane.widthProperty() ); imageTagPane.prefHeightProperty().bind( tabPane.heightProperty() ); Label label = new Label ( "Location: " ); label.setAlignment( Pos.CENTER_RIGHT ); locationField = new TextField(); locationField.setEditable( false ); locationField.setMaxWidth( Double.MAX_VALUE ); HBox.setHgrow( locationField, Priority.ALWAYS ); Button browseButton = new Button( "Browse" ); browseButton.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { if ( tracks.size() == 1 ) { ui.openFileBrowser( tracks.get( 0 ).getPath() ); } } }); locationBox = new HBox(); locationBox.getChildren().addAll( label, locationField, browseButton ); label.prefHeightProperty().bind( locationBox.heightProperty() ); VBox primaryPane = new VBox(); primaryPane.getChildren().addAll( tabPane, locationBox, controlPanel ); locationBox.prefWidthProperty().bind( primaryPane.widthProperty() ); tabPane.prefWidthProperty().bind( primaryPane.widthProperty() ); tabPane.prefHeightProperty().bind( primaryPane.heightProperty() .subtract( controlPanel.heightProperty() ) .subtract( locationBox.heightProperty() ) ); root.getChildren().add ( primaryPane ); primaryPane.prefWidthProperty().bind( root.widthProperty() ); primaryPane.prefHeightProperty().bind ( root.heightProperty() ); scene.addEventFilter( KeyEvent.KEY_PRESSED, new EventHandler <KeyEvent>() { @Override public void handle ( KeyEvent e ) { if ( e.getCode() == KeyCode.RIGHT && e.isControlDown() ) { nextButton.fire(); e.consume(); } else if ( e.getCode() == KeyCode.LEFT && e.isControlDown() ) { previousButton.fire(); e.consume(); } else if ( e.getCode() == KeyCode.ESCAPE ) { if ( imageTagTable.getEditingCell() == null && textTagTable.getEditingCell() == null ) { close(); e.consume(); } } } }); setScene( scene ); } public void setupControlPanel() { Button saveButton = new Button ( "Save" ); Button revertButton = new Button ( "Revert" ); Button cancelButton = new Button ( "Cancel" ); saveButton.setPrefWidth( 80 ); revertButton.setMinWidth( 80 ); cancelButton.setMinWidth( 80 ); saveButton.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent e ) { saveCurrentTags(); close(); } }); revertButton.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent e ) { setTracks ( tracks, albums, hiddenTextTagsList.toArray(new FieldKey[0]) ); } }); Stage stage = this; cancelButton.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent e ) { stage.hide(); } }); previousButton = new Button ( "< Save & Prev" ); previousButton.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent e ) { saveCurrentTags(); loadAtOffset ( -1 ); } }); nextButton = new Button ( "Save & Next >" ); nextButton.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent e ) { saveCurrentTags(); loadAtOffset ( 1 ); } }); HBox centerPanel = new HBox(); centerPanel.getChildren().addAll ( cancelButton, revertButton, saveButton ); centerPanel.setAlignment( Pos.CENTER ); controlPanel.setCenter ( centerPanel ); controlPanel.setLeft ( previousButton ); controlPanel.setRight ( nextButton ); controlPanel.prefWidthProperty().bind( this.widthProperty() ); controlPanel.setPadding( new Insets( 5 ) ); } private void loadAtOffset ( int offset ) { if ( albums != null ) { List <Album> albumList = ui.library.getAlbumsSorted(); if ( albumList == null || albumList.size() == 0 ) return; int thisIndex = albumList.indexOf( albums.get ( 0 ) ); int targetIndex = 0; if ( thisIndex != -1 ) targetIndex = ( thisIndex + albumList.size() + offset ) % albumList.size(); FieldKey[] hidden = hiddenTextTagsList == null ? null : hiddenTextTagsList.toArray( new FieldKey[hiddenTextTagsList.size()] ); Album nextAlbum = albumList.get( targetIndex ); if ( nextAlbum != null ) setTracks ( nextAlbum.getTracks(), Arrays.asList( nextAlbum ), hidden ); } else if ( tracks != null && tracks.get( 0 ) instanceof CurrentListTrack ) { List <CurrentListTrack> currentList = ui.audioSystem.getCurrentList().getItems(); if ( currentList == null || currentList.size() == 0 ) return; int thisIndex = currentList.indexOf( tracks.get ( 0 ) ); int targetIndex = 0; if ( thisIndex != -1 ) targetIndex = ( thisIndex + currentList.size() + offset ) % currentList.size(); FieldKey[] hidden = hiddenTextTagsList == null ? null : hiddenTextTagsList.toArray( new FieldKey[hiddenTextTagsList.size()] ); Track nextTrack = currentList.get( targetIndex ); if ( nextTrack != null ) setTracks ( Arrays.asList( nextTrack ), albums, hidden ); } else { List <Track> trackList = ui.library.getTracksSorted(); if ( trackList == null || trackList.size() == 0 ) return; int thisIndex = trackList.indexOf( tracks.get ( 0 ) ); int targetIndex = 0; if ( thisIndex != -1 ) targetIndex = ( thisIndex + trackList.size() + offset ) % trackList.size(); FieldKey[] hidden = hiddenTextTagsList == null ? null : hiddenTextTagsList.toArray( new FieldKey[hiddenTextTagsList.size()] ); Track nextTrack = trackList.get( targetIndex ); if ( nextTrack != null ) setTracks ( Arrays.asList( nextTrack ), albums, hidden ); } } private void saveCurrentTags() { List <Track> saveMe = tracks; List <MultiFileTextTagPair> saveMeTextPairs = new ArrayList <>( textTagPairs ); List <MultiFileImageTagPair> saveMeImagePairs = new ArrayList <>( imageTagPairs ); Thread saverThread = new Thread( () -> { if ( saveMe != null ) { for ( Track track : saveMe ) { track.updateTagsAndSave( saveMeTextPairs, saveMeImagePairs, ui.audioSystem ); } } audioSystem.getCurrentList().setHasUnsavedData(true); ui.refreshCurrentList(); ui.refreshQueueList(); ui.refreshImages(); }); saverThread.setName ( "Tag Window Track Updater" ); saverThread.setDaemon( true ); saverThread.start(); } public void setTracks ( List <Track> tracks, List <Album> albumsToRefresh, FieldKey ... hiddenTags ) { setTracks ( tracks, albumsToRefresh, false, hiddenTags ); } public void setTracks ( List <Track> tracks, List <Album> albumsToRefresh, boolean hideCoverArt, FieldKey ... hiddenTags ) { List <Track> nonMissing = new ArrayList <Track> (); for ( Track track : tracks ) if ( Utils.isMusicFile( track.getPath() ) ) nonMissing.add( track ); tracks = nonMissing; textTagPairs.clear(); imageTagPairs.clear(); this.hiddenTextTagsList = Arrays.asList( hiddenTags ); this.tracks = tracks; this.albums = albumsToRefresh; if ( tracks.size() <= 0 ) return; if ( tracks.size() == 1 ) { previousButton.setDisable( false ); nextButton.setDisable ( false ); previousButton.setVisible( true ); nextButton.setVisible( true ); locationField.setText( tracks.get( 0 ).getPath().toString() ); locationBox.setVisible( true ); } else if ( albums != null && albums.size() == 1 ) { previousButton.setDisable( false ); nextButton.setDisable ( false ); previousButton.setVisible( true ); nextButton.setVisible( true ); locationField.setText( albums.get( 0 ).getPath().toString() ); locationBox.setVisible( true ); } else { previousButton.setDisable( true ); nextButton.setDisable ( true ); previousButton.setVisible( false ); nextButton.setVisible( false ); locationBox.setVisible( false ); } try { Track firstTrack = tracks.get( 0 ); AudioFile firstAudioFile = AudioFileIO.read( firstTrack.getPath().toFile() ); Tag firstTag = firstAudioFile.getTag(); if ( firstTag == null ) { firstTag = firstAudioFile.createDefaultTag(); } for ( FieldKey key : supportedTextTags ) { if ( hiddenTextTagsList.contains( key ) ) continue; try { String value = firstTag.getFirst( key ); textTagPairs.add( new MultiFileTextTagPair ( key, value ) ); } catch ( KeyNotFoundException e ) { textTagPairs.add( new MultiFileTextTagPair ( key, "" ) ); } } List<Artwork> firstArtworkList = firstTag.getArtworkList(); for ( ImageFieldKey key : ImageFieldKey.values() ) { boolean added = false; for ( Artwork artwork : firstArtworkList ) { ImageFieldKey artworkKey = ImageFieldKey.getKeyFromTagIndex( artwork.getPictureType() ); if ( artworkKey == key ) { imageTagPairs.add ( new MultiFileImageTagPair ( key, artwork.getBinaryData() ) ); added = true; } } if ( !added ) { imageTagPairs.add ( new MultiFileImageTagPair ( key, null ) ); } } if ( tracks.size() > 1 ) { for ( int k = 1 ; k < tracks.size() ; k++ ) { Track track = tracks.get ( k ); AudioFile audioFile = AudioFileIO.read( track.getPath().toFile() ); Tag tag = audioFile.getTag(); if ( tag == null ) { tag = audioFile.createDefaultTag(); } for ( MultiFileTextTagPair tagPair : textTagPairs ) { FieldKey key = tagPair.getKey(); if ( hiddenTextTagsList.contains( key ) ) continue; try { String value = tag.getFirst( key ); tagPair.anotherFileValue( value ); } catch ( KeyNotFoundException e ) { tagPair.anotherFileValue( null ); } } List<Artwork> artworkList = tag.getArtworkList(); for ( MultiFileImageTagPair tagPair : imageTagPairs ) { for ( Artwork artwork : artworkList ) { ImageFieldKey artworkKey = ImageFieldKey.getKeyFromTagIndex( artwork.getPictureType() ); if ( artworkKey == tagPair.getKey() ) { tagPair.anotherFileValue( artwork.getBinaryData() ); } } } } } List <MultiFileImageTagPair> hideMe = new ArrayList <MultiFileImageTagPair> (); for ( MultiFileImageTagPair tagPair : imageTagPairs ) { if ( tagPair.getKey() == ImageFieldKey.ALBUM_FRONT && hideCoverArt ) { hideMe.add ( tagPair ); } if ( tagPair.getKey() == ImageFieldKey.ALBUM_FRONT || tagPair.getKey() == ImageFieldKey.ARTIST ) { continue; } if ( tagPair.getImageData() == null ) { hideMe.add ( tagPair ); } } imageTagPairs.removeAll( hideMe ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to set data for tag window.", e ); } } }
24,851
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
MusicRootWindow.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/fxui/MusicRootWindow.java
package net.joshuad.hypnos.fxui; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javafx.beans.property.SimpleStringProperty; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.SelectionMode; import javafx.scene.control.Slider; import javafx.scene.control.TableColumn; import javafx.scene.control.TableRow; import javafx.scene.control.TableView; import javafx.scene.control.Tooltip; import javafx.scene.image.Image; import javafx.scene.input.Dragboard; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.TransferMode; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.scene.text.TextAlignment; import javafx.stage.DirectoryChooser; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.util.Callback; import net.joshuad.hypnos.Hypnos; import net.joshuad.hypnos.library.Library; import net.joshuad.hypnos.library.MusicRoot; import net.joshuad.hypnos.library.Library.LoaderSpeed; public class MusicRootWindow extends Stage { private static final Logger LOGGER = Logger.getLogger( MusicRootWindow.class.getName() ); TableView <MusicRoot> musicSourceTable; Library library; Scene scene; Slider prioritySlider; private final ProgressIndicatorBar progressBar; FXUI ui; public MusicRootWindow ( FXUI ui, Stage mainStage, Library library ) { super(); this.ui = ui; this.library = library; initModality( Modality.NONE ); initOwner( mainStage ); setTitle( "Music Search Locations" ); setWidth( 400 ); setHeight( 500 ); Pane root = new Pane(); scene = new Scene( root ); try { getIcons().add( new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( "resources" + File.separator + "icon.png" ).toFile() ) ) ); } catch ( FileNotFoundException e ) { LOGGER.log( Level.WARNING, "Unable to load program icon: resources/icon.png", e ); } VBox primaryPane = new VBox(); musicSourceTable = new TableView<MusicRoot> (); Label emptyLabel = new Label( "No directories in your library. Either '+ Add' or drop directories here." ); emptyLabel.setPadding( new Insets( 20, 10, 20, 10 ) ); emptyLabel.setWrapText( true ); emptyLabel.setTextAlignment( TextAlignment.CENTER ); musicSourceTable.setColumnResizePolicy( TableView.CONSTRAINED_RESIZE_POLICY ); musicSourceTable.setPlaceholder( emptyLabel ); musicSourceTable.setItems( library.getMusicRootDisplayCache() ); musicSourceTable.getSelectionModel().setSelectionMode( SelectionMode.MULTIPLE ); musicSourceTable.widthProperty().addListener( new ChangeListener <Number>() { @Override public void changed ( ObservableValue <? extends Number> source, Number oldWidth, Number newWidth ) { Pane header = (Pane) musicSourceTable.lookup( "TableHeaderRow" ); if ( header.isVisible() ) { header.setMaxHeight( 0 ); header.setMinHeight( 0 ); header.setPrefHeight( 0 ); header.setVisible( false ); } } } ); TableColumn <MusicRoot, String> dirListColumn = new TableColumn<> ( "Location" ); dirListColumn.setCellValueFactory( new Callback <TableColumn.CellDataFeatures <MusicRoot, String>, ObservableValue <String>>() { @Override public ObservableValue <String> call ( TableColumn.CellDataFeatures <MusicRoot, String> p ) { if ( p.getValue() != null ) { return new SimpleStringProperty( p.getValue().getPath().toAbsolutePath().toString() ); } else { return new SimpleStringProperty( "<no name>" ); } } } ); musicSourceTable.setRowFactory( tv -> { TableRow <MusicRoot> row = new TableRow <>(); row.itemProperty().addListener( (obs, oldValue, newValue ) -> { if ( newValue != null && row != null ) { if ( !newValue.validSearchLocationProperty().get() ) { row.getStyleClass().add( "file-missing" ); } else { row.getStyleClass().remove( "file-missing" ); } } }); row.itemProperty().addListener( ( obs, oldValue, newTrackValue ) -> { if ( newTrackValue != null && row != null ) { newTrackValue.validSearchLocationProperty().addListener( ( o, old, newValue ) -> { if ( !newValue ) { row.getStyleClass().add( "file-missing" ); } else { row.getStyleClass().remove( "file-missing" ); } }); } }); return row; }); musicSourceTable.setOnDragDropped( event -> { Dragboard db = event.getDragboard(); if ( db.hasFiles() ) { List <File> files = db.getFiles(); for ( File file : files ) { library.addMusicRoot( file.toPath() ); } event.setDropCompleted( true ); event.consume(); } }); musicSourceTable.getColumns().add( dirListColumn ); musicSourceTable.setOnDragOver( event -> { Dragboard db = event.getDragboard(); if ( db.hasFiles() ) { event.acceptTransferModes( TransferMode.COPY ); event.consume(); } }); DirectoryChooser chooser = new DirectoryChooser(); chooser.setTitle( "Music Folder" ); File defaultDirectory = new File( System.getProperty( "user.home" ) ); // PENDING: start windows on desktop maybe. chooser.setInitialDirectory( defaultDirectory ); Button addButton = new Button( "+ Add" ); Button removeButton = new Button( "- Remove" ); addButton.setPrefWidth( 100 ); removeButton.setPrefWidth( 100 ); addButton.setMinWidth( 100 ); removeButton.setMinWidth( 100 ); MusicRootWindow me = this; addButton.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent e ) { File selectedFile = chooser.showDialog( me ); if ( selectedFile != null ) { library.addMusicRoot( selectedFile.toPath() ); } } }); removeButton.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent e ) { List <MusicRoot> removeMe = new ArrayList<>(musicSourceTable.getSelectionModel().getSelectedItems()); for (MusicRoot musicRoot : removeMe ) { library.removeMusicRoot( musicRoot ); } musicSourceTable.getSelectionModel().clearSelection(); } }); musicSourceTable.setOnKeyPressed( new EventHandler <KeyEvent>() { @Override public void handle ( final KeyEvent keyEvent ) { if ( keyEvent.getCode().equals( KeyCode.DELETE ) ) { for (MusicRoot musicRoot : musicSourceTable.getSelectionModel().getSelectedItems() ) { library.removeMusicRoot( musicRoot ); } } } }); progressBar = new ProgressIndicatorBar(); progressBar.prefWidthProperty().bind( widthProperty() ); progressBar.setPrefHeight( 30 ); HBox controlBox = new HBox(); controlBox.getChildren().addAll( addButton, removeButton); controlBox.setAlignment( Pos.CENTER ); controlBox.prefWidthProperty().bind( widthProperty() ); controlBox.setPadding( new Insets( 5 ) ); Label priorityLabel = new Label ( "Scan Speed:" ); priorityLabel.setTooltip ( new Tooltip ( "How much resources to consume while loading and updating the library.\n(If your computer or hypnos is choppy while loading, try turning this down.)" ) ); priorityLabel.setPadding( new Insets ( 0, 10, 0, 0 ) ); prioritySlider = new Slider ( 1, 3, 1 ); prioritySlider.prefWidthProperty().bind( widthProperty().subtract( 150 ) ); prioritySlider.setShowTickMarks( true ); prioritySlider.setMinorTickCount( 0 ); prioritySlider.setMajorTickUnit( 1 ); prioritySlider.setShowTickLabels( true ); prioritySlider.setSnapToTicks( true ); prioritySlider.valueProperty().addListener( new ChangeListener <Number>() { public void changed ( ObservableValue <? extends Number> oldValueObs, Number oldValue, Number newValue ) { switch ( newValue.intValue() ) { case 1: Hypnos.setLoaderSpeed( LoaderSpeed.LOW ); break; case 2: Hypnos.setLoaderSpeed( LoaderSpeed.MED ); break; case 3: Hypnos.setLoaderSpeed( LoaderSpeed.HIGH ); break; } } } ); Button libraryLogButton = new Button ( "?" ); libraryLogButton.setOnAction( e -> ui.libraryLogWindow.show() ); HBox progressBox = new HBox(); progressBox.getChildren().addAll ( progressBar, libraryLogButton ); HBox priorityBox = new HBox(); priorityBox.getChildren().addAll( priorityLabel, prioritySlider); priorityBox.setAlignment( Pos.CENTER ); priorityBox.prefWidthProperty().bind( widthProperty() ); priorityBox.setPadding( new Insets( 5 ) ); primaryPane.prefWidthProperty().bind( root.widthProperty() ); primaryPane.prefHeightProperty().bind( root.heightProperty() ); musicSourceTable.prefHeightProperty().bind( root.heightProperty() .subtract( controlBox.heightProperty() ) .subtract( progressBox.heightProperty() ) .subtract( priorityBox.heightProperty() ) ); primaryPane.getChildren().addAll( musicSourceTable, progressBox, priorityBox, controlBox ); root.getChildren().add( primaryPane ); setScene( scene ); scene.addEventFilter( KeyEvent.KEY_PRESSED, new EventHandler <KeyEvent>() { @Override public void handle ( KeyEvent e ) { if ( e.getCode() == KeyCode.ESCAPE && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() && !e.isAltDown() ) { hide(); e.consume(); } } }); } public void setLoaderSpeedDisplay ( LoaderSpeed speed ) { switch ( speed ) { case LOW: prioritySlider.setValue( 1 ); break; case MED: prioritySlider.setValue( 2 ); break; case HIGH: prioritySlider.setValue( 3 ); break; } } public void setLoaderStatus ( String message, double percentDone ) { progressBar.setStatus( message, percentDone ); } public void setLibraryLoaderStatusToStandby () { setLoaderStatus ( "", 0 ); } }
10,189
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
FormattedAlbumCell.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/fxui/FormattedAlbumCell.java
package net.joshuad.hypnos.fxui; import javafx.scene.control.ContentDisplay; import javafx.scene.control.Label; import javafx.scene.control.TableCell; import javafx.scene.control.TableRow; import javafx.scene.text.TextFlow; import net.joshuad.hypnos.library.AlbumInfoSource; public class FormattedAlbumCell<T extends AlbumInfoSource> extends TableCell<T, String> { private TextFlow flow; private Label albumName, albumType, albumDisc; public FormattedAlbumCell () { albumName = new Label(); albumType = new Label(); albumDisc = new Label(); albumName.getStyleClass().add( "tableAlbumName" ); albumDisc.getStyleClass().add( "tableAlbumDisc" ); albumType.getStyleClass().add( "tableAlbumType" ); flow = new TextFlow( albumName, albumDisc, albumType ) { @Override protected double computePrefHeight ( double width ) { // quick hack to force into single line return super.computePrefHeight( -1 ); } }; setContentDisplay( ContentDisplay.GRAPHIC_ONLY ); flow.setMinWidth( Double.MAX_VALUE ); setGraphic ( flow ); } @Override protected void updateItem ( String text, boolean empty ) { super.updateItem ( text, empty ); TableRow <T> row = this.getTableRow(); AlbumInfoSource item = null; if ( row != null ) item = row.getItem(); if ( empty || text == null || row == null || item == null ) { albumName.setText ( "" ); albumType.setText ( "" ); albumDisc.setText ( "" ); this.setText ( null ); } else { String title = item.getAlbumTitle(); String releaseType = item.getReleaseType(); String discSubtitle = item.getDiscSubtitle(); Integer discCount = item.getDiscCount(); Integer discNumber = item.getDiscNumber(); this.setText ( text ); albumName.setText( title ); if ( releaseType != null && !releaseType.equals( "" ) ) { albumType.setText ( " [" + releaseType + "]" ); } else { albumType.setText( "" ); } if ( discSubtitle != null && !discSubtitle.equals( "" ) ) { albumDisc.setText( " (" + discSubtitle + ")" ); } else if ( discCount == null && discNumber != null && discNumber > 1 ) { albumDisc.setText( " (Disc " + discNumber + ")" ); } else if ( discCount != null && discCount > 1 && discNumber != null ) { albumDisc.setText( " (Disc " + discNumber + ")" ); } else { albumDisc.setText( "" ); } } } }
2,393
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
LibraryLogWindow.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/fxui/LibraryLogWindow.java
package net.joshuad.hypnos.fxui; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Platform; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.ListView; import javafx.scene.image.Image; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.layout.VBox; import javafx.stage.Modality; import javafx.stage.Stage; import net.joshuad.hypnos.Hypnos; import net.joshuad.hypnos.library.Library; public class LibraryLogWindow extends Stage { private static final Logger LOGGER = Logger.getLogger( LibraryLogWindow.class.getName() ); ListView<String> logView; ObservableList<String> logData = FXCollections.observableArrayList(); Library library; public LibraryLogWindow ( FXUI ui, Library library ) { super(); this.library = library; initModality( Modality.NONE ); initOwner( ui.getMainStage() ); setTitle( "Library Log" ); setWidth( 600 ); setHeight( 600 ); try { getIcons().add( new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( "resources" + File.separator + "icon.png" ).toFile() ) ) ); } catch ( FileNotFoundException e ) { LOGGER.log( Level.WARNING, "Unable to load program icon: resources/icon.png", e ); } VBox root = new VBox(); Scene scene = new Scene( root ); logView = new ListView<>(logData); logView.setEditable( false ); logView.prefHeightProperty().bind( root.heightProperty() ); logView.getStyleClass().add( "monospaced" ); logView.fixedCellSizeProperty().set(24); root.getChildren().add( logView ); setScene( scene ); scene.addEventFilter( KeyEvent.KEY_PRESSED, new EventHandler <KeyEvent>() { @Override public void handle ( KeyEvent e ) { if ( e.getCode() == KeyCode.ESCAPE && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() && !e.isAltDown() ) { hide(); e.consume(); } } }); Thread logReader = new Thread( () -> { while(true) { String[] newData = library.getScanLogger().dumpBuffer().split("\n"); Platform.runLater(() -> { for( String line : newData ) { if(!line.isBlank()) { logData.add(line); } } }); try { Thread.sleep( 1000 ); } catch (InterruptedException e1) { // TODO Auto-generated catch block } } }); logReader.setName( "Library Log UI Text Loader" ); logReader.setDaemon( true ); logReader.start(); } }
2,732
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
TrackInfoWindow.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/fxui/TrackInfoWindow.java
package net.joshuad.hypnos.fxui; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.logging.Level; import java.util.logging.Logger; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.image.Image; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Priority; import javafx.scene.layout.VBox; import javafx.stage.Modality; import javafx.stage.Stage; import net.joshuad.hypnos.Hypnos; import net.joshuad.hypnos.library.Track; public class TrackInfoWindow extends Stage { private static final Logger LOGGER = Logger.getLogger( TrackInfoWindow.class.getName() ); private Track track = null; private TableView <TrackFieldPair> table; Button browseButton; TextField locationField; public TrackInfoWindow ( FXUI ui ) { super(); initModality( Modality.NONE ); initOwner( ui.getMainStage() ); setTitle( "Track Info" ); setWidth( 600 ); setHeight( 400 ); try { getIcons().add( new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( "resources" + File.separator + "icon.png" ).toFile() ) ) ); } catch ( FileNotFoundException e ) { LOGGER.log( Level.WARNING, "Unable to load program icon: resources/icon.png", e ); } BorderPane root = new BorderPane(); Scene scene = new Scene( root ); VBox primaryPane = new VBox(); primaryPane.prefWidthProperty().bind( root.widthProperty() ); primaryPane.prefHeightProperty().bind( root.heightProperty() ); Label label = new Label ( "Location: " ); label.setAlignment( Pos.CENTER_RIGHT ); locationField = new TextField(); locationField.setEditable( false ); locationField.setMaxWidth( Double.MAX_VALUE ); HBox.setHgrow( locationField, Priority.ALWAYS ); browseButton = new Button( "Browse" ); browseButton.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { if ( track != null ) { ui.openFileBrowser( track.getPath() ); } } }); HBox locationBox = new HBox(); locationBox.getChildren().addAll( label, locationField, browseButton ); label.prefHeightProperty().bind( locationBox.heightProperty() ); locationBox.prefWidthProperty().bind( primaryPane.widthProperty() ); table = new TableView <> (); table.setColumnResizePolicy( TableView.CONSTRAINED_RESIZE_POLICY ); table.setEditable( false ); table.prefWidthProperty().bind( primaryPane.widthProperty() ); table.prefHeightProperty().bind( primaryPane.heightProperty() ); TableColumn <TrackFieldPair, String> labelColumn = new TableColumn<> (); TableColumn <TrackFieldPair, Object> valueColumn = new TableColumn<> (); labelColumn.setMaxWidth ( 25000 ); valueColumn.setMaxWidth ( 75000 ); labelColumn.setReorderable ( false ); valueColumn.setReorderable ( false ); labelColumn.setCellValueFactory( new PropertyValueFactory <TrackFieldPair, String> ( "Label" ) ); valueColumn.setCellValueFactory( new PropertyValueFactory <TrackFieldPair, Object> ( "Value" ) ); labelColumn.setText( "Field" ); valueColumn.setText( "Value" ); table.getColumns().addAll( labelColumn, valueColumn ); primaryPane.getChildren().add( table ); root.setTop ( locationBox ); root.setCenter ( primaryPane ); setScene( scene ); scene.addEventFilter( KeyEvent.KEY_PRESSED, new EventHandler <KeyEvent>() { @Override public void handle ( KeyEvent e ) { if ( e.getCode() == KeyCode.ESCAPE && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() && !e.isAltDown() ) { hide(); e.consume(); } } }); } public void setTrack ( Track track ) { this.track = track; table.getItems().clear(); if ( track == null ) return; locationField.setText( track.getPath().toString() ); table.getItems().add ( new TrackFieldPair ( "Title", track.getTitle() ) ); table.getItems().add ( new TrackFieldPair ( "Artist", track.getArtist() ) ); table.getItems().add ( new TrackFieldPair ( "Album", track.getFullAlbumTitle() ) ); table.getItems().add ( new TrackFieldPair ( "Year", track.getYear() ) ); table.getItems().add ( new TrackFieldPair ( "Length", track.getLengthDisplay() ) ); table.getItems().add ( new TrackFieldPair ( "File Name", track.getPath().getFileName().toString() ) ); table.getItems().add ( new TrackFieldPair ( "Encoding", track.getShortEncodingString() ) ); } }
4,834
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
QueueWindow.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/fxui/QueueWindow.java
package net.joshuad.hypnos.fxui; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javafx.beans.property.ReadOnlyObjectWrapper; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.ContextMenu; import javafx.scene.control.Label; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.scene.control.SelectionMode; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.scene.control.TableRow; import javafx.scene.control.TableView; import javafx.scene.control.TableColumn.CellDataFeatures; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.image.Image; import javafx.scene.input.ClipboardContent; import javafx.scene.input.Dragboard; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.TransferMode; import javafx.scene.layout.Pane; import javafx.scene.text.TextAlignment; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.util.Callback; import net.joshuad.hypnos.CurrentListTrack; import net.joshuad.hypnos.Hypnos; import net.joshuad.hypnos.Utils; import net.joshuad.hypnos.audio.AudioSystem; import net.joshuad.hypnos.fxui.DraggedTrackContainer.DragSource; import net.joshuad.hypnos.library.Library; import net.joshuad.hypnos.library.Playlist; import net.joshuad.hypnos.library.Track; public class QueueWindow extends Stage { private static final Logger LOGGER = Logger.getLogger( QueueWindow.class.getName() ); TableView <Track> queueTable; FXUI ui; AudioSystem audioSystem; Library library; public QueueWindow ( FXUI ui, Library library, AudioSystem audioSystem, TagWindow tagWindow ) { super(); this.ui = ui; this.audioSystem = audioSystem; this.library = library; initModality( Modality.NONE ); initOwner( ui.getMainStage() ); setTitle( "Queue" ); setWidth( 500 ); setHeight ( 400 ); Pane root = new Pane(); Scene scene = new Scene( root ); try { getIcons().add( new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( "resources" + File.separator + "icon.png" ).toFile() ) ) ); } catch ( FileNotFoundException e ) { LOGGER.log( Level.WARNING, "Unable to load program icon: resources/icon.png", new NullPointerException() ); } queueTable = new TableView<Track> (); Label emptyLabel = new Label( "Queue is empty." ); emptyLabel.setPadding( new Insets( 20, 10, 20, 10 ) ); emptyLabel.setWrapText( true ); emptyLabel.setTextAlignment( TextAlignment.CENTER ); queueTable.setColumnResizePolicy( TableView.CONSTRAINED_RESIZE_POLICY ); queueTable.setPlaceholder( emptyLabel ); queueTable.setItems( audioSystem.getQueue().getData() ); queueTable.getSelectionModel().setSelectionMode( SelectionMode.MULTIPLE ); queueTable.widthProperty().addListener( new ChangeListener <Number>() { @Override public void changed ( ObservableValue <? extends Number> source, Number oldWidth, Number newWidth ) { Pane header = (Pane) queueTable.lookup( "TableHeaderRow" ); if ( header.isVisible() ) { header.setMaxHeight( 0 ); header.setMinHeight( 0 ); header.setPrefHeight( 0 ); header.setVisible( false ); } } }); queueTable.getSelectionModel().selectedItemProperty().addListener( ( obs, oldSelection, newSelection ) -> { ui.trackSelected ( newSelection ); }); //TODO: I Don't like this <Track, Track> thing, it's inaccurate. //However, if we make it <Track, Integer> or <Track, String>, I get cast error when add something //to th queue and display the queue window. Gotta sort this out. TableColumn<Track, Track> numberColumn = new TableColumn<Track, Track> ( "#" ); TableColumn<Track, String> artistColumn = new TableColumn<Track, String> ( "Artist" ); TableColumn<Track, String> titleColumn = new TableColumn<Track, String> ( "Title" ); numberColumn.setMaxWidth( 10000 ); artistColumn.setMaxWidth( 45000 ); titleColumn.setMaxWidth ( 45000 ); numberColumn.setCellValueFactory( new Callback <CellDataFeatures <Track, Track>, ObservableValue <Track>>() { @SuppressWarnings("rawtypes") //REFACTOR: Figure out how to get rid of this. @Override public ObservableValue <Track> call ( CellDataFeatures <Track, Track> p ) { return new ReadOnlyObjectWrapper ( p.getValue() ); } }); numberColumn.setCellFactory( new Callback <TableColumn <Track, Track>, TableCell <Track, Track>>() { @Override public TableCell <Track, Track> call ( TableColumn <Track, Track> param ) { return new TableCell <Track, Track>() { @Override protected void updateItem ( Track item, boolean empty ) { super.updateItem( item, empty ); if ( this.getTableRow() != null && item != null ) { setText( this.getTableRow().getIndex() + 1 + "" ); } else { setText( "" ); } } }; } }); numberColumn.setSortable(false); artistColumn.setCellValueFactory( new PropertyValueFactory <Track, String>( "Artist" ) ); titleColumn.setCellValueFactory( new PropertyValueFactory <Track, String>( "Title" ) ); queueTable.getColumns().addAll( numberColumn, artistColumn, titleColumn ); Menu lastFMMenu = new Menu( "LastFM" ); MenuItem loveMenuItem = new MenuItem ( "Love" ); MenuItem unloveMenuItem = new MenuItem ( "Unlove" ); MenuItem scrobbleMenuItem = new MenuItem ( "Scrobble" ); lastFMMenu.getItems().addAll ( loveMenuItem, unloveMenuItem, scrobbleMenuItem ); lastFMMenu.setVisible ( false ); lastFMMenu.visibleProperty().bind( ui.showLastFMWidgets ); loveMenuItem.setOnAction( ( event ) -> { ui.audioSystem.getLastFM().loveTrack( queueTable.getSelectionModel().getSelectedItem() ); }); unloveMenuItem.setOnAction( ( event ) -> { ui.audioSystem.getLastFM().unloveTrack( queueTable.getSelectionModel().getSelectedItem() ); }); scrobbleMenuItem.setOnAction( ( event ) -> { ui.audioSystem.getLastFM().scrobbleTrack( queueTable.getSelectionModel().getSelectedItem() ); }); ContextMenu contextMenu = new ContextMenu(); MenuItem playMenuItem = new MenuItem( "Play" ); MenuItem appendMenuItem = new MenuItem( "Append" ); MenuItem editTagMenuItem = new MenuItem( "Edit Tag(s)" ); MenuItem infoMenuItem = new MenuItem( "Info" ); MenuItem lyricsMenuItem = new MenuItem( "Lyrics" ); MenuItem goToAlbumMenuItem = new MenuItem( "Go to Album" ); MenuItem browseMenuItem = new MenuItem( "Browse Folder" ); Menu addToPlaylistMenuItem = new Menu( "Add to Playlist" ); MenuItem cropMenuItem = new MenuItem( "Crop" ); MenuItem removeMenuItem = new MenuItem( "Remove from Queue" ); contextMenu.getItems().addAll( playMenuItem, appendMenuItem, editTagMenuItem, infoMenuItem, lyricsMenuItem, goToAlbumMenuItem, browseMenuItem, addToPlaylistMenuItem, lastFMMenu, cropMenuItem, removeMenuItem ); MenuItem newPlaylistButton = new MenuItem( "<New>" ); queueTable.setOnKeyPressed( ( KeyEvent e ) -> { if ( e.getCode() == KeyCode.ESCAPE && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { if ( queueTable.getSelectionModel().getSelectedItems().size() > 0 ) { queueTable.getSelectionModel().clearSelection(); e.consume(); } else { this.hide(); } } else if ( e.getCode() == KeyCode.G && e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { goToAlbumMenuItem.fire(); } else if ( e.getCode() == KeyCode.F2 && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { editTagMenuItem.fire(); e.consume(); } else if ( e.getCode() == KeyCode.F3 && !e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { infoMenuItem.fire(); e.consume(); } else if ( e.getCode() == KeyCode.F4 && !e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { browseMenuItem.fire(); e.consume(); } else if ( e.getCode() == KeyCode.L && !e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { lyricsMenuItem.fire(); e.consume(); } else if ( e.getCode() == KeyCode.ENTER && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { playMenuItem.fire(); e.consume(); } else if ( e.getCode() == KeyCode.ENTER && e.isShiftDown() && !e.isAltDown() && !e.isControlDown() && !e.isMetaDown() ) { audioSystem.getCurrentList().insertTracks( 0, queueTable.getSelectionModel().getSelectedItems() ); } else if ( e.getCode() == KeyCode.ENTER && e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { appendMenuItem.fire(); e.consume(); } else if ( e.getCode() == KeyCode.DELETE && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { removeMenuItem.fire(); e.consume(); } else if ( e.getCode() == KeyCode.DELETE && e.isShiftDown() && !e.isAltDown() && !e.isControlDown() && !e.isMetaDown() ) { cropMenuItem.fire(); e.consume(); } }); queueTable.setRowFactory( tv -> { TableRow <Track> row = new TableRow <>(); row.itemProperty().addListener( (obs, oldValue, newValue ) -> { if ( newValue != null ) { row.setContextMenu( contextMenu ); } else { row.setContextMenu( null ); } }); row.setOnContextMenuRequested( event -> { goToAlbumMenuItem.setDisable( row.getItem().getAlbum() == null ); }); row.setOnDragDetected( event -> { if ( !row.isEmpty() ) { ArrayList <Integer> indices = new ArrayList <Integer>( queueTable.getSelectionModel().getSelectedIndices() ); ArrayList <Track> tracks = new ArrayList <Track>( queueTable.getSelectionModel().getSelectedItems() ); DraggedTrackContainer dragObject = new DraggedTrackContainer( indices, tracks, null, null, null, DragSource.QUEUE ); Dragboard db = row.startDragAndDrop( TransferMode.COPY ); db.setDragView( row.snapshot( null, null ) ); ClipboardContent cc = new ClipboardContent(); cc.put( FXUI.DRAGGED_TRACKS, dragObject ); db.setContent( cc ); event.consume(); } }); row.setOnDragOver( event -> { Dragboard db = event.getDragboard(); if ( db.hasContent( FXUI.DRAGGED_TRACKS ) || db.hasFiles() ) { event.acceptTransferModes( TransferMode.COPY ); event.consume(); } } ); row.setOnDragDropped( event -> { Dragboard db = event.getDragboard(); if ( db.hasContent( FXUI.DRAGGED_TRACKS ) ) { DraggedTrackContainer container = (DraggedTrackContainer) db.getContent( FXUI.DRAGGED_TRACKS ); List <Integer> draggedIndices = container.getIndices(); int dropIndex = row.isEmpty() ? dropIndex = audioSystem.getQueue().size() : row.getIndex(); switch ( container.getSource() ) { case ARTIST_LIST: case ALBUM_LIST: case PLAYLIST_LIST: case HISTORY: case TAG_ERROR_LIST: case ALBUM_INFO: case PLAYLIST_INFO: case TRACK_LIST: case CURRENT_TRACK: { List <Track> tracksToCopy = container.getTracks(); audioSystem.getQueue().queueAllTracks( tracksToCopy, dropIndex ); } break; case CURRENT_LIST: { //PENDING: Should I refactor this? synchronized ( audioSystem.getCurrentList() ) { ArrayList <CurrentListTrack> tracksToCopy = new ArrayList <CurrentListTrack> ( ); for ( int index : draggedIndices ) { if ( index >= 0 && index < audioSystem.getCurrentList().getItems().size() ) { tracksToCopy.add( audioSystem.getCurrentList().getItems().get( index ) ); } } audioSystem.getQueue().queueAllTracks( tracksToCopy, dropIndex ); } } break; case QUEUE: { ArrayList <Track> tracksToMove = new ArrayList <Track> ( draggedIndices.size() ); for ( int index : draggedIndices ) { if ( index >= 0 && index < audioSystem.getQueue().size() ) { tracksToMove.add( audioSystem.getQueue().get( index ) ); } } for ( int k = draggedIndices.size() - 1; k >= 0; k-- ) { int index = draggedIndices.get( k ).intValue(); if ( index >= 0 && index < audioSystem.getQueue().size() ) { audioSystem.getQueue().remove ( index ); } } dropIndex = Math.min( audioSystem.getQueue().size(), row.getIndex() ); audioSystem.getQueue().queueAllTracks( tracksToMove, dropIndex ); queueTable.getSelectionModel().clearSelection(); for ( int k = 0; k < draggedIndices.size(); k++ ) { queueTable.getSelectionModel().select( dropIndex + k ); } audioSystem.getQueue().updateQueueIndexes(); } break; } audioSystem.getQueue().updateQueueIndexes( ); event.setDropCompleted( true ); event.consume(); } else if ( db.hasFiles() ) { ArrayList <Path> pathsToAdd = new ArrayList<Path> (); for ( File file : db.getFiles() ) { Path droppedPath = Paths.get( file.getAbsolutePath() ); if ( Utils.isMusicFile( droppedPath ) ) { pathsToAdd.add( droppedPath ); } else if ( Files.isDirectory( droppedPath ) ) { pathsToAdd.addAll( Utils.getAllTracksInDirectory( droppedPath ) ); } else if ( Utils.isPlaylistFile ( droppedPath ) ) { List<Path> paths = Playlist.getTrackPaths( droppedPath ); pathsToAdd.addAll( paths ); } } ArrayList <Track> tracksToAdd = new ArrayList<Track> ( pathsToAdd.size() ); for ( Path path : pathsToAdd ) { tracksToAdd.add( new Track ( path ) ); } if ( !tracksToAdd.isEmpty() ) { int dropIndex = row.isEmpty() ? dropIndex = audioSystem.getQueue().size() : row.getIndex(); audioSystem.getQueue().queueAllTracks( tracksToAdd, Math.min( dropIndex, audioSystem.getQueue().size() ) ); } event.setDropCompleted( true ); event.consume(); } }); return row; }); queueTable.setOnDragOver( event -> { Dragboard db = event.getDragboard(); if ( db.hasContent( FXUI.DRAGGED_TRACKS ) || db.hasFiles() ) { event.acceptTransferModes( TransferMode.COPY ); event.consume(); } } ); queueTable.setOnDragDropped( event -> { Dragboard db = event.getDragboard(); if ( db.hasContent( FXUI.DRAGGED_TRACKS ) ) { DraggedTrackContainer container = (DraggedTrackContainer) db.getContent( FXUI.DRAGGED_TRACKS ); List <Integer> draggedIndices = container.getIndices(); switch ( container.getSource() ) { case ARTIST_LIST: case ALBUM_LIST: case PLAYLIST_LIST: case HISTORY: case ALBUM_INFO: case PLAYLIST_INFO: case TAG_ERROR_LIST: case TRACK_LIST: case CURRENT_TRACK: { List <Track> tracksToCopy = container.getTracks(); audioSystem.getQueue().queueAllTracks( tracksToCopy ); } break; case CURRENT_LIST: { //PENDING: should I refactor this synchronized ( audioSystem.getCurrentList() ) { ArrayList <CurrentListTrack> tracksToCopy = new ArrayList <CurrentListTrack> ( ); for ( int index : draggedIndices ) { if ( index >= 0 && index < audioSystem.getCurrentList().getItems().size() ) { tracksToCopy.add( audioSystem.getCurrentList().getItems().get( index ) ); } } audioSystem.getQueue().queueAllTracks( tracksToCopy ); } } break; case QUEUE: { //Dragging from an empty queue to the queue has no meaning. } break; } audioSystem.getQueue().updateQueueIndexes(); event.setDropCompleted( true ); event.consume(); } else if ( db.hasFiles() ) { ArrayList <Path> pathsToAdd = new ArrayList<Path> (); for ( File file : db.getFiles() ) { Path droppedPath = Paths.get( file.getAbsolutePath() ); if ( Utils.isMusicFile( droppedPath ) ) { pathsToAdd.add( droppedPath ); } else if ( Files.isDirectory( droppedPath ) ) { pathsToAdd.addAll( Utils.getAllTracksInDirectory( droppedPath ) ); } else if ( Utils.isPlaylistFile ( droppedPath ) ) { List<Path> paths = Playlist.getTrackPaths( droppedPath ); pathsToAdd.addAll( paths ); } } ArrayList <Track> tracksToAdd = new ArrayList<Track> ( pathsToAdd.size() ); for ( Path path : pathsToAdd ) { tracksToAdd.add( new Track ( path ) ); } if ( !tracksToAdd.isEmpty() ) { audioSystem.getQueue().queueAllTracks( tracksToAdd ); } event.setDropCompleted( true ); event.consume(); } } ); addToPlaylistMenuItem.getItems().add( newPlaylistButton ); newPlaylistButton.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent e ) { ui.promptAndSavePlaylist ( queueTable.getSelectionModel().getSelectedItems() ); } }); EventHandler <ActionEvent> addToPlaylistHandler = new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { Playlist playlist = (Playlist) ((MenuItem) event.getSource()).getUserData(); ui.addToPlaylist ( queueTable.getSelectionModel().getSelectedItems(), playlist ); } }; library.getPlaylistsSorted().addListener( ( ListChangeListener.Change <? extends Playlist> change ) -> { ui.updatePlaylistMenuItems( addToPlaylistMenuItem.getItems(), addToPlaylistHandler ); }); ui.updatePlaylistMenuItems( addToPlaylistMenuItem.getItems(), addToPlaylistHandler ); playMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { List <Track> selectedItems = new ArrayList<Track> ( queueTable.getSelectionModel().getSelectedItems() ); if ( selectedItems.size() == 1 ) { audioSystem.playItems( selectedItems ); } else if ( selectedItems.size() > 1 ) { if ( ui.okToReplaceCurrentList() ) { audioSystem.playItems( selectedItems ); } } } }); appendMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { audioSystem.getCurrentList().appendTracks ( queueTable.getSelectionModel().getSelectedItems() ); } }); editTagMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { List<Track> tracks = queueTable.getSelectionModel().getSelectedItems(); tagWindow.setTracks( tracks, null ); tagWindow.show(); } }); infoMenuItem.setOnAction( event -> { ui.trackInfoWindow.setTrack( queueTable.getSelectionModel().getSelectedItem() ); ui.trackInfoWindow.show(); }); lyricsMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { ui.lyricsWindow.setTrack( queueTable.getSelectionModel().getSelectedItem() ); ui.lyricsWindow.show(); } }); goToAlbumMenuItem.setOnAction( ( event ) -> { ui.goToAlbumOfTrack ( queueTable.getSelectionModel().getSelectedItem() ); }); browseMenuItem.setOnAction( ( ActionEvent event ) -> { ui.openFileBrowser( queueTable.getSelectionModel().getSelectedItem().getPath() ); }); cropMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { ObservableList <Integer> selectedIndexes = queueTable.getSelectionModel().getSelectedIndices(); ArrayList <Integer> removeMe = new ArrayList<Integer> (); for ( int k = 0; k < queueTable.getItems().size(); k++ ) { if ( !selectedIndexes.contains( k ) ) { removeMe.add ( k ); } } if ( !removeMe.isEmpty() ) { for ( int k = removeMe.size() - 1; k >= 0; k-- ) { audioSystem.getQueue().remove ( removeMe.get( k ).intValue() ); } queueTable.getSelectionModel().clearSelection(); } } } ); removeMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { synchronized ( queueTable.getItems() ) { List<Integer> selectedIndices = queueTable.getSelectionModel().getSelectedIndices(); ArrayList<Integer> removeMeIndices = new ArrayList<Integer> ( selectedIndices ); for ( int k = removeMeIndices.size() - 1; k >= 0 ; k-- ) { audioSystem.getQueue().remove( removeMeIndices.get( k ).intValue() ); } } } }); queueTable.prefWidthProperty().bind( root.widthProperty() ); queueTable.prefHeightProperty().bind( root.heightProperty() ); root.getChildren().add( queueTable ); setScene( scene ); } public void refresh () { for ( Track track : queueTable.getItems() ) { try { track.refreshTagData(); } catch ( Exception e ) {} } queueTable.refresh(); } }
21,424
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
LibraryArtistPane.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/fxui/LibraryArtistPane.java
package net.joshuad.hypnos.fxui; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.EnumMap; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.jaudiotagger.tag.FieldKey; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.scene.control.Button; import javafx.scene.control.CheckMenuItem; import javafx.scene.control.ContextMenu; import javafx.scene.control.Label; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.scene.control.SelectionMode; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.scene.control.TableRow; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.Tooltip; import javafx.scene.control.TableColumn.SortType; import javafx.scene.control.TableView.ResizeFeatures; import javafx.scene.effect.ColorAdjust; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.ClipboardContent; import javafx.scene.input.Dragboard; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.TransferMode; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.text.TextAlignment; import net.joshuad.hypnos.AlphanumComparator; import net.joshuad.hypnos.Persister; import net.joshuad.hypnos.Utils; import net.joshuad.hypnos.AlphanumComparator.CaseHandling; import net.joshuad.hypnos.Persister.Setting; import net.joshuad.hypnos.Hypnos; import net.joshuad.hypnos.audio.AudioSystem; import net.joshuad.hypnos.fxui.DraggedTrackContainer.DragSource; import net.joshuad.hypnos.library.Album; import net.joshuad.hypnos.library.Artist; import net.joshuad.hypnos.library.Library; import net.joshuad.hypnos.library.Playlist; import net.joshuad.hypnos.library.Track; public class LibraryArtistPane extends BorderPane { private static final Logger LOGGER = Logger.getLogger( LibraryArtistPane.class.getName() ); private FXUI ui; private AudioSystem audioSystem; private Library library; private HBox filterPane; TextField filterBox; TableView<Artist> artistTable; TableColumn<Artist, String> artistColumn; TableColumn<Artist, Number> tracksColumn, albumsColumn, lengthColumn; ContextMenu columnSelectorMenu; Label emptyListLabel = new Label( "No artists loaded. To add to your library, click on the + button or drop folders here." ); Label filteredListLabel = new Label( "No artists match." ); Label noColumnsLabel = new Label( "All columns hidden." ); Label loadingListLabel = new Label( "Loading..." ); private ThrottledArtistFilter tableFilter; private ImageView addSourceImage, filterClearImage; public LibraryArtistPane ( FXUI ui, AudioSystem audioSystem, Library library ) { this.ui = ui; this.audioSystem = audioSystem; this.library = library; setupFilterPane(); artistTable = setupArtistTable(); filterPane.prefWidthProperty().bind( filterPane.widthProperty() ); setTop( filterPane ); setCenter( artistTable ); resetTableSettingsToDefault(); library.getArtistsSorted().addListener( new ListChangeListener<Artist>() { @Override public void onChanged(Change<? extends Artist> arg0) { updatePlaceholders(); } }); artistColumn.visibleProperty().addListener( e -> updatePlaceholders() ); tracksColumn.visibleProperty().addListener( e -> updatePlaceholders() ); albumsColumn.visibleProperty().addListener( e -> updatePlaceholders() ); lengthColumn.visibleProperty().addListener( e -> updatePlaceholders() ); resetTableSettingsToDefault(); } public void updatePlaceholders() { Platform.runLater( () -> { boolean someVisible = false; for ( TableColumn<?,?> column : artistTable.getColumns() ) { if ( column.isVisible() ) { someVisible = true; break; } } if ( !someVisible ) { artistTable.setPlaceholder( noColumnsLabel ); } else if ( library.getArtistDisplayCache().isEmpty() ) { if ( artistTable.getPlaceholder() != emptyListLabel ) { artistTable.setPlaceholder( emptyListLabel ); } } else { if ( !artistTable.getPlaceholder().equals( filteredListLabel ) ) { artistTable.setPlaceholder( filteredListLabel ); } } }); } public void resetTableSettingsToDefault() { artistColumn.setVisible( true ); albumsColumn.setVisible( true ); tracksColumn.setVisible( true ); lengthColumn.setVisible( true ); artistTable.getColumns().remove( artistColumn ); artistTable.getColumns().add( artistColumn ); artistTable.getColumns().remove( albumsColumn ); artistTable.getColumns().add( albumsColumn ); artistTable.getColumns().remove( tracksColumn ); artistTable.getColumns().add( tracksColumn ); artistTable.getColumns().remove( lengthColumn ); artistTable.getColumns().add( lengthColumn ); //Note: setSortType needs to be called before getSortOrder().add artistTable.getSortOrder().clear(); artistColumn.setSortType( SortType.ASCENDING ); artistTable.getSortOrder().add( artistColumn ); artistColumn.setPrefWidth( 300 ); albumsColumn.setPrefWidth( 40 ); tracksColumn.setPrefWidth( 40 ); lengthColumn.setPrefWidth( 80 ); artistTable.getColumnResizePolicy().call( new ResizeFeatures<Artist> ( artistTable, null, 0d ) ); } private TableView<Artist> setupArtistTable () { artistColumn = new TableColumn<Artist, String>( "Artist" ); albumsColumn = new TableColumn<Artist, Number>( ); tracksColumn = new TableColumn<Artist, Number> ( ); lengthColumn = new TableColumn<Artist, Number> ( "Length" ); Label tracksLabel = new Label( "T" ); tracksLabel.setTooltip( new Tooltip( "Tracks" ) ); tracksColumn.setGraphic( tracksLabel ); Label albumsLabel = new Label( "A" ); albumsLabel.setTooltip( new Tooltip( "Albums" ) ); albumsColumn.setGraphic( albumsLabel ); artistColumn.setComparator( new AlphanumComparator( CaseHandling.CASE_INSENSITIVE ) ); artistColumn.setCellValueFactory( cellData -> cellData.getValue().nameProperty() ); albumsColumn.setCellValueFactory( cellData -> cellData.getValue().albumCountProperty() ); tracksColumn.setCellValueFactory( cellData -> cellData.getValue().trackCountProperty() ); lengthColumn.setCellValueFactory( cellData -> cellData.getValue().lengthProperty() ); lengthColumn.setCellFactory( col -> new TableCell<Artist, Number> () { @Override public void updateItem ( Number length, boolean empty ) { super.updateItem( length, empty ); if ( empty ) { setText( null ); } else { setText( Utils.getLengthDisplay( length.intValue() ) ); } } }); columnSelectorMenu = new ContextMenu (); CheckMenuItem nameMenuItem = new CheckMenuItem ( "Show Name Column" ); CheckMenuItem albumsMenuItem = new CheckMenuItem ( "Show Albums Column" ); CheckMenuItem tracksMenuItem = new CheckMenuItem ( "Show Tracks Column" ); CheckMenuItem lengthMenuItem = new CheckMenuItem ( "Show Length Column" ); MenuItem defaultMenuItem = new MenuItem ( "Reset to Default View" ); columnSelectorMenu.getItems().addAll( nameMenuItem, albumsMenuItem, tracksMenuItem, lengthMenuItem, defaultMenuItem ); artistColumn.setContextMenu( columnSelectorMenu ); albumsColumn.setContextMenu( columnSelectorMenu ); tracksColumn.setContextMenu( columnSelectorMenu ); lengthColumn.setContextMenu( columnSelectorMenu ); nameMenuItem.selectedProperty().bindBidirectional( artistColumn.visibleProperty() ); albumsMenuItem.selectedProperty().bindBidirectional( albumsColumn.visibleProperty() ); tracksMenuItem.selectedProperty().bindBidirectional( tracksColumn.visibleProperty() ); lengthMenuItem.selectedProperty().bindBidirectional( lengthColumn.visibleProperty() ); defaultMenuItem.setOnAction( e -> this.resetTableSettingsToDefault() ); TableView<Artist> retMe = new TableView<Artist>(); retMe.getColumns().addAll( artistColumn, albumsColumn, tracksColumn, lengthColumn ); retMe.setEditable( false ); retMe.setItems( library.getArtistsSorted() ); retMe.getSelectionModel().setSelectionMode( SelectionMode.MULTIPLE ); HypnosResizePolicy resizePolicy = new HypnosResizePolicy(); retMe.setColumnResizePolicy( resizePolicy ); resizePolicy.registerFixedWidthColumns( albumsColumn, tracksColumn /*, lengthColumn*/ ); library.getArtistsSorted().comparatorProperty().bind( retMe.comparatorProperty() ); emptyListLabel.setPadding( new Insets( 20, 10, 20, 10 ) ); emptyListLabel.setWrapText( true ); emptyListLabel.setTextAlignment( TextAlignment.CENTER ); filteredListLabel.setPadding( new Insets( 20, 10, 20, 10 ) ); filteredListLabel.setWrapText( true ); filteredListLabel.setTextAlignment( TextAlignment.CENTER ); retMe.setPlaceholder( emptyListLabel ); ContextMenu contextMenu = new ContextMenu(); MenuItem playMenuItem = new MenuItem( "Play" ); MenuItem appendMenuItem = new MenuItem( "Append" ); MenuItem playNextMenuItem = new MenuItem( "Play Next" ); MenuItem enqueueMenuItem = new MenuItem( "Enqueue" ); MenuItem editTagMenuItem = new MenuItem( "Edit Tag(s)" ); Menu addToPlaylistMenuItem = new Menu( "Add to Playlist" ); MenuItem trackListItem = new MenuItem( "Track List" ); retMe.setOnKeyPressed( ( KeyEvent e ) -> { if ( e.getCode() == KeyCode.ESCAPE && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { if ( filterBox.getText().length() > 0 ) { filterBox.clear(); Platform.runLater( ()-> retMe.scrollTo( retMe.getSelectionModel().getSelectedItem() ) ); } else { retMe.getSelectionModel().clearSelection(); } } else if ( e.getCode() == KeyCode.Q && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { enqueueMenuItem.fire(); } else if ( e.getCode() == KeyCode.Q && e.isShiftDown() && !e.isAltDown() && !e.isControlDown() && !e.isMetaDown() ) { playNextMenuItem.fire(); } else if ( e.getCode() == KeyCode.F2 && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { editTagMenuItem.fire(); } else if ( e.getCode() == KeyCode.F3 && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { trackListItem.fire(); } else if ( e.getCode() == KeyCode.ENTER && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { playMenuItem.fire(); } else if ( e.getCode() == KeyCode.ENTER && e.isShiftDown() && !e.isAltDown() && !e.isControlDown() && !e.isMetaDown() ) { audioSystem.getCurrentList().insertArtists( 0, retMe.getSelectionModel().getSelectedItems() ); } else if ( e.getCode() == KeyCode.ENTER && e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { appendMenuItem.fire(); } else if ( e.getCode() == KeyCode.UP ) { if ( retMe.getSelectionModel().getSelectedIndex() == 0 ) { filterBox.requestFocus(); } } }); contextMenu.getItems().addAll( playMenuItem, appendMenuItem, playNextMenuItem, enqueueMenuItem, editTagMenuItem, trackListItem, addToPlaylistMenuItem ); MenuItem newPlaylistButton = new MenuItem( "<New>" ); addToPlaylistMenuItem.getItems().add( newPlaylistButton ); newPlaylistButton.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent e ) { ObservableList <Artist> selectedArtists = retMe.getSelectionModel().getSelectedItems(); ArrayList <Track> tracks = new ArrayList <Track> (); for ( Artist artist : selectedArtists ) { tracks.addAll( artist.getAllTracks() ); } ui.promptAndSavePlaylist ( tracks ); } }); EventHandler<ActionEvent> addToPlaylistHandler = new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { Playlist playlist = (Playlist) ((MenuItem) event.getSource()).getUserData(); ArrayList <Artist> artists = new ArrayList <Artist> ( retMe.getSelectionModel().getSelectedItems() ); ArrayList <Track> tracksToAdd = new ArrayList <Track> (); for ( Artist artist : artists ) { tracksToAdd.addAll( artist.getAllTracks() ); } ui.addToPlaylist ( tracksToAdd, playlist ); } }; library.getPlaylistsSorted().addListener( ( ListChangeListener.Change <? extends Playlist> change ) -> { ui.updatePlaylistMenuItems( addToPlaylistMenuItem.getItems(), addToPlaylistHandler ); } ); ui.updatePlaylistMenuItems( addToPlaylistMenuItem.getItems(), addToPlaylistHandler ); playMenuItem.setOnAction( event -> { if ( ui.okToReplaceCurrentList() ) { List <Artist> playMe = retMe.getSelectionModel().getSelectedItems(); audioSystem.getCurrentList().setAndPlayArtists( playMe ); } }); appendMenuItem.setOnAction( event -> { audioSystem.getCurrentList().appendArtists( retMe.getSelectionModel().getSelectedItems() ); }); playNextMenuItem.setOnAction( event -> { audioSystem.getQueue().queueAllArtists( retMe.getSelectionModel().getSelectedItems(), 0 ); }); enqueueMenuItem.setOnAction( event -> { audioSystem.getQueue().queueAllArtists( retMe.getSelectionModel().getSelectedItems() ); }); editTagMenuItem.setOnAction( event -> { List<Artist> artists = retMe.getSelectionModel().getSelectedItems(); ArrayList<Track> editMe = new ArrayList<Track>(); for ( Artist artist : artists ) { if ( artist != null ) { editMe.addAll( artist.getAllTracks() ); } } ui.tagWindow.setTracks( editMe, null, true, FieldKey.TRACK, FieldKey.TITLE, FieldKey.ALBUM, FieldKey.YEAR, FieldKey.ORIGINAL_YEAR, FieldKey.DISC_SUBTITLE, FieldKey.DISC_NO, FieldKey.DISC_TOTAL, FieldKey.MUSICBRAINZ_RELEASE_TYPE, FieldKey.ARTIST ); ui.tagWindow.show(); }); trackListItem.setOnAction( event -> { ui.artistInfoWindow.setArtist ( artistTable.getSelectionModel().getSelectedItem() ); ui.artistInfoWindow.show(); }); retMe.setOnDragOver( event -> { Dragboard db = event.getDragboard(); if ( db.hasFiles() ) { event.acceptTransferModes( TransferMode.COPY ); event.consume(); } }); retMe.setOnDragDropped( event -> { Dragboard db = event.getDragboard(); if ( db.hasFiles() ) { List <File> files = db.getFiles(); for ( File file : files ) { library.addMusicRoot( file.toPath() ); } event.setDropCompleted( true ); event.consume(); } }); retMe.getSelectionModel().selectedItemProperty().addListener( ( obs, oldSelection, newSelection ) -> { if ( newSelection != null ) { ui.artistSelected ( newSelection ); } else if ( audioSystem.getCurrentTrack() != null ) { ui.trackSelected ( audioSystem.getCurrentTrack() ); } else { //Do nothing, leave the old artwork there. We can set to null if we like that better //I don't think so though } }); retMe.setRowFactory( tv -> { TableRow <Artist> row = new TableRow <>(); row.itemProperty().addListener( (obs, oldValue, newValue ) -> { if ( newValue != null ) { row.setContextMenu( contextMenu ); } else { row.setContextMenu( null ); } }); row.setOnMouseClicked( event -> { if ( event.getClickCount() == 2 && (!row.isEmpty()) ) { if ( ui.okToReplaceCurrentList() ) { audioSystem.getCurrentList().setAndPlayArtist( row.getItem() ); } } } ); row.setOnDragOver( event -> { Dragboard db = event.getDragboard(); if ( db.hasFiles() ) { event.acceptTransferModes( TransferMode.COPY ); event.consume(); } }); row.setOnDragDropped( event -> { Dragboard db = event.getDragboard(); if ( db.hasFiles() ) { List <File> files = db.getFiles(); for ( File file : files ) { library.addMusicRoot( file.toPath() ); } event.setDropCompleted( true ); event.consume(); } }); row.setOnDragDetected( event -> { if ( !row.isEmpty() ) { ArrayList <Artist> artists = new ArrayList <Artist>( retMe.getSelectionModel().getSelectedItems() ); ArrayList <Album> albums = new ArrayList <Album>(); ArrayList <Track> tracks = new ArrayList <Track> (); for ( Artist artist : artists ) { albums.addAll ( artist.getAlbums() ); tracks.addAll( artist.getAllTracks() ); } DraggedTrackContainer dragObject = new DraggedTrackContainer( null, tracks, albums, null, artists, DragSource.ARTIST_LIST ); Dragboard db = row.startDragAndDrop( TransferMode.COPY ); db.setDragView( row.snapshot( null, null ) ); ClipboardContent cc = new ClipboardContent(); cc.put( FXUI.DRAGGED_TRACKS, dragObject ); db.setContent( cc ); event.consume(); } }); return row; }); return retMe; } private void setupFilterPane () { tableFilter = new ThrottledArtistFilter ( library.getArtistsFiltered() ); filterPane = new HBox(); filterBox = new TextField(); filterBox.setPrefWidth( 500000 ); filterBox.textProperty().addListener( new ChangeListener <String> () { @Override public void changed ( ObservableValue <? extends String> observable, String oldValue, String newValue ) { tableFilter.setFilter( newValue ); } }); filterBox.setOnKeyPressed( ( KeyEvent event ) -> { if ( event.getCode() == KeyCode.ESCAPE ) { event.consume(); if ( filterBox.getText().length() > 0 ) { filterBox.clear(); } else { artistTable.requestFocus(); } } else if ( event.getCode() == KeyCode.DOWN ) { event.consume(); artistTable.requestFocus(); artistTable.getSelectionModel().select( artistTable.getSelectionModel().getFocusedIndex() ); } else if ( event.getCode() == KeyCode.ENTER && !event.isAltDown() && !event.isShiftDown() && !event.isControlDown() && !event.isMetaDown() ) { event.consume(); Artist playMe = artistTable.getSelectionModel().getSelectedItem(); if( playMe == null ) artistTable.getItems().get( 0 ); audioSystem.getCurrentList().setAndPlayArtist( playMe ); } else if ( event.getCode() == KeyCode.ENTER && event.isShiftDown() && !event.isAltDown() && !event.isControlDown() && !event.isMetaDown() ) { event.consume(); Artist playMe = artistTable.getSelectionModel().getSelectedItem(); if( playMe == null ) artistTable.getItems().get( 0 ); audioSystem.getQueue().queueAllArtists( Arrays.asList( playMe ) ); } else if ( event.getCode() == KeyCode.ENTER && event.isControlDown() && !event.isAltDown() && !event.isShiftDown() && !event.isMetaDown() ) { event.consume(); Artist playMe = artistTable.getSelectionModel().getSelectedItem(); if( playMe == null ) artistTable.getItems().get( 0 ); audioSystem.getCurrentList().appendArtist( playMe ); } }); float width = 33; float height = Hypnos.getOS().isWindows() ? 28 : 26; filterBox.setPrefHeight( height ); String addLocation = "resources/add.png"; String clearLocation = "resources/clear.png"; try { double currentListControlsButtonFitWidth = 15; double currentListControlsButtonFitHeight = 15; Image image = new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( addLocation ).toFile() ) ); addSourceImage = new ImageView ( image ); addSourceImage.setFitWidth( currentListControlsButtonFitWidth ); addSourceImage.setFitHeight( currentListControlsButtonFitHeight ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to load add icon: " + addLocation, e ); } try { Image clearImage = new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( clearLocation ).toFile() ) ); filterClearImage = new ImageView ( clearImage ); filterClearImage.setFitWidth( 12 ); filterClearImage.setFitHeight( 12 ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to load clear icon: " + clearLocation, e ); } Button libraryButton = new Button( ); libraryButton.setGraphic( addSourceImage ); libraryButton.setMinSize( width, height ); libraryButton.setPrefSize( width, height ); libraryButton.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent e ) { if ( ui.libraryLocationWindow.isShowing() ) { ui.libraryLocationWindow.hide(); } else { ui.libraryLocationWindow.show(); } } }); Button clearButton = new Button( ); clearButton.setGraphic( filterClearImage ); clearButton.setMinSize( width, height ); clearButton.setPrefSize( width, height ); clearButton.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent e ) { filterBox.setText( "" ); } }); libraryButton.setTooltip( new Tooltip( "Add or Remove Music Folders" ) ); filterBox.setTooltip ( new Tooltip ( "Filter/Search albums" ) ); clearButton.setTooltip( new Tooltip( "Clear the filter text" ) ); filterPane.getChildren().addAll( libraryButton, filterBox, clearButton ); } public void applyDarkTheme ( ColorAdjust buttonColor ) { if ( filterClearImage != null ) filterClearImage.setEffect( buttonColor ); if ( addSourceImage != null ) addSourceImage.setEffect( buttonColor ); } public void applyLightTheme () { if ( filterClearImage != null ) filterClearImage.setEffect( ui.lightThemeButtonEffect ); if ( addSourceImage != null ) addSourceImage.setEffect( ui.lightThemeButtonEffect ); } @SuppressWarnings("incomplete-switch") public void applySettingsBeforeWindowShown ( EnumMap<Persister.Setting, String> settings ) { settings.forEach( ( setting, value )-> { try { switch ( setting ) { case AR_TABLE_ARTIST_COLUMN_SHOW: artistColumn.setVisible( Boolean.valueOf ( value ) ); settings.remove ( setting ); break; case AR_TABLE_ALBUMS_COLUMN_SHOW: albumsColumn.setVisible( Boolean.valueOf ( value ) ); settings.remove ( setting ); break; case AR_TABLE_TRACKS_COLUMN_SHOW: tracksColumn.setVisible( Boolean.valueOf ( value ) ); settings.remove ( setting ); break; case AR_TABLE_LENGTH_COLUMN_SHOW: lengthColumn.setVisible( Boolean.valueOf ( value ) ); settings.remove ( setting ); break; case AR_TABLE_ARTIST_COLUMN_WIDTH: artistColumn.setPrefWidth( Double.valueOf( value ) ); settings.remove ( setting ); break; case AR_TABLE_ALBUMS_COLUMN_WIDTH: albumsColumn.setPrefWidth( Double.valueOf( value ) ); settings.remove ( setting ); break; case AR_TABLE_TRACKS_COLUMN_WIDTH: tracksColumn.setPrefWidth( Double.valueOf( value ) ); settings.remove ( setting ); break; case AR_TABLE_LENGTH_COLUMN_WIDTH: lengthColumn.setPrefWidth( Double.valueOf( value ) ); settings.remove ( setting ); break; case ARTIST_COLUMN_ORDER: { String[] order = value.split( " " ); int newIndex = 0; for ( String columnName : order ) { try { if ( columnName.equals( "artist" ) ) { artistTable.getColumns().remove( artistColumn ); artistTable.getColumns().add( newIndex, artistColumn ); } else if ( columnName.equals( "albums" ) ) { artistTable.getColumns().remove( albumsColumn ); artistTable.getColumns().add( newIndex, albumsColumn ); } else if ( columnName.equals( "tracks" ) ) { artistTable.getColumns().remove( tracksColumn ); artistTable.getColumns().add( newIndex, tracksColumn ); } else if ( columnName.equals( "length" ) ) { artistTable.getColumns().remove( lengthColumn ); artistTable.getColumns().add( newIndex, lengthColumn ); } newIndex++; } catch ( Exception e ) { LOGGER.log( Level.INFO, "Unable to set album table column order: '" + value + "'", e ); } } settings.remove ( setting ); break; } case ARTIST_SORT_ORDER: { artistTable.getSortOrder().clear(); if ( !value.equals( "" ) ) { String[] order = value.split( " " ); for ( String fullValue : order ) { try { String columnName = fullValue.split( "-" )[0]; SortType sortType = SortType.valueOf( fullValue.split( "-" )[1] ); if ( columnName.equals( "artist" ) ) { artistTable.getSortOrder().add( artistColumn ); artistColumn.setSortType( sortType ); } else if ( columnName.equals( "albums" ) ) { artistTable.getSortOrder().add( albumsColumn ); albumsColumn.setSortType( sortType ); } else if ( columnName.equals( "tracks" ) ) { artistTable.getSortOrder().add( tracksColumn ); tracksColumn.setSortType( sortType ); } else if ( columnName.equals( "length" ) ) { artistTable.getSortOrder().add( lengthColumn ); lengthColumn.setSortType( sortType ); } } catch ( Exception e ) { LOGGER.log( Level.INFO, "Unable to set album table sort order: '" + value + "'", e ); } } } settings.remove ( setting ); break; } } } catch ( Exception e ) { LOGGER.log( Level.INFO, "Unable to apply setting: " + setting + " to UI.", e ); } }); } public EnumMap<Persister.Setting, ? extends Object> getSettings () { EnumMap <Persister.Setting, Object> retMe = new EnumMap <Persister.Setting, Object> ( Persister.Setting.class ); String columnOrderValue = ""; for ( TableColumn<Artist, ?> column : artistTable.getColumns() ) { if ( column == artistColumn ) { columnOrderValue += "artist "; } else if ( column == albumsColumn ) { columnOrderValue += "albums "; } else if ( column == tracksColumn ) { columnOrderValue += "tracks "; } else if ( column == lengthColumn ) { columnOrderValue += "length "; } } retMe.put ( Setting.ARTIST_COLUMN_ORDER, columnOrderValue ); String sortValue = ""; for ( TableColumn<Artist, ?> column : artistTable.getSortOrder() ) { if ( column == artistColumn ) { sortValue += "artist-" + artistColumn.getSortType() + " "; } else if ( column == albumsColumn ) { sortValue += "albums-" + albumsColumn.getSortType() + " "; } else if ( column == tracksColumn ) { sortValue += "tracks-" + tracksColumn.getSortType() + " "; } else if ( column == lengthColumn ) { sortValue += "length-" + lengthColumn.getSortType() + " "; } } retMe.put ( Setting.ALBUM_SORT_ORDER, sortValue ); retMe.put ( Setting.AR_TABLE_ARTIST_COLUMN_SHOW, artistColumn.isVisible() ); retMe.put ( Setting.AR_TABLE_ALBUMS_COLUMN_SHOW, albumsColumn.isVisible() ); retMe.put ( Setting.AR_TABLE_TRACKS_COLUMN_SHOW, tracksColumn.isVisible() ); retMe.put ( Setting.AR_TABLE_LENGTH_COLUMN_SHOW, lengthColumn.isVisible() ); retMe.put ( Setting.AR_TABLE_ARTIST_COLUMN_WIDTH, artistColumn.getPrefWidth() ); retMe.put ( Setting.AR_TABLE_ALBUMS_COLUMN_WIDTH, albumsColumn.getPrefWidth() ); retMe.put ( Setting.AR_TABLE_TRACKS_COLUMN_WIDTH, tracksColumn.getPrefWidth() ); retMe.put ( Setting.AR_TABLE_LENGTH_COLUMN_WIDTH, lengthColumn.getPrefWidth() ); return retMe; } public void focusFilter() { artistTable.requestFocus(); filterBox.requestFocus(); artistTable.getSelectionModel().clearSelection(); } }
27,824
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
PlaylistInfoWindow.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/fxui/PlaylistInfoWindow.java
package net.joshuad.hypnos.fxui; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javafx.collections.ListChangeListener; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.ContextMenu; import javafx.scene.control.Label; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.scene.control.SelectionMode; import javafx.scene.control.TableColumn; import javafx.scene.control.TableRow; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.image.Image; import javafx.scene.input.ClipboardContent; import javafx.scene.input.Dragboard; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.TransferMode; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.stage.Modality; import javafx.stage.Stage; import net.joshuad.hypnos.CurrentList; import net.joshuad.hypnos.Hypnos; import net.joshuad.hypnos.Utils; import net.joshuad.hypnos.audio.AudioSystem; import net.joshuad.hypnos.fxui.DraggedTrackContainer.DragSource; import net.joshuad.hypnos.library.Album; import net.joshuad.hypnos.library.Library; import net.joshuad.hypnos.library.Playlist; import net.joshuad.hypnos.library.Track; public class PlaylistInfoWindow extends Stage { private static final Logger LOGGER = Logger.getLogger( PlaylistInfoWindow.class.getName() ); Playlist playlist; TableView <Track> trackTable; TextField locationField; FXUI ui; Library library; AudioSystem audioSystem; public PlaylistInfoWindow( FXUI ui, Library library, AudioSystem audioSystem ) { super(); this.ui = ui; this.library = library; this.audioSystem = audioSystem; this.initModality( Modality.NONE ); this.initOwner( ui.getMainStage() ); this.setTitle( "Album Info" ); this.setWidth( 600 ); this.setHeight( 400 ); Pane root = new Pane(); Scene scene = new Scene( root ); try { getIcons().add( new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( "resources" + File.separator + "icon.png" ).toFile() ) ) ); } catch ( FileNotFoundException e ) { LOGGER.log( Level.WARNING, "Unable to load program icon: resources/icon.png", e ); } VBox primaryPane = new VBox(); setupPlaylistTable( primaryPane ); primaryPane.prefWidthProperty().bind( root.widthProperty() ); primaryPane.prefHeightProperty().bind( root.heightProperty() ); primaryPane.getChildren().addAll( trackTable ); root.getChildren().add( primaryPane ); setScene( scene ); scene.addEventFilter( KeyEvent.KEY_PRESSED, new EventHandler <KeyEvent>() { @Override public void handle ( KeyEvent e ) { if ( e.getCode() == KeyCode.ESCAPE && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() && !e.isAltDown() ) { hide(); e.consume(); } } }); } public void setPlaylist ( Playlist playlist ) { this.playlist = playlist; if ( playlist != null ) { trackTable.setItems( playlist.getTracks() ); this.setTitle( "Playlist Info: " + playlist.getName() ); } } private void setupPlaylistTable ( VBox primaryPane ) { TableColumn<Track, String> artistColumn = new TableColumn<Track, String>( "Artist" ); TableColumn<Track, String> titleColumn = new TableColumn<Track, String>( "Title" ); TableColumn<Track, Integer> lengthColumn = new TableColumn<Track, Integer>( "Length" ); artistColumn.setMaxWidth( 400000 ); titleColumn.setMaxWidth( 500000 ); lengthColumn.setMaxWidth( 90000 ); artistColumn.setEditable( false ); titleColumn.setEditable( false ); lengthColumn.setEditable( false ); artistColumn.setReorderable( false ); titleColumn.setReorderable( false ); lengthColumn.setReorderable( false ); artistColumn.setCellValueFactory( new PropertyValueFactory <Track, String>( "Artist" ) ); titleColumn.setCellValueFactory( new PropertyValueFactory <Track, String>( "Title" ) ); lengthColumn.setCellValueFactory( new PropertyValueFactory <Track, Integer>( "LengthDisplay" ) ); trackTable = new TableView<Track> (); trackTable.getColumns().addAll( artistColumn, titleColumn, lengthColumn ); trackTable.setColumnResizePolicy( TableView.CONSTRAINED_RESIZE_POLICY ); trackTable.setEditable( true ); trackTable.getSelectionModel().setSelectionMode( SelectionMode.MULTIPLE ); trackTable.prefWidthProperty().bind( primaryPane.widthProperty() ); trackTable.prefHeightProperty().bind( primaryPane.heightProperty() ); trackTable.setPlaceholder( new Label( "Empty Playlist." ) ); trackTable.setOnDragOver( event -> { Dragboard db = event.getDragboard(); if ( db.hasContent( FXUI.DRAGGED_TRACKS ) || db.hasFiles() ) { event.acceptTransferModes( TransferMode.COPY ); event.consume(); } } ); trackTable.getSelectionModel().selectedItemProperty().addListener( ( obs, oldSelection, newSelection ) -> { ui.trackSelected ( newSelection ); }); trackTable.setOnDragDropped( event -> { Dragboard db = event.getDragboard(); if ( db.hasContent( FXUI.DRAGGED_TRACKS ) ) { DraggedTrackContainer container = (DraggedTrackContainer) db.getContent( FXUI.DRAGGED_TRACKS ); switch ( container.getSource() ) { case PLAYLIST_LIST: { if ( container.getPlaylists() == null ) { LOGGER.log ( Level.INFO, "Recieved null data from playlist list, ignoring.", new NullPointerException() ); } else { List <Track> tracksToCopy = new ArrayList<Track>(); for ( Playlist playlist : container.getPlaylists() ) { if ( playlist == null ) { LOGGER.log ( Level.INFO, "Recieved null playlist from playlist list, ignoring.", new NullPointerException() ); } else { tracksToCopy.addAll( playlist.getTracks() ); } } trackTable.getItems().addAll ( tracksToCopy ); } } break; case ALBUM_LIST: { if ( container.getAlbums() == null ) { LOGGER.log ( Level.INFO, "Recieved null data from playlist list, ignoring.", new NullPointerException() ); } else { List <Track> tracksToCopy = new ArrayList<Track>(); for ( Album album : container.getAlbums() ) { if ( album == null ) { LOGGER.log ( Level.INFO, "Null album dropped in playlist window, ignoring.", new NullPointerException() ); } else { tracksToCopy.addAll( album.getTracks() ); } } trackTable.getItems().addAll ( tracksToCopy ); } } break; case ARTIST_LIST: case TRACK_LIST: case ALBUM_INFO: case HISTORY: case CURRENT_LIST: case TAG_ERROR_LIST: case QUEUE: case CURRENT_TRACK: { List <Track> tracksToCopy = container.getTracks(); trackTable.getItems().addAll( tracksToCopy ); } break; case PLAYLIST_INFO: { //Not possible; table is currently empty } break; } event.setDropCompleted( true ); event.consume(); } else if ( db.hasFiles() ) { ArrayList <Path> pathsToAdd = new ArrayList<Path> (); for ( File file : db.getFiles() ) { Path droppedPath = Paths.get( file.getAbsolutePath() ); if ( Utils.isMusicFile( droppedPath ) ) { pathsToAdd.add( droppedPath ); } else if ( Files.isDirectory( droppedPath ) ) { pathsToAdd.addAll( Utils.getAllTracksInDirectory( droppedPath ) ); } else if ( Utils.isPlaylistFile ( droppedPath ) ) { List<Path> paths = Playlist.getTrackPaths( droppedPath ); pathsToAdd.addAll( paths ); } } ArrayList <Track> tracksToAdd = new ArrayList<Track> ( pathsToAdd.size() ); for ( Path path : pathsToAdd ) { tracksToAdd.add( new Track ( path ) ); } if ( !tracksToAdd.isEmpty() ) { trackTable.getItems().addAll( tracksToAdd ); } event.setDropCompleted( true ); event.consume(); } } ); Menu lastFMMenu = new Menu( "LastFM" ); MenuItem loveMenuItem = new MenuItem ( "Love" ); MenuItem unloveMenuItem = new MenuItem ( "Unlove" ); MenuItem scrobbleMenuItem = new MenuItem ( "Scrobble" ); lastFMMenu.getItems().addAll ( loveMenuItem, unloveMenuItem, scrobbleMenuItem ); lastFMMenu.setVisible ( false ); lastFMMenu.visibleProperty().bind( ui.showLastFMWidgets ); loveMenuItem.setOnAction( ( event ) -> { ui.audioSystem.getLastFM().loveTrack( trackTable.getSelectionModel().getSelectedItem() ); }); unloveMenuItem.setOnAction( ( event ) -> { ui.audioSystem.getLastFM().unloveTrack( trackTable.getSelectionModel().getSelectedItem() ); }); scrobbleMenuItem.setOnAction( ( event ) -> { ui.audioSystem.getLastFM().scrobbleTrack( trackTable.getSelectionModel().getSelectedItem() ); }); ContextMenu contextMenu = new ContextMenu(); MenuItem playMenuItem = new MenuItem( "Play" ); MenuItem appendMenuItem = new MenuItem( "Append" ); MenuItem playNextMenuItem = new MenuItem( "Play Next" ); MenuItem enqueueMenuItem = new MenuItem( "Enqueue" ); MenuItem editTagMenuItem = new MenuItem( "Edit Tag(s)" ); MenuItem infoMenuItem = new MenuItem( "Info" ); MenuItem lyricsMenuItem = new MenuItem( "Lyrics" ); MenuItem goToAlbumMenuItem = new MenuItem( "Go to Album" ); MenuItem browseMenuItem = new MenuItem( "Browse Folder" ); Menu addToPlaylistMenuItem = new Menu( "Add to Playlist" ); MenuItem removeMenuItem = new MenuItem ( "Remove" ); contextMenu.getItems().addAll ( playMenuItem, appendMenuItem, playNextMenuItem, enqueueMenuItem, editTagMenuItem, infoMenuItem, lyricsMenuItem, goToAlbumMenuItem, browseMenuItem, addToPlaylistMenuItem, lastFMMenu, removeMenuItem ); MenuItem newPlaylistButton = new MenuItem( "<New>" ); addToPlaylistMenuItem.getItems().add( newPlaylistButton ); newPlaylistButton.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent e ) { ui.promptAndSavePlaylist ( new ArrayList <Track> ( trackTable.getSelectionModel().getSelectedItems() ) ); } }); EventHandler <ActionEvent> addToPlaylistHandler = new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { Playlist playlist = (Playlist) ((MenuItem) event.getSource()).getUserData(); ui.addToPlaylist ( trackTable.getSelectionModel().getSelectedItems(), playlist ); } }; library.getPlaylistsSorted().addListener( ( ListChangeListener.Change <? extends Playlist> change ) -> { ui.updatePlaylistMenuItems( addToPlaylistMenuItem.getItems(), addToPlaylistHandler ); }); ui.updatePlaylistMenuItems( addToPlaylistMenuItem.getItems(), addToPlaylistHandler ); trackTable.setOnKeyPressed( ( KeyEvent e ) -> { if ( e.getCode() == KeyCode.ESCAPE && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { trackTable.getSelectionModel().clearSelection(); } else if ( e.getCode() == KeyCode.Q && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { enqueueMenuItem.fire(); } else if ( e.getCode() == KeyCode.Q && e.isShiftDown() && !e.isAltDown() && !e.isControlDown() && !e.isMetaDown() ) { playNextMenuItem.fire(); } else if ( e.getCode() == KeyCode.F2 && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { editTagMenuItem.fire(); } else if ( e.getCode() == KeyCode.F3 && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { infoMenuItem.fire(); } else if ( e.getCode() == KeyCode.F3 && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { infoMenuItem.fire(); } else if ( e.getCode() == KeyCode.F4 && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { ui.openFileBrowser( trackTable.getSelectionModel().getSelectedItem().getPath() ); } else if ( e.getCode() == KeyCode.L && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { lyricsMenuItem.fire(); } else if ( e.getCode() == KeyCode.ENTER && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { playMenuItem.fire(); } else if ( e.getCode() == KeyCode.ENTER && e.isShiftDown() && !e.isAltDown() && !e.isControlDown() && !e.isMetaDown() ) { audioSystem.getCurrentList().insertTracks( 0, trackTable.getSelectionModel().getSelectedItems() ); } else if ( e.getCode() == KeyCode.ENTER && e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { appendMenuItem.fire(); } else if ( e.getCode() == KeyCode.DELETE && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { removeMenuItem.fire(); } }); playNextMenuItem.setOnAction( event -> { audioSystem.getQueue().queueAllTracks( trackTable.getSelectionModel().getSelectedItems(), 0 ); }); enqueueMenuItem.setOnAction( event -> { audioSystem.getQueue().queueAllTracks( trackTable.getSelectionModel().getSelectedItems() ); }); infoMenuItem.setOnAction( event -> { ui.trackInfoWindow.setTrack( trackTable.getSelectionModel().getSelectedItem() ); ui.trackInfoWindow.show(); }); lyricsMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { ui.lyricsWindow.setTrack( trackTable.getSelectionModel().getSelectedItem() ); ui.lyricsWindow.show(); } }); goToAlbumMenuItem.setOnAction( ( event ) -> { ui.goToAlbumOfTrack ( trackTable.getSelectionModel().getSelectedItem() ); }); browseMenuItem.setOnAction( event -> { ui.openFileBrowser( trackTable.getSelectionModel().getSelectedItem().getPath() ); }); editTagMenuItem.setOnAction( event -> { ui.tagWindow.setTracks( (List<Track>)(List<?>)trackTable.getSelectionModel().getSelectedItems(), null ); ui.tagWindow.show(); }); appendMenuItem.setOnAction( event -> { ui.getCurrentListPane().currentListTable.getItems().addAll( Utils.convertTrackList( trackTable.getSelectionModel().getSelectedItems() ) ); }); removeMenuItem.setOnAction( event -> { List <Track> removeMe = new ArrayList<> (); for ( int k = 0; k < playlist.getTracks().size(); k++ ) { if ( trackTable.getSelectionModel().getSelectedIndices().contains( k ) ) { removeMe.add( playlist.getTracks().get( k ) ); } } trackTable.getSelectionModel().clearSelection(); playlist.getTracks().removeAll( removeMe ); }); playMenuItem.setOnAction( event -> { List <Track> selectedItems = new ArrayList<Track> ( trackTable.getSelectionModel().getSelectedItems() ); if ( selectedItems.size() == 1 ) { audioSystem.playItems( selectedItems ); } else if ( selectedItems.size() > 1 ) { if ( ui.okToReplaceCurrentList() ) { audioSystem.playItems( selectedItems ); } } }); trackTable.setRowFactory( tv -> { TableRow <Track> row = new TableRow <>(); row.itemProperty().addListener( (obs, oldValue, newValue ) -> { if ( newValue != null ) { row.setContextMenu( contextMenu ); } else { row.setContextMenu( null ); } }); row.setOnContextMenuRequested( event -> { goToAlbumMenuItem.setDisable( row.getItem().getAlbum() == null ); }); row.setOnMouseClicked( event -> { if ( event.getClickCount() == 2 && (!row.isEmpty()) ) { audioSystem.playTrack( row.getItem() ); } } ); row.setOnDragDetected( event -> { if ( !row.isEmpty() ) { ArrayList <Integer> indices = new ArrayList <Integer>( trackTable.getSelectionModel().getSelectedIndices() ); ArrayList <Track> tracks = new ArrayList <Track>( trackTable.getSelectionModel().getSelectedItems() ); DraggedTrackContainer dragObject = new DraggedTrackContainer( indices, tracks, null, null, null, DragSource.PLAYLIST_INFO ); Dragboard db = row.startDragAndDrop( TransferMode.COPY ); db.setDragView( row.snapshot( null, null ) ); ClipboardContent cc = new ClipboardContent(); cc.put( FXUI.DRAGGED_TRACKS, dragObject ); db.setContent( cc ); event.consume(); } }); row.setOnDragOver( event -> { Dragboard db = event.getDragboard(); if ( db.hasContent( FXUI.DRAGGED_TRACKS ) || db.hasFiles() ) { event.acceptTransferModes( TransferMode.COPY ); event.consume(); } } ); row.setOnDragDropped( event -> { Dragboard db = event.getDragboard(); if ( db.hasContent( FXUI.DRAGGED_TRACKS ) ) { DraggedTrackContainer container = (DraggedTrackContainer) db.getContent( FXUI.DRAGGED_TRACKS ); int dropIndex = row.isEmpty() ? dropIndex = trackTable.getItems().size() : row.getIndex(); switch ( container.getSource() ) { case PLAYLIST_LIST: { if ( container.getPlaylists() == null ) { LOGGER.log ( Level.INFO, "Recieved null data from playlist list, ignoring.", new NullPointerException() ); } else { List <Track> tracksToCopy = new ArrayList<Track>(); for ( Playlist playlist : container.getPlaylists() ) { if ( playlist == null ) { LOGGER.log ( Level.INFO, "Recieved null playlist from playlist list, ignoring.", new NullPointerException() ); } else { tracksToCopy.addAll( playlist.getTracks() ); } } trackTable.getItems().addAll ( tracksToCopy ); } } break; case ALBUM_LIST: { if ( container.getAlbums() == null ) { LOGGER.log ( Level.INFO, "Recieved null data from playlist list, ignoring.", new NullPointerException() ); } else { List <Track> tracksToCopy = new ArrayList<Track>(); for ( Album album : container.getAlbums() ) { if ( album == null ) { LOGGER.log ( Level.INFO, "Null album dropped in playlist window, ignoring.", new NullPointerException() ); } else { tracksToCopy.addAll( album.getTracks() ); } } trackTable.getItems().addAll ( dropIndex, tracksToCopy ); } } break; case ARTIST_LIST: case TRACK_LIST: case ALBUM_INFO: case HISTORY: case CURRENT_LIST: case TAG_ERROR_LIST: case QUEUE: case CURRENT_TRACK: { List <Track> tracksToCopy = container.getTracks(); trackTable.getItems().addAll( dropIndex, tracksToCopy ); } break; case PLAYLIST_INFO: { List <Integer> draggedIndices = container.getIndices(); ArrayList <Track> tracksToMove = new ArrayList <Track> ( draggedIndices.size() ); for ( int index : draggedIndices ) { if ( index >= 0 && index < trackTable.getItems().size() ) { tracksToMove.add( trackTable.getItems().get( index ) ); } } for ( int k = draggedIndices.size() - 1; k >= 0; k-- ) { int index = draggedIndices.get( k ).intValue(); if ( index >= 0 && index < trackTable.getItems().size() ) { trackTable.getItems().remove ( index ); } } dropIndex = Math.min( trackTable.getItems().size(), row.getIndex() ); trackTable.getItems().addAll( dropIndex, tracksToMove ); trackTable.getSelectionModel().clearSelection(); for ( int k = 0; k < draggedIndices.size(); k++ ) { trackTable.getSelectionModel().select( dropIndex + k ); } playlist.setTracks( new ArrayList <Track> ( trackTable.getItems() ) ); } break; } if ( audioSystem.getCurrentList().getState().getMode() == CurrentList.Mode.PLAYLIST ) { Playlist currentListPlaylist = audioSystem.getCurrentList().getState().getPlaylist(); if ( currentListPlaylist != null && currentListPlaylist.equals( this.playlist ) ) { audioSystem.getCurrentList().setPlaylist( playlist ); } } event.setDropCompleted( true ); event.consume(); } else if ( db.hasFiles() ) { ArrayList <Path> pathsToAdd = new ArrayList<Path> (); for ( File file : db.getFiles() ) { Path droppedPath = Paths.get( file.getAbsolutePath() ); if ( Utils.isMusicFile( droppedPath ) ) { pathsToAdd.add( droppedPath ); } else if ( Files.isDirectory( droppedPath ) ) { pathsToAdd.addAll( Utils.getAllTracksInDirectory( droppedPath ) ); } else if ( Utils.isPlaylistFile ( droppedPath ) ) { List<Path> paths = Playlist.getTrackPaths( droppedPath ); pathsToAdd.addAll( paths ); } } ArrayList <Track> tracksToAdd = new ArrayList<Track> ( pathsToAdd.size() ); for ( Path path : pathsToAdd ) { tracksToAdd.add( new Track ( path ) ); } if ( !tracksToAdd.isEmpty() ) { int dropIndex = row.isEmpty() ? dropIndex = trackTable.getItems().size() : row.getIndex(); trackTable.getItems().addAll( Math.min( dropIndex, trackTable.getItems().size() ), tracksToAdd ); } event.setDropCompleted( true ); event.consume(); } }); return row; }); } }
21,470
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
CurrentListPane.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/fxui/CurrentListPane.java
package net.joshuad.hypnos.fxui; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.EnumMap; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.control.CheckMenuItem; import javafx.scene.control.ContentDisplay; import javafx.scene.control.ContextMenu; import javafx.scene.control.Label; import javafx.scene.control.Menu; import javafx.scene.control.MenuButton; import javafx.scene.control.MenuItem; import javafx.scene.control.SelectionMode; import javafx.scene.control.SeparatorMenuItem; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.scene.control.TableRow; import javafx.scene.control.TableView; import javafx.scene.control.TableView.ResizeFeatures; import javafx.scene.control.Tooltip; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.TableColumn.SortType; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.effect.ColorAdjust; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.ClipboardContent; import javafx.scene.input.Dragboard; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.TransferMode; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Region; import javafx.stage.FileChooser; import net.joshuad.hypnos.AlphanumComparator; import net.joshuad.hypnos.CurrentListState; import net.joshuad.hypnos.CurrentListTrack; import net.joshuad.hypnos.CurrentListTrackState; import net.joshuad.hypnos.Hypnos; import net.joshuad.hypnos.Persister; import net.joshuad.hypnos.Utils; import net.joshuad.hypnos.AlphanumComparator.CaseHandling; import net.joshuad.hypnos.Persister.Setting; import net.joshuad.hypnos.audio.AudioSystem; import net.joshuad.hypnos.audio.AudioSystem.RepeatMode; import net.joshuad.hypnos.audio.AudioSystem.ShuffleMode; import net.joshuad.hypnos.fxui.DraggedTrackContainer.DragSource; import net.joshuad.hypnos.library.Library; import net.joshuad.hypnos.library.Playlist; import net.joshuad.hypnos.library.Track; import net.joshuad.hypnos.library.Track.Format; public class CurrentListPane extends BorderPane { private static final Logger LOGGER = Logger.getLogger( CurrentListPane.class.getName() ); HBox currentListControls; public TableView <CurrentListTrack> currentListTable; //TODO: why public? private Label currentListLength; TableColumn<CurrentListTrack, String> artistColumn, albumColumn, titleColumn, lengthColumn; TableColumn<CurrentListTrack, CurrentListTrackState> playingColumn; TableColumn<CurrentListTrack, Integer> yearColumn, numberColumn; ContextMenu currentListColumnSelectorMenu; Button toggleRepeatButton, toggleShuffleButton; Button showQueueButton; MenuItem saveMenuItem, exportToM3U, exportToFolder, loadMenuItem, historyMenuItem; MenuItem playMenuItem, playNextMenuItem, queueMenuItem, editTagMenuItem, infoMenuItem; MenuItem lyricsMenuItem, cropMenuItem, removeMenuItem, goToAlbumMenuItem, browseMenuItem, addToPlaylistMenuItem; ImageView noRepeatImage, repeatImage, repeatOneImage, sequentialImage, shuffleImage; ImageView queueImage, menuImage; Image repeatImageSource; InfoFilterHybrid infoLabelAndFilter; FXUI ui; AudioSystem audioSystem; Library library; public CurrentListPane( FXUI ui, AudioSystem audioSystem, Library library ) { this.ui = ui; this.audioSystem = audioSystem; this.library = library; loadImages(); setupTable(); resetTableSettingsToDefault(); setupControlPane(); this.setTop( currentListControls ); this.setCenter( currentListTable ); this.setMinWidth( 0 ); } private void loadImages() { double currentListControlsButtonFitWidth = 15; double currentListControlsButtonFitHeight = 15; try { noRepeatImage = new ImageView ( new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( "resources/no-repeat.png" ).toFile() ) ) ); noRepeatImage.setFitWidth( currentListControlsButtonFitWidth ); noRepeatImage.setFitHeight( currentListControlsButtonFitHeight ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to load no repeat icon: resources/no-repeat.png", e ); } try { repeatImageSource = new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( "resources/repeat.png" ).toFile() ) ); repeatImage = new ImageView ( repeatImageSource ); repeatImage.setFitWidth( currentListControlsButtonFitWidth ); repeatImage.setFitHeight( currentListControlsButtonFitHeight ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to load repeat icon: resources/repeat.png", e ); } try { repeatOneImage = new ImageView ( new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( "resources/repeat-one.png" ).toFile() ) ) ); repeatOneImage.setFitWidth( currentListControlsButtonFitWidth ); repeatOneImage.setFitHeight( currentListControlsButtonFitHeight ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to load repeat one icon: resources/repeat-one", e ); } try { sequentialImage = new ImageView ( new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( "resources/sequential.png" ).toFile() ) ) ); sequentialImage.setFitWidth( currentListControlsButtonFitWidth ); sequentialImage.setFitHeight( currentListControlsButtonFitHeight ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to load sequential icon: resources/sequential.png", e ); } try { shuffleImage = new ImageView ( new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( "resources/shuffle.png" ).toFile() ) ) ); shuffleImage.setFitWidth( currentListControlsButtonFitWidth ); shuffleImage.setFitHeight( currentListControlsButtonFitHeight ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to load shuffle icon: resources/shuffle.png", e ); } try { queueImage = new ImageView ( new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( "resources/queue.png" ).toFile() ) ) ); queueImage.setFitWidth( currentListControlsButtonFitWidth ); queueImage.setFitHeight( currentListControlsButtonFitHeight ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to load queue icon: resources/queue.png", e ); } try { menuImage = new ImageView ( new Image( new FileInputStream ( Hypnos.getRootDirectory().resolve( "resources/menu.png" ).toFile() ) ) ); menuImage.setFitWidth( currentListControlsButtonFitWidth ); menuImage.setFitHeight( currentListControlsButtonFitHeight ); } catch ( Exception e ) { LOGGER.log( Level.WARNING, "Unable to load menu icon: resources/menu.png", e ); } } public void resetTableSettingsToDefault() { playingColumn.setVisible( true ); artistColumn.setVisible( true ); yearColumn.setVisible( true ); albumColumn.setVisible( true ); titleColumn.setVisible( true ); numberColumn.setVisible( true ); lengthColumn.setVisible( true ); currentListTable.getColumns().remove( playingColumn ); currentListTable.getColumns().add( playingColumn ); currentListTable.getColumns().remove( numberColumn ); currentListTable.getColumns().add( numberColumn ); currentListTable.getColumns().remove( artistColumn ); currentListTable.getColumns().add( artistColumn ); currentListTable.getColumns().remove( yearColumn ); currentListTable.getColumns().add( yearColumn ); currentListTable.getColumns().remove( albumColumn ); currentListTable.getColumns().add( albumColumn ); currentListTable.getColumns().remove( titleColumn ); currentListTable.getColumns().add( titleColumn ); currentListTable.getColumns().remove( lengthColumn ); currentListTable.getColumns().add( lengthColumn ); artistColumn.setPrefWidth( 100 ); numberColumn.setPrefWidth( 40 ); yearColumn.setPrefWidth( 60 ); albumColumn.setPrefWidth( 100 ); titleColumn.setPrefWidth( 100 ); lengthColumn.setPrefWidth( 70 ); ((HypnosResizePolicy)currentListTable.getColumnResizePolicy()).call( new ResizeFeatures<CurrentListTrack> ( currentListTable, null, (double)0 ) ); } private void setupControlPane () { toggleRepeatButton = new Button( ); toggleShuffleButton = new Button( ); showQueueButton = new Button ( ); showQueueButton.setGraphic( queueImage ); updateRepeatButtonImages(); updateShuffleButtonImages(); float width = 33; float height = 26; toggleRepeatButton.setMinSize( width, height ); toggleShuffleButton.setMinSize( width, height ); showQueueButton.setMinSize( width, height ); toggleRepeatButton.setPrefSize( width, height ); toggleShuffleButton.setPrefSize( width, height ); showQueueButton.setPrefSize( width, height ); toggleRepeatButton.setTooltip( new Tooltip( "Toggle Repeat Type" ) ); toggleShuffleButton.setTooltip( new Tooltip( "Toggle Shuffle" ) ); showQueueButton.setTooltip( new Tooltip( "Show Queue" ) ); showQueueButton.setOnAction ( new EventHandler <ActionEvent>() { public void handle ( ActionEvent e ) { if ( ui.queueWindow.isShowing() ) { ui.queueWindow.hide(); } else { ui.queueWindow.show(); } } }); audioSystem.getQueue().getData().addListener( new ListChangeListener<Track> () { @Override public void onChanged ( Change <? extends Track> arg0 ) { if ( audioSystem.getQueue().isEmpty() ) { showQueueButton.getStyleClass().removeAll ( "queueActive" ); } else { showQueueButton.getStyleClass().add ( "queueActive" ); } } }); toggleRepeatButton.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent e ) { audioSystem.toggleRepeatMode(); updateRepeatButtonImages(); } }); toggleShuffleButton.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent e ) { audioSystem.toggleShuffleMode(); updateShuffleButtonImages(); } }); currentListControls = new HBox(); currentListControls.setAlignment( Pos.CENTER_RIGHT ); currentListControls.setId( "currentListControls" ); currentListLength = new Label ( "" ); currentListLength.setMinWidth( Region.USE_PREF_SIZE ); currentListLength.setPadding( new Insets ( 0, 10, 0, 10 ) ); audioSystem.getCurrentList().getItems().addListener( new ListChangeListener<CurrentListTrack> () { @Override public void onChanged ( Change<? extends CurrentListTrack> changes ) { updateLengthAndCountDisplay(); } }); currentListTable.getSelectionModel().getSelectedIndices().addListener ( new ListChangeListener<Integer>() { @Override public void onChanged ( Change<? extends Integer> c ) { updateLengthAndCountDisplay(); } }); infoLabelAndFilter = new InfoFilterHybrid ( ui ); infoLabelAndFilter.prefWidthProperty().bind( currentListControls.widthProperty() ); infoLabelAndFilter.setFilteredTable( currentListTable ); infoLabelAndFilter.getFilter().setOnKeyPressed( ( KeyEvent e ) -> { if ( e.getCode() == KeyCode.ENTER && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { e.consume(); Track playMe = currentListTable.getSelectionModel().getSelectedItem(); if ( playMe == null ) playMe = currentListTable.getItems().get( 0 ); audioSystem.playTrack( playMe ); } else if ( e.getCode() == KeyCode.F2 && !e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { e.consume(); editTagMenuItem.fire(); } else if ( e.getCode() == KeyCode.F3 && !e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { e.consume(); infoMenuItem.fire(); } else if ( e.getCode() == KeyCode.F4 && !e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { e.consume(); browseMenuItem.fire(); } else if ( e.getCode() == KeyCode.DOWN && !e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { e.consume(); currentListTable.requestFocus(); currentListTable.getSelectionModel().select( currentListTable.getSelectionModel().getFocusedIndex() ); } }); infoLabelAndFilter.textProperty().addListener( new ChangeListener <String> () { @Override public void changed ( ObservableValue <? extends String> observable, String oldValue, String newValue ) { Platform.runLater( () -> { audioSystem.getCurrentList().setFilter( newValue ); }); } }); audioSystem.getCurrentList().addListener( ( CurrentListState currentState ) -> { Platform.runLater( () -> { infoLabelAndFilter.setInfoText( currentState.getDisplayString() ); }); }); final ContextMenu queueButtonMenu = new ContextMenu(); MenuItem clearQueue = new MenuItem ( "Clear Queue" ); MenuItem replaceWithQueue = new MenuItem ( "Replace list with queue" ); MenuItem dumpQueueBefore = new MenuItem ( "Prepend to list" ); MenuItem dumpQueueAfter = new MenuItem ( "Append to list" ); queueButtonMenu.getItems().addAll( clearQueue, replaceWithQueue, dumpQueueBefore, dumpQueueAfter ); showQueueButton.setContextMenu( queueButtonMenu ); clearQueue.setOnAction( ( ActionEvent e ) -> { audioSystem.getQueue().clear(); }); replaceWithQueue.setOnAction( ( ActionEvent e ) -> { audioSystem.getCurrentList().clearList(); audioSystem.getCurrentList().appendTracks ( audioSystem.getQueue().getData() ); audioSystem.getQueue().clear(); }); dumpQueueAfter.setOnAction( ( ActionEvent e ) -> { audioSystem.getCurrentList().appendTracks ( audioSystem.getQueue().getData() ); audioSystem.getQueue().clear(); }); dumpQueueBefore.setOnAction( ( ActionEvent e ) -> { audioSystem.getCurrentList().insertTracks( 0, audioSystem.getQueue().getData() ); audioSystem.getQueue().clear(); }); final ContextMenu shuffleButtonMenu = new ContextMenu(); toggleShuffleButton.setContextMenu( shuffleButtonMenu ); MenuItem sequential = new MenuItem ( "Sequential" ); MenuItem shuffle = new MenuItem ( "Shuffle" ); MenuItem shuffleList = new MenuItem ( "Randomize List Order" ); shuffleButtonMenu.getItems().addAll( sequential, shuffle, shuffleList ); sequential.setOnAction( ( actionEvent ) -> { audioSystem.setShuffleMode( ShuffleMode.SEQUENTIAL ); }); shuffle.setOnAction( ( actionEvent ) -> { audioSystem.setShuffleMode( ShuffleMode.SHUFFLE ); }); shuffleList.setOnAction( ( actionEvent ) -> { audioSystem.shuffleList(); }); final ContextMenu repeatButtonMenu = new ContextMenu(); toggleRepeatButton.setContextMenu( repeatButtonMenu ); MenuItem noRepeat = new MenuItem ( "No Repeat" ); MenuItem repeatAll = new MenuItem ( "Repeat All" ); MenuItem repeatOne = new MenuItem ( "Repeat One Track" ); repeatButtonMenu.getItems().addAll( noRepeat, repeatAll, repeatOne ); noRepeat.setOnAction( ( actionEvent ) -> { audioSystem.setRepeatMode( RepeatMode.PLAY_ONCE ); }); repeatAll.setOnAction( ( actionEvent ) -> { audioSystem.setRepeatMode( RepeatMode.REPEAT ); }); repeatOne.setOnAction( ( actionEvent ) -> { audioSystem.setRepeatMode( RepeatMode.REPEAT_ONE_TRACK ); }); MenuButton currentListMenu = new MenuButton ( "" ); currentListMenu.setTooltip ( new Tooltip ( "Current List Controls" ) ); currentListMenu.setGraphic ( menuImage ); MenuItem currentListClear = new MenuItem ( "Clear" ); saveMenuItem = new MenuItem ( "Save Playlist" ); exportToM3U = new MenuItem ( "Export as M3U" ); exportToFolder = new MenuItem ( "Export as Folder" ); loadMenuItem = new MenuItem ( "Load File(s)" ); historyMenuItem = new MenuItem ( "History" ); MenuItem currentListShuffle = new MenuItem ( "Shuffle" ); MenuItem searchMenuItem = new MenuItem ( "Search" ); MenuItem removeDuplicatesMenuItem = new MenuItem ( "Remove Duplicates" ); currentListClear.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent e ) { audioSystem.getCurrentList().clearList(); } }); historyMenuItem.setOnAction ( new EventHandler <ActionEvent>() { public void handle ( ActionEvent e ) { ui.historyWindow.show(); } }); saveMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent e ) { ui.promptAndSavePlaylist( new ArrayList <Track>( audioSystem.getCurrentList().getItems() ) ); } }); currentListShuffle.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { List<Integer> selectedIndices = currentListTable.getSelectionModel().getSelectedIndices(); if ( selectedIndices.size() < 2 ) { audioSystem.shuffleList(); } else { audioSystem.getCurrentList().shuffleItems( selectedIndices ); } } }); loadMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent e ) { FileChooser fileChooser = new FileChooser(); ArrayList <String> filters = new ArrayList <String> (); for ( Format format : Format.values() ) { filters.add( "*." + format.getExtension() ); } FileChooser.ExtensionFilter fileExtensions = new FileChooser.ExtensionFilter( "Audio Files", filters ); fileChooser.getExtensionFilters().add( fileExtensions ); List <File> selectedFiles = fileChooser.showOpenMultipleDialog( ui.mainStage ); if ( selectedFiles == null ) { return; } ArrayList <Path> paths = new ArrayList <Path> (); for ( File file : selectedFiles ) { paths.add( file.toPath() ); } audioSystem.getCurrentList().setTracksPathList( paths ); } }); exportToM3U.setOnAction( ( ActionEvent e ) -> { File targetFile = ui.promptUserForPlaylistFile(); if ( targetFile == null ) { return; } CurrentListState state = audioSystem.getCurrentList().getState(); Playlist saveMe = null; switch ( state.getMode() ) { case ARTIST: case ALBUM: case ALBUM_REORDERED: { saveMe = new Playlist( targetFile.getName(), Utils.convertCurrentTrackList( state.getItems() ) ); } break; case PLAYLIST: case PLAYLIST_UNSAVED: { saveMe = state.getPlaylist(); if ( saveMe == null ) saveMe = new Playlist( targetFile.getName() ); saveMe.setTracks( Utils.convertCurrentTrackList( state.getItems() ) ); } break; case EMPTY: break; } try { saveMe.saveAs( targetFile ); } catch ( IOException e1 ) { ui.alertUser ( AlertType.ERROR, "Warning", "Unable to save playlist.", "Unable to save the playlist to the specified location" ); } }); exportToFolder.setOnAction( ( ActionEvent e ) -> { List<CurrentListTrack> tracks = currentListTable.getSelectionModel().getSelectedItems(); if ( tracks.size() == 0 ) { tracks = audioSystem.getCurrentList().getSortedItemsNoFilter(); } List<Track> exportMe = new ArrayList <Track> ( tracks ); ui.exportPopup.export( exportMe ); }); removeDuplicatesMenuItem.setOnAction( ( ActionEvent e ) -> { audioSystem.getCurrentList().removeDuplicates(); }); searchMenuItem.setOnAction( ( ActionEvent e ) -> { infoLabelAndFilter.beginEditing(); }); currentListMenu.getItems().addAll ( loadMenuItem, saveMenuItem, currentListClear, currentListShuffle, new SeparatorMenuItem(), exportToM3U, exportToFolder, new SeparatorMenuItem(), searchMenuItem, historyMenuItem, removeDuplicatesMenuItem ); currentListControls.getChildren().addAll( toggleShuffleButton, toggleRepeatButton, showQueueButton, infoLabelAndFilter, currentListLength, currentListMenu ); currentListControls.prefWidthProperty().bind( this.widthProperty() ); } private void setupTable () { playingColumn = new TableColumn<CurrentListTrack, CurrentListTrackState>( "" ); artistColumn = new TableColumn<CurrentListTrack, String>( "Artist" ); yearColumn = new TableColumn<CurrentListTrack, Integer>( "Year" ); albumColumn = new TableColumn<CurrentListTrack, String>( "Album" ); titleColumn = new TableColumn<CurrentListTrack, String>( "Title" ); numberColumn = new TableColumn<CurrentListTrack, Integer>( "#" ); lengthColumn = new TableColumn<CurrentListTrack, String>( "Length" ); albumColumn.setComparator( new AlphanumComparator( CaseHandling.CASE_INSENSITIVE ) ); artistColumn.setComparator( new AlphanumComparator( CaseHandling.CASE_INSENSITIVE ) ); titleColumn.setComparator( new AlphanumComparator( CaseHandling.CASE_INSENSITIVE ) ); playingColumn.setCellValueFactory( new PropertyValueFactory <CurrentListTrack, CurrentListTrackState>( "displayState" ) ); artistColumn.setCellValueFactory( new PropertyValueFactory <CurrentListTrack, String>( "artist" ) ); yearColumn.setCellValueFactory( new PropertyValueFactory <CurrentListTrack, Integer>( "year" ) ); albumColumn.setCellValueFactory( new PropertyValueFactory <CurrentListTrack, String>( "fullAlbumTitle" ) ); titleColumn.setCellValueFactory( new PropertyValueFactory <CurrentListTrack, String>( "title" ) ); numberColumn.setCellValueFactory( new PropertyValueFactory <CurrentListTrack, Integer>( "trackNumber" ) ); lengthColumn.setCellValueFactory( new PropertyValueFactory <CurrentListTrack, String>( "lengthDisplay" ) ); albumColumn.setCellFactory( e -> new FormattedAlbumCell<>() ); playingColumn.setCellFactory ( column -> { return new CurrentListTrackStateCell( ui, ui.transport.playImageSource, ui.transport.pauseImageSource ); } ); numberColumn.setCellFactory( column -> { return new TableCell <CurrentListTrack, Integer>() { @Override protected void updateItem ( Integer value, boolean empty ) { super.updateItem( value, empty ); if ( value == null || value.equals( Track.NO_TRACK_NUMBER ) || empty ) { setText( null ); } else { setText( value.toString() ); } } }; }); currentListColumnSelectorMenu = new ContextMenu (); CheckMenuItem playingMenuItem = new CheckMenuItem ( "Show Playing Column" ); CheckMenuItem artistMenuItem = new CheckMenuItem ( "Show Artist Column" ); CheckMenuItem yearMenuItem = new CheckMenuItem ( "Show Year Column" ); CheckMenuItem albumMenuItem = new CheckMenuItem ( "Show Album Column" ); CheckMenuItem numberMenuItem = new CheckMenuItem ( "Show Track # Column" ); CheckMenuItem titleMenuItem = new CheckMenuItem ( "Show Title Column" ); CheckMenuItem lengthMenuItem = new CheckMenuItem ( "Show Length Column" ); MenuItem resetMenuItem = new MenuItem ( "Reset To Default View" ); playingMenuItem.setSelected( true ); artistMenuItem.setSelected( true ); yearMenuItem.setSelected( true ); albumMenuItem.setSelected( true ); numberMenuItem.setSelected( true ); titleMenuItem.setSelected( true ); lengthMenuItem.setSelected( true ); currentListColumnSelectorMenu.getItems().addAll( playingMenuItem, numberMenuItem,artistMenuItem, yearMenuItem, albumMenuItem, titleMenuItem, lengthMenuItem, resetMenuItem ); playingColumn.setContextMenu( currentListColumnSelectorMenu ); artistColumn.setContextMenu( currentListColumnSelectorMenu ); yearColumn.setContextMenu( currentListColumnSelectorMenu ); albumColumn.setContextMenu( currentListColumnSelectorMenu ); titleColumn.setContextMenu( currentListColumnSelectorMenu ); numberColumn.setContextMenu( currentListColumnSelectorMenu ); lengthColumn.setContextMenu( currentListColumnSelectorMenu ); playingMenuItem.selectedProperty().bindBidirectional( playingColumn.visibleProperty() ); artistMenuItem.selectedProperty().bindBidirectional( artistColumn.visibleProperty() ); yearMenuItem.selectedProperty().bindBidirectional( yearColumn.visibleProperty() ); albumMenuItem.selectedProperty().bindBidirectional( albumColumn.visibleProperty() ); numberMenuItem.selectedProperty().bindBidirectional( numberColumn.visibleProperty() ); titleMenuItem.selectedProperty().bindBidirectional( titleColumn.visibleProperty() ); lengthMenuItem.selectedProperty().bindBidirectional( lengthColumn.visibleProperty() ); currentListTable = new TableView<CurrentListTrack> (); currentListTable.getColumns().addAll( playingColumn, numberColumn, artistColumn, yearColumn, albumColumn, titleColumn, lengthColumn ); currentListTable.setEditable( false ); currentListTable.setItems( audioSystem.getCurrentList().getSortedItems() ); audioSystem.getCurrentList().getSortedItems().comparatorProperty().bind( currentListTable.comparatorProperty() ); HypnosResizePolicy resizePolicy = new HypnosResizePolicy(); currentListTable.setColumnResizePolicy( resizePolicy ); currentListTable.setPlaceholder( new Label( "No tracks in playlist." ) ); currentListTable.getSelectionModel().setSelectionMode( SelectionMode.MULTIPLE ); playingColumn.setMaxWidth( 38 ); playingColumn.setMinWidth( 38 ); playingColumn.setResizable( false ); resizePolicy.registerFixedWidthColumns( yearColumn, numberColumn, lengthColumn ); currentListTable.setOnDragOver( event -> { Dragboard db = event.getDragboard(); if ( db.hasContent( FXUI.DRAGGED_TRACKS ) || db.hasFiles() ) { event.acceptTransferModes( TransferMode.COPY ); event.consume(); } }); currentListTable.setOnDragDropped( event -> { Dragboard db = event.getDragboard(); if ( db.hasContent( FXUI.DRAGGED_TRACKS ) ) { //REFACTOR: This code is duplicated below. Put it in a function. DraggedTrackContainer container = (DraggedTrackContainer) db.getContent( FXUI.DRAGGED_TRACKS ); switch ( container.getSource() ) { case TRACK_LIST: case ALBUM_INFO: case PLAYLIST_INFO: case TAG_ERROR_LIST: case HISTORY: case CURRENT_TRACK: { List <Track> tracks = container.getTracks(); if ( tracks.size() > 0 ) { audioSystem.getCurrentList().setItemsToSortedOrder(); currentListTable.getSortOrder().clear(); audioSystem.getCurrentList().appendTracks( tracks ); } } break; case PLAYLIST_LIST: { audioSystem.getCurrentList().setItemsToSortedOrder(); currentListTable.getSortOrder().clear(); audioSystem.getCurrentList().appendPlaylists( container.getPlaylists() ); } break; case ARTIST_LIST: { audioSystem.getCurrentList().setItemsToSortedOrder(); currentListTable.getSortOrder().clear(); audioSystem.getCurrentList().appendArtists( container.getArtists() ); } break; case ALBUM_LIST: { audioSystem.getCurrentList().setItemsToSortedOrder(); currentListTable.getSortOrder().clear(); audioSystem.getCurrentList().appendAlbums ( container.getAlbums() ); } break; case CURRENT_LIST: { //There is no meaning in dragging from an empty list to an empty list. } break; case QUEUE: { synchronized ( audioSystem.getQueue().getData() ) { List <Integer> draggedIndices = container.getIndices(); ArrayList <Track> tracksToCopy = new ArrayList <Track> ( draggedIndices.size() ); for ( int index : draggedIndices ) { if ( index >= 0 && index < audioSystem.getQueue().getData().size() ) { Track addMe = audioSystem.getQueue().getData().get( index ); if ( addMe instanceof CurrentListTrack ) { tracksToCopy.add( (CurrentListTrack)addMe ); } else { CurrentListTrack newAddMe = new CurrentListTrack ( addMe ); audioSystem.getQueue().getData().remove ( index ); audioSystem.getQueue().getData().add( index, newAddMe ); tracksToCopy.add( newAddMe ); } } } audioSystem.getCurrentList().setItemsToSortedOrder(); currentListTable.getSortOrder().clear(); audioSystem.getCurrentList().appendTracks( tracksToCopy ); } } break; } audioSystem.getQueue().updateQueueIndexes(); event.setDropCompleted( true ); event.consume(); } else if ( db.hasFiles() ) { ArrayList <Path> tracksToAdd = new ArrayList<Path> (); for ( File file : db.getFiles() ) { Path droppedPath = Paths.get( file.getAbsolutePath() ); if ( Utils.isMusicFile( droppedPath ) ) { tracksToAdd.add ( droppedPath ); } else if ( Files.isDirectory( droppedPath ) ) { tracksToAdd.addAll ( Utils.getAllTracksInDirectory( droppedPath ) ); } else if ( Utils.isPlaylistFile ( droppedPath ) ) { List<Path> paths = Playlist.getTrackPaths( droppedPath ); tracksToAdd.addAll( paths ); } } if ( !tracksToAdd.isEmpty() ) { audioSystem.getCurrentList().setItemsToSortedOrder(); currentListTable.getSortOrder().clear(); audioSystem.getCurrentList().insertTrackPathList ( 0, tracksToAdd ); } event.setDropCompleted( true ); event.consume(); } }); ContextMenu contextMenu = new ContextMenu(); playMenuItem = new MenuItem( "Play" ); playNextMenuItem = new MenuItem( "Play Next" ); queueMenuItem = new MenuItem( "Enqueue" ); editTagMenuItem = new MenuItem( "Edit Tag(s)" ); infoMenuItem = new MenuItem( "Info" ); lyricsMenuItem = new MenuItem( "Lyrics" ); cropMenuItem = new MenuItem( "Crop" ); removeMenuItem = new MenuItem( "Remove" ); goToAlbumMenuItem = new MenuItem( "Go to Album" ); browseMenuItem = new MenuItem( "Browse Folder" ); Menu addToPlaylistMenuItem = new Menu( "Add to Playlist" ); currentListTable.addEventFilter( KeyEvent.KEY_PRESSED, ( KeyEvent e ) -> { if ( e.getCode() == KeyCode.ESCAPE && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { currentListTable.getSelectionModel().clearSelection(); e.consume(); } }); currentListTable.setOnKeyPressed( ( KeyEvent e ) -> { if ( e.getCode() == KeyCode.DELETE && !e.isAltDown() && !e.isControlDown() && !e.isShiftDown() && !e.isMetaDown() ) { removeMenuItem.fire(); e.consume(); } else if ( e.getCode() == KeyCode.DELETE && e.isShiftDown() && !e.isAltDown() && !e.isControlDown() && !e.isMetaDown() ) { cropMenuItem.fire(); e.consume(); } else if ( e.getCode() == KeyCode.Q && !e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { queueMenuItem.fire(); e.consume(); } else if ( e.getCode() == KeyCode.G && e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { goToAlbumMenuItem.fire(); } else if ( e.getCode() == KeyCode.Q && e.isShiftDown() && !e.isControlDown() && !e.isAltDown() && !e.isMetaDown() ) { playNextMenuItem.fire(); e.consume(); } else if ( e.getCode() == KeyCode.L && !e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { lyricsMenuItem.fire(); e.consume(); } else if ( e.getCode() == KeyCode.F2 && !e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { editTagMenuItem.fire(); e.consume(); } else if ( e.getCode() == KeyCode.F3 && !e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { infoMenuItem.fire(); e.consume(); } else if ( e.getCode() == KeyCode.F4 && !e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { browseMenuItem.fire(); e.consume(); } else if ( e.getCode() == KeyCode.ENTER && !e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { playMenuItem.fire(); e.consume(); } else if ( e.getCode() == KeyCode.UP && !e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) { if ( currentListTable.getSelectionModel().getSelectedIndex() == 0 && infoLabelAndFilter.isFilterMode() ) { infoLabelAndFilter.beginEditing(); e.consume(); } } }); Menu lastFMMenu = new Menu( "LastFM" ); MenuItem loveMenuItem = new MenuItem ( "Love" ); MenuItem unloveMenuItem = new MenuItem ( "Unlove" ); MenuItem scrobbleMenuItem = new MenuItem ( "Scrobble" ); lastFMMenu.getItems().addAll ( loveMenuItem, unloveMenuItem, scrobbleMenuItem ); lastFMMenu.setVisible ( false ); lastFMMenu.visibleProperty().bind( ui.showLastFMWidgets ); loveMenuItem.setOnAction( ( event ) -> { ui.audioSystem.getLastFM().loveTrack( currentListTable.getSelectionModel().getSelectedItem() ); }); unloveMenuItem.setOnAction( ( event ) -> { ui.audioSystem.getLastFM().unloveTrack( currentListTable.getSelectionModel().getSelectedItem() ); }); scrobbleMenuItem.setOnAction( ( event ) -> { ui.audioSystem.getLastFM().scrobbleTrack( currentListTable.getSelectionModel().getSelectedItem() ); }); MenuItem newPlaylistButton = new MenuItem( "<New>" ); addToPlaylistMenuItem.getItems().add( newPlaylistButton ); contextMenu.getItems().addAll( playMenuItem, playNextMenuItem, queueMenuItem, editTagMenuItem, infoMenuItem, lyricsMenuItem, goToAlbumMenuItem, browseMenuItem, addToPlaylistMenuItem, lastFMMenu, cropMenuItem, removeMenuItem ); newPlaylistButton.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent e ) { ui.promptAndSavePlaylist ( new ArrayList <Track> ( currentListTable.getSelectionModel().getSelectedItems() ) ); } }); resetMenuItem.setOnAction ( ( e ) -> this.resetTableSettingsToDefault() ); EventHandler<ActionEvent> addToPlaylistHandler = new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { Playlist playlist = (Playlist) ((MenuItem) event.getSource()).getUserData(); ui.addToPlaylist ( Utils.convertCurrentTrackList ( currentListTable.getSelectionModel().getSelectedItems() ), playlist ); } }; library.getPlaylistsSorted().addListener( ( ListChangeListener.Change <? extends Playlist> change ) -> { ui.updatePlaylistMenuItems( addToPlaylistMenuItem.getItems(), addToPlaylistHandler ); } ); ui.updatePlaylistMenuItems( addToPlaylistMenuItem.getItems(), addToPlaylistHandler ); playNextMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { audioSystem.getQueue().queueAllTracks( currentListTable.getSelectionModel().getSelectedItems(), 0 ); } }); queueMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { audioSystem.getQueue().queueAllTracks( currentListTable.getSelectionModel().getSelectedItems() ); } }); editTagMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { ui.tagWindow.setTracks( (List<Track>)(List<?>)currentListTable.getSelectionModel().getSelectedItems(), null ); ui.tagWindow.show(); } }); infoMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { ui.trackInfoWindow.setTrack( currentListTable.getSelectionModel().getSelectedItem() ); ui.trackInfoWindow.show(); } }); lyricsMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { ui.lyricsWindow.setTrack( currentListTable.getSelectionModel().getSelectedItem() ); ui.lyricsWindow.show(); } }); playMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { audioSystem.playTrack( currentListTable.getSelectionModel().getSelectedItem() ); } } ); browseMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { ui.openFileBrowser ( currentListTable.getSelectionModel().getSelectedItem().getPath() ); } }); goToAlbumMenuItem.setOnAction( ( event ) -> { ui.goToAlbumOfTrack ( currentListTable.getSelectionModel().getSelectedItem() ); }); removeMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { ObservableList <Integer> selectedIndexes = currentListTable.getSelectionModel().getSelectedIndices(); List <Integer> removeMe = new ArrayList<> ( selectedIndexes ); currentListTable.getSelectionModel().clearSelection(); ui.removeFromCurrentList ( removeMe ); } }); cropMenuItem.setOnAction( new EventHandler <ActionEvent>() { @Override public void handle ( ActionEvent event ) { ObservableList <Integer> selectedIndexes = currentListTable.getSelectionModel().getSelectedIndices(); List <Integer> removeMe = new ArrayList<Integer> ( selectedIndexes.size() ); for ( int k = 0; k < currentListTable.getItems().size(); k++ ) { if ( !selectedIndexes.contains( k ) ) { removeMe.add ( k ); } } ui.removeFromCurrentList ( removeMe ); currentListTable.getSelectionModel().clearSelection(); } }); currentListTable.getSelectionModel().selectedItemProperty().addListener( ( obs, oldSelection, newSelection ) -> { ui.trackSelected ( newSelection ); }); currentListTable.setRowFactory( tv -> { TableRow <CurrentListTrack> row = new TableRow <>(); row.setOnContextMenuRequested( event -> { goToAlbumMenuItem.setDisable( row.getItem().getAlbum() == null ); }); row.setOnMouseClicked( event -> { if ( event.getClickCount() == 2 && !row.isEmpty() ) { audioSystem.playTrack( row.getItem() ); } }); row.itemProperty().addListener( (obs, oldValue, newValue ) -> { if ( newValue != null ) { row.setContextMenu( contextMenu ); } else { row.setContextMenu( null ); } if ( newValue != null && row != null ) { if ( newValue.isMissingFile() ) { row.getStyleClass().add( "file-missing" ); } else { row.getStyleClass().remove( "file-missing" ); } } }); row.itemProperty().addListener( ( obs, oldValue, newTrackValue ) -> { if ( newTrackValue != null && row != null ) { newTrackValue.fileIsMissingProperty().addListener( ( o, old, newValue ) -> { if ( newValue ) { row.getStyleClass().add( "file-missing" ); } else { row.getStyleClass().remove( "file-missing" ); } }); } }); row.setOnDragDetected( event -> { if ( !row.isEmpty() ) { ArrayList <Integer> indices = new ArrayList <Integer>( currentListTable.getSelectionModel().getSelectedIndices() ); ArrayList <Track> tracks = new ArrayList <Track>( currentListTable.getSelectionModel().getSelectedItems() ); DraggedTrackContainer dragObject = new DraggedTrackContainer( indices, tracks, null, null, null, DragSource.CURRENT_LIST ); Dragboard db = row.startDragAndDrop( TransferMode.COPY ); db.setDragView( row.snapshot( null, null ) ); ClipboardContent cc = new ClipboardContent(); cc.put( FXUI.DRAGGED_TRACKS, dragObject ); db.setContent( cc ); event.consume(); } }); row.setOnDragOver( event -> { Dragboard db = event.getDragboard(); if ( db.hasContent( FXUI.DRAGGED_TRACKS ) || db.hasFiles() ) { event.acceptTransferModes( TransferMode.COPY ); event.consume(); } }); row.setOnDragDropped( event -> { Dragboard db = event.getDragboard(); if ( db.hasContent( FXUI.DRAGGED_TRACKS ) ) { DraggedTrackContainer container = (DraggedTrackContainer) db.getContent( FXUI.DRAGGED_TRACKS ); int dropIndex = row.getIndex(); switch ( container.getSource() ) { case ALBUM_LIST: { audioSystem.getCurrentList().setItemsToSortedOrder(); currentListTable.getSortOrder().clear(); audioSystem.getCurrentList().insertAlbums( dropIndex, container.getAlbums() ); } break; case ARTIST_LIST: case PLAYLIST_LIST: case TRACK_LIST: case ALBUM_INFO: case PLAYLIST_INFO: case TAG_ERROR_LIST: case HISTORY: case CURRENT_TRACK: { audioSystem.getCurrentList().setItemsToSortedOrder(); currentListTable.getSortOrder().clear(); audioSystem.getCurrentList().insertTracks( dropIndex, Utils.convertTrackList( container.getTracks() ) ); } break; case CURRENT_LIST: { audioSystem.getCurrentList().setItemsToSortedOrder(); currentListTable.getSortOrder().clear(); List<Integer> draggedIndices = container.getIndices(); audioSystem.getCurrentList().moveTracks ( draggedIndices, dropIndex ); currentListTable.getSelectionModel().clearSelection(); for ( int k = 0; k < draggedIndices.size(); k++ ) { int selectIndex = dropIndex + k; if ( selectIndex < currentListTable.getItems().size() ) { currentListTable.getSelectionModel().select( dropIndex + k ); } } } break; case QUEUE: { synchronized ( audioSystem.getQueue().getData() ) { List <Integer> draggedIndices = container.getIndices(); ArrayList <CurrentListTrack> tracksToCopy = new ArrayList <CurrentListTrack> ( draggedIndices.size() ); for ( int index : draggedIndices ) { if ( index >= 0 && index < audioSystem.getQueue().getData().size() ) { Track addMe = audioSystem.getQueue().getData().get( index ); if ( addMe instanceof CurrentListTrack ) { tracksToCopy.add( (CurrentListTrack)addMe ); } else { CurrentListTrack newAddMe = new CurrentListTrack ( addMe ); audioSystem.getQueue().getData().remove ( index ); audioSystem.getQueue().getData().add( index, newAddMe ); tracksToCopy.add( newAddMe ); } } } audioSystem.getCurrentList().setItemsToSortedOrder(); currentListTable.getSortOrder().clear(); audioSystem.getCurrentList().insertTracks ( dropIndex, tracksToCopy ); } } break; } audioSystem.getQueue().updateQueueIndexes( ); event.setDropCompleted( true ); event.consume(); } else if ( db.hasFiles() ) { //REFACTOR: this code is in a bunch of places. We should probably make it a function ArrayList <Path> tracksToAdd = new ArrayList<Path> (); for ( File file : db.getFiles() ) { Path droppedPath = Paths.get( file.getAbsolutePath() ); if ( Utils.isMusicFile( droppedPath ) ) { tracksToAdd.add( droppedPath ); } else if ( Files.isDirectory( droppedPath ) ) { tracksToAdd.addAll( Utils.getAllTracksInDirectory( droppedPath ) ); } else if ( Utils.isPlaylistFile ( droppedPath ) ) { List<Path> paths = Playlist.getTrackPaths( droppedPath ); tracksToAdd.addAll( paths ); } } if ( !tracksToAdd.isEmpty() ) { audioSystem.getCurrentList().setItemsToSortedOrder(); currentListTable.getSortOrder().clear(); int dropIndex = row.isEmpty() ? dropIndex = currentListTable.getItems().size() : row.getIndex(); audioSystem.getCurrentList().insertTrackPathList ( dropIndex, tracksToAdd ); } event.setDropCompleted( true ); event.consume(); } }); return row; }); } void updateShuffleButtonImages() { switch ( audioSystem.getShuffleMode() ) { case SHUFFLE: toggleShuffleButton.setGraphic( shuffleImage ); break; case SEQUENTIAL: //Fall through default: toggleShuffleButton.setGraphic( sequentialImage ); break; } } void updateRepeatButtonImages() { switch ( audioSystem.getRepeatMode() ) { case REPEAT: toggleRepeatButton.setGraphic( repeatImage ); break; case REPEAT_ONE_TRACK: toggleRepeatButton.setGraphic( repeatOneImage ); break; default: //Fall through case PLAY_ONCE: toggleRepeatButton.setGraphic( noRepeatImage ); break; } } public void applyDarkTheme ( ColorAdjust darkThemeButtons ) { if ( noRepeatImage != null ) noRepeatImage.setEffect( darkThemeButtons ); if ( repeatImage != null ) repeatImage.setEffect( darkThemeButtons ); if ( repeatOneImage != null ) repeatOneImage.setEffect( darkThemeButtons ); if ( sequentialImage != null ) sequentialImage.setEffect( darkThemeButtons ); if ( shuffleImage != null ) shuffleImage.setEffect( darkThemeButtons ); if ( menuImage != null ) menuImage.setEffect( darkThemeButtons ); if ( queueImage != null ) queueImage.setEffect( darkThemeButtons ); infoLabelAndFilter.applyButtonColorAdjust( darkThemeButtons ); currentListTable.refresh(); } public void applyLightTheme () { if ( noRepeatImage != null ) noRepeatImage.setEffect( ui.lightThemeButtonEffect ); if ( repeatImage != null ) repeatImage.setEffect( ui.lightThemeButtonEffect ); if ( repeatOneImage != null ) repeatOneImage.setEffect( ui.lightThemeButtonEffect ); if ( sequentialImage != null ) sequentialImage.setEffect( ui.lightThemeButtonEffect ); if ( shuffleImage != null ) shuffleImage.setEffect( ui.lightThemeButtonEffect ); if ( menuImage != null ) menuImage.setEffect( ui.lightThemeButtonEffect ); if ( queueImage != null ) queueImage.setEffect( ui.lightThemeButtonEffect ); infoLabelAndFilter.applyButtonColorAdjust( ui.lightThemeButtonEffect ); currentListTable.refresh(); } @SuppressWarnings("incomplete-switch") public void applySettingsBeforeWindowShown( EnumMap<Persister.Setting, String> settings ) { settings.forEach( ( setting, value )-> { try { switch ( setting ) { case CL_TABLE_PLAYING_COLUMN_SHOW: playingColumn.setVisible( Boolean.valueOf ( value ) ); settings.remove ( setting ); break; case CL_TABLE_NUMBER_COLUMN_SHOW: numberColumn.setVisible( Boolean.valueOf ( value ) ); settings.remove ( setting ); break; case CL_TABLE_ARTIST_COLUMN_SHOW: artistColumn.setVisible( Boolean.valueOf ( value ) ); settings.remove ( setting ); break; case CL_TABLE_YEAR_COLUMN_SHOW: yearColumn.setVisible( Boolean.valueOf ( value ) ); settings.remove ( setting ); break; case CL_TABLE_ALBUM_COLUMN_SHOW: albumColumn.setVisible( Boolean.valueOf ( value ) ); settings.remove ( setting ); break; case CL_TABLE_TITLE_COLUMN_SHOW: titleColumn.setVisible( Boolean.valueOf ( value ) ); settings.remove ( setting ); break; case CL_TABLE_LENGTH_COLUMN_SHOW: lengthColumn.setVisible( Boolean.valueOf ( value ) ); settings.remove ( setting ); break; case CL_SORT_ORDER: currentListTable.getSortOrder().clear(); if ( !value.equals( "" ) ) { String[] order = value.split( " " ); for ( String fullValue : order ) { try { String columnName = fullValue.split( "-" )[0]; SortType sortType = SortType.valueOf( fullValue.split( "-" )[1] ); if ( columnName.equals( "playing" ) ) { currentListTable.getSortOrder().add( playingColumn ); playingColumn.setSortType( sortType ); } else if ( columnName.equals( "artist" ) ) { currentListTable.getSortOrder().add( artistColumn ); artistColumn.setSortType( sortType ); } else if ( columnName.equals( "year" ) ) { currentListTable.getSortOrder().add( yearColumn ); yearColumn.setSortType( sortType ); } else if ( columnName.equals( "album" ) ) { currentListTable.getSortOrder().add( albumColumn ); albumColumn.setSortType( sortType ); } else if ( columnName.equals( "title" ) ) { currentListTable.getSortOrder().add( titleColumn ); titleColumn.setSortType( sortType ); } else if ( columnName.equals( "number" ) ) { currentListTable.getSortOrder().add( numberColumn ); numberColumn.setSortType( sortType ); } else if ( columnName.equals( "length" ) ) { currentListTable.getSortOrder().add( lengthColumn ); lengthColumn.setSortType( sortType ); } } catch ( Exception e ) { LOGGER.log( Level.INFO, "Unable to set album table sort order: '" + value + "'", e ); } } } settings.remove ( setting ); break; case CL_COLUMN_ORDER: { String[] order = value.split( " " ); int newIndex = 0; for ( String columnName : order ) { try { if ( columnName.equals( "playing" ) ) { currentListTable.getColumns().remove( playingColumn ); currentListTable.getColumns().add( newIndex, playingColumn ); } else if ( columnName.equals( "artist" ) ) { currentListTable.getColumns().remove( artistColumn ); currentListTable.getColumns().add( newIndex, artistColumn ); } else if ( columnName.equals( "year" ) ) { currentListTable.getColumns().remove( yearColumn ); currentListTable.getColumns().add( newIndex, yearColumn ); } else if ( columnName.equals( "album" ) ) { currentListTable.getColumns().remove( albumColumn ); currentListTable.getColumns().add( newIndex, albumColumn ); } else if ( columnName.equals( "title" ) ) { currentListTable.getColumns().remove( titleColumn ); currentListTable.getColumns().add( newIndex, titleColumn ); } else if ( columnName.equals( "number" ) ) { currentListTable.getColumns().remove( numberColumn ); currentListTable.getColumns().add( newIndex, numberColumn ); } else if ( columnName.equals( "length" ) ) { currentListTable.getColumns().remove( lengthColumn ); currentListTable.getColumns().add( newIndex, lengthColumn ); } newIndex++; } catch ( Exception e ) { LOGGER.log( Level.INFO, "Unable to set album table column order: '" + value + "'", e ); } } settings.remove ( setting ); break; } } } catch ( Exception e ) { LOGGER.log( Level.INFO, "Unable to apply setting: " + setting + " to current list.", e ); } }); } public EnumMap<Persister.Setting, ? extends Object> getSettings () { EnumMap <Persister.Setting, Object> retMe = new EnumMap <Persister.Setting, Object> ( Persister.Setting.class ); String sortOrderValue = ""; for ( TableColumn<CurrentListTrack, ?> column : currentListTable.getSortOrder() ) { if ( column == playingColumn ) { sortOrderValue += "playing-" + playingColumn.getSortType() + " "; } else if ( column == artistColumn ) { sortOrderValue += "artist-" + artistColumn.getSortType() + " "; } else if ( column == yearColumn ) { sortOrderValue += "year-" + yearColumn.getSortType() + " "; } else if ( column == albumColumn ) { sortOrderValue += "album-" + albumColumn.getSortType() + " "; } else if ( column == titleColumn ) { sortOrderValue += "title-" + titleColumn.getSortType() + " "; } else if ( column == numberColumn ) { sortOrderValue += "number-" + numberColumn.getSortType() + " "; } else if ( column == lengthColumn ) { sortOrderValue += "length-" + lengthColumn.getSortType() + " "; } } retMe.put ( Setting.CL_SORT_ORDER, sortOrderValue ); String columnOrderValue = ""; for ( TableColumn<CurrentListTrack, ?> column : currentListTable.getColumns() ) { if ( column == playingColumn ) { columnOrderValue += "playing "; } else if ( column == artistColumn ) { columnOrderValue += "artist "; } else if ( column == yearColumn ) { columnOrderValue += "year "; } else if ( column == albumColumn ) { columnOrderValue += "album "; } else if ( column == titleColumn ) { columnOrderValue += "title "; } else if ( column == numberColumn ) { columnOrderValue += "number "; } else if ( column == lengthColumn ) { columnOrderValue += "length "; } } retMe.put ( Setting.CL_COLUMN_ORDER, columnOrderValue ); retMe.put ( Setting.CL_TABLE_PLAYING_COLUMN_SHOW, playingColumn.isVisible() ); retMe.put ( Setting.CL_TABLE_NUMBER_COLUMN_SHOW, numberColumn.isVisible() ); retMe.put ( Setting.CL_TABLE_ARTIST_COLUMN_SHOW, artistColumn.isVisible() ); retMe.put ( Setting.CL_TABLE_YEAR_COLUMN_SHOW, yearColumn.isVisible() ); retMe.put ( Setting.CL_TABLE_ALBUM_COLUMN_SHOW, albumColumn.isVisible() ); retMe.put ( Setting.CL_TABLE_TITLE_COLUMN_SHOW, titleColumn.isVisible() ); retMe.put ( Setting.CL_TABLE_LENGTH_COLUMN_SHOW, lengthColumn.isVisible() ); return retMe; } private void updateLengthAndCountDisplay() { int lengthS = 0; int trackCount = 0; List<Integer> selected = currentListTable.getSelectionModel().getSelectedIndices(); if ( selected.size() == 0 || selected.size() == 1 ) { for ( Track track : audioSystem.getCurrentList().getItems() ) { if ( track != null ) { lengthS += track.getLengthS(); } } trackCount = audioSystem.getCurrentList().getItems().size(); } else { for ( int index : selected ) { if ( index >= 0 && index < audioSystem.getCurrentList().getItems().size() ) { lengthS += audioSystem.getCurrentList().getItems().get( index ).getLengthS(); trackCount++; } } } final int lengthArgument = lengthS; final int trackArgument = trackCount; Platform.runLater( () -> { currentListLength.setText( trackArgument + " / " + Utils.getLengthDisplay( lengthArgument ) ); }); } } class CurrentListTrackStateCell extends TableCell <CurrentListTrack, CurrentListTrackState> { private ImageView pauseImage, playImage; private FXUI ui; private boolean isDarkTheme = false; public CurrentListTrackStateCell ( FXUI ui, Image playImageSource, Image pauseImageSource ) { this.ui = ui; playImage = new ImageView ( playImageSource ); playImage.setFitHeight( 13 ); playImage.setFitWidth( 13 ); pauseImage = new ImageView ( pauseImageSource ); pauseImage.setFitHeight( 13 ); pauseImage.setFitWidth( 13 ); setContentDisplay ( ContentDisplay.LEFT ); setGraphicTextGap ( 2 ); this.setAlignment( Pos.BOTTOM_LEFT ); } protected void updateImageThemes ( ) { if ( ui.isDarkTheme() && !isDarkTheme ) { playImage.setEffect( ui.transport.darkThemeButtonEffect ); pauseImage.setEffect( ui.transport.darkThemeButtonEffect ); isDarkTheme = true; } else if ( !ui.isDarkTheme() ) { playImage.setEffect( ui.transport.lightThemeButtonEffect ); pauseImage.setEffect( ui.transport.lightThemeButtonEffect ); isDarkTheme = false; } } @Override protected void updateItem ( CurrentListTrackState state, boolean empty ) { super.updateItem( state, empty ); updateImageThemes(); if ( state != null ) { if ( state.getIsCurrentTrack() ) { ImageView playPauseImage = ui.audioSystem.isPaused() ? pauseImage : playImage; if ( state.getQueueIndices().size() > 0 ) { setGraphic ( playPauseImage ); setText ( "+" ); } else { setGraphic ( playPauseImage ); setText ( null ); } } else if ( state.getQueueIndices().size() == 1 ) { setText ( state.getQueueIndices().get( 0 ).toString() ); setGraphic ( null ); } else if ( state.getQueueIndices().size() >= 1 ) { setText ( state.getQueueIndices().get( 0 ).toString() + "+" ); setGraphic ( null ); } else { setText ( "" ); setGraphic ( null ); } } else { setText( null ); setGraphic( null ); } } }
56,057
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
ThrottledAlbumFilter.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/fxui/ThrottledAlbumFilter.java
package net.joshuad.hypnos.fxui; import java.text.Normalizer; import java.util.ArrayList; import javafx.application.Platform; import javafx.collections.transformation.FilteredList; import net.joshuad.hypnos.library.Album; public class ThrottledAlbumFilter { private String requestedFilter = ""; private long timeRequestMadeMS = 0; private Thread filterThread; private boolean interruptFiltering = false; private String currentAppliedFilter = ""; private FilteredList <Album> filteredList; public ThrottledAlbumFilter ( FilteredList <Album> filteredList ) { this.filteredList = filteredList; try { filterThread = new Thread ( () -> { while ( true ) { String filter = requestedFilter; if ( !filter.equals( currentAppliedFilter ) ) { if ( System.currentTimeMillis() >= timeRequestMadeMS + 100 ) { interruptFiltering = false; Platform.runLater(()->setPredicate( filter )); currentAppliedFilter = filter; } } try { Thread.sleep( 50 ); } catch ( InterruptedException e ) {} } }); filterThread.setName( "Throttled Album Filter" ); filterThread.setDaemon( true ); filterThread.start(); } catch ( Exception e ) { //TODO: Logging, what is this exception? System.out.println ( "Caught here" ); } } public void setFilter ( String filter ) { if ( filter == null ) filter = ""; timeRequestMadeMS = System.currentTimeMillis(); this.requestedFilter = filter; interruptFiltering = true; } private void setPredicate ( String filterText ) { filteredList.setPredicate( album -> { if ( interruptFiltering ) return true; if ( filterText.isEmpty() ) return true; ArrayList <String> matchableText = new ArrayList <String>(); matchableText.add( album.getAlbumArtist().toLowerCase() ); matchableText.add( album.getYear().toLowerCase() ); matchableText.add( album.getFullAlbumTitle().toLowerCase() ); matchableText.add( Normalizer.normalize( album.getFullAlbumTitle(), Normalizer.Form.NFD ) .replaceAll( "[^\\p{ASCII}]", "" ).toLowerCase() ); matchableText.add( Normalizer.normalize( album.getYear(), Normalizer.Form.NFD ) .replaceAll( "[^\\p{ASCII}]", "" ).toLowerCase() ); matchableText.add( Normalizer.normalize( album.getAlbumArtist(), Normalizer.Form.NFD ) .replaceAll( "[^\\p{ASCII}]", "" ).toLowerCase() ); String[] lowerCaseFilterTokens = filterText.toLowerCase().split( "\\s+" ); for ( String token : lowerCaseFilterTokens ) { boolean tokenMatches = false; for ( String test : matchableText ) { if ( test.contains( token ) ) { tokenMatches = true; } } if ( !tokenMatches ) { return false; } } return true; }); } }
2,769
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
Lyrics.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/lyrics/Lyrics.java
package net.joshuad.hypnos.lyrics; import java.util.logging.Level; import java.util.logging.Logger; import net.joshuad.hypnos.lyrics.LyricsFetcher.LyricSite; public class Lyrics { private static transient final Logger LOGGER = Logger.getLogger( Lyrics.class.getName() ); public enum ScrapeError { NONE, NOT_FOUND, NOT_AVAILABLE, RESTRICTED } private String lyrics; private ScrapeError error; private LyricSite site; private String sourceURL; public Lyrics ( String lyrics, LyricSite site, String sourceURL ) { this ( lyrics, site, sourceURL, ScrapeError.NONE ); } public Lyrics ( String lyrics, LyricSite site, String sourceURL, ScrapeError error ) { if ( lyrics == null ) lyrics = ""; this.lyrics = lyrics; this.error = error; this.site = site; this.sourceURL = sourceURL; } public String getLyrics() { if ( error != ScrapeError.NONE ) { LOGGER.log ( Level.INFO, "Asked for lyrics when there was a scrape error.", new Exception() ); } return lyrics; } public ScrapeError getError() { return error; } public boolean hadScrapeError() { return error != ScrapeError.NONE; } public String getSourceURL() { return sourceURL; } public LyricSite getSite() { return site; } }
1,244
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
LyricsFetcher.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/lyrics/LyricsFetcher.java
package net.joshuad.hypnos.lyrics; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import net.joshuad.hypnos.library.Track; import net.joshuad.hypnos.lyrics.scrapers.AZScraper; import net.joshuad.hypnos.lyrics.scrapers.AbstractScraper; import net.joshuad.hypnos.lyrics.scrapers.GeniusScraper; import net.joshuad.hypnos.lyrics.scrapers.MetroScraper; import net.joshuad.hypnos.lyrics.scrapers.MusixScraper; public class LyricsFetcher { @SuppressWarnings("unused") private static transient final Logger LOGGER = Logger.getLogger( LyricsFetcher.class.getName() ); public enum LyricSite { NONE ( "No Source" ), METRO ( "Metro Lyrics" ), GENIUS ( "Genius Lyrics" ), AZ ( "AZLyrics" ), MUSIX ( "MusixMatch" ); private String name; LyricSite ( String name ) { this.name = name; } public String getName() { return name; } } private MetroScraper metroParser = new MetroScraper(); private GeniusScraper geniusParser = new GeniusScraper(); private AZScraper azParser = new AZScraper(); private MusixScraper musixParser = new MusixScraper(); private List <AbstractScraper> parseOrder = new ArrayList <AbstractScraper> (); public LyricsFetcher () { setParseOrder ( LyricSite.GENIUS, LyricSite.AZ, LyricSite.MUSIX, LyricSite.METRO ); } public Lyrics get ( Track track ) { Lyrics lyrics = new Lyrics ( "", LyricSite.NONE, "", Lyrics.ScrapeError.NOT_FOUND ); List<String> failedUrls = new ArrayList<>(); for ( AbstractScraper parser : parseOrder ) { lyrics = parser.getLyrics( track ); if ( !lyrics.hadScrapeError() ) { break; } else { failedUrls.add(lyrics.getSourceURL()); } } if ( lyrics.hadScrapeError() ) { LOGGER.info("Failed to fetch lyrics at the following urls:\n\t" + String.join("\n\t", failedUrls)); String simplifiedTrackTitle = track.getTitle().replaceAll( " ?\\(.*\\)", "" ); if ( !simplifiedTrackTitle.equals( track.getTitle() ) ) { for ( AbstractScraper parser : parseOrder ) { lyrics = parser.getLyrics ( track.getAlbumArtist(), simplifiedTrackTitle ); if ( !lyrics.hadScrapeError() ) break; lyrics = parser.getLyrics ( track.getArtist(), simplifiedTrackTitle ); if ( !lyrics.hadScrapeError() ) break; lyrics = parser.getLyrics ( track.getAlbumArtist().toLowerCase().replaceFirst( "the ", "" ), simplifiedTrackTitle ); if ( !lyrics.hadScrapeError() ) break; lyrics = parser.getLyrics ( track.getArtist().toLowerCase().replaceFirst( "the ", "" ), simplifiedTrackTitle ); if ( !lyrics.hadScrapeError() ) break; } } } return lyrics; } public void setParseOrder ( LyricSite ... parsers ) { parseOrder.clear(); for ( LyricSite type : parsers ) { switch ( type ) { case AZ: parseOrder.add ( azParser ); break; case GENIUS: parseOrder.add ( geniusParser ); break; case METRO: parseOrder.add ( metroParser ); break; case MUSIX: parseOrder.add ( musixParser ); break; case NONE: //Do nothing break; } } } /** Testing **/ private static void testAll ( String artist, String song, boolean printLyrics ) { MetroScraper metroParser = new MetroScraper(); GeniusScraper geniusParser = new GeniusScraper(); AZScraper azParser = new AZScraper(); MusixScraper musixParser = new MusixScraper(); Lyrics metro = metroParser.getLyrics( artist, song ); Lyrics az = azParser.getLyrics( artist, song ); Lyrics genius = geniusParser.getLyrics( artist, song ); Lyrics musix = musixParser.getLyrics( artist, song ); if ( printLyrics ) { printTestResults ( metro ); printTestResults ( az ); printTestResults ( genius ); printTestResults ( musix ); } System.out.println ( artist + " - " + song ); System.out.println ( "------------" ); System.out.println ( "Metro: " + ( metro.hadScrapeError() ? "Fail - " + metro.getError() + " - " + metro.getSourceURL(): "Success" ) ); System.out.println ( "AZ: " + ( az.hadScrapeError() ? "Fail - " + az.getError() + " - " + az.getSourceURL() : "Success - " + az.getSourceURL() ) ); System.out.println ( "Genius: " + ( genius.hadScrapeError() ? "Fail - " + genius.getError() + " - " + genius.getSourceURL(): "Success" ) ); System.out.println ( "Musix: " + ( musix.hadScrapeError() ? "Fail - " + musix.getError() + " - " + musix.getSourceURL(): "Success" ) ); System.out.println ( "\n" ); } private static void printTestResults ( Lyrics results ) { System.out.println ( "\n\n---------------------- Begin " + results.getSite().getName() + " ------------------------" ); System.out.println ( results.hadScrapeError() ? "No lyrics found" : results.getLyrics() ); System.out.println ( "----------------------- End " + results.getSite().getName() + " -------------------------\n\n" ); } public static void main ( String[] args ) { /* testAll ( "Regina Spektor", "Apres Moi", true ); testAll ( "Regina Spektor", "Après Moi", true ); testAll ( "Andrew Bird", "Action/Adventure", true ); testAll ( "Björk", "Aeroplane", true ); testAll ( "Bjork", "Aeroplane", true ); testAll ( "311", "Rollin'", true ); testAll ( "John Lennon", "Oh Yoko!", true ); testAll ( "Jenny Lewis", "Aloha & The Three Johns", true ); testAll ( "John Frusciante", "Away & Anywhere", true ); testAll ( "John Vanderslice", "C & O Canal", true ); testAll ( "The Roots", "Thought @ Work", true ); testAll ( "Elliott Smith", "Waltz #1", true ); testAll ( "Ani DiFranco", "78% H2O", true ); testAll ( "Radiohead", "2+2=5", true ); testAll ( "Florence + the Machine", "Bird Song", true ); testAll ( "M. Ward", "Lullaby + Exile", true ); testAll ( "PJ Harvey", "Is This Desire?", true ); */ testAll ( "Andrew Bird", "Imitosis", true ); } }
5,864
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
AZScraper.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/lyrics/scrapers/AZScraper.java
package net.joshuad.hypnos.lyrics.scrapers; import java.io.IOException; import java.text.Normalizer; import java.util.logging.Logger; import org.apache.commons.text.StringEscapeUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.safety.Whitelist; import net.joshuad.hypnos.lyrics.Lyrics; import net.joshuad.hypnos.lyrics.LyricsFetcher; public class AZScraper extends AbstractScraper { @SuppressWarnings("unused") private static transient final Logger LOGGER = Logger.getLogger( AZScraper.class.getName() ); public AZScraper() { baseURL = "https://www.azlyrics.com/"; } @Override public Lyrics getLyrics ( String artist, String song ) { String artistBase = makeURLReady ( artist ); String songBase = makeURLReady ( song ); String url = baseURL + "lyrics/" + artistBase + "/" + songBase + ".html"; String lyrics = null; try { Document doc = Jsoup.connect( url ).get(); //We can't select the lyrics div directly since it has no id or class. //But it's the first div after the "div class=ringtone" //Thankfully, jsoup can do exactly that selection Element verses = doc.select( ".ringtone ~ div" ).get( 0 ); lyrics = cleanPreserveLineBreaks ( verses.html() ).replaceAll( "\n +", "\n" ).replaceAll( "^\\s*", "" ); } catch ( IOException e ) { return new Lyrics ( "", LyricsFetcher.LyricSite.AZ, url, Lyrics.ScrapeError.NOT_FOUND ); } return new Lyrics ( StringEscapeUtils.unescapeHtml4 ( lyrics ), LyricsFetcher.LyricSite.AZ, url ); } private String makeURLReady ( String string ) { return Normalizer.normalize( string, Normalizer.Form.NFD ).replaceAll( "[^\\p{ASCII}]", "" ) .replaceAll ( "& ", "" ).replaceAll( "&", "" ) .replaceAll ( "@ ", "" ).replaceAll( "@", "" ) .replaceAll ( "# ", "" ).replaceAll( "#", "" ) .replaceAll( "[%+=]", "" ) .replaceAll ( "[?]", "" ) .replaceAll( "['\"\\/,.! ]", "" ).toLowerCase(); } public static String cleanPreserveLineBreaks ( String bodyHtml ) { String prettyPrintedBodyFragment = Jsoup.clean( bodyHtml, "", Whitelist.none().addTags( "br", "p" ), new Document.OutputSettings().prettyPrint( true ) ); prettyPrintedBodyFragment = prettyPrintedBodyFragment.replaceAll ( "(?i)<br */?>", "" ).replaceAll ( "(?i)< */? *p *>", "\n\n" ); return prettyPrintedBodyFragment; } public static void main ( String [] args ) { AZScraper parser = new AZScraper(); Lyrics result = parser.getLyrics( "Rilo Kiley", "Silver Lining" ); if ( result.hadScrapeError() ) { System.out.println ( "Error: " + result.getError() ); } else { System.out.println ( result.getLyrics() ); } } }
2,695
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
AbstractScraper.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/lyrics/scrapers/AbstractScraper.java
package net.joshuad.hypnos.lyrics.scrapers; import net.joshuad.hypnos.library.Track; import net.joshuad.hypnos.lyrics.Lyrics; public abstract class AbstractScraper { String baseURL = "undefined"; public Lyrics getLyrics ( Track track ) { Lyrics lyrics = null; lyrics = getLyrics ( track.getAlbumArtist(), track.getTitle() ); if ( lyrics.hadScrapeError() ) { lyrics = getLyrics ( track.getArtist(), track.getTitle() ); } return lyrics; } public abstract Lyrics getLyrics ( String artist, String title ); public String getURL() { return baseURL; } }
586
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
MetroScraper.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/lyrics/scrapers/MetroScraper.java
package net.joshuad.hypnos.lyrics.scrapers; import java.io.IOException; import java.text.Normalizer; import java.util.logging.Logger; import org.apache.commons.text.StringEscapeUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; import net.joshuad.hypnos.lyrics.Lyrics; import net.joshuad.hypnos.lyrics.LyricsFetcher; public class MetroScraper extends AbstractScraper { @SuppressWarnings("unused") private static transient final Logger LOGGER = Logger.getLogger( MetroScraper.class.getName() ); public MetroScraper() { baseURL = "http://www.metrolyrics.com/"; } @Override public Lyrics getLyrics ( String artist, String song ) { String artistBase = makeURLReady ( artist ); String songBase = makeURLReady ( song ); String url = baseURL + songBase + "-lyrics-" + artistBase + ".html"; String lyrics = null; try { Document doc = Jsoup.connect( url ).get(); Elements message = doc.getElementsByClass( "lyric-message" ); if ( message.html().matches( "^Unfortunately.*" ) ) { return new Lyrics ( "", LyricsFetcher.LyricSite.METRO, url, Lyrics.ScrapeError.RESTRICTED ); } Elements verses = doc.getElementsByClass( "verse" ); lyrics = verses.html().replaceAll("\n", "\n\n").replaceAll("<br> ?", "\n"); } catch ( IOException e ) { return new Lyrics ( "", LyricsFetcher.LyricSite.METRO, url, Lyrics.ScrapeError.NOT_FOUND ); } if ( lyrics != null && lyrics.isEmpty() ) { lyrics = null; return new Lyrics ( "", LyricsFetcher.LyricSite.METRO, url, Lyrics.ScrapeError.NOT_AVAILABLE ); } return new Lyrics ( StringEscapeUtils.unescapeHtml4 ( lyrics ), LyricsFetcher.LyricSite.METRO, url ); } private String makeURLReady ( String string ) { //Unfortunately it doesn't appear that MetroScraper has a standard for handling "/". //Sometimes it replaces it with - and sometims with an empty string //See Bon Iver - Beth/Rest and Bright Eyes - Easy/Lucky/Free return Normalizer.normalize( string, Normalizer.Form.NFD ).replaceAll( "[^\\p{ASCII}]", "" ) .replaceAll ( "& ?", "" ) .replaceAll ( "@ ?", "" ) .replaceAll ( "[#%]", "" ) .replaceAll ( "[+=] ?", "" ) .replaceAll ( "[?]", "" ) .replaceAll( "['\",.!-]", "" ).replaceAll( "[\\/ ]", "-" ).toLowerCase(); } private static void test ( String artist, String song ) { MetroScraper parser = new MetroScraper(); Lyrics result = parser.getLyrics( artist, song ); if ( result.hadScrapeError() ) { System.out.println ( "Error - " + result.getError() ); System.out.println ( "---------------" ); System.out.println ( "url: " + result.getSourceURL() ); System.out.println ( "\n" ); } else { System.out.println ( "Success" ); System.out.println ( "---------------" ); System.out.println ( result.getLyrics() ); System.out.println ( "\n" ); } } public static void main ( String [] args ) { //test ( "Björk", "Aeroplane" ); test ( "Andrew Bird", "Action/Adventure" ); //test ( "Bon Iver", "Beth/Rest" ); //test ( "Bright Eyes", "Easy/Lucky/Free" ); //test ( "Bjork", "Aeroplane" ); //System.out.println ( Normalizer.normalize( "Björk", Normalizer.Form.NFD ) ); } }
3,220
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
MusixScraper.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/lyrics/scrapers/MusixScraper.java
package net.joshuad.hypnos.lyrics.scrapers; import java.io.IOException; import java.text.Normalizer; import java.util.logging.Logger; import org.apache.commons.text.StringEscapeUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; import net.joshuad.hypnos.lyrics.Lyrics; import net.joshuad.hypnos.lyrics.LyricsFetcher; public class MusixScraper extends AbstractScraper { @SuppressWarnings("unused") private static transient final Logger LOGGER = Logger.getLogger( MusixScraper.class.getName() ); public MusixScraper() { baseURL = "https://www.musixmatch.com/"; } @Override public Lyrics getLyrics ( String artist, String song ) { String artistBase = makeURLReady ( artist ); String songBase = makeURLReady ( song ); String url = baseURL + "lyrics/" + artistBase + "/" + songBase; String lyrics = null; try { Document doc = Jsoup.connect( url ).get(); doc.outputSettings().prettyPrint( false ); Elements lyricElement = doc.getElementsByClass( "mxm-lyrics__content" ); lyrics = lyricElement.html(); lyrics = lyrics.replaceAll( "<span class=\"lyrics__content__.*\">", "" ); lyrics = lyrics.replaceAll( "</span>", "" ); } catch ( IOException e ) { return new Lyrics ( "", LyricsFetcher.LyricSite.MUSIX, url, Lyrics.ScrapeError.NOT_FOUND ); } if ( lyrics == null || lyrics.equals( "" ) ) { return new Lyrics ( "", LyricsFetcher.LyricSite.MUSIX, url, Lyrics.ScrapeError.NOT_FOUND ); } if ( lyrics.matches( "^Restricted Lyrics.*" ) ) { lyrics = null; return new Lyrics ( "", LyricsFetcher.LyricSite.MUSIX, url, Lyrics.ScrapeError.RESTRICTED ); } return new Lyrics ( StringEscapeUtils.unescapeHtml4 ( lyrics ), LyricsFetcher.LyricSite.MUSIX, url ); } private String makeURLReady ( String string ) { return Normalizer.normalize( string, Normalizer.Form.NFD ).replaceAll( "[^\\p{ASCII}]", "" ) .replaceAll ( "& ", "" ).replaceAll( "&", "" ) .replaceAll ( "@ ", "" ).replaceAll( "@", "" ) .replaceAll ( "[#%]", "" ) .replaceAll ( "[+] ?", "" ) .replaceAll ( "[?]", "" ) .replaceAll( "['\",.!]", "" ).replaceAll( "[\\/+= ]", "-" ).toLowerCase(); } public static void main ( String [] args ) { MusixScraper parser = new MusixScraper(); Lyrics result = parser.getLyrics( "Blind Guardian", "The Eldar" ); if ( result.hadScrapeError() ) { System.out.println ( "Error: " + result.getError() ); } else { System.out.println ( result.getLyrics() ); } } }
2,528
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
GeniusScraper.java
/FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/lyrics/scrapers/GeniusScraper.java
package net.joshuad.hypnos.lyrics.scrapers; import java.io.IOException; import java.text.Normalizer; import java.util.logging.Logger; import org.apache.commons.text.StringEscapeUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.safety.Whitelist; import org.jsoup.select.Elements; import net.joshuad.hypnos.lyrics.Lyrics; import net.joshuad.hypnos.lyrics.LyricsFetcher; public class GeniusScraper extends AbstractScraper { @SuppressWarnings("unused") private static transient final Logger LOGGER = Logger.getLogger(GeniusScraper.class.getName()); public GeniusScraper() { baseURL = "http://www.genius.com/"; } @Override public Lyrics getLyrics(String artist, String song) { String artistBase = makeURLReady(artist); String songBase = makeURLReady(song); String url = baseURL + artistBase + "-" + songBase + "-lyrics"; String lyrics = null; try { Document doc = Jsoup.connect(url).get(); Elements verses = doc.getElementsByClass("lyrics"); lyrics = cleanPreserveLineBreaks(verses.html()).replaceAll("\n +", "\n").replaceAll("^\\s*", ""); } catch (IOException e) { return new Lyrics("", LyricsFetcher.LyricSite.GENIUS, url, Lyrics.ScrapeError.NOT_FOUND); } return new Lyrics(StringEscapeUtils.unescapeHtml4(lyrics), LyricsFetcher.LyricSite.GENIUS, url); } private String makeURLReady(String string) { return Normalizer.normalize(string, Normalizer.Form.NFD).replaceAll("[^\\p{ASCII}]", "").replaceAll("&", "and") .replaceAll("@", "at").replaceAll("[#%]", "").replaceAll("[+] ?", "").replaceAll("[?]", "") .replaceAll("['\",.!]", "").replaceAll("[\\/= ]", "-").toLowerCase(); } private static String cleanPreserveLineBreaks(String bodyHtml) { String prettyPrintedBodyFragment = Jsoup.clean(bodyHtml, "", Whitelist.none().addTags("br", "p"), new Document.OutputSettings().prettyPrint(true)); prettyPrintedBodyFragment = prettyPrintedBodyFragment.replaceAll("(?i)<br */?>", "\n").replaceAll("(?i)< */? *p *>", "\n\n"); return prettyPrintedBodyFragment; } public static void main(String[] args) { GeniusScraper parser = new GeniusScraper(); Lyrics result = parser.getLyrics("Sufjan Stevens", "Impossible Soul"); if (result.hadScrapeError()) { System.out.println("Error: " + result.getError()); } else { System.out.println(result.getLyrics()); } } }
2,362
Java
.java
JoshuaD84/HypnosMusicPlayer
21
2
0
2017-05-02T07:06:13Z
2020-08-30T02:20:45Z
ErrMsgBox.java
/FileExtraction/Java_unseen/ignasi-p_eq-diagr/DataMaintenance/src/dataMaintenance/ErrMsgBox.java
package dataMaintenance; /** Displays a "message box" modal dialog with an "OK" button and a title. * The message is displayed in a text area (non-editable), * which can be copied and pasted elsewhere. * * Copyright (C) 2014-2016 I.Puigdomenech. * * 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 * 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/ * * @author Ignasi Puigdomenech */ public class ErrMsgBox { private static final String nl = System.getProperty("line.separator"); //<editor-fold defaultstate="collapsed" desc="ErrMsgBox(msg, title)"> /** Displays a "message box" modal dialog with an "OK" button and a title. * The message is displayed in a text area (non-editable), * which can be copied and pasted elsewhere. * @param msg will be displayed in a text area, and line breaks may be * included, for example: <code>new MsgBox("Very\nbad!",""); </code> * If null or empty nothing is done. * @param title for the dialog. If null or empty, "Error:" is used * @see #showErrMsg(java.awt.Component, java.lang.String, int) showErrMsg * @version 2015-July-14 */ public ErrMsgBox(String msg, String title) { if(msg == null || msg.trim().length() <=0) { System.out.println("--- MsgBox: null or empty \"message\"."); return; } //--- Title if(title == null || title.length() <=0) {title = " Error:";} java.awt.Frame frame = new java.awt.Frame(title); //--- Icon String iconName = "images/ErrMsgBx.gif"; java.net.URL imgURL = this.getClass().getResource(iconName); if(imgURL != null) {frame.setIconImage(new javax.swing.ImageIcon(imgURL).getImage());} else {System.out.println("--- Error in MsgBox constructor: Could not load image = \""+iconName+"\"");} frame.pack(); //--- centre Window frame on Screen java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); int left; int top; left = Math.max(55, (screenSize.width - frame.getWidth() ) / 2); top = Math.max(10, (screenSize.height - frame.getHeight()) / 2); frame.setLocation(Math.min(screenSize.width-100, left), Math.min(screenSize.height-100, top)); //--- final String msgText = wrapString(msg.trim(),80); //System.out.println("--- MsgBox:"+nl+msgText+nl+"---"); frame.setVisible(true); //javax.swing.JOptionPane.showMessageDialog(frame, msg, title, javax.swing.JOptionPane.ERROR_MESSAGE); MsgBoxDialog msgBox = new MsgBoxDialog(frame, msgText, title, true); msgBox.setVisible(true); // becase the dialog is modal, statements below will wait msgBox.dispose(); frame.setVisible(false); frame.dispose(); } // </editor-fold> //<editor-fold defaultstate="collapsed" desc="private class MsgBoxDialog"> private static class MsgBoxDialog extends java.awt.Dialog { private java.awt.Button ok; private java.awt.Panel p; private final java.awt.TextArea text; /** Creates new form NewDialog */ public MsgBoxDialog(java.awt.Frame parent, String msg, String title, boolean modal) { super(parent, (" "+title), modal); addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent evt) { MsgBoxDialog.this.setVisible(false); } }); setLayout(new java.awt.BorderLayout()); p = new java.awt.Panel(); p.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER)); ok = new java.awt.Button(); // find out the size of the message (width and height) final int wMax = 85; final int hMax=20; final int wMin = 5; final int hMin = 1; int w = wMin; int h=hMin; int i=0; int j=wMin; final String eol = "\n"; char c; final String nl = System.getProperty("line.separator"); while (true) { c = msg.charAt(i); String s = String.valueOf(c); if(s.equals(eol) || s.equals(nl)) { h++; j=wMin; } else { j++; w = Math.max(j,w); } i++; if(i >= msg.length()-1) {break;} } // create a text area int scroll = java.awt.TextArea.SCROLLBARS_NONE; if(w > wMax && h <= hMax) {scroll = scroll & java.awt.TextArea.SCROLLBARS_HORIZONTAL_ONLY;} if(h > hMax && w <= wMax) {scroll = scroll & java.awt.TextArea.SCROLLBARS_VERTICAL_ONLY;} if(w > wMax && h > hMax) {scroll = java.awt.TextArea.SCROLLBARS_BOTH;} w = Math.min(Math.max(w,10),wMax); h = Math.min(h,hMax); text = new java.awt.TextArea(msg, h, w, scroll); text.setEditable(false); //text.setBackground(java.awt.Color.white); text.addKeyListener(new java.awt.event.KeyAdapter() { @Override public void keyPressed(java.awt.event.KeyEvent evt) { if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER || evt.getKeyCode() == java.awt.event.KeyEvent.VK_ESCAPE) {closeDialog();} if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_TAB) {ok.requestFocusInWindow();} } }); text.setBackground(java.awt.Color.WHITE); text.setFont(new java.awt.Font("monospaced", java.awt.Font.PLAIN, 12)); add(text, java.awt.BorderLayout.CENTER); ok.setLabel("OK"); ok.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent evt) { closeDialog(); } }); ok.addKeyListener(new java.awt.event.KeyAdapter() { @Override public void keyPressed(java.awt.event.KeyEvent evt) { if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER || evt.getKeyCode() == java.awt.event.KeyEvent.VK_ESCAPE) {closeDialog();} } }); p.add(ok); add(p, java.awt.BorderLayout.SOUTH); pack(); ok.requestFocusInWindow(); //--- centre Window frame on Screen java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); int left; int top; left = Math.max(55, (screenSize.width - getWidth() ) / 2); top = Math.max(10, (screenSize.height - getHeight()) / 2); setLocation(Math.min(screenSize.width-100, left), Math.min(screenSize.height-100, top)); } private void closeDialog() {this.setVisible(false);} } // private static class MsgBoxDialog //</editor-fold> //<editor-fold defaultstate="collapsed" desc="private wrapString"> /** Returns an input string, with lines that are longer than <code>maxLength</code> * word-wrapped and indented. * * @param s input string * @param maxLength if an input line is longer than this length, * the line will be word-wrapped at the first white space after <code>maxLength</code> * and indented with 4 spaces * @return string with long-lines word-wrapped */ private static String wrapString(String s, int maxLength) { String deliminator = "\n"; StringBuilder result = new StringBuilder(); StringBuffer wrapLine; int lastdelimPos; for (String line : s.split(deliminator, -1)) { if(line.length()/(maxLength+1) < 1) { result.append(line).append(deliminator); } else { //line too long, try to split it wrapLine = new StringBuffer(); lastdelimPos = 0; for (String token : line.trim().split("\\s+", -1)) { if (wrapLine.length() - lastdelimPos + token.length() > maxLength) { if(wrapLine.length()>0) {wrapLine.append(deliminator);} wrapLine.append(" ").append(token); lastdelimPos = wrapLine.length() + 1; } else { if(wrapLine.length() <=0) {wrapLine.append(token);} else {wrapLine.append(" ").append(token);} } } result.append(wrapLine).append(deliminator); } } return result.toString(); } // </editor-fold> }
8,985
Java
.java
ignasi-p/eq-diagr
18
3
0
2018-08-17T08:25:37Z
2023-04-30T09:33:35Z
Main.java
/FileExtraction/Java_unseen/ignasi-p_eq-diagr/DataMaintenance/src/dataMaintenance/Main.java
package dataMaintenance; /** Checks for all the jar-libraries needed. * <br> * Copyright (C) 2014-2016 I.Puigdomenech. * * 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 * 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/ * * @author Ignasi Puigdomenech */ public class Main { private static final String progName = "Data Maintenace"; /** New-line character(s) to substitute "\n" */ private static final String nl = System.getProperty("line.separator"); private static boolean started = false; private static final String SLASH = java.io.File.separator; /** Check that all the jar-libraries needed do exist. * @param args the command line arguments */ public static void main(String[] args) { // ---- are all jar files needed there? if(!doJarFilesExist()) {return;} // ---- ok! dataMaintenance.DataMaintenance.main(args); } //main //<editor-fold defaultstate="collapsed" desc="doJarFilesExist"> /** Look in the running jar file's classPath Manifest for any other "library" * jar-files listed under "Class-path". * If any of these jar files does not exist display an error message * (and an error Frame) and continue. * @return true if all needed jar files exist; false otherwise. * @version 2016-Aug-03 */ private static boolean doJarFilesExist() { java.io.File libJarFile, libPathJarFile; java.util.jar.JarFile runningJar = getRunningJarFile(); // runningJar.getName() = C:\Eq-Calc_Java\dist\Prog.jar if(runningJar != null) { // if running within Netbeans there will be no jar-file java.util.jar.Manifest manifest; try {manifest = runningJar.getManifest();} catch (java.io.IOException ex) { manifest = null; String msg = "Warning: no manifest found in the application's jar file:"+nl+ "\""+runningJar.getName()+"\""; ErrMsgBox emb = new ErrMsgBox(msg, progName); //this will return true; } if(manifest != null) { String classPath = manifest.getMainAttributes().getValue("Class-Path"); if(classPath != null && classPath.length() > 0) { // this will be a list of space-separated names String[] jars = classPath.split("\\s+"); //regular expression to match one or more spaces if(jars.length >0) { java.io.File[] rootNames = java.io.File.listRoots(); boolean isPathAbsolute; String pathJar; String p = getPathApp(); // get the application's path for(String jar : jars) { // loop through all jars needed libJarFile = new java.io.File(jar); if(libJarFile.exists()) {continue;} isPathAbsolute = false; for(java.io.File f : rootNames) { if(jar.toLowerCase().startsWith(f.getAbsolutePath().toLowerCase())) { isPathAbsolute = true; break;} } if(!isPathAbsolute) { // add the application's path if(!p.endsWith(SLASH) && !jar.startsWith(SLASH)) {p = p+SLASH;} pathJar = p + jar; } else {pathJar = jar;} libPathJarFile = new java.io.File(pathJar); if(libPathJarFile.exists()) {continue;} libPathJarFile = new java.io.File(libPathJarFile.getAbsolutePath()); ErrMsgBox emb = new ErrMsgBox(progName+" - Error:"+nl+ " File: \""+jar+"\" NOT found."+nl+ " And file: \""+libPathJarFile.getName()+"\" is NOT in folder:"+nl+ " \""+libPathJarFile.getParent()+"\""+nl+ " either!"+nl+nl+ " This file is needed by the program."+nl, progName); return false; } } }//if classPath != null } //if Manifest != null } //if runningJar != null return true; } //doJarFilesExist() //<editor-fold defaultstate="collapsed" desc="getRunningJarFile()"> /** Find out the jar file that contains this class * @return a File object of the jar file containing the enclosing class "Main", * or null if the main class is not inside a jar file. * @version 2014-Jan-17 */ public static java.util.jar.JarFile getRunningJarFile() { //from http://www.rgagnon.com/javadetails/ //and the JarClassLoader class C c = new C(); String className = c.getClass().getName().replace('.', '/'); // class = "progPackage.Main"; className = "progPackage/Main" java.net.URL url = c.getClass().getResource("/" + className + ".class"); // url = "jar:file:/C:/Eq-Calc_Java/dist/Prog.jar!/progPackage/Main.class" if(url.toString().startsWith("jar:")) { java.net.JarURLConnection jUrlC; try{ jUrlC = (java.net.JarURLConnection)url.openConnection(); return jUrlC.getJarFile(); } catch(java.io.IOException ex) { ErrMsgBox emb = new ErrMsgBox("Error "+ex.toString(), progName); return null; } } else { // it might not be a jar file if running within NetBeans return null; } } //getRunningJarFile() //</editor-fold> //</editor-fold> //<editor-fold defaultstate="collapsed" desc="getPathApp"> /** Get the path where an application is located. * @return the directory where the application is located, * or "user.dir" if an error occurs * @version 2014-Jan-17 */ private static class C {private static void C(){}} public static String getPathApp() { C c = new C(); String path; java.net.URI dir; try{ dir = c.getClass(). getProtectionDomain(). getCodeSource(). getLocation(). toURI(); if(dir != null) { String d = dir.toString(); if(d.startsWith("jar:") && d.endsWith("!/")) { d = d.substring(4, d.length()-2); dir = new java.net.URI(d); } path = (new java.io.File(dir.getPath())).getParent(); } else {path = System.getProperty("user.dir");} } catch (java.net.URISyntaxException e) { if(!started) { ErrMsgBox emb = new ErrMsgBox("Error: "+e.toString()+nl+ " trying to get the application's directory.", progName); } path = System.getProperty("user.dir"); } // catch started = true; return path; } //getPathApp() //</editor-fold> }
7,293
Java
.java
ignasi-p/eq-diagr
18
3
0
2018-08-17T08:25:37Z
2023-04-30T09:33:35Z
Statistics.java
/FileExtraction/Java_unseen/ignasi-p_eq-diagr/DataMaintenance/src/dataMaintenance/Statistics.java
package dataMaintenance; import lib.common.MsgExceptn; import lib.common.Util; import lib.database.CheckDatabases; import lib.database.ProgramDataDB; import lib.huvud.Div; import lib.huvud.ProgramConf; import lib.huvud.SortedListModel; /** Find out possible errors in the databases in the list. * <br> * Copyright (C) 2014-2020 I.Puigdomenech. * * 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 * 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/ * * @author Ignasi Puigdomenech */ public class Statistics extends javax.swing.JFrame { private boolean finished = false; private final ProgramDataDB pd; private final ProgramConf pc; private final javax.swing.JFrame parent; /** the output file where statistics and errors are written */ private java.io.Writer w; /** the output file where statistics and errors are written */ java.io.FileOutputStream fos; private final SortedListModel sortedModelCompsFnd = new SortedListModel(); private final SortedListModel sortedModelCompsUnknown = new SortedListModel(); private final SortedListModel sortedModelNameWoutNumber = new SortedListModel(); private final SortedListModel sortedModelNumberWoutName = new SortedListModel(); private final SortedListModel sortedModelChargeError = new SortedListModel(); private final javax.swing.border.Border defBorder; private final javax.swing.border.Border highlightedBorder = javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED, new java.awt.Color(102,102,102), new java.awt.Color(255,255,255), new java.awt.Color(102,102,102), new java.awt.Color(0,0,0)); private java.awt.Dimension windowSize = new java.awt.Dimension(400,280); /** New-line character(s) to substitute "\n" */ private static final String nl = System.getProperty("line.separator"); private static final String SLASH = java.io.File.separator; //<editor-fold defaultstate="collapsed" desc="Constructor"> /** Creates new form Statistics * @param pc0 * @param pd0 * @param parent */ public Statistics( ProgramConf pc0, ProgramDataDB pd0, javax.swing.JFrame parent) { initComponents(); this.parent = parent; setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR)); pc = pc0; pd = pd0; System.out.println(DataMaintenance.LINE+nl+"Starting \"Statistics\""); defBorder = jScrollPaneComps.getBorder(); // get the default list border setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); //--- Close window on ESC key javax.swing.KeyStroke escKeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE,0, false); getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(escKeyStroke,"ESCAPE"); javax.swing.Action escAction = new javax.swing.AbstractAction() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { closeWindow(); }}; getRootPane().getActionMap().put("ESCAPE", escAction); //--- Alt-X eXit javax.swing.KeyStroke altXKeyStroke = javax.swing.KeyStroke.getKeyStroke( java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK, false); getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altXKeyStroke,"ALT_X"); getRootPane().getActionMap().put("ALT_X", escAction); //--- Alt-Q quit javax.swing.KeyStroke altQKeyStroke = javax.swing.KeyStroke.getKeyStroke( java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.ALT_MASK, false); getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altQKeyStroke,"ALT_Q"); getRootPane().getActionMap().put("ALT_Q", escAction); //--- F1 for help javax.swing.KeyStroke f1KeyStroke = javax.swing.KeyStroke.getKeyStroke( java.awt.event.KeyEvent.VK_F1,0, false); getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(f1KeyStroke,"F1"); javax.swing.Action f1Action = new javax.swing.AbstractAction() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { Statistics.this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR)); Thread hlp = new Thread() {@Override public void run(){ String[] a = {"DB_Databases_htm"}; lib.huvud.RunProgr.runProgramInProcess(null,ProgramConf.HELP_JAR,a,false,pc.dbg,pc.pathAPP); try{Thread.sleep(2000);} //show the "wait" cursor for 2 sec catch (InterruptedException e) {} Statistics.this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); }};//new Thread hlp.start(); }}; getRootPane().getActionMap().put("F1", f1Action); //---- Position the window on the screen java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); java.awt.Point frameLocation = new java.awt.Point(-1000,-1000); frameLocation.x = Math.max(0, (screenSize.width - this.getWidth() ) / 2); frameLocation.y = Math.max(0, (screenSize.height - this.getHeight() ) / 2); this.setLocation(frameLocation); //---- Title, menus, etc this.setTitle("Database - Statistics"); setPanelsEnabled(false); //---- Icon String iconName = "images/Sigma.gif"; java.net.URL imgURL = this.getClass().getResource(iconName); if (imgURL != null) {this.setIconImage(new javax.swing.ImageIcon(imgURL).getImage());} else {System.out.println("Error: Could not load image = \""+iconName+"\"");} } //constructor //</editor-fold> public void start() { this.jButtonClose.setEnabled(false); this.setVisible(true); windowSize = this.getSize(); if(pd.msgFrame != null) { pd.msgFrame.setParentFrame(Statistics.this); jCheckBoxDebugFrame.setSelected(pd.msgFrame.isVisible()); } sortedModelCompsFnd.clear(); sortedModelCompsUnknown.clear(); sortedModelNameWoutNumber.clear(); sortedModelNumberWoutName.clear(); sortedModelChargeError.clear(); parent.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); if(!startStatistics()) {closeWindow();} } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanelCheckBox = new javax.swing.JPanel(); jCheckBoxDebugFrame = new javax.swing.JCheckBox(); jButtonClose = new javax.swing.JButton(); jLabelWait = new javax.swing.JLabel(); jLabelComps = new javax.swing.JLabel(); jScrollPaneComps = new javax.swing.JScrollPane(); jListComps = new javax.swing.JList(); jPanelTot = new javax.swing.JPanel(); jLabelTot = new javax.swing.JLabel(); jLabelTotCmplx = new javax.swing.JLabel(); jLabelN = new javax.swing.JLabel(); jLabelTotComps = new javax.swing.JLabel(); jLabelTotCompsFiles = new javax.swing.JLabel(); jLabelNa = new javax.swing.JLabel(); jLabelNaFiles = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(); jPanelErrs = new javax.swing.JPanel(); jLabelErr = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); jLabelNameWoutNumb = new javax.swing.JLabel(); jScrollNameWoutNumb = new javax.swing.JScrollPane(); jListNameWoutNumb = new javax.swing.JList(); jPanel2 = new javax.swing.JPanel(); jLabelNumbWoutName = new javax.swing.JLabel(); jScrollNumbWoutName = new javax.swing.JScrollPane(); jListNumbWoutName = new javax.swing.JList(); jPanel4 = new javax.swing.JPanel(); jLabelChargeError = new javax.swing.JLabel(); jScrollChargeError = new javax.swing.JScrollPane(); jListChargeError = new javax.swing.JList(); jPanel5 = new javax.swing.JPanel(); jLabelCompsUnknown = new javax.swing.JLabel(); jScrollCompsUnk = new javax.swing.JScrollPane(); jListCompsUnk = new javax.swing.JList(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); addComponentListener(new java.awt.event.ComponentAdapter() { public void componentResized(java.awt.event.ComponentEvent evt) { formComponentResized(evt); } }); addWindowFocusListener(new java.awt.event.WindowFocusListener() { public void windowGainedFocus(java.awt.event.WindowEvent evt) { formWindowGainedFocus(evt); } public void windowLostFocus(java.awt.event.WindowEvent evt) { } }); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } }); jCheckBoxDebugFrame.setMnemonic('s'); jCheckBoxDebugFrame.setText("show messages"); jCheckBoxDebugFrame.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxDebugFrameActionPerformed(evt); } }); jButtonClose.setMnemonic('c'); jButtonClose.setText(" Close "); jButtonClose.setAlignmentX(0.5F); jButtonClose.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jButtonClose.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonCloseActionPerformed(evt); } }); jLabelWait.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabelWait.setText("( Please wait ...)"); javax.swing.GroupLayout jPanelCheckBoxLayout = new javax.swing.GroupLayout(jPanelCheckBox); jPanelCheckBox.setLayout(jPanelCheckBoxLayout); jPanelCheckBoxLayout.setHorizontalGroup( jPanelCheckBoxLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelCheckBoxLayout.createSequentialGroup() .addComponent(jButtonClose) .addGap(52, 52, 52) .addComponent(jCheckBoxDebugFrame) .addGap(73, 73, 73) .addComponent(jLabelWait) .addContainerGap(137, Short.MAX_VALUE)) ); jPanelCheckBoxLayout.setVerticalGroup( jPanelCheckBoxLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelCheckBoxLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jCheckBoxDebugFrame) .addComponent(jButtonClose) .addComponent(jLabelWait)) ); jLabelComps.setLabelFor(jListComps); jLabelComps.setText("Components found:"); jListComps.setModel(sortedModelCompsFnd); jListComps.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { jListCompsFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { jListCompsFocusLost(evt); } }); jScrollPaneComps.setViewportView(jListComps); jLabelTot.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabelTot.setText("Totals"); jLabelTotCmplx.setText("Number of reactions ="); jLabelN.setText("0"); jLabelTotComps.setText("Number of components ="); jLabelTotCompsFiles.setText("Nbr comps. in \"element\" files: "); jLabelNa.setText("0"); jLabelNaFiles.setText("0"); javax.swing.GroupLayout jPanelTotLayout = new javax.swing.GroupLayout(jPanelTot); jPanelTot.setLayout(jPanelTotLayout); jPanelTotLayout.setHorizontalGroup( jPanelTotLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelTotLayout.createSequentialGroup() .addGroup(jPanelTotLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabelTot) .addGroup(jPanelTotLayout.createSequentialGroup() .addContainerGap() .addGroup(jPanelTotLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelTotLayout.createSequentialGroup() .addComponent(jLabelTotCmplx) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabelN)) .addGroup(jPanelTotLayout.createSequentialGroup() .addComponent(jLabelTotComps) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabelNa)) .addGroup(jPanelTotLayout.createSequentialGroup() .addComponent(jLabelTotCompsFiles) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabelNaFiles))))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanelTotLayout.setVerticalGroup( jPanelTotLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelTotLayout.createSequentialGroup() .addComponent(jLabelTot) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanelTotLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelTotCmplx) .addComponent(jLabelN)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanelTotLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelTotComps) .addComponent(jLabelNa)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanelTotLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelTotCompsFiles) .addComponent(jLabelNaFiles)) .addContainerGap(31, Short.MAX_VALUE)) ); jPanelErrs.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabelErr.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabelErr.setText("Errors:"); javax.swing.GroupLayout jPanelErrsLayout = new javax.swing.GroupLayout(jPanelErrs); jPanelErrs.setLayout(jPanelErrsLayout); jPanelErrsLayout.setHorizontalGroup( jPanelErrsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelErrsLayout.createSequentialGroup() .addComponent(jLabelErr) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanelErrsLayout.setVerticalGroup( jPanelErrsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelErrsLayout.createSequentialGroup() .addComponent(jLabelErr) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jLabelNameWoutNumb.setLabelFor(jListNameWoutNumb); jLabelNameWoutNumb.setText("<html>Reactions with a<br>component and<br>no stoich.coef.</html>"); jListNameWoutNumb.setBackground(new java.awt.Color(215, 215, 215)); jListNameWoutNumb.setModel(sortedModelNameWoutNumber); jListNameWoutNumb.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { jListNameWoutNumbFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { jListNameWoutNumbFocusLost(evt); } }); jScrollNameWoutNumb.setViewportView(jListNameWoutNumb); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollNameWoutNumb, javax.swing.GroupLayout.DEFAULT_SIZE, 127, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabelNameWoutNumb, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabelNameWoutNumb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollNameWoutNumb, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)) ); jLabelNumbWoutName.setLabelFor(jListNumbWoutName); jLabelNumbWoutName.setText("<html>Reactions with a<br>stoich.coef. and<br>no component</html>"); jListNumbWoutName.setModel(sortedModelNumberWoutName); jListNumbWoutName.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { jListNumbWoutNameFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { jListNumbWoutNameFocusLost(evt); } }); jScrollNumbWoutName.setViewportView(jListNumbWoutName); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollNumbWoutName, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabelNumbWoutName, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 0, 0)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabelNumbWoutName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollNumbWoutName)) ); jLabelChargeError.setLabelFor(jListChargeError); jLabelChargeError.setText("<html>Reactions with<br>charge<br>imbalance</html>"); jListChargeError.setModel(sortedModelChargeError); jListChargeError.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { jListChargeErrorFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { jListChargeErrorFocusLost(evt); } }); jScrollChargeError.setViewportView(jListChargeError); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabelChargeError, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jScrollChargeError, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 0, 0)) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(jLabelChargeError, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollChargeError, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)) ); jLabelCompsUnknown.setText("<html>&nbsp;<br>Unknown<br>components:</html>"); jLabelCompsUnknown.setVerticalAlignment(javax.swing.SwingConstants.TOP); jListCompsUnk.setModel(sortedModelCompsUnknown); jListCompsUnk.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { jListCompsUnkFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { jListCompsUnkFocusLost(evt); } }); jScrollCompsUnk.setViewportView(jListCompsUnk); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabelCompsUnknown, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jScrollCompsUnk, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addGap(0, 0, 0) .addComponent(jLabelCompsUnknown, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollCompsUnk, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jSeparator1) .addContainerGap()) .addComponent(jPanelErrs, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabelComps) .addComponent(jScrollPaneComps, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(jPanelTot, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jPanelCheckBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(0, 0, Short.MAX_VALUE)))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(jPanelCheckBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanelTot, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(jLabelComps) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPaneComps, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanelErrs, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents //<editor-fold defaultstate="collapsed" desc="Events"> private void jButtonCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCloseActionPerformed closeWindow(); }//GEN-LAST:event_jButtonCloseActionPerformed private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing closeWindow(); }//GEN-LAST:event_formWindowClosing private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized if(windowSize != null) { int w = windowSize.width; int h = windowSize.height; if(this.getHeight()<h){this.setSize(this.getWidth(), h);} if(this.getWidth()<w){this.setSize(w,this.getHeight());} } }//GEN-LAST:event_formComponentResized private void jCheckBoxDebugFrameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxDebugFrameActionPerformed if(pd.msgFrame != null) {pd.msgFrame.setVisible(jCheckBoxDebugFrame.isSelected());} }//GEN-LAST:event_jCheckBoxDebugFrameActionPerformed private void jListCompsFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jListCompsFocusGained jScrollPaneComps.setBorder(highlightedBorder); if(sortedModelCompsFnd.getSize()>0) { int i = Math.max(0,jListComps.getSelectedIndex()); jListComps.setSelectedIndex(i); jListComps.ensureIndexIsVisible(i); } }//GEN-LAST:event_jListCompsFocusGained private void jListCompsFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jListCompsFocusLost jScrollPaneComps.setBorder(defBorder); }//GEN-LAST:event_jListCompsFocusLost private void jListNameWoutNumbFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jListNameWoutNumbFocusGained jScrollNameWoutNumb.setBorder(highlightedBorder); if(sortedModelNameWoutNumber.getSize()>0) { int i = Math.max(0,jListNameWoutNumb.getSelectedIndex()); jListNameWoutNumb.setSelectedIndex(i); jListNameWoutNumb.ensureIndexIsVisible(i); } }//GEN-LAST:event_jListNameWoutNumbFocusGained private void jListNameWoutNumbFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jListNameWoutNumbFocusLost jScrollNameWoutNumb.setBorder(defBorder); }//GEN-LAST:event_jListNameWoutNumbFocusLost private void jListNumbWoutNameFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jListNumbWoutNameFocusGained jScrollNumbWoutName.setBorder(highlightedBorder); if(sortedModelNumberWoutName.getSize()>0) { int i = Math.max(0,jListNumbWoutName.getSelectedIndex()); jListNumbWoutName.setSelectedIndex(i); jListNumbWoutName.ensureIndexIsVisible(i); } }//GEN-LAST:event_jListNumbWoutNameFocusGained private void jListNumbWoutNameFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jListNumbWoutNameFocusLost jScrollNumbWoutName.setBorder(defBorder); }//GEN-LAST:event_jListNumbWoutNameFocusLost private void jListChargeErrorFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jListChargeErrorFocusGained jScrollChargeError.setBorder(highlightedBorder); if(sortedModelChargeError.getSize()>0) { int i = Math.max(0,jListChargeError.getSelectedIndex()); jListChargeError.setSelectedIndex(i); jListChargeError.ensureIndexIsVisible(i); } }//GEN-LAST:event_jListChargeErrorFocusGained private void jListChargeErrorFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jListChargeErrorFocusLost jScrollChargeError.setBorder(defBorder); }//GEN-LAST:event_jListChargeErrorFocusLost private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowGainedFocus if(pd.msgFrame != null) {jCheckBoxDebugFrame.setSelected(pd.msgFrame.isVisible());} else {jCheckBoxDebugFrame.setEnabled(false);} }//GEN-LAST:event_formWindowGainedFocus private void jListCompsUnkFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jListCompsUnkFocusGained jScrollCompsUnk.setBorder(highlightedBorder); if(sortedModelCompsUnknown.getSize()>0) { int i = Math.max(0,jListCompsUnk.getSelectedIndex()); jListCompsUnk.setSelectedIndex(i); jListCompsUnk.ensureIndexIsVisible(i); } }//GEN-LAST:event_jListCompsUnkFocusGained private void jListCompsUnkFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jListCompsUnkFocusLost jScrollCompsUnk.setBorder(defBorder); }//GEN-LAST:event_jListCompsUnkFocusLost //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Methods"> private void closeWindow() { finished = true; //return from "waitFor()" this.notify_All(); this.dispose(); } // closeWindow() /** this method will wait for this window to be closed */ public synchronized void waitFor() { while(!finished) { try {wait();} catch (InterruptedException ex) {} } // while } // waitFor() private synchronized void notify_All() { //needed by "waitFor()" notifyAll(); } //<editor-fold defaultstate="collapsed" desc="setPanelsEnabled(enable)"> private void setPanelsEnabled(boolean enable) { jButtonClose.setEnabled(enable); jLabelComps.setEnabled(enable); showJPanelTot(enable); jLabelErr.setEnabled(enable); java.awt.Color clr; if(enable) { clr = new java.awt.Color(0,0,0); } else { clr = new java.awt.Color(153,153,153); } jLabelNameWoutNumb.setForeground(clr); jLabelNumbWoutName.setForeground(clr); jLabelChargeError.setForeground(clr); jLabelCompsUnknown.setForeground(clr); if(enable) { clr = new java.awt.Color(255,255,255); } else { clr = new java.awt.Color(215,215,215); } jListComps.setEnabled(enable); jListComps.setBackground(clr); jListNameWoutNumb.setEnabled(enable); jListNameWoutNumb.setBackground(clr); jListNumbWoutName.setEnabled(enable); jListNumbWoutName.setBackground(clr); jListChargeError.setEnabled(enable); jListChargeError.setBackground(clr); jListCompsUnk.setEnabled(enable); jListCompsUnk.setBackground(clr); if(enable) {jLabelWait.setText(" ");} else {jLabelWait.setText("( Please wait... )");} } private void showJPanelTot(boolean show) { if(show) { jLabelTot.setText("Totals:"); jLabelTotCmplx.setText("Number of reactions ="); jLabelN.setText("0"); jLabelTotComps.setText("Number of components ="); jLabelNa.setText("0"); jLabelTotCompsFiles.setText("Nbr comps. in files: "); jLabelNaFiles.setText("0"); } else { jLabelTot.setText(" "); jLabelTotCmplx.setText(" "); jLabelN.setText(" "); jLabelTotComps.setText(" "); jLabelNa.setText(" "); jLabelTotCompsFiles.setText(" "); jLabelNaFiles.setText(" "); } jListComps.setEnabled(show); jListNameWoutNumb.setEnabled(show); jListNumbWoutName.setEnabled(show); jListChargeError.setEnabled(show); jListCompsUnk.setEnabled(show); } //showJPanelTot(show) //</editor-fold> //<editor-fold defaultstate="collapsed" desc="startStatistics"> /** Performs the "real" work: checks and statistics * * @return false if the procedure ends "unexpectedly": the user selects to quit */ private boolean startStatistics() { System.out.println("---- startStatistics()"+nl+"default path: "+pc.pathDef); // ----- get an output file name String dir = pc.pathDef.toString(); if(dir.endsWith(SLASH)) {dir = dir.substring(0, dir.length()-1);} System.out.println("querying for an output file name..."); final String outFileName = Util.getSaveFileName(this, pc.progName, "Select an output file:", 7, dir + SLASH + "Statistics.txt", null); if(outFileName == null || outFileName.trim().length() <=0) { System.out.println("---- cancelled by the user"); return false; } final java.io.File outFile = new java.io.File(outFileName); pc.setPathDef(outFile); fos = null; w = null; try { fos = new java.io.FileOutputStream(outFile); w = new java.io.BufferedWriter(new java.io.OutputStreamWriter(fos,"UTF8")); } catch (java.io.IOException ex) { String msg = "Error \""+ex.getMessage()+"\","+nl+ " while preparing file:"+nl+" \""+outFileName+"\""; MsgExceptn.exception(msg); javax.swing.JOptionPane.showMessageDialog(this, msg, pc.progName, javax.swing.JOptionPane.ERROR_MESSAGE); try{if(w != null) {w.close();} if(fos != null) {fos.close();}} catch (Exception e) { msg = "Error \""+e.getMessage()+"\","+nl+ " while closing file:"+nl+" \""+outFileName+"\""; MsgExceptn.exception(msg); } return false; } System.out.println("Output file: "+outFileName); this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR)); this.jButtonClose.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); System.out.println("---- start scanning of databases, checking errors, calculating statistics..."); try{ // ----- scan the files java.text.DateFormat dateFormatter = java.text.DateFormat.getDateTimeInstance (java.text.DateFormat.DEFAULT, java.text.DateFormat.DEFAULT, java.util.Locale.getDefault()); java.util.Date today = new java.util.Date(); String dateOut = dateFormatter.format(today); w.write("DataMaintenance (java) - "+dateOut+nl+ "Statistics for LogK databases:"+nl+nl+"Database(s) for reactions:"+nl); java.io.File f; String name; java.text.DateFormat df = java.text.DateFormat.getDateTimeInstance(java.text.DateFormat.DEFAULT, java.text.DateFormat.SHORT); for(int i=0; i < pd.dataBasesList.size(); i++) { name = pd.dataBasesList.get(i).trim(); if(name.length() >0) { f = new java.io.File(name); w.write(" "+f.getAbsolutePath()+" "+df.format(f.lastModified())+nl); } }//for i w.write(nl+"Element-reactant file(s):"+nl); for(int i=0; i < pd.dataBasesList.size(); i++) { name = pd.dataBasesList.get(i).trim(); if(name.length() >0) { f = new java.io.File(Div.getFileNameWithoutExtension(name)+".elt"); if(!f.exists()) {f = new java.io.File(Div.getFileNameWithoutExtension(name)+".elb");} if(f.exists()) {w.write(" "+f.getAbsolutePath()+" "+df.format(f.lastModified())+nl);} } }//for i } catch (Exception ex) { String msg = "Error \""+ex.getMessage()+"\","+nl+ " with file:"+nl+" \""+outFileName+"\""; MsgExceptn.exception(msg); javax.swing.JOptionPane.showMessageDialog(this, msg, pc.progName, javax.swing.JOptionPane.ERROR_MESSAGE); try{if(w != null) {w.close();} if(fos != null) {fos.close();}} catch (Exception e) { msg = "Error \""+e.getMessage()+"\","+nl+ " while closing file:"+nl+" \""+outFileName+"\""; MsgExceptn.exception(msg); } return false; } final CheckDatabases.CheckDataBasesLists lists = new CheckDatabases.CheckDataBasesLists(); new javax.swing.SwingWorker<Void,Void>() { @Override protected Void doInBackground() throws Exception { if(pc.dbg) {System.out.println("---- doInBackground(), dbg = "+pc.dbg);} try{ CheckDatabases.checkDatabases(pc.dbg, Statistics.this, pd.dataBasesList, pd.references, lists); if(finished) { // if the user closed the window System.out.println("---- startStatistics() - doInBackground() - cancelled by the user!"); w.flush(); w.close(); fos.close(); return null; } java.util.ArrayList<String> arrayList; java.util.TreeSet<String> treeSet; w.write(nl+"Total nbr reactions = "+lists.productsReactionsSet.size()+nl); w.write("Total nbr reactants found in reaction databases = "+lists.reactantsSet.size()+nl+ " (nbr reactants in element-reactant files = "+lists.nbrCompsInElementFiles+")"+nl+nl); if(lists.reactantsSet.size()>0) { w.write( "Reactants found in reaction database(s):"+nl+ " Name & Nbr of reactions they participate in"+nl); treeSet = new java.util.TreeSet<String>(lists.reactantsSet.keySet()); int j; for(String t : treeSet) { j = lists.reactantsSet.get(t); if(t.length() <=20) { w.write(String.format(" %-20s %d", t, j)+nl); } else { w.write(String.format(" %s %d", t, j+nl)); } } } // -- if(lists.reactantsUnknown.size() > 0) { w.write(nl+"Error: reactants (components) in the reactions database(s) NOT found"+nl+ " in the element-reactant file(s)."+nl+ " Note that any reaction involving these components"+nl+ " will NOT be found in a database search!"+nl); treeSet = new java.util.TreeSet<String>(lists.reactantsUnknown); for(String t : treeSet) {w.write(" "+t+nl);} } // -- if(lists.reactantsNotUsed.size()>0) { w.write(nl+"Warning: components in the element-reactant file(s)"+nl+ " not used in the reactions database(s):"+nl); treeSet = new java.util.TreeSet<String>(lists.reactantsNotUsed); for(String t : treeSet) {w.write(" "+t+nl);} } // -- if(lists.reactantsCompare.size()>0) { w.write(nl+"Error: names of reactants in the database file(s)"+nl+ " that are equivalent but will be treated as different:"+nl); java.util.Collections.sort(lists.reactantsCompare,String.CASE_INSENSITIVE_ORDER); for(String t : lists.reactantsCompare) {w.write(" "+t+nl);} } if(lists.elementReactantsCompare.size()>0) { w.write(nl+"Error: names of reactants in the element-reactant file(s)"+nl+ " that are equivalent but will be treated as different:"+nl); java.util.Collections.sort(lists.elementReactantsCompare,String.CASE_INSENSITIVE_ORDER); for(String t : lists.elementReactantsCompare) {w.write(" "+t+nl);} } // -- if(lists.reactantWithoutCoef.size() >0) { w.write(nl+"Error: reactions having a reactant with name but without its stoich.coeff:"+nl); treeSet = new java.util.TreeSet<String>(lists.reactantWithoutCoef); for(String t : treeSet) {w.write(" "+t+nl);} } if(lists.coefWithoutReactant.size() >0) { w.write(nl+"Error: reactions having a stoich.coeff with no reactant:"+nl); treeSet = new java.util.TreeSet<String>(lists.coefWithoutReactant); for(String t : treeSet) {w.write(" "+t+nl);} } if(lists.chargeImbalance.size() >0) { w.write(nl+"Error: reactions with charge imbalance:"+nl); treeSet = new java.util.TreeSet<String>(lists.chargeImbalance); for(String t : treeSet) {w.write(" "+t+nl);} } if(lists.duplReactionsSameProdctSet.size() > 0) { w.write(nl+"Warning: reactions found more than once"+nl+ " (with the same product):"+nl); for(String t : lists.duplReactionsSameProdctSet) {w.write(" "+t+nl);} } if(lists.duplReactionsDifProductSet.size() > 0) { w.write(nl+"Warning: reactions found more than once"+nl+ " (with a different product):"+nl); for(String t : lists.duplReactionsDifProductSet) {w.write(" "+t+nl);} } if(lists.duplProductsSet.size() > 0) { w.write(nl+"Warning: reaction products found more than once"+nl+ " (with a different reaction):"+nl); for(String t : lists.duplProductsSet) {w.write(" "+t+nl);} } if(lists.duplSolidsSet.size() > 0) { w.write(nl+"Note: solids found more than once"+nl+ " (with different phase designator)"+nl); for(String t : lists.duplSolidsSet) {w.write(" "+t+nl);} } if(lists.itemsNames.size() >0) { java.util.Collections.sort(lists.itemsNames,String.CASE_INSENSITIVE_ORDER); w.write(nl+"Error? reaction products where the name"+nl+ " does not contain one or more reactant(s):"+nl); for(String t : lists.itemsNames) {w.write(" "+t+nl);} } if(finished) { // if the user closed the window System.out.println("---- startStatistics() - doInBackground() - cancelled by the user!"); w.flush(); w.close(); fos.close(); return null; } // -- References if(pd.references == null) { w.write(nl+"No reference file found."+nl); } else { if(lists.refsNotFnd != null && !lists.refsNotFnd.isEmpty()) { w.write(nl+"Error: citations with no references:"+nl); java.util.Collections.sort(lists.refsNotFnd,String.CASE_INSENSITIVE_ORDER); for(String t : lists.refsNotFnd) {w.write(" "+t+nl);} } if(lists.refsFnd != null && !lists.refsFnd.isEmpty()) { boolean ok; arrayList = new java.util.ArrayList<String>(); for (Object k : pd.references.referenceKeys()) { if(k != null) { ok = false; String t = k.toString().trim(); for(String t2 : lists.refsFnd) { if(t2 != null && t2.equalsIgnoreCase(t)) {ok = true; break;} } if(!ok) {arrayList.add(t);} } } // for Object k if(arrayList.size() >0) { java.util.Collections.sort(arrayList,String.CASE_INSENSITIVE_ORDER); w.write(nl+"Warning: references not used in the database(s):"+nl); for(String t : arrayList) {w.write(" "+t+nl);} } } }// references // -- close w.flush(); w.close(); fos.close(); if(finished) { // if the user closed the window System.out.println("---- startStatistics() - doInBackground() - cancelled by the user!"); return null; } } catch (Exception ex) { String msg = "Error \""+ex.getMessage()+"\","+nl+ " with file:"+nl+" \""+outFileName+"\""; MsgExceptn.exception(msg); javax.swing.JOptionPane.showMessageDialog(Statistics.this, msg, pc.progName, javax.swing.JOptionPane.ERROR_MESSAGE); try{if(w != null) {w.close();} if(fos != null) {fos.close();}} catch (Exception e) { msg = "Error \""+e.getMessage()+"\","+nl+ " while closing file:"+nl+" \""+outFileName+"\""; MsgExceptn.exception(msg); } } if(pc.dbg) {System.out.println("\"doInBackground()\" finished.");} return null; } // doInBackground() @Override protected void done(){ // ---- The end if(finished) { // if the user closed the window System.out.println("---- startStatistics() - doInBackground() - cancelled by the user!"); return; } Statistics.this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); setPanelsEnabled(true); jLabelNaFiles.setText(String.valueOf(lists.nbrCompsInElementFiles)); jLabelN.setText(String.valueOf(lists.productsReactionsSet.size())); for (String r : lists.reactantsSet.keySet()) { sortedModelCompsFnd.add(r); } jLabelNa.setText(String.valueOf(lists.reactantsSet.size())); for (String r : lists.reactantWithoutCoef) { sortedModelNameWoutNumber.add(r); } for (String r : lists.coefWithoutReactant) { sortedModelNumberWoutName.add(r); } for (String r : lists.chargeImbalance) { sortedModelChargeError.add(r); } for (String r : lists.reactantsUnknown) { sortedModelCompsUnknown.add(r); } jButtonClose.setEnabled(true); jButtonClose.requestFocusInWindow(); String msg = "Written file:"+nl+" \""+outFileName+"\""; System.out.println(msg+nl+"\"Statistics\" finished."); javax.swing.JOptionPane.showMessageDialog(Statistics.this,msg, pc.progName,javax.swing.JOptionPane.INFORMATION_MESSAGE); } // done() }.execute(); // SwingWorker return true; // this returns inmediately } //startStatistics //</editor-fold> //</editor-fold> // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButtonClose; private javax.swing.JCheckBox jCheckBoxDebugFrame; private javax.swing.JLabel jLabelChargeError; private javax.swing.JLabel jLabelComps; private javax.swing.JLabel jLabelCompsUnknown; private javax.swing.JLabel jLabelErr; private javax.swing.JLabel jLabelN; private javax.swing.JLabel jLabelNa; private javax.swing.JLabel jLabelNaFiles; private javax.swing.JLabel jLabelNameWoutNumb; private javax.swing.JLabel jLabelNumbWoutName; private javax.swing.JLabel jLabelTot; private javax.swing.JLabel jLabelTotCmplx; private javax.swing.JLabel jLabelTotComps; private javax.swing.JLabel jLabelTotCompsFiles; private javax.swing.JLabel jLabelWait; private javax.swing.JList jListChargeError; private javax.swing.JList jListComps; private javax.swing.JList jListCompsUnk; private javax.swing.JList jListNameWoutNumb; private javax.swing.JList jListNumbWoutName; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanelCheckBox; private javax.swing.JPanel jPanelErrs; private javax.swing.JPanel jPanelTot; private javax.swing.JScrollPane jScrollChargeError; private javax.swing.JScrollPane jScrollCompsUnk; private javax.swing.JScrollPane jScrollNameWoutNumb; private javax.swing.JScrollPane jScrollNumbWoutName; private javax.swing.JScrollPane jScrollPaneComps; private javax.swing.JSeparator jSeparator1; // End of variables declaration//GEN-END:variables }
52,738
Java
.java
ignasi-p/eq-diagr
18
3
0
2018-08-17T08:25:37Z
2023-04-30T09:33:35Z
DataMaintenance.java
/FileExtraction/Java_unseen/ignasi-p_eq-diagr/DataMaintenance/src/dataMaintenance/DataMaintenance.java
package dataMaintenance; import java.io.IOException; import lib.common.MsgExceptn; import lib.common.Util; import lib.database.*; import lib.huvud.Div; import lib.huvud.ProgramConf; import lib.huvud.RedirectedFrame; import lib.huvud.SortedProperties; /** The main frame. * <br> * Copyright (C) 2015-2020 I.Puigdomenech. * * 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 * 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/ * * @author Ignasi Puigdomenech */ public class DataMaintenance extends javax.swing.JFrame { private static final String VERS = "2020-June-11"; /** all instances will use the same redirected frame */ private static RedirectedFrame msgFrame = null; private final ProgramDataDB pd = new ProgramDataDB(); private final ProgramConf pc; private java.awt.Dimension windowSize = new java.awt.Dimension(390,230); // private final javax.swing.DefaultListModel modelFiles = new javax.swing.DefaultListModel(); // java 1.6 private final javax.swing.DefaultListModel<String> modelFiles = new javax.swing.DefaultListModel<>(); private static final String DEF_DataBase = "Reactions.db"; private static java.io.File fileIni; private static final String FileINI_NAME = ".DataMaintenance.ini"; private boolean working = false; /** a counter indicating how many reactions have been read so far */ private long cmplxNbr = 0; private final double F_TXT_CMPLX = 54.15; //=186863/3451 private final double F_BIN_ELEM = 38.64; //=3323/86 private final double F_BIN_CMPLX =123.39; //=425835/3451 /** the length in bytes of the file being read */ private double fLength; /** the complexes and solid products found in the database search */ private final java.util.Set<Complex> dataList = new java.util.TreeSet<Complex>(); private final java.awt.Color frgrnd; private final java.awt.Color bckgrnd; private boolean finished = false; private FrameAddData addData = null; private final javax.swing.border.Border defBorder; private final javax.swing.border.Border highlightedBorder = javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED, java.awt.Color.gray, java.awt.Color.black); // variables used when dealing with command-line args. private boolean doNotExit = false; private boolean dispatchingArgs = false; private String fileCmplxSaveName = null; /** New-line character(s) to substitute "\n" */ private static final String nl = System.getProperty("line.separator"); private static final String SLASH = java.io.File.separator; static final String LINE = "- - - - - - - - - - - - - - - - - - - - - - - - - - -"; //<editor-fold defaultstate="collapsed" desc="Constructor"> /** Creates new form DataMaintenance * @param pc0 */ public DataMaintenance(ProgramConf pc0) { initComponents(); this.pc = pc0; this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR)); frgrnd = jButtonExit.getForeground(); bckgrnd = jButtonExit.getBackground().darker(); setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); //--- Close window on ESC key javax.swing.KeyStroke escKeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE,0, false); getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(escKeyStroke,"ESCAPE"); javax.swing.Action escAction = new javax.swing.AbstractAction() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { closeWindow(); }}; getRootPane().getActionMap().put("ESCAPE", escAction); //--- Alt-Q Quit javax.swing.KeyStroke altQKeyStroke = javax.swing.KeyStroke.getKeyStroke( java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.ALT_MASK, false); getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altQKeyStroke,"ALT_Q"); getRootPane().getActionMap().put("ALT_Q", escAction); //--- Alt-X eXit javax.swing.KeyStroke altXKeyStroke = javax.swing.KeyStroke.getKeyStroke( java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK, false); getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altXKeyStroke,"ALT_X"); getRootPane().getActionMap().put("ALT_X", escAction); //--- Alt-S show debug frame javax.swing.KeyStroke altSKeyStroke = javax.swing.KeyStroke.getKeyStroke( java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.ALT_MASK, false); getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altSKeyStroke,"ALT_S"); javax.swing.Action altSAction = new javax.swing.AbstractAction() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { jCheckBoxDebugFrame.doClick(); }}; getRootPane().getActionMap().put("ALT_S", altSAction); //--- F1 for help javax.swing.KeyStroke f1KeyStroke = javax.swing.KeyStroke.getKeyStroke( java.awt.event.KeyEvent.VK_F1,0, false); getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(f1KeyStroke,"F1"); javax.swing.Action f1Action = new javax.swing.AbstractAction() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { jButtonHelp.doClick(); }}; getRootPane().getActionMap().put("F1", f1Action); //---- forward/backwards arrow keys java.util.Set<java.awt.AWTKeyStroke> keys = getFocusTraversalKeys(java.awt.KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS); java.util.Set<java.awt.AWTKeyStroke> newKeys = new java.util.HashSet<java.awt.AWTKeyStroke>(keys); newKeys.add(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_RIGHT, 0)); setFocusTraversalKeys(java.awt.KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,newKeys); keys = getFocusTraversalKeys(java.awt.KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS); newKeys = new java.util.HashSet<java.awt.AWTKeyStroke>(keys); newKeys.add(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_LEFT, 0)); setFocusTraversalKeys(java.awt.KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,newKeys); defBorder = jScrollPaneDBlist.getBorder(); //---- Position the window on the screen java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); java.awt.Point frameLocation = new java.awt.Point(-1000,-1000); frameLocation.x = Math.max(0, (screenSize.width - this.getWidth() ) / 2); frameLocation.y = Math.max(0, (screenSize.height - this.getHeight() ) / 2); this.setLocation(frameLocation); //---- Icon String iconName = "images/Data.gif"; java.net.URL imgURL = this.getClass().getResource(iconName); java.awt.Image icon; if (imgURL != null) { icon = new javax.swing.ImageIcon(imgURL).getImage(); this.setIconImage(icon); //com.apple.eawt.Application.getApplication().setDockIconImage(new javax.swing.ImageIcon("Football.png").getImage()); if(System.getProperty("os.name").startsWith("Mac OS")) { try { Class<?> c = Class.forName("com.apple.eawt.Application"); //Class params[] = new Class[] {java.awt.Image.class}; java.lang.reflect.Method m = c.getDeclaredMethod("setDockIconImage",new Class[] { java.awt.Image.class }); Object i = c.newInstance(); Object paramsObj[] = new Object[]{icon}; m.invoke(i, paramsObj); } catch (Exception e) {System.out.println("Error: "+e.getMessage());} } } else { System.out.println("Error: Could not load image = \""+iconName+"\""); } //---- Title, menus, etc this.setTitle("Data Maintenance"); jButtonCancel.setEnabled(false); jLabelSession.setText(" "); jLabelVersion.setText("vers. "+VERS); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="start(args)"> /** Performs start-up actions that require an "object" of this class to be * present, for example actions that may display a message dialog box * (because a dialog requires a parent frame). * @param args the command-line arguments */ private void start(final String[] args) { this.setVisible(true); if(msgFrame != null) { pd.msgFrame = msgFrame; pd.msgFrame.setParentFrame(this); if(pd.msgFrame.isVisible()) {jCheckBoxDebugFrame.setSelected(true);} } else { jCheckBoxDebugFrame.setEnabled(false); } // ----- read the list of database files readIni(); for(int i=0; i < pd.dataBasesList.size(); i++) { modelFiles.addElement(pd.dataBasesList.get(i)); } LibDB.getElements(this, pc.dbg, pd.dataBasesList, pd.elemComp); setFrameEnabled(true); windowSize = this.getSize(); pd.references = new References(false); String r; String dir = pc.pathAPP; if(dir != null) { if(dir.endsWith(SLASH)) {dir = dir.substring(0, dir.length()-1);} r = dir + SLASH + "References.txt"; } else {r = "References.txt";} if(!pd.references.readRefsFile(r, pc.dbg)) {pd.references = null;} if(pc.pathAPP != null && pc.pathAPP.trim().length()>0) { pd.pathDatabaseFiles.replace(0,pd.pathDatabaseFiles.length(),pc.pathAPP); } else {pd.pathDatabaseFiles.replace(0,pd.pathDatabaseFiles.length(),".");} System.out.println(LINE); System.out.println("User's home directory: "+System.getProperty("user.home")); System.out.println("User's current working directory: "+System.getProperty("user.dir")); System.out.print("Application path: "); if(pc.pathAPP == null) { System.out.print("\"null\""); } else { if(pc.pathAPP.trim().length()<=0) {System.out.print("\"\"");} else {System.out.print(pc.pathAPP);} } System.out.println(); System.out.println("Default path for database files: "+pd.pathDatabaseFiles.toString()); System.out.print("Add-data path: "); if(pd.pathAddData == null) { System.out.print("\"null\""); } else { if(pd.pathAddData.toString().trim().length()<=0) {System.out.print("\"\"");} else {System.out.print(pd.pathAddData);} } System.out.println(nl+"Default path: "+pc.pathDef.toString()); System.out.println(LINE); //---- deal with command-line arguments if(args != null && args.length >0){ this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR)); Thread dArg = new Thread() {@Override public void run(){ for(String arg : args) { dispatchingArgs = true; dispatchArg(arg); dispatchingArgs = false; } // do not end the program if an error occurred if(msgFrame == null || !msgFrame.isVisible() && !doNotExit) {closeWindow();} }}; //new Thread dArg.start(); } // args != null this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); } //</editor-fold> /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jButtonOpen = new javax.swing.JButton(); jButtonSave = new javax.swing.JButton(); jButtonExit = new javax.swing.JButton(); jButtonHelp = new javax.swing.JButton(); jLabelSession = new javax.swing.JLabel(); jLabelDataBases = new javax.swing.JLabel(); jScrollPaneDBlist = new javax.swing.JScrollPane(); jListDBlist = new javax.swing.JList(); jPanelButtons = new javax.swing.JPanel(); jButtonStatistics = new javax.swing.JButton(); jButtonAddData = new javax.swing.JButton(); jButton2text = new javax.swing.JButton(); jButton2binary = new javax.swing.JButton(); jButtonSingle = new javax.swing.JButton(); jPanelShow = new javax.swing.JPanel(); jCheckBoxDebugFrame = new javax.swing.JCheckBox(); jPanelOutput = new javax.swing.JPanel(); jProgressBar = new javax.swing.JProgressBar(); jButtonCancel = new javax.swing.JButton(); jLabelNbr = new javax.swing.JLabel(); jLabelVersion = new javax.swing.JLabel(); jLabelUnicode = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); addComponentListener(new java.awt.event.ComponentAdapter() { public void componentResized(java.awt.event.ComponentEvent evt) { formComponentResized(evt); } }); addWindowFocusListener(new java.awt.event.WindowFocusListener() { public void windowGainedFocus(java.awt.event.WindowEvent evt) { formWindowGainedFocus(evt); } public void windowLostFocus(java.awt.event.WindowEvent evt) { } }); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } }); jButtonOpen.setMnemonic('o'); jButtonOpen.setText("<html><center>Open<br>session</center></html>"); jButtonOpen.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jButtonOpen.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonOpenActionPerformed(evt); } }); jButtonSave.setMnemonic('v'); jButtonSave.setText("<html><center>Save<br>session</center></html>"); jButtonSave.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jButtonSave.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonSaveActionPerformed(evt); } }); jButtonExit.setMnemonic('e'); jButtonExit.setText(" Exit "); jButtonExit.setAlignmentX(0.5F); jButtonExit.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jButtonExit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonExitActionPerformed(evt); } }); jButtonHelp.setMnemonic('h'); jButtonHelp.setText(" Help "); jButtonHelp.setAlignmentX(0.5F); jButtonHelp.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jButtonHelp.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonHelpActionPerformed(evt); } }); jLabelSession.setText("<html><b>Session:</b> DataBaseMaintenance</html>"); jLabelDataBases.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabelDataBases.setLabelFor(jScrollPaneDBlist); jLabelDataBases.setText("Databases:"); jListDBlist.setModel(modelFiles); jListDBlist.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jListDBlistMouseClicked(evt); } }); jListDBlist.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { jListDBlistFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { jListDBlistFocusLost(evt); } }); jListDBlist.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { jListDBlistKeyTyped(evt); } }); jScrollPaneDBlist.setViewportView(jListDBlist); jButtonStatistics.setMnemonic('c'); jButtonStatistics.setText("<html><center>statistics<br>and<br>Checks</center></html>"); jButtonStatistics.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jButtonStatistics.setMargin(new java.awt.Insets(2, 7, 2, 7)); jButtonStatistics.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonStatisticsActionPerformed(evt); } }); jButtonAddData.setMnemonic('a'); jButtonAddData.setText("<html><center>Add data<br>or edit<br>a text-file</center></html>"); jButtonAddData.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jButtonAddData.setMargin(new java.awt.Insets(2, 7, 2, 7)); jButtonAddData.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonAddDataActionPerformed(evt); } }); jButton2text.setMnemonic('t'); jButton2text.setText("<html><center>convert binary<br>databases<br>to Text</center></html>"); jButton2text.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jButton2text.setMargin(new java.awt.Insets(2, 7, 2, 7)); jButton2text.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2textActionPerformed(evt); } }); jButton2binary.setMnemonic('b'); jButton2binary.setText("<html><center>merge all<br>databases to<br>a single Binary</center></html>"); jButton2binary.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jButton2binary.setMargin(new java.awt.Insets(2, 7, 2, 7)); jButton2binary.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2binaryActionPerformed(evt); } }); jButtonSingle.setText("<html><center>show Data<br>for a single<br>component</center></html>"); jButtonSingle.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jButtonSingle.setMargin(new java.awt.Insets(2, 7, 2, 7)); jButtonSingle.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonSingleActionPerformed(evt); } }); javax.swing.GroupLayout jPanelButtonsLayout = new javax.swing.GroupLayout(jPanelButtons); jPanelButtons.setLayout(jPanelButtonsLayout); jPanelButtonsLayout.setHorizontalGroup( jPanelButtonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelButtonsLayout.createSequentialGroup() .addComponent(jButtonStatistics, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(12, 12, 12) .addComponent(jButtonAddData, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton2text, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton2binary, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButtonSingle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanelButtonsLayout.setVerticalGroup( jPanelButtonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelButtonsLayout.createSequentialGroup() .addGroup(jPanelButtonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton2binary, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton2text, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButtonAddData, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButtonStatistics, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButtonSingle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); jCheckBoxDebugFrame.setMnemonic('s'); jCheckBoxDebugFrame.setText("show messages window"); jCheckBoxDebugFrame.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxDebugFrameActionPerformed(evt); } }); javax.swing.GroupLayout jPanelShowLayout = new javax.swing.GroupLayout(jPanelShow); jPanelShow.setLayout(jPanelShowLayout); jPanelShowLayout.setHorizontalGroup( jPanelShowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelShowLayout.createSequentialGroup() .addContainerGap() .addComponent(jCheckBoxDebugFrame) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanelShowLayout.setVerticalGroup( jPanelShowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jCheckBoxDebugFrame) ); jProgressBar.setForeground(java.awt.Color.blue); jButtonCancel.setMnemonic('c'); jButtonCancel.setText(" Cancel "); jButtonCancel.setAlignmentX(0.5F); jButtonCancel.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jButtonCancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonCancelActionPerformed(evt); } }); jLabelNbr.setText("0000"); javax.swing.GroupLayout jPanelOutputLayout = new javax.swing.GroupLayout(jPanelOutput); jPanelOutput.setLayout(jPanelOutputLayout); jPanelOutputLayout.setHorizontalGroup( jPanelOutputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelOutputLayout.createSequentialGroup() .addComponent(jButtonCancel) .addGap(31, 31, 31) .addComponent(jProgressBar, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabelNbr) .addContainerGap(206, Short.MAX_VALUE)) ); jPanelOutputLayout.setVerticalGroup( jPanelOutputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabelNbr, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButtonCancel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanelOutputLayout.createSequentialGroup() .addGap(6, 6, 6) .addComponent(jProgressBar, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addGap(6, 6, 6)) ); jLabelVersion.setText("vers. 2014-Aug-31"); jLabelUnicode.setText("(Unicode UTF-8)"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanelShow, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanelOutput, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanelButtons, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPaneDBlist) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabelDataBases) .addComponent(jLabelSession, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(jButtonOpen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jButtonSave, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(38, 38, 38) .addComponent(jButtonExit) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButtonHelp))) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jLabelVersion) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabelUnicode) .addGap(0, 0, 0))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButtonOpen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButtonSave, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButtonExit) .addComponent(jButtonHelp)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabelSession, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(7, 7, 7) .addComponent(jLabelDataBases) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPaneDBlist, javax.swing.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanelButtons, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanelShow, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanelOutput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelVersion) .addComponent(jLabelUnicode))) ); pack(); }// </editor-fold>//GEN-END:initComponents //<editor-fold defaultstate="collapsed" desc="Events"> private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized if(windowSize != null) { int w = windowSize.width; int h = windowSize.height; if(this.getHeight()<h){this.setSize(this.getWidth(), h);} if(this.getWidth()<w){this.setSize(w,this.getHeight());} } }//GEN-LAST:event_formComponentResized private void jButtonExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonExitActionPerformed closeWindow(); }//GEN-LAST:event_jButtonExitActionPerformed private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing closeWindow(); }//GEN-LAST:event_formWindowClosing private void jCheckBoxDebugFrameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxDebugFrameActionPerformed if(pd.msgFrame != null) { pd.msgFrame.setVisible(jCheckBoxDebugFrame.isSelected()); pd.msgFrame.setParentFrame(this); } }//GEN-LAST:event_jCheckBoxDebugFrameActionPerformed private void jButton2binaryActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2binaryActionPerformed toBinary(pd.elemComp); }//GEN-LAST:event_jButton2binaryActionPerformed private void jButton2textActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2textActionPerformed toText(); }//GEN-LAST:event_jButton2textActionPerformed private void jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelActionPerformed if(!working) { jButtonCancel.setEnabled(false); } else { Object[] opt = {"Yes, cancel", "Continue"}; int m = javax.swing.JOptionPane.showOptionDialog(this, "Cancel job?"+nl+"Are you sure?"+nl+" ", pc.progName, javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.WARNING_MESSAGE, null, opt, opt[1]); if(m != javax.swing.JOptionPane.YES_OPTION) {return;} working = false; System.err.println("--- Cancelled by the user"+nl+nl+ "--- Close this window to terminate the program ---"); } }//GEN-LAST:event_jButtonCancelActionPerformed private void jListDBlistMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListDBlistMouseClicked //if(evt == null || evt.getClickCount() >=2) { setCursorWait(); DBnamesDialog dbND = new DBnamesDialog(this, true, pc, pd.dataBasesList, pd.pathDatabaseFiles, pd.elemComp); setFrameEnabled(false); dbND.setVisible(true); //this will wait for the modal dialog to close if(!dbND.cancel) { LibDB.checkListOfDataBases(this, pd.dataBasesList, null, true); //---- read the elements/components for the databases LibDB.getElements(this, pc.dbg, pd.dataBasesList, pd.elemComp); //---- modelFiles.clear(); for(int i=0; i < pd.dataBasesList.size(); i++) {modelFiles.addElement(pd.dataBasesList.get(i));} } setFrameEnabled(true); dbND.dispose(); System.out.println("---- pathAddData = "+pd.pathAddData.toString()); //this.setVisible(true); setCursorDef(); this.bringToFront(); //} //if(evt.getClickCount() >=2) }//GEN-LAST:event_jListDBlistMouseClicked private void jListDBlistKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jListDBlistKeyTyped if(evt.getKeyChar() == java.awt.event.KeyEvent.VK_DELETE || evt.getKeyChar() == java.awt.event.KeyEvent.VK_BACK_SPACE) { evt.consume(); jListDBlistMouseClicked(null); return; } char c = Character.toUpperCase(evt.getKeyChar()); if(evt.getKeyChar() != java.awt.event.KeyEvent.VK_ESCAPE && evt.getKeyChar() != java.awt.event.KeyEvent.VK_ENTER && !(evt.isAltDown() && ((c == 'X') || (c == 'S')) ) //isAltDown ) { // if not ESC or Alt-something evt.consume(); // remove the typed key jListDBlistMouseClicked(null); } // if char ok }//GEN-LAST:event_jListDBlistKeyTyped private void jButtonStatisticsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonStatisticsActionPerformed setCursorWait(); this.setVisible(false); new javax.swing.SwingWorker<Void,Void>() { @Override protected Void doInBackground() throws Exception { Statistics s = new Statistics(pc, pd, DataMaintenance.this); s.start(); s.waitFor(); return null; } @Override protected void done(){ bringToFront(); pd.msgFrame.setParentFrame(DataMaintenance.this); setCursorDef(); } }.execute(); }//GEN-LAST:event_jButtonStatisticsActionPerformed private void jListDBlistFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jListDBlistFocusGained if(jListDBlist.isFocusOwner()) {jScrollPaneDBlist.setBorder(highlightedBorder);} if(modelFiles.getSize()>0) { int i = jListDBlist.getSelectedIndex(); if(i>=0) { jListDBlist.ensureIndexIsVisible(i); } else { jListDBlist.setSelectedIndex(0); } } }//GEN-LAST:event_jListDBlistFocusGained private void jListDBlistFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jListDBlistFocusLost jListDBlist.clearSelection(); if(!jListDBlist.isFocusOwner()) {jScrollPaneDBlist.setBorder(defBorder);} }//GEN-LAST:event_jListDBlistFocusLost private void jButtonOpenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOpenActionPerformed String fn = Util.getOpenFileName(this, pc.progName, true, "Open INI-file", 11, null, pc.pathDef.toString()); if(fn == null || fn.length() <=0) {return;} java.io.File f = new java.io.File(fn); try {fn = f.getCanonicalPath();} catch (java.io.IOException ex) {fn = null;} if(fn == null) { try {fn = f.getAbsolutePath();} catch (Exception ex) {fn = f.getPath();}} f = new java.io.File(fn); pc.setPathDef(f); modelFiles.clear(); readIni2(f); for(int i=0; i < pd.dataBasesList.size(); i++) {modelFiles.addElement(pd.dataBasesList.get(i));} setFrameEnabled(true); jLabelSession.setText("<html><b>Session:</b>&nbsp; \""+f.getName()+"\"</html>"); setCursorDef(); }//GEN-LAST:event_jButtonOpenActionPerformed private void jButtonSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSaveActionPerformed String fn = Util.getSaveFileName(this, pc.progName, "Save INI-file", 11, null, pc.pathDef.toString()); if(fn == null || fn.length() <=0) {return;} java.io.File f = new java.io.File(fn); try {fn = f.getCanonicalPath();} catch (java.io.IOException ex) {fn = null;} if(fn == null) { try {fn = f.getAbsolutePath();} catch (Exception ex) {fn = f.getPath();}} f = new java.io.File(fn); pc.setPathDef(f); saveIni(f); jLabelSession.setText("<html><b>Session:</b>&nbsp; \""+f.getName()+"\"</html>"); }//GEN-LAST:event_jButtonSaveActionPerformed private void jButtonAddDataActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAddDataActionPerformed if(addData != null) {MsgExceptn.exception("Programming error: addData != null"); return;} setCursorWait(); jButtonAddData.setEnabled(false); // ---- Going to wait for another frame: Start a thread new javax.swing.SwingWorker<Void,Void>() { @Override protected Void doInBackground() throws Exception { addData = new FrameAddData(pc, pd, DataMaintenance.this); DataMaintenance.this.setVisible(false); addData.start(); addData.waitFor(); return null; } //doInBackground() @Override protected void done(){ addData = null; setFrameEnabled(true); bringToFront(); setCursorDef(); } //done() }.execute(); }//GEN-LAST:event_jButtonAddDataActionPerformed private void jButtonSingleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSingleActionPerformed setCursorWait(); jButtonSingle.setEnabled(false); // ---- Going to wait for another frame: Start a thread new javax.swing.SwingWorker<Void,Void>() { @Override protected Void doInBackground() throws Exception { LibDB.getElements(DataMaintenance.this, pc.dbg, pd.dataBasesList, pd.elemComp); FrameSingleComponent sc = new FrameSingleComponent(DataMaintenance.this, pc, pd); setCursorDef(); DataMaintenance.this.setVisible(false); sc.start(); sc.waitFor(); return null; } @Override protected void done(){ setFrameEnabled(true); bringToFront(); } }.execute(); }//GEN-LAST:event_jButtonSingleActionPerformed private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowGainedFocus if(pd.msgFrame != null) { jCheckBoxDebugFrame.setSelected(pd.msgFrame.isVisible()); } else { jCheckBoxDebugFrame.setEnabled(false); } }//GEN-LAST:event_formWindowGainedFocus private void jButtonHelpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonHelpActionPerformed setCursorWait(); Thread hlp = new Thread() {@Override public void run(){ String[] a = {"DB_Databases_htm"}; lib.huvud.RunProgr.runProgramInProcess(null,ProgramConf.HELP_JAR,a,false,pc.dbg,pc.pathAPP); try{Thread.sleep(2000);} //show the "wait" cursor for 2 sec catch (InterruptedException e) {} setCursorDef(); }};//new Thread hlp.start(); }//GEN-LAST:event_jButtonHelpActionPerformed //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Methods"> private void closeWindow() { if(fileIni != null) {saveIni(fileIni);} finished = true; //return from "waitFor()" this.notify_All(); this.dispose(); System.exit(0); } // closeWindow() /** this method will wait for this window to be closed */ public synchronized void waitFor() { while(!finished) { try {wait();} catch (InterruptedException ex) {} } // while } // waitFor() private synchronized void notify_All() { //needed by "waitFor()" notifyAll(); } //<editor-fold defaultstate="collapsed" desc="bringToFront()"> public void bringToFront() { if(this != null) { java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { setVisible(true); setAlwaysOnTop(true); toFront(); requestFocus(); setAlwaysOnTop(false); } }); } } // bringToFront() // </editor-fold> //<editor-fold defaultstate="collapsed" desc="setFrameEnabled(enable)"> /** Sets buttons enabled - disabled * @param enable */ private void setFrameEnabled(boolean enable) { jButtonExit.setEnabled(enable); jButtonOpen.setEnabled(enable); jButtonAddData.setEnabled(enable); jButtonCancel.setEnabled(!enable); boolean b = enable; if(pd.dataBasesList.size() <=0) {b = false;} jButtonSave.setEnabled(b); jButtonStatistics.setEnabled(b); jButton2binary.setEnabled(b); jButton2text.setEnabled(b); jButtonSingle.setEnabled(b); if(b) { jButtonSave.setForeground(frgrnd); jButtonStatistics.setForeground(frgrnd); jButton2binary.setForeground(frgrnd); jButton2text.setForeground(frgrnd); jButtonSingle.setForeground(frgrnd); } else { jButtonSave.setForeground(bckgrnd); jButtonStatistics.setForeground(bckgrnd); jButton2binary.setForeground(bckgrnd); jButton2text.setForeground(bckgrnd); jButtonSingle.setForeground(bckgrnd); } if(enable) { jButtonOpen.setForeground(frgrnd); jButtonAddData.setForeground(frgrnd); jLabelNbr.setVisible(false); jProgressBar.setVisible(false); jButtonOpen.requestFocusInWindow(); enable2Text(); setCursorDef(); } else { jButtonOpen.setForeground(bckgrnd); jButtonAddData.setForeground(bckgrnd); jButtonCancel.requestFocusInWindow(); setCursorWait(); } } //setFrameEnabled(enable) // </editor-fold> //<editor-fold defaultstate="collapsed" desc="enable2Text"> /** enable jButton2text to convert binary files to text format */ private void enable2Text() { boolean found = false; for(int i = 0; i < pd.dataBasesList.size(); i++) { if(Div.getFileNameExtension(pd.dataBasesList.get(i)).equalsIgnoreCase("db")) { found = true; break; } }//for i if(!found) { jButton2text.setEnabled(false); jButton2text.setForeground(bckgrnd); } else { jButton2text.setEnabled(true); jButton2text.setForeground(frgrnd); } } //enable2Text() // </editor-fold> //<editor-fold defaultstate="collapsed" desc="setCursorWait and setCursorDef"> public void setCursorWait() { this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR)); if(pd.msgFrame != null && pd.msgFrame.isShowing()) {pd.msgFrame.setCursorWait();} } public void setCursorDef() { this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); if(pd.msgFrame != null) {pd.msgFrame.setCursorDef();} } // </editor-fold> //<editor-fold defaultstate="collapsed" desc="readIni - writeINI"> /** Reads program settings saved when the program was previously closed. * Exceptions are reported both to the console (if there is one) and to a dialog.<br> * Reads the ini-file in:<ul> * <li> the Application Path if found there.</ul> * If not found in the application path, or if the file is write-protected, then:<ul> * <li> in %HomeDrive%%HomePath% if found there; if write-protected also * <li> in %Home% if found there; if write-protected also * <li> in the user's home directory (system dependent) if it is found there * otherwise: give a warning and create a new file. Note: except for the * installation directory, the ini-file will be writen in a sub-folder * named "<code>.config\eq-diag</code>". * <p> * This method also saves the ini-file in the application path if * "saveIniFileToApplicationPathOnly" is <code>true</code>. Otherwise, * if an ini-file was read and if it was not write-protected, then program * options are saved in that file on exit. If no ini-file was found, * an ini file is created on the first non-write protected directory of * those listed above. */ private void readIni() { // start by getting the defaults (this is needed because the arrays must be initialised) iniDefaults(); // needed to initialise arrays etc. if(pc.dbg) {System.out.println("--- readIni() --- reading ini-file(s)");} fileIni = null; java.io.File p = null, fileRead = null, fileINInotRO = null; boolean ok, readOk = false; //--- check the application path ---// if(pc.pathAPP == null || pc.pathAPP.trim().length() <=0) { if(pc.saveIniFileToApplicationPathOnly) { String name = "\"null\"" + SLASH + FileINI_NAME; MsgExceptn.exception("Error: can not read ini file"+nl+ " "+name+nl+ " (application path is \"null\")"); return; } } else { //pathApp is defined String dir = pc.pathAPP; if(dir.endsWith(SLASH)) {dir = dir.substring(0, dir.length()-1);} fileIni = new java.io.File(dir + SLASH + FileINI_NAME); p = new java.io.File(dir); if(!p.exists()) { p = null; fileIni = null; if(pc.saveIniFileToApplicationPathOnly) { MsgExceptn.exception("Error: can not read ini file:"+nl+ " "+fileIni.getPath()+nl+ " (application path does not exist)"); return; } } } success: { // --- first read the ini-file from the application path, if possible if(pc.saveIniFileToApplicationPathOnly && fileIni != null) { // If the ini-file must be written to the application path, // then try to read this file, even if the file is write-protected fileINInotRO = fileIni; if(fileIni.exists()) { readOk = readIni2(fileIni); if(readOk) {fileRead = fileIni;} } break success; } else { // not saveIniFileToApplicationPathOnly or fileINI does not exist if(fileIni != null && fileIni.exists()) { readOk = readIni2(fileIni); if(readOk) {fileRead = fileIni;} if(fileIni.canWrite() && fileIni.setWritable(true)) { fileINInotRO = fileIni; if(readOk) {break success;} } } else { //ini-file null or does not exist if(fileIni != null && p != null) { try{ // can we can write to this directory? java.io.File tmp = java.io.File.createTempFile("datbm",".tmp", p); ok = tmp.exists(); if(ok) {tmp.delete();} } catch (java.io.IOException ex) {ok = false;} if(pc.dbg) { String s; if(ok) {s="";} else {s="NOT ";} System.out.println(" can "+s+"write files to path: "+p.getAbsolutePath()); } // file does not exist, but the path is not write-protected if(ok && fileINInotRO == null) {fileINInotRO = fileIni;} } } } // --- an ini-file has not been read in the application path // and saveIniFileToApplicationPathOnly = false. Read the ini-file from // the user's path, if possible java.util.ArrayList<String> dirs = new java.util.ArrayList<String>(5); String homeDrv = System.getenv("HOMEDRIVE"); String homePath = System.getenv("HOMEPATH"); if(homePath != null && homePath.trim().length() >0 && !homePath.startsWith(SLASH)) { homePath = SLASH + homePath; } if(homeDrv != null && homeDrv.trim().length() >0 && homeDrv.endsWith(SLASH)) { homeDrv = homeDrv.substring(0, homeDrv.length()-1); } if((homeDrv != null && homeDrv.trim().length() >0) && (homePath != null && homePath.trim().length() >0)) { p = new java.io.File(homeDrv+homePath); if(p.exists()) {dirs.add(p.getAbsolutePath());} } String home = System.getenv("HOME"); if(home != null && home.trim().length() >0) { p = new java.io.File(home); if(p.exists()) {dirs.add(p.getAbsolutePath());} } home = System.getProperty("user.home"); if(home != null && home.trim().length() >0) { p = new java.io.File(home); if(p.exists()) {dirs.add(p.getAbsolutePath());} } for(String t : dirs) { if(t.endsWith(SLASH)) {t = t.substring(0, t.length()-1);} fileIni = new java.io.File(t+SLASH+".config"+SLASH+"eq-diagr"+SLASH+FileINI_NAME); if(fileIni.exists()) { readOk = readIni2(fileIni); if(readOk) {fileRead = fileIni;} if(fileIni.canWrite() && fileIni.setWritable(true)) { if(fileINInotRO == null) {fileINInotRO = fileIni;} if(readOk) {break success;} } } else { //ini-file does not exist try{ // can we can write to this directory? p = new java.io.File(t); java.io.File tmp = java.io.File.createTempFile("datbm",".tmp", p); ok = tmp.exists(); if(ok) {tmp.delete();} } catch (java.io.IOException ex) {ok = false;} if(pc.dbg) { String s; if(ok) {s="";} else {s="NOT ";} System.out.println(" can "+s+"write files to path: "+t); } // file does not exist, but the path is not write-protected if(ok && fileINInotRO == null) {fileINInotRO = fileIni;} } } // for(dirs) } //--- success? if(pc.dbg) { String s; if(fileINInotRO != null) {s=fileINInotRO.getAbsolutePath();} else {s="\"null\"";} System.out.println(" fileINInotRO = "+s); if(fileRead != null) {s=fileRead.getAbsolutePath();} else {s="\"null\"";} System.out.println(" fileRead = "+s); } if(!readOk) { String msg = "Failed to read any INI-file."+nl+ "Default program settings will be used."; System.out.println("----"+nl+msg+nl+"----"); } if(fileINInotRO != null && fileINInotRO != fileRead) { ok = saveIni(fileINInotRO); if(ok) {fileIni = fileINInotRO;} else {fileIni = null;} } } // readIni() private boolean readIni2(java.io.File f) { System.out.flush(); System.out.println("Reading ini-file: \""+f.getPath()+"\""); java.util.Properties propertiesIni = new java.util.Properties(); java.io.FileInputStream fis = null; java.io.BufferedReader r = null; boolean ok = true; try { fis = new java.io.FileInputStream(f); r = new java.io.BufferedReader(new java.io.InputStreamReader(fis,"UTF8")); propertiesIni.load(r); } //try catch (java.io.FileNotFoundException e) { System.out.println("Warning: file not found: \""+f.getPath()+"\""+nl+ "using default parameter values."); checkIniValues(); ok = false; } //catch FileNotFoundException catch (java.io.IOException e) { MsgExceptn.exception(Util.stack2string(e)); String msg = "Error: \""+e.toString()+"\""+nl+ " while loading INI-file:"+nl+ " \""+f.getPath()+"\""; MsgExceptn.showErrMsg(this, msg, 1); ok = false; } // catch loading-exception finally { try {if(r != null) {r.close();} if(fis != null) {fis.close();}} catch (java.io.IOException e) { String msg = "Error: \""+e.toString()+"\""+nl+ " while closing INI-file:"+nl+ " \""+f.getPath()+"\""; MsgExceptn.showErrMsg(this, msg, 1); } } if(!ok) {return ok;} try { pd.pathAddData.replace(0, pd.pathAddData.length(), propertiesIni.getProperty("pathAddData")); int nbr = pd.dataBasesList.size(); if(nbr > 0) {pd.dataBasesList.clear();} nbr = Integer.parseInt(propertiesIni.getProperty("DataBases_Nbr")); String dbName; for(int i=0; i < nbr; i++) { dbName = propertiesIni.getProperty("DataBase["+String.valueOf(i+1).trim()+"]"); if(dbName != null && dbName.length() >0) {pd.dataBasesList.add(dbName);} } } catch (Exception e) { MsgExceptn.exception(Util.stack2string(e)); String msg = "Error: \""+e.toString()+"\""+nl+ " while reading INI-file:"+nl+ " \""+f.getPath()+"\""+nl+nl+ "Setting default program parameters."; MsgExceptn.showErrMsg(this, msg, 1); ok = false; } try { pc.pathDef.replace(0, pc.pathDef.length(), propertiesIni.getProperty("defaultPath")); } catch (Exception ex) {pc.setPathDef();} if(pc.dbg) {System.out.println("Finished reading ini-file");} System.out.flush(); checkIniValues(); return ok; } // readIni2() private void checkIniValues() { System.out.flush(); System.out.println(LINE+nl+"Checking ini-values."); //-- check Default Path java.io.File f = new java.io.File(pc.pathDef.toString()); if(!f.exists()) { pc.setPathDef(pc.pathAPP); } //-- check pathAddData if(pd.pathAddData.length() >0) { f = new java.io.File(pd.pathAddData.toString()); if(!f.exists()) { if(pd.pathAddData.length() >0) {pd.pathAddData.delete(0, pd.pathAddData.length());} pd.pathAddData.append(pc.pathDef.toString()); } } else { pd.pathAddData.append(pc.pathDef.toString()); } String dir = pc.pathAPP; if(dir != null && dir.endsWith(SLASH)) {dir = dir.substring(0, dir.length()-1);} String msg; String dbName; boolean warn = false; int nbr = pd.dataBasesList.size(); if(nbr <=0) { msg = "There are no databases selected."; warn = true; if(dir != null && dir.trim().length()>0) {dbName = dir + SLASH + DEF_DataBase;} else {dbName = DEF_DataBase;} java.io.File db = new java.io.File(dbName); if(db.exists() && db.canRead()) { msg = null; pd.dataBasesList.add(dbName); } } else { LibDB.checkListOfDataBases(this, pd.dataBasesList, pc.pathAPP, true); nbr = pd.dataBasesList.size(); if(nbr <=0) { // none of the databases exist. msg = "Error: none of the databases in the \"INI\"-file exist."; if(dir != null && dir.trim().length()>0) {dbName = dir + SLASH + DEF_DataBase;} else {dbName = DEF_DataBase;} if(LibDB.isDBnameOK(this, dbName, false)) {pd.dataBasesList.add(dbName);} } else {msg = null;} } // no databases in INI-file if(msg != null) { System.out.println(msg); msg = msg + nl+nl+"Please select databases"+nl+ "by double-clicking on the empty panel!"+nl+" "; int type = javax.swing.JOptionPane.ERROR_MESSAGE; if(warn) {type = javax.swing.JOptionPane.WARNING_MESSAGE;} javax.swing.JOptionPane.showMessageDialog(this, msg, pc.progName, type); } } // checkIniValues() private void iniDefaults() { // Set default values for program variables if (pc.dbg) { System.out.flush(); System.out.println("Setting default parameter values (\"ini\"-values)."); } pc.setPathDef("."); pd.pathAddData.replace(0, pd.pathAddData.length(), System.getProperty("user.home")); pd.pathDatabaseFiles.replace(0, pd.pathDatabaseFiles.length(), pc.pathAPP); pd.dataBasesList.clear(); String dir = pc.pathAPP; if(dir != null && dir.endsWith(SLASH)) {dir = dir.substring(0, dir.length()-1);} String dbName; if(dir != null && dir.trim().length()>0) {dbName = dir + SLASH + DEF_DataBase;} else {dbName = DEF_DataBase;} java.io.File db = new java.io.File(dbName); if(db.exists() && db.canRead()) {pd.dataBasesList.add(dbName);} } // iniDefaults() /** Save program settings. * Exceptions are reported both to the console (if there is one) and to a dialog */ private boolean saveIni(java.io.File f) { if(f == null) {return false;} if(pc.dbg) {System.out.println("--- saveIni("+f.getAbsolutePath()+")");} boolean ok = true; String msg = null; if(f.exists() && (!f.canWrite() || !f.setWritable(true))) { msg = "Error - can not write ini-file:"+nl+ "\""+f.getAbsolutePath()+"\""+nl+ "The file is read-only."; } if(!f.exists() && !f.getParentFile().exists()) { ok = f.getParentFile().mkdirs(); if(!ok) { msg = "Error - can not create directory:"+nl+ "\""+f.getParent()+"\""+nl+ "Can not write ini-file."; } } if(msg != null) { MsgExceptn.showErrMsg(this, msg, 2); return false; } java.util.Properties propertiesIni= new SortedProperties(); propertiesIni.setProperty("<program_version>", VERS); propertiesIni.setProperty("pathAddData", pd.pathAddData.toString()); propertiesIni.setProperty("defaultPath", pc.pathDef.toString()); int nbr = pd.dataBasesList.size(); propertiesIni.setProperty("DataBases_Nbr", String.valueOf(nbr)); for (int i = 0; i < nbr; i++) { propertiesIni.setProperty("DataBase["+String.valueOf(i+1).trim()+"]", pd.dataBasesList.get(i)); } System.out.println("Saving ini-file: \""+f.getPath()+"\""); java.io.FileOutputStream fos = null; java.io.Writer w = null; try { fos = new java.io.FileOutputStream(f); w = new java.io.BufferedWriter(new java.io.OutputStreamWriter(fos,"UTF8")); propertiesIni.store(w,null); if (pc.dbg) {System.out.println("Written: \""+f.getPath()+"\"");} } catch (java.io.IOException e) { msg = "Error: \""+e.toString()+"\""+nl+ " while writing INI-file:"+nl+ " \""+f.getPath()+"\""; MsgExceptn.showErrMsg(this, msg, 1); ok = false; } // catch store-exception finally { try {if(w != null) {w.close();} if(fos != null) {fos.close();}} catch (java.io.IOException e) { msg = e.getMessage()+nl+ " trying to write ini-file: \""+f.getPath()+"\""; if(!this.isVisible()) {this.setVisible(true);} MsgExceptn.showErrMsg(this, msg, 1); } } //finally return ok; } // saveIni() //</editor-fold> //<editor-fold defaultstate="collapsed" desc="toBinary"> /** Combines the information in all databases and stores it in a single binary file * @param eComp array list of String[3] objects<br> * [0] contains the element name (e.g. "C"),<br> * [1] the component formula ("CN-" or "Fe+2"),<br> * [2] the component name ("cyanide" or null), which is not really needed, * but used to help the user * @see lib.database.ProgramDataDB#elemComp */ private void toBinary(final java.util.ArrayList<String[]> eComp) { if(pd == null || pd.dataBasesList == null || pd.dataBasesList.size() <=0) { String msg = "There are NO databases to convert to binary!"+nl+" "; if(dispatchingArgs) {msg = msg +nl+ "Please run the program again"+nl+ "WITHOUT the \"-bin\" command line option,"+nl+ "select some databases, and THEN"+nl+ "run again with the \"-bin\" option."+nl+" ";} MsgExceptn.showErrMsg(this, msg, 1); return; } if(fileCmplxSaveName == null || fileCmplxSaveName.trim().length()<=0) { fileCmplxSaveName = DEF_DataBase; } fileCmplxSaveName = Util.getSaveFileName(this,pc.progName, "Enter an output binary database name", 4, fileCmplxSaveName, pc.pathDef.toString()); if(fileCmplxSaveName == null || fileCmplxSaveName.trim().length() <=0) {return;} pc.setPathDef(fileCmplxSaveName); //Check that the output file is not equal to an input file boolean found = false; for(int i=0; i < pd.dataBasesList.size(); i++) { if(pd.dataBasesList.get(i).equalsIgnoreCase(fileCmplxSaveName)) {found = true; break;} } if(found) { String msg = "? Can not create output file:"+nl+ " \""+fileCmplxSaveName + "\""+nl+ "Because it is given in the input database-list."; MsgExceptn.showErrMsg(this, msg, 1); return; } if(pd.dataBasesList.size() >1) { System.out.println(LINE+nl+"Merging all files into a single binary database . . ."); } else { System.out.println(LINE+nl+"Converting the text file into a binary database . . ."); } //if(pc.dbg) { // System.out.println("- - - eComp.get()[1]:"); // for(int j=0; j < eComp.size(); j++) {System.out.println(eComp.get(j)[1]);} // System.out.println("- - -"); //} setFrameEnabled(false); working = true; // --- display the messages frame if(pd.msgFrame != null) { pd.msgFrame.setVisible(true); jCheckBoxDebugFrame.setSelected(true); } new javax.swing.SwingWorker<Void,Integer>() { @Override protected Void doInBackground() throws Exception { // -------------------------------------- // ---- Elements-Components file ---- // -------------------------------------- //--- read the elements and components from all databases into "eComp" if(!LibDB.getElements(DataMaintenance.this, pc.dbg, pd.dataBasesList, eComp)) {working = false;} if(!working) {return null;} //--- write the elements and components into a single database String fileElemSaveName = Div.getFileNameWithoutExtension(fileCmplxSaveName)+".elb"; java.io.File fileElemSave = new java.io.File(fileElemSaveName); if(fileElemSave.exists()) { Object[] opt = {"Yes", "Cancel"}; int m = javax.swing.JOptionPane.showOptionDialog(DataMaintenance.this, "Note: the elements-components file"+nl+"\""+fileElemSaveName+"\""+nl+" already exists. Overwrite?", pc.progName, javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.WARNING_MESSAGE, null, opt, opt[1]); if(m != javax.swing.JOptionPane.YES_OPTION) { System.out.println("---- Cancelled by the user."); return null; }//if !yes }//if output file exists // --------------------------- // ---- Reactions file ---- // --------------------------- // all datafiles are read and a single binary file generated, // including the reactions in both binary and text files java.io.File fileCmplxSave = new java.io.File(fileCmplxSaveName); System.out.println("--- Reading reactions to write binary file:"+nl+ " \""+fileCmplxSaveName+"\""); // There is not need to ask permission to overwrite an existing file, // it has already been done in "Util.getSaveFileName" Complex complex, oldCmplx; dataList.clear(); java.io.File f; java.io.BufferedReader br; java.io.DataInputStream dis = null; boolean binary, added, removed, found; String msg; int db = 0, nTot; publish(0); jLabelNbr.setText("0"); jLabelNbr.setVisible(true); java.util.ArrayList<Complex> toRemove = new java.util.ArrayList<Complex>(); // ------------------------------------- // --- loop through all databases ---- // ------------------------------------- int converted = 0; while (db < pd.dataBasesList.size()) { if(!working) {return null;} f = new java.io.File(pd.dataBasesList.get(db)); if(!f.exists() || !f.canRead()) { msg = "Error - file \""+pd.dataBasesList.get(db)+"\""+nl; if(f.exists()) {msg = msg.concat(" can not be read.");} else {msg = msg.concat(" does not exist.");} System.err.println(msg); continue; } binary = false; if(Div.getFileNameExtension(pd.dataBasesList.get(db)).equalsIgnoreCase("db")) {binary = true;} publish(0); System.out.println("Reading file \""+f.getName()+"\""); // -- read a txt file if(!binary) { fLength = (double)f.length(); try{br = new java.io.BufferedReader( new java.io.InputStreamReader( new java.io.FileInputStream(f), "UTF8")); } catch (java.io.FileNotFoundException ex) { msg = "Error: "+ex.toString()+nl+"while trying to open file: \""+f.getName()+"\""; System.err.println(msg+nl+"in procedure \"toBinary\"."); javax.swing.JOptionPane.showMessageDialog(null, msg, pc.progName, javax.swing.JOptionPane.ERROR_MESSAGE); return null; } try{ cmplxNbr = 0; loopComplex: while (true) { if(!working) {return null;} try{complex = LibDB.getTxtComplex(br);} catch (LibDB.EndOfFileException ex) {complex = null;} catch (LibDB.ReadTxtCmplxException ex) { msg = "Error: in \"toBinary\", cmplxNbr = "+cmplxNbr+nl+ex.toString(); MsgExceptn.exception(msg); javax.swing.JOptionPane.showMessageDialog(DataMaintenance.this, msg, pc.progName, javax.swing.JOptionPane.ERROR_MESSAGE); return null; } publish((int)(100*(double)cmplxNbr*F_TXT_CMPLX/fLength)); jLabelNbr.setText(String.valueOf(cmplxNbr)); if(complex == null) {break;} // loopComplex // end-of-file, open next database //if name starts with "@": remove any existing complex with this name if(complex.name.startsWith("@")) { complex.name = complex.name.substring(1); System.out.println(" removing any previous occurrences of species: \""+complex.name+"\""); // this is time consuming, but hopefully it is not done many times java.util.Iterator<Complex> datIt = dataList.iterator(); toRemove.clear(); while(datIt.hasNext()) { if(!working) {return null;} //this will go to finally oldCmplx = datIt.next(); if(Util.nameCompare(oldCmplx.name, complex.name)) {toRemove.add(oldCmplx);} } if(!toRemove.isEmpty()) { for(Complex c : toRemove) { System.out.println(" - removing complex \""+c.toString()+"\""); removed = dataList.remove(c); if(!removed) { msg = "Error: in \"toBinary\", can not remove complex:"+nl+" \""+c.toString()+"\""; MsgExceptn.exception(msg); javax.swing.JOptionPane.showMessageDialog(DataMaintenance.this, msg, pc.progName, javax.swing.JOptionPane.ERROR_MESSAGE); } } System.out.println(" - finished searching for: \""+complex.name+"\""); } else { System.out.println(" - no previous occurrences of \""+complex.name+"\" were found."); } } else { //name does not start with "@": add complex... //check if the components are in the list of possible components msg = complex.check(); nTot = Math.min(complex.reactionComp.size(),complex.reactionCoef.size()); for(int i=0; i < nTot; i++) { if(complex.reactionComp.get(i) != null && complex.reactionComp.get(i).length() >0) { found = false; for(int j=0; j < eComp.size(); j++) { if(complex.reactionComp.get(i).equals(eComp.get(j)[1])) {found = true; break;} } //for j if(!found) { String t = "Component \""+complex.reactionComp.get(i)+"\" in complex \""+complex.name+"\""+nl+"not found in the element-files."; if(msg == null || msg.length() <= 0) {msg = t;} else {msg = msg +nl+ t;} }//not found } } // for i if(msg != null) { System.out.println("---- Error: "+msg); Object[] opt = {"OK", "Cancel"}; int answer = javax.swing.JOptionPane.showOptionDialog(DataMaintenance.this, "Error in file \""+f.getName()+"\""+nl+msg, pc.progName, javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.WARNING_MESSAGE, null, opt, opt[1]); if(answer != javax.swing.JOptionPane.YES_OPTION) { return null; //this will go to finally } } //if msg !=null //if the complex already is in the list, replace it. // (this is perhaps time consuming) found = false; toRemove.clear(); java.util.Iterator<Complex> datIt = dataList.iterator(); while(datIt.hasNext()) { if(!working) {return null;} //this will go to finally oldCmplx = datIt.next(); if(Complex.sameNameAndStoichiometry(oldCmplx, complex) || (Util.nameCompare(oldCmplx.name, complex.name) && (!oldCmplx.isRedox() || !complex.isRedox())) ) { toRemove.add(oldCmplx); } } if(!toRemove.isEmpty()) { found = true; for(Complex c : toRemove) { System.out.println(" - removing complex \""+c.toString()+"\""); removed = dataList.remove(c); if(!removed) { msg = "Error: in \"toBinary\", can not remove complex:"+nl+" \""+c.toString()+"\""; MsgExceptn.exception(msg); javax.swing.JOptionPane.showMessageDialog(DataMaintenance.this, msg, pc.progName, javax.swing.JOptionPane.ERROR_MESSAGE); } } } if(found){ System.out.println(" - adding complex \""+complex.toString()+"\""); } added = dataList.add(complex); if(!added) { msg = "Error: in \"toBinary\", can not add complex:"+nl+" \""+complex.toString()+"\""; MsgExceptn.exception(msg); javax.swing.JOptionPane.showMessageDialog(DataMaintenance.this, msg, pc.progName, javax.swing.JOptionPane.ERROR_MESSAGE); } } //starts with "@"? cmplxNbr++; } //while - loopComplex } catch (Exception ex) {System.out.println("An exception occurred."); return null;} converted++; try{br.close();} catch (java.io.IOException ex) {System.err.println("Error "+ex.toString()); return null;} } else { // -- read a binary file fLength = (double)f.length(); try{ dis = new java.io.DataInputStream(new java.io.FileInputStream(f)); cmplxNbr = 0; while (true){ if(!working) {return null;} //this will go to finally publish((int)(100*(double)cmplxNbr*F_BIN_CMPLX/fLength)); javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() { jLabelNbr.setText(String.valueOf(cmplxNbr)); }}); complex = LibDB.getBinComplex(dis); if(complex == null) {break;} //end of file // this is perhaps time consuming for (java.util.Iterator<Complex> datIt = dataList.iterator(); datIt.hasNext(); ) { if(!working) {return null;} //this will go to finally oldCmplx = datIt.next(); if(Util.nameCompare(oldCmplx.name, complex.name)) { System.out.println(" replacing \""+oldCmplx.name+"\" with: \""+complex.name+"\", logK="+Util.formatDbl3(complex.constant)); removed = dataList.remove(complex); if(!removed) { msg = "Error: in \"toBinary\", can not remove complex:"+nl+" \""+complex.toString()+"\""; MsgExceptn.exception(msg); javax.swing.JOptionPane.showMessageDialog(DataMaintenance.this, msg, pc.progName, javax.swing.JOptionPane.ERROR_MESSAGE); } } // names are equivalent added = dataList.add(complex); if(!added) { msg = "Error: in \"toBinary\", can not add complex:"+nl+" \""+complex.toString()+"\""; MsgExceptn.exception(msg); javax.swing.JOptionPane.showMessageDialog(DataMaintenance.this, msg, pc.progName, javax.swing.JOptionPane.ERROR_MESSAGE); } } //for datIt-Iterator cmplxNbr++; }// while(true) loop through the whole file converted++; } catch (Exception ex) { System.err.println("Error: "+ex.getMessage()+nl+"with \""+f.getAbsolutePath()+"\""); return null; } finally { if(dis != null) { try{dis.close();} catch (java.io.IOException ex) {System.err.println("Input-Output error: "+ex.toString()); return null;} } publish(0); } if(!working) {return null;} } // binary? // -- next database db++; } //while - db // --- end database loop // --- save all reactions that have been read from all files (in datIt) // into a single binary file publish(0); System.out.println("Writing file \""+fileCmplxSave.getName()+"\""); boolean fnd; int eCompSize = eComp.size(); // only components (metals or ligands) that are used // will be saved in the elements file boolean[] eCompUsed = new boolean[eCompSize]; for(int i=0; i<eCompSize; i++) {eCompUsed[i] = false;} java.io.FileOutputStream fos = null; java.io.DataOutputStream dos = null; try { // Wrap the FileOutputStream with a DataOutputStream to obtain its writeInt(), etc methods fos = new java.io.FileOutputStream(fileCmplxSave);; dos = new java.io.DataOutputStream(fos); cmplxNbr = 0; System.out.println("total nbr of reactions: "+dataList.size()); double w = (double)dataList.size(); for (java.util.Iterator<Complex> datIt = dataList.iterator(); datIt.hasNext(); ) { if(!working) {return null;} //this will go to finally publish((int)(100*(double)cmplxNbr/w)); jLabelNbr.setText(String.valueOf(cmplxNbr)); complex = datIt.next(); LibDB.writeBinCmplx(dos,complex); dos.flush(); //mark the components that are used as "needed" nTot = Math.min(complex.reactionComp.size(),complex.reactionCoef.size()); loopNDIM: for(int j=0; j < nTot; j++) { if((Math.abs(complex.reactionCoef.get(j)) < 0.0001) || complex.reactionComp.get(j) == null || complex.reactionComp.get(j).length() <=0) {continue;} fnd = false; for(int i = 0; i < eCompSize; i++) { if(eComp.get(i)[1].equals(complex.reactionComp.get(j))) { // only components (metals or ligands) that are used // will be saved in the elements file eCompUsed[i] = true; fnd = true; //no "break": a component (ligand) might be in under several elements } }//for i if(!fnd) {MsgExceptn.exception("--- Component: "+complex.reactionComp.get(j)+" in complex "+complex.name+nl+" not found in the element files.");} }//for j cmplxNbr++; } //for datIt-Iterator } catch (Exception ex) { System.out.println(ex.toString()+nl+ "while writing binary reactions database file:"+nl+" \""+fileCmplxSaveName+"\""); return null; } finally { try{if(dos != null) {dos.close();} if(fos != null) {fos.close();}} catch (java.io.IOException ex) {System.err.println(ex.toString()); return null;} } if(!working) {return null;} // -------------------------------------- // ---- Elements-Components file ---- // -------------------------------------- //--- write the elements and components into a single database publish(0); System.out.println("Writing binary \"elements\"-file:"+nl+" \""+fileElemSaveName+"\""); int n; StringBuilder elemSymbol = new StringBuilder(); dos = null; final int ELEMENTS = LibDB.ELEMENTS; try { fos = new java.io.FileOutputStream(fileElemSave);; dos = new java.io.DataOutputStream(fos); for(int i=0; i < ELEMENTS; i++) { if(!working) {return null;} //a return here will enter "finally" publish((int)(100*(double)i/(double)ELEMENTS)); elemSymbol.replace(0, elemSymbol.length(), LibDB.elementSymb[i]); n=0; for(int j=0; j < eCompSize; j++) { if(!working) {return null;} //this would go to "finally" if(eComp.get(j)[0].equals(elemSymbol.toString()) && eCompUsed[j]) {n++;} }//for j if(n > 0) { dos.writeUTF(elemSymbol.toString()); dos.writeInt(n); for(int j=0; j < eCompSize; j++) { if(!working) {return null;} if(eComp.get(j)[0].equals(elemSymbol.toString()) && eCompUsed[j]) { dos.writeUTF(eComp.get(j)[1]); dos.writeUTF(eComp.get(j)[2]); } }//for j }//if n>0 } //for i //--- For components in the database not belonging to any element: // set all of them into "XX" publish(100); n = 0; for(int j=0; j < eCompSize; j++) { if(!working) {return null;} //if(eComp.get(j)[1].equals("H2O")) {eCompUsed[j] = true;} if(!eCompUsed[j]) { System.out.println(" Component: "+eComp.get(j)[1]+" not used."); continue; } elemSymbol.replace(0, elemSymbol.length(), eComp.get(j)[0]); found = false; for(int i=0; i < ELEMENTS; i++) { if(!working) {return null;} if(LibDB.elementSymb[i].equals(elemSymbol.toString())) { found = true; break; } } //for i if(!found) { System.out.println(" Component: "+eComp.get(j)[1]+" not connected to an element."); n++; } }//for j if(n > 0) { if(!working) {return null;} dos.writeUTF("XX"); dos.writeInt(n); for(int j=0; j < eCompSize; j++) { if(!working) {return null;} if(!eCompUsed[j]) {continue;} //has it been used? elemSymbol.replace(0, elemSymbol.length(), eComp.get(j)[0]); found = false; for(int i=0; i < ELEMENTS; i++) { if(!working) {return null;} if(LibDB.elementSymb[i].equals(elemSymbol.toString())) { found = true; break; } }//for i if(!found) { dos.writeUTF(eComp.get(j)[1]); dos.writeUTF(eComp.get(j)[2]); }//if !found }//for j }//if n>0 } catch (Exception ioe) { System.err.println("Error: "+ioe.toString()+nl+"with \""+fileElemSaveName+"\""); return null; } finally { try{if(dos != null) {dos.close();} if(fos != null) {fos.close();}} catch (java.io.IOException ex) {System.err.println("Error: "+ex.toString()); return null;} } if(converted > 1) {msg = "Finished merging "+converted+" text databases";} else {msg = "Finished converting the text database";} msg = msg+"."+nl+ "The following binary files were created:"+nl+ " \""+fileElemSaveName+"\""+nl+ " \""+fileCmplxSaveName+"\""; System.out.println("----"+nl+msg+nl+"----"); javax.swing.JOptionPane.showMessageDialog(DataMaintenance.this,msg, pc.progName,javax.swing.JOptionPane.INFORMATION_MESSAGE); return null; } //doInBackground() @Override protected void done(){ jProgressBar.setVisible(false); setFrameEnabled(true); working = false; bringToFront(); } //done() @Override protected void process(java.util.List<Integer> chunks) { // Here we receive the values that we publish(). They may come grouped in chunks. final int i = chunks.get(chunks.size()-1); if(!jProgressBar.isVisible()) {jProgressBar.setVisible(true);} jProgressBar.setValue(i); } //process(java.util.List<Integer> chunks) }.execute(); //any statements placed below are executed inmediately } //toBinary() //</editor-fold> //<editor-fold defaultstate="collapsed" desc="toText"> /** * Reads one or several binary files and writes the into a text database. */ private void toText() { boolean found = false; for(int i = 0; i < pd.dataBasesList.size(); i++) { final String db = pd.dataBasesList.get(i); if(Div.getFileNameExtension(db).equalsIgnoreCase("db")) {found = true; break;} }//for i if(!found) { String msg = "No binary (*.db) files selected!"; System.err.println(msg); javax.swing.JOptionPane.showMessageDialog(DataMaintenance.this, msg, pc.progName, javax.swing.JOptionPane.ERROR_MESSAGE); return; } setFrameEnabled(false); working = true; if(pd.msgFrame != null) { pd.msgFrame.setVisible(true); jCheckBoxDebugFrame.setSelected(true); } System.out.println("--- Converting binary database files to text format."); new javax.swing.SwingWorker<Void,Integer>() { @Override protected Void doInBackground() throws Exception { StringBuilder elemSymbol = new StringBuilder(); int n; StringBuilder elemFileNameIn = new StringBuilder(); StringBuilder elemFileNameOut = new StringBuilder(); StringBuilder dbOut = new StringBuilder(); java.io.File fileRead, fileSave; String msg; publish(0); int converted = 0; try { for(int i = 0; i < pd.dataBasesList.size(); i++) { if(!working) {return null;} //a return here will enter "finally" final String db = pd.dataBasesList.get(i); if(Div.getFileNameExtension(db).equalsIgnoreCase("db")) { fileRead = new java.io.File(db); if(!fileRead.exists()) { msg = "File not found:"+nl+"\""+db+"\""+nl; System.err.println(msg); javax.swing.JOptionPane.showMessageDialog(DataMaintenance.this, msg, pc.progName, javax.swing.JOptionPane.ERROR_MESSAGE); continue; } fLength = (double)fileRead.length(); //------------------------------------------- //--- process the element/component file ---- //------------------------------------------- elemFileNameIn.replace(0, elemFileNameIn.length(), Div.getFileNameWithoutExtension(db)); elemFileNameOut.replace(0, elemFileNameOut.length(), elemFileNameIn.toString()); elemFileNameIn.append(".elb"); fileRead = new java.io.File(elemFileNameIn.toString()); if(!fileRead.exists()) { msg = "File not found:"+nl+"\""+elemFileNameIn.toString()+"\""+nl; System.err.println(msg); javax.swing.JOptionPane.showMessageDialog(DataMaintenance.this, msg, pc.progName, javax.swing.JOptionPane.ERROR_MESSAGE); continue; } elemFileNameOut.append(".elt"); fileSave = new java.io.File(elemFileNameOut.toString()); if(fileSave.exists()) { Object[] opt = {"Yes", "Cancel"}; int m = javax.swing.JOptionPane.showOptionDialog(DataMaintenance.this, "Note: the elements-components file"+nl+"\""+elemFileNameOut.toString()+"\""+nl+"already exists. Overwrite?", pc.progName, javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.WARNING_MESSAGE, null, opt, opt[1]); if(m != javax.swing.JOptionPane.YES_OPTION) {continue;} //next database } //if output file exists System.err.println("Converting \""+fileRead.getName()+"\" into \""+fileSave.getName()+"\""); fLength = (double)fileRead.length(); java.io.DataInputStream dis = null; java.io.FileOutputStream fos = null; java.io.Writer w = null; try{ dis = new java.io.DataInputStream(new java.io.FileInputStream(fileRead)); fos = new java.io.FileOutputStream(fileSave); w = new java.io.BufferedWriter(new java.io.OutputStreamWriter(fos,"UTF-8")); cmplxNbr = 0; while (true){ if(!working) {return null;} //this will go to finally publish((int)(100*(double)cmplxNbr*F_BIN_ELEM/fLength)); elemSymbol.replace(0, elemSymbol.length(), dis.readUTF()); //System.out.println(" element="+elemSymbol.toString()); n = dis.readInt(); w.write(String.format("%-2s,%2d ,",elemSymbol.toString(),n)); for(int j = 0; j < n; j++) { w.write(dis.readUTF()+","+dis.readUTF()+","); } w.write(nl); w.flush(); cmplxNbr++; } } //try catch (java.io.EOFException ex) { converted++; System.out.println("Finished; file \""+fileSave.getName()+"\" written."); } catch (java.io.IOException ex) { System.err.println("Error: "+ex.toString()+nl+"with \""+elemFileNameIn.toString()+"\""); } finally { try{ if(dis != null) {dis.close();} if(w != null) {w.close();} if(fos != null) {fos.close();} } catch (java.io.IOException ex) {System.err.println("Input-Output error: "+ex.toString());} publish(0); } if(!working) {return null;} //----------------------------------- //--- process reactions database ---- //----------------------------------- fileRead = new java.io.File(db); dbOut.replace(0, dbOut.length(), Div.getFileNameWithoutExtension(db)); dbOut.append(".txt"); fileSave = new java.io.File(dbOut.toString()); if(fileSave.exists()) { Object[] opt = {"Yes", "Cancel"}; int m = javax.swing.JOptionPane.showOptionDialog(DataMaintenance.this, "Note: the reactions database file"+nl+"\""+dbOut.toString()+"\""+nl+"already exists. Overwrite?", pc.progName, javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.WARNING_MESSAGE, null, opt, opt[1]); if(m != javax.swing.JOptionPane.YES_OPTION) {continue;} //next database } //if output file exists System.err.println("Converting \""+fileRead.getName()+"\" into \""+fileSave.getName()+"\""); fLength = (double)fileRead.length(); dis = null; fos = null; w = null; try{ dis = new java.io.DataInputStream(new java.io.FileInputStream(fileRead)); fos = new java.io.FileOutputStream(fileSave); w = new java.io.BufferedWriter(new java.io.OutputStreamWriter(fos,"UTF-8")); w.write(Complex.FILE_FIRST_LINE+nl); Complex cmplx; cmplxNbr = 0; while (true){ if(!working) {return null;} //this will go to finally publish((int)(100*(double)cmplxNbr*F_BIN_CMPLX/fLength)); cmplx = LibDB.getBinComplex(dis); if(cmplx == null) {break;} //end of file LibDB.writeTxtComplex(w, cmplx); cmplxNbr++; } converted++; System.out.println("Finished; file \""+fileSave.getName()+"\" written."); } //try catch (java.io.IOException ex) { System.err.println("Error: "+ex.toString()+nl+"with \""+elemFileNameIn.toString()+"\""); } finally { try { if(dis != null) {dis.close();} if(w != null) {w.close();} if(fos != null) {fos.close();} } catch (java.io.IOException ex) {System.err.println("Input-Output error: "+ex.toString());} publish(0); } if(!working) {return null;} }//if binary datafile }//for i } //try catch (java.awt.HeadlessException ex) { System.err.println("Error: "+ex.toString()); ex.printStackTrace(); } catch (LibDB.ReadBinCmplxException ex) { System.err.println("Error: "+ex.toString()); ex.printStackTrace(); } catch (LibDB.WriteTxtCmplxException ex) { System.err.println("Error: "+ex.toString()); ex.printStackTrace(); } finally { msg = "---- Converted "+converted+" file"; if(converted > 1) {msg = msg+"s";} System.out.println(msg); } return null; } //doInBackground() @Override protected void done(){ setCursorDef(); jProgressBar.setVisible(false); setFrameEnabled(true); working = false; } //done() @Override protected void process(java.util.List<Integer> chunks) { // Here we receive the values that we publish(). They may come grouped in chunks. final int i = chunks.get(chunks.size()-1); if(!jProgressBar.isVisible()) {jProgressBar.setVisible(true);} jProgressBar.setValue(i); } //process(java.util.List<Integer> chunks) }.execute(); //any statements placed below are executed inmediately } //toText() //</editor-fold> //<editor-fold defaultstate="collapsed" desc="dispatchArg(String)"> /** Execute the command-line arguments (one by one) * @param arg String containing a command-line argument */ public void dispatchArg(String arg) { if(arg == null || arg.length() <=0) {return;} System.out.println("Command-line argument: \""+arg+"\", length = "+arg.length()); //these are handled in "main" if(arg.equals("-dbg") || arg.equals("/dbg")) {doNotExit = true; return;} if(arg.equals("-?") || arg.equals("/?") || arg.equals("?")) { printInstructions(); msgFrame.setVisible(true); doNotExit = true; return;} // ---- starts with "-bin" if(arg.length() >3) { String arg0 = arg.substring(0, 4).toLowerCase(); if((arg.charAt(0) == '-' || arg.charAt(0) == '/') && arg0.substring(1,4).equals("bin")) { if(arg.charAt(4) == '=' || arg.charAt(4) == ':' && arg.length() >5) { setFrameEnabled(false); fileCmplxSaveName = arg.substring(5); if(fileCmplxSaveName.length() > 2 && fileCmplxSaveName.startsWith("\"") && fileCmplxSaveName.endsWith("\"")) { fileCmplxSaveName = fileCmplxSaveName.substring(1, arg.length()-1); } if(fileCmplxSaveName.length()>3 && fileCmplxSaveName.toLowerCase().endsWith(".db")) { java.io.File f = new java.io.File(fileCmplxSaveName); try{fileCmplxSaveName = f.getCanonicalPath();} catch (IOException ex) { try{fileCmplxSaveName = f.getAbsolutePath();} catch (Exception e) {fileCmplxSaveName = f.getPath();} } if(f.exists()) { Object[] opt = {"Yes", "Cancel"}; int m = javax.swing.JOptionPane.showOptionDialog(DataMaintenance.this, "Note: the database"+nl+"\""+fileCmplxSaveName+"\""+nl+" already exists. Overwrite?", pc.progName, javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.WARNING_MESSAGE, null, opt, opt[1]); if(m != javax.swing.JOptionPane.YES_OPTION) {fileCmplxSaveName = null;} } } else { // if it does not end with ".db" fileCmplxSaveName = null; } } // if a file name is given toBinary(pd.elemComp); return; } // if it starts with "-bin" or "/bin" } // if length > 5 String msg = "Error: bad format for"+nl+ " command-line argument: \""+arg+"\""; System.out.println(msg); printInstructions(); msgFrame.setVisible(true); javax.swing.JOptionPane.showMessageDialog(this,msg, pc.progName,javax.swing.JOptionPane.ERROR_MESSAGE); setCursorWait(); Thread hlp = new Thread() {@Override public void run(){ String[] a = {"S_Batch_htm"}; lib.huvud.RunProgr.runProgramInProcess(null,ProgramConf.HELP_JAR,a,false,pc.dbg,pc.pathAPP); try{Thread.sleep(2000);} //show the "wait" cursor for 2 sec catch (InterruptedException e) {} setCursorDef(); }};//new Thread hlp.start(); doNotExit = true; } // dispatchArg(arg) // </editor-fold> //<editor-fold defaultstate="collapsed" desc="printInstructions"> public static void printInstructions() { System.out.flush(); String msg = "Possible commands are:"+nl+ " -dbg (output debugging information to the messages window)"+nl+ " -bin (merge all databases to a single binary file;"+nl+ " the input databases are those from last run of the program,"+nl+ " a list of names is stored in file 'DataMaintenance.ini')"+nl+ " -bin:out-file-name (as for \"-bin\", but the name of the output"+nl+ " database (possibly including a path) is given."+nl+ " Note: out-file-name must end with \".db\")"+nl+ "Enclose file names with double quotes (\"\") it they contain blank space."+nl+ "Example: java -jar DataMaintenance.jar /dbg -bin=\"..\\plt\\db 2.db\""; System.out.println(msg); System.out.flush(); System.err.println(LINE); // show the message window System.err.flush(); } //printInstructions() //</editor-fold> //</editor-fold> //<editor-fold defaultstate="collapsed" desc="main(args)"> /** * @param args the command line arguments */ public static void main(final String[] args) { //---- create a local instance of ProgramConf. // Contains information read from the configuration file. // This variable can not be static because the program might be started // from different locations having different configuration files. final ProgramConf pc = new ProgramConf("DataMaintenance"); pc.saveIniFileToApplicationPathOnly = false; //---- java.text.DateFormat dateFormatter = java.text.DateFormat.getDateTimeInstance (java.text.DateFormat.DEFAULT, java.text.DateFormat.DEFAULT, java.util.Locale.getDefault()); java.util.Date today = new java.util.Date(); String dateOut = dateFormatter.format(today); System.out.println("DataMaintenance started: \""+dateOut+"\""); //---- deal with some command-line arguments boolean dbg = false; if(args.length > 0) { for (String arg : args) { if(arg.equalsIgnoreCase("-dbg") || arg.equalsIgnoreCase("/dbg")) { System.out.println("Command-line argument = \"" + arg + "\""); dbg = true; } if(arg.equals("-?") || arg.equalsIgnoreCase("/?")) { printInstructions(); } } } //---- all output to System.err will show the error in a frame. if(msgFrame == null) {msgFrame = new RedirectedFrame(500, 400, pc);} System.out.println("DataMaintenance started: \""+dateOut+"\""); boolean windows = System.getProperty("os.name").startsWith("Windows"); //---- set Look-And-Feel try{ if(windows) { javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName()); System.out.println("--- setLookAndFeel(System);"); } else { javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getCrossPlatformLookAndFeelClassName()); System.out.println("--- setLookAndFeel(CrossPlatform);"); } } catch (Exception ex) {System.out.println("Error: "+ex.getMessage());} //---- for JOptionPanes set the default button to the one with the focus // so that pressing "enter" behaves as expected: javax.swing.UIManager.put("Button.defaultButtonFollowsFocus", Boolean.TRUE); // and make the arrow keys work: Util.configureOptionPane(); //---- get the Application Path pc.pathAPP = Main.getPathApp(); //---- read the CFG-file of "DataBase" java.io.File fileNameCfg; String dir = pc.pathAPP; if(dir != null && dir.trim().length()>0) { if(dir.endsWith(SLASH)) {dir = dir.substring(0, dir.length()-1);} fileNameCfg = new java.io.File(dir + SLASH + "DataMaintenance.cfg"); } else {fileNameCfg = new java.io.File("DataMaintenance.cfg");} ProgramConf.read_cfgFile(fileNameCfg, pc); if(!pc.dbg) {pc.dbg=dbg;} msgFrame.setVisible(dbg); //---- set Default Path = Start Directory pc.setPathDef("."); //---- show the main window java.awt.EventQueue.invokeLater(new Runnable() {@Override public void run() { DataMaintenance m = new DataMaintenance(pc); //send configuration data m.start(args); } // run }); // invokeLater } //main //</editor-fold> // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton2binary; private javax.swing.JButton jButton2text; private javax.swing.JButton jButtonAddData; private javax.swing.JButton jButtonCancel; private javax.swing.JButton jButtonExit; private javax.swing.JButton jButtonHelp; private javax.swing.JButton jButtonOpen; private javax.swing.JButton jButtonSave; private javax.swing.JButton jButtonSingle; private javax.swing.JButton jButtonStatistics; private javax.swing.JCheckBox jCheckBoxDebugFrame; private javax.swing.JLabel jLabelDataBases; private javax.swing.JLabel jLabelNbr; private javax.swing.JLabel jLabelSession; private javax.swing.JLabel jLabelUnicode; private javax.swing.JLabel jLabelVersion; private javax.swing.JList jListDBlist; private javax.swing.JPanel jPanelButtons; private javax.swing.JPanel jPanelOutput; private javax.swing.JPanel jPanelShow; private javax.swing.JProgressBar jProgressBar; private javax.swing.JScrollPane jScrollPaneDBlist; // End of variables declaration//GEN-END:variables }
105,205
Java
.java
ignasi-p/eq-diagr
18
3
0
2018-08-17T08:25:37Z
2023-04-30T09:33:35Z
DBnamesDialog.java
/FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibDataBase/src/lib/database/DBnamesDialog.java
package lib.database; import lib.common.MsgExceptn; import lib.common.Util; import lib.huvud.ProgramConf; /** Allows the user to choose which databases to use. * <br> * Copyright (C) 2015-2020 I.Puigdomenech. * * 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 * 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/ * * @author Ignasi Puigdomenech */ public class DBnamesDialog extends javax.swing.JDialog { private ProgramConf pc; /** array list of String[3] objects<br> * [0] contains the element name (e.g. "C"),<br> * [1] the component formula ("CN-" or "Fe+2"),<br> * [2] the component name ("cyanide" or null), which is not really needed, * but used to help the user */ private final java.util.ArrayList<String[]> elemComp; /** the database list when the window is created, updated on exit */ private final java.util.ArrayList<String> dbList; /** the database list, local copy */ private final java.util.ArrayList<String> dbListLocal; /** the default path to open database files */ private StringBuffer pathDatabaseFiles; // private final javax.swing.DefaultListModel dBnamesModel = new javax.swing.DefaultListModel(); // java 1.6 private final javax.swing.DefaultListModel<String> dBnamesModel = new javax.swing.DefaultListModel<>(); private java.awt.Dimension windowSize = new java.awt.Dimension(300,200); private final javax.swing.border.Border defBorder; private final javax.swing.border.Border highlightedBorder = javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED, java.awt.Color.gray, java.awt.Color.black); private String dbn; /** New-line character(s) to substitute "\n". */ private static final String nl = System.getProperty("line.separator"); public boolean working = false; public boolean cancel = false; //<editor-fold defaultstate="collapsed" desc="Constructor"> /** Creates new form DBNamesDialog * @param parent * @param modal * @param pc0 * @param dbList0 * @param pathDatabaseFiles0 * @param elemComp0 */ public DBnamesDialog(final java.awt.Frame parent, boolean modal, ProgramConf pc0, java.util.ArrayList<String> dbList0, StringBuffer pathDatabaseFiles0, java.util.ArrayList<String[]> elemComp0) { super(parent, modal); initComponents(); pc = pc0; dbList = dbList0; pathDatabaseFiles = pathDatabaseFiles0; elemComp = elemComp0; if(pathDatabaseFiles == null) {pathDatabaseFiles = new StringBuffer();} if(pathDatabaseFiles.length() > 0) { java.io.File f = new java.io.File(pathDatabaseFiles.toString()); if(f.exists()) { if(f.isFile()) { pathDatabaseFiles.replace(0,pathDatabaseFiles.length(),f.getParent()); } } else { //path does not exist: if(pc.pathAPP != null && pc.pathAPP.trim().length()>0) { pathDatabaseFiles.replace(0,pathDatabaseFiles.length(),pc.pathAPP); } else {pathDatabaseFiles.replace(0,pathDatabaseFiles.length(),".");} } } if(pc.dbg) {System.out.println("---- Select Databases ----");} setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); //--- Close window on ESC key javax.swing.KeyStroke escKeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE,0, false); getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(escKeyStroke,"ESCAPE"); javax.swing.Action escAction = new javax.swing.AbstractAction() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { cancel = true; closeWindow(); }}; getRootPane().getActionMap().put("ESCAPE", escAction); //--- Alt-Q quit javax.swing.KeyStroke altQKeyStroke = javax.swing.KeyStroke.getKeyStroke( java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.ALT_MASK, false); getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altQKeyStroke,"ALT_Q"); getRootPane().getActionMap().put("ALT_Q", escAction); //--- Alt-X eXit javax.swing.KeyStroke altXKeyStroke = javax.swing.KeyStroke.getKeyStroke( java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK, false); getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altXKeyStroke,"ALT_X"); javax.swing.Action altXAction = new javax.swing.AbstractAction() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { jButtonOK.doClick(); }}; getRootPane().getActionMap().put("ALT_X", altXAction); //--- F1 for help javax.swing.KeyStroke f1KeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1,0, false); getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(f1KeyStroke,"F1"); javax.swing.Action f1Action = new javax.swing.AbstractAction() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { if(parent != null) {parent.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));} DBnamesDialog.this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR)); Thread hlp = new Thread() {@Override public void run(){ String[] a = {"DB_Remove_change_data_htm"}; lib.huvud.RunProgr.runProgramInProcess(null,ProgramConf.HELP_JAR,a,false,pc.dbg,pc.pathAPP); try{Thread.sleep(2000);} //show the "wait" cursor for 2 sec catch (InterruptedException e) {} DBnamesDialog.this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); if(parent != null) {parent.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));} }};//new Thread hlp.start(); }}; getRootPane().getActionMap().put("F1", f1Action); //--- Alt-H help javax.swing.KeyStroke altHKeyStroke = javax.swing.KeyStroke.getKeyStroke( java.awt.event.KeyEvent.VK_H, java.awt.event.InputEvent.ALT_MASK, false); getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altHKeyStroke,"ALT_H"); getRootPane().getActionMap().put("ALT_H", f1Action); //---- forward/backwards arrow keys java.util.Set<java.awt.AWTKeyStroke> keys = getFocusTraversalKeys(java.awt.KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS); java.util.Set<java.awt.AWTKeyStroke> newKeys = new java.util.HashSet<java.awt.AWTKeyStroke>(keys); newKeys.add(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_RIGHT, 0)); setFocusTraversalKeys(java.awt.KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,newKeys); keys = getFocusTraversalKeys(java.awt.KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS); newKeys = new java.util.HashSet<java.awt.AWTKeyStroke>(keys); newKeys.add(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_LEFT, 0)); setFocusTraversalKeys(java.awt.KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,newKeys); //---- Title, etc //getContentPane().setBackground(new java.awt.Color(255, 255, 153)); this.setTitle(pc.progName+" - Set Database Names"); defBorder = jScrollPane1.getBorder(); //---- Centre window on parent/screen int left,top; java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); if(parent != null) { left = Math.max(0,(parent.getX() + (parent.getWidth()/2) - this.getWidth()/2)); top = Math.max(0,(parent.getY()+(parent.getHeight()/2)-this.getHeight()/2)); } else { left = Math.max(0,(screenSize.width-this.getWidth())/2); top = Math.max(0,(screenSize.height-this.getHeight())/2); } this.setLocation(Math.min(screenSize.width-this.getWidth()-20,left), Math.min(screenSize.height-this.getHeight()-20, top)); //---- OK-button icon if(parent != null) {jButtonOK.setIcon(new javax.swing.ImageIcon(parent.getIconImage()));} //---- Make a local copy dbListLocal = new java.util.ArrayList<String>(); dbListLocal.addAll(dbList); if(pc.dbg) { if(dbListLocal.size()>0) {System.out.println("---- Database list:"+nl+dbListLocal.toString());} else {System.out.println("---- Database list is empty.");} } //---- updateDBnames(); windowSize = this.getSize(); jButtonRemove.setEnabled(false); if(dBnamesModel.getSize() <=0) {jButtonAdd.requestFocusInWindow();} else {jButtonOK.requestFocusInWindow();} } //</editor-fold> /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel2 = new javax.swing.JPanel(); jLabelNr = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jListDBnames = new javax.swing.JList(); jPanel1 = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); jButtonOK = new javax.swing.JButton(); jButtonCancel = new javax.swing.JButton(); jPanel4 = new javax.swing.JPanel(); jButtonAdd = new javax.swing.JButton(); jButtonRemove = new javax.swing.JButton(); jButtonUp = new javax.swing.JButton(); jButtonDn = new javax.swing.JButton(); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); addComponentListener(new java.awt.event.ComponentAdapter() { public void componentResized(java.awt.event.ComponentEvent evt) { formComponentResized(evt); } }); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } }); jLabelNr.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N jLabelNr.setText("0 Databases"); jListDBnames.setModel(dBnamesModel); jListDBnames.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jListDBnamesMouseClicked(evt); } }); jListDBnames.addListSelectionListener(new javax.swing.event.ListSelectionListener() { public void valueChanged(javax.swing.event.ListSelectionEvent evt) { jListDBnamesValueChanged(evt); } }); jListDBnames.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { jListDBnamesFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { jListDBnamesFocusLost(evt); } }); jListDBnames.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { jListDBnamesKeyTyped(evt); } }); jScrollPane1.setViewportView(jListDBnames); jButtonOK.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jButtonOK.setIcon(new javax.swing.ImageIcon(getClass().getResource("/lib/database/images/Java_32x32.gif"))); // NOI18N jButtonOK.setMnemonic('o'); jButtonOK.setText("OK"); jButtonOK.setToolTipText("exit"); jButtonOK.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jButtonOK.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); jButtonOK.setMargin(new java.awt.Insets(2, 2, 2, 2)); jButtonOK.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); jButtonOK.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonOKActionPerformed(evt); } }); jButtonCancel.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jButtonCancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/lib/database/images/Quit_32x32.gif"))); // NOI18N jButtonCancel.setMnemonic('C'); jButtonCancel.setText("Cancel"); jButtonCancel.setToolTipText("quit"); jButtonCancel.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jButtonCancel.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); jButtonCancel.setMargin(new java.awt.Insets(2, 2, 2, 2)); jButtonCancel.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); jButtonCancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonCancelActionPerformed(evt); } }); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup() .addComponent(jButtonOK, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButtonCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButtonCancel) .addComponent(jButtonOK)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jButtonAdd.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N jButtonAdd.setMnemonic('a'); jButtonAdd.setText("<html><u>A</u>dd another file</html>"); jButtonAdd.setToolTipText("Add a new file to the list"); jButtonAdd.setAlignmentX(0.5F); jButtonAdd.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jButtonAdd.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonAddActionPerformed(evt); } }); jButtonRemove.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N jButtonRemove.setMnemonic('r'); jButtonRemove.setText(" Remove "); jButtonRemove.setToolTipText("Remove the selected file from the list"); jButtonRemove.setAlignmentX(0.5F); jButtonRemove.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jButtonRemove.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonRemoveActionPerformed(evt); } }); jButtonUp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/lib/database/images/ArrowUp.gif"))); // NOI18N jButtonUp.setMnemonic('u'); jButtonUp.setToolTipText("move Up (Alt-U)"); jButtonUp.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jButtonUp.setIconTextGap(0); jButtonUp.setMargin(new java.awt.Insets(0, 2, 0, 2)); jButtonUp.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonUpActionPerformed(evt); } }); jButtonDn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/lib/database/images/ArrowDn.gif"))); // NOI18N jButtonDn.setMnemonic('d'); jButtonDn.setToolTipText("move Down (Alt-D)"); jButtonDn.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jButtonDn.setIconTextGap(0); jButtonDn.setMargin(new java.awt.Insets(0, 2, 0, 2)); jButtonDn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonDnActionPerformed(evt); } }); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addComponent(jButtonAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButtonRemove) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButtonUp, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButtonDn, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(14, 14, 14)) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(jButtonRemove, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jButtonAdd) .addGroup(jPanel4Layout.createSequentialGroup() .addGap(2, 2, 2) .addComponent(jButtonUp, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE) .addComponent(jButtonDn, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(0, 0, 0) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabelNr) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabelNr) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 174, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents //<editor-fold defaultstate="collapsed" desc="Events"> private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing cancel = true; closeWindow(); }//GEN-LAST:event_formWindowClosing private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized if(windowSize != null) { int w = windowSize.width; int h = windowSize.height; if(this.getHeight()<h){this.setSize(this.getWidth(), h);} if(this.getWidth()<w){this.setSize(w,this.getHeight());} } }//GEN-LAST:event_formComponentResized private void jButtonOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOKActionPerformed if(pc.dbg) {System.out.println("---- Exit: New database list:"+nl+dbListLocal.toString()+nl+"----");} dbList.clear(); dbList.addAll(dbListLocal); closeWindow(); }//GEN-LAST:event_jButtonOKActionPerformed private void jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelActionPerformed cancel = true; closeWindow(); }//GEN-LAST:event_jButtonCancelActionPerformed private void jListDBnamesKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jListDBnamesKeyTyped if(evt.getKeyChar() == java.awt.event.KeyEvent.VK_DELETE || evt.getKeyChar() == java.awt.event.KeyEvent.VK_BACK_SPACE) { evt.consume(); jButtonRemoveActionPerformed(null); return; } char c = Character.toUpperCase(evt.getKeyChar()); if(evt.getKeyChar() != java.awt.event.KeyEvent.VK_ESCAPE && evt.getKeyChar() != java.awt.event.KeyEvent.VK_ENTER && !(evt.isAltDown() && ((c == 'X') || (c == 'A') || (c == 'R') || (c == 'U') || (c == 'D') || (c == 'C') || (c == 'O') || (evt.getKeyChar() == java.awt.event.KeyEvent.VK_ENTER)) ) //isAltDown ) { // if not ESC or Alt-something evt.consume(); // remove the typed key dBnames_Click(); } // if char ok }//GEN-LAST:event_jListDBnamesKeyTyped private void jListDBnamesFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jListDBnamesFocusGained if(jListDBnames.isFocusOwner()) { jScrollPane1.setBorder(highlightedBorder); } if(dBnamesModel.getSize()>0) { int i = Math.max(0,jListDBnames.getSelectedIndex()); jListDBnames.setSelectedIndex(i); jListDBnames.ensureIndexIsVisible(i); } }//GEN-LAST:event_jListDBnamesFocusGained private void jListDBnamesValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jListDBnamesValueChanged int i = -1; if(dBnamesModel.getSize()>0) { i = jListDBnames.getSelectedIndex(); } else {jButtonRemove.setEnabled(false);} int n = dBnamesModel.size(); if(i < 0 || i >= n) { jButtonRemove.setEnabled(false); return; } jButtonRemove.setEnabled(true); jButtonUp.setEnabled(i>0); jButtonDn.setEnabled(i < (n-1)); }//GEN-LAST:event_jListDBnamesValueChanged private void jButtonAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAddActionPerformed dBnames_Click(); }//GEN-LAST:event_jButtonAddActionPerformed private void jButtonRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonRemoveActionPerformed dbNameRemove(); }//GEN-LAST:event_jButtonRemoveActionPerformed private void jButtonUpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonUpActionPerformed int i = -1; if(dBnamesModel.getSize()>0) {i = jListDBnames.getSelectedIndex();} if(i < 1 || i >= dBnamesModel.size()) {return;} // move the name one position up synchronized (this) { String dbname = dBnamesModel.get(i).toString(); if(pc.dbg) {System.out.println("---- Moving up: \""+dbname+"\"");} String dbnUp = dBnamesModel.get(i-1).toString(); dbListLocal.set(i, dbnUp); dbListLocal.set(i-1, dbname); } updateDBnames(); jListDBnames.setSelectedIndex(i-1); jListDBnames.ensureIndexIsVisible(i-1); jListDBnames.requestFocusInWindow(); }//GEN-LAST:event_jButtonUpActionPerformed private void jButtonDnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDnActionPerformed int i = -1; if(dBnamesModel.getSize()>0) {i = jListDBnames.getSelectedIndex();} if(i < 0 || i >= (dBnamesModel.size()-1)) {return;} // move the name one position down synchronized (this) { String dbname = dBnamesModel.get(i).toString(); if(pc.dbg) {System.out.println("---- Moving down: \""+dbname+"\"");} String dbnDn = dBnamesModel.get(i+1).toString(); dbListLocal.set(i, dbnDn); dbListLocal.set(i+1, dbname); } updateDBnames(); jListDBnames.setSelectedIndex(i+1); jListDBnames.ensureIndexIsVisible(i+1); jListDBnames.requestFocusInWindow(); }//GEN-LAST:event_jButtonDnActionPerformed private void jListDBnamesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListDBnamesMouseClicked if(evt.getClickCount()>=2) {dBnames_Click();} }//GEN-LAST:event_jListDBnamesMouseClicked private void jListDBnamesFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jListDBnamesFocusLost if(!jListDBnames.isFocusOwner()) {jScrollPane1.setBorder(defBorder);} }//GEN-LAST:event_jListDBnamesFocusLost //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Methods"> private void closeWindow() { if(working) {return;} if(!cancel && dbListLocal.size() <=0) { javax.swing.JOptionPane.showMessageDialog(this, "There are no databases selected?"+nl+ "Please note that the program is useless without databases."+nl+nl, pc.progName, javax.swing.JOptionPane.WARNING_MESSAGE); } if(cancel && pc.dbg) {System.out.println("---- Quit: database list unchanged.");} this.setVisible(false); //this.dispose(); } // closeWindow() //<editor-fold defaultstate="collapsed" desc="bringToFront()"> public void bringToFront() { if(this != null) { java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { setVisible(true); setAlwaysOnTop(true); toFront(); requestFocus(); setAlwaysOnTop(false); } }); } } // bringToFront() //</editor-fold> //<editor-fold defaultstate="collapsed" desc="dBnames_Click"> private void dBnames_Click() { setCursorWait(); if(pc.dbg) {System.out.println(nl+"--- dBnames_Click()");} //--- get a name dbn = getDBFileName(); // if(dbn == null) { setCursorDef(); jListDBnames.requestFocusInWindow(); return; } setCursorWait(); //--- OK? if(!LibDB.isDBnameOK(this, dbn, pc.dbg)) {System.out.println("--- isDBnameOK("+dbn+") = false"); setCursorDef(); return;} final java.io.File dbf = new java.io.File(dbn); try {dbn = dbf.getCanonicalPath();} catch(java.io.IOException ex) { try{dbn = dbf.getAbsolutePath();} catch(Exception ex2) {dbn = dbf.getPath();} } if(pc.dbg) {System.out.println(" database: \""+dbn+"\""); System.out.flush();} //--- element-reactants file final String dbnEle = AddDataElem.getElemFileName(pc.dbg, this, dbn); if(dbnEle == null) { if(pc.dbg){System.out.println("--- Could not get an element file name for file: "+dbn);} setCursorDef(); return; } final java.io.File dbfEle = new java.io.File(dbnEle); final boolean binaryDB = dbn.toLowerCase().endsWith(".db"); if(binaryDB) { if(!dbfEle.exists()) { String msg = "Could not find the \"element\"-file"+nl+ " \""+dbfEle.getName()+"\""+nl+ "for database: \""+dbf.getName()+"\"."+nl+nl+ "The database can NOT be used."; MsgExceptn.showErrMsg(this, msg, 1); setCursorDef(); return; } } else { // not binary database if(!dbfEle.exists()) { String msg = "Could not find the \"element\"-file"+nl+ "for database: \""+dbf.getName()+"\"."+nl+nl+ "The file \""+dbfEle.getName()+"\" will be created."; System.out.println("--- Could not find the \"element\"-file for database: \""+dbf.getName()+"\""); Object[] opt = {"OK", "Cancel"}; int m = javax.swing.JOptionPane.showOptionDialog(this,msg, pc.progName, javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.WARNING_MESSAGE, null, opt, opt[0]); if(m != javax.swing.JOptionPane.YES_OPTION) { if(pc.dbg) {System.out.println("Cancelled by the user");} setCursorDef(); return; } } } // binary database? // --- check the database for errors // ---- Start a thread to wait for the database checks // (for a large database it takes several seconds) buttonsEnable(false); new javax.swing.SwingWorker<Void,Void>() { @Override protected Void doInBackground() throws Exception { if(!binaryDB) { // list of reactants and their chemical elements java.util.ArrayList<String[]> elemCompNewFile = new java.util.ArrayList<String[]>(); if(pc.dbg) {System.out.println("--- Checking that the reactants in \""+dbn+"\" are found in \""+dbnEle+"\"..."); System.out.flush();} // are the reactants in "dbn" not found in "dbnEle"? // if so, are they in "elemComp"? // if new reactants are found the file "dbnEle" is automatically saved try{AddDataElem.elemCompAdd_Update(pc.dbg, DBnamesDialog.this, dbn, dbnEle, elemComp, elemCompNewFile);} catch (AddDataElem.AddDataException ex) { if(!DBnamesDialog.this.isVisible()) {DBnamesDialog.this.setVisible(true);} MsgExceptn.showErrMsg(DBnamesDialog.this, ex.getMessage(), 1); dbn = ""; // flag to indicate failure return null; } } // --- check the database for errors if(pc.dbg) {System.out.println("--- Checking for errors in database \""+dbn+"\""); System.out.flush();} java.util.ArrayList<String> arrayList = new java.util.ArrayList<String>(); arrayList.add(dbn); CheckDatabases.CheckDataBasesLists lists = new CheckDatabases.CheckDataBasesLists(); CheckDatabases.checkDatabases(pc.dbg, DBnamesDialog.this, arrayList, null, lists); String title = pc.progName; boolean ok = CheckDatabases.displayDatabaseErrors(pc.dbg, DBnamesDialog.this, title, dbf.getName(), lists); if(!ok) { System.out.println("--- displayDatabaseErrors: NOT OK for file: "+dbn); dbn = ""; // flag to indicate failure } return null; } // SwingWorker.doInBackground() @Override protected void done(){ //--- failure? if(dbn.isEmpty()) { jButtonCancel.requestFocusInWindow(); buttonsEnable(true); setCursorDef(); return; } //--- add new name to list // check that the name is not already in the list synchronized (DBnamesDialog.this) { int n = dbListLocal.size(); boolean found = false; for(int j=0; j<n; j++) { if(dbListLocal.get(j).equalsIgnoreCase(dbn)) { found = true; break; } } //--- add new name to list if(!found) { if(pc.dbg) {System.out.println("---- Adding database: \""+dbn+"\"");} dbListLocal.add(dbn); } } // synchronized //--- updateDBnames(); jListDBnames.requestFocusInWindow(); for(int i=0; i < dBnamesModel.size(); i++) { if(dBnamesModel.get(i).equals(dbn)) { jListDBnames.setSelectedIndex(i); jListDBnames.ensureIndexIsVisible(i); break; } } buttonsEnable(true); jButtonOK.requestFocusInWindow(); setCursorDef(); } // SwingWorker.done() }.execute(); // this returns inmediately, // but the SwingWorker continues running... } //dBnames_Click private void buttonsEnable(boolean b) { jButtonAdd.setEnabled(b); jButtonRemove.setEnabled(b); jButtonCancel.setEnabled(b); jButtonOK.setEnabled(b); jButtonDn.setEnabled(b); jButtonUp.setEnabled(b); working = !b; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="getDBFileName()"> /** Get a database file name from the user using an Open File dialog. * @return "null" if the user cancels the opertion; a file name otherwise. */ private String getDBFileName() { // Ask the user for a file name using a Open File dialog setCursorWait(); String dbFileName; dbFileName = Util.getOpenFileName(this, pc.progName, true, "Select a database file:", 2, null, pathDatabaseFiles.toString()); if(dbFileName == null || dbFileName.trim().length() <= 0) { // cancelled or error return null; } setCursorWait(); java.io.File dbFile = new java.io.File(dbFileName); if(pathDatabaseFiles.length() >0) {pathDatabaseFiles.delete(0, pathDatabaseFiles.length());} pathDatabaseFiles.append(dbFile.getParent()); return dbFileName; } // getDBFileName() // </editor-fold> //<editor-fold defaultstate="collapsed" desc="dbNameRemove"> private synchronized void dbNameRemove() { int iold = -1; if(dBnamesModel.getSize()>0) {iold = jListDBnames.getSelectedIndex();} if(iold < 0) {return;} String dbn = dBnamesModel.get(iold).toString(); String warning = ""; if(dBnamesModel.getSize() ==1) {warning = "Removing the last database is not a very good idea!"+nl+nl;} warning = warning+"Do you want to remove the database:"+nl+" \""+dbn+"\" ??"; Object[] opt1 = {"OK", "Cancel"}; int m = javax.swing.JOptionPane.showOptionDialog(this, warning, pc.progName, javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.QUESTION_MESSAGE, null, opt1, opt1[1]); if(m == javax.swing.JOptionPane.NO_OPTION) { //the second button is "cancel" jListDBnames.requestFocusInWindow(); if(iold < dBnamesModel.getSize()) { jListDBnames.setSelectedIndex(iold); jListDBnames.ensureIndexIsVisible(iold); } return; } int n = dbListLocal.size(); boolean found = false; // In principle "i" should be the index to remove. Just in case: check // in the array list that the name matches... int k = 0; for(int j=0; j<n; j++) { if(dbListLocal.get(j).equalsIgnoreCase(dbn)) {k = j; found = true; break;} } //--- remove name from list if(found) { if(pc.dbg) {System.out.println("---- Removing database: \""+dbn+"\"");} dbListLocal.remove(k); } //--- updateDBnames(); jListDBnames.requestFocusInWindow(); if(iold >= dBnamesModel.getSize()) {iold = dBnamesModel.getSize()-1;} if(iold < dBnamesModel.getSize() && iold >=0) { jListDBnames.setSelectedIndex(iold); jListDBnames.ensureIndexIsVisible(iold); } } //dBnameRemove //</editor-fold> //<editor-fold defaultstate="collapsed" desc="updateDBnames"> private synchronized void updateDBnames(){ dBnamesModel.clear(); int n = dbListLocal.size(); for(int i = 0; i < n; i++) { dBnamesModel.addElement(dbListLocal.get(i)); } String t; if(n == 1) {t = "1 Database used:";} else {t = String.valueOf(n)+" Databases used:";} jLabelNr.setText(t); if(dBnamesModel.getSize() <=0) { jButtonAdd.setText("<html><u>A</u>dd a file</html>"); } else { jButtonAdd.setText("<html><u>A</u>dd another file</html>"); } jButtonUp.setEnabled(false); jButtonDn.setEnabled(false); } //updateDBnames //</editor-fold> private void setCursorWait() { setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR)); jPanel1.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR)); jListDBnames.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR)); } private void setCursorDef() { setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); jPanel1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); jListDBnames.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); } //</editor-fold> // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButtonAdd; private javax.swing.JButton jButtonCancel; private javax.swing.JButton jButtonDn; private javax.swing.JButton jButtonOK; private javax.swing.JButton jButtonRemove; private javax.swing.JButton jButtonUp; private javax.swing.JLabel jLabelNr; private javax.swing.JList jListDBnames; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JScrollPane jScrollPane1; // End of variables declaration//GEN-END:variables }
41,443
Java
.java
ignasi-p/eq-diagr
18
3
0
2018-08-17T08:25:37Z
2023-04-30T09:33:35Z
CheckDatabases.java
/FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibDataBase/src/lib/database/CheckDatabases.java
package lib.database; import lib.common.MsgExceptn; import lib.common.Util; /** Check for errors in the reactions in a database file. * <br> * Copyright (C) 2017-2020 I.Puigdomenech. * * 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 * 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/ * * @author Ignasi Puigdomenech */ public class CheckDatabases { /** New-line character(s) to substitute "\n" */ private static final String nl = System.getProperty("line.separator"); //<editor-fold defaultstate="collapsed" desc="static nested class CheckDataBasesLists"> /** static nested class to transfer results from checkADatabase * @see CheckDatabases#checkADatabase(boolean, lib.database.ProgramDataDB, java.awt.Component, java.lang.String, lib.database.CheckDatabases.CheckDataBasesLists) checkADatabase */ public static class CheckDataBasesLists { public int nbrCompsInElementFiles; /** a list of all product-reaction combinations: String[]{product,reaction} */ public java.util.HashSet<String []> productsReactionsSet; /** a map of reactants found in the database(s), mapping each reactant * to how many reactions it participates */ public java.util.HashMap<String, Integer> reactantsSet; /** reactants (components) present in the reactions database(s) not found in the * corresponding element-reactants file(s) */ public java.util.HashSet<String> reactantsUnknown; /** Components in the element-reactant file(s) not used in the reactions database(s): */ public java.util.HashSet<String> reactantsNotUsed; /** Reactant names in the reaction database(s) that are equivalent but will be treated as different */ public java.util.ArrayList<String> reactantsCompare; /** Reactant names in the element-reactant files(s) that are equivalent but will be treated as different */ public java.util.ArrayList<String> elementReactantsCompare; /** reactions (product name) where a reactant is given without a coefficient */ public java.util.HashSet<String> reactantWithoutCoef; /** reactions (product name) where a coefficient is given with an empty reactant */ public java.util.HashSet<String> coefWithoutReactant; /** reactions (product name) with charge imbalance */ public java.util.HashSet<String> chargeImbalance; /** reaction products present in two or more different reactions */ public java.util.TreeSet<String> duplProductsSet; /** duplicate reactions (with the same reaction product) */ public java.util.TreeSet<String> duplReactionsSameProdctSet; /** duplicate reactions (with different reaction product) */ public java.util.TreeSet<String> duplReactionsDifProductSet; /** duplicate solids (with different ending: "(s)" and "(cr)") */ public java.util.TreeSet<String> duplSolidsSet; /** reaction product names not containing one or more reactant names, for example Fe+2 + Cl- = ZnCl+ * (in this case "ZnCl+" does not contain "Fe") */ public java.util.ArrayList<String> itemsNames; /** list of reference citations (key) not matching any known reference */ public java.util.ArrayList<String> refsNotFnd; /** list of reference citations (key) that do match a known reference */ public java.util.ArrayList<String> refsFnd; public CheckDataBasesLists() {} } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="checkDataBases"> /** Checks databases, writing statistics and errors in a CheckDataBasesLists object * * @param dbg write debug information? * @param parent as the owner of error messages * @param dataBaseList the list of file names to check * @param refs the references available for the calling program. It may be "null". * @param lists an object where the errors and statistics will be written * @return <code>true</code> if no errors occurr, <code>false</code> otherwise */ public static boolean checkDatabases(final boolean dbg, final java.awt.Component parent, final java.util.ArrayList<String> dataBaseList, final References refs, final CheckDataBasesLists lists) { if(dbg) {System.out.println("---- checkDatabases, debug = true");} if(lists == null) { MsgExceptn.exception("Error in \"checkADatabase\":"+nl+ "parameter \"lists\" (where output arrays would be stored) is null."); return false; } lists.nbrCompsInElementFiles = 0; lists.productsReactionsSet = new java.util.HashSet<String []>(); lists.reactantsSet = new java.util.HashMap<String, Integer>(); lists.reactantsUnknown = new java.util.HashSet<String>(); lists.reactantsNotUsed = new java.util.HashSet<String>(); lists.reactantsCompare = new java.util.ArrayList<String>(); lists.elementReactantsCompare = new java.util.ArrayList<String>(); lists.reactantWithoutCoef = new java.util.HashSet<String>(); lists.coefWithoutReactant = new java.util.HashSet<String>(); lists.chargeImbalance = new java.util.HashSet<String>(); lists.duplProductsSet = new java.util.TreeSet<String>(); lists.duplReactionsSameProdctSet = new java.util.TreeSet<String>(); lists.duplReactionsDifProductSet = new java.util.TreeSet<String>(); lists.duplSolidsSet = new java.util.TreeSet<String>(); lists.itemsNames = new java.util.ArrayList<String>(); lists.refsNotFnd = null; lists.refsFnd = null; if(refs != null) { lists.refsNotFnd = new java.util.ArrayList<String>(); lists.refsFnd = new java.util.ArrayList<String>(); } if(dataBaseList == null) { MsgExceptn.exception("Error in \"checkDatabases\": dataBaseList is null."); return false; } if(dataBaseList.size() <=0) { MsgExceptn.exception("Error in \"checkDatabases\": dataBaseList is empty."); return false; } java.io.File f; for(String dbName : dataBaseList) { if(dbg) {System.out.println(" database name = "+dbName);} f = new java.io.File(dbName); if(!f.exists() || !f.isFile()) { MsgExceptn.msg("Warning in \"checkADatabase\":"+nl+ "file \""+dbName+"\" either does not exist or is not a normal file..."); return false; } if(!f.canRead()) { MsgExceptn.exception("Error in \"checkADatabase\":"+nl+ "can NOT read file \""+dbName+"\"."); return false; } } int i, j; boolean fnd, ok, isRedoxReaction; Complex cmplx; String product, reaction; /** the reference text for each reaction is split into keys and each key * is stored in array "rfs" */ java.util.ArrayList<String> rfs; // -- get and prepare the search engine "LibSearch" final LibSearch libS; try{libS = new LibSearch(dataBaseList);} catch (LibSearch.LibSearchException ex) { MsgExceptn.exception(ex.getMessage()); return false; } // -- read the elements/components found in the database's element file /** array list of String[3] objects<br> * [0] contains the element name (e.g. "C"),<br> * [1] the component formula ("CN-" or "Fe+2"),<br> * [2] the component name ("cyanide" or null), which is not really needed, * but used to help the user */ java.util.ArrayList<String[]> elemsComps = new java.util.ArrayList<String[]>(); LibDB.getElements(parent, dbg, dataBaseList, elemsComps); //the number of unique reactants in elemsComps lists.nbrCompsInElementFiles = elemsComps.size()+1; for(i=0; i < (elemsComps.size()-1); i++) { for(j=(i+1); j < elemsComps.size(); j++) { if(elemsComps.get(i)[1].equals(elemsComps.get(j)[1])) {lists.nbrCompsInElementFiles--;} } } // -- loop through all reactions boolean fistComplex = true; try{ while(true) { try {cmplx = libS.getComplex(fistComplex);} catch (LibSearch.LibSearchException ex) { libS.libSearchClose(); String msg = ex.getMessage(); MsgExceptn.showErrMsg(parent, msg, 1); break; } fistComplex = false; if(cmplx == null) {break;} // last complex if(cmplx.name.startsWith("@")) {product = cmplx.name.substring(1);} else {product = cmplx.name;} reaction = cmplx.sortedReactionString(); // if it starts with "@" the reaction is "" (empty) isRedoxReaction = cmplx.isRedox(); for(String[] r : lists.productsReactionsSet) { // -- find out duplicate reaction products having different reactions if(Util.nameCompare(product, r[0])) { if(!isRedoxReaction && !(r[1].length() > 0 && Util.stringsEqual(r[1], reaction))) { lists.duplProductsSet.add(product); } } // (empty reaction products are not compared) if(r[1].length() > 0 && Util.stringsEqual(r[1], reaction)) { // -- find out duplicate reactions (with the same reaction product) if(Util.nameCompare(product, r[0])) {lists.duplReactionsSameProdctSet.add(product);} // -- find out duplicate reactions (with different reaction product) // Names that will not give a warning, for example: // - Fe(OH)2(s) and Fe(OH)2(cr) and Fe(OH)2 // - CO2 and CO2(g) // but Fe(c) and Fe(cr) will give a warning if(// both are solid but not equal, e.g. AmCO3OH(s) and AmOHCO3(cr) (Util.isSolid(product) && Util.isSolid(r[0]) && !Util.bareNameOf(product).equals(Util.bareNameOf(r[0]))) // both are solid and equal except for "(c)" and "(cr)" || (Util.is_cr_or_c_solid(product) && Util.is_cr_or_c_solid(r[0]) && Util.bareNameOf(product).equals(Util.bareNameOf(r[0]))) // both gas but different, e.g. H2S(g) and SH2(g) || (Util.isGas(product) && Util.isGas(r[0]) && !Util.bareNameOf(product).equals(Util.bareNameOf(r[0]))) // none is solid or gas, but different, such as VO2(OH)2- and VO3- || (!Util.isSolid(product) && !Util.isSolid(r[0]) && !Util.isGas(product) && !Util.isGas(r[0]) && !Util.nameCompare(product, r[0]))) { lists.duplReactionsDifProductSet.add(product+" and: "+r[0]); } // -- find out duplicate solids (with different phase designation) if(!product.equals(r[0]) && Util.isSolid(product) && Util.isSolid(r[0]) && Util.bareNameOf(product).equals(Util.bareNameOf(r[0]))) { if(product.endsWith("(am)")) { lists.duplSolidsSet.add(r[0]+" and: "+product); } else { lists.duplSolidsSet.add(product+" and: "+r[0]); } } } } // -- keep a list of all products/reactions lists.productsReactionsSet.add(new String[]{product,reaction}); // -- if(cmplx.name.startsWith("@")) {continue;} // -- list all reactions with a reactant with no coefficients int nTot = Math.min(cmplx.reactionComp.size(),cmplx.reactionCoef.size()); for(i=0; i < nTot; i++) { if(cmplx.reactionComp.get(i) != null && cmplx.reactionComp.get(i).trim().length()>0) { if(Math.abs(cmplx.reactionCoef.get(i)) < 0.0001) { lists.reactantWithoutCoef.add(cmplx.name); break; } } } // -- find reactions with a coefficnet with no reactant name for(i=0; i < nTot; i++) { if(Math.abs(cmplx.reactionCoef.get(i)) >= 0.0001 && (cmplx.reactionComp.get(i) == null || cmplx.reactionComp.get(i).trim().length() <=0)) { lists.coefWithoutReactant.add(cmplx.name); break; } } // -- find reactions not charge balanced if(!cmplx.isChargeBalanced()) {lists.chargeImbalance.add(cmplx.name);} // -- list reactants for(i =0; i < nTot; i++) { if(cmplx.reactionComp.get(i) == null || cmplx.reactionComp.get(i).trim().length() <=0) {continue;} if(lists.reactantsSet.containsKey(cmplx.reactionComp.get(i))) { j = lists.reactantsSet.get(cmplx.reactionComp.get(i)); lists.reactantsSet.put(cmplx.reactionComp.get(i),j+1); } else { lists.reactantsSet.put(cmplx.reactionComp.get(i),1); } } // -- find out if the reactants are in the name of the product //<editor-fold defaultstate="collapsed" desc="is reactant in product name?"> for(i =0; i < nTot; i++) { String t = cmplx.reactionComp.get(i); if(t == null || t.length() <=0) {continue;} if(Util.isElectron(t) || Util.isProton(t) || Util.isWater(t)) {continue;} t = Util.bareNameOf(t); ok = cmplx.name.contains(t); if(!ok && (t.equals("Sn(OH)2")|| t.equals("Sn(OH)6")|| t.equals("Sn(OH)5"))) {ok = cmplx.name.contains("Sn");} if(!ok && t.equals("Tl(OH)3")) {ok = cmplx.name.contains("Tl");} if(!ok && (t.equals("Hg2")|| t.equals("Hg(OH)2"))) {ok = cmplx.name.contains("Hg");} if(!ok && t.equals("CH3Hg")) {ok = (cmplx.name.contains("Hg") && cmplx.name.contains("CH"));} if(!ok && (t.equals("NH3") || t.equals("NH4") || t.equals("N3"))) {ok = cmplx.name.contains("N");} if(!ok && (t.equals("NO2") || t.equals("NO3") || t.equals("N2"))) {ok = cmplx.name.contains("N");} if(!ok && (t.equals("CO3") || t.equals("HCO3")|| t.equals("HCOO") || t.equals("CH4")|| t.equals("C2H4")|| t.equals("C2H6"))) {ok = cmplx.name.contains("C");} if(!ok && (t.equals("MoO4") || t.equals("Mo2O2") || t.equals("Mo2O4") || t.equals("Mo2(OH)2"))) {ok = cmplx.name.contains("Mo");} if(!ok && t.equals("MnO4")) {ok = cmplx.name.contains("Mn");} if(!ok && t.equals("WO4")) {ok = cmplx.name.contains("W");} if(!ok && (t.equals("CrO4")|| t.equals("Cr(OH)2"))) {ok = cmplx.name.contains("Cr");} if(!ok && t.equals("VO2")) {ok = cmplx.name.contains("V");} if(!ok && t.equals("UO2")) {ok = cmplx.name.contains("U");} if(!ok && t.equals("AmO2")) {ok = cmplx.name.contains("Am");} if(!ok && t.equals("NpO2")) {ok = cmplx.name.contains("Np");} if(!ok && t.equals("PuO2")) {ok = cmplx.name.contains("Pu");} if(!ok && (t.equals("As(OH)3")|| t.equals("AsO4")|| t.equals("H3AsO4")|| t.equals("H3(AsO3)") || t.equals("H3AsO3")|| t.equals ("H2AsO3")|| t.equals ("H2AsO4"))) {ok = cmplx.name.contains("As");} if(!ok && (t.equals("Sb(OH)3")|| t.equals("Sb(OH)6")|| t.equals("Sb(OH)5"))) {ok = cmplx.name.contains("Sb");} if(!ok && (t.equals("Ge(OH)4")|| t.equals("Ge(OH)2"))) {ok = cmplx.name.contains("Ge");} if(!ok && (t.equals("Te(OH)4")|| t.equals("Te(OH)6")|| t.equals("HTe"))) {ok = cmplx.name.contains("Te");} if(!ok && (t.contains("TeO3") || t.contains("TeO4") || t.contains("TeO6"))) {ok = cmplx.name.contains("Te");} if(!ok && t.equals("Ta(OH)5")) {ok = cmplx.name.contains("Ta");} if(!ok && (t.equals("Nb(OH)5")|| t.equals("Nb(OH)6"))) {ok = cmplx.name.contains("Nb");} if(!ok && (t.equals("PoO") || t.equals("HPo"))) {ok = cmplx.name.contains("Po");} if(!ok && (t.equals("PaO2")|| t.equals("PaOOH"))) {ok = cmplx.name.contains("Pa");} if(!ok && (t.equals("Si(OH)4")|| t.equals("H4SiO4")|| t.equals("H4(SiO4)")|| t.equals("SiO2"))) {ok = cmplx.name.contains("Si");} if(!ok && t.equals("OsO4")) {ok = cmplx.name.contains("Os");} if(!ok && (t.equals("TcO4")|| t.equals("TcO(OH)2")|| t.equals("TcO"))) {ok = cmplx.name.contains("Tc");} if(!ok && (t.equals("ReO4") || t.equals("Re(OH)4"))) {ok = cmplx.name.contains("Re");} if(!ok && (t.equals("RuO4") || t.equals("Ru(OH)2"))) {ok = cmplx.name.contains("Ru");} if(!ok && (t.equals("TiO") || t.equals("Ti(OH)4")|| t.equals("H4TiO4"))) {ok = cmplx.name.contains("Ti");} if(!ok && t.equals("VO")) {ok = cmplx.name.contains("V");} if(!ok && (t.equals("B(OH)3")|| t.equals("B(OH)4")|| t.equals("H3BO3")|| t.equals("BH4"))) {ok = cmplx.name.contains("B");} if(!ok && (t.equals("PO4")|| t.equals("HPO4")|| t.equals("H2(PO4)")|| t.equals("H2PO2") || t.equals("HPO3") || t.equals("P2O6") || t.equals("PH4"))) {ok = cmplx.name.contains("P");} if(!ok && t.equals("CNO")) {ok = cmplx.name.contains("CN");} if(!ok && (t.equals("BrO") || t.equals("BrO3"))) {ok = cmplx.name.contains("Br");} if(!ok && t.equals("H2O2")) {ok = cmplx.name.contains("O2");} if(!ok && (t.equals("H2Se")|| t.equals("HSe")|| t.equals("SeO4")|| t.equals("SeO3") || t.equals("HSeO3")|| t.equals("SeCN"))) {ok = cmplx.name.contains("Se");} if(!ok && (t.equals("HS") || t.equals("H2S"))) {ok = cmplx.name.contains("S");} if(!ok && (t.equals("SO4") || t.equals("SO3")|| t.equals("S2O3")|| t.equals("S2O6") || t.equals("S2O4")|| t.equals("S2O8")|| t.equals("HSO5"))) {ok = cmplx.name.contains("S");} if(!ok && (t.equals("ClO") || t.equals("ClO2") || t.equals("ClO3") || t.equals("ClO4"))) {ok = cmplx.name.contains("Cl");} if(!ok && (t.equals("Br2") || t.equals("Br3") || t.equals("BrO4"))) {ok = cmplx.name.contains("Br");} if(!ok && (t.equals("I3")|| t.equals("IO")|| t.equals("IO3")|| t.equals("IO4"))) {ok = cmplx.name.contains("I");} if(!ok && t.equals("HAcetate")) {ok = cmplx.name.contains("Acetate");} if(!ok && t.equals("Zr(OH)2")) {ok = cmplx.name.contains("Zr");} if(!ok) { lists.itemsNames.add(cmplx.name+" does not contain "+cmplx.reactionComp.get(i)); } } //</editor-fold> if(cmplx.reference !=null && cmplx.reference.trim().length()>0 && refs !=null && lists.refsNotFnd != null) { rfs = refs.splitRefs(cmplx.reference); for(String r : rfs) { if(refs.isRefThere(r) == null) { if(!lists.refsNotFnd.contains(r)) { lists.refsNotFnd.add(r); } } else { if(lists.refsFnd != null && !lists.refsFnd.contains(r)) { lists.refsFnd.add(r); } } } } } // -- while // (loop through all reactions) } catch (Exception ex) {MsgExceptn.exception(ex.getMessage());} // -- for(String component : lists.reactantsSet.keySet()) { fnd = false; for(i=0; i < elemsComps.size(); i++) { if(elemsComps.get(i)[1].equals(component)) {fnd = true; break;} } if(!fnd) {lists.reactantsUnknown.add(component);} } // -- Components in element-reactant files not used in the databases for reactions for(i=0; i < elemsComps.size(); i++) { if(!lists.reactantsSet.containsKey(elemsComps.get(i)[1])) { lists.reactantsNotUsed.add(elemsComps.get(i)[1]); } } // -- Reactant names in the reaction database that are equivalent but will be treated as different java.util.ArrayList<String> arrayList = new java.util.ArrayList<String>(lists.reactantsSet.keySet()); java.util.Collections.sort(arrayList, String.CASE_INSENSITIVE_ORDER); for(j=0; j < (arrayList.size()-1); j++) { for(i=(j+1); i < arrayList.size(); i++) { if(Util.nameCompare(arrayList.get(j),arrayList.get(i))) { lists.reactantsCompare.add(arrayList.get(j)+" and: "+arrayList.get(i)); } } } // -- Reactant names in the elements-reactants file(s) that are equivalent but will be treated as different arrayList = new java.util.ArrayList<String>(); for(i=0; i<elemsComps.size(); i++) {arrayList.add(elemsComps.get(i)[1]);} java.util.Collections.sort(arrayList, String.CASE_INSENSITIVE_ORDER); for(j=0; j < (arrayList.size()-1); j++) { for(i=(j+1); i < arrayList.size(); i++) { if(!arrayList.get(j).equals(arrayList.get(i)) && Util.nameCompare(arrayList.get(j),arrayList.get(i))) { lists.elementReactantsCompare.add(arrayList.get(j)+" and: "+arrayList.get(i)); } } } return true; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="displayDatabaseErrors"> /** Displays errors in dialogs containing two buttons (ok and cancel). * The errors are provided in an object of CheckDataBasesLists. * The text on the first button is provided by the user, for example * "Exit anyway", the second button is always "Cancel". * * @param dbg write debug information? * @param parent as the owner of error messages * @param title for error messages * @param database the name of the database, written in the error message (html). * Several file names may be given separated by lne brakes "&lt;br&gt;". * @param lists an object where the errors have been reported * @return <code>true</code> if no errors are found or if the user selects "ok" anyway; * <code>false</code> if there are errors and the user selects "cancel" */ public static boolean displayDatabaseErrors(final boolean dbg, final java.awt.Component parent, final String title, final String database, final CheckDataBasesLists lists) { if(dbg) {System.out.println("---- CheckDatabases.displayDatabaseErrors, debug = true");} if(lists == null) { MsgExceptn.exception("Error in \"displayDatabaseErrors\":"+nl+ " parameter \"lists\" (where output arrays would be stored) is null."); return false; } if(lists.reactantsUnknown == null) { MsgExceptn.exception("Error in \"displayDatabaseErrors\":"+nl+ " \"lists.reactantsUnknown\" is null."); return false; } if(lists.reactantWithoutCoef == null) { MsgExceptn.exception("Error in \"displayDatabaseErrors\":"+nl+ " \"lists.reactantWithoutCoef\" is null."); return false; } if(lists.coefWithoutReactant == null) { MsgExceptn.exception("Error in \"displayDatabaseErrors\":"+nl+ " \"lists.coefWithoutReactant\" is null."); return false; } java.util.TreeSet<String> treeSet; javax.swing.DefaultListModel<String> aModel; // javax.swing.DefaultListModel aModel; // java 1.6 String msg; boolean answer = true; if(lists.reactantsUnknown.size() >0) { treeSet = new java.util.TreeSet<String>(lists.reactantsUnknown); aModel = new javax.swing.DefaultListModel<>(); // aModel = new javax.swing.DefaultListModel(); // java 1.6 if(dbg) {System.out.println(nl+"Error: reactants (components) in the reactions database(s) NOT found"+nl+ " in the element-reactant file(s)."+nl+ " Note that any reaction involving these components"+nl+ " will NOT be found in a database search!");} for (String r : treeSet) { aModel.addElement(r); if(dbg){System.out.println(" "+r);} } msg = "<html>File: <b>"+database+"</b><br>&nbsp;<br>Could NOT find the following reactant"; if(aModel.size()>1) {msg = msg+"s";} msg = msg + ".<br>&nbsp;<br>You should add "; if(aModel.size()>1) {msg = msg+"them";} else {msg = msg+"it";} msg = msg+" to<br>the element-reactant file<br>before proceeding.<br>&nbsp;</html>"; answer = showListDialog(parent, title, msg, "Proceed anyway", "Cancel", aModel); } if(!answer) {return false;} if(lists.reactantWithoutCoef.size()>0 || lists.coefWithoutReactant.size()>0) { treeSet = new java.util.TreeSet<String>(); if(lists.reactantWithoutCoef.size()>0) { for(String t : lists.reactantWithoutCoef) {treeSet.add(t);} } if(lists.coefWithoutReactant.size()>0) { for(String t : lists.coefWithoutReactant) {treeSet.add(t);} } aModel = new javax.swing.DefaultListModel<>(); // aModel = new javax.swing.DefaultListModel(); // java 1.6 if(dbg) {System.out.println(nl+"The following reaction(s) had either"+nl+ " - reactants with zero coefficients, or"+nl+ " - non-zero coefficient without reactants.");} for (String r : treeSet) { aModel.addElement(r); if(dbg){System.out.println(" "+r);} } msg = "<html>File: <b>"+database+"</b><br>&nbsp;<br>The following reaction"; if(aModel.size()>1) {msg = msg+"s";} msg = msg + " have either<br>"+ " - reactants with zero coefficients, or<br>"+ " - non-zero coefficient without reactants.<br><br>"+ "Please remove the unused reactants/coefficients<br>"+ "in the following reactions before proceeding.<br>&nbsp;</html>"; answer = showListDialog(parent, title, msg, "Proceed anyway", "Cancel", aModel); } if(!answer) {return false;} if(lists.chargeImbalance.size()>0) { treeSet = new java.util.TreeSet<String>(lists.chargeImbalance); aModel = new javax.swing.DefaultListModel<>(); // aModel = new javax.swing.DefaultListModel(); // java 1.6 if(dbg) {System.out.println(nl+"The following reactions are NOT charge balanced:");} for (String r : treeSet) { aModel.addElement(r); if(dbg){System.out.println(" "+r);} } msg = "<html>File: <b>"+database+"</b><br>&nbsp;<br>The following reaction"; if(aModel.size()>1) {msg = msg+"s";} msg = msg + "<br>"; if(aModel.size()>1) {msg = msg+"are";} else {msg = msg+"is";} msg = msg + " NOT charge balanced.<br>"; msg = msg + "Please correct "; if(aModel.size()>1) {msg = msg + "them";} else {msg = msg + "it";} msg = msg + " before proceeding.<br>&nbsp;</html>"; answer = showListDialog(parent, title, msg, "Proceed anyway", "Cancel", aModel); } return answer; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="-- show List Dialog --"> /** Show a dialog with a label, a list, and two buttons (for example OK/Cancel) * @param parent * @param title * @param labelText a label to be displayed on top of the JList * @param opt1 for example "OK" * @param opt2 for example "Cancel" * @param aModel a list of objects to display in a JList * @return true if the user selects "opt1" (OK); false otherwise */ public static boolean showListDialog(java.awt.Component parent, String title, String labelText, String opt1, String opt2, javax.swing.DefaultListModel<String> aModel) { // javax.swing.DefaultListModel aModel) { // java 1.6 if(opt1 == null || opt1.length() <=0) {opt1 = "OK";} if(opt2 == null || opt2.length() <=0) {opt1 = "Cancel";} //-- create the object to display in the JOptionPane javax.swing.JLabel label = new javax.swing.JLabel(labelText); Object[] array; if(aModel != null && !aModel.isEmpty()) { javax.swing.JList<String> aList = new javax.swing.JList<>(); // javax.swing.JList aList = new javax.swing.JList(); // java 1.6 aList.setModel(aModel); aList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); aList.setVisibleRowCount(5); javax.swing.JScrollPane aScrollPane = new javax.swing.JScrollPane(); aScrollPane.setViewportView(aList); aList.setFocusable(false); array = new Object[2]; array[0] = label; array[1] = aScrollPane; } else { array = new Object[1]; array[0] = label; } //-- the option pane Object[] options = {opt1,opt2}; javax.swing.JOptionPane pane = new javax.swing.JOptionPane(array, javax.swing.JOptionPane.ERROR_MESSAGE, javax.swing.JOptionPane.OK_CANCEL_OPTION, null, options, options[0]); //-- bind to the arrow keys java.util.Set<java.awt.AWTKeyStroke> keys = new java.util.HashSet<java.awt.AWTKeyStroke>( pane.getFocusTraversalKeys(java.awt.KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS)); keys.add(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_RIGHT, 0)); pane.setFocusTraversalKeys(java.awt.KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, keys); keys = new java.util.HashSet<java.awt.AWTKeyStroke>( pane.getFocusTraversalKeys(java.awt.KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS)); keys.add(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_LEFT, 0)); pane.setFocusTraversalKeys(java.awt.KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, keys); //-- show the dialog if(!parent.isVisible()) {parent.setVisible(true);} javax.swing.JDialog dialog = pane.createDialog(parent, title); dialog.setVisible(true); //-- Get the return value int res = javax.swing.JOptionPane.CLOSED_OPTION; //default return value, signals nothing selected // Get the selected Value Object selectedValue = pane.getValue(); // If none, then nothing selected if(selectedValue != null) { options = pane.getOptions(); if (options == null) {// default buttons, no array specified if (selectedValue instanceof Integer) { res = ((Integer) selectedValue); } } else {// Array of option buttons specified for (int i = 0, n = options.length; i < n; i++) { if (options[i].equals(selectedValue)) {res = i; break;} } } } return res == javax.swing.JOptionPane.OK_OPTION; } //</editor-fold> }
31,569
Java
.java
ignasi-p/eq-diagr
18
3
0
2018-08-17T08:25:37Z
2023-04-30T09:33:35Z
FrameAddData.java
/FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibDataBase/src/lib/database/FrameAddData.java
package lib.database; import lib.common.MsgExceptn; import lib.common.Util; import lib.huvud.Div; import lib.huvud.ProgramConf; /** Add new data. * <br> * Copyright (C) 2015-2020 I.Puigdomenech. * * 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 * 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/ * * @author Ignasi Puigdomenech */ public class FrameAddData extends javax.swing.JFrame { // Note: for java 1.6 jComBox must be without type // for java 1.7 jComBox must be <String> private ProgramConf pc; private ProgramDataDB pd; private final javax.swing.JFrame parent; private boolean finished = false; private boolean dbg = false; /** the name, with complete path, of the file with new data to add */ private String addFile; /** the name, with complete path, of a temprary file to store the database when making modifications */ private String addFileTmp; /** the name, with complete path, of the chemical element - reactant file corresponding to the database "addFile" */ private String addFileEle; /** Array list of all known components (e.g. "CN-" or "Fe+2"). * This is used to fill the drop-down combo boxes, and to check for * unknown reactants in reactions. * <p>It contains all the components in the databases selected in the program, * plus those in the add-data file. * @see FrameAddData#elemCompAdd elemCompAdd */ private java.util.ArrayList<String> componentsAdd = new java.util.ArrayList<String>(); /** Array list of String[3] objects with the components used in file "addFile"<br> * [0] contains the element name (e.g. "C"),<br> * [1] the component formula ("CN-" or "Fe+2"),<br> * [2] the component name ("cyanide" or null), which is not really needed, * but used to help the user. * <br> * This array list must contain all components needed for the "add" file. * That is, all components initially in file "addFileEle" (if any), * <b>and</b> any component in the reactions in file "addFile" * that were missing in "addFileEle" (if any), but which are found in the * list of components from the main database(s), that is, found in "elemComp". * @see ProgramDataDB#elemComp elemComp * @see FrameAddData#componentsAdd componentsAdd * @see AddDataElem#elemCompAdd_Update(boolean, java.awt.Component, java.lang.String, java.lang.String, java.util.ArrayList, java.util.ArrayList) elemCompAdd_Update() */ public java.util.ArrayList<String[]> elemCompAdd = new java.util.ArrayList<String[]>(); private java.awt.Dimension windowSize = new java.awt.Dimension(460,383); /** a model used for jListReact. It contains Object[2] arrays with the first object * being a text and the second being a Color indicating if the reaction * is charge balanced or not */ private javax.swing.DefaultListModel<ModelComplexesItem> modelComplexes = new javax.swing.DefaultListModel<>(); // private javax.swing.DefaultListModel modelComplexes = new javax.swing.DefaultListModel(); // java 1.6 /** The objects in <code>modelComplexes</code> * with two variables (fields): a text string and a colour (the foreground). */ private static class ModelComplexesItem { String txt; java.awt.Color clr; /** create an object for <code>modelComplexes</code>. * It has two variables (fields): a text string and a colour (the foreground) */ public ModelComplexesItem(String t, java.awt.Color c) {txt =t; clr =c;} @Override public String toString() {return txt;} /** @return the foreground colour to be used for the text string <code>txt</code> * of this object */ public java.awt.Color getForeground() {return clr;} } /** a model used for jListComps */ private javax.swing.DefaultListModel<String> modelComponents = new javax.swing.DefaultListModel<>(); // private javax.swing.DefaultListModel modelComponents = new javax.swing.DefaultListModel(); // java 1.6 private java.awt.CardLayout cl; // there are six JComboBox and six JFieldText private java.util.ArrayList <javax.swing.JComboBox<String>> boxes = new java.util.ArrayList<javax.swing.JComboBox<String>>(6); // private java.util.ArrayList <javax.swing.JComboBox> boxes = new java.util.ArrayList<javax.swing.JComboBox>(6); // java 1.6 private ComboBoxActionListener boxAListener = new ComboBoxActionListener(); private ComboBoxFocusListener boxFListener = new ComboBoxFocusListener(); private ComboBoxKeyListener boxKListener = new ComboBoxKeyListener(); private javax.swing.JTextField[] texts = new javax.swing.JTextField[6]; private TextFieldFocusListener textFListener = new TextFieldFocusListener(); private TextFieldActionListener textAListener = new TextFieldActionListener(); private TextFieldKeyListener textKListener = new TextFieldKeyListener(); private Complex newC; private Complex oldNewC; private String oldComponentName; private String oldComponentDescr; private String oldComponentLinked; private boolean editingReaction = false; private boolean rearranging = false; private boolean loading = true; private boolean keyUpDown = false; /** the selected index in jListReact when the focus was lost */ private int old_i_react = -1; /** the selected index in jListComps when the focus was lost */ private int old_i_comps = -1; /** indicates if a mouse click on the reactions list should show the popup menu */ private boolean isPopup = false; private static final java.awt.Color vermilion = new java.awt.Color(213,94,0); private static final String SLASH = java.io.File.separator; /** New-line character(s) to substitute "\n" */ private static final String nl = System.getProperty("line.separator"); //<editor-fold defaultstate="collapsed" desc="Constructor"> /** Creates new form FrameAddData * @param pc0 * @param pd0 * @param parent */ public FrameAddData(ProgramConf pc0, ProgramDataDB pd0, javax.swing.JFrame parent) { //there are six JComboBox and six JTextField initComponents(); loading = true; pc = pc0; pd = pd0; this.parent = parent; dbg = pc.dbg; System.out.println(nl+"---- FrameAddData"); boxes.trimToSize(); // ---- setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); //--- Alt-S show/hide messages window javax.swing.KeyStroke altSKeyStroke = javax.swing.KeyStroke.getKeyStroke( java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.ALT_MASK, false); getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altSKeyStroke,"ALT_S"); javax.swing.Action altSAction = new javax.swing.AbstractAction() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { jCheckBoxMenuMsg.doClick(); }}; getRootPane().getActionMap().put("ALT_S", altSAction); //--- Alt-Q quit javax.swing.KeyStroke altQKeyStroke = javax.swing.KeyStroke.getKeyStroke( java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.ALT_MASK, false); getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altQKeyStroke,"ALT_Q"); javax.swing.Action altQAction = new javax.swing.AbstractAction() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { closeWindow(); }}; getRootPane().getActionMap().put("ALT_Q", altQAction); //--- F1 for help javax.swing.KeyStroke f1KeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1,0, false); getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(f1KeyStroke,"F1"); javax.swing.Action f1Action = new javax.swing.AbstractAction() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { jMenuHelpHlp.doClick(); }}; getRootPane().getActionMap().put("F1", f1Action); //---- Icon String iconName = "images/Save_32x32.gif"; java.net.URL imgURL = this.getClass().getResource(iconName); if (imgURL != null) {this.setIconImage(new javax.swing.ImageIcon(imgURL).getImage());} else {System.out.println("Error: Could not load image = \""+iconName+"\"");} //---- Title, etc this.setTitle(pc.progName+" - Add data"); jMenuBar.add(javax.swing.Box.createHorizontalGlue(),2); //move "Help" menu to the right //---- waiting... setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR)); frameEnable(false); //--- Set the location of the window in the screen int left = Math.max(0,(LibDB.screenSize.width-this.getWidth())/2); int top = Math.max(0,(LibDB.screenSize.height-this.getHeight())/2); if(pd.addDataLocation.x < 0 || pd.addDataLocation.y < 0) { pd.addDataLocation.x = left; pd.addDataLocation.y = top; } pd.addDataLocation.x = Math.max(60,Math.min(pd.addDataLocation.x,(LibDB.screenSize.width-this.getWidth()))); pd.addDataLocation.y = Math.max(10,Math.min(pd.addDataLocation.y,(LibDB.screenSize.height-this.getHeight()))); this.setLocation(pd.addDataLocation); //---- Fill in combo boxes boxes.add(jComboBox0); boxes.add(jComboBox1); boxes.add(jComboBox2); boxes.add(jComboBox3); boxes.add(jComboBox4); boxes.add(jComboBox5); texts[0] = jTextField0; texts[1] = jTextField1; texts[2] = jTextField2; texts[3] = jTextField3; texts[4] = jTextField4; texts[5] = jTextField5; // add the mouse and action listeners for(int i=0; i < boxes.size(); i++) { javax.swing.JComboBox<String> jcb; // javax.swing.JComboBox jcb; // java 1.6 jcb = boxes.get(i); jcb.setActionCommand(String.valueOf(i)); jcb.addActionListener(boxAListener); jcb.addFocusListener(boxFListener); jcb.addKeyListener(boxKListener); boxes.set(i, jcb); texts[i].setName("jTextField"+String.valueOf(i).trim()); texts[i].addFocusListener(textFListener); texts[i].addActionListener(textAListener); texts[i].addKeyListener(textKListener); } // java.awt.Font fN = jLabelReactionText.getFont(); fN = new java.awt.Font(fN.getName(), java.awt.Font.PLAIN, fN.getSize()); jLabelReactionText.setFont(fN); jLabelCharge.setText(" "); jLabelLinked.setText(""); // fill the elements combo box jComboBoxElems.removeAllItems(); java.util.AbstractList<String> items = new java.util.ArrayList<String>(LibDB.ELEMENTS); loop: for(int i =1; i < LibDB.ELEMENTS; i++) { for(int j=0; j<items.size(); j++) { //do not add duplicates if(LibDB.elementSymb[i].equals(items.get(j))) {continue loop;} } items.add(LibDB.elementSymb[i]); } jComboBoxElems.addItem(""); java.util.Collections.sort(items,String.CASE_INSENSITIVE_ORDER); java.util.Iterator<String> iter = items.iterator(); while(iter.hasNext()) {jComboBoxElems.addItem(iter.next());} jMenuFileSave.setEnabled(false); jButtonSaveReac.setEnabled(false); jButtonSaveComp.setEnabled(false); if(pd.references != null) {jMenuItemDetails.setEnabled(true);} else {jMenuItemDetails.setEnabled(false);} } //constructor //</editor-fold> //<editor-fold defaultstate="collapsed" desc="start"> public void start() { this.setVisible(true); if(pd.msgFrame != null) { pd.msgFrame.setParentFrame(FrameAddData.this); jCheckBoxMenuMsg.setSelected(pd.msgFrame.isVisible()); } // get the names of files "addFile" and "addFileEle" if(!getAddFileName()) {closeWindow(); return;} frameEnable(true); windowSize = FrameAddData.this.getSize(); java.io.File aF = new java.io.File(addFile); if(aF.exists()) { jMenuAddShow.setEnabled(true); jMenuAddShow.doClick(); addAddFileToList(); } else { jMenuAddReact.doClick(); } parent.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); pd.msgFrame.setCursorDef(); loading = false; } //start //</editor-fold> //<editor-fold defaultstate="collapsed" desc="ComboBox & TextField Array Listeners"> private void ComboBox_Click(int i) { if(loading || rearranging || editingReaction || keyUpDown) {return;} if(!jPanelReaction.isShowing()) {return;} if(i < 0 || i >= boxes.size()) {return;} javax.swing.JComboBox<String> jcb_i = boxes.get(i); // javax.swing.JComboBox jcb_i = boxes.get(i); // java 1.6 if(jcb_i.getSelectedItem() == null) {return;} //if(dbg) {System.out.println("--- ComboBox_Click("+i+")");} String ti = jcb_i.getSelectedItem().toString(); if(ti.length()>0) { if(texts[i].getText().length() <=0) {texts[i].setText("1");} for(int j=0; j < boxes.size(); j++) { javax.swing.JComboBox<String> jcb_j = boxes.get(j); // javax.swing.JComboBox jcb_j = boxes.get(j); // java 1.6 if(j != i && jcb_j.getSelectedItem().toString().length()>0) { if(jcb_j.getSelectedItem().toString().equals(ti)) { jcb_i.setSelectedIndex(0); texts[i].setText(""); showErr("You already have \""+ti+"\""+nl+"in the reaction.",2); break; } } } //for j } else {texts[i].setText("");} rearrangeReaction(); update_newC(); //boxes[i].requestFocusInWindow(); } //ComboBox_Click() private class ComboBoxActionListener implements java.awt.event.ActionListener { @Override public void actionPerformed(java.awt.event.ActionEvent e) { if(loading || rearranging || editingReaction || keyUpDown) {return;} int i; if(e.getSource() instanceof javax.swing.JComboBox) { i = Integer.parseInt(e.getActionCommand()); ComboBox_Click(i); } //if jComboBox } //actionPerformed } //class ComboBoxActionListener private class ComboBoxFocusListener implements java.awt.event.FocusListener { @Override public void focusGained(java.awt.event.FocusEvent evt) { //int i = getI(evt); //if(i < 0) {return;} //buttons[i].setBorder(buttonBorderSelected); //buttons[i].setPreferredSize(buttonSize); } @Override public void focusLost(java.awt.event.FocusEvent evt) { if(loading) {return;} int i = getI(evt); if(i < 0) {return;} //buttons[i].setBorder(buttonBorder); //if(dbg) {System.out.println("--- ComboBox("+i+") lost focus");} ComboBox_Click(i); rearrangeReaction(); update_newC(); } private int getI(java.awt.event.FocusEvent evt) { javax.swing.JComboBox b = (javax.swing.JComboBox)evt.getSource(); if(b == null) {return -1;} int i = Integer.parseInt(b.getActionCommand()); if(i < 0 || i >= boxes.size()) {return -1;} return i; }//getI(evt) } //class ComboBoxFocusListener private class ComboBoxKeyListener extends java.awt.event.KeyAdapter { @Override public void keyPressed(java.awt.event.KeyEvent evt) { int i = getI(evt); if(i < 0) {return;} int k = evt.getKeyCode(); if(k == java.awt.event.KeyEvent.VK_UP || k == java.awt.event.KeyEvent.VK_DOWN) { keyUpDown = true; } else { keyUpDown = false; if(k == java.awt.event.KeyEvent.VK_LEFT || k == java.awt.event.KeyEvent.VK_RIGHT) { if(k == java.awt.event.KeyEvent.VK_LEFT) { texts[i].requestFocusInWindow(); } else if(k == java.awt.event.KeyEvent.VK_RIGHT) { if(i < (boxes.size()-1)) {texts[i+1].requestFocusInWindow();} else {jTextFieldComplex.requestFocusInWindow();} } } else if(k == java.awt.event.KeyEvent.VK_ENTER || k == java.awt.event.KeyEvent.VK_SPACE) { ComboBox_Click(i); } } } //keyTyped private int getI(java.awt.event.KeyEvent evt) { javax.swing.JComboBox b = (javax.swing.JComboBox)evt.getSource(); if(b == null) {return -1;} int i = Integer.parseInt(b.getActionCommand()); if(i < 0 || i >= boxes.size()) {return -1;} return i; }//getI(evt) } //class ComboBoxKeyListener private class TextFieldActionListener implements java.awt.event.ActionListener { @Override public void actionPerformed(java.awt.event.ActionEvent e) { if(loading || rearranging) {return;} javax.swing.JTextField tf = (javax.swing.JTextField)e.getSource(); int i = -1; try{ String t = tf.getName(); if(t != null && t.length()>0) { i = Integer.parseInt(t.substring(t.length()-1, t.length())); } } catch (NumberFormatException ex) {i=-1;} if(i < 0 || i >= texts.length) {return;} //if(dbg) {System.out.println("--- TextFieldActionListener("+i+")");} validateReactionCoeff(i); rearrangeReaction(); update_newC(); texts[i].requestFocusInWindow(); } //actionPerformed } //class TextFieldActionListener private class TextFieldFocusListener implements java.awt.event.FocusListener { @Override public void focusGained(java.awt.event.FocusEvent evt) { int i = getI(evt); if(i < 0 || i >= texts.length) {return;} texts[i].selectAll(); } //focusGained @Override public void focusLost(java.awt.event.FocusEvent evt) { int i = getI(evt); if(i < 0 || i >= texts.length) {return;} //if(dbg) {System.out.println("--- TextField("+i+") lost focus");} validateReactionCoeff(i); update_newC(); } //focusLost private int getI(java.awt.event.FocusEvent evt) { javax.swing.JTextField b = (javax.swing.JTextField)evt.getSource(); if(b == null) {return -1;} int i = -1; try{ String t = b.getName(); if(t != null && t.length()>0) {//name is "jTextFieldN" with N=0 to 5 i = Integer.parseInt(t.substring(t.length()-1, t.length())); } } catch (NumberFormatException ex) {i=-1;} return i; }//getI(evt) } //class TextFieldFocusListener private class TextFieldKeyListener extends java.awt.event.KeyAdapter { @Override public void keyTyped(java.awt.event.KeyEvent evt) { char key = evt.getKeyChar(); if(!isCharOKforNumberInput(key)) {evt.consume();} //return; } //keyTyped @Override public void keyReleased(java.awt.event.KeyEvent evt) { //int i = getI(evt); //if(i < 0 || i >= texts.length) {return;} //if(dbg) {System.out.println("--- TextFieldKeyListener");} update_newC(); } //keyReleased @Override public void keyPressed(java.awt.event.KeyEvent evt) { int i = getI(evt); if(i < 0 || i >= texts.length) {return;} if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_UP || evt.getKeyCode() == java.awt.event.KeyEvent.VK_DOWN) { if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_UP) { if(i==0) {jTextFieldRef.requestFocusInWindow();} else { javax.swing.JComboBox<String> jcb = boxes.get(i-1); // javax.swing.JComboBox jcb = boxes.get(i-1); // java 1.6 jcb.requestFocusInWindow(); } } else if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_DOWN) { javax.swing.JComboBox<String> jcb = boxes.get(i); // javax.swing.JComboBox jcb = boxes.get(i); // java 1.6 jcb.requestFocusInWindow(); } //return; } } //keyPressed private int getI(java.awt.event.KeyEvent evt) { javax.swing.JTextField tf = (javax.swing.JTextField)evt.getSource(); if(tf == null) {return -1;} int i = -1; try{ String t = tf.getName(); if(t != null && t.length()>0) { i = Integer.parseInt(t.substring(t.length()-1, t.length())); } } catch (NumberFormatException ex) {i=-1;} return i; }//getI(evt) } //class TextFieldKeyListener //</editor-fold> /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonGroup = new javax.swing.ButtonGroup(); jPopupMenu = new javax.swing.JPopupMenu(); jMenuItemEdit = new javax.swing.JMenuItem(); jMenuItemDel = new javax.swing.JMenuItem(); jMenuItemDetails = new javax.swing.JMenuItem(); jSeparator = new javax.swing.JPopupMenu.Separator(); jMenuItemCancel = new javax.swing.JMenuItem(); jPanelReaction = new javax.swing.JPanel(); jLabelReaction = new javax.swing.JLabel(); jPanelReaction1 = new javax.swing.JPanel(); jTextField0 = new javax.swing.JTextField(); jComboBox0 = new javax.swing.JComboBox<>(); jLabelPlus1 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jComboBox1 = new javax.swing.JComboBox<>(); jTextField2 = new javax.swing.JTextField(); jComboBox2 = new javax.swing.JComboBox<>(); jLabelPlus3 = new javax.swing.JLabel(); jTextField3 = new javax.swing.JTextField(); jComboBox3 = new javax.swing.JComboBox<>(); jTextField4 = new javax.swing.JTextField(); jComboBox4 = new javax.swing.JComboBox<>(); jLabelPlus5 = new javax.swing.JLabel(); jTextField5 = new javax.swing.JTextField(); jComboBox5 = new javax.swing.JComboBox<>(); jLabelPlus6 = new javax.swing.JLabel(); jLabelPlus7 = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); jLabelRLh = new javax.swing.JLabel(); jTextFieldComplex = new javax.swing.JTextField(); jLabelCharge = new javax.swing.JLabel(); jPanelReaction2 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jTextFieldComment = new javax.swing.JTextField(); jLabelRef = new javax.swing.JLabel(); jTextFieldRef = new javax.swing.JTextField(); jLabelNote = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); jLabelLogK = new javax.swing.JLabel(); jTextFieldLogK = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jTextFieldDeltH = new javax.swing.JTextField(); jLabelKJmol = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jTextFieldDeltCp = new javax.swing.JTextField(); jLabelJKmol = new javax.swing.JLabel(); jButtonSaveReac = new javax.swing.JButton(); jPanelComponent = new javax.swing.JPanel(); jLabelComp = new javax.swing.JLabel(); jLabelCompName = new javax.swing.JLabel(); jTextFieldCompName = new javax.swing.JTextField(); jLabelLinked = new javax.swing.JLabel(); jLabelCompDescr = new javax.swing.JLabel(); jTextFieldCompDescr = new javax.swing.JTextField(); jLabelElems = new javax.swing.JLabel(); jComboBoxElems = new javax.swing.JComboBox<>(); jButtonLink = new javax.swing.JButton(); jButtonSaveComp = new javax.swing.JButton(); jPanelFiles = new javax.swing.JPanel(); jLabelFiles = new javax.swing.JLabel(); jScrollPaneFiles = new javax.swing.JScrollPane(); jTextAreaFiles = new javax.swing.JTextArea(); jPanelReactions = new javax.swing.JPanel(); jLabelReact = new javax.swing.JLabel(); jScrollPaneReact = new javax.swing.JScrollPane(); jListReact = new javax.swing.JList(); jLabelReactionText = new javax.swing.JLabel(); jLabelHelp = new javax.swing.JLabel(); jPanelComps = new javax.swing.JPanel(); jLabelComps = new javax.swing.JLabel(); jScrollPaneComps = new javax.swing.JScrollPane(); jListComps = new javax.swing.JList(); jMenuBar = new javax.swing.JMenuBar(); jMenuFile = new javax.swing.JMenu(); jMenuFileShowFile = new javax.swing.JMenuItem(); jMenuFileSave = new javax.swing.JMenuItem(); jMenuFileExit = new javax.swing.JMenuItem(); jMenuAdd = new javax.swing.JMenu(); jMenuAddReact = new javax.swing.JMenuItem(); jMenuAddComp = new javax.swing.JMenuItem(); jMenuAddShow = new javax.swing.JMenuItem(); jSeparatorAdd = new javax.swing.JPopupMenu.Separator(); jCheckBoxMenuMsg = new javax.swing.JCheckBoxMenuItem(); jMenuHelp = new javax.swing.JMenu(); jMenuHelpHlp = new javax.swing.JMenuItem(); jMenuItemEdit.setMnemonic('e'); jMenuItemEdit.setText("Edit"); jMenuItemEdit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItemEditActionPerformed(evt); } }); jPopupMenu.add(jMenuItemEdit); jMenuItemDel.setMnemonic('d'); jMenuItemDel.setText("Delete"); jMenuItemDel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItemDelActionPerformed(evt); } }); jPopupMenu.add(jMenuItemDel); jMenuItemDetails.setMnemonic('d'); jMenuItemDetails.setText("show Details"); jMenuItemDetails.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItemDetailsActionPerformed(evt); } }); jPopupMenu.add(jMenuItemDetails); jPopupMenu.add(jSeparator); jMenuItemCancel.setMnemonic('c'); jMenuItemCancel.setText("Cancel"); jMenuItemCancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItemCancelActionPerformed(evt); } }); jPopupMenu.add(jMenuItemCancel); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); addComponentListener(new java.awt.event.ComponentAdapter() { public void componentMoved(java.awt.event.ComponentEvent evt) { formComponentMoved(evt); } public void componentResized(java.awt.event.ComponentEvent evt) { formComponentResized(evt); } }); addWindowFocusListener(new java.awt.event.WindowFocusListener() { public void windowGainedFocus(java.awt.event.WindowEvent evt) { formWindowGainedFocus(evt); } public void windowLostFocus(java.awt.event.WindowEvent evt) { } }); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } }); getContentPane().setLayout(new java.awt.CardLayout()); jLabelReaction.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabelReaction.setText("New reaction:"); jTextField0.setHorizontalAlignment(javax.swing.JTextField.TRAILING); jTextField0.setText("1"); jLabelPlus1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabelPlus1.setText("+"); jTextField1.setHorizontalAlignment(javax.swing.JTextField.TRAILING); jTextField1.setText("1"); jTextField2.setHorizontalAlignment(javax.swing.JTextField.TRAILING); jTextField2.setText("1"); jLabelPlus3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabelPlus3.setText("+"); jTextField3.setHorizontalAlignment(javax.swing.JTextField.TRAILING); jTextField3.setText("1"); jTextField4.setHorizontalAlignment(javax.swing.JTextField.TRAILING); jTextField4.setText("1"); jLabelPlus5.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabelPlus5.setText("+"); jTextField5.setHorizontalAlignment(javax.swing.JTextField.TRAILING); jTextField5.setText("1"); jLabelPlus6.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabelPlus6.setText("+"); jLabelPlus7.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabelPlus7.setText("+"); jLabelRLh.setIcon(new javax.swing.ImageIcon(getClass().getResource("/lib/database/images/rlh.gif"))); // NOI18N jLabelRLh.setLabelFor(jTextFieldComplex); jTextFieldComplex.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextFieldComplexActionPerformed(evt); } }); jTextFieldComplex.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { jTextFieldComplexFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { jTextFieldComplexFocusLost(evt); } }); jTextFieldComplex.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jTextFieldComplexKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { jTextFieldComplexKeyReleased(evt); } public void keyTyped(java.awt.event.KeyEvent evt) { jTextFieldComplexKeyTyped(evt); } }); jLabelCharge.setText("<html>Reaction is chage balanced.</html>"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addComponent(jLabelRLh) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextFieldComplex, javax.swing.GroupLayout.PREFERRED_SIZE, 271, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabelCharge, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabelRLh) .addComponent(jTextFieldComplex, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabelCharge, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); javax.swing.GroupLayout jPanelReaction1Layout = new javax.swing.GroupLayout(jPanelReaction1); jPanelReaction1.setLayout(jPanelReaction1Layout); jPanelReaction1Layout.setHorizontalGroup( jPanelReaction1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelReaction1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanelReaction1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jTextField0, javax.swing.GroupLayout.DEFAULT_SIZE, 42, Short.MAX_VALUE) .addComponent(jTextField2) .addComponent(jTextField4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanelReaction1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanelReaction1Layout.createSequentialGroup() .addGroup(jPanelReaction1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jComboBox4, 0, 109, Short.MAX_VALUE) .addComponent(jComboBox2, javax.swing.GroupLayout.Alignment.TRAILING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jComboBox0, javax.swing.GroupLayout.Alignment.TRAILING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanelReaction1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanelReaction1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabelPlus3) .addComponent(jLabelPlus5, javax.swing.GroupLayout.Alignment.TRAILING)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanelReaction1Layout.createSequentialGroup() .addComponent(jLabelPlus1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanelReaction1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jTextField1) .addComponent(jTextField3) .addComponent(jTextField5, javax.swing.GroupLayout.DEFAULT_SIZE, 43, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanelReaction1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jComboBox3, javax.swing.GroupLayout.Alignment.LEADING, 0, 119, Short.MAX_VALUE) .addComponent(jComboBox1, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jComboBox5, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanelReaction1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabelPlus6) .addComponent(jLabelPlus7)))))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanelReaction1Layout.setVerticalGroup( jPanelReaction1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelReaction1Layout.createSequentialGroup() .addGroup(jPanelReaction1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField0, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox0, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabelPlus1) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabelPlus6)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanelReaction1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabelPlus3) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabelPlus7)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanelReaction1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabelPlus5) .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jLabel1.setLabelFor(jTextFieldComment); jLabel1.setText("Comment:"); jTextFieldComment.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextFieldCommentActionPerformed(evt); } }); jTextFieldComment.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { jTextFieldCommentFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { jTextFieldCommentFocusLost(evt); } }); jTextFieldComment.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jTextFieldCommentKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { jTextFieldCommentKeyReleased(evt); } }); jLabelRef.setLabelFor(jTextFieldRef); jLabelRef.setText("Reference(s):"); jTextFieldRef.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextFieldRefActionPerformed(evt); } }); jTextFieldRef.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { jTextFieldRefFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { jTextFieldRefFocusLost(evt); } }); jTextFieldRef.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jTextFieldRefKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { jTextFieldRefKeyReleased(evt); } }); jLabelNote.setText("<html><b>Note:</b> Temperature variation<br>\nof logK uses a power-series<br>expression.</html>"); jLabelLogK.setLabelFor(jTextFieldLogK); jLabelLogK.setText("log K° (25°C) ="); jTextFieldLogK.setText("-99999"); jTextFieldLogK.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextFieldLogKActionPerformed(evt); } }); jTextFieldLogK.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { jTextFieldLogKFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { jTextFieldLogKFocusLost(evt); } }); jTextFieldLogK.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jTextFieldLogKKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { jTextFieldLogKKeyReleased(evt); } public void keyTyped(java.awt.event.KeyEvent evt) { jTextFieldLogKKeyTyped(evt); } }); jLabel2.setText("<html>&#916;<i>H</i>&deg; =</html>"); jTextFieldDeltH.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextFieldDeltHActionPerformed(evt); } }); jTextFieldDeltH.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { jTextFieldDeltHFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { jTextFieldDeltHFocusLost(evt); } }); jTextFieldDeltH.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jTextFieldDeltHKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { jTextFieldDeltHKeyReleased(evt); } public void keyTyped(java.awt.event.KeyEvent evt) { jTextFieldDeltHKeyTyped(evt); } }); jLabelKJmol.setText("kJ/mol"); jLabel4.setText("<html>&#916;<i>C<sub>p</sub></i>&deg;=</html>"); jTextFieldDeltCp.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextFieldDeltCpActionPerformed(evt); } }); jTextFieldDeltCp.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { jTextFieldDeltCpFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { jTextFieldDeltCpFocusLost(evt); } }); jTextFieldDeltCp.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jTextFieldDeltCpKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { jTextFieldDeltCpKeyReleased(evt); } public void keyTyped(java.awt.event.KeyEvent evt) { jTextFieldDeltCpKeyTyped(evt); } }); jLabelJKmol.setText("J/(K mol)"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabelLogK)) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(44, 44, 44) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jTextFieldDeltCp, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabelJKmol)) .addComponent(jTextFieldLogK, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jTextFieldDeltH, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabelKJmol))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabelLogK) .addComponent(jTextFieldLogK, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextFieldDeltH, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabelKJmol)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextFieldDeltCp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabelJKmol))) ); javax.swing.GroupLayout jPanelReaction2Layout = new javax.swing.GroupLayout(jPanelReaction2); jPanelReaction2.setLayout(jPanelReaction2Layout); jPanelReaction2Layout.setHorizontalGroup( jPanelReaction2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelReaction2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanelReaction2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelReaction2Layout.createSequentialGroup() .addGroup(jPanelReaction2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabelRef) .addComponent(jLabel1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanelReaction2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextFieldComment) .addComponent(jTextFieldRef))) .addGroup(jPanelReaction2Layout.createSequentialGroup() .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, Short.MAX_VALUE) .addComponent(jLabelNote, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); jPanelReaction2Layout.setVerticalGroup( jPanelReaction2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelReaction2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanelReaction2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabelNote, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanelReaction2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jTextFieldComment, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanelReaction2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextFieldRef, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabelRef)) .addGap(1, 1, 1)) ); jButtonSaveReac.setMnemonic('v'); jButtonSaveReac.setText(" Save "); jButtonSaveReac.setAlignmentX(0.5F); jButtonSaveReac.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jButtonSaveReac.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonSaveReacActionPerformed(evt); } }); javax.swing.GroupLayout jPanelReactionLayout = new javax.swing.GroupLayout(jPanelReaction); jPanelReaction.setLayout(jPanelReactionLayout); jPanelReactionLayout.setHorizontalGroup( jPanelReactionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelReactionLayout.createSequentialGroup() .addContainerGap() .addGroup(jPanelReactionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelReactionLayout.createSequentialGroup() .addComponent(jLabelReaction) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelReactionLayout.createSequentialGroup() .addGroup(jPanelReactionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanelReactionLayout.createSequentialGroup() .addComponent(jPanelReaction1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanelReactionLayout.createSequentialGroup() .addComponent(jPanelReaction2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButtonSaveReac))) .addGap(18, 18, 18)))) ); jPanelReactionLayout.setVerticalGroup( jPanelReactionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelReactionLayout.createSequentialGroup() .addGap(15, 15, 15) .addGroup(jPanelReactionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButtonSaveReac) .addGroup(jPanelReactionLayout.createSequentialGroup() .addComponent(jLabelReaction) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanelReaction1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0) .addComponent(jPanelReaction2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(16, Short.MAX_VALUE)) ); getContentPane().add(jPanelReaction, "cardReaction"); jLabelComp.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabelComp.setText("New component:"); jLabelCompName.setLabelFor(jTextFieldCompName); jLabelCompName.setText("name:"); jTextFieldCompName.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jTextFieldCompNameKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { jTextFieldCompNameKeyReleased(evt); } public void keyTyped(java.awt.event.KeyEvent evt) { jTextFieldCompNameKeyTyped(evt); } }); jLabelLinked.setText("Linked to: Cu"); jLabelCompDescr.setLabelFor(jTextFieldCompDescr); jLabelCompDescr.setText("description:"); jTextFieldCompDescr.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jTextFieldCompDescrKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { jTextFieldCompDescrKeyReleased(evt); } }); jLabelElems.setLabelFor(jComboBoxElems); jLabelElems.setText("elements:"); jComboBoxElems.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); jComboBoxElems.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBoxElemsActionPerformed(evt); } }); jComboBoxElems.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jComboBoxElemsKeyPressed(evt); } }); jButtonLink.setMnemonic('l'); jButtonLink.setText(" Link component to element "); jButtonLink.setAlignmentX(0.5F); jButtonLink.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jButtonLink.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonLinkActionPerformed(evt); } }); jButtonLink.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jButtonLinkKeyPressed(evt); } }); jButtonSaveComp.setMnemonic('v'); jButtonSaveComp.setText(" Save "); jButtonSaveComp.setAlignmentX(0.5F); jButtonSaveComp.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jButtonSaveComp.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonSaveCompActionPerformed(evt); } }); javax.swing.GroupLayout jPanelComponentLayout = new javax.swing.GroupLayout(jPanelComponent); jPanelComponent.setLayout(jPanelComponentLayout); jPanelComponentLayout.setHorizontalGroup( jPanelComponentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelComponentLayout.createSequentialGroup() .addContainerGap() .addGroup(jPanelComponentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButtonSaveComp) .addGroup(jPanelComponentLayout.createSequentialGroup() .addGroup(jPanelComponentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabelElems) .addComponent(jLabelCompDescr) .addComponent(jLabelCompName) .addComponent(jLabelComp)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanelComponentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanelComponentLayout.createSequentialGroup() .addComponent(jComboBoxElems, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jButtonLink)) .addGroup(jPanelComponentLayout.createSequentialGroup() .addComponent(jTextFieldCompName, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabelLinked)) .addComponent(jTextFieldCompDescr)))) .addContainerGap(135, Short.MAX_VALUE)) ); jPanelComponentLayout.setVerticalGroup( jPanelComponentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelComponentLayout.createSequentialGroup() .addContainerGap() .addComponent(jLabelComp) .addGap(18, 18, 18) .addGroup(jPanelComponentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelCompName) .addComponent(jTextFieldCompName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabelLinked)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanelComponentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextFieldCompDescr, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabelCompDescr)) .addGap(23, 23, 23) .addGroup(jPanelComponentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jComboBoxElems, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButtonLink) .addComponent(jLabelElems)) .addGap(34, 34, 34) .addComponent(jButtonSaveComp) .addContainerGap(156, Short.MAX_VALUE)) ); getContentPane().add(jPanelComponent, "cardComponent"); jLabelFiles.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabelFiles.setLabelFor(jTextAreaFiles); jLabelFiles.setText("Files:"); jScrollPaneFiles.setFont(new java.awt.Font("Monospaced", 0, 13)); // NOI18N jTextAreaFiles.setColumns(20); jTextAreaFiles.setRows(3); jTextAreaFiles.setText("D:\\_USB\\Eq-Calc_Java\\Prog\\data\\DataMaintenance\\Th.elt D:\\_USB\\Eq-Calc_Java\\Prog\\data\\DataMaintenance\\Th.skv"); jTextAreaFiles.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jTextAreaFilesMouseClicked(evt); } }); jTextAreaFiles.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { jTextAreaFilesFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { jTextAreaFilesFocusLost(evt); } }); jTextAreaFiles.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jTextAreaFilesKeyPressed(evt); } public void keyTyped(java.awt.event.KeyEvent evt) { jTextAreaFilesKeyTyped(evt); } }); jScrollPaneFiles.setViewportView(jTextAreaFiles); jLabelReact.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabelReact.setLabelFor(jListReact); jLabelReact.setText("Reactions:"); jListReact.setModel(modelComplexes); jListReact.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); jListReact.setCellRenderer(new ComplexListCellRenderer()); jListReact.setName("jListReact"); // NOI18N jListReact.setVisibleRowCount(6); jListReact.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { jListReactFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { jListReactFocusLost(evt); } }); jListReact.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jListReactMouseClicked(evt); } public void mousePressed(java.awt.event.MouseEvent evt) { jListReactMousePressed(evt); } public void mouseReleased(java.awt.event.MouseEvent evt) { jListReactMouseReleased(evt); } }); jListReact.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jListReactKeyPressed(evt); } }); jListReact.addListSelectionListener(new javax.swing.event.ListSelectionListener() { public void valueChanged(javax.swing.event.ListSelectionEvent evt) { jListReactValueChanged(evt); } }); jScrollPaneReact.setViewportView(jListReact); jLabelReactionText.setLabelFor(jListReact); jLabelReactionText.setText("jLabelReactionText jLabelReactionText jLabelReactionText"); javax.swing.GroupLayout jPanelReactionsLayout = new javax.swing.GroupLayout(jPanelReactions); jPanelReactions.setLayout(jPanelReactionsLayout); jPanelReactionsLayout.setHorizontalGroup( jPanelReactionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelReactionsLayout.createSequentialGroup() .addComponent(jLabelReact) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(jScrollPaneReact) .addComponent(jLabelReactionText, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); jPanelReactionsLayout.setVerticalGroup( jPanelReactionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelReactionsLayout.createSequentialGroup() .addComponent(jLabelReact) .addGap(4, 4, 4) .addComponent(jScrollPaneReact, javax.swing.GroupLayout.DEFAULT_SIZE, 93, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabelReactionText)) ); jLabelHelp.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); jLabelHelp.setText("Press [Del] to delete; double-click or Alt-E to edit"); jLabelComps.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabelComps.setLabelFor(jListComps); jLabelComps.setText("Components:"); jListComps.setModel(modelComponents); jListComps.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); jListComps.setName("jListComps"); // NOI18N jListComps.setVisibleRowCount(5); jListComps.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jListCompsMouseClicked(evt); } public void mousePressed(java.awt.event.MouseEvent evt) { jListCompsMousePressed(evt); } public void mouseReleased(java.awt.event.MouseEvent evt) { jListCompsMouseReleased(evt); } }); jListComps.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { jListCompsFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { jListCompsFocusLost(evt); } }); jListComps.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jListCompsKeyPressed(evt); } }); jScrollPaneComps.setViewportView(jListComps); javax.swing.GroupLayout jPanelCompsLayout = new javax.swing.GroupLayout(jPanelComps); jPanelComps.setLayout(jPanelCompsLayout); jPanelCompsLayout.setHorizontalGroup( jPanelCompsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelCompsLayout.createSequentialGroup() .addComponent(jLabelComps) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jScrollPaneComps) ); jPanelCompsLayout.setVerticalGroup( jPanelCompsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelCompsLayout.createSequentialGroup() .addComponent(jLabelComps) .addGap(4, 4, 4) .addComponent(jScrollPaneComps, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE)) ); javax.swing.GroupLayout jPanelFilesLayout = new javax.swing.GroupLayout(jPanelFiles); jPanelFiles.setLayout(jPanelFilesLayout); jPanelFilesLayout.setHorizontalGroup( jPanelFilesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelFilesLayout.createSequentialGroup() .addGroup(jPanelFilesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelFilesLayout.createSequentialGroup() .addContainerGap() .addGroup(jPanelFilesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelFilesLayout.createSequentialGroup() .addComponent(jLabelFiles) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPaneFiles)) .addComponent(jPanelReactions, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanelComps, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGroup(jPanelFilesLayout.createSequentialGroup() .addGap(160, 160, 160) .addComponent(jLabelHelp) .addGap(0, 104, Short.MAX_VALUE))) .addContainerGap()) ); jPanelFilesLayout.setVerticalGroup( jPanelFilesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelFilesLayout.createSequentialGroup() .addContainerGap() .addGroup(jPanelFilesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabelFiles) .addComponent(jScrollPaneFiles, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanelReactions, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(0, 0, 0) .addComponent(jLabelHelp, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0) .addComponent(jPanelComps, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); getContentPane().add(jPanelFiles, "cardFiles"); jMenuFile.setMnemonic('f'); jMenuFile.setText("File"); jMenuFileShowFile.setMnemonic('o'); jMenuFileShowFile.setText("Show File contents"); jMenuFileShowFile.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuFileShowFileActionPerformed(evt); } }); jMenuFile.add(jMenuFileShowFile); jMenuFileSave.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK)); jMenuFileSave.setMnemonic('v'); jMenuFileSave.setText("Save file"); jMenuFileSave.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuFileSaveActionPerformed(evt); } }); jMenuFile.add(jMenuFileSave); jMenuFileExit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK)); jMenuFileExit.setMnemonic('x'); jMenuFileExit.setText("Exit"); jMenuFileExit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuFileExitActionPerformed(evt); } }); jMenuFile.add(jMenuFileExit); jMenuBar.add(jMenuFile); jMenuAdd.setMnemonic('a'); jMenuAdd.setText("Add data"); jMenuAddReact.setMnemonic('r'); jMenuAddReact.setText("add Reaction"); jMenuAddReact.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuAddReactActionPerformed(evt); } }); jMenuAdd.add(jMenuAddReact); jMenuAddComp.setMnemonic('c'); jMenuAddComp.setText("add Component"); jMenuAddComp.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuAddCompActionPerformed(evt); } }); jMenuAdd.add(jMenuAddComp); jMenuAddShow.setMnemonic('o'); jMenuAddShow.setText("Show File contents"); jMenuAddShow.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuAddShowActionPerformed(evt); } }); jMenuAdd.add(jMenuAddShow); jMenuAdd.add(jSeparatorAdd); jCheckBoxMenuMsg.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.ALT_MASK)); jCheckBoxMenuMsg.setMnemonic('s'); jCheckBoxMenuMsg.setText("Show messages"); jCheckBoxMenuMsg.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxMenuMsgActionPerformed(evt); } }); jMenuAdd.add(jCheckBoxMenuMsg); jMenuBar.add(jMenuAdd); jMenuHelp.setMnemonic('h'); jMenuHelp.setText("Help"); jMenuHelpHlp.setMnemonic('h'); jMenuHelpHlp.setText("Help"); jMenuHelpHlp.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuHelpHlpActionPerformed(evt); } }); jMenuHelp.add(jMenuHelpHlp); jMenuBar.add(jMenuHelp); setJMenuBar(jMenuBar); pack(); }// </editor-fold>//GEN-END:initComponents //<editor-fold defaultstate="collapsed" desc="events"> private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing closeWindow(); }//GEN-LAST:event_formWindowClosing private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized if(loading || windowSize == null) {return;} int x = this.getX(); int y = this.getY(); int w = this.getWidth(); int h = this.getHeight(); int nw = Math.max(w, windowSize.width); int nh = Math.max(h, windowSize.height); int nx=x, ny=y; if(x+nw > LibDB.screenSize.width) {nx = LibDB.screenSize.width - nw;} if(y+nh > LibDB.screenSize.height) {ny = LibDB.screenSize.height -nh;} if(x!=nx || y!=ny) {this.setLocation(nx, ny);} if(w!=nw || h!=nh) {this.setSize(nw, nh);} }//GEN-LAST:event_formComponentResized private void jTextFieldLogKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldLogKActionPerformed validateLogK(); }//GEN-LAST:event_jTextFieldLogKActionPerformed private void jTextFieldLogKFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldLogKFocusGained jTextFieldLogK.selectAll(); }//GEN-LAST:event_jTextFieldLogKFocusGained private void jTextFieldRefFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldRefFocusGained jTextFieldRef.selectAll(); }//GEN-LAST:event_jTextFieldRefFocusGained private void jTextFieldComplexFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldComplexFocusGained rearrangeReaction(); jTextFieldComplex.requestFocusInWindow(); //jTextFieldComplex.setSelectionStart(jTextFieldComplex.getText().length()); //jTextFieldComplex.selectAll(); rearranging = false; }//GEN-LAST:event_jTextFieldComplexFocusGained private void jTextFieldLogKFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldLogKFocusLost validateLogK(); //if(dbg) {System.out.println("--- jTextFieldLogKFocusLost");} update_newC(); }//GEN-LAST:event_jTextFieldLogKFocusLost private void jTextFieldLogKKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldLogKKeyPressed if(evt.getKeyChar() == java.awt.event.KeyEvent.VK_ENTER) { validateLogK(); } else if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_UP) { jTextFieldComplex.requestFocusInWindow(); } else if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_DOWN) { jTextFieldDeltH.requestFocusInWindow(); } }//GEN-LAST:event_jTextFieldLogKKeyPressed private void jTextFieldLogKKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldLogKKeyTyped char key = evt.getKeyChar(); if(!isCharOKforNumberInput(key)) {evt.consume();} }//GEN-LAST:event_jTextFieldLogKKeyTyped private void jTextAreaFilesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextAreaFilesMouseClicked String addFileOld = addFile; if(!getAddFileName()) {return;} if(!addFileOld.equalsIgnoreCase(addFile)) { jMenuAddShow.setEnabled(true); jMenuAddShow.doClick(); } }//GEN-LAST:event_jTextAreaFilesMouseClicked private void jListCompsFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jListCompsFocusGained int i = 0; if(old_i_comps >=0 && old_i_comps < modelComponents.getSize()) {i = old_i_comps;} jLabelHelp.setText("Press [Del] to delete; double-click or Alt-E to edit"); jListComps.setSelectedIndex(i); }//GEN-LAST:event_jListCompsFocusGained private void jListCompsFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jListCompsFocusLost old_i_comps = jListComps.getSelectedIndex(); if(!jPopupMenu.isVisible()) {jListComps.clearSelection();} jLabelHelp.setText(" "); }//GEN-LAST:event_jListCompsFocusLost private void jListReactFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jListReactFocusGained int i = 0; if(old_i_react >=0 && old_i_react < modelComplexes.getSize()) {i = old_i_react;} jListReact.setSelectedIndex(i); Object value = jListReact.getSelectedValue(); if(value == null) {jListReact.setSelectedIndex(0);} if(value != null) { String t; java.awt.Color fC; if (value instanceof Object[]) { Object values[] = (Object[]) value; try{ t = values[0].toString(); fC = (java.awt.Color) values[1]; } catch (Exception ex) { fC = jListReact.getForeground(); t = value.toString(); } } else { fC = jListReact.getForeground(); t = value.toString(); } Complex c = null; try{c = Complex.fromString(t);} catch (Complex.ReadComplexException ex) {MsgExceptn.exception(ex.toString());} if(c != null) { jLabelReactionText.setText(c.reactionTextWithLogK(25,1)); jLabelReactionText.setForeground(fC); jLabelHelp.setText("Press [Del] to delete; double-click or Alt-E to edit"); } } }//GEN-LAST:event_jListReactFocusGained private void jListReactFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jListReactFocusLost if(!jPopupMenu.isVisible()) { old_i_react = jListReact.getSelectedIndex(); jListReact.clearSelection(); jLabelHelp.setText(" "); jLabelReactionText.setText(" "); } }//GEN-LAST:event_jListReactFocusLost private void jTextAreaFilesFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextAreaFilesFocusGained jTextAreaFiles.selectAll(); }//GEN-LAST:event_jTextAreaFilesFocusGained private void jTextAreaFilesFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextAreaFilesFocusLost jTextAreaFiles.setCaretPosition(0); }//GEN-LAST:event_jTextAreaFilesFocusLost private void jTextAreaFilesKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextAreaFilesKeyTyped char c = Character.toUpperCase(evt.getKeyChar()); if(evt.getKeyChar() != java.awt.event.KeyEvent.VK_ESCAPE && evt.getKeyChar() != java.awt.event.KeyEvent.VK_TAB && evt.getKeyChar() != java.awt.event.KeyEvent.VK_ENTER && !(evt.isAltDown() && ((c == 'X') || (c == 'H') || (c == 'Q') || (c == 'S') || (c == 'F') || (c == 'A') || (evt.getKeyChar() == java.awt.event.KeyEvent.VK_ENTER)) ) //isAltDown && !(evt.isControlDown()) ) { // if not ESC or Alt-something String addFileOld = addFile; if(!getAddFileName()) {return;} if(!addFileOld.equalsIgnoreCase(addFile)) { jMenuAddShow.setEnabled(true); jMenuAddShow.doClick(); } } // if char ok evt.consume(); }//GEN-LAST:event_jTextAreaFilesKeyTyped private void jTextAreaFilesKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextAreaFilesKeyPressed int k = evt.getKeyCode(); if(k == java.awt.event.KeyEvent.VK_LEFT || k == java.awt.event.KeyEvent.VK_UP) { evt.consume(); jListComps.requestFocusInWindow(); return; } else if(k == java.awt.event.KeyEvent.VK_RIGHT || k == java.awt.event.KeyEvent.VK_DOWN) { evt.consume(); jListReact.requestFocusInWindow(); return; } int shft = java.awt.event.InputEvent.SHIFT_DOWN_MASK; if(k == java.awt.event.KeyEvent.VK_TAB) { evt.consume(); if((evt.getModifiersEx() & shft) == shft) { jListComps.requestFocusInWindow(); } else { jListReact.requestFocusInWindow(); } return; } if(!Util.isKeyPressedOK(evt)) {evt.consume();} }//GEN-LAST:event_jTextAreaFilesKeyPressed private void jListReactValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jListReactValueChanged int i = jListReact.getSelectedIndex(); if(i>=0) { if(modelComplexes.get(i) != null) { String t; java.awt.Color fC; if (modelComplexes.get(i) instanceof ModelComplexesItem) { ModelComplexesItem value = (ModelComplexesItem) modelComplexes.get(i); try{ t = value.toString(); fC = value.getForeground(); } catch (Exception ex) { MsgExceptn.msg(ex.toString()); t = modelComplexes.get(i).toString(); fC = java.awt.Color.BLACK; } } else { t = modelComplexes.get(i).toString(); fC = java.awt.Color.BLACK; if(dbg) {MsgExceptn.msg("modelComplexes.get("+i+") not instanceof ModelComplexesItem at \"jListReactValueChanged\""+nl+" t = \""+t+"\"");} } Complex c = null; try{c = Complex.fromString(t); if(c != null) { jLabelReactionText.setText(c.reactionTextWithLogK(25,1)); jLabelReactionText.setForeground(fC); //if(fC != null && fC == vermilion) {jLabelReactionText.setText("<html>"+jLabelReactionText.getText()+" (<b>NOT</b> charge balanced)</html>");} jLabelHelp.setText("Press [Del] to delete; double-click or Alt-E to edit"); } } catch (Complex.ReadComplexException ex) {MsgExceptn.exception(ex.toString());} } //value != null } else { //i<0 jLabelReactionText.setText(" "); } //i? }//GEN-LAST:event_jListReactValueChanged private void jTextFieldCompNameKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldCompNameKeyPressed int k = evt.getKeyCode(); if(k == java.awt.event.KeyEvent.VK_UP) { jButtonLink.requestFocusInWindow(); } else if(k == java.awt.event.KeyEvent.VK_DOWN) { jTextFieldCompDescr.requestFocusInWindow(); } }//GEN-LAST:event_jTextFieldCompNameKeyPressed private void jTextFieldCompDescrKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldCompDescrKeyPressed int k = evt.getKeyCode(); if(k == java.awt.event.KeyEvent.VK_UP) { jTextFieldCompName.requestFocusInWindow(); } else if(k == java.awt.event.KeyEvent.VK_DOWN) { jComboBoxElems.requestFocusInWindow(); } }//GEN-LAST:event_jTextFieldCompDescrKeyPressed private void jButtonLinkKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jButtonLinkKeyPressed int k = evt.getKeyCode(); if(k == java.awt.event.KeyEvent.VK_UP) { jTextFieldCompDescr.requestFocusInWindow(); } else if(k == java.awt.event.KeyEvent.VK_DOWN) { jTextFieldCompName.requestFocusInWindow(); } else if(k == java.awt.event.KeyEvent.VK_LEFT) { jComboBoxElems.requestFocusInWindow(); } else if(k == java.awt.event.KeyEvent.VK_RIGHT) { jTextFieldCompName.requestFocusInWindow(); } }//GEN-LAST:event_jButtonLinkKeyPressed private void jTextFieldComplexKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldComplexKeyPressed int k = evt.getKeyCode(); if(k == java.awt.event.KeyEvent.VK_UP) { javax.swing.JComboBox<String> jcb = boxes.get(boxes.size()-1); // javax.swing.JComboBox jcb = boxes.get(boxes.size()-1); // java 1.6 jcb.requestFocusInWindow(); } else if(k == java.awt.event.KeyEvent.VK_DOWN) { jTextFieldLogK.requestFocusInWindow(); } }//GEN-LAST:event_jTextFieldComplexKeyPressed private void jTextFieldRefKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldRefKeyPressed int k = evt.getKeyCode(); if(k == java.awt.event.KeyEvent.VK_UP) { jTextFieldComment.requestFocusInWindow(); } else if(k == java.awt.event.KeyEvent.VK_DOWN) { jTextField0.requestFocusInWindow(); } }//GEN-LAST:event_jTextFieldRefKeyPressed private void jTextFieldRefActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldRefActionPerformed //if(dbg) {System.out.println("--- jTextFieldRefActionPerformed");} update_newC(); }//GEN-LAST:event_jTextFieldRefActionPerformed private void jTextFieldRefFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldRefFocusLost //if(dbg) {System.out.println("--- jTextFieldRefFocusLost");} update_newC(); }//GEN-LAST:event_jTextFieldRefFocusLost private void jTextFieldComplexActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldComplexActionPerformed //if(dbg) {System.out.println("--- jTextFieldComplexActionPerformed");} update_newC(); }//GEN-LAST:event_jTextFieldComplexActionPerformed private void jTextFieldComplexFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldComplexFocusLost //if(dbg) {System.out.println("--- jTextFieldComplexFocusLost");} update_newC(); }//GEN-LAST:event_jTextFieldComplexFocusLost private void jTextFieldComplexKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldComplexKeyTyped if(evt.getKeyChar() == ',') { showErr("Sorry, No commas allowed"+nl+"in names for chemical species.",2); evt.consume(); } }//GEN-LAST:event_jTextFieldComplexKeyTyped private void jComboBoxElemsKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jComboBoxElemsKeyPressed int k = evt.getKeyCode(); if(k == java.awt.event.KeyEvent.VK_LEFT) { jTextFieldCompDescr.requestFocusInWindow(); } else if(k == java.awt.event.KeyEvent.VK_RIGHT) { jButtonLink.requestFocusInWindow(); } }//GEN-LAST:event_jComboBoxElemsKeyPressed private void jListCompsKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jListCompsKeyPressed int k = evt.getKeyCode(); int alt = java.awt.event.InputEvent.ALT_DOWN_MASK; if(k == java.awt.event.KeyEvent.VK_LEFT) { jListReact.requestFocusInWindow(); } else if(k == java.awt.event.KeyEvent.VK_RIGHT) { jTextAreaFiles.requestFocusInWindow(); } else if(k == java.awt.event.KeyEvent.VK_ENTER || k == java.awt.event.KeyEvent.VK_SPACE) { jListComps_click(); } else if(((evt.getModifiersEx() & alt) == alt) && k == java.awt.event.KeyEvent.VK_E) { jListComps_click(); } else if (k == java.awt.event.KeyEvent.VK_DELETE || k == java.awt.event.KeyEvent.VK_BACK_SPACE) { jListComps_Del(); } //delete }//GEN-LAST:event_jListCompsKeyPressed private void jListReactKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jListReactKeyPressed int k = evt.getKeyCode(); int alt = java.awt.event.InputEvent.ALT_DOWN_MASK; if(k == java.awt.event.KeyEvent.VK_LEFT) { jTextAreaFiles.requestFocusInWindow(); } else if(k == java.awt.event.KeyEvent.VK_RIGHT) { jListComps.requestFocusInWindow(); } else if(k == java.awt.event.KeyEvent.VK_ENTER || k == java.awt.event.KeyEvent.VK_SPACE) { jListReact_click(); } else if(((evt.getModifiersEx() & alt) == alt) && k == java.awt.event.KeyEvent.VK_E) { jListReact_click(); } else if (k == java.awt.event.KeyEvent.VK_DELETE || k == java.awt.event.KeyEvent.VK_BACK_SPACE) { jListReact_Del(); } }//GEN-LAST:event_jListReactKeyPressed private void jTextFieldCompNameKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldCompNameKeyTyped if(loading) {return;} if(evt.getKeyChar() == java.awt.event.KeyEvent.VK_COMMA) {evt.consume();} }//GEN-LAST:event_jTextFieldCompNameKeyTyped private void jListReactMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListReactMouseClicked if(evt.getClickCount() >=2) {jListReact_click();} else { java.awt.Point p = evt.getPoint(); int i = jListReact.locationToIndex(p); if(i>=0) { java.awt.Rectangle r = jListReact.getCellBounds(i, i); if(p.y < r.y || p.y > r.y+r.height) {i=-1;} if(i>=0 && i < modelComplexes.getSize()) { old_i_react = i; jListReact.requestFocusInWindow(); if(!isPopup) {return;} jMenuItemEdit.setEnabled(true); jMenuItemDel.setEnabled(true); jMenuItemDetails.setVisible(true); jPopupMenu.show(jListReact, evt.getX(), evt.getY()); jListReact.setSelectedIndex(i); } }//if i>=0 isPopup = false; } //double-click? }//GEN-LAST:event_jListReactMouseClicked private void jListCompsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListCompsMouseClicked if(evt.getClickCount() >=2) {jListComps_click();} else { java.awt.Point p = evt.getPoint(); int i = jListComps.locationToIndex(p); if(i>=0) { java.awt.Rectangle r = jListComps.getCellBounds(i, i); if(r == null || p.y < r.y || p.y > r.y+r.height) {i=-1;} if(i>=0 && i < modelComponents.getSize()) { old_i_comps = i; jListComps.requestFocusInWindow(); jListComps.setSelectedIndex(i); if(!isPopup) {return;} boolean enabled = true; String comp = modelComponents.get(i).toString(); try { comp = CSVparser.splitLine_1(comp); if(comp.equals("e-") || comp.equals("H+") || comp.equals("H2O")) {enabled = false;} } catch (CSVparser.CSVdataException ex) {} jMenuItemEdit.setEnabled(enabled); jMenuItemDel.setEnabled(enabled); jMenuItemDetails.setVisible(false); jPopupMenu.show(jListComps, evt.getX(), evt.getY()); } }//if i>=0 isPopup = false; } //double-click? }//GEN-LAST:event_jListCompsMouseClicked private void jComboBoxElemsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxElemsActionPerformed if(loading) {return;} String element = jComboBoxElems.getSelectedItem().toString(); if(element == null || element.length() <=0) { jButtonLink.setText("Link component to element"); jButtonLink.setEnabled(false); return; } else {jButtonLink.setEnabled(true);} if(jLabelLinked.getText().length()>10) { String t = jLabelLinked.getText().substring(11); if(t.indexOf(element+",") >=0 || t.endsWith(element)) { jButtonLink.setText("un-Link component to element"); }else { jButtonLink.setText("Link component to element"); } } else { jButtonLink.setText("Link component to element"); } }//GEN-LAST:event_jComboBoxElemsActionPerformed private void jButtonLinkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonLinkActionPerformed String element = null; if(jComboBoxElems.getSelectedIndex()>=0) {element = jComboBoxElems.getSelectedItem().toString();} if(element == null || element.length() <=0) {return;} java.util.ArrayList<String> aL; if(jLabelLinked.getText() == null || jLabelLinked.getText().length() <=10 || !jLabelLinked.getText().startsWith("Linked to:")) { jLabelLinked.setText(""); aL = new java.util.ArrayList<String>(1); aL.add(element); jButtonLink.setText("un-Link component to element"); } else { // there is jLabelLinked try{ aL = CSVparser.splitLine(jLabelLinked.getText().substring(10)); } catch (CSVparser.CSVdataException ex) { MsgExceptn.exception(Util.stack2string(ex)); return; } if(jButtonLink.getText().startsWith("un-L")) { //un-link for(int i=0; i<aL.size(); i++) { if(aL.get(i).equals(element)) {aL.set(i,""); break;} } jButtonLink.setText("Link component to element"); } else { //link aL.add(element); jButtonLink.setText("un-Link component to element"); } // un-link? } // was there a jLabelLinked? boolean empty = true; jLabelLinked.setText("Linked to: "); java.util.Collections.sort(aL,String.CASE_INSENSITIVE_ORDER); for(int i=0; i<aL.size(); i++) { if(aL.get(i).length() <=0) {continue;} empty = false; //append ", "? if(!jLabelLinked.getText().endsWith(" ")) {jLabelLinked.setText(jLabelLinked.getText()+", ");} jLabelLinked.setText(jLabelLinked.getText() + aL.get(i)); } if(empty) {jLabelLinked.setText("");} if(!jLabelLinked.getText().equals(oldComponentLinked) || !jTextFieldCompName.getText().equals(oldComponentName) || !jTextFieldCompDescr.getText().equals(oldComponentDescr)) { jMenuFileSave.setEnabled(true); jButtonSaveComp.setEnabled(true); } else { jMenuFileSave.setEnabled(false); jButtonSaveComp.setEnabled(false); } }//GEN-LAST:event_jButtonLinkActionPerformed private void jTextFieldCompNameKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldCompNameKeyReleased if(!jLabelLinked.getText().equals(oldComponentLinked) || !jTextFieldCompName.getText().equals(oldComponentName) || !jTextFieldCompDescr.getText().equals(oldComponentDescr)) { jMenuFileSave.setEnabled(true); jButtonSaveComp.setEnabled(true); } else { jMenuFileSave.setEnabled(false); jButtonSaveComp.setEnabled(false); } }//GEN-LAST:event_jTextFieldCompNameKeyReleased private void jTextFieldCompDescrKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldCompDescrKeyReleased if(!jLabelLinked.getText().equals(oldComponentLinked) || !jTextFieldCompName.getText().equals(oldComponentName) || !jTextFieldCompDescr.getText().equals(oldComponentDescr)) { jMenuFileSave.setEnabled(true); jButtonSaveComp.setEnabled(true); } else { jMenuFileSave.setEnabled(false); jButtonSaveComp.setEnabled(false); } }//GEN-LAST:event_jTextFieldCompDescrKeyReleased private void jTextFieldComplexKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldComplexKeyReleased //if(dbg) {System.out.println("--- jTextFieldComplexKeyReleased");} update_newC(); }//GEN-LAST:event_jTextFieldComplexKeyReleased private void jTextFieldRefKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldRefKeyReleased //if(dbg) {System.out.println("--- jTextFieldRefKeyReleased");} update_newC(); }//GEN-LAST:event_jTextFieldRefKeyReleased private void jTextFieldLogKKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldLogKKeyReleased //if(dbg) {System.out.println("--- jTextFieldLogKKeyReleased");} update_newC(); }//GEN-LAST:event_jTextFieldLogKKeyReleased private void jMenuItemCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemCancelActionPerformed jPopupMenu.setVisible(false); }//GEN-LAST:event_jMenuItemCancelActionPerformed private void jListReactMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListReactMousePressed if(evt.isPopupTrigger()) {isPopup = true;} }//GEN-LAST:event_jListReactMousePressed private void jListReactMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListReactMouseReleased if(evt.isPopupTrigger()) {isPopup = true;} }//GEN-LAST:event_jListReactMouseReleased private void jMenuItemEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemEditActionPerformed if(jPopupMenu.getInvoker().getName().equals(jListReact.getName())) { jListReact_click(); } else if(jPopupMenu.getInvoker().getName().equals(jListComps.getName())) { jListComps_click(); } }//GEN-LAST:event_jMenuItemEditActionPerformed private void jMenuItemDelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemDelActionPerformed if(jPopupMenu.getInvoker().getName().equals(jListReact.getName())) { jListReact_Del(); } else if(jPopupMenu.getInvoker().getName().equals(jListComps.getName())) { jListComps_Del(); } }//GEN-LAST:event_jMenuItemDelActionPerformed private void jListCompsMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListCompsMousePressed if(evt.isPopupTrigger()) {isPopup = true;} }//GEN-LAST:event_jListCompsMousePressed private void jListCompsMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListCompsMouseReleased if(evt.isPopupTrigger()) {isPopup = true;} }//GEN-LAST:event_jListCompsMouseReleased private void jMenuItemDetailsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemDetailsActionPerformed int index = jListReact.getSelectedIndex(); if(index <0 || index >= modelComplexes.size()) {return;} Complex cmplx; try{cmplx = Complex.fromString(modelComplexes.get(index).toString());} catch (Complex.ReadComplexException ex) {cmplx = null;} if(cmplx == null || cmplx.name == null || cmplx.name.length() <=0) {return;} String refKeys = cmplx.reference.trim(); if(pc.dbg) {System.out.println("Show reference(s) for: \""+cmplx.name+"\""+nl+ " ref: \""+cmplx.reference.trim()+"\"");} ShowDetailsDialog sd = new ShowDetailsDialog(this, true, cmplx, pd.temperature_C, pd.pressure_bar, pd.references); jListReact.requestFocusInWindow(); jListReact.setSelectedIndex(index); }//GEN-LAST:event_jMenuItemDetailsActionPerformed private void jMenuAddReactActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuAddReactActionPerformed if(!loading && jPanelComponent.isShowing()) { //if(dbg) {System.out.println("--- jMenuAddReactActionPerformed");} if(jMenuFileSave.isEnabled()) { if(!discardChanges()) { jTextAreaFiles.requestFocusInWindow(); return; } } } cl = (java.awt.CardLayout)getContentPane().getLayout(); cl.show(getContentPane(),"cardReaction"); newC = new Complex(); try {oldNewC = (Complex)newC.clone();} catch (CloneNotSupportedException ex) { MsgExceptn.exception("CloneNotSupportedException in jMenuAddReact."); oldNewC = null; } updateJPanelReaction(newC); jLabelReaction.setText("New reaction:"); jMenuAddReact.setEnabled(false); jMenuAddComp.setEnabled(true); jMenuAddShow.setEnabled(true); jMenuFileSave.setEnabled(false); jButtonSaveReac.setEnabled(false); jButtonSaveComp.setEnabled(false); jMenuFileShowFile.setEnabled(true); texts[0].requestFocusInWindow(); }//GEN-LAST:event_jMenuAddReactActionPerformed private void jMenuAddCompActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuAddCompActionPerformed if(!loading && jPanelReaction.isShowing()) { //if(dbg) {System.out.println("--- jMenuAddCompActionPerformed");} update_newC(); if(jMenuFileSave.isEnabled()) { if(!newC.isChargeBalanced()) { if(!noChargeBalanceQuestion(newC.name)) { jTextFieldComplex.requestFocusInWindow(); return; } else { jMenuFileSave.setEnabled(false); jButtonSaveComp.setEnabled(false); } } else if(!discardChanges()) { jTextFieldComplex.requestFocusInWindow(); return; } } } cl = (java.awt.CardLayout)getContentPane().getLayout(); cl.show(getContentPane(),"cardComponent"); for(int i=0; i < jComboBoxElems.getItemCount(); i++) { if(jComboBoxElems.getItemAt(i).equals("C")) { jComboBoxElems.setSelectedIndex(i); break; } } oldComponentName = ""; oldComponentDescr = ""; oldComponentLinked = ""; jLabelLinked.setText(""); jTextFieldCompName.setText(""); jTextFieldCompDescr.setText(""); jLabelComp.setText("New component:"); jMenuAddReact.setEnabled(true); jMenuAddComp.setEnabled(false); jMenuAddShow.setEnabled(true); jMenuFileShowFile.setEnabled(true); jTextFieldCompName.requestFocusInWindow(); }//GEN-LAST:event_jMenuAddCompActionPerformed private void jMenuAddShowActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuAddShowActionPerformed if(!loading && jPanelReaction.isShowing()) { if(dbg) {System.out.println("-- jMenuAddShow ActionPerformed (evt)");} update_newC(); if(jMenuFileSave.isEnabled()) { if(!newC.isChargeBalanced()) { if(!noChargeBalanceQuestion(newC.name)) { jTextFieldComplex.requestFocusInWindow(); return; } else { jMenuFileSave.setEnabled(false); jButtonSaveReac.setEnabled(false); jButtonSaveComp.setEnabled(false); } } else if(!discardChanges()) { jTextFieldComplex.requestFocusInWindow(); return; } } } if(!loading && jPanelComponent.isShowing()) { if(jMenuFileSave.isEnabled()) { if(!discardChanges()) { jTextFieldCompName.requestFocusInWindow(); return; } } } //if(dbg) {System.out.println("-- jMenuAddShow");} cl = (java.awt.CardLayout)getContentPane().getLayout(); cl.show(getContentPane(),"cardFiles"); jLabelReactionText.setText(" "); jLabelHelp.setText(" "); jMenuFileSave.setEnabled(false); jButtonSaveReac.setEnabled(false); jButtonSaveComp.setEnabled(false); modelComplexes.clear(); modelComponents.clear(); jMenuAddReact.setEnabled(true); jMenuAddComp.setEnabled(true); jMenuAddShow.setEnabled(false); jMenuFileShowFile.setEnabled(false); final java.io.File f = new java.io.File(addFile); final java.io.File fe = new java.io.File(addFileEle); if(f.exists() || fe.exists()) { this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR)); Thread work = new Thread() {@Override public void run() { update_componentsAdd(); //needed if later trying to edit a reaction if(f.exists()) {addFile_Read();} try{ AddDataElem.elemCompAdd_Update(dbg, FrameAddData.this, addFile, addFileEle, pd.elemComp, elemCompAdd); } catch (AddDataElem.AddDataException ex) {showErr(ex.toString(),0);} modelComps_update(dbg, elemCompAdd, modelComponents); javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() { FrameAddData.this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); }}); //invokeLater(Runnable) }};//new Thread work.start(); //any statements placed below are executed inmediately } }//GEN-LAST:event_jMenuAddShowActionPerformed private void jMenuFileShowFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuFileShowFileActionPerformed jMenuAddShow.doClick(); }//GEN-LAST:event_jMenuFileShowFileActionPerformed private void jMenuFileSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuFileSaveActionPerformed if(jPanelReaction.isShowing()) {jButtonSaveReac.doClick();} else if(jPanelComponent.isShowing()) {jButtonSaveComp.doClick();} }//GEN-LAST:event_jMenuFileSaveActionPerformed private void jMenuFileExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuFileExitActionPerformed closeWindow(); }//GEN-LAST:event_jMenuFileExitActionPerformed private void jMenuHelpHlpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuHelpHlpActionPerformed setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR)); Thread hlp = new Thread() {@Override public void run(){ String[] a = {"DB_Add_data_htm"}; lib.huvud.RunProgr.runProgramInProcess(null,ProgramConf.HELP_JAR,a,false,pc.dbg,pc.pathAPP); try{Thread.sleep(2000);} //show the "wait" cursor for 2 sec catch (InterruptedException e) {} setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); }};//new Thread hlp.start(); }//GEN-LAST:event_jMenuHelpHlpActionPerformed private void jCheckBoxMenuMsgActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxMenuMsgActionPerformed if(pd.msgFrame != null) {pd.msgFrame.setVisible(jCheckBoxMenuMsg.isSelected());} }//GEN-LAST:event_jCheckBoxMenuMsgActionPerformed private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowGainedFocus if(pd.msgFrame != null) {jCheckBoxMenuMsg.setSelected(pd.msgFrame.isVisible());} else {jCheckBoxMenuMsg.setEnabled(false);} }//GEN-LAST:event_formWindowGainedFocus private void jButtonSaveReacActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSaveReacActionPerformed addFile_SaveReaction(); }//GEN-LAST:event_jButtonSaveReacActionPerformed private void jButtonSaveCompActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSaveCompActionPerformed componentSave(); }//GEN-LAST:event_jButtonSaveCompActionPerformed private void formComponentMoved(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentMoved if(!loading) {pd.addDataLocation = this.getLocation();} }//GEN-LAST:event_formComponentMoved private void jTextFieldCommentFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldCommentFocusGained jTextFieldComment.selectAll(); }//GEN-LAST:event_jTextFieldCommentFocusGained private void jTextFieldDeltHKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldDeltHKeyPressed if(evt.getKeyChar() == java.awt.event.KeyEvent.VK_ENTER) { validateDeltH(); } else if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_UP) { jTextFieldLogK.requestFocusInWindow(); } else if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_DOWN) { jTextFieldDeltCp.requestFocusInWindow(); } }//GEN-LAST:event_jTextFieldDeltHKeyPressed private void jTextFieldDeltCpKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldDeltCpKeyPressed if(evt.getKeyChar() == java.awt.event.KeyEvent.VK_ENTER) { validateDeltCp(); } else if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_UP) { jTextFieldDeltH.requestFocusInWindow(); } else if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_DOWN) { jTextFieldComment.requestFocusInWindow(); } }//GEN-LAST:event_jTextFieldDeltCpKeyPressed private void jTextFieldCommentKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldCommentKeyPressed int k = evt.getKeyCode(); if(k == java.awt.event.KeyEvent.VK_UP) { jTextFieldDeltCp.requestFocusInWindow(); } else if(k == java.awt.event.KeyEvent.VK_DOWN) { jTextFieldRef.requestFocusInWindow(); } }//GEN-LAST:event_jTextFieldCommentKeyPressed private void jTextFieldCommentKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldCommentKeyReleased //if(dbg) {System.out.println("--- jTextFieldCommentKeyReleased");} update_newC(); }//GEN-LAST:event_jTextFieldCommentKeyReleased private void jTextFieldDeltHKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldDeltHKeyReleased //if(dbg) {System.out.println("--- jTextFieldDeltHKeyReleased");} update_newC(); }//GEN-LAST:event_jTextFieldDeltHKeyReleased private void jTextFieldDeltCpKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldDeltCpKeyReleased //if(dbg) {System.out.println("--- jTextFieldDeltCpKeyReleased");} update_newC(); }//GEN-LAST:event_jTextFieldDeltCpKeyReleased private void jTextFieldCommentActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldCommentActionPerformed //if(dbg) {System.out.println("--- jTextFieldCommentActionPerformed");} update_newC(); }//GEN-LAST:event_jTextFieldCommentActionPerformed private void jTextFieldCommentFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldCommentFocusLost //if(dbg) {System.out.println("--- jTextFieldCommentFocusLost");} update_newC(); }//GEN-LAST:event_jTextFieldCommentFocusLost private void jTextFieldDeltHKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldDeltHKeyTyped char key = evt.getKeyChar(); if(!isCharOKforNumberInput(key)) {evt.consume();} }//GEN-LAST:event_jTextFieldDeltHKeyTyped private void jTextFieldDeltCpKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldDeltCpKeyTyped char key = evt.getKeyChar(); if(!isCharOKforNumberInput(key)) {evt.consume();} }//GEN-LAST:event_jTextFieldDeltCpKeyTyped private void jTextFieldDeltHActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldDeltHActionPerformed validateDeltH(); }//GEN-LAST:event_jTextFieldDeltHActionPerformed private void jTextFieldDeltCpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldDeltCpActionPerformed validateDeltCp(); }//GEN-LAST:event_jTextFieldDeltCpActionPerformed private void jTextFieldDeltHFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldDeltHFocusGained jTextFieldDeltH.selectAll(); }//GEN-LAST:event_jTextFieldDeltHFocusGained private void jTextFieldDeltCpFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldDeltCpFocusGained jTextFieldDeltCp.selectAll(); }//GEN-LAST:event_jTextFieldDeltCpFocusGained private void jTextFieldDeltHFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldDeltHFocusLost //if(dbg) {System.out.println("--- jTextFieldDeltHFocusLost");} validateDeltH(); update_newC(); }//GEN-LAST:event_jTextFieldDeltHFocusLost private void jTextFieldDeltCpFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldDeltCpFocusLost //if(dbg) {System.out.println("--- jTextFieldDeltCpFocusLost");} validateDeltCp(); update_newC(); }//GEN-LAST:event_jTextFieldDeltCpFocusLost //</editor-fold> //<editor-fold defaultstate="collapsed" desc="methods"> //<editor-fold defaultstate="collapsed" desc="closeWindow()"> private void closeWindow() { System.out.println("---- FrameAddData.closeWindow()"); if(!loading) { if(jPanelReaction.isShowing()) { update_newC(); if(jMenuFileSave.isEnabled()) { if(!newC.isChargeBalanced()) {if(!noChargeBalanceQuestion(newC.name)) {return;}} if(!discardChanges()) {return;} } } else { //jPanelReaction is not showing if(jMenuFileSave.isEnabled()) {if(!discardChanges()) {return;}} } //jPanelReaction showing? // --- check the database for errors java.util.ArrayList<String> arrayList = new java.util.ArrayList<String>(); arrayList.add(addFile); CheckDatabases.CheckDataBasesLists lists = new CheckDatabases.CheckDataBasesLists(); CheckDatabases.checkDatabases(pc.dbg, this, arrayList, null, lists); java.io.File f = new java.io.File(addFile); boolean ok = CheckDatabases.displayDatabaseErrors(pc.dbg, this, pc.progName, f.getName(), lists); if(!ok) { if(dbg) {System.out.println("--- displayDatabaseErrors: NOT OK for file: "+addFile);} return; } // remove un-needed components? removeUnusedComps(); pd.addDataLocation.x = this.getX(); pd.addDataLocation.y = this.getY(); }//if !loading finished = true; //return from "waitFor()" this.notify_All(); this.dispose(); } // closeWindow() //</editor-fold> //<editor-fold defaultstate="collapsed" desc="bringToFront()"> public void bringToFront() { if(this != null) { java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { setVisible(true); if((getExtendedState() & javax.swing.JFrame.ICONIFIED) // minimised? == javax.swing.JFrame.ICONIFIED) { setExtendedState(javax.swing.JFrame.NORMAL); } // if minimized setAlwaysOnTop(true); toFront(); requestFocus(); setAlwaysOnTop(false); } }); } } // bringToFront() //</editor-fold> /** @return true if it is ok to close this window */ public boolean queryClose() { if(dbg) {System.out.println("---- FrameAddData.queryClose()");} return !jMenuFileSave.isEnabled() || discardChanges(); } /** this method will wait for this window to be closed */ public synchronized void waitFor() { while(!finished) { try {wait();} catch (InterruptedException ex) {} } // while } // waitFor() private synchronized void notify_All() { //needed by "waitFor()" notifyAll(); } //<editor-fold defaultstate="collapsed" desc="frameEnable"> /** If <code>false</code> sets the card layout to show files, * and sets background colours to grey; menus are disabled and * a text label shows "please wait". If <code>true</code> then * the window is restored to working state; swithching to some * other card in the layout is done elsewhere. * @param enable */ private void frameEnable(boolean enable) { java.awt.Color clr; if(enable) { clr = new java.awt.Color(255,255,255); } else { clr = new java.awt.Color(215,215,215); } jLabelFiles.setEnabled(enable); jLabelReact.setEnabled(enable); jLabelComps.setEnabled(enable); jTextAreaFiles.setEnabled(enable); jListReact.setEnabled(enable); jListComps.setEnabled(enable); jTextAreaFiles.setBackground(clr); jListReact.setBackground(clr); jListComps.setBackground(clr); jMenuFileShowFile.setEnabled(enable); jMenuFileSave.setEnabled(enable); jMenuAddReact.setEnabled(enable); jMenuAddComp.setEnabled(enable); jMenuAddShow.setEnabled(enable); jLabelReactionText.setText(" "); if(!enable) { cl = (java.awt.CardLayout)getContentPane().getLayout(); cl.show(getContentPane(),"cardFiles"); jLabelHelp.setText("( Please wait ... )"); } else { jLabelHelp.setText(" "); } } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="noChargeBalance Warning/Question"> private void noChargeBalanceWarning(String name) { showErr("The reaction for \""+name+"\""+nl+ "is NOT charge balanced."+nl+nl+ "Please correct either the reaction or"+nl+ "the electric charge of \""+name+"\"",-1); } //noChargeBalanceWarning(name) /** call this method if Complex with "name" is not charge balanced * @param name of the Complex * @return true if the user wants to go ahead ("exit anyway"), even with * a non-charge balanced complex; false if the user cancels the operation * (to adjust the charge balance before proceeding) */ private boolean noChargeBalanceQuestion(String name) { Object[] opt = {"Exit anyway", "Cancel"}; int m = javax.swing.JOptionPane.showOptionDialog(this, "The reaction for \""+name+"\""+nl+ "is NOT charge balanced."+nl+nl+ "Choose \"[Cancel]\" to make corrections.", pc.progName, javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.WARNING_MESSAGE, null, opt, opt[1]); return m == javax.swing.JOptionPane.YES_OPTION; } //</editor-fold> //</editor-fold> //<editor-fold defaultstate="collapsed" desc="addFile_Initialise"> /** If <code>reactionFile</code> does not exist, create a new file with a single * title line. * @param dbg set to true in order to output messages to System.out * @param reactionFile name with path * @return true if the file did not exist and it has been created; * false if the file already exists * @throws FrameAddData.AddDataFrameInternalException */ private static boolean addFile_Initialise(boolean dbg, String reactionFile) throws AddDataFrameInternalException { if(reactionFile == null || reactionFile.length() <=0) { throw new AddDataFrameInternalException("Error: empty file name"); } java.io.File rf = new java.io.File(reactionFile); if(dbg) {System.out.println("-- addFile_Initialise("+rf.getName()+")");} if(rf.exists()) { if(dbg) {System.out.println(" file already exists");} return false; } java.io.Writer w = null; try { w = new java.io.BufferedWriter( new java.io.OutputStreamWriter( new java.io.FileOutputStream(rf),"UTF8")); w.write(Complex.FILE_FIRST_LINE+nl); } catch (java.io.IOException ex) { try{if(w != null) {w.close();}} catch (Exception e) {} throw new AddDataFrameInternalException("Error: "+ex.getMessage()+nl+ " for file \""+reactionFile+"\""); } finally { try{if(w != null) {w.close();}} catch (Exception e) {} } return true; } //addFile_Initialise(file) //</editor-fold> //<editor-fold defaultstate="collapsed" desc="addFile_ComplexAppend"> /** Append a line to <code>reactionFile</code> with a Complex. * @param dbg set to true in order to output messages to System.out * @param reactionFile name with path * @return true if the file did not exist and it has been created; * false if the file already exists * @throws FrameAddData.AddDataFrameInternalException */ private static void addFile_ComplexAppend(boolean dbg, String reactionFile, Complex c) throws AddDataFrameInternalException { if(dbg) {System.out.println("-- addFile_ComplexAppend("+c.name+")");} if(reactionFile == null || reactionFile.length() <=0) { throw new AddDataFrameInternalException("Error: empty file name"); } if(c == null || c.name.length() <=0) { throw new AddDataFrameInternalException("Error: no complex to append"); } java.io.File rf = new java.io.File(reactionFile); if(rf.exists() && (!rf.canWrite() || !rf.setWritable(true))) { throw new AddDataFrameInternalException ("Error: can not write to file"+nl+" \""+reactionFile+"\"."); } java.io.Writer w = null; try { boolean append = true; w = new java.io.BufferedWriter( new java.io.OutputStreamWriter( new java.io.FileOutputStream(rf,append),"UTF8")); w.write(c.toString()+nl); } catch (java.io.IOException ex) { try{if(w != null) {w.close();}} catch (Exception e) {} throw new AddDataFrameInternalException("Error: "+ex.toString()+nl+ " appending complex "+c.name+nl+ " to file \""+reactionFile+"\""); } try{if(w != null) {w.close();}} catch (Exception e) {} } //addFile_ComplexAppend(file, complex) //</editor-fold> //<editor-fold defaultstate="collapsed" desc="addFile_ComplexDelete"> /** Read the file <code>addFile</code> and write a temporary file line by line, * excluding lines with the complex to remove; * delete the original file, rename the temporary file to the original name. * If <code>cDel.name</code> starts with "@" then any line starting with the name, * with or without "@", will be removed. * * @param cDel complex to delete * @throws FrameAddData.AddDataFrameInternalException */ private void addFile_ComplexDelete(Complex cDel) throws AddDataFrameInternalException { if(dbg) {System.out.println("-- addFile_ComplexDelete("+cDel.name+")");} // ---- make some checks if(cDel == null || cDel.name == null || cDel.name.length() <=0) { throw new AddDataFrameInternalException("Error: empty species name"); } if(addFile == null || addFile.length() <=0) { throw new AddDataFrameInternalException("Error: empty file name"); } boolean startsWithAt = false; String cName = cDel.name; if(cName.startsWith("@")) { if(cName.length() <=1) {throw new AddDataFrameInternalException("Error: species name is \"@\" (must contain additional characters)");} startsWithAt = true; cName = cName.substring(1); } if(cName.contains(",")) { throw new AddDataFrameInternalException("Error: species "+cName+" contains a comma (,)"); } java.io.File rf = new java.io.File(addFile); if(!rf.exists() || !rf.canRead()) { String msg = "Error: can not open file"+nl+" \""+addFile+"\""; if(!rf.exists()) {msg = msg +nl+ "(the file does not exist)";} throw new AddDataFrameInternalException(msg); } if(!rf.canWrite() || !rf.setWritable(true)) { throw new AddDataFrameInternalException ("Error: can not write to file"+nl+" \""+addFile+"\""); } // --- before doing the work check that the species name is really there int n; if(startsWithAt) {n = addFile_ComplexFindName(cName,false);} else {n = addFile_ComplexFindName(cName,true);} if(n == 0) { if(dbg) {System.out.println(" "+cName+" not found. No lines to delete");} return; } // --- open input and output files java.io.BufferedReader br; try{br = new java.io.BufferedReader(new java.io.InputStreamReader( new java.io.FileInputStream(rf),"UTF8"));} catch (Exception ex) {throw new AddDataFrameInternalException(ex.toString());} java.io.File tmpF = new java.io.File(addFileTmp); if(dbg) {System.out.println(" copying lines from \""+rf.getName()+"\" to \""+tmpF.getName()+"\"");} boolean ok; if(tmpF.exists()) { if(dbg) {System.out.println(" deleting \""+tmpF.getName()+"\"");} try{ok = tmpF.delete();} catch (Exception ex) {throw new AddDataFrameInternalException(ex.toString());} if(!ok) {throw new AddDataFrameInternalException("Could not delete file:"+nl+"\""+addFileTmp+"\"");} } addFile_Initialise(dbg, addFileTmp); java.io.Writer w; boolean append = true; try { w = new java.io.BufferedWriter( new java.io.OutputStreamWriter( new java.io.FileOutputStream(tmpF,append),"UTF8")); } catch (java.io.IOException ex) {throw new AddDataFrameInternalException(ex.toString());} String line = null, errMsg = null; Complex cRead; try{ while ((line = br.readLine()) != null){ if(line.trim().length() <=0) {continue;} if(line.toUpperCase().startsWith("COMPLEX")) {continue;} cRead = Complex.fromString(line); if(cRead.name.startsWith("@")) {cRead.name = cRead.name.substring(1);} if(Util.nameCompare(cName, cRead.name)) {continue;} w.write(line+nl); w.flush(); } //while } //try catch (java.io.IOException ex) { MsgExceptn.exception(Util.stack2string(ex)); errMsg = ex.toString()+nl+"with file:\""+addFile+"\""; } catch (Complex.ReadComplexException ex) { MsgExceptn.exception(Util.stack2string(ex)); errMsg = ex.toString()+nl+"in line: \""+line+"\""+nl+"in file:\""+addFile+"\""; } finally { if(errMsg != null) {showErr(errMsg,0);} if(dbg) {System.out.println(" closing files");} try {br.close();} catch (java.io.IOException ex) {showErr(ex.toString()+nl+"with file:\""+addFile+"\"",0);} try{w.close();} catch (Exception e) {MsgExceptn.exception(Util.stack2string(e));} } line = null; if(dbg) {System.out.println(" deleting \""+rf.getName()+"\"");} try{ok = rf.delete();} catch (Exception ex) { line = ex.toString()+nl; ok = false; } if(!ok || line != null) { if(line == null) {line = "";} showErr(line+"Could not delete file:"+nl+"\""+addFile+"\"",0); return; } if(dbg) {System.out.println(" renaming \""+tmpF.getName()+"\" to \""+rf.getName()+"\"");} line = null; try{ok = tmpF.renameTo(rf);} catch (Exception ex) { line = ex.toString()+nl; ok = false; } if(!ok || line != null) { if(line == null) {line = "";} showErr(line+"Could not rename file:"+nl+"\""+addFileTmp+"\""+nl+"into: \""+addFile+"\"",0); } } //addFile_ComplexDelete(name) //</editor-fold> //<editor-fold defaultstate="collapsed" desc="addFile_ComplexFind"> /** Is the reaction "<code>c</code>" found in file <code>addFile</code>? * The names of the products are compared taking into account different ways to write * charges so that "Fe+3" is equal to "Fe 3+". Also "CO2" is equivalent to "CO2(aq)". * Note however that names of reactants must match exactly: "Fe+3" is NOT equal * to "Fe 3+" and "H+" is not equal to "H +". Two reactions are equivalent if * they have the same product name and if the reaction is the same, * even if the order of the reactants differs. * For example, <code>A + B = C</code> is equal to <code>B + A = C</code> * <p> * If "<code>c.name</code>" starts with "@" then only the reaction name * is searched, equivalent to: <code>addFile_ComplexFindName(c.name, true)</code>, * that is, it looks for an equivalent name also stating with "@". For example, * "@Fe+2" will match "@Fe 2+" but not "Fe+2" * @param c * @return how many times the given reaction is found; zero if not found * @see FrameAddData#addFile_ComplexFindName addFile_ComplexFindName */ private int addFile_ComplexFind(Complex c) { if(c == null) { MsgExceptn.exception("Error: complex = null in \"addFile_ComplexFind\""); return 0; } Complex cFind; try {cFind = (Complex)c.clone();} catch (CloneNotSupportedException ex) { MsgExceptn.exception("Error: CloneNotSupportedException in \"addFile_ComplexFind\""); return 0; } if(dbg) {System.out.println("-- addFile_ComplexFind("+cFind.name+")");} if(cFind.name == null || cFind.name.length() <= 0) { MsgExceptn.exception("Error: empty complex name in \"addFile_ComplexFind\""); return 0; } if(cFind.name.contains(",")) { MsgExceptn.exception("Error: complex name contains \",\" in \"addFile_ComplexFind\""); return 0; } if(cFind.name.startsWith("@")) { return addFile_ComplexFindName(cFind.name, true); } if(addFile == null || addFile.length() <=0) { MsgExceptn.exception("Error: empty file name in \"addFile_ComplexFind\""); return 0; } java.io.File afF = new java.io.File(addFile); if(!afF.exists()) {if(dbg) {System.out.println(" file \""+afF.getName()+"\" not found");} return 0;} if(!afF.canRead()) { showErr("Error: can not open file"+nl+" \""+addFile+"\".",-1); return 0; } int lineNbr = 0; int fnd = 0; java.io.BufferedReader br = null; Complex cRead; String line = null; try{ br = new java.io.BufferedReader(new java.io.InputStreamReader( new java.io.FileInputStream(afF),"UTF8")); while ((line = br.readLine()) != null){ lineNbr++; if(line.length()<=0 || line.toUpperCase().startsWith("COMPLEX")) {continue;} cRead = Complex.fromString(line); if(Complex.sameNameAndStoichiometry(cFind, cRead)) {fnd++;} } //while } //try catch (java.io.IOException ex) { MsgExceptn.exception(Util.stack2string(ex)); showErr(ex.toString()+nl+"reading line "+lineNbr+" in file:\""+addFile+"\"",0); } catch (Complex.ReadComplexException ex) { MsgExceptn.exception(Util.stack2string(ex)); showErr(ex.toString()+nl+"reading line: \""+line+"\""+nl+" in file:\""+addFile+"\"",0); } finally { if(br != null) { try {br.close();} catch (java.io.IOException ex) {showErr(ex.toString()+nl+"with file:\""+addFile+"\"",0);} } } return fnd; } //addFile_ComplexFind //</editor-fold> //<editor-fold defaultstate="collapsed" desc="addFile_ComplexFindName"> /** Is the species <code>cName</code> found in file <code>addFile</code>? * This takes into account electrical charges. Therefore, "Fe 3+" is equal * to "Fe+3". Note that "I2-" has charge 1-, and "I 2-" has charge 2-. * Also Ca(OH)2(aq) is equal to Ca(OH)2 which is different to Ca(OH)2(s). * In addition CO2 and CO2(g) are different. * @param cName the name of a species * @param exactMatch if <code>false</code> names starting both with or without "@" * will be ok, that is, "@Na+" and "Na+" are considered equal; * if <code>true</code> then the first character counts, that is, "@Cl-" and "Cl-" * are not considered to be the same * @return how many times the given complex name is found; zero if not found * @see FrameAddData#addFile_ComplexFind addFile_ComplexFind */ private int addFile_ComplexFindName(String cName, boolean exactMatch) { if(dbg) {System.out.println("-- addFile_ComplexFindName("+cName+", "+exactMatch+")");} if(cName == null) { MsgExceptn.exception("Error: complex name = null in \"addFile_ComplexFindName\""); return 0; } if(cName.length() <= 0) { MsgExceptn.exception("Error: empty complex name in \"addFile_ComplexFindName\""); return 0; } if(cName.contains(",")) { MsgExceptn.exception("Error: complex name contains \",\" in \"addFile_ComplexFindName\""); return 0; } if(!exactMatch && cName.startsWith("@")) {cName = cName.substring(1);} if(addFile == null || addFile.length() <=0) { MsgExceptn.exception("Error: empty file name in \"addFile_ComplexFindName\""); return 0; } java.io.File afF = new java.io.File(addFile); if(!afF.exists()) {if(dbg) {System.out.println(" file \""+afF.getName()+"\" not found");} return 0;} if(!afF.canRead()) { showErr("Error: can not open file"+nl+" \""+addFile+"\".",-1); return 0; } int lineNbr = 0; int fnd = 0; java.io.BufferedReader br = null; String line = null; try{ br = new java.io.BufferedReader( new java.io.InputStreamReader( new java.io.FileInputStream(afF),"UTF8")); String t; while ((line = br.readLine()) != null){ lineNbr++; if(line.length()<=0 || line.toUpperCase().startsWith("COMPLEX")) {continue;} t = CSVparser.splitLine_1(line); //get the first token from the line if(!exactMatch && t.startsWith("@")) {t = t.substring(1);} if(Util.nameCompare(cName,t)) {fnd++;} } //while } //try catch (java.io.IOException ex) { MsgExceptn.exception(Util.stack2string(ex)); showErr(ex.toString()+nl+"reading line "+lineNbr+" in file:\""+addFile+"\"",0); } catch (CSVparser.CSVdataException ex) { MsgExceptn.exception(Util.stack2string(ex)); showErr(ex.toString()+nl+"reading line: \""+line+"\""+nl+" in file:\""+addFile+"\"",0); } finally { if(br != null) { try{br.close();} catch(java.io.IOException ex) {showErr(ex.toString()+nl+"with file:\""+addFile+"\"",0);} } } return fnd; } //addFile_ComplexFindName //</editor-fold> //<editor-fold defaultstate="collapsed" desc="addFile_Read(name)"> /** Read a text reaction-file and add sorted entries in "modelComplexes". * Erroneous lines are skipped. Reactants with zero coefficients are removed. * Reactions with charge imbalance are indicated with a different text colour */ private void addFile_Read() { if(dbg) {System.out.println("-- addFile_Read(..)");} if(addFile == null || addFile.length() <=0) { MsgExceptn.exception("Error: empty file name in \"addFile_Read\""); return; } java.io.File afF = new java.io.File(addFile); if(dbg) {System.out.println("Reading file \""+afF.getName()+"\"");} if(!afF.exists() || !afF.canRead()) { String msg = "Error: can not open file"+nl+" \""+addFile+"\"."; if(!afF.exists()) {msg = msg +nl+ "(the file does not exist).";} showErr(msg,0); return; } int cmplxNbr = 0; java.io.BufferedReader br = null; try{ br = new java.io.BufferedReader( new java.io.InputStreamReader( new java.io.FileInputStream(afF),"UTF8")); Complex c; java.util.ArrayList<String> items = new java.util.ArrayList<String>(); while(true){ try{c = lib.database.LibDB.getTxtComplex(br);} catch (LibDB.EndOfFileException ex) {break;} catch (LibDB.ReadTxtCmplxException ex) {showErr(ex.getMessage()+nl+"Line discarded!",0);continue;} cmplxNbr++; if(!c.name.startsWith("@")) { int j=0, nTot = Math.min(c.reactionComp.size(),c.reactionCoef.size()); while(j < nTot) { if((c.reactionComp.get(j) != null && c.reactionComp.get(j).length()>0 && Math.abs(c.reactionCoef.get(j)) < 0.0001) || (Math.abs(c.reactionCoef.get(j)) >= 0.0001 && (c.reactionComp.get(j) == null || c.reactionComp.get(j).length() <=0))) { c.reactionComp.remove(j); c.reactionCoef.remove(j); nTot--; continue; } j++; } // while } //if not starts with "@" items.add(c.toString()); } //java.util.Collections.sortReactants(items, String.CASE_INSENSITIVE_ORDER); java.util.Iterator<String> iter = items.iterator(); while(iter.hasNext()) { String cLine = iter.next(); try{c = Complex.fromString(cLine);} catch (Complex.ReadComplexException ex) {c = null; MsgExceptn.exception(ex.getMessage());} if(c == null) {continue;} //c.sortReactants(); final ModelComplexesItem o; if(c.isChargeBalanced()) { o = new ModelComplexesItem(cLine, java.awt.Color.BLACK); } else { o = new ModelComplexesItem(cLine, vermilion); } javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() { modelComplexes.addElement(o); }}); //invokeLater(Runnable) } } catch (Exception ex) {showErr(ex.toString()+nl+"reading line "+cmplxNbr,0);} finally { try{if(br != null) {br.close();}} catch(java.io.IOException ex) {showErr(ex.toString(),0);} } //return; } //addFile_Read(fileName) //</editor-fold> //<editor-fold defaultstate="collapsed" desc="addFile_SaveReaction()"> /** Save the reaction displayed in "jPanelReaction" to file "addFile" */ private void addFile_SaveReaction() { if(dbg) {System.out.println("-- addFile_SaveReaction()");} // ---- make some checks if(!jPanelReaction.isShowing()) { MsgExceptn.exception("Programming error: jPanelReaction is not showing in \"AddFile_SaveReaction()\"."); } if(newC == null || newC.name == null) { MsgExceptn.exception("Programming error: empty \"newC\" in \"AddFile_SaveReaction()\"."); } // -- make some checks if(jTextFieldComplex.getText().length() <=0 || newC.name.length() <=0) { showErr("A name is needed for the complex!",-1); return; } String msg = ""; if(!newC.name.startsWith("@")) { boolean ok = false; int nTot = Math.min(newC.reactionComp.size(),newC.reactionCoef.size()); for(int i=0; i < nTot; i++) { if(newC.reactionComp.get(i) != null && newC.reactionComp.get(i).length() >0 && Math.abs(newC.reactionCoef.get(i)) >= 0.0001) {ok = true; break;} } //for i if(!ok) { showErr("At least one reactant is needed in the reaction"+nl+ "for the formation of the complex \""+newC.name+"\"",-1); return; } for(int i=0; i < nTot; i++) { if(newC.reactionComp.get(i) != null && newC.reactionComp.get(i).length() >0 && Math.abs(newC.reactionCoef.get(i)) < 0.0001) { showErr("The stoichiometric coefficient"+nl+ "for reactant \""+newC.reactionComp.get(i)+"\" may not be zero!",-1); return; } } //for i if(jTextFieldLogK.getText().length() <=0) { showErr("Please: enter a value for the equilibrium constant"+nl+ "for the complex \""+newC.name+"\"",-1); return; } if(!newC.isChargeBalanced()) { noChargeBalanceWarning(newC.name); return; } } //does not start with "@" else { //name starts with "@" msg = "The species name begins with \"@\"."+nl+nl+"This will exclude the "; if(Util.isSolid(newC.name)) {msg = msg + "solid";} else if(Util.isGas(newC.name)) {msg = msg + "gas";} else {msg = msg + "aqueous species";} msg = msg + " \""+newC.name.substring(1) +"\""+nl+"when searching the databases."+nl+nl; } //name starts with "@" // ---- ask for confirmation boolean replaceComplex; if(addFile_ComplexFindName(newC.name,false) > 0) { msg = msg + "Replace existing reaction for \""+ newC.name+"\""+nl+ "with"+nl+ newC.reactionTextWithLogK(25,1); replaceComplex = true; } else { msg = msg + "Add reaction?"+nl+newC.reactionTextWithLogK(25,1)+nl+" "; replaceComplex = false; } if(dbg) {System.out.println("----- "+msg+" [Yes] [No]");} Object[] opt = {"Yes", "Cancel"}; int m = javax.swing.JOptionPane.showOptionDialog(this, msg, pc.progName, javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.WARNING_MESSAGE, null, opt, opt[1]); if(m != javax.swing.JOptionPane.YES_OPTION) {return;} // ---- user confirmed and no errors: go ahead update_newC(); if(replaceComplex) { // the file already exists try {addFile_Initialise(dbg, addFile);} catch (AddDataFrameInternalException ex) { showErr(ex.toString(),0); return; } // To replace a reaction: read the file, write a temp file excluding // the replaced complex, delete the original file, rename the temp file // to the original name. Then append the changed reaction at the end of the new file. try {addFile_ComplexDelete(newC);} catch (AddDataFrameInternalException ex) { showErr(ex.toString(),0); return; } } try {addFile_ComplexAppend(dbg, addFile, newC);} catch (AddDataFrameInternalException ex) { showErr(ex.toString(),0); return; } newC = new Complex(); try {oldNewC = (Complex)newC.clone();} catch (CloneNotSupportedException ex) { MsgExceptn.exception("Error "+ex.toString()+nl+" in Complex.clone()."); oldNewC = null; } updateJPanelReaction(newC); jLabelReaction.setText("New reaction:"); jMenuFileSave.setEnabled(false); jButtonSaveReac.setEnabled(false); jButtonSaveComp.setEnabled(false); // create a list of components if it does not exist try{ AddDataElem.elemCompAdd_Update(dbg, this, addFile, addFileEle, pd.elemComp, elemCompAdd); } catch (AddDataElem.AddDataException ex) { showErr(ex.toString(),0); return; } // update the element file // save changes made in "elemCompAdd" in file "addFileEle" try {AddDataElem.addFileEle_Write(dbg, addFileEle, elemCompAdd);} catch (AddDataElem.AddDataException ex) { showErr(ex.toString(),0); return; } // -- add this database file to the list? addAddFileToList(); //return; } //addFile_SaveReaction() //</editor-fold> //<editor-fold defaultstate="collapsed" desc="addAddFileToList()"> private void addAddFileToList() { //--- check that the name is not already in the list boolean found = false; int n = pd.dataBasesList.size(); for(int j=0; j<n; j++) { if(pd.dataBasesList.get(j).equalsIgnoreCase(addFile)) { found = true; break; } } //--- add new name to list if(!found) { java.io.File f = new java.io.File(addFile); Object[] opt = {"OK", "No, thanks"}; int m = javax.swing.JOptionPane.showOptionDialog(this, "The file \""+f.getName()+"\""+nl+ "will be added to the list"+nl+ "of available databases", pc.progName, javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.QUESTION_MESSAGE, null, opt, opt[0]); if(m != javax.swing.JOptionPane.YES_OPTION) {return;} if(pc.dbg) {System.out.println("---- Adding database: \""+addFile+"\"");} pd.dataBasesList.add(addFile); } } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="componentSave()"> /** Add a component to file "addFileEle" (re-writes the file) */ private void componentSave() { if(dbg) {System.out.println("-- componentSave()");} // ---- make some checks if(!jPanelComponent.isShowing()) { MsgExceptn.exception("Programming error: jPanelComponent is not showing in \"componentSave()\"."); return; } if(jTextFieldCompName.getText() == null || jTextFieldCompName.getText().trim().length() <=0) {return;} String newComp = jTextFieldCompName.getText().trim(); if(jLabelLinked.getText().length() <=10 || !jLabelLinked.getText().startsWith("Linked to:")) { showErr("Please: link component \""+newComp+"\""+nl+"to some element(s)",-1); return; } String linkedTo = jLabelLinked.getText().substring(10).trim(); String descr = jTextFieldCompDescr.getText().trim(); boolean ok; try{ ok = AddDataElem.addFileEle_ComponentSave(dbg, this, newComp, linkedTo, descr, addFile, addFileEle, pd.elemComp, elemCompAdd); } catch (AddDataElem.AddDataException ex) { showErr(ex.toString(),0); ok = false; } if(!ok) {return;} // - - no problems: the end jMenuFileSave.setEnabled(false); jButtonSaveReac.setEnabled(false); jButtonSaveComp.setEnabled(false); // focus on "C" for(int i=0; i < jComboBoxElems.getItemCount(); i++) { if(jComboBoxElems.getItemAt(i).equals("C")) { jComboBoxElems.setSelectedIndex(i); break; } } oldComponentName = ""; oldComponentDescr = ""; oldComponentLinked = ""; jLabelLinked.setText(""); jTextFieldCompName.setText(""); jTextFieldCompDescr.setText(""); jLabelComp.setText("New component:"); jButtonLink.setText("Link component to element"); // -- add this database file to the list? addAddFileToList(); // return; } //componentSave() //</editor-fold> //<editor-fold defaultstate="collapsed" desc="discardChanges()"> /** Ask the user if to discard changes or to continue * @return true if the user wants to discard changes; false otherwise */ private boolean discardChanges() { bringToFront(); if(jPanelReaction.isShowing() && newC != null && oldNewC != null && newC.isEqualTo(oldNewC)) {return true;} String msg = "Save changes?"+nl+nl+ "Press [Cancel] and then [Save] to keep changes;"+nl+ "or choose [Discard] to reject changes."; Object[] opt = {"Discard", "Cancel"}; int m = javax.swing.JOptionPane.showOptionDialog(this,msg, "Add Data to "+pc.progName, javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.WARNING_MESSAGE, null, opt, opt[1]); if(m != javax.swing.JOptionPane.YES_OPTION) { return false; //Cancel = do Not discard changes } jMenuFileSave.setEnabled(false); jButtonSaveReac.setEnabled(false); jButtonSaveComp.setEnabled(false); return true; // OK/Yes = discard changes } //discardChanges() //</editor-fold> //<editor-fold defaultstate="collapsed" desc="getAddFileName"> /** Get a database file name from the uer. If it is an existing file, check * that it is ok. * @return false if there is an error or if the user cancels the process */ private boolean getAddFileName() { if(dbg) {System.out.println("-- getAddFileName()");} // -- ask for the file name boolean fileMustExist = false; System.out.println("querying for a file name..."); String newFile = Util.getOpenFileName(this, pc.progName, fileMustExist, "Open or Create a file: Enter a file name", 3, "New-Data.txt", pd.pathAddData.toString()); if(newFile == null || newFile.length() <= 0) { if(dbg) {System.out.println("No \"add\" file name given.");} return false; } // -- get full path and get a temporary file name // save variables in case the user cancels or there is an error String f01 = addFile; String f02 = addFileTmp; addFile = newFile; java.io.File f = new java.io.File(addFile); String fn; try {fn = f.getCanonicalPath();} catch (java.io.IOException ex) {fn = null;} if (fn == null) {try {fn = f.getAbsolutePath();} catch (Exception ex) {fn = f.getPath();}} f = new java.io.File(fn); pd.pathAddData.replace(0, pd.pathAddData.length(), f.getParent()); String dir = pd.pathAddData.toString(); if(dir.endsWith(SLASH)) {dir = dir.substring(0, dir.length()-1);} addFile = dir + SLASH + f.getName(); String ext = Div.getFileNameExtension(addFile); if(ext == null || ext.length() <=0) {ext = "txt";} addFileTmp = Div.getFileNameWithoutExtension(addFile)+"-"+ext+".tmp"; // -- element file name String f03 = addFileEle; // if reactants (components) are not found in the element file, // they will be added if found in "pd.elemComp" addFileEle = AddDataElem.elemFileCheck(dbg, this, addFile, pd.elemComp); if(addFileEle == null) { if(dbg) {System.out.println("AddDataElem.elemFileCheck("+f.getName()+") returns \"null\".");} addFile = f01; addFileTmp = f02; addFileEle = f03; return false; } // -- check the add file if(f.exists()) { // --- check the database for errors java.util.ArrayList<String> arrayList = new java.util.ArrayList<String>(); arrayList.add(addFile); CheckDatabases.CheckDataBasesLists lists = new CheckDatabases.CheckDataBasesLists(); CheckDatabases.checkDatabases(pc.dbg, this, arrayList, null, lists); boolean ok = CheckDatabases.displayDatabaseErrors(pc.dbg, this, pc.progName, f.getName(), lists); if(!ok) { if(dbg) {System.out.println("--- displayDatabaseErrors: NOT OK for file: "+addFile);} addFile = f01; addFileTmp = f02; addFileEle = f03; return false; } } //if f.exists() System.out.println("add-file = "+addFile); jTextAreaFiles.setText(addFile+nl+addFileEle); return true; } //getAddFileName() //</editor-fold> //<editor-fold defaultstate="collapsed" desc="isCharOKforNumberInput"> /** @param key a character * @return true if the character is ok, that is, it is either a number, * or a dot, or a minus sign, or an "E" (such as in "2.5e-6") */ private boolean isCharOKforNumberInput(char key) { return Character.isDigit(key) || key == '-' || key == '+' || key == '.' || key == 'E' || key == 'e'; } // isCharOKforNumberInput(char) //</editor-fold> //<editor-fold defaultstate="collapsed" desc="isComponentNeeded(reactant)"> /** is a component (reactant) found among the reactions listed in jListReact * (that is, in file addFile)? * @param reactant the component's name * @return true if <code>reactant</code> is not null and not empty and it is found * in the reactions listed in <code>modelComplexes</code>; false otherwise */ private boolean isComponentNeeded(String reactant) { if(dbg) {System.out.println("-- isComponentNeeded("+reactant+")");} if(reactant == null || reactant.length() <=0) {return false;} String line = null; for(int i=0; i < modelComplexes.size(); i++) { Object o = modelComplexes.get(i); if(o != null) {line = o.toString();} if(line != null && line.length() >0) { Complex c = null; try{c = Complex.fromString(line);} catch (Complex.ReadComplexException ex) {MsgExceptn.exception(ex.getMessage());} if(c != null && c.name != null && c.name.length() >0) { int nTot = Math.min(c.reactionComp.size(),c.reactionCoef.size()); for(int j=0; j < nTot; j++) { if(c.reactionComp.get(j) == null || c.reactionComp.get(j).length() <=0 || Math.abs(c.reactionCoef.get(j)) < 0.0001) {continue;} if(reactant.equals(c.reactionComp.get(j))) {return true;} }//for j } } //if line != null } //for i in modelComplexes return false; } //isComponentNeeded(reactant) //</editor-fold> //<editor-fold defaultstate="collapsed" desc="jListComps_click()"> private void jListComps_click() { if(dbg) {System.out.println("-- jListComps_click()");} int i = jListComps.getSelectedIndex(); if(i >= 0 && i < modelComponents.getSize()) { String dataLine = modelComponents.get(i).toString(); if(dataLine != null && dataLine.length() >0) { jMenuAddComp.doClick(); try{ //CSVparser.splitLine will remove enclosing quotes java.util.ArrayList<String> aL = CSVparser.splitLine_N(dataLine, 3); jTextFieldCompName.setText(aL.get(0)); jTextFieldCompDescr.setText(aL.get(1)); if(aL.get(2).length() >9 && aL.get(2).toLowerCase().startsWith("linked to")) { aL.set(2, "Linked to"+aL.get(2).substring(9)); jLabelLinked.setText(aL.get(2)); } else { jLabelLinked.setText(""); jMenuFileSave.setEnabled(true); jButtonSaveReac.setEnabled(true); jButtonSaveComp.setEnabled(true); } oldComponentName = jTextFieldCompName.getText(); oldComponentDescr = jTextFieldCompDescr.getText(); oldComponentLinked = jLabelLinked.getText(); jLabelComp.setText("Edit component:"); } catch (CSVparser.CSVdataException ex) { showErr(ex.toString(),0); } } } } //jListComps_click() //</editor-fold> //<editor-fold defaultstate="collapsed" desc="jListReact_click()"> private void jListReact_click() { if(dbg) {System.out.println(nl+"--- jListReact_click()");} int i = jListReact.getSelectedIndex(); if(i < 0 || i >= modelComplexes.getSize()) {jMenuAddReact.doClick();} else { String dataLine = null; Object value = modelComplexes.get(i); if(value != null) { dataLine = value.toString(); } //value != null if(dataLine != null && dataLine.length() >0) { Complex c = null; try{c = Complex.fromString(dataLine);} catch (Complex.ReadComplexException ex) {MsgExceptn.exception(ex.getMessage());} if(c != null) { //check that all reactants for this reaction are in the list of available components boolean fnd; int nTot = Math.min(c.reactionComp.size(), c.reactionCoef.size()); for(int j=0; j < nTot; j++) { if(c.reactionComp.get(j) == null || c.reactionComp.get(j).length() <=0 || Math.abs(c.reactionCoef.get(j)) < 0.0001) {continue;} fnd = false; for(String t : componentsAdd) { if(t.equals(c.reactionComp.get(j))) {fnd = true; break;} } //for if(!fnd) { java.io.File eF = new java.io.File(addFileEle); showErr("Error: component \""+c.reactionComp.get(j)+"\""+nl+ "for species \""+c.name+"\""+nl+ "can not be found."+nl+nl+ "You must save the component first.",-1); jMenuAddComp.doClick(); try{ jTextFieldCompName.setText(c.reactionComp.get(j)); jTextFieldCompDescr.setText(""); jLabelLinked.setText(""); oldComponentName = ""; oldComponentDescr = ""; oldComponentLinked = ""; jLabelComp.setText("Edit component:"); jMenuFileSave.setEnabled(true); jButtonSaveReac.setEnabled(true); jButtonSaveReac.setEnabled(true); } catch (Exception ex) {MsgExceptn.exception(ex.toString());} return; }//if !fnd }//for j if(c.reactionComp.size() > boxes.size()) { javax.swing.JOptionPane.showMessageDialog(this, "The reaction for \""+c.name+"\" can not be edited here"+nl+ "because it has more than "+boxes.size()+" reactants."+nl+ "Please use a text editor to change this reaction.", pc.progName, javax.swing.JOptionPane.INFORMATION_MESSAGE); return; } jMenuAddReact.doClick(); newC = c; try{oldNewC = (Complex)newC.clone();} catch (CloneNotSupportedException ex) { MsgExceptn.exception("Error "+ex.toString()+nl+" in Complex.clone()."); oldNewC = null; } jLabelReaction.setText("Edit reaction:"); updateJPanelReaction(newC); } // if c != null } //if dataLine != null } } //jListReact_click() //</editor-fold> //<editor-fold defaultstate="collapsed" desc="jListReact_Del()"> private void jListReact_Del() { if(dbg) {System.out.println("-- jListReact_Del()");} int i = jListReact.getSelectedIndex(); newC = null; if(i >= 0 && i < modelComplexes.getSize()) { String dataLine = null; Object value = modelComplexes.get(i); if(value != null) {dataLine = value.toString();} if(dataLine != null && dataLine.length() >0) { try{newC = Complex.fromString(dataLine);} catch (Complex.ReadComplexException ex) {MsgExceptn.exception(ex.getMessage());} } if(newC == null || newC.name.length() <=0) { showErr("Error: empty reaction",0); return; } String cName; if(newC.name.startsWith("@")) {cName = newC.name.substring(1);} else {cName = newC.name;} String msg = "Delete "+cName+" ?"; int n = addFile_ComplexFindName(cName, false); Object[] opt = {"Yes", "Cancel"}; int m = javax.swing.JOptionPane.showOptionDialog(this, msg, pc.progName, javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.WARNING_MESSAGE, null, opt, opt[1]); if(m != javax.swing.JOptionPane.YES_OPTION) {return;} try{addFile_ComplexDelete(newC);} catch (AddDataFrameInternalException ex) {showErr(ex.toString(),0);} // -- remove components not needed eanymore removeUnusedComps(); } // -- update the window contents jMenuAddShow.setEnabled(true); jMenuAddShow.doClick(); } //jListReact_Del() //</editor-fold> //<editor-fold defaultstate="collapsed" desc="jListComps_Del()"> private void jListComps_Del() { if(dbg) {System.out.println("-- jListComps_Del()");} int i = jListComps.getSelectedIndex(); if(i < 0 || i >= modelComponents.getSize()) {return;} //String dataLine = modelComponents.get(i).toString(); String dataLine = modelComponents.get(i).toString(); if(dataLine == null || dataLine.length() <=0) {return;} java.util.ArrayList<String> aL; try{ aL = CSVparser.splitLine_N(dataLine, 3); if(aL.get(2).length() >10 && aL.get(2).toLowerCase().startsWith("linked to:")) { aL.set(2, "Linked to:"+aL.get(2).substring(10)); } } catch (CSVparser.CSVdataException ex) { showErr(ex.toString(),0); return; } boolean needed = false; try{ needed = isComponentNeeded(aL.get(0)); } catch (Exception ex) {} if(needed) { showErr("It is not possible to delete"+nl+" "+aL.get(0)+nl+ "because it is used in"+nl+"one or more reactions.",2); return; } Object[] opt = {"Yes", "Cancel"}; int m = javax.swing.JOptionPane.showOptionDialog(this, "Delete "+aL.get(0)+" ?", pc.progName, javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.WARNING_MESSAGE, null, opt, opt[1]); if(m != javax.swing.JOptionPane.YES_OPTION) {return;} if(aL.get(2).length() <=10 || !aL.get(2).startsWith("Linked to:")) { System.out.println("Warning - deleting component \""+aL.get(0)+"\":"+nl+ " but it is not linked to any chemical element"); } try{AddDataElem.addFileEle_ComponentDelete(dbg,aL.get(0),addFileEle,elemCompAdd);} catch (AddDataElem.AddDataException ex) { showErr(ex.toString(),0); } // the list elemCompAdd has been updated, but componentsAdd not for(i=0;i<componentsAdd.size();i++) { if(componentsAdd.get(i).equals(aL.get(0))) { componentsAdd.remove(i); break; // assume there are no duplicate entries } } //for i // -- update window frame jMenuAddShow.setEnabled(true); jMenuAddShow.doClick(); } //jListComps_Del() //</editor-fold> //<editor-fold defaultstate="collapsed" desc="modelComps_update()"> /** Sort the data in "eleCmpAdd" and add the sorted lines to "modelComponentsLocal" * @param dbg if true output some information to System.out * @param eleCmpAdd (see <code>elemCompAdd</code> below) * @param modelComponentsLocal * @see FrameAddData#elemCompAdd elemCompAdd * @see LibDB#readElemFileText(java.io.File, java.util.ArrayList) readElemFileText * @see AddDataElem#elemCompAdd_Update(boolean, java.awt.Component, java.lang.String, java.lang.String, java.util.ArrayList, java.util.ArrayList) elemCompAdd_Update */ private static void modelComps_update(boolean dbg, java.util.ArrayList<String[]> eleCmpAdd, final javax.swing.DefaultListModel<String> modelComponentsLocal) { // final javax.swing.DefaultListModel modelComponentsLocal) { // java 1.6 if(dbg) {System.out.println("-- modelComps_update(..)");} if(modelComponentsLocal == null) { MsgExceptn.exception("Programming error: model = null in \"modelComps_update\""); return; } if(eleCmpAdd == null) { MsgExceptn.exception("Programming error: eleCmpAdd = null in \"modelComps_update\""); return; } if(eleCmpAdd.size() <= 0) { if(dbg) {System.out.println("Empty eleCmpAdd in \"modelComps_update\"");} return; } javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {modelComponentsLocal.clear();}}); java.util.ArrayList<String> items = new java.util.ArrayList<String>(eleCmpAdd.size()); String compName; boolean fnd; for(int i = 0; i < eleCmpAdd.size(); i++) { compName = Complex.encloseInQuotes(eleCmpAdd.get(i)[1]); fnd = false; if(!items.isEmpty()) { for(int k =0; k < items.size(); k++) { if(items.get(k).startsWith(compName)) { fnd = true; String n = items.get(k)+", "+Complex.encloseInQuotes(eleCmpAdd.get(i)[0]); items.set(k, n); break; } }//for k }//if items !empty if(!fnd) { if(eleCmpAdd.get(i)[2].length() >0) { compName = compName + "; " + Complex.encloseInQuotes(eleCmpAdd.get(i)[2].trim()); } else { //no description compName = compName + ";"; } if(!eleCmpAdd.get(i)[0].equals("XX")) { compName = compName + "; linked to: " + Complex.encloseInQuotes(eleCmpAdd.get(i)[0]); } else { compName = compName + ";"; } items.add(compName); } //if !fnd }//for i // sortReactants the list alphabetically and update the "model" java.util.Collections.sort(items,String.CASE_INSENSITIVE_ORDER); java.util.Iterator<String> iter = items.iterator(); while(iter.hasNext()) { final String o = iter.next(); javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() { modelComponentsLocal.addElement(o); }}); //invokeLater(Runnable) } //while // return; } //modelComps_update //</editor-fold> //<editor-fold defaultstate="collapsed" desc="rearrangeReaction"> /** Move reactants towards the upper left corner, so that there is no empty * space between reactants */ private void rearrangeReaction() { if(dbg) {System.out.println("-- rearrangeReaction()");} // this method does nothing unless // -the user creates a "hole" by emptying a combo box in the middle of the reaction, or // -a new reactant is added in a combo box towards the end of the list, leaving empty // empty space between // if so, the reactants are moved so tha empty space is at the end // // -- keep track of focus owner (fo) javax.swing.JComboBox<String> jcb_i, jcb_j; // javax.swing.JComboBox jcb_i, jcb_j; // java 1.6 int fo = -1; for(int i=0; i < boxes.size(); i++) { jcb_i = boxes.get(i); if(jcb_i.isFocusOwner()) {fo = i; break;} } boolean good = true; do { loop_i: for(int i=0; i < boxes.size(); i++) { jcb_i = boxes.get(i); // is this an empty reactant? if(jcb_i.getSelectedIndex() <=0 || texts[i].getText().length() <=0) { good = true; for(int j=i+1; j<boxes.size(); j++) { jcb_j = boxes.get(j); // is this reactant not empty? if(jcb_j.getSelectedIndex() >0 && texts[j].getText().length() >0) { rearranging = true; jcb_i.setSelectedIndex(jcb_j.getSelectedIndex()); texts[i].setText(texts[j].getText()); if(fo >=0) {fo = Math.min(fo, i);} //change the focus owner? jcb_j.setSelectedIndex(0); texts[j].setText(""); rearranging = false; good = false; break loop_i; //start all over }//if j-box not empty boxes.set(j, jcb_j); }//for j }//if i-box empty boxes.set(i, jcb_i); }//for i } while (!good); //set focus to the new focus owner if(fo >=0) { jcb_i = boxes.get(fo); jcb_i.requestFocusInWindow(); boxes.set(fo, jcb_i); } } //rearrangeReaction() //</editor-fold> //<editor-fold defaultstate="collapsed" desc="removeUnusedComps()"> /** Check that all reactants in "elemCompAdd" are used in "addFile"; * and if not ask the user if they should be removed. */ private synchronized void removeUnusedComps() { // ---- remove from "elemCompAdd" any components that are not // present in any of the reactions in file "addFile" if(dbg) {System.out.println("-- removeUnusedComps()");} if(addFile == null || addFile.length() <=0) { MsgExceptn.exception("Error: empty file name in \"addFile_Read\""); return; } java.io.File afF = new java.io.File(addFile); if(dbg) {System.out.println(" reading file \""+afF.getName()+"\"");} if(!afF.exists()) { if(dbg) {System.out.println(" file: \""+afF.getName()+"\" does not exist");} return; } if(!afF.canRead()) { showErr("Error: can not open file"+nl+" \""+addFile+"\".",-1); return; } int lineNbr = 0; java.io.BufferedReader br = null; // ---- Array "found" keeps track of which reactants in "elemCompAdd" are found in "addFile" // The two lists, "found" and "elemCompAdd", need to be synchronized boolean[] found = new boolean[elemCompAdd.size()]; for(int i=0; i < elemCompAdd.size(); i++) { found[i] = (elemCompAdd.get(i)[1].equals("H+") || elemCompAdd.get(i)[1].equals("e-") || elemCompAdd.get(i)[1].equals("H2O")); } try{ br = new java.io.BufferedReader( new java.io.InputStreamReader( new java.io.FileInputStream(afF),"UTF8")); Complex c; while (true){ lineNbr++; try{c = lib.database.LibDB.getTxtComplex(br);} catch (LibDB.EndOfFileException ex) {break;} catch (LibDB.ReadTxtCmplxException ex) { String msg = ex.toString()+nl+"reading complex "+lineNbr+nl+"in file: \""+addFile+"\""; MsgExceptn.exception("Error "+msg+nl+" Complex discarded!"); continue; } if(c.name.startsWith("@")) {continue;} int nTot = Math.min(c.reactionComp.size(), c.reactionCoef.size()); int j = 0; while(j < nTot) { if((c.reactionComp.get(j) != null && c.reactionComp.get(j).length()<=0) || Math.abs(c.reactionCoef.get(j)) < 0.0001) { c.reactionComp.remove(j); c.reactionCoef.remove(j); nTot--; continue; } // is this reactant in the list? for(int i = 0; i < elemCompAdd.size(); i++) { if(c.reactionComp.get(j).equals(elemCompAdd.get(i)[1])) { found[i] = true; //can not break: one must go through all "elemCompAdd" because // some reactants will be listed with two elements // (CN- will occur twice under "N" and "C") //break; } } //for i j++; } // while } //while } //try catch (Exception ex) { MsgExceptn.msg(ex.getMessage()+nl+"reading line "+lineNbr); } finally { try{if(br != null) {br.close();}} catch(java.io.IOException ex) {showErr(ex.toString(),0);} } //---------------------------- //-- remove unused components? javax.swing.DefaultListModel<String> aModel = new javax.swing.DefaultListModel<>(); // javax.swing.DefaultListModel aModel = new javax.swing.DefaultListModel(); // java 1.6 boolean there; for(int i =0; i < elemCompAdd.size(); i++) { if(!found[i]) { there = false; for(int j =0; j < aModel.size(); j++) { if(aModel.get(j).equals(elemCompAdd.get(i)[1])) {there = true; break;} } //for j if(!there) {aModel.addElement(elemCompAdd.get(i)[1]);} } //if !found }//for i if(aModel.size() <= 0) {return;} java.io.File afE = new java.io.File(addFileEle); String msg = "<html>The following reactant"; if(aModel.size() > 1) {msg = msg+"s";} msg = msg+"<br>in file \""+afE.getName()+"\"<br>"; if(aModel.size() > 1) {msg = msg+"are";} else {msg = msg+"is";} msg = msg+" not used. &nbsp; Remove "; if(aModel.size() > 1) {msg = msg+"them";} else {msg = msg+"it";} msg = msg+"?<br>&nbsp;</html>"; if(!CheckDatabases.showListDialog(this, pc.progName, msg, "Remove", "Keep", aModel)) {return;} if(dbg) {System.out.println(" removing unused components");} int i = elemCompAdd.size() -1; while(true) { for(int j=0; j < aModel.size(); j++) { if(aModel.get(j).equals(elemCompAdd.get(i)[1])) {elemCompAdd.remove(i); break;} } i--; if(i <= 0) {break;} } //while //-- save changes try {AddDataElem.addFileEle_Write(dbg, addFileEle, elemCompAdd);} catch (AddDataElem.AddDataException ex) {showErr(ex.toString(),0);} //return; } //removeUnusedComps() //</editor-fold> //<editor-fold defaultstate="collapsed" desc="update_componentsAdd()"> /** All known reactants are added into the array list "componentsAdd". */ private void update_componentsAdd() { if(dbg) {System.out.println("-- update_componentsAdd()");} // make a local copy of the database-list java.util.ArrayList<String> dataBasesListLocal = new java.util.ArrayList<String>(pd.dataBasesList); // include "addFile" at the end of the list // (check that the name is not already in the list) int n = dataBasesListLocal.size(); boolean found = false; for(int j=0; j<n; j++) { if(dataBasesListLocal.get(j).equalsIgnoreCase(addFile)) {found = true; break;} } if(!found) {dataBasesListLocal.add(addFile);} // read components-elements java.util.ArrayList<String[]> arrL = new java.util.ArrayList<String[]>(); LibDB.getElements(this, pc.dbg, dataBasesListLocal, arrL); componentsAdd.clear(); for(int i = 0; i < arrL.size(); i++) { componentsAdd.add(arrL.get(i)[1]); } //return; } //update_componentsAdd() //</editor-fold> //<editor-fold defaultstate="collapsed" desc="updateJPanelReaction(Complex)"> /** Show a Complex data in the jPanelReaction */ private void updateJPanelReaction(Complex c) { if(dbg) {System.out.println("-- updateJPanelReaction("+c.name+")");} int nTot = Math.min(c.reactionComp.size(),c.reactionCoef.size()); if(nTot > boxes.size()) { System.out.println("updateJPanelReaction("+c.name+"): too many reactants (>"+boxes.size()+"); quitting."); } editingReaction = true; // --- update the combo boxes update_componentsAdd(); for(int i=0; i<boxes.size();i++){ java.util.Collections.sort(componentsAdd, String.CASE_INSENSITIVE_ORDER); javax.swing.JComboBox<String> jcb = boxes.get(i); // javax.swing.JComboBox jcb = boxes.get(i); // java 1.6 jcb.removeAllItems(); jcb.addItem(""); jcb.addItem("H+"); jcb.addItem("e-"); jcb.addItem("H2O"); for(String t : componentsAdd) { if(!t.equals("H+") && !t.equals("e-") && !t.equals("H2O")) { jcb.addItem(t); } } //for boxes.set(i, jcb); } for(javax.swing.JTextField tf : texts) {tf.setText("");} // --- display the complex in the pannel jTextFieldComplex.setText(c.name); if(c.constant != Complex.EMPTY) { jTextFieldLogK.setText(Util.formatNumAsInt(c.constant)); } else {jTextFieldLogK.setText("");} double w; if(c.analytic || c.lookUp) { // analytic equation or lookUp table jTextFieldDeltH.setText(""); jTextFieldDeltH.setEnabled(false); jLabelKJmol.setText(""); jTextFieldDeltCp.setText(""); jTextFieldDeltCp.setEnabled(false); jLabelJKmol.setText(""); jLabelNote.setVisible(true); if(c.lookUp) {jLabelNote.setText("<html><b>Note:</b> logK values at different<br>temperatures are given<br>in a look-up table.</html>");} else {jLabelNote.setText("<html><b>Note:</b> Temperature variation<br> of logK uses a power-series<br>expression.</html>");} } else { // delta-H and delta-Cp jLabelKJmol.setText("kJ/mol"); jLabelJKmol.setText("J/(K mol)"); jTextFieldDeltH.setEnabled(true); jTextFieldDeltCp.setEnabled(true); jLabelNote.setVisible(false); w = c.getDeltaH(); if(w != Complex.EMPTY) { jTextFieldDeltH.setText(Util.formatNumAsInt(w)); } else {jTextFieldDeltH.setText("");} w = c.getDeltaCp(); if(w != Complex.EMPTY) { jTextFieldDeltCp.setText(Util.formatNumAsInt(w)); } else {jTextFieldDeltCp.setText("");} } jTextFieldComment.setText(c.comment); jTextFieldRef.setText(c.reference); int fnd; for(int i = 0; i < nTot; i++) { javax.swing.JComboBox<String> jcb = boxes.get(i); // javax.swing.JComboBox jcb = boxes.get(i); // java 1.6 if(c.reactionComp.get(i) != null && c.reactionComp.get(i).length() >0) { fnd = -1; for(int j=0; j < jcb.getItemCount(); j++) { if(c.reactionComp.get(i).equals(jcb.getItemAt(j))) {fnd = j; break;} } //for j if(fnd > -1) { jcb.setSelectedIndex(fnd); if(Math.abs(c.reactionCoef.get(i)) >= 0.001) { texts[i].setText(Util.formatNumAsInt(c.reactionCoef.get(i))); } else {texts[i].setText("1");} } else { MsgExceptn.exception("Programming error? Component "+c.reactionComp.get(i)+nl+"not found in combo box"); jcb.setSelectedIndex(0); texts[i].setText(""); }//if fnd } else { jcb.setSelectedIndex(0); texts[i].setText(""); } boxes.set(i, jcb); } //for i if(!c.isChargeBalanced()) { jLabelCharge.setText("<html>Reaction is <b>NOT</b> charge balanced</html>"); jLabelCharge.setForeground(vermilion); jMenuFileSave.setEnabled(true); jButtonSaveReac.setEnabled(true); jButtonSaveComp.setEnabled(true); } else { jLabelCharge.setText("<html>Reaction is charge balanced</html>"); jLabelCharge.setForeground(java.awt.Color.BLACK); } editingReaction = false; rearrangeReaction(); } //updateJPanelReaction(c) //</editor-fold> //<editor-fold defaultstate="collapsed" desc="update_newC()"> /** Reads the contents of "jPanelReaction" and stores it in complex "newC". * If a change is detected the [Save] button is enabled */ private synchronized void update_newC() { //if(dbg) {System.out.println("-- update_newC()");} if(loading || editingReaction || !jPanelReaction.isShowing()) {return;} if(newC == null) {newC = new Complex();} newC.name = jTextFieldComplex.getText(); if(!jTextFieldLogK.getText().equals("")) { try {newC.constant = Double.parseDouble(jTextFieldLogK.getText());} catch (NumberFormatException ex) { //System.err.println("Error reading double from \""+jTextFieldLogK.getText()+"\""); newC.constant = Complex.EMPTY; } } else {newC.constant = Complex.EMPTY;} if(!newC.analytic && !newC.lookUp) { double deltaH, deltaCp; if(!jTextFieldDeltH.getText().equals("")) { try {deltaH = Double.parseDouble(jTextFieldDeltH.getText());} catch (NumberFormatException ex) { //System.err.println("Error reading double from \""+jTextFieldLogK.getText()+"\""); deltaH = Complex.EMPTY; } } else {deltaH = Complex.EMPTY;} if(!jTextFieldDeltCp.getText().equals("")) { try {deltaCp = Double.parseDouble(jTextFieldDeltCp.getText());} catch (NumberFormatException ex) { //System.err.println("Error reading double from \""+jTextFieldLogK.getText()+"\""); deltaCp = Complex.EMPTY; } } else {deltaCp = Complex.EMPTY;} newC.a = Complex.deltaToA(newC.constant, deltaH, deltaCp); newC.tMax = 25.; newC.pMax = 1.; if(deltaH != Complex.EMPTY) { newC.tMax = 100.; if(deltaCp != Complex.EMPTY) {newC.tMax = 300.; newC.pMax = 85.9;} // pSat(300) = 85.9 } } // if not analytic or lookUp String txt; newC.reactionComp.clear(); newC.reactionCoef.clear(); for (int i=0; i < boxes.size(); i++) { javax.swing.JComboBox<String> jcb = boxes.get(i); // javax.swing.JComboBox jcb = boxes.get(i); // java 1.6 txt = jcb.getSelectedItem().toString(); if(txt == null || txt.trim().length() <=0) {continue;} newC.reactionComp.add(txt); try {newC.reactionCoef.add(Double.parseDouble(texts[i].getText()));} catch (NumberFormatException ex) { //System.err.println("Error reading double from \""+texts[i].getText()+"\""); newC.reactionComp.remove(newC.reactionComp.size()-1); } }//for i newC.reference = jTextFieldRef.getText(); newC.comment = jTextFieldComment.getText(); //newC.comment = ""; boolean ok = newC.isChargeBalanced(); // if there has been a change: enable the Save button if(oldNewC != null && newC.isEqualTo(oldNewC) && ok) { //no changes? jMenuFileSave.setEnabled(false); jButtonSaveReac.setEnabled(false); } else { jMenuFileSave.setEnabled(true); jButtonSaveReac.setEnabled(true); } if(newC.name != null && newC.name.length() >0) { if(ok) { jLabelCharge.setText("<html>Reaction is charge balanced</html>"); jLabelCharge.setForeground(java.awt.Color.BLACK); } else { jLabelCharge.setText("<html>Reaction is <b>NOT</b> charge balanced</html>"); jLabelCharge.setForeground(vermilion); } } else { jLabelCharge.setText(" "); } } //update_newC() //</editor-fold> //<editor-fold defaultstate="collapsed" desc="validateReactionCoeff"> private synchronized void validateReactionCoeff(int i) { if(loading || rearranging) {return;} if(i < 0 || i >= texts.length) {return;} String t = texts[i].getText(); if(t.length() <= 0) {return;} double w; try {w = Double.parseDouble(t); w = Math.min(1000,Math.max(w,-1000));} catch (NumberFormatException nfe) { texts[i].setText(""); System.out.println("Error reading reaction coefficient "+i+" from text \""+t+"\""+nl+ " "+nfe.toString()); return; } if(Math.abs(w) > 999) { if(w>0) {w = 999;} else {w = -999;} texts[i].setText(Util.formatNumAsInt(w)); javax.swing.JOptionPane.showMessageDialog(this, "The reaction coefficient is outside \"reasonable\" range", pc.progName, javax.swing.JOptionPane.ERROR_MESSAGE); return; } if(Math.abs(w) < 0.001) {w = 0;} texts[i].setText(Util.formatNumAsInt(w)); } //validateReactionCoeff(i) //</editor-fold> //<editor-fold defaultstate="collapsed" desc="validateLogK"> private void validateLogK(){ if(loading) {return;} String t = jTextFieldLogK.getText(); if(t.length() <= 0) {return;} double w; try {w = Double.parseDouble(t); w = Math.min(10000,Math.max(w,-10000));} catch (NumberFormatException nfe) { jTextFieldLogK.setText(""); MsgExceptn.msg("Error reading reaction logK from text \""+t+"\""+nl+ " "+nfe.toString()); return; } if(Math.abs(w) > 9999) { if(w>0) {w = 9999;} else {w = -9999;} jTextFieldLogK.setText(Util.formatNumAsInt(w)); javax.swing.JOptionPane.showMessageDialog(this, "logK is outside \"reasonable\" range", pc.progName, javax.swing.JOptionPane.ERROR_MESSAGE); return; } jTextFieldLogK.setText(Util.formatNumAsInt(w)); } //validateLogK() //</editor-fold> //<editor-fold defaultstate="collapsed" desc="validateDeltH"> private void validateDeltH(){ if(loading) {return;} String t = jTextFieldDeltH.getText(); if(t.length() <= 0) {return;} double w; try {w = Double.parseDouble(t); w = Math.min(100000,Math.max(w,-100000));} catch (NumberFormatException nfe) { jTextFieldDeltH.setText(""); MsgExceptn.msg("Error reading reaction Delta-H from text \""+t+"\""+nl+ " "+nfe.toString()); return; } if(Math.abs(w) > 99999) { if(w>0) {w = 99999;} else {w = -99999;} jTextFieldDeltH.setText(Util.formatNumAsInt(w)); javax.swing.JOptionPane.showMessageDialog(this, "Delta-H is outside \"reasonable\" range", pc.progName, javax.swing.JOptionPane.ERROR_MESSAGE); return; } jTextFieldDeltH.setText(Util.formatNumAsInt(w)); } //validateDeltH() //</editor-fold> //<editor-fold defaultstate="collapsed" desc="validateDeltCp"> private void validateDeltCp(){ if(loading) {return;} String t = jTextFieldDeltCp.getText(); if(t.length() <= 0) {return;} double w; try {w = Double.parseDouble(t); w = Math.min(100000,Math.max(w,-100000));} catch (NumberFormatException nfe) { jTextFieldDeltCp.setText(""); MsgExceptn.msg("Error reading reaction Delta-Cp from text \""+t+"\""+nl+ " "+nfe.toString()); return; } if(Math.abs(w) > 99999) { if(w>0) {w = 99999;} else {w = -99999;} jTextFieldDeltCp.setText(Util.formatNumAsInt(w)); javax.swing.JOptionPane.showMessageDialog(this, "Delta-Cp is outside \"reasonable\" range", pc.progName, javax.swing.JOptionPane.ERROR_MESSAGE); return; } jTextFieldDeltCp.setText(Util.formatNumAsInt(w)); } //validateDeltCp() //</editor-fold> /** Shows a message box (and optionally outputs a message) * @param msg * @param type =-1 shows an error message dialog only; 0 shows an error message dialog and * the message is logged; =1 warning dialog; =2 information dialog */ void showErr(String msg, int type) { if(msg == null || msg.trim().length() <=0) {return;} int j; if(type == 1 || type == 2) { if(type==2) {j=javax.swing.JOptionPane.INFORMATION_MESSAGE;} else {j=javax.swing.JOptionPane.WARNING_MESSAGE;} } else { if(type == 0) {MsgExceptn.msg(msg);} j = javax.swing.JOptionPane.ERROR_MESSAGE; } if(!this.isVisible()) {this.setVisible(true);} javax.swing.JOptionPane.showMessageDialog(this, msg, pc.progName,j); } //showErr private static class AddDataFrameInternalException extends Exception { public AddDataFrameInternalException() {super();} public AddDataFrameInternalException(String txt) {super(txt);} } //AddDataInternalException //</editor-fold> //<editor-fold defaultstate="collapsed" desc="class ComplexListCellRenderer"> /** used to display text lines in a JList using different colours. Items in the * DefaultListModel of the JList are Object[2] where the first Object is a String * and the second a Color*/ private class ComplexListCellRenderer implements javax.swing.ListCellRenderer { private final javax.swing.DefaultListCellRenderer defaultRenderer = new javax.swing.DefaultListCellRenderer(); private final java.awt.Font defFont = new java.awt.Font("Monospaced", java.awt.Font.PLAIN, 12); @Override public java.awt.Component getListCellRendererComponent( javax.swing.JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { java.awt.Color theForeground; String theText; javax.swing.JLabel renderer = (javax.swing.JLabel) defaultRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (value instanceof ModelComplexesItem) { ModelComplexesItem item = (ModelComplexesItem) value; theText = item.toString(); theForeground = item.getForeground(); } else { theText = value.toString(); theForeground = list.getForeground(); } if (!isSelected) { renderer.setForeground(theForeground); } renderer.setText(theText); renderer.setFont(defFont); return renderer; } //getListCellRendererComponent }//class ComplexListCellRenderer //</editor-fold> // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.ButtonGroup buttonGroup; private javax.swing.JButton jButtonLink; private javax.swing.JButton jButtonSaveComp; private javax.swing.JButton jButtonSaveReac; private javax.swing.JCheckBoxMenuItem jCheckBoxMenuMsg; private javax.swing.JComboBox<String> jComboBox0; private javax.swing.JComboBox<String> jComboBox1; private javax.swing.JComboBox<String> jComboBox2; private javax.swing.JComboBox<String> jComboBox3; private javax.swing.JComboBox<String> jComboBox4; private javax.swing.JComboBox<String> jComboBox5; private javax.swing.JComboBox<String> jComboBoxElems; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabelCharge; private javax.swing.JLabel jLabelComp; private javax.swing.JLabel jLabelCompDescr; private javax.swing.JLabel jLabelCompName; private javax.swing.JLabel jLabelComps; private javax.swing.JLabel jLabelElems; private javax.swing.JLabel jLabelFiles; private javax.swing.JLabel jLabelHelp; private javax.swing.JLabel jLabelJKmol; private javax.swing.JLabel jLabelKJmol; private javax.swing.JLabel jLabelLinked; private javax.swing.JLabel jLabelLogK; private javax.swing.JLabel jLabelNote; private javax.swing.JLabel jLabelPlus1; private javax.swing.JLabel jLabelPlus3; private javax.swing.JLabel jLabelPlus5; private javax.swing.JLabel jLabelPlus6; private javax.swing.JLabel jLabelPlus7; private javax.swing.JLabel jLabelRLh; private javax.swing.JLabel jLabelReact; private javax.swing.JLabel jLabelReaction; private javax.swing.JLabel jLabelReactionText; private javax.swing.JLabel jLabelRef; private javax.swing.JList jListComps; private javax.swing.JList jListReact; private javax.swing.JMenu jMenuAdd; private javax.swing.JMenuItem jMenuAddComp; private javax.swing.JMenuItem jMenuAddReact; private javax.swing.JMenuItem jMenuAddShow; private javax.swing.JMenuBar jMenuBar; private javax.swing.JMenu jMenuFile; private javax.swing.JMenuItem jMenuFileExit; private javax.swing.JMenuItem jMenuFileSave; private javax.swing.JMenuItem jMenuFileShowFile; private javax.swing.JMenu jMenuHelp; private javax.swing.JMenuItem jMenuHelpHlp; private javax.swing.JMenuItem jMenuItemCancel; private javax.swing.JMenuItem jMenuItemDel; private javax.swing.JMenuItem jMenuItemDetails; private javax.swing.JMenuItem jMenuItemEdit; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanelComponent; private javax.swing.JPanel jPanelComps; private javax.swing.JPanel jPanelFiles; private javax.swing.JPanel jPanelReaction; private javax.swing.JPanel jPanelReaction1; private javax.swing.JPanel jPanelReaction2; private javax.swing.JPanel jPanelReactions; private javax.swing.JPopupMenu jPopupMenu; private javax.swing.JScrollPane jScrollPaneComps; private javax.swing.JScrollPane jScrollPaneFiles; private javax.swing.JScrollPane jScrollPaneReact; private javax.swing.JPopupMenu.Separator jSeparator; private javax.swing.JPopupMenu.Separator jSeparatorAdd; private javax.swing.JTextArea jTextAreaFiles; private javax.swing.JTextField jTextField0; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; private javax.swing.JTextField jTextField3; private javax.swing.JTextField jTextField4; private javax.swing.JTextField jTextField5; private javax.swing.JTextField jTextFieldComment; private javax.swing.JTextField jTextFieldCompDescr; private javax.swing.JTextField jTextFieldCompName; private javax.swing.JTextField jTextFieldComplex; private javax.swing.JTextField jTextFieldDeltCp; private javax.swing.JTextField jTextFieldDeltH; private javax.swing.JTextField jTextFieldLogK; private javax.swing.JTextField jTextFieldRef; // End of variables declaration//GEN-END:variables }
195,373
Java
.java
ignasi-p/eq-diagr
18
3
0
2018-08-17T08:25:37Z
2023-04-30T09:33:35Z
Version.java
/FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibDataBase/src/lib/database/Version.java
package lib.database; /** Copyright (C) 2014-2020 I.Puigdomenech. * * 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 * 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/ * * @author Ignasi Puigdomenech */ public class Version { static final String VERSION = "2020-06-17"; public static String version() {return VERSION;} }
903
Java
.java
ignasi-p/eq-diagr
18
3
0
2018-08-17T08:25:37Z
2023-04-30T09:33:35Z
AddDataElem.java
/FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibDataBase/src/lib/database/AddDataElem.java
package lib.database; import lib.common.MsgExceptn; import lib.huvud.Div; /** Procedures dealing with reactants and chemical elements. * Used for example by "FrameAddData" * <br> * Copyright (C) 2015-2020 I.Puigdomenech. * * 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 * 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/ * * @author Ignasi Puigdomenech */ public class AddDataElem { /** New-line character(s) to substitute "\n" */ private static final String nl = System.getProperty("line.separator"); //<editor-fold defaultstate="collapsed" desc="elemFileCheck"> /** For a given <b>text</b> database "dbName", check if the corresponding element-reactant * file exists. If it does not exist, create it, including any reactants * found in "elemComp". If it exists, check that all reactants in "dbName" * are found in the element file. * @param dbg if true, extra output messages will be printed * @param parent used to display dialogs, if needed. * @param addFile the name, with complete path, of the file with data. * It may not exist, or it may be null. * @param elemComp Array list of String[3] objects with the reactants (components):<br> * [0] contains the element name (e.g. "C"),<br> * [1] the component formula ("CN-" or "cit-3"),<br> * [2] the component name ("cyanide" or null); not really needed, but used to help the user * @return the name of the element-reactant file if everything is ok; <code>null</code> otherwise */ public static String elemFileCheck(final boolean dbg, java.awt.Component parent, String addFile, java.util.ArrayList<String[]> elemComp) { if(addFile == null || addFile.trim().length() <=0) { if(dbg){System.out.println("--- elemFileCheck(); addFile is \"null\" or empty");} return null; } if(dbg) {System.out.println("--- elemFileCheck("+addFile+")");} java.io.File af = new java.io.File(addFile); String addFileEle = getElemFileName(dbg, parent, addFile); if(addFileEle == null) { if(dbg){System.out.println("--- elemFileCheck(); could not get an element file name for file: "+addFile);} return null; } java.io.File afE = new java.io.File(addFileEle); if(!afE.exists()) { System.out.println("--- The \"element\"-file for database: \""+af.getName()+"\" does not exist."); String msg = "Could not find the \"element\"-file"+nl+ "for database: \""+af.getName()+"\"."+nl+nl+ "The file \""+afE.getName()+"\" will be created."; Object[] opt = {"OK", "Cancel"}; int m = javax.swing.JOptionPane.showOptionDialog(parent,msg, "Missing file", javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.WARNING_MESSAGE, null, opt, opt[0]); if(m != javax.swing.JOptionPane.YES_OPTION) { if(dbg) {System.out.println("Cancelled by the user");} return null; } } //--- List of reactants and their chemical elements java.util.ArrayList<String[]> elemCompNewFile = new java.util.ArrayList<String[]>(); //--- Are reactants in "addFile" not found in "addFileEle"? // if so, are they in "elemComp"? // if new reactants are found the file "addFileEle" is automatically saved try{elemCompAdd_Update(dbg, parent, addFile, addFileEle, elemComp, elemCompNewFile);} catch (AddDataException ex) { if(parent != null) {if(!parent.isVisible()) {parent.setVisible(true);}} MsgExceptn.showErrMsg(parent,ex.getMessage(),1); return null; } return addFileEle; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="getElemFileName"> /** returns the name, with complete path, for the * "chemical element and reactant" file that corresponds to the * database "addFile". Note that the file might not exist. * @param dbg if true, extra output messages will be printed * @param parent * @param addFile the name, with complete path, of the database file * @return a file name with complete path. It is equal to "addFile" but * with extension either "elb", "elt" or "elm". For a text database:<br> * -- If both "elt" and "elm" files exist, or none exists, the returned extension is "elt".<br> * -- If "elm" exists, and "elt" does not exist, "elm" is returned<br> * -- Note: if both files exist, a warning dialog is displayed. If the user selects * "cancel", <code>null</code> is returned, if the user selects "ok" the returned extension is "elt"<br> * -- If "addFile" is null or empty, or if its * extension is either "elb", "elt" or "elm", then <code>null</code> is returned */ public static String getElemFileName(final boolean dbg, java.awt.Component parent, final String addFile) { if(addFile == null || addFile.trim().length() <= 0) {return null;} if(Div.getFileNameExtension(addFile).equalsIgnoreCase("elt") || Div.getFileNameExtension(addFile).equalsIgnoreCase("elm") || Div.getFileNameExtension(addFile).equalsIgnoreCase("elb")) { String msg = "File \""+addFile+"\":"+nl+"can not have extension \"elb\", \"elt\", nor \"elm\"."; MsgExceptn.showErrMsg(parent,msg,1); return null; } String addFileEle; boolean binary = Div.getFileNameExtension(addFile).equalsIgnoreCase("db"); if(binary) { addFileEle = Div.getFileNameWithoutExtension(addFile)+".elb"; } else { addFileEle = Div.getFileNameWithoutExtension(addFile)+".elt"; java.io.File elemFile = new java.io.File(addFileEle); String elN = elemFile.getName(); if(!elemFile.exists()) { addFileEle = Div.getFileNameWithoutExtension(addFile)+".elm"; elemFile = new java.io.File(addFileEle); if(!elemFile.exists()) { addFileEle = Div.getFileNameWithoutExtension(addFile)+".elt"; } } else { // "*.elt" exists //check if both "*.elb" and "*.elt" exist String elN2 = Div.getFileNameWithoutExtension(addFile)+".elm"; java.io.File elemFile2 = new java.io.File(elN2); if(elemFile2.exists()) { Object[] opt = {"OK", "Cancel"}; elN2 = elemFile2.getName(); if(dbg) {System.out.println(" Warning: both \""+elN+"\""+nl+" and \""+elN2+"\""+nl+" exist.");} int m = javax.swing.JOptionPane.showOptionDialog(parent,"Note: both \""+elN+"\""+nl+ "and \""+elN2+"\" exist."+nl+nl+"Only file \""+elN+"\" will be used."+nl+" ", "Warning", javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.WARNING_MESSAGE, null, opt, opt[0]); if(m != javax.swing.JOptionPane.YES_OPTION) { if(dbg) {System.out.println("Cancelled by the user");} return null; } } //both files exist } // "*.elt" exists } // text or binary? return addFileEle; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="addFileEle_Read()"> /** Reads the text element-file "addFileEle", and stores the data in "elemCompAdd" * @param dbg if true, extra output messages will be printed * @param addFileEle the name, with complete path, of the chemical element and * reactant file (that corresponds to the database "addFile"). * Note: if the file "addFileEle" does not exist, "elemCompAdd" will only contain H2O, H+ and e-. * @param elemCompAdd This array list will contain the components (reactants) and * the corresponding chemical elements in the "add" file. Contains String[3] objects:<br> * [0] contains the element name (e.g. "C"),<br> * [1] the component formula ("CN-" or "cit-3"),<br> * [2] the component description ("cyanide" or null); not really needed, but used to help the user * @see ProgramDataDB#elemComp elemComp * @see LibDB#readElemFileText(java.io.File, java.util.ArrayList) readElemFileText * @see AddDataElem#elemCompAdd_Update(boolean, java.awt.Component, java.lang.String, java.lang.String, java.util.ArrayList, java.util.ArrayList) elemCompAdd_Update * @throws lib.database.AddDataElem.AddDataException */ public static void addFileEle_Read(final boolean dbg, final String addFileEle, java.util.ArrayList<String[]> elemCompAdd) throws AddDataException { if(dbg) {System.out.println("-- addFileEle_Read(..)");} if(addFileEle == null || addFileEle.length() <=0) { throw new AddDataException("Programming error: \"addFileEle\"=null or empty in \"addFileEle_Read\""); } if(elemCompAdd == null) { throw new AddDataException("Programming error: \"elemCompAdd\"=null in \"addFileEle_Read\""); } elemCompAdd.clear(); elemCompAdd.add(new String[]{"XX","H2O","water"}); elemCompAdd.add(new String[]{"H","H+","hydrogen ion"}); elemCompAdd.add(new String[]{"e-","e-","electron (= redox potential)"}); java.io.File ef = new java.io.File(addFileEle); if(ef.exists()) { if(dbg) {System.out.println("Reading file \""+ef.getName()+"\" in addFileEle_Read");} try {LibDB.readElemFileText(ef, elemCompAdd);} catch (LibDB.ReadElemException ex) {throw new AddDataException(ex.getMessage());} } //if element file exists //return; } //addFileEle_Read //</editor-fold> //<editor-fold defaultstate="collapsed" desc="addFileEle_Write()"> /** Writes the contents of array list "elemCompAdd" to text file "addFileEle". * First a temporary file is created, and if no error occurs, the original file * is deleted, and the temporary file is renamed. * Note: "elemCompAdd" is not changed. * @param dbg if true, extra output messages will be printed * @param addFileEle the name, with complete path, of the chemical element - * reactant file (that corresponds to the database "addFile") * @param elemCompAdd Array list of String[3] objects with the reactants (components) * used in file "addFile"<br> * [0] contains the element name (e.g. "C"),<br> * [1] the component formula ("CN-" or "cit-3"),<br> * [2] the component name ("cyanide" or null); not really needed, but used to help the user * @see ProgramDataDB#elemComp elemComp * @see AddDataElem#elemCompAdd_Update(boolean, java.awt.Component, java.lang.String, java.lang.String, java.util.ArrayList, java.util.ArrayList) elemCompAdd_Update * @throws lib.database.AddDataElem.AddDataException */ public static void addFileEle_Write(final boolean dbg, final String addFileEle, java.util.ArrayList<String[]> elemCompAdd) throws AddDataException { if(dbg) {System.out.println("-- addFileEle_Write(..)");} if(addFileEle == null || addFileEle.length() <=0) { throw new AddDataException("Error: \"addFileEle\"=null or empty in \"addFileEle_Write\""); } if(elemCompAdd == null || elemCompAdd.size() <=0) { throw new AddDataException("Error: \"elemCompAdd\"=null or empty in \"addFileEle_Write\""); } java.io.File wf = new java.io.File(addFileEle); if(wf.exists() && (!wf.canWrite() || !wf.setWritable(true))) { throw new AddDataException ("Error: can not write to file"+nl+" \""+addFileEle+"\""); } // --- open output files boolean ok; boolean replace = wf.exists(); java.io.File tmpF; String addFileEleTmp = Div.getFileNameWithoutExtension(addFileEle)+"-"+ Div.getFileNameExtension(addFileEle)+".tmp"; if(replace) { tmpF = new java.io.File(addFileEleTmp); if(tmpF.exists()) { try {ok = tmpF.delete();} catch (Exception ex) {throw new AddDataException(ex.getMessage());} if(!ok) {throw new AddDataException("Could not delete file:"+nl+"\""+addFileEleTmp+"\"");} } } else {tmpF = wf;} java.io.Writer w; try {w = new java.io.BufferedWriter( new java.io.OutputStreamWriter( new java.io.FileOutputStream(tmpF),"UTF8"));} catch (java.io.IOException ex) {throw new AddDataException(ex.getMessage()+nl+ "opening file: \""+addFileEleTmp+"\"");} int n; for(int i =0; i < LibDB.elementName.length; i++) { n=0; for(int j=0; j < elemCompAdd.size(); j++) { if(elemCompAdd.get(j)[0].equals(LibDB.elementSymb[i])) {n++;} } //for j if(n == 0) {continue;} try{ w.write(String.format("%-2s,%2d ,", LibDB.elementSymb[i],n)); for(int j=0; j < elemCompAdd.size(); j++) { if(elemCompAdd.get(j)[0].equals(LibDB.elementSymb[i])) { w.write(Complex.encloseInQuotes(elemCompAdd.get(j)[1])+","); w.write(Complex.encloseInQuotes(elemCompAdd.get(j)[2])+","); } } //for j w.write(nl); w.flush(); } catch (Exception ex) {throw new AddDataException(ex.getMessage()+nl+ "writing file: \""+addFileEleTmp+"\"");} } //for i // For components in the database not belonging to any element // set all of them into "XX" n = 0; for(int j=0; j < elemCompAdd.size(); j++) { ok = false; for(int i =0; i < LibDB.elementName.length; i++) { if(elemCompAdd.get(j)[0].equals(LibDB.elementSymb[i])) {ok = true; break;} } //for i if(!ok) {n++;} } //for j if(n > 0) { try{ w.write(String.format("%-2s,%2d ,", "XX",n)); for(int j=0; j < elemCompAdd.size(); j++) { ok = false; for(int i =0; i < LibDB.elementName.length; i++) { if(elemCompAdd.get(j)[0].equals(LibDB.elementSymb[i])) {ok = true; break;} } //for i if(!ok) { w.write(Complex.encloseInQuotes(elemCompAdd.get(j)[1])+","); w.write(Complex.encloseInQuotes(elemCompAdd.get(j)[2])+","); } } //for j w.write(nl); } catch (Exception ex) {throw new AddDataException(ex.getMessage()+nl+ "writing file: \""+addFileEleTmp+"\"");} } // n>0 // finished try{w.close();} catch (Exception ex) {throw new AddDataException(ex.getMessage()+nl+ "closing file: \""+addFileEleTmp+"\"");} if(replace) { // copy temporary file to final destination String line = null; try {ok = wf.delete();} catch (Exception ex) { line = ex.getMessage()+nl; ok = false; } if(!ok || line != null) { if(line == null) {line = "";} throw new AddDataException(line+"Could not delete file:"+nl+"\""+addFileEle+"\""); } line = null; try {ok = tmpF.renameTo(wf);} catch (Exception ex) { line = ex.getMessage()+nl; ok = false; } if(!ok || line != null) { if(line == null) {line = "";} throw new AddDataException(line+"Could not rename file:"+nl+ "\""+addFileEleTmp+"\""+nl+ "into: \""+addFileEle+"\""); } } //if replace } //addFileEle_Write //</editor-fold> //<editor-fold defaultstate="collapsed" desc="elemCompAdd_Update()"> /** Creates "elemCompAdd": the matrix with all existing reactants (components) * and the corresponding chemical elements. * <br> * - Reads the components found in text file "addFileEle" (if any). If the file * does not exist it is created. * <br> * - Then adds any components in the reactions in text file "addFile" (if any) * that were missing in "addFileEle" but that are found in "elemComp" (the * list of reactants from the main database) * @param dbg if true, extra output messages will be printed * @param parent used to display dialogs, if needed. * @param addFile the name, with complete path, of the text file with new data. * It may not exist, or it may be null. * @param addFileEle the name, with complete path, of the chemical element - * reactant text file corresponding to the database "addFile". * If it does not exist it will be created. * @param elemComp * @param elemCompAdd Array list of String[3] objects with the reactants (components) * used in file "addFile"<br> * [0] contains the element name (e.g. "C"),<br> * [1] the component formula ("CN-" or "cit-3"),<br> * [2] the component name ("cyanide" or null); not really needed, but used to help the user<br> * In this method this array list is "updated" to contain all components needed * for the "add" file. That is, all components initially in file "addFileEle" (if any) * are read, <b>and</b> any component in the reactions in file "addFile" * that were missing in "addFileEle" (if any), are added if found in the * list of components from the main database(s), that is, if found in "elemComp". * @see ProgramDataDB#elemComp elemComp * @see AddDataElem#addFileEle_Read(boolean, java.lang.String, java.util.ArrayList) addFileEle_Read * @throws lib.database.AddDataElem.AddDataException */ public static synchronized void elemCompAdd_Update(final boolean dbg, java.awt.Component parent, String addFile, String addFileEle, java.util.ArrayList<String[]> elemComp, java.util.ArrayList<String[]> elemCompAdd) throws AddDataException { if(dbg) {System.out.println("-- elemCompAdd_Update(..)");} if(addFileEle == null || addFileEle.length() <=0) { throw new AddDataException("Programming error: \"addFileEle\"=null or empty in \"elemCompAdd_Update\""); } if(elemComp == null) { throw new AddDataException("Programming error: \"elemComp\"=null in \"elemCompAdd_Update\""); } if(elemCompAdd == null) { elemCompAdd = new java.util.ArrayList<String[]>(); } else {elemCompAdd.clear();} // ---- read file "addFileEle" (if it exists) into "elemCompAdd" addFileEle_Read(dbg, addFileEle, elemCompAdd); java.io.File afE = new java.io.File(addFileEle); if(!afE.exists()) { try{addFileEle_Write(dbg, addFileEle, elemCompAdd);} catch (AddDataException ex) {throw new AddDataException(ex.getMessage());} } // ---- add to "elemCompAdd" any components in reactions // in file "addFile" that were missing in "addFileEle" // but that are found in the component-list from the main database if(addFile == null || addFile.length() <=0) {return;} java.io.File afF = new java.io.File(addFile); if(!afF.exists()) {return;} if(!afF.canRead()) { throw new AddDataException("Error: can not open file"+nl+" \""+addFile+"\"."); } if(dbg) { System.out.println(" reading file \""+afF.getName()+"\" to search for missing components"); } java.util.ArrayList<String> items = new java.util.ArrayList<String>(); int cmplxNbr = 0; java.io.BufferedReader br = null; try{ br = new java.io.BufferedReader( new java.io.InputStreamReader(new java.io.FileInputStream(afF),"UTF8")); Complex c; boolean fnd, there; // read the reaction-file "addFile" while (true){ cmplxNbr++; try{c = lib.database.LibDB.getTxtComplex(br);} catch (LibDB.EndOfFileException ex) {break;} catch (LibDB.ReadTxtCmplxException ex) { String msg = ex.toString()+nl+"reading complex "+cmplxNbr+nl+"in file: \""+addFile+"\""; MsgExceptn.exception("Error "+msg+nl+" Complex discarded!"); break; } if(c.name.startsWith("@")) {continue;} int nTot = Math.min(c.reactionComp.size(),c.reactionCoef.size()); for(int i=0; i < nTot; i++) { // take each reactant if(c.reactionComp.get(i) != null && c.reactionComp.get(i).length()>0 && Math.abs(c.reactionCoef.get(i)) >=0.0001) { fnd = false; for (int j=0; j < elemCompAdd.size(); j++) { // search in data from "addFileEle" if(elemCompAdd.get(j)[1].equals(c.reactionComp.get(i))) {fnd = true; break;} } //for j if(!fnd) { // if not found in "addFileEle" // search in other open databases for(int j=0; j < elemComp.size(); j++) { if(elemComp.get(j)[1].equals(c.reactionComp.get(i))) { there = false; for(String t : items) {if(t.equals(elemComp.get(j)[1])) {there = true; break;}} if(!there) {items.add(elemComp.get(j)[1]);} String[] s = {elemComp.get(j)[0],elemComp.get(j)[1],elemComp.get(j)[2]}; elemCompAdd.add(s); } } //for j } //if !fnd } //if reactant not empty } //for i } //while } //try catch (Exception ex) { String msg = ex.getMessage()+nl+"reading line "+cmplxNbr+nl+"in file: \""+addFile+"\""; if(dbg) {System.out.println("Error "+msg);} items.clear(); throw new AddDataException(msg); } finally { if(dbg) {System.out.println(" elemCompAdd_Update() finished reading \""+afF.getName()+"\"");} try{if(br != null) {br.close();}} catch(java.io.IOException ex) { items.clear(); String msg = ex.getMessage()+nl+"with file: \""+addFile+"\""; throw new AddDataException(msg); } } if(items.size() <= 0) {return;} // javax.swing.DefaultListModel aModel = new javax.swing.DefaultListModel(); // java 1.6 javax.swing.DefaultListModel<String> aModel = new javax.swing.DefaultListModel<>(); java.util.Collections.sort(items,String.CASE_INSENSITIVE_ORDER); java.util.Iterator<String> iter = items.iterator(); while(iter.hasNext()) {aModel.addElement(iter.next());} String msg = "<html>The following reactant"; if(aModel.size()>1) {msg = msg+"s";} msg = msg + "<br>will be written to file<br>\""+afE.getName()+"\".<br>&nbsp;</html>"; javax.swing.JLabel aLabel = new javax.swing.JLabel(msg); // javax.swing.JList aList = new javax.swing.JList(aModel); // java 1.6 javax.swing.JList<String> aList = new javax.swing.JList<>(aModel); aList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); aList.setVisibleRowCount(5); javax.swing.JScrollPane aScrollPane = new javax.swing.JScrollPane(); aScrollPane.setViewportView(aList); aList.setFocusable(false); Object[] o = {aLabel, aScrollPane}; javax.swing.JOptionPane.showMessageDialog(parent, o, "Writing: Elements - Components", javax.swing.JOptionPane.INFORMATION_MESSAGE); addFileEle_Write(dbg, addFileEle, elemCompAdd); } //elemCompAdd_Update() //</editor-fold> //<editor-fold defaultstate="collapsed" desc="addFileEle_ComponentDelete()"> /** Removes the component "compName" from the "elemCompAdd" list and saves the list * to the text file "addFileEle" * @param dbg if true, extra output messages will be printed * @param compName the reactant (component) to remove. * @param addFileEle * @param elemCompAdd * @throws lib.database.AddDataElem.AddDataException * @see FrameAddData#elemCompAdd elemCompAdd */ public static void addFileEle_ComponentDelete(final boolean dbg, final String compName, final String addFileEle, final java.util.ArrayList<String[]> elemCompAdd) throws AddDataException { if(dbg) {System.out.println("-- addFileEle_ComponentDelete("+compName+" ..)");} if(compName == null || compName.trim().length() <=0) {return;} String compDel = compName.trim(); // make a copy in case something goes wrong java.util.ArrayList<String[]> elemCompAdd0 = new java.util.ArrayList<String[]>(elemCompAdd); //remove "compDel" int i = 0; while(i < elemCompAdd.size()) { if(compDel.equals(elemCompAdd.get(i)[1])) { elemCompAdd.remove(i); continue; } i++; } //while //save changes made in "elemCompAdd" in file "addFileEle" try{addFileEle_Write(dbg, addFileEle, elemCompAdd);} catch (AddDataException ex) { // undo the deletion elemCompAdd.clear(); for(i =0; i < elemCompAdd0.size(); i++) {elemCompAdd.add(elemCompAdd0.get(i));} throw new AddDataException(ex.getMessage()); } //return; } //addFileEle_ComponentDelete() //</editor-fold> //<editor-fold defaultstate="collapsed" desc="addFileEle_ComponentSave()"> /** Adds a component to text file "addFileEle" (re-writes the file) * @param dbg * @param parent * @param newComp the new component, for example "SCN-" * @param linkedTo text describing what elements are "linked to" this component, * for example: "C,N" for cyanide, "C" for oxalate. * @param descr text describing the component, for example "cyanide" * @param addFile * @param addFileEle * @param elemComp * @param elemCompAdd * @return true if "newComp" has been saved. * False otherwise: if an error occurs or if the user cancels the operation * @throws lib.database.AddDataElem.AddDataException */ public static boolean addFileEle_ComponentSave(final boolean dbg, java.awt.Component parent, final String newComp, final String linkedTo, final String descr, final String addFile, final String addFileEle, java.util.ArrayList<String[]> elemComp, final java.util.ArrayList<String[]> elemCompAdd) throws AddDataException { if(dbg) {System.out.println("-- addFileEle_ComponentSave()");} // ---- Find out if new component is already in the database boolean fnd = false; String linkedToOld = ""; for(int i=0; i < elemCompAdd.size(); i++) { if(newComp.equals(elemCompAdd.get(i)[1])) { fnd = true; if(linkedToOld.indexOf(elemCompAdd.get(i)[0]) < 0) { if(linkedToOld.length()>0) {linkedToOld = linkedToOld+", ";} linkedToOld = linkedToOld + elemCompAdd.get(i)[0]; } } } //for i // ---- ask the user for confirmation String msg; if(fnd) { msg = "Replace:"+nl+" \""+newComp+"\" linked to: "+linkedToOld+nl+nl+ "with:"+nl+" \""+newComp+"\" linked to: "+linkedTo; } else { msg = "Add component \""+newComp+"\""+nl+"linked to: "+linkedTo+" ?"; } Object[] opt = {"Yes", "Cancel"}; int m = javax.swing.JOptionPane.showOptionDialog(parent, msg, "Writing: Elements - Components", javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.WARNING_MESSAGE, null, opt, opt[1]); if(m != javax.swing.JOptionPane.YES_OPTION) {return false;} // ---- To add a component, the matrix with all existing components is created: "elemCompAdd". // If a file with data for reactions exists (addFile), any missing component is added, // then the new component is added at the end of the "elemCompAdd". // Finally "elemCompAdd" is saved in the element-file "addFileEle" elemCompAdd_Update(dbg,parent,addFile,addFileEle,elemComp,elemCompAdd); // ---- make a copy in case something goes wrong java.util.ArrayList<String[]> elemCompAdd0 = new java.util.ArrayList<String[]>(elemCompAdd); // ---- remove any old occurences of this component if(fnd) { int i = 0; while(i < elemCompAdd.size()) { if(newComp.equals(elemCompAdd.get(i)[1])) { elemCompAdd.remove(i); continue; } i++; } //while } //if fnd // ---- add the new component java.util.ArrayList<String> aL; try{aL = CSVparser.splitLine(linkedTo);} catch (CSVparser.CSVdataException ex) { elemCompAdd.clear(); for(int i =0; i < elemCompAdd0.size(); i++) {elemCompAdd.add(elemCompAdd0.get(i));} throw new AddDataException(ex.getMessage()); } for(int i=0; i<aL.size(); i++) { String[] s = {aL.get(i), newComp, descr}; elemCompAdd.add(s); } // ---- save changes made in "elemCompAdd" in file "addFileEle" try{addFileEle_Write(dbg, addFileEle, elemCompAdd);} catch (AddDataException ex) { elemCompAdd.clear(); for(int i =0; i < elemCompAdd0.size(); i++) {elemCompAdd.add(elemCompAdd0.get(i));} throw new AddDataException(ex.getMessage()); } return true; } //addFileEle_ComponentSave() //</editor-fold> public static class AddDataException extends Exception { public AddDataException() {super();} public AddDataException(String txt) {super(txt);} } //AddDataInternalException }
30,132
Java
.java
ignasi-p/eq-diagr
18
3
0
2018-08-17T08:25:37Z
2023-04-30T09:33:35Z
LibSearch.java
/FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibDataBase/src/lib/database/LibSearch.java
package lib.database; import lib.common.MsgExceptn; /** Search reactions in the databases. * <br> * Copyright (C) 2014-2020 I.Puigdomenech. * * 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 * 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/ * * @author Ignasi Puigdomenech */ public class LibSearch { //<editor-fold defaultstate="collapsed" desc="private fields"> private java.util.ArrayList<String> localDBlist; /** counter: the database being read */ private int db; /** name of the database being read */ private String complxFileName; /** a counter indicating how many reactions have been read so far */ private long cmplxNbr; /** the binary database being read */ private java.io.DataInputStream dis; /** the text database being read */ private java.io.BufferedReader br; /** if <code>binaryOrText</code> = 2 reading a binary database<br> * if <code>binaryOrText</code> = 1 reading text database<br> * if <code>binaryOrText</code> = 0 then all files are closed (e.g. when all have been read) */ private int binaryOrText; /** true if the current database has been searched to the end and therefore the next * database must be opened (if there are any databases left to be searched) */ private boolean openNextFile; /** true if no databases could be openend and searched */ private boolean noFilesFound; /** New-line character(s) to substitute "\n" */ private static final String nl = System.getProperty("line.separator"); //</editor-fold> /** Constructor of a LibSearch instance * @param dataBaseslist an ArrayList with the names of the database files to search. * It will not be modified by this code * @throws LibSearch.LibSearchException */ public LibSearch(java.util.ArrayList<String> dataBaseslist) throws LibSearchException{ db = 0; cmplxNbr = 0; binaryOrText = 0; noFilesFound = true; openNextFile = true; dis = null; br = null; if(dataBaseslist == null) {throw new LibSearchException("Error: dataBaseslist = null in \"DBSearch\" constructor");} if(dataBaseslist.size() <=0) {throw new LibSearchException("Error: dataBaseslist is empty in \"DBSearch\" constructor");} this.localDBlist = dataBaseslist; } //<editor-fold defaultstate="collapsed" desc="getComplex(first)"> /** Get the next "complex" (without checking if the complex fits with selected components). * Both binary and text files will be read. * This routine must NOT be called to convert database files (Text <=> Binary), because * it reads both binary and text files. * <p>On output:<br> * if <code>binaryOrText</code> = 2 reading binary database<br> * if <code>binaryOrText</code> = 1 reading text database<br> * if <code>binaryOrText</code> = 0 then all files are closed * (because they have been read) * * @param firstComplex if true the first file is opened and the first complex * is searched for; if false then find the next complex from the list of * database files * @return either a "Complex" object, or null if nomore reactionsare found. * @throws LibSearch.LibSearchException */ public Complex getComplex(boolean firstComplex) throws LibSearchException { if(firstComplex) { // open the first file openNextFile = true; db = 0; }//firstComplex while (db < localDBlist.size()) { if(openNextFile) { try{ if(dis != null) {dis.close();} else if(br != null) {br.close();} } catch (java.io.IOException ioe) {MsgExceptn.msg(ioe.getMessage());} complxFileName = localDBlist.get(db); if(complxFileName == null || complxFileName.length() <=0) {continue;} java.io.File dbf = new java.io.File(complxFileName); if(!dbf.exists() || !dbf.canRead()) { String msg = "Can not open file"+nl+ " \""+complxFileName+"\"."; if(!dbf.exists()) {msg = msg +nl+ "(the file does not exist)."+nl+ "Search terminated";} throw new LibSearchException(msg); } cmplxNbr = 0; //--- text or binary? try{ if(complxFileName.toLowerCase().endsWith("db")) { //--- binary file binaryOrText = 2; dis = new java.io.DataInputStream(new java.io.FileInputStream(dbf)); } else { //--- text file binaryOrText = 1; br = new java.io.BufferedReader( new java.io.InputStreamReader( new java.io.FileInputStream(dbf),"UTF8")); } //--- text or binary? } catch (Exception ex) { try{ if(dis != null) {dis.close();} else if(br != null) {br.close();} } catch (java.io.IOException ioe) {MsgExceptn.msg(ioe.getMessage());} String msg = "Error: "+ex.getMessage()+nl+ "while trying to open file: \""+complxFileName+"\"."+nl+"Search terminated"; throw new LibSearchException(msg); } noFilesFound = false; openNextFile = false; } //if openNextFile Complex complex = null; loopComplex: while (true) { cmplxNbr++; if(binaryOrText ==2) { //Binary complex database try {complex = LibDB.getBinComplex(dis);} catch (LibDB.ReadBinCmplxException ex) { String msg = ex.getMessage()+nl+ "reading reaction nbr. = "+cmplxNbr+" in \"getComplex\""+nl+ "from file: \""+complxFileName+"\""; throw new LibSearchException(msg); } } else if(binaryOrText ==1) { // Text complex database try { try {complex = LibDB.getTxtComplex(br);} catch (LibDB.EndOfFileException ex) {complex = null;} } catch (LibDB.ReadTxtCmplxException ex) { String msg = ex.getMessage()+nl+ "reading reaction nbr. = "+cmplxNbr+" in \"getComplex\""+nl+ "from file: \""+complxFileName+"\""; throw new LibSearchException(msg); } } //binaryOrText =1 (Text file) if(complex == null) {break;} // loopComplex // end-of-file, open next database return complex; } //while (true) --- loopComplex: // ----- no complex found: end-of-file, or error. Get next file db++; openNextFile = true; binaryOrText = 0; } //while sd.db < pd.dataBasesList.size() if(noFilesFound) { // this should not happen... throw new LibSearchException("None of the databases could be found."); } libSearchClose(); return null; //return null if no more reactions } //getComplex(firstComplex) //</editor-fold> //<editor-fold defaultstate="collapsed" desc="libSearchClose"> public void libSearchClose() { try{ if(dis != null) {dis.close();} else if(br != null) {br.close();} } catch (java.io.IOException ioe) {MsgExceptn.exception(ioe.getMessage());} binaryOrText = 0; openNextFile = true; } //</editor-fold> public class LibSearchException extends Exception { public LibSearchException() {super();} public LibSearchException(String txt) {super(txt);} } }
7,854
Java
.java
ignasi-p/eq-diagr
18
3
0
2018-08-17T08:25:37Z
2023-04-30T09:33:35Z
LibDB.java
/FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibDataBase/src/lib/database/LibDB.java
package lib.database; import java.io.IOException; import lib.common.MsgExceptn; import lib.common.Util; import lib.huvud.Div; /** Some procedures used within this package. * <br> * Copyright (C) 2015-2020 I.Puigdomenech. * * 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 * 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/ * * @author Ignasi Puigdomenech */ public class LibDB { public static final java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();; public static final int ELEMENTS = 104; /** electron, Hydrogen, Helium, Lithium... */ public static String[] elementName = new String[113]; /** e-, H, He, Li ... */ public static String[] elementSymb = new String[113]; /** New-line character(s) to substitute "\n" */ private static final String nl = System.getProperty("line.separator"); /** java.io.File.separator - the system-dependent default name-separator character, * represented as a string for convenience. This string contains a single character, * namely File.separatorChar */ private static final String SLASH = java.io.File.separator; static { // static initializer setElementNames(); } // static initializer //<editor-fold defaultstate="collapsed" desc="setElementNames()"> private static void setElementNames(){ elementSymb[0]="e-"; elementSymb[1]="H"; elementSymb[2]="He"; elementSymb[3]="Li"; elementSymb[4]="Be"; elementSymb[5]="B"; elementSymb[6]="C"; elementSymb[7]="N"; elementSymb[8]="O"; elementSymb[9]="F"; elementSymb[10]="Ne"; elementSymb[11]="Na"; elementSymb[12]="Mg"; elementSymb[13]="Al"; elementSymb[14]="Si"; elementSymb[15]="P"; elementSymb[16]="S"; elementSymb[17]="Cl"; elementSymb[18]="Ar"; elementSymb[19]="K"; elementSymb[20]="Ca"; elementSymb[21]="Sc"; elementSymb[22]="Ti"; elementSymb[23]="V"; elementSymb[24]="Cr"; elementSymb[25]="Mn"; elementSymb[26]="Fe"; elementSymb[27]="Co"; elementSymb[28]="Ni"; elementSymb[29]="Cu"; elementSymb[30]="Zn"; elementSymb[31]="Ga"; elementSymb[32]="Ge"; elementSymb[33]="As"; elementSymb[34]="Se"; elementSymb[35]="Br"; elementSymb[36]="Kr"; elementSymb[37]="Rb"; elementSymb[38]="Sr"; elementSymb[39]="Y"; elementSymb[40]="Zr"; elementSymb[41]="Nb"; elementSymb[42]="Mo"; elementSymb[43]="Tc"; elementSymb[44]="Ru"; elementSymb[45]="Rh"; elementSymb[46]="Pd"; elementSymb[47]="Ag"; elementSymb[48]="Cd"; elementSymb[49]="In"; elementSymb[50]="Sn"; elementSymb[51]="Sb"; elementSymb[52]="Te"; elementSymb[53]="I"; elementSymb[54]="Xe"; elementSymb[55]="Cs"; elementSymb[56]="Ba"; elementSymb[57]="La"; elementSymb[58]="Ce"; elementSymb[59]="Pr"; elementSymb[60]="Nd"; elementSymb[61]="Pm"; elementSymb[62]="Sm"; elementSymb[63]="Eu"; elementSymb[64]="Gd"; elementSymb[65]="Tb"; elementSymb[66]="Dy"; elementSymb[67]="Ho"; elementSymb[68]="Er"; elementSymb[69]="Tm"; elementSymb[70]="Yb"; elementSymb[71]="Lu"; elementSymb[72]="Hf"; elementSymb[73]="Ta"; elementSymb[74]="W"; elementSymb[75]="Re"; elementSymb[76]="Os"; elementSymb[77]="Ir"; elementSymb[78]="Pt"; elementSymb[79]="Au"; elementSymb[80]="Hg"; elementSymb[81]="Tl"; elementSymb[82]="Pb"; elementSymb[83]="Bi"; elementSymb[84]="Po"; elementSymb[85]="At"; elementSymb[86]="Rn"; elementSymb[87]="Fr"; elementSymb[88]="Ra"; elementSymb[89]="Ac"; elementSymb[90]="Th"; elementSymb[91]="Pa"; elementSymb[92]="U"; elementSymb[93]="Np"; elementSymb[94]="Pu"; elementSymb[95]="Am"; elementSymb[96]="Cm"; elementSymb[97]="Bk"; elementSymb[98]="Cf"; elementSymb[99]="Es"; elementSymb[100]="Fm"; elementSymb[101]="Md"; elementSymb[102]="No"; elementSymb[103]="Lr"; elementSymb[104]="Rf"; elementSymb[105]="Db"; elementSymb[106]="Sg"; elementSymb[107]="Bh"; elementSymb[108]="Hs"; elementSymb[109]="Mt"; elementSymb[110]="Ds"; elementSymb[111]="Rg"; elementSymb[112]="Cn"; elementName[0]="Electron"; elementName[1]="Hydrogen"; elementName[2]="Helium"; elementName[3]="Lithium"; elementName[4]="Beryllium"; elementName[5]="Boron"; elementName[6]="Carbon"; elementName[7]="Nitrogen"; elementName[8]="Oxygen"; elementName[9]="Fluorine"; elementName[10]="Neon"; elementName[11]="Sodium"; elementName[12]="Magnesium"; elementName[13]="Aluminium"; elementName[14]="Silicon"; elementName[15]="Phosphorus"; elementName[16]="Sulfur"; elementName[17]="Chlorine"; elementName[18]="Argon"; elementName[19]="Potassium"; elementName[20]="Calcium"; elementName[21]="Scandium"; elementName[22]="Titanium"; elementName[23]="Vanadium"; elementName[24]="Chromium"; elementName[25]="Manganese"; elementName[26]="Iron"; elementName[27]="Cobalt"; elementName[28]="Nickel"; elementName[29]="Copper"; elementName[30]="Zinc"; elementName[31]="Gallium"; elementName[32]="Germanium"; elementName[33]="Arsenic"; elementName[34]="Selenium"; elementName[35]="Bromine"; elementName[36]="Krypton"; elementName[37]="Rubidium"; elementName[38]="Strontium"; elementName[39]="Yttrium"; elementName[40]="Zirconium"; elementName[41]="Niobium"; elementName[42]="Molybdenum"; elementName[43]="Technetium"; elementName[44]="Ruthenium"; elementName[45]="Rhodium"; elementName[46]="Palladium"; elementName[47]="Silver"; elementName[48]="Cadmium"; elementName[49]="Indium"; elementName[50]="Tin"; elementName[51]="Antimony"; elementName[52]="Tellurium"; elementName[53]="Iodine"; elementName[54]="Xenon"; elementName[55]="Caesium"; elementName[56]="Barium"; elementName[57]="Lanthanum"; elementName[58]="Cerium"; elementName[59]="Praseodymium"; elementName[60]="Neodymium"; elementName[61]="Promethium"; elementName[62]="Samarium"; elementName[63]="Europium"; elementName[64]="Gadolinium"; elementName[65]="Terbium"; elementName[66]="Dysprosium"; elementName[67]="Holmium"; elementName[68]="Erbium"; elementName[69]="Thulium"; elementName[70]="Ytterbium"; elementName[71]="Lutetium"; elementName[72]="Hafnium"; elementName[73]="Tantalum"; elementName[74]="Tungsten"; elementName[75]="Rhenium"; elementName[76]="Osmium"; elementName[77]="Iridium"; elementName[78]="Platinum"; elementName[79]="Gold"; elementName[80]="Mercury"; elementName[81]="Thallium"; elementName[82]="Lead"; elementName[83]="Bismuth"; elementName[84]="Polonium"; elementName[85]="Astatine"; elementName[86]="Radon"; elementName[87]="Francium"; elementName[88]="Radium"; elementName[89]="Actinium"; elementName[90]="Thorium"; elementName[91]="Protactinium"; elementName[92]="Uranium"; elementName[93]="Neptunium"; elementName[94]="Plutonium"; elementName[95]="Americium"; elementName[96]="Curium"; elementName[97]="Berkelium"; elementName[98]="Californium"; elementName[99]="Einsteinium"; elementName[100]="Fermium"; elementName[101]="Mendelevium"; elementName[102]="Nobelium"; elementName[103]="Lawrencium"; elementName[104]="Rutherfordium"; elementName[105]="Dubnium"; elementName[106]="Seaborgium"; elementName[107]="Bohrium"; elementName[108]="Hassium"; elementName[109]="Meitnerium"; elementName[110]="Darmstadtium"; elementName[111]="Roentgenium"; elementName[112]="Copernicium"; } //setElementNames() //</editor-fold> //<editor-fold defaultstate="collapsed" desc="getElements"> /** Reads (from the element-component file) the components (reactants) and the elements and * stores them in elemCompStringArray. * <p>This routine should be called at the program start. * <p>elemCompStringArray[0..2] contains the name-of-the-element (e.g. "C"), * the formula of the component ("CN-"), and the name of the component ("cyanide"). * Note that for CN- there can be two entries, one associated to "C" and another to "N"; * while for EDTA there is perhaps only one entry: with "C". * @param parent the owner of error messages * @param dbg print debugging info * @param dataBasesList list of database names to read * @param elemCompStringArray data is returned here (chemical element, * component formula, component name) * @return true if all is ok, false if some file is missing, etc */ public static boolean getElements(java.awt.Component parent, boolean dbg, java.util.ArrayList<String> dataBasesList, java.util.ArrayList<String[]> elemCompStringArray) { if(dbg) {System.out.println("-- getElements(..)");} if(dataBasesList == null) { MsgExceptn.exception("Programming error: dataBasesList = null in \"getElements\""); return false; } if(elemCompStringArray == null) { MsgExceptn.exception("Programming error: elemCompStringArray = null in \"getElements\""); return false; } elemCompStringArray.clear(); elemCompStringArray.add(new String[]{"H","H+","hydrogen ion"}); if(dataBasesList.size() <= 0) { System.out.println("---- Warning: dataBasesList.size() = 0 in \"getElements\""); return true; } if(dbg) {System.out.println("Reading metals and ligands from "+dataBasesList.size()+" data bases.");} int i, db = 0; boolean binaryDB; String elN; // --- loop through the databases while (db < dataBasesList.size()) { String dbName = dataBasesList.get(db); java.io.File dbFile = new java.io.File(dbName); java.io.File elemFile; binaryDB = dbName.toLowerCase().endsWith(".db"); if(binaryDB) { elemFile = new java.io.File(Div.getFileNameWithoutExtension(dbName)+".elb"); elN = elemFile.getName(); if(dbFile.exists() && !elemFile.exists()) { String msg = "Can not find the \"element\"-file"+nl+ "for database: \""+dbFile.getName()+"\"."+nl+nl+ "Expected to find file \""+elN+"\"."; if(parent != null && !parent.isVisible()) {parent.setVisible(true);} MsgExceptn.showErrMsg(parent,msg,1); return false; } else if(dbFile.exists() && !elemFile.canRead()) { String msg = "Error: can not read the \"element\"-file"+nl+ "for database: \""+dbFile.getName()+"\"."+nl+nl+ "You might not have permissions to read file \""+elN+"\"."; if(parent != null && !parent.isVisible()) {parent.setVisible(true);} MsgExceptn.showErrMsg(parent, msg, 1); return false; } else if(!dbFile.exists() && !elemFile.canRead()) { if(dbg) {System.out.println("-- Warning: files \""+dbFile.getName()+"\" and \""+elN+"\" do not exist.");} db++; continue; } } else { // not binaryDB String elemFileN = AddDataElem.getElemFileName(dbg, parent, dbName); if(elemFileN == null || elemFileN.trim().length() <=0) {return false;} elemFile = new java.io.File(elemFileN); elN = elemFile.getName(); if(dbFile.exists()) { //if the data file exists, error if the element file is not there if(!elemFile.exists()) { String msg = "Could not find the \"element\"-file"+nl+ "for database: \""+dbFile.getName()+"\"."+nl+nl+ "The file \""+elN+"\" will be created."; if(parent != null && !parent.isVisible()) {parent.setVisible(true);} MsgExceptn.showErrMsg(parent, msg, 1); try {AddDataElem.elemCompAdd_Update(dbg, parent, dbName, elemFileN, elemCompStringArray, new java.util.ArrayList<String[]>());} catch (AddDataElem.AddDataException ex) { if(parent != null && !parent.isVisible()) {parent.setVisible(true);} MsgExceptn.showErrMsg(parent, ex.getMessage(),1); return false; } } else if(!elemFile.canRead()) { String msg ="Error: can not rean the \"element\"-file"+nl+ "for database: \""+dbFile.getName()+"\"."+nl+nl+ "You might not have permissions to read file \""+elN+"\"."; if(parent != null && !parent.isVisible()) {parent.setVisible(true);} MsgExceptn.showErrMsg(parent,msg,1); return false; } } else { //!dbFile.exists() if(!elemFile.canRead()) { if(dbg) {System.out.println("-- Warning: files \""+dbFile.getName()+"\" and \""+elN+"\" do not exist.");} db++; continue; } } // dbFile.exists() ? } // binaryDB ? if(dbg) {System.out.println(" File \""+elemFile+"\"");} try { if(binaryDB) { readElemFileBinary(dbg, elemFile, elemCompStringArray); } else { //!binaryDB readElemFileText(elemFile, elemCompStringArray); } } catch (ReadElemException ex) { if(parent != null && !parent.isVisible()) {parent.setVisible(true);} MsgExceptn.showErrMsg(parent,ex.getMessage(),1); System.err.println("Removing file \""+dbName+"\""+nl+"from the database list"); for(i=0; i < dataBasesList.size(); i++) { if(dataBasesList.get(i).equals(dbName)) {dataBasesList.remove(i); break;} } } db++; } //loop through databases return true; } //getElements() //</editor-fold> //<editor-fold defaultstate="collapsed" desc="readElemFileText"> /** Reads (from a single element database file) the components and the elements and * stores them either in elemCompStringArray or in elemCompString. * <p>elemCompStringArray[0..2] contains the name-of-the-element (e.g. "C"), * the formula of the component ("CN-"), and the name of the component ("cyanide"). * For CN- there can be two entries associated to "C" and "N"; * while for EDTA there is perhaps only one entry with "C". * @param elemFile * @param elemCompStringArray data is returned here (chemical element, * component formula, component name) * @throws ReadElemException */ public static void readElemFileText( java.io.File elemFile, java.util.ArrayList<String[]> elemCompStringArray) throws ReadElemException { if(elemFile == null) {throw new ReadElemException("Input file is \"null\"!");} String elN = elemFile.getName(); if(elN == null) {throw new ReadElemException("Input file is \"null\"!");} elN = elemFile.getAbsolutePath(); if(!elemFile.exists()) {throw new ReadElemException("Input file does not exist"+nl+"\""+elN+"\"");} if(!elemFile.canRead()) {throw new ReadElemException("Can not read input file"+nl+"\""+elN+"\"");} java.io.BufferedReader br; try {br = new java.io.BufferedReader( new java.io.InputStreamReader( new java.io.FileInputStream(elemFile),"UTF8")); } catch (Exception ex) {throw new ReadElemException(ex.getMessage());} String line = null; int lineNbr = 0; int i,j,k,n; boolean found; String t1, t2; String[] elemCompLocal = null; String element; java.util.ArrayList<String> aList; try { while((line = br.readLine()) != null) { //--- read all elements (lines) in the input file lineNbr++; if(line.length()<=0 || line.trim().startsWith("/")) {continue;} try {aList = CSVparser.splitLine(line);} // this will remove enclosing quotes catch (CSVparser.CSVdataException ex) { throw new ReadTxtElemEx("Error (CSVdataException) "+ex.getMessage()+nl+ "while reading line nbr "+lineNbr+":"+nl+ " "+line+nl+"from file:"+nl+" \""+elN+"\""); } element = aList.get(0); if(element == null || element.length() <=0) { throw new ReadTxtElemEx("Error: empty element in line"+nl+ " "+line+nl+"in file"+nl+" \""+elN+"\""); } try {n = Integer.parseInt(aList.get(1));} catch(NumberFormatException ex) { throw new ReadTxtElemEx("Error reading an integer from \""+aList.get(1)+"\" in line"+nl+ " "+line+nl+"in file"+nl+" \""+elN+"\""); } if(n>0) { if(aList.size()<3 || n*2 > (aList.size()-1)) { String msg = "Error: too litle data"+nl+"while reading line"+nl+ " "+line+nl+"from file:"+nl+" \""+elN+"\""; throw new ReadTxtElemEx(msg); } found = false; for(i=0; i< elementSymb.length; i++) { if(element.equals(elementSymb[i])) {found = true; break;} } if(!found) {element = "XX";} for(i=0; i<n; i++) { t1 = aList.get((i*2)+2); if(t1.length() <=0) { String msg = "Error: empty reactant"+nl+"while reading line"+nl+ " "+line+nl+"from file:"+nl+" \""+elN+"\""; throw new ReadTxtElemEx(msg); } j = (i*2)+3; if(j < aList.size()) {t2 = aList.get(j);} else {t2 = "";} if(t1.startsWith("@") && elemCompStringArray.size() >0) { //--- remove an existing ligand/metal t1 = t1.substring(1); //remove @ j = elemCompStringArray.size(); while(j >0) { j--; if(elemCompStringArray.get(j)[1].equals(t1)) {elemCompStringArray.remove(j); break;} } } //starts with "@" else { //does not start with "@" int jFound = -1; k = elemCompStringArray.size(); for(j=0; j < k; j++) { if(elemCompStringArray.get(j)[0].equals(element) && elemCompStringArray.get(j)[1].equals(t1)) { jFound = j; elemCompLocal = elemCompStringArray.get(jFound); break; } } //for j if(jFound > -1) { if(t2.length()>0) { elemCompLocal[2] = t2; elemCompStringArray.set(jFound,elemCompLocal); } } else { //jFound =-1 elemCompLocal = new String[3]; elemCompLocal[0] = element; elemCompLocal[1] = t1; elemCompLocal[2] = t2; elemCompStringArray.add(elemCompLocal); } //jFound? } //starts with "@"? } //for i } //if n>0 else { throw new ReadTxtElemEx("Error reading \""+aList.get(1)+"\" (must be a number >0)"+nl+ "in line"+nl+" "+line+nl+"in file"+nl+" \""+elN+"\""); } //if n<=0 } //while loop through elements } //try catch (ReadTxtElemEx ex) { throw new ReadElemException(ex.getMessage()); } catch (java.io.IOException ex) { MsgExceptn.exception(Util.stack2string(ex)); throw new ReadElemException("Error "+ex.getMessage()+nl+"while reading line"+nl+ " "+line+nl+"from file:"+nl+" \""+elN+"\""); } finally { try {br.close();} catch (java.io.IOException ex) { throw new ReadElemException("Error "+ex.getMessage()+nl+ "closing file:"+nl+" \""+elN+"\""); } } //return; } //readElemFileText //</editor-fold> //<editor-fold defaultstate="collapsed" desc="readElemFileBinary"> /** Read (from a single element database file) the components and the elements and * store them either in elemCompStringArray or in elemCompString. * <p>elemCompStringArray[0..2] contains the name-of-the-element (e.g. "C"), * the formula of the component ("CN-"), and the name of the component ("cyanide"). * For CN- there can be two entries associated to "C" and "N"; * while for EDTA there is perhaps only one entry with "C". * @param dbg if true then some output is written to System.out * @param elemFile * @param elemCompStringArray data is returned here (chemical element, * component formula, component name) * @throws ReadElemException */ private static void readElemFileBinary(boolean dbg, java.io.File elemFile, java.util.ArrayList<String[]> elemCompStringArray) throws ReadElemException { if(elemFile == null) {throw new ReadElemException("Input file is \"null\"!");} String elN = elemFile.getName(); if(elN == null) {throw new ReadElemException("Input file is \"null\"!");} if(!elemFile.exists()) {throw new ReadElemException("Input file does not exist"+nl+"\""+elN+"\"");} if(!elemFile.canRead()) {throw new ReadElemException("Can not read input file"+nl+"\""+elN+"\"");} java.io.DataInputStream dis = null; try {dis = new java.io.DataInputStream(new java.io.FileInputStream(elemFile));} catch (java.io.FileNotFoundException ex) { if(dis != null) {try {dis.close();} catch (java.io.IOException e) {}} throw new ReadElemException("Error "+ex.getMessage()+nl+" in \"readElemFileBinary\""); } int i,j,k,n; boolean found; String t1, t2; if(dbg) {System.out.println(" readElemFileBinary("+elemFile+")");} String[] elemCompLocal = null; String element; boolean first = true; try { while(true) { //--- loop reading all elements in the input file element = dis.readUTF(); if(element == null || element.length() <=0) { if(first){ throw new ReadElemException("Error in \"readElemFileBinary\""+nl+ "could not read the first element from file:"+nl+" \""+elN+"\"."); } break; } first = false; n = dis.readInt(); if(n>0) { found = false; for(i=0; i< elementSymb.length; i++) { if(element.equals(elementSymb[i])) {found = true; break;} } if(!found) {element = "XX";} for(i=0; i<n; i++) { t1 = dis.readUTF(); t2 = dis.readUTF(); if(t1.startsWith("@") && elemCompStringArray.size() >0) { //--- remove an existing ligand/metal t1 = t1.substring(1); //remove @ j = elemCompStringArray.size(); while(j >0) { j--; if(elemCompStringArray.get(j)[1].equals(t1)) {elemCompStringArray.remove(j); break;} } } //starts with "@" else { //does not start with "@" int jFound = -1; k = elemCompStringArray.size(); for(j=0; j < k; j++) { if(elemCompStringArray.get(j)[0].equals(element) && elemCompStringArray.get(j)[1].equals(t1)) { jFound = j; elemCompLocal = elemCompStringArray.get(jFound); break; } } //for j if(jFound > -1) { if(t2.length()>0) { elemCompLocal[2] = t2; elemCompStringArray.set(jFound,elemCompLocal); } } else { //jFound =-1 elemCompLocal = new String[3]; elemCompLocal[0] = element; elemCompLocal[1] = t1; elemCompLocal[2] = t2; elemCompStringArray.add(elemCompLocal); } //jFound? } //starts with "@"? } //for i } //if n>0 } //while loop through elements } //try catch (java.io.EOFException eof) { if(first) { throw new ReadElemException("Error in \"readElemFileBinary\""+nl+ "could not read the first element from file:"+nl+" \""+elN+"\"."); } } catch (IOException ex) { throw new ReadElemException(Util.stack2string(ex)); } catch (ReadElemException ex) { throw new ReadElemException(Util.stack2string(ex)); } finally {try{dis.close();} catch (java.io.IOException ex) {}} //return; } //readElemFileBinary //</editor-fold> //<editor-fold defaultstate="collapsed" desc="checkListOfDataBases"> /** Check that the database names are not empty, the files exist * and can be read, and that there are no duplicates * @param parent * @param dataBasesList the databases * @param pathApp the path where the application (jar-file) is located. May be "null" * @param dbg ture if warnings and error messages are to be printed */ public static synchronized void checkListOfDataBases( java.awt.Component parent, java.util.ArrayList<String> dataBasesList, String pathApp, boolean dbg) { if(dataBasesList == null || dataBasesList.size() <=0) {return;} //--- check for non-existing files int nbr = dataBasesList.size(); String dbName; int i=0; while(i < nbr) { dbName = dataBasesList.get(i); if(dbName != null && dbName.length() >0) { java.io.File dbf = new java.io.File(dbName); // if the database does not exist, and it is a plain name // (does not contain a "slash"), check if it is found in the // application path if(!dbf.exists() && !dbName.contains(SLASH) && pathApp != null) { String dir = pathApp; if(dir != null && dir.endsWith(SLASH)) {dir = dir.substring(0, dir.length()-1);} dbName = dir + SLASH + dbName.trim(); } if(isDBnameOK(parent, dbName, dbg)) { // replace the name in case the the application path has been added dataBasesList.set(i, dbName); i++; continue; } } else { if(dbg) {System.out.println("Error: found an empty database name in position "+i);} } dataBasesList.remove(i); nbr--; } //while i < nbr //--- check for duplicates i=0; int j; if(nbr >1) { boolean found; while(i < nbr) { dbName = dataBasesList.get(i); found = false; for(j=i+1; j < nbr; j++) { if(dbName.equalsIgnoreCase(dataBasesList.get(j))) {found = true; break;} } if(!found) {i++; continue;} if(dbg) {System.out.println("Warning: found duplicated database: \""+dbName+"\"");} dataBasesList.remove(j); nbr--; } //while i < nbr } // nbr >1 } //checkListOfDataBases //</editor-fold> //<editor-fold defaultstate="collapsed" desc="isDBnameOK"> /** Check if a database exists and can be read. If the database does not * exist, and it is a plain name (does not contain a "slash"), * and if "pathApp" is not null, check if it is found in the directory * "pathApp" (the application path) * @param parent * @param dBname a database * @param dbg set to <code>true</code> to print error messages to <code>System.err</code> * @return true if the database exists and can be read, false otherwise */ public static boolean isDBnameOK( java.awt.Component parent, String dBname, boolean dbg) { boolean ok = true; if(dBname != null && dBname.length() >0) { java.io.File dbf = new java.io.File(dBname); if(!dbf.exists()) { MsgExceptn.msg("Note: database file does not exist:"+nl+dBname); ok = false; } else if(!dbf.canRead()) { MsgExceptn.showErrMsg(parent, "Error: no read permission for database:"+nl+dBname, 1); ok = false; } } else {ok = false;} return ok; } //isDBnameOK //</editor-fold> //<editor-fold defaultstate="collapsed" desc="getTxtComplex"> /** Read a <code>Complex</code> from the text file "connected" to a BufferedReader * @param br * @return * @throws ReadTxtCmplxException * @throws EndOfFileException */ public static Complex getTxtComplex(java.io.BufferedReader br) throws ReadTxtCmplxException, EndOfFileException { if(br == null) {return null;} Complex cmplx; String line, line2; try{ while ((line = br.readLine()) != null){ if(line.trim().length()<=0 || line.trim().toUpperCase().startsWith("COMPLEX") || line.trim().startsWith("/")) {continue;} if(line.toLowerCase().contains("lookup")) { // lookUpTable for(int i = 0; i < 5; i++) { line2 = br.readLine(); if(line2 != null) {line = line + nl + line2;} } } try{cmplx = Complex.fromString(line);} catch (Complex.ReadComplexException ex) {throw new ReadTxtCmplxException(ex.getMessage());} if(cmplx != null) {return cmplx;} } // while } catch (java.io.IOException ex) {throw new ReadTxtCmplxException(ex.toString());} //if(line == null) throw new EndOfFileException(); } //getTxtComplex(rd) //</editor-fold> //<editor-fold defaultstate="collapsed" desc="writeTxtComplex"> public static void writeTxtComplex(java.io.Writer w, Complex cmplx) throws WriteTxtCmplxException { if(w == null) {throw new WriteTxtCmplxException(nl+"Error: Writer = null in \"writeTxtComplex\"");} if(cmplx == null) { throw new WriteTxtCmplxException(nl+"Error: cmplx = null in \"writeTxtComplex\""); } if(cmplx.name == null || cmplx.name.length() <=0) { throw new WriteTxtCmplxException(nl+"Error: empty cmplx name in \"writeTxtComplex\""); } try { w.write(cmplx.toString()); w.write(nl); } catch (Exception ex) { throw new WriteTxtCmplxException(nl+"Error: "+ex.getMessage()+nl+" in \"writeTxtComplex\""); } } //writeTxtComplex //</editor-fold> //<editor-fold defaultstate="collapsed" desc="getBinComplex"> /** Read a <code>Complex</code> from the binary file "connected" to a DataInputStream instance. * Returns null after a java.io.EOFException. * @param dis * @return * @throws ReadBinCmplxException */ public static Complex getBinComplex(java.io.DataInputStream dis) throws ReadBinCmplxException { if(dis == null) {return null;} Complex cmplx = new Complex(); String txt; int nTot, nr; boolean thereisHplus = false; double n_H, deltaH, deltaCp; StringBuilder nowReading = new StringBuilder(); nowReading.replace(0, nowReading.length(), "Name of complex"); try{ cmplx.name = dis.readUTF(); if(cmplx.name == null) {throw new ReadBinCmplxException(nl+"Error: complex name = \"null\".");} nowReading.replace(0, nowReading.length(), "logK for `"+cmplx.name+"´"); cmplx.constant = dis.readDouble(); nowReading.replace(0, nowReading.length(), "delta-H for `"+cmplx.name+"´ (or \"analytic - lookUp\" flag)"); deltaH = dis.readDouble(); if(deltaH == Complex.ANALYTIC) { // analytic equation cmplx.analytic = true; cmplx.lookUp = false; nowReading.replace(0, nowReading.length(), "max temperature for `"+cmplx.name+"´"); cmplx.tMax = dis.readDouble(); cmplx.tMax = Math.max(25., cmplx.tMax); if(cmplx.tMax > 373.) {throw new ReadBinCmplxException(nl+"Error: while reading \""+nowReading.toString()+"\": should be below 373 C (critical point).");} cmplx.pMax = Math.max(1.,lib.kemi.H2O.IAPWSF95.pSat(cmplx.tMax)); for(int i = 0; i < cmplx.a.length; i++) { nowReading.replace(0, nowReading.length(), "parameter a[+"+i+"] for `"+cmplx.name+"´"); cmplx.a[i] = dis.readDouble(); } } else if(deltaH == Complex.LOOKUP) { // look-up table cmplx.lookUp = true; cmplx.analytic = false; nowReading.replace(0, nowReading.length(), "max temperature for `"+cmplx.name+"´"); cmplx.tMax = dis.readDouble(); if(cmplx.tMax != 600) {throw new ReadBinCmplxException(nl+"Error: while reading \""+nowReading.toString()+"\": should be 600 C.");} cmplx.pMax = 5000.; } else { // delta-H and delta-Cp cmplx.analytic = false; cmplx.lookUp = false; nowReading.replace(0, nowReading.length(), "delta-Cp for `"+cmplx.name+"´"); deltaCp = dis.readDouble(); cmplx.a = Complex.deltaToA(cmplx.constant, deltaH, deltaCp); cmplx.tMax = 25.; cmplx.pMax = 1.; if(deltaH != Complex.EMPTY) { cmplx.tMax = 100.; if(deltaCp != Complex.EMPTY) {cmplx.tMax = 300.; cmplx.pMax = 85.9;} // pSat(300) = 85.9 } } nowReading.replace(0, nowReading.length(), "reactant nbr.1 or nbr of reactants for `"+cmplx.name+"´"); txt = dis.readUTF(); try {nTot = Integer.parseInt(txt);} catch (Exception ex) {nTot = -1;} if(nTot <= 0) { // nTot < 0 ---- old format ---- nr = 0; for(int i=0; i < Complex.NDIM; i++) { if(i>0) { nowReading.replace(0, nowReading.length(), "reactant nbr."+(i+1)+" for `"+cmplx.name+"´"); txt = dis.readUTF(); } if(txt.trim().isEmpty()) {dis.readDouble(); continue;} cmplx.reactionComp.add(txt); nr++; nowReading.replace(0, nowReading.length(), "stoichiometric coeff. nbr."+(i+1)+" for `"+cmplx.name+"´"); cmplx.reactionCoef.add(dis.readDouble()); if(Util.isProton(cmplx.reactionComp.get(nr-1))) { thereisHplus = true; n_H = cmplx.reactionCoef.get(nr-1); } } // for i nowReading.replace(0, nowReading.length(), "nbr H+ for `"+cmplx.name+"´"); n_H = dis.readDouble(); if(!thereisHplus && Math.abs(n_H) > 0.00001) {cmplx.reactionComp.add("H+"); cmplx.reactionCoef.add(n_H);} } else { // nTot >0 ---- new format ---- for(int i=0; i < nTot; i++) { nowReading.replace(0, nowReading.length(), "reactant nbr."+(i+1)+" for `"+cmplx.name+"´"); cmplx.reactionComp.add(dis.readUTF()); nowReading.replace(0, nowReading.length(), "stoichiometric coeff. nbr."+(i+1)+" for `"+cmplx.name+"´"); cmplx.reactionCoef.add(dis.readDouble()); } } nowReading.replace(0, nowReading.length(), "reference for `"+cmplx.name+"´"); cmplx.reference = dis.readUTF(); cmplx.comment = dis.readUTF(); if(cmplx.lookUp) { // read look-up table for(int i=0; i < cmplx.logKarray.length; i++) { cmplx.logKarray[i] = new float[14]; for(int j=0; j < cmplx.logKarray[i].length; j++) {cmplx.logKarray[i][j]=Float.NaN;} if(i == 0) {nr = 9;} else if(i == 1) {nr = 11;} else {nr = 14;} for(int j=0; j < nr; j++) { nowReading.replace(0, nowReading.length(), "logKarray["+i+"]["+j+"] for `"+cmplx.name+"´"); cmplx.logKarray[i][j] = dis.readFloat(); } } } } catch (java.io.EOFException eof) {return null;} catch (IOException ex) { throw new ReadBinCmplxException(nl+"Error: "+ex.getMessage()+nl+"while reading \""+nowReading.toString()+"\""); } catch (ReadBinCmplxException ex) { throw new ReadBinCmplxException(nl+"Error: "+ex.getMessage()+nl+"while reading \""+nowReading.toString()+"\""); } if(cmplx.name == null) {return null;} return cmplx; } //getBinComplex(dis) //</editor-fold> //<editor-fold defaultstate="collapsed" desc="writeBinCmplx"> public static void writeBinCmplx(java.io.DataOutputStream ds, Complex cmplx) throws WriteBinCmplxException { if(ds == null) {throw new WriteBinCmplxException(nl+"Error: DataOutputStream = null in \"writeBinCmplx\"");} if(cmplx == null) {throw new WriteBinCmplxException(nl+"Error: cmplx = null in \"writeBinCmplx\"");} if(cmplx.name == null || cmplx.name.length() <=0) { throw new WriteBinCmplxException(nl+"Error: empty cmplx in \"writeBinCmplx\""); } // If there is no second row of logKarray, it means that the look-up-table // (if it is not null) has been constructed from array a[]. boolean thereIsLookUpTable = false; if(cmplx.logKarray[1] != null) { for(int j = 0; j < cmplx.logKarray[1].length; j++) { if(!Float.isNaN(cmplx.logKarray[1][j])) {thereIsLookUpTable = true; break;} } } try{ ds.writeUTF(cmplx.name); ds.writeDouble(cmplx.constant); if(cmplx.analytic) { // analytic equation ds.writeDouble(Complex.ANALYTIC); ds.writeDouble(cmplx.tMax); for(int i = 0; i < cmplx.a.length; i++) {ds.writeDouble(cmplx.a[i]);} } else if(cmplx.lookUp && thereIsLookUpTable) { // look-up Table ds.writeDouble(Complex.LOOKUP); ds.writeDouble(cmplx.tMax); } else { // delta-H and delta-Cp ds.writeDouble(cmplx.getDeltaH()); ds.writeDouble(cmplx.getDeltaCp()); } int nTot = Math.min(cmplx.reactionComp.size(),cmplx.reactionCoef.size()); ds.writeUTF(String.valueOf(nTot)); for(int i = 0; i < nTot; i++) { ds.writeUTF(cmplx.reactionComp.get(i)); ds.writeDouble(cmplx.reactionCoef.get(i)); } ds.writeUTF(cmplx.reference); if(cmplx.comment != null && cmplx.comment.length() >=0) {ds.writeUTF(cmplx.comment);} else {ds.writeUTF("");} if(cmplx.lookUp && thereIsLookUpTable) { // write look-up Table int nr; for(int i=0; i < cmplx.logKarray.length; i++) { if(cmplx.logKarray[i] == null) { cmplx.logKarray[i] = new float[14]; for(int j=0; j < cmplx.logKarray[i].length; j++) {cmplx.logKarray[i][j] = Float.NaN;} } for(int j=0; j < cmplx.logKarray[i].length; j++) {ds.writeFloat(cmplx.logKarray[i][j]);} } } } catch (java.io.IOException ex) {throw new WriteBinCmplxException(nl+"Error: "+ex.getMessage()+nl+"in \"writeBinCmplx\"");} } //writeBinCmplx(DataOutputStream, complex) // </editor-fold> //<editor-fold defaultstate="collapsed" desc="getDiagramProgr"> /** Check if the program "diagramProgr" exists. If "prog" is the name * without extension, then if both "prog.jar" and "prog.exe" exist, * then the jar-file name is returned. If none exists, <code>null</code> is returned. * This means that if the user selects an "exe" file, the corresponding * "jar" file, if it exists, will be anyway executed. * @param diagramProgr a program name with existing directory path. * With or without file extension. * @return the program name with extension ".jar" if a jar-file exists, otherwise * with the extension ".exe" if the exe-file exists, otherwise <code>null</code>. * Note that the directory is not changed. */ public static String getDiagramProgr(String diagramProgr) { if(diagramProgr == null || diagramProgr.trim().length() <= 0) {return null;} java.io.File f = new java.io.File(diagramProgr); String os = System.getProperty("os.name").toLowerCase(); if(f.isDirectory() && !os.startsWith("mac os")) {return null;} String dir = f.getParent(); if(dir == null || dir.trim().length() <=0) {return null;} String prog = f.getName(); if(prog == null || prog.trim().length() <=0) {return null;} f = new java.io.File(dir); if(!f.exists() || !f.isDirectory()) {return null;} dir = f.getAbsolutePath(); if(dir != null && dir.endsWith(SLASH)) {dir = dir.substring(0,dir.length()-1);} // get "prog" without extension String progName; if(prog.length() == 1) { if(prog.equals(".")) {return null;} else {progName = prog;} } else { int dot = prog.lastIndexOf("."); if(dot <= 0) { progName = prog; //no extension in name } else { progName = prog.substring(0,dot); } } // String name; name = dir + SLASH + progName + ".jar"; f = new java.io.File(name); if(f.exists() && f.isFile()) { return name; } else if(os.startsWith("windows")) { name = dir + SLASH + progName + ".exe"; f = new java.io.File(name); if(f.exists() && f.isFile()) {return name;} } else if(os.startsWith("mac os")) { name = dir + SLASH + progName + ".app"; f = new java.io.File(name); if(f.exists()) {return name;} } return null; } //</editor-fold> public static class ReadElemException extends Exception { public ReadElemException() {super();} public ReadElemException(String txt) {super(txt);} } private static class ReadTxtElemEx extends Exception { public ReadTxtElemEx() {super();} public ReadTxtElemEx(String txt) {super(txt);} } public static class ReadTxtCmplxException extends Exception { public ReadTxtCmplxException() {super();} public ReadTxtCmplxException(String txt) {super(txt);} } public static class EndOfFileException extends Exception { public EndOfFileException() {super();} public EndOfFileException(String txt) {super(txt);} } public static class ReadBinCmplxException extends Exception { public ReadBinCmplxException() {super();} public ReadBinCmplxException(String txt) {super(txt);} } public static class WriteTxtCmplxException extends Exception { public WriteTxtCmplxException() {super();} public WriteTxtCmplxException(String txt) {super(txt);} } public static class WriteBinCmplxException extends Exception { public WriteBinCmplxException() {super();} public WriteBinCmplxException(String txt) {super(txt);} } }
42,929
Java
.java
ignasi-p/eq-diagr
18
3
0
2018-08-17T08:25:37Z
2023-04-30T09:33:35Z
ShowDetailsDialog.java
/FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibDataBase/src/lib/database/ShowDetailsDialog.java
package lib.database; import lib.common.Util; /** Show the data in the databases for a single reaction. * <br> * Copyright (C) 2014-2020 I.Puigdomenech. * * 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 * 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/ * * @author Ignasi Puigdomenech */ public class ShowDetailsDialog extends javax.swing.JDialog { private java.awt.Dimension windowSize = new java.awt.Dimension(280,170); private boolean loading = true; private final java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); private final javax.swing.border.Border defBorder; private final javax.swing.border.Border highlightedBorder = javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED, java.awt.Color.gray, java.awt.Color.black); /** Creates new form NewJDialog * @param parent * @param modal * @param species * @param tC temperature in degrees Celsius * @param pBar pressure in bar * @param references */ public ShowDetailsDialog(java.awt.Frame parent, boolean modal, Complex species, double tC, double pBar, References references) { super(parent, modal); initComponents(); if(references == null) { jLabelRefText.setText("(file \"References.txt\" not found) "); jLabelRefText.setEnabled(false); jScrollPaneRefs.setVisible(false); pack(); } boolean dbg = true; if(species == null) { if(dbg) {System.out.println("Warning in \"DataDisplayDialog\": null species.");} } setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); //--- Close window on ESC key javax.swing.KeyStroke escKeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE,0, false); getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(escKeyStroke,"ESCAPE"); javax.swing.Action escAction = new javax.swing.AbstractAction() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { closeWindow(); }}; getRootPane().getActionMap().put("ESCAPE", escAction); //--- Alt-Q quit javax.swing.KeyStroke altQKeyStroke = javax.swing.KeyStroke.getKeyStroke( java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.ALT_MASK, false); getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altQKeyStroke,"ALT_Q"); getRootPane().getActionMap().put("ALT_Q", escAction); //--- Alt-X eXit javax.swing.KeyStroke altXKeyStroke = javax.swing.KeyStroke.getKeyStroke( java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK, false); getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altXKeyStroke,"ALT_X"); getRootPane().getActionMap().put("ALT_X", escAction); //---- Title, etc if(species != null && species.name.trim().length() > 0) { this.setTitle(" Data for \""+species.name.trim()+"\""); } else {this.setTitle(" Display Data");} defBorder = jScrollPaneRefs.getBorder(); //---- Centre window on parent/screen int left,top; if(parent != null) { left = Math.max(0,(parent.getX() + (parent.getWidth()/2) - this.getWidth()/2)); top = Math.max(0,(parent.getY()+(parent.getHeight()/2)-this.getHeight()/2)); } else { left = Math.max(0,(screenSize.width-this.getWidth())/2); top = Math.max(0,(screenSize.height-this.getHeight())/2); } this.setLocation(Math.min(screenSize.width-this.getWidth()-20,left), Math.min(screenSize.height-this.getHeight()-20, top)); //---- jTextAreaRefs.setLineWrap(true); jTextAreaRefs.setWrapStyleWord(true); jTextAreaRefs.setColumns(40); jTextAreaRefs.setText(""); //---- if(species == null) { jLabelReaction.setText("\"null\""); jLabellogK.setText(" (empty)"); jLabelDeltaH.setText(" (empty)"); jLabelDeltaCp.setText(" (empty)"); } else { double w,z; jLabelReaction.setText(species.reactionText()); if(Double.isNaN(species.constant) || species.constant == Complex.EMPTY) { jLabellogK.setText(" (empty)"); } else {jLabellogK.setText(Util.formatDbl3(species.constant));} if(!Double.isNaN(tC) && !Double.isNaN(pBar) && (tC<24.9 || tC > 25.1 || pBar > 1.1)) { w = species.logKatTandP(tC, pBar); if(!Double.isNaN(w) && w != Complex.EMPTY) { if(pBar < lib.kemi.H2O.IAPWSF95.CRITICAL_pBar) { jLabellogKTP.setText("<html>log <i>K</i>°("+Util.formatNumAsInt(tC).trim()+","+ String.format(java.util.Locale.ENGLISH,"%.2f bar",pBar)+") = "+Util.formatDbl3(w)+"</html>"); } else { jLabellogKTP.setText("<html>log <i>K</i>°("+Util.formatNumAsInt(tC).trim()+","+ String.format("%.0f bar",pBar)+") = "+Util.formatDbl3(w)+"</html>"); } } else {jLabellogKTP.setText("<html>log <i>K</i>°("+Util.formatNumAsInt(tC).trim()+","+ Util.formatNumAsInt((float)pBar).trim()+") = ??</html>");} } else {jLabellogKTP.setVisible(false);} if(species.analytic) { // analytic equation jLabel4.setVisible(false); jLabelDeltaCp.setVisible(false); jLabelDeltaH.setVisible(false); jLabel3.setText("<html>A 6-parameter function is used<br>to evaluate logK(t,p).</html>"); } else if(species.lookUp) { // look-up table of logK values jLabel4.setVisible(false); jLabelDeltaCp.setVisible(false); jLabelDeltaH.setVisible(false); jLabel3.setText("<html>A look-up table is used<br>to interpolate logK(t,p).</html>"); } else { // delta-H and delta-Cp w = species.getDeltaH(); if(w == Complex.EMPTY) { jLabelDeltaH.setText(" (empty)"); } else {jLabelDeltaH.setText(Util.formatDbl3(w));} w = species.getDeltaCp(); if(w == Complex.EMPTY) { jLabelDeltaCp.setText(" (empty)"); } else {jLabelDeltaCp.setText(Util.formatDbl3(w));} } w = species.tMax; if(Double.isNaN(w) || w == Complex.EMPTY || w <25) {w = 25.;} z = species.pMax; if(Double.isNaN(z) || z == Complex.EMPTY || z <1) {z = 1.;} jLabelTmax.setText("<html>Max logK extrapolation temperature: "+ String.format("%.0f",w)+"&deg;C, pressure: "+String.format("%.0f",z)+" bar</html>"); } if(species != null && species.reference != null && species.reference.trim().length() > 0) { String refs = species.reference.trim(); jLabelRefCit.setText(refs); if(references != null) { if(refs.trim().length() >0) { java.util.ArrayList<String> refKeys = lib.database.References.splitRefs(refs); jTextAreaRefs.append(references.refsAsString(refKeys)); } } } else {jLabelRefCit.setText(" (none)");} if(species != null && species.comment != null && species.comment.trim().length() > 0) { jLabelComments.setText(species.comment); } else {jLabelComments.setText(" (none)");} jTextAreaRefs.setCaretPosition(0); windowSize = this.getSize(); loading = false; pack(); jButtonOK.requestFocusInWindow(); } // constructor /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonGroup1 = new javax.swing.ButtonGroup(); jButtonOK = new javax.swing.JButton(); jLabel0 = new javax.swing.JLabel(); jLabelReaction = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); jLabellogK25 = new javax.swing.JLabel(); jLabellogK = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabelDeltaH = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabelDeltaCp = new javax.swing.JLabel(); jLabelTmax = new javax.swing.JLabel(); jLabellogKTP = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabelComments = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabelRefCit = new javax.swing.JLabel(); jLabelRefText = new javax.swing.JLabel(); jScrollPaneRefs = new javax.swing.JScrollPane(); jTextAreaRefs = new javax.swing.JTextArea(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); addComponentListener(new java.awt.event.ComponentAdapter() { public void componentResized(java.awt.event.ComponentEvent evt) { formComponentResized(evt); } }); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } }); jButtonOK.setMnemonic('c'); jButtonOK.setText(" Close "); jButtonOK.setAlignmentX(0.5F); jButtonOK.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jButtonOK.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonOKActionPerformed(evt); } }); jLabel0.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N jLabel0.setText("Reaction:"); jLabelReaction.setText("A + B = C"); jLabellogK25.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N jLabellogK25.setLabelFor(jLabellogK); jLabellogK25.setText("<html>log <i>K</i>&deg; (25&deg;C) =</html>"); jLabellogK.setText("-10.000"); jLabel3.setLabelFor(jLabelDeltaH); jLabel3.setText("<html>&#916;<i>H</i>&deg; =</html>"); jLabelDeltaH.setText("-10.000"); jLabel4.setLabelFor(jLabelDeltaCp); jLabel4.setText("<html>&#916;<i>C<sub>p</sub></i>&deg;=</html>"); jLabelDeltaCp.setText("-10.000"); jLabelTmax.setText("<html>Max temperature for extrapolation of logK = 25&deg;C</html>"); jLabellogKTP.setText("logK(32,8.64) = -10.000"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabelDeltaCp)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabellogK25, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabellogK) .addGap(49, 49, 49) .addComponent(jLabellogKTP)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabelDeltaH))) .addContainerGap(54, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabelTmax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabellogK25, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabellogK) .addComponent(jLabellogKTP)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabelDeltaH)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabelDeltaCp)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabelTmax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); jLabel6.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N jLabel6.setText("Comments:"); jLabelComments.setText(" (none)"); jLabel5.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N jLabel5.setText("Reference citations:"); jLabelRefCit.setText("##"); jLabelRefText.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N jLabelRefText.setText("References:"); jTextAreaRefs.setEditable(false); jTextAreaRefs.setColumns(40); jTextAreaRefs.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { jTextAreaRefsFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { jTextAreaRefsFocusLost(evt); } }); jTextAreaRefs.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jTextAreaRefsKeyPressed(evt); } public void keyTyped(java.awt.event.KeyEvent evt) { jTextAreaRefsKeyTyped(evt); } }); jScrollPaneRefs.setViewportView(jTextAreaRefs); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabelRefText) .addGap(242, 242, 242) .addComponent(jButtonOK) .addGap(24, 24, 24)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPaneRefs) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel0) .addGroup(layout.createSequentialGroup() .addGap(10, 10, 10) .addComponent(jLabelReaction)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabelComments)) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabelRefCit))) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel0) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabelReaction) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(jLabelComments)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(jLabelRefCit)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButtonOK, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabelRefText)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPaneRefs, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents //<editor-fold defaultstate="collapsed" desc="events"> private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing closeWindow(); }//GEN-LAST:event_formWindowClosing private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized if(loading || windowSize == null) {return;} int x = this.getX(); int y = this.getY(); int w = this.getWidth(); int h = this.getHeight(); int nw = Math.max(w, windowSize.width); int nh = Math.max(h, windowSize.height); int nx=x, ny=y; if(x+nw > screenSize.width) {nx = screenSize.width - nw;} if(y+nh > screenSize.height) {ny = screenSize.height -nh;} if(x!=nx || y!=ny) {this.setLocation(nx, ny);} if(w!=nw || h!=nh) {this.setSize(nw, nh);} }//GEN-LAST:event_formComponentResized private void jButtonOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOKActionPerformed closeWindow(); }//GEN-LAST:event_jButtonOKActionPerformed private void jTextAreaRefsKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextAreaRefsKeyPressed int ctrl = java.awt.event.InputEvent.CTRL_DOWN_MASK; if(((evt.getModifiersEx() & ctrl) == ctrl) && (evt.getKeyCode() == java.awt.event.KeyEvent.VK_V || evt.getKeyCode() == java.awt.event.KeyEvent.VK_X)) {evt.consume(); return;} if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) {evt.consume(); closeWindow(); return;} if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_TAB) {evt.consume(); return;} if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_DELETE) {evt.consume(); return;} if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_BACK_SPACE) {evt.consume();} }//GEN-LAST:event_jTextAreaRefsKeyPressed private void jTextAreaRefsKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextAreaRefsKeyTyped evt.consume(); }//GEN-LAST:event_jTextAreaRefsKeyTyped private void jTextAreaRefsFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextAreaRefsFocusGained if(jTextAreaRefs.isFocusOwner()) {jScrollPaneRefs.setBorder(highlightedBorder);} }//GEN-LAST:event_jTextAreaRefsFocusGained private void jTextAreaRefsFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextAreaRefsFocusLost if(!jTextAreaRefs.isFocusOwner()) {jScrollPaneRefs.setBorder(defBorder);} }//GEN-LAST:event_jTextAreaRefsFocusLost //</editor-fold> //<editor-fold defaultstate="collapsed" desc="closeWindow()"> private void closeWindow() { this.dispose(); } // closeWindow() // </editor-fold> // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.ButtonGroup buttonGroup1; private javax.swing.JButton jButtonOK; private javax.swing.JLabel jLabel0; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabelComments; private javax.swing.JLabel jLabelDeltaCp; private javax.swing.JLabel jLabelDeltaH; private javax.swing.JLabel jLabelReaction; private javax.swing.JLabel jLabelRefCit; private javax.swing.JLabel jLabelRefText; private javax.swing.JLabel jLabelTmax; private javax.swing.JLabel jLabellogK; private javax.swing.JLabel jLabellogK25; private javax.swing.JLabel jLabellogKTP; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPaneRefs; private javax.swing.JTextArea jTextAreaRefs; // End of variables declaration//GEN-END:variables }
23,960
Java
.java
ignasi-p/eq-diagr
18
3
0
2018-08-17T08:25:37Z
2023-04-30T09:33:35Z
Complex.java
/FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibDataBase/src/lib/database/Complex.java
package lib.database; import lib.kemi.H2O.IAPWSF95; import lib.common.Util; /** Contains data for a "complex": name, stoichiometry, formation equilibrium * constant, reference, etc. May be sorted according to name. * <br> * Copyright (C) 2014-2020 I.Puigdomenech. * * 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 * 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/ * * @author Ignasi Puigdomenech */ public class Complex implements Comparable<Complex>, Cloneable { /** the name of the reaction product */ public String name; /** the value of logK at 25 C */ public double constant; /** if <b>true</b>, parameter values (a[]) for an equation describing the * logK temperature dependency have been given for this reaction; * if <b>false</b> then either a look-up table is used, or * the values of delta-H (enthalpy) and delta-Cp (heat capacity) * for the reaction have been given, or are empty. * @see lib.database.Complex#lookUp lookUp * @see lib.database.Complex#a a[] * @see lib.database.Complex#pMax pMax * @see lib.database.Complex#tMax tMax */ public boolean analytic; /** if <b>true</b>, a look-up table of logK values (logKarray[][]) * is used to interpolate values of logK at the desired temperature * and pressure; if <b>false</b> then either an analytic power series * expression is used, or the values of delta-H (enthalpy) and delta-Cp * (heat capacity) for the reaction have been given, or are empty. * @see lib.database.Complex#analytic analytic * @see lib.database.Complex#logKarray logKarray * @see lib.database.Complex#pMax pMax * @see lib.database.Complex#tMax tMax */ public boolean lookUp; /** the parameters for the analytic logK(t) equation<br> * (log K(t)= a[0] + a[1] T + a[2]/T + a[3] log10(T) + a[4] / T^2 + a[5] T^2)<br> * where T is the temperature in Kelvin. If <b>analytic</b> = false, then * the enthalpy + heat-capacity values have been given, and * values of a[0], a[2] and a[3] are calculated from the enthalpy * and heat capacity. * @see lib.database.Complex#analytic analytic * @see lib.database.Complex#pMax pMax * @see lib.database.Complex#tMax tMax */ public double[] a; /** A grid of logK values, from which values are interpolated at the * desired temperature and pressure; pressure is the first index (0 to 4) * and temperatures is the second index (0 to 13). The temperature * (degrees Celsius) and pressure (bar) grid is in the following table: * <pre> * t= 0, 25, 50, 100, 150, 200, 250, 300, 350,400,450,500,550,600C * p= 1, 1, 1, 1.01, 4.76, 15.6, 39.8, 85.9, 165,300, - , - , - , - * 500,500,500, 500, 500, 500, 500, 500, 500,500,500,650,900,950 * 1k, 1k, 1k, 1k, 1k, 1k, 1k, 1k, 1k, 1k, 1k, 1k, 1k, 1k * 3k, 3k, 3k, 3k, 3k, 3k, 3k, 3k, 3k, 3k, 3k, 3k, 3k, 3k * 5k, 5k, 5k, 5k, 5k, 5k, 5k, 5k, 5k, 5k, 5k, 5k, 5k, 5k</pre> * <b>Note:</b> use Double.NaN (Not-a-Number) where no data is available, * for example at temperatures above 400C and pressures below 300bar. * @see lib.database.Complex#lookUp lookUp * @see lib.database.Complex#pMax pMax * @see lib.database.Complex#tMax tMax */ public float[][] logKarray; /** The highest temperature limit (Celsius) for the temperature extrapolations. * If no <b>analytic</b> equation has been given (that is, * if <b>analytic</b> = false) then: tMax = 25 if values for * enthalpy and heat capacity have not been given, tMax = 100 * if enthalpy has been given but not the heat capacity, and * tMax = 300 if both enthalpy and heat capacity have been given * for this reaction. Upper limit for tMax is 1000 in "logKatTandP" * and in "logKatTpSat" * @see lib.database.Complex#pMax pMax * @see lib.database.Complex#a a[] * @see lib.database.Complex#analytic analytic */ public double tMax; /** The highest pressure limit (bar) for the pressure extrapolations. * If no <b>analytic</b> equation has been given (that is, * if <b>analytic</b> = false) then: pMax = 1 if values for * enthalpy and heat capacity have not been given or if only the * enthalpy has been given (but not the heat capacity), and * pMax = 85.9 (= pSat(300)) if both enthalpy and heat capacity have * been given for this reaction. If <b>analytic</b> = true then the * value of "pSat" at the tMax temperature is used for pMax. * Upper limit for pMax is 5000 in "logKatTandP" and in "logKatTpSat" * @see lib.database.Complex#tMax tMax * @see lib.database.Complex#a a[] * @see lib.database.Complex#analytic analytic */ public double pMax; /** the names of the reactants */ public java.util.ArrayList<String> reactionComp; /** the stoichiometric coefficients for the reactants */ public java.util.ArrayList<Double> reactionCoef; /** a text containing citations to zero or more references (the source of logK etc). * Citations may be separated by comma (,) semicolon (;) or plus (+). * Separators may be enclosed between parentheses, for example: "A+(=Fe+3),D" * contains three citations to "A", "(=Fe+3)" and "D". */ public String reference; /** a comment, such a chemical formula, etc */ public String comment; /** EMPTY = -999999.9, a value used to indicate missing data **/ public static final double EMPTY = -999999.9; /** ANALYTIC = -888888.8, a value used when reading the enthalpy of reaction * from binary databases, to indicate that instead of enthalpy and heat * capacity, an anlytic power series expression is used to represent the * temperature and pressure variation of loK * @see lib.database.Complex#anaytic analytic * @see lib.database.Complex#a a[] */ public static final double ANALYTIC = -888888.8; /** LOOKUP = -888888.8, a value used when reading the enthalpy of reaction * from binary databases, to indicate that instead of enthalpy and heat * capacity, an analytic power series expression is used to represent the * temperature and pressure variation of loK * @see lib.database.Complex#anaytic analytic * @see lib.database.Complex#a a[] */ public static final double LOOKUP = -777777.7; public static final String FILE_FIRST_LINE = "COMPLEX;LogK;DH_kJmol;DCp_Jmol;R1;N1;R2;N2;R3;N3;R4;N4;R5;N5;R6;N6;H;Reference / Comment"; /** the number of reactants for the "old" complex format */ public static final int NDIM = 6; /** New-line character(s) to substitute "\n" */ private static final String nl = System.getProperty("line.separator"); /** natural logarithm of 10 */ private static final double ln10 = Math.log(10); /** the reference temperature = 298.15 K (=25C) */ private static final double T0 = 298.15; /** the gas constant R = 8.3144598 J/(mol K) */ private static final double R = 8.3144598; // J/(mol K) /** R * ln(10) */ private static final double R_LN10 = R*ln10; // J/(mol K) /** (1 + ln(T0) */ private static final double lnT0plus1 = 1.+Math.log(T0); // public Complex() { name = ""; // flags that no value has been given constant = EMPTY; analytic = false; lookUp = false; tMax = 25.; pMax = 1.; a = new double[6]; for(int i=0; i < a.length; i++) {a[i] = EMPTY;} logKarray = new float[5][]; reactionComp = new java.util.ArrayList<>(); reactionCoef = new java.util.ArrayList<>(); reference = ""; comment = ""; } @Override public Complex clone() throws CloneNotSupportedException { super.clone(); Complex c = new Complex(); c.name = this.name; c.constant = this.constant; c.analytic = this.analytic; c.lookUp = this.lookUp; c.tMax = this.tMax; c.pMax = this.pMax; if(this.a != null && this.a.length > 0) {System.arraycopy(this.a, 0, c.a, 0, this.a.length);} for (int i = 0; i < this.logKarray.length; i++) { if (this.logKarray[i] != null) { c.logKarray[i] = new float[this.logKarray[i].length]; System.arraycopy(this.logKarray[i], 0, c.logKarray[i], 0, this.logKarray[i].length); } } for (String t : this.reactionComp) {c.reactionComp.add(t);} for (Double w : this.reactionCoef) {c.reactionCoef.add(w);} c.reference = this.reference; c.comment = this.comment; return c; } //<editor-fold defaultstate="collapsed" desc="compareTo(Complex)"> /** For sorting reaction products. With different names (ignoring case) reaction products are sorted * alphabetically. * <p> * If the name is the same (ignoring case): then if they have the same stoichiometry, * they are considered equal. Note: If you store Complexes in a sorted java.util.TreeSet, then * you will not be able to have two Complexes that are equal. * <p> * If the name is the same but the stoichiometry differs: they will be sorted according * to their components (and "proton"): the complex with more components goes after, * or if equal number of components, the complex with larger sum of (stoichiometric coefficients) * is sorted after. * <p> * <b>Note:</b> this is not fool proof. For example, it does not check if a * component is given twice for any of the Complexes, or if a stoichiometric * coefficient is given but the component has no name, etc. * @param other a Complex * @return The compareTo method returns zero if the Complex passed is equal to this instance. * It returns a negative value if this Complex is less than (preceedes) the Complex argument; * and a value >0 if this Complex is greater than the Complex argument. */ @Override public int compareTo(Complex other) { // --- check for empty names if(this.name == null) { if(other.name != null) {return -1;} } else if(this.name.length() <=0) { if(other.name == null) {return 1;} if(other.name.length() >0) {return -1;} } else { //this name is not empty if(other.name == null || other.name.length() <=0) {return 1;} } // --- names are not empty int k =0; if(this.name != null && other.name != null) {k = this.name.compareToIgnoreCase(other.name);} // --- names are not equal (ignoring case): if(k != 0) {return k;} // --- names are equal (ignoring case): check stoichiometry k = this.sortReactants().toString().compareToIgnoreCase(other.sortReactants().toString()); return k; } //compareTo(Complex) //</editor-fold> //<editor-fold defaultstate="collapsed" desc="isEqualTo(Complex)"> /** Check if two Complexes are "equal". * The names of species are compared taking into account different ways to write * charges so that "Fe+3" is equal to "Fe 3+". Also "CO2" is equivalent to "CO2(aq)". * @param other * @return true if the two Complexes have the same name and data (equilibrium constant) * and if the reaction is the same, even if the order of the reactants differs. * For example, <code>A + B = C</code> is equal to <code>B + A = C</code> * @see Complex#sameNameAndStoichiometry sameNameAndStoichiometry */ public boolean isEqualTo(Complex other) { final boolean dbg = false; if(this == null && other == null) { if(dbg) {System.out.println("isEqualTo = true (both null)");} return true; } else if(this == null || other == null) { if(dbg) {System.out.println("isEqualTo = false (one is null)");} return false; } // -- check names if(!Util.nameCompare(this.name, other.name)) { if(dbg) {System.out.println("isEqualTo = false (names different)");} return false; } // -- check data if(!Util.areEqualDoubles(this.constant, other.constant)) { if(dbg) {System.out.println("isEqualTo = false (logK different)");} return false; } if(this.analytic != other.analytic) { if(dbg) {System.out.println("isEqualTo = false (analytic flag different)");} return false; } if(this.lookUp != other.lookUp) { if(dbg) {System.out.println("isEqualTo = false (look-up flag different)");} return false; } if(!Util.areEqualDoubles(this.tMax, other.tMax)) { if(dbg) {System.out.println("isEqualTo = false (tMax different)");} return false; } if(!Util.areEqualDoubles(this.pMax, other.pMax)) { if(dbg) {System.out.println("isEqualTo = false (pMax different)");} return false; } for(int i = 0; i < this.a.length; i++) { if(!Util.areEqualDoubles(this.a[i], other.a[i])) { if(dbg) {System.out.println("isEqualTo = false (a["+i+"] different: "+this.a[i]+", "+other.a[i]+")");} return false; } } for(int i = 0; i < this.logKarray.length; i++) { if(this.logKarray[i] == null && other.logKarray[i] == null) {continue;} if((this.logKarray[i] != null && other.logKarray[i] == null) || (this.logKarray[i] == null && other.logKarray[i] != null)) { if(dbg) {System.out.println("isEqualTo = false (one of logKarray["+i+"] is null.");} return false; } for(int j = 0; j < this.logKarray[i].length; j++) { if(!Util.areEqualDoubles(this.logKarray[i][j], other.logKarray[i][j])) { if(dbg) {System.out.println("isEqualTo = false (logKarray["+i+"]["+j+"] different: "+ this.logKarray[i][j]+", "+other.logKarray[i][j]+")");} return false; } } } this.reactionComp.trimToSize(); other.reactionComp.trimToSize(); int nTotThis = Math.min(this.reactionComp.size(),this.reactionCoef.size()); int nTotOther = Math.min(other.reactionComp.size(),other.reactionCoef.size()); if(nTotThis != nTotOther) { if(dbg) {System.out.println("isEqualTo = false (reaction sizes: this="+nTotThis+", other="+nTotOther+" are different)");} return false; } int thisNComps = 0, otherNComps = 0; int k; double coef1, coef2; // -- first check that all components in "this" are found in "other" int nTot = Math.min(this.reactionComp.size(),this.reactionCoef.size()); for(int i=0; i < nTot; i++) { coef1 = this.reactionCoef.get(i); if(Math.abs(coef1) >= 0.001) {thisNComps++;} if(this.reactionComp.get(i) == null || this.reactionComp.get(i).length()<=0) {continue;} k =-1; for(int i2=0; i2 < nTot; i2++) { if(other.reactionComp.get(i2) == null || other.reactionComp.get(i2).length()<=0) {continue;} if(Util.nameCompare(this.reactionComp.get(i),other.reactionComp.get(i2))) {k = i2; break;} }//for i2 if(k < 0) { //the component "i" is not present in the other Complex if(dbg) {System.out.println("isEqualTo = false (reactions different; "+this.reactionComp.get(i)+")");} return false; } else { //k >= 0: both Complexes have the same component coef2 = other.reactionCoef.get(k); if(Math.abs(coef1-coef2) >= 0.001) { if(dbg) {System.out.println("isEqualTo = false (reactions different; "+this.reactionComp.get(i)+")");} return false; } } //k } //for i // -- now check that all components in "other" are also found in "this" // so that "other" does not have more components than "this" for(int i=0; i < nTot; i++) { coef2 = other.reactionCoef.get(i); if(Math.abs(coef2) >= 0.001) {otherNComps++;} if(other.reactionComp.get(i) == null || other.reactionComp.get(i).length()<=0) {continue;} k =-1; for(int i2=0; i2 < nTot; i2++) { if(this.reactionComp.get(i2) == null || this.reactionComp.get(i2).length()<=0) {continue;} if(Util.stringsEqual(other.reactionComp.get(i),this.reactionComp.get(i2))) {k = i2; break;} }//for i2 if(k < 0) { //the component "i" is not present in the other Complex if(dbg) {System.out.println("isEqualTo = false (reactions different; "+other.reactionComp.get(i)+")");} return false; } else { //k >= 0: both Complexes have the same component coef1 = this.reactionCoef.get(k); if(Math.abs(coef2-coef1) >= 0.001) { if(dbg) {System.out.println("isEqualTo = false (reactions different; "+other.reactionComp.get(i)+")");} return false; } } //k } //for i if(thisNComps != otherNComps) { if(dbg) {System.out.println("isEqualTo = false (different nbr reactants)");} return false; } if(!Util.stringsEqual(this.reference,other.reference)) { if(dbg) {System.out.println("isEqualTo = false (reference different)");} return false; } if(!Util.stringsEqual(this.comment,other.comment)) { if(dbg) {System.out.println("isEqualTo = false (comment different)");} return false; } if(dbg) {System.out.println("isEqualTo = true ("+this.name+")");} return true; } //isEqualTo(Complex) //</editor-fold> //<editor-fold defaultstate="collapsed" desc="isRedox()"> /** Check if "electron" is one of the reactants. * @return true if "electron" is one of the reactants and its stoichiometric coefficient is not zero */ public boolean isRedox() { int nTot = Math.min(this.reactionComp.size(),this.reactionCoef.size()); for(int i=0; i < nTot; i++) { if(Double.isNaN(this.reactionCoef.get(i)) || Math.abs(this.reactionCoef.get(i)) < 0.0001) {continue;} if(this.reactionComp.get(i) == null || this.reactionComp.get(i).trim().length() <=0) {continue;} if(Util.isElectron(this.reactionComp.get(i))) {return true;} } return false; } //isRedox(Complex) //</editor-fold> //<editor-fold defaultstate="collapsed" desc="sortReactants()"> /** Sorts the reactants of a complex in alphabetical order, * except that:<ul> * <li>If the reaction contains H+, e-, H2O, these reactants are placed first. </li> * <li>If two reactants are equal the result is not predictable.</li> * <li>Empty reactants (or reactants with zero coefficient) are removed.</li> * </ul> * @return a Complex with the reactants sorted */ public Complex sortReactants() { int nTot = Math.min(this.reactionComp.size(),this.reactionCoef.size()); String[] r = new String[nTot]; double[] d = new double[nTot]; for(int i = 0; i < nTot; i++) { r[i] = this.reactionComp.get(i); } java.util.Arrays.sort(r); for(int i=0; i < r.length; i++) { for(int j=0; j < nTot; j++) { if(Util.nameCompare(r[i],this.reactionComp.get(j))) {d[i] = this.reactionCoef.get(j);} } } double w; String s; // move H2O to the top for(int i=1; i < r.length; i++) { // if "H2O" is in positio zero, do nothing s = r[i]; w = d[i]; if(Util.isWater(s)) { for(int j=i-1; j >= 0; j--) {r[j+1] =r[j]; d[j+1] =d[j];} r[0] = s; d[0] = w; break; } } // move e- to the top for(int i=1; i < r.length; i++) { // if "e-" is in positio zero, do nothing s = r[i]; w = d[i]; if(Util.isElectron(s)) { for(int j=i-1; j >= 0; j--) {r[j+1] =r[j]; d[j+1] =d[j];} r[0] = s; d[0] = w; break; } } // move H+ to the top for(int i=1; i < r.length; i++) { // if "H+" is in positio zero, do nothing s = r[i]; w = d[i]; if(Util.isProton(s)) { for(int j=i-1; j >= 0; j--) {r[j+1] =r[j]; d[j+1] =d[j];} r[0] = s; d[0] = w; break; } } this.reactionComp.clear(); this.reactionCoef.clear(); for(int i = 0; i < r.length; i++) { if(r[i] == null || r[i].trim().length() <= 0 || Math.abs(d[i]) < 0.00001) {continue;} this.reactionComp.add(r[i]); this.reactionCoef.add(d[i]); } return this; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="sameNameAndStoichiometry(cmplx1, cmplx2)"> /** Checks if the name of the two products is equivalent, and if the two Complexes * have the same reaction, even if the order of the reactants differs. * The names of the reaction products are compared taking into account different ways to write * charges so that <nobr>"Fe+3"</nobr> is equal to <nobr>"Fe 3+".</nobr> * Also <nobr>"CO2"</nobr> is equivalent to <nobr>"CO2(aq)".</nobr> * But <nobr>H4SiO4</nobr> is not equal to <nobr>Si(OH)4,</nobr> and not equal to <nobr>SiO2.</nobr> * @param cmplx1 * @param cmplx2 * @return <ul><li>if the two Complexes have the same reaction, even if the order of the * reactants differs, then returns <code>true</code> if the product names are * equvalent and <code>false</code> if they differ.</li> * <li>if the two Complexes have a different reaction it returns <code>false</code></li> * <li>For example,<br> * (1) <code>A + B = C</code><br> * (2) <code>B + A = C</code><br> * (3) <code>A + B + H2O = C</code><br> * (4) <code>A + B = F</code><br> * then (1)+(3) returns <code>false</code> (different reaction), * <nobr>(1)+(2)</nobr> returns <code>true</code> (same reaction, same name), * <nobr>(1)+(4)</nobr> returns <code>false</code> (same reaction, different name).</li></ul> * @see lib.database.Complex#checkNameSameStoichiometry(lib.database.Complex, lib.database.Complex) checkNameSameStoichiometry * @see lib.database.Complex#isEqualTo isEqualTo */ public static boolean sameNameAndStoichiometry(Complex cmplx1, Complex cmplx2) { if(cmplx1.name == null) { if(cmplx2.name != null) {return false;} } else if(cmplx1.name.length() <=0) { if(cmplx2.name == null || cmplx2.name.length() >0) {return false;} } else { //cmplx1.name.length() >0 if(cmplx2.name == null || cmplx2.name.length() <=0) {return false;} if(!Util.nameCompare(cmplx1.name,cmplx2.name)) {return false;} } if(cmplx1.reactionComp.size() != cmplx2.reactionComp.size() || cmplx1.reactionCoef.size() != cmplx2.reactionCoef.size()) {return false;} double coef1, coef2; int found; // -- first check that all components in "1" are found in "2" int nTot = Math.min(cmplx1.reactionComp.size(), cmplx1.reactionCoef.size()); for(int i=0; i< nTot; i++) { if(cmplx1.reactionComp.get(i) == null || cmplx1.reactionComp.get(i).length() <=0) {continue;} coef1 = cmplx1.reactionCoef.get(i); found =-1; for(int i2=0; i2< nTot; i2++) { if(cmplx2.reactionComp.get(i2) == null || cmplx2.reactionComp.get(i2).length() <=0) {continue;} if(Util.nameCompare(cmplx1.reactionComp.get(i),cmplx2.reactionComp.get(i2))) {found = i2; break;} }//for i2 if(found > -1) { coef2 = cmplx2.reactionCoef.get(found); if(Math.abs(coef1-coef2) > 0.001) {return false;} } //if found else { //not found return false; } //found? } //for i // -- now check that all components in "2" are also found in "1" // so that "2" does not have more components than "1" for(int i=0; i< nTot; i++) { if(cmplx2.reactionComp.get(i) == null || cmplx2.reactionComp.get(i).length() <=0) {continue;} coef2 = cmplx2.reactionCoef.get(i); found =-1; for(int i2=0; i2< nTot; i2++) { if(cmplx1.reactionComp.get(i) == null || cmplx1.reactionComp.get(i).length() <=0) {continue;} if(Util.nameCompare(cmplx2.reactionComp.get(i),cmplx1.reactionComp.get(i2))) {found = i2; break;} }//for i2 if(found > -1) { coef1 = cmplx1.reactionCoef.get(found); if(Math.abs(coef2-coef1) > 0.001) {return false;} } //if found else { //not found return false; } //found? } //for i return true; } //sameNameAndStoichiometry //</editor-fold> //<editor-fold defaultstate="collapsed" desc="toLookUp()"> /** Converts the analytic expression to values of logKarray at pSat * (the saturated vapor-liquid pressure) for temperatures between * 0 and 350 C. Sets "lookUp"=true. * The values of logKarray are calculated using the <b>a[]</b>-parameters * for the logK(t) equation<br> * (log K(t)= a[0] + a[1] T + a[2]/T + a[3] log10(T) + a[4] / T^2 + a[5] T^2)<br> * where T is the temperature in Kelvin. The value of "tMax" is set to a * maximum value of 350, and "pMax" is set to 165.3 bar (=pSat(350)). * * @see lib.database.Complex#analytic analytic * @see lib.database.Complex#a a * @see lib.database.Complex#lookUp lookUp * @see lib.database.Complex#deltaToA(double, double, double) deltaToA * @see lib.database.Complex#logKatTandP(double, double) logKatTandP * @see lib.database.Complex#logKarray logKarray */ public void toLookUp() { if(lookUp) {return;} if(logKarray == null) {logKarray = new float[5][];} for(int i=0; i < logKarray.length; i++) { if(logKarray[i] == null) { logKarray[i] = new float[14]; for(int j=0; j < logKarray[i].length; j++) {logKarray[i][j] = Float.NaN;} } } double[] t = new double[]{0, 25, 50, 100, 150, 200, 250, 300, 350}; double[] p = new double[]{1, 1, 1, 1.0142, 4.762, 15.55, 39.764, 85.88, 165.3}; // values of pSat for(int j=0; j < t.length; j++) { logKarray[0][j] = (float)logKatTpSat(t[j]); if(!Float.isNaN(logKarray[0][j])) { tMax = Math.max(t[j], tMax); pMax = Math.max(p[j], pMax); } } tMax = Math.max(25.,Math.min(350., tMax)); pMax = Math.max(1., Math.min(165.3, pMax)); // = pSat(350) lookUp = true; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="deltaToA(logK0,deltaH,deltaCp)"> /** Returns the <b>a[]</b>-parameters for the logK(t) equation<br> * (log K(t)= a[0] + a[1] T + a[2]/T + a[3] log10(T) + a[4] / T^2 + a[5] T^2)<br> * where T is the temperature in Kelvin, equivalent to the given values of * delta-H (entropy) and deltaCp (heat capacity) for the reaction. * @param logK0 the log10 of the equilibrium constant at 25C * @param deltaH the enthalpy change for the reaction in kJ/mol * @param deltaCp the heat capacity change for the reaction in J/(K mol) * @return the values of the <b>a[]</b> parameters: all EMPTY except<br> * a[0] = logK + deltaH*1000/(R T0 ln(10)) − deltaCp /(R ln(10)) (1 + ln(T0))<br> * a[2] = -deltaH*1000/(R ln(10)) + deltaCp T0 /(R ln(10)) * a[3] = deltaCp /R<br> * where R is the gas constant, and T0 is the reference temperature (298.15 K). * These values are obtained from<pre> * logK(T) = logK(T0) - (deltaH/(R ln(10)))((1/T)-(1/T0))-(deltaCp/(R ln(10)))(1-(T0/T)+ln(10)*log(T0/T)) * logK(T) = logK(T0) + deltaH/(R T0 ln(10)) - deltaCp/(R ln(10))(1+ln(T0)) * +(- deltaH/(R ln(10)) + deltaCp T0 /(R ln(10))) / T * +(deltaCp/R) log10(T)</pre> * * @see lib.database.Complex#anaytic analytic * @see lib.database.Complex#a a[] * @see lib.database.Complex#aToDeltaH(double[]) aToDeltaH */ public static double[] deltaToA(final double logK0, final double deltaH, final double deltaCp) { double[] a = new double[6]; for(int i=0; i < a.length; i++) {a[i] = EMPTY;} a[0] = logK0; if(Double.isNaN(deltaH) || deltaH == EMPTY) {return a;} a[0] = a[0] + deltaH*1000/(R_LN10*T0); a[2] = - deltaH*1000/R_LN10; if(Double.isNaN(deltaCp) || deltaCp == EMPTY) {return a;} a[0] = a[0] - (deltaCp * lnT0plus1) / R_LN10; a[2] = a[2] + (deltaCp*T0) /R_LN10; a[3] = deltaCp / R; return a; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="getDeltaH()"> /** returns the reaction enthalpy calculated from the <b>a[]</b>-parameters * for the logK(t) equation<br> * (log K(t)= a[0] + a[1] T + a[2]/T + a[3] log10(T) + a[4] / T^2 + a[5] T^2<br> * + (a[6] + a[7] T + a[8] log10(T)+ a[9] T^2) log(rho-H2O))<br> * (T is the temperature in Kelvin). * @return the enthalpy of reaction in kJ/mol<br> * deltaH = R ln(10) (a[1] T0^2 − a[2] + a[3] T0 /ln(10) − 2 a[4] / T0 + 2 a[5] T0^3)<br> * where R is the gas constant, and T0 is the reference temperature (298.15 K). * @see lib.database.Complex#anaytic analytic * @see lib.database.Complex#deltaToA(double, double, double) deltaToA * @see lib.database.Complex#aToDeltaCp(double[]) aToDeltaCp * @see lib.database.Complex#a a[] */ public double getDeltaH() { double deltaH; if(a[0] == EMPTY || a[2] == EMPTY) {return EMPTY;} deltaH = 0.; if(a[1] != EMPTY && a[1] != 0.) {deltaH = a[1]*T0*T0;} if(a[2] != EMPTY && a[2] != 0.) {deltaH = deltaH - a[2];} if(a[3] != EMPTY && a[3] != 0.) {deltaH = deltaH + a[3]*T0/ln10;} if(a[4] != EMPTY && a[4] != 0.) {deltaH = deltaH - 2.*a[4]/T0;} if(a[5] != EMPTY && a[5] != 0.) {deltaH = deltaH - 2.*a[5]*T0*T0*T0;} return R_LN10*deltaH/1000.; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="getDeltaCp()"> /** returns the reaction heat capacity calculated from the <b>a[]</b>-parameters * for the logK(t) equation<br> * (log K(t)= a[0] + a[1] T + a[2]/T + a[3] log10(T) + a[4] / T^2 + a[5] T^2<br> * + (a[6] + a[7] T + a[8] log10(T)+ a[9] T^2) log(rho-H2O))<br> * (T is the temperature in Kelvin). * @return the heat capacity of reaction in J/(K mol)<br> * deltaCp = deltaCp = R ln(10) (2 a[1] T0 + a[3]/ln(10) + 2 a[4] / T0^2 + 6 a[5] T0^2)<br> * where R is the gas constant, and T0 is the reference temperature (298.15 K). * @see lib.database.Complex#anaytic analytic * @see lib.database.Complex#deltaToA(double, double, double) deltaToA * @see lib.database.Complex#aToDeltaH(double[]) aToDeltaH * @see lib.database.Complex#a a[] */ public double getDeltaCp() { double deltaCp; if(a[0] == EMPTY || a[2] == EMPTY || a[3] == EMPTY) {return EMPTY;} deltaCp = 0.; if(a[1] != EMPTY && a[1] != 0.) {deltaCp = 2.*a[1]*T0;} if(a[3] != EMPTY && a[3] != 0.) {deltaCp = deltaCp + a[3]/ln10;} if(a[4] != EMPTY && a[4] != 0.) {deltaCp = deltaCp + 2.*a[4]/(T0*T0);} if(a[5] != EMPTY && a[5] != 0.) {deltaCp = deltaCp + 6.*a[5]*T0*T0;} return R_LN10*deltaCp; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="fromString(text)"> /** Get a Complex with data read within a sting with ";" separated values. * The comment (if any) is read after a slash "/" following either a semicolon, a space, or a comma. * @param textLines for example: "<code>Fe 3+;-13.02;;;Fe 2+;1;;;e-;-1;;;;;;;0;Wateq4F /comment</code>" * @return an instance of Complex or <code>null</code> if the reaction product is empty or "COMPLEX" * @see lib.database.Complex#toString() toString * @throws lib.database.Complex.ReadComplexException */ public static Complex fromString(String textLines) throws ReadComplexException { if(textLines == null || textLines.length() <= 0 || textLines.trim().startsWith("/")) {return null;} // Check if the input text string contains several lines java.util.ArrayList<String> lines = new java.util.ArrayList<>(); try (java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.StringReader(textLines))) { String line = reader.readLine(); while (line != null) { lines.add(line); line = reader.readLine(); } } catch (java.io.IOException exc) { String msg; if(textLines.length() <=40) {msg = textLines;} else {msg = textLines.substring(0, 38)+"...";} throw new ReadComplexException("\"Complex.fromString("+msg+"): "+nl+ lib.common.Util.stack2string(exc)); } StringBuilder nowReading = new StringBuilder(); java.util.ArrayList<String> aList; int i,j,nr, n, line = -1; String t; double deltaH, deltaCp; Complex c = new Complex(); // -- loop through the lines // (in most cases there is only one line) for(String text: lines) { line++; if(text.indexOf(';')<0 && text.indexOf(',')<0) { if(line == 0 && text.startsWith("@")) {text = text.trim()+";";} else {throw new ReadComplexException("Line \""+text+"\""+nl+ "contains neither semicolons nor commas"+nl+ "in \"Complex.fromString()\"");} } try{aList = CSVparser.splitLine(text);} catch (CSVparser.CSVdataException ex) {throw new ReadComplexException("CSVdataException: "+ ex.getMessage()+nl+"in \"Complex.fromString()\"");} n = 0; //System.out.println("line = "+text); if(c.lookUp) { // this means that this is not the first line //System.out.println("line nr="+line); c.logKarray[line-1] = new float[14]; try{ for(i = 0; i < c.logKarray[line-1].length; i++) { nowReading.replace(0, nowReading.length(), "logKarray["+(line-1)+"]["+i+"]"); if(n < aList.size()) { if(aList.get(n).length() >0) {c.logKarray[line-1][i] = Float.parseFloat(aList.get(n));} else {c.logKarray[line-1][i] = Float.NaN;} } else { throw new ReadComplexException("Error in \"Complex.fromString()\":"+nl+ "missing data in line: "+text+nl+ "while reading "+nowReading.toString()+nl+"for \""+c.name+"\""); } n++; } // for a[i] } catch (NumberFormatException ex) { throw new ReadComplexException("Error in \"Complex.fromString()\":"+nl+ ex.toString()+nl+"in line: "+text+nl+ "while reading "+nowReading.toString()+""); } continue; } // if c.lookUp try{ nowReading.replace(0, nowReading.length(), "name"); if(n < aList.size()) {c.name = aList.get(n);} else { throw new ReadComplexException("Error in \"Complex.fromString()\":"+nl+ "missing reaction product name in line: \""+text+"\""); } if(c.name.equalsIgnoreCase("COMPLEX")) {return null;} if(c.name.length() <=0) { for (i=1; i<aList.size(); i++) { // check that the reaction is empty. Comments are OK if(aList.get(i) != null && aList.get(i).trim().length() >0) { throw new ReadComplexException( "Empty reaction product in line:"+nl+" \""+text+"\""+nl+ "found in \"Complex.fromString()\""); } } return null; } n++; nowReading.replace(0, nowReading.length(), "logK"); if(n < aList.size()) { if(aList.get(n).length() >0) {c.constant = Double.parseDouble(aList.get(n)); } else {c.constant = EMPTY;} } else { throw new ReadComplexException("Error in \"Complex.fromString()\":"+nl+ "missing data while reading "+nowReading.toString()+nl+"for \""+c.name+"\""); } n++; nowReading.replace(0, nowReading.length(), "delta-H or \"analytic\""); if(n < aList.size()) { t = aList.get(n).trim(); if(t != null && t.length() >0) { if(t.equalsIgnoreCase("analytic") || t.equalsIgnoreCase("-analytic")) {c.analytic = true;} if(t.toLowerCase().startsWith("lookup") || t.toLowerCase().startsWith("-lookup")) {c.lookUp = true;} } } else { throw new ReadComplexException("Error in \"Complex.fromString()\":"+nl+ "missing data while reading "+nowReading.toString()+nl+"for \""+c.name+"\""); } n++; if(!c.analytic) { if(!c.lookUp) { // not analytic and not look-up table if(t != null && t.length() >0) {deltaH = Double.parseDouble(t);} else {deltaH = EMPTY;} nowReading.replace(0, nowReading.length(), "delta-Cp"); if(n < aList.size()) { if(aList.get(n).length() >0) {deltaCp = Double.parseDouble(aList.get(n));} else {deltaCp = EMPTY;} } else { throw new ReadComplexException("Error in \"Complex.fromString()\":"+nl+ "missing data while reading "+nowReading.toString()+nl+"for \""+c.name+"\""); } n++; c.tMax = 25.; c.pMax = 1.; if(deltaH != EMPTY) {c.tMax = 100.; if(deltaCp != EMPTY) {c.tMax = 300.; c.pMax = 85.9;}} // = pSat(300) c.a = deltaToA(c.constant, deltaH, deltaCp); } else { // look-up Table nowReading.replace(0, nowReading.length(), "Max-temperature"); c.pMax = 5000.; if(n < aList.size()) { if(aList.get(n).length() >0) {c.tMax = Double.parseDouble(aList.get(n));} if(c.tMax > 600) {throw new ReadComplexException("Error in \"Complex.fromString()\":"+nl+ "while reading \""+nowReading.toString()+"\" (should <= 600 C)"+nl+"for \""+c.name+"\"");} } else { throw new ReadComplexException("Error in \"Complex.fromString()\":"+nl+ "missing data while reading "+nowReading.toString()+nl+"for \""+c.name+"\""); } n++; } // lookUp? } else { // analytic nowReading.replace(0, nowReading.length(), "Max-temperature"); if(n < aList.size()) { if(aList.get(n).length() >0) {c.tMax = Double.parseDouble(aList.get(n));} } else { throw new ReadComplexException("Error in \"Complex.fromString()\":"+nl+ "missing data while reading "+nowReading.toString()+nl+"for \""+c.name+"\""); } if(c.tMax > 373.) {throw new ReadComplexException("Error in \"Complex.fromString()\":"+nl+ "while reading \""+nowReading.toString()+"\" (should be below 373 C: the critical point)"+nl+"for \""+c.name+"\"");} c.pMax = Math.max(1.,lib.kemi.H2O.IAPWSF95.pSat(c.tMax)); n++; for(i = 0; i < c.a.length; i++) { nowReading.replace(0, nowReading.length(), "parameter a["+i+"]"); if(n < aList.size()) { if(aList.get(n).length() >0) { nowReading.append(", text:\""+aList.get(n)+"\""); c.a[i] = Double.parseDouble(aList.get(n)); } else {c.a[i] = EMPTY;} } else { throw new ReadComplexException("Error in \"Complex.fromString()\":"+nl+ "missing data while reading "+nowReading.toString()+nl+"for \""+c.name+"\""); } n++; } // for a[i] } // analytic double n_H = 0; boolean thereisHplus = false, foundReactant; c.reactionComp.clear(); c.reactionCoef.clear(); int nTot; nowReading.replace(0, nowReading.length(), "name of 1st reactant or nbr of reactants in reaction"); if(n < aList.size()) {t = aList.get(n);} else { throw new ReadComplexException("Error in \"Complex.fromString()\":"+nl+ "missing data while reading "+nowReading.toString()+nl+"for \""+c.name+"\""); } n++; if(t.trim().length() > 0) { try{nTot = Integer.parseInt(t);} catch (NumberFormatException ex) {nTot = -1;} } else {nTot = -1;} if(nTot <= 0) { // ---- old format ---- nr = 0; for(i =0; i < NDIM; i++) { if(i >0) { nowReading.replace(0, nowReading.length(), "name of reactant["+(i+1)+"]"); if(n < aList.size()) {t = aList.get(n);} else { throw new ReadComplexException("Error in \"Complex.fromString()\":"+nl+ "missing data while reading "+nowReading.toString()+nl+"for \""+c.name+"\""); } n++; } foundReactant = false; if(!t.isEmpty()) { nr++; c.reactionComp.add(t); foundReactant = true; } nowReading.replace(0, nowReading.length(), "coefficient for reactant["+(i+1)+"]"); if(n < aList.size()) { if(foundReactant) { if(aList.get(n).length() >0) {c.reactionCoef.add(Double.parseDouble(aList.get(n)));} else {c.reactionCoef.add(0.);} } } else { throw new ReadComplexException("Error in \"Complex.fromString()\":"+nl+ "missing data while reading "+nowReading.toString()+nl+"for \""+c.name+"\""); } n++; if(nr > 0 && Util.isProton(c.reactionComp.get(nr-1))) {thereisHplus = true; n_H = c.reactionCoef.get(nr-1);} } //for i nowReading.replace(0, nowReading.length(), "number of H+"); if(n < aList.size()) { if(aList.get(n).length() >0) { n_H = Double.parseDouble(aList.get(n)); } } else { throw new ReadComplexException("Error in \"Complex.fromString()\":"+nl+ "missing data while reading "+nowReading.toString()+nl+"for \""+c.name+"\""); } n++; if(!thereisHplus && Math.abs(n_H) > 0.00001) {c.reactionComp.add("H+"); c.reactionCoef.add(n_H);} } else { // nTot >0 ---- new format ---- for(i =0; i < nTot; i++) { nowReading.replace(0, nowReading.length(), "name of reactant["+(i+1)+"]"); if(n < aList.size()) {c.reactionComp.add(aList.get(n));} else { throw new ReadComplexException("Error in \"Complex.fromString()\":"+nl+ "missing data while reading "+nowReading.toString()+nl+"for \""+c.name+"\""); } n++; nowReading.replace(0, nowReading.length(), "coefficient for reactant["+(i+1)+"]"); if(n < aList.size()) { if(aList.get(n).length() >0) { c.reactionCoef.add(Double.parseDouble(aList.get(n))); } else {c.reactionCoef.add(0.);} } else { throw new ReadComplexException("Error in \"Complex.fromString()\":"+nl+ "missing data while reading "+nowReading.toString()+nl+"for \""+c.name+"\""); } n++; } //for i } // new format? } catch (NumberFormatException ex) { throw new ReadComplexException("Error in \"Complex.fromString()\":"+nl+ ex.toString()+nl+"in line: "+text+nl+ "while reading "+nowReading.toString()+nl+"for \""+c.name+"\""); } nowReading.replace(0, nowReading.length(), "reference"); if(n < aList.size()) {c.reference = aList.get(n);} else { throw new ReadComplexException("Error in \"Complex.fromString()\":"+nl+ "missing data while reading "+nowReading.toString()+nl+"for \""+c.name+"\""); } n++; while (n < aList.size()) { c.reference = c.reference +","+ aList.get(n); n++; } // System.out.println("\""+c.name+"\", ref="+c.reference); // remove ";" or "," at the beginning while (true) { if(c.reference.startsWith(";") || c.reference.startsWith(",")) { c.reference = c.reference.substring(1).trim(); } else {break;} } c.reference = c.reference.trim(); if(c.reference.startsWith("/")) { c.comment = c.reference.substring(1).trim(); c.reference = ""; } else { int commentStart = c.reference.length(); j = c.reference.indexOf(";/"); if(j > -1 && j < commentStart) {commentStart = j;} j = c.reference.indexOf(",/"); if(j > -1 && j < commentStart) {commentStart = j;} j = c.reference.indexOf(" /"); if(j > -1 && j < commentStart) {commentStart = j;} if(commentStart >=0 && commentStart < c.reference.length()) { c.comment = c.reference.substring((commentStart+2), c.reference.length()).trim(); c.reference = c.reference.substring(0, commentStart).trim(); } } } // for(String text: lines) if(c.lookUp) { for(i = 0; i < c.logKarray.length; i++) { if(c.logKarray[i] == null) { throw new ReadComplexException("Error in \"Complex.fromString()\":"+nl+ "missing line "+(i+1)+" of logK look-up table for \""+c.name+"\""); } } } return c; } // fromString public static class ReadComplexException extends Exception { public ReadComplexException() {super();} public ReadComplexException(String txt) {super(txt);} } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="toString()"> /** converts a Complex into a String, such as: * "<code>Fe 3+;-13.02;;;Fe 2+;1;;;e-;-1;;;;;;;0;Wateq4F /comment</code>" * @return the string describing the Complex object * @see lib.database.Complex#fromString(java.lang.String) fromString */ @Override public String toString() { StringBuilder text = new StringBuilder(); double w; text.append(encloseInQuotes(this.name)); text.append(";"); if(this.name.startsWith("@")) {return text.toString();} if(this.constant != EMPTY) {text.append(Util.formatDbl3(this.constant).trim());} text.append(";"); // If there is no second row of logKarray, it means that the look-up-table // (if it is not null) has been constructed from array a[]. boolean thereIsLookUpTable = false; if(this.logKarray[1] != null) { for(int j = 0; j < this.logKarray[1].length; j++) { if(!Float.isNaN(this.logKarray[1][j])) {thereIsLookUpTable = true; break;} } } // are there protons involved in the reaction? boolean proton = false; double n_H = 0; int nTot = Math.min(this.reactionComp.size(),this.reactionCoef.size()); for(int ic =0; ic < nTot; ic++) { if(this.reactionComp.get(ic) == null || this.reactionComp.get(ic).length()<=0) {continue;} if(Math.abs(this.reactionCoef.get(ic)) < 0.0001) {continue;} if(Util.isProton(this.reactionComp.get(ic))) {n_H = this.reactionCoef.get(ic); proton = true;} } if(nTot > 7 || (nTot == 7 && !proton) || this.analytic || this.lookUp && thereIsLookUpTable) { //System.out.println("toStringShort()..."); return this.toStringShort(); } // delta-H and delta-Cp w = this.getDeltaH(); if(w != EMPTY) {text.append(Util.formatDbl3(w).trim());} text.append(";"); w = this.getDeltaCp(); if(w != EMPTY) {text.append(Util.formatDbl3(w).trim());} text.append(";"); for(int ic =0; ic < 6; ic++) { if(ic >= nTot || this.reactionComp.get(ic) == null || this.reactionComp.get(ic).length()<=0) { text.append(";;"); continue; } else { text.append(encloseInQuotes(this.reactionComp.get(ic))); text.append(";"); } if(Math.abs(this.reactionCoef.get(ic)) > 0.0001) { text.append(Util.formatDbl4(this.reactionCoef.get(ic)).trim()); } text.append(";"); } if(Math.abs(n_H) >=0.001) {text.append(Util.formatDbl4(n_H).trim());} text.append(";"); String t; if(this.comment != null && this.comment.length() >0) { t = this.reference + " /" + this.comment; } else { t = this.reference; } text.append(encloseInQuotes(t)); return text.toString(); } // toString() //</editor-fold> //<editor-fold defaultstate="collapsed" desc="toStringShort()"> /** converts a Complex into a String, such as: * "<code>Fe 3+;-13.02;;;2;Fe 2+;1;e-;-1;0;Wateq4F / comment</code>" * @return the string describing the Complex object * @see lib.database.Complex#fromString(java.lang.String) fromString */ // @Override public String toStringShort() { StringBuilder text = new StringBuilder(); double w; text.append(encloseInQuotes(this.name)); text.append(";"); if(this.name.startsWith("@")) {return text.toString();} if(this.constant != EMPTY) {text.append(Util.formatDbl3(this.constant).trim());} text.append(";"); // If there is no second row of logKarray, it means that the look-up-table // (if it is not null) has been constructed from array a[]. boolean thereIsLookUpTable = false; if(this.logKarray[1] != null) { for(int j = 0; j < this.logKarray[1].length; j++) { if(!Float.isNaN(this.logKarray[1][j])) {thereIsLookUpTable = true; break;} } } if(this.analytic) { text.append("analytic;"); if(this.tMax == EMPTY || this.tMax < 25) {this.tMax = 25.;} text.append(Util.formatNumAsInt(this.tMax).trim()); text.append(";"); for (int i = 0; i < this.a.length; i++) { if(this.a[i] != EMPTY && this.a[i] !=0) { text.append(Util.formatDbl6(this.a[i]).trim()); } text.append(";"); } } else if(this.lookUp && thereIsLookUpTable) { text.append("lookUpTable;"); if(this.tMax == EMPTY) {this.tMax = 600.;} text.append(Util.formatNumAsInt(this.tMax).trim()); text.append(";"); } else { // delta-H and delta-Cp w = this.getDeltaH(); if(w != EMPTY) {text.append(Util.formatDbl3(w).trim());} text.append(";"); w = this.getDeltaCp(); if(w != EMPTY) {text.append(Util.formatDbl3(w).trim());} text.append(";"); } int nTot = Math.min(this.reactionComp.size(),this.reactionCoef.size()); text.append(Integer.toString(nTot)); text.append(";"); for(int ic =0; ic < nTot; ic++) { if(this.reactionComp.get(ic) == null || this.reactionComp.get(ic).length()<=0) { text.append(";;"); continue; } else { text.append(encloseInQuotes(this.reactionComp.get(ic))); text.append(";"); } if(Math.abs(this.reactionCoef.get(ic)) > 0.0001) { text.append(Util.formatDbl4(this.reactionCoef.get(ic)).trim()); } text.append(";"); } String t; if(this.comment != null && this.comment.length() >0) { t = this.reference + " /" + this.comment; } else { t = this.reference; } text.append(encloseInQuotes(t)); if(this.lookUp && thereIsLookUpTable) { for(int i = 0; i < this.logKarray.length; i++) { text.append(nl); if(this.logKarray[i] == null) { this.logKarray[i] = new float[14]; for(int j = 0; j < this.logKarray[i].length; j++) {this.logKarray[i][j] = Float.NaN;} } for(int j = 0; j < this.logKarray[i].length; j++) { if(!Float.isNaN(this.logKarray[i][j])) { text.append(Util.formatDbl3(this.logKarray[i][j])); } else {text.append("NaN");} text.append(";"); } } } return text.toString(); } // toStringShort() //</editor-fold> //<editor-fold defaultstate="collapsed" desc="sortedReactionString()"> /** Returns a String representation of the reaction such as:<pre> * "<code>Fe 2+;1;;;e-;-1;;;;;;;0;</code>"</pre> * Equivalent to <code>Complex.toString</code>, except that (1) the product name, * the logK and the reference are excluded, and (2) the reactants are sorted. * That is, it returns only the reaction (sorted). * If the product name starts with "@" this method returns an empty String (""). * @return a text representing the reaction * @see lib.database.Complex#toString() Complex.toString */ public String sortedReactionString() { if(this.name.startsWith("@")) {return "";} Complex c; try {c = (Complex)this.clone();} catch(CloneNotSupportedException cex) {return "";} // -- exclude water? //for(int ic =0; ic < Complex.NDIM; ic++) { // if(Util.isWater(c.component[ic])) {c.component[ic] = ""; c.numcomp[ic] = 0; break;} //} StringBuilder text = new StringBuilder(); //text.append(Complex.encloseInQuotes(c.name)); text.append(";"); c.sortReactants(); int nTot = Math.min(c.reactionComp.size(),c.reactionCoef.size()); for(int ic =0; ic < nTot; ic++) { if(c.reactionComp.get(ic) == null || c.reactionComp.get(ic).length()<=0 // || Util.isWater(c.component[ic]) || Math.abs(c.reactionCoef.get(ic)) < 0.0001) {text.append(";;"); continue;} text.append(Complex.encloseInQuotes(c.reactionComp.get(ic))); text.append(";"); text.append(Util.formatDbl4(c.reactionCoef.get(ic)).trim()); text.append(";"); } return text.toString(); } //sortedReactionString() //</editor-fold> //<editor-fold defaultstate="collapsed" desc="reactionText()"> /** returns a simple, easy to read description of the reaction defining * this complex. For example: "Fe 2+ + H2O = FeOH- + H+". * @return a text describing the reaction */ public String reactionText() { StringBuilder text = new StringBuilder(); StringBuffer stoich = new StringBuffer(); boolean first = true; double aX; int nTot = Math.min(this.reactionComp.size(),this.reactionCoef.size()); for(int ic =0; ic < nTot; ic++) { aX = this.reactionCoef.get(ic); if(aX > 0 && this.reactionComp.get(ic) != null && this.reactionComp.get(ic).length() >0) { if(first) { stoich.delete(0, stoich.length()); first = false; } else { stoich.delete(0, stoich.length()); stoich.append(" +"); }//first? if(Math.abs(aX-1)>0.001) { // aX != +1 stoich.append(Util.formatDbl3(aX)); } text.append(stoich.toString()); text.append(" "); text.append(this.reactionComp.get(ic)); }//if aX > 0 }//for ic text.append(" = "); first = true; for(int ic =0; ic < nTot; ic++) { aX = -this.reactionCoef.get(ic); if(aX > 0 && this.reactionComp.get(ic) != null && this.reactionComp.get(ic).length() >0) { if(first) { stoich.delete(0, stoich.length()); first = false; } else { stoich.delete(0, stoich.length()); stoich.append(" +"); }//first? if(Math.abs(aX-1)>=0.001) { // aX != +1 stoich.append(Util.formatDbl3(aX)); } text.append(stoich.toString()); text.append(" "); text.append(this.reactionComp.get(ic)); }//if aX > 0 }//for ic stoich.delete(0, stoich.length()); if(first) {stoich.append(" ");} else {stoich.append(" + ");} text.append(stoich); text.append(this.name); String t = text.toString().trim(); text.delete(0, text.length()); text.append(t); if(t.startsWith("=") && t.contains("@")) {text.deleteCharAt(0);} return text.toString(); } //reactionText //</editor-fold> //<editor-fold defaultstate="collapsed" desc="reactionTextWithLogK(temperature)"> /** returns a simple, easy to read description of the reaction defining * this complex, including the equilibrium constant (logK) and reference code. * For example: "Fe 2+ + H2O = FeOH- + H+; logK=X.XX [99ref]". * @param tC temperature in degrees Celsius, to calculate logK * @param pBar pressure in bar, to calculate logK * @return a text describing the reaction, the equilibrium constant and the reference code */ public String reactionTextWithLogK(double tC, double pBar) { StringBuilder text = new StringBuilder(); double lgK; text.append(reactionText()); if(this.constant != EMPTY && !this.name.startsWith("@")) { lgK = this.logKatTandP(tC, pBar); if(!Double.isNaN(lgK) && lgK != EMPTY) {text.append("; logK="); text.append(Util.formatDbl3(lgK));} else {text.append("; logK= ??");} } else { if(!this.name.startsWith("@")) {text.append("; logK= ??");} } text.append(" "); if(this.comment != null && this.comment.length() >0) {text.append(" ("); text.append(this.comment); text.append(")");} if(this.reference != null && this.reference.length() >0) {text.append(" ["); text.append(this.reference); text.append("]");} String t = text.toString().trim(); text.delete(0, text.length()); text.append(t); if(t.startsWith("=") && t.contains("@")) {text.deleteCharAt(0);} return text.toString(); } //reactionText //</editor-fold> //<editor-fold defaultstate="collapsed" desc="logKatTpSat(tC)"> /** Returns the logK value at the requested temperature (below the * critical point) and at the saturated liquid-vapor pressure (pSat). * @param tC0 the temperature in degrees Celsius * @return the logK value at the requested temperature and pSat. * It returns NaN (not-a-number) if the logK value can not be calculated, * or if the temperature is either NaN or above the critical point * or higher than tMax * @see lib.database.Complex#tMax tMax * @see lib.database.Complex#analytic analytic * @see lib.database.Complex#a a * @see lib.database.Complex#lookUp lookUp * @see lib.database.Complex#logKarray logKarray */ public double logKatTpSat(final double tC0) { if(Double.isNaN(tC0)) {return Double.NaN;} this.tMax = Math.min(1000,Math.max(25, this.tMax)); if(tC0 > this.tMax+0.001) {return Double.NaN;} double tC = Math.max(tC0,0.01); // triple point of water if(tC >= 373.946) {return Double.NaN;} // crtitical point of water if(this.lookUp) { if(logKarray[0] == null) {return Double.NaN;} // t= 0, 25, 50, 100, 150, 200, 250, 300, 350 C float[] logK = new float[9]; System.arraycopy(logKarray[0], 0, logK, 0, logK.length); return lib.kemi.interpolate.Interpolate.logKinterpolatePsat((float)tC, logK); } else { return analyticExpression(this, tC); } } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="logKatTandP(tC,pBar)"> /** Returns the logK value at the requested temperature and pressure * if it can be calculated. * @param tC0 the temperature in degrees Celsius * @param pBar the pressure in bar. At temperatures below 100 C, if pBar is equal * to one, it is assumed that max(pSat,1) is intended, where "pSat" is the steam * saturated pressure. Note that at 100 C pSat is approx. 1.015 bar * @return the logK value at the requested temperature and pressure. * It returns NaN (not-a-number) if (a) the logK value can not be calculated * (t-P in the vapor region or in the low-density region) or (b) if either * the temperature or the pressure are NaNs, or (c) if tC0 is higher than tMax, * or (d) if lookUp is false and pBar is larger than 221 bar. * @see lib.database.Complex#tMax tMax * @see lib.database.Complex#pMax pMax * @see lib.database.Complex#analytic analytic * @see lib.database.Complex#a a * @see lib.database.Complex#lookUp lookUp * @see lib.database.Complex#logKarray logKarray */ public double logKatTandP(final double tC0, final double pBar) { if(Double.isNaN(tC0) || Double.isNaN(pBar)) {return Double.NaN;} this.tMax = Math.min(1000,Math.max(25, this.tMax)); this.pMax = Math.min(5000,Math.max(1, this.pMax)); if(tC0 > this.tMax+0.001 || pBar > this.pMax*1.01) {return Double.NaN;} double tC = Math.max(tC0,0.01); // triple point of water boolean thereIsLookUpTable = false; if(this.logKarray[1] != null) { for(int j = 0; j < this.logKarray[1].length; j++) { if(!Float.isNaN(this.logKarray[1][j])) {thereIsLookUpTable = true; break;} } } if(tC < 373.) { // crtitical point of water = 373.946 // is the pressure = vapour-liquid equilibrium? double pSat = Math.max(1,IAPWSF95.pSat(tC)); // if tC <=100 and pBar = 1 if(tC <= 100.001 && Math.abs(pBar-1)<0.001) {return logKatTpSat(tC);} if(pBar < (pSat*0.99)) { // below saturated liquid-vapor pressure return Double.NaN; // pBar is in the gas range } else { if(pBar < (pSat*1.01)) {return logKatTpSat(tC);} } } else if(tC <= 376.) {return Double.NaN;} // between 373 and 376 C // if tC > 376 double[] tLimit = new double[]{373.946,400,410,430,440,460,470,490,510,520,540,550,570,580,600}; double[] pLimit = new double[]{ 300,350,400,450,500,550,600,650,700,750,800,850,900,950}; for(int i = 0; i < (tLimit.length-1); i++) { if(tC > tLimit[i] && tC <= tLimit[i+1] && pBar < pLimit[i]) {return Double.NaN;} } // If there is no second row of logKarray, it means that the look-up-table // (if it is not null) has been constructed from array a[]. if(thereIsLookUpTable) { return lib.kemi.interpolate.Interpolate.logKinterpolateTP((float)tC, (float)pBar, this.logKarray); } else { if(pBar > 221) {return Double.NaN;} return analyticExpression(this, tC); } } //<editor-fold defaultstate="collapsed" desc="Not used: constCp(complex,tC)"> /** Extrapolates the log10 of an equilibrium constant "logK0" using the * the constant heat capacity approximation, or if deltaCp is not provided, * using the constant enthalpy (van't Hoff) equation. The temperature is * forced to be in the range 0 to 100 degrees Celsius. * @param cmplx * @param tC * @return logK(tC) calculated using the reaction enthalpy and heat capacity. * It returns NaN if either of the input parameters is NaN or if * cmplx.constant = EMPTY. * @see Complex#EMPTY EMPTY */ /** private static double constantCp(Complex cmplx, final double tC) { if(Double.isNaN(cmplx.constant) || cmplx.constant == EMPTY || Double.isNaN(tC)) { MsgExceptn.exception("Constant heat-capacity model for \""+cmplx.name+":"+nl+ " logK="+cmplx.constant+", temperature = "+tC); return Double.NaN; } if(tC>24.9 && tC<25.1) {return cmplx.constant;} if(tC > 100.1) { MsgExceptn.exception("Constant heat-capacity model for \""+cmplx.name+":"+nl+ " temperature = "+tC+" (must be < 100)."); return Double.NaN; } if(Double.isNaN(cmplx.deltH) || cmplx.deltH == EMPTY) { MsgExceptn.exception("Constant heat-capacity model for \""+cmplx.name+": no enthalpy data."); return Double.NaN; } final double tK = 273.15 + Math.min(350,Math.max(0,tC)); final double T0 = 298.15; final double R_LN10 = 19.1448668; // J/(mol K) double logK = cmplx.constant + (cmplx.deltH * 1000 / R_LN10) * ((1/T0) - (1/tK)); if(Double.isNaN(cmplx.deltCp) || cmplx.deltCp == EMPTY) { // no heat capacity if(tC > 50.1) { MsgExceptn.exception("Constant heat-capacity model for \""+cmplx.name+":"+nl+ " temperature = "+tC+" and no delta-Cp data (needed for t > 50 C)."); return Double.NaN; } else {return logK;} } // there a value for the heat capacity: logK = logK + (cmplx.deltCp / R_LN10) * ((T0/tK)-1+Math.log(tK/T0)); return logK; } // */ //</editor-fold> //<editor-fold defaultstate="collapsed" desc="analyticExpression(complex,tC)"> /** Extrapolates the log10 of an equilibrium constant "logK0" using the * an analytic expression of logK(t) * @param cmplx * @param tC the temperature (degrees Celsius, between 0 and cmplx.tMax degrees) * @return the logK(t) * It returns NaN if either: any of the input parameters is NaN, or if the array * "a" is not defined. Returns EMPTY if logK0 = EMPTY. * @see lib.database.Complex#deltaToA(double, double, double) deltaToA * @see lib.database.Complex#analytic analytic * @see lib.database.Complex#a a[] * @see lib.database.Complex#tMax tMax * @see lib.database.Complex#EMPTY EMPTY */ private static double analyticExpression(Complex cmplx, final double tC) { if(Double.isNaN(cmplx.constant) || cmplx.constant == EMPTY || Double.isNaN(tC)) {return Double.NaN;} if(tC>24.99 && tC<25.01) {return cmplx.constant;} if(cmplx.a[0] == EMPTY) {return Double.NaN;} if(cmplx.tMax == EMPTY || cmplx.tMax < 25) {cmplx.tMax = 25;} cmplx.tMax = Math.min(1000,cmplx.tMax); if(tC > cmplx.tMax+0.001) {return Double.NaN;} final double tK = Math.max(0.01,tC)+273.15; // triple point of water double logK = cmplx.a[0]; // log K = A0 + A1 T + A2/T + A3 log(T) + A4 / T^2 + A5 T^2 if(cmplx.a[1] != EMPTY && cmplx.a[1] != 0.) {logK = logK + cmplx.a[1]*tK;} if(cmplx.a[2] != EMPTY && cmplx.a[2] != 0.) {logK = logK + cmplx.a[2]/tK;} if(cmplx.a[3] != EMPTY && cmplx.a[3] != 0.) {logK = logK + cmplx.a[3]*Math.log10(tK);} if(cmplx.a[4] != EMPTY && cmplx.a[4] != 0.) {logK = logK + cmplx.a[4]/(tK*tK);} if(cmplx.a[5] != EMPTY && cmplx.a[5] != 0.) {logK = logK + cmplx.a[5]*(tK*tK);} return logK; } //</editor-fold> //</editor-fold> //<editor-fold defaultstate="collapsed" desc="isChargeBalanced()"> /** is the reaction specified in "complex" charge balanced? * @return true if the reaction specified in "complex" is charge balanced */ public boolean isChargeBalanced() { if(this.name.startsWith("@")) { //prefix "@" means remove such a component/complex if already included return true; } double totCharge = Util.chargeOf(this.name); int nTot = Math.min(this.reactionComp.size(),this.reactionCoef.size()); for(int i=0; i < nTot; i++) { if(this.reactionComp.get(i) == null || this.reactionComp.get(i).length() <=0 || Math.abs(this.reactionCoef.get(i)) < 0.0001) {continue;} totCharge = totCharge - this.reactionCoef.get(i) * Util.chargeOf(this.reactionComp.get(i)); } //for i return Math.abs(totCharge) < 0.001; } //isChargeBalanced(complex) //</editor-fold> //<editor-fold defaultstate="collapsed" desc="check()"> /** Check that<ul> * <li>if a component is given, it has non-zero stoichiometric coefficient, and * <i>vice-versa</i>, that if a reaction coefficient is given, the component name is * not empty * <li>the reaction is charge balanced * <li>that if "H+" is given as one of the component names, its reaction * coeffitient and "proton" agree</ul> * * @return either an error message or "null" */ public String check() { StringBuilder sb = new StringBuilder(); boolean start = true; if(this.reactionComp.size() != this.reactionCoef.size()) { if(start) {sb.append("Complex: \""); sb.append(this.name); sb.append("\""); sb.append(nl); start = false;} sb.append("Length of reaction arrays (components and coefficients) do not match."); } int nTot = Math.min(this.reactionComp.size(), this.reactionCoef.size()); for(int i=0; i < nTot; i++) { if((this.reactionComp.get(i) == null || this.reactionComp.get(i).length() <=0) && Math.abs(this.reactionCoef.get(i)) >= 0.001) { if(start) {sb.append("Complex: \""); sb.append(this.name); sb.append("\""); sb.append(nl); start = false;} sb.append("Reaction coefficient given with no component."); } else if(this.reactionComp.get(i) != null && this.reactionComp.get(i).length() >0) { if(Math.abs(this.reactionCoef.get(i)) < 0.0001) { if(start) {sb.append("Complex: \""); sb.append(this.name); sb.append("\""); sb.append(nl); start = false;} sb.append("No reaction coefficient for component \""); sb.append(this.reactionComp.get(i)); sb.append("\""); } } }//for i //--- check for charge balance if(!this.isChargeBalanced()) { if(sb.length() >0) {sb.append(nl);} if(start) {sb.append("Complex: \""); sb.append(this.name); sb.append("\""); sb.append(nl);} sb.append("Reaction is not charge balanced."); } if(sb.length() > 0) {return sb.toString();} else {return null;} } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="encloseInQuotes(text)"> /** Enclose a text in quotes if:<br> * - it starts with either a single quote or a double quote<br> * - it contains either a comma or a semicolon<br> * If the text is enclosed in quotes, an enclosed quote is duplicated. For example * if text is "a'b" then the procedure returns '"a''b"'. * @param text * @return <code>text</code> enclose in quotes if needed */ public static String encloseInQuotes(String text) { if(text == null) {return null;} if(text.length()<=0) {return text;} StringBuilder sb = new StringBuilder(text); if(sb.charAt(0) == '"') { duplicateQuote(sb,'\''); return ("'"+sb.toString()+"'"); } else if(sb.charAt(0) == '\'') { duplicateQuote(sb,'"'); return ("\""+sb.toString()+"\""); } else if(sb.indexOf(",") >-1 || sb.indexOf(";") >-1) { // contains separator if(sb.indexOf("\"") >-1) { duplicateQuote(sb,'\''); return ("'"+sb.toString()+"'"); } else { duplicateQuote(sb,'"'); return ("\""+sb.toString()+"\""); } } //if separator return text; } //encloseInQuotes(text) private static void duplicateQuote(StringBuilder sb, char quote) { int pos = 0; int l = sb.length(); while(pos < l) { if(sb.charAt(pos) == quote) {sb.insert(pos, quote); l++; pos++;} pos++; } //while } //duplicateQuote //</editor-fold> }
71,760
Java
.java
ignasi-p/eq-diagr
18
3
0
2018-08-17T08:25:37Z
2023-04-30T09:33:35Z
FrameSingleComponent.java
/FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibDataBase/src/lib/database/FrameSingleComponent.java
package lib.database; import lib.common.MsgExceptn; import lib.common.Util; import lib.huvud.ProgramConf; import lib.huvud.SortedListModel; /** Show the data in the databases involving a single component. * <br> * Copyright (C) 2014-2020 I.Puigdomenech. * * 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 * 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/ * * @author Ignasi Puigdomenech */ public class FrameSingleComponent extends javax.swing.JFrame { // Note: for java 1.6 jComboBox must not have type, // for java 1.7 jComboBox must be <String> private ProgramConf pc; private ProgramDataDB pd; private boolean finished = false; /** the number of reactions read so far from the databases */ private int n; private LibSearch hs; private java.awt.Dimension windowSize = new java.awt.Dimension(227,122); private final SortedListModel sortedModelComplexes = new SortedListModel(); /** indicates if a mouse click on the reaction list should show the popup menu */ private boolean isPopup = false; /** New-line character(s) to substitute "\n" */ private static final String nl = System.getProperty("line.separator"); private static final String SLASH = java.io.File.separator; //<editor-fold defaultstate="collapsed" desc="Constructor"> /** Creates new form FrameSingleComponent * @param parent * @param pc0 * @param pd0 */ public FrameSingleComponent(final java.awt.Frame parent, ProgramConf pc0, ProgramDataDB pd0) { initComponents(); pc = pc0; pd = pd0; setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); //--- Close window on ESC key javax.swing.KeyStroke escKeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE,0, false); getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(escKeyStroke,"ESCAPE"); javax.swing.Action escAction = new javax.swing.AbstractAction() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { closeWindow(); }}; getRootPane().getActionMap().put("ESCAPE", escAction); //--- Alt-Q quit javax.swing.KeyStroke altQKeyStroke = javax.swing.KeyStroke.getKeyStroke( java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.ALT_MASK, false); getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altQKeyStroke,"ALT_Q"); getRootPane().getActionMap().put("ALT_Q", escAction); //--- F1 for help javax.swing.KeyStroke f1KeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1,0, false); getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(f1KeyStroke,"F1"); javax.swing.Action f1Action = new javax.swing.AbstractAction() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { if(parent != null) {parent.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));} FrameSingleComponent.this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR)); Thread hlp = new Thread() {@Override public void run(){ String[] a = {"DB_0_Main_htm"}; lib.huvud.RunProgr.runProgramInProcess(null,ProgramConf.HELP_JAR,a,false,pc.dbg,pc.pathAPP); try{Thread.sleep(2000);} //show the "wait" cursor for 2 sec catch (InterruptedException e) {} FrameSingleComponent.this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); if(parent != null) {parent.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));} }};//new Thread hlp.start(); }}; getRootPane().getActionMap().put("F1", f1Action); //--- Alt-H help javax.swing.KeyStroke altHKeyStroke = javax.swing.KeyStroke.getKeyStroke( java.awt.event.KeyEvent.VK_H, java.awt.event.InputEvent.ALT_MASK, false); getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altHKeyStroke,"ALT_H"); getRootPane().getActionMap().put("ALT_H", f1Action); //--- Alt-S message frame on/off javax.swing.KeyStroke altSKeyStroke = javax.swing.KeyStroke.getKeyStroke( java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.ALT_MASK, false); getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altSKeyStroke,"ALT_S"); javax.swing.Action altSAction = new javax.swing.AbstractAction() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { if(pd.msgFrame != null) {pd.msgFrame.setVisible(!pd.msgFrame.isVisible());} }}; getRootPane().getActionMap().put("ALT_S", altSAction); //--- Ctrl-S save javax.swing.KeyStroke ctrlSKeyStroke = javax.swing.KeyStroke.getKeyStroke( java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK, false); getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(ctrlSKeyStroke,"CTRL_S"); javax.swing.Action ctrlSAction = new javax.swing.AbstractAction() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { jButtonSave.doClick(); }}; getRootPane().getActionMap().put("CTRL_S", ctrlSAction); //---- forward/backwards arrow keys java.util.Set<java.awt.AWTKeyStroke> keys = getFocusTraversalKeys(java.awt.KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS); java.util.Set<java.awt.AWTKeyStroke> newKeys = new java.util.HashSet<java.awt.AWTKeyStroke>(keys); newKeys.add(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_RIGHT, 0)); setFocusTraversalKeys(java.awt.KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,newKeys); keys = getFocusTraversalKeys(java.awt.KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS); newKeys = new java.util.HashSet<java.awt.AWTKeyStroke>(keys); newKeys.add(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_LEFT, 0)); setFocusTraversalKeys(java.awt.KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,newKeys); //---- Icon String iconName = "images/Kemi.gif"; java.net.URL imgURL = this.getClass().getResource(iconName); if (imgURL != null) {this.setIconImage(new javax.swing.ImageIcon(imgURL).getImage());} else {System.out.println("Error: Could not load image = \""+iconName+"\"");} if(parent != null) {jButtonExit.setIcon(new javax.swing.ImageIcon(parent.getIconImage()));} //---- Title, etc this.setTitle(pc.progName+" - Display a single component"); //---- Centre window on parent/screen int left,top; java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); if(parent != null) { left = Math.max(0,(parent.getX() + (parent.getWidth()/2) - this.getWidth()/2)); top = Math.max(0,(parent.getY()+(parent.getHeight()/2)-this.getHeight()/2)); } else { left = Math.max(0,(screenSize.width-this.getWidth())/2); top = Math.max(0,(screenSize.height-this.getHeight())/2); } this.setLocation(Math.min(screenSize.width-this.getWidth()-20,left), Math.min(screenSize.height-this.getHeight()-20, top)); //---- fill in the Combo Box, sorting items first fillComboBox(jComboBox, pd.elemComp, pd.includeH2O); jComboBox.removeItemAt(0); //the top item is empty jLabelTop.setText("<html>Select one of the following<br>"+(jComboBox.getItemCount())+" components:</html>"); if(pd.dataBasesList.size() >1) { jLabelFound.setText("Contents of databases:"); } else { jLabelFound.setText("Contents of the database:"); } jLabelN.setText(" "); jLabelSpecies.setText(" "); jButtonSave.setEnabled(false); if(pd.references != null) {jMenuItemRef.setEnabled(true);} else {jMenuItemRef.setEnabled(false);} } //constructor public void start() { this.setVisible(true); pd.msgFrame.setParentFrame(this); windowSize = this.getSize(); jButtonExit.requestFocusInWindow(); } private static void fillComboBox( javax.swing.JComboBox<String> jComboBox, // javax.swing.JComboBox jComboBox, // java 1.6 java.util.ArrayList<String[]> elemCompStr, final boolean includeH2O) { if(jComboBox == null) {MsgExceptn.exception("Error: \"JComboBox\" = null in \"fillComboBox\""); return;} if(elemCompStr == null || elemCompStr.size() <= 0) {MsgExceptn.exception("Error: \"elemCompStr\" empy in \"fillComboBox\""); return;} java.util.ArrayList<String> components = new java.util.ArrayList<String>(); for(int i=0; i < elemCompStr.size(); i++) {components.add(elemCompStr.get(i)[1]);} java.util.Collections.sort(components, String.CASE_INSENSITIVE_ORDER); jComboBox.removeAllItems(); jComboBox.addItem(" "); jComboBox.addItem("H+"); jComboBox.addItem("e-"); if(includeH2O) {jComboBox.addItem("H2O");} int i = jComboBox.getItemCount()-1; for(String t : components) { if(!t.equals("H+") && !t.equals("e-") && !t.equals("H2O")) { if(!jComboBox.getItemAt(i).toString().equals(t)) {jComboBox.addItem(t); i++;} } } } //fillComboBox //</editor-fold> /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPopupMenu = new javax.swing.JPopupMenu(); jMenuItemRef = new javax.swing.JMenuItem(); jSeparator = new javax.swing.JPopupMenu.Separator(); jMenuItemCancel = new javax.swing.JMenuItem(); jLabelTop = new javax.swing.JLabel(); jComboBox = new javax.swing.JComboBox<>(); jLabelFound = new javax.swing.JLabel(); jLabelN = new javax.swing.JLabel(); jLabelSpecies = new javax.swing.JLabel(); jScrollPaneList = new javax.swing.JScrollPane(); jList = new javax.swing.JList(); jPanel1 = new javax.swing.JPanel(); jButtonExit = new javax.swing.JButton(); jButtonSave = new javax.swing.JButton(); jButtonSearch = new javax.swing.JButton(); jMenuItemRef.setMnemonic('r'); jMenuItemRef.setText("show References"); jMenuItemRef.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItemRefActionPerformed(evt); } }); jPopupMenu.add(jMenuItemRef); jPopupMenu.add(jSeparator); jMenuItemCancel.setText("Cancel"); jMenuItemCancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItemCancelActionPerformed(evt); } }); jPopupMenu.add(jMenuItemCancel); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); addComponentListener(new java.awt.event.ComponentAdapter() { public void componentResized(java.awt.event.ComponentEvent evt) { formComponentResized(evt); } }); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } }); jLabelTop.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N jLabelTop.setText("<html>Select one of the following<br>321 components:</html>"); jComboBox.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); jLabelFound.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabelFound.setText("Contents of databases:"); jLabelN.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabelN.setText("0000"); jLabelSpecies.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabelSpecies.setText("species"); jScrollPaneList.setFont(new java.awt.Font("Monospaced", 0, 12)); // NOI18N jList.setFont(new java.awt.Font("Monospaced", 0, 12)); // NOI18N jList.setModel(sortedModelComplexes); jList.setFocusable(false); jList.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jListMouseClicked(evt); } public void mousePressed(java.awt.event.MouseEvent evt) { jListMousePressed(evt); } public void mouseReleased(java.awt.event.MouseEvent evt) { jListMouseReleased(evt); } }); jList.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { jListFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { jListFocusLost(evt); } }); jScrollPaneList.setViewportView(jList); jButtonExit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/lib/database/images/Java_32x32.gif"))); // NOI18N jButtonExit.setMnemonic('x'); jButtonExit.setText("Exit"); jButtonExit.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jButtonExit.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); jButtonExit.setMargin(new java.awt.Insets(5, 2, 5, 2)); jButtonExit.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); jButtonExit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonExitActionPerformed(evt); } }); jButtonSave.setIcon(new javax.swing.ImageIcon(getClass().getResource("/lib/database/images/Save_32x32.gif"))); // NOI18N jButtonSave.setMnemonic('a'); jButtonSave.setText("Save"); jButtonSave.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jButtonSave.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); jButtonSave.setMargin(new java.awt.Insets(5, 2, 5, 2)); jButtonSave.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); jButtonSave.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonSaveActionPerformed(evt); } }); jButtonSearch.setIcon(new javax.swing.ImageIcon(getClass().getResource("/lib/database/images/Search_32x32.gif"))); // NOI18N jButtonSearch.setMnemonic('e'); jButtonSearch.setText("Search"); jButtonSearch.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jButtonSearch.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); jButtonSearch.setMargin(new java.awt.Insets(5, 2, 5, 2)); jButtonSearch.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); jButtonSearch.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonSearchActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addComponent(jButtonSearch) .addGap(31, 31, 31) .addComponent(jButtonSave) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButtonExit)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButtonExit) .addComponent(jButtonSave) .addComponent(jButtonSearch) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabelFound) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabelN) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabelSpecies)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabelTop, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jScrollPaneList, javax.swing.GroupLayout.DEFAULT_SIZE, 421, Short.MAX_VALUE)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabelTop, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(20, 20, 20) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelFound) .addComponent(jLabelN) .addComponent(jLabelSpecies))) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPaneList, javax.swing.GroupLayout.DEFAULT_SIZE, 188, Short.MAX_VALUE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents //<editor-fold defaultstate="collapsed" desc="events"> private void jButtonSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSearchActionPerformed doSearch(); }//GEN-LAST:event_jButtonSearchActionPerformed private void jButtonSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSaveActionPerformed if(sortedModelComplexes.getSize() <= 0) { javax.swing.JOptionPane.showMessageDialog(this, "Nothig to save!", pc.progName, javax.swing.JOptionPane.INFORMATION_MESSAGE); return; } String d = pd.pathAddData.toString(); if(!d.endsWith(SLASH)) {d = d + SLASH;} String fn = Util.getSaveFileName(this, pc.progName, "Enter a file name:", 7, (d + "single_comp.txt"), pd.pathAddData.toString()); if(fn == null || fn.length() <=0) {return;} java.io.File f = new java.io.File(fn); try {fn = f.getCanonicalPath();} catch (java.io.IOException ex) {fn = null;} if(fn == null) {try {fn = f.getAbsolutePath();} catch (Exception ex) {fn = f.getPath();}} f = new java.io.File(fn); if(f.exists()) {f.delete();} if(pc.dbg) {System.out.println("--- Saving file: \""+fn+"\"");} java.io.Writer w; try {w = new java.io.BufferedWriter( new java.io.OutputStreamWriter( new java.io.FileOutputStream(f),"UTF8"));} catch (java.io.IOException ex) { String msg = "Error: "+ex.toString()+nl+ "while opening file:"+nl+"\""+fn+"\""; MsgExceptn.exception(msg); javax.swing.JOptionPane.showMessageDialog(this, msg, pc.progName,javax.swing.JOptionPane.ERROR_MESSAGE); return; } try{ w.write(Complex.FILE_FIRST_LINE+nl); for(int i=0; i<sortedModelComplexes.getSize(); i++) { w.write(sortedModelComplexes.getElementAt(i).toString()+nl); } //for i w.close(); } catch (Exception ex) { String msg = "Error: "+ex.toString()+nl+ "while writing file:"+nl+"\""+fn+"\""; MsgExceptn.exception(msg); javax.swing.JOptionPane.showMessageDialog(this, msg, pc.progName,javax.swing.JOptionPane.ERROR_MESSAGE); return; } }//GEN-LAST:event_jButtonSaveActionPerformed private void jButtonExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonExitActionPerformed closeWindow(); }//GEN-LAST:event_jButtonExitActionPerformed private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing closeWindow(); }//GEN-LAST:event_formWindowClosing private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized if(windowSize != null) { int w = windowSize.width; int h = windowSize.height; if(this.getHeight()<h){this.setSize(this.getWidth(), h);} if(this.getWidth()<w){this.setSize(w,this.getHeight());} } }//GEN-LAST:event_formComponentResized private void jListFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jListFocusGained int i = jList.getSelectedIndex(); if(i < 0) {i = 0;} jList.setSelectedIndex(i); jList.ensureIndexIsVisible(i); }//GEN-LAST:event_jListFocusGained private void jListFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jListFocusLost if(!jPopupMenu.isVisible()) {jList.clearSelection();} }//GEN-LAST:event_jListFocusLost private void jMenuItemCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemCancelActionPerformed jPopupMenu.setVisible(false); }//GEN-LAST:event_jMenuItemCancelActionPerformed private void jMenuItemRefActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemRefActionPerformed int index = jList.getSelectedIndex(); if(pc.dbg) {System.out.println("jMenuItemRef("+index+")");} if(index <0 || index >= sortedModelComplexes.getSize()) {return;} Complex cmplx; try{cmplx = Complex.fromString(sortedModelComplexes.getElementAt(index).toString());} catch (Complex.ReadComplexException ex) {cmplx = null;} if(cmplx == null || cmplx.name == null) {return;} if(pc.dbg) {System.out.println("Show reference(s) for: \""+cmplx.name+"\""+nl+ " ref: \""+cmplx.reference.trim()+"\"");} pd.references.displayRefs(this, true, cmplx.name, pd.references.splitRefs(cmplx.reference)); jList.requestFocusInWindow(); jList.setSelectedIndex(index); }//GEN-LAST:event_jMenuItemRefActionPerformed private void jListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListMouseClicked if(!isPopup) {return;} java.awt.Point p = evt.getPoint(); int i = jList.locationToIndex(p); if(i>=0) { java.awt.Rectangle r = jList.getCellBounds(i, i); if(p.y < r.y || p.y > r.y+r.height) {i=-1;} if(i>=0) { jPopupMenu.show(jList, evt.getX(), evt.getY()); jList.setSelectedIndex(i); } }//if i>=0 isPopup = false; }//GEN-LAST:event_jListMouseClicked private void jListMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListMousePressed if(evt.isPopupTrigger()) {isPopup = true;} }//GEN-LAST:event_jListMousePressed private void jListMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListMouseReleased if(evt.isPopupTrigger()) {isPopup = true;} }//GEN-LAST:event_jListMouseReleased //</editor-fold> //<editor-fold defaultstate="collapsed" desc="methods"> private void closeWindow() { finished = true; //return from "waitFor()" this.notify_All(); this.dispose(); } // closeWindow() private synchronized void notify_All() { //needed by "waitFor()" notifyAll(); } /** this method will wait for this window to be closed */ public synchronized void waitFor() { while(!finished) { try {wait();} catch (InterruptedException ex) {} } // while } // waitFor() //<editor-fold defaultstate="collapsed" desc="bringToFront()"> public void bringToFront() { if(this != null) { java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { setVisible(true); if((getExtendedState() & javax.swing.JFrame.ICONIFIED) // minimised? == javax.swing.JFrame.ICONIFIED) { setExtendedState(javax.swing.JFrame.NORMAL); } // if minimized setAlwaysOnTop(true); toFront(); requestFocus(); setAlwaysOnTop(false); } }); } } // bringToFront() //</editor-fold> private void doSearch() { sortedModelComplexes.clear(); int i = jComboBox.getSelectedIndex(); if(i < 0 || i >= jComboBox.getItemCount()) { javax.swing.JOptionPane.showMessageDialog( this, "Please select a component"+nl+"from the pull-down list.", pc.progName, javax.swing.JOptionPane.INFORMATION_MESSAGE); return; } setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR)); jButtonSearch.setEnabled(false); final String choosenComp = jComboBox.getItemAt(i).toString(); try {hs = new LibSearch(pd.dataBasesList);} catch (LibSearch.LibSearchException ex) { MsgExceptn.exception(ex.toString()); jButtonSearch.setEnabled(true); setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); return;} jLabelFound.setText("Checking species:"); jLabelN.setText("0"); jLabelSpecies.setText(" "); Thread srch = new Thread() {@Override public void run() { boolean fistComplex = true; n = 0; int j; boolean fnd; double coef1; Complex cmplx = null; String errMsg = null; while(true) { try { cmplx = hs.getComplex(fistComplex); } catch (LibSearch.LibSearchException ex) { hs.libSearchClose(); String msg = ex.toString()+nl+"when reading complex nbr."+(n+1); MsgExceptn.showErrMsg(FrameSingleComponent.this,msg,1); System.err.println(Util.stack2string(ex)); } if(cmplx == null) {break;} if(cmplx.name.startsWith("@")) { cmplx.name = cmplx.name.substring(1); j = 0; while(j < sortedModelComplexes.getSize()) { if(sortedModelComplexes.getElementAt(j).toString().startsWith(cmplx.name)) { final int jj = j; try { javax.swing.SwingUtilities.invokeAndWait(new Runnable() {@Override public void run() { sortedModelComplexes.removeElement(sortedModelComplexes.getElementAt(jj)); }}); } catch (InterruptedException ex) { errMsg = ex.toString()+nl+"when reading complex nbr."+(n); System.err.println(Util.stack2string(ex)); } catch (java.lang.reflect.InvocationTargetException ex) { errMsg = ex.toString()+nl+"when reading complex nbr."+(n); System.err.println(Util.stack2string(ex)); } if(errMsg != null) { MsgExceptn.exception(errMsg); javax.swing.JOptionPane.showMessageDialog(FrameSingleComponent.this, errMsg, pc.progName,javax.swing.JOptionPane.ERROR_MESSAGE); } } else {j++;} } //while } else { // does not start with "@" fnd = false; int nTot = Math.min(cmplx.reactionComp.size(), cmplx.reactionCoef.size()); for(j =0; j < nTot; j++) { coef1 = cmplx.reactionCoef.get(j); if(cmplx.reactionComp.get(j).equals(choosenComp) && Math.abs(coef1) > 0.0001) {fnd = true; break;} } //for i if(fnd) { n++; javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() { jLabelN.setText(String.valueOf(n)); }}); final String o = cmplx.toString(); errMsg = null; try { javax.swing.SwingUtilities.invokeAndWait(new Runnable() {@Override public void run() { sortedModelComplexes.add(o); }}); } catch (InterruptedException ex) { errMsg = ex.toString()+nl+"when reading complex nbr."+(n); System.err.println(Util.stack2string(ex)); } catch (java.lang.reflect.InvocationTargetException ex) { errMsg = ex.toString()+nl+"when reading complex nbr."+(n); System.err.println(Util.stack2string(ex)); } if(errMsg != null) { MsgExceptn.exception(errMsg); javax.swing.JOptionPane.showMessageDialog(FrameSingleComponent.this, errMsg, pc.progName,javax.swing.JOptionPane.ERROR_MESSAGE); } } //if fnd } // starts with "@"? fistComplex = false; } //while n = sortedModelComplexes.getSize(); javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() { if(pd.dataBasesList.size() >1) { jLabelFound.setText("Found in databases:"); } else { jLabelFound.setText("Found in the database:"); } jLabelN.setText(String.valueOf(n)); if(n>=1) { jLabelSpecies.setText("species"); jButtonSave.setEnabled(true); jList.setFocusable(true); } else { jButtonSave.setEnabled(false); jList.setFocusable(false); } jScrollPaneList.validate(); jButtonSearch.setEnabled(true); FrameSingleComponent.this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); } }); // invokeLater }};//new Thread srch.start(); //any statements placed below are executed inmediately } // doSearch //</editor-fold> // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButtonExit; private javax.swing.JButton jButtonSave; private javax.swing.JButton jButtonSearch; private javax.swing.JComboBox<String> jComboBox; private javax.swing.JLabel jLabelFound; private javax.swing.JLabel jLabelN; private javax.swing.JLabel jLabelSpecies; private javax.swing.JLabel jLabelTop; private javax.swing.JList jList; private javax.swing.JMenuItem jMenuItemCancel; private javax.swing.JMenuItem jMenuItemRef; private javax.swing.JPanel jPanel1; private javax.swing.JPopupMenu jPopupMenu; private javax.swing.JScrollPane jScrollPaneList; private javax.swing.JPopupMenu.Separator jSeparator; // End of variables declaration//GEN-END:variables }
33,621
Java
.java
ignasi-p/eq-diagr
18
3
0
2018-08-17T08:25:37Z
2023-04-30T09:33:35Z