Favorites draft implementation
authorThomas Perl <m@thp.io>
Wed, 14 Mar 2012 19:44:15 +0000 (20:44 +0100)
committerThomas Perl <m@thp.io>
Wed, 14 Mar 2012 19:44:15 +0000 (20:44 +0100)
gotovienna-qml
gotovienna/defaults.py
qml/MainPage.qml
qml/main.qml

index d2dc8fa..9ebfa55 100755 (executable)
@@ -19,10 +19,13 @@ from gotovienna.gps import *
 from gotovienna.update import *
 from gotovienna.config import config as conf
 
+from gotovienna import defaults
+
 import urllib2
 import os
 import sys
 import threading
+import json
 from datetime import time
 
 class Config(QObject):
@@ -81,6 +84,58 @@ class AboutInfo(QObject):
     def getLicense(self):
         return __license__
 
+class FavoriteManager(QObject):
+    def __init__(self):
+        QObject.__init__(self)
+        self._faves = []
+        if os.path.exists(defaults.favorites_file):
+            try:
+                self._faves = json.load(open(defaults.favorites_file, 'r'))
+                self._faves = map(tuple, self._faves)
+                print 'faves loaded:', self._faves
+            except Exception, e:
+                print 'faves load error:', e
+
+    @Slot(result=int)
+    def getCount(self):
+        result = len(self._faves)
+        print 'getCount->', result
+        return result
+
+    @Slot(int, result=unicode)
+    def getItem(self, index):
+        keys = ['gline', 'gdirection', 'gstation', 'sourceurl', 'isstation']
+        result = dict(zip(keys, self._faves[index]))
+        result['name'] = u'%(gline)s -> %(gdirection)s @ %(gstation)s' % result
+        result = json.dumps(result)
+        print 'getItem:', index, result
+        return result
+
+    def _persist(self):
+        print 'persist:', self._faves, '->', defaults.favorites_file
+        try:
+            fp = open(defaults.favorites_file, 'w')
+            json.dump(self._faves, fp)
+            fp.close()
+        except Exception, e:
+            print 'faves save error:', e
+
+    @Slot(unicode, unicode, unicode, unicode, bool, int, result=bool)
+    def isFavorite(self, gline, gdirection, gstation, sourceurl, isstation, x):
+        k = (gline, gdirection, gstation, sourceurl, isstation)
+        return (k in self._faves)
+
+    @Slot(unicode, unicode, unicode, unicode, bool)
+    def toggleFavorite(self, gline, gdirection, gstation, sourceurl, isstation):
+        k = (gline, gdirection, gstation, sourceurl, isstation)
+        if k in self._faves:
+            self._faves.remove(k)
+        else:
+            self._faves.append(k)
+
+        self._persist()
+
+
 class GotoViennaListModel(QAbstractListModel):
     def __init__(self, objects=None):
         QAbstractListModel.__init__(self)
@@ -91,6 +146,7 @@ class GotoViennaListModel(QAbstractListModel):
 
     def set_objects(self, objects):
         self._objects = objects
+        self.reset()
 
     def get_objects(self):
         return self._objects
@@ -278,11 +334,14 @@ if __name__ == '__main__':
     # instantiate the Python object
     itip = Gui()
 
+    favManager = FavoriteManager()
+
     # expose the object to QML
     context = view.rootContext()
     context.setContextProperty('itip', itip)
     context.setContextProperty('aboutInfo', aboutInfo)
     context.setContextProperty('config', config)
+    context.setContextProperty('favManager', favManager)
 
     if os.path.abspath(__file__).startswith('/usr/bin/'):
         # Assume system-wide installation, QML from /usr/share/
index 9f5df69..051030c 100644 (file)
@@ -19,6 +19,9 @@ cache_stations = path.join(cache_folder, 'stations.json')
 sql_gps_query = 'SELECT name FROM stations WHERE lat > ? and lat < ? and lon > ? and lon < ?'
 sql_file = path.expanduser('~/.gotovienna/stations.db')
 
+# Favorites store
+favorites_file = path.expanduser('~/.gotovienna/favorites.json')
+
 # iTip
 
 line_overview = 'http://www.wienerlinien.at/itip/linienwahl/'
index c6deee0..b3582c7 100644 (file)
@@ -13,6 +13,16 @@ Page {
     //property alias stationSelect: stationSelector
     property variant nearbyStations
 
+    function showFavorites() {
+        favSelector.model.clear();
+        for (var i=0; i<favManager.getCount(); i++) {
+            var data = eval('(' + favManager.getItem(i) + ')');
+            favSelector.model.append(data);
+        }
+        favSelector.model.sync();
+        favSelector.open();
+    }
+
     function search() {
         lineSearchButton.clicked()
     }
@@ -76,6 +86,26 @@ Page {
             }
         }
 
+
+        ToolIcon {
+            property int increaseMeGently: 0
+            anchors {
+                verticalCenter: parent.verticalCenter
+                right: parent.right
+                rightMargin: 10
+            }
+            platformIconId: {
+                if (favManager.isFavorite(realtimeResult.gline, realtimeResult.gdirection, realtimeResult.gstation, realtimeResult.sourceUrl, realtimeResult.isStation, increaseMeGently)) {
+                    'icon-m-toolbar-favorite-mark'
+                } else {
+                    'icon-m-toolbar-favorite-unmark'
+                }
+            }
+            onClicked: {
+                favManager.toggleFavorite(realtimeResult.gline, realtimeResult.gdirection, realtimeResult.gstation, realtimeResult.sourceUrl, realtimeResult.isStation);
+                increaseMeGently = increaseMeGently + 1;
+            }
+        }
     }
 
     PositionSource {
@@ -237,5 +267,21 @@ Page {
 
         sourceUrl: stationSheet.currentUrl
     }
+
+    SelectionDialog {
+        id: favSelector
+        titleText: 'Your favorites'
+
+        model: ListModel {}
+
+        onAccepted: {
+            realtimeResult.isStation = model.get(selectedIndex).isstation
+            realtimeResult.gline = model.get(selectedIndex).gline
+            realtimeResult.gdirection = model.get(selectedIndex).gdirection
+            realtimeResult.sourceUrl = model.get(selectedIndex).sourceurl
+            realtimeResult.gstation = model.get(selectedIndex).gstation
+            realtimeResult.refresh()
+        }
+    }
 }
 
index 5a2a01f..01d0010 100644 (file)
@@ -77,6 +77,10 @@ PageStackWindow {
                 text: 'Nearby stations'
                 onClicked: mainPage.showNearby()
             }
+            MenuItem {
+                text: 'Favorites'
+                onClicked: mainPage.showFavorites()
+            }
             //MenuItem {
             //    text: 'Map'
             //    onClicked: pageStack.push(map)