-
Notifications
You must be signed in to change notification settings - Fork 0
/
gotovienna-qml
executable file
·444 lines (356 loc) · 13.8 KB
/
gotovienna-qml
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
#!/usr/bin/env python
"""Public transport information for Vienna"""
__author__ = 'kelvan <[email protected]>'
__version__ = '0.9.3'
__website__ = 'http://tinyurl.com/gotoVienna'
__license__ = 'GNU General Public License v3 or later'
from datetime import datetime
from PySide.QtCore import QAbstractListModel, QModelIndex, QObject, Slot, Signal, Qt, Property
from PySide.QtGui import QApplication, QTextItem, QStringListModel
from PySide.QtDeclarative import QDeclarativeView
from gotovienna.utils import *
from gotovienna.realtime import *
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):
def __init__(self):
QObject.__init__(self)
@Slot(result=bool)
def getGpsEnabled(self):
return conf.getGpsEnabled()
@Slot(bool, result=unicode)
def setGpsEnabled(self, val):
# TODO
return conf.setGpsEnabled(val)
@Slot(result=unicode)
def getLastUpdate(self):
# TODO
return conf.getLastStationsUpdate()
@Slot(result=unicode)
def updateStations(self):
# TODO
try:
update_stations()
return datetime.now().strftime('%c')
except Exception as e:
print e
return ''
@Slot(result=bool)
def checkStationsUpdate(self):
# FIXME exception handling foo
try:
return check_stations_update()
except:
return False
@Slot(result=bool)
def clearCache(self):
print "clear cache"
try:
for root, dirs, files in os.walk(defaults.cache_folder, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))
except:
return False
return True
@Slot(result=bool)
def checkClearedCache(self):
dirlst = os.listdir(defaults.cache_folder)
return bool(dirlst)
class AboutInfo(QObject):
def __init__(self):
QObject.__init__(self)
@Slot(result=unicode)
def getAppName(self):
return u'gotoVienna %s' % __version__
@Slot(result=unicode)
def getWebsiteURL(self):
return __website__
@Slot(result=unicode)
def getCopyright(self):
return 'Copyright 2011, 2012 %s' % __author__
@Slot(result=unicode)
def getLicense(self):
return __license__
class QmlDataModel(QAbstractListModel):
'''Base class for 2d qml datamodels'''
def __init__(self, keys, parent=None):
super(QmlDataModel, self).__init__(parent)
self._data = []
self.keys = {}
i = 1
for key in keys:
self.keys[Qt.UserRole + i] = key
i += 1
self.setRoleNames(self.keys)
def rowCount(self, index):
return len(self._data)
def indexIsValid(self, index, role):
if not index.isValid():
return False
if index.row() > len(self._data):
return False
if self.keys.has_key(role):
return True
else:
return False
def data(self, index, role):
if not self.indexIsValid(index, role):
return None
else:
return self._data[index.row()][role - (Qt.UserRole + 1)]
def setData(self, data):
self.beginResetModel()
self._data = data
self.endResetModel()
class QmlSelectionDialogDataModel(QmlDataModel):
'''Base class for 2d qml datamodels for Seclection Dialogs
contains workaround for fsckd implementation'''
'''qml SelectionDialog requires a property count in order to display stuff
also the callback for a valid selection has no model data avaiable besides
the selected index, so the model has to provide data methods'''
def keyIndex(self, key):
return [k for k, v in self.keys.iteritems() if v == key][0]
def _count(self):
return len(self._data)
@Signal
def count_changed(self): pass
count = Property(int, _count, notify=count_changed)
@Slot(int, unicode, result=unicode)
def getString(self, index, roleString):
print u'{0}: {1}'.format(roleString,self._data[index][self.keyIndex(roleString) - (Qt.UserRole + 1)])
return self._data[index][self.keyIndex(roleString) - (Qt.UserRole + 1)]
@Slot(int, unicode, result=bool)
def getBool(self, index, roleString):
print u'{0}: {1}'.format(roleString,self._data[index][self.keyIndex(roleString) - (Qt.UserRole + 1)])
return self._data[index][self.keyIndex(roleString) - (Qt.UserRole + 1)]
class DepartureModel(QAbstractListModel):
LINE_ROLE = Qt.UserRole + 1
DIRECTION_ROLE = Qt.UserRole + 2
STATION_ROLE = Qt.UserRole + 3
TIME_ROLE = Qt.UserRole + 4
LOWFLOOR_ROLE = Qt.UserRole + 5
def __init__(self, parent=None):
super(DepartureModel, self).__init__(parent)
self._data = []
self.keys = {}
self.keys[DepartureModel.LINE_ROLE] = 'line'
self.keys[DepartureModel.DIRECTION_ROLE] = 'direction'
self.keys[DepartureModel.STATION_ROLE] = 'station'
self.keys[DepartureModel.TIME_ROLE] = 'time'
self.keys[DepartureModel.LOWFLOOR_ROLE] = 'lowfloor'
self.setRoleNames(self.keys)
def rowCount(self, index):
return len(self._data)
def data(self, index, role):
if not index.isValid():
return None
if index.row() > len(self._data):
return None
departure = self._data[index.row()]
if self.keys.has_key(role):
return departure[self.keys[role]]
else:
return None
def setDepartures(self, dep):
self.beginResetModel()
self._data = dep
self.endResetModel()
class FavoriteModel(QmlSelectionDialogDataModel):
def __init__(self, parent=None):
keys = ['line', 'direction', 'station', 'url', 'isStation', 'name']
super(FavoriteModel, self).__init__(keys, parent)
if os.path.exists(defaults.favorites_file):
try:
self._data = json.load(open(defaults.favorites_file, 'r'))
self._data = map(tuple, self._data)
print 'faves loaded:', self._data
except Exception, e:
print 'faves load error:', e
def data(self, index, role):
if self.indexIsValid(index, role):
favorite = self._data[index.row()]
if role == self.keyIndex('name'):
return u'{0} -> {1} @ {2}'.format(favorite[0], favorite[2], favorite[1])
else:
return favorite[role - (Qt.UserRole + 1)]
else:
return None
def _persist(self):
print 'persist:', self._data, '->', defaults.favorites_file
try:
fp = open(defaults.favorites_file, 'w')
json.dump(self._data, 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._data)
@Slot(unicode, unicode, unicode, unicode, bool)
def toggleFavorite(self, gline, gdirection, gstation, sourceurl, isstation):
k = (gline, gdirection, gstation, sourceurl, isstation)
if k in self._data:
self.beginRemoveRows(QModelIndex(), self._data.index(k), self._data.index(k))
self._data.remove(k)
self.endRemoveRows()
else:
self.beginInsertRows(QModelIndex(), len(self._data), len(self._data))
self._data.append(k)
self.endInsertRows()
self._persist()
class Gui(QObject):
def __init__(self, depModel, nearbyModel):
QObject.__init__(self)
self.itip = ITipParser()
self.lines = []
self.departureModel = depModel
self.nearbyModel = nearbyModel
# Read line names in categorized/sorted order
for _, lines in categorize_lines(self.itip.lines):
self.lines.extend(lines)
self.current_line = ''
self.current_stations = []
self.current_departures = []
@Slot(int, result=str)
def get_direction(self, idx):
return self.current_stations[idx][0]
@Slot(str, str, result='QStringList')
def get_stations(self, line, direction):
print 'line:', line, 'current line:', self.current_line
for dx, stations in self.current_stations:
print 'dx:', dx, 'direction:', direction
if dx == direction:
return [stationname for stationname, url in stations]
return ['no stations found']
directionsLoaded = Signal()
@Slot(str)
def load_directions(self, line):
def load_async():
stations = sorted(self.itip.get_stations(line).items())
self.current_line = line
self.current_stations = stations
self.directionsLoaded.emit()
threading.Thread(target=load_async).start()
#def map_departure(self, dep):
# """ prepare departure list for qml gui
# """
# dep['lowfloor'] = 1 if dep['lowfloor'] else 0
# dep['realtime'] = 1 if dep['realtime'] else 0
# dep['time'] = dep['ftime']
# return dep
departuresLoaded = Signal()
@Slot(str)
def load_departures_test(self, **args):
""" valid args combinations
station
line, station
"""
def load_async():
if args.has_key('station'):
if args.has_key('line'):
self.current_departures = map(self.map_departure, \
self.itip.get_departures(args['line'], args['station']))
#print self.current_departures
self.departuresLoaded.emit()
else:
self.current_departures = map(self.map_departure, \
sort_departures(self.itip.get_departures_by_station(station)))
else:
raise KeyError('Missing valid argument combination')
threading.Thread(target=load_async).start()
@Slot(str)
def load_departures(self, url):
def load_async():
self.departureModel.setDepartures(self.itip.get_departures(url))
#print self.current_departures
self.departuresLoaded.emit()
threading.Thread(target=load_async).start()
@Slot(str)
def load_station_departures(self, station):
def load_async():
self.departureModel.setDepartures(sort_departures(self.itip.get_departures_by_station(station)))
self.departuresLoaded.emit()
threading.Thread(target=load_async).start()
@Slot(float, float)
def load_nearby_departures(self, lat, lon):
def load_async():
self.current_departures = []
try:
stations = get_nearby_stations(lat, lon)
for station in stations:
try:
self.current_departures += self.itip.get_departures_by_station(station)
except Exception as e:
print e.message
self.current_departures = map(self.map_departure, \
sort_departures(self.current_departures))
#print self.current_departures
except Exception as e:
print e.message
print 'loaded'
self.departuresLoaded.emit()
threading.Thread(target=load_async).start()
@Slot(str, str, str, result=str)
def get_directions_url(self, line, direction, station):
return self.itip.get_url_from_direction(line, direction, station)
@Slot(result='QStringList')
def get_lines(self):
return self.lines
@Slot(float, float, result='QStringList')
def get_nearby_stations(self, lat, lon):
try:
return get_nearby_stations(lat, lon)
except BaseException as e:
# No/wrong stations.db file
print e.message
return []
@Slot(float, float, result=str)
def load_nearby_stations(self, lat, lon):
self.nearbyModel.setData(get_nearby_stations(lat, lon))
if __name__ == '__main__':
app = QApplication(sys.argv)
view = QDeclarativeView()
aboutInfo = AboutInfo()
config = Config()
departureModel = DepartureModel()
nearbyModel = QmlSelectionDialogDataModel(['name'])
# instantiate the Python object
itip = Gui(departureModel, nearbyModel)
favModel = FavoriteModel()
# expose the object to QML
context = view.rootContext()
context.setContextProperty('itip', itip)
context.setContextProperty('aboutInfo', aboutInfo)
context.setContextProperty('config', config)
context.setContextProperty('resultModel', departureModel)
context.setContextProperty('nearbyModel', nearbyModel)
context.setContextProperty('favModel', favModel)
if os.path.abspath(__file__).startswith('/usr/bin/'):
# Assume system-wide installation, QML from /usr/share/
view.setSource('/usr/share/gotovienna/qml/main.qml')
else:
# Assume test from source directory, use relative path
view.setSource(os.path.join(os.path.dirname(__file__), 'qml/main.qml'))
if '--windowed' in sys.argv:
desktop = app.desktop()
if desktop.height() < 1000:
FACTOR = .8
view.scale(FACTOR, FACTOR)
size = view.size()
size *= FACTOR
view.resize(size)
view.show()
else:
view.showFullScreen()
sys.exit(app.exec_())