chore: minor fixes and renaming

This commit is contained in:
cschen 2025-01-18 20:13:49 +01:00
parent a996e9d558
commit 637ce762a3
8 changed files with 79 additions and 72 deletions

40
main.py
View file

@ -11,22 +11,9 @@ from .plugin.core.session import session
from .plugin.core.workspace import workspaces from .plugin.core.workspace import workspaces
from .plugin.core.buffers import buffers from .plugin.core.buffers import buffers
from .plugin.text_listener import TEXT_LISTENER from .plugin.text_listener import TEXT_LISTENER
from .plugin.input_handlers import SimpleListInput
from .plugin import globals as g from .plugin import globals as g
# We import these just to showcase the commands available.
from .plugin.commands.client import CodempConnectCommand
from .plugin.commands.client import CodempDisconnectCommand
from .plugin.commands.client import CodempCreateWorkspaceCommand
from .plugin.commands.client import CodempDeleteWorkspaceCommand
from .plugin.commands.client import CodempJoinWorkspaceCommand
from .plugin.commands.client import CodempLeaveWorkspaceCommand
from .plugin.commands.client import CodempInviteToWorkspaceCommand
from .plugin.commands.workspace import CodempCreateBufferCommand
from .plugin.commands.workspace import CodempDeleteBufferCommand
from .plugin.commands.workspace import CodempJoinBufferCommand
from .plugin.commands.workspace import CodempLeaveBufferCommand
from .plugin.quickpanel.qpbrowser import QPServerBrowser from .plugin.quickpanel.qpbrowser import QPServerBrowser
from .plugin.quickpanel.qpbrowser import QPWorkspaceBrowser from .plugin.quickpanel.qpbrowser import QPWorkspaceBrowser
@ -55,7 +42,6 @@ def plugin_unloaded():
safe_listener_detach(TEXT_LISTENER) safe_listener_detach(TEXT_LISTENER)
package_logger.removeHandler(handler) package_logger.removeHandler(handler)
def kill_all(): def kill_all():
for ws in workspaces.lookup(): for ws in workspaces.lookup():
session.client.leave_workspace(ws.id) session.client.leave_workspace(ws.id)
@ -63,12 +49,18 @@ def kill_all():
session.stop() session.stop()
def objects_from_view(view): def vbuff_form_view(view):
assert view.settings().get(g.CODEMP_VIEW_TAG, False) if not view.settings().get(g.CODEMP_VIEW_TAG, False):
buffid = str(view.settings().get(g.CODEMP_BUFFER_ID)) raise ValueError("The view is not a Codemp Buffer.")
buffid = str(view.settings().get(g.CODEMP_BUFFER_ID))
vbuff = buffers.lookupId(buffid) vbuff = buffers.lookupId(buffid)
return vbuff
def objects_from_view(view):
vbuff = vbuff_form_view(view)
vws = buffers.lookupParent(vbuff) vws = buffers.lookupParent(vbuff)
win = workspaces.lookupParent(vws) win = workspaces.lookupParent(vws)
@ -83,6 +75,13 @@ class CodempBrowseWorkspaceCommand(sublime_plugin.WindowCommand):
buffers = wks.handle.fetch_buffers() buffers = wks.handle.fetch_buffers()
QPWorkspaceBrowser(self.window, workspace_id, buffers.wait()).run() QPWorkspaceBrowser(self.window, workspace_id, buffers.wait()).run()
def input(self, args):
if "workspace_id" not in args:
wslist = session.client.active_workspaces()
return SimpleListInput(
("workspace_id", wslist),
)
class CodempBrowseServerCommand(sublime_plugin.WindowCommand): class CodempBrowseServerCommand(sublime_plugin.WindowCommand):
def is_enabled(self) -> bool: def is_enabled(self) -> bool:
@ -104,7 +103,7 @@ class CodempReplaceTextCommand(sublime_plugin.TextCommand):
class CodempSyncBuffer(sublime_plugin.TextCommand): class CodempSyncBuffer(sublime_plugin.TextCommand):
def run(self, edit): def run(self, edit):
buff = buffers.lookupId(self.view.settings().get(g.CODEMP_BUFFER_ID)) buff = buffers.lookupId(str(self.view.settings().get(g.CODEMP_BUFFER_ID)))
buff.sync(TEXT_LISTENER) buff.sync(TEXT_LISTENER)
@ -114,9 +113,6 @@ class EventListener(sublime_plugin.EventListener):
def on_exit(self): def on_exit(self):
kill_all() kill_all()
# client.disconnect()
# if client.driver is not None:
# client.driver.stop()
def on_pre_close_window(self, window): def on_pre_close_window(self, window):
for vws in workspaces.lookup(window): for vws in workspaces.lookup(window):

View file

@ -1,5 +1,6 @@
import sublime import sublime
import sublime_plugin import sublime_plugin
import logging import logging
import random import random
@ -27,6 +28,7 @@ class CodempConnectCommand(sublime_plugin.WindowCommand):
("password", "password?"), ("password", "password?"),
) )
if "password" not in args: if "password" not in args:
return SimpleTextInput( return SimpleTextInput(
("password", "password?"), ("password", "password?"),
@ -94,17 +96,16 @@ class CodempJoinWorkspaceCommand(sublime_plugin.WindowCommand):
except Exception as e: except Exception as e:
logger.error(f"Could not join workspace '{workspace_id}': {e}") logger.error(f"Could not join workspace '{workspace_id}': {e}")
sublime.error_message(f"Could not join workspace '{workspace_id}'") sublime.error_message(f"Could not join workspace '{workspace_id}'")
return raise e
logger.debug("Joined! Adding workspace to registry") logger.debug("Joined! Adding workspace to registry")
workspaces.add(ws) workspaces.register(ws)
# Leave Workspace Command # Leave Workspace Command
class CodempLeaveWorkspaceCommand(sublime_plugin.WindowCommand): class CodempLeaveWorkspaceCommand(sublime_plugin.WindowCommand):
def is_enabled(self): def is_enabled(self):
return session.is_active() and \ return session.is_active() and workspaces.hasactive()
len(workspaces.lookup(self.window)) > 0
def input(self, args): def input(self, args):
if "workspace_id" not in args: if "workspace_id" not in args:
@ -123,7 +124,7 @@ class CodempLeaveWorkspaceCommand(sublime_plugin.WindowCommand):
class CodempInviteToWorkspaceCommand(sublime_plugin.WindowCommand): class CodempInviteToWorkspaceCommand(sublime_plugin.WindowCommand):
def is_enabled(self) -> bool: def is_enabled(self) -> bool:
return session.is_active() and len(workspaces.lookup(self.window)) > 0 return session.is_active() and workspaces.hasactive() > 0
def input(self, args): def input(self, args):
if "workspace_id" not in args: if "workspace_id" not in args:

View file

@ -53,18 +53,6 @@ class CodempJoinBufferCommand(sublime_plugin.WindowCommand):
except KeyError: except KeyError:
pass pass
# # if doesn't exist in the workspace, ask for creation.
# if vws.handle.get_buffer(buffer_id) is None:
# if sublime.ok_cancel_dialog(
# f"There is no buffer named '{buffer_id}' in the workspace '{workspace_id}'.\n\
# Do you want to create it?",
# ok_title="yes", title="Create Buffer?",
# ):
# sublime.run_command("codemp_create_buffer", {
# "workspace_id": workspace_id,
# "buffer_id": buffer_id
# })
# now we can defer the attaching process # now we can defer the attaching process
logger.debug(f"attempting to attach to {buffer_id}...") logger.debug(f"attempting to attach to {buffer_id}...")
ctl_promise = vws.handle.attach_buffer(buffer_id) ctl_promise = vws.handle.attach_buffer(buffer_id)
@ -80,12 +68,12 @@ class CodempJoinBufferCommand(sublime_plugin.WindowCommand):
safe_listener_detach(TEXT_LISTENER) safe_listener_detach(TEXT_LISTENER)
content_promise = buff_ctl.content() content_promise = buff_ctl.content()
vbuff = buffers.add(buff_ctl, vws) vbuff = buffers.register(buff_ctl, vws)
content = content_promise.wait() content = content_promise.wait()
populate_view(vbuff.view, content) populate_view(vbuff.view, content)
if self.window.active_view() == vbuff.view: if self.window.active_view() == vbuff.view:
# if view is already active focusing it won't trigger `on_activate`. # if view is already active, focusing it won't trigger `on_activate`.
safe_listener_attach(TEXT_LISTENER, vbuff.view.buffer()) safe_listener_attach(TEXT_LISTENER, vbuff.view.buffer())
else: else:
self.window.focus_view(vbuff.view) self.window.focus_view(vbuff.view)

View file

@ -25,7 +25,7 @@ def bind_callback(v: sublime.View):
multi_tryrecv_lock = threading.Lock() multi_tryrecv_lock = threading.Lock()
def _callback(bufctl: codemp.BufferController): def _callback(bufctl: codemp.BufferController):
def _(): def _innercb():
try: try:
# change_id = v.change_id() # change_id = v.change_id()
change_id = None change_id = None
@ -67,7 +67,7 @@ def bind_callback(v: sublime.View):
if multi_tryrecv_lock.acquire(blocking=False): if multi_tryrecv_lock.acquire(blocking=False):
logger.debug("acquiring lock") logger.debug("acquiring lock")
sublime.set_timeout(_) sublime.set_timeout(_innercb)
return _callback return _callback
class BufferManager(): class BufferManager():
@ -102,8 +102,8 @@ class BufferManager():
def sync(self, text_listener): def sync(self, text_listener):
promise = self.handle.content() promise = self.handle.content()
def _(): def _():
content = promise.wait()
current_contents = get_contents(self.view) current_contents = get_contents(self.view)
content = promise.wait()
if content == current_contents: if content == current_contents:
return return
@ -117,6 +117,14 @@ class BufferRegistry():
def __init__(self): def __init__(self):
self._buffers: bidict[BufferManager, WorkspaceManager] = bidict() self._buffers: bidict[BufferManager, WorkspaceManager] = bidict()
def __contains__(self, item: str):
try: self.lookupId(item)
except KeyError: return False
return True
def hasactive(self):
return len(self._buffers.keys()) > 0
def lookup(self, ws: Optional[WorkspaceManager] = None) -> list[BufferManager]: def lookup(self, ws: Optional[WorkspaceManager] = None) -> list[BufferManager]:
if not ws: if not ws:
return list(self._buffers.keys()) return list(self._buffers.keys())
@ -133,13 +141,16 @@ class BufferRegistry():
if not bfm: raise KeyError if not bfm: raise KeyError
return bfm return bfm
def add(self, bhandle: codemp.BufferController, wsm: WorkspaceManager): def register(self, bhandle: codemp.BufferController, wsm: WorkspaceManager):
bid = bhandle.path() bid = bhandle.path()
# tmpfile = os.path.join(wsm.rootdir, bid) # tmpfile = os.path.join(wsm.rootdir, bid)
# open(tmpfile, "a").close() # open(tmpfile, "a").close()
win = sublime.active_window() win = sublime.active_window()
view = win.open_file(bid) view = win.open_file(bid)
while view.is_loading():
pass # yes spinlock, fite me.
view.set_scratch(True) view.set_scratch(True)
# view.retarget(tmpfile) # view.retarget(tmpfile)
view.settings().set(g.CODEMP_VIEW_TAG, True) view.settings().set(g.CODEMP_VIEW_TAG, True)

View file

@ -14,6 +14,8 @@ from codemp import Selection
from .. import globals as g from .. import globals as g
from ..utils import draw_cursor_region from ..utils import draw_cursor_region
from ..utils import bidict from ..utils import bidict
from .session import session
from .buffers import buffers from .buffers import buffers
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -99,6 +101,14 @@ class WorkspaceRegistry():
def __init__(self) -> None: def __init__(self) -> None:
self._workspaces: bidict[WorkspaceManager, sublime.Window] = bidict() self._workspaces: bidict[WorkspaceManager, sublime.Window] = bidict()
def __contains__(self, item: str):
try: self.lookupId(item)
except KeyError: return False
return True
def hasactive(self):
return len(session.client.active_workspaces()) > 0
def lookup(self, w: Optional[sublime.Window] = None) -> list[WorkspaceManager]: def lookup(self, w: Optional[sublime.Window] = None) -> list[WorkspaceManager]:
if not w: if not w:
return list(self._workspaces.keys()) return list(self._workspaces.keys())
@ -115,7 +125,7 @@ class WorkspaceRegistry():
if not wsm: raise KeyError if not wsm: raise KeyError
return wsm return wsm
def add(self, wshandle: codemp.Workspace) -> WorkspaceManager: def register(self, wshandle: codemp.Workspace) -> WorkspaceManager:
win = sublime.active_window() win = sublime.active_window()
# tmpdir = tempfile.mkdtemp(prefix="codemp_") # tmpdir = tempfile.mkdtemp(prefix="codemp_")

View file

@ -30,7 +30,7 @@ class SimpleTextInput(sublime_plugin.TextInputHandler):
class SimpleListInput(sublime_plugin.ListInputHandler): class SimpleListInput(sublime_plugin.ListInputHandler):
def __init__(self, *args: Tuple[str, Union["list[str]", str]]): def __init__(self, *args: Tuple[str, Union[List[str], str]]):
self.input, *self.next_inputs = args self.input, *self.next_inputs = args
self.argname = self.input[0] self.argname = self.input[0]
self.list = self.input[1] self.list = self.input[1]

View file

@ -17,7 +17,6 @@ def show_qp(window, choices, on_done, placeholder=''):
window.show_quick_panel(choices, on_done, flags, placeholder=placeholder) window.show_quick_panel(choices, on_done, flags, placeholder=placeholder)
sublime.set_timeout(_, 10) sublime.set_timeout(_, 10)
class QPServerBrowser(): class QPServerBrowser():
def __init__(self, window, host, raw_input_items): def __init__(self, window, host, raw_input_items):
self.window = window self.window = window
@ -55,36 +54,39 @@ class QPServerBrowser():
self.current_wid_selection = wid self.current_wid_selection = wid
# self.select_workspace() # self.select_workspace()
def _(): def _():
self.window.run_command( if not wid in workspaces:
"codemp_join_workspace", try: self.window.run_command(
{"workspace_id": self.current_wid_selection}) "codemp_join_workspace", {"workspace_id": wid})
except Exception as e:
return
ws = workspaces.lookupId(wid) ws = workspaces.lookupId(wid)
buffers = ws.handle.fetch_buffers() buffers = ws.handle.fetch_buffers()
QPWorkspaceBrowser(self.window, wid, buffers.wait()).run() QPWorkspaceBrowser(self.window, wid, buffers.wait()).run()
sublime.set_timeout(_) sublime.set_timeout(_)
logger.debug("exiting the server_broswer.") logger.debug("exiting the server_broswer.")
def select_workspace(self): # def select_workspace(self):
assert self.current_wid_selection # assert self.current_wid_selection
actions = [ # actions = [
qpi("Join", details=self.current_wid_selection, color=qpg.QP_COLOR_BLUISH, letter=qpg.QP_FORWARD), # qpi("Join", details=self.current_wid_selection, color=qpg.QP_COLOR_BLUISH, letter=qpg.QP_FORWARD),
# qpi("Join and open all", # # qpi("Join and open all",
# details="opens all buffer in the workspace", # # details="opens all buffer in the workspace",
# color=qpg.QP_COLOR_PINKISH, letter=qpg.QP_DETAILS), # # color=qpg.QP_COLOR_PINKISH, letter=qpg.QP_DETAILS),
qpi("Back", color=qpg.QP_COLOR_BLUISH, letter=qpg.QP_BACK) # qpi("Back", color=qpg.QP_COLOR_BLUISH, letter=qpg.QP_BACK)
] # ]
show_qp(self.window, actions, self.select_workspace_actions, self.qp_placeholder()) # show_qp(self.window, actions, self.select_workspace_actions, self.qp_placeholder())
def select_workspace_actions(self, index): # def select_workspace_actions(self, index):
if index == -1: # if index == -1:
return # return
elif index == 0: # elif index == 0:
self.window.run_command( # self.window.run_command(
"codemp_join_workspace", # "codemp_join_workspace",
{"workspace_id": self.current_wid_selection}) # {"workspace_id": self.current_wid_selection})
elif index == 1: # elif index == 1:
self.run() # self.run()
def edit_server(self): def edit_server(self):
@ -168,7 +170,6 @@ class QPWorkspaceBrowser():
"buffer_id": bid "buffer_id": bid
}) })
def edit_workspace(self): def edit_workspace(self):
actions = [ actions = [
qpi("Back", color=qpg.QP_COLOR_CYANISH, letter=qpg.QP_BACK), qpi("Back", color=qpg.QP_COLOR_CYANISH, letter=qpg.QP_BACK),