def on_pre_close(self, view):
if view.file_name() is None:
return
window = view.window()
this_project_path = find_project_dir(view)
def perform():
all_views = [view for win in sublime.windows() for view in win.views()]
all_project_paths = [find_project_dir(v) for v in all_views]
all_project_paths = [p for p in all_project_paths if p is not None]
all_project_paths = list(set(all_project_paths))
if this_project_path not in all_project_paths:
stop_server(this_project_path)
window.status_message('Closed server for path:' + this_project_path)
# delay server closing for 0.5s, because we may be "switching" between files
sublime.set_timeout(perform, 500)
python类set_timeout()的实例源码
def run(self, i):
if not self.thread.is_alive():
if hasattr(self.thread, 'result') and not self.thread.result:
sublime.status_message('')
return
sublime.status_message(self.success_message)
if self.callback != None:
self.callback()
return
before = i % self.size
after = (self.size - 1) - before
sublime.status_message('%s [%s=%s]' % \
(self.message, ' ' * before, ' ' * after))
if not after:
self.addend = -1
if not before:
self.addend = 1
i += self.addend
sublime.set_timeout(lambda: self.run(i), 100)
def detect(view, file_name, cnt):
if not file_name or not os.path.exists(file_name) or os.path.getsize(file_name) == 0:
return
encoding = encoding_cache.pop(file_name)
if encoding:
sublime.set_timeout(lambda: init_encoding_vars(view, encoding, detect_on_fail=True), 0)
return
sublime.set_timeout(lambda: view.set_status('origin_encoding', 'Detecting encoding, please wait...'), 0)
detector = UniversalDetector()
fp = open(file_name, 'rb')
for line in fp:
# cut MS-Windows CR code
line = line.replace(b'\r',b'')
detector.feed(line)
cnt -= 1
if detector.done or cnt == 0:
break
fp.close()
detector.close()
encoding = detector.result['encoding']
if encoding:
encoding = encoding.upper()
confidence = detector.result['confidence']
sublime.set_timeout(lambda: check_encoding(view, encoding, confidence), 0)
def _run(self, thread, count=0):
"""Evaluate environment in a separate thread and show an activity
indicator. Inspect thread at regular intervals until it's finished, at
which point `make_requests` can be invoked. Return if thread times out.
"""
REFRESH_MULTIPLIER = 2
activity = self.get_activity_indicator(count//REFRESH_MULTIPLIER, self.ACTIVITY_SPACES)
if count > 0: # don't distract user with RequesterEnv status if env can be evaluated quickly
self.view.set_status('requester.activity', '{} {}'.format('RequesterEnv', activity))
if thread.is_alive():
timeout = self.config.get('timeout_env', None)
if timeout is not None and count * self.REFRESH_MS/REFRESH_MULTIPLIER > timeout * 1000:
sublime.error_message('Timeout Error: environment took too long to parse')
self.view.set_status('requester.activity', '')
return
sublime.set_timeout(lambda: self._run(thread, count+1), self.REFRESH_MS/REFRESH_MULTIPLIER)
else:
requests = self.get_requests()
self.view.set_status('requester.activity', '')
self.make_requests(requests, self._env)
def on_close(self, view):
if view.settings().get('auto_close_empty_groups') is not True:
return
def run():
w = get_window()
reset_layouts = False
for group in range(w.num_groups()):
if len(w.views_in_group(group)) == 0:
reset_layouts = True
if reset_layouts:
w.set_layout({
"cols": [0.0, 1.0],
"rows": [0.0, 1.0],
"cells": [[0, 0, 1, 1]]
})
sublime.set_timeout(run, 50)
def run(self, edit, event):
if self.symbol_details:
view_path = self.symbol_details[0]
focus_region = self.symbol_details[1]
# collapse the region to a single point, the region start
focus_region = sublime.Region(focus_region.begin(), focus_region.begin())
# get the view with this path
view = sublime.active_window().find_open_file(view_path)
if view:
self.showSymbol(view, focus_region)
else:
# weird issue, but unless we open the file with 'ENCODED_POSITION' it won't scroll afterwards
# https://github.com/SublimeTextIssues/Core/issues/538
view = sublime.active_window().open_file("%s:%d:%d" % (view_path, 1, 0), sublime.ENCODED_POSITION)
def viewLoadedTimeout():
# we can run methods only on loaded views
if not view.is_loading():
self.showSymbol(view, focus_region)
else:
sublime.set_timeout(viewLoadedTimeout, 100)
# open is asynchronous, wait for a bit and then try to focus
sublime.set_timeout(viewLoadedTimeout, 100)
def run(self):
self.menu = [
"0. Reload Cache",
"1. Search All",
"2. SObject Data",
"3. SObject Setting",
"4. ApexClass",
"5. Trigger",
"6. VisualForce Page",
"7. VisualForce Components",
"8. Email Template",
"9. Static Resource"
# "10. Workflow Rule",
# "11. Validate Rule"
]
sublime.set_timeout(lambda:self.window.show_quick_panel(self.menu, self.select_menu), 10)
def create_codemap_group():
"""Adds a column on the right, and scales down the layout."""
w = win()
layout = win().get_layout()
cols = layout['cols']
cells = layout['cells']
last_col = len(cols) - 1
last_row = len(layout['rows']) - 1
width = 1 - settings().get("codemap_width")
for i, col in enumerate(cols):
if col > 0:
cols[i] = col*width
cols.append(1)
newcell = [last_col, 0, last_col + 1, last_row]
cells.append(newcell)
groups = w.num_groups()
w.run_command("set_layout", layout)
sublime.set_timeout(lambda: Mapper.block_max_pane(False), 10)
return (groups + 1)
# -----------------
def reset_layout():
"""Removes the Code Map group, and scales up the layout."""
w = win()
layout = w.get_layout()
cols = layout['cols']
width = 1 - settings().get("codemap_width")
alone_in_group = len(win().views_in_group(CodeMapListener.map_group)) == 0
if alone_in_group:
for i, col in enumerate(cols):
if col > 0:
cols[i] = col/width
cols[-2] = 1.0
del cols[-1]
del layout['cells'][-1]
Mapper.block_max_pane(True)
w.run_command("set_layout", layout)
sublime.set_timeout(lambda: Mapper.block_max_pane(False), 10)
# -----------------
def ensure_reload():
"""
Ensure all modules reload to initialize plugin successfully.
"""
start_upgrade_msg = "Do not close the Sublime Text. Upgrading {}".format(
PACKAGE_NAME
)
finish_upgrade_msg = "{} upgrade finished.".format(PACKAGE_NAME)
active_view = sublime.active_window().active_view()
active_view.set_status("afi_status", start_upgrade_msg)
def erase_status():
active_view.erase_status("afi_status")
def reload():
sublime.run_command("afi_reload")
active_view.set_status("afi_status", finish_upgrade_msg)
sublime.set_timeout(erase_status, 2000)
sublime.set_timeout_async(reload, 5000)
def confirm(self, paths, display_paths):
import functools
window = sublime.active_window()
window.show_input_panel("BUG!", '', '', None, None)
window.run_command('hide_panel');
yes = []
yes.append('Yes, delete the selected items.');
for item in display_paths:
yes.append(item);
no = []
no.append('No');
no.append('Cancel the operation.');
while len(no) != len(yes):
no.append('');
if sublime.platform() == 'osx':
sublime.set_timeout(lambda:window.show_quick_panel([yes, no], functools.partial(self.on_confirm, paths)), 200);
else:
window.show_quick_panel([yes, no], functools.partial(self.on_confirm, paths))
def confirm(self, paths, display_paths):
import functools
window = sublime.active_window()
window.show_input_panel("BUG!", '', '', None, None)
window.run_command('hide_panel');
yes = []
yes.append('Yes, empty the selected items.');
for item in display_paths:
yes.append(item);
no = []
no.append('No');
no.append('Cancel the operation.');
while len(no) != len(yes):
no.append('');
if sublime.platform() == 'osx':
sublime.set_timeout(lambda:window.show_quick_panel([yes, no], functools.partial(self.on_confirm, paths)), 200);
else:
window.show_quick_panel([yes, no], functools.partial(self.on_confirm, paths))
def on_select(self, index: int, transient: bool=False) -> None:
"""Called when an option is been made in the quick panel
"""
if index == -1:
self._restore_view()
return
cluster = self.last_cluster
node = cluster[index]
if transient and 'options' in node:
return
if 'options' in node:
self.prev_cluster = self.last_cluster
opts = node['options'][:]
opts.insert(0, {'title': '<- Go Back', 'position': 'back'})
sublime.set_timeout(lambda: self.show(opts), 0)
else:
if node['position'] == 'back' and not transient:
sublime.set_timeout(lambda: self.show(self.prev_cluster), 0)
elif node['position'] != 'back':
Jumper(self.view, node['position']).jump(transient)
def _toggle_indicator(self) -> None:
"""Toggle mark indicator to focus the cursor
"""
path, line, column = self.position.rsplit(':', 2)
pt = self.view.text_point(int(line) - 1, int(column))
region_name = 'anaconda.indicator.{}.{}'.format(
self.view.id(), line
)
for i in range(3):
delta = 300 * i * 2
sublime.set_timeout(lambda: self.view.add_regions(
region_name,
[sublime.Region(pt, pt)],
'comment',
'bookmark',
sublime.DRAW_EMPTY_AS_OVERWRITE
), delta)
sublime.set_timeout(
lambda: self.view.erase_regions(region_name),
delta + 300
)
def _toggle_indicator(self, lineno: int =0, columno: int =0) -> None:
"""Toggle mark indicator for focus the cursor
"""
pt = self.text.view.text_point(lineno - 1, columno)
region_name = 'anaconda.indicator.{}.{}'.format(
self.text.view.id(), lineno
)
for i in range(3):
delta = 300 * i * 2
sublime.set_timeout(lambda: self.text.view.add_regions(
region_name,
[sublime.Region(pt, pt)],
'comment',
'bookmark',
sublime.DRAW_EMPTY_AS_OVERWRITE
), delta)
sublime.set_timeout(
lambda: self.text.view.erase_regions(region_name),
delta + 300
)
def initialize_timeout(self) -> None:
"""Initialize the timeouts if any
"""
def _timeout_callback(*args: Any, **kwargs: Any) -> None:
"""Defualt timeout callback dummy method, can be overriden
"""
raise RuntimeError('Timeout occurred on {}'.format(self.hexid))
def _on_timeout(func: Callable, *args: Any, **kwargs: Any) -> None:
"""We need this wrapper to don't call timeout by accident
"""
if self._status is CallbackStatus.unfired:
self.status = CallbackStatus.timed_out
func(*args, **kwargs)
if self.timeout > 0:
self.waiting_for_timeout = True
callback = self.callbacks.get('timed_out', _timeout_callback)
sublime.set_timeout(
partial(_on_timeout, callback), self.timeout * 1000
)
def lint(self) -> None:
view = sublime.active_window().active_view()
if get_settings(view, 'anaconda_linting_behaviour') != 'always':
if not self.check_auto_lint:
self.check_auto_lint = True
return
delay = get_settings(view, 'anaconda_linter_delay', 0.5)
valid_code = is_code(view, lang=self.lang.lower())
if not ANACONDA['ALREADY_LINTED'] and valid_code:
if time.time() - ANACONDA['LAST_PULSE'] >= delay:
ANACONDA['ALREADY_LINTED'] = True
self.run_linter(view)
if not self._force_non_auto:
sublime.set_timeout(lambda: self.lint(), int(delay * 1000))
def _focus_error_in_view(self, view, point, set_cursor=True):
if view.is_loading():
sublime.set_timeout(lambda: self._focus_error_in_view(view, point, set_cursor), 100)
return
else:
a = view.text_point(*point[0])
b = view.text_point(*point[1])
region = sublime.Region(a,b)
Debug('focus', 'Error click -> _focus_error_in_view %i, %s' % (view.id(), view.file_name()))
view.window().focus_view(view)
Debug('focus', "show_at_center, Region @pos %i, (%s -> %s)" % (region.begin(), point[0], point[1]))
view.show_at_center(region)
draw = sublime.DRAW_NO_FILL
view.add_regions('typescript-error-hint', [region], 'invalid', 'dot')
# redraw region in 50ms because selection modification will remove it
sublime.set_timeout(lambda: view.add_regions('typescript-error-hint', [region], 'invalid', 'dot'), 50)
if set_cursor:
sel = view.sel()
sel.clear()
sel.add(a)
def _wait_for_finish_and_notify_user(self, i=1, dir=-1):
""" Displays animated Message as long as TSS is initing. Is recoursive function. """
if self.get_initialisation_error_message():
sublime.error_message('Typescript initializion error for : %s\n >>> %s\n ArcticTypescript is disabled until you restart sublime.'
% (self.project.tsconfigfile, self.get_initialisation_error_message()))
set_plugin_temporarily_disabled()
return
if not self.is_initialized():
(i, dir) = self._display_animated_init_message(i, dir)
# recursive:
sublime.set_timeout(lambda: self._wait_for_finish_and_notify_user(i, dir), 100)
else:
# starting finished ->
MESSAGE.show('Typescript project intialized for file : %s' % self.project.tsconfigfile, True, with_panel=False)
self.project.on_services_started()
def _show_and_action(self):
""" Show quick dialog and execute action """
# every message must consist of the same number of lines
max_lines = 0
for m in self.messages:
max_lines = max(max_lines, len(m))
for m in self.messages:
while len(m) < max_lines:
m.append('')
def on_select(i):
#self.window.run_command("hide_overlay")
if i == -1:
Debug('project+', '-1: Quick panel canceled')
sublime.set_timeout(self._cleanup, 50)
if self.action_cancel is not None:
sublime.set_timeout(self.action_cancel, 50)
elif i >= 0:
if self.actions[i] is not None:
sublime.set_timeout(self.actions[i], 50)
elif self.action_default is not None:
sublime.set_timeout(self.action_default, 50)
Debug('project+', 'Nr %i selected' % i)
self.window.show_quick_panel(self.messages, on_select)
def on_load(self, view):
if view.settings().get("_anf_new", False):
absolute_file_path = view.file_name()
if absolute_file_path is None:
return
file_name = self.get_basename(absolute_file_path)
_, full_extension = os.path.splitext(file_name)
if len(full_extension) == 0:
extension = file_name
else:
extension = full_extension[1:]
settings = get_settings(view)
if extension in settings.get(FILE_TEMPLATES_SETTING):
template = settings.get(FILE_TEMPLATES_SETTING)[extension]
if type(template) == list:
if len(template) == 1:
view.run_command("insert_snippet", {"contents": self.get_snippet_from_file(template[0])})
else:
entries = list(map(self.get_basename, template))
self.entries = list(map(self.expand_path, template))
self.view = view
sublime.set_timeout(lambda: view.window().show_quick_panel(entries, self.quick_panel_selection), 10)
else:
view.run_command("insert_snippet", {"contents": template})
view.settings().set("_anf_new", "")
def show_progress(message, status_key, view=None):
view = view if view else sublime.active_window().active_view()
counter = 0
def progress():
nonlocal counter
if counter == -1:
view.set_status(status_key, '')
return
counter += 1 % 1000
# Pad with spaces so it reserves space in the status bar.
view.set_status(status_key, message + '{:<3}'.format('.' * (counter % 3 + 1)))
sublime.set_timeout(progress, 350)
sublime.set_timeout(progress, 100)
def dispose():
nonlocal counter
counter = -1
return dispose
def service_text_queue(self):
self.text_queue_lock.acquire()
try:
if len(self.text_queue) == 0:
return
str = self.text_queue.popleft()
is_empty = (len(self.text_queue) == 0)
finally:
self.text_queue_lock.release()
self.append_data_to_output_view(str)
if not is_empty:
sublime.set_timeout(self.service_text_queue, 1)
def blink(times=4, delay=55):
prefs = sublime.load_settings('Preferences.sublime-settings')
if prefs.get('vintageous_visualbell') is False:
return
v = sublime.active_window().active_view()
settings = v.settings()
# Ensure we leave the setting as we found it.
times = times if (times % 2) == 0 else times + 1
def do_blink():
nonlocal times
if times > 0:
settings.set('highlight_line', not settings.get('highlight_line'))
times -= 1
sublime.set_timeout(do_blink, delay)
do_blink()
def anim_loading(self):
if self.loading > 0:
self.loading_anim = (self.loading_anim + 1) % 8
char = '????????'[self.loading_anim]
html = '''<body id="loader">
<style>
.spinner {
display: inline;
color: var(--redish);
}
</style>
Loading <span class="spinner">%s</span></body>''' % char
self.loader = sublime.Phantom(sublime.Region(len(self.server['remote_path'])), html, sublime.LAYOUT_INLINE)
self.phantom_set.update([self.loader, self.phantom] if self.phantom else [self.loader])
sublime.set_timeout(self.anim_loading, 100)
else:
print('removing anim')
self.phantom_set.update([self.phantom] if self.phantom else [])
def run(self, i):
if not self.thread.is_alive():
if hasattr(self.thread, 'result') and not self.thread.result:
sublime.status_message('')
return
sublime.status_message(self.success_message)
return
before = i % self.size
after = (self.size - 1) - before
sublime.status_message('%s [%s=%s]' % \
(self.message, ' ' * before, ' ' * after))
if not after:
self.addend = -1
if not before:
self.addend = 1
i += self.addend
sublime.set_timeout(lambda: self.run(i), 100)
def run(self, edit):
sel = self.view.sel()[0]
self.view.insert(edit, sel.end(), '.')
if not isJavaFile(self.view):
return
findClassCompletions(self.view, sel)
imLen = len(instanceMethodCompletions)
ifLen = len(instanceFieldCompletions)
smLen = len(staticMethodCompletions)
sfLen = len(staticFieldCompletions)
if imLen == 0 and smLen == 0 and ifLen == 0 and sfLen == 0:
return
self.view.run_command('hide_auto_complete')
def show_auto_complete():
self.view.run_command('auto_complete', {
'disable_auto_insert': True,
'api_completions_only': True,
'next_completion_if_showing': False,
'auto_complete_commit_on_tab': True
})
sublime.set_timeout(show_auto_complete, 0)
def tick(self, position):
current_view = self.window.active_view()
if self.tick_view is not None and current_view != self.tick_view:
self.tick_view.erase_status(self.key)
self.tick_view = None
if not self.thread.is_alive():
current_view.erase_status(self.key)
return
text = "%s [%s]" % (self.prefix, self.spin_text[position])
position = (position + 1) % len(self.spin_text)
current_view.set_status(self.key, text)
if self.tick_view is None:
self.tick_view = current_view
sublime.set_timeout(lambda: self.tick(position), 250)
###----------------------------------------------------------------------------
def check_thread(self, thread, i=0, dir=1):
"""Check if the thread is still running."""
before = i % 8
after = (7) - before
if not after:
dir = -1
if not before:
dir = 1
i += dir
self.view.set_status(
'flow_loader',
'FlowType [%s=%s]' % (' ' * before, ' ' * after)
)
if thread.is_alive():
return sublime.set_timeout(lambda: self.check_thread(
thread, i, dir), 100)
self.view.erase_status('flow_loader')
self.handle_process(thread.returncode, thread.stdout, thread.stderr)
def _go(self):
if self.going == 0:
return sublime.status_message(self.final_message)
msg = '['
msg += ' ' * self.pos
msg += '='
msg += ' ' * (self.length - self.pos)
msg += '] ' + self.loading_message
msg = '[{}={}] {}'.format(' ' * self.pos, ' ' * (self.length - self.pos), self.loading_message)
self.pos += self.going
if self.pos >= self.length:
self.going = -1
if self.pos <= 0:
self.going = 1
sublime.status_message(msg)
sublime.set_timeout(self._go, 100)