root/branches/gajim_0.11.1/src/common/optparser.py

Revision 8700, 15.1 kB (checked in by asterix, 15 months ago)

rename gtk+ theme to default theme fixes #2794

  • Property svn:eol-style set to LF
  • Property svn:keywords set to LastChangedDate LastChangedRevision LastChangedBy HeadURL Id
Line 
1##
2## Copyright (C) 2005-2006 Yann Le Boulanger <asterix@lagaule.org>
3## Copyright (C) 2005-2006 Nikos Kouremenos <kourem@gmail.com>
4##
5## This program is free software; you can redistribute it and/or modify
6## it under the terms of the GNU General Public License as published
7## by the Free Software Foundation; version 2 only.
8##
9## This program is distributed in the hope that it will be useful,
10## but WITHOUT ANY WARRANTY; without even the implied warranty of
11## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12## GNU General Public License for more details.
13##
14
15import os
16import locale
17from common import gajim
18
19import exceptions
20try:
21        import sqlite3 as sqlite # python 2.5
22except ImportError:
23        try:
24                from pysqlite2 import dbapi2 as sqlite
25        except ImportError:
26                raise exceptions.PysqliteNotAvailable
27import logger
28
29class OptionsParser:
30        def __init__(self, filename):
31                self.__filename = filename
32                self.old_values = {}    # values that are saved in the file and maybe
33                                                                # no longer valid
34
35        def read_line(self, line):
36                index = line.find(' = ')
37                var_str = line[0:index]
38                value_str = line[index + 3:-1]
39               
40                i_start = var_str.find('.')
41                i_end = var_str.rfind('.')
42               
43                if i_start == -1:
44                        self.old_values[var_str] = value_str
45                        gajim.config.set(var_str, value_str)
46                else:
47                        optname = var_str[0:i_start]
48                        key = var_str[i_start + 1:i_end]
49                        subname = var_str[i_end + 1:]
50                        gajim.config.add_per(optname, key)
51                        gajim.config.set_per(optname, key, subname, value_str)
52               
53        def read(self):
54                try:
55                        fd = open(self.__filename)
56                except:
57                        if os.path.exists(self.__filename):
58                                #we talk about a file
59                                print _('error: cannot open %s for reading') % self.__filename
60                        return
61
62                new_version = gajim.config.get('version')
63                for line in fd.readlines():
64                        try:
65                                line = line.decode('utf-8')
66                        except UnicodeDecodeError:
67                                line = line.decode(locale.getpreferredencoding())
68                        self.read_line(line)
69                old_version = gajim.config.get('version')
70
71                self.update_config(old_version, new_version)
72                self.old_values = {} # clean mem
73
74                fd.close()
75
76        def write_line(self, fd, opt, parents, value):
77                if value == None:
78                        return
79                value = value[1]
80                # convert to utf8 before writing to file if needed
81                if isinstance(value, unicode):
82                        value = value.encode('utf-8')
83                else:
84                        value = str(value)
85                if isinstance(opt, unicode):
86                        opt = opt.encode('utf-8')
87                s = ''
88                if parents:
89                        if len(parents) == 1:
90                                return
91                        for p in parents:
92                                if isinstance(p, unicode):
93                                        p = p.encode('utf-8')
94                                s += p + '.'
95                s += opt
96                fd.write(s + ' = ' + value + '\n')
97       
98        def write(self):
99                (base_dir, filename) = os.path.split(self.__filename)
100                self.__tempfile = os.path.join(base_dir, '.' + filename)
101                try:
102                        f = open(self.__tempfile, 'w')
103                except IOError, e:
104                        return str(e)
105                try:
106                        gajim.config.foreach(self.write_line, f)
107                except IOError, e:
108                        return str(e)
109                f.close()
110                if os.path.exists(self.__filename):
111                        # win32 needs this
112                        try:
113                                os.remove(self.__filename)
114                        except:
115                                pass
116                try:
117                        os.rename(self.__tempfile, self.__filename)
118                except IOError, e:
119                        return str(e)
120                os.chmod(self.__filename, 0600)
121
122        def update_config(self, old_version, new_version):
123                old_version_list = old_version.split('.') # convert '0.x.y' to (0, x, y)
124                old = []
125                while len(old_version_list):
126                        old.append(int(old_version_list.pop(0)))
127                new_version_list = new_version.split('.')
128                new = []
129                while len(new_version_list):
130                        new.append(int(new_version_list.pop(0)))
131
132                if old < [0, 9] and new >= [0, 9]:
133                        self.update_config_x_to_09()
134                if old < [0, 10] and new >= [0, 10]:
135                        self.update_config_09_to_010()
136                if old < [0, 10, 1, 1] and new >= [0, 10, 1, 1]:
137                        self.update_config_to_01011()
138                if old < [0, 10, 1, 2] and new >= [0, 10, 1, 2]:
139                        self.update_config_to_01012()
140                if old < [0, 10, 1, 3] and new >= [0, 10, 1, 3]:
141                        self.update_config_to_01013()
142                if old < [0, 10, 1, 4] and new >= [0, 10, 1, 4]:
143                        self.update_config_to_01014()
144                if old < [0, 10, 1, 5] and new >= [0, 10, 1, 5]:
145                        self.update_config_to_01015()
146                if old < [0, 10, 1, 6] and new >= [0, 10, 1, 6]:
147                        self.update_config_to_01016()
148                if old < [0, 10, 1, 7] and new >= [0, 10, 1, 7]:
149                        self.update_config_to_01017()
150                if old < [0, 10, 1, 8] and new >= [0, 10, 1, 8]:
151                        self.update_config_to_01018()
152                if old < [0, 11, 0, 1] and new >= [0, 11, 0, 1]:
153                        self.update_config_to_01101()
154                if old < [0, 11, 0, 2] and new >= [0, 11, 0, 2]:
155                        self.update_config_to_01102()
156                if old < [0, 11, 1, 1] and new >= [0, 11, 1, 1]:
157                        self.update_config_to_01111()
158                if old < [0, 11, 1, 2] and new >= [0, 11, 1, 2]:
159                        self.update_config_to_01112()
160                if old < [0, 11, 1, 3] and new >= [0, 11, 1, 3]:
161                        self.update_config_to_01113()
162                if old < [0, 11, 1, 4] and new >= [0, 11, 1, 4]:
163                        self.update_config_to_01114()
164
165                gajim.logger.init_vars()
166                gajim.config.set('version', new_version)
167       
168        def update_config_x_to_09(self):
169                # Var name that changed:
170                # avatar_width /height -> chat_avatar_width / height
171                if self.old_values.has_key('avatar_width'):
172                        gajim.config.set('chat_avatar_width', self.old_values['avatar_width'])
173                if self.old_values.has_key('avatar_height'):
174                        gajim.config.set('chat_avatar_height', self.old_values['avatar_height'])
175                if self.old_values.has_key('use_dbus'):
176                        gajim.config.set('remote_control', self.old_values['use_dbus'])
177                # always_compact_view -> always_compact_view_chat / _gc
178                if self.old_values.has_key('always_compact_view'):
179                        gajim.config.set('always_compact_view_chat',
180                                self.old_values['always_compact_view'])
181                        gajim.config.set('always_compact_view_gc',
182                                self.old_values['always_compact_view'])
183                # new theme: grocery, plain
184                d = ['accounttextcolor', 'accountbgcolor', 'accountfont',
185                        'accountfontattrs', 'grouptextcolor', 'groupbgcolor', 'groupfont',
186                        'groupfontattrs', 'contacttextcolor', 'contactbgcolor', 'contactfont',
187                        'contactfontattrs', 'bannertextcolor', 'bannerbgcolor', 'bannerfont', 
188                        'bannerfontattrs']
189                for theme_name in (_('grocery'), _('default')):
190                        if theme_name not in gajim.config.get_per('themes'):
191                                gajim.config.add_per('themes', theme_name)
192                                theme = gajim.config.themes_default[theme_name]
193                                for o in d:
194                                        gajim.config.set_per('themes', theme_name, o, theme[d.index(o)])
195                # Remove cyan theme if it's not the current theme
196                if 'cyan' in gajim.config.get_per('themes'):
197                        gajim.config.del_per('themes', 'cyan')
198                if _('cyan') in gajim.config.get_per('themes'):
199                        gajim.config.del_per('themes', _('cyan'))
200                # If we removed our roster_theme, choose the default green one or another
201                # one if doesn't exists in config
202                if gajim.config.get('roster_theme') not in gajim.config.get_per('themes'):
203                        theme = _('green')
204                        if theme not in gajim.config.get_per('themes'):
205                                theme = gajim.config.get_per('themes')[0]
206                        gajim.config.set('roster_theme', theme)
207                # new proxies in accounts.name.file_transfer_proxies
208                for account in gajim.config.get_per('accounts'):
209                        proxies = gajim.config.get_per('accounts', account,
210                                'file_transfer_proxies')
211                        if proxies.find('proxy.netlab.cz') < 0:
212                                proxies += ', ' + 'proxy.netlab.cz'
213                        gajim.config.set_per('accounts', account, 'file_transfer_proxies',
214                                proxies)
215
216                gajim.config.set('version', '0.9')
217
218        def assert_unread_msgs_table_exists(self):
219                '''create table unread_messages if there is no such table'''
220                back = os.getcwd()
221                os.chdir(logger.LOG_DB_FOLDER)
222                con = sqlite.connect(logger.LOG_DB_FILE)
223                os.chdir(back)
224                cur = con.cursor()
225                try:
226                        cur.executescript(
227                                '''
228                                CREATE TABLE unread_messages (
229                                        message_id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
230                                        jid_id INTEGER
231                                );
232                                '''
233                        )
234                        con.commit()
235                        gajim.logger.init_vars()
236                except sqlite.OperationalError, e:
237                        pass
238                con.close()
239
240        def update_config_09_to_010(self):
241                if self.old_values.has_key('usetabbedchat') and not \
242                self.old_values['usetabbedchat']:
243                        gajim.config.set('one_message_window', 'never')
244                if self.old_values.has_key('autodetect_browser_mailer') and \
245                self.old_values['autodetect_browser_mailer'] is True:
246                        gajim.config.set('autodetect_browser_mailer', False)
247                if self.old_values.has_key('useemoticons') and \
248                not self.old_values['useemoticons']:
249                        gajim.config.set('emoticons_theme', '')
250                if self.old_values.has_key('always_compact_view_chat') and \
251                self.old_values['always_compact_view_chat'] != 'False':
252                        gajim.config.set('always_hide_chat_buttons', True)
253                if self.old_values.has_key('always_compact_view_gc') and \
254                self.old_values['always_compact_view_gc'] != 'False':
255                        gajim.config.set('always_hide_groupchat_buttons', True)
256               
257                for account in gajim.config.get_per('accounts'):
258                        proxies_str = gajim.config.get_per('accounts', account,
259                                'file_transfer_proxies')
260                        proxies = proxies_str.split(',')
261                        for i in range(0, len(proxies)):
262                                proxies[i] = proxies[i].strip()
263                        for wrong_proxy in ['proxy65.jabber.autocom.pl', 
264                                'proxy65.jabber.ccc.de']: 
265                                if wrong_proxy in proxies:
266                                        proxies.remove(wrong_proxy)
267                        if not 'transfer.jabber.freenet.de' in proxies:
268                                proxies.append('transfer.jabber.freenet.de')
269                        proxies_str = ', '.join(proxies)
270                        gajim.config.set_per('accounts', account, 'file_transfer_proxies',
271                                proxies_str)
272                # create unread_messages table if needed
273                self.assert_unread_msgs_table_exists()
274
275                gajim.config.set('version', '0.10')
276
277        def update_config_to_01011(self):
278                if self.old_values.has_key('print_status_in_muc') and \
279                        self.old_values['print_status_in_muc'] in (True, False):
280                        gajim.config.set('print_status_in_muc', 'in_and_out')
281                gajim.config.set('version', '0.10.1.1')
282
283        def update_config_to_01012(self):
284                # See [6456]
285                if self.old_values.has_key('emoticons_theme') and \
286                        self.old_values['emoticons_theme'] == 'Disabled':
287                        gajim.config.set('emoticons_theme', '')
288                gajim.config.set('version', '0.10.1.2')
289
290        def update_config_to_01013(self):
291                '''create table transports_cache if there is no such table'''
292                #FIXME see #2812
293                back = os.getcwd()
294                os.chdir(logger.LOG_DB_FOLDER)
295                con = sqlite.connect(logger.LOG_DB_FILE)
296                os.chdir(back)
297                cur = con.cursor()
298                try:
299                        cur.executescript(
300                                '''
301                                CREATE TABLE transports_cache (
302                                        transport TEXT UNIQUE,
303                                        type INTEGER
304                                );
305                                '''
306                        )
307                        con.commit()
308                except sqlite.OperationalError, e:
309                        pass
310                con.close()
311                gajim.config.set('version', '0.10.1.3')
312
313        def update_config_to_01014(self):
314                '''apply indeces to the logs database'''
315                print _('migrating logs database to indices')
316                #FIXME see #2812
317                back = os.getcwd()
318                os.chdir(logger.LOG_DB_FOLDER)
319                con = sqlite.connect(logger.LOG_DB_FILE)
320                os.chdir(back)
321                cur = con.cursor()
322                # apply indeces
323                try:
324                        cur.executescript(
325                                '''
326                                CREATE INDEX idx_logs_jid_id_kind ON logs (jid_id, kind);
327                                CREATE INDEX idx_unread_messages_jid_id ON unread_messages (jid_id);
328                                '''
329                        )
330
331                        con.commit()
332                except:
333                        pass
334                con.close()
335                gajim.config.set('version', '0.10.1.4')
336
337        def update_config_to_01015(self):
338                '''clean show values in logs database'''
339                #FIXME see #2812
340                back = os.getcwd()
341                os.chdir(logger.LOG_DB_FOLDER)
342                con = sqlite.connect(logger.LOG_DB_FILE)
343                os.chdir(back)
344                cur = con.cursor()
345                status = dict((i[5:].lower(), logger.constants.__dict__[i]) for i in \
346                        logger.constants.__dict__.keys() if i.startswith('SHOW_'))
347                for show in status:
348                        cur.execute('update logs set show = ? where show = ?;', (status[show],
349                                show))
350                cur.execute('update logs set show = NULL where show not in (0, 1, 2, 3, 4, 5);')
351                con.commit()
352                cur.close() # remove this in 2007 [pysqlite old versions need this]
353                con.close()
354                gajim.config.set('version', '0.10.1.5')
355               
356        def update_config_to_01016(self):
357                '''#2494 : Now we play gc_received_message sound even if
358                notify_on_all_muc_messages is false. Keep precedent behaviour.'''
359                if self.old_values.has_key('notify_on_all_muc_messages') and \
360                self.old_values['notify_on_all_muc_messages'] == 'False' and \
361                gajim.config.get_per('soundevents', 'muc_message_received', 'enabled'):
362                        gajim.config.set_per('soundevents',\
363                                'muc_message_received', 'enabled', False)
364                gajim.config.set('version', '0.10.1.6')
365
366        def update_config_to_01017(self):
367                '''trayicon_notification_on_new_messages ->
368                trayicon_notification_on_events '''
369                if self.old_values.has_key('trayicon_notification_on_new_messages'):
370                        gajim.config.set('trayicon_notification_on_events',
371                                self.old_values['trayicon_notification_on_new_messages'])
372                gajim.config.set('version', '0.10.1.7')
373
374        def update_config_to_01018(self):
375                '''chat_state_notifications -> outgoing_chat_state_notifications'''
376                if self.old_values.has_key('chat_state_notifications'):
377                        gajim.config.set('outgoing_chat_state_notifications',
378                                self.old_values['chat_state_notifications'])
379                gajim.config.set('version', '0.10.1.8')
380
381        def update_config_to_01101(self):
382                '''fill time_stamp from before_time and after_time'''
383                if self.old_values.has_key('before_time'):
384                        gajim.config.set('time_stamp', '%s%%X%s ' % (
385                                self.old_values['before_time'], self.old_values['after_time']))
386                gajim.config.set('version', '0.11.0.1')
387
388        def update_config_to_01102(self):
389                '''fill time_stamp from before_time and after_time'''
390                if self.old_values.has_key('ft_override_host_to_send'):
391                        gajim.config.set('ft_add_hosts_to_send',
392                                self.old_values['ft_override_host_to_send'])
393                gajim.config.set('version', '0.11.0.2')
394       
395        def update_config_to_01111(self):
396                '''always_hide_chatbuttons -> compact_view'''
397                if self.old_values.has_key('always_hide_groupchat_buttons') and \
398                self.old_values.has_key('always_hide_chat_buttons'):
399                        gajim.config.set('compact_view', self.old_values['always_hide_groupchat_buttons'] and \
400                        self.old_values['always_hide_chat_buttons'])
401                gajim.config.set('version', '0.11.1.1')
402
403        def update_config_to_01112(self):
404                '''gtk+ theme is renamed to default'''
405                if self.old_values.has_key('roster_theme') and \
406                self.old_values['roster_theme'] == 'gtk+':
407                        gajim.config.set('roster_theme', _('default'))
408                gajim.config.set('version', '0.11.1.2')
409
410        def update_config_to_01113(self):
411                # copy&pasted from update_config_to_01013
412                back = os.getcwd()
413                os.chdir(logger.LOG_DB_FOLDER)
414                con = sqlite.connect(logger.LOG_DB_FILE)
415                os.chdir(back)
416                cur = con.cursor()
417                try:
418                        cur.executescript(
419                                '''
420                                CREATE TABLE caps_cache (
421                                        node TEXT,
422                                        ver TEXT,
423                                        ext TEXT,
424                                        data BLOB
425                                );
426                                '''
427                        )
428                        con.commit()
429                except sqlite.OperationalError, e:
430                        pass
431                con.close()
432                gajim.config.set('version', '0.11.1.3')
433
434        def update_config_to_01114(self):
435                # add default theme if it doesn't exist
436                d = ['accounttextcolor', 'accountbgcolor', 'accountfont',
437                        'accountfontattrs', 'grouptextcolor', 'groupbgcolor', 'groupfont',
438                        'groupfontattrs', 'contacttextcolor', 'contactbgcolor', 'contactfont',
439                        'contactfontattrs', 'bannertextcolor', 'bannerbgcolor', 'bannerfont', 
440                        'bannerfontattrs']
441                theme_name = _('default')
442                if theme_name not in gajim.config.get_per('themes'):
443                        gajim.config.add_per('themes', theme_name)
444                        if gajim.config.get_per('themes', 'gtk+'):
445                                # copy from old gtk+ theme
446                                for o in d:
447                                        val = gajim.config.get_per('themes', 'gtk+', o)
448                                        gajim.config.set_per('themes', theme_name, o, val)
449                                gajim.config.del_per('themes', 'gtk+')
450                        else:
451                                # copy from default theme
452                                theme = gajim.config.themes_default[theme_name]
453                                for o in d:
454                                        gajim.config.set_per('themes', theme_name, o, theme[d.index(o)])
455                gajim.config.set('version', '0.11.1.4')
Note: See TracBrowser for help on using the browser.