Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Remove unused code, use one object to deal with settings, fix bugs

  • Loading branch information...
commit 84281563f41be73afe38c0392329fd58f714aa00 1 parent 05877d7
Alexandr Skurikhin Name authored a.sk committed
View
22 livecolors.py
@@ -17,7 +17,7 @@
from livecss.theme import theme
from livecss.utils import (need_colorization, need_uncolorization, generate_default_settings,
is_colorizable, generate_menu, colorize_on_select_new_theme)
-from livecss.settings import LocalSettings, settings
+from livecss.settings import settings_for, toggle
class CssColorizeCommand(sublime_plugin.TextCommand):
@@ -39,7 +39,6 @@ def __init__(self):
def on_load(self, view):
# set hook to recolorize if different theme was chosen
theme.on_select_new_theme(lambda: colorize_on_select_new_theme(view))
-
if need_colorization(view):
colorize_file(view, state_for(view))
@@ -56,8 +55,9 @@ def on_activated(self, view):
generate_menu(view)
state = state_for(view)
+ state.focused = True
if state and state.theme_path:
- # set file's own theme path, because we use one per css file
+ # set file's own theme path, because we use one per file
theme.set(state.theme_path)
if need_colorization(view):
@@ -71,12 +71,12 @@ class ToggleLocalLiveCssCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
state = state_for(view)
- autocolorize_locally = LocalSettings(view).local_on
- if autocolorize_locally:
+ settings = settings_for(view)
+ if settings.local.autocolorize:
uncolorize_file(view, state)
else:
colorize_file(view, state, True)
- LocalSettings(view).local_on = not LocalSettings(view).local_on
+ toggle(settings.local, 'autocolorize')
generate_menu(view)
def is_visible(self):
@@ -87,14 +87,12 @@ class ToggleGlobalLiveCssCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
state = state_for(view)
- autocolorize_locally = LocalSettings(view).local_on
- autocolorize_globally = settings['autocolorization']
- if autocolorize_globally and autocolorize_locally:
+ settings = settings_for(view)
+ if settings.glob.autocolorize and settings.local.autocolorize:
uncolorize_file(view, state)
- elif not autocolorize_globally and autocolorize_locally in ['undefined', False]:
+ elif not settings.glob.autocolorize and settings.local.autocolorize in ['undefined', False]:
colorize_file(view, state, True)
-
- settings['autocolorization'] = not settings['autocolorization']
+ toggle(settings.glob, 'autocolorize')
generate_menu(view)
def is_visible(self):
View
5 livecss/colorizer.py
@@ -39,12 +39,13 @@ def colorize_file(view, state, forse_redraw=False):
if forse_redraw or state.need_generate_theme_file:
colorized_theme_path = generate_theme(uncolorized_path(theme.abspath), colors)
- theme.set(colorized_theme_path)
+ if state.focused:
+ theme.set(colorized_theme_path)
# remove previously used theme if any
rm_theme(state.theme_path)
# associate theme with file
- state.theme_path = theme.abspath
+ state.theme_path = colorized_theme_path
def uncolorize_file(view, state):
View
63 livecss/helpers.py
@@ -4,68 +4,17 @@
~~~~~~~~~
This module implements some python helper objects.
-
- Usage examples:
- --------------
- >>> checker = AvailabilityChecker("checkme")
- >>> "checkme" in checker
- True
- >>> checker = AvailabilityChecker(lambda s: s.startswith('_'))
- >>> "_checkme" in checker
- True
- >>> checker = AvailabilityChecker((lambda s: s.startswith('_'), 4))
- >>> "__checkme" in checker
- True
- >>> 4 in checker
- True
- >>> 5 in checker
- False
+ > import re
+ > one_of_os = one_of(['win', 'mac', 'linux'])
+ > bool(re.match(one_of_os, 'win'))
+ True
"""
-class AvailabilityChecker(object):
- """Provides convenient a in b checking.
- It works by applying given `comparators` to a comparing object.
- If item in `comparators` is not callable,
- checks if comparing object is equal to the item in `comparators`
- If `comparators` > 1, iterate over `comparators`, till first match.
-
- :param comparators: sequence of `comparators`,
- where one `comparator` is expected to be a comparator function,
- otherwise is turned into one, using :attr:`make_eq`
-
- """
-
- def __init__(self, comparators):
- if not isinstance(comparators, list) and \
- not isinstance(comparators, tuple):
- comparators = [comparators]
-
- self._comparators = []
- for cb in comparators:
- if not callable(cb):
- self._comparators.append(make_eq(cb))
- else:
- self._comparators.append(cb)
-
- def __contains__(self, attr):
- matches = []
- for cb in self._comparators:
- try:
- matches.append(cb(attr))
- except AttributeError:
- # if cb was applied to not supported type
- continue
- return any(matches)
-
-
-escape = lambda s: "\'" + s + "\'"
-
-make_eq = lambda x: lambda y: x == y
-
-
def one_of(seq):
"Return regex which mathes one element of seq"
seq = [r'\b%s\b' % el for el in seq]
return reduce(lambda x, y: str(x) + '|' + str(y), seq)
+
+escape = lambda s: "\'" + s + "\'"
View
21 livecss/settings.py
@@ -1,16 +1,17 @@
+import sublime
+
from .wrappers import PerFileConfig
from .wrappers import Settings
-settings = Settings('LiveCSS.sublime-settings', False)
-
-class LocalSettings(PerFileConfig):
- """Object which wraps ST settings entity.
- Properties started with `global_` are global setting.
- Properties started with `local_` are unique for file.
- Default value is True.
+def settings_for(view):
+ class wrapper:
+ pass
+ if view.__class__ == sublime.View:
+ wrapper.local = PerFileConfig(view.buffer_id(), 'LivecssState.sublime-settings', True)
+ wrapper.glob = Settings('LiveCSS.sublime-settings', False)
+ return wrapper
- """
- def __init__(self, view):
- super(LocalSettings, self).__init__(view.buffer_id(), 'LivecssState.sublime-settings', in_memory=False)
+def toggle(obj, key):
+ setattr(obj, key, not getattr(obj, key))
View
29 livecss/state.py
@@ -70,7 +70,28 @@ def get_highlighted_regions(view, last_highlighted_region):
states = dict()
-def state_for(view):
- if view.buffer_id() not in states:
- states[view.buffer_id()] = State(view)
- return states[view.buffer_id()]
+class state_for(object):
+ """Store and retrieve state"""
+ def __init__(self, view):
+ """Create or retrieve state for given view
+ self.focused = unique attribute for all states
+ """
+ if view.buffer_id() not in states:
+ states[view.buffer_id()] = State(view)
+ self.view = view
+
+ def __getattribute__(self, attr):
+ if attr == 'focused':
+ bid, is_focused = states['focused']
+ if bid == self.view.buffer_id():
+ return True
+ elif attr == 'view' or attr.startswith('__'):
+ return object.__getattribute__(self, attr)
+ return getattr(states[self.view.buffer_id()], attr)
+
+ def __setattr__(self, attr, value):
+ object.__setattr__(self, attr, value)
+ if attr == 'focused':
+ states['focused'] = [self.view.buffer_id(), value]
+ elif attr != 'view' and not attr.startswith('__'):
+ setattr(states[self.view.buffer_id()], attr, value)
View
2  livecss/theme.py
@@ -9,7 +9,7 @@
"""
# std lib
-from os.path import basename, normpath, relpath, exists
+from os.path import basename, normpath, exists
from random import randint
import os.path
import re
View
35 livecss/utils.py
@@ -17,7 +17,7 @@
from .theme import theme, uncolorized_path
from .colorizer import colorize_file
from .menu import create_menu
-from .settings import LocalSettings, settings
+from .settings import settings_for
def colorize_on_select_new_theme(view):
@@ -31,9 +31,8 @@ def colorize_on_select_new_theme(view):
def generate_menu(view):
- autocolorize_locally = LocalSettings(view).local_on
- autocolorize_globally = settings['autocolorization']
- create_menu(autocolorize_locally, autocolorize_globally)
+ s = settings_for(view)
+ create_menu(s.local.autocolorize, s.glob.autocolorize)
def file_id(view):
@@ -41,6 +40,7 @@ def file_id(view):
def is_colorizable(view):
+ s = settings_for(view)
point = view.sel()[0].begin()
file_scope = view.scope_name(point).split()[0]
file_name = view.file_name()
@@ -50,39 +50,32 @@ def is_colorizable(view):
file_ext = ""
# if not file_scope is 'source.python':
# return True
- if file_scope in settings['colorized_formats'] or file_ext in settings['colorized_formats']:
+ if file_scope in s.glob.colorized_formats or file_ext in s.glob.colorized_formats:
return True
def need_colorization(view):
if not is_colorizable(view):
return
-
- autocolorize_locally = LocalSettings(view).local_on
- autocolorize_globally = settings['autocolorization']
-
- if autocolorize_globally and autocolorize_locally in ['undefined', True]:
+ s = settings_for(view)
+ if s.glob.autocolorize and s.local.autocolorize in ['undefined', True]:
return True
-
- if not autocolorize_locally:
+ if not s.local.autocolorize:
return False
def need_uncolorization(view):
if not is_colorizable(view):
return
-
- autocolorize_locally = LocalSettings(view).local_on
- autocolorize_globally = settings['autocolorization']
-
- if not autocolorize_globally and autocolorize_locally is 'undefined':
+ s = settings_for(view)
+ if not s.glob.autocolorize and s.local.autocolorize is 'undefined':
return True
-
- if autocolorize_locally:
+ if s.local.autocolorize:
return False
def generate_default_settings():
if not os.path.exists(os.path.join(sublime.packages_path(), 'User', 'LiveCSS.sublime-settings')):
- settings['colorized_formats'] = ["source.css", "source.css.less", "source.sass"]
- settings['autocolorization'] = True
+ s = settings_for(False)
+ s.glob.colorized_formats = ["source.css", "source.css.less", "source.sass"]
+ s.glob.autocolorize = True
View
33 livecss/wrappers.py
@@ -9,9 +9,6 @@
"""
import sublime
-# local imports
-from .helpers import AvailabilityChecker
-
class Settings(object):
@@ -62,18 +59,15 @@ class PerFileConfig(object):
"""
- def __init__(self, name, settings_file, in_memory, ignored_attrs=False):
+ def __init__(self, name, settings_file, in_memory):
"""
@param {anytype} name: identification sign
@param {str} settings_file: settings file name
@param {bool} in_memory: save on each attribute setting
- @param {anytype} ignored_attrs: attribute to ignore from storing
- in ST settings object
"""
self._id = str(name)
- self._ignored_attrs = AvailabilityChecker(ignored_attrs)
self._s = Settings(settings_file, in_memory)
if self._id not in self._s:
@@ -81,31 +75,24 @@ def __init__(self, name, settings_file, in_memory, ignored_attrs=False):
def __getattribute__(self, attr):
"""Retrieve attribute from ST settings.
- Ignore underscored and those in ignored_attrs.
-
"""
if attr.startswith("_"):
return object.__getattribute__(self, attr)
- if attr not in self._ignored_attrs:
- # default val is undef
- val = self._s[self._id].get(attr)
- if not isinstance(val, bool):
- val = 'undefined'
- return val
- else:
- return object.__getattribute__(self, attr)
+ # default val is undefined
+ val = self._s[self._id].get(attr)
+ if not isinstance(val, bool):
+ val = 'undefined'
+ return val
def __setattr__(self, attr, value):
"""Always uses standard attribute setter
- If it's not underscored or found in ignored,
- it stores in ST settings
+ If it's not underscored it is stored in ST settings
"""
object.__setattr__(self, attr, value)
if not attr.startswith("_"):
- if not attr in self._ignored_attrs:
- s = self._s[self._id]
- s[attr] = value
- self._s[self._id] = s
+ s = self._s[self._id]
+ s[attr] = value
+ self._s[self._id] = s
Please sign in to comment.
Something went wrong with that request. Please try again.