[UI] Splitted code to prepare mobile audio implementation

This commit is contained in:
emeric
2015-01-17 17:23:33 +01:00
parent fe5b010b84
commit e5a5e7dbc9
20 changed files with 232 additions and 66 deletions
+229
View File
@@ -0,0 +1,229 @@
/*
* Copyright (C) 2013 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS 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 LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Wt/WMediaPlayer>
#include <Wt/WProgressBar>
#include <Wt/WCheckBox>
#include <Wt/WTemplate>
#include <Wt/WHBoxLayout>
#include <Wt/WVBoxLayout>
#include <Wt/WApplication>
#include <Wt/WEnvironment>
#include "AudioMediaPlayer.hpp"
namespace UserInterface {
namespace Desktop {
Wt::WMediaPlayer::Encoding
AudioMediaPlayer::getEncoding()
{
const Wt::WEnvironment& env = Wt::WApplication::instance()->environment();
if (env.agentIsIE())
return Wt::WMediaPlayer::MP3;
else
return Wt::WMediaPlayer::OGA;
}
AudioMediaPlayer::AudioMediaPlayer( Wt::WContainerWidget *parent)
: Wt::WContainerWidget(parent),
_mediaResource(nullptr)
{
this->setStyleClass("mediaplayer");
this->setHeight(90);
Wt::WVBoxLayout* mainLayout = new Wt::WVBoxLayout();
this->setLayout(mainLayout);
Wt::WHBoxLayout *sliderLayout = new Wt::WHBoxLayout();
mainLayout->addLayout(sliderLayout);
sliderLayout->addWidget(_curTime = new Wt::WText("00:00:00"));
_curTime->setLineHeight(30);
sliderLayout->addWidget(_timeSlider = new Wt::WSlider( ), 1);
sliderLayout->addWidget(_duration = new Wt::WText("00:00:00"));
_duration->setLineHeight(30);
Wt::WHBoxLayout *controlsLayout = new Wt::WHBoxLayout();
mainLayout->addLayout(controlsLayout);
Wt::WContainerWidget *btnContainer = new Wt::WContainerWidget();
// Do not allow button to wrap
btnContainer->setMinimumSize(155, Wt::WLength::Auto);
Wt::WTemplate *t = new Wt::WTemplate(Wt::WString::tr("mediaplayer-controls"), btnContainer);
Wt::WPushButton *prevBtn = new Wt::WPushButton("<<");
t->bindWidget("prev", prevBtn);
prevBtn->setStyleClass("mediaplayer-controls");
_playBtn = new Wt::WPushButton("Play");
t->bindWidget("play", _playBtn);
_playBtn->setWidth(70);
_playBtn->setStyleClass("mediaplayer-controls");
_pauseBtn = new Wt::WPushButton("Pause");
t->bindWidget("pause", _pauseBtn);
_pauseBtn->setWidth(70);
_pauseBtn->setStyleClass("mediaplayer-controls");
Wt::WPushButton *nextBtn = new Wt::WPushButton(">>");
t->bindWidget("next", nextBtn);
nextBtn->setStyleClass("mediaplayer-controls");
controlsLayout->addWidget(btnContainer);
_volumeSlider = new Wt::WSlider();
_volumeSlider->setRange(0,100);
_volumeSlider->setWidth(60);
_volumeSlider->setMinimumSize(60, Wt::WLength::Auto);
controlsLayout->addWidget(_volumeSlider, 1);
Wt::WPushButton *loop = new Wt::WPushButton("Loop");
loop->setCheckable(true);
loop->setStyleClass("btn-xs");
loop->checked().connect(std::bind([=] () { _loop.emit( true ); }));
loop->unChecked().connect(std::bind([=] () { _loop.emit( false ); }));
controlsLayout->addWidget(loop);
Wt::WPushButton *shuffle = new Wt::WPushButton("Shuffle");
shuffle->setCheckable(true);
shuffle->setStyleClass("btn-xs");
shuffle->checked().connect(std::bind([=] () { _shuffle.emit( true ); }));
shuffle->unChecked().connect(std::bind([=] () { _shuffle.emit( false );}));
controlsLayout->addWidget(shuffle);
_mediaPlayer = new Wt::WMediaPlayer( Wt::WMediaPlayer::Audio, btnContainer );
_mediaPlayer->addSource( getEncoding(), "" );
_mediaPlayer->ended().connect(this, &AudioMediaPlayer::handleTrackEnded);
_mediaPlayer->setControlsWidget( 0 );
_mediaPlayer->setButton(Wt::WMediaPlayer::Play, _playBtn);
_mediaPlayer->setButton(Wt::WMediaPlayer::Pause, _pauseBtn);
_mediaPlayer->timeUpdated().connect(this, &AudioMediaPlayer::handleTimeUpdated);
_volumeSlider->setValue(_mediaPlayer->volume() * 100);
nextBtn->clicked().connect(std::bind([=] ()
{
_mediaPlayer->stop();
_playNext.emit();
}));
prevBtn->clicked().connect(std::bind([=] ()
{
_mediaPlayer->stop();
_playPrevious.emit();
}));
_timeSlider->valueChanged().connect(this, &AudioMediaPlayer::handlePlayOffset);
_timeSlider->setDisabled(true);
_volumeSlider->sliderMoved().connect(this, &AudioMediaPlayer::handleVolumeSliderMoved);
}
void
AudioMediaPlayer::loadPlayer(void)
{
_mediaPlayer->clearSources();
_mediaInternalLink.setResource( nullptr );
if (_mediaResource)
delete _mediaResource;
assert( _currentParameters );
_mediaResource = new AvConvTranscodeStreamResource( *_currentParameters, this );
_mediaInternalLink.setResource( _mediaResource );
_mediaPlayer->addSource( getEncoding(), _mediaInternalLink );
}
void
AudioMediaPlayer::load(const Transcode::Parameters& parameters)
{
_timeSlider->setDisabled(false);
_currentParameters = std::make_shared<Transcode::Parameters>( parameters );
loadPlayer();
_timeSlider->setRange(0, parameters.getInputMediaFile().getDuration().total_seconds() );
_timeSlider->setValue(0);
_duration->setText( boost::posix_time::to_simple_string( parameters.getInputMediaFile().getDuration() ));
_mediaPlayer->play();
}
void
AudioMediaPlayer::handlePlayOffset(int offsetSecs)
{
if (!_currentParameters)
return;
_currentParameters->setOffset( boost::posix_time::seconds(offsetSecs) );
loadPlayer();
_mediaPlayer->play();
}
void
AudioMediaPlayer::handleTrackEnded(void)
{
_playbackEnded.emit();
}
void
AudioMediaPlayer::handleValueChanged(double value)
{
// TODO
}
void
AudioMediaPlayer::handleSliderMoved(int value)
{
;
}
void
AudioMediaPlayer::handleTimeUpdated(void)
{
if (!_currentParameters)
return;
boost::posix_time::time_duration currentTime ( boost::posix_time::seconds( _mediaPlayer->currentTime() + _currentParameters->getOffset().total_seconds()));
_timeSlider->setValue( currentTime.total_seconds() );
_curTime->setText( boost::posix_time::to_simple_string( currentTime) );
}
void
AudioMediaPlayer::handleVolumeSliderMoved(int value)
{
_mediaPlayer->setVolume( value / 100. );
}
} // namespace Desktop
} // namespace UserInterface
+96
View File
@@ -0,0 +1,96 @@
/*
* Copyright (C) 2013 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS 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 LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __AUDIO_MEDIA_PLAYER_HPP
#define __AUDIO_MEDIA_PLAYER_HPP
#include <memory>
#include <Wt/WSlider>
#include <Wt/WPushButton>
#include <Wt/WContainerWidget>
#include <Wt/WMediaPlayer>
#include <Wt/WLink>
#include <Wt/WText>
#include "transcode/Parameters.hpp"
#include "resource/AvConvTranscodeStreamResource.hpp"
namespace UserInterface {
namespace Desktop {
class AudioMediaPlayer : public Wt::WContainerWidget
{
public:
// Encoding is set based on environment
static Wt::WMediaPlayer::Encoding getEncoding();
AudioMediaPlayer( Wt::WContainerWidget *parent = 0);
void load(const Transcode::Parameters& parameters);
// Signal slots
Wt::Signal<void>& playbackEnded() {return _playbackEnded;}
Wt::Signal<void>& playNext() {return _playNext;}
Wt::Signal<void>& playPrevious() {return _playPrevious;}
Wt::Signal<bool>& shuffle() {return _shuffle;}
Wt::Signal<bool>& loop() {return _loop;}
private:
void handlePlayOffset(int offsetSecs);
void handleTrackEnded(void);
void handleValueChanged(double);
void handleTimeUpdated(void);
void handleSliderMoved(int value);
void handleVolumeSliderMoved(int value);
void loadPlayer(void);
// Signals
Wt::Signal<void> _playbackEnded;
Wt::Signal<void> _playNext;
Wt::Signal<void> _playPrevious;
Wt::Signal<bool> _shuffle;
Wt::Signal<bool> _loop;
// Core
Wt::WMediaPlayer* _mediaPlayer;
AvConvTranscodeStreamResource* _mediaResource;
Wt::WLink _mediaInternalLink;
// Controls
std::shared_ptr<Transcode::Parameters> _currentParameters;
Wt::WPushButton* _playBtn;
Wt::WPushButton* _pauseBtn;
Wt::WSlider* _timeSlider;
Wt::WSlider* _volumeSlider;
Wt::WText* _curTime;
Wt::WText* _duration;
};
} // namespace Desktop
} // namespace UserInterface
#endif
+531
View File
@@ -0,0 +1,531 @@
/*
* Copyright (C) 2013 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS 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 LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/bind.hpp>
#include <Wt/WVBoxLayout>
#include <Wt/WHBoxLayout>
#include <Wt/WGridLayout>
#include <Wt/WComboBox>
#include <Wt/WPushButton>
#include <Wt/WMessageBox>
#include <Wt/WLengthValidator>
#include <Wt/WDialog>
#include <Wt/WLineEdit>
#include <Wt/WLabel>
#include "logger/Logger.hpp"
#include "TableFilter.hpp"
#include "KeywordSearchFilter.hpp"
#include "DesktopAudio.hpp"
namespace {
void WPopupMenuClear(Wt::WPopupMenu* menu)
{
while(menu->count() > 0)
menu->removeItem(menu->itemAt(0));
}
}
namespace UserInterface {
namespace Desktop {
Audio::Audio(SessionData& sessionData, Wt::WContainerWidget* parent)
: UserInterface::Audio(parent),
_db(sessionData.getDatabaseHandler()),
_mediaPlayer(nullptr),
_trackView(nullptr),
_playQueue(nullptr)
{
Wt::WGridLayout *mainLayout = new Wt::WGridLayout();
this->setLayout(mainLayout);
mainLayout->setContentsMargins(9,4,9,9);
// Filters
Wt::WHBoxLayout *filterLayout = new Wt::WHBoxLayout();
TableFilterGenre *filterGenre = new TableFilterGenre(_db);
filterLayout->addWidget(filterGenre);
_filterChain.addFilter(filterGenre);
TableFilterArtist *filterArtist = new TableFilterArtist(_db);
filterLayout->addWidget(filterArtist);
_filterChain.addFilter(filterArtist);
TableFilterRelease *filterRelease = new TableFilterRelease(_db);
filterLayout->addWidget(filterRelease);
_filterChain.addFilter(filterRelease);
mainLayout->addLayout(filterLayout, 0, 1);
// ENDOF(Filters)
// TODO ADD some stats (nb files, total duration, etc.)
Wt::WVBoxLayout* trackLayout = new Wt::WVBoxLayout();
_trackView = new TrackView(_db);
trackLayout->addWidget(_trackView, 1);
Wt::WHBoxLayout* trackControls = new Wt::WHBoxLayout();
Wt::WPushButton* playBtn = new Wt::WPushButton("Play");
playBtn->setStyleClass("btn-sm");
trackControls->addWidget(playBtn);
Wt::WPushButton* addBtn = new Wt::WPushButton("Add");
addBtn->setStyleClass("btn-sm");
trackControls->addWidget(addBtn);
trackControls->addWidget(new Wt::WText("Total duration: "), 1);
trackLayout->addLayout(trackControls);
mainLayout->addLayout(trackLayout, 1, 1);
_filterChain.addFilter(_trackView);
_playQueue = new PlayQueue(_db);
// Playlist/PlayQueue
{
Wt::Dbo::Transaction transaction(_db.getSession());
Wt::WContainerWidget* playQueueContainer = new Wt::WContainerWidget();
playQueueContainer->setStyleClass("playqueue");
Wt::WVBoxLayout* playQueueLayout = new Wt::WVBoxLayout();
playQueueContainer->setLayout(playQueueLayout);
_mediaPlayer = new AudioMediaPlayer();
playQueueLayout->addWidget(_mediaPlayer);
playQueueLayout->addWidget( _playQueue, 1);
Wt::WHBoxLayout* playlistControls = new Wt::WHBoxLayout();
Wt::WPushButton *playlistBtn = new Wt::WPushButton("Playlist");
playlistBtn->setStyleClass("btn-sm btn-primary");
playlistControls->addWidget(playlistBtn);
// Playlist menu
{
Wt::WPopupMenu *popupMain = new Wt::WPopupMenu();
_popupMenuSave = new Wt::WPopupMenu();
popupMain->addMenu("Save", _popupMenuSave);
_popupMenuLoad = new Wt::WPopupMenu();
popupMain->addMenu("Load", _popupMenuLoad);
_popupMenuDelete = new Wt::WPopupMenu();
popupMain->addMenu("Delete", _popupMenuDelete);
playlistBtn->setMenu(popupMain);
}
Wt::WPushButton *upBtn = new Wt::WPushButton("UP");
upBtn->setStyleClass("btn-sm");
playlistControls->addWidget(upBtn);
Wt::WPushButton *downBtn = new Wt::WPushButton("DO");
downBtn->setStyleClass("btn-sm");
playlistControls->addWidget(downBtn);
Wt::WPushButton *delBtn = new Wt::WPushButton("DEL");
delBtn->setStyleClass("btn-sm btn-warning");
playlistControls->addWidget(delBtn);
Wt::WPushButton *clearBtn = new Wt::WPushButton("CLR");
clearBtn->setStyleClass("btn-sm btn-danger");
playlistControls->addWidget(clearBtn);
delBtn->clicked().connect(_playQueue, &PlayQueue::delSelected);
upBtn->clicked().connect(_playQueue, &PlayQueue::moveSelectedUp);
downBtn->clicked().connect(_playQueue, &PlayQueue::moveSelectedDown);
clearBtn->clicked().connect(_playQueue, &PlayQueue::delAll);
playQueueLayout->addLayout(playlistControls);
mainLayout->addWidget(playQueueContainer, 0, 0, 2, 1);
}
mainLayout->setRowStretch(1, 1);
mainLayout->setRowResizable(0, true, Wt::WLength(250, Wt::WLength::Pixel));
mainLayout->setColumnResizable(0, true, Wt::WLength(400, Wt::WLength::Pixel));
// Double click on track
// Set the selected tracks to the play queue
_trackView->trackDoubleClicked().connect(boost::bind(&Audio::playSelectedTracks, this, PlayQueueAddSelectedTracks));
// Double click on artist
// Set the selected tracks to the play queue
filterArtist->sigDoubleClicked().connect(boost::bind(&Audio::playSelectedTracks, this, PlayQueueAddAllTracks));
filterRelease->sigDoubleClicked().connect(boost::bind(&Audio::playSelectedTracks, this, PlayQueueAddAllTracks));
filterGenre->sigDoubleClicked().connect(boost::bind(&Audio::playSelectedTracks, this, PlayQueueAddAllTracks));
// Play button
// Set the selected tracks to the play queue
playBtn->clicked().connect(boost::bind(&Audio::playSelectedTracks, this, PlayQueueAddSelectedTracks));
// Add Button
// Add the selected tracks at the end of the play queue
addBtn->clicked().connect(this, &Audio::addSelectedTracks);
_playQueue->playTrack().connect(this, &Audio::playTrack);
_mediaPlayer->playbackEnded().connect(_playQueue, &PlayQueue::handlePlaybackComplete);
_mediaPlayer->playNext().connect(_playQueue, &PlayQueue::playNext);
_mediaPlayer->playPrevious().connect(_playQueue, &PlayQueue::playPrevious);
_mediaPlayer->shuffle().connect(boost::bind(&PlayQueue::setShuffle, _playQueue, _1));
_mediaPlayer->loop().connect(boost::bind(&PlayQueue::setLoop,_playQueue, _1));
playlistRefreshMenus();
}
void
Audio::playlistShowSaveNewDialog()
{
Wt::WDialog *dialog = new Wt::WDialog("New playlist");
Wt::WLabel *label = new Wt::WLabel("Name", dialog->contents());
Wt::WLineEdit *edit = new Wt::WLineEdit(dialog->contents());
label->setBuddy(edit);
Wt::WLengthValidator* validator = new Wt::WLengthValidator();
validator->setMinimumLength(3);
validator->setMandatory(true);
edit->setValidator(validator);
Wt::WPushButton *save = new Wt::WPushButton("Save", dialog->footer());
save->setStyleClass("btn-success");
save->setDefault(true);
save->disable();
Wt::WPushButton *cancel = new Wt::WPushButton("Cancel", dialog->footer());
dialog->rejectWhenEscapePressed();
edit->keyWentUp().connect(std::bind([=] () {
save->setDisabled(edit->validate() != Wt::WValidator::Valid);
}));
save->clicked().connect(std::bind([=] ()
{
if (edit->validate())
dialog->accept();
}));
cancel->clicked().connect(dialog, &Wt::WDialog::reject);
dialog->finished().connect(std::bind([=] ()
{
if (dialog->result() == Wt::WDialog::Accepted)
{
playlistShowSaveDialog(edit->text().toUTF8());
}
delete dialog;
}));
dialog->show();
}
void
Audio::playlistShowSaveDialog(std::string playlistName)
{
Wt::Dbo::Transaction transaction(_db.getSession());
Database::User::pointer user = _db.getCurrentUser();
if (!user)
return;
// Actually create the dialog only if the given list already exists
if (Database::Playlist::get(_db.getSession(), playlistName, user))
{
Wt::WMessageBox *messageBox = new Wt::WMessageBox
("Overwrite playlist",
Wt::WString( "Overwrite playlist '{1}'?").arg(playlistName),
Wt::Question, Wt::Yes | Wt::No);
messageBox->setModal(true);
messageBox->buttonClicked().connect(std::bind([=] () {
if (messageBox->buttonResult() == Wt::Yes)
playlistSaveFromPlayqueue(playlistName);
delete messageBox;
}));
messageBox->show();
}
else
{
playlistSaveFromPlayqueue(playlistName);
playlistRefreshMenus();
}
}
void
Audio::playlistSaveFromPlayqueue(std::string playlistName)
{
LMS_LOG(MOD_UI, SEV_INFO) << "Saving playqueue to playlist '" << playlistName << "'";
Wt::Dbo::Transaction transaction(_db.getSession());
Database::User::pointer user = _db.getCurrentUser();
if (!user)
return;
Database::Playlist::pointer playlist = Database::Playlist::get(_db.getSession(), playlistName, user);
if (playlist)
{
LMS_LOG(MOD_UI, SEV_INFO) << "Erasing playlist '" << playlistName << "'";
playlist.remove();
}
playlist = Database::Playlist::create(_db.getSession(), playlistName, false, user);
std::vector<Database::Track::id_type> trackIds;
_playQueue->getTracks(trackIds);
int pos = 0;
BOOST_FOREACH(Database::Track::id_type trackId, trackIds)
{
Database::Track::pointer track = Database::Track::getById(_db.getSession(), trackId);
if (track)
Database::PlaylistEntry::create(_db.getSession(), track, playlist, pos++);
}
LMS_LOG(MOD_UI, SEV_INFO) << "Saving playqueue to playlist '" << playlistName << "' done. Contains " << pos << " entries";
}
void
Audio::playlistLoadToPlayqueue(std::string playlistName)
{
LMS_LOG(MOD_UI, SEV_DEBUG) << "Loading playlist '" << playlistName << "' to playqueue";
Wt::Dbo::Transaction transaction(_db.getSession());
Database::User::pointer user = _db.getCurrentUser();
if (!user)
return;
Database::Playlist::pointer playlist = Database::Playlist::get(_db.getSession(), playlistName, user);
if (!playlist)
return;
std::vector<Database::Track::id_type> entries = Database::PlaylistEntry::getEntries(_db.getSession(), playlist);
_playQueue->clear();
_playQueue->addTracks(entries);
LMS_LOG(MOD_UI, SEV_DEBUG) << "Loading playlist '" << playlistName << "' to playqueue done. " << entries.size() << " entries";
}
void
Audio::playlistShowDeleteDialog(std::string name)
{
Wt::WMessageBox *messageBox = new Wt::WMessageBox
("Delete playlist",
Wt::WString( "Deleting playlist '{1}'?").arg(name),
Wt::Question, Wt::Yes | Wt::No);
messageBox->setModal(true);
messageBox->buttonClicked().connect(std::bind([=] () {
if (messageBox->buttonResult() == Wt::Yes)
{
Wt::Dbo::Transaction transaction(_db.getSession());
Database::User::pointer user = _db.getCurrentUser();
if (!user)
return;
Database::Playlist::pointer playlist = Database::Playlist::get(_db.getSession(), name, user);
if (playlist)
playlist.remove();
playlistRefreshMenus();
}
delete messageBox;
}));
messageBox->show();
}
void
Audio::playlistRefreshMenus()
{
Wt::Dbo::Transaction transaction(_db.getSession());
Database::User::pointer user = _db.getCurrentUser();
if (!user)
return;
// Clear playlists in each menu
LMS_LOG(MOD_UI, SEV_DEBUG) << "Save item count: " << _popupMenuSave->count();
WPopupMenuClear(_popupMenuDelete);
WPopupMenuClear(_popupMenuLoad);
WPopupMenuClear(_popupMenuSave);
_popupMenuSave->addItem("New")->triggered().connect(std::bind([=] ()
{
playlistShowSaveNewDialog();
}));
_popupMenuSave->addSeparator();
std::vector<Database::Playlist::pointer> playlists = Database::Playlist::get(_db.getSession(), user);
BOOST_FOREACH(Database::Playlist::pointer playlist, playlists)
{
// Add playlists in each menu
_popupMenuDelete->addItem(playlist->getName())->triggered().connect(std::bind([=] ()
{
playlistShowDeleteDialog(playlist->getName());
}));
_popupMenuLoad->addItem(playlist->getName())->triggered().connect(std::bind([=] ()
{
playlistLoadToPlayqueue(playlist->getName());
playlistRefreshMenus(); // in case deleted in other session
}));
_popupMenuSave->addItem(playlist->getName())->triggered().connect(std::bind([=] ()
{
playlistShowSaveDialog(playlist->getName());
}));
}
}
void
Audio::search(std::string searchText)
{
_filterChain.searchKeyword(searchText);
}
void
Audio::addSelectedTracks(void)
{
std::vector<Database::Track::id_type> trackIds;
_trackView->getSelectedTracks(trackIds);
// If nothing is selected, get the whole track list
if (trackIds.empty())
_trackView->getTracks(trackIds);
_playQueue->addTracks(trackIds);
}
void
Audio::playSelectedTracks(PlayQueueAddType addType)
{
std::vector<Database::Track::id_type> trackIds;
_playQueue->clear();
switch(addType)
{
case PlayQueueAddAllTracks:
// Play all the tracks
_trackView->getTracks(trackIds);
_playQueue->addTracks(trackIds);
_playQueue->play();
break;
case PlayQueueAddSelectedTracks:
// If nothing selected, get all the track and play everything
if (_trackView->getNbSelectedTracks() == 0)
{
_trackView->getTracks(trackIds);
_playQueue->addTracks(trackIds);
_playQueue->play();
}
// If only ONE selected, get them all and pre select the track
else if (_trackView->getNbSelectedTracks() == 1)
{
// Start to play at the selected track, if any
_trackView->getTracks(trackIds);
_playQueue->addTracks(trackIds);
_playQueue->play(_trackView->getFirstSelectedTrackPosition());
}
else
{
// Play all the selected tracks
_trackView->getSelectedTracks(trackIds);
_playQueue->addTracks(trackIds);
_playQueue->play();
}
break;
}
}
void
Audio::playTrack(boost::filesystem::path p)
{
LMS_LOG(MOD_UI, SEV_DEBUG) << "play track '" << p << "'";
try {
std::size_t bitrate = 0;
// Get user preferences
{
Wt::Dbo::Transaction transaction(_db.getSession());
Database::User::pointer user = _db.getCurrentUser();
if (user)
bitrate = user->getAudioBitrate();
else
{
LMS_LOG(MOD_UI, SEV_ERROR) << "Can't play: user does not exists!";
return; // TODO logout?
}
}
Transcode::InputMediaFile inputFile(p);
// Determine the output format using the encoding of the player
Transcode::Format::Encoding encoding;
switch(AudioMediaPlayer::getEncoding())
{
case Wt::WMediaPlayer::MP3: encoding = Transcode::Format::MP3; break;
case Wt::WMediaPlayer::M4A: encoding = Transcode::Format::M4A; break;
case Wt::WMediaPlayer::OGA: encoding = Transcode::Format::OGA; break;
default:
encoding = Transcode::Format::MP3;
}
Transcode::Parameters parameters(inputFile, Transcode::Format::get(encoding));
parameters.setBitrate(Transcode::Stream::Audio, bitrate);
_mediaPlayer->load( parameters );
}
catch( std::exception &e)
{
LMS_LOG(MOD_UI, SEV_ERROR) << "Caught exception while loading '" << p << "': " << e.what();
}
}
} // namespace Desktop
} // namespace UserInterface
+88
View File
@@ -0,0 +1,88 @@
/*
* Copyright (C) 2013 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS 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 LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef UI_AUDIO_DESKTOP_HPP
#define UI_AUDIO_DESKTOP_HPP
#include <string>
#include <Wt/WPopupMenu>
#include "common/SessionData.hpp"
#include "AudioMediaPlayer.hpp"
#include "TrackView.hpp"
#include "PlayQueue.hpp"
#include "FilterChain.hpp"
#include "audio/Audio.hpp"
namespace UserInterface {
namespace Desktop {
class Audio : public UserInterface::Audio
{
public:
Audio(SessionData& sessionData, Wt::WContainerWidget* parent = 0);
void search(std::string searchText);
private:
void playlistSaveFromPlayqueue(std::string name);
void playlistLoadToPlayqueue(std::string name);
void playlistShowSaveNewDialog();
void playlistShowSaveDialog(std::string name);
void playlistShowDeleteDialog(std::string name);
void playlistRefreshMenus();
void playTrack(boost::filesystem::path p);
enum PlayQueueAddType
{
PlayQueueAddAllTracks,
PlayQueueAddSelectedTracks,
};
void playSelectedTracks(PlayQueueAddType addType);
void addSelectedTracks();
void handlePlaylistSelected(Wt::WString name);
Database::Handler& _db;
AudioMediaPlayer* _mediaPlayer;
TrackView* _trackView;
PlayQueue* _playQueue;
FilterChain _filterChain;
Wt::WPopupMenu* _popupMenuSave;
Wt::WPopupMenu* _popupMenuLoad;
Wt::WPopupMenu* _popupMenuDelete;
};
} // namespace Desktop
} // namespace UserInterface
#endif
+65
View File
@@ -0,0 +1,65 @@
/*
* Copyright (C) 2013 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS 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 LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef FILTER_HPP
#define FILTER_HPP
#include <Wt/WSignal>
#include "database/Types.hpp"
namespace UserInterface {
namespace Desktop {
class Filter
{
public:
struct Constraint {
std::vector<std::string> search;
typedef std::map<std::string, std::vector<std::string> > ColumnValues;
ColumnValues columnValues;
};
Filter() {}
virtual ~Filter() {}
// Refresh filter using constraints created by parent filters
virtual void refresh(Database::SearchFilter& filter) = 0;
// Update constraints for next filters
virtual void getConstraint(Database::SearchFilter& filter) = 0;
// Emitted when a constraint has changed
Wt::Signal<void>& update() { return _update; };
protected:
void emitUpdate() { _update.emit(); }
private:
Wt::Signal<void> _update;
};
} // namespace Dekstop
} // namespace UserInterface
#endif
+75
View File
@@ -0,0 +1,75 @@
/*
* Copyright (C) 2014 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS 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 LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#include "FilterChain.hpp"
namespace UserInterface {
namespace Desktop {
FilterChain::FilterChain()
: _refreshingFilters(false)
{
addFilter(&_keywordSearchFilter);
}
void
FilterChain::addFilter(Filter* filter)
{
filter->update().connect(boost::bind(&FilterChain::updateFilters, this, _filters.size()));
_filters.push_back(filter);
}
void
FilterChain::searchKeyword(const std::string& text)
{
_keywordSearchFilter.setText(text);
}
void
FilterChain::updateFilters(std::size_t startIdx)
{
// Prevent loops
if (_refreshingFilters)
return;
_refreshingFilters = true;
Database::SearchFilter searchFilter;
for (std::size_t idFilter = 0; idFilter < _filters.size(); ++idFilter)
{
Filter* filter = _filters.at(idFilter);
// Apply contraints created by previous filters
if (idFilter > startIdx) {
filter->refresh(searchFilter);
}
// Get constraints generated by this filter
// (Note: adding accross successive calls)
filter->getConstraint(searchFilter);
}
_refreshingFilters = false;
}
} // namespace Desktop
} // namespace UserInterface
+59
View File
@@ -0,0 +1,59 @@
/*
* Copyright (C) 2014 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS 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 LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef FILTER_CHAIN_HPP
#define FILTER_CHAIN_HPP
#include <Wt/WSignal>
#include "Filter.hpp"
#include "KeywordSearchFilter.hpp"
namespace UserInterface {
namespace Desktop {
// FilterChain
class FilterChain
{
public:
FilterChain();
void addFilter(Filter* filter);
// First filter is a keywork search
void searchKeyword(const std::string& text);
// Update filters from filter @ startIdx
void updateFilters(std::size_t startIdx);
private:
KeywordSearchFilter _keywordSearchFilter;
// No ownership
std::vector<Filter*> _filters;
bool _refreshingFilters;
};
} // namespace Desktop
} // namespace UserInterface
#endif
@@ -0,0 +1,66 @@
/*
* Copyright (C) 2013 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS 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 LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/foreach.hpp>
#include "KeywordSearchFilter.hpp"
namespace UserInterface {
namespace Desktop {
KeywordSearchFilter::KeywordSearchFilter()
{
}
void
KeywordSearchFilter::setText(const std::string& text)
{
_lastEmittedText = text;
emitUpdate();
}
// Get constraints created by this filter
void
KeywordSearchFilter::getConstraint(Database::SearchFilter& filter)
{
// No active search means no constaint!
if (!_lastEmittedText.empty()) {
std::vector<std::string> values;
boost::algorithm::split(values, _lastEmittedText, boost::is_any_of(" "), boost::token_compress_on);
// For each part, do a global search on all searchable fields
BOOST_FOREACH(std::string value, values)
{
Database::SearchFilter::FieldValues likeMatch;
likeMatch[Database::SearchFilter::Field::Artist].push_back(value);
likeMatch[Database::SearchFilter::Field::Release].push_back(value);
likeMatch[Database::SearchFilter::Field::Genre].push_back(value);
likeMatch[Database::SearchFilter::Field::Track].push_back(value);
filter.likeMatches.push_back(likeMatch);
}
}
}
} // namespace Desktop
} // namespace UserInterface
@@ -0,0 +1,54 @@
/*
* Copyright (C) 2013 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS 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 LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef KEYWORD_SEARCH_FILTER_HPP
#define KEYWORD_SEARCH_FILTER_HPP
#include <string>
#include "Filter.hpp"
namespace UserInterface {
namespace Desktop {
class KeywordSearchFilter : public Filter
{
public:
KeywordSearchFilter();
void setText(const std::string& text);
// Set constraint on this filter
void refresh(Database::SearchFilter& filter) {}
// Get constraints created by this filter
void getConstraint(Database::SearchFilter& filter);
private:
void handleKeyWentUp(void);
std::string _lastEmittedText;
};
} // namespace Desktop
} // namespace UserInterface
#endif
+616
View File
@@ -0,0 +1,616 @@
/*
* Copyright (C) 2014 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS 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 LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int_distribution.hpp>
#include <Wt/WApplication>
#include <Wt/WImage>
#include <Wt/WLink>
#include <Wt/WItemDelegate>
#include <Wt/WStandardItem>
#include <Wt/WFileResource>
#include <Wt/WTheme>
#include "resource/CoverResource.hpp"
#include "logger/Logger.hpp"
#include "PlayQueue.hpp"
static const int NameRole = Wt::UserRole;
namespace {
void swapRows(Wt::WStandardItemModel *model, int row1, int row2)
{
// Swap data column by column
for (int i = 0; i < model->columnCount(); ++i)
{
Wt::WModelIndex index1 = model->index(row1, i);
Wt::WModelIndex index2 = model->index(row2, i);
// swap data associated with standard roles
{
auto tmp = model->itemData(index1); // 1 -> tmp
model->setItemData(index1, model->itemData(index2)); // 2 -> 1
model->setItemData(index2, tmp); // tmp-> 2
}
// caution: swap data associated with our custom roles if any!!
}
}
}
namespace UserInterface {
namespace Desktop {
enum ColumnId
{
COLUMN_ID_TRACK_ID = 0,
COLUMN_ID_COVER = 1,
COLUMN_ID_NAME = 2,
};
static const int trackPosInvalid = -1;
class TrackSelector
{
public:
TrackSelector();
void setShuffle(bool enable);
void setLoop(bool enable) { _loop = enable; }
int previous(void);
int next(void);
int getCurrent(void);
// Set the internal pos thanks to the track pos
void setPosByRowId(int rowId);
void setPos(int pos) { _curPos = pos; }
void setSize(std::size_t size);
std::size_t getSize(void) const { return _size;}
private:
void refreshPositions();
bool _loop;
bool _shuffle;
std::size_t _size;
std::size_t _curPos;
std::vector<int> _trackPos;
};
TrackSelector::TrackSelector()
: _loop(false),
_shuffle(false),
_size(0),
_curPos(0)
{
}
void
TrackSelector::refreshPositions()
{
_trackPos.clear();
if (_size == 0)
return;
for (std::size_t i = 0; i < _size; ++i)
_trackPos.push_back(i);
// Now shuffle
// Source: http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
boost::random::mt19937 rng; // produces randomness out of thin air
rng.seed(static_cast<unsigned int>(std::time(0)));
for (std::size_t i = 0; i < _size; ++i)
{
boost::random::uniform_int_distribution<> distribution(i, _size - 1);
int val1 = distribution(rng);
int tmp = _trackPos[i];
_trackPos[i] = _trackPos[val1];
_trackPos[val1] = tmp;
}
}
int
TrackSelector::getCurrent()
{
return _shuffle ? _trackPos[_curPos] : _curPos;
}
void
TrackSelector::setShuffle(bool enable)
{
_shuffle = enable;
if (_size != 0)
{
// Update the current index we are playing if we switch shuffle
if (_shuffle)
setPosByRowId(_curPos);
else
setPos(_trackPos[_curPos]);
}
}
int
TrackSelector::next()
{
if (_size == 0)
return trackPosInvalid;
if (_curPos == _size - 1)
{
if (!_loop)
return trackPosInvalid;
else
_curPos = 0;
}
else
++_curPos;
return _shuffle ? _trackPos[_curPos] : _curPos;
}
int
TrackSelector::previous()
{
if (_size == 0)
return trackPosInvalid;
if (_curPos == 0)
{
if (!_loop)
return trackPosInvalid;
else
_curPos = _size - 1;
}
else
--_curPos;
return _shuffle ? _trackPos[_curPos] : _curPos;
}
void
TrackSelector::setPosByRowId(int rowId)
{
if (_shuffle)
{
for (std::size_t i = 0; i < _trackPos.size(); ++i)
{
if (rowId == _trackPos[i])
{
_curPos = i;
break;
}
}
}
else
_curPos = rowId;
}
void
TrackSelector::setSize(std::size_t size)
{
_size = size;
_curPos = 0;
refreshPositions();
}
struct Name
{
Wt::WString track;
Wt::WString artist;
};
class PlayQueueItemDelegate : public Wt::WItemDelegate
{
public:
PlayQueueItemDelegate(Wt::WObject *parent = 0) : Wt::WItemDelegate(parent) {}
Wt::WWidget* update(Wt::WWidget *widget, const Wt::WModelIndex &index, Wt::WFlags< Wt::ViewItemRenderFlag > flags)
{
Wt::WWidget* res;
if (!index.data(NameRole).empty())
{
Name name = boost::any_cast<Name>(index.data(NameRole));
Wt::WContainerWidget *container = new Wt::WContainerWidget();
Wt::WText* track = new Wt::WText(name.track, Wt::PlainText, container);
Wt::WText* artist = new Wt::WText(name.artist, Wt::PlainText, container);
artist->setInline(false);
track->setInline(false);
artist->setStyleClass("playqueue-artist");
track->setStyleClass("playqueue-track");
// Apply style if any
Wt::WString styleClass = Wt::asString(index.data(Wt::StyleClassRole));
// Apply selection style if any
if (flags & Wt::RenderSelected)
styleClass += " " + Wt::WApplication::instance()->theme()->activeClass();
container->setStyleClass(styleClass);
res = container;
}
else
res = Wt::WItemDelegate::update(widget, index, flags);
return res;
}
private:
};
PlayQueue::PlayQueue(Database::Handler& db, Wt::WContainerWidget* parent)
: Wt::WTableView(parent),
_db(db),
_curPlayedTrackPos(trackPosInvalid),
_trackSelector(new TrackSelector())
{
_model = new Wt::WStandardItemModel(0, 3, this);
// 0 Column is hidden (track id)
_model->setHeaderData(COLUMN_ID_TRACK_ID, Wt::WString("#"));
_model->setHeaderData(COLUMN_ID_COVER, Wt::WString("Cover"));
_model->setHeaderData(COLUMN_ID_NAME, Wt::WString("Track"));
this->setModel(_model);
this->setSelectionMode(Wt::ExtendedSelection);
this->setSortingEnabled(false);
this->setAlternatingRowColors(true);
this->setRowHeight(64);
this->setColumnWidth(COLUMN_ID_COVER, 64);
this->setColumnWidth(COLUMN_ID_NAME, 240);
this->setLayoutSizeAware(true);
this->setColumnHidden(COLUMN_ID_TRACK_ID, true);
_itemDelegate = new PlayQueueItemDelegate();
this->setItemDelegate(_itemDelegate);
this->doubleClicked().connect( std::bind([=] (Wt::WModelIndex idx, Wt::WMouseEvent evt)
{
if (!idx.isValid())
return;
// Update selection
Wt::WModelIndexSet indexSet;
indexSet.insert(idx);
this->setSelectedIndexes( indexSet );
// Read the requested track
play(idx.row());
}, std::placeholders::_1, std::placeholders::_2));
_coverResource = new CoverResource(db, 64);
}
void
PlayQueue::layoutSizeChanged (int width, int height)
{
std::size_t coverColumnSize = this->columnWidth(COLUMN_ID_COVER).toPixels();
// Set the remaining size for the name column
this->setColumnWidth(COLUMN_ID_NAME, width - coverColumnSize - (7 * 2) - 2);
}
void
PlayQueue::setShuffle(bool enable)
{
_trackSelector->setShuffle(enable);
}
void
PlayQueue::setLoop(bool enable)
{
_trackSelector->setLoop(enable);
}
void
PlayQueue::play()
{
_trackSelector->setPos(0);
if (!readTrack(_trackSelector->getCurrent()))
playNext();
}
void
PlayQueue::play(int rowId)
{
// Update the track selector to use the requested track as current position
_trackSelector->setPosByRowId(rowId);
if (!readTrack(_trackSelector->getCurrent()))
playNext();
}
void
PlayQueue::addTracks(const std::vector<Database::Track::id_type>& trackIds)
{
// Add tracks to model
Wt::Dbo::Transaction transaction(_db.getSession());
BOOST_FOREACH(Database::Track::id_type trackId, trackIds)
{
Database::Track::pointer track (Database::Track::getById(_db.getSession(), trackId));
if (track)
{
int dataRow = _model->rowCount();
_model->insertRows(dataRow, 1);
_model->setData(dataRow, COLUMN_ID_TRACK_ID, track.id(), Wt::UserRole);
std::string coverUrl;
if (track->hasCover())
coverUrl = _coverResource->url() + "&coverid=" + Wt::asString(track.id()).toUTF8();
else
coverUrl = "images/unknown-cover.jpg";
_model->setData(dataRow, COLUMN_ID_COVER, coverUrl, Wt::DecorationRole);
Name name;
name.track = Wt::WString::fromUTF8(track->getName());
name.artist = Wt::WString::fromUTF8(track->getArtistName());
_model->setData(dataRow, COLUMN_ID_NAME, name, NameRole);
}
}
_trackSelector->setSize( _model->rowCount() );
}
void
PlayQueue::clear(void)
{
_model->removeRows(0, _model->rowCount());
// Reset play id
_curPlayedTrackPos = trackPosInvalid;
_trackSelector->setSize( 0 );
}
void
PlayQueue::handlePlaybackComplete(void)
{
playNext();
}
void
PlayQueue::playNext(void)
{
std::size_t nbTries = _trackSelector->getSize();
while (nbTries > 0)
{
int pos = _trackSelector->next();
if (pos == trackPosInvalid)
break;
if (readTrack(pos))
break;
--nbTries;
}
}
void
PlayQueue::playPrevious(void)
{
std::size_t nbTries = _trackSelector->getSize();
while (nbTries > 0)
{
int pos = _trackSelector->previous();
if (pos == trackPosInvalid)
break;
if (readTrack(pos))
break;
--nbTries;
}
}
bool
PlayQueue::readTrack(int rowPos)
{
Wt::Dbo::Transaction transaction(_db.getSession());
LMS_LOG(MOD_UI, SEV_DEBUG) << "Reading track at pos " << rowPos;
Database::Track::id_type trackId = boost::any_cast<Database::Track::id_type>(_model->data(rowPos, COLUMN_ID_TRACK_ID, Wt::UserRole));
Database::Track::pointer track = Database::Track::getById(_db.getSession(), trackId);
if (track)
{
setPlayingTrackPos(rowPos);
_sigTrackPlay.emit(track->getPath());
this->scrollTo( _model->index(_trackSelector->getCurrent(), 0));
return true;
}
else
return false;
}
void
PlayQueue::setPlayingTrackPos(int newRowPos)
{
int oldRowPos = _curPlayedTrackPos;
_curPlayedTrackPos = newRowPos;
// Hack re-set the data in order to trigger the rerending of the widget
// calling the update method of our custom item delegate gives bad results
if (oldRowPos >= 0)
{
_model->setData(oldRowPos, COLUMN_ID_NAME, boost::any(), Wt::StyleClassRole);
}
if (newRowPos >= 0)
{
_model->setData(newRowPos, COLUMN_ID_NAME, "playqueue-playing", Wt::StyleClassRole);
}
}
void
PlayQueue::delSelected(void)
{
int minId = _model->rowCount();
Wt::WModelIndexSet indexSet = this->selectedIndexes();
BOOST_REVERSE_FOREACH(Wt::WModelIndex index, indexSet)
{
_model->removeRow(index.row());
if (index.row() < minId)
minId = index.row();
}
// If the current played track is removed, make sure to unselect it
_trackSelector->setSize(_model->rowCount());
renumber(minId, _model->rowCount() - 1);
}
void
PlayQueue::delAll(void)
{
_model->removeRows(0, _model->rowCount());
_trackSelector->setSize(0);
}
void
PlayQueue::moveSelectedUp(void)
{
int minId = _model->rowCount();
int maxId = 0;
Wt::WModelIndexSet indexSet = this->selectedIndexes();
Wt::WModelIndexSet newIndexSet;
// ordered from up to down
BOOST_FOREACH(Wt::WModelIndex index, indexSet)
{
// Do nothing if the first selected index is on the top
if (index.row() == 0)
return;
// TODO optimize for blocks
swapRows(_model, index.row() - 1, index.row());
if (index.row() - 1 < minId)
minId = index.row() - 1;
if (index.row() > maxId)
maxId = index.row();
// Update playing status
if (_curPlayedTrackPos == index.row())
setPlayingTrackPos(_curPlayedTrackPos - 1);
else if (_curPlayedTrackPos == index.row() - 1)
setPlayingTrackPos(_curPlayedTrackPos + 1);
newIndexSet.insert( _model->index(index.row() - 1, 0));
}
_trackSelector->setPosByRowId(_curPlayedTrackPos);
this->setSelectedIndexes( newIndexSet );
renumber(minId, maxId);
}
void
PlayQueue::moveSelectedDown(void)
{
int minId = _model->rowCount();
int maxId = 0;
Wt::WModelIndexSet indexSet = this->selectedIndexes();
Wt::WModelIndexSet newIndexSet;
// ordered from up to down
BOOST_REVERSE_FOREACH(Wt::WModelIndex index, indexSet)
{
// Do nothing if the last selected index is the last one
if (index.row() == _model->rowCount() - 1)
return;
// TODO optimize for blocks
swapRows(_model, index.row(), index.row() + 1);
if (index.row() < minId)
minId = index.row();
if (index.row() + 1 > maxId)
maxId = index.row() + 1;
// Update playing status
if (_curPlayedTrackPos == index.row())
setPlayingTrackPos(_curPlayedTrackPos + 1);
else if (_curPlayedTrackPos == index.row() + 1)
setPlayingTrackPos(_curPlayedTrackPos - 1);
newIndexSet.insert( _model->index(index.row() + 1, 0));
}
_trackSelector->setPosByRowId(_curPlayedTrackPos);
this->setSelectedIndexes( newIndexSet );
renumber(minId, maxId);
}
void
PlayQueue::renumber(int firstId, int lastId)
{
for (int i = firstId; i <= lastId; ++i)
_model->setData( i, 1, i + 1);
}
void
PlayQueue::getTracks(std::vector<Database::Track::id_type>& trackIds) const
{
// Now add each entry in the playlist
for (int i = 0; i < _model->rowCount(); ++i)
{
Database::Track::id_type trackId = boost::any_cast<Database::Track::id_type>(_model->data(i, COLUMN_ID_TRACK_ID, Wt::UserRole));
trackIds.push_back(trackId);
}
}
} // namespace Desktop
} // namespace UserInterface
+93
View File
@@ -0,0 +1,93 @@
/*
* Copyright (C) 2014 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS 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 LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PLAY_QUEUE_HPP
#define PLAY_QUEUE_HPP
#include <Wt/WTableView>
#include <Wt/WStandardItemModel>
#include "database/DatabaseHandler.hpp"
#include "resource/CoverResource.hpp"
namespace UserInterface {
namespace Desktop {
class PlayQueueItemDelegate;
class TrackSelector;
class PlayQueue : public Wt::WTableView
{
public:
PlayQueue(Database::Handler& db, Wt::WContainerWidget* parent = 0);
void addTracks(const std::vector<Database::Track::id_type>& trackIds);
void getTracks(std::vector<Database::Track::id_type>& trackIds) const;
void clear(void);
void setShuffle(bool enable); // true to enable shuffle
void setLoop(bool enable); // true to enable loop
// Play functions
void play(void); // Play the queue from the beginning
void play(int rowId); // Play the queue from the given rowId
void playNext(void); // Play the next track
void playPrevious(void); // Play the previous track
// List manipulations
void delSelected(void);
void delAll(void);
void moveSelectedUp(void);
void moveSelectedDown(void);
// Signals
Wt::Signal< boost::filesystem::path >& playTrack() { return _sigTrackPlay; }
// Slots
void handlePlaybackComplete(void);
private:
void layoutSizeChanged (int width, int height);
bool readTrack(int rowId);
void setPlayingTrackPos(int newRowPos);
void renumber(int firstId, int lastId);
Wt::Signal< boost::filesystem::path > _sigTrackPlay;
Database::Handler& _db;
Wt::WStandardItemModel* _model;
PlayQueueItemDelegate* _itemDelegate;
CoverResource* _coverResource;
int _curPlayedTrackPos;
std::unique_ptr<TrackSelector> _trackSelector;
};
} // namespace Desktop
} // namespace UserInterface
#endif
+259
View File
@@ -0,0 +1,259 @@
/*
* Copyright (C) 2013 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS 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 LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/foreach.hpp>
#include <Wt/WItemDelegate>
#include "database/Types.hpp"
#include "logger/Logger.hpp"
#include "TableFilter.hpp"
namespace UserInterface {
namespace Desktop {
using namespace Database;
TableFilterGenre::TableFilterGenre(Database::Handler& db, Wt::WContainerWidget* parent)
: Wt::WTableView( parent ), Filter(),
_db(db)
{
const std::vector<Wt::WString> columnNames = {"Genre", "Tracks"};
SearchFilter filter;
Genre::updateGenreQueryModel(_db.getSession(), _queryModel, filter, columnNames);
this->setSelectionMode(Wt::ExtendedSelection);
this->setSortingEnabled(true);
this->setAlternatingRowColors(true);
this->setModel(&_queryModel);
this->setColumnWidth(1, 80);
this->selectionChanged().connect(this, &TableFilterGenre::emitUpdate);
setLayoutSizeAware(true);
_queryModel.setBatchSize(100);
// If an item is double clicked, select and emit signal
this->doubleClicked().connect( std::bind([=] (Wt::WModelIndex idx, Wt::WMouseEvent evt)
{
if (!idx.isValid())
return;
Wt::WModelIndexSet indexSet;
indexSet.insert(idx);
this->setSelectedIndexes( indexSet );
_sigDoubleClicked.emit( );
}, std::placeholders::_1, std::placeholders::_2));
}
void
TableFilterGenre::layoutSizeChanged (int width, int height)
{
std::size_t trackColumnSize = this->columnWidth(1).toPixels();
// Set the remaining size for the name column
this->setColumnWidth(0, width - trackColumnSize - (7 * 2) - 2);
}
// Set constraints on this filter
void
TableFilterGenre::refresh(SearchFilter& filter)
{
Genre::updateGenreQueryModel(_db.getSession(), _queryModel, filter);
}
// Get constraint created by this filter
void
TableFilterGenre::getConstraint(SearchFilter& filter)
{
Wt::WModelIndexSet indexSet = this->selectedIndexes();
BOOST_FOREACH(Wt::WModelIndex index, indexSet) {
if (!index.isValid())
continue;
std::string name = _queryModel.resultRow( index.row() ).get<0>();
filter.exactMatch[Database::SearchFilter::Field::Genre].push_back(name);
}
}
TableFilterArtist::TableFilterArtist(Database::Handler& db, Wt::WContainerWidget* parent)
: Wt::WTableView( parent ), Filter(),
_db(db)
{
const std::vector<Wt::WString> columnNames = {"Artist", "Releases", "Tracks"};
SearchFilter filter;
Track::updateArtistQueryModel(_db.getSession(), _queryModel, filter, columnNames);
this->setSelectionMode(Wt::ExtendedSelection);
this->setSortingEnabled(true);
this->setAlternatingRowColors(true);
this->setModel(&_queryModel);
this->setColumnWidth(1, 80);
this->setColumnWidth(2, 80);
this->selectionChanged().connect(this, &TableFilterArtist::emitUpdate);
setLayoutSizeAware(true);
_queryModel.setBatchSize(100);
// If an item is double clicked, select and emit signal
this->doubleClicked().connect( std::bind([=] (Wt::WModelIndex idx, Wt::WMouseEvent evt)
{
if (!idx.isValid())
return;
Wt::WModelIndexSet indexSet;
indexSet.insert(idx);
this->setSelectedIndexes( indexSet );
_sigDoubleClicked.emit( );
}, std::placeholders::_1, std::placeholders::_2));
}
void
TableFilterArtist::layoutSizeChanged (int width, int height)
{
std::size_t otherColumnsSize = this->columnWidth(1).toPixels() + this->columnWidth(2).toPixels();
// Set the remaining size for the name column
this->setColumnWidth(0, width - otherColumnsSize - (7 * 3) - 2);
}
// Set constraints on this filter
void
TableFilterArtist::refresh(SearchFilter& filter)
{
Track::updateArtistQueryModel(_db.getSession(), _queryModel, filter);
}
// Get constraint created by this filter
void
TableFilterArtist::getConstraint(SearchFilter& filter)
{
Wt::WModelIndexSet indexSet = this->selectedIndexes();
BOOST_FOREACH(Wt::WModelIndex index, indexSet) {
if (!index.isValid())
continue;
std::string name = _queryModel.resultRow( index.row() ).get<0>();
filter.exactMatch[Database::SearchFilter::Field::Artist].push_back(name);
}
}
TableFilterRelease::TableFilterRelease(Database::Handler& db, Wt::WContainerWidget* parent)
: Wt::WTableView( parent ), Filter(),
_db(db)
{
const std::vector<Wt::WString> columnNames = {"Release", "Date", "Tracks"};
SearchFilter filter;
Track::updateReleaseQueryModel(_db.getSession(), _queryModel, filter, columnNames);
this->setSelectionMode(Wt::ExtendedSelection);
this->setSortingEnabled(true);
this->setAlternatingRowColors(true);
this->setModel(&_queryModel);
this->setColumnWidth(1, 60);
this->setColumnWidth(2, 80);
// Date display, just the year
{
Wt::WItemDelegate *delegate = new Wt::WItemDelegate(this);
delegate->setTextFormat("yyyy");
this->setItemDelegateForColumn(1, delegate);
}
this->selectionChanged().connect(this, &TableFilterRelease::emitUpdate);
setLayoutSizeAware(true);
_queryModel.setBatchSize(100);
// If an item is double clicked, select and emit signal
this->doubleClicked().connect( std::bind([=] (Wt::WModelIndex idx, Wt::WMouseEvent evt)
{
if (!idx.isValid())
return;
Wt::WModelIndexSet indexSet;
indexSet.insert(idx);
this->setSelectedIndexes( indexSet );
_sigDoubleClicked.emit( );
}, std::placeholders::_1, std::placeholders::_2));
}
void
TableFilterRelease::layoutSizeChanged (int width, int height)
{
std::size_t otherColumnSizes = this->columnWidth(1).toPixels() + this->columnWidth(2).toPixels();
// Set the remaining size for the name column
this->setColumnWidth(0, width - otherColumnSizes - (7 * 3) - 2);
}
// Set constraints on this filter
void
TableFilterRelease::refresh(SearchFilter& filter)
{
Track::updateReleaseQueryModel(_db.getSession(), _queryModel, filter);
}
// Get constraint created by this filter
void
TableFilterRelease::getConstraint(SearchFilter& filter)
{
Wt::WModelIndexSet indexSet = this->selectedIndexes();
BOOST_FOREACH(Wt::WModelIndex index, indexSet) {
if (!index.isValid())
continue;
std::string name = _queryModel.resultRow( index.row() ).get<0>();
filter.exactMatch[Database::SearchFilter::Field::Release].push_back(name);
}
}
} // namespace Desktop
} // namespace UserInterface
+119
View File
@@ -0,0 +1,119 @@
/*
* Copyright (C) 2013 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS 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 LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef TABLE_FILTER_HPP
#define TABLE_FILTER_HPP
#include <Wt/Dbo/QueryModel>
#include <Wt/WTableView>
#include "Filter.hpp"
#include "database/DatabaseHandler.hpp"
namespace UserInterface {
namespace Desktop {
class TableFilterGenre : public Wt::WTableView, public Filter
{
public:
TableFilterGenre(Database::Handler& db, Wt::WContainerWidget* parent = 0);
// Set constraints on this filter
void refresh(Database::SearchFilter& filter);
// Get constraints created by this filter
void getConstraint(Database::SearchFilter& filter);
void layoutSizeChanged (int width, int height);
typedef Wt::Signal<void> SigDoubleClicked;
SigDoubleClicked& sigDoubleClicked() { return _sigDoubleClicked; }
protected:
SigDoubleClicked _sigDoubleClicked;
Database::Handler& _db;
// Name, track count
Wt::Dbo::QueryModel<Database::Genre::GenreResult> _queryModel;
};
class TableFilterArtist : public Wt::WTableView, public Filter
{
public:
TableFilterArtist(Database::Handler& db, Wt::WContainerWidget* parent = 0);
// Set constraints on this filter
void refresh(Database::SearchFilter& filter);
// Get constraints created by this filter
void getConstraint(Database::SearchFilter& filter);
void layoutSizeChanged (int width, int height);
typedef Wt::Signal<void> SigDoubleClicked;
SigDoubleClicked& sigDoubleClicked() { return _sigDoubleClicked; }
protected:
SigDoubleClicked _sigDoubleClicked;
Database::Handler& _db;
// Name, track count
Wt::Dbo::QueryModel<Database::Track::ArtistResult> _queryModel;
};
class TableFilterRelease : public Wt::WTableView, public Filter
{
public:
TableFilterRelease(Database::Handler& db, Wt::WContainerWidget* parent = 0);
// Set constraints on this filter
void refresh(Database::SearchFilter& filter);
// Get constraints created by this filter
void getConstraint(Database::SearchFilter& filter);
void layoutSizeChanged (int width, int height);
typedef Wt::Signal<void> SigDoubleClicked;
SigDoubleClicked& sigDoubleClicked() { return _sigDoubleClicked; }
protected:
SigDoubleClicked _sigDoubleClicked;
Database::Handler& _db;
// Name, track count
Wt::Dbo::QueryModel<Database::Track::ReleaseResult> _queryModel;
};
} // namespace Desktop
} // namespace UserInterface
#endif
+175
View File
@@ -0,0 +1,175 @@
/*
* Copyright (C) 2013 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS 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 LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/foreach.hpp>
#include <Wt/WItemDelegate>
#include <Wt/WBreak>
#include "logger/Logger.hpp"
#include "TrackView.hpp"
namespace UserInterface {
namespace Desktop {
TrackView::TrackView( Database::Handler& db, Wt::WContainerWidget* parent)
: Wt::WTableView( parent ),
_db(db)
{
static const std::vector<Wt::WString> columnNames =
{
"Artist",
"Album",
"Disc #",
"Track #",
"Track",
"Duration",
"Date",
"Original Date",
"Genres",
};
Database::SearchFilter filter;
Database::Track::updateTracksQueryModel(_db.getSession(), _queryModel, filter, columnNames);
_queryModel.setBatchSize(300);
this->setSortingEnabled(true);
this->setSelectionMode(Wt::ExtendedSelection);
this->setAlternatingRowColors(true);
this->setModel(&_queryModel);
this->setColumnWidth(0, 180); // Artist
this->setColumnWidth(1, 180); // Album
this->setColumnWidth(2, 70); // Disc Number
this->setColumnWidth(3, 70); // Track Number
this->setColumnWidth(4, 180); // Track
this->setColumnWidth(5, 70); // Duration
this->setColumnWidth(6, 70); // Date
this->setColumnWidth(7, 70); // Original Date
this->setColumnWidth(8, 180); // Genres
// this->setOverflow(Wt::WContainerWidget::OverflowScroll, Wt::Vertical);
// Duration display
{
// TODO better handle 1 hour+ files!
Wt::WItemDelegate *delegate = new Wt::WItemDelegate(this);
delegate->setTextFormat("mm:ss");
this->setItemDelegateForColumn(5, delegate);
}
// Date display, just the year
{
Wt::WItemDelegate *delegate = new Wt::WItemDelegate(this);
delegate->setTextFormat("yyyy");
this->setItemDelegateForColumn(6, delegate);
}
{
Wt::WItemDelegate *delegate = new Wt::WItemDelegate(this);
delegate->setTextFormat("yyyy");
this->setItemDelegateForColumn(7, delegate);
}
// If an item is double clicked, select the track and emit signal
this->doubleClicked().connect( std::bind([=] (Wt::WModelIndex idx, Wt::WMouseEvent evt)
{
if (!idx.isValid())
return;
Wt::WModelIndexSet indexSet;
indexSet.insert(idx);
this->setSelectedIndexes( indexSet );
_sigTrackDoubleClicked.emit( );
}, std::placeholders::_1, std::placeholders::_2));
}
// Set constraints created by parent filters
void
TrackView::refresh(Database::SearchFilter& filter)
{
Database::Track::updateTracksQueryModel(_db.getSession(), _queryModel, filter);
}
void
TrackView::getSelectedTracks(std::vector<Database::Track::id_type>& track_ids)
{
LMS_LOG(MOD_UI, SEV_DEBUG) << "Getting selected tracks...";
Wt::WModelIndexSet indexSet = this->selectedIndexes();
BOOST_FOREACH(Wt::WModelIndex index, indexSet)
{
if (!index.isValid())
continue;
Database::Track::pointer track = _queryModel.resultRow( index.row() );
track_ids.push_back(track.id());
}
LMS_LOG(MOD_UI, SEV_DEBUG) << "Getting all selected tracks DONE...";
}
std::size_t
TrackView::getNbSelectedTracks(void)
{
return this->selectedIndexes().size();
}
int
TrackView::getFirstSelectedTrackPosition(void)
{
Wt::WModelIndexSet indexSet = this->selectedIndexes();
BOOST_FOREACH(Wt::WModelIndex index, indexSet)
{
if (!index.isValid())
continue;
return index.row();
}
return 0;
}
void
TrackView::getTracks(std::vector<Database::Track::id_type>& trackIds)
{
LMS_LOG(MOD_UI, SEV_DEBUG) << "Getting all tracks...";
for (int i = 0; i < _queryModel.rowCount(); ++i)
{
Database::Track::pointer track = _queryModel.resultRow(i);
trackIds.push_back(track.id());
}
LMS_LOG(MOD_UI, SEV_DEBUG) << "Getting all tracks done!";
}
} // namespace Desktop
} // namespace UserInterface
+77
View File
@@ -0,0 +1,77 @@
/*
* Copyright (C) 2013 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS 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 LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef TRACK_HPP
#define TRACK_HPP
#include <Wt/WTableView>
#include <Wt/Dbo/QueryModel>
#include "database/DatabaseHandler.hpp"
#include "Filter.hpp"
namespace UserInterface {
namespace Desktop {
class TrackView : public Wt::WTableView, public Filter
{
public:
TrackView( Database::Handler& db, Wt::WContainerWidget* parent = 0);
// Filter interface
// Set constraints created by parent filters
void refresh(Database::SearchFilter& filter);
// Create constraints for child filters (N/A)
void getConstraint(Database::SearchFilter& filter) {}
// Get all the tracks that are currently selected
void getSelectedTracks(std::vector<Database::Track::id_type>& trackIds);
std::size_t getNbSelectedTracks(void);
// Get the first position of the selected tracks (0 if nothing selected)
int getFirstSelectedTrackPosition(void);
// Get all the tracks
void getTracks(std::vector<Database::Track::id_type>& track_ids);
typedef Wt::Signal<void> SigTrackDoubleClicked;
SigTrackDoubleClicked& trackDoubleClicked() { return _sigTrackDoubleClicked; }
private:
SigTrackDoubleClicked _sigTrackDoubleClicked;
Database::Handler& _db;
typedef Database::Track::pointer ResultType;
Wt::Dbo::QueryModel< ResultType > _queryModel;
Wt::WTableView* _tableView;
};
} // namespace Desktop
} // namespace UserInterface
#endif