~ahayzen/music-app/show-toolbar-on-play

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
/*
 * Copyright (C) 2013 Andrew Hayzen <ahayzen@gmail.com>
 *                    Daniel Holm <d.holmen@gmail.com>
 *                    Victor Thompson <victor.thompson@gmail.com>
 *
 * 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; version 3.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import QtQuick 2.0
import Ubuntu.Components 0.1
import Ubuntu.Components.ListItems 0.1
import Ubuntu.Components.Popups 0.1
import Ubuntu.Components.ListItems 0.1 as ListItem
import Ubuntu.Unity.Action 1.0 as UnityActions
import QtPowerd 0.1
import org.nemomobile.grilo 0.1
import QtMultimedia 5.0
import QtQuick.LocalStorage 2.0
import QtQuick.XmlListModel 2.0
import QtGraphicalEffects 1.0
import "settings.js" as Settings
import "meta-database.js" as Library
import "scrobble.js" as Scrobble
import "playlists.js" as Playlists
import "common"

MainView {
    objectName: "music"
    applicationName: "com.ubuntu.music"
    id: mainView

    // Arguments during startup
    Arguments {
        id: args
        //defaultArgument.help: "Expects URI of the track to play." // should be used when bug is resolved
        //defaultArgument.valueNames: ["URI"] // should be used when bug is resolved
        // grab a file
        Argument {
            name: "file"
            help: "URI for track to run at start."
            required: false
            valueNames: ["track"]
        }
        // Debug/development mode
        Argument {
            name: "debug"
            help: "Start Music in a debug mode. Will show more output."
            required: false
        }
    }

    // HUD Actions
    Action {
        id: nextAction
        text: i18n.tr("Next")
        keywords: i18n.tr("Next Track")
        onTriggered: nextSong()
    }
    Action {
        id: playsAction
        text: player.playbackState === MediaPlayer.PlayingState ?
                   i18n.tr("Pause") : i18n.tr("Play")
        keywords: player.playbackState === MediaPlayer.PlayingState ?
                   i18n.tr("Pause Playback") : i18n.tr("Continue or start playback")
        onTriggered: {
            if (player.playbackState === MediaPlayer.PlayingState)  {
                player.pause()
            } else {
                player.play()
            }
        }
    }
    Action {
        id: prevAction
        text: i18n.tr("Previous")
        keywords: i18n.tr("Previous Track")
        onTriggered: previousSong()
    }
    Action {
        id: stopAction
        text: i18n.tr("Stop")
        keywords: i18n.tr("Stop Playback")
        onTriggered: player.stop()
    }
    Action {
        id: backAction
        text: i18n.tr("Back")
        keywords: i18n.tr("Go back to last page")
        onTriggered: musicToolbar.goBack();
    }
    Action {
        id: settingsAction
        text: i18n.tr("Settings")
        keywords: i18n.tr("Music Settings")
        onTriggered: {
            customdebug('Show settings')
            musicSettings.visible = true
        }
    }
    Action {
        id: quitAction
        text: i18n.tr("Quit")
        keywords: i18n.tr("Close application")
        onTriggered: Qt.quit()
    }

    actions: [nextAction, playsAction, prevAction, stopAction, backAction, settingsAction, quitAction]

    // signal to open new URIs
    // TODO currently this only allows playing file:// URIs of known files
    // (already in the database), not e.g. http:// URIs or files in directories
    // not picked up by Grilo
    Connections {
        target: UriHandler
        onOpened: {
            // clear play queue
            trackQueue.model.clear()
            for (var i=0; i < uris.length; i++) {
                console.debug("URI=" + uris[i])
                // skip non-file:// URIs
                if (uris[i].substring(0, 7) !== "file://") {
                    console.debug("Unsupported URI " + uris[i] + ", skipping")
                    continue
                }

                // search pathname in library
                var file = decodeURIComponent(uris[i])
                var index = libraryModel.indexOf(file)
                if (index <= -1) {
                    console.debug("Unknown file " + file + ", skipping")
                    continue
                }

                // enqueue
                trackQueue.model.append(libraryModel.model.get(index))

                // play first URI
                if (i == 0) {
                    trackClicked(trackQueue, 0, true)
                }
            }
        }
    }

    // Design stuff
    Style { id: styleMusic }
    width: units.gu(50)
    height: units.gu(75)

    // RUn on startup
    Component.onCompleted: {
        customdebug("Version "+appVersion) // print the curren version
        customdebug("Arguments on startup: Debug: "+args.values.debug)

        customdebug("Arguments on startup: Debug: "+args.values.debug+ " and file: ")
        if (args.values.file) {
            argFile = args.values.file
            if (argFile.indexOf("file://") != -1) {
                //customdebug("arg contained file://")
                // strip that!
                argFile = argFile.substring(7)
            }
            else {
                // do nothing
                customdebug("arg did not contain file://")
            }
            customdebug(argFile)
        }

        Settings.initialize()
        console.debug("INITIALIZED in tracks")
        if (Settings.getSetting("initialized") !== "true") {
            // initialize settings
            console.debug("reset settings")
            Settings.setSetting("initialized", "true") // setting to make sure the DB is there
            Settings.setSetting("snaptrack", "1") // default state of snaptrack
            Settings.setSetting("shuffle", "0") // default state of shuffle
            Settings.setSetting("repeat", "0") // default state of repeat
            //Settings.setSetting("scrobble", "0") // default state of scrobble
        }
        Library.reset()

        // initialize playlists
        Playlists.initializePlaylists()
        Playlists.initializePlaylist()
        // everything else
        loading.visible = true
        random = Settings.getSetting("shuffle") == "1" // shuffle state
        scrobble = Settings.getSetting("scrobble") == "1" // scrobble state
        lastfmusername = Settings.getSetting("lastfmusername") // lastfm username
        lastfmpassword = Settings.getSetting("lastfmpassword") // lastfm password

        // push the page to view
        pageStack.push(tabs)
    }


    // VARIABLES
    property string musicName: i18n.tr("Music")
    property string appVersion: '1.0'
    property bool isPlaying: false
    property bool random: false
    property bool scrobble: false
    property string lastfmusername
    property string lastfmpassword
    property string timestamp // used to scrobble
    property string argFile // used for argumented track
    property string chosenTrack: ""
    property string chosenTitle: ""
    property string chosenArtist: ""
    property string chosenAlbum: ""
    property string chosenCover: ""
    property string chosenGenre: ""
    property int chosenIndex: 0
    property string currentArtist: ""
    property string currentAlbum: ""
    property string currentTracktitle: ""
    property string currentFile: ""
    property int currentIndex: -1
    property LibraryListModel currentModel: null  // Current model being used
    property var currentQuery: null
    property var currentParam: null
    property string currentCover: ""
    property string currentCoverSmall: currentCover === "" ?
                                           "images/cover_default_icon.png" :
                                            currentCover
    property string currentCoverFull: currentCover !== "" ?
                                          currentCover :
                                          "images/cover_default.png"
    property bool queueChanged: false
    signal onPlayingTrackChange(string source)
    signal onToolbarShownChanged(bool shown, var currentPage, var currentTab)

    // FUNCTIONS

    // Custom debug funtion that's easier to shut off
    function customdebug(text) {
        var debug = true; // set to "0" for not debugging
        //if (args.values.debug) { // *USE LATER*
        if (debug) {
            console.debug(i18n.tr("Debug: ")+text);
        }
    }

    function previousSong(startPlaying) {
        getSong(-1, startPlaying)
    }


    function nextSong(startPlaying) {
        getSong(1, startPlaying)
    }

    function stopSong() {
        currentIndex = -1;
        player.source = "";  // changing to "" triggers the player to stop and removes the highlight
    }

    function getSong(direction, startPlaying) {
        if (trackQueue.model.count == 0)
        {
            customdebug("No tracks in queue.");
            return;
        }

        if (startPlaying === undefined)  // default startPlaying to true
        {
            startPlaying = true;
        }

        if (random) {
            var now = new Date();
            var seed = now.getSeconds();

            // trackQueue must be above 1 otherwise an infinite loop will occur
            do {
                var num = (Math.floor((trackQueue.model.count) * Math.random(seed)));
                console.log(num)
            } while (num == currentIndex && trackQueue.model.count > 1)
            currentIndex = num
            player.source = Qt.resolvedUrl(trackQueue.model.get(num).file)
            console.log("MediaPlayer statusChanged, currentIndex: " + currentIndex)
        } else {
            if ((currentIndex < trackQueue.model.count - 1 && direction === 1 )
                    || (currentIndex > 0 && direction === -1)) {
                console.log("currentIndex: " + currentIndex)
                console.log("trackQueue.count: " + trackQueue.model.count)
                currentIndex += direction
                player.source = Qt.resolvedUrl(trackQueue.model.get(currentIndex).file)
            } else if(direction === 1 && Settings.getSetting("repeat") === "1") {
                console.log("currentIndex: " + currentIndex)
                console.log("trackQueue.count: " + trackQueue.model.count)
                currentIndex = 0
                player.source = Qt.resolvedUrl(trackQueue.model.get(currentIndex).file)
            } else if(direction === -1 && Settings.getSetting("repeat") === "1") {
                console.log("currentIndex: " + currentIndex)
                console.log("trackQueue.count: " + trackQueue.model.count)
                currentIndex = trackQueue.model.count - 1
                player.source = Qt.resolvedUrl(trackQueue.model.get(currentIndex).file)
            }
            else
            {
                player.stop()
                return;
            }

            console.log("MediaPlayer statusChanged, currentIndex: " + currentIndex)
        }
        player.stop()  // Add stop so that if same song is selected it restarts
        console.log("Playing: "+player.source)

        if (startPlaying === true)  // only start the track if told
        {
            player.play()
        }

        timestamp = new Date().getTime(); // contains current date and time in Unix time, used to scrobble
        // scrobble it
        if (Settings.getSetting("scrobble") === "1") {
            Scrobble.now_playing(player.source,timestamp) // send "now playing" to last.fm
        }
        else {
            console.debug("Debug: no scrobbling")
        }
    }

    // Add items from a stored query in libraryModel into the queue
    function addQueueFromModel(libraryModel)
    {
        var items;

        if (libraryModel.query === null)
        {
            return
        }

        if (libraryModel.param === null)
        {
            items = libraryModel.query()
        }
        else
        {
            items = libraryModel.query(libraryModel.param)
        }

        for (var key in items)
        {
            trackQueue.model.append(items[key])
        }
    }

    function trackClicked(libraryModel, index, play)
    {
        if (play === undefined)
        {
            play = true
        }

        if (index > libraryModel.model.count - 1 || index < 0)
        {
            customdebug("Incorrect index given to trackClicked.")
            return;
        }

        var file = libraryModel.model.get(index).file

        console.debug(player.source, Qt.resolvedUrl(file))

        // Clear the play queue and load the new tracks - if not trackQueue
        // Don't reload queue if model, query and parameters are the same
        // Same file different pages is treated as a new session
        if (libraryModel !== trackQueue &&
                (currentModel !== libraryModel ||
                    currentQuery !== libraryModel.query ||
                        currentParam !== libraryModel.param ||
                            queueChanged === true))
        {
                trackQueue.model.clear()
                addQueueFromModel(libraryModel)
        }
        else if (player.source == Qt.resolvedUrl(file))
        {
            if (play === false)
            {
                return
            }

            console.log("Is current track: "+player.playbackState)

            if (player.playbackState == MediaPlayer.PlayingState)
            {
                player.pause()
            }
            else
            {
                player.play()

                // Show the Now Playing page and make sure the track is visible
                nowPlaying.visible = true;
                nowPlaying.ensureVisibleIndex = index;

                musicToolbar.showToolbar();
            }

            return
        }

        // Current index must be updated before player.source
        currentModel = libraryModel
        currentQuery = libraryModel.query
        currentParam = libraryModel.param
        currentIndex = trackQueue.indexOf(file)
        queueChanged = false

        console.log("Click of fileName: " + file)

        if (play === true)
        {
            player.stop()
        }

        player.source = Qt.resolvedUrl(file)

        if (play === true)
        {
            player.play()
        }

        console.log("Source: " + player.source.toString())
        console.log("Index: " + currentIndex)

        if (play === true)
        {
            // Show the Now Playing page and make sure the track is visible
            nowPlaying.visible = true;
            nowPlaying.ensureVisibleIndex = index;

            musicToolbar.showToolbar();
        }

        return file
    }

    function updateMeta()
    {
        // Load metadata for the track
        currentArtist = trackQueue.model.get(currentIndex).artist
        currentAlbum = trackQueue.model.get(currentIndex).album
        currentTracktitle = trackQueue.model.get(currentIndex).title

        // hasCover and currentCover require no file://
        var file = currentFile

        if (file.indexOf("file://") == 0)
        {
            file = file.slice(7, file.length)
        }

        currentCover = trackQueue.model.get(currentIndex).cover !== "" ? trackQueue.model.get(currentIndex).cover : "images/cover_default_icon.png"
    }

    // undo removal function to use when swipe to remove
    function undoRemoval (listmodel,index,title,artist,album,file) {
        // show an undo button instead of removed track
        listmodel.set(index, {"title": i18n.tr("Undo")} )
        // set the removed track in undo listmodel
        undo.set(0, {"artist": artist, "title": title, "album": album, "path": file})
    }

    // WHERE THE MAGIC HAPPENS
    MediaPlayer {
        id: player
        objectName: "player"
        muted: false

        signal positionChange(int position, int duration)

        property bool seeking: false;  // Is the user seeking?

        // String versions of pos/dur that labels listen to
        property string durationStr: "00:00"
        property string positionStr: "00:00"

        onSourceChanged: {
            currentFile = source

            if (source != "" && source != undefined && source !== false)
            {
                onPlayingTrackChange(source)
                updateMeta()
            }
            else
            {
                onPlayingTrackChange(source)  // removes highlight as will get -1 index
                player.stop()
            }
        }

        onStatusChanged: {
            if (status == MediaPlayer.EndOfMedia) {
                // scrobble it
                if (Settings.getSetting("scrobble") === "1") {
                    Scrobble.scrobble(player.source,currentArtist,timestamp)
                }
                else {
                    console.debug("Debug: no scrobbling")
                }

                nextSong() // next track
            }
        }

        // Update the duration text unless seeking (seeking overrides the text)
        onDurationChanged: {
            if (seeking == false)
            {
                durationStr = __durationToString(player.duration)
            }

            positionChange(position, duration)
        }

        // Update the position text unless seeking (seeking overrides the text)
        onPositionChanged: {
            if (seeking == false)
            {
                positionStr = __durationToString(player.position)
            }

            positionChange(position, duration)
        }

        onPlaybackStateChanged: {
          mainView.isPlaying = player.playbackState === MediaPlayer.PlayingState
          QtPowerd.keepAlive = mainView.isPlaying
          console.log("mainView.isPlaying=" + mainView.isPlaying + ", QtPowerd.keepAlive=" + QtPowerd.keepAlive)
        }
    }

    // Model to send the data
    XmlListModel {
        id: scrobblemodel
        query: "/"

        function rpcRequest(request,handler) {
            var http = new XMLHttpRequest()

            http.open("POST",scrobble_url,true)
            http.setRequestHeader("User-Agent", "Music-App/"+appVersion)
            http.setRequestHeader("Content-type", "text/xml")
            http.setRequestHeader("Content-length", request.length)
            if (root.authenticate) {
                http.setRequestHeader("Authorization", "Basic " + Qt.btoa(lastfmusername+":"+lastfmusername))
            }
            http.setRequestHeader("Connection", "close")
            http.onreadystatechange = function() {
                if(http.readyState == 4 && http.status == 200) {
                    console.debug("Debug: XmlRpc::rpcRequest.onreadystatechange()")
                    handler(http.responseText)
                }
            }
            http.send(request)
        }

        function callHandler(response) {
            xml = response
        }

        function call(cmd,params) {
            console.debug("Debug: XmlRpc.call(",cmd,params,")")
            var request = ""
            request += "<?xml version='1.0'?>"
            request += "<methodCall>"
            request += "<methodName>" + cmd + "</methodName>"
            request += "<params>"
            for (var i=0; i<params.length; i++) {
            request += "<param><value>"
            if (typeof(params[i])=="string") {
                request += "<string>" + params[i] + "</string>"
            }
            if (typeof(params[i])=="number") {
                request += "<int>" + params[i] + "</int>"
            }
            request += "</value></param>"
            }
            request += "</params>"
            request += "</methodCall>"
            rpcRequest(request,callHandler)
        }
    }

    GriloModel {
        id: griloModel
        property bool loaded: false

        source: GriloBrowse {
            id: browser
            source: "grl-mediascanner"
            registry: registry
            metadataKeys: [GriloBrowse.Title]
            typeFilter: [GriloBrowse.Audio]
            Component.onCompleted: {
                console.log(browser.supportedKeys);
                console.log(browser.slowKeys);
                refresh();
                console.log("Refreshing");
            }

            onAvailableChanged: {
                console.log("Available ? " + available);
                if (available === true) {
                    console.log("griloModel.count " + griloModel.count)
                }
            }
            onBaseMediaChanged: refresh();

            onFinished: {
                griloModel.loaded = true
            }
        }

        onCountChanged: {
            if (count > 0) {
                timer.start()
                for (var i = timer.counted; i < griloModel.count; i++)
                {
                    var file = griloModel.get(i).url.toString()
                    if (file.indexOf("file://") == 0)
                    {
                        file = file.slice(7, file.length)
                    }
                    //console.log("Artist:"+ griloModel.get(i).artist + ", Album:"+griloModel.get(i).album + ", Title:"+griloModel.get(i).title + ", File:"+file + ", Cover:"+griloModel.get(i).thumbnail + ", Number:"+griloModel.get(i).trackNumber + ", Genre:"+griloModel.get(i).genre);
                    Library.setMetadata(file, griloModel.get(i).title, griloModel.get(i).artist, griloModel.get(i).album, griloModel.get(i).thumbnail, griloModel.get(i).year, griloModel.get(i).trackNumber, griloModel.get(i).duration, griloModel.get(i).genre)
                }
            }

        }
    }

    GriloRegistry {
        id: registry

        Component.onCompleted: {
            console.log("Registry is ready");
            loadAll();
        }
    }

    LibraryListModel {
        id: libraryModel

        onCountChanged: {
            if (argFile === model.get(count - 1).file)
            {
                trackQueue.model.clear();
                trackQueue.model.append(model.get(count - 1));
                trackClicked(trackQueue, 0, true);
            }
        }
    }

    LibraryListModel {
        id: artistModel
    }
    LibraryListModel {
        id: artistTracksModel
    }

    LibraryListModel {
        id: albumModel
    }
    LibraryListModel {
        id: albumTracksModel
    }

    LibraryListModel {
        id: recentAlbumTracksModel
    }

    LibraryListModel {
        id: genreModel
    }

    LibraryListModel {
        id: genreTracksModel
    }

    // list of tracks on startup. This is just during development
    LibraryListModel {
        id: trackQueue
        property bool isEmpty: count == 0

        onIsEmptyChanged: {
            /*
             * If changed to false then must have been empty before
             * Therefore set the first song as the current item
             * and update any metadata
             */
            if (isEmpty === false && currentIndex == -1 && player.source == "")
            {
                currentIndex = 0;
                player.source = trackQueue.model.get(currentIndex).file;
                updateMeta();
            }
        }
    }

    // list of songs, which has been removed.
    ListModel {
        id: removedTrackQueue
    }

    // list of single tracks
    ListModel {
        id: singleTracksgriloMo
    }

    // create the listmodel to use for playlists
    ListModel {
        id: playlistModel
    }

    // create the listmodel for tracks in playlists
    LibraryListModel {
        id: playlisttracksModel
    }

    // ListModel for Undo functionality
    ListModel {
        id: undo
    }

    Timer {
        id: timer
        interval: 200; repeat: true
        running: false
        triggeredOnStart: false
        property int counted: 0

        onTriggered: {
            console.log("Counted: " + counted)
            console.log("griloModel.count: " + griloModel.count)
            if (counted === griloModel.count) {
                console.log("MOVING ON")
                Library.writeDb()
                libraryModel.populate()
                albumModel.filterAlbums()
                artistModel.filterArtists()
                genreModel.filterGenres()
                timer.stop()
                loading.visible = false
            }
            counted = griloModel.count
        }
    }

    // Blurred background
    BlurredBackground {
    }

    LoadingSpinnerComponent {
        id:loading
    }

    // Popover for tracks, queue and add to playlist, for example
    Component {
        id: trackPopoverComponent
        Popover {
            id: trackPopover
            Column {
                id: containerLayout
                anchors {
                    left: parent.left
                    top: parent.top
                    right: parent.right
                }
                ListItem.Standard {
                    Label {
                        text: i18n.tr("Add to queue")
                        color: styleMusic.popover.labelColor
                        fontSize: "large"
                        anchors.horizontalCenter: parent.horizontalCenter
                        anchors.verticalCenter: parent.verticalCenter
                    }
                    onClicked: {
                        console.debug("Debug: Add track to queue: " + chosenTitle)
                        PopupUtils.close(trackPopover)
                        trackQueue.model.append({"title": chosenTitle, "artist": chosenArtist, "file": chosenTrack, "album": chosenAlbum, "cover": chosenCover, "genre": chosenGenre})
                    }
                }
                ListItem.Standard {
                    Label {
                        text: i18n.tr("Add to playlist")
                        color: styleMusic.popover.labelColor
                        fontSize: "large"
                        anchors.horizontalCenter: parent.horizontalCenter
                        anchors.verticalCenter: parent.verticalCenter
                    }
                    onClicked: {
                        console.debug("Debug: Add track to playlist")
                        PopupUtils.close(trackPopover)
                        PopupUtils.open(Qt.resolvedUrl("MusicaddtoPlaylist.qml"), mainView,
                                        {
                                            title: i18n.tr("Select playlist")
                                        } )
                    }
                }
            }
        }
    }

    // New playlist dialog
    Component {
         id: newPlaylistDialog
         Dialog {
             id: dialogueNewPlaylist
             title: i18n.tr("New Playlist")
             text: i18n.tr("Name your playlist.")
             TextField {
                 id: playlistName
                 placeholderText: i18n.tr("Name")
             }
             ListItem.Standard {
                 id: newplaylistoutput
                 visible: false // should only be visible when an error is made.
             }

             Button {
                 text: i18n.tr("Create")
                 onClicked: {
                     newplaylistoutput.visible = false // make sure its hidden now if there was an error last time
                     if (playlistName.text.length > 0) { // make sure something is acually inputed
                         var newList = Playlists.addPlaylist(playlistName.text)
                         if (newList === "OK") {
                             console.debug("Debug: User created a new playlist named: "+playlistName.text)
                             // add the new playlist to the tab
                             var index = Playlists.getID(); // get the latest ID
                             playlistModel.append({"id": index, "name": playlistName.text, "count": "0"})
                             PopupUtils.close(dialogueNewPlaylist)
                         }
                         else {
                             console.debug("Debug: Something went wrong: "+newList)
                             newplaylistoutput.visible = true
                             newplaylistoutput.text = i18n.tr("Error: "+newList)
                         }
                     }
                     else {
                         newplaylistoutput.visible = true
                         newplaylistoutput.text = i18n.tr("Error: You didn't type a name.")
                     }
                }
             }

             Button {
                 text: i18n.tr("Cancel")
                 color: styleMusic.dialog.buttonColor
                 onClicked: PopupUtils.close(dialogueNewPlaylist)
             }
         }
    }

    MusicToolbar {
        id: musicToolbar
        objectName: "musicToolbarObject"
        z: 200  // put on top of everything else

        property bool animating: false
        property bool opened: false
    }

    PageStack {
        id: pageStack
        Tabs {
            id: tabs
            anchors.fill: parent

            // First tab is all music
            Tab {
                id: startTab
                objectName: "starttab"
                anchors.fill: parent
                title: i18n.tr("Music")

                // Tab content begins here
                page: MusicStart {
                    id: musicStartPage
                }
            }

            // Second tab is arists
            Tab {
                id: artistsTab
                objectName: "artiststab"
                anchors.fill: parent
                title: i18n.tr("Artists")

                // tab content
                page: MusicArtists {
                    id: musicArtistsPage
                }
            }

            // third tab is albums
            Tab {
                id: albumsTab
                objectName: "albumstab"
                anchors.fill: parent
                title: i18n.tr("Albums")

                // Tab content begins here
                page: MusicAlbums {
                    id: musicAlbumsPage
                }
            }

            // fourth tab is all songs
            Tab {
                id: tracksTab
                objectName: "trackstab"
                anchors.fill: parent
                title: i18n.tr("Songs")

                // Tab content begins here
                page: MusicTracks {
                    id: musicTracksPage
                }
            }


            // fifth tab is the playlists
            Tab {
                id: playlistTab
                objectName: "playlisttab"
                anchors.fill: parent
                title: i18n.tr("Playlists")

                // Tab content begins here
                page: MusicPlaylists {
                    id: musicPlaylistPage
                }
            }

            function getCurrentTab()
            {
                musicToolbar.currentTab = selectedTab;
            }

            onSelectedTabChanged: {
                getCurrentTab();
            }
        } // end of tabs
    }

    MusicNowPlaying {
        id: nowPlaying
    }

    MusicaddtoPlaylist {
        id: addtoPlaylist
    }

    // Converts an duration in ms to a formated string ("minutes:seconds")
    function __durationToString(duration) {
        var minutes = Math.floor((duration/1000) / 60);
        var seconds = Math.floor((duration/1000)) % 60;
        return minutes + ":" + (seconds<10 ? "0"+seconds : seconds);
    }

    // Overlay to show when no tracks detected on the device
    Rectangle {
        id: libraryEmpty
        anchors.fill: parent
        color: styleMusic.libraryEmpty.backgroundColor
        visible: griloModel.count === 0 && griloModel.loaded === true

        Label {
            anchors.horizontalCenter: parent.horizontalCenter
            anchors.verticalCenter: parent.verticalCenter
            color: styleMusic.libraryEmpty.labelColor
            fontSize: "medium"
            text: "Please import music and restart the app"
        }

    }

} // end of main view