Add "on_drag_mark_played" config option
[gpodder.git] / src / gpodder / config.py
bloba78cd8c7e87c37dd74bcf54f538d0921d67be376
1 # -*- coding: utf-8 -*-
3 # gPodder - A media aggregator and podcast client
4 # Copyright (c) 2005-2009 Thomas Perl and the gPodder Team
6 # gPodder is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3 of the License, or
9 # (at your option) any later version.
11 # gPodder is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
22 # config.py -- gPodder Configuration Manager
23 # Thomas Perl <thp@perli.net> 2007-11-02
27 import gpodder
28 from gpodder import util
29 from gpodder.liblogger import log
31 import atexit
32 import os
33 import time
34 import threading
35 import ConfigParser
37 _ = gpodder.gettext
39 if gpodder.ui.fremantle:
40 default_download_dir = os.path.join(os.path.expanduser('~'), 'MyDocs/Podcasts')
41 elif gpodder.ui.diablo:
42 default_download_dir = '/media/mmc2/gpodder'
43 else:
44 default_download_dir = os.path.join(os.path.expanduser('~'), 'gpodder-downloads')
46 gPodderSettings = {
47 # General settings
48 'player': (str, 'default',
49 ("The default player for all media, if set to 'default' this will "
50 "attempt to use xdg-open on linux or the built-in media player on maemo.")),
51 'videoplayer': (str, 'default',
52 ("The default player for video")),
53 'opml_url': (str, 'http://gpodder.org/directory.opml',
54 ("A URL pointing to an OPML file which can be used to bulk-add podcasts.")),
55 'toplist_url': (str, 'http://gpodder.org/toplist.opml',
56 ("A URL pointing to a gPodder web services top podcasts list")),
57 'custom_sync_name': ( str, '{episode.basename}',
58 ("The name used when copying a file to a FS-based device. Available "
59 "options are: episode.basename, episode.title, episode.published")),
60 'custom_sync_name_enabled': ( bool, True,
61 ("Enables renaming files when transfered to an FS-based device with "
62 "respect to the 'custom_sync_name'.")),
63 'max_downloads': ( int, 1,
64 ("The maximum number of simultaneous downloads allowed at a single "
65 "time. Requires 'max_downloads_enabled'.")),
66 'max_downloads_enabled': ( bool, True,
67 ("The 'max_downloads' setting will only work if this is set to 'True'.")),
68 'limit_rate': ( bool, False,
69 ("The 'limit_rate_value' setting will only work if this is set to 'True'.")),
70 'limit_rate_value': ( float, 500.0,
71 ("Set a global speed limit (in KB/s) when downloading files. "
72 "Requires 'limit_rate'.")),
73 'episode_old_age': ( int, 7,
74 ("The number of days before an episode is considered old. "
75 "Must be used in conjunction with 'auto_remove_old_episodes'.")),
77 # Boolean config flags
78 'update_on_startup': ( bool, False,
79 ("Update the feed cache on startup.")),
80 'only_sync_not_played': ( bool, False,
81 ("Only sync episodes to a device that have not been marked played in gPodder.")),
82 'fssync_channel_subfolders': ( bool, True,
83 ("Create a directory for every feed when syncing to an FS-based device "
84 "instead of putting all the episodes in a single directory.")),
85 'on_sync_mark_played': ( bool, False,
86 ("After syncing an episode, mark it as played in gPodder.")),
87 'on_sync_delete': ( bool, False,
88 ("After syncing an episode, delete it from gPodder.")),
89 'auto_remove_old_episodes': ( bool, False,
90 ("Remove episodes older than 'episode_old_age' days on startup.")),
91 'auto_update_feeds': (bool, False,
92 ("Automatically update feeds when gPodder is minimized. "
93 "See 'auto_update_frequency' and 'auto_download'.")),
94 'auto_update_frequency': (int, 20,
95 ("The frequency (in minutes) at which gPodder will update all feeds "
96 "if 'auto_update_feeds' is enabled.")),
97 'episode_list_descriptions': (bool, True,
98 ("Display the episode's description under the episode title in the GUI.")),
99 'show_toolbar': (bool, True,
100 ("Show the toolbar in the GUI's main window.")),
101 'ipod_purge_old_episodes': (bool, False,
102 ("Remove episodes from an iPod device if they've been marked as played "
103 "on the device and they have no rating set (the rating can be set on "
104 "the device by the user to prevent deletion).")),
105 'ipod_delete_played_from_db': (bool, False,
106 ("Remove episodes from gPodder if they've been marked as played "
107 "on the device and they have no rating set (the rating can be set on "
108 "the device by the user to prevent deletion).")),
109 'mp3_player_delete_played': (bool, False,
110 ("Removes episodes from an FS-based device that have been marked as "
111 "played in gPodder. Note: only works if 'only_sync_not_played' is "
112 "also enabled.")),
113 'disable_pre_sync_conversion': (bool, False,
114 ("Disable pre-synchronization conversion of OGG files. This should be "
115 "enabled for deviced that natively support OGG. Eg. Rockbox, iAudio")),
117 # Tray icon and notification settings
118 'display_tray_icon': (bool, False,
119 ("Whether or not gPodder should display an icon in the system tray.")),
120 'minimize_to_tray': (bool, False,
121 ("If 'display_tray_icon' is enabled, when gPodder is minimized it will "
122 "not be visible in the window list.")),
123 'start_iconified': (bool, False,
124 ("When gPodder starts, send it to the tray immediately.")),
125 'enable_notifications': (bool, True,
126 ("Let gPodder use notification bubbles when it can completed certain "
127 "tasks like downloading an episode or finishing syncing to a device.")),
128 'on_quit_ask': (bool, True,
129 ("Ask the user to confirm quitting the application.")),
130 'auto_download': (str, 'never',
131 ("Auto download episodes (never, minimized, always)")),
132 'do_not_show_new_episodes_dialog': (bool, False,
133 ("Do not show the new episodes dialog after updating feed cache when "
134 "gPodder is not minimized")),
137 # Settings that are updated directly in code
138 'ipod_mount': ( str, '/media/ipod',
139 ("The moint point for an iPod Device.")),
140 'mp3_player_folder': ( str, '/media/usbdisk',
141 ("The moint point for an FS-based device.")),
142 'device_type': ( str, 'none',
143 ("The device type: 'mtp', 'filesystem' or 'ipod'")),
144 'download_dir': (str, default_download_dir,
145 ("The default directory that podcast episodes are downloaded to.")),
147 # Playlist Management settings
148 'mp3_player_playlist_file': (str, 'PLAYLISTS/gpodder.m3u',
149 ("The relative path to where the playlist is stored on an FS-based device.")),
150 'mp3_player_playlist_absolute_path': (bool, True,
151 ("Whether or not the the playlist should contain relative or absolute "
152 "paths; this is dependent on the player.")),
153 'mp3_player_playlist_win_path': (bool, True,
154 ("Whether or not the player requires Windows-style paths in the playlist.")),
156 # Special settings (not in preferences)
157 'on_quit_systray': (bool, False,
158 ("When the 'X' button is clicked do not quit, send gPodder to the tray.")),
159 'max_episodes_per_feed': (int, 200,
160 ("The maximum number of episodes that gPodder will display in the episode "
161 "list. Note: Set this to a lower value on slower hardware to speed up "
162 "rendering of the episode list.")),
163 'mp3_player_use_scrobbler_log': (bool, False,
164 ("Attempt to use a Device's scrobbler.log to mark episodes as played in "
165 "gPodder. Useful for Rockbox players.")),
166 'mp3_player_max_filename_length': (int, 100,
167 ("The maximum filename length for FS-based devices.")),
168 'rockbox_copy_coverart' : (bool, False,
169 ("Create rockbox-compatible coverart and copy it to the device when "
170 "syncing. See: 'rockbox_coverart_size'.")),
171 'rockbox_coverart_size' : (int, 100,
172 ("The width of the coverart for the user's Rockbox player/skin.")),
173 'custom_player_copy_coverart' : (bool, False,
174 ("Create custom coverart for FS-based players.")),
175 'custom_player_coverart_size' : (int, 176,
176 ("The width of the coverart for the user's FS-based player.")),
177 'custom_player_coverart_name' : (str, 'folder.jpg',
178 ("The name of the coverart file accepted by the user's FS-based player.")),
179 'custom_player_coverart_format' : (str, 'JPEG',
180 ("The image format accepted by the user's FS-based player.")),
181 'podcast_list_icon_size': (int, 32,
182 ("The width of the icon used in the podcast channel list.")),
183 'cmd_all_downloads_complete': (str, '',
184 ("The path to a command that gets run after all downloads are completed.")),
185 'cmd_download_complete': (str, '',
186 ("The path to a command that gets run after a single download completes. "
187 "See http://wiki.gpodder.org/wiki/Time_stretching for more info.")),
188 'enable_html_shownotes': (bool, True,
189 ("Allow HTML to be rendered in the episode information dialog.")),
190 'maemo_enable_gestures': (bool, False,
191 ("Enable fancy gestures on Maemo.")),
192 'sync_disks_after_transfer': (bool, True,
193 ("Call 'sync' after tranfering episodes to a device.")),
194 'resume_ask_every_episode': (bool, False,
195 ("If there are episode downloads that can be resumed, ask whether or "
196 "not to resume every single one.")),
197 'enable_fingerscroll': (bool, False,
198 ("Enable the use of finger-scrollable widgets on Maemo.")),
199 'double_click_episode_action': (str, 'shownotes',
200 ("Episode double-click/enter action handler (shownotes, download, stream)")),
201 'on_drag_mark_played': (bool, False,
202 ("Mark episode as played when using drag'n'drop to copy/open it")),
204 'feed_update_skipping': (bool, True,
205 ('Skip podcasts that are unlikely to have new episodes when updating feeds.')),
207 'episode_list_view_mode': (int, 1, # "Hide deleted episodes" (see gtkui/model.py)
208 ('Internally used (current view mode)')),
209 'podcast_list_view_mode': (int, 1, # Only on Fremantle
210 ('Internally used (current view mode)')),
211 'podcast_list_hide_boring': (bool, False,
212 ('Hide podcasts in the main window for which the episode list is empty')),
214 'audio_played_dbus': (bool, False,
215 ('Set to True if the audio player notifies gPodder about played episodes')),
216 'video_played_dbus': (bool, False,
217 ('Set to True if the video player notifies gPodder about played episodes')),
219 'rotation_mode': (int, 0,
220 ('Internally used on Maemo 5 for the current rotation mode')),
222 # Settings for my.gpodder.org
223 'my_gpodder_username': (str, '',
224 ("The user's gPodder web services username.")),
225 'my_gpodder_password': (str, '',
226 ("The user's gPodder web services password.")),
227 'my_gpodder_autoupload': (bool, False,
228 ("Upload the user's podcast list to the gPodder web services when "
229 "gPodder is closed.")),
230 'my_gpodder_service': (str, 'http://my.gpodder.org',
231 ('The base URL of the my.gpodder.org service.')),
233 # Paned position
234 'paned_position': ( int, 200,
235 ("The width of the channel list.")),
238 # Helper function to add window-specific properties (position and size)
239 def window_props(config_prefix, x=-1, y=-1, width=700, height=500):
240 return {
241 config_prefix+'_x': (int, x),
242 config_prefix+'_y': (int, y),
243 config_prefix+'_width': (int, width),
244 config_prefix+'_height': (int, height),
245 config_prefix+'_maximized': (bool, False),
248 # Register window-specific properties
249 gPodderSettings.update(window_props('main_window', width=700, height=500))
250 gPodderSettings.update(window_props('episode_selector', width=600, height=400))
251 gPodderSettings.update(window_props('episode_window', width=500, height=400))
254 class Config(dict):
255 Settings = gPodderSettings
257 # Number of seconds after which settings are auto-saved
258 WRITE_TO_DISK_TIMEOUT = 60
260 def __init__(self, filename='gpodder.conf'):
261 dict.__init__(self)
262 self.__save_thread = None
263 self.__filename = filename
264 self.__section = 'gpodder-conf-1'
265 self.__observers = []
267 self.load()
268 self.apply_fixes()
270 atexit.register( self.__atexit)
272 def apply_fixes(self):
273 # Here you can add fixes in case syntax changes. These will be
274 # applied whenever a configuration file is loaded.
275 if '{channel' in self.custom_sync_name:
276 log('Fixing OLD syntax {channel.*} => {podcast.*} in custom_sync_name.', sender=self)
277 self.custom_sync_name = self.custom_sync_name.replace('{channel.', '{podcast.')
279 def __getattr__(self, name):
280 if name in self.Settings:
281 return self[name]
282 else:
283 raise AttributeError('%s is not a setting' % name)
285 def get_description(self, option_name):
286 description = _('No description available.')
288 if self.Settings.get(option_name) is not None:
289 row = self.Settings[option_name]
290 if len(row) >= 3:
291 description = row[2]
293 return description
295 def add_observer(self, callback):
297 Add a callback function as observer. This callback
298 will be called when a setting changes. It should
299 have this signature:
301 observer(name, old_value, new_value)
303 The "name" is the setting name, the "old_value" is
304 the value that has been overwritten with "new_value".
306 if callback not in self.__observers:
307 self.__observers.append(callback)
308 else:
309 log('Observer already added: %s', repr(callback), sender=self)
311 def remove_observer(self, callback):
313 Remove an observer previously added to this object.
315 if callback in self.__observers:
316 self.__observers.remove(callback)
317 else:
318 log('Observer not added :%s', repr(callback), sender=self)
320 def schedule_save(self):
321 if self.__save_thread is None:
322 self.__save_thread = threading.Thread(target=self.save_thread_proc)
323 self.__save_thread.setDaemon(True)
324 self.__save_thread.start()
326 def save_thread_proc(self):
327 time.sleep(self.WRITE_TO_DISK_TIMEOUT)
328 if self.__save_thread is not None:
329 self.save()
331 def __atexit(self):
332 if self.__save_thread is not None:
333 self.save()
335 def save(self, filename=None):
336 if filename is None:
337 filename = self.__filename
339 log('Flushing settings to disk', sender=self)
341 parser = ConfigParser.RawConfigParser()
342 parser.add_section(self.__section)
344 for key, value in self.Settings.items():
345 fieldtype, default = value[:2]
346 parser.set(self.__section, key, getattr(self, key, default))
348 try:
349 parser.write(open(filename, 'w'))
350 except:
351 log('Cannot write settings to %s', filename, sender=self)
352 raise IOError('Cannot write to file: %s' % filename)
354 self.__save_thread = None
356 def load(self, filename=None):
357 if filename is not None:
358 self.__filename = filename
360 parser = ConfigParser.RawConfigParser()
362 if os.path.exists(self.__filename):
363 try:
364 parser.read(self.__filename)
365 except:
366 log('Cannot parse config file: %s', self.__filename,
367 sender=self, traceback=True)
369 for key, value in self.Settings.items():
370 fieldtype, default = value[:2]
371 try:
372 if not parser.has_section(self.__section):
373 value = default
374 elif fieldtype == int:
375 value = parser.getint(self.__section, key)
376 elif fieldtype == float:
377 value = parser.getfloat(self.__section, key)
378 elif fieldtype == bool:
379 value = parser.getboolean(self.__section, key)
380 else:
381 value = fieldtype(parser.get(self.__section, key))
382 except:
383 log('Invalid value in %s for %s: %s', self.__filename,
384 key, value, sender=self, traceback=True)
385 value = default
387 self[key] = value
389 def toggle_flag(self, name):
390 if name in self.Settings:
391 (fieldtype, default) = self.Settings[name][:2]
392 if fieldtype == bool:
393 setattr(self, name, not getattr(self, name))
394 else:
395 log('Cannot toggle value: %s (not boolean)', name, sender=self)
396 else:
397 log('Invalid setting name: %s', name, sender=self)
399 def update_field(self, name, new_value):
400 if name in self.Settings:
401 (fieldtype, default) = self.Settings[name][:2]
402 try:
403 new_value = fieldtype(new_value)
404 except:
405 log('Cannot convert "%s" to %s. Ignoring.', str(new_value), fieldtype.__name__, sender=self)
406 return False
407 setattr(self, name, new_value)
408 return True
409 else:
410 log('Invalid setting name: %s', name, sender=self)
411 return False
413 def __setattr__(self, name, value):
414 if name in self.Settings:
415 fieldtype, default = self.Settings[name][:2]
416 try:
417 if self[name] != fieldtype(value):
418 old_value = self[name]
419 log('Update %s: %s => %s', name, old_value, value, sender=self)
420 self[name] = fieldtype(value)
421 for observer in self.__observers:
422 try:
423 # Notify observer about config change
424 observer(name, old_value, self[name])
425 except:
426 log('Error while calling observer: %s',
427 repr(observer), sender=self,
428 traceback=True)
429 self.schedule_save()
430 except:
431 raise ValueError('%s has to be of type %s' % (name, fieldtype.__name__))
432 else:
433 object.__setattr__(self, name, value)