def start_indicator(view, msg) -> None: global activity_indicator if activity_indicator: activity_indicator.label = msg else: activity_indicator = ActivityIndicator(view, msg) activity_indicator.start()
def _start_indicator(self, msg: str = "") -> None: if self._activity_indicator: self._activity_indicator.label = msg else: view = sublime.active_window().active_view() if view: self._activity_indicator = ActivityIndicator(view, msg) self._activity_indicator.start()
class LspIntelephensePlugin(NpmClientHandler): package_name = __package__.split(".")[0] server_directory = "language-server" server_binary_path = os.path.join(server_directory, "node_modules", "intelephense", "lib", "intelephense.js") def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._activity_indicator = None # type: Optional[ActivityIndicator] @classmethod def get_additional_variables(cls) -> Optional[Dict[str, str]]: variables = super().get_additional_variables() or {} variables.update({ "cache_path": sublime.cache_path(), "home": os.path.expanduser("~"), "package_storage": cls.package_storage(), "temp_dir": tempfile.gettempdir(), }) return variables @classmethod def minimum_node_version(cls) -> Tuple[int, int, int]: return (10, 0, 0) # ---------------- # # message handlers # # ---------------- # @notification_handler("indexingStarted") def handle_indexing_started(self, params: None) -> None: self._start_indicator("{}: Indexing...".format(self.package_name)) @notification_handler("indexingEnded") def handle_indexing_ended(self, params: None) -> None: self._stop_indicator() # -------------- # # custom methods # # -------------- # def _start_indicator(self, msg: str = "") -> None: if self._activity_indicator: self._activity_indicator.label = msg else: view = sublime.active_window().active_view() if view: self._activity_indicator = ActivityIndicator(view, msg) self._activity_indicator.start() def _stop_indicator(self) -> None: if self._activity_indicator: self._activity_indicator.stop() self._activity_indicator = None
def _install_or_update(cls) -> None: try: with ActivityIndicator( target=sublime.active_window(), label="Downloading TAGML language server binary", ): dest_path = os.path.dirname(cls.binary) os.makedirs(dest_path, exist_ok=True) urlretrieve(url=SERVER_URL, filename=cls.binary) cls.ready = not cls._needs_update_or_installation() if not cls.ready: try: os.remove(cls.binary) except FileNotFoundError: pass raise Exception("CRC error!") else: # clear old server binaries for file_name in os.listdir(dest_path): if os.path.splitext(file_name)[1].lower() != ".jar": continue try: file_path = os.path.join(dest_path, file_name) if not os.path.samefile(file_path, cls.binary): os.remove(file_path) except FileNotFoundError: pass except Exception as error: sublime.error_message( "Error downloading TAGML server binary!\n\n" + str(error)) cls.thread = None
def _download() -> None: debug('Downloading server from', url) target = sublime.active_window() label = 'Downloading PromQL language server' with ActivityIndicator(target, label): try: opener = FancyURLopener() tmp_file, _ = opener.retrieve(url) if not checksum_verified(checksum, tmp_file): debug('Checksum error.') sublime.status_message('Server binary', os.path.basename(tmp_file), 'checkusm error.') return # extract and copy the cache with tarfile.open(tmp_file) as tf: tf.extractall(self._cache_path) os.unlink(tmp_file) self._ready = True except Exception as ex: debug('Failed downloading server:', ex) finally: opener.close()
def download_server(self) -> None: target = sublime.active_window() label = "Downloading zip file..." with ActivityIndicator(target, label): tmp_file, _ = urlretrieve(self._url) self.unpack_server(tmp_file) os.unlink(tmp_file)
def perform_install() -> None: try: message = '{}: Installing server in path: {}'.format(name, cls.storage_path()) log_and_show_message(message, show_in_status=False) with ActivityIndicator(sublime.active_window(), message): server.install_or_update() log_and_show_message('{}: Server installed. Sublime Text restart is required.'.format(name)) except Exception as exception: log_and_show_message('{}: Server installation error: {}'.format(name, str(exception)))
def test_tick_called(self): target = Mock() indicator = ActivityIndicator(target) with indicator: target.set.assert_called_once_with('[= ]') target.set.reset_mock() import time time.sleep(0.15) target.set.assert_called_once_with('[ = ]')
def run(self, edit, only_selection=True): settings = sublime.load_settings(settings_filename()) binary_path = settings.get(PREF_CLANG_FORMAT_PATH) if not binary_path: binary_path = which(binary_name()) if not binary_path or not is_exe(binary_path): sublime.message_dialog(MISSING_BINARY_MESSAGE % binary_name()) return args = [binary_path, '-fallback-style', style] if self.view.file_name(): args.extend(['-assume-filename', self.view.file_name()]) else: print( 'Checking style without knowing file type. Results might be innacurate!' ) if only_selection: for region in self.view.sel(): region_offset = min(region.a, region.b) region_length = abs(region.b - region.a) args.extend([ '-offset', str(region_offset), '-length', str(region_length) ]) buffer_text = self.view.substr(sublime.Region(0, self.view.size())) encoding = self.view.encoding() encoding = encoding if encoding != 'Undefined' else 'utf-8' stdin = buffer_text.encode(encoding) viewport_pos = self.view.viewport_position() # Show progress indicator if formatting takes longer than 1s. self._indicator = ActivityIndicator(self.view, 'ClangFormat: Formatting...') sublime.set_timeout(self.start_indicator, 1000) start_thread( lambda output: self.on_formatting_success( viewport_pos, output, encoding), self.on_formatting_error, args, stdin)
def _install_dependencies(self, cache_server_path): dependencies_installed = os.path.isdir(os.path.join(cache_server_path, 'node_modules')) if dependencies_installed: self._is_ready = True return # this will be called only when the plugin gets: # - installed for the first time, # - or when updated on package control install_message = '{}: Installing server'.format(self._package_name) log_and_show_message(install_message, show_in_status=False) active_window = sublime.active_window() if active_window: self._activity_indicator = ActivityIndicator(active_window.active_view(), install_message) self._activity_indicator.start() run_command( self._on_install_success, self._on_install_error, ["npm", "install", "--verbose", "--production", "--prefix", cache_server_path, cache_server_path] )
class LspPyrightPlugin(NpmClientHandler): package_name = __package__.split(".")[0] server_directory = "language-server" server_binary_path = os.path.join(server_directory, "node_modules", "pyright", "langserver.index.js") def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._activity_indicator = None # type: Optional[ActivityIndicator] @classmethod def install_in_cache(cls) -> bool: return False @classmethod def minimum_node_version(cls) -> Tuple[int, int, int]: return (12, 0, 0) def on_settings_changed(self, settings: DottedDict) -> None: super().on_settings_changed(settings) if self.get_plugin_setting("dev_environment") == "sublime_text": # add package dependencies into "python.analysis.extraPaths" extraPaths = settings.get("python.analysis.extraPaths") or [ ] # type: List[str] extraPaths.extend(self.find_package_dependency_dirs()) settings.set("python.analysis.extraPaths", extraPaths) # ---------------- # # message handlers # # ---------------- # @notification_handler("pyright/beginProgress") def handle_begin_progress(self, params) -> None: # we don't know why we begin this progress # the reason will be updated in "pyright/reportProgress" self._start_indicator("{}: Working...".format(self.package_name)) @notification_handler("pyright/endProgress") def handle_end_progress(self, params) -> None: self._stop_indicator() @notification_handler("pyright/reportProgress") def handle_report_progress(self, params: List[str]) -> None: self._start_indicator("{}: {}".format(self.package_name, "; ".join(params))) # -------------- # # custom methods # # -------------- # @classmethod def get_plugin_setting(cls, key: str, default: Optional[Any] = None) -> Any: return sublime.load_settings(cls.package_name + ".sublime-settings").get(key, default) @staticmethod def find_package_dependency_dirs() -> List[str]: dep_dirs = sys.path.copy() # move the "Packages/" to the last # @see https://github.com/sublimelsp/LSP-pyright/pull/26#discussion_r520747708 packages_path = sublime.packages_path() dep_dirs.remove(packages_path) dep_dirs.append(packages_path) return [path for path in dep_dirs if os.path.isdir(path)] def _start_indicator(self, msg: str = "") -> None: if self._activity_indicator: self._activity_indicator.label = msg # type: ignore self._activity_indicator.update() else: view = sublime.active_window().active_view() if view: self._activity_indicator = ActivityIndicator( view, msg) # type: ignore self._activity_indicator.start() def _stop_indicator(self) -> None: if self._activity_indicator: self._activity_indicator.stop() self._activity_indicator = None