aboutsummaryrefslogtreecommitdiff
path: root/src/plugins/Input/flac/flacmetadatamodel.cpp
blob: 9e057a6fdda67b04e8e4e6168a2f841028b57e47 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
/***************************************************************************
 *   Copyright (C) 2009-2012 by Ilya Kotov                                 *
 *   forkotov02@hotmail.ru                                                 *
 *                                                                         *
 *   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 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
 ***************************************************************************/

#include <QPixmap>
#include <taglib/tag.h>
#include <taglib/fileref.h>
#include <taglib/tmap.h>
#include <FLAC/all.h>
#include <qmmp/metadatamanager.h>
#include "flacmetadatamodel.h"

#define QStringToTString_qt4(s) TagLib::String(s.toUtf8().constData(), TagLib::String::UTF8)
#define TStringToQString_qt4(s) QString::fromUtf8(s.toCString(true)).trimmed()

FLACMetaDataModel::FLACMetaDataModel(const QString &path, QObject *parent) : MetaDataModel(parent)
{
    if(path.startsWith("flac://"))
    {
        QString p = path;
        p.remove("flac://");
        p.remove(QRegExp("#\\d+$"));
        m_path = p;
    }
    else
    {
        m_path = path;
        m_tags << new VorbisCommentModel(path);
    }
}

FLACMetaDataModel::~FLACMetaDataModel()
{
    while(!m_tags.isEmpty())
        delete m_tags.takeFirst();
}

QHash<QString, QString> FLACMetaDataModel::audioProperties()
{
    QHash<QString, QString> ap;
    TagLib::FLAC::File *flacFile = 0;
    TagLib::Ogg::FLAC::File *oggFlacFile = 0;
    TagLib::FLAC::Properties *taglib_ap = 0;
    qint64 size = 0;
    if(m_path.endsWith(".flac"))
    {
        flacFile = new TagLib::FLAC::File(m_path.toLocal8Bit().constData());
        taglib_ap = flacFile->audioProperties();
        size = flacFile->length();
    }
    else if(m_path.endsWith(".oga"))
    {
        oggFlacFile = new TagLib::Ogg::FLAC::File(m_path.toLocal8Bit().constData());
        taglib_ap = oggFlacFile->audioProperties();
        size = oggFlacFile->length();
    }
    else
        return ap;

    if(taglib_ap)
    {
        QString text = QString("%1").arg(taglib_ap->length()/60);
        text +=":"+QString("%1").arg(taglib_ap->length()%60,2,10,QChar('0'));
        ap.insert(tr("Length"), text);
        ap.insert(tr("Sample rate"), QString("%1 " + tr("Hz")).arg(taglib_ap->sampleRate()));
        ap.insert(tr("Channels"), QString("%1").arg(taglib_ap->channels()));
        ap.insert(tr("Bitrate"), QString("%1 " + tr("kbps")).arg(taglib_ap->bitrate()));
    }
    ap.insert(tr("File size"), QString("%1 "+tr("KB")).arg(size/1024));
    if(flacFile)
        delete flacFile;
    if(oggFlacFile)
        delete oggFlacFile;
    return ap;
}

QList<TagModel* > FLACMetaDataModel::tags()
{
    return m_tags;
}

QPixmap FLACMetaDataModel::cover()
{
    //embedded cover
    FLAC__StreamMetadata *metadata;
    FLAC__metadata_get_picture (qPrintable(m_path),
                                &metadata,
                                FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER,
                                0,0, -1,-1,-1,-1);
    if(metadata)
    {
        FLAC__StreamMetadata_Picture *pict = &metadata->data.picture;
        QPixmap cover;
        cover.loadFromData(QByteArray((char *)pict->data, (int) pict->data_length));
        FLAC__metadata_object_delete(metadata);
        return cover;
    }
    QString cPath = coverPath();
    return cPath.isEmpty() ? QPixmap() : QPixmap(cPath);
}

QString FLACMetaDataModel::coverPath()
{
    return MetaDataManager::instance()->getCoverPath(m_path);
}

VorbisCommentModel::VorbisCommentModel(const QString &path) : TagModel(TagModel::Save)
{
    m_file = 0;
    m_ogg_file = 0;
    m_tag = 0;
    if(path.endsWith(".flac"))
    {
        m_file = new TagLib::FLAC::File (path.toLocal8Bit().constData());
        m_tag = m_file->xiphComment();
    }
    else if (path.endsWith(".oga"))
    {
        m_ogg_file = new TagLib::Ogg::FLAC::File(path.toLocal8Bit().constData());
        m_tag = m_ogg_file->tag();
    }
}

VorbisCommentModel::~VorbisCommentModel()
{
    if(m_file)
        delete m_file;
    if(m_ogg_file)
        delete m_ogg_file;
}

const QString VorbisCommentModel::name()
{
    return "Vorbis Comment";
}

const QString VorbisCommentModel::value(Qmmp::MetaData key)
{
    if(!m_tag)
        return QString();
    switch((int) key)
    {
    case Qmmp::TITLE:
        return TStringToQString_qt4(m_tag->title());
    case Qmmp::ARTIST:
        return TStringToQString_qt4(m_tag->artist());
    case Qmmp::ALBUM:
        return TStringToQString_qt4(m_tag->album());
    case Qmmp::COMMENT:
        return TStringToQString_qt4(m_tag->comment());
    case Qmmp::GENRE:
        return TStringToQString_qt4(m_tag->genre());
    case Qmmp::COMPOSER:
        if(m_tag->fieldListMap()["COMPOSER"].isEmpty())
            return QString();
        else
            return TStringToQString_qt4(m_tag->fieldListMap()["COMPOSER"].front());
    case Qmmp::YEAR:
        return QString::number(m_tag->year());
    case Qmmp::TRACK:
        return QString::number(m_tag->track());
    case  Qmmp::DISCNUMBER:
        if(m_tag->fieldListMap()["DISCNUMBER"].isEmpty())
            return QString();
        else
            return TStringToQString_qt4(m_tag->fieldListMap()["DISCNUMBER"].front());
    }
    return QString();
}

void VorbisCommentModel::setValue(Qmmp::MetaData key, const QString &value)
{
    if(!m_tag)
        return;

    TagLib::String str = QStringToTString_qt4(value);

    switch((int) key)
    {
    case Qmmp::TITLE:
        m_tag->setTitle(str);
        return;
    case Qmmp::ARTIST:
        m_tag->setArtist(str);
        return;
    case Qmmp::ALBUM:
        m_tag->setAlbum(str);
        return;
    case Qmmp::COMMENT:
        m_tag->setComment(str);
        return;
    case Qmmp::GENRE:
        m_tag->setGenre(str);
        return;
    case Qmmp::COMPOSER:
        value.isEmpty() ?
        m_tag->removeField("COMPOSER"):
        m_tag->addField("COMPOSER", str, true);
        return;
    case Qmmp::TRACK:
        m_tag->setTrack(value.toInt());
        return;
    case Qmmp::YEAR:
        m_tag->setYear(value.toInt());
        return;
    case Qmmp::DISCNUMBER:
        value == "0" ?
        m_tag->removeField("DISCNUMBER"):
        m_tag->addField("DISCNUMBER", str, true);
    }
}

void VorbisCommentModel::save()
{
    if(m_file)
        m_file->save();
    else if(m_ogg_file)
        m_ogg_file->save();
}
lass='alt'>
87b310fbe

245027ffc



87b310fbe
0bc5775ba
245027ffc
0bc5775ba

bd16af99a

c532681be
87b310fbe




fc03804ef

d29d9953f
87b310fbe



fc03804ef



d29d9953f
87b310fbe



463f4e95c
1e31fe896
87b310fbe










fc03804ef































7ef8d11ba







fc03804ef
















87b310fbe

d29d9953f
87b310fbe
463f4e95c
87b310fbe
1e31fe896
87b310fbe


845322411
87b310fbe









bd16af99a

0bc5775ba




d29d9953f


0bc5775ba

87b310fbe
1b61b0b61
0bc5775ba
0bc5775ba




c532681be
0bc5775ba

c532681be




0bc5775ba



87b310fbe

1b61b0b61
87b310fbe


















0bc5775ba

87b310fbe
0bc5775ba
87b310fbe
0bc5775ba












6bdb7ebea


87b310fbe
0bc5775ba




87b310fbe
0bc5775ba








0bc5775ba














eb74cc322
0bc5775ba

eb74cc322


0bc5775ba
eb74cc322
0bc5775ba

5ab256d56











1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
                                                                            
                                                                            
                                                                            













                                                                            
                                                                            





                                                                             
                             
                                


                      
                

                           
                
                    


                                   
                             
                            

                         

                                                 
 
                        


                                            
                             
             

                                                                      
                   

                                                                         


                                                        
                                                       


                                                                        
                   





                                                                                                






                                                                           
                                                         



                                                                          





                                                                                                  
                                             
 
                              
 





                                                                                               

                                                         











                                                                                         


                                                                                                                  

                        
                                

                                    

                           
                
                                                                 
                                      
                                       

                                      
                                                                    



                                          



                                                                                                                  
                                      




                                                                                                   
                                    

                                                                                                         
                                           

 
                             
  


                                                 
                                           

                                                 
                                                
                                                                       
                                 




                               
                                 
                                       







                                                       
                                                                                              
                                          

                                                



                                             
                                  
                                            
     
                                                                                                    
                                                         

                                                                                  




                                                                                                       



         
                                                                                                  
                                                         

                                                                                



                                                                                                     
         
     
                                             

 

                                                                     
                                                     




                                                       

                                                                                 
                                                                              



                                                       



                                                                                   
                                                                                  



                                   
                                                                                              
                                                     










                                                                              































                                                                                                







                                                                                     
















                                                                                                                          

                                        
                                            
               
                                                                                                
                              
                                                     


                                                                                
                                                                   









                                                            

 




                                                                 


                                                                                                      

                        
                             
                                                                 
                                    




                                          
                                                       

                                          




                                                                                            



                                 

                    
                                                                    


















                                                                                               

 
                                                                       
 
                                            












                                                                             


                                                                              
                                                          




                                                                             
                                                                          








                                                                  














                                                           
 

                                                                                    


                                                                                                          
                                                                                                       
      

     











                                                                        
/***************************************************************************
 *   Copyright (C) 2012-2021 by Ilya Kotov                                 *
 *   forkotov02@ya.ru                                                      *
 *                                                                         *
 *   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 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
 ***************************************************************************/

#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkProxy>
#include <QUrl>
#include <QStandardItemModel>
#include <QSortFilterProxyModel>
#include <QSettings>
#include <QDir>
#include <QMessageBox>
#include <QMenu>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
#include <QIcon>
#include <algorithm>
#include <qmmp/qmmpsettings.h>
#include <qmmp/qmmp.h>
#include <qmmpui/playlistmanager.h>
#include "editstreamdialog.h"
#include "ui_streamwindow.h"
#include "streamwindow.h"

StreamWindow::StreamWindow(QWidget *parent)
    : QWidget(parent), m_ui(new Ui::StreamWindow)
{
    m_ui->setupUi(this);
    setWindowFlags(Qt::Window);
    setAttribute(Qt::WA_DeleteOnClose);
    setAttribute(Qt::WA_QuitOnClose, false);
    m_requestReply = nullptr;
    //buttons
    m_ui->addPushButton->setIcon(QIcon::fromTheme("list-add"));
    m_ui->updatePushButton->setIcon(QIcon::fromTheme("view-refresh"));
    //icecast model
    m_iceCastModel = new QStandardItemModel(this);
    m_iceCastModel->setHorizontalHeaderLabels(QStringList() << tr("Name")
                                       << tr("Genre")
                                       << tr("Bitrate")
                                       << tr("Format"));
    m_iceCastFilterModel = new StreamsProxyModel(this);
    m_iceCastFilterModel->setSourceModel(m_iceCastModel);
    m_iceCastFilterModel->setDynamicSortFilter(true);
    m_iceCastFilterModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
    //icecast table
    m_ui->icecastTableView->setModel(m_iceCastFilterModel);
    m_ui->icecastTableView->verticalHeader()->setDefaultSectionSize(fontMetrics().height() + 3);
    m_ui->icecastTableView->verticalHeader()->setSectionResizeMode(QHeaderView::Fixed);
    m_ui->icecastTableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    m_ui->icecastTableView->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(m_ui->icecastTableView, SIGNAL(customContextMenuRequested(QPoint)),
            SLOT(execIceCastMenu(QPoint)));
    //favorites model
    m_favoritesModel = new QStandardItemModel(this);
    m_favoritesModel->setHorizontalHeaderLabels(QStringList() << tr("Name")
                                                     << tr("Genre")
                                                     << tr("Bitrate")
                                                     << tr("Format"));
    m_favoritesFilterModel = new StreamsProxyModel(this);
    m_favoritesFilterModel->setSourceModel(m_favoritesModel);
    m_favoritesFilterModel->setDynamicSortFilter(true);
    m_favoritesFilterModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
    //favorites table
    m_ui->favoritesTableView->setModel(m_favoritesFilterModel);
    m_ui->favoritesTableView->verticalHeader()->setDefaultSectionSize(fontMetrics().height() + 3);
    m_ui->favoritesTableView->verticalHeader()->setSectionResizeMode(QHeaderView::Fixed);
    m_ui->favoritesTableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    m_ui->favoritesTableView->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(m_ui->favoritesTableView, SIGNAL(customContextMenuRequested(QPoint)),
            SLOT(execFavoritesMenu(QPoint)));

    m_ui->statusLabel->hide();

    m_http = new QNetworkAccessManager(this);
     //load global proxy settings
    QmmpSettings *gs = QmmpSettings::instance();
    if (gs->isProxyEnabled())
    {
        QNetworkProxy proxy(QNetworkProxy::HttpProxy, gs->proxy().host(),  gs->proxy().port());
        if(gs->proxyType() == QmmpSettings::SOCKS5_PROXY)
            proxy.setType(QNetworkProxy::Socks5Proxy);
        if(gs->useProxyAuth())
        {
            proxy.setUser(gs->proxy().userName());
            proxy.setPassword(gs->proxy().password());
        }
        m_http->setProxy(proxy);
    }
    connect(m_http, SIGNAL(finished (QNetworkReply *)), SLOT(showText(QNetworkReply *)));
    //read settings
    QSettings settings(Qmmp::configFile(), QSettings::IniFormat);
    settings.beginGroup("StreamBrowser");
    restoreGeometry(settings.value("geometry").toByteArray());
    m_ui->icecastTableView->horizontalHeader()->restoreState(settings.value("icecast_headers").toByteArray());
    m_ui->favoritesTableView->horizontalHeader()->restoreState(settings.value("favorites_headers").toByteArray());
    m_ui->tabWidget->setCurrentIndex(settings.value("current_tab", 1).toInt());
    settings.endGroup();
    //create cache dir
    QDir dir(Qmmp::configDir());
    if(!dir.exists("streambrowser"))
        dir.mkdir("streambrowser");
    //create initial config
    createInitialConfig();
    //read cache
    QFile file(Qmmp::configDir() + "/streambrowser/icecast.xml");
    if(file.open(QIODevice::ReadOnly))
        readXml(&file, m_iceCastModel);
    else
        on_updatePushButton_clicked();
    QFile file2(Qmmp::configDir() + "/streambrowser/favorites.xml");
    if(file2.open(QIODevice::ReadOnly))
        readXml(&file2, m_favoritesModel);
    //create menus
    m_iceCastMenu = new QMenu(this);
    m_addToFavoritesAction = m_iceCastMenu->addAction(QIcon::fromTheme("user-bookmarks"), tr("&Add to favorites"),
                                                      this, SLOT(addToFavorites()));
    m_addAction = m_iceCastMenu->addAction(QIcon::fromTheme("list-add"),
                                           tr("&Add to playlist"), this, SLOT(on_addPushButton_clicked()));
    m_favoritesMenu = new QMenu(this);
    m_favoritesMenu->addAction(m_addAction);
    m_favoritesMenu->addAction(QIcon::fromTheme("document-new"), tr("&Create"),
                               this, SLOT(createStream()));
    m_editAction = m_favoritesMenu->addAction(QIcon::fromTheme("document-properties"), tr("&Edit"),
                                              this, SLOT(editStream()));
    m_favoritesMenu->addSeparator();
    m_removeAction = m_favoritesMenu->addAction(QIcon::fromTheme("edit-delete"), tr("&Remove"),
                                                this, SLOT(removeFromFavorites()), QKeySequence::Delete);
    addActions(m_favoritesMenu->actions());
}

StreamWindow::~StreamWindow()
{}

void StreamWindow::showText(QNetworkReply *reply)
{
    m_ui->statusLabel->setText(tr("Done"));
    if (reply->error() != QNetworkReply::NoError)
    {
        m_ui->statusLabel->setText(tr("Error"));
        QMessageBox::warning (this, tr("Error"), reply->errorString());
        m_requestReply = nullptr;
        reply->deleteLater();
        return;
    }
    if(m_requestReply == reply)
    {
        m_requestReply = nullptr;
        readXml(reply, m_iceCastModel);
    }
    reply->deleteLater();
}

void StreamWindow::on_updatePushButton_clicked()
{
    QNetworkRequest request;
    request.setUrl(QUrl("http://dir.xiph.org/yp.xml"));
    request.setRawHeader("User-Agent", QString("qmmp/%1").arg(Qmmp::strVersion()).toLatin1());
    m_requestReply = m_http->get(request);
    m_ui->statusLabel->setText(tr("Receiving"));
    m_ui->statusLabel->show();
}

void StreamWindow::on_addPushButton_clicked()
{
    QList<PlayListTrack *> tracks;
    if(m_ui->tabWidget->currentIndex() == 0)
    {
        const QModelIndexList indexes = m_ui->favoritesTableView->selectionModel()->selectedRows(0);
        for(const QModelIndex &index : qAsConst(indexes))
        {
            QModelIndex source_index = m_favoritesFilterModel->mapToSource(index);
            tracks << new PlayListTrack();
            tracks.last()->setPath(m_favoritesModel->item(source_index.row(),0)->data().toString());
            tracks.last()->setValue(Qmmp::TITLE, m_favoritesModel->item(source_index.row(),0)->text());
            tracks.last()->setValue(Qmmp::GENRE, m_favoritesModel->item(source_index.row(),1)->text());

        }
    }
    else
    {
        const QModelIndexList indexes = m_ui->icecastTableView->selectionModel()->selectedRows(0);
        for(const QModelIndex &index : qAsConst(indexes))
        {
            QModelIndex source_index = m_iceCastFilterModel->mapToSource(index);
            tracks << new PlayListTrack();
            tracks.last()->setPath(m_iceCastModel->item(source_index.row(),0)->data().toString());
            tracks.last()->setValue(Qmmp::TITLE, m_iceCastModel->item(source_index.row(),0)->text());
            tracks.last()->setValue(Qmmp::GENRE, m_iceCastModel->item(source_index.row(),1)->text());
        }
    }
    PlayListManager::instance()->add(tracks);
}

void StreamWindow::on_filterLineEdit_textChanged(const QString &text)
{
    m_iceCastFilterModel->setFilterFixedString(text);
    m_favoritesFilterModel->setFilterFixedString(text);
}

void StreamWindow::execIceCastMenu(const QPoint &pos)
{
    QModelIndex index = m_ui->icecastTableView->selectionModel()->currentIndex();
    m_addToFavoritesAction->setEnabled(index.isValid());
    m_iceCastMenu->exec(m_ui->icecastTableView->viewport()->mapToGlobal(pos));
}

void StreamWindow::execFavoritesMenu(const QPoint &pos)
{
    QModelIndex index = m_ui->favoritesTableView->selectionModel()->currentIndex();
    m_addAction->setEnabled(index.isValid());
    m_editAction->setEnabled(index.isValid());
    m_removeAction->setEnabled(index.isValid());
    m_favoritesMenu->exec(m_ui->favoritesTableView->viewport()->mapToGlobal(pos));
}

void StreamWindow::addToFavorites()
{
    const QModelIndexList indexes = m_ui->icecastTableView->selectionModel()->selectedRows(0);
    for(const QModelIndex &index : qAsConst(indexes))
    {
        QModelIndex source_index = m_iceCastFilterModel->mapToSource(index);
        int row = source_index.row();
        m_favoritesModel->appendRow(QList<QStandardItem *> ()
                                    << m_iceCastModel->item(row, 0)->clone()
                                    << m_iceCastModel->item(row, 1)->clone()
                                    << m_iceCastModel->item(row, 2)->clone()
                                    << m_iceCastModel->item(row, 3)->clone());
    }
}

void StreamWindow::createStream()
{
    EditStreamDialog dialog(this);
    if(dialog.exec() == QDialog::Accepted)
    {
         QMap<EditStreamDialog::Key, QString> values = dialog.values();

        if(values[EditStreamDialog::NAME].isEmpty())
            values[EditStreamDialog::NAME] = values[EditStreamDialog::URL].section("/", -1);

        m_favoritesModel->appendRow(QList<QStandardItem *> ()
                                  << new QStandardItem(values[EditStreamDialog::NAME])
                                  << new QStandardItem(values[EditStreamDialog::GENRE])
                                  << new QStandardItem(values[EditStreamDialog::BITRATE])
                                  << new QStandardItem(values[EditStreamDialog::TYPE]));

        QStandardItem *item = m_favoritesModel->item(m_favoritesModel->rowCount()-1, 0);
        item->setToolTip(values[EditStreamDialog::NAME] + "\n" + values[EditStreamDialog::URL]);
        item->setData(values[EditStreamDialog::URL]);
    }
}

void StreamWindow::editStream()
{
    QModelIndex index = m_ui->favoritesTableView->selectionModel()->currentIndex();
    if(!index.isValid())
        return;

    int row = m_favoritesFilterModel->mapToSource(index).row();

    EditStreamDialog dialog(this);
    dialog.setWindowTitle(tr("Edit Stream"));
    QMap<EditStreamDialog::Key, QString> initialValues = {
        { EditStreamDialog::URL, m_favoritesModel->item(row, 0)->data().toString() },
        { EditStreamDialog::NAME, m_favoritesModel->item(row, 0)->text() },
        { EditStreamDialog::GENRE, m_favoritesModel->item(row, 1)->text() },
        { EditStreamDialog::BITRATE, m_favoritesModel->item(row, 2)->text() },
        { EditStreamDialog::TYPE, m_favoritesModel->item(row, 3)->text() }
    };
    dialog.setValues(initialValues);

    if(dialog.exec() == QDialog::Accepted)
    {
        QMap<EditStreamDialog::Key, QString> values = dialog.values();

        if(values[EditStreamDialog::NAME].isEmpty())
            values[EditStreamDialog::NAME] = values[EditStreamDialog::URL].section("/", -1);

        m_favoritesModel->item(row, 0)->setData(values[EditStreamDialog::URL]);
        m_favoritesModel->item(row, 0)->setText(values[EditStreamDialog::NAME]);
        m_favoritesModel->item(row, 1)->setText(values[EditStreamDialog::GENRE]);
        m_favoritesModel->item(row, 2)->setText(values[EditStreamDialog::BITRATE]);
        m_favoritesModel->item(row, 3)->setText(values[EditStreamDialog::TYPE]);
        m_favoritesModel->item(row, 0)->setToolTip(values[EditStreamDialog::NAME] + "\n" + values[EditStreamDialog::URL]);
    }
}

void StreamWindow::removeFromFavorites()
{
    if(m_ui->tabWidget->currentIndex() != 0)
        return;
    const QModelIndexList indexes = m_ui->favoritesTableView->selectionModel()->selectedRows(0);
    QList<int> rows_to_remove;
    for(const QModelIndex &index : qAsConst(indexes))
    {
        rows_to_remove.append(m_favoritesFilterModel->mapToSource(index).row());
    }
    std::stable_sort(rows_to_remove.begin(), rows_to_remove.end());
    int prev_row = -1;
    for(int i = rows_to_remove.count() - 1; i >= 0; i -= 1 )
    {
        int current = rows_to_remove[i];
        if(current != prev_row)
        {
            m_favoritesFilterModel->removeRows(current, 1);
            prev_row = current;
        }
    }
}

void StreamWindow::closeEvent(QCloseEvent *)
{
    QSettings settings(Qmmp::configFile(), QSettings::IniFormat);
    settings.beginGroup("StreamBrowser");
    settings.setValue("geometry", saveGeometry());
    settings.setValue("icecast_headers", m_ui->icecastTableView->horizontalHeader()->saveState());
    settings.setValue("favorites_headers", m_ui->favoritesTableView->horizontalHeader()->saveState());
    settings.setValue("current_tab", m_ui->tabWidget->currentIndex());
    settings.endGroup();

     //save icecast directory
    QFile file(Qmmp::configDir() + "/streambrowser/icecast.xml");
    file.open(QIODevice::WriteOnly);
    QXmlStreamWriter writer(&file);
    writer.setCodec("UTF-8");
    writer.setAutoFormatting(true);
    writer.writeStartDocument();
    writer.writeStartElement("directory");
    for(int i = 0; i < m_iceCastModel->rowCount(); ++i)
    {
        writer.writeStartElement("entry");
        writer.writeTextElement("server_name", m_iceCastModel->item(i,0)->text());
        writer.writeTextElement("listen_url", m_iceCastModel->item(i,0)->data().toString());
        writer.writeTextElement("genre", m_iceCastModel->item(i,1)->text());
        writer.writeTextElement("bitrate", m_iceCastModel->item(i,2)->text());
        writer.writeTextElement("server_type", m_iceCastModel->item(i,3)->text());
        writer.writeEndElement();
    }
    writer.writeEndElement();
    writer.writeEndDocument();
    file.close();
    //save favorites
    QFile file2(Qmmp::configDir() + "/streambrowser/favorites.xml");
    file2.open(QIODevice::WriteOnly);
    QXmlStreamWriter writer2(&file2);
    writer2.setCodec("UTF-8");
    writer2.setAutoFormatting(true);
    writer2.writeStartDocument();
    writer2.writeStartElement("directory");
    for(int i = 0; i < m_favoritesModel->rowCount(); ++i)
    {
        writer2.writeStartElement("entry");
        writer2.writeTextElement("server_name", m_favoritesModel->item(i,0)->text());
        writer2.writeTextElement("listen_url", m_favoritesModel->item(i,0)->data().toString());
        writer2.writeTextElement("genre", m_favoritesModel->item(i,1)->text());
        writer2.writeTextElement("bitrate", m_favoritesModel->item(i,2)->text());
        writer2.writeTextElement("server_type", m_favoritesModel->item(i,3)->text());
        writer2.writeEndElement();
    }
    writer2.writeEndElement();
    writer2.writeEndDocument();
    file2.close();
}

void StreamWindow::readXml(QIODevice *input, QStandardItemModel *model)
{
    model->removeRows(0, model->rowCount());
    QXmlStreamReader xml(input);
    QString currentTag, server_name, listen_url, genre, bitrate, server_type;
    while (!xml.atEnd())
    {
        xml.readNext();
        if (xml.isStartElement())
        {
            currentTag = xml.name().toString();
        }
        else if (xml.isEndElement())
        {
            if (xml.name() == "entry")
            {
                if(server_name == "Unspecified name" || server_name.isEmpty())
                    server_name = listen_url.section("/", -1);

                model->appendRow(QList<QStandardItem *> ()
                                          << new QStandardItem(server_name)
                                          << new QStandardItem(genre)
                                          << new QStandardItem(bitrate)
                                          << new QStandardItem(server_type));

                QStandardItem *item = model->item(model->rowCount()-1, 0);
                item->setToolTip(server_name + "\n" + listen_url);
                item->setData(listen_url);

                server_name.clear();
                listen_url.clear();
                genre.clear();
                bitrate.clear();
                server_type.clear();
            }
        }
        else if (xml.isCharacters() && !xml.isWhitespace())
        {
            if (currentTag == "server_name")
                server_name += xml.text().toString();
            else if (currentTag == "listen_url")
                listen_url += xml.text().toString();
            else if (currentTag == "genre")
                genre += xml.text().toString();
            else if (currentTag == "bitrate")
                bitrate += xml.text().toString();
            else if(currentTag == "server_type")
                server_type += xml.text().toString();
        }
    }

    if (xml.error() && xml.error() != QXmlStreamReader::PrematureEndOfDocumentError)
    {
#ifdef Q_OS_WIN
        qWarning("StreamWindow: xml error: %d: %s", (int)xml.lineNumber(), qPrintable(xml.errorString()));
#else
        qWarning("StreamWindow: xml error: %lld: %s", xml.lineNumber(), qPrintable(xml.errorString()));
#endif
    }
}

void StreamWindow::createInitialConfig()
{
    QString config = Qmmp::configDir() + "/streambrowser/favorites.xml";
    QString defaultConfig = Qmmp::dataPath() + "/favorites.xml.default";

    if(!QFile::exists(config) && QFile::exists(defaultConfig))
    {
        qDebug("StreamWindow: creating initial config");
        QFile::copy(defaultConfig, config);
    }
}