/
__init__.py
1129 lines (887 loc) · 37.9 KB
/
__init__.py
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
997
998
999
1000
# -*- coding: utf-8 -*-
#
# gPodder - A media aggregator and podcast client
# Copyright (c) 2005-2012 Thomas Perl and the gPodder Team
#
# gPodder is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# gPodder 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/>.
#
# gpodder.qmlui - gPodder's QML interface
# Thomas Perl <thp@gpodder.org>; 2011-02-06
from PySide.QtGui import QApplication
from PySide.QtCore import Qt, QObject, Signal, Slot, Property, QUrl
from PySide.QtCore import QAbstractListModel, QModelIndex
from PySide.QtDeclarative import QDeclarativeView
import os
import signal
import functools
import subprocess
import dbus
import dbus.service
from dbus.mainloop.glib import DBusGMainLoop
import gpodder
_ = gpodder.gettext
N_ = gpodder.ngettext
from gpodder import core
from gpodder import util
from gpodder import my
from gpodder import query
from gpodder.model import Model
from gpodder.qmlui import model
from gpodder.qmlui import helper
from gpodder.qmlui import images
import logging
logger = logging.getLogger("qmlui")
EPISODE_LIST_FILTERS = [
# (UI label, EQL expression)
(_('All'), None),
(_('Hide deleted'), 'not deleted'),
(_('New'), 'new or downloading'),
(_('Downloaded'), 'downloaded or downloading'),
(_('Deleted'), 'deleted'),
(_('Finished'), 'finished'),
(_('Archived'), 'downloaded and archive'),
(_('Videos'), 'video'),
]
class ConfigProxy(QObject):
def __init__(self, config):
QObject.__init__(self)
self._config = config
config.add_observer(self._on_config_changed)
def _on_config_changed(self, name, old_value, new_value):
if name == 'ui.qml.autorotate':
self.autorotateChanged.emit()
elif name == 'flattr.token':
self.flattrTokenChanged.emit()
elif name == 'flattr.flattr_on_play':
self.flattrOnPlayChanged.emit()
def get_autorotate(self):
return self._config.ui.qml.autorotate
def set_autorotate(self, autorotate):
self._config.ui.qml.autorotate = autorotate
autorotateChanged = Signal()
autorotate = Property(bool, get_autorotate, set_autorotate,
notify=autorotateChanged)
def get_flattr_token(self):
return self._config.flattr.token
def set_flattr_token(self, flattr_token):
self._config.flattr.token = flattr_token
flattrTokenChanged = Signal()
flattrToken = Property(unicode, get_flattr_token, set_flattr_token,
notify=flattrTokenChanged)
def get_flattr_on_play(self):
return self._config.flattr.flattr_on_play
def set_flattr_on_play(self, flattr_on_play):
self._config.flattr.flattr_on_play = flattr_on_play
flattrOnPlayChanged = Signal()
flattrOnPlay = Property(bool, get_flattr_on_play, set_flattr_on_play,
notify=flattrOnPlayChanged)
class Controller(QObject):
def __init__(self, root):
QObject.__init__(self)
self.root = root
self.context_menu_actions = []
self.episode_list_title = u''
self.current_input_dialog = None
self.root.config.add_observer(self.on_config_changed)
self._flattr = self.root.core.flattr
self.flattr_button_text = u''
def on_config_changed(self, name, old_value, new_value):
logger.info('Config changed: %s (%s -> %s)', name,
old_value, new_value)
if name == 'mygpo.enabled':
self.myGpoEnabledChanged.emit()
elif name == 'mygpo.username':
self.myGpoUsernameChanged.emit()
elif name == 'mygpo.password':
self.myGpoPasswordChanged.emit()
elif name == 'mygpo.device.caption':
self.myGpoDeviceCaptionChanged.emit()
episodeListTitleChanged = Signal()
def setEpisodeListTitle(self, title):
if self.episode_list_title != title:
self.episode_list_title = title
self.episodeListTitleChanged.emit()
def getEpisodeListTitle(self):
return self.episode_list_title
episodeListTitle = Property(unicode, getEpisodeListTitle, \
setEpisodeListTitle, notify=episodeListTitleChanged)
flattrButtonTextChanged = Signal()
def setFlattrButtonText(self, flattr_button_text):
if self.flattr_button_text != flattr_button_text:
self.flattr_button_text = flattr_button_text
self.flattrButtonTextChanged.emit()
def getFlattrButtonText(self):
return self.flattr_button_text
flattrButtonText = Property(unicode, getFlattrButtonText,
setFlattrButtonText, notify=flattrButtonTextChanged)
@Slot(QObject)
def onPlayback(self, qepisode):
if (qepisode.payment_url and self.root.config.flattr.token and
self.root.config.flattr.flattr_on_play):
success, message = self._flattr.flattr_url(qepisode.payment_url)
if not success:
logger.warn('Flattr message on playback action: %s', message)
@Slot(QObject)
def updateFlattrButtonText(self, qepisode):
self.setFlattrButtonText('')
if qepisode is None:
return
episode = qepisode._episode
if not episode.payment_url:
return
if not self._flattr.has_token():
self.setFlattrButtonText(_('Sign in'))
return
@util.run_in_background
def get_flattr_info():
flattrs, flattred = self._flattr.get_thing_info(episode.payment_url)
if flattred:
self.setFlattrButtonText(_('Flattred (%(count)d)') % {
'count': flattrs
})
else:
self.setFlattrButtonText(_('Flattr this (%(count)d)') % {
'count': flattrs
})
@Slot(QObject)
def flattrEpisode(self, qepisode):
if not qepisode:
return
episode = qepisode._episode
if not episode.payment_url:
return
if not self._flattr.has_token():
self.root.show_message(_('Sign in to Flattr in the settings.'))
return
self.root.start_progress(_('Flattring episode...'))
@util.run_in_background
def flattr_episode():
try:
success, message = self._flattr.flattr_url(episode.payment_url)
if success:
self.updateFlattrButtonText(qepisode)
else:
self.root.show_message(message)
finally:
self.root.end_progress()
@Slot(result=str)
def getFlattrLoginURL(self):
return self._flattr.get_auth_url()
@Slot(result=str)
def getFlattrCallbackURL(self):
return self._flattr.CALLBACK
@Slot(str)
def processFlattrCode(self, url):
if not self._flattr.process_retrieved_code(url):
self.root.show_message(_('Could not log in to Flattr.'))
@Slot(result='QStringList')
def getEpisodeListFilterNames(self):
return [caption for caption, eql in EPISODE_LIST_FILTERS]
@Slot('QVariant', str)
def multiEpisodeAction(self, selected, action):
if not selected:
return
count = len(selected)
episodes = map(self.root.episode_model.get_object_by_index, selected)
def delete():
for episode in episodes:
if not episode.qarchive:
episode.delete_episode()
self.update_subset_stats()
self.root.mygpo_client.on_delete(episodes)
self.root.mygpo_client.flush()
for episode in episodes:
self.root.on_episode_deleted(episode)
self.root.episode_model.sort()
if action == 'delete':
msg = N_('Delete %(count)d episode?', 'Delete %(count)d episodes?', count) % {'count':count}
self.confirm_action(msg, _('Delete'), delete)
elif action == 'download':
for episode in episodes:
if episode.qdownloaded:
print ' XXX already downloaded'
continue
episode.qdownload(self.root.config, self.update_subset_stats)
self.root.mygpo_client.on_download(episodes)
self.root.mygpo_client.flush()
elif action == 'play':
for episode in episodes:
self.root.enqueue_episode(episode)
@Slot(str, result=str)
def translate(self, x):
return _(x)
@Slot(str, str, int, result=str)
def ntranslate(self, singular, plural, count):
return N_(singular, plural, count)
@Slot(str, int, result=str)
def formatCount(self, template, count):
return template % {'count': count}
@Slot(result=str)
def getVersion(self):
return gpodder.__version__
@Slot(result=str)
def getReleased(self):
return gpodder.__date__
@Slot(result=unicode)
def getCredits(self):
credits_file = os.path.join(gpodder.prefix, 'share', 'gpodder', 'credits.txt')
return util.convert_bytes(open(credits_file).read())
@Slot(result=unicode)
def getCopyright(self):
return util.convert_bytes(gpodder.__copyright__)
@Slot(result=str)
def getLicense(self):
return gpodder.__license__
@Slot(result=str)
def getURL(self):
return gpodder.__url__
@Slot()
def loadLastEpisode(self):
self.root.load_last_episode()
@Slot(QObject, int, int)
def storePlaybackAction(self, episode, start, end):
if end - 5 < start:
logger.info('Ignoring too short playback action.')
return
total = episode.qduration
self.root.mygpo_client.on_playback_full(episode, start, end, total)
self.root.mygpo_client.flush()
@Slot(QObject)
def playVideo(self, episode):
"""Video Playback on MeeGo 1.2 Harmattan"""
if episode.qnew:
episode.toggle_new()
self.update_subset_stats()
url = episode.get_playback_url()
if gpodder.ui.harmattan:
subprocess.Popen(['video-suite', url])
else:
util.gui_open(url)
self.root.mygpo_client.on_playback([episode])
self.root.mygpo_client.flush()
@Slot(QObject)
def podcastSelected(self, podcast):
self.setEpisodeListTitle(podcast.qtitle)
self.root.select_podcast(podcast)
windowTitleChanged = Signal()
def getWindowTitle(self):
return self.root.view.windowTitle()
def setWindowTitle(self, windowTitle):
if gpodder.ui.fremantle:
self.root.view.setWindowTitle(windowTitle)
windowTitle = Property(unicode, getWindowTitle,
setWindowTitle, notify=windowTitleChanged)
@Slot()
def myGpoUploadList(self):
def upload_proc(self):
self.root.start_progress(_('Uploading subscriptions...'))
try:
try:
self.root.mygpo_client.set_subscriptions([podcast.url
for podcast in self.root.podcast_model.get_podcasts()])
except Exception, e:
self.root.show_message('\n'.join((_('Error on upload:'), unicode(e))))
finally:
self.root.end_progress()
util.run_in_background(lambda: upload_proc(self))
@Slot()
def saveMyGpoSettings(self):
# Update the device settings and upload changes
self.root.mygpo_client.create_device()
self.root.mygpo_client.flush(now=True)
myGpoEnabledChanged = Signal()
def getMyGpoEnabled(self):
return self.root.config.mygpo.enabled
def setMyGpoEnabled(self, enabled):
self.root.config.mygpo.enabled = enabled
myGpoEnabled = Property(bool, getMyGpoEnabled,
setMyGpoEnabled, notify=myGpoEnabledChanged)
myGpoUsernameChanged = Signal()
def getMyGpoUsername(self):
return model.convert(self.root.config.mygpo.username)
def setMyGpoUsername(self, username):
self.root.config.mygpo.username = username
myGpoUsername = Property(unicode, getMyGpoUsername,
setMyGpoUsername, notify=myGpoUsernameChanged)
myGpoPasswordChanged = Signal()
def getMyGpoPassword(self):
return model.convert(self.root.config.mygpo.password)
def setMyGpoPassword(self, password):
self.root.config.mygpo.password = password
myGpoPassword = Property(unicode, getMyGpoPassword,
setMyGpoPassword, notify=myGpoPasswordChanged)
myGpoDeviceCaptionChanged = Signal()
def getMyGpoDeviceCaption(self):
return model.convert(self.root.config.mygpo.device.caption)
def setMyGpoDeviceCaption(self, caption):
self.root.config.mygpo.device.caption = caption
myGpoDeviceCaption = Property(unicode, getMyGpoDeviceCaption,
setMyGpoDeviceCaption, notify=myGpoDeviceCaptionChanged)
@Slot(QObject)
def podcastContextMenu(self, podcast):
menu = []
if isinstance(podcast, model.EpisodeSubsetView):
menu.append(helper.Action(_('Update all'), 'update-all', podcast))
else:
menu.append(helper.Action(_('Update'), 'update', podcast))
menu.append(helper.Action(_('Mark episodes as old'), 'mark-as-read', podcast))
menu.append(helper.Action(_('Rename'), 'rename-podcast', podcast))
menu.append(helper.Action(_('Change section'), 'change-section', podcast))
menu.append(helper.Action(_('Unsubscribe'), 'unsubscribe', podcast))
#menu.append(helper.Action('Force update all', 'force-update-all', podcast))
#menu.append(helper.Action('Force update', 'force-update', podcast))
self.show_context_menu(menu)
def show_context_menu(self, actions):
if gpodder.ui.harmattan:
actions = filter(lambda a: a.caption != '', actions)
self.context_menu_actions = actions
self.root.open_context_menu(self.context_menu_actions)
def update_subset_stats(self):
# This should be called when an episode changes state,
# so that all subset views (e.g. "All episodes") can
# update its status (i.e. download/new counts, etc..)
for podcast in self.root.podcast_model.get_objects():
if isinstance(podcast, model.EpisodeSubsetView):
podcast.qupdate()
def find_episode(self, podcast_url, episode_url):
for podcast in self.root.podcast_model.get_podcasts():
if podcast.url == podcast_url:
for episode in podcast.get_all_episodes():
if episode.url == episode_url:
return episode
return None
@Slot()
def updateAllPodcasts(self):
# Process episode actions received from gpodder.net
def merge_proc(self):
self.root.start_progress(_('Merging episode actions...'))
def find_episode(podcast_url, episode_url, counter):
counter['x'] += 1
self.root.start_progress(_('Merging episode actions (%d)')
% counter['x'])
return self.find_episode(podcast_url, episode_url)
try:
d = {'x': 0} # Used to "remember" the counter inside find_episode
self.root.mygpo_client.process_episode_actions(lambda x, y:
find_episode(x, y, d))
finally:
self.root.end_progress()
util.run_in_background(lambda: merge_proc(self))
for podcast in self.root.podcast_model.get_objects():
podcast.qupdate(finished_callback=self.update_subset_stats)
@Slot(int)
def contextMenuResponse(self, index):
assert index < len(self.context_menu_actions)
action = self.context_menu_actions[index]
if action.action == 'update':
action.target.qupdate(finished_callback=self.update_subset_stats)
elif action.action == 'force-update':
action.target.qupdate(force=True, \
finished_callback=self.update_subset_stats)
elif action.action == 'update-all':
self.updateAllPodcasts()
elif action.action == 'force-update-all':
for podcast in self.root.podcast_model.get_objects():
podcast.qupdate(force=True, finished_callback=self.update_subset_stats)
if action.action == 'unsubscribe':
def unsubscribe():
action.target.remove_downloaded()
action.target.delete()
self.root.remove_podcast(action.target)
self.confirm_action(_('Remove this podcast and episodes?'),
_('Unsubscribe'), unsubscribe)
elif action.action == 'episode-toggle-new':
action.target.toggle_new()
self.update_subset_stats()
elif action.action == 'episode-toggle-archive':
action.target.toggle_archive()
self.update_subset_stats()
elif action.action == 'episode-delete':
self.deleteEpisode(action.target)
elif action.action == 'episode-enqueue':
self.root.enqueue_episode(action.target)
elif action.action == 'mark-as-read':
for episode in action.target.get_all_episodes():
if not episode.was_downloaded(and_exists=True):
episode.mark(is_played=True)
action.target.changed.emit()
self.update_subset_stats()
elif action.action == 'change-section':
def section_changer(podcast):
section = yield (_('New section name:'), podcast.section,
_('Rename'))
if section and section != podcast.section:
podcast.set_section(section)
self.root.resort_podcast_list()
self.start_input_dialog(section_changer(action.target))
elif action.action == 'rename-podcast':
def title_changer(podcast):
title = yield (_('New name:'), podcast.title,
_('Rename'))
if title and title != podcast.title:
podcast.rename(title)
self.root.resort_podcast_list()
self.start_input_dialog(title_changer(action.target))
def confirm_action(self, message, affirmative, callback):
def confirm(message, affirmative, callback):
args = (message, '', affirmative, _('Cancel'), False)
if (yield args):
callback()
self.start_input_dialog(confirm(message, affirmative, callback))
def start_input_dialog(self, generator):
"""Carry out an input dialog with the UI
This function takes a generator function as argument
which should yield a tuple of arguments for the
"show_input_dialog" function (i.e. message, default
value, accept and reject message - only the message
is mandatory, the other arguments have default values).
The generator will receive the user's response as a
result of the yield expression. If the user accepted
the dialog, a string is returned (the value that has
been input), otherwise None is returned.
Example usage:
def some_function():
result = yield ('A simple message', 'default value')
if result is None:
# user has rejected the dialog
else:
# user has accepted, new value in "result"
start_input_dialog(some_function())
"""
assert self.current_input_dialog is None
self.current_input_dialog = generator
args = generator.next()
self.root.show_input_dialog(*args)
@Slot(bool, str, bool)
def inputDialogResponse(self, accepted, value, is_text):
if not is_text:
value = accepted
elif not accepted:
value = None
try:
self.current_input_dialog.send(value)
except StopIteration:
# This is expected, as the generator
# should only have one yield statement
pass
self.current_input_dialog = None
@Slot(QObject)
def downloadEpisode(self, episode):
episode.qdownload(self.root.config, self.update_subset_stats)
self.root.mygpo_client.on_download([episode])
self.root.mygpo_client.flush()
@Slot(QObject)
def cancelDownload(self, episode):
episode.download_task.cancel()
episode.download_task.removed_from_list()
@Slot(QObject)
def deleteEpisode(self, episode):
def delete():
episode.delete_episode()
self.update_subset_stats()
self.root.mygpo_client.on_delete([episode])
self.root.mygpo_client.flush()
self.root.on_episode_deleted(episode)
self.root.episode_model.sort()
self.confirm_action(_('Delete this episode?'), _('Delete'), delete)
@Slot(QObject)
def acquireEpisode(self, episode):
self.root.add_active_episode(episode)
@Slot(QObject)
def releaseEpisode(self, episode):
self.root.remove_active_episode(episode)
@Slot()
def contextMenuClosed(self):
self.context_menu_actions = []
@Slot(QObject)
def episodeContextMenu(self, episode):
menu = []
toggle_new = _('Mark as old') if episode.is_new else _('Mark as new')
menu.append(helper.Action(toggle_new, 'episode-toggle-new', episode))
toggle_archive = _('Allow deletion') if episode.archive else _('Archive')
menu.append(helper.Action(toggle_archive, 'episode-toggle-archive', episode))
if episode.state != gpodder.STATE_DELETED:
menu.append(helper.Action(_('Delete'), 'episode-delete', episode))
menu.append(helper.Action(_('Add to play queue'), 'episode-enqueue', episode))
self.show_context_menu(menu)
@Slot('QVariant')
def addSubscriptions(self, urls):
def not_yet_subscribed(url):
for podcast in self.root.podcast_model.get_objects():
if isinstance(podcast, model.EpisodeSubsetView):
continue
if podcast.url == url:
logger.info('Already subscribed: %s', url)
return False
return True
urls = map(util.normalize_feed_url, urls)
urls = filter(not_yet_subscribed, urls)
def subscribe_proc(self, urls):
self.root.start_progress(_('Adding podcasts...'))
try:
for idx, url in enumerate(urls):
print idx, url
self.root.start_progress(_('Adding podcasts...') + ' (%d/%d)' % (idx, len(urls)))
try:
podcast = self.root.model.load_podcast(url=url, create=True,
max_episodes=self.root.config.max_episodes_per_feed)
podcast.save()
self.root.insert_podcast(model.QPodcast(podcast))
except Exception, e:
logger.warn('Cannot add pocast: %s', e)
# XXX: Visual feedback in the QML UI
finally:
self.root.end_progress()
util.run_in_background(lambda: subscribe_proc(self, urls))
@Slot()
def currentEpisodeChanging(self):
self.root.save_pending_data()
@Slot()
def quit(self):
self.root.quit.emit()
@Slot()
def switcher(self):
if gpodder.ui.harmattan:
self.root.view.showMinimized()
elif gpodder.ui.fremantle:
os.system('dbus-send /com/nokia/hildon_desktop '+
'com.nokia.hildon_desktop.exit_app_view')
else:
self.root.view.showMinimized()
class gPodderListModel(QAbstractListModel):
def __init__(self, objects=None):
QAbstractListModel.__init__(self)
if objects is None:
objects = []
self._objects = objects
self.setRoleNames({0: 'modelData', 1: 'section'})
def sort(self):
# Unimplemented for the generic list model
self.reset()
def insert_object(self, o):
self._objects.append(o)
self.sort()
def remove_object(self, o):
self._objects.remove(o)
self.reset()
def set_objects(self, objects):
self._objects = objects
self.sort()
def get_objects(self):
return self._objects
def get_object(self, index):
return self._objects[index.row()]
def rowCount(self, parent=QModelIndex()):
return len(self.get_objects())
def data(self, index, role):
if index.isValid():
if role == 0:
return self.get_object(index)
elif role == 1:
return self.get_object(index).qsection
return None
class gPodderPodcastListModel(gPodderListModel):
def set_podcasts(self, db, podcasts):
views = [
model.EpisodeSubsetView(db, self, _('All episodes'), ''),
]
self.set_objects(views + podcasts)
def get_podcasts(self):
return filter(lambda podcast: isinstance(podcast, model.QPodcast),
self.get_objects())
def sort(self):
self._objects = sorted(self._objects, key=model.QPodcast.sort_key)
self.reset()
class gPodderEpisodeListModel(gPodderListModel):
def __init__(self, config):
gPodderListModel.__init__(self)
self._filter = config.ui.qml.state.episode_list_filter
self._filtered = []
self._is_subset_view = False
self._config = config
config.add_observer(self._on_config_changed)
is_subset_view_changed = Signal()
def get_is_subset_view(self):
return self._is_subset_view
def set_is_subset_view(self, is_subset_view):
if is_subset_view != self.is_subset_view:
self._is_subset_view = is_subset_view
self.is_subset_view_changed.emit()
is_subset_view = Property(bool, get_is_subset_view,
set_is_subset_view, notify=is_subset_view_changed)
def _on_config_changed(self, name, old_value, new_value):
if name == 'ui.qml.state.episode_list_filter':
self._filter = new_value
self.sort()
def sort(self):
caption, eql = EPISODE_LIST_FILTERS[self._filter]
if eql is None:
self._filtered = self._objects
else:
eql = query.EQL(eql)
match = lambda episode: eql.match(episode._episode)
self._filtered = filter(match, self._objects)
self.reset()
def get_objects(self):
return self._filtered
def get_object(self, index):
return self._filtered[index.row()]
@Slot(int, result=QObject)
def get_object_by_index(self, index):
return self._filtered[int(index)]
@Slot(result=int)
def getFilter(self):
return self._filter
@Slot(int)
def setFilter(self, filter_index):
self._config.ui.qml.state.episode_list_filter = filter_index
def QML(filename):
for folder in gpodder.ui_folders:
filename = os.path.join(folder, filename)
if os.path.exists(filename):
return filename
class DeclarativeView(QDeclarativeView):
def __init__(self):
QDeclarativeView.__init__(self)
self.setAttribute(Qt.WA_OpaquePaintEvent)
self.setAttribute(Qt.WA_NoSystemBackground)
self.viewport().setAttribute(Qt.WA_OpaquePaintEvent)
self.viewport().setAttribute(Qt.WA_NoSystemBackground)
closing = Signal()
def closeEvent(self, event):
self.closing.emit()
event.ignore()
class qtPodder(QObject):
def __init__(self, args, gpodder_core, dbus_bus_name):
QObject.__init__(self)
self.dbus_bus_name = dbus_bus_name
# TODO: Expose the same D-Bus API as the Gtk UI D-Bus object (/gui)
# TODO: Create a gpodder.dbusproxy.DBusPodcastsProxy object (/podcasts)
# Enable OpenGL rendering without requiring QtOpenGL
# On Harmattan we let the system choose the best graphicssystem
if '-graphicssystem' not in args and not gpodder.ui.harmattan:
if gpodder.ui.fremantle:
args += ['-graphicssystem', 'opengl']
elif not gpodder.win32:
args += ['-graphicssystem', 'raster']
self.app = QApplication(args)
signal.signal(signal.SIGINT, signal.SIG_DFL)
self.quit.connect(self.on_quit)
self.core = gpodder_core
self.config = self.core.config
self.db = self.core.db
self.model = self.core.model
self.config_proxy = ConfigProxy(self.config)
# Initialize the gpodder.net client
self.mygpo_client = my.MygPoClient(self.config)
gpodder.user_extensions.on_ui_initialized(self.model,
self.extensions_podcast_update_cb,
self.extensions_episode_download_cb)
self.view = DeclarativeView()
self.view.closing.connect(self.on_quit)
self.view.setResizeMode(QDeclarativeView.SizeRootObjectToView)
self.controller = Controller(self)
self.media_buttons_handler = helper.MediaButtonsHandler()
self.tracker_miner_config = helper.TrackerMinerConfig()
self.podcast_model = gPodderPodcastListModel()
self.episode_model = gPodderEpisodeListModel(self.config)
self.last_episode = None
# A dictionary of episodes that are currently active
# in some way (i.e. playing back or downloading)
self.active_episode_wrappers = {}
engine = self.view.engine()
# Maemo 5: Experimental Qt Mobility packages are installed in /opt
if gpodder.ui.fremantle:
for path in ('/opt/qtm11/imports', '/opt/qtm12/imports'):
engine.addImportPath(path)
elif gpodder.win32:
for path in (r'C:\QtSDK\Desktop\Qt\4.7.4\msvc2008\imports',):
engine.addImportPath(path)
# Add the cover art image provider
self.cover_provider = images.LocalCachedImageProvider()
engine.addImageProvider('cover', self.cover_provider)
root_context = self.view.rootContext()
root_context.setContextProperty('controller', self.controller)
root_context.setContextProperty('configProxy', self.config_proxy)
root_context.setContextProperty('mediaButtonsHandler',
self.media_buttons_handler)
root_context.setContextProperty('trackerMinerConfig',
self.tracker_miner_config)
# Load the QML UI (this could take a while...)
self.view.setSource(QUrl.fromLocalFile(QML('main_default.qml')))
# Proxy to the "main" QML object for direct access to Qt Properties
self.main = helper.QObjectProxy(self.view.rootObject().property('main'))
self.main.podcastModel = self.podcast_model
self.main.episodeModel = self.episode_model
self.view.setWindowTitle('gPodder')
if gpodder.ui.harmattan:
self.view.showFullScreen()
elif gpodder.ui.fremantle:
self.view.setAttribute(Qt.WA_Maemo5AutoOrientation, True)
self.view.showFullScreen()
else:
# On the Desktop, scale to fit my small laptop screen..
desktop = self.app.desktop()
if desktop.height() < 1000:
FACTOR = .8
self.view.scale(FACTOR, FACTOR)
size = self.view.size()
size *= FACTOR
self.view.resize(size)
self.view.show()
self.do_start_progress.connect(self.on_start_progress)
self.do_end_progress.connect(self.on_end_progress)
self.do_show_message.connect(self.on_show_message)
self.load_podcasts()
def add_active_episode(self, episode):
self.active_episode_wrappers[episode.id] = episode
episode.episode_wrapper_refcount += 1
def remove_active_episode(self, episode):
episode.episode_wrapper_refcount -= 1
if episode.episode_wrapper_refcount == 0:
del self.active_episode_wrappers[episode.id]
def load_last_episode(self):
last_episode = None
last_podcast = None
for podcast in self.podcast_model.get_podcasts():
for episode in podcast.get_all_episodes():
if not episode.last_playback:
continue
if last_episode is None or \
episode.last_playback > last_episode.last_playback:
last_episode = episode
last_podcast = podcast
if last_episode is not None:
self.last_episode = self.wrap_episode(last_podcast, last_episode)
# FIXME: Send last episode to player
#self.select_episode(self.last_episode)
def on_episode_deleted(self, episode):
# Remove episode from play queue (if it's in there)
self.main.removeQueuedEpisode(episode)
# If the episode that has been deleted is currently
# being played back (or paused), stop playback now.
if self.main.currentEpisode == episode:
self.main.togglePlayback(None)
def enqueue_episode(self, episode):
self.main.enqueueEpisode(episode)
def run(self):
return self.app.exec_()
quit = Signal()
def on_quit(self):
# Make sure the audio playback is stopped immediately
self.main.togglePlayback(None)
self.save_pending_data()
self.view.hide()