def wait_for_open(self, dest):
"""Wait for new linter window to open in another thread."""
def open_linter_py():
"""Wait until the new linter window has opened and open linter.py."""
start = datetime.datetime.now()
while True:
time.sleep(0.25)
delta = datetime.datetime.now() - start
# Wait a maximum of 5 seconds
if delta.seconds > 5:
break
window = sublime.active_window()
folders = window.folders()
if folders and folders[0] == dest:
window.open_file(os.path.join(dest, 'linter.py'))
break
sublime.set_timeout_async(open_linter_py, 0)
python类set_timeout_async()的实例源码
def generate_color_scheme(from_reload=True):
"""
Asynchronously call generate_color_scheme_async.
from_reload is True if this is called from the change callback for user settings.
"""
# If this was called from a reload of prefs, turn off the prefs observer,
# otherwise we'll end up back here when ST updates the prefs with the new color.
if from_reload:
from . import persist
def prefs_reloaded():
persist.settings.observe_prefs()
persist.settings.observe_prefs(observer=prefs_reloaded)
# ST crashes unless this is run async
sublime.set_timeout_async(generate_color_scheme_async, 0)
def on_post_save(self, view):
file_name = view.file_name()
if not ReloadPlugin.PACKAGE_NAME in file_name: return
if ReloadPlugin.PLUGIN_PYTHON_FILE in file_name: return
original_file_name = view.file_name()
plugin_python_file = os.path.join(sublime.packages_path(), ReloadPlugin.PLUGIN_PYTHON_FILE)
if not os.path.isfile(plugin_python_file): return
def _open_original_file():
view.window().open_file(original_file_name)
plugin_view = view.window().open_file(plugin_python_file)
print("save", plugin_view.file_name())
plugin_view.run_command("save")
sublime.set_timeout_async(_open_original_file, self.PLUGIN_RELOAD_TIME_MS)
def on_modified(self, view):
"""
"""
sel = view.sel()
if not view.match_selector(sel[0].a, "source.swift"):
return
# clear linting
self.errors = {}
view.erase_regions("swiftkitten.diagnostics")
self.query_id = None
self.pending += 1
def handle_timeout():
self.handle_timeout(view)
sublime.set_timeout_async(handle_timeout, self.delay)
def queue_did_change(view: sublime.View):
buffer_id = view.buffer_id()
buffer_version = 1
pending_buffer = None
if buffer_id in pending_buffer_changes:
pending_buffer = pending_buffer_changes[buffer_id]
buffer_version = pending_buffer["version"] + 1
pending_buffer["version"] = buffer_version
else:
pending_buffer_changes[buffer_id] = {
"view": view,
"version": buffer_version
}
sublime.set_timeout_async(
lambda: purge_did_change(buffer_id, buffer_version), 500)
def on_window_command(self, window, command_name, args):
'''Very unstable switching projects, safety measure'''
reset = ["prompt_open_project_or_workspace",
"prompt_select_workspace",
"open_recent_project_or_workspace",
"close_workspace",
"project_manager",
'close_window']
if ACTIVE and command_name in reset:
# resetting variables and stopping CodeMap until CodeMap file is found again
reset_globals()
sublime.set_timeout_async(lambda: reactivate())
# -----------------
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 get(imageurl, user_callback=None):
cached = get_cache_for(imageurl)
if cached:
return cached
elif imageurl in ImageManager.loading.keys():
# return None (the file is still loading, already made a request)
# return string the base64 of the url (which is going to be cached)
temp_cached = ImageManager.loading[imageurl]
if temp_cached == 404:
return to_base64('404.png')
if temp_cached:
cache(imageurl, temp_cached)
del ImageManager.loading[imageurl]
return temp_cached
else:
# load from internet
ImageManager.loading[imageurl] = None
callback = get_base64_saver(ImageManager.loading, imageurl)
loader = ImageLoader(imageurl, callback)
loader.start()
sublime.set_timeout_async(lambda: loader.join(), TIMEOUT * 1000)
def run(self, changes=None):
# debug('workspace edit', changes)
if changes:
for uri, file_changes in changes.items():
path = uri_to_filename(uri)
view = self.window.open_file(path)
if view:
if view.is_loading():
# TODO: wait for event instead.
sublime.set_timeout_async(
lambda: view.run_command('lsp_apply_document_edit', {'changes': file_changes}),
500
)
else:
view.run_command('lsp_apply_document_edit',
{'changes': file_changes,
'show_status': False})
else:
debug('view not found to apply', path, file_changes)
message = 'Applied changes to {} documents'.format(len(changes))
self.window.status_message(message)
else:
self.window.status_message('No changes to apply to workspace')
def queue_did_change(view: sublime.View):
buffer_id = view.buffer_id()
buffer_version = 1
pending_buffer = None
if buffer_id in pending_buffer_changes:
pending_buffer = pending_buffer_changes[buffer_id]
buffer_version = pending_buffer["version"] + 1
pending_buffer["version"] = buffer_version
else:
pending_buffer_changes[buffer_id] = {
"view": view,
"version": buffer_version
}
sublime.set_timeout_async(
lambda: purge_did_change(buffer_id, buffer_version), 500)
def plugin_loaded() -> None:
"""Called directly from sublime on plugin load
"""
package_folder = os.path.dirname(__file__)
if not os.path.exists(os.path.join(package_folder, 'Main.sublime-menu')):
template_file = os.path.join(
package_folder, 'templates', 'Main.sublime-menu.tpl'
)
with open(template_file, 'r', encoding='utf8') as tplfile:
template = Template(tplfile.read())
menu_file = os.path.join(package_folder, 'Main.sublime-menu')
with open(menu_file, 'w', encoding='utf8') as menu:
menu.write(template.safe_substitute({
'package_folder': os.path.basename(package_folder)
}))
# unload any conflictive package while anaconda is running
sublime.set_timeout_async(monitor_plugins, 0)
if not LOOP_RUNNING:
ioloop.loop()
def update(self, i):
"""Update the progress bar
"""
if self.die:
return
size = 8
pos = i % size
status = '{}={}'.format(' ' * pos, ' ' * ((size - 1) - pos))
sublime.status_message('{} [{}]'.format(
self.messages['start'], status)
)
if not (size - 1) - pos:
self.addition = -1
if not pos:
self.addition = 1
i += self.addition
sublime.set_timeout_async(lambda: self.update(i), 100)
def wait_for_open(self, dest):
"""Wait for new linter window to open in another thread."""
def open_linter_py():
"""Wait until the new linter window has opened and open linter.py."""
start = datetime.datetime.now()
while True:
time.sleep(0.25)
delta = datetime.datetime.now() - start
# Wait a maximum of 5 seconds
if delta.seconds > 5:
break
window = sublime.active_window()
folders = window.folders()
if folders and folders[0] == dest:
window.open_file(os.path.join(dest, 'linter.py'))
break
sublime.set_timeout_async(open_linter_py, 0)
def generate_color_scheme(from_reload=True):
"""
Asynchronously call generate_color_scheme_async.
from_reload is True if this is called from the change callback for user settings.
"""
# If this was called from a reload of prefs, turn off the prefs observer,
# otherwise we'll end up back here when ST updates the prefs with the new color.
if from_reload:
from . import persist
def prefs_reloaded():
persist.settings.observe_prefs()
persist.settings.observe_prefs(observer=prefs_reloaded)
# ST crashes unless this is run async
sublime.set_timeout_async(generate_color_scheme_async, 0)
def update_logs(self):
def __update_logs():
logs_json = self.query_logs()
if not logs_json:
self.poll_url = None
return
self.poll_url = LogManager.get_poll_url(logs_json)
logs_list = logs_json["logs"]
i = len(logs_list) if logs_list else 0
while i > 0:
i -= 1
log = logs_list[i]
if self.last_shown_log and LogManager.logs_are_equal(self.last_shown_log, log):
i += 1
break
while i < len(logs_list):
log = logs_list[i]
self.write_to_console(log)
self.last_shown_log = log
i += 1
sublime.set_timeout_async(__update_logs, 0)
def on_hover(self, view, point, hover_zone):
# Popup only on text
if hover_zone != sublime.HOVER_TEXT:
return
# Check file size to optionnaly disable the feature (finding the information can be quite long)
threshold = view.settings().get('vhdl.hover_max_size',-1)
if view.size() > threshold and threshold!=-1 :
return
# Only show a popup for vhdl, when not in a string of a comment
scope = view.scope_name(point)
if 'source.vhdl' not in scope:
return
if any(w in scope for w in ['comment', 'string', 'keyword']):
return
popup = VhdlTypePopup(view)
sublime.set_timeout_async(lambda r=view.word(point), p=point: popup.show(r,p))
def plugin_loaded():
window.set_status_bar_message("")
window.subscribe(sublime.active_window().active_view())
open_settings_window_if_credentials_are_not_set()
def run_main_loop():
Spotify(
side_effect = window.set_status_bar_message
).run_main_loop(settings_manager)
'''
When sublime starts up and the plugin is enabled,
the server should start on a different thread,
so that sublime doesn't hang until the circuit breaker kicks in
'''
sublime.set_timeout_async(run_main_loop, 5000)
def run(self, callback):
with self._lock:
self._tasks_running += 1
if self._tasks_running == 1:
self._progress_animation = ProgressAnimation(self.tasks_running).start()
def callback_wrapper():
try:
callback()
except Exception as e:
log_exception(
'Background task failed with exception: [{exception}]'.format(
exception=e))
with self._lock:
self._tasks_running -= 1
self.log('tasks running = ' + str(self._tasks_running))
sublime.set_timeout_async(callback_wrapper, 0)
def run(self, edit):
# check whether the lua files
suffix_setting = self.view.settings().get('syntax')
file_suffix = suffix_setting.split('.')[0]
if file_suffix[-3:].lower() != 'lua': return
# get lines of replacement
r = sublime.Region(0, self.view.size())
lines = []
for region in self.view.lines(r):
cache = self.view.substr(region)
lines.append(cache)
# get cursor position before the replacement
selection = self.view.sel()[0].b
row, col = self.view.rowcol(selection)
# replace the content after format
print("Run Lua Format")
self.view.replace(edit, r, lua_format(lines, get_settings()))
# deal cursor position
selection = self.view.full_line(self.view.text_point(row - 1, 0)).b
cursor_pos = sublime.Region(selection, selection)
regions = self.view.sel()
regions.clear()
regions.add(cursor_pos)
sublime.set_timeout_async(lambda: self.view.show(cursor_pos), 0)
def generate_menus(**kwargs):
"""Asynchronously call generate_menus_async."""
sublime.set_timeout_async(generate_menus_async, 0)
def pfile_modified(pfile, view):
pfile.dirty = True
now = time.time()
if now - pfile.last_modified > .5:
pfile.last_modified = now
if is_st2:
sublime.set_timeout(lambda: maybe_save_pfile(pfile, view, now), 5000)
else:
sublime.set_timeout_async(lambda: maybe_save_pfile(pfile, view, now), 5000)
if pfile.cached_completions and sel_start(view.sel()[0]) < pfile.cached_completions[0]:
pfile.cached_completions = None
if pfile.cached_arguments and sel_start(view.sel()[0]) < pfile.cached_arguments[0]:
pfile.cached_arguments = None
def run(self, edit):
sublime.set_timeout_async(self.run_async)
def run(self, edit):
sublime.set_timeout_async(self.run_async)
def on_selection_modified_async(self, view):
self.view = view
sublime.set_timeout_async(
lambda: self.run_check(view)
)
def on_selection_modified_async(self, view):
self.view = view
sublime.set_timeout_async(
lambda: self.run_coverage(view)
)
def on_query_completions(self, view, prefix, locations):
# Return the pending completions and clear them
if self.completions_ready and self.completions:
self.completions_ready = False
return self.completions
sublime.set_timeout_async(
lambda: self.on_query_completions_async(
view, prefix, locations
)
)
def tab_selected(self, selected):
if selected > -1:
if self.is_file[selected]:
self.window.open_file(os.path.join(self.mypath,self.files[selected]))
else:
folder = self.files[selected]
if folder == "`":
folder = ".."
self.mypath = os.path.join(self.mypath, folder)
sublime.set_timeout_async(self.open_for_current_path, 50)
return selected
def make_requests(self, requests, env=None):
"""Make requests concurrently using a `ThreadPool`, which itself runs on
an alternate thread so as not to block the UI.
"""
pools = self.RESPONSE_POOLS
pool = ResponseThreadPool(requests, env, self.MAX_WORKERS) # pass along env vars to thread pool
pools.put(pool)
while pools.qsize() > self.MAX_NUM_RESPONSE_POOLS:
old_pool = pools.get()
old_pool.is_done = True # don't display responses for a pool which has already been removed
sublime.set_timeout_async(pool.run, 0) # run on an alternate thread
sublime.set_timeout(lambda: self.gather_responses(pool), 15)
# small delay to show activity for requests that are returned in less than REFRESH_MS
def handle_responses(self, responses):
"""Invoke the real function on a different thread to avoid blocking UI.
"""
sublime.set_timeout_async(self._handle_responses, 0)
def run(self):
view = self.window.active_view()
url = view.settings().get('requester.request_url', None)
if url is None:
return
sublime.set_timeout_async(lambda: self.show_options(url, view), 0)