repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/id.rs | lapce-app/src/id.rs | use floem::views::editor::id::Id;
pub type SplitId = Id;
pub type WindowTabId = Id;
pub type EditorTabId = Id;
pub type SettingsId = Id;
pub type KeymapId = Id;
pub type ThemeColorSettingsId = Id;
pub type VoltViewId = Id;
pub type DiffEditorId = Id;
pub type TerminalTabId = Id;
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/doc.rs | lapce-app/src/doc.rs | use std::{
borrow::Cow,
cell::RefCell,
collections::HashMap,
ops::Range,
path::{Path, PathBuf},
rc::Rc,
sync::{
Arc,
atomic::{self, AtomicUsize},
},
time::Duration,
};
use floem::{
ViewId,
action::exec_after,
ext_event::create_ext_action,
keyboard::Modifiers,
peniko::Color,
reactive::{
ReadSignal, RwSignal, Scope, SignalGet, SignalUpdate, SignalWith, batch,
},
text::{Attrs, AttrsList, FamilyOwned, TextLayout},
views::editor::{
CursorInfo, Editor, EditorStyle,
actions::CommonAction,
command::{Command, CommandExecuted},
id::EditorId,
layout::{LineExtraStyle, TextLayoutLine},
phantom_text::{PhantomText, PhantomTextKind, PhantomTextLine},
text::{Document, DocumentPhantom, PreeditData, Styling, SystemClipboard},
view::{ScreenLines, ScreenLinesBase},
},
};
use itertools::Itertools;
use lapce_core::{
buffer::{
Buffer, InvalLines,
diff::{DiffLines, rope_diff},
rope_text::RopeText,
},
char_buffer::CharBuffer,
command::EditCommand,
cursor::{Cursor, CursorAffinity},
editor::{Action, EditConf, EditType},
indent::IndentStyle,
language::LapceLanguage,
line_ending::LineEnding,
mode::MotionMode,
register::Register,
rope_text_pos::RopeTextPosition,
selection::{InsertDrift, Selection},
style::line_styles,
syntax::{BracketParser, Syntax, edit::SyntaxEdit},
word::{CharClassification, WordCursor, get_char_property},
};
use lapce_rpc::{
buffer::BufferId,
plugin::PluginId,
proxy::ProxyResponse,
style::{LineStyle, LineStyles, Style},
};
use lapce_xi_rope::{
Interval, Rope, RopeDelta, Transformer,
spans::{Spans, SpansBuilder},
};
use lsp_types::{
CodeActionOrCommand, CodeLens, Diagnostic, DiagnosticSeverity,
DocumentSymbolResponse, InlayHint, InlayHintLabel, TextEdit,
};
use serde::{Deserialize, Serialize};
use smallvec::SmallVec;
use crate::{
command::{CommandKind, LapceCommand},
config::{LapceConfig, color::LapceColor},
editor::{EditorData, compute_screen_lines, gutter::FoldingRanges},
find::{Find, FindProgress, FindResult},
history::DocumentHistory,
keypress::KeyPressFocus,
main_split::Editors,
panel::{
document_symbol::{SymbolData, SymbolInformationItemData},
kind::PanelKind,
},
window_tab::{CommonData, Focus},
workspace::LapceWorkspace,
};
#[derive(Clone, Debug)]
pub struct DiagnosticData {
pub expanded: RwSignal<bool>,
pub diagnostics: RwSignal<im::Vector<Diagnostic>>,
pub diagnostics_span: RwSignal<Spans<Diagnostic>>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EditorDiagnostic {
pub range: Option<(usize, usize)>,
pub diagnostic: Diagnostic,
}
#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub struct DocHistory {
pub path: PathBuf,
pub version: String,
}
#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum DocContent {
/// A file at some location. This can be a remote path.
File { path: PathBuf, read_only: bool },
/// A local document, which doens't need to be sync to the disk.
Local,
/// A document of an old version in the source control
History(DocHistory),
/// A new file which doesn't exist in the file system
Scratch { id: BufferId, name: String },
}
impl DocContent {
pub fn is_local(&self) -> bool {
matches!(self, DocContent::Local)
}
pub fn is_file(&self) -> bool {
matches!(self, DocContent::File { .. })
}
pub fn read_only(&self) -> bool {
match self {
DocContent::File { read_only, .. } => *read_only,
DocContent::Local => false,
DocContent::History(_) => true,
DocContent::Scratch { .. } => false,
}
}
pub fn path(&self) -> Option<&PathBuf> {
match self {
DocContent::File { path, .. } => Some(path),
DocContent::Local => None,
DocContent::History(_) => None,
DocContent::Scratch { .. } => None,
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DocInfo {
pub workspace: LapceWorkspace,
pub path: PathBuf,
pub scroll_offset: (f64, f64),
pub cursor_offset: usize,
}
/// (Offset -> (Plugin the code actions are from, Code Actions))
pub type CodeActions =
im::HashMap<usize, (PluginId, im::Vector<CodeActionOrCommand>)>;
pub type AllCodeLens = im::HashMap<usize, (PluginId, usize, im::Vector<CodeLens>)>;
#[derive(Clone)]
pub struct Doc {
pub scope: Scope,
pub buffer_id: BufferId,
pub content: RwSignal<DocContent>,
pub cache_rev: RwSignal<u64>,
/// Whether the buffer's content has been loaded/initialized into the buffer.
pub loaded: RwSignal<bool>,
pub buffer: RwSignal<Buffer>,
pub syntax: RwSignal<Syntax>,
semantic_styles: RwSignal<Option<Spans<Style>>>,
/// Inlay hints for the document
pub inlay_hints: RwSignal<Option<Spans<InlayHint>>>,
/// Current completion lens text, if any.
/// This will be displayed even on views that are not focused.
pub completion_lens: RwSignal<Option<String>>,
/// (line, col)
pub completion_pos: RwSignal<(usize, usize)>,
/// Current inline completion text, if any.
/// This will be displayed even on views that are not focused.
pub inline_completion: RwSignal<Option<String>>,
/// (line, col)
pub inline_completion_pos: RwSignal<(usize, usize)>,
/// (Offset -> (Plugin the code actions are from, Code Actions))
pub code_actions: RwSignal<CodeActions>,
pub code_lens: RwSignal<AllCodeLens>,
pub folding_ranges: RwSignal<FoldingRanges>,
/// Stores information about different versions of the document from source control.
histories: RwSignal<im::HashMap<String, DocumentHistory>>,
pub head_changes: RwSignal<im::Vector<DiffLines>>,
line_styles: Rc<RefCell<LineStyles>>,
pub parser: Rc<RefCell<BracketParser>>,
/// A cache for the sticky headers which maps a line to the lines it should show in the header.
pub sticky_headers: Rc<RefCell<HashMap<usize, Option<Vec<usize>>>>>,
pub preedit: PreeditData,
pub find_result: FindResult,
/// The diagnostics for the document
pub diagnostics: DiagnosticData,
editors: Editors,
pub common: Rc<CommonData>,
pub document_symbol_data: RwSignal<Option<SymbolData>>,
}
impl Doc {
pub fn new(
cx: Scope,
path: PathBuf,
diagnostics: DiagnosticData,
editors: Editors,
common: Rc<CommonData>,
) -> Self {
let syntax = Syntax::init(&path);
let config = common.config.get_untracked();
Doc {
scope: cx,
buffer_id: BufferId::next(),
buffer: cx.create_rw_signal(Buffer::new("")),
syntax: cx.create_rw_signal(syntax),
line_styles: Rc::new(RefCell::new(HashMap::new())),
parser: Rc::new(RefCell::new(BracketParser::new(
String::new(),
config.editor.bracket_pair_colorization,
config.editor.bracket_colorization_limit,
))),
semantic_styles: cx.create_rw_signal(None),
inlay_hints: cx.create_rw_signal(None),
diagnostics,
completion_lens: cx.create_rw_signal(None),
completion_pos: cx.create_rw_signal((0, 0)),
inline_completion: cx.create_rw_signal(None),
inline_completion_pos: cx.create_rw_signal((0, 0)),
cache_rev: cx.create_rw_signal(0),
content: cx.create_rw_signal(DocContent::File {
path,
read_only: false,
}),
loaded: cx.create_rw_signal(false),
histories: cx.create_rw_signal(im::HashMap::new()),
head_changes: cx.create_rw_signal(im::Vector::new()),
sticky_headers: Rc::new(RefCell::new(HashMap::new())),
code_actions: cx.create_rw_signal(im::HashMap::new()),
find_result: FindResult::new(cx),
preedit: PreeditData::new(cx),
editors,
common,
code_lens: cx.create_rw_signal(im::HashMap::new()),
document_symbol_data: cx.create_rw_signal(None),
folding_ranges: cx.create_rw_signal(FoldingRanges::default()),
}
}
pub fn new_local(cx: Scope, editors: Editors, common: Rc<CommonData>) -> Doc {
Self::new_content(cx, DocContent::Local, editors, common)
}
pub fn new_content(
cx: Scope,
content: DocContent,
editors: Editors,
common: Rc<CommonData>,
) -> Doc {
let cx = cx.create_child();
let config = common.config.get_untracked();
Self {
scope: cx,
buffer_id: BufferId::next(),
buffer: cx.create_rw_signal(Buffer::new("")),
syntax: cx.create_rw_signal(Syntax::plaintext()),
line_styles: Rc::new(RefCell::new(HashMap::new())),
parser: Rc::new(RefCell::new(BracketParser::new(
String::new(),
config.editor.bracket_pair_colorization,
config.editor.bracket_colorization_limit,
))),
semantic_styles: cx.create_rw_signal(None),
inlay_hints: cx.create_rw_signal(None),
diagnostics: DiagnosticData {
expanded: cx.create_rw_signal(true),
diagnostics: cx.create_rw_signal(im::Vector::new()),
diagnostics_span: cx.create_rw_signal(SpansBuilder::new(0).build()),
},
completion_lens: cx.create_rw_signal(None),
completion_pos: cx.create_rw_signal((0, 0)),
inline_completion: cx.create_rw_signal(None),
inline_completion_pos: cx.create_rw_signal((0, 0)),
cache_rev: cx.create_rw_signal(0),
content: cx.create_rw_signal(content),
histories: cx.create_rw_signal(im::HashMap::new()),
head_changes: cx.create_rw_signal(im::Vector::new()),
sticky_headers: Rc::new(RefCell::new(HashMap::new())),
loaded: cx.create_rw_signal(true),
find_result: FindResult::new(cx),
code_actions: cx.create_rw_signal(im::HashMap::new()),
preedit: PreeditData::new(cx),
editors,
common,
code_lens: cx.create_rw_signal(im::HashMap::new()),
document_symbol_data: cx.create_rw_signal(None),
folding_ranges: cx.create_rw_signal(FoldingRanges::default()),
}
}
pub fn new_history(
cx: Scope,
content: DocContent,
editors: Editors,
common: Rc<CommonData>,
) -> Doc {
let config = common.config.get_untracked();
let syntax = if let DocContent::History(history) = &content {
Syntax::init(&history.path)
} else {
Syntax::plaintext()
};
Self {
scope: cx,
buffer_id: BufferId::next(),
buffer: cx.create_rw_signal(Buffer::new("")),
syntax: cx.create_rw_signal(syntax),
line_styles: Rc::new(RefCell::new(HashMap::new())),
parser: Rc::new(RefCell::new(BracketParser::new(
String::new(),
config.editor.bracket_pair_colorization,
config.editor.bracket_colorization_limit,
))),
semantic_styles: cx.create_rw_signal(None),
inlay_hints: cx.create_rw_signal(None),
diagnostics: DiagnosticData {
expanded: cx.create_rw_signal(true),
diagnostics: cx.create_rw_signal(im::Vector::new()),
diagnostics_span: cx.create_rw_signal(SpansBuilder::new(0).build()),
},
completion_lens: cx.create_rw_signal(None),
completion_pos: cx.create_rw_signal((0, 0)),
inline_completion: cx.create_rw_signal(None),
inline_completion_pos: cx.create_rw_signal((0, 0)),
cache_rev: cx.create_rw_signal(0),
content: cx.create_rw_signal(content),
sticky_headers: Rc::new(RefCell::new(HashMap::new())),
loaded: cx.create_rw_signal(true),
histories: cx.create_rw_signal(im::HashMap::new()),
head_changes: cx.create_rw_signal(im::Vector::new()),
code_actions: cx.create_rw_signal(im::HashMap::new()),
find_result: FindResult::new(cx),
preedit: PreeditData::new(cx),
editors,
common,
code_lens: cx.create_rw_signal(im::HashMap::new()),
document_symbol_data: cx.create_rw_signal(None),
folding_ranges: cx.create_rw_signal(FoldingRanges::default()),
}
}
/// Create a styling instance for this doc
pub fn styling(self: &Rc<Doc>) -> Rc<DocStyling> {
Rc::new(DocStyling {
config: self.common.config,
doc: self.clone(),
})
}
/// Create an [`Editor`] instance from this [`Doc`]. Note that this needs to be registered
/// appropriately to create the [`EditorData`] and such.
pub fn create_editor(
self: &Rc<Doc>,
cx: Scope,
id: EditorId,
is_local: bool,
) -> Editor {
let common = &self.common;
let config = common.config.get_untracked();
let modal = config.core.modal && !is_local;
let register = common.register;
// TODO: we could have these Rcs created once and stored somewhere, maybe on
// common, to avoid recreating them everytime.
let cursor_info = CursorInfo {
blink_interval: Rc::new(move || config.editor.blink_interval()),
blink_timer: common.window_common.cursor_blink_timer,
hidden: common.window_common.hide_cursor,
should_blink: Rc::new(should_blink(common.focus, common.keyboard_focus)),
};
let mut editor =
Editor::new_direct(cx, id, self.clone(), self.styling(), modal);
editor.register = register;
editor.cursor_info = cursor_info;
editor.ime_allowed = common.window_common.ime_allowed;
editor.recreate_view_effects();
editor
}
fn editor_data(&self, id: EditorId) -> Option<EditorData> {
self.editors.editor_untracked(id)
}
pub fn syntax(&self) -> ReadSignal<Syntax> {
self.syntax.read_only()
}
pub fn set_syntax(&self, syntax: Syntax) {
batch(|| {
self.syntax.set(syntax);
if self.semantic_styles.with_untracked(|s| s.is_none()) {
self.clear_style_cache();
}
self.clear_sticky_headers_cache();
});
}
/// Set the syntax highlighting this document should use.
pub fn set_language(&self, language: LapceLanguage) {
self.syntax.set(Syntax::from_language(language));
}
pub fn find(&self) -> &Find {
&self.common.find
}
/// Whether or not the underlying buffer is loaded
pub fn loaded(&self) -> bool {
self.loaded.get_untracked()
}
//// Initialize the content with some text, this marks the document as loaded.
pub fn init_content(&self, content: Rope) {
batch(|| {
self.syntax.with_untracked(|syntax| {
self.buffer.update(|buffer| {
buffer.init_content(content);
buffer.detect_indent(|| {
IndentStyle::from_str(syntax.language.indent_unit())
});
});
});
self.loaded.set(true);
self.on_update(None);
self.init_parser();
self.init_diagnostics();
self.retrieve_head();
});
}
fn init_parser(&self) {
let code = self.buffer.get_untracked().to_string();
self.syntax.with_untracked(|syntax| {
if syntax.styles.is_some() {
self.parser.borrow_mut().update_code(
code,
&self.buffer.get_untracked(),
Some(syntax),
);
} else {
self.parser.borrow_mut().update_code(
code,
&self.buffer.get_untracked(),
None,
);
}
});
}
/// Reload the document's content, and is what you should typically use when you want to *set*
/// an existing document's content.
pub fn reload(&self, content: Rope, set_pristine: bool) {
// self.code_actions.clear();
// self.inlay_hints = None;
let delta = self
.buffer
.try_update(|buffer| buffer.reload(content, set_pristine))
.unwrap();
self.apply_deltas(&[delta]);
}
pub fn handle_file_changed(&self, content: Rope) {
if self.is_pristine() {
self.reload(content, true);
}
}
pub fn do_insert(
&self,
cursor: &mut Cursor,
s: &str,
config: &LapceConfig,
) -> Vec<(Rope, RopeDelta, InvalLines)> {
if self.content.with_untracked(|c| c.read_only()) {
return Vec::new();
}
let old_cursor = cursor.mode.clone();
let deltas = self.syntax.with_untracked(|syntax| {
self.buffer
.try_update(|buffer| {
Action::insert(
cursor,
buffer,
s,
&|buffer, c, offset| {
syntax_prev_unmatched(buffer, syntax, c, offset)
},
config.editor.auto_closing_matching_pairs,
config.editor.auto_surround,
)
})
.unwrap()
});
// Keep track of the change in the cursor mode for undo/redo
self.buffer.update(|buffer| {
buffer.set_cursor_before(old_cursor);
buffer.set_cursor_after(cursor.mode.clone());
});
self.apply_deltas(&deltas);
deltas
}
pub fn do_raw_edit(
&self,
edits: &[(impl AsRef<Selection>, &str)],
edit_type: EditType,
) -> Option<(Rope, RopeDelta, InvalLines)> {
if self.content.with_untracked(|c| c.read_only()) {
return None;
}
let (text, delta, inval_lines) = self
.buffer
.try_update(|buffer| buffer.edit(edits, edit_type))
.unwrap();
self.apply_deltas(&[(text.clone(), delta.clone(), inval_lines.clone())]);
Some((text, delta, inval_lines))
}
pub fn do_edit(
&self,
cursor: &mut Cursor,
cmd: &EditCommand,
modal: bool,
register: &mut Register,
smart_tab: bool,
) -> Vec<(Rope, RopeDelta, InvalLines)> {
if self.content.with_untracked(|c| c.read_only())
&& !cmd.not_changing_buffer()
{
return Vec::new();
}
let mut clipboard = SystemClipboard::new();
let old_cursor = cursor.mode.clone();
let deltas = self.syntax.with_untracked(|syntax| {
self.buffer
.try_update(|buffer| {
Action::do_edit(
cursor,
buffer,
cmd,
&mut clipboard,
register,
EditConf {
comment_token: syntax.language.comment_token(),
modal,
smart_tab,
keep_indent: true,
auto_indent: true,
},
)
})
.unwrap()
});
if !deltas.is_empty() {
self.buffer.update(|buffer| {
buffer.set_cursor_before(old_cursor);
buffer.set_cursor_after(cursor.mode.clone());
});
self.apply_deltas(&deltas);
}
deltas
}
pub fn apply_deltas(&self, deltas: &[(Rope, RopeDelta, InvalLines)]) {
let rev = self.rev() - deltas.len() as u64;
batch(|| {
for (i, (_, delta, inval)) in deltas.iter().enumerate() {
self.update_styles(delta);
self.update_inlay_hints(delta);
self.update_diagnostics(delta);
self.update_completion_lens(delta);
self.update_find_result(delta);
if let DocContent::File { path, .. } = self.content.get_untracked() {
self.update_breakpoints(delta, &path, &inval.old_text);
self.common.proxy.update(
path,
delta.clone(),
rev + i as u64 + 1,
);
}
}
});
// TODO(minor): We could avoid this potential allocation since most apply_delta callers are actually using a Vec
// which we could reuse.
// We use a smallvec because there is unlikely to be more than a couple of deltas
let edits: SmallVec<[SyntaxEdit; 3]> = deltas
.iter()
.map(|(before_text, delta, _)| {
SyntaxEdit::from_delta(before_text, delta.clone())
})
.collect();
self.on_update(Some(edits));
}
pub fn is_pristine(&self) -> bool {
self.buffer.with_untracked(|b| b.is_pristine())
}
/// Get the buffer's current revision. This is used to track whether the buffer has changed.
pub fn rev(&self) -> u64 {
self.buffer.with_untracked(|b| b.rev())
}
/// Get the buffer's line-ending.
/// Note: this may not be the same as what the actual line endings in the file are, rather this
/// is what the line-ending is set to (and what it will be saved as).
pub fn line_ending(&self) -> LineEnding {
self.buffer.with_untracked(|b| b.line_ending())
}
fn on_update(&self, edits: Option<SmallVec<[SyntaxEdit; 3]>>) {
batch(|| {
self.trigger_syntax_change(edits);
self.trigger_head_change();
self.check_auto_save();
self.get_inlay_hints();
self.find_result.reset();
self.get_semantic_styles();
self.do_bracket_colorization();
self.clear_code_actions();
self.clear_style_cache();
self.get_code_lens();
self.get_document_symbol();
self.get_folding_range();
});
}
fn do_bracket_colorization(&self) {
if self.parser.borrow().active {
self.syntax.with_untracked(|syntax| {
if syntax.rev == self.rev() && syntax.styles.is_some() {
self.parser.borrow_mut().update_code(
self.buffer.get_untracked().to_string(),
&self.buffer.get_untracked(),
Some(syntax),
);
} else {
self.parser.borrow_mut().update_code(
self.buffer.get_untracked().to_string(),
&self.buffer.get_untracked(),
None,
);
}
})
}
}
pub fn do_text_edit(&self, edits: &[TextEdit]) {
let edits = self.buffer.with_untracked(|buffer| {
edits
.iter()
.map(|edit| {
let selection = lapce_core::selection::Selection::region(
buffer.offset_of_position(&edit.range.start),
buffer.offset_of_position(&edit.range.end),
);
(selection, edit.new_text.as_str())
})
.collect::<Vec<_>>()
});
self.do_raw_edit(&edits, EditType::Completion);
}
fn check_auto_save(&self) {
let config = self.common.config.get_untracked();
if config.editor.autosave_interval > 0 {
let Some(path) = self.content.with_untracked(|c| c.path().cloned())
else {
return;
};
let rev = self.rev();
let doc = self.clone();
let scope = self.scope;
let proxy = self.common.proxy.clone();
let format = config.editor.format_on_save;
exec_after(
Duration::from_millis(config.editor.autosave_interval),
move |_| {
let current_rev = match doc
.buffer
.try_with_untracked(|b| b.as_ref().map(|b| b.rev()))
{
Some(rev) => rev,
None => return,
};
if current_rev != rev || doc.is_pristine() {
return;
}
if format {
let send = create_ext_action(scope, move |result| {
let current_rev = doc.rev();
if current_rev != rev {
return;
}
if let Ok(ProxyResponse::GetDocumentFormatting {
edits,
}) = result
{
doc.do_text_edit(&edits);
}
doc.save(|| {});
});
proxy.get_document_formatting(path, move |result| {
send(result);
});
} else {
doc.save(|| {});
}
},
);
}
}
/// Update the styles after an edit, so the highlights are at the correct positions.
/// This does not do a reparse of the document itself.
fn update_styles(&self, delta: &RopeDelta) {
batch(|| {
self.semantic_styles.update(|styles| {
if let Some(styles) = styles.as_mut() {
styles.apply_shape(delta);
}
});
self.syntax.update(|syntax| {
if let Some(styles) = syntax.styles.as_mut() {
styles.apply_shape(delta);
}
syntax.lens.apply_delta(delta);
});
});
}
/// Update the inlay hints so their positions are correct after an edit.
fn update_inlay_hints(&self, delta: &RopeDelta) {
self.inlay_hints.update(|inlay_hints| {
if let Some(hints) = inlay_hints.as_mut() {
hints.apply_shape(delta);
}
});
}
pub fn trigger_syntax_change(&self, edits: Option<SmallVec<[SyntaxEdit; 3]>>) {
let (rev, text) =
self.buffer.with_untracked(|b| (b.rev(), b.text().clone()));
let doc = self.clone();
let send = create_ext_action(self.scope, move |syntax| {
if doc.buffer.with_untracked(|b| b.rev()) == rev {
doc.syntax.set(syntax);
doc.do_bracket_colorization();
doc.clear_style_cache();
doc.clear_sticky_headers_cache();
}
});
self.syntax.update(|syntax| {
syntax.cancel_flag.store(1, atomic::Ordering::Relaxed);
syntax.cancel_flag = Arc::new(AtomicUsize::new(0));
});
let mut syntax = self.syntax.get_untracked();
rayon::spawn(move || {
syntax.parse(rev, text, edits.as_deref());
send(syntax);
});
}
fn clear_style_cache(&self) {
self.line_styles.borrow_mut().clear();
self.clear_text_cache();
}
fn clear_code_actions(&self) {
self.code_actions.update(|c| {
c.clear();
});
}
/// Inform any dependents on this document that they should clear any cached text.
pub fn clear_text_cache(&self) {
self.cache_rev.try_update(|cache_rev| {
*cache_rev += 1;
// TODO: ???
// Update the text layouts within the callback so that those alerted to cache rev
// will see the now empty layouts.
// self.text_layouts.borrow_mut().clear(*cache_rev, None);
});
}
fn clear_sticky_headers_cache(&self) {
self.sticky_headers.borrow_mut().clear();
}
/// Get the active style information, either the semantic styles or the
/// tree-sitter syntax styles.
fn styles(&self) -> Option<Spans<Style>> {
if let Some(semantic_styles) = self.semantic_styles.get_untracked() {
Some(semantic_styles)
} else {
self.syntax.with_untracked(|syntax| syntax.styles.clone())
}
}
/// Get the style information for the particular line from semantic/syntax highlighting.
/// This caches the result if possible.
pub fn line_style(&self, line: usize) -> Arc<Vec<LineStyle>> {
if self.line_styles.borrow().get(&line).is_none() {
let styles = self.styles();
let line_styles = styles
.map(|styles| {
let text =
self.buffer.with_untracked(|buffer| buffer.text().clone());
line_styles(&text, line, &styles)
})
.unwrap_or_default();
self.line_styles
.borrow_mut()
.insert(line, Arc::new(line_styles));
}
self.line_styles.borrow().get(&line).cloned().unwrap()
}
/// Request semantic styles for the buffer from the LSP through the proxy.
pub fn get_semantic_styles(&self) {
if !self.loaded() {
return;
}
let path =
if let DocContent::File { path, .. } = self.content.get_untracked() {
path
} else {
return;
};
let (atomic_rev, rev, len) = self
.buffer
.with_untracked(|b| (b.atomic_rev(), b.rev(), b.len()));
let doc = self.clone();
let send = create_ext_action(self.scope, move |styles| {
if let Some(styles) = styles {
if doc.buffer.with_untracked(|b| b.rev()) == rev {
doc.semantic_styles.set(Some(styles));
doc.clear_style_cache();
}
}
});
self.common.proxy.get_semantic_tokens(path, move |result| {
if let Ok(ProxyResponse::GetSemanticTokens { styles }) = result {
if styles.styles.is_empty() {
send(None);
return;
}
if atomic_rev.load(atomic::Ordering::Acquire) != rev {
send(None);
return;
}
std::thread::spawn(move || {
let mut styles_span = SpansBuilder::new(len);
for style in styles.styles {
if atomic_rev.load(atomic::Ordering::Acquire) != rev {
send(None);
return;
}
styles_span.add_span(
Interval::new(style.start, style.end),
style.style,
);
}
let styles = styles_span.build();
send(Some(styles));
});
} else {
send(None);
}
});
}
pub fn get_code_lens(&self) {
let cx = self.scope;
let doc = self.clone();
self.code_lens.update(|code_lens| {
code_lens.clear();
});
let rev = self.rev();
if let DocContent::File { path, .. } = doc.content.get_untracked() {
let send = create_ext_action(cx, move |result| {
if rev != doc.rev() {
return;
}
if let Ok(ProxyResponse::GetCodeLensResponse { plugin_id, resp }) =
result
{
let Some(codelens) = resp else {
return;
};
doc.code_lens.update(|code_lens| {
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | true |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/web_link.rs | lapce-app/src/web_link.rs | use floem::{
View,
peniko::Color,
style::CursorStyle,
views::{Decorators, label},
};
use crate::{command::InternalCommand, listener::Listener};
pub fn web_link(
text: impl Fn() -> String + 'static,
uri: impl Fn() -> String + 'static,
color: impl Fn() -> Color + 'static,
internal_command: Listener<InternalCommand>,
) -> impl View {
label(text)
.on_click_stop(move |_| {
internal_command.send(InternalCommand::OpenWebUri { uri: uri() });
})
.style(move |s| {
s.color(color())
.hover(move |s| s.cursor(CursorStyle::Pointer))
})
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/completion.rs | lapce-app/src/completion.rs | use std::{borrow::Cow, path::PathBuf, str::FromStr, sync::Arc};
use floem::{
peniko::kurbo::Rect,
reactive::{ReadSignal, RwSignal, Scope, SignalGet, SignalUpdate, SignalWith},
views::editor::{id::EditorId, text::Document},
};
use lapce_core::{
buffer::rope_text::RopeText, movement::Movement, rope_text_pos::RopeTextPosition,
};
use lapce_rpc::{plugin::PluginId, proxy::ProxyRpcHandler};
use lsp_types::{
CompletionItem, CompletionResponse, CompletionTextEdit, InsertTextFormat,
Position,
};
use nucleo::Utf32Str;
use crate::{config::LapceConfig, editor::EditorData, snippet::Snippet};
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum CompletionStatus {
Inactive,
Started,
Done,
}
#[derive(Clone, PartialEq)]
pub struct ScoredCompletionItem {
pub item: CompletionItem,
pub plugin_id: PluginId,
pub score: u32,
pub label_score: u32,
pub indices: Vec<usize>,
}
#[derive(Clone)]
pub struct CompletionData {
pub status: CompletionStatus,
/// The current request id. This is used to discard old requests.
pub request_id: usize,
/// An input id that is used for keeping track of whether the input has changed.
pub input_id: usize,
// TODO: A `PathBuf` has the issue that the proxy may not have the same format.
// TODO(minor): It might be nice to not require a path. LSPs cannot operate on scratch buffers
// as of now, but they might be allowed in the future.
pub path: PathBuf,
/// The offset that the completion is/was started at. Used for positioning the completion elem
pub offset: usize,
/// The active completion index in the list of filtered items
pub active: RwSignal<usize>,
/// The current input that the user has typed which is being sent for consideration by the LSP
pub input: String,
/// `(Input, CompletionItems)`
pub input_items: im::HashMap<String, im::Vector<ScoredCompletionItem>>,
/// The filtered items that are being displayed to the user
pub filtered_items: im::Vector<ScoredCompletionItem>,
/// The size of the completion element.
/// This is used for positioning the element.
/// As well, it is needed for some movement commands like page up/down that need to know the
/// height to compute how far to move.
pub layout_rect: Rect,
/// The editor id that was most recently used to trigger a completion.
pub latest_editor_id: Option<EditorId>,
/// Matcher for filtering the completion items
matcher: RwSignal<nucleo::Matcher>,
config: ReadSignal<Arc<LapceConfig>>,
}
impl CompletionData {
pub fn new(cx: Scope, config: ReadSignal<Arc<LapceConfig>>) -> Self {
let active = cx.create_rw_signal(0);
Self {
status: CompletionStatus::Inactive,
request_id: 0,
input_id: 0,
path: PathBuf::new(),
offset: 0,
active,
input: "".to_string(),
input_items: im::HashMap::new(),
filtered_items: im::Vector::new(),
layout_rect: Rect::ZERO,
matcher: cx
.create_rw_signal(nucleo::Matcher::new(nucleo::Config::DEFAULT)),
latest_editor_id: None,
config,
}
}
/// Handle the response to a completion request.
pub fn receive(
&mut self,
request_id: usize,
input: &str,
resp: &CompletionResponse,
plugin_id: PluginId,
) {
// If we've been canceled or the request id is old, ignore the response.
if self.status == CompletionStatus::Inactive || self.request_id != request_id
{
return;
}
let items = match resp {
CompletionResponse::Array(items) => items,
// TODO: Possibly handle the 'is_incomplete' field on List.
CompletionResponse::List(list) => &list.items,
};
let items: im::Vector<ScoredCompletionItem> = items
.iter()
.map(|i| ScoredCompletionItem {
item: i.to_owned(),
plugin_id,
score: 0,
label_score: 0,
indices: Vec::new(),
})
.collect();
self.input_items.insert(input.to_string(), items);
self.filter_items();
}
/// Request for completion items wit the current request id.
pub fn request(
&mut self,
editor_id: EditorId,
proxy_rpc: &ProxyRpcHandler,
path: PathBuf,
input: String,
position: Position,
) {
self.latest_editor_id = Some(editor_id);
self.input_items.insert(input.clone(), im::Vector::new());
proxy_rpc.completion(self.request_id, path, input, position);
}
/// Close the completion, clearing all the data.
pub fn cancel(&mut self) {
if self.status == CompletionStatus::Inactive {
return;
}
self.status = CompletionStatus::Inactive;
self.input_id = 0;
self.latest_editor_id = None;
self.active.set(0);
self.input.clear();
self.input_items.clear();
self.filtered_items.clear();
}
pub fn update_input(&mut self, input: String) {
if self.status == CompletionStatus::Inactive {
return;
}
self.input = input;
// TODO: If the user types a letter that continues the current active item, we should
// try keeping that item active. Possibly give this a setting.
// ex: `p` has `print!` and `println!` has options. If you select the second, then type
// `r` then it should stay on `println!` even as the overall filtering of the list changes.
self.active.set(0);
self.filter_items();
}
fn all_items(&self) -> im::Vector<ScoredCompletionItem> {
self.input_items
.get(&self.input)
.cloned()
.filter(|items| !items.is_empty())
.unwrap_or_else(move || {
self.input_items.get("").cloned().unwrap_or_default()
})
}
pub fn filter_items(&mut self) {
self.input_id += 1;
if self.input.is_empty() {
self.filtered_items = self.all_items();
return;
}
// Filter the items by the fuzzy matching with the input text.
let mut items: im::Vector<ScoredCompletionItem> = self
.matcher
.try_update(|matcher| {
let pattern = nucleo::pattern::Pattern::parse(
&self.input,
nucleo::pattern::CaseMatching::Ignore,
nucleo::pattern::Normalization::Smart,
);
self.all_items()
.iter()
.filter_map(|i| {
let filter_text =
i.item.filter_text.as_ref().unwrap_or(&i.item.label);
let shift = i
.item
.label
.match_indices(filter_text)
.next()
.map(|(shift, _)| shift)
.unwrap_or(0);
let mut indices = Vec::new();
let mut filter_text_buf = Vec::new();
let filter_text =
Utf32Str::new(filter_text, &mut filter_text_buf);
if let Some(score) =
pattern.indices(filter_text, matcher, &mut indices)
{
if shift > 0 {
for idx in indices.iter_mut() {
*idx += shift as u32;
}
}
let mut item = i.clone();
item.score = score;
item.label_score = score;
item.indices =
indices.into_iter().map(|i| i as usize).collect();
let mut label_buf = Vec::new();
let label_text =
Utf32Str::new(&i.item.label, &mut label_buf);
if let Some(score) = pattern.score(label_text, matcher) {
item.label_score = score;
}
Some(item)
} else {
None
}
})
.collect()
})
.unwrap();
// Sort all the items by their score, then their label score, then their length.
items.sort_by(|a, b| {
b.score
.cmp(&a.score)
.then_with(|| b.label_score.cmp(&a.label_score))
.then_with(|| a.item.label.len().cmp(&b.item.label.len()))
});
self.filtered_items = items;
}
/// Move down in the list of items.
pub fn next(&mut self) {
let active = self.active.get_untracked();
let new =
Movement::Down.update_index(active, self.filtered_items.len(), 1, true);
self.active.set(new);
}
/// Move up in the list of items.
pub fn previous(&mut self) {
let active = self.active.get_untracked();
let new =
Movement::Up.update_index(active, self.filtered_items.len(), 1, true);
self.active.set(new);
}
/// The amount of items that can be displayed in the current layout.
fn display_count(&self) -> usize {
let config = self.config.get_untracked();
((self.layout_rect.size().height / config.editor.line_height() as f64)
.floor() as usize)
.saturating_sub(1)
}
/// Move to the next page of items.
pub fn next_page(&mut self) {
let count = self.display_count();
let active = self.active.get_untracked();
let new = Movement::Down.update_index(
active,
self.filtered_items.len(),
count,
false,
);
self.active.set(new);
}
/// Move to the previous page of items.
pub fn previous_page(&mut self) {
let count = self.display_count();
let active = self.active.get_untracked();
let new = Movement::Up.update_index(
active,
self.filtered_items.len(),
count,
false,
);
self.active.set(new);
}
/// The currently selected/active item.
pub fn current_item(&self) -> Option<&ScoredCompletionItem> {
self.filtered_items.get(self.active.get_untracked())
}
/// Update the completion lens of the document with the active completion item.
pub fn update_document_completion(
&self,
editor_data: &EditorData,
cursor_offset: usize,
) {
let doc = editor_data.doc();
if !doc.content.with_untracked(|content| content.is_file()) {
return;
}
let config = self.config.get_untracked();
if !config.editor.enable_completion_lens {
doc.clear_completion_lens();
return;
}
let completion_lens = completion_lens_text(
doc.rope_text(),
cursor_offset,
self,
doc.completion_lens().as_deref(),
);
match completion_lens {
Some(Some(lens)) => {
let offset = self.offset + self.input.len();
// TODO: will need to be adjusted to use visual line.
// Could just store the offset in doc.
let (line, col) = editor_data.editor.offset_to_line_col(offset);
doc.set_completion_lens(lens, line, col);
}
// Unchanged
Some(None) => {}
None => {
doc.clear_completion_lens();
}
}
}
}
/// Get the text of the completion lens for the given completion item.
/// Returns `None` if the completion lens should be hidden.
/// Returns `Some(None)` if the completion lens should be shown, but not changed.
/// Returns `Some(Some(text))` if the completion lens should be shown and changed to the given text.
fn completion_lens_text(
rope_text: impl RopeText,
cursor_offset: usize,
completion: &CompletionData,
current_completion: Option<&str>,
) -> Option<Option<String>> {
let item = &completion.current_item()?.item;
let item: Cow<str> = if let Some(edit) = &item.text_edit {
// A text edit is used, because that is what will actually be inserted.
let text_format = item
.insert_text_format
.unwrap_or(InsertTextFormat::PLAIN_TEXT);
// We don't display insert and replace
let CompletionTextEdit::Edit(edit) = edit else {
return None;
};
// The completion offset can be different from the current cursor offset.
let completion_offset = completion.offset;
let start_offset = rope_text.prev_code_boundary(cursor_offset);
let edit_start = rope_text.offset_of_position(&edit.range.start);
// If the start of the edit isn't where the cursor currently is,
// and it is not at the start of the completion, then we ignore it.
// This captures most cases that we want, even if it skips over some
// displayable edits.
if start_offset != edit_start && completion_offset != edit_start {
return None;
}
match text_format {
InsertTextFormat::PLAIN_TEXT => {
// This is not entirely correct because it assumes that the position is
// `{start,end}_offset` when it may not necessarily be.
Cow::Borrowed(&edit.new_text)
}
InsertTextFormat::SNIPPET => {
// Parse the snippet. Bail if it's invalid.
let snippet = Snippet::from_str(&edit.new_text).ok()?;
let text = snippet.text();
Cow::Owned(text)
}
_ => {
// We don't know how to support this text format.
return None;
}
}
} else {
// There's no specific text edit, so we just use the label.
Cow::Borrowed(&item.label)
};
// We strip the prefix of the current input from the label.
// So that, for example, `p` with a completion of `println` only sets the lens text to `rintln`.
// If the text does not include a prefix in the expected position, then we do not display it.
let item = item.as_ref().strip_prefix(&completion.input)?;
// Get only the first line of text, because Lapce does not currently support
// multi-line phantom text.
let item = item.lines().next().unwrap_or(item);
if Some(item) == current_completion {
// If the item is the same as the current completion, then we don't display it.
Some(None)
} else {
Some(Some(item.to_string()))
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/rename.rs | lapce-app/src/rename.rs | use std::{path::PathBuf, rc::Rc};
use floem::{
ext_event::create_ext_action,
keyboard::Modifiers,
peniko::kurbo::Rect,
reactive::{RwSignal, Scope, SignalGet, SignalUpdate, SignalWith},
};
use lapce_core::{command::FocusCommand, mode::Mode, selection::Selection};
use lapce_rpc::proxy::ProxyResponse;
use lapce_xi_rope::Rope;
use lsp_types::Position;
use crate::{
command::{CommandExecuted, CommandKind, InternalCommand, LapceCommand},
editor::EditorData,
keypress::{KeyPressFocus, condition::Condition},
main_split::Editors,
window_tab::{CommonData, Focus},
};
#[derive(Clone, Debug)]
pub struct RenameData {
pub active: RwSignal<bool>,
pub editor: EditorData,
pub start: RwSignal<usize>,
pub position: RwSignal<Position>,
pub path: RwSignal<PathBuf>,
pub layout_rect: RwSignal<Rect>,
pub common: Rc<CommonData>,
}
impl KeyPressFocus for RenameData {
fn get_mode(&self) -> Mode {
Mode::Insert
}
fn check_condition(&self, condition: Condition) -> bool {
matches!(condition, Condition::RenameFocus | Condition::ModalFocus)
}
fn run_command(
&self,
command: &LapceCommand,
count: Option<usize>,
mods: Modifiers,
) -> CommandExecuted {
match &command.kind {
CommandKind::Workbench(_) => {}
CommandKind::Scroll(_) => {}
CommandKind::Focus(cmd) => {
self.run_focus_command(cmd);
}
CommandKind::Edit(_)
| CommandKind::Move(_)
| CommandKind::MultiSelection(_) => {
self.editor.run_command(command, count, mods);
}
CommandKind::MotionMode(_) => {}
}
CommandExecuted::Yes
}
fn receive_char(&self, c: &str) {
self.editor.receive_char(c);
}
}
impl RenameData {
pub fn new(cx: Scope, editors: Editors, common: Rc<CommonData>) -> Self {
let active = cx.create_rw_signal(false);
let start = cx.create_rw_signal(0);
let position = cx.create_rw_signal(Position::default());
let layout_rect = cx.create_rw_signal(Rect::ZERO);
let path = cx.create_rw_signal(PathBuf::new());
let editor = editors.make_local(cx, common.clone());
Self {
active,
editor,
start,
position,
layout_rect,
path,
common,
}
}
pub fn start(
&self,
path: PathBuf,
placeholder: String,
start: usize,
position: Position,
) {
self.editor.doc().reload(Rope::from(&placeholder), true);
self.editor.cursor().update(|cursor| {
cursor.set_insert(Selection::region(0, placeholder.len()))
});
self.path.set(path);
self.start.set(start);
self.position.set(position);
self.active.set(true);
self.common.focus.set(Focus::Rename);
}
fn run_focus_command(&self, cmd: &FocusCommand) -> CommandExecuted {
match cmd {
FocusCommand::ModalClose => {
self.cancel();
}
FocusCommand::ConfirmRename => {
self.confirm();
}
_ => return CommandExecuted::No,
}
CommandExecuted::Yes
}
fn cancel(&self) {
self.active.set(false);
if let Focus::Rename = self.common.focus.get_untracked() {
self.common.focus.set(Focus::Workbench);
}
}
fn confirm(&self) {
let new_name = self
.editor
.doc()
.buffer
.with_untracked(|buffer| buffer.to_string());
let new_name = new_name.trim();
if !new_name.is_empty() {
let path = self.path.get_untracked();
let position = self.position.get_untracked();
let internal_command = self.common.internal_command;
let send = create_ext_action(self.common.scope, move |result| {
if let Ok(ProxyResponse::Rename { edit }) = result {
internal_command
.send(InternalCommand::ApplyWorkspaceEdit { edit });
}
});
self.common.proxy.rename(
path,
position,
new_name.to_string(),
move |result| {
send(result);
},
);
}
self.cancel();
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/snippet.rs | lapce-app/src/snippet.rs | use core::fmt;
use std::{fmt::Display, str::FromStr};
use anyhow::Error;
use once_cell::sync::Lazy;
use regex::Regex;
#[derive(Debug, PartialEq)]
pub enum SnippetElement {
Text(String),
PlaceHolder(usize, Vec<SnippetElement>),
Tabstop(usize),
}
impl Display for SnippetElement {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self {
SnippetElement::Text(text) => f.write_str(text),
SnippetElement::PlaceHolder(tab, elements) => {
// Trying to write to the provided buffer in the form "${tab:text}"
write!(f, "${{{tab}:")?;
for child_snippet_elm in elements {
// call ourselves recursively
fmt::Display::fmt(child_snippet_elm, f)?;
}
f.write_str("}")
}
SnippetElement::Tabstop(tab) => write!(f, "${tab}"),
}
}
}
impl SnippetElement {
pub fn len(&self) -> usize {
match &self {
SnippetElement::Text(text) => text.len(),
SnippetElement::PlaceHolder(_, elements) => {
elements.iter().map(|e| e.len()).sum()
}
SnippetElement::Tabstop(_) => 0,
}
}
#[inline]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
#[inline]
pub fn text(&self) -> String {
let mut buf = String::new();
self.write_text_to(&mut buf)
.expect("a write_to function returned an error unexpectedly");
buf
}
fn write_text_to<Buffer: fmt::Write>(&self, buf: &mut Buffer) -> fmt::Result {
match self {
SnippetElement::Text(text) => buf.write_str(text),
SnippetElement::PlaceHolder(_, elements) => {
for child_snippet_elm in elements {
// call ourselves recursively
child_snippet_elm.write_text_to(buf)?;
}
fmt::Result::Ok(())
}
SnippetElement::Tabstop(_) => fmt::Result::Ok(()),
}
}
}
#[derive(Debug, PartialEq)]
pub struct Snippet {
elements: Vec<SnippetElement>,
}
impl FromStr for Snippet {
type Err = Error;
#[inline]
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (elements, _) = Self::extract_elements(s, 0, &['$', '\\'], &['}']);
Ok(Snippet { elements })
}
}
impl Display for Snippet {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for snippet_element in self.elements.iter() {
fmt::Display::fmt(snippet_element, f)?;
}
fmt::Result::Ok(())
}
}
impl Snippet {
#[inline]
fn extract_elements(
s: &str,
pos: usize,
escs: &[char],
loose_escs: &[char],
) -> (Vec<SnippetElement>, usize) {
let mut elements = Vec::new();
let mut pos = pos;
loop {
if s.len() == pos {
break;
} else if let Some((ele, end)) = Self::extract_tabstop(s, pos) {
elements.push(ele);
pos = end;
} else if let Some((ele, end)) = Self::extract_placeholder(s, pos) {
elements.push(ele);
pos = end;
} else if let Some((ele, end)) =
Self::extract_text(s, pos, escs, loose_escs)
{
elements.push(ele);
pos = end;
} else {
break;
}
}
(elements, pos)
}
#[inline]
fn extract_tabstop(str: &str, pos: usize) -> Option<(SnippetElement, usize)> {
// Regex for `$...` pattern, where `...` is some number (for example `$1`)
static REGEX_FIRST: Lazy<Regex> =
Lazy::new(|| Regex::new(r"^\$(\d+)").unwrap());
// Regex for `${...}` pattern, where `...` is some number (for example `${1}`)
static REGEX_SECOND: Lazy<Regex> =
Lazy::new(|| Regex::new(r"^\$\{(\d+)\}").unwrap());
let str = &str[pos..];
if let Some(matched) = REGEX_FIRST.find(str) {
// SAFETY:
// * The start index is guaranteed not to exceed the end index, since we
// compare with the `$ ...` pattern, and, therefore, the first element
// is always equal to the symbol `$`;
// * The indices are within the bounds of the original slice and lie on
// UTF-8 sequence boundaries, since we take the entire slice, with the
// exception of the first `$` char which is 1 byte in accordance with
// the UTF-8 standard.
let n = unsafe {
matched.as_str().get_unchecked(1..).parse::<usize>().ok()?
};
let end = pos + matched.end();
return Some((SnippetElement::Tabstop(n), end));
}
if let Some(matched) = REGEX_SECOND.find(str) {
let matched = matched.as_str();
// SAFETY:
// * The start index is guaranteed not to exceed the end index, since we
// compare with the `${...}` pattern, and, therefore, the first two elements
// are always equal to the `${` and the last one is equal to `}`;
// * The indices are within the bounds of the original slice and lie on UTF-8
// sequence boundaries, since we take the entire slice, with the exception
// of the first two `${` and last one `}` chars each of which is 1 byte in
// accordance with the UTF-8 standard.
let n = unsafe {
matched
.get_unchecked(2..matched.len() - 1)
.parse::<usize>()
.ok()?
};
let end = pos + matched.len();
return Some((SnippetElement::Tabstop(n), end));
}
None
}
#[inline]
fn extract_placeholder(s: &str, pos: usize) -> Option<(SnippetElement, usize)> {
// Regex for `${num:text}` pattern, where text can be empty (for example `${1:first}`
// and `${2:}`)
static REGEX: Lazy<Regex> =
Lazy::new(|| Regex::new(r"^\$\{(\d+):(.*?)\}").unwrap());
let caps = REGEX.captures(&s[pos..])?;
let tab = caps.get(1)?.as_str().parse::<usize>().ok()?;
let m = caps.get(2)?;
let content = m.as_str();
if content.is_empty() {
return Some((
SnippetElement::PlaceHolder(
tab,
vec![SnippetElement::Text(String::new())],
),
pos + caps.get(0).unwrap().end(),
));
}
let (els, pos) =
Self::extract_elements(s, pos + m.start(), &['$', '}', '\\'], &[]);
Some((SnippetElement::PlaceHolder(tab, els), pos + 1))
}
#[inline]
fn extract_text(
s: &str,
pos: usize,
escs: &[char],
loose_escs: &[char],
) -> Option<(SnippetElement, usize)> {
let mut ele = String::new();
let mut end = pos;
let mut chars_iter = s[pos..].chars().peekable();
while let Some(char) = chars_iter.next() {
if char == '\\' {
if let Some(&next) = chars_iter.peek() {
if escs.iter().chain(loose_escs.iter()).any(|c| *c == next) {
chars_iter.next();
ele.push(next);
end += 1 + next.len_utf8();
continue;
}
}
}
if escs.contains(&char) {
break;
}
ele.push(char);
end += char.len_utf8();
}
if ele.is_empty() {
return None;
}
Some((SnippetElement::Text(ele), end))
}
#[inline]
pub fn text(&self) -> String {
let mut buf = String::new();
self.write_text_to(&mut buf)
.expect("Snippet::write_text_to function unexpectedly return error");
buf
}
#[inline]
fn write_text_to<Buffer: fmt::Write>(&self, buf: &mut Buffer) -> fmt::Result {
for snippet_element in self.elements.iter() {
snippet_element.write_text_to(buf)?
}
fmt::Result::Ok(())
}
#[inline]
pub fn tabs(&self, pos: usize) -> Vec<(usize, (usize, usize))> {
Self::elements_tabs(&self.elements, pos)
}
pub fn elements_tabs(
elements: &[SnippetElement],
start: usize,
) -> Vec<(usize, (usize, usize))> {
let mut tabs = Vec::new();
let mut pos = start;
for el in elements {
match el {
SnippetElement::Text(t) => {
pos += t.len();
}
SnippetElement::PlaceHolder(tab, els) => {
let placeholder_tabs = Self::elements_tabs(els, pos);
let end = pos + els.iter().map(|e| e.len()).sum::<usize>();
tabs.push((*tab, (pos, end)));
tabs.extend_from_slice(&placeholder_tabs);
pos = end;
}
SnippetElement::Tabstop(tab) => {
tabs.push((*tab, (pos, pos)));
}
}
}
tabs
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_snippet() {
use SnippetElement::*;
let s = "start $1${2:second ${3:third}} $0";
let parsed = Snippet::from_str(s).unwrap();
assert_eq!(s, parsed.to_string());
let text = "start second third ";
assert_eq!(text, parsed.text());
assert_eq!(
vec![(1, (6, 6)), (2, (6, 18)), (3, (13, 18)), (0, (19, 19))],
parsed.tabs(0)
);
let s = "start ${1}${2:second ${3:third}} $0and ${4}fourth";
let parsed = Snippet::from_str(s).unwrap();
assert_eq!(
"start $1${2:second ${3:third}} $0and $4fourth",
parsed.to_string()
);
let text = "start second third and fourth";
assert_eq!(text, parsed.text());
assert_eq!(
vec![
(1, (6, 6)),
(2, (6, 18)),
(3, (13, 18)),
(0, (19, 19)),
(4, (23, 23))
],
parsed.tabs(0)
);
let s = "${1:first $6${2:second ${7}${3:third ${4:fourth ${5:fifth}}}}}";
let parsed = Snippet::from_str(s).unwrap();
assert_eq!(
"${1:first $6${2:second $7${3:third ${4:fourth ${5:fifth}}}}}",
parsed.to_string()
);
let text = "first second third fourth fifth";
assert_eq!(text, parsed.text());
assert_eq!(
vec![
(1, (0, 31)),
(6, (6, 6)),
(2, (6, 31)),
(7, (13, 13)),
(3, (13, 31)),
(4, (19, 31)),
(5, (26, 31))
],
parsed.tabs(0)
);
assert_eq!(
Snippet {
elements: vec![PlaceHolder(
1,
vec![
Text("first ".into()),
Tabstop(6),
PlaceHolder(
2,
vec![
Text("second ".into()),
Tabstop(7),
PlaceHolder(
3,
vec![
Text("third ".into()),
PlaceHolder(
4,
vec![
Text("fourth ".into()),
PlaceHolder(
5,
vec![Text("fifth".into())]
)
]
)
]
)
]
)
]
)]
},
parsed
);
let s = "\\$1 start \\$2$3${4}${5:some text\\${6:third\\} $7}";
let parsed = Snippet::from_str(s).unwrap();
assert_eq!(
"$1 start $2$3$4${5:some text${6:third} $7}",
parsed.to_string()
);
let text = "$1 start $2some text${6:third} ";
assert_eq!(text, parsed.text());
assert_eq!(
vec![(3, (11, 11)), (4, (11, 11)), (5, (11, 31)), (7, (31, 31))],
parsed.tabs(0)
);
assert_eq!(
Snippet {
elements: vec![
Text("$1 start $2".into()),
Tabstop(3),
Tabstop(4),
PlaceHolder(
5,
vec![Text("some text${6:third} ".into()), Tabstop(7)]
)
]
},
parsed
);
}
#[test]
fn test_extract_tabstop() {
fn vec_of_tab_elms(s: &str) -> Vec<(usize, usize)> {
let mut pos = 0;
let mut vec = Vec::new();
for char in s.chars() {
if let Some((SnippetElement::Tabstop(stop), end)) =
Snippet::extract_tabstop(s, pos)
{
vec.push((stop, end));
}
pos += char.len_utf8();
}
vec
}
let s = "start $1${2:second ${3:third}} $0";
assert_eq!(&[(1, 8), (0, 33)][..], &vec_of_tab_elms(s)[..]);
let s = "start ${1}${2:second ${3:third}} $0and ${4}fourth";
assert_eq!(&[(1, 10), (0, 35), (4, 43)][..], &vec_of_tab_elms(s)[..]);
let s = "$s$1first${2}$second$3${4}${5}$6and${7}$8fourth$9$$$10$$${11}$$$12$$$13$$${14}$$${15}";
assert_eq!(
&[
(1, 4),
(2, 13),
(3, 22),
(4, 26),
(5, 30),
(6, 32),
(7, 39),
(8, 41),
(9, 49),
(10, 54),
(11, 61),
(12, 66),
(13, 71),
(14, 78),
(15, 85)
][..],
&vec_of_tab_elms(s)[..]
);
let s = "$s$1ένα${2}$τρία$3${4}${5}$6τέσσερα${7}$8πέντε$9$$$10$$${11}$$$12$$$13$$${14}$$${15}";
assert_eq!(
&[
(1, 4),
(2, 14),
(3, 25),
(4, 29),
(5, 33),
(6, 35),
(7, 53),
(8, 55),
(9, 67),
(10, 72),
(11, 79),
(12, 84),
(13, 89),
(14, 96),
(15, 103)
][..],
&vec_of_tab_elms(s)[..]
);
}
#[test]
fn test_extract_placeholder() {
use super::SnippetElement::*;
let s1 = "${1:first ${2:second ${3:third ${4:fourth ${5:fifth}}}}}";
assert_eq!(
(
PlaceHolder(
1,
vec![
Text("first ".into()),
PlaceHolder(
2,
vec![
Text("second ".into()),
PlaceHolder(
3,
vec![
Text("third ".into()),
PlaceHolder(
4,
vec![
Text("fourth ".into()),
PlaceHolder(
5,
vec![Text("fifth".into())]
)
]
)
]
)
]
)
]
),
56
),
Snippet::extract_placeholder(s1, 0).unwrap()
);
let s1 = "${1:first}${2:second}${3:third }${4:fourth ${5:fifth}}}}}";
assert_eq!(
(PlaceHolder(1, vec![Text("first".to_owned())]), 10),
Snippet::extract_placeholder(s1, 0).unwrap()
);
assert_eq!(
(PlaceHolder(2, vec![Text("second".to_owned())]), 21),
Snippet::extract_placeholder(s1, 10).unwrap()
);
assert_eq!(
(PlaceHolder(3, vec![Text("third ".to_owned())]), 32),
Snippet::extract_placeholder(s1, 21).unwrap()
);
assert_eq!(
(
PlaceHolder(
4,
vec![
Text("fourth ".into()),
PlaceHolder(5, vec![Text("fifth".into())])
]
),
54
),
Snippet::extract_placeholder(s1, 32).unwrap()
);
}
#[test]
fn test_extract_text() {
use SnippetElement::*;
// 1. ====================================================================================
let s = "start $1${2:second ${3:third}} $0";
let (snip_elm, end) = Snippet::extract_text(s, 0, &['$'], &[]).unwrap();
assert_eq!((Text("start ".to_owned()), 6), (snip_elm, end));
let (snip_elm, end) =
Snippet::extract_text(s, end + 1, &['$'], &[]).unwrap();
assert_eq!((Text("1".to_owned()), 8), (snip_elm, end));
let (snip_elm, end) =
Snippet::extract_text(s, end + 1, &['$'], &[]).unwrap();
assert_eq!((Text("{2:second ".to_owned()), 19), (snip_elm, end));
let (snip_elm, end) =
Snippet::extract_text(s, end + 1, &['$'], &[]).unwrap();
assert_eq!((Text("{3:third}} ".to_owned()), 31), (snip_elm, end));
let (snip_elm, end) =
Snippet::extract_text(s, end + 1, &['$'], &[]).unwrap();
assert_eq!((Text("0".to_owned()), 33), (snip_elm, end));
// 2. ====================================================================================
let s = "start $1${2:second ${3:third}} $0";
let (snip_elm, end) = Snippet::extract_text(s, 0, &['{'], &[]).unwrap();
assert_eq!((Text("start $1$".to_owned()), 9), (snip_elm, end));
let (snip_elm, end) =
Snippet::extract_text(s, end + 1, &['{'], &[]).unwrap();
assert_eq!((Text("2:second $".to_owned()), 20), (snip_elm, end));
let (snip_elm, end) =
Snippet::extract_text(s, end + 1, &['{'], &[]).unwrap();
assert_eq!((Text("3:third}} $0".to_owned()), 33), (snip_elm, end));
// 3. ====================================================================================
let s = "start $1${2:second ${3:third}} $0";
let (snip_elm, end) = Snippet::extract_text(s, 0, &['}'], &[]).unwrap();
assert_eq!(
(Text("start $1${2:second ${3:third".to_owned()), 28),
(snip_elm, end)
);
assert_eq!(None, Snippet::extract_text(s, end + 1, &['}'], &[]));
let (snip_elm, end) =
Snippet::extract_text(s, end + 2, &['}'], &[]).unwrap();
assert_eq!((Text(" $0".to_owned()), 33), (snip_elm, end));
// 4. ====================================================================================
let s = "start $1${2:second ${3:third}} $0";
let (snip_elm, end) = Snippet::extract_text(s, 0, &['\\'], &[]).unwrap();
assert_eq!((Text(s.to_owned()), 33), (snip_elm, end));
// 5. ====================================================================================
let s = "start \\$1${2:second \\${3:third}} $0";
let (snip_elm, end) =
Snippet::extract_text(s, 0, &['$', '\\'], &[]).unwrap();
assert_eq!((Text("start $1".to_owned()), 9), (snip_elm, end));
let (snip_elm, end) =
Snippet::extract_text(s, end + 1, &['$', '\\'], &[]).unwrap();
assert_eq!(
(Text("{2:second ${3:third}} ".to_owned()), 33),
(snip_elm, end)
);
let (snip_elm, end) =
Snippet::extract_text(s, end + 1, &['$', '\\'], &[]).unwrap();
assert_eq!((Text("0".to_owned()), 35), (snip_elm, end));
// 6. ====================================================================================
let s = "\\{start $1${2:second $\\{3:third}} $0}";
let (snip_elm, end) =
Snippet::extract_text(s, 0, &['{', '\\'], &[]).unwrap();
assert_eq!((Text("{start $1$".to_owned()), 11), (snip_elm, end));
let (snip_elm, end) =
Snippet::extract_text(s, end + 1, &['{', '\\'], &[]).unwrap();
assert_eq!(
(Text("2:second ${3:third}} $0}".to_owned()), 37),
(snip_elm, end)
);
// 7. ====================================================================================
let s = "{start $1${2}:second $\\{3:third}} $0}";
let (snip_elm, end) =
Snippet::extract_text(s, 0, &['}', '\\'], &[]).unwrap();
assert_eq!((Text("{start $1${2".to_owned()), 12), (snip_elm, end));
let (snip_elm, end) =
Snippet::extract_text(s, end + 1, &['}', '\\'], &[]).unwrap();
assert_eq!((Text(":second $".to_owned()), 22), (snip_elm, end));
assert_eq!(None, Snippet::extract_text(s, end, &['}', '\\'], &[]));
let (snip_elm, end) =
Snippet::extract_text(s, end + 1, &['}', '\\'], &[]).unwrap();
assert_eq!((Text("{3:third".to_owned()), 31), (snip_elm, end));
assert_eq!(None, Snippet::extract_text(s, end + 1, &['}', '\\'], &[]));
let (snip_elm, end) =
Snippet::extract_text(s, end + 2, &['}', '\\'], &[]).unwrap();
assert_eq!((Text(" $0".to_owned()), 36), (snip_elm, end));
// 8. ====================================================================================
let s = "{start $1${2}:second $\\{3:third}} $0}";
let (snip_elm, end) =
Snippet::extract_text(s, 0, &['$', '\\'], &['}']).unwrap();
assert_eq!((Text("{start ".to_owned()), 7), (snip_elm, end));
let (snip_elm, end) =
Snippet::extract_text(s, end + 1, &['$', '\\'], &['}']).unwrap();
assert_eq!((Text("1".to_owned()), 9), (snip_elm, end));
let (snip_elm, end) =
Snippet::extract_text(s, end + 1, &['$', '\\'], &['}']).unwrap();
assert_eq!((Text("{2}:second ".to_owned()), 21), (snip_elm, end));
assert_eq!(
None,
Snippet::extract_text(s, end + 1, &['$', '\\'], &['}'])
);
let (snip_elm, end) =
Snippet::extract_text(s, end + 2, &['$', '\\'], &['}']).unwrap();
assert_eq!((Text("{3:third}} ".to_owned()), 34), (snip_elm, end));
let (snip_elm, end) =
Snippet::extract_text(s, end + 1, &['$', '\\'], &['}']).unwrap();
assert_eq!((Text("0}".to_owned()), 37), (snip_elm, end));
// 9. ====================================================================================
let s = "{start $1${2}:second $\\{3:third}} $0}";
let (snip_elm, end) =
Snippet::extract_text(s, 0, &['$', '}', '\\'], &[]).unwrap();
assert_eq!((Text("{start ".to_owned()), 7), (snip_elm, end));
let (snip_elm, end) =
Snippet::extract_text(s, end + 1, &['$', '}', '\\'], &[]).unwrap();
assert_eq!((Text("1".to_owned()), 9), (snip_elm, end));
let (snip_elm, end) =
Snippet::extract_text(s, end + 1, &['$', '}', '\\'], &[]).unwrap();
assert_eq!((Text("{2".to_owned()), 12), (snip_elm, end));
let (snip_elm, end) =
Snippet::extract_text(s, end + 1, &['$', '}', '\\'], &[]).unwrap();
assert_eq!((Text(":second ".to_owned()), 21), (snip_elm, end));
assert_eq!(
None,
Snippet::extract_text(s, end + 1, &['$', '}', '\\'], &[])
);
let (snip_elm, end) =
Snippet::extract_text(s, end + 2, &['$', '}', '\\'], &[]).unwrap();
assert_eq!((Text("{3:third".to_owned()), 31), (snip_elm, end));
assert_eq!(
None,
Snippet::extract_text(s, end + 1, &['$', '}', '\\'], &[])
);
let (snip_elm, end) =
Snippet::extract_text(s, end + 2, &['$', '}', '\\'], &[]).unwrap();
assert_eq!((Text(" ".to_owned()), 34), (snip_elm, end));
let (snip_elm, end) =
Snippet::extract_text(s, end + 1, &['$', '}', '\\'], &[]).unwrap();
assert_eq!((Text("0".to_owned()), 36), (snip_elm, end));
assert_eq!(
None,
Snippet::extract_text(s, end + 1, &['$', '}', '\\'], &[])
);
// 10. ====================================================================================
let s = "{start $1${2}:second $\\{3:third}} $0}";
assert_eq!(
None,
Snippet::extract_text(s, 0, &['$', '{', '}', '\\'], &[])
);
let (snip_elm, end) =
Snippet::extract_text(s, 1, &['$', '{', '}', '\\'], &[]).unwrap();
assert_eq!((Text("start ".to_owned()), 7), (snip_elm, end));
let (snip_elm, end) =
Snippet::extract_text(s, end + 1, &['$', '{', '}', '\\'], &[]).unwrap();
assert_eq!((Text("1".to_owned()), 9), (snip_elm, end));
assert_eq!(
None,
Snippet::extract_text(s, end + 1, &['$', '{', '}', '\\'], &[])
);
let (snip_elm, end) =
Snippet::extract_text(s, end + 2, &['$', '{', '}', '\\'], &[]).unwrap();
assert_eq!((Text("2".to_owned()), 12), (snip_elm, end));
let (snip_elm, end) =
Snippet::extract_text(s, end + 1, &['$', '{', '}', '\\'], &[]).unwrap();
assert_eq!((Text(":second ".to_owned()), 21), (snip_elm, end));
let (snip_elm, end) =
Snippet::extract_text(s, end + 1, &['$', '{', '}', '\\'], &[]).unwrap();
assert_eq!((Text("{3:third".to_owned()), 31), (snip_elm, end));
assert_eq!(
None,
Snippet::extract_text(s, end + 1, &['$', '{', '}', '\\'], &[])
);
let (snip_elm, end) =
Snippet::extract_text(s, end + 2, &['$', '{', '}', '\\'], &[]).unwrap();
assert_eq!((Text(" ".to_owned()), 34), (snip_elm, end));
let (snip_elm, end) =
Snippet::extract_text(s, end + 1, &['$', '{', '}', '\\'], &[]).unwrap();
assert_eq!((Text("0".to_owned()), 36), (snip_elm, end));
assert_eq!(
None,
Snippet::extract_text(s, end + 1, &['$', '{', '}', '\\'], &[])
);
// 11. ====================================================================================
let s = "{start\\\\ $1${2}:second\\ $\\{3:third}} $0}";
assert_eq!(
None,
Snippet::extract_text(s, 0, &['$', '{', '}', '\\'], &[])
);
let (snip_elm, end) =
Snippet::extract_text(s, 1, &['$', '{', '}', '\\'], &[]).unwrap();
assert_eq!((Text("start\\ ".to_owned()), 9), (snip_elm, end));
let (snip_elm, end) =
Snippet::extract_text(s, end + 1, &['$', '{', '}', '\\'], &[]).unwrap();
assert_eq!((Text("1".to_owned()), 11), (snip_elm, end));
assert_eq!(
None,
Snippet::extract_text(s, end + 1, &['$', '{', '}', '\\'], &[])
);
let (snip_elm, end) =
Snippet::extract_text(s, end + 2, &['$', '{', '}', '\\'], &[]).unwrap();
assert_eq!((Text("2".to_owned()), 14), (snip_elm, end));
let (snip_elm, end) =
Snippet::extract_text(s, end + 1, &['$', '{', '}', '\\'], &[]).unwrap();
assert_eq!((Text(":second".to_owned()), 22), (snip_elm, end));
let (snip_elm, end) =
Snippet::extract_text(s, end + 1, &['$', '{', '}', '\\'], &[]).unwrap();
assert_eq!((Text(" ".to_owned()), 24), (snip_elm, end));
let (snip_elm, end) =
Snippet::extract_text(s, end + 1, &['$', '{', '}', '\\'], &[]).unwrap();
assert_eq!((Text("{3:third".to_owned()), 34), (snip_elm, end));
assert_eq!(
None,
Snippet::extract_text(s, end + 1, &['$', '{', '}', '\\'], &[])
);
let (snip_elm, end) =
Snippet::extract_text(s, end + 2, &['$', '{', '}', '\\'], &[]).unwrap();
assert_eq!((Text(" ".to_owned()), 37), (snip_elm, end));
let (snip_elm, end) =
Snippet::extract_text(s, end + 1, &['$', '{', '}', '\\'], &[]).unwrap();
assert_eq!((Text("0".to_owned()), 39), (snip_elm, end));
assert_eq!(
None,
Snippet::extract_text(s, end + 1, &['$', '{', '}', '\\'], &[])
);
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/editor.rs | lapce-app/src/editor.rs | use std::{
collections::{HashMap, HashSet},
rc::Rc,
str::FromStr,
sync::Arc,
time::Duration,
};
use floem::{
ViewId,
action::{TimerToken, exec_after, show_context_menu},
ext_event::create_ext_action,
keyboard::Modifiers,
kurbo::{Point, Rect, Vec2},
menu::{Menu, MenuItem},
pointer::{MouseButton, PointerInputEvent, PointerMoveEvent},
prelude::SignalTrack,
reactive::{
ReadSignal, RwSignal, Scope, SignalGet, SignalUpdate, SignalWith, batch,
use_context,
},
views::editor::{
Editor,
command::CommandExecuted,
id::EditorId,
movement,
text::Document,
view::{
DiffSection, DiffSectionKind, LineInfo, ScreenLines, ScreenLinesBase,
},
visual_line::{ConfigId, Lines, TextLayoutProvider, VLine, VLineInfo},
},
};
use itertools::Itertools;
use lapce_core::{
buffer::{
InvalLines,
diff::DiffLines,
rope_text::{RopeText, RopeTextVal},
},
command::{
EditCommand, FocusCommand, MotionModeCommand, MultiSelectionCommand,
ScrollCommand,
},
cursor::{Cursor, CursorMode},
editor::EditType,
mode::{Mode, MotionMode},
rope_text_pos::RopeTextPosition,
selection::{InsertDrift, SelRegion, Selection},
};
use lapce_rpc::{buffer::BufferId, plugin::PluginId, proxy::ProxyResponse};
use lapce_xi_rope::{Rope, RopeDelta, Transformer};
use lsp_types::{
CodeActionResponse, CompletionItem, CompletionTextEdit, GotoDefinitionResponse,
HoverContents, InlayHint, InlayHintLabel, InlineCompletionTriggerKind, Location,
MarkedString, MarkupKind, Range, TextEdit,
};
use nucleo::Utf32Str;
use serde::{Deserialize, Serialize};
use view::StickyHeaderInfo;
use self::{
diff::DiffInfo,
location::{EditorLocation, EditorPosition},
};
use crate::{
command::{CommandKind, InternalCommand, LapceCommand, LapceWorkbenchCommand},
completion::CompletionStatus,
config::LapceConfig,
db::LapceDb,
doc::{Doc, DocContent},
editor_tab::EditorTabChild,
id::{DiffEditorId, EditorTabId},
inline_completion::{InlineCompletionItem, InlineCompletionStatus},
keypress::{KeyPressFocus, condition::Condition},
lsp::path_from_url,
main_split::{Editors, MainSplitData, SplitDirection, SplitMoveDirection},
markdown::{
MarkdownContent, from_marked_string, from_plaintext, parse_markdown,
},
panel::{
call_hierarchy_view::CallHierarchyItemData,
implementation_view::{init_implementation_root, map_to_location},
kind::PanelKind,
},
snippet::Snippet,
tracing::*,
window_tab::{CommonData, Focus, WindowTabData},
};
pub mod diff;
pub mod gutter;
pub mod location;
pub mod view;
#[derive(Clone, Debug)]
pub enum InlineFindDirection {
Left,
Right,
}
#[derive(Clone, Serialize, Deserialize)]
pub struct EditorInfo {
pub content: DocContent,
pub unsaved: Option<String>,
pub offset: usize,
pub scroll_offset: (f64, f64),
}
impl EditorInfo {
pub fn to_data(
&self,
data: MainSplitData,
editor_tab_id: EditorTabId,
) -> EditorId {
let editors = &data.editors;
let common = data.common.clone();
match &self.content {
DocContent::File { path, .. } => {
let (doc, new_doc) =
data.get_doc(path.clone(), self.unsaved.clone());
let editor = editors.make_from_doc(
data.scope,
doc,
Some(editor_tab_id),
None,
None,
common,
);
editor.go_to_location(
EditorLocation {
path: path.clone(),
position: Some(EditorPosition::Offset(self.offset)),
scroll_offset: Some(Vec2::new(
self.scroll_offset.0,
self.scroll_offset.1,
)),
ignore_unconfirmed: false,
same_editor_tab: false,
},
new_doc,
None,
);
editor.id()
}
DocContent::Local => editors.new_local(data.scope, common),
DocContent::History(_) => editors.new_local(data.scope, common),
DocContent::Scratch { name, .. } => {
let doc = data
.scratch_docs
.try_update(|scratch_docs| {
if let Some(doc) = scratch_docs.get(name) {
return doc.clone();
}
let content = DocContent::Scratch {
id: BufferId::next(),
name: name.to_string(),
};
let doc = Doc::new_content(
data.scope,
content,
data.editors,
data.common.clone(),
);
let doc = Rc::new(doc);
if let Some(unsaved) = &self.unsaved {
doc.reload(Rope::from(unsaved), false);
}
scratch_docs.insert(name.to_string(), doc.clone());
doc
})
.unwrap();
editors.new_from_doc(
data.scope,
doc,
Some(editor_tab_id),
None,
None,
common,
)
}
}
}
}
#[derive(Clone)]
pub enum EditorViewKind {
Normal,
Diff(DiffInfo),
}
impl EditorViewKind {
pub fn is_normal(&self) -> bool {
matches!(self, EditorViewKind::Normal)
}
}
#[derive(Clone)]
pub struct OnScreenFind {
pub active: bool,
pub pattern: String,
pub regions: Vec<SelRegion>,
}
pub type SnippetIndex = Vec<(usize, (usize, usize))>;
/// Shares data between cloned instances as long as the signals aren't swapped out.
#[derive(Clone, Debug)]
pub struct EditorData {
pub scope: Scope,
pub editor_tab_id: RwSignal<Option<EditorTabId>>,
pub diff_editor_id: RwSignal<Option<(EditorTabId, DiffEditorId)>>,
pub confirmed: RwSignal<bool>,
pub snippet: RwSignal<Option<SnippetIndex>>,
pub inline_find: RwSignal<Option<InlineFindDirection>>,
pub on_screen_find: RwSignal<OnScreenFind>,
pub last_inline_find: RwSignal<Option<(InlineFindDirection, String)>>,
pub find_focus: RwSignal<bool>,
pub editor: Rc<Editor>,
pub kind: RwSignal<EditorViewKind>,
pub sticky_header_height: RwSignal<f64>,
pub common: Rc<CommonData>,
pub sticky_header_info: RwSignal<StickyHeaderInfo>,
}
impl PartialEq for EditorData {
fn eq(&self, other: &Self) -> bool {
self.id() == other.id()
}
}
impl EditorData {
fn new(
cx: Scope,
editor: Editor,
editor_tab_id: Option<EditorTabId>,
diff_editor_id: Option<(EditorTabId, DiffEditorId)>,
confirmed: Option<RwSignal<bool>>,
common: Rc<CommonData>,
) -> Self {
let cx = cx.create_child();
let confirmed = confirmed.unwrap_or_else(|| cx.create_rw_signal(false));
EditorData {
scope: cx,
editor_tab_id: cx.create_rw_signal(editor_tab_id),
diff_editor_id: cx.create_rw_signal(diff_editor_id),
confirmed,
snippet: cx.create_rw_signal(None),
inline_find: cx.create_rw_signal(None),
on_screen_find: cx.create_rw_signal(OnScreenFind {
active: false,
pattern: "".to_string(),
regions: Vec::new(),
}),
last_inline_find: cx.create_rw_signal(None),
find_focus: cx.create_rw_signal(false),
editor: Rc::new(editor),
kind: cx.create_rw_signal(EditorViewKind::Normal),
sticky_header_height: cx.create_rw_signal(0.0),
common,
sticky_header_info: cx.create_rw_signal(StickyHeaderInfo::default()),
}
}
/// Create a new local editor.
/// You should prefer calling [`Editors::make_local`] / [`Editors::new_local`] instead to
/// register the editor.
pub fn new_local(cx: Scope, editors: Editors, common: Rc<CommonData>) -> Self {
Self::new_local_id(cx, EditorId::next(), editors, common)
}
/// Create a new local editor with the given id.
/// You should prefer calling [`Editors::make_local`] / [`Editors::new_local`] instead to
/// register the editor.
pub fn new_local_id(
cx: Scope,
editor_id: EditorId,
editors: Editors,
common: Rc<CommonData>,
) -> Self {
let cx = cx.create_child();
let doc = Rc::new(Doc::new_local(cx, editors, common.clone()));
let editor = doc.create_editor(cx, editor_id, true);
Self::new(cx, editor, None, None, None, common)
}
/// Create a new editor with a specific doc.
/// You should prefer calling [`Editors::new_editor_doc`] / [`Editors::make_from_doc`] instead.
pub fn new_doc(
cx: Scope,
doc: Rc<Doc>,
editor_tab_id: Option<EditorTabId>,
diff_editor_id: Option<(EditorTabId, DiffEditorId)>,
confirmed: Option<RwSignal<bool>>,
common: Rc<CommonData>,
) -> Self {
let editor = doc.create_editor(cx, EditorId::next(), false);
Self::new(cx, editor, editor_tab_id, diff_editor_id, confirmed, common)
}
/// Swap out the document this editor is for
pub fn update_doc(&self, doc: Rc<Doc>) {
let style = doc.styling();
self.editor.update_doc(doc, Some(style));
}
/// Create a new editor using the same underlying [`Doc`]
pub fn copy(
&self,
cx: Scope,
editor_tab_id: Option<EditorTabId>,
diff_editor_id: Option<(EditorTabId, DiffEditorId)>,
confirmed: Option<RwSignal<bool>>,
) -> Self {
let cx = cx.create_child();
let confirmed = confirmed.unwrap_or_else(|| cx.create_rw_signal(true));
let editor = Self::new_doc(
cx,
self.doc(),
editor_tab_id,
diff_editor_id,
Some(confirmed),
self.common.clone(),
);
editor.editor.cursor.set(self.editor.cursor.get_untracked());
editor
.editor
.viewport
.set(self.editor.viewport.get_untracked());
editor.editor.scroll_to.set(Some(
self.editor.viewport.get_untracked().origin().to_vec2(),
));
editor
.editor
.last_movement
.set(self.editor.last_movement.get_untracked());
editor
}
pub fn id(&self) -> EditorId {
self.editor.id()
}
pub fn editor_info(&self, _data: &WindowTabData) -> EditorInfo {
let offset = self.cursor().get_untracked().offset();
let scroll_offset = self.viewport().get_untracked().origin();
let doc = self.doc();
let is_pristine = doc.is_pristine();
let unsaved = if is_pristine {
None
} else {
Some(doc.buffer.with_untracked(|b| b.to_string()))
};
EditorInfo {
content: self.doc().content.get_untracked(),
unsaved,
offset,
scroll_offset: (scroll_offset.x, scroll_offset.y),
}
}
pub fn cursor(&self) -> RwSignal<Cursor> {
self.editor.cursor
}
pub fn viewport(&self) -> RwSignal<Rect> {
self.editor.viewport
}
pub fn window_origin(&self) -> RwSignal<Point> {
self.editor.window_origin
}
pub fn scroll_delta(&self) -> RwSignal<Vec2> {
self.editor.scroll_delta
}
pub fn scroll_to(&self) -> RwSignal<Option<Vec2>> {
self.editor.scroll_to
}
pub fn active(&self) -> RwSignal<bool> {
self.editor.active
}
/// Get the line information for lines on the screen.
pub fn screen_lines(&self) -> RwSignal<ScreenLines> {
self.editor.screen_lines
}
pub fn doc(&self) -> Rc<Doc> {
let doc = self.editor.doc();
let Ok(doc) = (doc as Rc<dyn ::std::any::Any>).downcast() else {
panic!("doc is not Rc<Doc>");
};
doc
}
/// The signal for the editor's document.
pub fn doc_signal(&self) -> DocSignal {
DocSignal {
inner: self.editor.doc_signal(),
}
}
pub fn text(&self) -> Rope {
self.editor.text()
}
pub fn rope_text(&self) -> RopeTextVal {
self.editor.rope_text()
}
fn run_edit_command(&self, cmd: &EditCommand) -> CommandExecuted {
let doc = self.doc();
let text = self.editor.rope_text();
let is_local = doc.content.with_untracked(|content| content.is_local());
let modal = self.editor.es.with_untracked(|s| s.modal()) && !is_local;
let smart_tab = self
.common
.config
.with_untracked(|config| config.editor.smart_tab);
let doc_before_edit = text.text().clone();
let mut cursor = self.editor.cursor.get_untracked();
let mut register = self.common.register.get_untracked();
let yank_data =
if let lapce_core::cursor::CursorMode::Visual { .. } = &cursor.mode {
Some(cursor.yank(&text))
} else {
None
};
let deltas =
batch(|| doc.do_edit(&mut cursor, cmd, modal, &mut register, smart_tab));
if !deltas.is_empty() {
if let Some(data) = yank_data {
register.add_delete(data);
}
}
self.editor.cursor.set(cursor);
self.editor.register.set(register);
if show_completion(cmd, &doc_before_edit, &deltas) {
self.update_completion(false);
} else {
self.cancel_completion();
}
if *cmd == EditCommand::InsertNewLine {
// Cancel so that there's no flickering
self.cancel_inline_completion();
self.update_inline_completion(InlineCompletionTriggerKind::Automatic);
self.quit_on_screen_find();
} else if show_inline_completion(cmd) {
self.update_inline_completion(InlineCompletionTriggerKind::Automatic);
} else {
self.cancel_inline_completion();
}
self.apply_deltas(&deltas);
if let EditCommand::NormalMode = cmd {
self.snippet.set(None);
self.quit_on_screen_find();
}
CommandExecuted::Yes
}
fn run_motion_mode_command(
&self,
cmd: &MotionModeCommand,
count: Option<usize>,
) -> CommandExecuted {
let count = count.unwrap_or(1);
let motion_mode = match cmd {
MotionModeCommand::MotionModeDelete => MotionMode::Delete { count },
MotionModeCommand::MotionModeIndent => MotionMode::Indent,
MotionModeCommand::MotionModeOutdent => MotionMode::Outdent,
MotionModeCommand::MotionModeYank => MotionMode::Yank { count },
};
let mut cursor = self.editor.cursor.get_untracked();
let mut register = self.common.register.get_untracked();
movement::do_motion_mode(
&self.editor,
&*self.doc(),
&mut cursor,
motion_mode,
&mut register,
);
self.editor.cursor.set(cursor);
self.common.register.set(register);
CommandExecuted::Yes
}
fn run_multi_selection_command(
&self,
cmd: &MultiSelectionCommand,
) -> CommandExecuted {
let mut cursor = self.editor.cursor.get_untracked();
let rope_text = self.rope_text();
let doc = self.doc();
let config = self.common.config.get_untracked();
// This is currently special-cased in Lapce because floem editor does not have 'find'
match cmd {
MultiSelectionCommand::SelectAllCurrent => {
if let CursorMode::Insert(mut selection) = cursor.mode.clone() {
if !selection.is_empty() {
let find = doc.find();
let first = selection.first().unwrap();
let (start, end) = if first.is_caret() {
rope_text.select_word(first.start)
} else {
(first.min(), first.max())
};
let search_str = rope_text.slice_to_cow(start..end);
let case_sensitive = find.case_sensitive(false);
let multicursor_case_sensitive =
config.editor.multicursor_case_sensitive;
let case_sensitive =
multicursor_case_sensitive || case_sensitive;
// let search_whole_word = config.editor.multicursor_whole_words;
find.set_case_sensitive(case_sensitive);
find.set_find(&search_str);
let mut offset = 0;
while let Some((start, end)) =
find.next(rope_text.text(), offset, false, false)
{
offset = end;
selection.add_region(SelRegion::new(start, end, None));
}
}
cursor.set_insert(selection);
}
}
MultiSelectionCommand::SelectNextCurrent => {
if let CursorMode::Insert(mut selection) = cursor.mode.clone() {
if !selection.is_empty() {
let mut had_caret = false;
for region in selection.regions_mut() {
if region.is_caret() {
had_caret = true;
let (start, end) =
rope_text.select_word(region.start);
region.start = start;
region.end = end;
}
}
if !had_caret {
let find = doc.find();
let r = selection.last_inserted().unwrap();
let search_str =
rope_text.slice_to_cow(r.min()..r.max());
let case_sensitive = find.case_sensitive(false);
let case_sensitive =
config.editor.multicursor_case_sensitive
|| case_sensitive;
// let search_whole_word =
// config.editor.multicursor_whole_words;
find.set_case_sensitive(case_sensitive);
find.set_find(&search_str);
let mut offset = r.max();
let mut seen = HashSet::new();
while let Some((start, end)) =
find.next(rope_text.text(), offset, false, true)
{
if !selection
.regions()
.iter()
.any(|r| r.min() == start && r.max() == end)
{
selection.add_region(SelRegion::new(
start, end, None,
));
break;
}
if seen.contains(&end) {
break;
}
offset = end;
seen.insert(offset);
}
}
}
cursor.set_insert(selection);
}
}
MultiSelectionCommand::SelectSkipCurrent => {
if let CursorMode::Insert(mut selection) = cursor.mode.clone() {
if !selection.is_empty() {
let r = selection.last_inserted().unwrap();
if r.is_caret() {
let (start, end) = rope_text.select_word(r.start);
selection.replace_last_inserted_region(SelRegion::new(
start, end, None,
));
} else {
let find = doc.find();
let search_str =
rope_text.slice_to_cow(r.min()..r.max());
find.set_find(&search_str);
let mut offset = r.max();
let mut seen = HashSet::new();
while let Some((start, end)) =
find.next(rope_text.text(), offset, false, true)
{
if !selection
.regions()
.iter()
.any(|r| r.min() == start && r.max() == end)
{
selection.replace_last_inserted_region(
SelRegion::new(start, end, None),
);
break;
}
if seen.contains(&end) {
break;
}
offset = end;
seen.insert(offset);
}
}
}
cursor.set_insert(selection);
}
}
_ => movement::do_multi_selection(&self.editor, &mut cursor, cmd),
};
self.editor.cursor.set(cursor);
// self.cancel_signature();
self.cancel_completion();
self.cancel_inline_completion();
CommandExecuted::Yes
}
fn run_move_command(
&self,
movement: &lapce_core::movement::Movement,
count: Option<usize>,
mods: Modifiers,
) -> CommandExecuted {
self.common.hover.active.set(false);
if movement.is_jump()
&& movement != &self.editor.last_movement.get_untracked()
{
let path = self
.doc()
.content
.with_untracked(|content| content.path().cloned());
if let Some(path) = path {
let offset = self.cursor().with_untracked(|c| c.offset());
let scroll_offset =
self.viewport().get_untracked().origin().to_vec2();
self.common.internal_command.send(
InternalCommand::SaveJumpLocation {
path,
offset,
scroll_offset,
},
);
}
}
self.editor.last_movement.set(movement.clone());
let mut cursor = self.cursor().get_untracked();
self.common.register.update(|register| {
movement::move_cursor(
&self.editor,
&*self.doc(),
&mut cursor,
movement,
count.unwrap_or(1),
mods.shift(),
register,
)
});
self.editor.cursor.set(cursor);
if self.snippet.with_untracked(|s| s.is_some()) {
self.snippet.update(|snippet| {
let offset = self.editor.cursor.get_untracked().offset();
let mut within_region = false;
for (_, (start, end)) in snippet.as_mut().unwrap() {
if offset >= *start && offset <= *end {
within_region = true;
break;
}
}
if !within_region {
*snippet = None;
}
})
}
self.cancel_completion();
CommandExecuted::Yes
}
pub fn run_scroll_command(
&self,
cmd: &ScrollCommand,
count: Option<usize>,
mods: Modifiers,
) -> CommandExecuted {
let prev_completion_index = self
.common
.completion
.with_untracked(|c| c.active.get_untracked());
match cmd {
ScrollCommand::PageUp => {
self.editor.page_move(false, mods);
}
ScrollCommand::PageDown => {
self.editor.page_move(true, mods);
}
ScrollCommand::ScrollUp => {
self.scroll(false, count.unwrap_or(1), mods);
}
ScrollCommand::ScrollDown => {
self.scroll(true, count.unwrap_or(1), mods);
}
// TODO:
ScrollCommand::CenterOfWindow => {}
ScrollCommand::TopOfWindow => {}
ScrollCommand::BottomOfWindow => {}
}
let current_completion_index = self
.common
.completion
.with_untracked(|c| c.active.get_untracked());
if prev_completion_index != current_completion_index {
self.common.completion.with_untracked(|c| {
let cursor_offset = self.cursor().with_untracked(|c| c.offset());
c.update_document_completion(self, cursor_offset);
});
}
CommandExecuted::Yes
}
pub fn run_focus_command(
&self,
cmd: &FocusCommand,
_count: Option<usize>,
mods: Modifiers,
) -> CommandExecuted {
// TODO(minor): Evaluate whether we should split this into subenums,
// such as actions specific to the actual editor pane, movement, and list movement.
let prev_completion_index = self
.common
.completion
.with_untracked(|c| c.active.get_untracked());
match cmd {
FocusCommand::ModalClose => {
self.cancel_completion();
}
FocusCommand::SplitVertical => {
if let Some(editor_tab_id) =
self.editor_tab_id.read_only().get_untracked()
{
self.common.internal_command.send(InternalCommand::Split {
direction: SplitDirection::Vertical,
editor_tab_id,
});
} else if let Some((editor_tab_id, _)) =
self.diff_editor_id.get_untracked()
{
self.common.internal_command.send(InternalCommand::Split {
direction: SplitDirection::Vertical,
editor_tab_id,
});
} else {
return CommandExecuted::No;
}
}
FocusCommand::SplitHorizontal => {
if let Some(editor_tab_id) = self.editor_tab_id.get_untracked() {
self.common.internal_command.send(InternalCommand::Split {
direction: SplitDirection::Horizontal,
editor_tab_id,
});
} else if let Some((editor_tab_id, _)) =
self.diff_editor_id.get_untracked()
{
self.common.internal_command.send(InternalCommand::Split {
direction: SplitDirection::Horizontal,
editor_tab_id,
});
} else {
return CommandExecuted::No;
}
}
FocusCommand::SplitRight => {
if let Some(editor_tab_id) = self.editor_tab_id.get_untracked() {
self.common
.internal_command
.send(InternalCommand::SplitMove {
direction: SplitMoveDirection::Right,
editor_tab_id,
});
} else if let Some((editor_tab_id, _)) =
self.diff_editor_id.get_untracked()
{
self.common
.internal_command
.send(InternalCommand::SplitMove {
direction: SplitMoveDirection::Right,
editor_tab_id,
});
} else {
return CommandExecuted::No;
}
}
FocusCommand::SplitLeft => {
if let Some(editor_tab_id) = self.editor_tab_id.get_untracked() {
self.common
.internal_command
.send(InternalCommand::SplitMove {
direction: SplitMoveDirection::Left,
editor_tab_id,
});
} else if let Some((editor_tab_id, _)) =
self.diff_editor_id.get_untracked()
{
self.common
.internal_command
.send(InternalCommand::SplitMove {
direction: SplitMoveDirection::Left,
editor_tab_id,
});
} else {
return CommandExecuted::No;
}
}
FocusCommand::SplitUp => {
if let Some(editor_tab_id) = self.editor_tab_id.get_untracked() {
self.common
.internal_command
.send(InternalCommand::SplitMove {
direction: SplitMoveDirection::Up,
editor_tab_id,
});
} else if let Some((editor_tab_id, _)) =
self.diff_editor_id.get_untracked()
{
self.common
.internal_command
.send(InternalCommand::SplitMove {
direction: SplitMoveDirection::Up,
editor_tab_id,
});
} else {
return CommandExecuted::No;
}
}
FocusCommand::SplitDown => {
if let Some(editor_tab_id) = self.editor_tab_id.get_untracked() {
self.common
.internal_command
.send(InternalCommand::SplitMove {
direction: SplitMoveDirection::Down,
editor_tab_id,
});
} else if let Some((editor_tab_id, _)) =
self.diff_editor_id.get_untracked()
{
self.common
.internal_command
.send(InternalCommand::SplitMove {
direction: SplitMoveDirection::Down,
editor_tab_id,
});
} else {
return CommandExecuted::No;
}
}
FocusCommand::SplitExchange => {
if let Some(editor_tab_id) = self.editor_tab_id.get_untracked() {
self.common
.internal_command
.send(InternalCommand::SplitExchange { editor_tab_id });
} else if let Some((editor_tab_id, _)) =
self.diff_editor_id.get_untracked()
{
self.common
.internal_command
.send(InternalCommand::SplitExchange { editor_tab_id });
} else {
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | true |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/status.rs | lapce-app/src/status.rs | use std::{
rc::Rc,
sync::{Arc, atomic::AtomicU64},
};
use floem::{
View,
event::EventPropagation,
reactive::{
Memo, ReadSignal, RwSignal, SignalGet, SignalUpdate, SignalWith, create_memo,
},
style::{AlignItems, CursorStyle, Display},
views::{Decorators, dyn_stack, label, stack, svg},
};
use indexmap::IndexMap;
use lapce_core::mode::{Mode, VisualMode};
use lsp_types::{DiagnosticSeverity, ProgressToken};
use crate::{
app::clickable_icon,
command::LapceWorkbenchCommand,
config::{LapceConfig, color::LapceColor, icon::LapceIcons},
editor::EditorData,
listener::Listener,
palette::kind::PaletteKind,
panel::{kind::PanelKind, position::PanelContainerPosition},
source_control::SourceControlData,
window_tab::{WindowTabData, WorkProgress},
};
pub fn status(
window_tab_data: Rc<WindowTabData>,
source_control: SourceControlData,
workbench_command: Listener<LapceWorkbenchCommand>,
status_height: RwSignal<f64>,
_config: ReadSignal<Arc<LapceConfig>>,
) -> impl View {
let config = window_tab_data.common.config;
let diagnostics = window_tab_data.main_split.diagnostics;
let editor = window_tab_data.main_split.active_editor;
let panel = window_tab_data.panel.clone();
let palette = window_tab_data.palette.clone();
let diagnostic_count = create_memo(move |_| {
let mut errors = 0;
let mut warnings = 0;
for (_, diagnostics) in diagnostics.get().iter() {
for diagnostic in diagnostics.diagnostics.get().iter() {
if let Some(severity) = diagnostic.severity {
match severity {
DiagnosticSeverity::ERROR => errors += 1,
DiagnosticSeverity::WARNING => warnings += 1,
_ => (),
}
}
}
}
(errors, warnings)
});
let branch = source_control.branch;
let file_diffs = source_control.file_diffs;
let branch = move || {
format!(
"{}{}",
branch.get(),
if file_diffs.with(|diffs| diffs.is_empty()) {
""
} else {
"*"
}
)
};
let progresses = window_tab_data.progresses;
let mode = create_memo(move |_| window_tab_data.mode());
let pointer_down = floem::reactive::create_rw_signal(false);
stack((
stack((
label(move || match mode.get() {
Mode::Normal => "Normal".to_string(),
Mode::Insert => "Insert".to_string(),
Mode::Visual(mode) => match mode {
VisualMode::Normal => "Visual".to_string(),
VisualMode::Linewise => "Visual Line".to_string(),
VisualMode::Blockwise => "Visual Block".to_string(),
},
Mode::Terminal => "Terminal".to_string(),
})
.style(move |s| {
let config = config.get();
let display = if config.core.modal {
Display::Flex
} else {
Display::None
};
let (bg, fg) = match mode.get() {
Mode::Normal => (
LapceColor::STATUS_MODAL_NORMAL_BACKGROUND,
LapceColor::STATUS_MODAL_NORMAL_FOREGROUND,
),
Mode::Insert => (
LapceColor::STATUS_MODAL_INSERT_BACKGROUND,
LapceColor::STATUS_MODAL_INSERT_FOREGROUND,
),
Mode::Visual(_) => (
LapceColor::STATUS_MODAL_VISUAL_BACKGROUND,
LapceColor::STATUS_MODAL_VISUAL_FOREGROUND,
),
Mode::Terminal => (
LapceColor::STATUS_MODAL_TERMINAL_BACKGROUND,
LapceColor::STATUS_MODAL_TERMINAL_FOREGROUND,
),
};
let bg = config.color(bg);
let fg = config.color(fg);
s.display(display)
.padding_horiz(10.0)
.color(fg)
.background(bg)
.height_pct(100.0)
.align_items(Some(AlignItems::Center))
.selectable(false)
}),
stack((
svg(move || config.get().ui_svg(LapceIcons::SCM)).style(move |s| {
let config = config.get();
let icon_size = config.ui.icon_size() as f32;
s.size(icon_size, icon_size)
.color(config.color(LapceColor::LAPCE_ICON_ACTIVE))
}),
label(branch).style(move |s| {
s.margin_left(10.0)
.color(config.get().color(LapceColor::STATUS_FOREGROUND))
.selectable(false)
}),
))
.style(move |s| {
s.display(if branch().is_empty() {
Display::None
} else {
Display::Flex
})
.height_pct(100.0)
.padding_horiz(10.0)
.align_items(Some(AlignItems::Center))
.hover(|s| {
s.cursor(CursorStyle::Pointer).background(
config.get().color(LapceColor::PANEL_HOVERED_BACKGROUND),
)
})
})
.on_event_cont(floem::event::EventListener::PointerDown, move |_| {
pointer_down.set(true);
})
.on_event(
floem::event::EventListener::PointerUp,
move |_| {
if pointer_down.get() {
workbench_command
.send(LapceWorkbenchCommand::PaletteSCMReferences);
}
pointer_down.set(false);
EventPropagation::Continue
},
),
{
let panel = panel.clone();
stack((
svg(move || config.get().ui_svg(LapceIcons::ERROR)).style(
move |s| {
let config = config.get();
let size = config.ui.icon_size() as f32;
s.size(size, size)
.color(config.color(LapceColor::LAPCE_ICON_ACTIVE))
},
),
label(move || diagnostic_count.get().0.to_string()).style(
move |s| {
s.margin_left(5.0)
.color(
config
.get()
.color(LapceColor::STATUS_FOREGROUND),
)
.selectable(false)
},
),
svg(move || config.get().ui_svg(LapceIcons::WARNING)).style(
move |s| {
let config = config.get();
let size = config.ui.icon_size() as f32;
s.size(size, size)
.margin_left(5.0)
.color(config.color(LapceColor::LAPCE_ICON_ACTIVE))
},
),
label(move || diagnostic_count.get().1.to_string()).style(
move |s| {
s.margin_left(5.0)
.color(
config
.get()
.color(LapceColor::STATUS_FOREGROUND),
)
.selectable(false)
},
),
))
.on_click_stop(move |_| {
panel.show_panel(&PanelKind::Problem);
})
.style(move |s| {
s.height_pct(100.0)
.padding_horiz(10.0)
.items_center()
.hover(|s| {
s.cursor(CursorStyle::Pointer).background(
config
.get()
.color(LapceColor::PANEL_HOVERED_BACKGROUND),
)
})
})
},
progress_view(config, progresses),
))
.style(|s| {
s.height_pct(100.0)
.min_width(0.0)
.flex_basis(0.0)
.flex_grow(1.0)
.items_center()
}),
stack((
{
let panel = panel.clone();
let icon = {
let panel = panel.clone();
move || {
if panel
.is_container_shown(&PanelContainerPosition::Left, true)
{
LapceIcons::SIDEBAR_LEFT
} else {
LapceIcons::SIDEBAR_LEFT_OFF
}
}
};
clickable_icon(
icon,
move || {
panel.toggle_container_visual(&PanelContainerPosition::Left)
},
|| false,
|| false,
|| "Toggle Left Panel",
config,
)
},
{
let panel = panel.clone();
let icon = {
let panel = panel.clone();
move || {
if panel.is_container_shown(
&PanelContainerPosition::Bottom,
true,
) {
LapceIcons::LAYOUT_PANEL
} else {
LapceIcons::LAYOUT_PANEL_OFF
}
}
};
clickable_icon(
icon,
move || {
panel
.toggle_container_visual(&PanelContainerPosition::Bottom)
},
|| false,
|| false,
|| "Toggle Bottom Panel",
config,
)
},
{
let panel = panel.clone();
let icon = {
let panel = panel.clone();
move || {
if panel
.is_container_shown(&PanelContainerPosition::Right, true)
{
LapceIcons::SIDEBAR_RIGHT
} else {
LapceIcons::SIDEBAR_RIGHT_OFF
}
}
};
clickable_icon(
icon,
move || {
panel.toggle_container_visual(&PanelContainerPosition::Right)
},
|| false,
|| false,
|| "Toggle Right Panel",
config,
)
},
))
.style(move |s| {
s.height_pct(100.0)
.items_center()
.color(config.get().color(LapceColor::STATUS_FOREGROUND))
}),
stack({
let palette_clone = palette.clone();
let cursor_info = status_text(config, editor, move || {
if let Some(editor) = editor.get() {
let mut status = String::new();
let cursor = editor.cursor().get();
if let Some((line, column, character)) = editor
.doc_signal()
.get()
.buffer
.with(|buffer| cursor.get_line_col_char(buffer))
{
status = format!(
"Ln {}, Col {}, Char {}",
line + 1,
column + 1,
character,
);
}
if let Some(selection) = cursor.get_selection() {
let selection_range = selection.0.abs_diff(selection.1);
if selection.0 != selection.1 {
status =
format!("{status} ({selection_range} selected)");
}
}
let selection_count = cursor.get_selection_count();
if selection_count > 1 {
status = format!("{status} {selection_count} selections");
}
return status;
}
String::new()
})
.on_click_stop(move |_| {
palette_clone.run(PaletteKind::Line);
});
let palette_clone = palette.clone();
let line_ending_info = status_text(config, editor, move || {
if let Some(editor) = editor.get() {
let doc = editor.doc_signal().get();
doc.buffer.with(|b| b.line_ending()).as_str()
} else {
""
}
})
.on_click_stop(move |_| {
palette_clone.run(PaletteKind::LineEnding);
});
let palette_clone = palette.clone();
let language_info = status_text(config, editor, move || {
if let Some(editor) = editor.get() {
let doc = editor.doc_signal().get();
doc.syntax().with(|s| s.language.name())
} else {
"unknown"
}
})
.on_click_stop(move |_| {
palette_clone.run(PaletteKind::Language);
});
(cursor_info, line_ending_info, language_info)
})
.style(|s| {
s.height_pct(100.0)
.flex_basis(0.0)
.flex_grow(1.0)
.justify_end()
}),
))
.on_resize(move |rect| {
let height = rect.height();
if height != status_height.get_untracked() {
status_height.set(height);
}
})
.style(move |s| {
let config = config.get();
s.border_top(1.0)
.border_color(config.color(LapceColor::LAPCE_BORDER))
.background(config.color(LapceColor::STATUS_BACKGROUND))
.flex_basis(config.ui.status_height() as f32)
.flex_grow(0.0)
.flex_shrink(0.0)
.items_center()
})
.debug_name("Status/Bottom Bar")
}
fn progress_view(
config: ReadSignal<Arc<LapceConfig>>,
progresses: RwSignal<IndexMap<ProgressToken, WorkProgress>>,
) -> impl View {
let id = AtomicU64::new(0);
dyn_stack(
move || progresses.get(),
move |_| id.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
move |(_, p)| {
let progress = match p.message {
Some(message) if !message.is_empty() => {
format!("{}: {}", p.title, message)
}
_ => p.title,
};
label(move || progress.clone()).style(move |s| {
s.height_pct(100.0)
.min_width(0.0)
.margin_left(10.0)
.text_ellipsis()
.selectable(false)
.items_center()
.color(config.get().color(LapceColor::STATUS_FOREGROUND))
})
},
)
.style(move |s| s.flex_row().height_pct(100.0).min_width(0.0))
}
fn status_text<S: std::fmt::Display + 'static>(
config: ReadSignal<Arc<LapceConfig>>,
editor: Memo<Option<EditorData>>,
text: impl Fn() -> S + 'static,
) -> impl View {
label(text).style(move |s| {
let config = config.get();
let display = if editor
.get()
.map(|editor| {
editor.doc_signal().get().content.with(|c| {
use crate::doc::DocContent;
matches!(c, DocContent::File { .. } | DocContent::Scratch { .. })
})
})
.unwrap_or(false)
{
Display::Flex
} else {
Display::None
};
s.display(display)
.height_full()
.padding_horiz(10.0)
.items_center()
.color(config.color(LapceColor::STATUS_FOREGROUND))
.hover(|s| {
s.cursor(CursorStyle::Pointer)
.background(config.color(LapceColor::PANEL_HOVERED_BACKGROUND))
})
.selectable(false)
})
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/text_input.rs | lapce-app/src/text_input.rs | use std::{rc::Rc, sync::Arc};
use floem::{
Renderer, View, ViewId,
action::{set_ime_allowed, set_ime_cursor_area},
context::EventCx,
event::{Event, EventListener, EventPropagation},
kurbo::Stroke,
peniko::{
Color,
kurbo::{Line, Point, Rect, Size, Vec2},
},
prop_extractor,
reactive::{
Memo, ReadSignal, RwSignal, Scope, SignalGet, SignalUpdate, SignalWith,
create_effect, create_memo, create_rw_signal,
},
style::{
CursorStyle, FontFamily, FontSize, FontStyle, FontWeight, LineHeight,
PaddingLeft, Style, TextColor,
},
taffy::prelude::NodeId,
text::{Attrs, AttrsList, FamilyOwned, TextLayout},
unit::PxPct,
views::Decorators,
};
use lapce_core::{
buffer::rope_text::RopeText,
cursor::{Cursor, CursorMode},
selection::Selection,
};
use lapce_xi_rope::Rope;
use crate::{
config::{LapceConfig, color::LapceColor},
doc::Doc,
editor::{DocSignal, EditorData, view::editor_style},
keypress::KeyPressFocus,
main_split::Editors,
window_tab::CommonData,
};
prop_extractor! {
Extractor {
color: TextColor,
font_size: FontSize,
font_family: FontFamily,
font_weight: FontWeight,
font_style: FontStyle,
line_height: LineHeight,
}
}
/// Builder for creating a [`TextInput`] easily.
pub struct TextInputBuilder {
is_focused: Option<Memo<bool>>,
// TODO: it'd be nice to not need to box this
key_focus: Option<Box<dyn KeyPressFocus>>,
value: Option<Rope>,
keyboard_focus: RwSignal<bool>,
}
impl Default for TextInputBuilder {
fn default() -> Self {
Self::new()
}
}
impl TextInputBuilder {
pub fn new() -> Self {
Self {
is_focused: None,
key_focus: None,
value: None,
keyboard_focus: create_rw_signal(false),
}
}
pub fn is_focused(mut self, is_focused: impl Fn() -> bool + 'static) -> Self {
let keyboard_focus = self.keyboard_focus;
self.is_focused =
Some(create_memo(move |_| is_focused() || keyboard_focus.get()));
self
}
/// Initialize with a specific value.
/// If this is set it will apply the value via reloading the editor's doc as pristine.
pub fn value(mut self, value: impl Into<Rope>) -> Self {
self.value = Some(value.into());
self
}
pub fn key_focus(mut self, key_focus: impl KeyPressFocus + 'static) -> Self {
self.key_focus = Some(Box::new(key_focus));
self
}
pub fn build(
self,
cx: Scope,
editors: Editors,
common: Rc<CommonData>,
) -> TextInput {
let editor = editors.make_local(cx, common);
let id = editor.id();
self.build_editor(editor).on_cleanup(move || {
editors.remove(id);
})
}
/// Build the text input with a specific editor.
/// This function does *not* perform add/cleanup the editor to/from [`Editors`]
pub fn build_editor(self, editor: EditorData) -> TextInput {
let keyboard_focus = self.keyboard_focus;
let is_focused = if let Some(is_focused) = self.is_focused {
is_focused
} else {
create_memo(move |_| keyboard_focus.get())
};
if let Some(value) = self.value {
editor.doc().reload(value, true);
}
text_input_full(editor, self.key_focus, is_focused, keyboard_focus)
}
}
/// Create a basic single line text input
/// `e_data` is the editor data that this input is associated with.
/// `supplied_editor`
/// `key_focus` is what receives the keydown events, leave as `None` to default to editor.
/// `is_focused` is a function that returns if the input is focused, used for certain events.
fn text_input_full<T: KeyPressFocus + 'static>(
e_data: EditorData,
key_focus: Option<T>,
is_focused: Memo<bool>,
keyboard_focus: RwSignal<bool>,
) -> TextInput {
let id = ViewId::new();
let doc = e_data.doc_signal();
let cursor = e_data.cursor();
let config = e_data.common.config;
let keypress = e_data.common.keypress;
let window_origin = create_rw_signal(Point::ZERO);
let cursor_line = create_rw_signal(Line::new(Point::ZERO, Point::ZERO));
let local_editor = e_data.clone();
let editor = local_editor.editor.clone();
{
let doc = doc.get();
create_effect(move |_| {
let offset = cursor.with(|c| c.offset());
let (content, offset, preedit_range) = {
let content = doc.buffer.with(|b| b.to_string());
if let Some(preedit) = doc.preedit.preedit.get().as_ref() {
let mut new_content = String::new();
new_content.push_str(&content[..offset]);
new_content.push_str(&preedit.text);
new_content.push_str(&content[offset..]);
let range = (offset, offset + preedit.text.len());
let offset = preedit
.cursor
.as_ref()
.map(|(_, end)| offset + *end)
.unwrap_or(offset);
(new_content, offset, Some(range))
} else {
(content, offset, None)
}
};
id.update_state(TextInputState::Content {
text: content,
offset,
preedit_range,
});
});
}
{
create_effect(move |_| {
let focus = is_focused.get();
id.update_state(TextInputState::Focus(focus));
});
let editor = editor.clone();
let ime_allowed = editor.ime_allowed;
create_effect(move |_| {
let focus = is_focused.get();
if focus {
if !ime_allowed.get_untracked() {
ime_allowed.set(true);
set_ime_allowed(true);
}
let cursor_line = cursor_line.get();
let window_origin = window_origin.get();
let viewport = editor.viewport.get();
let origin = window_origin
+ Vec2::new(
cursor_line.p1.x - viewport.x0,
cursor_line.p1.y - viewport.y0,
);
set_ime_cursor_area(origin, Size::new(800.0, 600.0));
}
});
}
let common_keyboard_focus = e_data.common.keyboard_focus;
let ed1 = editor.clone();
let ed2 = editor.clone();
TextInput {
id,
config,
offset: 0,
preedit_range: None,
layout_rect: Rect::ZERO,
content: "".to_string(),
focus: false,
text_node: None,
text_layout: create_rw_signal(None),
text_rect: Rect::ZERO,
text_viewport: Rect::ZERO,
cursor_line,
placeholder: "".to_string(),
placeholder_text_layout: None,
editor: e_data.clone(),
cursor_pos: Point::ZERO,
on_cursor_pos: None,
hide_cursor: editor.cursor_info.hidden,
style: Default::default(),
}
.style(move |s| {
editor_style(config, doc, s)
.cursor(CursorStyle::Text)
.padding_horiz(10.0)
.padding_vert(6.0)
})
.on_move(move |pos| {
window_origin.set(pos);
})
.on_event_stop(EventListener::FocusGained, move |_| {
keyboard_focus.set(true);
common_keyboard_focus.set(Some(id));
})
.on_event_stop(EventListener::FocusLost, move |_| {
keyboard_focus.set(false);
if common_keyboard_focus.get_untracked() == Some(id) {
common_keyboard_focus.set(None);
}
})
.on_event(EventListener::KeyDown, move |event| {
if let Event::KeyDown(key_event) = event {
let keypress = keypress.get_untracked();
let key_focus = key_focus
.as_ref()
.map(|k| k as &dyn KeyPressFocus)
.unwrap_or(&e_data);
if keypress.key_down(key_event, key_focus).handled {
EventPropagation::Stop
} else {
EventPropagation::Continue
}
} else {
EventPropagation::Continue
}
})
.on_event(EventListener::ImePreedit, move |event| {
if !is_focused.get_untracked() {
return EventPropagation::Continue;
}
if let Event::ImePreedit {
text,
cursor: ime_cursor,
} = event
{
if text.is_empty() {
ed1.clear_preedit();
} else {
let offset = cursor.with_untracked(|c| c.offset());
ed1.set_preedit(text.clone(), ime_cursor.to_owned(), offset);
}
}
EventPropagation::Stop
})
.on_event(EventListener::ImeCommit, move |event| {
if !is_focused.get_untracked() {
return EventPropagation::Continue;
}
if let Event::ImeCommit(text) = event {
ed2.clear_preedit();
ed2.receive_char(text.as_str());
}
EventPropagation::Stop
})
}
enum TextInputState {
Content {
text: String,
offset: usize,
preedit_range: Option<(usize, usize)>,
},
Focus(bool),
Placeholder(String),
}
pub struct TextInput {
id: ViewId,
content: String,
offset: usize,
preedit_range: Option<(usize, usize)>,
editor: EditorData,
focus: bool,
text_node: Option<NodeId>,
text_layout: RwSignal<Option<TextLayout>>,
text_rect: Rect,
text_viewport: Rect,
layout_rect: Rect,
cursor_line: RwSignal<Line>,
placeholder: String,
placeholder_text_layout: Option<TextLayout>,
cursor_pos: Point,
on_cursor_pos: Option<Box<dyn Fn(Point)>>,
hide_cursor: RwSignal<bool>,
config: ReadSignal<Arc<LapceConfig>>,
style: Extractor,
}
impl TextInput {
pub fn placeholder(self, placeholder: impl Fn() -> String + 'static) -> Self {
let id = self.id;
create_effect(move |_| {
let placeholder = placeholder();
id.update_state(TextInputState::Placeholder(placeholder));
});
self
}
pub fn on_cursor_pos(mut self, cursor_pos: impl Fn(Point) + 'static) -> Self {
self.on_cursor_pos = Some(Box::new(cursor_pos));
self
}
pub fn editor(&self) -> EditorData {
self.editor.clone()
}
pub fn doc_signal(&self) -> DocSignal {
self.editor.doc_signal()
}
pub fn doc(&self) -> Rc<Doc> {
self.editor.doc()
}
pub fn cursor(&self) -> RwSignal<Cursor> {
self.editor.cursor()
}
fn set_text_layout(&mut self) {
let mut text_layout = TextLayout::new();
let mut attrs =
Attrs::new().color(self.style.color().unwrap_or(Color::BLACK));
if let Some(font_size) = self.style.font_size() {
attrs = attrs.font_size(font_size);
}
if let Some(font_style) = self.style.font_style() {
attrs = attrs.style(font_style);
}
let font_family = self.style.font_family().as_ref().map(|font_family| {
let family: Vec<FamilyOwned> =
FamilyOwned::parse_list(font_family).collect();
family
});
if let Some(font_family) = font_family.as_ref() {
attrs = attrs.family(font_family);
}
if let Some(font_weight) = self.style.font_weight() {
attrs = attrs.weight(font_weight);
}
if let Some(line_height) = self.style.line_height() {
attrs = attrs.line_height(line_height);
}
text_layout.set_text(
if self.content.is_empty() {
" "
} else {
self.content.as_str()
},
AttrsList::new(attrs.clone()),
None,
);
self.text_layout.set(Some(text_layout));
let mut placeholder_text_layout = TextLayout::new();
attrs = attrs.color(
self.style
.color()
.unwrap_or(Color::BLACK)
.multiply_alpha(0.5),
);
placeholder_text_layout.set_text(
&self.placeholder,
AttrsList::new(attrs),
None,
);
self.placeholder_text_layout = Some(placeholder_text_layout);
}
fn hit_index(&self, _cx: &mut EventCx, point: Point) -> usize {
self.text_layout.with_untracked(|text_layout| {
if let Some(text_layout) = text_layout.as_ref() {
let padding_left =
match self.id.get_combined_style().get(PaddingLeft) {
PxPct::Px(v) => v,
PxPct::Pct(pct) => {
let layout = self.id.get_layout().unwrap_or_default();
pct * layout.size.width as f64
}
};
let hit =
text_layout.hit_point(Point::new(point.x - padding_left, 0.0));
hit.index.min(self.content.len())
} else {
0
}
})
}
fn clamp_text_viewport(&mut self, text_viewport: Rect) {
let text_rect = self.text_rect;
let actual_size = text_rect.size();
let width = text_rect.width();
let height = text_rect.height();
let child_size = self
.text_layout
.with_untracked(|text_layout| text_layout.as_ref().unwrap().size());
let mut text_viewport = text_viewport;
if width >= child_size.width {
text_viewport.x0 = 0.0;
} else if text_viewport.x0 > child_size.width - width {
text_viewport.x0 = child_size.width - width;
} else if text_viewport.x0 < 0.0 {
text_viewport.x0 = 0.0;
}
if height >= child_size.height {
text_viewport.y0 = 0.0;
} else if text_viewport.y0 > child_size.height - height {
text_viewport.y0 = child_size.height - height;
} else if text_viewport.y0 < 0.0 {
text_viewport.y0 = 0.0;
}
let text_viewport = text_viewport.with_size(actual_size);
if text_viewport != self.text_viewport {
self.text_viewport = text_viewport;
self.id.request_paint();
}
}
fn ensure_cursor_visible(&mut self) {
fn closest_on_axis(val: f64, min: f64, max: f64) -> f64 {
assert!(min <= max);
if val > min && val < max {
0.0
} else if val <= min {
val - min
} else {
val - max
}
}
let rect = Rect::ZERO.with_origin(self.cursor_pos).inflate(10.0, 0.0);
// clamp the target region size to our own size.
// this means we will show the portion of the target region that
// includes the origin.
let target_size = Size::new(
rect.width().min(self.text_viewport.width()),
rect.height().min(self.text_viewport.height()),
);
let rect = rect.with_size(target_size);
let x0 = closest_on_axis(
rect.min_x(),
self.text_viewport.min_x(),
self.text_viewport.max_x(),
);
let x1 = closest_on_axis(
rect.max_x(),
self.text_viewport.min_x(),
self.text_viewport.max_x(),
);
let y0 = closest_on_axis(
rect.min_y(),
self.text_viewport.min_y(),
self.text_viewport.max_y(),
);
let y1 = closest_on_axis(
rect.max_y(),
self.text_viewport.min_y(),
self.text_viewport.max_y(),
);
let delta_x = if x0.abs() > x1.abs() { x0 } else { x1 };
let delta_y = if y0.abs() > y1.abs() { y0 } else { y1 };
let new_origin = self.text_viewport.origin() + Vec2::new(delta_x, delta_y);
self.clamp_text_viewport(self.text_viewport.with_origin(new_origin));
}
}
impl View for TextInput {
fn id(&self) -> ViewId {
self.id
}
fn update(
&mut self,
_cx: &mut floem::context::UpdateCx,
state: Box<dyn std::any::Any>,
) {
if let Ok(state) = state.downcast() {
match *state {
TextInputState::Content {
text,
offset,
preedit_range,
} => {
self.content = text;
self.offset = offset;
self.preedit_range = preedit_range;
self.text_layout.set(None);
}
TextInputState::Focus(focus) => {
self.focus = focus;
}
TextInputState::Placeholder(placeholder) => {
self.placeholder = placeholder;
self.placeholder_text_layout = None;
}
}
self.id.request_layout();
}
}
fn style_pass(&mut self, cx: &mut floem::context::StyleCx<'_>) {
if self.style.read(cx) {
self.set_text_layout();
self.id.request_layout();
}
}
fn layout(
&mut self,
cx: &mut floem::context::LayoutCx,
) -> floem::taffy::prelude::NodeId {
cx.layout_node(self.id, true, |_cx| {
if self
.text_layout
.with_untracked(|text_layout| text_layout.is_none())
|| self.placeholder_text_layout.is_none()
{
self.set_text_layout();
}
let text_layout = self.text_layout;
text_layout.with_untracked(|text_layout| {
let text_layout = text_layout.as_ref().unwrap();
let offset = self.cursor().get_untracked().offset();
let cursor_point = text_layout.hit_position(offset).point;
if cursor_point != self.cursor_pos {
self.cursor_pos = cursor_point;
self.ensure_cursor_visible();
}
let size = text_layout.size();
let height = size.height as f32;
if self.text_node.is_none() {
self.text_node = Some(self.id.new_taffy_node());
}
let text_node = self.text_node.unwrap();
let style = Style::new().height(height).to_taffy_style();
self.id.set_taffy_style(text_node, style);
});
vec![self.text_node.unwrap()]
})
}
fn compute_layout(
&mut self,
_cx: &mut floem::context::ComputeLayoutCx,
) -> Option<Rect> {
let layout = self.id.get_layout().unwrap_or_default();
let style = self.id.get_combined_style();
let style = style.builtin();
let padding_left = match style.padding_left() {
PxPct::Px(padding) => padding,
PxPct::Pct(pct) => pct * layout.size.width as f64,
};
let padding_right = match style.padding_right() {
PxPct::Px(padding) => padding,
PxPct::Pct(pct) => pct * layout.size.width as f64,
};
let size = Size::new(layout.size.width as f64, layout.size.height as f64);
let mut text_rect = size.to_rect();
text_rect.x0 += padding_left;
text_rect.x1 -= padding_right;
self.text_rect = text_rect;
self.clamp_text_viewport(self.text_viewport);
let text_node = self.text_node.unwrap();
let location = self.id.taffy_layout(text_node).unwrap_or_default().location;
self.layout_rect = size
.to_rect()
.with_origin(Point::new(location.x as f64, location.y as f64));
let offset = self.cursor().with_untracked(|c| c.offset());
let cursor_line = self.text_layout.with_untracked(|text_layout| {
let hit_position = text_layout.as_ref().unwrap().hit_position(offset);
let point = Point::new(location.x as f64, location.y as f64)
- self.text_viewport.origin().to_vec2();
let cursor_point = hit_position.point + point.to_vec2();
Line::new(
Point::new(
cursor_point.x,
cursor_point.y - hit_position.glyph_ascent,
),
Point::new(
cursor_point.x,
cursor_point.y + hit_position.glyph_descent,
),
)
});
self.cursor_line.set(cursor_line);
None
}
fn event_before_children(
&mut self,
cx: &mut floem::context::EventCx,
event: &floem::event::Event,
) -> EventPropagation {
let text_offset = self.text_viewport.origin();
let event = event.clone().offset((-text_offset.x, -text_offset.y));
match event {
Event::PointerDown(pointer) => {
let offset = self.hit_index(cx, pointer.pos);
self.cursor().update(|cursor| {
cursor.set_insert(Selection::caret(offset));
});
if pointer.button.is_primary() && pointer.count == 2 {
let offset = self.hit_index(cx, pointer.pos);
let (start, end) = self
.doc()
.buffer
.with_untracked(|buffer| buffer.select_word(offset));
self.cursor().update(|cursor| {
cursor.set_insert(Selection::region(start, end));
});
} else if pointer.button.is_primary() && pointer.count == 3 {
self.cursor().update(|cursor| {
cursor.set_insert(Selection::region(0, self.content.len()));
});
}
cx.update_active(self.id);
}
Event::PointerMove(pointer) => {
if cx.is_active(self.id) {
let offset = self.hit_index(cx, pointer.pos);
self.cursor().update(|cursor| {
cursor.set_offset(offset, true, false);
});
}
}
Event::PointerWheel(pointer_event) => {
let delta = pointer_event.delta;
let delta = if delta.x == 0.0 && delta.y != 0.0 {
Vec2::new(delta.y, delta.x)
} else {
delta
};
self.clamp_text_viewport(self.text_viewport + delta);
return EventPropagation::Continue;
}
_ => {}
}
EventPropagation::Continue
}
fn paint(&mut self, cx: &mut floem::context::PaintCx) {
cx.save();
cx.clip(&self.text_rect.inflate(1.0, 0.0));
let text_node = self.text_node.unwrap();
let location = self.id.taffy_layout(text_node).unwrap_or_default().location;
let point = Point::new(location.x as f64, location.y as f64)
- self.text_viewport.origin().to_vec2();
self.text_layout.with_untracked(|text_layout| {
let text_layout = text_layout.as_ref().unwrap();
let height = text_layout.size().height;
let config = self.config.get_untracked();
let cursor = self.cursor().get_untracked();
if let CursorMode::Insert(selection) = &cursor.mode {
for region in selection.regions() {
if !region.is_caret() {
let min = text_layout.hit_position(region.min()).point.x;
let max = text_layout.hit_position(region.max()).point.x;
cx.fill(
&Rect::ZERO
.with_size(Size::new(max - min, height))
.with_origin(Point::new(min + point.x, point.y)),
config.color(LapceColor::EDITOR_SELECTION),
0.0,
);
}
}
}
if !self.content.is_empty() {
cx.draw_text(text_layout, point);
} else if !self.placeholder.is_empty() {
cx.draw_text(self.placeholder_text_layout.as_ref().unwrap(), point);
}
if let Some((start, end)) = self.preedit_range {
let start_position = text_layout.hit_position(start);
let start_point = start_position.point
+ self.layout_rect.origin().to_vec2()
- self.text_viewport.origin().to_vec2();
let end_position = text_layout.hit_position(end);
let end_point = end_position.point
+ self.layout_rect.origin().to_vec2()
- self.text_viewport.origin().to_vec2();
let line = Line::new(
Point::new(
start_point.x,
start_point.y + start_position.glyph_descent,
),
Point::new(
end_point.x,
end_point.y + end_position.glyph_descent,
),
);
cx.stroke(
&line,
config.color(LapceColor::EDITOR_FOREGROUND),
&Stroke::new(1.0),
);
}
if !self.hide_cursor.get_untracked()
&& (self.focus || cx.is_focused(self.id))
{
cx.clip(&self.text_rect.inflate(2.0, 2.0));
let hit_position = text_layout.hit_position(self.offset);
let cursor_point = hit_position.point
+ self.layout_rect.origin().to_vec2()
- self.text_viewport.origin().to_vec2();
let line = Line::new(
Point::new(
cursor_point.x,
cursor_point.y - hit_position.glyph_ascent,
),
Point::new(
cursor_point.x,
cursor_point.y + hit_position.glyph_descent,
),
);
cx.stroke(
&line,
self.config.get_untracked().color(LapceColor::EDITOR_CARET),
&Stroke::new(2.0),
);
}
cx.restore();
});
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/hover.rs | lapce-app/src/hover.rs | use floem::{
peniko::kurbo::Rect,
reactive::{RwSignal, Scope},
views::editor::id::EditorId,
};
use crate::markdown::MarkdownContent;
#[derive(Clone)]
pub struct HoverData {
pub active: RwSignal<bool>,
pub offset: RwSignal<usize>,
pub editor_id: RwSignal<EditorId>,
pub content: RwSignal<Vec<MarkdownContent>>,
pub layout_rect: RwSignal<Rect>,
}
impl HoverData {
pub fn new(cx: Scope) -> Self {
Self {
active: cx.create_rw_signal(false),
offset: cx.create_rw_signal(0),
content: cx.create_rw_signal(Vec::new()),
editor_id: cx.create_rw_signal(EditorId::next()),
layout_rect: cx.create_rw_signal(Rect::ZERO),
}
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/listener.rs | lapce-app/src/listener.rs | use floem::reactive::{RwSignal, Scope, SignalGet, SignalUpdate};
/// A signal listener that receives 'events' from the outside and runs the callback.
/// This is implemented using effects and normal rw signals. This should be used when it doesn't
/// make sense to think of it as 'storing' a value, like an `RwSignal` would typically be used for.
///
/// Copied/Cloned listeners refer to the same listener.
#[derive(Debug)]
pub struct Listener<T: 'static> {
cx: Scope,
val: RwSignal<Option<T>>,
}
impl<T: Clone + 'static> Listener<T> {
pub fn new(cx: Scope, on_val: impl Fn(T) + 'static) -> Listener<T> {
let val = cx.create_rw_signal(None);
let listener = Listener { val, cx };
listener.listen(on_val);
listener
}
/// Construct a listener when you can't yet give it a callback.
/// Call `listen` to set a callback.
pub fn new_empty(cx: Scope) -> Listener<T> {
let val = cx.create_rw_signal(None);
Listener { val, cx }
}
pub fn scope(&self) -> Scope {
self.cx
}
/// Listen for values sent to this listener.
pub fn listen(self, on_val: impl Fn(T) + 'static) {
self.listen_with(self.cx, on_val)
}
/// Listen for values sent to this listener.
/// Allows creating the effect with a custom scope, letting it be disposed of.
pub fn listen_with(self, cx: Scope, on_val: impl Fn(T) + 'static) {
let val = self.val;
cx.create_effect(move |_| {
// TODO(minor): Signals could have a `take` method to avoid cloning.
if let Some(cmd) = val.get() {
on_val(cmd);
}
});
}
/// Send a value to the listener.
pub fn send(&self, v: T) {
self.val.set(Some(v));
}
}
impl<T: 'static> Copy for Listener<T> {}
impl<T: 'static> Clone for Listener<T> {
fn clone(&self) -> Self {
*self
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/find.rs | lapce-app/src/find.rs | use std::cmp::{max, min};
use floem::{
prelude::SignalTrack,
reactive::{RwSignal, Scope, SignalGet, SignalUpdate, SignalWith},
};
use lapce_core::{
selection::{SelRegion, Selection},
word::WordCursor,
};
use lapce_xi_rope::{
Cursor, Interval, Rope,
find::{CaseMatching, find, is_multiline_regex},
};
use regex::{Regex, RegexBuilder};
use serde::{Deserialize, Serialize};
const REGEX_SIZE_LIMIT: usize = 1000000;
/// Indicates what changed in the find state.
#[derive(PartialEq, Debug, Clone)]
pub enum FindProgress {
/// Incremental find is done/not running.
Ready,
/// The find process just started.
Started,
/// Incremental find is in progress. Keeps tracked of already searched range.
InProgress(Selection),
}
#[derive(Serialize, Deserialize, Debug)]
pub struct FindStatus {
/// Identifier for the current search query.
id: usize,
/// The current search query.
chars: Option<String>,
/// Whether the active search is case matching.
case_sensitive: Option<bool>,
/// Whether the search query is considered as regular expression.
is_regex: Option<bool>,
/// Query only matches whole words.
whole_words: Option<bool>,
/// Total number of matches.
matches: usize,
/// Line numbers which have find results.
lines: Vec<usize>,
}
#[derive(Clone)]
pub struct FindSearchString {
pub content: String,
pub regex: Option<Regex>,
}
#[derive(Clone)]
pub struct Find {
pub rev: RwSignal<u64>,
/// If the find is shown
pub visual: RwSignal<bool>,
/// The currently active search string.
pub search_string: RwSignal<Option<FindSearchString>>,
/// The case matching setting for the currently active search.
pub case_matching: RwSignal<CaseMatching>,
/// Query matches only whole words.
pub whole_words: RwSignal<bool>,
/// The search query should be considered as regular expression.
pub is_regex: RwSignal<bool>,
/// replace editor is shown
pub replace_active: RwSignal<bool>,
/// replace editor is focused
pub replace_focus: RwSignal<bool>,
/// Triggered by changes in the search string
pub triggered_by_changes: RwSignal<bool>,
}
impl Find {
pub fn new(cx: Scope) -> Self {
let find = Self {
rev: cx.create_rw_signal(0),
visual: cx.create_rw_signal(false),
search_string: cx.create_rw_signal(None),
case_matching: cx.create_rw_signal(CaseMatching::CaseInsensitive),
whole_words: cx.create_rw_signal(false),
is_regex: cx.create_rw_signal(false),
replace_active: cx.create_rw_signal(false),
replace_focus: cx.create_rw_signal(false),
triggered_by_changes: cx.create_rw_signal(false),
};
{
let find = find.clone();
cx.create_effect(move |_| {
find.is_regex.with(|_| ());
let s = find.search_string.with_untracked(|s| {
if let Some(s) = s.as_ref() {
s.content.clone()
} else {
"".to_string()
}
});
if !s.is_empty() {
find.set_find(&s);
}
});
}
{
let find = find.clone();
cx.create_effect(move |_| {
find.search_string.track();
find.case_matching.track();
find.whole_words.track();
find.rev.update(|rev| {
*rev += 1;
});
});
}
find
}
/// Returns `true` if case sensitive, otherwise `false`
pub fn case_sensitive(&self, tracked: bool) -> bool {
match if tracked {
self.case_matching.get()
} else {
self.case_matching.get_untracked()
} {
CaseMatching::Exact => true,
CaseMatching::CaseInsensitive => false,
}
}
/// Sets find case sensitivity.
pub fn set_case_sensitive(&self, case_sensitive: bool) {
if self.case_sensitive(false) == case_sensitive {
return;
}
let case_matching = if case_sensitive {
CaseMatching::Exact
} else {
CaseMatching::CaseInsensitive
};
self.case_matching.set(case_matching);
}
pub fn set_find(&self, search_string: &str) {
if search_string.is_empty() {
self.search_string.set(None);
return;
}
if !self.visual.get_untracked() {
self.visual.set(true);
}
let is_regex = self.is_regex.get_untracked();
let search_string_unchanged = self.search_string.with_untracked(|search| {
if let Some(s) = search {
s.content == search_string && s.regex.is_some() == is_regex
} else {
false
}
});
if search_string_unchanged {
return;
}
// create regex from untrusted input
let regex = match is_regex {
false => None,
true => RegexBuilder::new(search_string)
.size_limit(REGEX_SIZE_LIMIT)
.case_insensitive(!self.case_sensitive(false))
.build()
.ok(),
};
self.triggered_by_changes.set(true);
self.search_string.set(Some(FindSearchString {
content: search_string.to_string(),
regex,
}));
}
pub fn next(
&self,
text: &Rope,
offset: usize,
reverse: bool,
wrap: bool,
) -> Option<(usize, usize)> {
if !self.visual.get_untracked() {
self.visual.set(true);
}
let case_matching = self.case_matching.get_untracked();
let whole_words = self.whole_words.get_untracked();
self.search_string.with_untracked(
|search_string| -> Option<(usize, usize)> {
let search_string = search_string.as_ref()?;
if !reverse {
let mut raw_lines = text.lines_raw(offset..text.len());
let mut find_cursor = Cursor::new(text, offset);
while let Some(start) = find(
&mut find_cursor,
&mut raw_lines,
case_matching,
&search_string.content,
search_string.regex.as_ref(),
) {
let end = find_cursor.pos();
if whole_words
&& !Self::is_matching_whole_words(text, start, end)
{
raw_lines =
text.lines_raw(find_cursor.pos()..text.len());
continue;
}
raw_lines = text.lines_raw(find_cursor.pos()..text.len());
if start > offset {
return Some((start, end));
}
}
if wrap {
let mut raw_lines = text.lines_raw(0..offset);
let mut find_cursor = Cursor::new(text, 0);
while let Some(start) = find(
&mut find_cursor,
&mut raw_lines,
case_matching,
&search_string.content,
search_string.regex.as_ref(),
) {
let end = find_cursor.pos();
if whole_words
&& !Self::is_matching_whole_words(text, start, end)
{
raw_lines =
text.lines_raw(find_cursor.pos()..offset);
continue;
}
return Some((start, end));
}
}
} else {
let mut raw_lines = text.lines_raw(0..offset);
let mut find_cursor = Cursor::new(text, 0);
let mut regions = Vec::new();
while let Some(start) = find(
&mut find_cursor,
&mut raw_lines,
case_matching,
&search_string.content,
search_string.regex.as_ref(),
) {
let end = find_cursor.pos();
raw_lines = text.lines_raw(find_cursor.pos()..offset);
if whole_words
&& !Self::is_matching_whole_words(text, start, end)
{
continue;
}
if start < offset {
regions.push((start, end));
}
}
if !regions.is_empty() {
return Some(regions[regions.len() - 1]);
}
if wrap {
let mut raw_lines = text.lines_raw(offset..text.len());
let mut find_cursor = Cursor::new(text, offset);
let mut regions = Vec::new();
while let Some(start) = find(
&mut find_cursor,
&mut raw_lines,
case_matching,
&search_string.content,
search_string.regex.as_ref(),
) {
let end = find_cursor.pos();
if whole_words
&& !Self::is_matching_whole_words(text, start, end)
{
raw_lines =
text.lines_raw(find_cursor.pos()..text.len());
continue;
}
raw_lines =
text.lines_raw(find_cursor.pos()..text.len());
if start > offset {
regions.push((start, end));
}
}
if !regions.is_empty() {
return Some(regions[regions.len() - 1]);
}
}
}
None
},
)
}
/// Checks if the start and end of a match is matching whole words.
fn is_matching_whole_words(text: &Rope, start: usize, end: usize) -> bool {
let mut word_end_cursor = WordCursor::new(text, end - 1);
let mut word_start_cursor = WordCursor::new(text, start + 1);
if word_start_cursor.prev_code_boundary() != start {
return false;
}
if word_end_cursor.next_code_boundary() != end {
return false;
}
true
}
/// Returns `true` if the search query is a multi-line regex.
pub fn is_multiline_regex(&self) -> bool {
self.search_string.with_untracked(|search| {
if let Some(search) = search.as_ref() {
search.regex.is_some() && is_multiline_regex(&search.content)
} else {
false
}
})
}
#[allow(clippy::too_many_arguments)]
pub fn find(
text: &Rope,
search: &FindSearchString,
start: usize,
end: usize,
case_matching: CaseMatching,
whole_words: bool,
include_slop: bool,
occurrences: &mut Selection,
) {
let search_string = &search.content;
let slop = if include_slop {
search.content.len() * 2
} else {
0
};
// expand region to be able to find occurrences around the region's edges
let expanded_start = max(start, slop) - slop;
let expanded_end = min(end + slop, text.len());
let from = text
.at_or_prev_codepoint_boundary(expanded_start)
.unwrap_or(0);
let to = text
.at_or_next_codepoint_boundary(expanded_end)
.unwrap_or_else(|| text.len());
let mut to_cursor = Cursor::new(text, to);
let _ = to_cursor.next_leaf();
let sub_text = text.subseq(Interval::new(0, to_cursor.pos()));
let mut find_cursor = Cursor::new(&sub_text, from);
let mut raw_lines = text.lines_raw(from..to);
while let Some(start) = find(
&mut find_cursor,
&mut raw_lines,
case_matching,
search_string,
search.regex.as_ref(),
) {
let end = find_cursor.pos();
if whole_words && !Self::is_matching_whole_words(text, start, end) {
raw_lines = text.lines_raw(find_cursor.pos()..to);
continue;
}
let region = SelRegion::new(start, end, None);
let (_, e) = occurrences.add_range_distinct(region);
// in case of ambiguous search results (e.g. search "aba" in "ababa"),
// the search result closer to the beginning of the file wins
if e != end {
// Skip the search result and keep the occurrence that is closer to
// the beginning of the file. Re-align the cursor to the kept
// occurrence
find_cursor.set(e);
raw_lines = text.lines_raw(find_cursor.pos()..to);
continue;
}
// in case current cursor matches search result (for example query a* matches)
// all cursor positions, then cursor needs to be increased so that search
// continues at next position. Otherwise, search will result in overflow since
// search will always repeat at current cursor position.
if start == end {
// determine whether end of text is reached and stop search or increase
// cursor manually
if end + 1 >= text.len() {
break;
} else {
find_cursor.set(end + 1);
}
}
// update line iterator so that line starts at current cursor position
raw_lines = text.lines_raw(find_cursor.pos()..to);
}
}
/// Execute the search on the provided text in the range provided by `start` and `end`.
pub fn update_find(
&self,
text: &Rope,
start: usize,
end: usize,
include_slop: bool,
occurrences: &mut Selection,
) {
if self.search_string.with_untracked(|search| search.is_none()) {
return;
}
let search = self.search_string.get_untracked().unwrap();
let search_string = &search.content;
// extend the search by twice the string length (twice, because case matching may increase
// the length of an occurrence)
let slop = if include_slop {
search.content.len() * 2
} else {
0
};
// expand region to be able to find occurrences around the region's edges
let expanded_start = max(start, slop) - slop;
let expanded_end = min(end + slop, text.len());
let from = text
.at_or_prev_codepoint_boundary(expanded_start)
.unwrap_or(0);
let to = text
.at_or_next_codepoint_boundary(expanded_end)
.unwrap_or_else(|| text.len());
let mut to_cursor = Cursor::new(text, to);
let _ = to_cursor.next_leaf();
let sub_text = text.subseq(Interval::new(0, to_cursor.pos()));
let mut find_cursor = Cursor::new(&sub_text, from);
let mut raw_lines = text.lines_raw(from..to);
let case_matching = self.case_matching.get_untracked();
let whole_words = self.whole_words.get_untracked();
while let Some(start) = find(
&mut find_cursor,
&mut raw_lines,
case_matching,
search_string,
search.regex.as_ref(),
) {
let end = find_cursor.pos();
if whole_words && !Self::is_matching_whole_words(text, start, end) {
raw_lines = text.lines_raw(find_cursor.pos()..to);
continue;
}
let region = SelRegion::new(start, end, None);
let (_, e) = occurrences.add_range_distinct(region);
// in case of ambiguous search results (e.g. search "aba" in "ababa"),
// the search result closer to the beginning of the file wins
if e != end {
// Skip the search result and keep the occurrence that is closer to
// the beginning of the file. Re-align the cursor to the kept
// occurrence
find_cursor.set(e);
raw_lines = text.lines_raw(find_cursor.pos()..to);
continue;
}
// in case current cursor matches search result (for example query a* matches)
// all cursor positions, then cursor needs to be increased so that search
// continues at next position. Otherwise, search will result in overflow since
// search will always repeat at current cursor position.
if start == end {
// determine whether end of text is reached and stop search or increase
// cursor manually
if end + 1 >= text.len() {
break;
} else {
find_cursor.set(end + 1);
}
}
// update line iterator so that line starts at current cursor position
raw_lines = text.lines_raw(find_cursor.pos()..to);
}
}
}
#[derive(Clone)]
pub struct FindResult {
pub find_rev: RwSignal<u64>,
pub progress: RwSignal<FindProgress>,
pub occurrences: RwSignal<Selection>,
pub search_string: RwSignal<Option<FindSearchString>>,
pub case_matching: RwSignal<CaseMatching>,
pub whole_words: RwSignal<bool>,
pub is_regex: RwSignal<bool>,
}
impl FindResult {
pub fn new(cx: Scope) -> Self {
Self {
find_rev: cx.create_rw_signal(0),
progress: cx.create_rw_signal(FindProgress::Started),
occurrences: cx.create_rw_signal(Selection::new()),
search_string: cx.create_rw_signal(None),
case_matching: cx.create_rw_signal(CaseMatching::Exact),
whole_words: cx.create_rw_signal(false),
is_regex: cx.create_rw_signal(false),
}
}
pub fn reset(&self) {
self.progress.set(FindProgress::Started);
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/keypress.rs | lapce-app/src/keypress.rs | pub mod condition;
mod key;
pub mod keymap;
mod loader;
mod press;
use std::{path::PathBuf, rc::Rc, str::FromStr, time::SystemTime};
use anyhow::Result;
use floem::{
keyboard::{Key, KeyEvent, KeyEventExtModifierSupplement, Modifiers, NamedKey},
pointer::{MouseButton, PointerButton, PointerInputEvent},
reactive::{RwSignal, Scope, SignalUpdate, SignalWith},
};
use indexmap::IndexMap;
use itertools::Itertools;
use lapce_core::mode::{Mode, Modes};
pub use self::press::KeyPress;
use self::{
key::KeyInput,
keymap::{KeyMap, KeyMapPress},
loader::KeyMapLoader,
};
use crate::{
command::{CommandExecuted, CommandKind, LapceCommand, lapce_internal_commands},
config::LapceConfig,
keypress::{
condition::{CheckCondition, Condition},
keymap::KeymapMatch,
},
tracing::*,
};
const DEFAULT_KEYMAPS_COMMON: &str =
include_str!("../../defaults/keymaps-common.toml");
const DEFAULT_KEYMAPS_MACOS: &str =
include_str!("../../defaults/keymaps-macos.toml");
const DEFAULT_KEYMAPS_NONMACOS: &str =
include_str!("../../defaults/keymaps-nonmacos.toml");
pub trait KeyPressFocus: std::fmt::Debug {
fn get_mode(&self) -> Mode;
fn check_condition(&self, condition: Condition) -> bool;
fn run_command(
&self,
command: &LapceCommand,
count: Option<usize>,
mods: Modifiers,
) -> CommandExecuted;
fn expect_char(&self) -> bool {
false
}
fn focus_only(&self) -> bool {
false
}
fn receive_char(&self, c: &str);
}
impl KeyPressFocus for () {
fn get_mode(&self) -> Mode {
Mode::Normal
}
fn check_condition(&self, _condition: Condition) -> bool {
false
}
fn run_command(
&self,
_command: &LapceCommand,
_count: Option<usize>,
_mods: Modifiers,
) -> CommandExecuted {
CommandExecuted::No
}
fn expect_char(&self) -> bool {
false
}
fn focus_only(&self) -> bool {
false
}
fn receive_char(&self, _c: &str) {}
}
impl KeyPressFocus for Box<dyn KeyPressFocus> {
fn get_mode(&self) -> Mode {
(**self).get_mode()
}
fn check_condition(&self, condition: Condition) -> bool {
(**self).check_condition(condition)
}
fn run_command(
&self,
command: &LapceCommand,
count: Option<usize>,
mods: Modifiers,
) -> CommandExecuted {
(**self).run_command(command, count, mods)
}
fn expect_char(&self) -> bool {
(**self).expect_char()
}
fn focus_only(&self) -> bool {
(**self).focus_only()
}
fn receive_char(&self, c: &str) {
(**self).receive_char(c)
}
}
#[derive(Clone, Copy, Debug)]
pub enum EventRef<'a> {
Keyboard(&'a floem::keyboard::KeyEvent),
Pointer(&'a floem::pointer::PointerInputEvent),
}
impl<'a> From<&'a KeyEvent> for EventRef<'a> {
fn from(ev: &'a KeyEvent) -> Self {
Self::Keyboard(ev)
}
}
impl<'a> From<&'a PointerInputEvent> for EventRef<'a> {
fn from(ev: &'a PointerInputEvent) -> Self {
Self::Pointer(ev)
}
}
pub struct KeyPressHandle {
pub handled: bool,
pub keypress: KeyPress,
pub keymatch: KeymapMatch,
}
#[derive(Clone, Debug)]
pub struct KeyPressData {
count: RwSignal<Option<usize>>,
pending_keypress: RwSignal<(Vec<KeyPress>, Option<SystemTime>)>,
pub commands: Rc<IndexMap<String, LapceCommand>>,
pub keymaps: Rc<IndexMap<Vec<KeyMapPress>, Vec<KeyMap>>>,
pub command_keymaps: Rc<IndexMap<String, Vec<KeyMap>>>,
pub commands_with_keymap: Rc<Vec<KeyMap>>,
pub commands_without_keymap: Rc<Vec<LapceCommand>>,
}
impl KeyPressData {
pub fn new(cx: Scope, config: &LapceConfig) -> Self {
let (keymaps, command_keymaps) =
Self::get_keymaps(config).unwrap_or((IndexMap::new(), IndexMap::new()));
let mut keypress = Self {
count: cx.create_rw_signal(None),
pending_keypress: cx.create_rw_signal((Vec::new(), None)),
keymaps: Rc::new(keymaps),
command_keymaps: Rc::new(command_keymaps),
commands: Rc::new(lapce_internal_commands()),
commands_with_keymap: Rc::new(Vec::new()),
commands_without_keymap: Rc::new(Vec::new()),
};
keypress.load_commands();
keypress
}
pub fn update_keymaps(&mut self, config: &LapceConfig) {
if let Ok((new_keymaps, new_command_keymaps)) = Self::get_keymaps(config) {
self.keymaps = Rc::new(new_keymaps);
self.command_keymaps = Rc::new(new_command_keymaps);
self.load_commands();
}
}
fn load_commands(&mut self) {
let mut commands_with_keymap = Vec::new();
let mut commands_without_keymap = Vec::new();
for (_, keymaps) in self.command_keymaps.iter() {
for keymap in keymaps.iter() {
if self.commands.get(&keymap.command).is_some() {
commands_with_keymap.push(keymap.clone());
}
}
}
for (_, cmd) in self.commands.iter() {
if self
.command_keymaps
.get(cmd.kind.str())
.map(|x| x.is_empty())
.unwrap_or(true)
{
commands_without_keymap.push(cmd.clone());
}
}
self.commands_with_keymap = Rc::new(commands_with_keymap);
self.commands_without_keymap = Rc::new(commands_without_keymap);
}
fn handle_count<T: KeyPressFocus + ?Sized>(
&self,
focus: &T,
keypress: &KeyPress,
) -> bool {
if focus.expect_char() {
return false;
}
let mode = focus.get_mode();
if mode == Mode::Insert || mode == Mode::Terminal {
return false;
}
if !keypress.mods.is_empty() {
return false;
}
if let KeyInput::Keyboard {
logical: Key::Character(c),
..
} = &keypress.key
{
if let Ok(n) = c.parse::<usize>() {
if self.count.with_untracked(|count| count.is_some()) || n > 0 {
self.count
.update(|count| *count = Some(count.unwrap_or(0) * 10 + n));
return true;
}
}
}
false
}
fn run_command<T: KeyPressFocus + ?Sized>(
&self,
command: &str,
count: Option<usize>,
mods: Modifiers,
focus: &T,
) -> CommandExecuted {
if let Some(cmd) = self.commands.get(command) {
focus.run_command(cmd, count, mods)
} else {
CommandExecuted::No
}
}
pub fn keypress<'a>(event: impl Into<EventRef<'a>>) -> Option<KeyPress> {
let event = event.into();
let keypress = match event {
EventRef::Keyboard(ev) => KeyPress {
key: KeyInput::Keyboard {
logical: ev.key.logical_key.to_owned(),
physical: ev.key.physical_key,
key_without_modifiers: ev.key.key_without_modifiers(),
location: ev.key.location,
repeat: ev.key.repeat,
},
mods: Self::get_key_modifiers(ev),
},
EventRef::Pointer(ev) => KeyPress {
key: KeyInput::Pointer(ev.button),
mods: ev.modifiers,
},
};
Some(keypress)
}
pub fn key_down<'a, T: KeyPressFocus + ?Sized>(
&self,
event: impl Into<EventRef<'a>>,
focus: &T,
) -> KeyPressHandle {
let keypress = match Self::keypress(event) {
Some(keypress) => keypress,
None => {
return KeyPressHandle {
handled: false,
keymatch: KeymapMatch::None,
keypress: KeyPress {
key: KeyInput::Pointer(PointerButton::Mouse(
MouseButton::Primary,
)),
mods: Modifiers::empty(),
},
};
}
};
if self.handle_count(focus, &keypress) {
return KeyPressHandle {
handled: true,
keymatch: KeymapMatch::None,
keypress,
};
}
self.pending_keypress
.update(|(pending_keypress, last_time)| {
let last_time = last_time.replace(SystemTime::now());
if let Some(last_time_val) = last_time {
if last_time_val
.elapsed()
.map(|x| x.as_millis() > 1000)
.unwrap_or_default()
{
pending_keypress.clear();
}
}
pending_keypress.push(keypress.clone());
});
let keymatch =
self.pending_keypress
.with_untracked(|(pending_keypress, _)| {
self.match_keymap(pending_keypress, focus)
});
self.handle_keymatch(focus, keymatch, keypress)
}
pub fn handle_keymatch<T: KeyPressFocus + ?Sized>(
&self,
focus: &T,
keymatch: KeymapMatch,
keypress: KeyPress,
) -> KeyPressHandle {
let mods = keypress.mods;
match &keymatch {
KeymapMatch::Full(command) => {
self.pending_keypress
.update(|(pending_keypress, last_time)| {
last_time.take();
pending_keypress.clear();
});
let count = self.count.try_update(|count| count.take()).unwrap();
let handled = self.run_command(command, count, mods, focus)
== CommandExecuted::Yes;
return KeyPressHandle {
handled,
keymatch,
keypress,
};
}
KeymapMatch::Multiple(commands) => {
self.pending_keypress
.update(|(pending_keypress, last_time)| {
last_time.take();
pending_keypress.clear();
});
let count = self.count.try_update(|count| count.take()).unwrap();
for command in commands {
let handled = self.run_command(command, count, mods, focus)
== CommandExecuted::Yes;
if handled {
return KeyPressHandle {
handled,
keymatch,
keypress,
};
}
}
return KeyPressHandle {
handled: false,
keymatch,
keypress,
};
}
KeymapMatch::Prefix => {
// Here pending_keypress contains only a prefix of some keymap, so let's keep
// collecting key presses.
return KeyPressHandle {
handled: true,
keymatch,
keypress,
};
}
KeymapMatch::None => {
self.pending_keypress
.update(|(pending_keypress, last_time)| {
pending_keypress.clear();
last_time.take();
});
if focus.get_mode() == Mode::Insert {
let old_keypress = keypress.clone();
let mut keypress = keypress.clone();
keypress.mods.set(Modifiers::SHIFT, false);
if let KeymapMatch::Full(command) =
self.match_keymap(&[keypress], focus)
{
if let Some(cmd) = self.commands.get(&command) {
if let CommandKind::Move(_) = cmd.kind {
let handled = focus.run_command(cmd, None, mods)
== CommandExecuted::Yes;
return KeyPressHandle {
handled,
keymatch,
keypress: old_keypress,
};
}
}
}
}
}
}
let mut mods = keypress.mods;
#[cfg(target_os = "macos")]
{
mods.set(Modifiers::SHIFT, false);
mods.set(Modifiers::ALT, false);
}
#[cfg(not(target_os = "macos"))]
{
mods.set(Modifiers::SHIFT, false);
mods.set(Modifiers::ALTGR, false);
}
if mods.is_empty() {
if let KeyInput::Keyboard { logical, .. } = &keypress.key {
if let Key::Character(c) = logical {
focus.receive_char(c);
self.count.set(None);
return KeyPressHandle {
handled: true,
keymatch,
keypress,
};
} else if let Key::Named(NamedKey::Space) = logical {
focus.receive_char(" ");
self.count.set(None);
return KeyPressHandle {
handled: true,
keymatch,
keypress,
};
}
}
}
KeyPressHandle {
handled: false,
keymatch,
keypress,
}
}
fn get_key_modifiers(key_event: &KeyEvent) -> Modifiers {
let mut mods = key_event.modifiers;
match &key_event.key.logical_key {
Key::Named(NamedKey::Shift) => mods.set(Modifiers::SHIFT, false),
Key::Named(NamedKey::Alt) => mods.set(Modifiers::ALT, false),
Key::Named(NamedKey::Meta) => mods.set(Modifiers::META, false),
Key::Named(NamedKey::Control) => mods.set(Modifiers::CONTROL, false),
Key::Named(NamedKey::AltGraph) => mods.set(Modifiers::ALTGR, false),
_ => (),
}
mods
}
fn match_keymap<T: KeyPressFocus + ?Sized>(
&self,
keypresses: &[KeyPress],
check: &T,
) -> KeymapMatch {
let keypresses: Vec<KeyMapPress> =
keypresses.iter().filter_map(|k| k.keymap_press()).collect();
let matches: Vec<_> = self
.keymaps
.get(&keypresses)
.map(|keymaps| {
keymaps
.iter()
.filter(|keymap| {
if check.expect_char()
&& keypresses.len() == 1
&& keypresses[0].is_char()
{
return false;
}
if !keymap.modes.is_empty()
&& !keymap.modes.contains(check.get_mode().into())
{
return false;
}
if let Some(condition) = &keymap.when {
if !Self::check_condition(condition, check) {
return false;
}
}
true
})
.collect()
})
.unwrap_or_default();
if matches.is_empty() {
KeymapMatch::None
} else if matches.len() == 1 && matches[0].key == keypresses {
KeymapMatch::Full(matches[0].command.clone())
} else if matches.len() > 1
&& matches.iter().filter(|m| m.key != keypresses).count() == 0
{
KeymapMatch::Multiple(
matches.iter().rev().map(|m| m.command.clone()).collect(),
)
} else {
KeymapMatch::Prefix
}
}
fn check_condition<T: KeyPressFocus + ?Sized>(
condition: &str,
check: &T,
) -> bool {
fn check_one_condition<T: KeyPressFocus + ?Sized>(
condition: &str,
check: &T,
) -> bool {
let trimmed = condition.trim();
if let Some(stripped) = trimmed.strip_prefix('!') {
if let Ok(condition) = Condition::from_str(stripped) {
!check.check_condition(condition)
} else {
true
}
} else if let Ok(condition) = Condition::from_str(trimmed) {
check.check_condition(condition)
} else {
false
}
}
match CheckCondition::parse_first(condition) {
CheckCondition::Single(condition) => {
check_one_condition(condition, check)
}
CheckCondition::Or(left, right) => {
let left = check_one_condition(left, check);
let right = Self::check_condition(right, check);
left || right
}
CheckCondition::And(left, right) => {
let left = check_one_condition(left, check);
let right = Self::check_condition(right, check);
left && right
}
}
}
#[allow(clippy::type_complexity)]
fn get_keymaps(
config: &LapceConfig,
) -> Result<(
IndexMap<Vec<KeyMapPress>, Vec<KeyMap>>,
IndexMap<String, Vec<KeyMap>>,
)> {
let is_modal = config.core.modal;
let mut loader = KeyMapLoader::new();
if let Err(err) = loader.load_from_str(DEFAULT_KEYMAPS_COMMON, is_modal) {
trace!(TraceLevel::ERROR, "Failed to load common defaults: {err}");
}
let os_keymaps = if std::env::consts::OS == "macos" {
DEFAULT_KEYMAPS_MACOS
} else {
DEFAULT_KEYMAPS_NONMACOS
};
if let Err(err) = loader.load_from_str(os_keymaps, is_modal) {
trace!(TraceLevel::ERROR, "Failed to load OS defaults: {err}");
}
if let Some(path) = Self::file() {
if let Ok(content) = std::fs::read_to_string(&path) {
if let Err(err) = loader.load_from_str(&content, is_modal) {
trace!(TraceLevel::WARN, "Failed to load from {path:?}: {err}");
}
}
}
Ok(loader.finalize())
}
pub fn file() -> Option<PathBuf> {
LapceConfig::keymaps_file()
}
fn get_file_array() -> Option<toml_edit::ArrayOfTables> {
let path = Self::file()?;
let content = std::fs::read_to_string(path).ok()?;
let document: toml_edit::Document = content.parse().ok()?;
document
.as_table()
.get("keymaps")?
.as_array_of_tables()
.cloned()
}
pub fn update_file(keymap: &KeyMap, keys: &[KeyMapPress]) -> Option<()> {
let mut array = Self::get_file_array().unwrap_or_default();
let index = array.iter().position(|value| {
Some(keymap.command.as_str())
== value.get("command").and_then(|c| c.as_str())
&& keymap.when.as_deref()
== value.get("when").and_then(|w| w.as_str())
&& keymap.modes == get_modes(value)
&& Some(keymap.key.clone())
== value
.get("key")
.and_then(|v| v.as_str())
.map(KeyMapPress::parse)
});
if let Some(index) = index {
if !keys.is_empty() {
array.get_mut(index)?.insert(
"key",
toml_edit::value(toml_edit::Value::from(keys.iter().join(" "))),
);
} else {
array.remove(index);
};
} else {
let mut table = toml_edit::Table::new();
table.insert(
"command",
toml_edit::value(toml_edit::Value::from(keymap.command.clone())),
);
if !keymap.modes.is_empty() {
table.insert(
"mode",
toml_edit::value(toml_edit::Value::from(
keymap.modes.to_string(),
)),
);
}
if let Some(when) = keymap.when.as_ref() {
table.insert(
"when",
toml_edit::value(toml_edit::Value::from(when.to_string())),
);
}
if !keys.is_empty() {
table.insert(
"key",
toml_edit::value(toml_edit::Value::from(keys.iter().join(" "))),
);
array.push(table.clone());
}
if !keymap.key.is_empty() {
table.insert(
"key",
toml_edit::value(toml_edit::Value::from(
keymap.key.iter().join(" "),
)),
);
table.insert(
"command",
toml_edit::value(toml_edit::Value::from(format!(
"-{}",
keymap.command
))),
);
array.push(table.clone());
}
}
let mut table = toml_edit::Document::new();
table.insert("keymaps", toml_edit::Item::ArrayOfTables(array));
let path = Self::file()?;
std::fs::write(path, table.to_string().as_bytes()).ok()?;
None
}
}
fn get_modes(toml_keymap: &toml_edit::Table) -> Modes {
toml_keymap
.get("mode")
.and_then(|v| v.as_str())
.map(Modes::parse)
.unwrap_or_else(Modes::empty)
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/global_search.rs | lapce-app/src/global_search.rs | use std::{ops::Range, path::PathBuf, rc::Rc};
use floem::{
ext_event::create_ext_action,
keyboard::Modifiers,
reactive::{Memo, RwSignal, Scope, SignalGet, SignalUpdate, SignalWith},
views::VirtualVector,
};
use indexmap::IndexMap;
use lapce_core::{mode::Mode, selection::Selection};
use lapce_rpc::proxy::{ProxyResponse, SearchMatch};
use lapce_xi_rope::Rope;
use crate::{
command::{CommandExecuted, CommandKind},
editor::EditorData,
keypress::{KeyPressFocus, condition::Condition},
main_split::MainSplitData,
window_tab::CommonData,
};
#[derive(Clone)]
pub struct SearchMatchData {
pub expanded: RwSignal<bool>,
pub matches: RwSignal<im::Vector<SearchMatch>>,
pub line_height: Memo<f64>,
}
impl SearchMatchData {
pub fn height(&self) -> f64 {
let line_height = self.line_height.get();
let count = if self.expanded.get() {
self.matches.with(|m| m.len()) + 1
} else {
1
};
line_height * count as f64
}
}
#[derive(Clone, Debug)]
pub struct GlobalSearchData {
pub editor: EditorData,
pub search_result: RwSignal<IndexMap<PathBuf, SearchMatchData>>,
pub main_split: MainSplitData,
pub common: Rc<CommonData>,
}
impl KeyPressFocus for GlobalSearchData {
fn get_mode(&self) -> Mode {
Mode::Insert
}
fn check_condition(&self, condition: Condition) -> bool {
matches!(condition, Condition::PanelFocus)
}
fn run_command(
&self,
command: &crate::command::LapceCommand,
count: Option<usize>,
mods: Modifiers,
) -> CommandExecuted {
match &command.kind {
CommandKind::Workbench(_) => {}
CommandKind::Scroll(_) => {}
CommandKind::Focus(_) => {}
CommandKind::Edit(_)
| CommandKind::Move(_)
| CommandKind::MultiSelection(_) => {
return self.editor.run_command(command, count, mods);
}
CommandKind::MotionMode(_) => {}
}
CommandExecuted::No
}
fn receive_char(&self, c: &str) {
self.editor.receive_char(c);
}
}
impl VirtualVector<(PathBuf, SearchMatchData)> for GlobalSearchData {
fn total_len(&self) -> usize {
self.search_result.with(|result| {
result
.iter()
.map(|(_, data)| {
if data.expanded.get() {
data.matches.with(|m| m.len()) + 1
} else {
1
}
})
.sum()
})
}
fn slice(
&mut self,
_range: Range<usize>,
) -> impl Iterator<Item = (PathBuf, SearchMatchData)> {
self.search_result.get().into_iter()
}
}
impl GlobalSearchData {
pub fn new(cx: Scope, main_split: MainSplitData) -> Self {
let common = main_split.common.clone();
let editor = main_split.editors.make_local(cx, common.clone());
let search_result = cx.create_rw_signal(IndexMap::new());
let global_search = Self {
editor,
search_result,
main_split,
common,
};
{
let global_search = global_search.clone();
let buffer = global_search.editor.doc().buffer;
cx.create_effect(move |_| {
let pattern = buffer.with(|buffer| buffer.to_string());
if pattern.is_empty() {
global_search.search_result.update(|r| r.clear());
return;
}
let case_sensitive = global_search.common.find.case_sensitive(true);
let whole_word = global_search.common.find.whole_words.get();
let is_regex = global_search.common.find.is_regex.get();
let send = {
let global_search = global_search.clone();
create_ext_action(cx, move |result| {
if let Ok(ProxyResponse::GlobalSearchResponse { matches }) =
result
{
global_search.update_matches(matches);
}
})
};
global_search.common.proxy.global_search(
pattern,
case_sensitive,
whole_word,
is_regex,
move |result| {
send(result);
},
);
});
}
{
let buffer = global_search.editor.doc().buffer;
let main_split = global_search.main_split.clone();
cx.create_effect(move |_| {
let content = buffer.with(|buffer| buffer.to_string());
main_split.set_find_pattern(Some(content));
});
}
global_search
}
fn update_matches(&self, matches: IndexMap<PathBuf, Vec<SearchMatch>>) {
let current = self.search_result.get_untracked();
self.search_result.set(
matches
.into_iter()
.map(|(path, matches)| {
let match_data =
current.get(&path).cloned().unwrap_or_else(|| {
SearchMatchData {
expanded: self.common.scope.create_rw_signal(true),
matches: self
.common
.scope
.create_rw_signal(im::Vector::new()),
line_height: self.common.ui_line_height,
}
});
match_data.matches.set(matches.into());
(path, match_data)
})
.collect(),
);
}
pub fn set_pattern(&self, pattern: String) {
let pattern_len = pattern.len();
self.editor.doc().reload(Rope::from(pattern), true);
self.editor
.cursor()
.update(|cursor| cursor.set_insert(Selection::region(0, pattern_len)));
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/debug.rs | lapce-app/src/debug.rs | use std::{
collections::{BTreeMap, HashMap},
fmt::Display,
path::PathBuf,
rc::Rc,
time::Instant,
};
use floem::{
ext_event::create_ext_action,
reactive::{Memo, RwSignal, Scope, SignalGet, SignalUpdate, SignalWith},
views::VirtualVector,
};
use lapce_rpc::{
dap_types::{
self, DapId, RunDebugConfig, SourceBreakpoint, StackFrame, Stopped,
ThreadId, Variable,
},
proxy::ProxyResponse,
terminal::TermId,
};
use serde::{Deserialize, Serialize};
use crate::{
command::InternalCommand,
editor::location::{EditorLocation, EditorPosition},
window_tab::CommonData,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RunDebugMode {
Run,
Debug,
}
impl Display for RunDebugMode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = match self {
RunDebugMode::Run => "Run",
RunDebugMode::Debug => "Debug",
};
f.write_str(s)
}
}
#[derive(Clone)]
pub struct RunDebugProcess {
pub mode: RunDebugMode,
pub config: RunDebugConfig,
pub stopped: bool,
pub created: Instant,
pub is_prelaunch: bool,
}
#[derive(Deserialize, Serialize)]
pub struct RunDebugConfigs {
pub configs: Vec<RunDebugConfig>,
}
#[derive(Clone)]
pub struct RunDebugData {
pub active_term: RwSignal<Option<TermId>>,
pub daps: RwSignal<im::HashMap<DapId, DapData>>,
pub breakpoints: RwSignal<BTreeMap<PathBuf, BTreeMap<usize, LapceBreakpoint>>>,
}
impl RunDebugData {
pub fn new(
cx: Scope,
breakpoints: RwSignal<BTreeMap<PathBuf, BTreeMap<usize, LapceBreakpoint>>>,
) -> Self {
let active_term: RwSignal<Option<TermId>> = cx.create_rw_signal(None);
let daps: RwSignal<im::HashMap<DapId, DapData>> =
cx.create_rw_signal(im::HashMap::new());
Self {
active_term,
daps,
breakpoints,
}
}
pub fn source_breakpoints(&self) -> HashMap<PathBuf, Vec<SourceBreakpoint>> {
self.breakpoints
.get_untracked()
.iter()
.map(|(path, breakpoints)| {
(
path.to_path_buf(),
breakpoints
.iter()
.filter_map(|(_, b)| {
if b.active {
Some(SourceBreakpoint {
line: b.line + 1,
column: None,
condition: None,
hit_condition: None,
log_message: None,
})
} else {
None
}
})
.collect(),
)
})
.collect()
}
}
#[derive(Clone, PartialEq)]
pub struct StackTraceData {
pub expanded: RwSignal<bool>,
pub frames: RwSignal<im::Vector<StackFrame>>,
pub frames_shown: usize,
}
#[derive(Clone, Serialize, Deserialize)]
pub struct LapceBreakpoint {
pub id: Option<usize>,
pub verified: bool,
pub message: Option<String>,
pub line: usize,
pub offset: usize,
pub dap_line: Option<usize>,
pub active: bool,
}
#[derive(Clone, PartialEq, Eq)]
#[allow(clippy::large_enum_variant)]
pub enum ScopeOrVar {
Scope(dap_types::Scope),
Var(dap_types::Variable),
}
impl Default for ScopeOrVar {
fn default() -> Self {
ScopeOrVar::Scope(dap_types::Scope::default())
}
}
impl ScopeOrVar {
pub fn name(&self) -> &str {
match self {
ScopeOrVar::Scope(scope) => &scope.name,
ScopeOrVar::Var(var) => &var.name,
}
}
pub fn value(&self) -> Option<&str> {
match self {
ScopeOrVar::Scope(_) => None,
ScopeOrVar::Var(var) => Some(&var.value),
}
}
pub fn ty(&self) -> Option<&str> {
match self {
ScopeOrVar::Scope(_) => None,
ScopeOrVar::Var(var) => var.ty.as_deref(),
}
}
pub fn reference(&self) -> usize {
match self {
ScopeOrVar::Scope(scope) => scope.variables_reference,
ScopeOrVar::Var(var) => var.variables_reference,
}
}
}
#[derive(Clone, Default)]
pub struct DapVariable {
pub item: ScopeOrVar,
pub parent: Vec<usize>,
pub expanded: bool,
pub read: bool,
pub children: Vec<DapVariable>,
pub children_expanded_count: usize,
}
#[derive(Clone)]
pub struct DapData {
pub term_id: TermId,
pub dap_id: DapId,
pub stopped: RwSignal<bool>,
pub thread_id: RwSignal<Option<ThreadId>>,
pub stack_traces: RwSignal<BTreeMap<ThreadId, StackTraceData>>,
pub variables_id: RwSignal<usize>,
pub variables: RwSignal<DapVariable>,
pub breakline: Memo<Option<(usize, PathBuf)>>,
pub common: Rc<CommonData>,
}
impl DapData {
pub fn new(
cx: Scope,
dap_id: DapId,
term_id: TermId,
common: Rc<CommonData>,
) -> Self {
let stopped = cx.create_rw_signal(false);
let thread_id = cx.create_rw_signal(None);
let stack_traces: RwSignal<BTreeMap<ThreadId, StackTraceData>> =
cx.create_rw_signal(BTreeMap::new());
let breakline = cx.create_memo(move |_| {
let thread_id = thread_id.get();
if let Some(thread_id) = thread_id {
let trace = stack_traces
.with(|stack_traces| stack_traces.get(&thread_id).cloned());
if let Some(trace) = trace {
let breakline = trace.frames.with(|f| {
f.get(0)
.and_then(|f| {
f.source
.as_ref()
.map(|s| (f.line.saturating_sub(1), s))
})
.and_then(|(line, s)| s.path.clone().map(|p| (line, p)))
});
return breakline;
}
None
} else {
None
}
});
Self {
term_id,
dap_id,
stopped,
thread_id,
stack_traces,
variables_id: cx.create_rw_signal(0),
variables: cx.create_rw_signal(DapVariable {
item: ScopeOrVar::Scope(dap_types::Scope::default()),
parent: Vec::new(),
expanded: true,
read: true,
children: Vec::new(),
children_expanded_count: 0,
}),
breakline,
common,
}
}
pub fn stopped(
&self,
cx: Scope,
stopped: &Stopped,
stack_traces: &HashMap<ThreadId, Vec<StackFrame>>,
variables: &[(dap_types::Scope, Vec<Variable>)],
) {
self.stopped.set(true);
self.thread_id.update(|thread_id| {
*thread_id = Some(stopped.thread_id.unwrap_or_default());
});
let main_thread_id = self.thread_id.get_untracked();
let mut current_stack_traces = self.stack_traces.get_untracked();
current_stack_traces.retain(|t, _| stack_traces.contains_key(t));
for (thread_id, frames) in stack_traces {
let is_main_thread = main_thread_id.as_ref() == Some(thread_id);
if is_main_thread {
if let Some(frame) = frames.first() {
if let Some(path) =
frame.source.as_ref().and_then(|source| source.path.clone())
{
self.common.internal_command.send(
InternalCommand::JumpToLocation {
location: EditorLocation {
path,
position: Some(EditorPosition::Line(
frame.line.saturating_sub(1),
)),
scroll_offset: None,
ignore_unconfirmed: false,
same_editor_tab: false,
},
},
);
}
}
}
if let Some(current) = current_stack_traces.get_mut(thread_id) {
current.frames.set(frames.into());
if is_main_thread {
current.expanded.set(true);
}
} else {
current_stack_traces.insert(
*thread_id,
StackTraceData {
expanded: cx.create_rw_signal(is_main_thread),
frames: cx.create_rw_signal(frames.into()),
frames_shown: 20,
},
);
}
}
self.stack_traces.set(current_stack_traces);
self.variables.update(|dap_var| {
dap_var.children = variables
.iter()
.enumerate()
.map(|(i, (scope, vars))| DapVariable {
item: ScopeOrVar::Scope(scope.to_owned()),
parent: Vec::new(),
expanded: i == 0,
read: true,
children: vars
.iter()
.map(|var| DapVariable {
item: ScopeOrVar::Var(var.to_owned()),
parent: vec![scope.variables_reference],
expanded: false,
read: false,
children: Vec::new(),
children_expanded_count: 0,
})
.collect(),
children_expanded_count: if i == 0 { vars.len() } else { 0 },
})
.collect();
dap_var.children_expanded_count = dap_var
.children
.iter()
.map(|v| v.children_expanded_count + 1)
.sum::<usize>();
});
}
pub fn toggle_expand(&self, parent: Vec<usize>, reference: usize) {
self.variables_id.update(|id| {
*id += 1;
});
self.variables.update(|variables| {
if let Some(var) = variables.get_var_mut(&parent, reference) {
if var.expanded {
var.expanded = false;
variables.update_count_recursive(&parent, reference);
} else {
var.expanded = true;
if !var.read {
var.read = true;
self.read_var_children(&parent, reference);
} else {
variables.update_count_recursive(&parent, reference);
}
}
}
});
}
fn read_var_children(&self, parent: &[usize], reference: usize) {
let root = self.variables;
let parent = parent.to_vec();
let variables_id = self.variables_id;
let send = create_ext_action(self.common.scope, move |result| {
if let Ok(ProxyResponse::DapVariableResponse { varialbes }) = result {
variables_id.update(|id| {
*id += 1;
});
root.update(|root| {
if let Some(var) = root.get_var_mut(&parent, reference) {
let mut new_parent = parent.clone();
new_parent.push(reference);
var.read = true;
var.children = varialbes
.into_iter()
.map(|v| DapVariable {
item: ScopeOrVar::Var(v),
parent: new_parent.clone(),
expanded: false,
read: false,
children: Vec::new(),
children_expanded_count: 0,
})
.collect();
root.update_count_recursive(&parent, reference);
}
});
}
});
self.common
.proxy
.dap_variable(self.dap_id, reference, move |result| {
send(result);
});
}
}
pub struct DapVariableViewdata {
pub item: ScopeOrVar,
pub parent: Vec<usize>,
pub expanded: bool,
pub level: usize,
}
impl VirtualVector<DapVariableViewdata> for DapVariable {
fn total_len(&self) -> usize {
self.children_expanded_count
}
fn slice(
&mut self,
range: std::ops::Range<usize>,
) -> impl Iterator<Item = DapVariableViewdata> {
let min = range.start;
let max = range.end;
let mut i = 0;
let mut view_items = Vec::new();
for item in self.children.iter() {
i = item.append_view_slice(&mut view_items, min, max, i + 1, 0);
if i > max {
return view_items.into_iter();
}
}
view_items.into_iter()
}
}
impl DapVariable {
pub fn append_view_slice(
&self,
view_items: &mut Vec<DapVariableViewdata>,
min: usize,
max: usize,
current: usize,
level: usize,
) -> usize {
if current > max {
return current;
}
if current + self.children_expanded_count < min {
return current + self.children_expanded_count;
}
let mut i = current;
if current >= min {
view_items.push(DapVariableViewdata {
item: self.item.clone(),
parent: self.parent.clone(),
expanded: self.expanded,
level,
});
}
if self.expanded {
for item in self.children.iter() {
i = item.append_view_slice(view_items, min, max, i + 1, level + 1);
if i > max {
return i;
}
}
}
i
}
pub fn get_var_mut(
&mut self,
parent: &[usize],
reference: usize,
) -> Option<&mut DapVariable> {
let parent = if parent.is_empty() {
self
} else {
parent.iter().try_fold(self, |item, parent| {
item.children
.iter_mut()
.find(|c| c.item.reference() == *parent)
})?
};
parent
.children
.iter_mut()
.find(|c| c.item.reference() == reference)
}
pub fn update_count_recursive(&mut self, parent: &[usize], reference: usize) {
let mut parent = parent.to_vec();
self.update_count(&parent, reference);
while let Some(reference) = parent.pop() {
self.update_count(&parent, reference);
}
self.children_expanded_count = self
.children
.iter()
.map(|item| item.children_expanded_count + 1)
.sum::<usize>();
}
pub fn update_count(
&mut self,
parent: &[usize],
reference: usize,
) -> Option<()> {
let var = self.get_var_mut(parent, reference)?;
var.children_expanded_count = if var.expanded {
var.children
.iter()
.map(|item| item.children_expanded_count + 1)
.sum::<usize>()
} else {
0
};
Some(())
}
}
#[cfg(test)]
mod tests {
use lapce_rpc::dap_types::{Scope, Variable};
use super::{DapVariable, ScopeOrVar};
#[test]
fn test_update_count() {
let variables = [
(
Scope {
variables_reference: 0,
..Default::default()
},
vec![
Variable {
variables_reference: 3,
..Default::default()
},
Variable {
variables_reference: 4,
..Default::default()
},
],
),
(
Scope {
variables_reference: 1,
..Default::default()
},
vec![
Variable {
variables_reference: 5,
..Default::default()
},
Variable {
variables_reference: 6,
..Default::default()
},
],
),
(
Scope {
variables_reference: 2,
..Default::default()
},
vec![
Variable {
variables_reference: 7,
..Default::default()
},
Variable {
variables_reference: 8,
..Default::default()
},
],
),
];
let mut root = DapVariable {
item: ScopeOrVar::Scope(Scope::default()),
parent: Vec::new(),
expanded: true,
read: true,
children: variables
.iter()
.map(|(scope, vars)| DapVariable {
item: ScopeOrVar::Scope(scope.to_owned()),
parent: Vec::new(),
expanded: true,
read: true,
children: vars
.iter()
.map(|var| DapVariable {
item: ScopeOrVar::Var(var.to_owned()),
parent: vec![scope.variables_reference],
expanded: false,
read: false,
children: Vec::new(),
children_expanded_count: 0,
})
.collect(),
children_expanded_count: vars.len(),
})
.collect(),
children_expanded_count: 0,
};
root.children_expanded_count = root
.children
.iter()
.map(|v| v.children_expanded_count + 1)
.sum::<usize>();
assert_eq!(root.children_expanded_count, 9);
let var = root.get_var_mut(&[0], 3).unwrap();
var.expanded = true;
var.read = true;
var.children = [
Variable {
variables_reference: 9,
..Default::default()
},
Variable {
variables_reference: 10,
..Default::default()
},
]
.iter()
.map(|var| DapVariable {
item: ScopeOrVar::Var(var.to_owned()),
parent: vec![0, 3],
expanded: false,
read: false,
children: Vec::new(),
children_expanded_count: 0,
})
.collect();
root.update_count_recursive(&[0], 3);
let var = root.get_var_mut(&[0], 3).unwrap();
assert_eq!(var.children_expanded_count, 2);
let var = root.get_var_mut(&[], 0).unwrap();
assert_eq!(var.children_expanded_count, 4);
assert_eq!(root.children_expanded_count, 11);
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/lsp.rs | lapce-app/src/lsp.rs | use std::path::PathBuf;
use tracing::{Level, event};
use url::Url;
// Rust-analyzer returns paths in the form of "file:///<drive>:/...", which gets parsed into URL
// as "/<drive>://" which is then interpreted by PathBuf::new() as a UNIX-like path from root.
// This function strips the additional / from the beginning, if the first segment is a drive letter.
#[cfg(windows)]
pub fn path_from_url(url: &Url) -> PathBuf {
use percent_encoding::percent_decode_str;
event!(Level::DEBUG, "Converting `{:?}` to path", url);
if let Ok(path) = url.to_file_path() {
return path;
}
let path = url.path();
let path = if path.contains('%') {
percent_decode_str(path)
.decode_utf8()
.unwrap_or(std::borrow::Cow::from(path))
} else {
std::borrow::Cow::from(path)
};
if let Some(path) = path.strip_prefix('/') {
event!(Level::DEBUG, "Found `/` prefix");
if let Some((maybe_drive_letter, path_second_part)) =
path.split_once(['/', '\\'])
{
event!(Level::DEBUG, maybe_drive_letter);
event!(Level::DEBUG, path_second_part);
let b = maybe_drive_letter.as_bytes();
if !b.is_empty() && !b[0].is_ascii_alphabetic() {
event!(Level::ERROR, "First byte is not ascii alphabetic: {b:?}");
}
match maybe_drive_letter.len() {
2 => match maybe_drive_letter.chars().nth(1) {
Some(':') => {
event!(Level::DEBUG, "Returning path `{:?}`", path);
return PathBuf::from(path);
}
v => {
event!(
Level::ERROR,
"Unhandled 'maybe_drive_letter' chars: {v:?}"
);
}
},
4 => {
if maybe_drive_letter.contains("%3A") {
let path = path.replace("%3A", ":");
event!(Level::DEBUG, "Returning path `{:?}`", path);
return PathBuf::from(path);
} else {
event!(
Level::ERROR,
"Unhandled 'maybe_drive_letter' pattern: {maybe_drive_letter:?}"
);
}
}
v => {
event!(
Level::ERROR,
"Unhandled 'maybe_drive_letter' length: {v}"
);
}
}
}
}
event!(Level::DEBUG, "Returning unmodified path `{:?}`", path);
PathBuf::from(path.into_owned())
}
#[cfg(not(windows))]
pub fn path_from_url(url: &Url) -> PathBuf {
event!(Level::DEBUG, "Converting `{:?}` to path", url);
url.to_file_path().unwrap_or_else(|_| {
let path = url.path();
if let Ok(path) = percent_encoding::percent_decode_str(path).decode_utf8() {
return PathBuf::from(path.into_owned());
}
PathBuf::from(path)
})
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/history.rs | lapce-app/src/history.rs | use std::path::PathBuf;
use lapce_core::buffer::Buffer;
#[derive(Clone)]
pub struct DocumentHistory {
pub buffer: Buffer,
// path: PathBuf,
// version: String,
// styles: Arc<Spans<Style>>,
// line_styles: Rc<RefCell<LineStyles>>,
// text_layouts: Rc<RefCell<TextLayoutCache>>,
}
impl DocumentHistory {
pub fn new(_path: PathBuf, _version: String, content: &str) -> Self {
Self {
buffer: Buffer::new(content),
// path,
// version,
// styles: Arc::new(Spans::default()),
// line_styles: Rc::new(RefCell::new(LineStyles::new())),
// text_layouts: Rc::new(RefCell::new(TextLayoutCache::new())),
}
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/markdown.rs | lapce-app/src/markdown.rs | use floem::text::{
Attrs, AttrsList, FamilyOwned, LineHeightValue, Style, TextLayout, Weight,
};
use lapce_core::{language::LapceLanguage, syntax::Syntax};
use lapce_xi_rope::Rope;
use lsp_types::MarkedString;
use pulldown_cmark::{CodeBlockKind, CowStr, Event, Options, Parser, Tag};
use smallvec::SmallVec;
use crate::config::{LapceConfig, color::LapceColor};
#[derive(Clone)]
pub enum MarkdownContent {
Text(TextLayout),
Image { url: String, title: String },
Separator,
}
pub fn parse_markdown(
text: &str,
line_height: f64,
config: &LapceConfig,
) -> Vec<MarkdownContent> {
let mut res = Vec::new();
let mut current_text = String::new();
let code_font_family: Vec<FamilyOwned> =
FamilyOwned::parse_list(&config.editor.font_family).collect();
let default_attrs = Attrs::new()
.color(config.color(LapceColor::EDITOR_FOREGROUND))
.font_size(config.ui.font_size() as f32)
.line_height(LineHeightValue::Normal(line_height as f32));
let mut attr_list = AttrsList::new(default_attrs.clone());
let mut builder_dirty = false;
let mut pos = 0;
let mut tag_stack: SmallVec<[(usize, Tag); 4]> = SmallVec::new();
let parser = Parser::new_ext(
text,
Options::ENABLE_TABLES
| Options::ENABLE_FOOTNOTES
| Options::ENABLE_STRIKETHROUGH
| Options::ENABLE_TASKLISTS
| Options::ENABLE_HEADING_ATTRIBUTES,
);
let mut last_text = CowStr::from("");
// Whether we should add a newline on the next entry
// This is used so that we don't emit newlines at the very end of the generation
let mut add_newline = false;
for event in parser {
// Add the newline since we're going to be outputting more
if add_newline {
current_text.push('\n');
builder_dirty = true;
pos += 1;
add_newline = false;
}
match event {
Event::Start(tag) => {
tag_stack.push((pos, tag));
}
Event::End(end_tag) => {
if let Some((start_offset, tag)) = tag_stack.pop() {
if end_tag != tag.to_end() {
tracing::warn!("Mismatched markdown tag");
continue;
}
if let Some(attrs) = attribute_for_tag(
default_attrs.clone(),
&tag,
&code_font_family,
config,
) {
attr_list
.add_span(start_offset..pos.max(start_offset), attrs);
}
if should_add_newline_after_tag(&tag) {
add_newline = true;
}
match &tag {
Tag::CodeBlock(kind) => {
let language =
if let CodeBlockKind::Fenced(language) = kind {
md_language_to_lapce_language(language)
} else {
None
};
highlight_as_code(
&mut attr_list,
default_attrs.clone().family(&code_font_family),
language,
&last_text,
start_offset,
config,
);
builder_dirty = true;
}
Tag::Image {
link_type: _,
dest_url: dest,
title,
id: _,
} => {
// TODO: Are there any link types that would change how the
// image is rendered?
if builder_dirty {
let mut text_layout = TextLayout::new();
text_layout.set_text(¤t_text, attr_list, None);
res.push(MarkdownContent::Text(text_layout));
attr_list = AttrsList::new(default_attrs.clone());
current_text.clear();
pos = 0;
builder_dirty = false;
}
res.push(MarkdownContent::Image {
url: dest.to_string(),
title: title.to_string(),
});
}
_ => {
// Presumably?
builder_dirty = true;
}
}
} else {
tracing::warn!("Unbalanced markdown tag")
}
}
Event::Text(text) => {
if let Some((_, tag)) = tag_stack.last() {
if should_skip_text_in_tag(tag) {
continue;
}
}
current_text.push_str(&text);
pos += text.len();
last_text = text;
builder_dirty = true;
}
Event::Code(text) => {
attr_list.add_span(
pos..pos + text.len(),
default_attrs.clone().family(&code_font_family),
);
current_text.push_str(&text);
pos += text.len();
builder_dirty = true;
}
// TODO: Some minimal 'parsing' of html could be useful here, since some things use
// basic html like `<code>text</code>`.
Event::Html(text) => {
attr_list.add_span(
pos..pos + text.len(),
default_attrs
.clone()
.family(&code_font_family)
.color(config.color(LapceColor::MARKDOWN_BLOCKQUOTE)),
);
current_text.push_str(&text);
pos += text.len();
builder_dirty = true;
}
Event::HardBreak => {
current_text.push('\n');
pos += 1;
builder_dirty = true;
}
Event::SoftBreak => {
current_text.push(' ');
pos += 1;
builder_dirty = true;
}
Event::Rule => {}
Event::FootnoteReference(_text) => {}
Event::TaskListMarker(_text) => {}
Event::InlineHtml(_) => {} // TODO(panekj): Implement
Event::InlineMath(_) => {} // TODO(panekj): Implement
Event::DisplayMath(_) => {} // TODO(panekj): Implement
}
}
if builder_dirty {
let mut text_layout = TextLayout::new();
text_layout.set_text(¤t_text, attr_list, None);
res.push(MarkdownContent::Text(text_layout));
}
res
}
fn attribute_for_tag<'a>(
default_attrs: Attrs<'a>,
tag: &Tag,
code_font_family: &'a [FamilyOwned],
config: &LapceConfig,
) -> Option<Attrs<'a>> {
use pulldown_cmark::HeadingLevel;
match tag {
Tag::Heading {
level,
id: _,
classes: _,
attrs: _,
} => {
// The size calculations are based on the em values given at
// https://drafts.csswg.org/css2/#html-stylesheet
let font_scale = match level {
HeadingLevel::H1 => 2.0,
HeadingLevel::H2 => 1.5,
HeadingLevel::H3 => 1.17,
HeadingLevel::H4 => 1.0,
HeadingLevel::H5 => 0.83,
HeadingLevel::H6 => 0.75,
};
let font_size = font_scale * config.ui.font_size() as f64;
Some(
default_attrs
.font_size(font_size as f32)
.weight(Weight::BOLD),
)
}
Tag::BlockQuote(_block_quote) => Some(
default_attrs
.style(Style::Italic)
.color(config.color(LapceColor::MARKDOWN_BLOCKQUOTE)),
),
Tag::CodeBlock(_) => Some(default_attrs.family(code_font_family)),
Tag::Emphasis => Some(default_attrs.style(Style::Italic)),
Tag::Strong => Some(default_attrs.weight(Weight::BOLD)),
// TODO: Strikethrough support
Tag::Link {
link_type: _,
dest_url: _,
title: _,
id: _,
} => {
// TODO: Link support
Some(default_attrs.color(config.color(LapceColor::EDITOR_LINK)))
}
// All other tags are currently ignored
_ => None,
}
}
/// Decides whether newlines should be added after a specific markdown tag
fn should_add_newline_after_tag(tag: &Tag) -> bool {
!matches!(
tag,
Tag::Emphasis | Tag::Strong | Tag::Strikethrough | Tag::Link { .. }
)
}
/// Whether it should skip the text node after a specific tag
/// For example, images are skipped because it emits their title as a separate text node.
fn should_skip_text_in_tag(tag: &Tag) -> bool {
matches!(tag, Tag::Image { .. })
}
fn md_language_to_lapce_language(lang: &str) -> Option<LapceLanguage> {
// TODO: There are many other names commonly used that should be supported
LapceLanguage::from_name(lang)
}
/// Highlight the text in a richtext builder like it was a markdown codeblock
pub fn highlight_as_code(
attr_list: &mut AttrsList,
default_attrs: Attrs,
language: Option<LapceLanguage>,
text: &str,
start_offset: usize,
config: &LapceConfig,
) {
let syntax = language.map(Syntax::from_language);
let styles = syntax
.map(|mut syntax| {
syntax.parse(0, Rope::from(text), None);
syntax.styles
})
.unwrap_or(None);
if let Some(styles) = styles {
for (range, style) in styles.iter() {
if let Some(color) = style
.fg_color
.as_ref()
.and_then(|fg| config.style_color(fg))
{
attr_list.add_span(
start_offset + range.start..start_offset + range.end,
default_attrs.clone().color(color),
);
}
}
}
}
pub fn from_marked_string(
text: MarkedString,
config: &LapceConfig,
) -> Vec<MarkdownContent> {
match text {
MarkedString::String(text) => parse_markdown(&text, 1.8, config),
// This is a short version of a code block
MarkedString::LanguageString(code) => {
// TODO: We could simply construct the MarkdownText directly
// Simply construct the string as if it was written directly
parse_markdown(
&format!("```{}\n{}\n```", code.language, code.value),
1.8,
config,
)
}
}
}
pub fn from_plaintext(
text: &str,
line_height: f64,
config: &LapceConfig,
) -> Vec<MarkdownContent> {
let mut text_layout = TextLayout::new();
text_layout.set_text(
text,
AttrsList::new(
Attrs::new()
.font_size(config.ui.font_size() as f32)
.line_height(LineHeightValue::Normal(line_height as f32)),
),
None,
);
vec![MarkdownContent::Text(text_layout)]
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/window.rs | lapce-app/src/window.rs | use std::{path::PathBuf, rc::Rc, sync::Arc};
use floem::{
ViewId,
action::TimerToken,
peniko::kurbo::{Point, Size},
reactive::{
Memo, ReadSignal, RwSignal, Scope, SignalGet, SignalUpdate, SignalWith,
use_context,
},
window::WindowId,
};
use serde::{Deserialize, Serialize};
use crate::{
app::AppCommand,
command::{InternalCommand, WindowCommand},
config::LapceConfig,
db::LapceDb,
keypress::EventRef,
listener::Listener,
update::ReleaseInfo,
window_tab::WindowTabData,
workspace::LapceWorkspace,
};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TabsInfo {
pub active_tab: usize,
pub workspaces: Vec<LapceWorkspace>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WindowInfo {
pub size: Size,
pub pos: Point,
pub maximised: bool,
pub tabs: TabsInfo,
}
#[derive(Clone)]
pub struct WindowCommonData {
pub window_command: Listener<WindowCommand>,
pub window_scale: RwSignal<f64>,
pub size: RwSignal<Size>,
pub num_window_tabs: Memo<usize>,
pub window_maximized: RwSignal<bool>,
pub window_tab_header_height: RwSignal<f64>,
pub latest_release: ReadSignal<Arc<Option<ReleaseInfo>>>,
pub ime_allowed: RwSignal<bool>,
pub cursor_blink_timer: RwSignal<TimerToken>,
// the value to be update by curosr blinking
pub hide_cursor: RwSignal<bool>,
pub app_view_id: RwSignal<ViewId>,
pub extra_plugin_paths: Arc<Vec<PathBuf>>,
}
/// `WindowData` is the application model for a top-level window.
///
/// A top-level window can be independently moved around and
/// resized using your window manager. Normally Lapce has only one
/// top-level window, but new ones can be created using the "New Window"
/// command.
///
/// Each window has its own collection of "window tabs" (again, there is
/// normally only one window tab), size, position etc.
#[derive(Clone)]
pub struct WindowData {
pub window_id: WindowId,
pub scope: Scope,
/// The set of tabs within the window. These tabs are high-level
/// constructs for workspaces, in particular they are not **editor tabs**.
pub window_tabs: RwSignal<im::Vector<(RwSignal<usize>, Rc<WindowTabData>)>>,
pub num_window_tabs: Memo<usize>,
/// The index of the active window tab.
pub active: RwSignal<usize>,
pub app_command: Listener<AppCommand>,
pub position: RwSignal<Point>,
pub root_view_id: RwSignal<ViewId>,
pub window_scale: RwSignal<f64>,
pub config: RwSignal<Arc<LapceConfig>>,
pub ime_enabled: RwSignal<bool>,
pub common: Rc<WindowCommonData>,
}
impl WindowData {
pub fn new(
window_id: WindowId,
app_view_id: RwSignal<ViewId>,
info: WindowInfo,
window_scale: RwSignal<f64>,
latest_release: ReadSignal<Arc<Option<ReleaseInfo>>>,
extra_plugin_paths: Arc<Vec<PathBuf>>,
app_command: Listener<AppCommand>,
) -> Self {
let cx = Scope::new();
let config =
LapceConfig::load(&LapceWorkspace::default(), &[], &extra_plugin_paths);
let config = cx.create_rw_signal(Arc::new(config));
let root_view_id = cx.create_rw_signal(ViewId::new());
let window_tabs = cx.create_rw_signal(im::Vector::new());
let num_window_tabs =
cx.create_memo(move |_| window_tabs.with(|tabs| tabs.len()));
let active = info.tabs.active_tab;
let window_command = Listener::new_empty(cx);
let ime_allowed = cx.create_rw_signal(false);
let window_maximized = cx.create_rw_signal(false);
let size = cx.create_rw_signal(Size::ZERO);
let window_tab_header_height = cx.create_rw_signal(0.0);
let cursor_blink_timer = cx.create_rw_signal(TimerToken::INVALID);
let hide_cursor = cx.create_rw_signal(false);
let common = Rc::new(WindowCommonData {
window_command,
window_scale,
size,
num_window_tabs,
window_maximized,
window_tab_header_height,
latest_release,
ime_allowed,
cursor_blink_timer,
hide_cursor,
app_view_id,
extra_plugin_paths,
});
for w in info.tabs.workspaces {
let window_tab =
Rc::new(WindowTabData::new(cx, Arc::new(w), common.clone()));
window_tabs.update(|window_tabs| {
window_tabs.push_back((cx.create_rw_signal(0), window_tab));
});
}
if window_tabs.with_untracked(|window_tabs| window_tabs.is_empty()) {
let window_tab = Rc::new(WindowTabData::new(
cx,
Arc::new(LapceWorkspace::default()),
common.clone(),
));
window_tabs.update(|window_tabs| {
window_tabs.push_back((cx.create_rw_signal(0), window_tab));
});
}
let active = cx.create_rw_signal(active);
let position = cx.create_rw_signal(info.pos);
let window_data = Self {
window_id,
scope: cx,
window_tabs,
num_window_tabs,
active,
position,
root_view_id,
window_scale,
app_command,
config,
ime_enabled: cx.create_rw_signal(false),
common,
};
{
let window_data = window_data.clone();
window_data.common.window_command.listen(move |cmd| {
window_data.run_window_command(cmd);
});
}
{
cx.create_effect(move |_| {
let active = active.get();
let tab = window_tabs
.with(|tabs| tabs.get(active).map(|(_, tab)| tab.clone()));
if let Some(tab) = tab {
tab.common
.internal_command
.send(InternalCommand::ResetBlinkCursor);
}
})
}
window_data
}
pub fn reload_config(&self) {
let config = LapceConfig::load(
&LapceWorkspace::default(),
&[],
&self.common.extra_plugin_paths,
);
self.config.set(Arc::new(config));
let window_tabs = self.window_tabs.get_untracked();
for (_, window_tab) in window_tabs {
window_tab.reload_config();
}
}
pub fn run_window_command(&self, cmd: WindowCommand) {
match cmd {
WindowCommand::SetWorkspace { workspace } => {
let db: Arc<LapceDb> = use_context().unwrap();
if let Err(err) = db.update_recent_workspace(&workspace) {
tracing::error!("{:?}", err);
}
let active = self.active.get_untracked();
self.window_tabs.with_untracked(|window_tabs| {
if !window_tabs.is_empty() {
let active = window_tabs.len().saturating_sub(1).min(active);
if let Err(err) =
db.insert_window_tab(window_tabs[active].1.clone())
{
tracing::error!("{:?}", err);
}
}
});
let window_tab = Rc::new(WindowTabData::new(
self.scope,
Arc::new(workspace),
self.common.clone(),
));
self.window_tabs.update(|window_tabs| {
if window_tabs.is_empty() {
window_tabs
.push_back((self.scope.create_rw_signal(0), window_tab));
} else {
let active = window_tabs.len().saturating_sub(1).min(active);
let (_, old_window_tab) = window_tabs.set(
active,
(self.scope.create_rw_signal(0), window_tab),
);
old_window_tab.proxy.shutdown();
}
})
}
WindowCommand::NewWorkspaceTab { workspace, end } => {
let db: Arc<LapceDb> = use_context().unwrap();
if let Err(err) = db.update_recent_workspace(&workspace) {
tracing::error!("{:?}", err);
}
let window_tab = Rc::new(WindowTabData::new(
self.scope,
Arc::new(workspace),
self.common.clone(),
));
let active = self.active.get_untracked();
let active = self
.window_tabs
.try_update(|tabs| {
if end || tabs.is_empty() {
tabs.push_back((
self.scope.create_rw_signal(0),
window_tab,
));
tabs.len() - 1
} else {
let index = tabs.len().min(active + 1);
tabs.insert(
index,
(self.scope.create_rw_signal(0), window_tab),
);
index
}
})
.unwrap();
self.active.set(active);
}
WindowCommand::CloseWorkspaceTab { index } => {
let active = self.active.get_untracked();
let index = index.unwrap_or(active);
self.window_tabs.update(|window_tabs| {
if window_tabs.len() < 2 {
return;
}
if index < window_tabs.len() {
let (_, old_window_tab) = window_tabs.remove(index);
old_window_tab.proxy.shutdown();
let db: Arc<LapceDb> = use_context().unwrap();
if let Err(err) = db.save_window_tab(old_window_tab) {
tracing::error!("{:?}", err);
}
}
});
let tabs_len = self.window_tabs.with_untracked(|tabs| tabs.len());
if active > index && active > 0 {
self.active.set(active - 1);
} else if active >= tabs_len.saturating_sub(1) {
self.active.set(tabs_len.saturating_sub(1));
}
}
WindowCommand::NextWorkspaceTab => {
let active = self.active.get_untracked();
let tabs_len = self.window_tabs.with_untracked(|tabs| tabs.len());
if tabs_len > 1 {
let active = if active >= tabs_len - 1 {
0
} else {
active + 1
};
self.active.set(active);
}
}
WindowCommand::PreviousWorkspaceTab => {
let active = self.active.get_untracked();
let tabs_len = self.window_tabs.with_untracked(|tabs| tabs.len());
if tabs_len > 1 {
let active = if active == 0 {
tabs_len - 1
} else {
active - 1
};
self.active.set(active);
}
}
WindowCommand::NewWindow => {
self.app_command
.send(AppCommand::NewWindow { folder: None });
}
WindowCommand::CloseWindow => {
self.app_command
.send(AppCommand::CloseWindow(self.window_id));
}
}
self.app_command.send(AppCommand::SaveApp);
}
pub fn key_down<'a>(&self, event: impl Into<EventRef<'a>> + Copy) -> bool {
let active = self.active.get_untracked();
let window_tab = self.window_tabs.with_untracked(|window_tabs| {
window_tabs
.get(active)
.or_else(|| window_tabs.last())
.cloned()
});
if let Some((_, window_tab)) = window_tab {
window_tab.key_down(event)
} else {
false
}
}
pub fn info(&self) -> WindowInfo {
let workspaces: Vec<LapceWorkspace> = self
.window_tabs
.get_untracked()
.iter()
.map(|(_, t)| (*t.workspace).clone())
.collect();
WindowInfo {
size: self.common.size.get_untracked(),
pos: self.position.get_untracked(),
maximised: false,
tabs: TabsInfo {
active_tab: self.active.get_untracked(),
workspaces,
},
}
}
pub fn active_window_tab(&self) -> Option<Rc<WindowTabData>> {
let window_tabs = self.window_tabs.get_untracked();
let active = self
.active
.get_untracked()
.min(window_tabs.len().saturating_sub(1));
window_tabs.get(active).map(|(_, tab)| tab.clone())
}
pub fn move_tab(&self, from_index: usize, to_index: usize) {
if from_index == to_index {
return;
}
let to_index = if from_index < to_index {
to_index - 1
} else {
to_index
};
self.window_tabs.update(|tabs| {
let tab = tabs.remove(from_index);
tabs.insert(to_index, tab);
});
self.active.set(to_index);
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/keymap.rs | lapce-app/src/keymap.rs | use std::{rc::Rc, sync::Arc};
use floem::{
View,
event::{Event, EventListener},
reactive::{
Memo, ReadSignal, RwSignal, Scope, SignalGet, SignalUpdate, SignalWith,
create_effect, create_memo, create_rw_signal,
},
style::CursorStyle,
views::{
Decorators, container, dyn_stack, label, scroll, stack, text, virtual_stack,
},
};
use lapce_core::mode::Modes;
use crate::{
command::LapceCommand,
config::{LapceConfig, color::LapceColor},
keypress::{
KeyPressData,
keymap::{KeyMap, KeyMapPress},
},
main_split::Editors,
text_input::TextInputBuilder,
window_tab::CommonData,
};
#[derive(Clone)]
pub struct KeymapPicker {
cmd: RwSignal<Option<LapceCommand>>,
keymap: RwSignal<Option<KeyMap>>,
keys: RwSignal<Vec<(KeyMapPress, bool)>>,
}
pub fn keymap_view(editors: Editors, common: Rc<CommonData>) -> impl View {
let config = common.config;
let keypress = common.keypress;
let ui_line_height_memo = common.ui_line_height;
let ui_line_height = move || ui_line_height_memo.get() * 1.2;
let modal = create_memo(move |_| config.get().core.modal);
let picker = KeymapPicker {
cmd: create_rw_signal(None),
keymap: create_rw_signal(None),
keys: create_rw_signal(Vec::new()),
};
let cx = Scope::current();
let text_input_view = TextInputBuilder::new().build(cx, editors, common.clone());
let doc = text_input_view.doc_signal();
let items = move || {
let doc = doc.get();
let pattern = doc.buffer.with(|b| b.to_string().to_lowercase());
let keypress = keypress.get();
let mut items = keypress
.commands_with_keymap
.iter()
.filter_map(|keymap| {
let cmd = keypress.commands.get(&keymap.command).cloned()?;
let cmd_name_contains_pattern =
cmd.kind.str().replace('_', " ").contains(&pattern);
let cmd_desc_contains_pattern = cmd
.kind
.desc()
.map(|desc| desc.to_lowercase().contains(&pattern))
.unwrap_or(false);
let shortcut_contains_pattern = keymap
.key
.iter()
.any(|k| k.label().trim().to_lowercase().contains(&pattern));
let when_contains_pattern = keymap
.when
.as_ref()
.map(|when| when.to_lowercase().contains(&pattern))
.unwrap_or(false);
if cmd_name_contains_pattern
|| cmd_desc_contains_pattern
|| shortcut_contains_pattern
|| when_contains_pattern
{
Some((cmd, Some(keymap.clone())))
} else {
None
}
})
.collect::<im::Vector<(LapceCommand, Option<KeyMap>)>>();
items.extend(keypress.commands_without_keymap.iter().filter_map(|cmd| {
let match_pattern = cmd.kind.str().replace('_', " ").contains(&pattern)
|| cmd
.kind
.desc()
.map(|desc| desc.to_lowercase().contains(&pattern))
.unwrap_or(false);
if !match_pattern {
return None;
}
Some((cmd.clone(), None))
}));
items
.into_iter()
.enumerate()
.collect::<im::Vector<(usize, (LapceCommand, Option<KeyMap>))>>()
};
let view_fn =
move |(i, (cmd, keymap)): (usize, (LapceCommand, Option<KeyMap>))| {
let local_keymap = keymap.clone();
let local_cmd = cmd.clone();
stack((
container(
text(
cmd.kind
.desc()
.map(|desc| desc.to_string())
.unwrap_or_else(|| cmd.kind.str().replace('_', " ")),
)
.style(|s| {
s.text_ellipsis()
.absolute()
.items_center()
.min_width(0.0)
.padding_horiz(10.0)
.size_pct(100.0, 100.0)
}),
)
.style(move |s| {
s.height_pct(100.0)
.min_width(0.0)
.flex_basis(0.0)
.flex_grow(1.0)
.border_right(1.0)
.border_color(config.get().color(LapceColor::LAPCE_BORDER))
}),
{
let keymap = keymap.clone();
dyn_stack(
move || {
keymap
.as_ref()
.map(|keymap| {
keymap
.key
.iter()
.map(|key| key.label())
.filter(|l| !l.is_empty())
.collect::<Vec<String>>()
})
.unwrap_or_default()
},
|k| k.clone(),
move |key| {
text(key.clone()).style(move |s| {
s.padding_horiz(5.0)
.padding_vert(1.0)
.margin_right(5.0)
.border(1.0)
.border_radius(3.0)
.border_color(
config.get().color(LapceColor::LAPCE_BORDER),
)
})
},
)
.style(move |s| {
s.items_center()
.padding_horiz(10.0)
.min_width(200.0)
.height_pct(100.0)
.border_right(1.0)
.border_color(
config.get().color(LapceColor::LAPCE_BORDER),
)
})
},
{
let keymap = keymap.clone();
let bits = [
(Modes::INSERT, "Insert"),
(Modes::NORMAL, "Normal"),
(Modes::VISUAL, "Visual"),
(Modes::TERMINAL, "Terminal"),
];
let modes = keymap
.as_ref()
.map(|keymap| {
bits.iter()
.filter_map(|(bit, mode)| {
if keymap.modes.contains(*bit) {
Some(mode.to_string())
} else {
None
}
})
.collect::<Vec<String>>()
})
.unwrap_or_default();
dyn_stack(
move || modes.clone(),
|m| m.clone(),
move |mode| {
text(mode.clone()).style(move |s| {
s.padding_horiz(5.0)
.padding_vert(1.0)
.margin_right(5.0)
.border(1.0)
.border_radius(3.0)
.border_color(
config.get().color(LapceColor::LAPCE_BORDER),
)
})
},
)
.style(move |s| {
s.items_center()
.padding_horiz(10.0)
.min_width(200.0)
.height_pct(100.0)
.border_right(1.0)
.border_color(
config.get().color(LapceColor::LAPCE_BORDER),
)
.apply_if(!modal.get(), |s| s.hide())
})
},
container(
text(
keymap
.as_ref()
.and_then(|keymap| keymap.when.clone())
.unwrap_or_default(),
)
.style(|s| {
s.text_ellipsis()
.absolute()
.items_center()
.min_width(0.0)
.padding_horiz(10.0)
.size_pct(100.0, 100.0)
}),
)
.style(move |s| {
s.height_pct(100.0)
.min_width(0.0)
.flex_basis(0.0)
.flex_grow(1.0)
}),
))
.on_click_stop(move |_| {
let keymap = if let Some(keymap) = local_keymap.clone() {
keymap
} else {
KeyMap {
command: local_cmd.kind.str().to_string(),
key: Vec::new(),
modes: Modes::empty(),
when: None,
}
};
picker.keymap.set(Some(keymap));
picker.cmd.set(Some(local_cmd.clone()));
picker.keys.update(|keys| {
keys.clear();
});
})
.style(move |s| {
let config = config.get();
s.items_center()
.height(ui_line_height() as f32)
.width_pct(100.0)
.apply_if(i % 2 > 0, |s| {
s.background(config.color(LapceColor::EDITOR_CURRENT_LINE))
})
.border_bottom(1.0)
.border_color(config.color(LapceColor::LAPCE_BORDER))
})
};
stack((
container(
text_input_view
.placeholder(|| "Search Key Bindings".to_string())
.keyboard_navigable()
.request_focus(|| {})
.style(move |s| {
s.width_pct(100.0)
.border_radius(6.0)
.border(1.0)
.border_color(config.get().color(LapceColor::LAPCE_BORDER))
}),
)
.style(|s| s.padding_bottom(10.0).width_pct(100.0)),
stack((
container(text("Command").style(move |s| {
s.text_ellipsis().padding_horiz(10.0).min_width(0.0)
}))
.style(move |s| {
s.items_center()
.height_pct(100.0)
.min_width(0.0)
.flex_basis(0.0)
.flex_grow(1.0)
.border_right(1.0)
.border_color(config.get().color(LapceColor::LAPCE_BORDER))
}),
text("Key Binding").style(move |s| {
s.width(200.0)
.items_center()
.padding_horiz(10.0)
.height_pct(100.0)
.border_right(1.0)
.border_color(config.get().color(LapceColor::LAPCE_BORDER))
}),
text("Modes").style(move |s| {
s.width(200.0)
.items_center()
.padding_horiz(10.0)
.height_pct(100.0)
.border_right(1.0)
.border_color(config.get().color(LapceColor::LAPCE_BORDER))
.apply_if(!modal.get(), |s| s.hide())
}),
container(text("When").style(move |s| {
s.text_ellipsis().padding_horiz(10.0).min_width(0.0)
}))
.style(move |s| {
s.items_center()
.height_pct(100.0)
.min_width(0.0)
.flex_basis(0.0)
.flex_grow(1.0)
}),
))
.style(move |s| {
let config = config.get();
s.font_bold()
.height(ui_line_height() as f32)
.width_pct(100.0)
.border_top(1.0)
.border_bottom(1.0)
.border_color(config.color(LapceColor::LAPCE_BORDER))
.background(config.color(LapceColor::EDITOR_CURRENT_LINE))
}),
container(
scroll(
virtual_stack(
items,
|(i, (cmd, keymap)): &(
usize,
(LapceCommand, Option<KeyMap>),
)| { (*i, cmd.kind.str(), keymap.clone()) },
view_fn,
)
.item_size_fixed(ui_line_height)
.style(|s| s.flex_col().width_pct(100.0)),
)
.style(|s| s.absolute().size_pct(100.0, 100.0)),
)
.style(|s| s.width_pct(100.0).flex_basis(0.0).flex_grow(1.0)),
keyboard_picker_view(picker, common.ui_line_height, config),
))
.style(|s| {
s.absolute()
.size_pct(100.0, 100.0)
.flex_col()
.padding_top(20.0)
.padding_left(20.0)
.padding_right(20.0)
})
}
fn keyboard_picker_view(
picker: KeymapPicker,
ui_line_height: Memo<f64>,
config: ReadSignal<Arc<LapceConfig>>,
) -> impl View {
let picker_cmd = picker.cmd;
let view = container(
stack((
label(move || {
picker_cmd.with(|cmd| {
cmd.as_ref()
.map(|cmd| {
cmd.kind
.desc()
.map(|desc| desc.to_string())
.unwrap_or_else(|| cmd.kind.str().replace('_', " "))
})
.unwrap_or_default()
})
}),
dyn_stack(
move || {
picker
.keys
.get()
.iter()
.map(|(key, _)| key.label())
.filter(|l| !l.is_empty())
.enumerate()
.collect::<Vec<(usize, String)>>()
},
|(i, k)| (*i, k.clone()),
move |(_, key)| {
text(key.clone()).style(move |s| {
s.padding_horiz(5.0)
.padding_vert(1.0)
.margin_right(5.0)
.height(ui_line_height.get() as f32)
.border(1.0)
.border_radius(6.0)
.border_color(
config.get().color(LapceColor::LAPCE_BORDER),
)
})
},
)
.style(move |s| {
let config = config.get();
s.items_center()
.justify_center()
.width_pct(100.0)
.margin_top(20.0)
.height((ui_line_height.get() as f32) * 1.2)
.border(1.0)
.border_radius(6.0)
.border_color(config.color(LapceColor::LAPCE_BORDER))
.background(config.color(LapceColor::EDITOR_BACKGROUND))
}),
stack((
text("Save")
.style(move |s| {
let config = config.get();
s.width(100.0)
.justify_center()
.padding_vert(8.0)
.border(1.0)
.border_radius(6.0)
.border_color(config.color(LapceColor::LAPCE_BORDER))
.hover(|s| {
s.cursor(CursorStyle::Pointer).background(
config
.color(LapceColor::PANEL_HOVERED_BACKGROUND),
)
})
.active(|s| {
s.background(config.color(
LapceColor::PANEL_HOVERED_ACTIVE_BACKGROUND,
))
})
})
.on_click_stop(move |_| {
let keymap = picker.keymap.get_untracked();
if let Some(keymap) = keymap {
let keys = picker.keys.get_untracked();
picker.keymap.set(None);
KeyPressData::update_file(
&keymap,
&keys
.iter()
.map(|(key, _)| key.clone())
.collect::<Vec<KeyMapPress>>(),
);
}
}),
text("Cancel")
.style(move |s| {
let config = config.get();
s.margin_left(20.0)
.width(100.0)
.justify_center()
.padding_vert(8.0)
.border(1.0)
.border_radius(6.0)
.border_color(config.color(LapceColor::LAPCE_BORDER))
.hover(|s| {
s.cursor(CursorStyle::Pointer).background(
config
.color(LapceColor::PANEL_HOVERED_BACKGROUND),
)
})
.active(|s| {
s.background(config.color(
LapceColor::PANEL_HOVERED_ACTIVE_BACKGROUND,
))
})
})
.on_click_stop(move |_| {
picker.keymap.set(None);
}),
))
.style(move |s| {
let config = config.get();
s.items_center()
.justify_center()
.width_pct(100.0)
.margin_top(20.0)
.border_color(config.color(LapceColor::LAPCE_BORDER))
}),
))
.on_event_stop(EventListener::PointerDown, |_| {})
.style(move |s| {
let config = config.get();
s.items_center()
.flex_col()
.padding(20.0)
.width(400.0)
.border(1.0)
.border_radius(6.0)
.border_color(config.color(LapceColor::LAPCE_BORDER))
.background(config.color(LapceColor::PANEL_BACKGROUND))
}),
)
.keyboard_navigable()
.on_event_stop(EventListener::KeyDown, move |event| {
if let Event::KeyDown(key_event) = event {
if let Some(keypress) = KeyPressData::keypress(key_event) {
if let Some(keypress) = keypress.keymap_press() {
picker.keys.update(|keys| {
if let Some((last_key, last_key_confirmed)) = keys.last() {
if !*last_key_confirmed && last_key.is_modifiers() {
keys.pop();
}
}
if keys.len() == 2 {
keys.clear();
}
keys.push((keypress, false));
})
}
}
}
})
.on_event_stop(EventListener::KeyUp, move |event| {
if let Event::KeyUp(_key_event) = event {
picker.keys.update(|keys| {
if let Some((_last_key, last_key_confirmed)) = keys.last_mut() {
*last_key_confirmed = true;
}
})
}
})
.style(move |s| {
s.absolute()
.size_pct(100.0, 100.0)
.items_center()
.justify_center()
.apply_if(picker.keymap.with(|keymap| keymap.is_none()), |s| s.hide())
})
.debug_name("keyboard picker");
let id = view.id();
create_effect(move |_| {
if picker.keymap.with(|k| k.is_some()) {
id.request_focus();
}
});
view
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/wave.rs | lapce-app/src/wave.rs | use floem::{
Renderer, View, ViewId,
peniko::kurbo::{BezPath, Point, Size},
style::TextColor,
};
pub fn wave_box() -> WaveBox {
WaveBox { id: ViewId::new() }
}
pub struct WaveBox {
id: ViewId,
}
impl View for WaveBox {
fn id(&self) -> ViewId {
self.id
}
fn paint(&mut self, cx: &mut floem::context::PaintCx) {
if let Some(color) = self.id.get_combined_style().get(TextColor) {
let layout = self.id.get_layout().unwrap_or_default();
let size = layout.size;
let size = Size::new(size.width as f64, size.height as f64);
let radius = 4.0;
let origin = Point::new(0.0, size.height);
let mut path = BezPath::new();
path.move_to(origin);
let mut x = 0.0;
let mut direction = -1.0;
while x < size.width {
let point = origin + (x, 0.0);
let p1 = point + (radius * 1.5, -radius * direction);
let p2 = point + (radius * 3.0, 0.0);
path.quad_to(p1, p2);
x += radius * 3.0;
direction *= -1.0;
}
{
let origin = Point::new(0.0, 0.0);
path.line_to(origin + (x, 0.0));
direction *= -1.0;
while x >= 0.0 {
x -= radius * 3.0;
let point = origin + (x, 0.0);
let p1 = point + (radius * 1.5, -radius * direction);
let p2 = point;
path.quad_to(p1, p2);
direction *= -1.0;
}
}
path.line_to(origin);
cx.fill(&path, color, 0.0);
}
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/tracing.rs | lapce-app/src/tracing.rs | // Re-export `tracing` crate under own name to not collide and as convenient import
pub use tracing::{
self, Instrument, Level as TraceLevel, event as trace, instrument,
};
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/alert.rs | lapce-app/src/alert.rs | use std::{
fmt,
rc::Rc,
sync::{Arc, atomic::AtomicU64},
};
use floem::{
View,
event::EventListener,
reactive::{ReadSignal, RwSignal, Scope, SignalGet, SignalUpdate},
style::CursorStyle,
views::{Decorators, container, dyn_stack, label, stack, svg},
};
use crate::{
config::{LapceConfig, color::LapceColor, icon::LapceIcons},
window_tab::CommonData,
};
#[derive(Clone)]
pub struct AlertButton {
pub text: String,
pub action: Rc<dyn Fn()>,
}
impl fmt::Debug for AlertButton {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut s = f.debug_struct("AlertButton");
s.field("text", &self.text);
s.finish()
}
}
#[derive(Clone)]
pub struct AlertBoxData {
pub active: RwSignal<bool>,
pub title: RwSignal<String>,
pub msg: RwSignal<String>,
pub buttons: RwSignal<Vec<AlertButton>>,
pub config: ReadSignal<Arc<LapceConfig>>,
}
impl AlertBoxData {
pub fn new(cx: Scope, common: Rc<CommonData>) -> Self {
Self {
active: cx.create_rw_signal(false),
title: cx.create_rw_signal("".to_string()),
msg: cx.create_rw_signal("".to_string()),
buttons: cx.create_rw_signal(Vec::new()),
config: common.config,
}
}
}
pub fn alert_box(alert_data: AlertBoxData) -> impl View {
let config = alert_data.config;
let active = alert_data.active;
let title = alert_data.title;
let msg = alert_data.msg;
let buttons = alert_data.buttons;
let button_id = AtomicU64::new(0);
container({
container({
stack((
svg(move || config.get().ui_svg(LapceIcons::WARNING)).style(
move |s| {
s.size(50.0, 50.0)
.color(config.get().color(LapceColor::LAPCE_WARN))
},
),
label(move || title.get()).style(move |s| {
s.margin_top(20.0)
.width_pct(100.0)
.font_bold()
.font_size((config.get().ui.font_size() + 1) as f32)
}),
label(move || msg.get())
.style(move |s| s.width_pct(100.0).margin_top(10.0)),
dyn_stack(
move || buttons.get(),
move |_button| {
button_id.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
},
move |button| {
label(move || button.text.clone())
.on_click_stop(move |_| {
(button.action)();
})
.style(move |s| {
let config = config.get();
s.margin_top(10.0)
.width_pct(100.0)
.justify_center()
.font_size((config.ui.font_size() + 1) as f32)
.line_height(1.6)
.border(1.0)
.border_radius(6.0)
.border_color(
config.color(LapceColor::LAPCE_BORDER),
)
.hover(|s| {
s.cursor(CursorStyle::Pointer).background(
config.color(
LapceColor::PANEL_HOVERED_BACKGROUND,
),
)
})
.active(|s| {
s.background(config.color(
LapceColor::PANEL_HOVERED_ACTIVE_BACKGROUND,
))
})
})
},
)
.style(|s| s.flex_col().width_pct(100.0).margin_top(10.0)),
label(|| "Cancel".to_string())
.on_click_stop(move |_| {
active.set(false);
})
.style(move |s| {
let config = config.get();
s.margin_top(20.0)
.width_pct(100.0)
.justify_center()
.font_size((config.ui.font_size() + 1) as f32)
.line_height(1.5)
.border(1.0)
.border_radius(6.0)
.border_color(config.color(LapceColor::LAPCE_BORDER))
.hover(|s| {
s.cursor(CursorStyle::Pointer).background(
config
.color(LapceColor::PANEL_HOVERED_BACKGROUND),
)
})
.active(|s| {
s.background(config.color(
LapceColor::PANEL_HOVERED_ACTIVE_BACKGROUND,
))
})
}),
))
.style(|s| s.flex_col().items_center().width_pct(100.0))
})
.on_event_stop(EventListener::PointerDown, |_| {})
.style(move |s| {
let config = config.get();
s.padding(20.0)
.width(250.0)
.border(1.0)
.border_radius(6.0)
.border_color(config.color(LapceColor::LAPCE_BORDER))
.color(config.color(LapceColor::EDITOR_FOREGROUND))
.background(config.color(LapceColor::PANEL_BACKGROUND))
})
})
.on_event_stop(EventListener::PointerDown, move |_| {})
.style(move |s| {
s.absolute()
.size_pct(100.0, 100.0)
.items_center()
.justify_center()
.apply_if(!active.get(), |s| s.hide())
.background(
config
.get()
.color(LapceColor::LAPCE_DROPDOWN_SHADOW)
.multiply_alpha(0.5),
)
})
.debug_name("Alert Box")
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/window_tab.rs | lapce-app/src/window_tab.rs | use std::{
collections::{BTreeMap, HashSet},
env,
path::{Path, PathBuf},
rc::Rc,
sync::{
Arc,
mpsc::{Sender, channel},
},
time::Instant,
};
use alacritty_terminal::vte::ansi::Handler;
use floem::{
ViewId,
action::{TimerToken, open_file, remove_overlay},
ext_event::{create_ext_action, create_signal_from_channel},
file::FileDialogOptions,
keyboard::Modifiers,
kurbo::Size,
peniko::kurbo::{Point, Rect, Vec2},
prelude::SignalTrack,
reactive::{
Memo, ReadSignal, RwSignal, Scope, SignalGet, SignalUpdate, SignalWith,
WriteSignal, use_context,
},
text::{Attrs, AttrsList, FamilyOwned, LineHeightValue, TextLayout},
views::editor::core::buffer::rope_text::RopeText,
};
use im::HashMap;
use indexmap::IndexMap;
use itertools::Itertools;
use lapce_core::{
command::FocusCommand, cursor::CursorAffinity, directory::Directory, meta,
mode::Mode, register::Register,
};
use lapce_rpc::{
RpcError,
core::CoreNotification,
dap_types::{ConfigSource, RunDebugConfig},
file::{Naming, PathObject},
plugin::PluginId,
proxy::{ProxyResponse, ProxyRpcHandler, ProxyStatus},
source_control::FileDiff,
terminal::TermId,
};
use lsp_types::{
CodeActionOrCommand, CodeLens, Diagnostic, ProgressParams, ProgressToken,
ShowMessageParams,
};
use serde_json::Value;
use tracing::{Level, debug, error, event};
use crate::{
about::AboutData,
alert::{AlertBoxData, AlertButton},
code_action::{CodeActionData, CodeActionStatus},
command::{
CommandExecuted, CommandKind, InternalCommand, LapceCommand,
LapceWorkbenchCommand, WindowCommand,
},
completion::{CompletionData, CompletionStatus},
config::LapceConfig,
db::LapceDb,
debug::{DapData, LapceBreakpoint, RunDebugMode, RunDebugProcess},
doc::DocContent,
editor::location::{EditorLocation, EditorPosition},
editor_tab::EditorTabChild,
file_explorer::data::FileExplorerData,
find::Find,
global_search::GlobalSearchData,
hover::HoverData,
id::WindowTabId,
inline_completion::InlineCompletionData,
keypress::{EventRef, KeyPressData, KeyPressFocus, condition::Condition},
listener::Listener,
lsp::path_from_url,
main_split::{MainSplitData, SplitData, SplitDirection, SplitMoveDirection},
palette::{DEFAULT_RUN_TOML, PaletteData, PaletteStatus, kind::PaletteKind},
panel::{
call_hierarchy_view::{CallHierarchyData, CallHierarchyItemData},
data::{PanelData, PanelSection, default_panel_order},
kind::PanelKind,
position::PanelContainerPosition,
},
plugin::PluginData,
proxy::{ProxyData, new_proxy},
rename::RenameData,
source_control::SourceControlData,
terminal::{
event::{TermEvent, TermNotification, terminal_update_process},
panel::TerminalPanelData,
},
tracing::*,
window::WindowCommonData,
workspace::{LapceWorkspace, LapceWorkspaceType, WorkspaceInfo},
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Focus {
Workbench,
Palette,
CodeAction,
Rename,
AboutPopup,
Panel(PanelKind),
}
#[derive(Clone)]
pub enum DragContent {
Panel(PanelKind),
EditorTab(EditorTabChild),
}
impl DragContent {
pub fn is_panel(&self) -> bool {
matches!(self, DragContent::Panel(_))
}
}
#[derive(Clone)]
pub struct WorkProgress {
pub token: ProgressToken,
pub title: String,
pub message: Option<String>,
pub percentage: Option<u32>,
}
#[derive(Clone)]
pub struct CommonData {
pub workspace: Arc<LapceWorkspace>,
pub scope: Scope,
pub focus: RwSignal<Focus>,
pub keypress: RwSignal<KeyPressData>,
pub completion: RwSignal<CompletionData>,
pub inline_completion: RwSignal<InlineCompletionData>,
pub hover: HoverData,
pub register: RwSignal<Register>,
pub find: Find,
pub workbench_size: RwSignal<Size>,
pub window_origin: RwSignal<Point>,
pub internal_command: Listener<InternalCommand>,
pub lapce_command: Listener<LapceCommand>,
pub workbench_command: Listener<LapceWorkbenchCommand>,
pub term_tx: Sender<(TermId, TermEvent)>,
pub term_notification_tx: Sender<TermNotification>,
pub proxy: ProxyRpcHandler,
pub view_id: RwSignal<ViewId>,
pub ui_line_height: Memo<f64>,
pub dragging: RwSignal<Option<DragContent>>,
pub config: ReadSignal<Arc<LapceConfig>>,
pub proxy_status: RwSignal<Option<ProxyStatus>>,
pub mouse_hover_timer: RwSignal<TimerToken>,
pub breakpoints: RwSignal<BTreeMap<PathBuf, BTreeMap<usize, LapceBreakpoint>>>,
// the current focused view which will receive keyboard events
pub keyboard_focus: RwSignal<Option<ViewId>>,
pub window_common: Rc<WindowCommonData>,
}
impl std::fmt::Debug for CommonData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CommonData")
.field("workspace", &self.workspace)
.finish()
}
}
#[derive(Clone)]
pub struct WindowTabData {
pub scope: Scope,
pub window_tab_id: WindowTabId,
pub workspace: Arc<LapceWorkspace>,
pub palette: PaletteData,
pub main_split: MainSplitData,
pub file_explorer: FileExplorerData,
pub panel: PanelData,
pub terminal: TerminalPanelData,
pub plugin: PluginData,
pub code_action: RwSignal<CodeActionData>,
pub code_lens: RwSignal<Option<ViewId>>,
pub source_control: SourceControlData,
pub rename: RenameData,
pub global_search: GlobalSearchData,
pub call_hierarchy_data: CallHierarchyData,
pub about_data: AboutData,
pub alert_data: AlertBoxData,
pub layout_rect: RwSignal<Rect>,
pub title_height: RwSignal<f64>,
pub status_height: RwSignal<f64>,
pub proxy: ProxyData,
pub set_config: WriteSignal<Arc<LapceConfig>>,
pub update_in_progress: RwSignal<bool>,
pub progresses: RwSignal<IndexMap<ProgressToken, WorkProgress>>,
pub messages: RwSignal<Vec<(String, ShowMessageParams)>>,
pub common: Rc<CommonData>,
}
impl std::fmt::Debug for WindowTabData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WindowTabData")
.field("window_tab_id", &self.window_tab_id)
.finish()
}
}
impl KeyPressFocus for WindowTabData {
fn get_mode(&self) -> Mode {
Mode::Normal
}
fn check_condition(&self, condition: Condition) -> bool {
match condition {
Condition::PanelFocus => {
matches!(self.common.focus.get_untracked(), Focus::Panel(_))
}
Condition::SourceControlFocus => {
self.common.focus.get_untracked()
== Focus::Panel(PanelKind::SourceControl)
}
_ => false,
}
}
fn run_command(
&self,
command: &LapceCommand,
_count: Option<usize>,
_mods: Modifiers,
) -> CommandExecuted {
match &command.kind {
CommandKind::Workbench(cmd) => {
self.run_workbench_command(cmd.clone(), None);
}
CommandKind::Focus(cmd) => {
if self.common.focus.get_untracked() == Focus::Workbench {
match cmd {
FocusCommand::SplitClose => {
self.main_split.editor_tab_child_close_active();
}
FocusCommand::SplitVertical => {
self.main_split.split_active(SplitDirection::Vertical);
}
FocusCommand::SplitHorizontal => {
self.main_split.split_active(SplitDirection::Horizontal);
}
FocusCommand::SplitRight => {
self.main_split
.split_move_active(SplitMoveDirection::Right);
}
FocusCommand::SplitLeft => {
self.main_split
.split_move_active(SplitMoveDirection::Left);
}
FocusCommand::SplitUp => {
self.main_split
.split_move_active(SplitMoveDirection::Up);
}
FocusCommand::SplitDown => {
self.main_split
.split_move_active(SplitMoveDirection::Down);
}
FocusCommand::SplitExchange => {
self.main_split.split_exchange_active();
}
_ => {
return CommandExecuted::No;
}
}
}
}
_ => {
return CommandExecuted::No;
}
}
CommandExecuted::Yes
}
fn receive_char(&self, _c: &str) {}
}
impl WindowTabData {
#[allow(clippy::too_many_arguments)]
pub fn new(
cx: Scope,
workspace: Arc<LapceWorkspace>,
window_common: Rc<WindowCommonData>,
) -> Self {
let cx = cx.create_child();
let db: Arc<LapceDb> = use_context().unwrap();
let disabled_volts = db.get_disabled_volts().unwrap_or_default();
let workspace_disabled_volts = db
.get_workspace_disabled_volts(&workspace)
.unwrap_or_default();
let mut all_disabled_volts = disabled_volts.clone();
all_disabled_volts.extend(workspace_disabled_volts.clone());
let workspace_info = if workspace.path.is_some() {
db.get_workspace_info(&workspace).ok()
} else {
let mut info = db.get_workspace_info(&workspace).ok();
if let Some(info) = info.as_mut() {
info.split.children.clear();
}
info
};
let config = LapceConfig::load(
&workspace,
&all_disabled_volts,
&window_common.extra_plugin_paths,
);
let lapce_command = Listener::new_empty(cx);
let workbench_command = Listener::new_empty(cx);
let internal_command = Listener::new_empty(cx);
let keypress = cx.create_rw_signal(KeyPressData::new(cx, &config));
let proxy_status = cx.create_rw_signal(None);
let (term_tx, term_rx) = channel();
let (term_notification_tx, term_notification_rx) = channel();
{
let term_notification_tx = term_notification_tx.clone();
std::thread::Builder::new()
.name("terminal update process".to_owned())
.spawn(move || {
terminal_update_process(term_rx, term_notification_tx);
})
.unwrap();
}
let proxy = new_proxy(
workspace.clone(),
all_disabled_volts,
window_common.extra_plugin_paths.as_ref().clone(),
config.plugins.clone(),
term_tx.clone(),
);
let (config, set_config) = cx.create_signal(Arc::new(config));
let focus = cx.create_rw_signal(Focus::Workbench);
let completion = cx.create_rw_signal(CompletionData::new(cx, config));
let inline_completion = cx.create_rw_signal(InlineCompletionData::new(cx));
let hover = HoverData::new(cx);
let register = cx.create_rw_signal(Register::default());
let view_id = cx.create_rw_signal(ViewId::new());
let find = Find::new(cx);
let ui_line_height = cx.create_memo(move |_| {
let config = config.get();
let mut text_layout = TextLayout::new();
let family: Vec<FamilyOwned> =
FamilyOwned::parse_list(&config.ui.font_family).collect();
let attrs = Attrs::new()
.family(&family)
.font_size(config.ui.font_size() as f32)
.line_height(LineHeightValue::Normal(1.8));
let attrs_list = AttrsList::new(attrs);
text_layout.set_text("W", attrs_list, None);
text_layout.size().height
});
let common = Rc::new(CommonData {
workspace: workspace.clone(),
scope: cx,
keypress,
focus,
completion,
inline_completion,
hover,
register,
find,
internal_command,
lapce_command,
workbench_command,
term_tx,
term_notification_tx,
proxy: proxy.proxy_rpc.clone(),
view_id,
ui_line_height,
dragging: cx.create_rw_signal(None),
workbench_size: cx.create_rw_signal(Size::ZERO),
config,
proxy_status,
mouse_hover_timer: cx.create_rw_signal(TimerToken::INVALID),
window_origin: cx.create_rw_signal(Point::ZERO),
breakpoints: cx.create_rw_signal(BTreeMap::new()),
keyboard_focus: cx.create_rw_signal(None),
window_common: window_common.clone(),
});
let main_split = MainSplitData::new(cx, common.clone());
let code_action =
cx.create_rw_signal(CodeActionData::new(cx, common.clone()));
let source_control =
SourceControlData::new(cx, main_split.editors, common.clone());
let file_explorer =
FileExplorerData::new(cx, main_split.editors, common.clone());
if let Some(info) = workspace_info.as_ref() {
let root_split = main_split.root_split;
info.split.to_data(main_split.clone(), None, root_split);
} else {
let root_split = main_split.root_split;
let root_split_data = {
let cx = cx.create_child();
let root_split_data = SplitData {
scope: cx,
parent_split: None,
split_id: root_split,
children: Vec::new(),
direction: SplitDirection::Horizontal,
window_origin: Point::ZERO,
layout_rect: Rect::ZERO,
};
cx.create_rw_signal(root_split_data)
};
main_split.splits.update(|splits| {
splits.insert(root_split, root_split_data);
});
}
let palette = PaletteData::new(
cx,
workspace.clone(),
main_split.clone(),
keypress.read_only(),
source_control.clone(),
common.clone(),
);
let title_height = cx.create_rw_signal(0.0);
let status_height = cx.create_rw_signal(0.0);
let panel_available_size = cx.create_memo(move |_| {
let title_height = title_height.get();
let status_height = status_height.get();
let num_window_tabs = window_common.num_window_tabs.get();
let window_size = window_common.size.get();
Size::new(
window_size.width,
window_size.height
- title_height
- status_height
- if num_window_tabs > 1 {
window_common.window_tab_header_height.get()
} else {
0.0
},
)
});
let panel = workspace_info
.as_ref()
.map(|i| {
let panel_order = db
.get_panel_orders()
.unwrap_or_else(|_| default_panel_order());
PanelData {
panels: cx.create_rw_signal(panel_order),
styles: cx.create_rw_signal(i.panel.styles.clone()),
size: cx.create_rw_signal(i.panel.size.clone()),
available_size: panel_available_size,
sections: cx.create_rw_signal(
i.panel
.sections
.iter()
.map(|(key, value)| (*key, cx.create_rw_signal(*value)))
.collect(),
),
common: common.clone(),
}
})
.unwrap_or_else(|| {
let panel_order = db
.get_panel_orders()
.unwrap_or_else(|_| default_panel_order());
PanelData::new(
cx,
panel_order,
panel_available_size,
im::HashMap::new(),
common.clone(),
)
});
let terminal = TerminalPanelData::new(
workspace.clone(),
common.config.get_untracked().terminal.get_default_profile(),
common.clone(),
main_split.clone(),
);
if let Some(workspace_info) = workspace_info.as_ref() {
terminal.debug.breakpoints.set(
workspace_info
.breakpoints
.clone()
.into_iter()
.map(|(path, breakpoints)| {
(
path,
breakpoints
.into_iter()
.map(|b| (b.line, b))
.collect::<BTreeMap<usize, LapceBreakpoint>>(),
)
})
.collect(),
);
}
let rename = RenameData::new(cx, main_split.editors, common.clone());
let global_search = GlobalSearchData::new(cx, main_split.clone());
let plugin = PluginData::new(
cx,
HashSet::from_iter(disabled_volts),
HashSet::from_iter(workspace_disabled_volts),
main_split.editors,
common.clone(),
proxy.core_rpc.clone(),
);
{
let notification = create_signal_from_channel(term_notification_rx);
let terminal = terminal.clone();
cx.create_effect(move |_| {
notification.with(|notification| {
if let Some(notification) = notification.as_ref() {
match notification {
TermNotification::SetTitle { term_id, title } => {
terminal.set_title(term_id, title);
}
TermNotification::RequestPaint => {
view_id.get_untracked().request_paint();
}
}
}
});
});
}
let about_data = AboutData::new(cx, common.focus);
let alert_data = AlertBoxData::new(cx, common.clone());
let window_tab_data = Self {
scope: cx,
window_tab_id: WindowTabId::next(),
workspace,
palette,
main_split,
terminal,
panel,
file_explorer,
code_action,
code_lens: cx.create_rw_signal(None),
source_control,
plugin,
rename,
global_search,
call_hierarchy_data: CallHierarchyData {
root: cx.create_rw_signal(None),
common: common.clone(),
scroll_to_line: cx.create_rw_signal(None),
},
about_data,
alert_data,
layout_rect: cx.create_rw_signal(Rect::ZERO),
title_height,
status_height,
proxy,
set_config,
update_in_progress: cx.create_rw_signal(false),
progresses: cx.create_rw_signal(IndexMap::new()),
messages: cx.create_rw_signal(Vec::new()),
common,
};
{
let focus = window_tab_data.common.focus;
let active_editor = window_tab_data.main_split.active_editor;
let rename_active = window_tab_data.rename.active;
let internal_command = window_tab_data.common.internal_command;
cx.create_effect(move |_| {
let focus = focus.get();
active_editor.track();
internal_command.send(InternalCommand::ResetBlinkCursor);
if focus != Focus::Rename && rename_active.get_untracked() {
rename_active.set(false);
}
});
}
{
let window_tab_data = window_tab_data.clone();
window_tab_data.common.lapce_command.listen(move |cmd| {
window_tab_data.run_lapce_command(cmd);
});
}
{
let window_tab_data = window_tab_data.clone();
window_tab_data.common.workbench_command.listen(move |cmd| {
window_tab_data.run_workbench_command(cmd, None);
});
}
{
let window_tab_data = window_tab_data.clone();
let internal_command = window_tab_data.common.internal_command;
internal_command.listen(move |cmd| {
window_tab_data.run_internal_command(cmd);
});
}
{
let window_tab_data = window_tab_data.clone();
let notification = window_tab_data.proxy.notification;
cx.create_effect(move |_| {
notification.with(|rpc| {
if let Some(rpc) = rpc.as_ref() {
window_tab_data.handle_core_notification(rpc);
}
});
});
}
window_tab_data
}
pub fn reload_config(&self) {
let db: Arc<LapceDb> = use_context().unwrap();
let disabled_volts = db.get_disabled_volts().unwrap_or_default();
let workspace_disabled_volts = db
.get_workspace_disabled_volts(&self.workspace)
.unwrap_or_default();
let mut all_disabled_volts = disabled_volts;
all_disabled_volts.extend(workspace_disabled_volts);
let config = LapceConfig::load(
&self.workspace,
&all_disabled_volts,
&self.common.window_common.extra_plugin_paths,
);
self.common.keypress.update(|keypress| {
keypress.update_keymaps(&config);
});
let mut change_plugins = Vec::new();
for (key, configs) in self.common.config.get_untracked().plugins.iter() {
if config
.plugins
.get(key)
.map(|x| x != configs)
.unwrap_or_default()
{
change_plugins.push(key.clone());
}
}
self.set_config.set(Arc::new(config.clone()));
if !change_plugins.is_empty() {
self.common
.proxy
.update_plugin_configs(config.plugins.clone());
if config.core.auto_reload_plugin {
let mut plugin_metas: HashMap<
String,
lapce_rpc::plugin::VoltMetadata,
> = self
.plugin
.installed
.get_untracked()
.values()
.map(|x| {
let meta = x.meta.get_untracked();
(meta.name.clone(), meta)
})
.collect();
for name in change_plugins {
if let Some(meta) = plugin_metas.remove(&name) {
self.common.proxy.reload_volt(meta);
} else {
tracing::error!("not found volt metadata of {}", name);
}
}
}
}
}
pub fn run_lapce_command(&self, cmd: LapceCommand) {
match cmd.kind {
CommandKind::Workbench(command) => {
self.run_workbench_command(command, cmd.data);
}
CommandKind::Scroll(_)
| CommandKind::Focus(_)
| CommandKind::Edit(_)
| CommandKind::Move(_) => {
if self.palette.status.get_untracked() != PaletteStatus::Inactive {
self.palette.run_command(&cmd, None, Modifiers::empty());
} else if let Some(editor_data) =
self.main_split.active_editor.get_untracked()
{
editor_data.run_command(&cmd, None, Modifiers::empty());
} else {
// TODO: dispatch to current focused view?
}
}
CommandKind::MotionMode(_) => {}
CommandKind::MultiSelection(_) => {}
}
}
pub fn run_workbench_command(
&self,
cmd: LapceWorkbenchCommand,
data: Option<Value>,
) {
use LapceWorkbenchCommand::*;
match cmd {
// ==== Modal ====
EnableModal => {
let internal_command = self.common.internal_command;
internal_command.send(InternalCommand::SetModal { modal: true });
}
DisableModal => {
let internal_command = self.common.internal_command;
internal_command.send(InternalCommand::SetModal { modal: false });
}
// ==== Files / Folders ====
OpenFolder => {
if !self.workspace.kind.is_remote() {
let window_command = self.common.window_common.window_command;
let mut options = FileDialogOptions::new().title("Choose a folder").select_directories();
options = if let Some(parent) = self.workspace.path.as_ref().and_then(|x| x.parent()) {
options.force_starting_directory(parent)
} else {
options
};
open_file(options, move |file| {
if let Some(mut file) = file {
let workspace = LapceWorkspace {
kind: LapceWorkspaceType::Local,
path: Some(if let Some(path) = file.path.pop() {
path
} else {
tracing::error!("No path");
return;
}),
last_open: std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs(),
};
window_command
.send(WindowCommand::SetWorkspace { workspace });
}
});
}
}
CloseFolder => {
if !self.workspace.kind.is_remote() {
let window_command = self.common.window_common.window_command;
let workspace = LapceWorkspace {
kind: LapceWorkspaceType::Local,
path: None,
last_open: 0,
};
window_command.send(WindowCommand::SetWorkspace { workspace });
}
}
OpenFile => {
if !self.workspace.kind.is_remote() {
let internal_command = self.common.internal_command;
let options = FileDialogOptions::new().title("Choose a file");
open_file(options, move |file| {
if let Some(mut file) = file {
internal_command.send(InternalCommand::OpenFile {
path: if let Some(path) = file.path.pop() {
path
} else {
tracing::error!("No path");
return;
},
})
}
});
}
}
NewFile => {
self.main_split.new_file();
}
RevealActiveFileInFileExplorer => {
if let Some(editor_data) = self.main_split.active_editor.get() {
let doc = editor_data.doc();
let path = if let DocContent::File { path, .. } =
doc.content.get_untracked()
{
Some(path)
} else {
None
};
let Some(path) = path else { return };
let path = path.parent().unwrap_or(&path);
open_uri(path);
}
}
SaveAll => {
self.main_split.editors.with_editors_untracked(|editors| {
let mut paths = HashSet::new();
for (_, editor_data) in editors.iter() {
let doc = editor_data.doc();
let should_save = if let DocContent::File { path, .. } =
doc.content.get_untracked()
{
if paths.contains(&path) {
false
} else {
paths.insert(path.clone());
true
}
} else {
false
};
if should_save {
editor_data.save(true, || {});
}
}
});
}
// ==== Configuration / Info Files and Folders ====
OpenSettings => {
self.main_split.open_settings();
}
OpenSettingsFile => {
if let Some(path) = LapceConfig::settings_file() {
self.main_split.jump_to_location(
EditorLocation {
path,
position: None,
scroll_offset: None,
ignore_unconfirmed: false,
same_editor_tab: false,
},
None,
);
}
}
OpenSettingsDirectory => {
if let Some(dir) = Directory::config_directory() {
open_uri(&dir);
}
}
OpenThemeColorSettings => {
self.main_split.open_theme_color_settings();
}
OpenKeyboardShortcuts => {
self.main_split.open_keymap();
}
OpenKeyboardShortcutsFile => {
if let Some(path) = LapceConfig::keymaps_file() {
self.main_split.jump_to_location(
EditorLocation {
path,
position: None,
scroll_offset: None,
ignore_unconfirmed: false,
same_editor_tab: false,
},
None,
);
}
}
OpenLogFile => {
if let Some(dir) = Directory::logs_directory() {
self.open_paths(&[PathObject::from_path(
dir.join(format!(
"lapce.{}.log",
chrono::prelude::Local::now().format("%Y-%m-%d")
)),
false,
)])
}
}
OpenLogsDirectory => {
if let Some(dir) = Directory::logs_directory() {
open_uri(&dir);
}
}
OpenProxyDirectory => {
if let Some(dir) = Directory::proxy_directory() {
open_uri(&dir);
}
}
OpenThemesDirectory => {
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | true |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/text_area.rs | lapce-app/src/text_area.rs | use floem::{
View,
peniko::kurbo::Rect,
reactive::{
SignalGet, SignalUpdate, SignalWith, create_effect, create_rw_signal,
},
text::{Attrs, AttrsList, LineHeightValue, TextLayout},
views::{Decorators, container, label, rich_text, scroll, stack},
};
use lapce_core::buffer::rope_text::RopeText;
use crate::{config::color::LapceColor, editor::EditorData};
pub fn text_area(
editor: EditorData,
is_active: impl Fn() -> bool + 'static,
) -> impl View {
let config = editor.common.config;
let doc = editor.doc_signal();
let cursor = editor.cursor();
let text_area_rect = create_rw_signal(Rect::ZERO);
let text_layout = create_rw_signal(TextLayout::new());
let line_height = 1.2;
create_effect(move |_| {
let config = config.get();
let font_size = config.ui.font_size();
let font_family = config.ui.font_family();
let color = config.color(LapceColor::EDITOR_FOREGROUND);
let attrs = Attrs::new()
.color(color)
.family(&font_family)
.font_size(font_size as f32)
.line_height(LineHeightValue::Normal(line_height));
let attrs_list = AttrsList::new(attrs);
let doc = doc.get();
let text = doc.buffer.with(|b| b.to_string());
text_layout.update(|text_layout| {
text_layout.set_text(&text, attrs_list, None);
});
});
create_effect(move |last_rev| {
let rev = doc.with(|doc| doc.rev());
if last_rev == Some(rev) {
return rev;
}
let config = config.get_untracked();
let font_size = config.ui.font_size();
let font_family = config.ui.font_family();
let color = config.color(LapceColor::EDITOR_FOREGROUND);
let attrs = Attrs::new()
.color(color)
.family(&font_family)
.font_size(font_size as f32)
.line_height(LineHeightValue::Normal(1.2));
let attrs_list = AttrsList::new(attrs);
let doc = doc.get();
let text = doc.buffer.with(|b| b.to_string());
text_layout.update(|text_layout| {
text_layout.set_text(&text, attrs_list, None);
});
rev
});
create_effect(move |last_width| {
let width = text_area_rect.get().width();
if last_width == Some(width) {
return width;
}
text_layout.update(|text_layout| {
text_layout.set_size(width as f32, f32::MAX);
});
width
});
let cursor_pos = move || {
let offset = cursor.with(|c| c.offset());
let (line, col) = doc
.with_untracked(|doc| doc.buffer.with(|b| b.offset_to_line_col(offset)));
text_layout.with(|text_layout| {
let pos = text_layout.line_col_position(line, col);
pos.point - (0.0, pos.glyph_ascent)
})
};
container(
scroll(
stack((
rich_text(move || text_layout.get())
.on_resize(move |rect| {
text_area_rect.set(rect);
})
.style(|s| s.width_pct(100.0)),
label(|| " ".to_string()).style(move |s| {
let cursor_pos = cursor_pos();
s.absolute()
.line_height(line_height)
.margin_left(cursor_pos.x as f32 - 1.0)
.margin_top(cursor_pos.y as f32)
.border_left(2.0)
.border_color(config.get().color(LapceColor::EDITOR_CARET))
.apply_if(!is_active(), |s| s.hide())
}),
))
.style(|s| s.width_pct(100.0).padding(6.0)),
)
.style(|s| s.absolute().size_pct(100.0, 100.0)),
)
.style(move |s| {
let config = config.get();
s.border(1.0)
.border_radius(6.0)
.border_color(config.color(LapceColor::LAPCE_BORDER))
.background(config.color(LapceColor::EDITOR_BACKGROUND))
})
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/main_split.rs | lapce-app/src/main_split.rs | use std::{
collections::HashMap,
path::{Path, PathBuf},
rc::Rc,
};
use floem::{
action::save_as,
ext_event::create_ext_action,
file::{FileDialogOptions, FileInfo},
keyboard::Modifiers,
peniko::kurbo::{Point, Rect, Vec2},
reactive::{Memo, RwSignal, Scope, SignalGet, SignalUpdate, SignalWith},
views::editor::id::EditorId,
};
use itertools::Itertools;
use lapce_core::{
buffer::rope_text::RopeText, command::FocusCommand, cursor::Cursor,
rope_text_pos::RopeTextPosition, selection::Selection, syntax::Syntax,
};
use lapce_rpc::{
buffer::BufferId,
core::FileChanged,
plugin::{PluginId, VoltID},
proxy::ProxyResponse,
};
use lapce_xi_rope::{Rope, spans::SpansBuilder};
use lsp_types::{
CodeAction, CodeActionOrCommand, DiagnosticSeverity, DocumentChangeOperation,
DocumentChanges, OneOf, Position, TextEdit, Url, WorkspaceEdit,
};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tracing::{Level, event};
use crate::{
alert::AlertButton,
code_lens::CodeLensData,
command::InternalCommand,
doc::{DiagnosticData, Doc, DocContent, DocHistory, EditorDiagnostic},
editor::{
EditorData,
diff::DiffEditorData,
location::{EditorLocation, EditorPosition},
},
editor_tab::{
EditorTabChild, EditorTabChildSource, EditorTabData, EditorTabInfo,
},
id::{
DiffEditorId, EditorTabId, KeymapId, SettingsId, SplitId,
ThemeColorSettingsId, VoltViewId,
},
keypress::{EventRef, KeyPressData, KeyPressHandle},
panel::implementation_view::ReferencesRoot,
window_tab::{CommonData, Focus, WindowTabData},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum SplitDirection {
Vertical,
Horizontal,
}
#[derive(Clone, Copy, Debug)]
pub enum SplitMoveDirection {
Up,
Down,
Right,
Left,
}
impl SplitMoveDirection {
pub fn direction(&self) -> SplitDirection {
match self {
SplitMoveDirection::Up | SplitMoveDirection::Down => {
SplitDirection::Horizontal
}
SplitMoveDirection::Left | SplitMoveDirection::Right => {
SplitDirection::Vertical
}
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SplitContent {
EditorTab(EditorTabId),
Split(SplitId),
}
impl SplitContent {
pub fn id(&self) -> u64 {
match self {
SplitContent::EditorTab(id) => id.to_raw(),
SplitContent::Split(id) => id.to_raw(),
}
}
pub fn content_info(&self, data: &WindowTabData) -> SplitContentInfo {
match &self {
SplitContent::EditorTab(editor_tab_id) => {
let editor_tab_data = data
.main_split
.editor_tabs
.get_untracked()
.get(editor_tab_id)
.cloned()
.unwrap();
SplitContentInfo::EditorTab(
editor_tab_data.get_untracked().tab_info(data),
)
}
SplitContent::Split(split_id) => {
let split_data = data
.main_split
.splits
.get_untracked()
.get(split_id)
.cloned()
.unwrap();
SplitContentInfo::Split(split_data.get_untracked().split_info(data))
}
}
}
}
#[derive(Clone)]
pub struct SplitData {
pub scope: Scope,
pub parent_split: Option<SplitId>,
pub split_id: SplitId,
pub children: Vec<(RwSignal<f64>, SplitContent)>,
pub direction: SplitDirection,
pub window_origin: Point,
pub layout_rect: Rect,
}
#[derive(Clone, Serialize, Deserialize)]
pub struct SplitInfo {
pub children: Vec<SplitContentInfo>,
pub direction: SplitDirection,
}
impl SplitInfo {
pub fn to_data(
&self,
data: MainSplitData,
parent_split: Option<SplitId>,
split_id: SplitId,
) -> RwSignal<SplitData> {
let split_data = {
let cx = data.scope.create_child();
let split_data = SplitData {
scope: cx,
split_id,
direction: self.direction,
parent_split,
children: self
.children
.iter()
.map(|child| {
(
cx.create_rw_signal(1.0),
child.to_data(data.clone(), split_id),
)
})
.collect(),
window_origin: Point::ZERO,
layout_rect: Rect::ZERO,
};
cx.create_rw_signal(split_data)
};
data.splits.update(|splits| {
splits.insert(split_id, split_data);
});
split_data
}
}
#[derive(Clone, Serialize, Deserialize)]
pub enum SplitContentInfo {
EditorTab(EditorTabInfo),
Split(SplitInfo),
}
impl SplitContentInfo {
pub fn to_data(
&self,
data: MainSplitData,
parent_split: SplitId,
) -> SplitContent {
match &self {
SplitContentInfo::EditorTab(tab_info) => {
let tab_data = tab_info.to_data(data, parent_split);
SplitContent::EditorTab(
tab_data.with_untracked(|tab_data| tab_data.editor_tab_id),
)
}
SplitContentInfo::Split(split_info) => {
let split_id = SplitId::next();
split_info.to_data(data, Some(parent_split), split_id);
SplitContent::Split(split_id)
}
}
}
}
impl SplitData {
pub fn split_info(&self, data: &WindowTabData) -> SplitInfo {
SplitInfo {
direction: self.direction,
children: self
.children
.iter()
.map(|(_, child)| child.content_info(data))
.collect(),
}
}
pub fn editor_tab_index(&self, editor_tab_id: EditorTabId) -> Option<usize> {
self.children
.iter()
.position(|(_, c)| c == &SplitContent::EditorTab(editor_tab_id))
}
pub fn content_index(&self, content: &SplitContent) -> Option<usize> {
self.children.iter().position(|(_, c)| c == content)
}
}
/// All the editors in a main split
#[derive(Clone, Copy)]
pub struct Editors(pub RwSignal<im::HashMap<EditorId, EditorData>>);
impl Editors {
fn new(cx: Scope) -> Self {
Self(cx.create_rw_signal(im::HashMap::new()))
}
/// Add an editor to the editors.
/// Returns the id of the editor.
pub fn insert(&self, editor: EditorData) -> EditorId {
let id = editor.id();
self.0.update(|editors| {
if editors.insert(id, editor).is_some() {
event!(Level::WARN, "Inserted EditorId that already exists");
}
});
id
}
pub fn insert_with_id(&self, id: EditorId, editor: EditorData) {
self.0.update(|editors| {
editors.insert(id, editor);
});
}
pub fn new_local(&self, cx: Scope, common: Rc<CommonData>) -> EditorId {
let editor = EditorData::new_local(cx, *self, common);
self.insert(editor)
}
/// Equivalent to [`Self::new_local`], but immediately gets the created editor.
pub fn make_local(&self, cx: Scope, common: Rc<CommonData>) -> EditorData {
let id = self.new_local(cx, common);
self.editor_untracked(id).unwrap()
}
pub fn new_from_doc(
&self,
cx: Scope,
doc: Rc<Doc>,
editor_tab_id: Option<EditorTabId>,
diff_editor_id: Option<(EditorTabId, DiffEditorId)>,
confirmed: Option<RwSignal<bool>>,
common: Rc<CommonData>,
) -> EditorId {
let editor = EditorData::new_doc(
cx,
doc,
editor_tab_id,
diff_editor_id,
confirmed,
common,
);
self.insert(editor)
}
/// Equivalent to [`Self::new_editor_doc`], but immediately gets the created editor.
pub fn make_from_doc(
&self,
cx: Scope,
doc: Rc<Doc>,
editor_tab_id: Option<EditorTabId>,
diff_editor_id: Option<(EditorTabId, DiffEditorId)>,
confirmed: Option<RwSignal<bool>>,
common: Rc<CommonData>,
) -> EditorData {
let id = self.new_from_doc(
cx,
doc,
editor_tab_id,
diff_editor_id,
confirmed,
common,
);
self.editor_untracked(id).unwrap()
}
/// Copy an existing editor which is inserted into [`Editors`]
pub fn copy(
&self,
editor_id: EditorId,
cx: Scope,
editor_tab_id: Option<EditorTabId>,
diff_editor_id: Option<(EditorTabId, DiffEditorId)>,
confirmed: Option<RwSignal<bool>>,
) -> Option<EditorId> {
let editor = self.editor_untracked(editor_id)?;
let new_editor = editor.copy(cx, editor_tab_id, diff_editor_id, confirmed);
Some(self.insert(new_editor))
}
pub fn make_copy(
&self,
editor_id: EditorId,
cx: Scope,
editor_tab_id: Option<EditorTabId>,
diff_editor_id: Option<(EditorTabId, DiffEditorId)>,
confirmed: Option<RwSignal<bool>>,
) -> Option<EditorData> {
let editor_id =
self.copy(editor_id, cx, editor_tab_id, diff_editor_id, confirmed)?;
self.editor_untracked(editor_id)
}
pub fn remove(&self, id: EditorId) -> Option<EditorData> {
self.0.try_update(|editors| editors.remove(&id)).unwrap()
}
pub fn get_editor_id_by_path(&self, path: &Path) -> Option<EditorId> {
self.0.with_untracked(|x| {
for (id, data) in x {
if data.doc().content.with_untracked(|x| {
if let Some(doc_path) = x.path() {
doc_path == path
} else {
false
}
}) {
return Some(*id);
}
}
None
})
}
pub fn contains_untracked(&self, id: EditorId) -> bool {
self.0.with_untracked(|editors| editors.contains_key(&id))
}
/// Get the editor (tracking the signal)
pub fn editor(&self, id: EditorId) -> Option<EditorData> {
self.0.with(|editors| editors.get(&id).cloned())
}
/// Get the editor (not tracking the signal)
pub fn editor_untracked(&self, id: EditorId) -> Option<EditorData> {
self.0.with_untracked(|editors| editors.get(&id).cloned())
}
pub fn with_editors<O>(
&self,
f: impl FnOnce(&im::HashMap<EditorId, EditorData>) -> O,
) -> O {
self.0.with(f)
}
pub fn with_editors_untracked<O>(
&self,
f: impl FnOnce(&im::HashMap<EditorId, EditorData>) -> O,
) -> O {
self.0.with_untracked(f)
}
}
#[derive(Clone)]
pub struct MainSplitData {
pub scope: Scope,
pub root_split: SplitId,
pub active_editor_tab: RwSignal<Option<EditorTabId>>,
pub splits: RwSignal<im::HashMap<SplitId, RwSignal<SplitData>>>,
pub editor_tabs: RwSignal<im::HashMap<EditorTabId, RwSignal<EditorTabData>>>,
pub editors: Editors,
pub diff_editors: RwSignal<im::HashMap<DiffEditorId, DiffEditorData>>,
pub docs: RwSignal<im::HashMap<PathBuf, Rc<Doc>>>,
pub scratch_docs: RwSignal<im::HashMap<String, Rc<Doc>>>,
pub diagnostics: RwSignal<im::HashMap<PathBuf, DiagnosticData>>,
pub references: RwSignal<ReferencesRoot>,
pub implementations: RwSignal<crate::panel::implementation_view::ReferencesRoot>,
pub active_editor: Memo<Option<EditorData>>,
pub find_editor: EditorData,
pub replace_editor: EditorData,
pub locations: RwSignal<im::Vector<EditorLocation>>,
pub current_location: RwSignal<usize>,
pub width: RwSignal<f64>,
pub code_lens: RwSignal<CodeLensData>,
pub common: Rc<CommonData>,
}
impl std::fmt::Debug for MainSplitData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("MainSplitData")
.field("root_split", &self.root_split)
.finish()
}
}
impl MainSplitData {
pub fn new(cx: Scope, common: Rc<CommonData>) -> Self {
let splits = cx.create_rw_signal(im::HashMap::new());
let active_editor_tab = cx.create_rw_signal(None);
let editor_tabs: RwSignal<
im::HashMap<EditorTabId, RwSignal<EditorTabData>>,
> = cx.create_rw_signal(im::HashMap::new());
let editors = Editors::new(cx);
let diff_editors: RwSignal<im::HashMap<DiffEditorId, DiffEditorData>> =
cx.create_rw_signal(im::HashMap::new());
let docs: RwSignal<im::HashMap<PathBuf, Rc<Doc>>> =
cx.create_rw_signal(im::HashMap::new());
let scratch_docs = cx.create_rw_signal(im::HashMap::new());
let locations = cx.create_rw_signal(im::Vector::new());
let references = cx.create_rw_signal(ReferencesRoot::default());
let implementations = cx.create_rw_signal(
crate::panel::implementation_view::ReferencesRoot::default(),
);
let current_location = cx.create_rw_signal(0);
let diagnostics = cx.create_rw_signal(im::HashMap::new());
let find_editor = editors.make_local(cx, common.clone());
let replace_editor = editors.make_local(cx, common.clone());
let active_editor = cx.create_memo(move |_| -> Option<EditorData> {
let active_editor_tab = active_editor_tab.get()?;
let editor_tab = editor_tabs
.with(|editor_tabs| editor_tabs.get(&active_editor_tab).copied())?;
let (_, _, child) = editor_tab.with(|editor_tab| {
editor_tab.children.get(editor_tab.active).cloned()
})?;
let editor = match child {
EditorTabChild::Editor(editor_id) => editors.editor(editor_id)?,
EditorTabChild::DiffEditor(diff_editor_id) => {
let diff_editor = diff_editors.with(|diff_editors| {
diff_editors.get(&diff_editor_id).cloned()
})?;
if diff_editor.focus_right.get() {
diff_editor.right
} else {
diff_editor.left
}
}
_ => return None,
};
Some(editor)
});
{
let buffer = find_editor.doc().buffer;
let find = common.find.clone();
cx.create_effect(move |_| {
let content = buffer.with(|buffer| buffer.to_string());
find.set_find(&content);
});
}
Self {
scope: cx,
root_split: SplitId::next(),
splits,
active_editor_tab,
editor_tabs,
editors,
diff_editors,
docs,
scratch_docs,
active_editor,
find_editor,
replace_editor,
diagnostics,
locations,
current_location,
width: cx.create_rw_signal(0.0),
code_lens: cx.create_rw_signal(CodeLensData::new(common.clone())),
common,
references,
implementations,
}
}
pub fn key_down<'a>(
&self,
event: impl Into<EventRef<'a>>,
keypress: &KeyPressData,
) -> Option<KeyPressHandle> {
let active_editor_tab = self.active_editor_tab.get_untracked()?;
let editor_tab = self.editor_tabs.with_untracked(|editor_tabs| {
editor_tabs.get(&active_editor_tab).copied()
})?;
let (_, _, child) = editor_tab.with_untracked(|editor_tab| {
editor_tab.children.get(editor_tab.active).cloned()
})?;
match child {
EditorTabChild::Editor(editor_id) => {
let editor = self.editors.editor_untracked(editor_id)?;
let handle = keypress.key_down(event, &editor);
editor.get_code_actions();
Some(handle)
}
EditorTabChild::DiffEditor(diff_editor_id) => {
let diff_editor =
self.diff_editors.with_untracked(|diff_editors| {
diff_editors.get(&diff_editor_id).cloned()
})?;
let editor = if diff_editor.focus_right.get_untracked() {
&diff_editor.right
} else {
&diff_editor.left
};
let handle = keypress.key_down(event, editor);
editor.get_code_actions();
Some(handle)
}
EditorTabChild::Settings(_) => None,
EditorTabChild::ThemeColorSettings(_) => None,
EditorTabChild::Keymap(_) => None,
EditorTabChild::Volt(_, _) => None,
}
}
fn save_current_jump_location(&self) -> bool {
if let Some(editor) = self.active_editor.get_untracked() {
let (cursor, viewport) = (editor.cursor(), editor.viewport());
let path = editor
.doc()
.content
.with_untracked(|content| content.path().cloned());
if let Some(path) = path {
let offset = cursor.with_untracked(|c| c.offset());
let scroll_offset = viewport.get_untracked().origin().to_vec2();
return self.save_jump_location(path, offset, scroll_offset);
}
}
false
}
pub fn save_jump_location(
&self,
path: PathBuf,
offset: usize,
scroll_offset: Vec2,
) -> bool {
let mut locations = self.locations.get_untracked();
if let Some(last_location) = locations.last() {
if last_location.path == path
&& last_location.position == Some(EditorPosition::Offset(offset))
&& last_location.scroll_offset == Some(scroll_offset)
{
return false;
}
}
let location = EditorLocation {
path,
position: Some(EditorPosition::Offset(offset)),
scroll_offset: Some(scroll_offset),
ignore_unconfirmed: false,
same_editor_tab: false,
};
locations.push_back(location.clone());
let current_location = locations.len();
self.locations.set(locations);
self.current_location.set(current_location);
let active_editor_tab_id = self.active_editor_tab.get_untracked();
let editor_tabs = self.editor_tabs.get_untracked();
if let Some((locations, current_location)) = active_editor_tab_id
.and_then(|id| editor_tabs.get(&id))
.map(|editor_tab| {
editor_tab.with_untracked(|editor_tab| {
(editor_tab.locations, editor_tab.current_location)
})
})
{
let mut l = locations.get_untracked();
l.push_back(location);
let new_current_location = l.len();
locations.set(l);
current_location.set(new_current_location);
}
true
}
pub fn jump_to_location(
&self,
location: EditorLocation,
edits: Option<Vec<TextEdit>>,
) {
self.save_current_jump_location();
self.go_to_location(location, edits);
}
pub fn get_doc(
&self,
path: PathBuf,
unsaved: Option<String>,
) -> (Rc<Doc>, bool) {
let cx = self.scope;
let doc = self.docs.with_untracked(|docs| docs.get(&path).cloned());
if let Some(doc) = doc {
(doc, false)
} else {
let diagnostic_data = self.get_diagnostic_data(&path);
let doc = Doc::new(
cx,
path.clone(),
diagnostic_data,
self.editors,
self.common.clone(),
);
let doc = Rc::new(doc);
self.docs.update(|docs| {
docs.insert(path.clone(), doc.clone());
});
{
let doc = doc.clone();
let local_doc = doc.clone();
let send = create_ext_action(cx, move |result| {
if let Ok(ProxyResponse::NewBufferResponse {
content,
read_only,
}) = result
{
local_doc.init_content(Rope::from(content));
if read_only {
local_doc.content.update(|content| {
if let DocContent::File { read_only, .. } = content {
*read_only = true;
}
});
} else if let Some(unsaved) = unsaved {
local_doc.reload(Rope::from(unsaved), false);
}
}
});
self.common
.proxy
.new_buffer(doc.buffer_id, path, move |result| {
send(result);
});
}
doc.get_code_lens();
doc.get_folding_range();
doc.get_document_symbol();
(doc, true)
}
}
pub fn go_to_location(
&self,
location: EditorLocation,
edits: Option<Vec<TextEdit>>,
) {
if self.common.focus.get_untracked() != Focus::Workbench {
self.common.focus.set(Focus::Workbench);
}
let path = location.path.clone();
let (doc, new_doc) = self.get_doc(path.clone(), None);
let child = self.get_editor_tab_child(
EditorTabChildSource::Editor { path, doc },
location.ignore_unconfirmed,
location.same_editor_tab,
);
if let EditorTabChild::Editor(editor_id) = child {
if let Some(editor) = self.editors.editor_untracked(editor_id) {
editor.go_to_location(location, new_doc, edits);
}
}
}
pub fn open_file_changes(&self, path: PathBuf) {
let (right, _) = self.get_doc(path.clone(), None);
let left = Doc::new_history(
self.scope,
DocContent::History(DocHistory {
path: path.clone(),
version: "head".to_string(),
}),
self.editors,
self.common.clone(),
);
let left = Rc::new(left);
let send = {
let left = left.clone();
create_ext_action(self.scope, move |result| {
if let Ok(ProxyResponse::BufferHeadResponse { content, .. }) = result
{
left.init_content(Rope::from(content));
}
})
};
self.common.proxy.get_buffer_head(path, move |result| {
send(result);
});
self.get_editor_tab_child(
EditorTabChildSource::DiffEditor { left, right },
false,
false,
);
}
pub fn open_diff_files(&self, left_path: PathBuf, right_path: PathBuf) {
let [left, right] =
[left_path, right_path].map(|path| self.get_doc(path, None).0);
self.get_editor_tab_child(
EditorTabChildSource::DiffEditor { left, right },
false,
false,
);
}
fn new_editor_tab(
&self,
editor_tab_id: EditorTabId,
split_id: SplitId,
) -> RwSignal<EditorTabData> {
let editor_tab = {
let cx = self.scope.create_child();
let editor_tab = EditorTabData {
scope: cx,
split: split_id,
active: 0,
editor_tab_id,
children: vec![],
window_origin: Point::ZERO,
layout_rect: Rect::ZERO,
locations: cx.create_rw_signal(im::Vector::new()),
current_location: cx.create_rw_signal(0),
};
cx.create_rw_signal(editor_tab)
};
self.editor_tabs.update(|editor_tabs| {
editor_tabs.insert(editor_tab_id, editor_tab);
});
editor_tab
}
fn get_editor_tab_child(
&self,
source: EditorTabChildSource,
ignore_unconfirmed: bool,
same_editor_tab: bool,
) -> EditorTabChild {
let config = self.common.config.get_untracked();
let active_editor_tab_id = self.active_editor_tab.get_untracked();
let editor_tabs = self.editor_tabs.get_untracked();
let active_editor_tab = active_editor_tab_id
.and_then(|id| editor_tabs.get(&id))
.cloned();
let editors = self.editors;
let diff_editors = self.diff_editors.get_untracked();
let active_editor_tab = if let Some(editor_tab) = active_editor_tab {
editor_tab
} else if editor_tabs.is_empty() {
let editor_tab_id = EditorTabId::next();
let editor_tab = self.new_editor_tab(editor_tab_id, self.root_split);
let root_split = self.splits.with_untracked(|splits| {
splits.get(&self.root_split).cloned().unwrap()
});
root_split.update(|root_split| {
root_split.children = vec![(
root_split.scope.create_rw_signal(1.0),
SplitContent::EditorTab(editor_tab_id),
)];
});
self.active_editor_tab.set(Some(editor_tab_id));
editor_tab
} else {
let (editor_tab_id, editor_tab) = editor_tabs.iter().next().unwrap();
self.active_editor_tab.set(Some(*editor_tab_id));
*editor_tab
};
let is_same_diff_editor =
|diff_editor_id: &DiffEditorId, left: &Rc<Doc>, right: &Rc<Doc>| {
diff_editors
.get(diff_editor_id)
.map(|diff_editor| {
left.content.get_untracked()
== diff_editor.left.doc().content.get_untracked()
&& right.content.get_untracked()
== diff_editor.right.doc().content.get_untracked()
})
.unwrap_or(false)
};
let selected = if !config.editor.show_tab {
active_editor_tab.with_untracked(|editor_tab| {
for (i, (_, _, child)) in editor_tab.children.iter().enumerate() {
let can_be_selected = match child {
EditorTabChild::Editor(editor_id) => {
if let Some(editor) =
editors.editor_untracked(*editor_id)
{
let doc = editor.doc();
let same_path =
if let EditorTabChildSource::Editor {
path,
..
} = &source
{
doc.content.with_untracked(|content| {
content
.path()
.map(|p| p == path)
.unwrap_or(false)
})
} else {
false
};
same_path
|| doc.buffer.with_untracked(|b| b.is_pristine())
} else {
false
}
}
EditorTabChild::DiffEditor(diff_editor_id) => {
if let EditorTabChildSource::DiffEditor { left, right } =
&source
{
is_same_diff_editor(diff_editor_id, left, right)
|| diff_editors
.get(diff_editor_id)
.map(|diff_editor| {
diff_editor.left.doc().is_pristine()
&& diff_editor
.right
.doc()
.is_pristine()
})
.unwrap_or(false)
} else {
false
}
}
EditorTabChild::Settings(_) => true,
EditorTabChild::ThemeColorSettings(_) => true,
EditorTabChild::Keymap(_) => true,
EditorTabChild::Volt(_, _) => true,
};
if can_be_selected {
return Some(i);
}
}
None
})
} else {
match &source {
EditorTabChildSource::Editor { path, .. } => active_editor_tab
.with_untracked(|editor_tab| {
editor_tab
.get_editor(editors, path)
.map(|(i, _)| i)
.or_else(|| {
if ignore_unconfirmed {
None
} else {
editor_tab
.get_unconfirmed_editor_tab_child(
editors,
&diff_editors,
)
.map(|(i, _)| i)
}
})
}),
EditorTabChildSource::DiffEditor { left, right } => {
if let Some(index) =
active_editor_tab.with_untracked(|editor_tab| {
editor_tab.children.iter().position(|(_, _, child)| {
if let EditorTabChild::DiffEditor(diff_editor_id) =
child
{
is_same_diff_editor(diff_editor_id, left, right)
} else {
false
}
})
})
{
Some(index)
} else if ignore_unconfirmed {
None
} else {
active_editor_tab.with_untracked(|editor_tab| {
editor_tab
.get_unconfirmed_editor_tab_child(
editors,
&diff_editors,
)
.map(|(i, _)| i)
})
}
}
EditorTabChildSource::NewFileEditor => {
if ignore_unconfirmed {
None
} else {
active_editor_tab.with_untracked(|editor_tab| {
editor_tab
.get_unconfirmed_editor_tab_child(
editors,
&diff_editors,
)
.map(|(i, _)| i)
})
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | true |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/proxy.rs | lapce-app/src/proxy.rs | use std::{
collections::HashMap,
path::PathBuf,
process::Command,
sync::{Arc, mpsc::Sender},
};
use floem::{ext_event::create_signal_from_channel, reactive::ReadSignal};
use lapce_proxy::dispatch::Dispatcher;
use lapce_rpc::{
core::{CoreHandler, CoreNotification, CoreRpcHandler},
plugin::VoltID,
proxy::{ProxyRpcHandler, ProxyStatus},
terminal::TermId,
};
use tracing::error;
use self::{remote::start_remote, ssh::SshRemote};
use crate::{
terminal::event::TermEvent,
workspace::{LapceWorkspace, LapceWorkspaceType},
};
mod remote;
mod ssh;
#[cfg(windows)]
mod wsl;
pub struct Proxy {
pub tx: Sender<CoreNotification>,
pub term_tx: Sender<(TermId, TermEvent)>,
}
#[derive(Clone)]
pub struct ProxyData {
pub proxy_rpc: ProxyRpcHandler,
pub core_rpc: CoreRpcHandler,
pub notification: ReadSignal<Option<CoreNotification>>,
}
impl ProxyData {
pub fn shutdown(&self) {
self.proxy_rpc.shutdown();
self.core_rpc.shutdown();
}
}
pub fn new_proxy(
workspace: Arc<LapceWorkspace>,
disabled_volts: Vec<VoltID>,
extra_plugin_paths: Vec<PathBuf>,
plugin_configurations: HashMap<String, HashMap<String, serde_json::Value>>,
term_tx: Sender<(TermId, TermEvent)>,
) -> ProxyData {
let proxy_rpc = ProxyRpcHandler::new();
let core_rpc = CoreRpcHandler::new();
{
let core_rpc = core_rpc.clone();
let proxy_rpc = proxy_rpc.clone();
std::thread::Builder::new()
.name("ProxyRpcHandler".to_owned())
.spawn(move || {
core_rpc.notification(CoreNotification::ProxyStatus {
status: ProxyStatus::Connecting,
});
proxy_rpc.initialize(
workspace.path.clone(),
disabled_volts,
extra_plugin_paths,
plugin_configurations,
1,
1,
);
match &workspace.kind {
LapceWorkspaceType::Local => {
let core_rpc = core_rpc.clone();
let proxy_rpc = proxy_rpc.clone();
let mut dispatcher = Dispatcher::new(core_rpc, proxy_rpc);
let proxy_rpc = dispatcher.proxy_rpc.clone();
proxy_rpc.mainloop(&mut dispatcher);
}
LapceWorkspaceType::RemoteSSH(remote) => {
if let Err(e) = start_remote(
SshRemote {
ssh: remote.clone(),
},
core_rpc.clone(),
proxy_rpc.clone(),
) {
error!("Failed to start SSH remote: {e}");
}
}
#[cfg(windows)]
LapceWorkspaceType::RemoteWSL(remote) => {
if let Err(e) = start_remote(
wsl::WslRemote {
wsl: remote.clone(),
},
core_rpc.clone(),
proxy_rpc.clone(),
) {
error!("Failed to start SSH remote: {e}");
}
}
}
core_rpc.notification(CoreNotification::ProxyStatus {
status: ProxyStatus::Disconnected,
});
})
.unwrap();
}
let (tx, rx) = std::sync::mpsc::channel();
{
let core_rpc = core_rpc.clone();
std::thread::Builder::new()
.name("CoreRpcHandler".to_owned())
.spawn(move || {
let mut proxy = Proxy { tx, term_tx };
core_rpc.mainloop(&mut proxy);
core_rpc.notification(CoreNotification::ProxyStatus {
status: ProxyStatus::Disconnected,
});
})
.unwrap()
};
let notification = create_signal_from_channel(rx);
ProxyData {
proxy_rpc,
core_rpc,
notification,
}
}
impl CoreHandler for Proxy {
fn handle_notification(&mut self, rpc: lapce_rpc::core::CoreNotification) {
if let CoreNotification::UpdateTerminal { term_id, content } = &rpc {
if let Err(err) = self
.term_tx
.send((*term_id, TermEvent::UpdateContent(content.to_vec())))
{
tracing::error!("{:?}", err);
}
return;
}
if let Err(err) = self.tx.send(rpc) {
tracing::error!("{:?}", err);
}
}
fn handle_request(
&mut self,
_id: lapce_rpc::RequestId,
_rpc: lapce_rpc::core::CoreRequest,
) {
}
}
pub fn new_command(program: &str) -> Command {
#[allow(unused_mut)]
let mut cmd = Command::new(program);
#[cfg(target_os = "windows")]
use std::os::windows::process::CommandExt;
#[cfg(target_os = "windows")]
cmd.creation_flags(0x08000000);
cmd
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/inline_completion.rs | lapce-app/src/inline_completion.rs | use std::{borrow::Cow, ops::Range, path::PathBuf, str::FromStr};
use floem::reactive::{RwSignal, Scope, SignalGet, SignalUpdate, SignalWith, batch};
use lapce_core::{
buffer::{
Buffer,
rope_text::{RopeText, RopeTextRef},
},
rope_text_pos::RopeTextPosition,
selection::Selection,
};
use lsp_types::InsertTextFormat;
use crate::{config::LapceConfig, doc::Doc, editor::EditorData, snippet::Snippet};
// TODO: we could integrate completion lens with this, so it is considered at the same time
/// Redefinition of lsp types inline completion item with offset range
#[derive(Debug, Clone)]
pub struct InlineCompletionItem {
/// The text to replace the range with.
pub insert_text: String,
/// Text used to decide if this inline completion should be shown.
pub filter_text: Option<String>,
/// The range (of offsets) to replace
pub range: Option<Range<usize>>,
pub command: Option<lsp_types::Command>,
pub insert_text_format: Option<InsertTextFormat>,
}
impl InlineCompletionItem {
pub fn from_lsp(buffer: &Buffer, item: lsp_types::InlineCompletionItem) -> Self {
let range = item.range.map(|r| {
let start = buffer.offset_of_position(&r.start);
let end = buffer.offset_of_position(&r.end);
start..end
});
Self {
insert_text: item.insert_text,
filter_text: item.filter_text,
range,
command: item.command,
insert_text_format: item.insert_text_format,
}
}
pub fn apply(
&self,
editor: &EditorData,
start_offset: usize,
) -> anyhow::Result<()> {
let text_format = self
.insert_text_format
.unwrap_or(InsertTextFormat::PLAIN_TEXT);
let selection = if let Some(range) = &self.range {
Selection::region(range.start, range.end)
} else {
Selection::caret(start_offset)
};
match text_format {
InsertTextFormat::PLAIN_TEXT => editor.do_edit(
&selection,
&[(selection.clone(), self.insert_text.as_str())],
),
InsertTextFormat::SNIPPET => {
editor.completion_apply_snippet(
&self.insert_text,
&selection,
Vec::new(),
start_offset,
)?;
}
_ => {
// We don't know how to support this text format
}
}
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InlineCompletionStatus {
/// The inline completion is not active.
Inactive,
/// The inline completion is active and is waiting for the server to respond.
Started,
/// The inline completion is active and has received a response from the server.
Active,
}
#[derive(Clone)]
pub struct InlineCompletionData {
pub status: InlineCompletionStatus,
/// The active inline completion index in the list of completions.
pub active: RwSignal<usize>,
pub items: im::Vector<InlineCompletionItem>,
pub start_offset: usize,
pub path: PathBuf,
}
impl InlineCompletionData {
pub fn new(cx: Scope) -> Self {
Self {
status: InlineCompletionStatus::Inactive,
active: cx.create_rw_signal(0),
items: im::vector![],
start_offset: 0,
path: PathBuf::new(),
}
}
pub fn current_item(&self) -> Option<&InlineCompletionItem> {
let active = self.active.get_untracked();
self.items.get(active)
}
pub fn next(&mut self) {
if !self.items.is_empty() {
let next_index = (self.active.get_untracked() + 1) % self.items.len();
self.active.set(next_index);
}
}
pub fn previous(&mut self) {
if !self.items.is_empty() {
let prev_index = if self.active.get_untracked() == 0 {
self.items.len() - 1
} else {
self.active.get_untracked() - 1
};
self.active.set(prev_index);
}
}
pub fn cancel(&mut self) {
if self.status == InlineCompletionStatus::Inactive {
return;
}
self.items.clear();
self.status = InlineCompletionStatus::Inactive;
}
/// Set the items for the inline completion.
/// Sets `active` to `0` and `status` to `InlineCompletionStatus::Active`.
pub fn set_items(
&mut self,
items: im::Vector<InlineCompletionItem>,
start_offset: usize,
path: PathBuf,
) {
batch(|| {
self.items = items;
self.active.set(0);
self.status = InlineCompletionStatus::Active;
self.start_offset = start_offset;
self.path = path;
});
}
pub fn update_doc(&self, doc: &Doc, offset: usize) {
if self.status != InlineCompletionStatus::Active {
doc.clear_inline_completion();
return;
}
if self.items.is_empty() {
doc.clear_inline_completion();
return;
}
let active = self.active.get_untracked();
let active = if active >= self.items.len() {
self.active.set(0);
0
} else {
active
};
let item = &self.items[active];
let text = item.insert_text.clone();
// TODO: is range really meant to be used for this?
let offset = item.range.as_ref().map(|r| r.start).unwrap_or(offset);
let (line, col) = doc
.buffer
.with_untracked(|buffer| buffer.offset_to_line_col(offset));
doc.set_inline_completion(text, line, col);
}
pub fn update_inline_completion(
&self,
config: &LapceConfig,
doc: &Doc,
cursor_offset: usize,
) {
if !config.editor.enable_inline_completion {
doc.clear_inline_completion();
return;
}
let text = doc.buffer.with_untracked(|buffer| buffer.text().clone());
let text = RopeTextRef::new(&text);
let Some(item) = self.current_item() else {
// TODO(minor): should we cancel completion
return;
};
let completion = doc.inline_completion.with_untracked(|cur| {
let cur = cur.as_deref();
inline_completion_text(text, self.start_offset, cursor_offset, item, cur)
});
match completion {
ICompletionRes::Hide => {
doc.clear_inline_completion();
}
ICompletionRes::Unchanged => {}
ICompletionRes::Set(new, shift) => {
let offset = self.start_offset + shift;
let (line, col) = text.offset_to_line_col(offset);
doc.set_inline_completion(new, line, col);
}
}
}
}
enum ICompletionRes {
Hide,
Unchanged,
Set(String, usize),
}
/// Get the text of the inline completion item
fn inline_completion_text(
rope_text: impl RopeText,
start_offset: usize,
cursor_offset: usize,
item: &InlineCompletionItem,
current_completion: Option<&str>,
) -> ICompletionRes {
let text_format = item
.insert_text_format
.unwrap_or(InsertTextFormat::PLAIN_TEXT);
// TODO: is this check correct? I mostly copied it from completion lens
let cursor_prev_offset = rope_text.prev_code_boundary(cursor_offset);
if let Some(range) = &item.range {
let edit_start = range.start;
// If the start of the edit isn't where the cursor currently is, and is not at the start of
// the inline completion, then we ignore it.
if cursor_prev_offset != edit_start && start_offset != edit_start {
return ICompletionRes::Hide;
}
}
let text = match text_format {
InsertTextFormat::PLAIN_TEXT => Cow::Borrowed(&item.insert_text),
InsertTextFormat::SNIPPET => {
let Ok(snippet) = Snippet::from_str(&item.insert_text) else {
return ICompletionRes::Hide;
};
let text = snippet.text();
Cow::Owned(text)
}
_ => {
// We don't know how to support this text format
return ICompletionRes::Hide;
}
};
let range = start_offset..rope_text.offset_line_end(start_offset, true);
let prefix = rope_text.slice_to_cow(range);
// We strip the prefix of the current input from the label.
// So that, for example `p` with a completion of `println` will show `rintln`.
let Some(text) = text.strip_prefix(prefix.as_ref()) else {
return ICompletionRes::Hide;
};
if Some(text) == current_completion {
ICompletionRes::Unchanged
} else {
ICompletionRes::Set(text.to_string(), prefix.len())
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/code_action.rs | lapce-app/src/code_action.rs | use std::rc::Rc;
use floem::{
keyboard::Modifiers,
peniko::kurbo::Rect,
reactive::{RwSignal, Scope, SignalGet, SignalUpdate},
};
use lapce_core::{command::FocusCommand, mode::Mode, movement::Movement};
use lapce_rpc::plugin::PluginId;
use lsp_types::CodeActionOrCommand;
use crate::{
command::{CommandExecuted, CommandKind, InternalCommand},
keypress::{KeyPressFocus, condition::Condition},
window_tab::{CommonData, Focus},
};
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum CodeActionStatus {
Inactive,
Active,
}
#[derive(Clone, Debug, PartialEq)]
pub struct ScoredCodeActionItem {
pub item: CodeActionOrCommand,
pub plugin_id: PluginId,
pub score: i64,
pub indices: Vec<usize>,
}
impl ScoredCodeActionItem {
pub fn title(&self) -> &str {
match &self.item {
CodeActionOrCommand::Command(c) => &c.title,
CodeActionOrCommand::CodeAction(c) => &c.title,
}
}
}
#[derive(Clone, Debug)]
pub struct CodeActionData {
pub status: RwSignal<CodeActionStatus>,
pub active: RwSignal<usize>,
pub request_id: usize,
pub input_id: usize,
pub offset: usize,
pub items: im::Vector<ScoredCodeActionItem>,
pub filtered_items: im::Vector<ScoredCodeActionItem>,
pub layout_rect: Rect,
pub mouse_click: bool,
pub common: Rc<CommonData>,
}
impl KeyPressFocus for CodeActionData {
fn get_mode(&self) -> Mode {
Mode::Insert
}
fn check_condition(&self, condition: Condition) -> bool {
matches!(condition, Condition::ListFocus | Condition::ModalFocus)
}
fn run_command(
&self,
command: &crate::command::LapceCommand,
_count: Option<usize>,
_mods: Modifiers,
) -> crate::command::CommandExecuted {
match &command.kind {
CommandKind::Workbench(_) => {}
CommandKind::Edit(_) => {}
CommandKind::Move(_) => {}
CommandKind::Scroll(_) => {}
CommandKind::Focus(cmd) => {
self.run_focus_command(cmd);
}
CommandKind::MotionMode(_) => {}
CommandKind::MultiSelection(_) => {}
}
CommandExecuted::Yes
}
fn receive_char(&self, _c: &str) {}
}
impl CodeActionData {
pub fn new(cx: Scope, common: Rc<CommonData>) -> Self {
let status = cx.create_rw_signal(CodeActionStatus::Inactive);
let active = cx.create_rw_signal(0);
let code_action = Self {
status,
active,
request_id: 0,
input_id: 0,
offset: 0,
items: im::Vector::new(),
filtered_items: im::Vector::new(),
layout_rect: Rect::ZERO,
mouse_click: false,
common,
};
{
let code_action = code_action.clone();
cx.create_effect(move |_| {
let focus = code_action.common.focus.get();
if focus != Focus::CodeAction
&& code_action.status.get_untracked()
!= CodeActionStatus::Inactive
{
code_action.cancel();
}
})
}
code_action
}
pub fn next(&self) {
let active = self.active.get_untracked();
let new =
Movement::Down.update_index(active, self.filtered_items.len(), 1, true);
self.active.set(new);
}
pub fn previous(&self) {
let active = self.active.get_untracked();
let new =
Movement::Up.update_index(active, self.filtered_items.len(), 1, true);
self.active.set(new);
}
pub fn next_page(&self) {
let config = self.common.config.get_untracked();
let count = ((self.layout_rect.size().height
/ config.editor.line_height() as f64)
.floor() as usize)
.saturating_sub(1);
let active = self.active.get_untracked();
let new = Movement::Down.update_index(
active,
self.filtered_items.len(),
count,
false,
);
self.active.set(new);
}
pub fn previous_page(&self) {
let config = self.common.config.get_untracked();
let count = ((self.layout_rect.size().height
/ config.editor.line_height() as f64)
.floor() as usize)
.saturating_sub(1);
let active = self.active.get_untracked();
let new = Movement::Up.update_index(
active,
self.filtered_items.len(),
count,
false,
);
self.active.set(new);
}
pub fn show(
&mut self,
plugin_id: PluginId,
code_actions: im::Vector<CodeActionOrCommand>,
offset: usize,
mouse_click: bool,
) {
self.active.set(0);
self.status.set(CodeActionStatus::Active);
self.offset = offset;
self.mouse_click = mouse_click;
self.request_id += 1;
self.items = code_actions
.into_iter()
.map(|code_action| ScoredCodeActionItem {
item: code_action,
plugin_id,
score: 0,
indices: Vec::new(),
})
.collect();
self.filtered_items = self.items.clone();
self.common.focus.set(Focus::CodeAction);
}
fn cancel(&self) {
self.status.set(CodeActionStatus::Inactive);
self.common.focus.set(Focus::Workbench);
}
pub fn select(&self) {
if let Some(item) = self.filtered_items.get(self.active.get_untracked()) {
self.common
.internal_command
.send(InternalCommand::RunCodeAction {
plugin_id: item.plugin_id,
action: item.item.clone(),
});
}
self.cancel();
}
fn run_focus_command(&self, cmd: &FocusCommand) -> CommandExecuted {
match cmd {
FocusCommand::ModalClose => {
self.cancel();
}
FocusCommand::ListNext => {
self.next();
}
FocusCommand::ListNextPage => {
self.next_page();
}
FocusCommand::ListPrevious => {
self.previous();
}
FocusCommand::ListPreviousPage => {
self.previous_page();
}
FocusCommand::ListSelect => {
self.select();
}
_ => return CommandExecuted::No,
}
CommandExecuted::Yes
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/about.rs | lapce-app/src/about.rs | use std::rc::Rc;
use floem::{
View,
event::EventListener,
keyboard::Modifiers,
reactive::{RwSignal, Scope, SignalGet, SignalUpdate},
style::{CursorStyle, Display, Position},
views::{Decorators, container, label, stack, svg},
};
use lapce_core::{command::FocusCommand, meta::VERSION, mode::Mode};
use crate::{
command::{CommandExecuted, CommandKind},
config::color::LapceColor,
keypress::KeyPressFocus,
web_link::web_link,
window_tab::{Focus, WindowTabData},
};
struct AboutUri {}
impl AboutUri {
const LAPCE: &'static str = "https://lapce.dev";
const GITHUB: &'static str = "https://github.com/lapce/lapce";
const MATRIX: &'static str = "https://matrix.to/#/#lapce-editor:matrix.org";
const DISCORD: &'static str = "https://discord.gg/n8tGJ6Rn6D";
const CODICONS: &'static str = "https://github.com/microsoft/vscode-codicons";
}
#[derive(Clone, Debug)]
pub struct AboutData {
pub visible: RwSignal<bool>,
pub focus: RwSignal<Focus>,
}
impl AboutData {
pub fn new(cx: Scope, focus: RwSignal<Focus>) -> Self {
let visible = cx.create_rw_signal(false);
Self { visible, focus }
}
pub fn open(&self) {
self.visible.set(true);
self.focus.set(Focus::AboutPopup);
}
pub fn close(&self) {
self.visible.set(false);
self.focus.set(Focus::Workbench);
}
}
impl KeyPressFocus for AboutData {
fn get_mode(&self) -> Mode {
Mode::Insert
}
fn check_condition(
&self,
_condition: crate::keypress::condition::Condition,
) -> bool {
self.visible.get_untracked()
}
fn run_command(
&self,
command: &crate::command::LapceCommand,
_count: Option<usize>,
_mods: Modifiers,
) -> crate::command::CommandExecuted {
match &command.kind {
CommandKind::Workbench(_) => {}
CommandKind::Edit(_) => {}
CommandKind::Move(_) => {}
CommandKind::Scroll(_) => {}
CommandKind::Focus(cmd) => {
if cmd == &FocusCommand::ModalClose {
self.close();
}
}
CommandKind::MotionMode(_) => {}
CommandKind::MultiSelection(_) => {}
}
CommandExecuted::Yes
}
fn receive_char(&self, _c: &str) {}
fn focus_only(&self) -> bool {
true
}
}
pub fn about_popup(window_tab_data: Rc<WindowTabData>) -> impl View {
let about_data = window_tab_data.about_data.clone();
let config = window_tab_data.common.config;
let internal_command = window_tab_data.common.internal_command;
let logo_size = 100.0;
exclusive_popup(window_tab_data, about_data.visible, move || {
stack((
svg(move || (config.get()).logo_svg()).style(move |s| {
s.size(logo_size, logo_size)
.color(config.get().color(LapceColor::EDITOR_FOREGROUND))
}),
label(|| "Lapce".to_string()).style(move |s| {
s.font_bold()
.margin_top(10.0)
.color(config.get().color(LapceColor::EDITOR_FOREGROUND))
}),
label(|| format!("Version: {}", VERSION)).style(move |s| {
s.margin_top(10.0)
.color(config.get().color(LapceColor::EDITOR_DIM))
}),
web_link(
|| "Website".to_string(),
|| AboutUri::LAPCE.to_string(),
move || config.get().color(LapceColor::EDITOR_LINK),
internal_command,
)
.style(|s| s.margin_top(20.0)),
web_link(
|| "GitHub".to_string(),
|| AboutUri::GITHUB.to_string(),
move || config.get().color(LapceColor::EDITOR_LINK),
internal_command,
)
.style(|s| s.margin_top(10.0)),
web_link(
|| "Discord".to_string(),
|| AboutUri::DISCORD.to_string(),
move || config.get().color(LapceColor::EDITOR_LINK),
internal_command,
)
.style(|s| s.margin_top(10.0)),
web_link(
|| "Matrix".to_string(),
|| AboutUri::MATRIX.to_string(),
move || config.get().color(LapceColor::EDITOR_LINK),
internal_command,
)
.style(|s| s.margin_top(10.0)),
label(|| "Attributions".to_string()).style(move |s| {
s.font_bold()
.color(config.get().color(LapceColor::EDITOR_DIM))
.margin_top(40.0)
}),
web_link(
|| "Codicons (CC-BY-4.0)".to_string(),
|| AboutUri::CODICONS.to_string(),
move || config.get().color(LapceColor::EDITOR_LINK),
internal_command,
)
.style(|s| s.margin_top(10.0)),
))
.style(|s| s.flex_col().items_center())
})
.debug_name("About Popup")
}
fn exclusive_popup<V: View + 'static>(
window_tab_data: Rc<WindowTabData>,
visibility: RwSignal<bool>,
content: impl FnOnce() -> V,
) -> impl View {
let config = window_tab_data.common.config;
container(
container(
container(content())
.style(move |s| {
let config = config.get();
s.padding_vert(25.0)
.padding_horiz(100.0)
.border(1.0)
.border_radius(6.0)
.border_color(config.color(LapceColor::LAPCE_BORDER))
.background(config.color(LapceColor::PANEL_BACKGROUND))
})
.on_event_stop(EventListener::PointerDown, move |_| {}),
)
.style(move |s| {
s.flex_grow(1.0)
.flex_row()
.items_center()
.hover(move |s| s.cursor(CursorStyle::Default))
}),
)
.on_event_stop(EventListener::PointerDown, move |_| {
window_tab_data.about_data.close();
})
// Prevent things behind the grayed out area from being hovered.
.on_event_stop(EventListener::PointerMove, move |_| {})
.style(move |s| {
s.display(if visibility.get() {
Display::Flex
} else {
Display::None
})
.position(Position::Absolute)
.size_pct(100.0, 100.0)
.flex_col()
.items_center()
.background(
config
.get()
.color(LapceColor::LAPCE_DROPDOWN_SHADOW)
.multiply_alpha(0.5),
)
})
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/plugin.rs | lapce-app/src/plugin.rs | use std::{
collections::HashSet,
rc::Rc,
sync::{Arc, atomic::AtomicU64},
};
use anyhow::Result;
use floem::{
IntoView, View,
action::show_context_menu,
ext_event::create_ext_action,
keyboard::Modifiers,
kurbo::Rect,
menu::{Menu, MenuItem},
reactive::{
RwSignal, Scope, SignalGet, SignalUpdate, SignalWith, create_effect,
create_memo, create_rw_signal, use_context,
},
style::CursorStyle,
views::{
Decorators, container, dyn_container, dyn_stack, empty, img, label,
rich_text, scroll, stack, svg, text,
},
};
use indexmap::IndexMap;
use lapce_core::{command::EditCommand, directory::Directory, mode::Mode};
use lapce_proxy::plugin::{download_volt, volt_icon, wasi::find_all_volts};
use lapce_rpc::{
core::{CoreNotification, CoreRpcHandler},
plugin::{VoltID, VoltInfo, VoltMetadata},
};
use lsp_types::MessageType;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use crate::{
command::{CommandExecuted, CommandKind},
config::{LapceConfig, color::LapceColor},
db::LapceDb,
editor::EditorData,
keypress::{KeyPressFocus, condition::Condition},
main_split::Editors,
markdown::{MarkdownContent, parse_markdown},
panel::plugin_view::VOLT_DEFAULT_PNG,
web_link::web_link,
window_tab::CommonData,
};
type PluginInfo = Option<(
Option<VoltMetadata>,
VoltInfo,
Option<VoltIcon>,
Option<VoltInfo>,
Option<RwSignal<bool>>,
)>;
#[derive(Clone, PartialEq, Eq)]
pub enum VoltIcon {
Svg(String),
Img(Vec<u8>),
}
impl VoltIcon {
pub fn from_bytes(buf: &[u8]) -> Result<Self> {
if let Ok(s) = std::str::from_utf8(buf) {
Ok(VoltIcon::Svg(s.to_string()))
} else {
Ok(VoltIcon::Img(buf.to_vec()))
}
}
}
#[derive(Deserialize, Serialize)]
pub struct VoltsInfo {
pub plugins: Vec<VoltInfo>,
pub total: usize,
}
#[derive(Clone)]
pub struct InstalledVoltData {
pub meta: RwSignal<VoltMetadata>,
pub icon: RwSignal<Option<VoltIcon>>,
pub latest: RwSignal<VoltInfo>,
}
#[derive(Clone, PartialEq)]
pub struct AvailableVoltData {
pub info: RwSignal<VoltInfo>,
pub icon: RwSignal<Option<VoltIcon>>,
pub installing: RwSignal<bool>,
}
#[derive(Clone, Debug)]
pub struct AvailableVoltList {
pub loading: RwSignal<bool>,
pub query_id: RwSignal<usize>,
pub query_editor: EditorData,
pub volts: RwSignal<IndexMap<VoltID, AvailableVoltData>>,
pub total: RwSignal<usize>,
}
#[derive(Clone, Debug)]
pub struct PluginData {
pub installed: RwSignal<IndexMap<VoltID, InstalledVoltData>>,
pub available: AvailableVoltList,
pub all: RwSignal<im::HashMap<VoltID, AvailableVoltData>>,
pub disabled: RwSignal<HashSet<VoltID>>,
pub workspace_disabled: RwSignal<HashSet<VoltID>>,
pub common: Rc<CommonData>,
}
impl KeyPressFocus for PluginData {
fn get_mode(&self) -> Mode {
Mode::Insert
}
fn check_condition(&self, condition: Condition) -> bool {
matches!(condition, Condition::PanelFocus)
}
fn run_command(
&self,
command: &crate::command::LapceCommand,
count: Option<usize>,
mods: Modifiers,
) -> CommandExecuted {
match &command.kind {
CommandKind::Workbench(_) => {}
CommandKind::Scroll(_) => {}
CommandKind::Focus(_) => {}
CommandKind::Edit(_)
| CommandKind::Move(_)
| CommandKind::MultiSelection(_) => {
#[allow(clippy::single_match)]
match command.kind {
CommandKind::Edit(EditCommand::InsertNewLine) => {
return CommandExecuted::Yes;
}
_ => {}
}
return self
.available
.query_editor
.run_command(command, count, mods);
}
CommandKind::MotionMode(_) => {}
}
CommandExecuted::No
}
fn receive_char(&self, c: &str) {
self.available.query_editor.receive_char(c);
}
}
impl PluginData {
pub fn new(
cx: Scope,
disabled: HashSet<VoltID>,
workspace_disabled: HashSet<VoltID>,
editors: Editors,
common: Rc<CommonData>,
core_rpc: CoreRpcHandler,
) -> Self {
let installed = cx.create_rw_signal(IndexMap::new());
let available = AvailableVoltList {
loading: cx.create_rw_signal(false),
volts: cx.create_rw_signal(IndexMap::new()),
total: cx.create_rw_signal(0),
query_id: cx.create_rw_signal(0),
query_editor: editors.make_local(cx, common.clone()),
};
let disabled = cx.create_rw_signal(disabled);
let workspace_disabled = cx.create_rw_signal(workspace_disabled);
let plugin = Self {
installed,
available,
all: cx.create_rw_signal(im::HashMap::new()),
disabled,
workspace_disabled,
common,
};
plugin.load_available_volts("", 0, core_rpc.clone());
{
let plugin = plugin.clone();
let extra_plugin_paths =
plugin.common.window_common.extra_plugin_paths.clone();
let send = create_ext_action(
cx,
move |volts: Vec<(Option<Vec<u8>>, VoltMetadata)>| {
for (icon, meta) in volts {
plugin.volt_installed(&meta, &icon);
}
},
);
std::thread::Builder::new()
.name("FindAllVolts".to_owned())
.spawn(move || {
let volts = find_all_volts(&extra_plugin_paths);
let volts = volts
.into_iter()
.filter_map(|meta| {
if meta.wasm.is_none() {
Some((volt_icon(&meta), meta))
} else {
None
}
})
.collect::<Vec<_>>();
send(volts);
})
.unwrap();
}
{
let plugin = plugin.clone();
cx.create_effect(move |s| {
let query = plugin
.available
.query_editor
.doc_signal()
.get()
.buffer
.with(|buffer| buffer.to_string());
if s.as_ref() == Some(&query) {
return query;
}
plugin.available.query_id.update(|id| *id += 1);
plugin.available.loading.set(false);
plugin.available.volts.update(|v| v.clear());
plugin.load_available_volts(&query, 0, core_rpc.clone());
query
});
}
plugin
}
pub fn volt_installed(&self, volt: &VoltMetadata, icon: &Option<Vec<u8>>) {
let volt_id = volt.id();
let (existing, is_latest, volt_data) = self
.installed
.try_update(|installed| {
if let Some(v) = installed.get(&volt_id) {
(true, true, v.to_owned())
} else {
let (info, is_latest) = if let Some(volt) = self
.available
.volts
.with_untracked(|all| all.get(&volt_id).cloned())
{
(volt.info.get_untracked(), true)
} else {
(volt.info(), false)
};
let latest = self.common.scope.create_rw_signal(info);
let data = InstalledVoltData {
meta: self.common.scope.create_rw_signal(volt.clone()),
icon: self.common.scope.create_rw_signal(
icon.as_ref()
.and_then(|icon| VoltIcon::from_bytes(icon).ok()),
),
latest,
};
installed.insert(volt_id, data.clone());
(false, is_latest, data)
}
})
.unwrap();
if existing {
volt_data.meta.set(volt.clone());
volt_data.icon.set(
icon.as_ref()
.and_then(|icon| VoltIcon::from_bytes(icon).ok()),
);
}
let latest = volt_data.latest;
if !is_latest {
let url = format!(
"https://plugins.lapce.dev/api/v1/plugins/{}/{}/latest",
volt.author, volt.name
);
let send = create_ext_action(self.common.scope, move |info| {
if let Some(info) = info {
latest.set(info);
}
});
std::thread::spawn(move || {
let info: Option<VoltInfo> = lapce_proxy::get_url(url, None)
.ok()
.and_then(|r| r.json().ok());
send(info);
});
}
}
pub fn volt_removed(&self, volt: &VoltInfo) {
let id = volt.id();
self.installed.update(|installed| {
installed.swap_remove(&id);
});
if self.disabled.with_untracked(|d| d.contains(&id)) {
self.disabled.update(|d| {
d.remove(&id);
});
let db: Arc<LapceDb> = use_context().unwrap();
db.save_disabled_volts(
self.disabled.get_untracked().into_iter().collect(),
);
}
if self.workspace_disabled.with_untracked(|d| d.contains(&id)) {
self.workspace_disabled.update(|d| {
d.remove(&id);
});
let db: Arc<LapceDb> = use_context().unwrap();
db.save_workspace_disabled_volts(
self.common.workspace.clone(),
self.workspace_disabled
.get_untracked()
.into_iter()
.collect(),
);
}
}
fn load_available_volts(
&self,
query: &str,
offset: usize,
core_rpc: CoreRpcHandler,
) {
if self.available.loading.get_untracked() {
return;
}
self.available.loading.set(true);
let volts = self.available.volts;
let volts_total = self.available.total;
let cx = self.common.scope;
let loading = self.available.loading;
let query_id = self.available.query_id;
let current_query_id = self.available.query_id.get_untracked();
let all = self.all;
let send =
create_ext_action(self.common.scope, move |new: Result<VoltsInfo>| {
loading.set(false);
if query_id.get_untracked() != current_query_id {
return;
}
match new {
Ok(new) => {
volts.update(|volts| {
volts.extend(new.plugins.into_iter().map(|volt| {
let icon = cx.create_rw_signal(None);
let send = create_ext_action(cx, move |result| {
if let Ok(i) = result {
icon.set(Some(i));
}
});
{
let volt = volt.clone();
std::thread::spawn(move || {
let result = Self::load_icon(&volt);
send(result);
});
}
let data = AvailableVoltData {
info: cx.create_rw_signal(volt.clone()),
icon,
installing: cx.create_rw_signal(false),
};
all.update(|all| {
all.insert(volt.id(), data.clone());
});
(volt.id(), data)
}));
});
volts_total.set(new.total);
}
Err(err) => {
tracing::error!("{:?}", err);
core_rpc.notification(CoreNotification::ShowMessage {
title: "Request Available Plugins".to_string(),
message: lsp_types::ShowMessageParams {
typ: MessageType::ERROR,
message: err.to_string(),
},
});
}
}
});
let query = query.to_string();
std::thread::spawn(move || {
let volts = Self::query_volts(&query, offset);
send(volts);
});
}
fn load_icon(volt: &VoltInfo) -> Result<VoltIcon> {
let url = format!(
"https://plugins.lapce.dev/api/v1/plugins/{}/{}/{}/icon?id={}",
volt.author, volt.name, volt.version, volt.updated_at_ts
);
let cache_file_path = Directory::cache_directory().map(|cache_dir| {
let mut hasher = Sha256::new();
hasher.update(url.as_bytes());
let filename = format!("{:x}", hasher.finalize());
cache_dir.join(filename)
});
let cache_content =
cache_file_path.as_ref().and_then(|p| std::fs::read(p).ok());
let content = match cache_content {
Some(content) => content,
None => {
let resp = lapce_proxy::get_url(&url, None)?;
if !resp.status().is_success() {
return Err(anyhow::anyhow!("can't download icon"));
}
let buf = resp.bytes()?.to_vec();
if let Some(path) = cache_file_path.as_ref() {
if let Err(err) = std::fs::write(path, &buf) {
tracing::error!("{:?}", err);
}
}
buf
}
};
VoltIcon::from_bytes(&content)
}
fn download_readme(
volt: &VoltInfo,
config: &LapceConfig,
) -> Result<Vec<MarkdownContent>> {
let url = format!(
"https://plugins.lapce.dev/api/v1/plugins/{}/{}/{}/readme",
volt.author, volt.name, volt.version
);
let resp = lapce_proxy::get_url(&url, None)?;
if resp.status() != 200 {
let text = parse_markdown("Plugin doesn't have a README", 2.0, config);
return Ok(text);
}
let text = resp.text()?;
let text = parse_markdown(&text, 2.0, config);
Ok(text)
}
fn query_volts(query: &str, offset: usize) -> Result<VoltsInfo> {
let url = format!(
"https://plugins.lapce.dev/api/v1/plugins?q={query}&offset={offset}"
);
let plugins: VoltsInfo = lapce_proxy::get_url(url, None)?.json()?;
Ok(plugins)
}
fn all_loaded(&self) -> bool {
self.available.volts.with_untracked(|v| v.len())
>= self.available.total.get_untracked()
}
pub fn load_more_available(&self, core_rpc: CoreRpcHandler) {
if self.all_loaded() {
return;
}
let query = self
.available
.query_editor
.doc()
.buffer
.with_untracked(|buffer| buffer.to_string());
let offset = self.available.volts.with_untracked(|v| v.len());
self.load_available_volts(&query, offset, core_rpc);
}
pub fn install_volt(&self, info: VoltInfo) {
self.available.volts.with_untracked(|volts| {
if let Some(volt) = volts.get(&info.id()) {
volt.installing.set(true);
};
});
if info.wasm {
self.common.proxy.install_volt(info);
} else {
let plugin = self.clone();
let send = create_ext_action(self.common.scope, move |result| {
if let Ok((meta, icon)) = result {
plugin.volt_installed(&meta, &icon);
}
});
std::thread::spawn(move || {
let download = || -> Result<(VoltMetadata, Option<Vec<u8>>)> {
let download_volt_result = download_volt(&info);
let meta = download_volt_result?;
let icon = volt_icon(&meta);
Ok((meta, icon))
};
send(download());
});
}
}
pub fn plugin_disabled(&self, id: &VoltID) -> bool {
self.disabled.with_untracked(|d| d.contains(id))
|| self.workspace_disabled.with_untracked(|d| d.contains(id))
}
pub fn enable_volt(&self, volt: VoltInfo) {
let id = volt.id();
self.disabled.update(|d| {
d.remove(&id);
});
if !self.plugin_disabled(&id) {
self.common.proxy.enable_volt(volt);
}
let db: Arc<LapceDb> = use_context().unwrap();
db.save_disabled_volts(self.disabled.get_untracked().into_iter().collect());
}
pub fn disable_volt(&self, volt: VoltInfo) {
let id = volt.id();
self.disabled.update(|d| {
d.insert(id);
});
self.common.proxy.disable_volt(volt);
let db: Arc<LapceDb> = use_context().unwrap();
db.save_disabled_volts(self.disabled.get_untracked().into_iter().collect());
}
pub fn enable_volt_for_ws(&self, volt: VoltInfo) {
let id = volt.id();
self.workspace_disabled.update(|d| {
d.remove(&id);
});
if !self.plugin_disabled(&id) {
self.common.proxy.enable_volt(volt);
}
let db: Arc<LapceDb> = use_context().unwrap();
db.save_workspace_disabled_volts(
self.common.workspace.clone(),
self.disabled.get_untracked().into_iter().collect(),
);
}
pub fn disable_volt_for_ws(&self, volt: VoltInfo) {
let id = volt.id();
self.workspace_disabled.update(|d| {
d.insert(id);
});
self.common.proxy.disable_volt(volt);
let db: Arc<LapceDb> = use_context().unwrap();
db.save_workspace_disabled_volts(
self.common.workspace.clone(),
self.disabled.get_untracked().into_iter().collect(),
);
}
pub fn uninstall_volt(&self, volt: VoltMetadata) {
if volt.wasm.is_some() {
self.common.proxy.remove_volt(volt);
} else {
let plugin = self.clone();
let info = volt.info();
let send =
create_ext_action(self.common.scope, move |result: Result<()>| {
if let Ok(()) = result {
plugin.volt_removed(&info);
}
});
std::thread::spawn(move || {
let uninstall = || -> Result<()> {
let path = volt
.dir
.as_ref()
.ok_or_else(|| anyhow::anyhow!("don't have dir"))?;
std::fs::remove_dir_all(path)?;
Ok(())
};
send(uninstall());
});
}
}
pub fn reload_volt(&self, volt: VoltMetadata) {
self.common.proxy.reload_volt(volt);
}
pub fn plugin_controls(&self, meta: VoltMetadata, latest: VoltInfo) -> Menu {
let volt_id = meta.id();
let mut menu = Menu::new("");
if meta.version != latest.version {
menu = menu
.entry(MenuItem::new("Upgrade Plugin").action({
let plugin = self.clone();
let info = latest.clone();
move || {
plugin.install_volt(info.clone());
}
}))
.separator();
}
menu = menu
.entry(MenuItem::new("Reload Plugin").action({
let plugin = self.clone();
let meta = meta.clone();
move || {
plugin.reload_volt(meta.clone());
}
}))
.separator()
.entry(
MenuItem::new("Enable")
.enabled(
self.disabled
.with_untracked(|disabled| disabled.contains(&volt_id)),
)
.action({
let plugin = self.clone();
let volt = meta.info();
move || {
plugin.enable_volt(volt.clone());
}
}),
)
.entry(
MenuItem::new("Disable")
.enabled(
self.disabled
.with_untracked(|disabled| !disabled.contains(&volt_id)),
)
.action({
let plugin = self.clone();
let volt = meta.info();
move || {
plugin.disable_volt(volt.clone());
}
}),
)
.separator()
.entry(
MenuItem::new("Enable For Workspace")
.enabled(
self.workspace_disabled
.with_untracked(|disabled| disabled.contains(&volt_id)),
)
.action({
let plugin = self.clone();
let volt = meta.info();
move || {
plugin.enable_volt_for_ws(volt.clone());
}
}),
)
.entry(
MenuItem::new("Disable For Workspace")
.enabled(
self.workspace_disabled
.with_untracked(|disabled| !disabled.contains(&volt_id)),
)
.action({
let plugin = self.clone();
let volt = meta.info();
move || {
plugin.disable_volt_for_ws(volt.clone());
}
}),
)
.separator()
.entry(MenuItem::new("Uninstall").action({
let plugin = self.clone();
move || {
plugin.uninstall_volt(meta.clone());
}
}));
menu
}
}
pub fn plugin_info_view(plugin: PluginData, volt: VoltID) -> impl View {
let config = plugin.common.config;
let header_rect = create_rw_signal(Rect::ZERO);
let scroll_width: RwSignal<f64> = create_rw_signal(0.0);
let internal_command = plugin.common.internal_command;
let local_plugin = plugin.clone();
let plugin_info = create_memo(move |_| {
plugin
.installed
.with(|volts| {
volts.get(&volt).map(|v| {
(
Some(v.meta.get()),
v.meta.get().info(),
v.icon.get(),
Some(v.latest.get()),
None,
)
})
})
.or_else(|| {
plugin.all.with(|volts| {
volts.get(&volt).map(|v| {
(None, v.info.get(), v.icon.get(), None, Some(v.installing))
})
})
})
});
let version_view = move |plugin: PluginData, plugin_info: PluginInfo| {
let version_info = plugin_info.as_ref().map(|(_, volt, _, latest, _)| {
(
volt.version.clone(),
latest.as_ref().map(|i| i.version.clone()),
)
});
let installing = plugin_info
.as_ref()
.and_then(|(_, _, _, _, installing)| *installing);
let local_version_info = version_info.clone();
let control = {
move |version_info: Option<(String, Option<String>)>| match version_info
.as_ref()
.map(|(v, l)| match l {
Some(l) => (true, l == v),
None => (false, false),
}) {
Some((true, true)) => "Installed ▼",
Some((true, false)) => "Upgrade ▼",
_ => {
if installing.map(|i| i.get()).unwrap_or(false) {
"Installing"
} else {
"Install"
}
}
}
};
let local_plugin_info = plugin_info.clone();
let local_plugin = plugin.clone();
stack((
text(
version_info
.as_ref()
.map(|(v, _)| format!("v{v}"))
.unwrap_or_default(),
),
label(move || control(local_version_info.clone()))
.style(move |s| {
let config = config.get();
s.margin_left(10)
.padding_horiz(10)
.border_radius(6.0)
.color(
config
.color(LapceColor::LAPCE_BUTTON_PRIMARY_FOREGROUND),
)
.background(
config
.color(LapceColor::LAPCE_BUTTON_PRIMARY_BACKGROUND),
)
.hover(|s| {
s.cursor(CursorStyle::Pointer).background(
config
.color(
LapceColor::LAPCE_BUTTON_PRIMARY_BACKGROUND,
)
.multiply_alpha(0.8),
)
})
.active(|s| {
s.background(
config
.color(
LapceColor::LAPCE_BUTTON_PRIMARY_BACKGROUND,
)
.multiply_alpha(0.6),
)
})
.disabled(|s| {
s.background(config.color(LapceColor::EDITOR_DIM))
})
.selectable(false)
})
.disabled(move || installing.map(|i| i.get()).unwrap_or(false))
.on_click_stop(move |_| {
if let Some((meta, info, _, latest, _)) =
local_plugin_info.as_ref()
{
if let Some(meta) = meta {
let menu = local_plugin.plugin_controls(
meta.to_owned(),
latest.clone().unwrap_or_else(|| info.to_owned()),
);
show_context_menu(menu, None);
} else {
local_plugin.install_volt(info.to_owned());
}
}
}),
))
};
scroll(
dyn_container(
move || plugin_info.get(),
move |plugin_info| {
stack((
stack((
match plugin_info
.as_ref()
.and_then(|(_, _, icon, _, _)| icon.clone())
{
None => container(
img(move || VOLT_DEFAULT_PNG.to_vec())
.style(|s| s.size_full()),
),
Some(VoltIcon::Svg(svg_str)) => container(
svg(move || svg_str.clone())
.style(|s| s.size_full()),
),
Some(VoltIcon::Img(buf)) => container(
img(move || buf.clone()).style(|s| s.size_full()),
),
}
.style(|s| {
s.min_size(150.0, 150.0).size(150.0, 150.0).padding(20)
}),
stack((
text(
plugin_info
.as_ref()
.map(|(_, volt, _, _, _)| {
volt.display_name.as_str()
})
.unwrap_or(""),
)
.style(move |s| {
s.font_bold().font_size(
(config.get().ui.font_size() as f32 * 1.6)
.round(),
)
}),
text(
plugin_info
.as_ref()
.map(|(_, volt, _, _, _)| {
volt.description.as_str()
})
.unwrap_or(""),
)
.style(move |s| {
let scroll_width = scroll_width.get();
s.max_width(
scroll_width
.clamp(200.0 + 60.0 * 2.0 + 200.0, 800.0)
- 60.0 * 2.0
- 200.0,
)
}),
{
let repo = plugin_info
.as_ref()
.and_then(|(_, volt, _, _, _)| {
volt.repository.as_deref()
})
.unwrap_or("")
.to_string();
let local_repo = repo.clone();
stack((
text("Repository: "),
web_link(
move || repo.clone(),
move || local_repo.clone(),
move || {
config
.get()
.color(LapceColor::EDITOR_LINK)
},
internal_command,
),
))
},
text(
plugin_info
.as_ref()
.map(|(_, volt, _, _, _)| volt.author.as_str())
.unwrap_or(""),
)
.style(move |s| {
s.color(config.get().color(LapceColor::EDITOR_DIM))
}),
version_view(local_plugin.clone(), plugin_info.clone()),
))
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | true |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/keypress/key.rs | lapce-app/src/keypress/key.rs | use floem::keyboard::{Key, KeyLocation, NamedKey, PhysicalKey};
use super::keymap::KeyMapKey;
#[derive(Clone, Debug)]
pub(crate) enum KeyInput {
Keyboard {
physical: PhysicalKey,
logical: Key,
location: KeyLocation,
key_without_modifiers: Key,
repeat: bool,
},
Pointer(floem::pointer::PointerButton),
}
impl KeyInput {
pub fn keymap_key(&self) -> Option<KeyMapKey> {
if let KeyInput::Keyboard {
repeat, logical, ..
} = self
{
if *repeat
&& (matches!(
logical,
Key::Named(NamedKey::Meta)
| Key::Named(NamedKey::Shift)
| Key::Named(NamedKey::Alt)
| Key::Named(NamedKey::Control),
))
{
return None;
}
}
Some(match self {
KeyInput::Pointer(b) => KeyMapKey::Pointer(*b),
KeyInput::Keyboard {
physical,
key_without_modifiers,
logical,
location,
..
} => {
#[allow(clippy::single_match)]
match location {
KeyLocation::Numpad => {
return Some(KeyMapKey::Logical(logical.to_owned()));
}
_ => {}
}
match key_without_modifiers {
Key::Named(_) => {
KeyMapKey::Logical(key_without_modifiers.to_owned())
}
Key::Character(c) => {
if c == " " {
KeyMapKey::Logical(Key::Named(NamedKey::Space))
} else if c.len() == 1 && c.is_ascii() {
KeyMapKey::Logical(Key::Character(
c.to_lowercase().into(),
))
} else {
KeyMapKey::Physical(*physical)
}
}
Key::Unidentified(_) => KeyMapKey::Physical(*physical),
Key::Dead(_) => KeyMapKey::Physical(*physical),
}
}
})
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/keypress/press.rs | lapce-app/src/keypress/press.rs | use floem::keyboard::Modifiers;
use super::{key::KeyInput, keymap::KeyMapPress};
#[derive(Clone, Debug)]
pub struct KeyPress {
pub(super) key: KeyInput,
pub(super) mods: Modifiers,
}
impl KeyPress {
pub fn keymap_press(&self) -> Option<KeyMapPress> {
self.key.keymap_key().map(|key| KeyMapPress {
key,
mods: self.mods,
})
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/keypress/condition.rs | lapce-app/src/keypress/condition.rs | use strum_macros::EnumString;
#[derive(Debug, PartialEq, Eq)]
pub(super) enum CheckCondition<'a> {
Single(&'a str),
Or(&'a str, &'a str),
And(&'a str, &'a str),
}
impl<'a> CheckCondition<'a> {
pub(super) fn parse_first(condition: &'a str) -> Self {
let or = condition.match_indices("||").next();
let and = condition.match_indices("&&").next();
match (or, and) {
(None, None) => CheckCondition::Single(condition),
(Some((pos, _)), None) => {
CheckCondition::Or(&condition[..pos], &condition[pos + 2..])
}
(None, Some((pos, _))) => {
CheckCondition::And(&condition[..pos], &condition[pos + 2..])
}
(Some((or_pos, _)), Some((and_pos, _))) => {
if or_pos < and_pos {
CheckCondition::Or(
&condition[..or_pos],
&condition[or_pos + 2..],
)
} else {
CheckCondition::And(
&condition[..and_pos],
&condition[and_pos + 2..],
)
}
}
}
}
}
#[derive(Clone, Copy, Debug, EnumString, PartialEq, Eq)]
pub enum Condition {
#[strum(serialize = "editor_focus")]
EditorFocus,
#[strum(serialize = "input_focus")]
InputFocus,
#[strum(serialize = "list_focus")]
ListFocus,
#[strum(serialize = "palette_focus")]
PaletteFocus,
#[strum(serialize = "completion_focus")]
CompletionFocus,
#[strum(serialize = "inline_completion_visible")]
InlineCompletionVisible,
#[strum(serialize = "modal_focus")]
ModalFocus,
#[strum(serialize = "in_snippet")]
InSnippet,
#[strum(serialize = "terminal_focus")]
TerminalFocus,
#[strum(serialize = "source_control_focus")]
SourceControlFocus,
#[strum(serialize = "panel_focus")]
PanelFocus,
#[strum(serialize = "rename_focus")]
RenameFocus,
#[strum(serialize = "search_active")]
SearchActive,
#[strum(serialize = "on_screen_find_active")]
OnScreenFindActive,
#[strum(serialize = "search_focus")]
SearchFocus,
#[strum(serialize = "replace_focus")]
ReplaceFocus,
}
#[cfg(test)]
mod test {
use floem::keyboard::Modifiers;
use lapce_core::mode::Mode;
use super::Condition;
use crate::keypress::{KeyPressData, KeyPressFocus, condition::CheckCondition};
#[derive(Clone, Copy, Debug)]
struct MockFocus {
accepted_conditions: &'static [Condition],
}
impl KeyPressFocus for MockFocus {
fn check_condition(&self, condition: Condition) -> bool {
self.accepted_conditions.contains(&condition)
}
fn get_mode(&self) -> Mode {
unimplemented!()
}
fn run_command(
&self,
_command: &crate::command::LapceCommand,
_count: Option<usize>,
_mods: Modifiers,
) -> crate::command::CommandExecuted {
unimplemented!()
}
fn receive_char(&self, _c: &str) {
unimplemented!()
}
}
#[test]
fn test_parse() {
assert_eq!(
CheckCondition::Or("foo", "bar"),
CheckCondition::parse_first("foo||bar")
);
assert_eq!(
CheckCondition::And("foo", "bar"),
CheckCondition::parse_first("foo&&bar")
);
assert_eq!(
CheckCondition::And("foo", "bar||baz"),
CheckCondition::parse_first("foo&&bar||baz")
);
assert_eq!(
CheckCondition::And("foo ", " bar || baz"),
CheckCondition::parse_first("foo && bar || baz")
);
}
#[test]
fn test_check_condition() {
let focus = MockFocus {
accepted_conditions: &[Condition::EditorFocus, Condition::ListFocus],
};
let test_cases = [
("editor_focus", true),
("list_focus", true),
("!editor_focus", false),
("!list_focus", false),
("editor_focus || list_focus", true),
("editor_focus || !list_focus", true),
("!editor_focus || list_focus", true),
("editor_focus && list_focus", true),
("editor_focus && !list_focus", false),
("!editor_focus && list_focus", false),
("editor_focus && list_focus || baz", true),
("editor_focus && list_focus && baz", false),
("editor_focus && list_focus && !baz", true),
];
for (condition, should_accept) in test_cases.into_iter() {
assert_eq!(
should_accept,
KeyPressData::check_condition(condition, &focus),
"Condition check failed. Condition: {condition}. Expected result: {should_accept}",
);
}
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/keypress/loader.rs | lapce-app/src/keypress/loader.rs | use anyhow::{Result, anyhow};
use indexmap::IndexMap;
use lapce_core::mode::Modes;
use tracing::{debug, error};
use super::keymap::{KeyMap, KeyMapPress};
pub struct KeyMapLoader {
keymaps: IndexMap<Vec<KeyMapPress>, Vec<KeyMap>>,
command_keymaps: IndexMap<String, Vec<KeyMap>>,
}
impl KeyMapLoader {
pub fn new() -> Self {
Self {
keymaps: Default::default(),
command_keymaps: Default::default(),
}
}
pub fn load_from_str<'a>(
&'a mut self,
s: &str,
modal: bool,
) -> Result<&'a mut Self> {
let toml_keymaps: toml_edit::Document = s.parse()?;
let toml_keymaps = toml_keymaps
.get("keymaps")
.and_then(|v| v.as_array_of_tables())
.ok_or_else(|| anyhow!("no keymaps"))?;
for toml_keymap in toml_keymaps {
let keymap = match Self::get_keymap(toml_keymap, modal) {
Ok(Some(keymap)) => keymap,
Ok(None) => {
// Keymap ignored
continue;
}
Err(err) => {
error!("Could not parse keymap: {err}");
continue;
}
};
let (command, bind) = match keymap.command.strip_prefix('-') {
Some(cmd) => (cmd.to_string(), false),
None => (keymap.command.clone(), true),
};
let current_keymaps = self.command_keymaps.entry(command).or_default();
if bind {
current_keymaps.push(keymap.clone());
for i in 1..keymap.key.len() + 1 {
let key = keymap.key[..i].to_vec();
self.keymaps.entry(key).or_default().push(keymap.clone());
}
} else {
let is_keymap = |k: &KeyMap| -> bool {
k.when == keymap.when
&& k.modes == keymap.modes
&& k.key == keymap.key
};
if let Some(index) = current_keymaps.iter().position(is_keymap) {
current_keymaps.remove(index);
}
for i in 1..keymap.key.len() + 1 {
if let Some(keymaps) = self.keymaps.get_mut(&keymap.key[..i]) {
if let Some(index) = keymaps.iter().position(is_keymap) {
keymaps.remove(index);
}
}
}
}
}
Ok(self)
}
#[allow(clippy::type_complexity)]
pub fn finalize(
self,
) -> (
IndexMap<Vec<KeyMapPress>, Vec<KeyMap>>,
IndexMap<String, Vec<KeyMap>>,
) {
let Self {
keymaps: map,
command_keymaps: command_map,
} = self;
(map, command_map)
}
fn get_keymap(
toml_keymap: &toml_edit::Table,
modal: bool,
) -> Result<Option<KeyMap>> {
let key = toml_keymap
.get("key")
.and_then(|v| v.as_str())
.ok_or_else(|| anyhow!("no key in keymap"))?;
let modes = get_modes(toml_keymap);
// If not using modal editing, remove keymaps that only make sense in modal.
if !modal
&& !modes.is_empty()
&& !modes.contains(Modes::INSERT)
&& !modes.contains(Modes::TERMINAL)
{
debug!("Keymap ignored: {}", key);
return Ok(None);
}
Ok(Some(KeyMap {
key: KeyMapPress::parse(key),
modes,
when: toml_keymap
.get("when")
.and_then(|w| w.as_str())
.map(|w| w.to_string()),
command: toml_keymap
.get("command")
.and_then(|c| c.as_str())
.map(|w| w.trim().to_string())
.unwrap_or_default(),
}))
}
}
fn get_modes(toml_keymap: &toml_edit::Table) -> Modes {
toml_keymap
.get("mode")
.and_then(|v| v.as_str())
.map(Modes::parse)
.unwrap_or_else(Modes::empty)
}
#[cfg(test)]
mod tests {
use floem::keyboard::Key;
use super::*;
use crate::keypress::keymap::KeyMapKey;
#[test]
fn test_keymap() {
let keymaps = r#"
[[keymaps]]
key = "ctrl+w l l"
command = "right"
when = "n"
[[keymaps]]
key = "ctrl+w l"
command = "right"
when = "n"
[[keymaps]]
key = "ctrl+w h"
command = "left"
when = "n"
[[keymaps]]
key = "ctrl+w"
command = "left"
when = "n"
[[keymaps]]
key = "End"
command = "line_end"
when = "n"
[[keymaps]]
key = "shift+i"
command = "insert_first_non_blank"
when = "n"
[[keymaps]]
key = "MouseForward"
command = "jump_location_forward"
[[keymaps]]
key = "MouseBackward"
command = "jump_location_backward"
[[keymaps]]
key = "Ctrl+MouseMiddle"
command = "goto_definition"
"#;
let mut loader = KeyMapLoader::new();
loader.load_from_str(keymaps, true).unwrap();
let (keymaps, _) = loader.finalize();
// Lower case modifiers
let keypress = KeyMapPress::parse("ctrl+w");
assert_eq!(keymaps.get(&keypress).unwrap().len(), 4);
let keypress = KeyMapPress::parse("ctrl+w l");
assert_eq!(keymaps.get(&keypress).unwrap().len(), 2);
let keypress = KeyMapPress::parse("ctrl+w h");
assert_eq!(keymaps.get(&keypress).unwrap().len(), 1);
let keypress = KeyMapPress::parse("ctrl+w l l");
assert_eq!(keymaps.get(&keypress).unwrap().len(), 1);
let keypress = KeyMapPress::parse("end");
assert_eq!(keymaps.get(&keypress).unwrap().len(), 1);
// Upper case modifiers
let keypress = KeyMapPress::parse("Ctrl+w");
assert_eq!(keymaps.get(&keypress).unwrap().len(), 4);
let keypress = KeyMapPress::parse("Ctrl+w l");
assert_eq!(keymaps.get(&keypress).unwrap().len(), 2);
let keypress = KeyMapPress::parse("Ctrl+w h");
assert_eq!(keymaps.get(&keypress).unwrap().len(), 1);
let keypress = KeyMapPress::parse("Ctrl+w l l");
assert_eq!(keymaps.get(&keypress).unwrap().len(), 1);
let keypress = KeyMapPress::parse("End");
assert_eq!(keymaps.get(&keypress).unwrap().len(), 1);
// No modifier
let keypress = KeyMapPress::parse("shift+i");
assert_eq!(keymaps.get(&keypress).unwrap().len(), 1);
// Mouse keys
let keypress = KeyMapPress::parse("MouseForward");
assert_eq!(keymaps.get(&keypress).unwrap().len(), 1);
let keypress = KeyMapPress::parse("mousebackward");
assert_eq!(keymaps.get(&keypress).unwrap().len(), 1);
let keypress = KeyMapPress::parse("Ctrl+MouseMiddle");
assert_eq!(keymaps.get(&keypress).unwrap().len(), 1);
let keypress = KeyMapPress::parse("Ctrl++");
assert_eq!(
keypress[0].key,
KeyMapKey::Logical(Key::Character("+".into()))
);
let keypress = KeyMapPress::parse("+");
assert_eq!(
keypress[0].key,
KeyMapKey::Logical(Key::Character("+".into()))
);
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/keypress/keymap.rs | lapce-app/src/keypress/keymap.rs | use std::{fmt::Display, str::FromStr};
use floem::{
keyboard::{Key, KeyCode, Modifiers, NamedKey, PhysicalKey},
pointer::{MouseButton, PointerButton},
};
use lapce_core::mode::Modes;
#[derive(PartialEq, Debug, Clone)]
pub enum KeymapMatch {
Full(String),
Multiple(Vec<String>),
Prefix,
None,
}
#[derive(PartialEq, Eq, Hash, Clone, Debug)]
pub struct KeyMap {
pub key: Vec<KeyMapPress>,
pub modes: Modes,
pub when: Option<String>,
pub command: String,
}
#[derive(PartialEq, Eq, Clone, Debug)]
pub enum KeyMapKey {
Pointer(PointerButton),
Logical(Key),
Physical(PhysicalKey),
}
impl std::hash::Hash for KeyMapKey {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
match self {
Self::Pointer(btn) => (btn.mouse_button() as u8).hash(state),
Self::Logical(key) => key.hash(state),
Self::Physical(physical) => physical.hash(state),
}
}
}
#[derive(PartialEq, Eq, Hash, Clone, Debug)]
pub struct KeyMapPress {
pub key: KeyMapKey,
pub mods: Modifiers,
}
impl KeyMapPress {
pub fn is_char(&self) -> bool {
let mut mods = self.mods;
mods.set(Modifiers::SHIFT, false);
if mods.is_empty() {
if let KeyMapKey::Logical(Key::Character(_)) = &self.key {
return true;
}
}
false
}
pub fn is_modifiers(&self) -> bool {
if let KeyMapKey::Physical(physical) = &self.key {
matches!(
physical,
PhysicalKey::Code(KeyCode::Meta)
| PhysicalKey::Code(KeyCode::SuperLeft)
| PhysicalKey::Code(KeyCode::SuperRight)
| PhysicalKey::Code(KeyCode::ShiftLeft)
| PhysicalKey::Code(KeyCode::ShiftRight)
| PhysicalKey::Code(KeyCode::ControlLeft)
| PhysicalKey::Code(KeyCode::ControlRight)
| PhysicalKey::Code(KeyCode::AltLeft)
| PhysicalKey::Code(KeyCode::AltRight)
)
} else if let KeyMapKey::Logical(Key::Named(key)) = &self.key {
matches!(
key,
NamedKey::Meta
| NamedKey::Super
| NamedKey::Shift
| NamedKey::Control
| NamedKey::Alt
| NamedKey::AltGraph
)
} else {
false
}
}
pub fn label(&self) -> String {
let mut keys = String::from("");
if self.mods.control() {
keys.push_str("Ctrl+");
}
if self.mods.alt() {
keys.push_str("Alt+");
}
if self.mods.altgr() {
keys.push_str("AltGr+");
}
if self.mods.meta() {
let keyname = match std::env::consts::OS {
"macos" => "Cmd+",
"windows" => "Win+",
_ => "Meta+",
};
keys.push_str(keyname);
}
if self.mods.shift() {
keys.push_str("Shift+");
}
keys.push_str(&self.key.to_string());
keys
}
pub fn parse(key: &str) -> Vec<Self> {
key.split(' ')
.filter_map(|k| {
let (modifiers, key) = if k == "+" {
("", "+")
} else if let Some(remaining) = k.strip_suffix("++") {
(remaining, "+")
} else {
match k.rsplit_once('+') {
Some(pair) => pair,
None => ("", k),
}
};
let key = match key.parse().ok() {
Some(key) => key,
None => {
// Skip past unrecognized key definitions
tracing::warn!("Unrecognized key: {key}");
return None;
}
};
let mut mods = Modifiers::empty();
for part in modifiers.to_lowercase().split('+') {
match part {
"ctrl" => mods.set(Modifiers::CONTROL, true),
"meta" => mods.set(Modifiers::META, true),
"shift" => mods.set(Modifiers::SHIFT, true),
"alt" => mods.set(Modifiers::ALT, true),
"altgr" => mods.set(Modifiers::ALTGR, true),
"" => (),
other => tracing::warn!("Invalid key modifier: {}", other),
}
}
Some(KeyMapPress { key, mods })
})
.collect()
}
}
impl FromStr for KeyMapKey {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let key = if s.starts_with('[') && s.ends_with(']') {
let code = match s[1..s.len() - 2].to_lowercase().as_str() {
"esc" => KeyCode::Escape,
"space" => KeyCode::Space,
"bs" => KeyCode::Backspace,
"up" => KeyCode::ArrowUp,
"down" => KeyCode::ArrowDown,
"left" => KeyCode::ArrowLeft,
"right" => KeyCode::ArrowRight,
"del" => KeyCode::Delete,
"alt" => KeyCode::AltLeft,
"altgraph" => KeyCode::AltRight,
"capslock" => KeyCode::CapsLock,
"control" => KeyCode::ControlLeft,
"fn" => KeyCode::Fn,
"fnlock" => KeyCode::FnLock,
"meta" => KeyCode::Meta,
"numlock" => KeyCode::NumLock,
"scrolllock" => KeyCode::ScrollLock,
"shift" => KeyCode::ShiftLeft,
"hyper" => KeyCode::Hyper,
"super" => KeyCode::Meta,
"enter" => KeyCode::Enter,
"tab" => KeyCode::Tab,
"arrowdown" => KeyCode::ArrowDown,
"arrowleft" => KeyCode::ArrowLeft,
"arrowright" => KeyCode::ArrowRight,
"arrowup" => KeyCode::ArrowUp,
"end" => KeyCode::End,
"home" => KeyCode::Home,
"pagedown" => KeyCode::PageDown,
"pageup" => KeyCode::PageUp,
"backspace" => KeyCode::Backspace,
"copy" => KeyCode::Copy,
"cut" => KeyCode::Cut,
"delete" => KeyCode::Delete,
"insert" => KeyCode::Insert,
"paste" => KeyCode::Paste,
"undo" => KeyCode::Undo,
"again" => KeyCode::Again,
"contextmenu" => KeyCode::ContextMenu,
"escape" => KeyCode::Escape,
"find" => KeyCode::Find,
"help" => KeyCode::Help,
"pause" => KeyCode::Pause,
"play" => KeyCode::MediaPlayPause,
"props" => KeyCode::Props,
"select" => KeyCode::Select,
"eject" => KeyCode::Eject,
"power" => KeyCode::Power,
"printscreen" => KeyCode::PrintScreen,
"wakeup" => KeyCode::WakeUp,
"convert" => KeyCode::Convert,
"nonconvert" => KeyCode::NonConvert,
"hiragana" => KeyCode::Hiragana,
"katakana" => KeyCode::Katakana,
"f1" => KeyCode::F1,
"f2" => KeyCode::F2,
"f3" => KeyCode::F3,
"f4" => KeyCode::F4,
"f5" => KeyCode::F5,
"f6" => KeyCode::F6,
"f7" => KeyCode::F7,
"f8" => KeyCode::F8,
"f9" => KeyCode::F9,
"f10" => KeyCode::F10,
"f11" => KeyCode::F11,
"f12" => KeyCode::F12,
"mediastop" => KeyCode::MediaStop,
"open" => KeyCode::Open,
_ => {
return Err(anyhow::anyhow!(
"unrecognized physical key code {}",
&s[1..s.len() - 2]
));
}
};
KeyMapKey::Physical(PhysicalKey::Code(code))
} else {
let key = match s.to_lowercase().as_str() {
"esc" => Key::Named(NamedKey::Escape),
"space" => Key::Named(NamedKey::Space),
"bs" => Key::Named(NamedKey::Backspace),
"up" => Key::Named(NamedKey::ArrowUp),
"down" => Key::Named(NamedKey::ArrowDown),
"left" => Key::Named(NamedKey::ArrowLeft),
"right" => Key::Named(NamedKey::ArrowRight),
"del" => Key::Named(NamedKey::Delete),
"alt" => Key::Named(NamedKey::Alt),
"altgraph" => Key::Named(NamedKey::AltGraph),
"capslock" => Key::Named(NamedKey::CapsLock),
"control" => Key::Named(NamedKey::Control),
"fn" => Key::Named(NamedKey::Fn),
"fnlock" => Key::Named(NamedKey::FnLock),
"meta" => Key::Named(NamedKey::Meta),
"numlock" => Key::Named(NamedKey::NumLock),
"scrolllock" => Key::Named(NamedKey::ScrollLock),
"shift" => Key::Named(NamedKey::Shift),
"hyper" => Key::Named(NamedKey::Hyper),
"super" => Key::Named(NamedKey::Meta),
"enter" => Key::Named(NamedKey::Enter),
"tab" => Key::Named(NamedKey::Tab),
"arrowdown" => Key::Named(NamedKey::ArrowDown),
"arrowleft" => Key::Named(NamedKey::ArrowLeft),
"arrowright" => Key::Named(NamedKey::ArrowRight),
"arrowup" => Key::Named(NamedKey::ArrowUp),
"end" => Key::Named(NamedKey::End),
"home" => Key::Named(NamedKey::Home),
"pagedown" => Key::Named(NamedKey::PageDown),
"pageup" => Key::Named(NamedKey::PageUp),
"backspace" => Key::Named(NamedKey::Backspace),
"copy" => Key::Named(NamedKey::Copy),
"cut" => Key::Named(NamedKey::Cut),
"delete" => Key::Named(NamedKey::Delete),
"insert" => Key::Named(NamedKey::Insert),
"paste" => Key::Named(NamedKey::Paste),
"undo" => Key::Named(NamedKey::Undo),
"again" => Key::Named(NamedKey::Again),
"contextmenu" => Key::Named(NamedKey::ContextMenu),
"escape" => Key::Named(NamedKey::Escape),
"find" => Key::Named(NamedKey::Find),
"help" => Key::Named(NamedKey::Help),
"pause" => Key::Named(NamedKey::Pause),
"play" => Key::Named(NamedKey::MediaPlayPause),
"props" => Key::Named(NamedKey::Props),
"select" => Key::Named(NamedKey::Select),
"eject" => Key::Named(NamedKey::Eject),
"power" => Key::Named(NamedKey::Power),
"printscreen" => Key::Named(NamedKey::PrintScreen),
"wakeup" => Key::Named(NamedKey::WakeUp),
"convert" => Key::Named(NamedKey::Convert),
"nonconvert" => Key::Named(NamedKey::NonConvert),
"hiragana" => Key::Named(NamedKey::Hiragana),
"katakana" => Key::Named(NamedKey::Katakana),
"f1" => Key::Named(NamedKey::F1),
"f2" => Key::Named(NamedKey::F2),
"f3" => Key::Named(NamedKey::F3),
"f4" => Key::Named(NamedKey::F4),
"f5" => Key::Named(NamedKey::F5),
"f6" => Key::Named(NamedKey::F6),
"f7" => Key::Named(NamedKey::F7),
"f8" => Key::Named(NamedKey::F8),
"f9" => Key::Named(NamedKey::F9),
"f10" => Key::Named(NamedKey::F10),
"f11" => Key::Named(NamedKey::F11),
"f12" => Key::Named(NamedKey::F12),
"mediastop" => Key::Named(NamedKey::MediaStop),
"open" => Key::Named(NamedKey::Open),
_ => Key::Character(s.to_lowercase().into()),
};
KeyMapKey::Logical(key)
};
Ok(key)
}
}
impl Display for KeyMapPress {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.mods.contains(Modifiers::CONTROL) {
if let Err(err) = f.write_str("Ctrl+") {
tracing::error!("{:?}", err);
}
}
if self.mods.contains(Modifiers::ALT) {
if let Err(err) = f.write_str("Alt+") {
tracing::error!("{:?}", err);
}
}
if self.mods.contains(Modifiers::ALTGR) {
if let Err(err) = f.write_str("AltGr+") {
tracing::error!("{:?}", err);
}
}
if self.mods.contains(Modifiers::META) {
if let Err(err) = f.write_str("Meta+") {
tracing::error!("{:?}", err);
}
}
if self.mods.contains(Modifiers::SHIFT) {
if let Err(err) = f.write_str("Shift+") {
tracing::error!("{:?}", err);
}
}
f.write_str(&self.key.to_string())
}
}
impl Display for KeyMapKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
use floem::pointer::PointerButton as B;
match self {
Self::Physical(physical) => {
f.write_str("[")?;
match physical {
PhysicalKey::Unidentified(_) => f.write_str("Unidentified"),
PhysicalKey::Code(KeyCode::Backquote) => {
f.write_str("Backquote")
}
PhysicalKey::Code(KeyCode::Backslash) => {
f.write_str("Backslash")
}
PhysicalKey::Code(KeyCode::BracketLeft) => {
f.write_str("BracketLeft")
}
PhysicalKey::Code(KeyCode::BracketRight) => {
f.write_str("BracketRight")
}
PhysicalKey::Code(KeyCode::Comma) => f.write_str("Comma"),
PhysicalKey::Code(KeyCode::Digit0) => f.write_str("0"),
PhysicalKey::Code(KeyCode::Digit1) => f.write_str("1"),
PhysicalKey::Code(KeyCode::Digit2) => f.write_str("2"),
PhysicalKey::Code(KeyCode::Digit3) => f.write_str("3"),
PhysicalKey::Code(KeyCode::Digit4) => f.write_str("4"),
PhysicalKey::Code(KeyCode::Digit5) => f.write_str("5"),
PhysicalKey::Code(KeyCode::Digit6) => f.write_str("6"),
PhysicalKey::Code(KeyCode::Digit7) => f.write_str("7"),
PhysicalKey::Code(KeyCode::Digit8) => f.write_str("8"),
PhysicalKey::Code(KeyCode::Digit9) => f.write_str("9"),
PhysicalKey::Code(KeyCode::Equal) => f.write_str("Equal"),
PhysicalKey::Code(KeyCode::IntlBackslash) => {
f.write_str("IntlBackslash")
}
PhysicalKey::Code(KeyCode::IntlRo) => f.write_str("IntlRo"),
PhysicalKey::Code(KeyCode::IntlYen) => f.write_str("IntlYen"),
PhysicalKey::Code(KeyCode::KeyA) => f.write_str("A"),
PhysicalKey::Code(KeyCode::KeyB) => f.write_str("B"),
PhysicalKey::Code(KeyCode::KeyC) => f.write_str("C"),
PhysicalKey::Code(KeyCode::KeyD) => f.write_str("D"),
PhysicalKey::Code(KeyCode::KeyE) => f.write_str("E"),
PhysicalKey::Code(KeyCode::KeyF) => f.write_str("F"),
PhysicalKey::Code(KeyCode::KeyG) => f.write_str("G"),
PhysicalKey::Code(KeyCode::KeyH) => f.write_str("H"),
PhysicalKey::Code(KeyCode::KeyI) => f.write_str("I"),
PhysicalKey::Code(KeyCode::KeyJ) => f.write_str("J"),
PhysicalKey::Code(KeyCode::KeyK) => f.write_str("K"),
PhysicalKey::Code(KeyCode::KeyL) => f.write_str("L"),
PhysicalKey::Code(KeyCode::KeyM) => f.write_str("M"),
PhysicalKey::Code(KeyCode::KeyN) => f.write_str("N"),
PhysicalKey::Code(KeyCode::KeyO) => f.write_str("O"),
PhysicalKey::Code(KeyCode::KeyP) => f.write_str("P"),
PhysicalKey::Code(KeyCode::KeyQ) => f.write_str("Q"),
PhysicalKey::Code(KeyCode::KeyR) => f.write_str("R"),
PhysicalKey::Code(KeyCode::KeyS) => f.write_str("S"),
PhysicalKey::Code(KeyCode::KeyT) => f.write_str("T"),
PhysicalKey::Code(KeyCode::KeyU) => f.write_str("U"),
PhysicalKey::Code(KeyCode::KeyV) => f.write_str("V"),
PhysicalKey::Code(KeyCode::KeyW) => f.write_str("W"),
PhysicalKey::Code(KeyCode::KeyX) => f.write_str("X"),
PhysicalKey::Code(KeyCode::KeyY) => f.write_str("Y"),
PhysicalKey::Code(KeyCode::KeyZ) => f.write_str("Z"),
PhysicalKey::Code(KeyCode::Minus) => f.write_str("Minus"),
PhysicalKey::Code(KeyCode::Period) => f.write_str("Period"),
PhysicalKey::Code(KeyCode::Quote) => f.write_str("Quote"),
PhysicalKey::Code(KeyCode::Semicolon) => {
f.write_str("Semicolon")
}
PhysicalKey::Code(KeyCode::Slash) => f.write_str("Slash"),
PhysicalKey::Code(KeyCode::AltLeft) => f.write_str("Alt"),
PhysicalKey::Code(KeyCode::AltRight) => f.write_str("Alt"),
PhysicalKey::Code(KeyCode::Backspace) => {
f.write_str("Backspace")
}
PhysicalKey::Code(KeyCode::CapsLock) => f.write_str("CapsLock"),
PhysicalKey::Code(KeyCode::ContextMenu) => {
f.write_str("ContextMenu")
}
PhysicalKey::Code(KeyCode::ControlLeft) => f.write_str("Ctrl"),
PhysicalKey::Code(KeyCode::ControlRight) => f.write_str("Ctrl"),
PhysicalKey::Code(KeyCode::Enter) => f.write_str("Enter"),
PhysicalKey::Code(KeyCode::SuperLeft) => f.write_str("Meta"),
PhysicalKey::Code(KeyCode::SuperRight) => f.write_str("Meta"),
PhysicalKey::Code(KeyCode::ShiftLeft) => f.write_str("Shift"),
PhysicalKey::Code(KeyCode::ShiftRight) => f.write_str("Shift"),
PhysicalKey::Code(KeyCode::Space) => f.write_str("Space"),
PhysicalKey::Code(KeyCode::Tab) => f.write_str("Tab"),
PhysicalKey::Code(KeyCode::Convert) => f.write_str("Convert"),
PhysicalKey::Code(KeyCode::KanaMode) => f.write_str("KanaMode"),
PhysicalKey::Code(KeyCode::Lang1) => f.write_str("Lang1"),
PhysicalKey::Code(KeyCode::Lang2) => f.write_str("Lang2"),
PhysicalKey::Code(KeyCode::Lang3) => f.write_str("Lang3"),
PhysicalKey::Code(KeyCode::Lang4) => f.write_str("Lang4"),
PhysicalKey::Code(KeyCode::Lang5) => f.write_str("Lang5"),
PhysicalKey::Code(KeyCode::NonConvert) => {
f.write_str("NonConvert")
}
PhysicalKey::Code(KeyCode::Delete) => f.write_str("Delete"),
PhysicalKey::Code(KeyCode::End) => f.write_str("End"),
PhysicalKey::Code(KeyCode::Help) => f.write_str("Help"),
PhysicalKey::Code(KeyCode::Home) => f.write_str("Home"),
PhysicalKey::Code(KeyCode::Insert) => f.write_str("Insert"),
PhysicalKey::Code(KeyCode::PageDown) => f.write_str("PageDown"),
PhysicalKey::Code(KeyCode::PageUp) => f.write_str("PageUp"),
PhysicalKey::Code(KeyCode::ArrowDown) => f.write_str("Down"),
PhysicalKey::Code(KeyCode::ArrowLeft) => f.write_str("Left"),
PhysicalKey::Code(KeyCode::ArrowRight) => f.write_str("Right"),
PhysicalKey::Code(KeyCode::ArrowUp) => f.write_str("Up"),
PhysicalKey::Code(KeyCode::NumLock) => f.write_str("NumLock"),
PhysicalKey::Code(KeyCode::Numpad0) => f.write_str("Numpad0"),
PhysicalKey::Code(KeyCode::Numpad1) => f.write_str("Numpad1"),
PhysicalKey::Code(KeyCode::Numpad2) => f.write_str("Numpad2"),
PhysicalKey::Code(KeyCode::Numpad3) => f.write_str("Numpad3"),
PhysicalKey::Code(KeyCode::Numpad4) => f.write_str("Numpad4"),
PhysicalKey::Code(KeyCode::Numpad5) => f.write_str("Numpad5"),
PhysicalKey::Code(KeyCode::Numpad6) => f.write_str("Numpad6"),
PhysicalKey::Code(KeyCode::Numpad7) => f.write_str("Numpad7"),
PhysicalKey::Code(KeyCode::Numpad8) => f.write_str("Numpad8"),
PhysicalKey::Code(KeyCode::Numpad9) => f.write_str("Numpad9"),
PhysicalKey::Code(KeyCode::NumpadAdd) => {
f.write_str("NumpadAdd")
}
PhysicalKey::Code(KeyCode::NumpadBackspace) => {
f.write_str("NumpadBackspace")
}
PhysicalKey::Code(KeyCode::NumpadClear) => {
f.write_str("NumpadClear")
}
PhysicalKey::Code(KeyCode::NumpadClearEntry) => {
f.write_str("NumpadClearEntry")
}
PhysicalKey::Code(KeyCode::NumpadComma) => {
f.write_str("NumpadComma")
}
PhysicalKey::Code(KeyCode::NumpadDecimal) => {
f.write_str("NumpadDecimal")
}
PhysicalKey::Code(KeyCode::NumpadDivide) => {
f.write_str("NumpadDivide")
}
PhysicalKey::Code(KeyCode::NumpadEnter) => {
f.write_str("NumpadEnter")
}
PhysicalKey::Code(KeyCode::NumpadEqual) => {
f.write_str("NumpadEqual")
}
PhysicalKey::Code(KeyCode::NumpadHash) => {
f.write_str("NumpadHash")
}
PhysicalKey::Code(KeyCode::NumpadMemoryAdd) => {
f.write_str("NumpadMemoryAdd")
}
PhysicalKey::Code(KeyCode::NumpadMemoryClear) => {
f.write_str("NumpadMemoryClear")
}
PhysicalKey::Code(KeyCode::NumpadMemoryRecall) => {
f.write_str("NumpadMemoryRecall")
}
PhysicalKey::Code(KeyCode::NumpadMemoryStore) => {
f.write_str("NumpadMemoryStore")
}
PhysicalKey::Code(KeyCode::NumpadMemorySubtract) => {
f.write_str("NumpadMemorySubtract")
}
PhysicalKey::Code(KeyCode::NumpadMultiply) => {
f.write_str("NumpadMultiply")
}
PhysicalKey::Code(KeyCode::NumpadParenLeft) => {
f.write_str("NumpadParenLeft")
}
PhysicalKey::Code(KeyCode::NumpadParenRight) => {
f.write_str("NumpadParenRight")
}
PhysicalKey::Code(KeyCode::NumpadStar) => {
f.write_str("NumpadStar")
}
PhysicalKey::Code(KeyCode::NumpadSubtract) => {
f.write_str("NumpadSubtract")
}
PhysicalKey::Code(KeyCode::Escape) => f.write_str("Escape"),
PhysicalKey::Code(KeyCode::Fn) => f.write_str("Fn"),
PhysicalKey::Code(KeyCode::FnLock) => f.write_str("FnLock"),
PhysicalKey::Code(KeyCode::PrintScreen) => {
f.write_str("PrintScreen")
}
PhysicalKey::Code(KeyCode::ScrollLock) => {
f.write_str("ScrollLock")
}
PhysicalKey::Code(KeyCode::Pause) => f.write_str("Pause"),
PhysicalKey::Code(KeyCode::BrowserBack) => {
f.write_str("BrowserBack")
}
PhysicalKey::Code(KeyCode::BrowserFavorites) => {
f.write_str("BrowserFavorites")
}
PhysicalKey::Code(KeyCode::BrowserForward) => {
f.write_str("BrowserForward")
}
PhysicalKey::Code(KeyCode::BrowserHome) => {
f.write_str("BrowserHome")
}
PhysicalKey::Code(KeyCode::BrowserRefresh) => {
f.write_str("BrowserRefresh")
}
PhysicalKey::Code(KeyCode::BrowserSearch) => {
f.write_str("BrowserSearch")
}
PhysicalKey::Code(KeyCode::BrowserStop) => {
f.write_str("BrowserStop")
}
PhysicalKey::Code(KeyCode::Eject) => f.write_str("Eject"),
PhysicalKey::Code(KeyCode::LaunchApp1) => {
f.write_str("LaunchApp1")
}
PhysicalKey::Code(KeyCode::LaunchApp2) => {
f.write_str("LaunchApp2")
}
PhysicalKey::Code(KeyCode::LaunchMail) => {
f.write_str("LaunchMail")
}
PhysicalKey::Code(KeyCode::MediaPlayPause) => {
f.write_str("MediaPlayPause")
}
PhysicalKey::Code(KeyCode::MediaSelect) => {
f.write_str("MediaSelect")
}
PhysicalKey::Code(KeyCode::MediaStop) => {
f.write_str("MediaStop")
}
PhysicalKey::Code(KeyCode::MediaTrackNext) => {
f.write_str("MediaTrackNext")
}
PhysicalKey::Code(KeyCode::MediaTrackPrevious) => {
f.write_str("MediaTrackPrevious")
}
PhysicalKey::Code(KeyCode::Power) => f.write_str("Power"),
PhysicalKey::Code(KeyCode::Sleep) => f.write_str("Sleep"),
PhysicalKey::Code(KeyCode::AudioVolumeDown) => {
f.write_str("AudioVolumeDown")
}
PhysicalKey::Code(KeyCode::AudioVolumeMute) => {
f.write_str("AudioVolumeMute")
}
PhysicalKey::Code(KeyCode::AudioVolumeUp) => {
f.write_str("AudioVolumeUp")
}
PhysicalKey::Code(KeyCode::WakeUp) => f.write_str("WakeUp"),
PhysicalKey::Code(KeyCode::Meta) => match std::env::consts::OS {
"macos" => f.write_str("Cmd"),
"windows" => f.write_str("Win"),
_ => f.write_str("Meta"),
},
PhysicalKey::Code(KeyCode::Hyper) => f.write_str("Hyper"),
PhysicalKey::Code(KeyCode::Turbo) => f.write_str("Turbo"),
PhysicalKey::Code(KeyCode::Abort) => f.write_str("Abort"),
PhysicalKey::Code(KeyCode::Resume) => f.write_str("Resume"),
PhysicalKey::Code(KeyCode::Suspend) => f.write_str("Suspend"),
PhysicalKey::Code(KeyCode::Again) => f.write_str("Again"),
PhysicalKey::Code(KeyCode::Copy) => f.write_str("Copy"),
PhysicalKey::Code(KeyCode::Cut) => f.write_str("Cut"),
PhysicalKey::Code(KeyCode::Find) => f.write_str("Find"),
PhysicalKey::Code(KeyCode::Open) => f.write_str("Open"),
PhysicalKey::Code(KeyCode::Paste) => f.write_str("Paste"),
PhysicalKey::Code(KeyCode::Props) => f.write_str("Props"),
PhysicalKey::Code(KeyCode::Select) => f.write_str("Select"),
PhysicalKey::Code(KeyCode::Undo) => f.write_str("Undo"),
PhysicalKey::Code(KeyCode::Hiragana) => f.write_str("Hiragana"),
PhysicalKey::Code(KeyCode::Katakana) => f.write_str("Katakana"),
PhysicalKey::Code(KeyCode::F1) => f.write_str("F1"),
PhysicalKey::Code(KeyCode::F2) => f.write_str("F2"),
PhysicalKey::Code(KeyCode::F3) => f.write_str("F3"),
PhysicalKey::Code(KeyCode::F4) => f.write_str("F4"),
PhysicalKey::Code(KeyCode::F5) => f.write_str("F5"),
PhysicalKey::Code(KeyCode::F6) => f.write_str("F6"),
PhysicalKey::Code(KeyCode::F7) => f.write_str("F7"),
PhysicalKey::Code(KeyCode::F8) => f.write_str("F8"),
PhysicalKey::Code(KeyCode::F9) => f.write_str("F9"),
PhysicalKey::Code(KeyCode::F10) => f.write_str("F10"),
PhysicalKey::Code(KeyCode::F11) => f.write_str("F11"),
PhysicalKey::Code(KeyCode::F12) => f.write_str("F12"),
PhysicalKey::Code(KeyCode::F13) => f.write_str("F13"),
PhysicalKey::Code(KeyCode::F14) => f.write_str("F14"),
PhysicalKey::Code(KeyCode::F15) => f.write_str("F15"),
PhysicalKey::Code(KeyCode::F16) => f.write_str("F16"),
PhysicalKey::Code(KeyCode::F17) => f.write_str("F17"),
PhysicalKey::Code(KeyCode::F18) => f.write_str("F18"),
PhysicalKey::Code(KeyCode::F19) => f.write_str("F19"),
PhysicalKey::Code(KeyCode::F20) => f.write_str("F20"),
PhysicalKey::Code(KeyCode::F21) => f.write_str("F21"),
PhysicalKey::Code(KeyCode::F22) => f.write_str("F22"),
PhysicalKey::Code(KeyCode::F23) => f.write_str("F23"),
PhysicalKey::Code(KeyCode::F24) => f.write_str("F24"),
PhysicalKey::Code(KeyCode::F25) => f.write_str("F25"),
PhysicalKey::Code(KeyCode::F26) => f.write_str("F26"),
PhysicalKey::Code(KeyCode::F27) => f.write_str("F27"),
PhysicalKey::Code(KeyCode::F28) => f.write_str("F28"),
PhysicalKey::Code(KeyCode::F29) => f.write_str("F29"),
PhysicalKey::Code(KeyCode::F30) => f.write_str("F30"),
PhysicalKey::Code(KeyCode::F31) => f.write_str("F31"),
PhysicalKey::Code(KeyCode::F32) => f.write_str("F32"),
PhysicalKey::Code(KeyCode::F33) => f.write_str("F33"),
PhysicalKey::Code(KeyCode::F34) => f.write_str("F34"),
PhysicalKey::Code(KeyCode::F35) => f.write_str("F35"),
_ => f.write_str("Unidentified"),
}?;
f.write_str("]")
}
Self::Logical(key) => match key {
Key::Named(key) => match key {
NamedKey::Backspace => f.write_str("Backspace"),
NamedKey::CapsLock => f.write_str("CapsLock"),
NamedKey::Enter => f.write_str("Enter"),
NamedKey::Delete => f.write_str("Delete"),
NamedKey::End => f.write_str("End"),
NamedKey::Home => f.write_str("Home"),
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | true |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/palette/kind.rs | lapce-app/src/palette/kind.rs | use strum_macros::EnumIter;
use crate::command::LapceWorkbenchCommand;
#[derive(Clone, Copy, Debug, PartialEq, Eq, EnumIter)]
pub enum PaletteKind {
PaletteHelp,
File,
Line,
Command,
Workspace,
Reference,
DocumentSymbol,
WorkspaceSymbol,
SshHost,
#[cfg(windows)]
WslHost,
RunAndDebug,
ColorTheme,
IconTheme,
Language,
LineEnding,
SCMReferences,
TerminalProfile,
DiffFiles,
HelpAndFile,
}
impl PaletteKind {
/// The symbol/prefix that is used to signify the behavior of the palette.
pub fn symbol(&self) -> &'static str {
match &self {
PaletteKind::PaletteHelp => "?",
PaletteKind::Line => "/",
PaletteKind::DocumentSymbol => "@",
PaletteKind::WorkspaceSymbol => "#",
// PaletteKind::GlobalSearch => "?",
PaletteKind::Workspace => ">",
PaletteKind::Command => ":",
PaletteKind::TerminalProfile => "<",
PaletteKind::File
| PaletteKind::Reference
| PaletteKind::SshHost
| PaletteKind::RunAndDebug
| PaletteKind::ColorTheme
| PaletteKind::IconTheme
| PaletteKind::Language
| PaletteKind::LineEnding
| PaletteKind::SCMReferences
| PaletteKind::HelpAndFile
| PaletteKind::DiffFiles => "",
#[cfg(windows)]
PaletteKind::WslHost => "",
}
}
/// Extract the palette kind from the input string. This is most often a prefix.
pub fn from_input(input: &str) -> PaletteKind {
match input {
_ if input.starts_with('?') => PaletteKind::PaletteHelp,
_ if input.starts_with('/') => PaletteKind::Line,
_ if input.starts_with('@') => PaletteKind::DocumentSymbol,
_ if input.starts_with('#') => PaletteKind::WorkspaceSymbol,
_ if input.starts_with('>') => PaletteKind::Workspace,
_ if input.starts_with(':') => PaletteKind::Command,
_ if input.starts_with('<') => PaletteKind::TerminalProfile,
_ => PaletteKind::File,
}
}
/// Get the [`LapceWorkbenchCommand`] that opens this palette kind, if one exists.
pub fn command(self) -> Option<LapceWorkbenchCommand> {
match self {
PaletteKind::PaletteHelp => Some(LapceWorkbenchCommand::PaletteHelp),
PaletteKind::Line => Some(LapceWorkbenchCommand::PaletteLine),
PaletteKind::DocumentSymbol => {
Some(LapceWorkbenchCommand::PaletteSymbol)
}
PaletteKind::WorkspaceSymbol => {
Some(LapceWorkbenchCommand::PaletteWorkspaceSymbol)
}
PaletteKind::Workspace => Some(LapceWorkbenchCommand::PaletteWorkspace),
PaletteKind::Command => Some(LapceWorkbenchCommand::PaletteCommand),
PaletteKind::File => Some(LapceWorkbenchCommand::Palette),
PaletteKind::HelpAndFile => {
Some(LapceWorkbenchCommand::PaletteHelpAndFile)
}
PaletteKind::Reference => None, // InternalCommand::PaletteReferences
PaletteKind::SshHost => Some(LapceWorkbenchCommand::ConnectSshHost),
#[cfg(windows)]
PaletteKind::WslHost => Some(LapceWorkbenchCommand::ConnectWslHost),
PaletteKind::RunAndDebug => {
Some(LapceWorkbenchCommand::PaletteRunAndDebug)
}
PaletteKind::ColorTheme => Some(LapceWorkbenchCommand::ChangeColorTheme),
PaletteKind::IconTheme => Some(LapceWorkbenchCommand::ChangeIconTheme),
PaletteKind::Language => Some(LapceWorkbenchCommand::ChangeFileLanguage),
PaletteKind::LineEnding => {
Some(LapceWorkbenchCommand::ChangeFileLineEnding)
}
PaletteKind::SCMReferences => {
Some(LapceWorkbenchCommand::PaletteSCMReferences)
}
PaletteKind::TerminalProfile => None, // InternalCommand::NewTerminal
PaletteKind::DiffFiles => Some(LapceWorkbenchCommand::DiffFiles),
}
}
// pub fn has_preview(&self) -> bool {
// matches!(
// self,
// PaletteType::Line
// | PaletteType::DocumentSymbol
// | PaletteType::WorkspaceSymbol
// | PaletteType::GlobalSearch
// | PaletteType::Reference
// )
// }
pub fn get_input<'a>(&self, input: &'a str) -> &'a str {
match self {
#[cfg(windows)]
PaletteKind::WslHost => input,
PaletteKind::File
| PaletteKind::Reference
| PaletteKind::SshHost
| PaletteKind::RunAndDebug
| PaletteKind::ColorTheme
| PaletteKind::IconTheme
| PaletteKind::Language
| PaletteKind::LineEnding
| PaletteKind::SCMReferences | PaletteKind::HelpAndFile
| PaletteKind::DiffFiles => input,
PaletteKind::PaletteHelp
| PaletteKind::Command
| PaletteKind::Workspace
| PaletteKind::DocumentSymbol
| PaletteKind::WorkspaceSymbol
| PaletteKind::Line
| PaletteKind::TerminalProfile
// | PaletteType::GlobalSearch
=> input.get(1..).unwrap_or(""),
}
}
/// Get the palette kind that it should be considered as based on the current
/// [`PaletteKind`] and the current input.
pub fn get_palette_kind(&self, input: &str) -> PaletteKind {
if self == &PaletteKind::HelpAndFile && input.is_empty() {
return *self;
}
if self != &PaletteKind::File
&& self != &PaletteKind::HelpAndFile
&& self.symbol() == ""
{
return *self;
}
PaletteKind::from_input(input)
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/palette/item.rs | lapce-app/src/palette/item.rs | use std::path::PathBuf;
use lapce_core::line_ending::LineEnding;
use lapce_rpc::dap_types::RunDebugConfig;
use lsp_types::{Range, SymbolKind};
use crate::{
command::{LapceCommand, LapceWorkbenchCommand},
debug::RunDebugMode,
editor::location::EditorLocation,
workspace::{LapceWorkspace, SshHost},
};
#[derive(Clone, Debug, PartialEq)]
pub struct PaletteItem {
pub content: PaletteItemContent,
pub filter_text: String,
pub score: u32,
pub indices: Vec<usize>,
}
#[derive(Clone, Debug, PartialEq)]
pub enum PaletteItemContent {
PaletteHelp {
cmd: LapceWorkbenchCommand,
},
File {
path: PathBuf,
full_path: PathBuf,
},
Line {
line: usize,
content: String,
},
Command {
cmd: LapceCommand,
},
Workspace {
workspace: LapceWorkspace,
},
Reference {
path: PathBuf,
location: EditorLocation,
},
DocumentSymbol {
kind: SymbolKind,
name: String,
range: Range,
container_name: Option<String>,
},
WorkspaceSymbol {
kind: SymbolKind,
name: String,
container_name: Option<String>,
location: EditorLocation,
},
SshHost {
host: SshHost,
},
#[cfg(windows)]
WslHost {
host: crate::workspace::WslHost,
},
RunAndDebug {
mode: RunDebugMode,
config: RunDebugConfig,
},
ColorTheme {
name: String,
},
IconTheme {
name: String,
},
Language {
name: String,
},
LineEnding {
kind: LineEnding,
},
SCMReference {
name: String,
},
TerminalProfile {
name: String,
profile: lapce_rpc::terminal::TerminalProfile,
},
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/app/grammars.rs | lapce-app/src/app/grammars.rs | use std::{
env,
fs::{self},
path::PathBuf,
};
use anyhow::{Context, Result, anyhow};
use lapce_core::directory::Directory;
use crate::{tracing::*, update::ReleaseInfo};
fn get_github_api(url: &str) -> Result<String> {
let user_agent = format!("Lapce/{}", lapce_core::meta::VERSION);
let resp = lapce_proxy::get_url(url, Some(user_agent.as_str()))?;
if !resp.status().is_success() {
return Err(anyhow!("get release info failed {}", resp.text()?));
}
Ok(resp.text()?)
}
pub fn find_grammar_release() -> Result<ReleaseInfo> {
let releases: Vec<ReleaseInfo> = serde_json::from_str(&get_github_api(
"https://api.github.com/repos/lapce/tree-sitter-grammars/releases?per_page=100",
).context("Failed to retrieve releases for tree-sitter-grammars")?)?;
use lapce_core::meta::{RELEASE, ReleaseType, VERSION};
let releases = releases
.into_iter()
.filter_map(|f| {
if matches!(RELEASE, ReleaseType::Debug | ReleaseType::Nightly) {
return Some(f);
}
let tag_name = if f.tag_name.starts_with('v') {
f.tag_name.trim_start_matches('v')
} else {
f.tag_name.as_str()
};
use std::cmp::Ordering;
use semver::Version;
let sv = Version::parse(tag_name).ok()?;
let version = Version::parse(VERSION).ok()?;
if matches!(sv.cmp_precedence(&version), Ordering::Equal) {
Some(f)
} else {
None
}
})
.collect::<Vec<_>>();
let Some(release) = releases.first() else {
return Err(anyhow!("Couldn't find any release"));
};
Ok(release.to_owned())
}
pub fn fetch_grammars(release: &ReleaseInfo) -> Result<bool> {
let dir = Directory::grammars_directory()
.ok_or_else(|| anyhow!("can't get grammars directory"))?;
let file_name = format!("grammars-{}-{}", env::consts::OS, env::consts::ARCH);
let updated = download_release(dir, release, &file_name)?;
trace!(TraceLevel::INFO, "Successfully downloaded grammars");
Ok(updated)
}
pub fn fetch_queries(release: &ReleaseInfo) -> Result<bool> {
let dir = Directory::queries_directory()
.ok_or_else(|| anyhow!("can't get queries directory"))?;
let file_name = "queries";
let updated = download_release(dir, release, file_name)?;
trace!(TraceLevel::INFO, "Successfully downloaded queries");
Ok(updated)
}
fn download_release(
dir: PathBuf,
release: &ReleaseInfo,
file_name: &str,
) -> Result<bool> {
if !dir.exists() {
fs::create_dir(&dir)?;
}
let current_version =
fs::read_to_string(dir.join("version")).unwrap_or_default();
let release_version = if release.tag_name == "nightly" {
format!("nightly-{}", &release.target_commitish[..7])
} else {
release.tag_name.clone()
};
if release_version == current_version {
return Ok(false);
}
for asset in &release.assets {
if asset.name.starts_with(file_name) {
let mut resp = lapce_proxy::get_url(&asset.browser_download_url, None)?;
if !resp.status().is_success() {
return Err(anyhow!("download file error {}", resp.text()?));
}
let file = tempfile::tempfile()?;
{
use std::io::{Seek, Write};
let file = &mut &file;
resp.copy_to(file)?;
file.flush()?;
file.rewind()?;
}
if asset.name.ends_with(".zip") {
let mut archive = zip::ZipArchive::new(file)?;
archive.extract(&dir)?;
} else if asset.name.ends_with(".tar.zst") {
let mut archive =
tar::Archive::new(zstd::stream::read::Decoder::new(file)?);
archive.unpack(&dir)?;
}
fs::write(dir.join("version"), &release_version)?;
}
}
Ok(true)
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/app/logging.rs | lapce-app/src/app/logging.rs | use lapce_core::directory::Directory;
use tracing::level_filters::LevelFilter;
use tracing_appender::non_blocking::WorkerGuard;
use tracing_subscriber::{filter::Targets, reload::Handle};
use crate::tracing::*;
#[inline(always)]
pub(super) fn logging() -> (Handle<Targets>, Option<WorkerGuard>) {
use tracing_subscriber::{filter, fmt, prelude::*, reload};
let (log_file, guard) = match Directory::logs_directory()
.and_then(|dir| {
tracing_appender::rolling::Builder::new()
.max_log_files(10)
.rotation(tracing_appender::rolling::Rotation::DAILY)
.filename_prefix("lapce")
.filename_suffix("log")
.build(dir)
.ok()
})
.map(tracing_appender::non_blocking)
{
Some((log_file, guard)) => (Some(log_file), Some(guard)),
None => (None, None),
};
let log_file_filter_targets = filter::Targets::new()
.with_target("lapce_app", LevelFilter::DEBUG)
.with_target("lapce_proxy", LevelFilter::DEBUG)
.with_target("lapce_core", LevelFilter::DEBUG)
.with_default(LevelFilter::from_level(TraceLevel::INFO));
let (log_file_filter, reload_handle) =
reload::Subscriber::new(log_file_filter_targets);
let console_filter_targets = std::env::var("LAPCE_LOG")
.unwrap_or_default()
.parse::<filter::Targets>()
.unwrap_or_default();
let registry = tracing_subscriber::registry();
if let Some(log_file) = log_file {
let file_layer = tracing_subscriber::fmt::subscriber()
.with_ansi(false)
.with_writer(log_file)
.with_filter(log_file_filter);
registry
.with(file_layer)
.with(
fmt::Subscriber::default()
.with_line_number(true)
.with_target(true)
.with_thread_names(true)
.with_filter(console_filter_targets),
)
.init();
} else {
registry
.with(fmt::Subscriber::default().with_filter(console_filter_targets))
.init();
};
(reload_handle, guard)
}
pub(super) fn panic_hook() {
std::panic::set_hook(Box::new(move |info| {
let thread = std::thread::current();
let thread = thread.name().unwrap_or("main");
let backtrace = backtrace::Backtrace::new();
let payload = if let Some(s) = info.payload().downcast_ref::<&str>() {
s
} else {
"<unknown>"
};
match info.location() {
Some(loc) => {
trace!(
target: "lapce_app::panic_hook",
TraceLevel::ERROR,
"thread {thread} panicked at {} | file://./{}:{}:{}\n{:?}",
payload,
loc.file(), loc.line(), loc.column(),
backtrace,
);
}
None => {
trace!(
target: "lapce_app::panic_hook",
TraceLevel::ERROR,
"thread {thread} panicked at {}\n{:?}",
payload,
backtrace,
);
}
}
#[cfg(windows)]
error_modal("Error", &info.to_string());
}))
}
#[cfg(windows)]
pub(super) fn error_modal(title: &str, msg: &str) -> i32 {
use std::{ffi::OsStr, iter::once, mem, os::windows::prelude::OsStrExt};
use windows::Win32::UI::WindowsAndMessaging::{
MB_ICONERROR, MB_SYSTEMMODAL, MessageBoxW,
};
let result: i32;
let title = OsStr::new(title)
.encode_wide()
.chain(once(0u16))
.collect::<Vec<u16>>();
let msg = OsStr::new(msg)
.encode_wide()
.chain(once(0u16))
.collect::<Vec<u16>>();
unsafe {
result = MessageBoxW(
mem::zeroed(),
msg.as_ptr(),
title.as_ptr(),
MB_ICONERROR | MB_SYSTEMMODAL,
);
}
result
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/proxy/remote.rs | lapce-app/src/proxy/remote.rs | use std::{
io::{BufReader, Write},
path::Path,
process::{Command, Stdio},
};
use anyhow::{Result, anyhow};
use flate2::read::GzDecoder;
use lapce_core::{
directory::Directory,
meta::{self, ReleaseType},
};
use lapce_rpc::{
RpcMessage,
core::CoreRpcHandler,
proxy::{ProxyRpc, ProxyRpcHandler},
stdio_transport,
};
use thiserror::Error;
use tracing::{debug, error};
const UNIX_PROXY_SCRIPT: &[u8] = include_bytes!("../../../extra/proxy.sh");
const WINDOWS_PROXY_SCRIPT: &[u8] = include_bytes!("../../../extra/proxy.ps1");
#[derive(Clone, Copy, Error, Debug, PartialEq, Eq, strum_macros::Display)]
#[strum(ascii_case_insensitive)]
enum HostPlatform {
UnknownOS,
#[strum(serialize = "windows")]
Windows,
#[strum(serialize = "linux")]
Linux,
#[strum(serialize = "darwin")]
Darwin,
#[strum(serialize = "bsd")]
Bsd,
}
/// serialise via strum to arch name that is used
/// in CI artefacts
#[derive(Clone, Copy, Error, Debug, PartialEq, Eq, strum_macros::Display)]
#[strum(ascii_case_insensitive)]
enum HostArchitecture {
UnknownArch,
#[strum(serialize = "x86_64")]
AMD64,
#[strum(serialize = "x86")]
X86,
#[strum(serialize = "aarch64")]
ARM64,
#[strum(serialize = "armv7")]
ARM32v7,
#[strum(serialize = "armhf")]
ARM32v6,
}
pub trait Remote: Sized {
#[allow(unused)]
fn home_dir(&self) -> Result<String> {
let cmd = self
.command_builder()
.arg("echo")
.arg("-n")
.arg("$HOME")
.stdout(Stdio::piped())
.output()?;
Ok(String::from_utf8(cmd.stdout)?)
}
fn upload_file(&self, local: impl AsRef<Path>, remote: &str) -> Result<()>;
fn command_builder(&self) -> Command;
}
pub fn start_remote(
remote: impl Remote,
core_rpc: CoreRpcHandler,
proxy_rpc: ProxyRpcHandler,
) -> Result<()> {
// Note about platforms:
// Windows can use either cmd.exe, powershell.exe or pwsh.exe as
// SSH shell, syntax logic varies significantly that's why we bet on
// cmd.exe as it doesn't add unwanted newlines and use powershell only
// for proxy install
//
// Unix-like systems due to POSIX, always have /bin/sh which should not
// be necessary to use explicitly most of the time, as many wide-spread
// shells retain similar syntax, although shells like Nushell might not
// work (hopefully no one uses it as login shell)
use HostPlatform::*;
let (platform, architecture) = host_specification(&remote).unwrap();
if platform == UnknownOS || architecture == HostArchitecture::UnknownArch {
error!("detected remote host: {platform}/{architecture}");
return Err(anyhow!("Unknown OS and/or architecture"));
}
// ! Below paths have to be synced with what is
// ! returned by Config::proxy_directory()
let remote_proxy_path = match platform {
Windows => format!(
"%HOMEDRIVE%%HOMEPATH%\\AppData\\Local\\lapce\\{}\\data\\proxy",
meta::NAME
),
Darwin => format!(
"~/Library/Application\\ Support/dev.lapce.{}/proxy",
meta::NAME
),
_ => {
format!("~/.local/share/{}/proxy", meta::NAME.to_lowercase())
}
};
let remote_proxy_file = match platform {
Windows => format!("{remote_proxy_path}\\lapce.exe"),
_ => format!("{remote_proxy_path}/lapce"),
};
if !remote
.command_builder()
.args([&remote_proxy_file, "--version"])
.output()
.map(|output| {
if meta::RELEASE == ReleaseType::Debug {
String::from_utf8_lossy(&output.stdout).starts_with("Lapce-proxy")
} else {
String::from_utf8_lossy(&output.stdout).trim()
== format!("Lapce-proxy {}", meta::VERSION)
}
})
.unwrap_or(false)
{
download_remote(
&remote,
&platform,
&architecture,
&remote_proxy_path,
&remote_proxy_file,
)?;
};
debug!("remote proxy path: {remote_proxy_path}");
let mut child = match platform {
// Force cmd.exe usage to resolve %envvar% variables
Windows => remote
.command_builder()
.args(["cmd", "/c"])
.arg(&remote_proxy_file)
.arg("--proxy")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()?,
_ => remote
.command_builder()
.arg(&remote_proxy_file)
.arg("--proxy")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()?,
};
let stdin = child
.stdin
.take()
.ok_or_else(|| anyhow!("can't find stdin"))?;
let stdout = BufReader::new(
child
.stdout
.take()
.ok_or_else(|| anyhow!("can't find stdout"))?,
);
debug!("process id: {}", child.id());
let (writer_tx, writer_rx) = crossbeam_channel::unbounded();
let (reader_tx, reader_rx) = crossbeam_channel::unbounded();
stdio_transport(stdin, writer_rx, stdout, reader_tx);
let local_proxy_rpc = proxy_rpc.clone();
let local_writer_tx = writer_tx.clone();
std::thread::Builder::new()
.name("ProxyRpcHandler".to_owned())
.spawn(move || {
for msg in local_proxy_rpc.rx() {
match msg {
ProxyRpc::Request(id, rpc) => {
if let Err(err) =
local_writer_tx.send(RpcMessage::Request(id, rpc))
{
tracing::error!("{:?}", err);
}
}
ProxyRpc::Notification(rpc) => {
if let Err(err) =
local_writer_tx.send(RpcMessage::Notification(rpc))
{
tracing::error!("{:?}", err);
}
}
ProxyRpc::Shutdown => {
if let Err(err) = child.kill() {
tracing::error!("{:?}", err);
}
if let Err(err) = child.wait() {
tracing::error!("{:?}", err);
}
return;
}
}
}
})
.unwrap();
for msg in reader_rx {
match msg {
RpcMessage::Request(id, req) => {
let writer_tx = writer_tx.clone();
let core_rpc = core_rpc.clone();
std::thread::spawn(move || match core_rpc.request(req) {
Ok(resp) => {
if let Err(err) =
writer_tx.send(RpcMessage::Response(id, resp))
{
tracing::error!("{:?}", err);
}
}
Err(e) => {
if let Err(err) = writer_tx.send(RpcMessage::Error(id, e)) {
tracing::error!("{:?}", err);
}
}
});
}
RpcMessage::Notification(n) => {
core_rpc.notification(n);
}
RpcMessage::Response(id, resp) => {
proxy_rpc.handle_response(id, Ok(resp));
}
RpcMessage::Error(id, err) => {
proxy_rpc.handle_response(id, Err(err));
}
}
}
Ok(())
}
fn download_remote(
remote: &impl Remote,
platform: &HostPlatform,
architecture: &HostArchitecture,
remote_proxy_path: &str,
remote_proxy_file: &str,
) -> Result<()> {
use base64::{Engine as _, engine::general_purpose};
let script_install = match platform {
HostPlatform::Windows => {
let local_proxy_script =
Directory::proxy_directory().unwrap().join("proxy.ps1");
let mut proxy_script = std::fs::OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.open(&local_proxy_script)?;
proxy_script.write_all(WINDOWS_PROXY_SCRIPT)?;
let remote_proxy_script = "${env:TEMP}\\lapce-proxy.ps1";
remote.upload_file(local_proxy_script, remote_proxy_script)?;
let cmd = remote
.command_builder()
.args([
"powershell",
"-c",
remote_proxy_script,
"-version",
meta::VERSION,
"-directory",
remote_proxy_path,
])
.output()?;
debug!("{}", String::from_utf8_lossy(&cmd.stderr));
debug!("{}", String::from_utf8_lossy(&cmd.stdout));
cmd.status
}
_ => {
let proxy_script = general_purpose::STANDARD.encode(UNIX_PROXY_SCRIPT);
let version = match meta::RELEASE {
ReleaseType::Debug => "nightly".to_string(),
ReleaseType::Nightly => "nightly".to_string(),
ReleaseType::Stable => format!("v{}", meta::VERSION),
};
let cmd = remote
.command_builder()
.args([
"echo",
&proxy_script,
"|",
"base64",
"-d",
"|",
"sh",
"/dev/stdin",
&version,
remote_proxy_path,
])
.output()?;
debug!("{}", String::from_utf8_lossy(&cmd.stderr));
debug!("{}", String::from_utf8_lossy(&cmd.stdout));
cmd.status
}
};
if !script_install.success() {
let cmd = match platform {
HostPlatform::Windows => remote
.command_builder()
.args(["dir", remote_proxy_file])
.status()?,
_ => remote
.command_builder()
.arg("test")
.arg("-e")
.arg(remote_proxy_file)
.status()?,
};
if !cmd.success() {
let proxy_filename = format!("lapce-proxy-{platform}-{architecture}");
let local_proxy_file = Directory::proxy_directory()
.ok_or_else(|| anyhow!("can't find proxy directory"))?
.join(&proxy_filename);
// remove possibly outdated proxy
if local_proxy_file.exists() {
// TODO: add proper proxy version detection and update proxy
// when needed
std::fs::remove_file(&local_proxy_file)?;
}
let proxy_version = match meta::RELEASE {
meta::ReleaseType::Stable => meta::VERSION,
_ => "nightly",
};
let url = format!(
"https://github.com/lapce/lapce/releases/download/{proxy_version}/{proxy_filename}.gz"
);
debug!("proxy download URI: {url}");
let mut resp = lapce_proxy::get_url(url, None).expect("request failed");
if resp.status().is_success() {
let mut out = std::fs::File::create(&local_proxy_file)
.expect("failed to create file");
let mut gz = GzDecoder::new(&mut resp);
std::io::copy(&mut gz, &mut out).expect("failed to copy content");
} else {
error!("proxy download failed with: {}", resp.status());
}
match platform {
// Windows creates all dirs in provided path
HostPlatform::Windows => remote
.command_builder()
.arg("mkdir")
.arg(remote_proxy_path)
.status()?,
// Unix needs -p to do same
_ => remote
.command_builder()
.arg("mkdir")
.arg("-p")
.arg(remote_proxy_path)
.status()?,
};
remote.upload_file(&local_proxy_file, remote_proxy_file)?;
if platform != &HostPlatform::Windows {
remote
.command_builder()
.arg("chmod")
.arg("+x")
.arg(remote_proxy_file)
.status()?;
}
}
}
Ok(())
}
fn host_specification(
remote: &impl Remote,
) -> Result<(HostPlatform, HostArchitecture)> {
use HostArchitecture::*;
use HostPlatform::*;
let cmd = remote.command_builder().args(["uname", "-sm"]).output();
let spec = match cmd {
Ok(cmd) => {
let stdout = String::from_utf8_lossy(&cmd.stdout).to_lowercase();
let stdout = stdout.trim();
debug!("{}", &stdout);
match stdout {
// If empty, then we probably deal with Windows and not Unix
// or something went wrong with command output
"" => {
// Try cmd explicitly
let cmd = remote
.command_builder()
.args(["cmd", "/c", "echo %OS% %PROCESSOR_ARCHITECTURE%"])
.output();
match cmd {
Ok(cmd) => {
let stdout =
String::from_utf8_lossy(&cmd.stdout).to_lowercase();
let stdout = stdout.trim();
debug!("{}", &stdout);
match stdout.split_once(' ') {
Some((os, arch)) => (parse_os(os), parse_arch(arch)),
None => {
// PowerShell fallback
let cmd = remote
.command_builder()
.args(["echo", "\"${env:OS} ${env:PROCESSOR_ARCHITECTURE}\""])
.output();
match cmd {
Ok(cmd) => {
let stdout =
String::from_utf8_lossy(&cmd.stdout)
.to_lowercase();
let stdout = stdout.trim();
debug!("{}", &stdout);
match stdout.split_once(' ') {
Some((os, arch)) => {
(parse_os(os), parse_arch(arch))
}
None => (UnknownOS, UnknownArch),
}
}
Err(e) => {
error!("{e}");
(UnknownOS, UnknownArch)
}
}
}
}
}
Err(e) => {
error!("{e}");
(UnknownOS, UnknownArch)
}
}
}
v => {
if let Some((os, arch)) = v.split_once(' ') {
(parse_os(os), parse_arch(arch))
} else {
(UnknownOS, UnknownArch)
}
}
}
}
Err(e) => {
error!("{e}");
(UnknownOS, UnknownArch)
}
};
Ok(spec)
}
fn parse_arch(arch: &str) -> HostArchitecture {
use HostArchitecture::*;
// processor architectures be like that
match arch {
"amd64" | "x64" | "x86_64" => AMD64,
"x86" | "i386" | "i586" | "i686" => X86,
"arm" | "armhf" | "armv6" => ARM32v6,
"armv7" | "armv7l" => ARM32v7,
"arm64" | "armv8" | "aarch64" => ARM64,
_ => UnknownArch,
}
}
fn parse_os(os: &str) -> HostPlatform {
use HostPlatform::*;
match os {
"linux" => Linux,
"darwin" => Darwin,
"windows_nt" => Windows,
v if v.ends_with("bsd") => Bsd,
_ => UnknownOS,
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/proxy/wsl.rs | lapce-app/src/proxy/wsl.rs | use std::{path::Path, process::Command};
use anyhow::Result;
use super::{new_command, remote::Remote};
use crate::workspace::WslHost;
pub struct WslRemote {
pub wsl: WslHost,
}
impl Remote for WslRemote {
fn upload_file(&self, local: impl AsRef<Path>, remote: &str) -> Result<()> {
let mut wsl_path = Path::new(r"\\wsl.localhost\").join(&self.wsl.host);
if !wsl_path.exists() {
wsl_path = Path::new(r"\\wsl$").join(&self.wsl.host);
}
wsl_path = if remote.starts_with('~') {
let home_dir = self.home_dir()?;
wsl_path.join(remote.replacen('~', &home_dir, 1))
} else {
wsl_path.join(remote)
};
std::fs::copy(local, wsl_path)?;
Ok(())
}
fn command_builder(&self) -> Command {
let mut cmd = new_command("wsl");
cmd.arg("-d").arg(&self.wsl.host).arg("--");
cmd
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/proxy/ssh.rs | lapce-app/src/proxy/ssh.rs | use std::{path::Path, process::Command};
use anyhow::Result;
use tracing::debug;
use super::remote::Remote;
use crate::{proxy::new_command, workspace::SshHost};
pub struct SshRemote {
pub ssh: SshHost,
}
impl SshRemote {
#[cfg(windows)]
const SSH_ARGS: &'static [&'static str] = &[];
#[cfg(unix)]
const SSH_ARGS: &'static [&'static str] = &[
"-o",
"ControlMaster=auto",
"-o",
"ControlPath=~/.ssh/cm_%C",
"-o",
"ControlPersist=30m",
"-o",
"ConnectTimeout=15",
];
}
impl Remote for SshRemote {
fn upload_file(&self, local: impl AsRef<Path>, remote: &str) -> Result<()> {
let mut cmd = new_command("scp");
cmd.args(Self::SSH_ARGS);
if let Some(port) = self.ssh.port {
cmd.arg("-P").arg(port.to_string());
}
let output = cmd
.arg(local.as_ref())
.arg(dbg!(format!("{}:{remote}", self.ssh.user_host())))
.output()?;
debug!("{}", String::from_utf8_lossy(&output.stderr));
debug!("{}", String::from_utf8_lossy(&output.stdout));
Ok(())
}
fn command_builder(&self) -> Command {
let mut cmd = new_command("ssh");
cmd.args(Self::SSH_ARGS);
if let Some(port) = self.ssh.port {
cmd.arg("-p").arg(port.to_string());
}
cmd.arg(self.ssh.user_host());
if !std::env::var("LAPCE_DEBUG").unwrap_or_default().is_empty() {
cmd.arg("-v");
}
cmd
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/file_explorer/node.rs | lapce-app/src/file_explorer/node.rs | use floem::views::VirtualVector;
use lapce_rpc::file::{FileNodeItem, FileNodeViewData, Naming};
pub struct FileNodeVirtualList {
file_node_item: FileNodeItem,
naming: Naming,
}
impl FileNodeVirtualList {
pub fn new(file_node_item: FileNodeItem, naming: Naming) -> Self {
Self {
file_node_item,
naming,
}
}
}
impl VirtualVector<FileNodeViewData> for FileNodeVirtualList {
fn total_len(&self) -> usize {
self.file_node_item.children_open_count + 1
}
fn slice(
&mut self,
range: std::ops::Range<usize>,
) -> impl Iterator<Item = FileNodeViewData> {
let naming = &self.naming;
let root = &self.file_node_item;
let min = range.start;
let max = range.end;
let mut view_items = Vec::new();
root.append_view_slice(&mut view_items, naming, min, max, 0, 1);
view_items.into_iter()
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/file_explorer/view.rs | lapce-app/src/file_explorer/view.rs | use std::{path::Path, rc::Rc, sync::Arc};
use floem::{
View,
event::{Event, EventListener},
kurbo::Rect,
peniko::Color,
reactive::{
ReadSignal, RwSignal, SignalGet, SignalUpdate, SignalWith, create_rw_signal,
},
style::{AlignItems, CursorStyle, Position, Style},
text::Style as FontStyle,
views::{
Container, Decorators, container, dyn_stack, label, scroll, stack, svg,
virtual_stack,
},
};
use lapce_core::selection::Selection;
use lapce_rpc::{
file::{FileNodeViewData, FileNodeViewKind, Naming},
source_control::FileDiffKind,
};
use lapce_xi_rope::Rope;
use super::{data::FileExplorerData, node::FileNodeVirtualList};
use crate::{
app::clickable_icon,
command::InternalCommand,
config::{LapceConfig, color::LapceColor, icon::LapceIcons},
editor_tab::{EditorTabChild, EditorTabData},
panel::{
data::PanelSection, kind::PanelKind, position::PanelPosition,
view::PanelBuilder,
},
plugin::PluginData,
source_control::SourceControlData,
text_input::TextInputBuilder,
window_tab::{Focus, WindowTabData},
};
/// Blends `foreground` with `background`.
///
/// Uses the alpha channel from `foreground` - if `foreground` is opaque, `foreground` will be
/// returned unchanged.
///
/// The result is always opaque regardless of the transparency of the inputs.
fn blend_colors(background: Color, foreground: Color) -> Color {
let background = background.to_rgba8();
let foreground = foreground.to_rgba8();
let a: u16 = foreground.a.into();
let [r, g, b] = [
[background.r, foreground.r],
[background.g, foreground.g],
[background.b, foreground.b],
]
.map(|x| x.map(u16::from))
.map(|[b, f]| (a * f + (255 - a) * b) / 255)
.map(|x| x as u8);
Color::from_rgba8(r, g, b, 255)
}
pub fn file_explorer_panel(
window_tab_data: Rc<WindowTabData>,
position: PanelPosition,
) -> impl View {
let config = window_tab_data.common.config;
let data = window_tab_data.file_explorer.clone();
let source_control = window_tab_data.source_control.clone();
PanelBuilder::new(config, position)
.add_height_style(
"Open Editors",
150.0,
container(open_editors_view(window_tab_data.clone()))
.style(|s| s.size_full()),
window_tab_data.panel.section_open(PanelSection::OpenEditor),
move |s| s.apply_if(!config.get().ui.open_editors_visible, |s| s.hide()),
)
.add(
"File Explorer",
container(file_explorer_view(data, source_control))
.style(|s| s.size_full()),
window_tab_data
.panel
.section_open(PanelSection::FileExplorer),
)
.build()
.debug_name("File Explorer Panel")
}
/// Initialize the file explorer's naming (renaming, creating, etc.) editor with the given path.
fn initialize_naming_editor_with_path(data: &FileExplorerData, path: &Path) {
let file_name = path.file_name().unwrap_or_default().to_string_lossy();
// Start with the part of the file or directory name before the extension
// selected.
let selection_end = {
let without_leading_dot = file_name.strip_prefix('.').unwrap_or(&file_name);
let idx = without_leading_dot
.find('.')
.unwrap_or(without_leading_dot.len());
idx + file_name.len() - without_leading_dot.len()
};
initialize_naming_editor(data, &file_name, Some(selection_end));
}
fn initialize_naming_editor(
data: &FileExplorerData,
text: &str,
selection_end: Option<usize>,
) {
let text = Rope::from(text);
let selection_end = selection_end.unwrap_or(text.len());
let doc = data.naming_editor_data.doc();
doc.reload(text, true);
data.naming_editor_data
.cursor()
.update(|cursor| cursor.set_insert(Selection::region(0, selection_end)));
data.naming
.update(|naming| naming.set_editor_needs_reset(false));
}
fn file_node_text_color(
config: ReadSignal<Arc<LapceConfig>>,
node: FileNodeViewData,
source_control: SourceControlData,
) -> Color {
let diff = source_control.file_diffs.with(|file_diffs| {
let FileNodeViewKind::Path(path) = &node.kind else {
return None;
};
if node.is_dir {
file_diffs
.keys()
.find(|p| p.as_path().starts_with(path))
.map(|_| FileDiffKind::Modified)
} else {
file_diffs.get(path).map(|(diff, _)| diff.kind())
}
});
let color = match diff {
Some(FileDiffKind::Modified | FileDiffKind::Renamed) => {
LapceColor::SOURCE_CONTROL_MODIFIED
}
Some(FileDiffKind::Added) => LapceColor::SOURCE_CONTROL_ADDED,
Some(FileDiffKind::Deleted) => LapceColor::SOURCE_CONTROL_REMOVED,
None => LapceColor::PANEL_FOREGROUND,
};
config.get().color(color)
}
fn file_node_text_view(
data: FileExplorerData,
node: FileNodeViewData,
source_control: SourceControlData,
) -> impl View {
let config = data.common.config;
let ui_line_height = data.common.ui_line_height;
match node.kind.clone() {
FileNodeViewKind::Path(path) => {
if node.is_root {
let file = path.clone();
container((
label(move || {
file.file_name()
.map(|f| f.to_string_lossy().to_string())
.unwrap_or_default()
})
.style(move |s| {
s.height(ui_line_height.get())
.color(file_node_text_color(
config,
node.clone(),
source_control.clone(),
))
.padding_right(5.0)
.selectable(false)
}),
label(move || path.to_string_lossy().to_string()).style(
move |s| {
s.height(ui_line_height.get())
.color(
config
.get()
.color(LapceColor::PANEL_FOREGROUND_DIM),
)
.selectable(false)
},
),
))
} else {
container(
label(move || {
path.file_name()
.map(|f| f.to_string_lossy().to_string())
.unwrap_or_default()
})
.style(move |s| {
s.height(ui_line_height.get())
.color(file_node_text_color(
config,
node.clone(),
source_control.clone(),
))
.selectable(false)
}),
)
}
}
FileNodeViewKind::Renaming { path, err } => {
if data.naming.with_untracked(Naming::editor_needs_reset) {
initialize_naming_editor_with_path(&data, &path);
}
file_node_input_view(data, err.clone())
}
FileNodeViewKind::Naming { err } => {
if data.naming.with_untracked(Naming::editor_needs_reset) {
initialize_naming_editor(&data, "", None);
}
file_node_input_view(data, err.clone())
}
FileNodeViewKind::Duplicating { source, err } => {
if data.naming.with_untracked(Naming::editor_needs_reset) {
initialize_naming_editor_with_path(&data, &source);
}
file_node_input_view(data, err.clone())
}
}
}
/// Input used for naming a file/directory
fn file_node_input_view(data: FileExplorerData, err: Option<String>) -> Container {
let ui_line_height = data.common.ui_line_height;
let naming_editor_data = data.naming_editor_data.clone();
let text_input_file_explorer_data = data.clone();
let focus = data.common.focus;
let config = data.common.config;
let is_focused = move || {
focus.with_untracked(|focus| focus == &Focus::Panel(PanelKind::FileExplorer))
};
let text_input_view = TextInputBuilder::new()
.is_focused(is_focused)
.key_focus(text_input_file_explorer_data)
.build_editor(naming_editor_data.clone())
.on_event_stop(EventListener::FocusLost, move |_| {
data.finish_naming();
data.naming.set(Naming::None);
})
.style(move |s| {
s.width_full()
.height(ui_line_height.get())
.padding(0.0)
.margin(0.0)
.border_radius(6.0)
.border(1.0)
.border_color(config.get().color(LapceColor::LAPCE_BORDER))
});
let text_input_id = text_input_view.id();
text_input_id.request_focus();
if let Some(err) = err {
container(
stack((
text_input_view,
label(move || err.clone()).style(move |s| {
let config = config.get();
let editor_background_color =
config.color(LapceColor::PANEL_CURRENT_BACKGROUND);
let error_background_color =
config.color(LapceColor::ERROR_LENS_ERROR_BACKGROUND);
let background_color = blend_colors(
editor_background_color,
error_background_color,
);
s.position(Position::Absolute)
.inset_top(ui_line_height.get())
.width_full()
.color(config.color(LapceColor::ERROR_LENS_ERROR_FOREGROUND))
.background(background_color)
.z_index(100)
}),
))
.style(|s| s.flex_grow(1.0)),
)
} else {
container(text_input_view)
}
.style(move |s| s.width_full())
}
fn file_explorer_view(
data: FileExplorerData,
source_control: SourceControlData,
) -> impl View {
let root = data.root;
let ui_line_height = data.common.ui_line_height;
let config = data.common.config;
let naming = data.naming;
let scroll_to_line = data.scroll_to_line;
let select = data.select;
let secondary_click_data = data.clone();
let scroll_rect = create_rw_signal(Rect::ZERO);
scroll(
virtual_stack(
move || FileNodeVirtualList::new(root.get(), data.naming.get()),
move |node| (node.kind.clone(), node.is_dir, node.open, node.level),
move |node| {
let level = node.level;
let data = data.clone();
let click_data = data.clone();
let double_click_data = data.clone();
let secondary_click_data = data.clone();
let aux_click_data = data.clone();
let kind = node.kind.clone();
let open = node.open;
let is_dir = node.is_dir;
let view = stack((
svg(move || {
let config = config.get();
let svg_str = match open {
true => LapceIcons::ITEM_OPENED,
false => LapceIcons::ITEM_CLOSED,
};
config.ui_svg(svg_str)
})
.style(move |s| {
let config = config.get();
let size = config.ui.icon_size() as f32;
let color = if is_dir {
config.color(LapceColor::LAPCE_ICON_ACTIVE)
} else {
Color::TRANSPARENT
};
s.size(size, size)
.flex_shrink(0.0)
.margin_left(10.0)
.color(color)
}),
{
let kind = kind.clone();
let kind_for_style = kind.clone();
// TODO: use the current naming input as the path for the file svg
svg(move || {
let config = config.get();
if is_dir {
let svg_str = match open {
true => LapceIcons::DIRECTORY_OPENED,
false => LapceIcons::DIRECTORY_CLOSED,
};
config.ui_svg(svg_str)
} else if let Some(path) = kind.path() {
config.file_svg(path).0
} else {
config.ui_svg(LapceIcons::FILE)
}
})
.style(move |s| {
let config = config.get();
let size = config.ui.icon_size() as f32;
s.size(size, size)
.flex_shrink(0.0)
.margin_horiz(6.0)
.apply_if(is_dir, |s| {
s.color(
config.color(LapceColor::LAPCE_ICON_ACTIVE),
)
})
.apply_if(!is_dir, |s| {
s.apply_opt(
kind_for_style
.path()
.and_then(|p| config.file_svg(p).1),
Style::color,
)
})
})
},
file_node_text_view(data, node, source_control.clone()),
))
.style({
let kind = kind.clone();
move |s| {
s.padding_right(15.0)
.min_width_full()
.padding_left((level * 10) as f32)
.align_items(AlignItems::Center)
.hover(|s| {
s.background(
config
.get()
.color(LapceColor::PANEL_HOVERED_BACKGROUND),
)
.cursor(CursorStyle::Pointer)
})
.apply_if(
select.get().map(|x| x == kind).unwrap_or_default(),
|x| {
x.background(
config.get().color(
LapceColor::PANEL_CURRENT_BACKGROUND,
),
)
},
)
}
})
.debug_name("file item");
// Only handle click events if we are not naming the file node
if let FileNodeViewKind::Path(path) = &kind {
let click_path = path.clone();
let double_click_path = path.clone();
let secondary_click_path = path.clone();
let aux_click_path = path.clone();
view.on_click_stop({
let kind = kind.clone();
move |_| {
click_data.click(&click_path, config);
select.update(|x| *x = Some(kind.clone()));
}
})
.on_double_click({
move |_| {
double_click_data
.double_click(&double_click_path, config)
}
})
.on_secondary_click_stop(move |_| {
secondary_click_data.secondary_click(&secondary_click_path);
})
.on_event_stop(
EventListener::PointerDown,
move |event| {
if let Event::PointerDown(pointer_event) = event {
if pointer_event.button.is_auxiliary() {
aux_click_data.middle_click(&aux_click_path);
}
}
},
)
} else {
view
}
},
)
.item_size_fixed(move || ui_line_height.get())
.style(|s| s.absolute().flex_col().min_width_full()),
)
.style(|s| s.absolute().size_full().line_height(1.8))
.on_secondary_click_stop(move |_| {
if let Naming::None = naming.get_untracked() {
if let Some(path) = &secondary_click_data.common.workspace.path {
secondary_click_data.secondary_click(path);
}
}
})
.on_resize(move |rect| {
scroll_rect.set(rect);
})
.scroll_to(move || {
if let Some(line) = scroll_to_line.get() {
let line_height = ui_line_height.get_untracked();
Some(
(
0.0,
line * line_height - scroll_rect.get_untracked().height() / 2.0,
)
.into(),
)
} else {
None
}
})
}
fn open_editors_view(window_tab_data: Rc<WindowTabData>) -> impl View {
let diff_editors = window_tab_data.main_split.diff_editors;
let editors = window_tab_data.main_split.editors;
let editor_tabs = window_tab_data.main_split.editor_tabs;
let config = window_tab_data.common.config;
let internal_command = window_tab_data.common.internal_command;
let active_editor_tab = window_tab_data.main_split.active_editor_tab;
let plugin = window_tab_data.plugin.clone();
let child_view = move |plugin: PluginData,
editor_tab: RwSignal<EditorTabData>,
child_index: RwSignal<usize>,
child: EditorTabChild| {
let editor_tab_id =
editor_tab.with_untracked(|editor_tab| editor_tab.editor_tab_id);
let child_for_close = child.clone();
let info = child.view_info(editors, diff_editors, plugin, config);
let hovered = create_rw_signal(false);
stack((
clickable_icon(
move || {
if hovered.get() || info.with(|info| info.is_pristine) {
LapceIcons::CLOSE
} else {
LapceIcons::UNSAVED
}
},
move || {
let editor_tab_id =
editor_tab.with_untracked(|t| t.editor_tab_id);
internal_command.send(InternalCommand::EditorTabChildClose {
editor_tab_id,
child: child_for_close.clone(),
});
},
|| false,
|| false,
|| "Close",
config,
)
.on_event_stop(EventListener::PointerEnter, move |_| {
hovered.set(true);
})
.on_event_stop(EventListener::PointerLeave, move |_| {
hovered.set(false);
})
.on_event_stop(EventListener::PointerDown, |_| {})
.style(|s| s.margin_left(10.0)),
container(svg(move || info.with(|info| info.icon.clone())).style(
move |s| {
let size = config.get().ui.icon_size() as f32;
s.size(size, size)
.apply_opt(info.with(|info| info.color), |s, c| s.color(c))
},
))
.style(|s| s.padding_horiz(6.0)),
label(move || info.with(|info| info.name.clone())).style(move |s| {
s.apply_if(
!info
.with(|info| info.confirmed)
.map(|confirmed| confirmed.get())
.unwrap_or(true),
|s| s.font_style(FontStyle::Italic),
)
}),
))
.style(move |s| {
let config = config.get();
s.items_center()
.width_pct(100.0)
.cursor(CursorStyle::Pointer)
.apply_if(
active_editor_tab.get() == Some(editor_tab_id)
&& editor_tab.with(|editor_tab| editor_tab.active)
== child_index.get(),
|s| {
s.background(
config.color(LapceColor::PANEL_CURRENT_BACKGROUND),
)
},
)
.hover(|s| {
s.background(config.color(LapceColor::PANEL_HOVERED_BACKGROUND))
})
})
.on_event_cont(EventListener::PointerDown, move |_| {
editor_tab.update(|editor_tab| {
editor_tab.active = child_index.get_untracked();
});
active_editor_tab.set(Some(editor_tab_id));
})
};
scroll(
dyn_stack(
move || editor_tabs.get().into_iter().enumerate(),
move |(index, (editor_tab_id, _))| (*index, *editor_tab_id),
move |(index, (_, editor_tab))| {
let plugin = plugin.clone();
stack((
label(move || format!("Group {}", index + 1))
.style(|s| s.margin_left(10.0)),
dyn_stack(
move || editor_tab.get().children,
move |(_, _, child)| child.id(),
move |(child_index, _, child)| {
child_view(
plugin.clone(),
editor_tab,
child_index,
child,
)
},
)
.style(|s| s.flex_col().width_pct(100.0)),
))
.style(|s| s.flex_col())
},
)
.style(|s| s.flex_col().width_pct(100.0)),
)
.style(|s| s.absolute().size_full().line_height(1.8))
.debug_name("Open Editors")
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/file_explorer/mod.rs | lapce-app/src/file_explorer/mod.rs | pub mod data;
pub mod node;
pub mod view;
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/file_explorer/data.rs | lapce-app/src/file_explorer/data.rs | use std::{
borrow::Cow,
collections::HashMap,
ffi::OsStr,
path::{Path, PathBuf},
rc::Rc,
sync::Arc,
};
use floem::{
action::show_context_menu,
event::EventPropagation,
ext_event::create_ext_action,
keyboard::Modifiers,
menu::{Menu, MenuItem},
reactive::{ReadSignal, RwSignal, Scope, SignalGet, SignalUpdate, SignalWith},
views::editor::text::SystemClipboard,
};
use globset::Glob;
use lapce_core::{
command::{EditCommand, FocusCommand},
mode::Mode,
register::Clipboard,
};
use lapce_rpc::{
file::{
Duplicating, FileNodeItem, FileNodeViewKind, Naming, NamingState, NewNode,
Renaming,
},
proxy::ProxyResponse,
};
use crate::{
command::{CommandExecuted, CommandKind, InternalCommand, LapceCommand},
config::LapceConfig,
editor::EditorData,
keypress::{KeyPressFocus, condition::Condition},
main_split::Editors,
window_tab::CommonData,
};
enum RenamedPath {
NotRenaming,
NameUnchanged,
Renamed {
current_path: PathBuf,
new_path: PathBuf,
},
}
#[derive(Clone, Debug)]
pub struct FileExplorerData {
pub root: RwSignal<FileNodeItem>,
pub naming: RwSignal<Naming>,
pub naming_editor_data: EditorData,
pub common: Rc<CommonData>,
pub scroll_to_line: RwSignal<Option<f64>>,
left_diff_path: RwSignal<Option<PathBuf>>,
pub select: RwSignal<Option<FileNodeViewKind>>,
}
impl KeyPressFocus for FileExplorerData {
fn get_mode(&self) -> Mode {
Mode::Insert
}
fn check_condition(&self, condition: Condition) -> bool {
self.naming.with_untracked(Naming::is_accepting_input)
&& condition == Condition::ModalFocus
}
fn run_command(
&self,
command: &LapceCommand,
count: Option<usize>,
mods: Modifiers,
) -> CommandExecuted {
if self.naming.with_untracked(Naming::is_accepting_input) {
match command.kind {
CommandKind::Focus(FocusCommand::ModalClose) => {
self.cancel_naming();
CommandExecuted::Yes
}
CommandKind::Edit(EditCommand::InsertNewLine) => {
self.finish_naming();
CommandExecuted::Yes
}
CommandKind::Edit(_) => {
let command_executed =
self.naming_editor_data.run_command(command, count, mods);
if let Some(new_path) = self.naming_path() {
self.common
.internal_command
.send(InternalCommand::TestPathCreation { new_path });
}
command_executed
}
_ => self.naming_editor_data.run_command(command, count, mods),
}
} else {
CommandExecuted::No
}
}
fn receive_char(&self, c: &str) {
if self.naming.with_untracked(Naming::is_accepting_input) {
self.naming_editor_data.receive_char(c);
if let Some(new_path) = self.naming_path() {
self.common
.internal_command
.send(InternalCommand::TestPathCreation { new_path });
}
}
}
}
impl FileExplorerData {
pub fn new(cx: Scope, editors: Editors, common: Rc<CommonData>) -> Self {
let path = common.workspace.path.clone().unwrap_or_default();
let root = cx.create_rw_signal(FileNodeItem {
path: path.clone(),
is_dir: true,
read: false,
open: false,
children: HashMap::new(),
children_open_count: 0,
});
let naming = cx.create_rw_signal(Naming::None);
let naming_editor_data = editors.make_local(cx, common.clone());
let data = Self {
root,
naming,
naming_editor_data,
common,
scroll_to_line: cx.create_rw_signal(None),
left_diff_path: cx.create_rw_signal(None),
select: cx.create_rw_signal(None),
};
if data.common.workspace.path.is_some() {
// only fill in the child files if there is open folder
data.toggle_expand(&path);
}
data
}
/// Reload the file explorer data via reading the root directory.
/// Note that this will not update immediately.
pub fn reload(&self) {
let path = self.root.with_untracked(|root| root.path.clone());
self.read_dir(&path);
}
/// Toggle whether the directory is expanded or not.
/// Does nothing if the path does not exist or is not a directory.
pub fn toggle_expand(&self, path: &Path) {
let Some(Some(read)) = self.root.try_update(|root| {
let read = if let Some(node) = root.get_file_node_mut(path) {
if !node.is_dir {
return None;
}
node.open = !node.open;
Some(node.read)
} else {
None
};
if Some(true) == read {
root.update_node_count_recursive(path);
}
read
}) else {
return;
};
// Read the directory's files if they haven't been read yet
if !read {
self.read_dir(path);
}
}
pub fn read_dir(&self, path: &Path) {
self.read_dir_cb(path, |_| {});
}
/// Read the directory's information and update the file explorer tree.
/// `done : FnOnce(was_read: bool)` is called when the operation is completed, whether success,
/// failure, or ignored.
pub fn read_dir_cb(&self, path: &Path, done: impl FnOnce(bool) + 'static) {
let root = self.root;
let data = self.clone();
let config = self.common.config;
let send = {
let path = path.to_path_buf();
create_ext_action(self.common.scope, move |result| {
let Ok(ProxyResponse::ReadDirResponse { mut items }) = result else {
done(false);
return;
};
root.update(|root| {
// Get the node for this path, which should already exist if we're calling
// read_dir on it.
if let Some(node) = root.get_file_node_mut(&path) {
// TODO: do not recreate glob every time we read a directory
// Retain only items that are not excluded from view by the configuration
match Glob::new(&config.get().editor.files_exclude) {
Ok(glob) => {
let matcher = glob.compile_matcher();
items.retain(|i| !matcher.is_match(&i.path));
}
Err(e) => tracing::error!(
target:"files_exclude",
"Failed to compile glob: {}",
e
),
}
node.read = true;
// Remove paths that no longer exist
let removed_paths: Vec<PathBuf> = node
.children
.keys()
.filter(|p| !items.iter().any(|i| &&i.path == p))
.map(PathBuf::from)
.collect();
for path in removed_paths {
node.children.remove(&path);
}
// Reread dirs that were already read and add new paths
for item in items {
if let Some(existing) = node.children.get(&item.path) {
if existing.read {
data.read_dir(&existing.path);
}
} else {
node.children.insert(item.path.clone(), item);
}
}
}
root.update_node_count_recursive(&path);
});
done(true);
})
};
// Ask the proxy for the directory information
self.common.proxy.read_dir(path.to_path_buf(), send);
}
/// Returns `true` if `path` exists in the file explorer tree and is a directory, `false`
/// otherwise.
fn is_dir(&self, path: &Path) -> bool {
self.root.with_untracked(|root| {
root.get_file_node(path).is_some_and(|node| node.is_dir)
})
}
/// The current path that we're renaming to / creating or duplicating a node at.
/// Note: returns `None` when renaming if the file name has not changed.
fn naming_path(&self) -> Option<PathBuf> {
self.naming.with_untracked(|naming| match naming {
Naming::None => None,
Naming::Renaming(_) => {
if let RenamedPath::Renamed { new_path, .. } = self.renamed_path() {
Some(new_path)
} else {
None
}
}
Naming::NewNode(n) => {
let relative_path = self.naming_editor_data.text();
let relative_path: Cow<OsStr> = match relative_path.slice_to_cow(..)
{
Cow::Borrowed(path) => Cow::Borrowed(path.as_ref()),
Cow::Owned(path) => Cow::Owned(path.into()),
};
Some(n.base_path.join(relative_path))
}
Naming::Duplicating(d) => {
let relative_path = self.naming_editor_data.text();
let relative_path: Cow<OsStr> = match relative_path.slice_to_cow(..)
{
Cow::Borrowed(path) => Cow::Borrowed(path.as_ref()),
Cow::Owned(path) => Cow::Owned(path.into()),
};
let new_path =
d.path.parent().unwrap_or("".as_ref()).join(relative_path);
Some(new_path)
}
})
}
/// If there is an in progress rename and the user has entered a path that differs from the
/// current path, gets the current and new paths of the renamed node.
fn renamed_path(&self) -> RenamedPath {
self.naming.with_untracked(|naming| {
if let Some(current_path) = naming.as_renaming().map(|x| &x.path) {
let current_file_name = current_path.file_name().unwrap_or_default();
// `new_relative_path` is the new path relative to the parent directory, unless the
// user has entered an absolute path.
let new_relative_path = self.naming_editor_data.text();
let new_relative_path: Cow<OsStr> =
match new_relative_path.slice_to_cow(..) {
Cow::Borrowed(path) => Cow::Borrowed(path.as_ref()),
Cow::Owned(path) => Cow::Owned(path.into()),
};
if new_relative_path == current_file_name {
RenamedPath::NameUnchanged
} else {
let new_path = current_path
.parent()
.unwrap_or("".as_ref())
.join(new_relative_path);
RenamedPath::Renamed {
current_path: current_path.to_owned(),
new_path,
}
}
} else {
RenamedPath::NotRenaming
}
})
}
/// If a naming is in progress and the user has entered a valid path, send the request to
/// actually perform the change.
pub fn finish_naming(&self) {
match self.naming.get_untracked() {
Naming::None => {}
Naming::Renaming(_) => {
let renamed_path = self.renamed_path();
match renamed_path {
// Should not occur
RenamedPath::NotRenaming => {}
RenamedPath::NameUnchanged => {
self.cancel_naming();
}
RenamedPath::Renamed {
current_path,
new_path,
} => {
self.common.internal_command.send(
InternalCommand::FinishRenamePath {
current_path,
new_path,
},
);
}
}
}
Naming::NewNode(n) => {
let Some(path) = self.naming_path() else {
return;
};
self.common
.internal_command
.send(InternalCommand::FinishNewNode {
is_dir: n.is_dir,
path,
});
}
Naming::Duplicating(d) => {
let Some(path) = self.naming_path() else {
return;
};
self.common.internal_command.send(
InternalCommand::FinishDuplicate {
source: d.path.to_owned(),
path,
},
);
}
}
}
/// Closes the naming text box without applying the effect.
pub fn cancel_naming(&self) {
self.naming.set(Naming::None);
}
pub fn click(&self, path: &Path, config: ReadSignal<Arc<LapceConfig>>) {
if self.is_dir(path) {
self.toggle_expand(path);
} else if !config.get_untracked().core.file_explorer_double_click {
self.common
.internal_command
.send(InternalCommand::OpenFile {
path: path.to_path_buf(),
})
}
}
pub fn reveal_in_file_tree(&self, path: PathBuf) {
let done = self
.root
.try_update(|root| {
// the directories in which the file are located are all readed and opened
if root.get_file_node(&path).is_some() {
for current_path in path.ancestors() {
if let Some(file) = root.get_file_node_mut(current_path) {
if file.is_dir {
file.open = true;
}
}
}
root.update_node_count_recursive(&path);
true
} else {
// read and open the directories in which the file are located
let mut read_dir = None;
// Whether the file is in the workspace
let mut exist = false;
for current_path in path.ancestors() {
if let Some(file) = root.get_file_node_mut(current_path) {
exist = true;
if file.is_dir {
file.open = true;
if !file.read {
read_dir = Some(current_path.to_path_buf())
}
}
break;
}
}
if let (true, Some(dir)) = (exist, read_dir) {
let explorer = self.clone();
let select_path = path.clone();
self.read_dir_cb(&dir, move |_| {
explorer.reveal_in_file_tree(select_path);
})
}
false
}
})
.unwrap_or(false);
if done {
let (found, line) =
self.root.with_untracked(|x| x.find_file_at_line(&path));
if found {
self.scroll_to_line.set(Some(line));
self.select.set(Some(FileNodeViewKind::Path(path)));
}
}
}
pub fn double_click(
&self,
path: &Path,
config: ReadSignal<Arc<LapceConfig>>,
) -> EventPropagation {
if self.is_dir(path) {
EventPropagation::Continue
} else if config.get_untracked().core.file_explorer_double_click {
self.common.internal_command.send(
InternalCommand::OpenAndConfirmedFile {
path: path.to_path_buf(),
},
);
EventPropagation::Stop
} else {
self.common
.internal_command
.send(InternalCommand::MakeConfirmed);
EventPropagation::Stop
}
}
pub fn secondary_click(&self, path: &Path) {
let common = self.common.clone();
let path_a = path.to_owned();
let left_diff_path = self.left_diff_path;
// TODO: should we just pass is_dir into secondary click?
let is_dir = self.is_dir(path);
let Some(workspace_path) = self.common.workspace.path.as_ref() else {
// There is no context menu if we are not in a workspace
return;
};
let is_workspace = path == workspace_path;
let base_path_a = if is_dir {
Some(path_a.clone())
} else {
path_a.parent().map(ToOwned::to_owned)
};
let base_path_a = base_path_a.as_ref().unwrap_or(workspace_path);
let mut menu = Menu::new("");
let base_path = base_path_a.clone();
let data = self.clone();
let naming = self.naming;
menu = menu.entry(MenuItem::new("New File").action(move || {
let base_path_b = &base_path;
let base_path = base_path.clone();
data.read_dir_cb(base_path_b, move |was_read| {
if !was_read {
tracing::warn!(
"Failed to read directory, avoiding creating node in: {:?}",
base_path
);
return;
}
naming.set(Naming::NewNode(NewNode {
state: NamingState::Naming,
base_path: base_path.clone(),
is_dir: false,
editor_needs_reset: true,
}));
});
}));
let base_path = base_path_a.clone();
let data = self.clone();
let naming = self.naming;
menu = menu.entry(MenuItem::new("New Directory").action(move || {
let base_path_b = &base_path;
let base_path = base_path.clone();
data.read_dir_cb(base_path_b, move |was_read| {
if !was_read {
tracing::warn!(
"Failed to read directory, avoiding creating node in: {:?}",
base_path
);
return;
}
naming.set(Naming::NewNode(NewNode {
state: NamingState::Naming,
base_path: base_path.clone(),
is_dir: true,
editor_needs_reset: true,
}));
})
}));
menu = menu.separator();
// TODO: there are situations where we can open the file explorer to remote files
if !common.workspace.kind.is_remote() {
let path = path_a.clone();
#[cfg(not(target_os = "macos"))]
let title = "Reveal in system file explorer";
#[cfg(target_os = "macos")]
let title = "Reveal in Finder";
menu = menu.entry(MenuItem::new(title).action(move || {
let path = path.parent().unwrap_or(&path);
if !path.exists() {
return;
}
if let Err(err) = open::that(path) {
tracing::error!(
"Failed to reveal file in system file explorer: {}",
err
);
}
}));
}
if !is_workspace {
let path = path_a.clone();
menu = menu.entry(MenuItem::new("Rename").action(move || {
naming.set(Naming::Renaming(Renaming {
state: NamingState::Naming,
path: path.clone(),
editor_needs_reset: true,
}));
}));
let path = path_a.clone();
menu = menu.entry(MenuItem::new("Duplicate").action(move || {
naming.set(Naming::Duplicating(Duplicating {
state: NamingState::Naming,
path: path.clone(),
editor_needs_reset: true,
}));
}));
// TODO: it is common for shift+right click to make 'Move file to trash' an actual
// Delete, which can be useful for large files.
let path = path_a.clone();
let proxy = common.proxy.clone();
let trash_text = if is_dir {
"Move Directory to Trash"
} else {
"Move File to Trash"
};
menu = menu.entry(MenuItem::new(trash_text).action(move || {
proxy.trash_path(path.clone(), |res| {
if let Err(err) = res {
tracing::warn!("Failed to trash path: {:?}", err);
}
})
}));
}
menu = menu.separator();
let path = path_a.clone();
menu = menu.entry(MenuItem::new("Copy Path").action(move || {
let mut clipboard = SystemClipboard::new();
clipboard.put_string(path.to_string_lossy());
}));
let path = path_a.clone();
let workspace = common.workspace.clone();
menu = menu.entry(MenuItem::new("Copy Relative Path").action(move || {
let relative_path = if let Some(workspace_path) = &workspace.path {
path.strip_prefix(workspace_path).unwrap_or(&path)
} else {
path.as_ref()
};
let mut clipboard = SystemClipboard::new();
clipboard.put_string(relative_path.to_string_lossy());
}));
menu = menu.separator();
let path = path_a.clone();
menu = menu.entry(
MenuItem::new("Select for Compare")
.action(move || left_diff_path.set(Some(path.clone()))),
);
if let Some(left_path) = self.left_diff_path.get_untracked() {
let common = self.common.clone();
let right_path = path_a.to_owned();
menu = menu.entry(MenuItem::new("Compare with Selected").action(
move || {
common
.internal_command
.send(InternalCommand::OpenDiffFiles {
left_path: left_path.clone(),
right_path: right_path.clone(),
})
},
))
}
menu = menu.separator();
let internal_command = common.internal_command;
menu = menu.entry(MenuItem::new("Refresh").action(move || {
internal_command.send(InternalCommand::ReloadFileExplorer);
}));
show_context_menu(menu, None);
}
pub fn middle_click(&self, path: &Path) -> EventPropagation {
if self.is_dir(path) {
EventPropagation::Continue
} else {
self.common
.internal_command
.send(InternalCommand::OpenFileInNewTab {
path: path.to_path_buf(),
});
EventPropagation::Stop
}
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/editor/gutter.rs | lapce-app/src/editor/gutter.rs | use floem::{
Renderer, View, ViewId,
context::PaintCx,
peniko::kurbo::{Point, Rect, Size},
reactive::{Memo, SignalGet, SignalWith},
text::{Attrs, AttrsList, FamilyOwned, TextLayout},
};
use im::HashMap;
use lapce_core::{buffer::rope_text::RopeText, mode::Mode};
use serde::{Deserialize, Serialize};
use super::{EditorData, view::changes_colors_screen};
use crate::config::{LapceConfig, color::LapceColor};
pub struct EditorGutterView {
id: ViewId,
editor: EditorData,
width: f64,
gutter_padding_right: Memo<f32>,
}
pub fn editor_gutter_view(
editor: EditorData,
gutter_padding_right: Memo<f32>,
) -> EditorGutterView {
let id = ViewId::new();
EditorGutterView {
id,
editor,
width: 0.0,
gutter_padding_right,
}
}
impl EditorGutterView {
fn paint_head_changes(
&self,
cx: &mut PaintCx,
e_data: &EditorData,
viewport: Rect,
is_normal: bool,
config: &LapceConfig,
) {
if !is_normal {
return;
}
let changes = e_data.doc().head_changes().get_untracked();
let line_height = config.editor.line_height() as f64;
let gutter_padding_right = self.gutter_padding_right.get_untracked() as f64;
let changes = changes_colors_screen(config, &e_data.editor, changes);
for (y, height, removed, color) in changes {
let height = if removed {
10.0
} else {
height as f64 * line_height
};
let mut y = y - viewport.y0;
if removed {
y -= 5.0;
}
cx.fill(
&Size::new(3.0, height).to_rect().with_origin(Point::new(
self.width + 5.0 - gutter_padding_right,
y,
)),
color,
0.0,
)
}
}
fn paint_sticky_headers(
&self,
cx: &mut PaintCx,
is_normal: bool,
config: &LapceConfig,
) {
if !is_normal {
return;
}
if !config.editor.sticky_header {
return;
}
let sticky_header_height = self.editor.sticky_header_height.get_untracked();
if sticky_header_height == 0.0 {
return;
}
let sticky_area_rect =
Size::new(self.width + 25.0 + 30.0, sticky_header_height)
.to_rect()
.with_origin(Point::new(-25.0, 0.0))
.inflate(25.0, 0.0);
cx.fill(
&sticky_area_rect,
config.color(LapceColor::LAPCE_DROPDOWN_SHADOW),
3.0,
);
cx.fill(
&sticky_area_rect,
config.color(LapceColor::EDITOR_STICKY_HEADER_BACKGROUND),
0.0,
);
}
}
impl View for EditorGutterView {
fn id(&self) -> ViewId {
self.id
}
fn compute_layout(
&mut self,
_cx: &mut floem::context::ComputeLayoutCx,
) -> Option<floem::peniko::kurbo::Rect> {
if let Some(width) = self.id.get_layout().map(|l| l.size.width as f64) {
self.width = width;
}
None
}
fn paint(&mut self, cx: &mut floem::context::PaintCx) {
let viewport = self.editor.viewport().get_untracked();
let cursor = self.editor.cursor();
let screen_lines = self.editor.screen_lines();
let config = self.editor.common.config;
let kind_is_normal =
self.editor.kind.with_untracked(|kind| kind.is_normal());
let (offset, mode) = cursor.with_untracked(|c| (c.offset(), c.get_mode()));
let config = config.get_untracked();
let line_height = config.editor.line_height() as f64;
let last_line = self.editor.editor.last_line();
let current_line = self
.editor
.doc()
.buffer
.with_untracked(|buffer| buffer.line_of_offset(offset));
let family: Vec<FamilyOwned> =
FamilyOwned::parse_list(&config.editor.font_family).collect();
let attrs = Attrs::new()
.family(&family)
.color(config.color(LapceColor::EDITOR_DIM))
.font_size(config.editor.font_size() as f32);
let attrs_list = AttrsList::new(attrs.clone());
let current_line_attrs_list = AttrsList::new(
attrs
.clone()
.color(config.color(LapceColor::EDITOR_FOREGROUND)),
);
let show_relative = config.core.modal
&& config.editor.modal_mode_relative_line_numbers
&& mode != Mode::Insert
&& kind_is_normal;
screen_lines.with_untracked(|screen_lines| {
for (line, y) in screen_lines.iter_lines_y() {
// If it ends up outside the bounds of the file, stop trying to display line numbers
if line > last_line {
break;
}
let text = if show_relative {
if line == current_line {
line + 1
} else {
line.abs_diff(current_line)
}
} else {
line + 1
}
.to_string();
let mut text_layout = TextLayout::new();
if line == current_line {
text_layout.set_text(
&text,
current_line_attrs_list.clone(),
None,
);
} else {
text_layout.set_text(&text, attrs_list.clone(), None);
}
let size = text_layout.size();
let height = size.height;
cx.draw_text(
&text_layout,
Point::new(
(self.width
- size.width
- self.gutter_padding_right.get_untracked() as f64)
.max(0.0),
y + (line_height - height) / 2.0 - viewport.y0,
),
);
}
});
self.paint_head_changes(cx, &self.editor, viewport, kind_is_normal, &config);
self.paint_sticky_headers(cx, kind_is_normal, &config);
}
fn debug_name(&self) -> std::borrow::Cow<'static, str> {
"Editor Gutter".into()
}
}
#[derive(Default, Clone)]
pub struct FoldingRanges(pub Vec<FoldingRange>);
#[derive(Default, Clone)]
pub struct FoldedRanges(pub Vec<FoldedRange>);
impl FoldingRanges {
pub fn get_folded_range(&self) -> FoldedRanges {
let mut range = Vec::new();
let mut limit_line = 0;
for item in &self.0 {
if item.start.line < limit_line && limit_line > 0 {
continue;
}
if item.status.is_folded() {
range.push(crate::editor::gutter::FoldedRange {
start: item.start,
end: item.end,
});
limit_line = item.end.line;
}
}
FoldedRanges(range)
}
pub fn to_display_items(&self) -> Vec<FoldingDisplayItem> {
let mut folded = HashMap::new();
let mut unfold_start: HashMap<u32, FoldingDisplayItem> = HashMap::new();
let mut unfold_end = HashMap::new();
let mut limit_line = 0;
for item in &self.0 {
if item.start.line < limit_line && limit_line > 0 {
continue;
}
match item.status {
FoldingRangeStatus::Fold => {
folded.insert(
item.start.line,
FoldingDisplayItem::Folded(item.start),
);
limit_line = item.end.line;
}
FoldingRangeStatus::Unfold => {
unfold_start.insert(
item.start.line,
FoldingDisplayItem::UnfoldStart(item.start),
);
unfold_end.insert(
item.end.line,
FoldingDisplayItem::UnfoldEnd(item.end),
);
limit_line = 0;
}
};
}
for (key, val) in unfold_end {
unfold_start.insert(key, val);
}
for (key, val) in folded {
unfold_start.insert(key, val);
}
unfold_start.into_iter().map(|x| x.1).collect()
}
}
impl FoldedRanges {
pub fn contain_line(&self, start_index: usize, line: u32) -> (bool, usize) {
if start_index >= self.0.len() {
return (false, start_index);
}
let mut last_index = start_index;
for range in self.0[start_index..].iter() {
if range.start.line >= line {
return (false, last_index);
} else if range.start.line < line && range.end.line > line {
return (true, last_index);
} else if range.end.line < line {
last_index += 1;
}
}
(false, last_index)
}
}
#[derive(Debug, Clone)]
pub struct FoldedRange {
pub start: FoldingPosition,
pub end: FoldingPosition,
}
#[derive(Debug, Clone)]
pub struct FoldingRange {
pub start: FoldingPosition,
pub end: FoldingPosition,
pub status: FoldingRangeStatus,
pub collapsed_text: Option<String>,
}
impl FoldingRange {
pub fn from_lsp(value: lsp_types::FoldingRange) -> Self {
let lsp_types::FoldingRange {
start_line,
start_character,
end_line,
end_character,
collapsed_text,
..
} = value;
let status = FoldingRangeStatus::Unfold;
Self {
start: FoldingPosition {
line: start_line,
character: start_character,
// kind: kind.clone().map(|x| FoldingRangeKind::from(x)),
},
end: FoldingPosition {
line: end_line,
character: end_character,
// kind: kind.map(|x| FoldingRangeKind::from(x)),
},
status,
collapsed_text,
}
}
}
#[derive(Debug, Clone, Eq, PartialEq, Hash, Copy)]
pub struct FoldingPosition {
pub line: u32,
pub character: Option<u32>,
// pub kind: Option<FoldingRangeKind>,
}
#[derive(Debug, Clone, Default, Eq, PartialEq)]
pub enum FoldingRangeStatus {
Fold,
#[default]
Unfold,
}
impl FoldingRangeStatus {
pub fn click(&mut self) {
// match self {
// FoldingRangeStatus::Fold => {
// *self = FoldingRangeStatus::Unfold;
// }
// FoldingRangeStatus::Unfold => {
// *self = FoldingRangeStatus::Fold;
// }
// }
}
pub fn is_folded(&self) -> bool {
*self == Self::Fold
}
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub enum FoldingDisplayItem {
UnfoldStart(FoldingPosition),
Folded(FoldingPosition),
UnfoldEnd(FoldingPosition),
}
impl FoldingDisplayItem {
pub fn position(&self) -> FoldingPosition {
match self {
FoldingDisplayItem::UnfoldStart(x) => *x,
FoldingDisplayItem::Folded(x) => *x,
FoldingDisplayItem::UnfoldEnd(x) => *x,
}
}
}
#[derive(Debug, Eq, PartialEq, Deserialize, Serialize, Clone, Hash, Copy)]
pub enum FoldingRangeKind {
Comment,
Imports,
Region,
}
impl From<lsp_types::FoldingRangeKind> for FoldingRangeKind {
fn from(value: lsp_types::FoldingRangeKind) -> Self {
match value {
lsp_types::FoldingRangeKind::Comment => FoldingRangeKind::Comment,
lsp_types::FoldingRangeKind::Imports => FoldingRangeKind::Imports,
lsp_types::FoldingRangeKind::Region => FoldingRangeKind::Region,
}
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/editor/view.rs | lapce-app/src/editor/view.rs | use std::{
cmp, collections::BTreeMap, ops::DerefMut, path::PathBuf, rc::Rc, sync::Arc,
};
use floem::{
Renderer, View, ViewId,
action::{set_ime_allowed, set_ime_cursor_area},
context::{PaintCx, StyleCx},
event::{Event, EventListener, EventPropagation},
keyboard::Modifiers,
kurbo::Stroke,
peniko::{
Color,
kurbo::{Line, Point, Rect, Size},
},
prelude::SignalTrack,
reactive::{
Memo, ReadSignal, RwSignal, SignalGet, SignalUpdate, SignalWith,
create_effect, create_memo, create_rw_signal,
},
style::{CursorColor, CursorStyle, Style, TextColor},
taffy::prelude::NodeId,
views::{
Decorators, clip, container, dyn_stack,
editor::{
CurrentLineColor, CursorSurroundingLines, Editor, EditorStyle,
IndentGuideColor, IndentStyleProp, Modal, ModalRelativeLine,
PhantomColor, PlaceholderColor, PreeditUnderlineColor,
RenderWhitespaceProp, ScrollBeyondLastLine, SelectionColor,
ShowIndentGuide, SmartTab, VisibleWhitespaceColor, WrapProp,
text::WrapMethod,
view::{
DiffSectionKind, EditorView as FloemEditorView, EditorViewClass,
LineRegion, ScreenLines, cursor_caret,
},
visual_line::{RVLine, VLine},
},
empty, label,
scroll::{PropagatePointerWheel, scroll},
stack, svg,
},
};
use itertools::Itertools;
use lapce_core::{
buffer::{Buffer, diff::DiffLines, rope_text::RopeText},
cursor::{CursorAffinity, CursorMode},
selection::SelRegion,
};
use lapce_rpc::{
dap_types::{DapId, SourceBreakpoint},
plugin::PluginId,
};
use lapce_xi_rope::find::CaseMatching;
use lsp_types::CodeLens;
use super::{DocSignal, EditorData, gutter::editor_gutter_view};
use crate::{
app::clickable_icon,
command::InternalCommand,
config::{LapceConfig, color::LapceColor, editor::WrapStyle, icon::LapceIcons},
debug::{DapData, LapceBreakpoint},
doc::DocContent,
editor::gutter::FoldingDisplayItem,
text_input::TextInputBuilder,
window_tab::{CommonData, Focus, WindowTabData},
workspace::LapceWorkspace,
};
#[derive(Clone, Debug, Default)]
pub struct StickyHeaderInfo {
pub sticky_lines: Vec<usize>,
pub last_sticky_should_scroll: bool,
pub y_diff: f64,
}
fn editor_wrap(config: &LapceConfig) -> WrapMethod {
/// Minimum width that we'll allow the view to be wrapped at.
const MIN_WRAPPED_WIDTH: f32 = 100.0;
match config.editor.wrap_style {
WrapStyle::None => WrapMethod::None,
WrapStyle::EditorWidth => WrapMethod::EditorWidth,
WrapStyle::WrapWidth => WrapMethod::WrapWidth {
width: (config.editor.wrap_width as f32).max(MIN_WRAPPED_WIDTH),
},
}
}
pub fn editor_style(
config: ReadSignal<Arc<LapceConfig>>,
doc: DocSignal,
s: Style,
) -> Style {
let config = config.get();
let doc = doc.get();
s.set(
IndentStyleProp,
doc.buffer.with_untracked(Buffer::indent_style),
)
.set(CursorColor, config.color(LapceColor::EDITOR_CARET))
.set(SelectionColor, config.color(LapceColor::EDITOR_SELECTION))
.set(
CurrentLineColor,
config.color(LapceColor::EDITOR_CURRENT_LINE),
)
.set(
VisibleWhitespaceColor,
config.color(LapceColor::EDITOR_VISIBLE_WHITESPACE),
)
.set(
IndentGuideColor,
config.color(LapceColor::EDITOR_INDENT_GUIDE),
)
.set(ScrollBeyondLastLine, config.editor.scroll_beyond_last_line)
.color(config.color(LapceColor::EDITOR_FOREGROUND))
.set(TextColor, config.color(LapceColor::EDITOR_FOREGROUND))
.set(PhantomColor, config.color(LapceColor::EDITOR_DIM))
.set(PlaceholderColor, config.color(LapceColor::EDITOR_DIM))
.set(
PreeditUnderlineColor,
config.color(LapceColor::EDITOR_FOREGROUND),
)
.set(ShowIndentGuide, config.editor.show_indent_guide)
.set(Modal, config.core.modal)
.set(
ModalRelativeLine,
config.editor.modal_mode_relative_line_numbers,
)
.set(SmartTab, config.editor.smart_tab)
.set(WrapProp, editor_wrap(&config))
.set(
CursorSurroundingLines,
config.editor.cursor_surrounding_lines,
)
.set(RenderWhitespaceProp, config.editor.render_whitespace)
}
pub struct EditorView {
id: ViewId,
editor: EditorData,
is_active: Memo<bool>,
inner_node: Option<NodeId>,
viewport: RwSignal<Rect>,
debug_breakline: Memo<Option<(usize, PathBuf)>>,
}
pub fn editor_view(
e_data: EditorData,
debug_breakline: Memo<Option<(usize, PathBuf)>>,
is_active: impl Fn(bool) -> bool + 'static + Copy,
) -> EditorView {
let id = ViewId::new();
let is_active = create_memo(move |_| is_active(true));
let viewport = e_data.viewport();
let doc = e_data.doc_signal();
let view_kind = e_data.kind;
let screen_lines = e_data.screen_lines();
create_effect(move |_| {
doc.track();
view_kind.track();
id.request_layout();
});
let hide_cursor = e_data.common.window_common.hide_cursor;
create_effect(move |_| {
hide_cursor.track();
let occurrences = doc.with(|doc| doc.find_result.occurrences);
occurrences.track();
id.request_paint();
});
create_effect(move |last_rev| {
let buffer = doc.with(|doc| doc.buffer);
let rev = buffer.with(|buffer| buffer.rev());
if last_rev == Some(rev) {
return rev;
}
id.request_layout();
rev
});
let config = e_data.common.config;
let sticky_header_height_signal = e_data.sticky_header_height;
let editor2 = e_data.clone();
create_effect(move |last_rev| {
let config = config.get();
if !config.editor.sticky_header {
return (DocContent::Local, 0, 0, Rect::ZERO, 0, None);
}
let doc = doc.get();
let rect = viewport.get();
let (screen_lines_len, screen_lines_first) = screen_lines
.with(|lines| (lines.lines.len(), lines.lines.first().copied()));
let rev = (
doc.content.get(),
doc.buffer.with(|b| b.rev()),
doc.cache_rev.get(),
rect,
screen_lines_len,
screen_lines_first,
);
if last_rev.as_ref() == Some(&rev) {
return rev;
}
let sticky_header_info = get_sticky_header_info(
&editor2,
viewport,
sticky_header_height_signal,
&config,
);
id.update_state(sticky_header_info);
rev
});
let ed1 = e_data.editor.clone();
let ed2 = ed1.clone();
let ed3 = ed1.clone();
let editor_window_origin = e_data.window_origin();
let cursor = e_data.cursor();
let find_focus = e_data.find_focus;
let ime_allowed = e_data.common.window_common.ime_allowed;
let editor_viewport = e_data.viewport();
let editor_cursor = e_data.cursor();
create_effect(move |_| {
let active = is_active.get();
if active && !find_focus.get() {
if !cursor.with(|c| c.is_insert()) {
if ime_allowed.get_untracked() {
ime_allowed.set(false);
set_ime_allowed(false);
}
} else {
if !ime_allowed.get_untracked() {
ime_allowed.set(true);
set_ime_allowed(true);
}
let (offset, affinity) = cursor.with(|c| (c.offset(), c.affinity));
let (_, point_below) = ed1.points_of_offset(offset, affinity);
let window_origin = editor_window_origin.get();
let viewport = editor_viewport.get();
let pos = window_origin
+ (point_below.x - viewport.x0, point_below.y - viewport.y0);
set_ime_cursor_area(pos, Size::new(800.0, 600.0));
}
}
});
let doc = e_data.doc_signal();
EditorView {
id,
editor: e_data,
is_active,
inner_node: None,
viewport,
debug_breakline,
}
.on_event(EventListener::ImePreedit, move |event| {
if !is_active.get_untracked() {
return EventPropagation::Continue;
}
if let Event::ImePreedit { text, cursor } = event {
if text.is_empty() {
ed2.clear_preedit();
} else {
let offset = editor_cursor.with_untracked(|c| c.offset());
ed2.set_preedit(text.clone(), *cursor, offset);
}
}
EventPropagation::Stop
})
.on_event(EventListener::ImeCommit, move |event| {
if !is_active.get_untracked() {
return EventPropagation::Continue;
}
if let Event::ImeCommit(text) = event {
ed3.clear_preedit();
ed3.receive_char(text);
}
EventPropagation::Stop
})
.class(EditorViewClass)
.style(move |s| editor_style(config, doc, s))
}
impl EditorView {
fn paint_diff_sections(
&self,
cx: &mut PaintCx,
viewport: Rect,
screen_lines: &ScreenLines,
config: &LapceConfig,
) {
let Some(diff_sections) = &screen_lines.diff_sections else {
return;
};
for section in diff_sections.iter() {
match section.kind {
DiffSectionKind::NoCode => self.paint_diff_no_code(
cx,
viewport,
section.y_idx,
section.height,
config,
),
DiffSectionKind::Added => {
cx.fill(
&Rect::ZERO
.with_size(Size::new(
viewport.width(),
(config.editor.line_height() * section.height)
as f64,
))
.with_origin(Point::new(
viewport.x0,
(section.y_idx * config.editor.line_height()) as f64,
)),
config
.color(LapceColor::SOURCE_CONTROL_ADDED)
.multiply_alpha(0.2),
0.0,
);
}
DiffSectionKind::Removed => {
cx.fill(
&Rect::ZERO
.with_size(Size::new(
viewport.width(),
(config.editor.line_height() * section.height)
as f64,
))
.with_origin(Point::new(
viewport.x0,
(section.y_idx * config.editor.line_height()) as f64,
)),
config
.color(LapceColor::SOURCE_CONTROL_REMOVED)
.multiply_alpha(0.2),
0.0,
);
}
}
}
}
fn paint_diff_no_code(
&self,
cx: &mut PaintCx,
viewport: Rect,
start_line: usize,
height: usize,
config: &LapceConfig,
) {
let line_height = config.editor.line_height();
let height = (height * line_height) as f64;
let y = (start_line * line_height) as f64;
let y_end = y + height;
if y_end < viewport.y0 || y > viewport.y1 {
return;
}
let y = y.max(viewport.y0 - 10.0);
let y_end = y_end.min(viewport.y1 + 10.0);
let height = y_end - y;
let start_x = viewport.x0.floor() as usize;
let start_x = start_x - start_x % 8;
for x in (start_x..viewport.x1.ceil() as usize + 1 + height.ceil() as usize)
.step_by(8)
{
let p0 = if x as f64 > viewport.x1.ceil() {
Point::new(viewport.x1.ceil(), y + (x as f64 - viewport.x1.ceil()))
} else {
Point::new(x as f64, y)
};
let height = if x as f64 - height < viewport.x0.floor() {
x as f64 - viewport.x0.floor()
} else {
height
};
if height > 0.0 {
let p1 = Point::new(x as f64 - height, y + height);
cx.stroke(
&Line::new(p0, p1),
config.color(LapceColor::EDITOR_DIM),
&Stroke::new(1.0),
);
}
}
}
fn paint_current_line(
&self,
cx: &mut PaintCx,
is_local: bool,
screen_lines: &ScreenLines,
) {
let e_data = self.editor.clone();
let ed = e_data.editor.clone();
let cursor = self.editor.cursor();
let config = self.editor.common.config;
let config = config.get_untracked();
let line_height = config.editor.line_height() as f64;
let viewport = self.viewport.get_untracked();
let current_line_color = ed.es.with_untracked(EditorStyle::current_line);
let breakline = self.debug_breakline.get_untracked().and_then(
|(breakline, breakline_path)| {
if e_data
.doc()
.content
.with_untracked(|c| c.path() == Some(&breakline_path))
{
Some(breakline)
} else {
None
}
},
);
// TODO: check if this is correct
if let Some(breakline) = breakline {
if let Some(info) = screen_lines.info_for_line(breakline) {
let rect = Rect::from_origin_size(
(viewport.x0, info.vline_y),
(viewport.width(), line_height),
);
cx.fill(
&rect,
config.color(LapceColor::EDITOR_DEBUG_BREAK_LINE),
0.0,
);
}
}
cursor.with_untracked(|cursor| {
let highlight_current_line = match cursor.mode {
CursorMode::Normal(_) | CursorMode::Insert(_) => true,
CursorMode::Visual { .. } => false,
};
if let Some(current_line_color) = current_line_color {
// Highlight the current line
if !is_local && highlight_current_line {
for (_, end) in cursor.regions_iter() {
// TODO: unsure if this is correct for wrapping lines
let rvline = ed.rvline_of_offset(end, cursor.affinity);
if let Some(info) = screen_lines
.info(rvline)
.filter(|_| Some(rvline.line) != breakline)
{
let rect = Rect::from_origin_size(
(viewport.x0, info.vline_y),
(viewport.width(), line_height),
);
cx.fill(&rect, current_line_color, 0.0);
}
}
}
}
});
}
fn paint_find(&self, cx: &mut PaintCx, screen_lines: &ScreenLines) {
let find_visual = self.editor.common.find.visual.get_untracked();
if !find_visual && self.editor.on_screen_find.with_untracked(|f| !f.active) {
return;
}
if screen_lines.lines.is_empty() {
return;
}
let min_vline = *screen_lines.lines.first().unwrap();
let max_vline = *screen_lines.lines.last().unwrap();
let min_line = screen_lines.info(min_vline).unwrap().vline_info.rvline.line;
let max_line = screen_lines.info(max_vline).unwrap().vline_info.rvline.line;
let e_data = &self.editor;
let ed = &e_data.editor;
let doc = e_data.doc();
let config = self.editor.common.config;
let occurrences = doc.find_result.occurrences;
let config = config.get_untracked();
let line_height = config.editor.line_height() as f64;
let color = config.color(LapceColor::EDITOR_FOREGROUND);
let start = ed.offset_of_line(min_line);
let end = ed.offset_of_line(max_line + 1);
// TODO: The selection rect creation logic for find is quite similar to the version
// within insert cursor. It would be good to deduplicate it.
if find_visual {
doc.update_find();
for region in occurrences.with_untracked(|selection| {
selection.regions_in_range(start, end).to_vec()
}) {
self.paint_find_region(
cx,
ed,
®ion,
color,
screen_lines,
line_height,
);
}
}
self.editor.on_screen_find.with_untracked(|find| {
if find.active {
for region in &find.regions {
self.paint_find_region(
cx,
ed,
region,
color,
screen_lines,
line_height,
);
}
}
});
}
fn paint_find_region(
&self,
cx: &mut PaintCx,
ed: &Editor,
region: &SelRegion,
color: Color,
screen_lines: &ScreenLines,
line_height: f64,
) {
let start = region.min();
let end = region.max();
// TODO(minor): the proper affinity here should probably be tracked by selregion
let (start_rvline, start_col) =
ed.rvline_col_of_offset(start, CursorAffinity::Forward);
let (end_rvline, end_col) =
ed.rvline_col_of_offset(end, CursorAffinity::Backward);
for line_info in screen_lines.iter_line_info() {
let rvline_info = line_info.vline_info;
let rvline = rvline_info.rvline;
let line = rvline.line;
if rvline < start_rvline {
continue;
}
if rvline > end_rvline {
break;
}
let left_col = if rvline == start_rvline { start_col } else { 0 };
let (right_col, _vline_end) = if rvline == end_rvline {
let max_col = ed.last_col(rvline_info, true);
(end_col.min(max_col), false)
} else {
(ed.last_col(rvline_info, true), true)
};
// TODO(minor): sel region should have the affinity of the start/end
let x0 = ed
.line_point_of_line_col(
line,
left_col,
CursorAffinity::Forward,
true,
)
.x;
let x1 = ed
.line_point_of_line_col(
line,
right_col,
CursorAffinity::Backward,
true,
)
.x;
if !rvline_info.is_empty() && start != end && left_col != right_col {
let rect = Size::new(x1 - x0, line_height)
.to_rect()
.with_origin(Point::new(x0, line_info.vline_y));
cx.stroke(&rect, color, &Stroke::new(1.0));
}
}
}
fn paint_sticky_headers(
&self,
cx: &mut PaintCx,
viewport: Rect,
screen_lines: &ScreenLines,
) {
let config = self.editor.common.config.get_untracked();
if !config.editor.sticky_header {
return;
}
if !self.editor.kind.get_untracked().is_normal() {
return;
}
let line_height = config.editor.line_height();
let Some(start_vline) = screen_lines.lines.first() else {
return;
};
let start_info = screen_lines.vline_info(*start_vline).unwrap();
let start_line = start_info.rvline.line;
let sticky_header_info = self.editor.sticky_header_info.get_untracked();
let total_sticky_lines = sticky_header_info.sticky_lines.len();
let paint_last_line = total_sticky_lines > 0
&& (sticky_header_info.last_sticky_should_scroll
|| sticky_header_info.y_diff != 0.0
|| start_line + total_sticky_lines - 1
!= *sticky_header_info.sticky_lines.last().unwrap());
let total_sticky_lines = if paint_last_line {
total_sticky_lines
} else {
total_sticky_lines.saturating_sub(1)
};
if total_sticky_lines == 0 {
return;
}
let scroll_offset = if sticky_header_info.last_sticky_should_scroll {
sticky_header_info.y_diff
} else {
0.0
};
// Clear background
let area_height = sticky_header_info
.sticky_lines
.iter()
.copied()
.map(|line| {
let layout = self.editor.editor.text_layout(line);
layout.line_count() * line_height
})
.sum::<usize>() as f64
- scroll_offset;
let sticky_area_rect = Size::new(viewport.x1, area_height)
.to_rect()
.with_origin(Point::new(0.0, viewport.y0))
.inflate(10.0, 0.0);
cx.fill(
&sticky_area_rect,
config.color(LapceColor::LAPCE_DROPDOWN_SHADOW),
3.0,
);
cx.fill(
&sticky_area_rect,
config.color(LapceColor::EDITOR_STICKY_HEADER_BACKGROUND),
0.0,
);
self.editor.sticky_header_info.get_untracked();
// Paint lines
let mut y_accum = 0.0;
for (i, line) in sticky_header_info.sticky_lines.iter().copied().enumerate()
{
let y_diff = if i == total_sticky_lines - 1 {
scroll_offset
} else {
0.0
};
let text_layout = self.editor.editor.text_layout(line);
let text_height = (text_layout.line_count() * line_height) as f64;
let height = text_height - y_diff;
cx.save();
let line_area_rect = Size::new(viewport.width(), height)
.to_rect()
.with_origin(Point::new(viewport.x0, viewport.y0 + y_accum));
cx.clip(&line_area_rect);
let y = viewport.y0 - y_diff + y_accum;
cx.draw_text(&text_layout.text, Point::new(viewport.x0, y));
y_accum += text_height;
cx.restore();
}
}
fn paint_scroll_bar(
&self,
cx: &mut PaintCx,
viewport: Rect,
is_local: bool,
config: Arc<LapceConfig>,
) {
const BAR_WIDTH: f64 = 10.0;
if is_local {
return;
}
cx.fill(
&Rect::ZERO
.with_size(Size::new(1.0, viewport.height()))
.with_origin(Point::new(
viewport.x0 + viewport.width() - BAR_WIDTH,
viewport.y0,
))
.inflate(0.0, 10.0),
config.color(LapceColor::LAPCE_SCROLL_BAR),
0.0,
);
if !self.editor.kind.get_untracked().is_normal() {
return;
}
let doc = self.editor.doc();
let total_len = doc.buffer.with_untracked(|buffer| buffer.last_line());
let changes = doc.head_changes().get_untracked();
let total_height = viewport.height();
let total_width = viewport.width();
let line_height = config.editor.line_height();
let content_height = if config.editor.scroll_beyond_last_line {
(total_len * line_height) as f64 + total_height - line_height as f64
} else {
(total_len * line_height) as f64
};
let colors = changes_colors_all(&config, &self.editor.editor, changes);
for (y, height, _, color) in colors {
let y = y / content_height * total_height;
let height = ((height * line_height) as f64 / content_height
* total_height)
.max(3.0);
let rect = Rect::ZERO.with_size(Size::new(3.0, height)).with_origin(
Point::new(
viewport.x0 + total_width - BAR_WIDTH + 1.0,
y + viewport.y0,
),
);
cx.fill(&rect, color, 0.0);
}
}
/// Paint a highlight around the characters at the given positions.
fn paint_char_highlights(
&self,
cx: &mut PaintCx,
screen_lines: &ScreenLines,
highlight_line_cols: impl Iterator<Item = (RVLine, usize)>,
) {
let editor = &self.editor.editor;
let config = self.editor.common.config.get_untracked();
let line_height = config.editor.line_height() as f64;
for (rvline, col) in highlight_line_cols {
// Is the given line on screen?
if let Some(line_info) = screen_lines.info(rvline) {
let x0 = editor
.line_point_of_line_col(
rvline.line,
col,
CursorAffinity::Forward,
true,
)
.x;
let x1 = editor
.line_point_of_line_col(
rvline.line,
col + 1,
CursorAffinity::Backward,
true,
)
.x;
let y0 = line_info.vline_y;
let y1 = y0 + line_height;
let rect = Rect::new(x0, y0, x1, y1);
cx.stroke(
&rect,
config.color(LapceColor::EDITOR_FOREGROUND),
&Stroke::new(1.0),
);
}
}
}
/// Paint scope lines between `(start_rvline, start_line, start_col)` and
/// `(end_rvline, end_line end_col)`.
fn paint_scope_lines(
&self,
cx: &mut PaintCx,
viewport: Rect,
screen_lines: &ScreenLines,
(start, start_col): (RVLine, usize),
(end, end_col): (RVLine, usize),
) {
let editor = &self.editor.editor;
let doc = self.editor.doc();
let config = self.editor.common.config.get_untracked();
let line_height = config.editor.line_height() as f64;
let brush = config.color(LapceColor::EDITOR_FOREGROUND);
if start == end {
if let Some(line_info) = screen_lines.info(start) {
// TODO: Due to line wrapping the y positions of these two spots could be different, do we need to change it?
let x0 = editor
.line_point_of_line_col(
start.line,
start_col + 1,
CursorAffinity::Forward,
true,
)
.x;
let x1 = editor
.line_point_of_line_col(
end.line,
end_col,
CursorAffinity::Backward,
true,
)
.x;
if x0 < x1 {
let y = line_info.vline_y + line_height;
let p0 = Point::new(x0, y);
let p1 = Point::new(x1, y);
let line = Line::new(p0, p1);
cx.stroke(&line, brush, &Stroke::new(1.0));
}
}
} else {
// Are start_line and end_line on screen?
let start_line_y = screen_lines
.info(start)
.map(|line_info| line_info.vline_y + line_height);
let end_line_y = screen_lines
.info(end)
.map(|line_info| line_info.vline_y + line_height);
// We only need to draw anything if start_line is on or before the visible section and
// end_line is on or after the visible section.
let y0 = start_line_y.or_else(|| {
screen_lines
.lines
.first()
.is_some_and(|&first_vline| first_vline > start)
.then(|| viewport.min_y())
});
let y1 = end_line_y.or_else(|| {
screen_lines
.lines
.last()
.is_some_and(|&last_line| last_line < end)
.then(|| viewport.max_y())
});
if let [Some(y0), Some(y1)] = [y0, y1] {
let start_x = editor
.line_point_of_line_col(
start.line,
start_col + 1,
CursorAffinity::Forward,
true,
)
.x;
let end_x = editor
.line_point_of_line_col(
end.line,
end_col,
CursorAffinity::Backward,
true,
)
.x;
// TODO(minor): is this correct with line wrapping?
// The vertical line should be drawn to the left of any non-whitespace characters
// in the enclosed section.
let min_text_x = doc.buffer.with_untracked(|buffer| {
((start.line + 1)..=end.line)
.filter(|&line| !buffer.is_line_whitespace(line))
.map(|line| {
let non_blank_offset =
buffer.first_non_blank_character_on_line(line);
let (_, col) =
editor.offset_to_line_col(non_blank_offset);
editor
.line_point_of_line_col(
line,
col,
CursorAffinity::Backward,
true,
)
.x
})
.min_by(f64::total_cmp)
});
let min_x = min_text_x.map_or(start_x, |min_text_x| {
cmp::min_by(min_text_x, start_x, f64::total_cmp)
});
// Is start_line on screen, and is the vertical line to the left of the opening
// bracket?
if let Some(y) = start_line_y.filter(|_| start_x > min_x) {
let p0 = Point::new(min_x, y);
let p1 = Point::new(start_x, y);
let line = Line::new(p0, p1);
cx.stroke(&line, brush, &Stroke::new(1.0));
}
// Is end_line on screen, and is the vertical line to the left of the closing
// bracket?
if let Some(y) = end_line_y.filter(|_| end_x > min_x) {
let p0 = Point::new(min_x, y);
let p1 = Point::new(end_x, y);
let line = Line::new(p0, p1);
cx.stroke(&line, brush, &Stroke::new(1.0));
}
let p0 = Point::new(min_x, y0);
let p1 = Point::new(min_x, y1);
let line = Line::new(p0, p1);
cx.stroke(&line, brush, &Stroke::new(1.0));
}
}
}
/// Paint enclosing bracket highlights and scope lines if the corresponding settings are
/// enabled.
fn paint_bracket_highlights_scope_lines(
&self,
cx: &mut PaintCx,
viewport: Rect,
screen_lines: &ScreenLines,
) {
let config = self.editor.common.config.get_untracked();
if config.editor.highlight_matching_brackets
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | true |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/editor/diff.rs | lapce-app/src/editor/diff.rs | use std::{rc::Rc, sync::atomic};
use floem::{
View,
event::{Event, EventListener},
ext_event::create_ext_action,
reactive::{RwSignal, Scope, SignalGet, SignalUpdate, SignalWith},
style::CursorStyle,
views::{
Decorators, clip, dyn_stack, editor::id::EditorId, empty, label, stack, svg,
},
};
use lapce_core::buffer::{
diff::{DiffExpand, DiffLines, expand_diff_lines, rope_diff},
rope_text::RopeText,
};
use lapce_rpc::{buffer::BufferId, proxy::ProxyResponse};
use lapce_xi_rope::Rope;
use serde::{Deserialize, Serialize};
use super::{EditorData, EditorViewKind};
use crate::{
config::{color::LapceColor, icon::LapceIcons},
doc::{Doc, DocContent},
id::{DiffEditorId, EditorTabId},
main_split::{Editors, MainSplitData},
wave::wave_box,
window_tab::CommonData,
};
#[derive(Clone)]
pub struct DiffInfo {
pub is_right: bool,
pub changes: Vec<DiffLines>,
}
#[derive(Clone, Serialize, Deserialize)]
pub struct DiffEditorInfo {
pub left_content: DocContent,
pub right_content: DocContent,
}
impl DiffEditorInfo {
pub fn to_data(
&self,
data: MainSplitData,
editor_tab_id: EditorTabId,
) -> DiffEditorData {
let cx = data.scope.create_child();
let diff_editor_id = DiffEditorId::next();
let new_doc = {
let data = data.clone();
let common = data.common.clone();
move |content: &DocContent| match content {
DocContent::File { path, .. } => {
let (doc, _) = data.get_doc(path.clone(), None);
doc
}
DocContent::Local => {
Rc::new(Doc::new_local(cx, data.editors, common.clone()))
}
DocContent::History(history) => {
let doc = Doc::new_history(
cx,
content.clone(),
data.editors,
common.clone(),
);
let doc = Rc::new(doc);
{
let doc = doc.clone();
let send = create_ext_action(cx, move |result| {
if let Ok(ProxyResponse::BufferHeadResponse {
content,
..
}) = result
{
doc.init_content(Rope::from(content));
}
});
common.proxy.get_buffer_head(
history.path.clone(),
move |result| {
send(result);
},
);
}
doc
}
DocContent::Scratch { name, .. } => {
let doc_content = DocContent::Scratch {
id: BufferId::next(),
name: name.to_string(),
};
let doc = Doc::new_content(
cx,
doc_content,
data.editors,
common.clone(),
);
let doc = Rc::new(doc);
data.scratch_docs.update(|scratch_docs| {
scratch_docs.insert(name.to_string(), doc.clone());
});
doc
}
}
};
let left_doc = new_doc(&self.left_content);
let right_doc = new_doc(&self.right_content);
let diff_editor_data = DiffEditorData::new(
cx,
diff_editor_id,
editor_tab_id,
left_doc,
right_doc,
data.editors,
data.common.clone(),
);
data.diff_editors.update(|diff_editors| {
diff_editors.insert(diff_editor_id, diff_editor_data.clone());
});
diff_editor_data
}
}
#[derive(Clone)]
pub struct DiffEditorData {
pub id: DiffEditorId,
pub editor_tab_id: RwSignal<EditorTabId>,
pub scope: Scope,
pub left: EditorData,
pub right: EditorData,
pub confirmed: RwSignal<bool>,
pub focus_right: RwSignal<bool>,
}
impl DiffEditorData {
pub fn new(
cx: Scope,
id: DiffEditorId,
editor_tab_id: EditorTabId,
left_doc: Rc<Doc>,
right_doc: Rc<Doc>,
editors: Editors,
common: Rc<CommonData>,
) -> Self {
let cx = cx.create_child();
let confirmed = cx.create_rw_signal(false);
// TODO: ensure that left/right are cleaned up
let [left, right] = [left_doc, right_doc].map(|doc| {
editors.make_from_doc(
cx,
doc,
None,
Some((editor_tab_id, id)),
Some(confirmed),
common.clone(),
)
});
let data = Self {
id,
editor_tab_id: cx.create_rw_signal(editor_tab_id),
scope: cx,
left,
right,
confirmed,
focus_right: cx.create_rw_signal(true),
};
data.listen_diff_changes();
data
}
pub fn diff_editor_info(&self) -> DiffEditorInfo {
DiffEditorInfo {
left_content: self.left.doc().content.get_untracked(),
right_content: self.right.doc().content.get_untracked(),
}
}
pub fn copy(
&self,
cx: Scope,
editor_tab_id: EditorTabId,
diff_editor_id: EditorId,
editors: Editors,
) -> Self {
let cx = cx.create_child();
let confirmed = cx.create_rw_signal(true);
let [left, right] = [&self.left, &self.right].map(|editor_data| {
editors
.make_copy(
editor_data.id(),
cx,
None,
Some((editor_tab_id, diff_editor_id)),
Some(confirmed),
)
.unwrap()
});
let diff_editor = DiffEditorData {
scope: cx,
id: diff_editor_id,
editor_tab_id: cx.create_rw_signal(editor_tab_id),
focus_right: cx.create_rw_signal(true),
left,
right,
confirmed,
};
diff_editor.listen_diff_changes();
diff_editor
}
fn listen_diff_changes(&self) {
let cx = self.scope;
let left = self.left.clone();
let left_doc_rev = {
let left = left.clone();
cx.create_memo(move |_| {
let doc = left.doc_signal().get();
(doc.content.get(), doc.buffer.with(|b| b.rev()))
})
};
let right = self.right.clone();
let right_doc_rev = {
let right = right.clone();
cx.create_memo(move |_| {
let doc = right.doc_signal().get();
(doc.content.get(), doc.buffer.with(|b| b.rev()))
})
};
cx.create_effect(move |_| {
let (_, left_rev) = left_doc_rev.get();
let (left_editor_view, left_doc) = (left.kind, left.doc());
let (left_atomic_rev, left_rope) =
left_doc.buffer.with_untracked(|buffer| {
(buffer.atomic_rev(), buffer.text().clone())
});
let (_, right_rev) = right_doc_rev.get();
let (right_editor_view, right_doc) = (right.kind, right.doc());
let (right_atomic_rev, right_rope) =
right_doc.buffer.with_untracked(|buffer| {
(buffer.atomic_rev(), buffer.text().clone())
});
let send = {
let right_atomic_rev = right_atomic_rev.clone();
create_ext_action(cx, move |changes: Option<Vec<DiffLines>>| {
let changes = if let Some(changes) = changes {
changes
} else {
return;
};
if left_atomic_rev.load(atomic::Ordering::Acquire) != left_rev {
return;
}
if right_atomic_rev.load(atomic::Ordering::Acquire) != right_rev
{
return;
}
left_editor_view.set(EditorViewKind::Diff(DiffInfo {
is_right: false,
changes: changes.clone(),
}));
right_editor_view.set(EditorViewKind::Diff(DiffInfo {
is_right: true,
changes,
}));
})
};
rayon::spawn(move || {
let changes = rope_diff(
left_rope,
right_rope,
right_rev,
right_atomic_rev.clone(),
Some(3),
);
send(changes);
});
});
}
}
#[derive(Clone, PartialEq)]
struct DiffShowMoreSection {
left_actual_line: usize,
right_actual_line: usize,
skip_start: usize,
lines: usize,
}
pub fn diff_show_more_section_view(
left_editor: &EditorData,
right_editor: &EditorData,
) -> impl View + use<> {
let left_editor_view = left_editor.kind;
let right_editor_view = right_editor.kind;
let right_screen_lines = right_editor.screen_lines();
let right_scroll_delta = right_editor.editor.scroll_delta;
let viewport = right_editor.viewport();
let config = right_editor.common.config;
let each_fn = move || {
let editor_view = right_editor_view.get();
if let EditorViewKind::Diff(diff_info) = editor_view {
diff_info
.changes
.iter()
.filter_map(|change| {
let DiffLines::Both(info) = change else {
return None;
};
let skip = info.skip.as_ref()?;
Some(DiffShowMoreSection {
left_actual_line: info.left.start,
right_actual_line: info.right.start,
skip_start: skip.start,
lines: skip.len(),
})
})
.collect()
} else {
Vec::new()
}
};
let key_fn = move |section: &DiffShowMoreSection| {
(
section.right_actual_line + section.skip_start,
section.lines,
)
};
let view_fn = move |section: DiffShowMoreSection| {
stack((
wave_box().style(move |s| {
s.absolute()
.size_pct(100.0, 100.0)
.color(config.get().color(LapceColor::PANEL_BACKGROUND))
}),
label(move || format!("{} Hidden Lines", section.lines)),
label(|| "|".to_string()).style(|s| s.margin_left(10.0)),
stack((
svg(move || config.get().ui_svg(LapceIcons::FOLD)).style(move |s| {
let config = config.get();
let size = config.ui.icon_size() as f32;
s.size(size, size)
.color(config.color(LapceColor::EDITOR_FOREGROUND))
}),
label(|| "Expand All".to_string()).style(|s| s.margin_left(6.0)),
))
.on_event_stop(EventListener::PointerDown, move |_| {})
.on_click_stop(move |_event| {
left_editor_view.update(|editor_view| {
if let EditorViewKind::Diff(diff_info) = editor_view {
expand_diff_lines(
&mut diff_info.changes,
section.left_actual_line,
DiffExpand::All,
false,
);
}
});
right_editor_view.update(|editor_view| {
if let EditorViewKind::Diff(diff_info) = editor_view {
expand_diff_lines(
&mut diff_info.changes,
section.right_actual_line,
DiffExpand::All,
true,
);
}
});
})
.style(|s| {
s.margin_left(10.0)
.height_pct(100.0)
.items_center()
.hover(|s| s.cursor(CursorStyle::Pointer))
}),
label(|| "|".to_string()).style(|s| s.margin_left(10.0)),
stack((
svg(move || config.get().ui_svg(LapceIcons::FOLD_UP)).style(
move |s| {
let config = config.get();
let size = config.ui.icon_size() as f32;
s.size(size, size)
.color(config.color(LapceColor::EDITOR_FOREGROUND))
},
),
label(|| "Expand Up".to_string()).style(|s| s.margin_left(6.0)),
))
.on_event_stop(EventListener::PointerDown, move |_| {})
.on_click_stop(move |_event| {
left_editor_view.update(|editor_view| {
if let EditorViewKind::Diff(diff_info) = editor_view {
expand_diff_lines(
&mut diff_info.changes,
section.left_actual_line,
DiffExpand::Up(10),
false,
);
}
});
right_editor_view.update(|editor_view| {
if let EditorViewKind::Diff(diff_info) = editor_view {
expand_diff_lines(
&mut diff_info.changes,
section.right_actual_line,
DiffExpand::Up(10),
true,
);
}
});
})
.style(move |s| {
s.margin_left(10.0)
.height_pct(100.0)
.items_center()
.hover(|s| s.cursor(CursorStyle::Pointer))
}),
label(|| "|".to_string()).style(|s| s.margin_left(10.0)),
stack((
svg(move || config.get().ui_svg(LapceIcons::FOLD_DOWN)).style(
move |s| {
let config = config.get();
let size = config.ui.icon_size() as f32;
s.size(size, size)
.color(config.color(LapceColor::EDITOR_FOREGROUND))
},
),
label(|| "Expand Down".to_string()).style(|s| s.margin_left(6.0)),
))
.on_event_stop(EventListener::PointerDown, move |_| {})
.on_click_stop(move |_event| {
left_editor_view.update(|editor_view| {
if let EditorViewKind::Diff(diff_info) = editor_view {
expand_diff_lines(
&mut diff_info.changes,
section.left_actual_line,
DiffExpand::Down(10),
false,
);
}
});
right_editor_view.update(|editor_view| {
if let EditorViewKind::Diff(diff_info) = editor_view {
expand_diff_lines(
&mut diff_info.changes,
section.right_actual_line,
DiffExpand::Down(10),
true,
);
}
});
})
.style(move |s| {
s.margin_left(10.0)
.height_pct(100.0)
.items_center()
.hover(|s| s.cursor(CursorStyle::Pointer))
}),
))
.on_event_cont(EventListener::PointerWheel, move |event| {
if let Event::PointerWheel(event) = event {
right_scroll_delta.set(event.delta);
}
})
.style(move |s| {
let right_screen_lines = right_screen_lines.get();
let mut right_line = section.right_actual_line + section.skip_start;
let is_before_skip = if right_line > 0 {
right_line -= 1;
true
} else {
right_line += section.lines;
false
};
let Some(line_info) = right_screen_lines.info_for_line(right_line)
else {
return s.hide();
};
let config = config.get();
let line_height = config.editor.line_height();
let mut y = line_info.y - viewport.get().y0;
if is_before_skip {
y += line_height as f64
} else {
y -= line_height as f64
}
s.absolute()
.width_pct(100.0)
.height(line_height as f32)
.justify_center()
.items_center()
.margin_top(y)
.pointer_events_auto()
.hover(|s| s.cursor(CursorStyle::Default))
})
};
stack((
empty().style(move |s| {
s.height(config.get().editor.line_height() as f32 + 1.0)
}),
clip(
dyn_stack(each_fn, key_fn, view_fn)
.style(|s| s.flex_col().size_pct(100.0, 100.0)),
)
.style(|s| s.size_pct(100.0, 100.0)),
))
.style(|s| {
s.absolute()
.flex_col()
.size_pct(100.0, 100.0)
.pointer_events_none()
})
.debug_name("Diff Show More Section")
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/editor/location.rs | lapce-app/src/editor/location.rs | use std::path::PathBuf;
use floem::peniko::kurbo::Vec2;
use lapce_core::{buffer::rope_text::RopeText, rope_text_pos::RopeTextPosition};
use lsp_types::Position;
#[derive(Clone, Debug, PartialEq)]
pub struct EditorLocation {
pub path: PathBuf,
pub position: Option<EditorPosition>,
pub scroll_offset: Option<Vec2>,
// This will ignore unconfirmed editors, and always create new editors
// if there's no match path on the active editor tab
pub ignore_unconfirmed: bool,
// This will stop finding matching path on different editor tabs
pub same_editor_tab: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EditorPosition {
Line(usize),
Position(Position),
Offset(usize),
}
impl EditorPosition {
pub fn to_offset(&self, text: &impl RopeText) -> usize {
match self {
EditorPosition::Line(n) => text.first_non_blank_character_on_line(*n),
EditorPosition::Position(position) => text.offset_of_position(position),
EditorPosition::Offset(offset) => *offset,
}
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/panel/document_symbol.rs | lapce-app/src/panel/document_symbol.rs | use std::{ops::AddAssign, path::PathBuf, rc::Rc};
use floem::{
View,
peniko::Color,
reactive::{RwSignal, Scope, SignalGet, SignalUpdate, SignalWith},
style::CursorStyle,
views::{
Decorators, VirtualVector, container, editor::id::Id, label, scroll, stack,
svg, virtual_stack,
},
};
use lsp_types::{DocumentSymbol, SymbolKind};
use super::position::PanelPosition;
use crate::{
command::InternalCommand,
config::{color::LapceColor, icon::LapceIcons},
editor::location::EditorLocation,
window_tab::WindowTabData,
};
#[derive(Clone, Debug)]
pub struct SymbolData {
pub path: PathBuf,
pub file: RwSignal<SymbolInformationItemData>,
}
impl SymbolData {
pub fn new(
items: Vec<RwSignal<SymbolInformationItemData>>,
path: PathBuf,
cx: Scope,
) -> Self {
let name = path
.file_name()
.and_then(|x| x.to_str())
.map(|x| x.to_string())
.unwrap_or_default();
#[allow(deprecated)]
let file_ds = DocumentSymbol {
name: name.clone(),
detail: None,
kind: SymbolKind::FILE,
tags: None,
deprecated: None,
range: Default::default(),
selection_range: Default::default(),
children: None,
};
let file = cx.create_rw_signal(SymbolInformationItemData {
id: Id::next(),
name,
detail: None,
item: file_ds,
open: cx.create_rw_signal(true),
children: items,
});
Self { path, file }
}
fn get_children(
&self,
min: usize,
max: usize,
) -> Vec<(
usize,
usize,
Rc<PathBuf>,
RwSignal<SymbolInformationItemData>,
)> {
let path = Rc::new(self.path.clone());
let level: usize = 0;
let mut next = 0;
get_children(self.file, &mut next, min, max, level, path.clone())
}
}
#[derive(Debug, Clone)]
pub struct SymbolInformationItemData {
pub id: Id,
pub name: String,
pub detail: Option<String>,
pub item: DocumentSymbol,
pub open: RwSignal<bool>,
pub children: Vec<RwSignal<SymbolInformationItemData>>,
}
impl From<(DocumentSymbol, Scope)> for SymbolInformationItemData {
fn from((mut item, cx): (DocumentSymbol, Scope)) -> Self {
let children = if let Some(children) = item.children.take() {
children
.into_iter()
.map(|x| cx.create_rw_signal(Self::from((x, cx))))
.collect()
} else {
Vec::with_capacity(0)
};
Self {
id: Id::next(),
name: item.name.clone(),
detail: item.detail.clone(),
item,
open: cx.create_rw_signal(true),
children,
}
}
}
impl SymbolInformationItemData {
pub fn child_count(&self) -> usize {
let mut count = 1;
if self.open.get() {
for child in &self.children {
count += child.with(|x| x.child_count())
}
}
count
}
}
fn get_children(
data: RwSignal<SymbolInformationItemData>,
next: &mut usize,
min: usize,
max: usize,
level: usize,
path: Rc<PathBuf>,
) -> Vec<(
usize,
usize,
Rc<PathBuf>,
RwSignal<SymbolInformationItemData>,
)> {
let mut children = Vec::new();
if *next >= min && *next < max {
children.push((*next, level, path.clone(), data));
} else if *next >= max {
return children;
}
next.add_assign(1);
if data.get_untracked().open.get() {
for child in data.get().children {
let child_children =
get_children(child, next, min, max, level + 1, path.clone());
children.extend(child_children);
if *next > max {
break;
}
}
}
children
}
pub struct VirtualList {
root: Option<RwSignal<Option<SymbolData>>>,
}
impl VirtualList {
pub fn new(root: Option<RwSignal<Option<SymbolData>>>) -> Self {
Self { root }
}
}
impl
VirtualVector<(
usize,
usize,
Rc<PathBuf>,
RwSignal<SymbolInformationItemData>,
)> for VirtualList
{
fn total_len(&self) -> usize {
if let Some(root) = self.root.as_ref().and_then(|x| x.get()) {
root.file.get_untracked().child_count()
} else {
0
}
}
fn slice(
&mut self,
range: std::ops::Range<usize>,
) -> impl Iterator<
Item = (
usize,
usize,
Rc<PathBuf>,
RwSignal<SymbolInformationItemData>,
),
> {
if let Some(root) = self.root.as_ref().and_then(|x| x.get()) {
let min = range.start;
let max = range.end;
let children = root.get_children(min, max);
children.into_iter()
} else {
Vec::new().into_iter()
}
}
}
pub fn symbol_panel(
window_tab_data: Rc<WindowTabData>,
_position: PanelPosition,
) -> impl View {
let config = window_tab_data.common.config;
let ui_line_height = window_tab_data.common.ui_line_height;
scroll(
virtual_stack(
{
let window_tab_data = window_tab_data.clone();
move || {
let editor = window_tab_data.main_split.get_active_editor();
VirtualList::new(editor.map(|x| x.doc().document_symbol_data))
}
},
move |(_, _, _, item)| item.get_untracked().id,
move |(_, level, path, rw_data)| {
let data = rw_data.get_untracked();
let open = data.open;
let has_child = !data.children.is_empty();
let kind = data.item.kind;
stack((
container(
svg(move || {
let config = config.get();
let svg_str = match open.get() {
true => LapceIcons::ITEM_OPENED,
false => LapceIcons::ITEM_CLOSED,
};
config.ui_svg(svg_str)
})
.style(move |s| {
let config = config.get();
let color = if has_child {
config.color(LapceColor::LAPCE_ICON_ACTIVE)
} else {
Color::TRANSPARENT
};
let size = config.ui.icon_size() as f32;
s.size(size, size)
.color(color)
})
).style(|s| s.padding(4.0).margin_left(6.0).margin_right(2.0))
.on_click_stop({
move |_x| {
if has_child {
open.update(|x| {
*x = !*x;
});
}
}
}),
svg(move || {
let config = config.get();
config
.symbol_svg(&kind)
.unwrap_or_else(|| config.ui_svg(LapceIcons::FILE))
}).style(move |s| {
let config = config.get();
let size = config.ui.icon_size() as f32;
s.min_width(size)
.size(size, size)
.margin_right(5.0)
.color(config.symbol_color(&kind).unwrap_or_else(|| {
config.color(LapceColor::LAPCE_ICON_ACTIVE)
}))
}),
label(move || {
data.name.replace('\n', "↵")
})
.style(move |s| {
s.selectable(false)
}),
label(move || {
data.detail.clone().unwrap_or_default()
}).style(move |s| s.margin_left(6.0)
.color(config.get().color(LapceColor::EDITOR_DIM))
.selectable(false)
.apply_if(
data.item.detail.clone().is_none(),
|s| s.hide())
),
))
.style(move |s| {
s.padding_right(5.0)
.padding_left((level * 10) as f32)
.items_center()
.height(ui_line_height.get())
.hover(|s| {
s.background(
config
.get()
.color(LapceColor::PANEL_HOVERED_BACKGROUND),
)
.cursor(CursorStyle::Pointer)
})
})
.on_click_stop({
let window_tab_data = window_tab_data.clone();
let data = rw_data;
move |_| {
let data = data.get_untracked();
window_tab_data
.common
.internal_command
.send(InternalCommand::JumpToLocation { location: EditorLocation {
path: path.to_path_buf(),
position: Some(crate::editor::location::EditorPosition::Position(data.item.selection_range.start)),
scroll_offset: None,
ignore_unconfirmed: false,
same_editor_tab: false,
} });
}
})
},
).item_size_fixed(move || ui_line_height.get())
.style(|s| s.flex_col().absolute().min_width_full()),
)
.style(|s| s.absolute().size_full())
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/panel/terminal_view.rs | lapce-app/src/panel/terminal_view.rs | use std::rc::Rc;
use floem::{
View, ViewId,
action::show_context_menu,
event::{Event, EventListener, EventPropagation},
kurbo::Size,
menu::{Menu, MenuItem},
reactive::{SignalGet, SignalUpdate, SignalWith, create_rw_signal},
style::CursorStyle,
views::{
Decorators, container, dyn_stack, empty, label,
scroll::{Thickness, VerticalScrollAsHorizontal, scroll},
stack, svg, tab,
},
};
use lapce_rpc::terminal::TermId;
use super::kind::PanelKind;
use crate::{
app::clickable_icon,
command::{InternalCommand, LapceWorkbenchCommand},
config::{color::LapceColor, icon::LapceIcons},
debug::RunDebugMode,
listener::Listener,
terminal::{
panel::TerminalPanelData, tab::TerminalTabData, view::terminal_view,
},
window_tab::{Focus, WindowTabData},
};
pub fn terminal_panel(window_tab_data: Rc<WindowTabData>) -> impl View {
let focus = window_tab_data.common.focus;
stack((
terminal_tab_header(window_tab_data.clone()),
terminal_tab_content(window_tab_data.clone()),
))
.on_event_cont(EventListener::PointerDown, move |_| {
if focus.get_untracked() != Focus::Panel(PanelKind::Terminal) {
focus.set(Focus::Panel(PanelKind::Terminal));
}
})
.style(|s| s.absolute().size_pct(100.0, 100.0).flex_col())
.debug_name("Terminal Panel")
}
fn terminal_tab_header(window_tab_data: Rc<WindowTabData>) -> impl View {
let terminal = window_tab_data.terminal.clone();
let config = window_tab_data.common.config;
let focus = window_tab_data.common.focus;
let active_index = move || terminal.tab_info.with(|info| info.active);
let tab_info = terminal.tab_info;
let header_width = create_rw_signal(0.0);
let header_height = create_rw_signal(0.0);
let icon_width = create_rw_signal(0.0);
let scroll_size = create_rw_signal(Size::ZERO);
let workbench_command = window_tab_data.common.workbench_command;
stack((
scroll(dyn_stack(
move || {
let tabs = terminal.tab_info.with(|info| info.tabs.clone());
for (i, (index, _)) in tabs.iter().enumerate() {
if index.get_untracked() != i {
index.set(i);
}
}
tabs
},
|(_, tab)| tab.terminal_tab_id,
move |(index, tab)| {
let terminal = terminal.clone();
let local_terminal = terminal.clone();
let terminal_tab_id = tab.terminal_tab_id;
let title = {
let tab = tab.clone();
move || {
let terminal = tab.active_terminal(true);
let run_debug = terminal.as_ref().map(|t| t.run_debug);
if let Some(run_debug) = run_debug {
if let Some(name) = run_debug.with(|run_debug| {
run_debug.as_ref().map(|r| r.config.name.clone())
}) {
return name;
}
}
let title = terminal.map(|t| t.title);
let title = title.map(|t| t.get());
title.unwrap_or_default()
}
};
let svg_string = move || {
let terminal = tab.active_terminal(true);
let run_debug = terminal.as_ref().map(|t| t.run_debug);
if let Some(run_debug) = run_debug {
if let Some((mode, stopped)) = run_debug.with(|run_debug| {
run_debug.as_ref().map(|r| (r.mode, r.stopped))
}) {
let svg = match (mode, stopped) {
(RunDebugMode::Run, false) => LapceIcons::START,
(RunDebugMode::Run, true) => LapceIcons::RUN_ERRORS,
(RunDebugMode::Debug, false) => LapceIcons::DEBUG,
(RunDebugMode::Debug, true) => {
LapceIcons::DEBUG_DISCONNECT
}
};
return svg;
}
}
LapceIcons::TERMINAL
};
stack((
container({
stack((
container(
svg(move || config.get().ui_svg(svg_string()))
.style(move |s| {
let config = config.get();
let size = config.ui.icon_size() as f32;
s.size(size, size).color(
config.color(
LapceColor::LAPCE_ICON_ACTIVE,
),
)
}),
)
.style(|s| s.padding_horiz(10.0).padding_vert(12.0)),
label(title).style(|s| {
s.min_width(0.0)
.flex_basis(0.0)
.flex_grow(1.0)
.text_ellipsis()
.selectable(false)
}),
clickable_icon(
|| LapceIcons::CLOSE,
move || {
terminal.close_tab(Some(terminal_tab_id));
},
|| false,
|| false,
|| "Close",
config,
)
.style(|s| s.margin_horiz(6.0)),
empty().style(move |s| {
s.absolute()
.width_full()
.height(header_height.get() - 15.0)
.border_right(1.0)
.border_color(
config.get().color(LapceColor::LAPCE_BORDER),
)
.pointer_events_none()
}),
))
.style(move |s| {
s.items_center().width(200.0).border_color(
config.get().color(LapceColor::LAPCE_BORDER),
)
})
})
.style(|s| s.items_center()),
container({
label(|| "".to_string()).style(move |s| {
s.size_pct(100.0, 100.0)
.border_bottom(if active_index() == index.get() {
2.0
} else {
0.0
})
.border_color(config.get().color(
if focus.get()
== Focus::Panel(PanelKind::Terminal)
{
LapceColor::LAPCE_TAB_ACTIVE_UNDERLINE
} else {
LapceColor::LAPCE_TAB_INACTIVE_UNDERLINE
},
))
})
})
.style(|s| {
s.absolute()
.padding_horiz(3.0)
.size_pct(100.0, 100.0)
.pointer_events_none()
}),
))
.style(|s| s.cursor(CursorStyle::Pointer))
.on_event_cont(
EventListener::PointerDown,
move |_| {
if tab_info.with_untracked(|tab| tab.active)
!= index.get_untracked()
{
tab_info.update(|tab| {
tab.active = index.get_untracked();
});
local_terminal.update_debug_active_term();
}
},
)
},
))
.on_resize(move |rect| {
if rect.size() != scroll_size.get_untracked() {
scroll_size.set(rect.size());
}
})
.style(move |s| {
let header_width = header_width.get();
let icon_width = icon_width.get();
s.set(VerticalScrollAsHorizontal, true)
.absolute()
.max_width(header_width - icon_width)
.set(Thickness, 3)
}),
empty().style(move |s| {
let size = scroll_size.get();
s.size(size.width, size.height).pointer_events_none()
}),
container(clickable_icon(
|| LapceIcons::ADD,
move || {
workbench_command.send(LapceWorkbenchCommand::NewTerminalTab);
},
|| false,
|| false,
|| "New Terminal",
config,
))
.on_resize(move |rect| {
let width = rect.size().width;
if icon_width.get_untracked() != width {
icon_width.set(width);
}
})
.style(|s| s.padding_horiz(10)),
))
.on_resize(move |rect| {
let size = rect.size();
if header_width.get_untracked() != size.width {
header_width.set(size.width);
}
if header_height.get_untracked() != size.height {
header_height.set(size.height);
}
})
.on_double_click(move |_| {
window_tab_data
.panel
.toggle_maximize(&crate::panel::kind::PanelKind::Terminal);
EventPropagation::Stop
})
.style(move |s| {
let config = config.get();
s.width_pct(100.0)
.items_center()
.border_bottom(1.0)
.border_color(config.color(LapceColor::LAPCE_BORDER))
})
}
fn terminal_tab_split(
terminal_panel_data: TerminalPanelData,
terminal_tab_data: TerminalTabData,
tab_index: usize,
) -> impl View {
let config = terminal_panel_data.common.config;
let internal_command = terminal_panel_data.common.internal_command;
let workspace = terminal_panel_data.workspace.clone();
let active = terminal_tab_data.active;
let terminal_tab_scope = terminal_tab_data.scope;
dyn_stack(
move || {
let terminals = terminal_tab_data.terminals.get();
for (i, (index, _)) in terminals.iter().enumerate() {
if index.get_untracked() != i {
index.set(i);
}
}
terminals
},
|(_, terminal)| terminal.term_id,
move |(index, terminal)| {
let terminal_panel_data = terminal_panel_data.clone();
let terminal_scope = terminal.scope;
container({
let terminal_view = terminal_view(
terminal.term_id,
terminal.raw.read_only(),
terminal.mode.read_only(),
terminal.run_debug.read_only(),
terminal_panel_data,
terminal.launch_error,
internal_command,
workspace.clone(),
);
let view_id = terminal_view.id();
let have_task = terminal.run_debug.get_untracked().is_some();
terminal_view
.on_event_cont(EventListener::PointerDown, move |_| {
active.set(index.get_untracked());
})
.on_secondary_click_stop(move |_| {
if have_task {
tab_secondary_click(
internal_command,
view_id,
tab_index,
index.get_untracked(),
terminal.term_id,
);
}
})
.on_event(EventListener::PointerWheel, move |event| {
if let Event::PointerWheel(pointer_event) = event {
terminal.clone().wheel_scroll(pointer_event.delta.y);
EventPropagation::Stop
} else {
EventPropagation::Continue
}
})
.on_cleanup(move || {
terminal_scope.dispose();
})
.style(|s| s.size_pct(100.0, 100.0))
})
.style(move |s| {
s.size_pct(100.0, 100.0).padding_horiz(10.0).apply_if(
index.get() > 0,
|s| {
s.border_left(1.0).border_color(
config.get().color(LapceColor::LAPCE_BORDER),
)
},
)
})
},
)
.on_cleanup(move || {
terminal_tab_scope.dispose();
})
.style(|s| s.size_pct(100.0, 100.0))
}
fn terminal_tab_content(window_tab_data: Rc<WindowTabData>) -> impl View {
let terminal = window_tab_data.terminal.clone();
tab(
move || terminal.tab_info.with(|info| info.active),
move || terminal.tab_info.with(|info| info.tabs.clone()),
|(_, tab)| tab.terminal_tab_id,
move |(tab_index, tab)| {
terminal_tab_split(terminal.clone(), tab, tab_index.get_untracked())
},
)
.style(|s| s.size_pct(100.0, 100.0))
}
fn tab_secondary_click(
internal_command: Listener<InternalCommand>,
view_id: ViewId,
tab_index: usize,
terminal_index: usize,
term_id: TermId,
) {
let mut menu = Menu::new("");
menu = menu
.entry(MenuItem::new("Stop").action(move || {
internal_command.send(InternalCommand::StopTerminal { term_id });
}))
.entry(MenuItem::new("Restart").action(move || {
internal_command.send(InternalCommand::RestartTerminal { term_id });
}))
.entry(MenuItem::new("Clear All").action(move || {
internal_command.send(InternalCommand::ClearTerminalBuffer {
view_id,
tab_index,
terminal_index,
});
}));
show_context_menu(menu, None);
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/panel/plugin_view.rs | lapce-app/src/panel/plugin_view.rs | use std::{ops::Range, rc::Rc};
use floem::{
IntoView, View,
event::EventListener,
peniko::kurbo::{Point, Rect, Size},
reactive::{
RwSignal, SignalGet, SignalUpdate, SignalWith, create_memo, create_rw_signal,
},
style::CursorStyle,
views::{
Decorators, VirtualVector, container, dyn_container, img, label,
scroll::scroll, stack, svg, virtual_stack,
},
};
use indexmap::IndexMap;
use lapce_rpc::{
core::CoreRpcHandler,
plugin::{VoltID, VoltInfo},
};
use super::{
data::PanelSection, kind::PanelKind, position::PanelPosition, view::PanelBuilder,
};
use crate::{
app::not_clickable_icon,
command::InternalCommand,
config::{color::LapceColor, icon::LapceIcons},
plugin::{AvailableVoltData, InstalledVoltData, PluginData, VoltIcon},
text_input::TextInputBuilder,
window_tab::{Focus, WindowTabData},
};
pub const VOLT_DEFAULT_PNG: &[u8] = include_bytes!("../../../extra/images/volt.png");
struct IndexMapItems<K, V>(IndexMap<K, V>);
impl<K: Clone, V: Clone> IndexMapItems<K, V> {
fn items(&self, range: Range<usize>) -> Vec<(K, V)> {
let mut items = Vec::new();
for i in range {
if let Some((k, v)) = self.0.get_index(i) {
items.push((k.clone(), v.clone()));
}
}
items
}
}
impl<K: Clone + 'static, V: Clone + 'static> VirtualVector<(usize, K, V)>
for IndexMapItems<K, V>
{
fn total_len(&self) -> usize {
self.0.len()
}
fn slice(&mut self, range: Range<usize>) -> impl Iterator<Item = (usize, K, V)> {
let start = range.start;
Box::new(
self.items(range)
.into_iter()
.enumerate()
.map(move |(i, (k, v))| (i + start, k, v)),
)
}
}
pub fn plugin_panel(
window_tab_data: Rc<WindowTabData>,
position: PanelPosition,
) -> impl View {
let config = window_tab_data.common.config;
let plugin = window_tab_data.plugin.clone();
let core_rpc = window_tab_data.proxy.core_rpc.clone();
PanelBuilder::new(config, position)
.add(
"Installed",
installed_view(plugin.clone()),
window_tab_data.panel.section_open(PanelSection::Installed),
)
.add(
"Available",
available_view(plugin.clone(), core_rpc),
window_tab_data.panel.section_open(PanelSection::Available),
)
.build()
.debug_name("Plugin Panel")
}
fn installed_view(plugin: PluginData) -> impl View {
let ui_line_height = plugin.common.ui_line_height;
let volts = plugin.installed;
let config = plugin.common.config;
let disabled = plugin.disabled;
let workspace_disabled = plugin.workspace_disabled;
let internal_command = plugin.common.internal_command;
let view_fn = move |volt: InstalledVoltData, plugin: PluginData| {
let meta = volt.meta.get_untracked();
let volt_id = meta.id();
let local_volt_id = volt_id.clone();
let icon = volt.icon;
stack((
dyn_container(
move || icon.get(),
move |icon| match icon {
None => img(move || VOLT_DEFAULT_PNG.to_vec())
.style(|s| s.size_full())
.into_any(),
Some(VoltIcon::Svg(svg_str)) => svg(move || svg_str.clone())
.style(|s| s.size_full())
.into_any(),
Some(VoltIcon::Img(buf)) => {
img(move || buf.clone()).style(|s| s.size_full()).into_any()
}
},
)
.style(|s| {
s.min_size(50.0, 50.0)
.size(50.0, 50.0)
.margin_top(5.0)
.margin_right(10.0)
.padding(5)
}),
stack((
label(move || meta.display_name.clone()).style(|s| {
s.font_bold()
.text_ellipsis()
.min_width(0.0)
.selectable(false)
}),
label(move || meta.description.clone())
.style(|s| s.text_ellipsis().min_width(0.0).selectable(false)),
stack((
stack((
label(move || meta.author.clone()).style(|s| {
s.text_ellipsis().max_width_pct(100.0).selectable(false)
}),
label(move || {
if disabled.with(|d| d.contains(&volt_id))
|| workspace_disabled.with(|d| d.contains(&volt_id))
{
"Disabled".to_string()
} else if volt.meta.with(|m| {
volt.latest.with(|i| i.version != m.version)
}) {
"Upgrade".to_string()
} else {
format!("v{}", volt.meta.with(|m| m.version.clone()))
}
})
.style(|s| s.text_ellipsis().selectable(false)),
))
.style(|s| {
s.justify_between()
.flex_grow(1.0)
.flex_basis(0.0)
.min_width(0.0)
}),
not_clickable_icon(
|| LapceIcons::SETTINGS,
|| false,
|| false,
|| "Options",
config,
)
.style(|s| s.padding_left(6.0))
.popout_menu(move || {
plugin.plugin_controls(volt.meta.get(), volt.latest.get())
}),
))
.style(|s| s.width_pct(100.0).items_center()),
))
.style(|s| s.flex_col().flex_grow(1.0).flex_basis(0.0).min_width(0.0)),
))
.on_click_stop(move |_| {
internal_command.send(InternalCommand::OpenVoltView {
volt_id: local_volt_id.clone(),
});
})
.style(move |s| {
s.width_pct(100.0)
.padding_horiz(10.0)
.padding_vert(5.0)
.cursor(CursorStyle::Pointer)
.hover(|s| {
s.background(
config.get().color(LapceColor::PANEL_HOVERED_BACKGROUND),
)
})
})
};
container(
scroll(
virtual_stack(
move || IndexMapItems(volts.get()),
move |(_, id, _)| id.clone(),
move |(_, _, volt)| view_fn(volt, plugin.clone()),
)
.item_size_fixed(move || ui_line_height.get() * 3.0 + 10.0)
.style(|s| s.flex_col().width_pct(100.0)),
)
.style(|s| s.absolute().size_pct(100.0, 100.0)),
)
.style(|s| {
s.width_pct(100.0)
.line_height(1.6)
.flex_grow(1.0)
.flex_basis(0.0)
})
}
fn available_view(plugin: PluginData, core_rpc: CoreRpcHandler) -> impl View {
let ui_line_height = plugin.common.ui_line_height;
let volts = plugin.available.volts;
let installed = plugin.installed;
let config = plugin.common.config;
let internal_command = plugin.common.internal_command;
let local_plugin = plugin.clone();
let install_button =
move |id: VoltID, info: RwSignal<VoltInfo>, installing: RwSignal<bool>| {
let plugin = local_plugin.clone();
let installed = create_memo(move |_| {
installed.with(|installed| installed.contains_key(&id))
});
label(move || {
if installed.get() {
"Installed".to_string()
} else if installing.get() {
"Installing".to_string()
} else {
"Install".to_string()
}
})
.disabled(move || installed.get() || installing.get())
.on_click_stop(move |_| {
plugin.install_volt(info.get_untracked());
})
.style(move |s| {
let config = config.get();
s.color(config.color(LapceColor::LAPCE_BUTTON_PRIMARY_FOREGROUND))
.background(
config.color(LapceColor::LAPCE_BUTTON_PRIMARY_BACKGROUND),
)
.margin_left(6.0)
.padding_horiz(6.0)
.border_radius(6.0)
.hover(|s| {
s.cursor(CursorStyle::Pointer).background(
config
.color(LapceColor::LAPCE_BUTTON_PRIMARY_BACKGROUND)
.multiply_alpha(0.8),
)
})
.active(|s| {
s.background(
config
.color(LapceColor::LAPCE_BUTTON_PRIMARY_BACKGROUND)
.multiply_alpha(0.6),
)
})
.disabled(|s| s.background(config.color(LapceColor::EDITOR_DIM)))
})
};
let view_fn = move |(_, id, volt): (usize, VoltID, AvailableVoltData)| {
let info = volt.info.get_untracked();
let icon = volt.icon;
let volt_id = info.id();
stack((
dyn_container(
move || icon.get(),
move |icon| match icon {
None => img(move || VOLT_DEFAULT_PNG.to_vec())
.style(|s| s.size_full())
.into_any(),
Some(VoltIcon::Svg(svg_str)) => svg(move || svg_str.clone())
.style(|s| s.size_full())
.into_any(),
Some(VoltIcon::Img(buf)) => {
img(move || buf.clone()).style(|s| s.size_full()).into_any()
}
},
)
.style(|s| {
s.min_size(50.0, 50.0)
.size(50.0, 50.0)
.margin_top(5.0)
.margin_right(10.0)
.padding(5)
}),
stack((
label(move || info.display_name.clone()).style(|s| {
s.font_bold()
.text_ellipsis()
.min_width(0.0)
.selectable(false)
}),
label(move || info.description.clone())
.style(|s| s.text_ellipsis().min_width(0.0).selectable(false)),
stack((
label(move || info.author.clone()).style(|s| {
s.text_ellipsis()
.min_width(0.0)
.flex_grow(1.0)
.flex_basis(0.0)
.selectable(false)
}),
install_button(id, volt.info, volt.installing),
))
.style(|s| s.width_pct(100.0).items_center()),
))
.style(|s| s.flex_col().flex_grow(1.0).flex_basis(0.0).min_width(0.0)),
))
.on_click_stop(move |_| {
internal_command.send(InternalCommand::OpenVoltView {
volt_id: volt_id.clone(),
});
})
.style(move |s| {
s.width_pct(100.0)
.padding_horiz(10.0)
.padding_vert(5.0)
.cursor(CursorStyle::Pointer)
.hover(|s| {
s.background(
config.get().color(LapceColor::PANEL_HOVERED_BACKGROUND),
)
})
})
};
let content_rect = create_rw_signal(Rect::ZERO);
let editor = plugin.available.query_editor.clone();
let focus = plugin.common.focus;
let is_focused = move || focus.get() == Focus::Panel(PanelKind::Plugin);
let cursor_x = create_rw_signal(0.0);
stack((
container({
scroll(
TextInputBuilder::new()
.is_focused(is_focused)
.build_editor(editor.clone())
.placeholder(|| "Search extensions".to_string())
.on_cursor_pos(move |point| {
cursor_x.set(point.x);
})
.style(|s| {
s.padding_vert(4.0).padding_horiz(10.0).min_width_pct(100.0)
}),
)
.ensure_visible(move || {
Size::new(20.0, 0.0)
.to_rect()
.with_origin(Point::new(cursor_x.get(), 0.0))
})
.on_event_cont(EventListener::PointerDown, move |_| {
focus.set(Focus::Panel(PanelKind::Plugin));
})
.scroll_style(|s| s.hide_bars(true))
.style(move |s| {
let config = config.get();
s.width_pct(100.0)
.cursor(CursorStyle::Text)
.items_center()
.background(config.color(LapceColor::EDITOR_BACKGROUND))
.border(1.0)
.border_radius(6.0)
.border_color(config.color(LapceColor::LAPCE_BORDER))
})
})
.style(|s| s.padding(10.0).width_pct(100.0)),
container({
scroll({
virtual_stack(
move || IndexMapItems(volts.get()),
move |(_, id, _)| id.clone(),
view_fn,
)
.item_size_fixed(move || ui_line_height.get() * 3.0 + 10.0)
.on_resize(move |rect| {
content_rect.set(rect);
})
.style(|s| s.flex_col().width_pct(100.0))
})
.on_scroll(move |rect| {
if rect.y1 + 30.0 > content_rect.get_untracked().y1 {
plugin.load_more_available(core_rpc.clone());
}
})
.style(|s| s.absolute().size_pct(100.0, 100.0))
})
.style(|s| s.size_pct(100.0, 100.0)),
))
.style(|s| {
s.width_pct(100.0)
.line_height(1.6)
.flex_grow(1.0)
.flex_basis(0.0)
.flex_col()
})
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/panel/global_search_view.rs | lapce-app/src/panel/global_search_view.rs | use std::{path::PathBuf, rc::Rc, sync::Arc};
use floem::{
View,
event::EventListener,
reactive::{ReadSignal, SignalGet, SignalUpdate},
style::{CursorStyle, Style},
views::{Decorators, container, label, scroll, stack, svg, virtual_stack},
};
use lapce_xi_rope::find::CaseMatching;
use super::{kind::PanelKind, position::PanelPosition};
use crate::{
app::clickable_icon,
command::InternalCommand,
config::{LapceConfig, color::LapceColor, icon::LapceIcons},
editor::location::{EditorLocation, EditorPosition},
focus_text::focus_text,
global_search::{GlobalSearchData, SearchMatchData},
listener::Listener,
text_input::TextInputBuilder,
window_tab::{Focus, WindowTabData},
workspace::LapceWorkspace,
};
pub fn global_search_panel(
window_tab_data: Rc<WindowTabData>,
_position: PanelPosition,
) -> impl View {
let global_search = window_tab_data.global_search.clone();
let editor = global_search.editor.clone();
let config = global_search.common.config;
let workspace = global_search.common.workspace.clone();
let internal_command = global_search.common.internal_command;
let case_matching = global_search.common.find.case_matching;
let whole_word = global_search.common.find.whole_words;
let is_regex = global_search.common.find.is_regex;
let focus = global_search.common.focus;
let is_focused = move || focus.get() == Focus::Panel(PanelKind::Search);
stack((
container(
stack((
TextInputBuilder::new()
.is_focused(is_focused)
.build_editor(editor.clone())
.style(|s| s.width_pct(100.0)),
clickable_icon(
|| LapceIcons::SEARCH_CASE_SENSITIVE,
move || {
let new = match case_matching.get_untracked() {
CaseMatching::Exact => CaseMatching::CaseInsensitive,
CaseMatching::CaseInsensitive => CaseMatching::Exact,
};
case_matching.set(new);
},
move || case_matching.get() == CaseMatching::Exact,
|| false,
|| "Case Sensitive",
config,
)
.style(|s| s.padding_vert(4.0)),
clickable_icon(
|| LapceIcons::SEARCH_WHOLE_WORD,
move || {
whole_word.update(|whole_word| {
*whole_word = !*whole_word;
});
},
move || whole_word.get(),
|| false,
|| "Whole Word",
config,
)
.style(|s| s.padding_left(6.0)),
clickable_icon(
|| LapceIcons::SEARCH_REGEX,
move || {
is_regex.update(|is_regex| {
*is_regex = !*is_regex;
});
},
move || is_regex.get(),
|| false,
|| "Use Regex",
config,
)
.style(|s| s.padding_left(6.0)),
))
.on_event_cont(EventListener::PointerDown, move |_| {
focus.set(Focus::Panel(PanelKind::Search));
})
.style(move |s| {
s.width_pct(100.0)
.padding_right(6.0)
.items_center()
.border(1.0)
.border_radius(6.0)
.border_color(config.get().color(LapceColor::LAPCE_BORDER))
}),
)
.style(|s| s.width_pct(100.0).padding(10.0)),
search_result(workspace, global_search, internal_command, config),
))
.style(|s| s.absolute().size_pct(100.0, 100.0).flex_col())
.debug_name("Global Search Panel")
}
fn search_result(
workspace: Arc<LapceWorkspace>,
global_search_data: GlobalSearchData,
internal_command: Listener<InternalCommand>,
config: ReadSignal<Arc<LapceConfig>>,
) -> impl View {
let ui_line_height = global_search_data.common.ui_line_height;
container({
scroll({
virtual_stack(
move || global_search_data.clone(),
move |(path, _)| path.to_owned(),
move |(path, match_data)| {
let full_path = path.clone();
let path = if let Some(workspace_path) = workspace.path.as_ref()
{
path.strip_prefix(workspace_path)
.unwrap_or(&full_path)
.to_path_buf()
} else {
path
};
let style_path = path.clone();
let file_name = path
.file_name()
.and_then(|s| s.to_str())
.unwrap_or("")
.to_string();
let folder = path
.parent()
.and_then(|s| s.to_str())
.unwrap_or("")
.to_string();
let expanded = match_data.expanded;
stack((
stack((
svg(move || {
config.get().ui_svg(if expanded.get() {
LapceIcons::ITEM_OPENED
} else {
LapceIcons::ITEM_CLOSED
})
})
.style(move |s| {
let config = config.get();
let size = config.ui.icon_size() as f32;
s.margin_left(10.0)
.margin_right(6.0)
.size(size, size)
.min_size(size, size)
.color(
config.color(LapceColor::LAPCE_ICON_ACTIVE),
)
}),
svg(move || config.get().file_svg(&path).0).style(
move |s| {
let config = config.get();
let size = config.ui.icon_size() as f32;
let color = config.file_svg(&style_path).1;
s.margin_right(6.0)
.size(size, size)
.min_size(size, size)
.apply_opt(color, Style::color)
},
),
stack((
label(move || file_name.clone()).style(|s| {
s.margin_right(6.0)
.max_width_pct(100.0)
.text_ellipsis()
}),
label(move || folder.clone()).style(move |s| {
s.color(
config.get().color(LapceColor::EDITOR_DIM),
)
.min_width(0.0)
.text_ellipsis()
}),
))
.style(move |s| s.min_width(0.0).items_center()),
))
.on_click_stop(move |_| {
expanded.update(|expanded| *expanded = !*expanded);
})
.style(move |s| {
s.width_pct(100.0)
.min_width_pct(100.0)
.items_center()
.hover(|s| {
s.cursor(CursorStyle::Pointer).background(
config.get().color(
LapceColor::PANEL_HOVERED_BACKGROUND,
),
)
})
}),
virtual_stack(
move || {
if expanded.get() {
match_data.matches.get()
} else {
im::Vector::new()
}
},
|m| (m.line, m.start, m.end),
move |m| {
let path = full_path.clone();
let line_number = m.line;
let start = m.start;
let end = m.end;
let line_content = m.line_content.clone();
focus_text(
move || {
let config = config.get();
let content = if config
.ui
.trim_search_results_whitespace
{
m.line_content.trim()
} else {
&m.line_content
};
format!("{}: {content}", m.line,)
},
move || {
let config = config.get();
let mut offset = if config
.ui
.trim_search_results_whitespace
{
line_content.trim_start().len() as i32
- line_content.len() as i32
} else {
0
};
offset +=
line_number.to_string().len() as i32 + 2;
((start as i32 + offset) as usize
..(end as i32 + offset) as usize)
.collect()
},
move || {
config.get().color(LapceColor::EDITOR_FOCUS)
},
)
.style(move |s| {
let config = config.get();
let icon_size = config.ui.icon_size() as f32;
s.margin_left(10.0 + icon_size + 6.0).hover(
|s| {
s.cursor(CursorStyle::Pointer)
.background(config.color(
LapceColor::PANEL_HOVERED_BACKGROUND,
))
},
)
})
.on_click_stop(
move |_| {
internal_command.send(
InternalCommand::JumpToLocation {
location: EditorLocation {
path: path.clone(),
position: Some(
EditorPosition::Line(
line_number
.saturating_sub(1),
),
),
scroll_offset: None,
ignore_unconfirmed: false,
same_editor_tab: false,
},
},
);
},
)
},
)
.item_size_fixed(move || ui_line_height.get())
.style(|s| s.flex_col()),
))
.style(|s| s.flex_col())
},
)
.item_size_fn(|(_, match_data): &(PathBuf, SearchMatchData)| {
match_data.height()
})
.style(|s| s.flex_col().min_width_pct(100.0).line_height(1.8))
})
.style(|s| s.absolute().size_pct(100.0, 100.0))
})
.style(|s| s.size_pct(100.0, 100.0))
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/panel/view.rs | lapce-app/src/panel/view.rs | use std::{rc::Rc, sync::Arc};
use floem::{
AnyView, IntoView, View,
event::{Event, EventListener, EventPropagation},
kurbo::{Point, Size},
reactive::{
ReadSignal, RwSignal, SignalGet, SignalUpdate, SignalWith, create_rw_signal,
},
style::{CursorStyle, Style},
taffy::AlignItems,
unit::PxPctAuto,
views::{
Decorators, container, dyn_stack, empty, h_stack, label, stack,
stack_from_iter, tab, text,
},
};
use super::{
debug_view::debug_panel,
global_search_view::global_search_panel,
kind::PanelKind,
plugin_view::plugin_panel,
position::{PanelContainerPosition, PanelPosition},
problem_view::problem_panel,
source_control_view::source_control_panel,
terminal_view::terminal_panel,
};
use crate::{
app::{clickable_icon, clickable_icon_base},
config::{LapceConfig, color::LapceColor, icon::LapceIcons},
file_explorer::view::file_explorer_panel,
panel::{
call_hierarchy_view::show_hierarchy_panel, document_symbol::symbol_panel,
implementation_view::implementation_panel,
references_view::references_panel,
},
window_tab::{DragContent, WindowTabData},
};
pub fn foldable_panel_section(
header: impl View + 'static,
child: impl View + 'static,
open: RwSignal<bool>,
config: ReadSignal<Arc<LapceConfig>>,
) -> impl View {
stack((
h_stack((
clickable_icon_base(
move || {
if open.get() {
LapceIcons::PANEL_FOLD_DOWN
} else {
LapceIcons::PANEL_FOLD_UP
}
},
None::<Box<dyn Fn()>>,
|| false,
|| false,
config,
),
header.style(|s| s.align_items(AlignItems::Center).padding_left(3.0)),
))
.style(move |s| {
s.padding_horiz(10.0)
.padding_vert(6.0)
.width_pct(100.0)
.cursor(CursorStyle::Pointer)
.background(config.get().color(LapceColor::EDITOR_BACKGROUND))
})
.on_click_stop(move |_| {
open.update(|open| *open = !*open);
}),
child.style(move |s| s.apply_if(!open.get(), |s| s.hide())),
))
}
/// A builder for creating a foldable panel out of sections
pub struct PanelBuilder {
views: Vec<AnyView>,
config: ReadSignal<Arc<LapceConfig>>,
position: PanelPosition,
}
impl PanelBuilder {
pub fn new(
config: ReadSignal<Arc<LapceConfig>>,
position: PanelPosition,
) -> Self {
Self {
views: Vec::new(),
config,
position,
}
}
fn add_general(
mut self,
name: &'static str,
height: Option<PxPctAuto>,
view: impl View + 'static,
open: RwSignal<bool>,
style: impl Fn(Style) -> Style + 'static,
) -> Self {
let position = self.position;
let view = foldable_panel_section(
text(name).style(move |s| s.selectable(false)),
view,
open,
self.config,
)
.style(move |s| {
let s = s.width_full().flex_col();
// Use the manual height if given, otherwise if we're open behave flex,
// otherwise, do nothing so that there's no height
let s = if open.get() {
if let Some(height) = height {
s.height(height)
} else {
s.flex_grow(1.0).flex_basis(0.0)
}
} else if position.is_bottom() {
s.flex_grow(0.3).flex_basis(0.0)
} else {
s
};
style(s)
});
self.views.push(view.into_any());
self
}
/// Add a view to the panel
pub fn add(
self,
name: &'static str,
view: impl View + 'static,
open: RwSignal<bool>,
) -> Self {
self.add_general(name, None, view, open, std::convert::identity)
}
/// Add a view to the panel with a custom style applied to the overall header+section-content
pub fn add_style(
self,
name: &'static str,
view: impl View + 'static,
open: RwSignal<bool>,
style: impl Fn(Style) -> Style + 'static,
) -> Self {
self.add_general(name, None, view, open, style)
}
/// Add a view to the panel with a custom height that is only used when the panel is open
pub fn add_height(
self,
name: &'static str,
height: impl Into<PxPctAuto>,
view: impl View + 'static,
open: RwSignal<bool>,
) -> Self {
self.add_general(
name,
Some(height.into()),
view,
open,
std::convert::identity,
)
}
/// Add a view to the panel with a custom height that is only used when the panel is open
/// and a custom style applied to the overall header+section-content
pub fn add_height_style(
self,
name: &'static str,
height: impl Into<PxPctAuto>,
view: impl View + 'static,
open: RwSignal<bool>,
style: impl Fn(Style) -> Style + 'static,
) -> Self {
self.add_general(name, Some(height.into()), view, open, style)
}
/// Add a view to the panel with a custom height that is only used when the panel is open
pub fn add_height_pct(
self,
name: &'static str,
height: f64,
view: impl View + 'static,
open: RwSignal<bool>,
) -> Self {
self.add_general(
name,
Some(PxPctAuto::Pct(height)),
view,
open,
std::convert::identity,
)
}
/// Build the panel into a view
pub fn build(self) -> impl View {
stack_from_iter(self.views).style(move |s| {
s.width_full()
.apply_if(!self.position.is_bottom(), |s| s.flex_col())
})
}
}
pub fn panel_container_view(
window_tab_data: Rc<WindowTabData>,
position: PanelContainerPosition,
) -> impl View {
let panel = window_tab_data.panel.clone();
let config = window_tab_data.common.config;
let dragging = window_tab_data.common.dragging;
let current_size = create_rw_signal(Size::ZERO);
let available_size = window_tab_data.panel.available_size;
let is_dragging_panel = move || {
dragging
.with(|d| d.as_ref().map(|d| d.is_panel()))
.unwrap_or(false)
};
let drop_view = {
let panel = panel.clone();
move |position: PanelPosition| {
let panel = panel.clone();
let dragging_over = create_rw_signal(false);
empty()
.on_event(EventListener::DragEnter, move |_| {
if is_dragging_panel() {
dragging_over.set(true);
EventPropagation::Stop
} else {
EventPropagation::Continue
}
})
.on_event(EventListener::DragLeave, move |_| {
if is_dragging_panel() {
dragging_over.set(false);
EventPropagation::Stop
} else {
EventPropagation::Continue
}
})
.on_event(EventListener::Drop, move |_| {
if let Some(DragContent::Panel(kind)) = dragging.get_untracked()
{
dragging_over.set(false);
panel.move_panel_to_position(kind, &position);
EventPropagation::Stop
} else {
EventPropagation::Continue
}
})
.style(move |s| {
s.size_pct(100.0, 100.0).apply_if(dragging_over.get(), |s| {
s.background(
config
.get()
.color(LapceColor::EDITOR_DRAG_DROP_BACKGROUND),
)
})
})
}
};
let resize_drag_view = {
let panel = panel.clone();
let panel_size = panel.size;
move |position: PanelContainerPosition| {
panel.panel_info();
let view = empty();
let view_id = view.id();
let drag_start: RwSignal<Option<Point>> = create_rw_signal(None);
view.on_event_stop(EventListener::PointerDown, move |event| {
view_id.request_active();
if let Event::PointerDown(pointer_event) = event {
drag_start.set(Some(pointer_event.pos));
}
})
.on_event_stop(EventListener::PointerMove, move |event| {
if let Event::PointerMove(pointer_event) = event {
if let Some(drag_start_point) = drag_start.get_untracked() {
let current_size = current_size.get_untracked();
let available_size = available_size.get_untracked();
match position {
PanelContainerPosition::Left => {
let new_size = current_size.width
+ pointer_event.pos.x
- drag_start_point.x;
let current_panel_size = panel_size.get_untracked();
let new_size = new_size
.max(150.0)
.min(available_size.width - 150.0 - 150.0);
if new_size != current_panel_size.left {
panel_size.update(|size| {
size.left = new_size;
size.right = size.right.min(
available_size.width - new_size - 150.0,
)
})
}
}
PanelContainerPosition::Bottom => {
let new_size = current_size.height
- (pointer_event.pos.y - drag_start_point.y);
let maximized = panel.panel_bottom_maximized(false);
if (maximized
&& new_size < available_size.height - 50.0)
|| (!maximized
&& new_size > available_size.height - 50.0)
{
panel.toggle_bottom_maximize();
}
let new_size = new_size
.max(100.0)
.min(available_size.height - 100.0);
let current_size =
panel_size.with_untracked(|s| s.bottom);
if current_size != new_size {
panel_size.update(|size| {
size.bottom = new_size;
})
}
}
PanelContainerPosition::Right => {
let new_size = current_size.width
- (pointer_event.pos.x - drag_start_point.x);
let current_panel_size = panel_size.get_untracked();
let new_size = new_size
.max(150.0)
.min(available_size.width - 150.0 - 150.0);
if new_size != current_panel_size.right {
panel_size.update(|size| {
size.right = new_size;
size.left = size.left.min(
available_size.width - new_size - 150.0,
)
})
}
}
}
}
}
})
.on_event_stop(EventListener::PointerUp, move |_| {
drag_start.set(None);
})
.style(move |s| {
let is_dragging = drag_start.get().is_some();
let current_size = current_size.get();
let config = config.get();
s.absolute()
.apply_if(position == PanelContainerPosition::Bottom, |s| {
s.width_pct(100.0).height(4.0).margin_top(-2.0)
})
.apply_if(position == PanelContainerPosition::Left, |s| {
s.width(4.0)
.margin_left(current_size.width as f32 - 2.0)
.height_pct(100.0)
})
.apply_if(position == PanelContainerPosition::Right, |s| {
s.width(4.0).margin_left(-2.0).height_pct(100.0)
})
.apply_if(is_dragging, |s| {
s.background(config.color(LapceColor::EDITOR_CARET))
.apply_if(
position == PanelContainerPosition::Bottom,
|s| s.cursor(CursorStyle::RowResize),
)
.apply_if(
position != PanelContainerPosition::Bottom,
|s| s.cursor(CursorStyle::ColResize),
)
.z_index(2)
})
.hover(|s| {
s.background(config.color(LapceColor::EDITOR_CARET))
.apply_if(
position == PanelContainerPosition::Bottom,
|s| s.cursor(CursorStyle::RowResize),
)
.apply_if(
position != PanelContainerPosition::Bottom,
|s| s.cursor(CursorStyle::ColResize),
)
.z_index(2)
})
})
}
};
let is_bottom = position.is_bottom();
stack((
panel_picker(window_tab_data.clone(), position.first()),
panel_view(window_tab_data.clone(), position.first()),
panel_view(window_tab_data.clone(), position.second()),
panel_picker(window_tab_data.clone(), position.second()),
resize_drag_view(position),
stack((drop_view(position.first()), drop_view(position.second()))).style(
move |s| {
let is_dragging_panel = is_dragging_panel();
s.absolute()
.size_pct(100.0, 100.0)
.apply_if(!is_bottom, |s| s.flex_col())
.apply_if(!is_dragging_panel, |s| s.pointer_events_none())
},
),
))
.on_resize(move |rect| {
let size = rect.size();
if size != current_size.get_untracked() {
current_size.set(size);
}
})
.style(move |s| {
let size = panel.size.with(|s| match position {
PanelContainerPosition::Left => s.left,
PanelContainerPosition::Bottom => s.bottom,
PanelContainerPosition::Right => s.right,
});
let is_maximized = panel.panel_bottom_maximized(true);
let config = config.get();
s.apply_if(!panel.is_container_shown(&position, true), |s| s.hide())
.apply_if(position == PanelContainerPosition::Bottom, |s| {
s.width_pct(100.0)
.apply_if(!is_maximized, |s| {
s.border_top(1.0).height(size as f32)
})
.apply_if(is_maximized, |s| s.flex_grow(1.0))
})
.apply_if(position == PanelContainerPosition::Left, |s| {
s.border_right(1.0)
.width(size as f32)
.height_pct(100.0)
.background(config.color(LapceColor::PANEL_BACKGROUND))
})
.apply_if(position == PanelContainerPosition::Right, |s| {
s.border_left(1.0)
.width(size as f32)
.height_pct(100.0)
.background(config.color(LapceColor::PANEL_BACKGROUND))
})
.apply_if(!is_bottom, |s| s.flex_col())
.border_color(config.color(LapceColor::LAPCE_BORDER))
.color(config.color(LapceColor::PANEL_FOREGROUND))
})
.debug_name(format!("{:?} Pannel Container View", position))
}
fn panel_view(
window_tab_data: Rc<WindowTabData>,
position: PanelPosition,
) -> impl View {
let panel = window_tab_data.panel.clone();
let panels = move || {
panel
.panels
.with(|p| p.get(&position).cloned().unwrap_or_default())
};
let active_fn = move || {
panel
.styles
.with(|s| s.get(&position).map(|s| s.active).unwrap_or(0))
};
tab(
active_fn,
panels,
|p| *p,
move |kind| {
let view = match kind {
PanelKind::Terminal => {
terminal_panel(window_tab_data.clone()).into_any()
}
PanelKind::FileExplorer => {
file_explorer_panel(window_tab_data.clone(), position).into_any()
}
PanelKind::SourceControl => {
source_control_panel(window_tab_data.clone(), position)
.into_any()
}
PanelKind::Plugin => {
plugin_panel(window_tab_data.clone(), position).into_any()
}
PanelKind::Search => {
global_search_panel(window_tab_data.clone(), position).into_any()
}
PanelKind::Problem => {
problem_panel(window_tab_data.clone(), position).into_any()
}
PanelKind::Debug => {
debug_panel(window_tab_data.clone(), position).into_any()
}
PanelKind::CallHierarchy => {
show_hierarchy_panel(window_tab_data.clone(), position)
.into_any()
}
PanelKind::DocumentSymbol => {
symbol_panel(window_tab_data.clone(), position).into_any()
}
PanelKind::References => {
references_panel(window_tab_data.clone(), position).into_any()
}
PanelKind::Implementation => {
implementation_panel(window_tab_data.clone(), position)
.into_any()
}
};
view.style(|s| s.size_pct(100.0, 100.0))
},
)
.style(move |s| {
s.size_pct(100.0, 100.0).apply_if(
!panel.is_position_shown(&position, true)
|| panel.is_position_empty(&position, true),
|s| s.hide(),
)
})
}
pub fn panel_header(
header: String,
config: ReadSignal<Arc<LapceConfig>>,
) -> impl View {
container(label(move || header.clone())).style(move |s| {
s.padding_horiz(10.0)
.padding_vert(6.0)
.width_pct(100.0)
.background(config.get().color(LapceColor::EDITOR_BACKGROUND))
})
}
fn panel_picker(
window_tab_data: Rc<WindowTabData>,
position: PanelPosition,
) -> impl View {
let panel = window_tab_data.panel.clone();
let panels = panel.panels;
let config = window_tab_data.common.config;
let dragging = window_tab_data.common.dragging;
let is_bottom = position.is_bottom();
let is_first = position.is_first();
dyn_stack(
move || {
panel
.panels
.with(|panels| panels.get(&position).cloned().unwrap_or_default())
},
|p| *p,
move |p| {
let window_tab_data = window_tab_data.clone();
let tooltip = match p {
PanelKind::Terminal => "Terminal",
PanelKind::FileExplorer => "File Explorer",
PanelKind::SourceControl => "Source Control",
PanelKind::Plugin => "Plugins",
PanelKind::Search => "Search",
PanelKind::Problem => "Problems",
PanelKind::Debug => "Debug",
PanelKind::CallHierarchy => "Call Hierarchy",
PanelKind::DocumentSymbol => "Document Symbol",
PanelKind::References => "References",
PanelKind::Implementation => "Implementation",
};
let icon = p.svg_name();
let is_active = {
let window_tab_data = window_tab_data.clone();
move || {
if let Some((active_panel, shown)) = window_tab_data
.panel
.active_panel_at_position(&position, true)
{
shown && active_panel == p
} else {
false
}
}
};
container(stack((
clickable_icon(
|| icon,
move || {
window_tab_data.toggle_panel_visual(p);
},
|| false,
|| false,
move || tooltip,
config,
)
.draggable()
.on_event_stop(EventListener::DragStart, move |_| {
dragging.set(Some(DragContent::Panel(p)));
})
.on_event_stop(EventListener::DragEnd, move |_| {
dragging.set(None);
})
.dragging_style(move |s| {
let config = config.get();
s.border(1.0)
.border_radius(6.0)
.border_color(config.color(LapceColor::LAPCE_BORDER))
.padding(6.0)
.background(
config
.color(LapceColor::PANEL_BACKGROUND)
.multiply_alpha(0.7),
)
})
.style(|s| s.padding(1.0)),
label(|| "".to_string()).style(move |s| {
s.selectable(false)
.pointer_events_none()
.absolute()
.size_pct(100.0, 100.0)
.apply_if(!is_bottom && is_first, |s| s.margin_top(2.0))
.apply_if(!is_bottom && !is_first, |s| s.margin_top(-2.0))
.apply_if(is_bottom && is_first, |s| s.margin_left(-2.0))
.apply_if(is_bottom && !is_first, |s| s.margin_left(2.0))
.apply_if(is_active(), |s| {
s.apply_if(!is_bottom && is_first, |s| {
s.border_bottom(2.0)
})
.apply_if(!is_bottom && !is_first, |s| s.border_top(2.0))
.apply_if(is_bottom && is_first, |s| s.border_left(2.0))
.apply_if(is_bottom && !is_first, |s| {
s.border_right(2.0)
})
})
.border_color(
config
.get()
.color(LapceColor::LAPCE_TAB_ACTIVE_UNDERLINE),
)
}),
)))
.style(|s| s.padding(6.0))
},
)
.style(move |s| {
s.border_color(config.get().color(LapceColor::LAPCE_BORDER))
.apply_if(
panels.with(|p| {
p.get(&position).map(|p| p.is_empty()).unwrap_or(true)
}),
|s| s.hide(),
)
.apply_if(is_bottom, |s| s.flex_col())
.apply_if(is_bottom && is_first, |s| s.border_right(1.0))
.apply_if(is_bottom && !is_first, |s| s.border_left(1.0))
.apply_if(!is_bottom && is_first, |s| s.border_bottom(1.0))
.apply_if(!is_bottom && !is_first, |s| s.border_top(1.0))
})
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/panel/source_control_view.rs | lapce-app/src/panel/source_control_view.rs | use std::{path::PathBuf, rc::Rc};
use floem::{
View,
action::show_context_menu,
event::{Event, EventListener},
menu::{Menu, MenuItem},
peniko::kurbo::Rect,
prelude::SignalTrack,
reactive::{SignalGet, SignalUpdate, SignalWith, create_memo, create_rw_signal},
style::{CursorStyle, Style},
views::{
Decorators, container, dyn_stack,
editor::view::{LineRegion, cursor_caret},
label, scroll, stack, svg, text,
},
};
use lapce_core::buffer::rope_text::RopeText;
use lapce_rpc::source_control::FileDiff;
use super::{
data::PanelSection, kind::PanelKind, position::PanelPosition,
view::foldable_panel_section,
};
use crate::{
command::{CommandKind, InternalCommand, LapceCommand, LapceWorkbenchCommand},
config::{color::LapceColor, icon::LapceIcons},
editor::view::editor_view,
settings::checkbox,
source_control::SourceControlData,
window_tab::{Focus, WindowTabData},
};
pub fn source_control_panel(
window_tab_data: Rc<WindowTabData>,
_position: PanelPosition,
) -> impl View {
let config = window_tab_data.common.config;
let source_control = window_tab_data.source_control.clone();
let focus = source_control.common.focus;
let editor = source_control.editor.clone();
let doc = editor.doc_signal();
let cursor = editor.cursor();
let viewport = editor.viewport();
let window_origin = editor.window_origin();
let editor = create_rw_signal(editor);
let is_active = move |tracked| {
let focus = if tracked {
focus.get()
} else {
focus.get_untracked()
};
focus == Focus::Panel(PanelKind::SourceControl)
};
let is_empty = create_memo(move |_| {
let doc = doc.get();
doc.buffer.with(|b| b.len() == 0)
});
let debug_breakline = create_memo(move |_| None);
stack((
stack((
container({
scroll({
let view = stack((
editor_view(
editor.get_untracked(),
debug_breakline,
is_active,
),
label(|| "Commit Message".to_string()).style(move |s| {
let config = config.get();
s.absolute()
.items_center()
.height(config.editor.line_height() as f32)
.color(config.color(LapceColor::EDITOR_DIM))
.apply_if(!is_empty.get(), |s| s.hide())
.selectable(false)
}),
))
.style(|s| {
s.absolute()
.min_size_pct(100.0, 100.0)
.padding_left(10.0)
.padding_vert(6.0)
.hover(|s| s.cursor(CursorStyle::Text))
});
let id = view.id();
view.on_event_cont(EventListener::PointerDown, move |event| {
let event = event.clone().offset((10.0, 6.0));
if let Event::PointerDown(pointer_event) = event {
id.request_active();
editor.get_untracked().pointer_down(&pointer_event);
}
})
.on_event_stop(EventListener::PointerMove, move |event| {
let event = event.clone().offset((10.0, 6.0));
if let Event::PointerMove(pointer_event) = event {
editor.get_untracked().pointer_move(&pointer_event);
}
})
.on_event_stop(
EventListener::PointerUp,
move |event| {
let event = event.clone().offset((10.0, 6.0));
if let Event::PointerUp(pointer_event) = event {
editor.get_untracked().pointer_up(&pointer_event);
}
},
)
})
.on_move(move |pos| {
window_origin.set(pos + (10.0, 6.0));
})
.on_scroll(move |rect| {
viewport.set(rect);
})
.ensure_visible(move || {
let cursor = cursor.get();
let offset = cursor.offset();
let e_data = editor.get_untracked();
e_data.doc_signal().track();
e_data.kind.track();
let LineRegion { x, width, rvline } = cursor_caret(
&e_data.editor,
offset,
!cursor.is_insert(),
cursor.affinity,
);
let config = config.get_untracked();
let line_height = config.editor.line_height();
// TODO: is there a way to avoid the calculation of the vline here?
let vline = e_data.editor.vline_of_rvline(rvline);
Rect::from_origin_size(
(x, (vline.get() * line_height) as f64),
(width, line_height as f64),
)
.inflate(30.0, 10.0)
})
.style(|s| s.absolute().size_pct(100.0, 100.0))
})
.style(move |s| {
let config = config.get();
s.width_pct(100.0)
.height(120.0)
.border(1.0)
.padding(-1.0)
.border_radius(6.0)
.border_color(config.color(LapceColor::LAPCE_BORDER))
.background(config.color(LapceColor::EDITOR_BACKGROUND))
}),
{
let source_control = source_control.clone();
label(|| "Commit".to_string())
.on_click_stop(move |_| {
source_control.commit();
})
.style(move |s| {
let config = config.get();
s.margin_top(10.0)
.line_height(1.6)
.width_pct(100.0)
.justify_center()
.border(1.0)
.border_radius(6.0)
.border_color(config.color(LapceColor::LAPCE_BORDER))
.hover(|s| {
s.cursor(CursorStyle::Pointer).background(
config
.color(LapceColor::PANEL_HOVERED_BACKGROUND),
)
})
.active(|s| {
s.background(config.color(
LapceColor::PANEL_HOVERED_ACTIVE_BACKGROUND,
))
})
.selectable(false)
})
},
))
.style(|s| s.flex_col().width_pct(100.0).padding(10.0)),
foldable_panel_section(
text("Changes"),
file_diffs_view(source_control),
window_tab_data.panel.section_open(PanelSection::Changes),
config,
)
.style(|s| s.flex_col().size_pct(100.0, 100.0)),
))
.on_event_stop(EventListener::PointerDown, move |_| {
if focus.get_untracked() != Focus::Panel(PanelKind::SourceControl) {
focus.set(Focus::Panel(PanelKind::SourceControl));
}
})
.style(|s| s.flex_col().size_pct(100.0, 100.0))
.debug_name("Source Control Panel")
}
fn file_diffs_view(source_control: SourceControlData) -> impl View {
let file_diffs = source_control.file_diffs;
let config = source_control.common.config;
let workspace = source_control.common.workspace.clone();
let panel_rect = create_rw_signal(Rect::ZERO);
let panel_width = create_memo(move |_| panel_rect.get().width());
let lapce_command = source_control.common.lapce_command;
let internal_command = source_control.common.internal_command;
let view_fn = move |(path, (diff, checked)): (PathBuf, (FileDiff, bool))| {
let diff_for_style = diff.clone();
let full_path = path.clone();
let diff_for_menu = diff.clone();
let path_for_click = full_path.clone();
let path = if let Some(workspace_path) = workspace.path.as_ref() {
path.strip_prefix(workspace_path)
.unwrap_or(&full_path)
.to_path_buf()
} else {
path
};
let file_name = path
.file_name()
.and_then(|s| s.to_str())
.unwrap_or("")
.to_string();
let folder = path
.parent()
.and_then(|s| s.to_str())
.unwrap_or("")
.to_string();
let style_path = path.clone();
stack((
checkbox(move || checked, config).on_click_stop(move |_| {
file_diffs.update(|diffs| {
if let Some((_, checked)) = diffs.get_mut(&full_path) {
*checked = !*checked;
}
});
}),
svg(move || config.get().file_svg(&path).0).style(move |s| {
let config = config.get();
let size = config.ui.icon_size() as f32;
let color = config.file_svg(&style_path).1;
s.min_width(size)
.size(size, size)
.margin(6.0)
.apply_opt(color, Style::color)
}),
label(move || file_name.clone()).style(move |s| {
let config = config.get();
let size = config.ui.icon_size() as f32;
let max_width = panel_width.get() as f32
- 10.0
- size
- 6.0
- size
- 6.0
- 10.0
- size
- 6.0;
s.text_ellipsis()
.margin_right(6.0)
.max_width(max_width)
.selectable(false)
}),
label(move || folder.clone()).style(move |s| {
s.text_ellipsis()
.flex_grow(1.0)
.flex_basis(0.0)
.color(config.get().color(LapceColor::EDITOR_DIM))
.min_width(0.0)
.selectable(false)
}),
container({
svg(move || {
let svg = match &diff {
FileDiff::Modified(_) => LapceIcons::SCM_DIFF_MODIFIED,
FileDiff::Added(_) => LapceIcons::SCM_DIFF_ADDED,
FileDiff::Deleted(_) => LapceIcons::SCM_DIFF_REMOVED,
FileDiff::Renamed(_, _) => LapceIcons::SCM_DIFF_RENAMED,
};
config.get().ui_svg(svg)
})
.style(move |s| {
let config = config.get();
let size = config.ui.icon_size() as f32;
let color = match &diff_for_style {
FileDiff::Modified(_) => LapceColor::SOURCE_CONTROL_MODIFIED,
FileDiff::Added(_) => LapceColor::SOURCE_CONTROL_ADDED,
FileDiff::Deleted(_) => LapceColor::SOURCE_CONTROL_REMOVED,
FileDiff::Renamed(_, _) => {
LapceColor::SOURCE_CONTROL_MODIFIED
}
};
let color = config.color(color);
s.min_width(size).size(size, size).color(color)
})
})
.style(|s| {
s.absolute()
.size_pct(100.0, 100.0)
.padding_right(20.0)
.items_center()
.justify_end()
}),
))
.on_click_stop(move |_| {
internal_command.send(InternalCommand::OpenFileChanges {
path: path_for_click.clone(),
});
})
.on_event_cont(EventListener::PointerDown, move |event| {
let diff_for_menu = diff_for_menu.clone();
let discard = move || {
lapce_command.send(LapceCommand {
kind: CommandKind::Workbench(
LapceWorkbenchCommand::SourceControlDiscardTargetFileChanges,
),
data: Some(serde_json::json!(diff_for_menu.clone())),
});
};
if let Event::PointerDown(pointer_event) = event {
if pointer_event.button.is_secondary() {
let menu = Menu::new("")
.entry(MenuItem::new("Discard Changes").action(discard));
show_context_menu(menu, None);
}
}
})
.style(move |s| {
let config = config.get();
let size = config.ui.icon_size() as f32;
s.padding_left(10.0)
.padding_right(10.0 + size + 6.0)
.width_pct(100.0)
.items_center()
.cursor(CursorStyle::Pointer)
.hover(|s| {
s.background(config.color(LapceColor::PANEL_HOVERED_BACKGROUND))
})
})
};
container({
scroll({
dyn_stack(
move || file_diffs.get(),
|(path, (diff, checked))| {
(path.to_path_buf(), diff.clone(), *checked)
},
view_fn,
)
.style(|s| s.line_height(1.6).flex_col().width_pct(100.0))
})
.style(|s| s.absolute().size_pct(100.0, 100.0))
})
.on_resize(move |rect| {
panel_rect.set(rect);
})
.style(|s| s.size_pct(100.0, 100.0))
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/panel/kind.rs | lapce-app/src/panel/kind.rs | use serde::{Deserialize, Serialize};
use strum_macros::EnumIter;
use super::{data::PanelOrder, position::PanelPosition};
use crate::config::icon::LapceIcons;
#[derive(
Clone, Copy, PartialEq, Serialize, Deserialize, Hash, Eq, Debug, EnumIter,
)]
pub enum PanelKind {
Terminal,
FileExplorer,
SourceControl,
Plugin,
Search,
Problem,
Debug,
CallHierarchy,
DocumentSymbol,
References,
Implementation,
}
impl PanelKind {
pub fn svg_name(&self) -> &'static str {
match &self {
PanelKind::Terminal => LapceIcons::TERMINAL,
PanelKind::FileExplorer => LapceIcons::FILE_EXPLORER,
PanelKind::SourceControl => LapceIcons::SCM,
PanelKind::Plugin => LapceIcons::EXTENSIONS,
PanelKind::Search => LapceIcons::SEARCH,
PanelKind::Problem => LapceIcons::PROBLEM,
PanelKind::Debug => LapceIcons::DEBUG,
PanelKind::CallHierarchy => LapceIcons::TYPE_HIERARCHY,
PanelKind::DocumentSymbol => LapceIcons::DOCUMENT_SYMBOL,
PanelKind::References => LapceIcons::REFERENCES,
PanelKind::Implementation => LapceIcons::IMPLEMENTATION,
}
}
pub fn position(&self, order: &PanelOrder) -> Option<(usize, PanelPosition)> {
for (pos, panels) in order.iter() {
let index = panels.iter().position(|k| k == self);
if let Some(index) = index {
return Some((index, *pos));
}
}
None
}
pub fn default_position(&self) -> PanelPosition {
match self {
PanelKind::Terminal => PanelPosition::BottomLeft,
PanelKind::FileExplorer => PanelPosition::LeftTop,
PanelKind::SourceControl => PanelPosition::LeftTop,
PanelKind::Plugin => PanelPosition::LeftTop,
PanelKind::Search => PanelPosition::BottomLeft,
PanelKind::Problem => PanelPosition::BottomLeft,
PanelKind::Debug => PanelPosition::LeftTop,
PanelKind::CallHierarchy => PanelPosition::BottomLeft,
PanelKind::DocumentSymbol => PanelPosition::RightTop,
PanelKind::References => PanelPosition::BottomLeft,
PanelKind::Implementation => PanelPosition::BottomLeft,
}
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/panel/mod.rs | lapce-app/src/panel/mod.rs | pub mod call_hierarchy_view;
pub mod data;
pub mod debug_view;
pub mod document_symbol;
pub mod global_search_view;
pub mod implementation_view;
pub mod kind;
pub mod plugin_view;
pub mod position;
pub mod problem_view;
pub mod references_view;
pub mod source_control_view;
pub mod style;
pub mod terminal_view;
pub mod view;
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/panel/implementation_view.rs | lapce-app/src/panel/implementation_view.rs | use std::{ops::AddAssign, path::PathBuf, rc::Rc};
use floem::{
IntoView, View, ViewId,
reactive::{RwSignal, Scope, SignalGet, SignalUpdate},
style::CursorStyle,
views::{
Decorators, VirtualVector, container, label, scroll, stack, svg,
virtual_stack,
},
};
use im::HashMap;
use itertools::Itertools;
use lapce_rpc::file_line::FileLine;
use lsp_types::{Location, SymbolKind, request::GotoImplementationResponse};
use super::position::PanelPosition;
use crate::{
command::InternalCommand,
config::{color::LapceColor, icon::LapceIcons},
editor::location::EditorLocation,
window_tab::WindowTabData,
};
pub fn implementation_panel(
window_tab_data: Rc<WindowTabData>,
_position: PanelPosition,
) -> impl View {
common_reference_panel(window_tab_data.clone(), _position, move || {
window_tab_data.main_split.implementations.get()
})
.debug_name("implementation panel")
}
pub fn common_reference_panel(
window_tab_data: Rc<WindowTabData>,
_position: PanelPosition,
each_fn: impl Fn() -> ReferencesRoot + 'static,
) -> impl View {
let config = window_tab_data.common.config;
let ui_line_height = window_tab_data.common.ui_line_height;
scroll(
virtual_stack(
each_fn,
move |(_, _, data)| data.view_id(),
move |(_, level, rw_data)| {
match rw_data {
ReferenceLocation::File { path, open, .. } => stack((
container(
svg(move || {
let config = config.get();
let svg_str = match open.get() {
true => LapceIcons::ITEM_OPENED,
false => LapceIcons::ITEM_CLOSED,
};
config.ui_svg(svg_str)
})
.style(move |s| {
let config = config.get();
let size = config.ui.icon_size() as f32;
s.size(size, size).color(
config.color(LapceColor::LAPCE_ICON_ACTIVE),
)
}),
)
.style(|s| s.padding(4.0).margin_left(6.0).margin_right(2.0))
.on_click_stop({
move |_x| {
open.update(|x| {
*x = !*x;
});
}
}),
svg(move || {
let config = config.get();
config
.symbol_svg(&SymbolKind::FILE)
.unwrap_or_else(|| config.ui_svg(LapceIcons::FILE))
})
.style(move |s| {
let config = config.get();
let size = config.ui.icon_size() as f32;
s.min_width(size)
.size(size, size)
.margin_right(5.0)
.color(
config
.symbol_color(&SymbolKind::FILE)
.unwrap_or_else(|| {
config
.color(LapceColor::LAPCE_ICON_ACTIVE)
}),
)
}),
label(move || format!("{:?}", path))
.style(move |s| {
s.margin_left(6.0).color(
config.get().color(LapceColor::EDITOR_DIM),
)
})
.into_any(),
))
.style(move |s| {
s.padding_right(5.0)
.height(ui_line_height.get())
.padding_left((level * 10) as f32)
.items_center()
.hover(|s| {
s.background(
config
.get()
.color(LapceColor::PANEL_HOVERED_BACKGROUND),
)
.cursor(CursorStyle::Pointer)
})
}),
ReferenceLocation::Line { file_line, .. } => stack((container(
label(move || format!("{} {}", file_line.position.line + 1, file_line.content))
.style(move |s| {
s.margin_left(6.0).color(
config.get().color(LapceColor::EDITOR_DIM),
)
})
.into_any(),
)
.style(move |s| {
s.padding_right(5.0)
.height(ui_line_height.get())
.padding_left((level * 20) as f32)
.items_center()
.hover(|s| {
s.background(
config
.get()
.color(LapceColor::PANEL_HOVERED_BACKGROUND),
)
.cursor(CursorStyle::Pointer)
})
}),))
.on_click_stop({
let window_tab_data = window_tab_data.clone();
let position = file_line.position;
move |_| {
window_tab_data.common.internal_command.send(
InternalCommand::JumpToLocation {
location: EditorLocation {
path: file_line.path.clone(),
position: Some(
crate::editor::location::EditorPosition::Position(
position,
),
),
scroll_offset: None,
ignore_unconfirmed: false,
same_editor_tab: false,
},
},
);
}
}),
}
.style(move |s| {
s.padding_right(5.0)
.height(ui_line_height.get())
.padding_left((level * 10) as f32)
.items_center()
.hover(|s| {
s.background(
config
.get()
.color(LapceColor::PANEL_HOVERED_BACKGROUND),
)
.cursor(CursorStyle::Pointer)
})
})
},
).item_size_fixed(move || ui_line_height.get())
.style(|s| s.flex_col().absolute().min_width_full()),
)
.style(|s| s.absolute().size_full())
}
pub fn map_to_location(resp: Option<GotoImplementationResponse>) -> Vec<Location> {
let Some(resp) = resp else {
return Vec::new();
};
match resp {
GotoImplementationResponse::Scalar(local) => {
vec![local]
}
GotoImplementationResponse::Array(items) => items,
GotoImplementationResponse::Link(items) => items
.into_iter()
.map(|x| Location {
uri: x.target_uri,
range: x.target_range,
})
.collect(),
}
}
pub fn init_implementation_root(
items: Vec<FileLine>,
scope: Scope,
) -> ReferencesRoot {
let mut refs_map: HashMap<PathBuf, HashMap<u32, Reference>> = HashMap::new();
for item in items {
let entry = refs_map.entry(item.path.clone()).or_default();
(*entry).insert(
item.position.line,
Reference::Line {
location: ReferenceLocation::Line {
file_line: item,
view_id: ViewId::new(),
},
},
);
}
let mut refs = Vec::new();
for (path, items) in refs_map {
let open = scope.create_rw_signal(true);
let children = items
.into_iter()
.sorted_by(|x, y| x.0.cmp(&y.0))
.map(|x| x.1)
.collect();
let ref_item = Reference::File {
location: ReferenceLocation::File {
open,
path,
view_id: ViewId::new(),
},
children,
open,
};
refs.push(ref_item);
}
ReferencesRoot { children: refs }
}
#[derive(Clone, Default)]
pub struct ReferencesRoot {
pub(crate) children: Vec<Reference>,
}
impl ReferencesRoot {
pub fn total(&self) -> usize {
let mut total = 0;
for child in &self.children {
total += child.total_len()
}
total
}
fn get_children(
&self,
next: &mut usize,
min: usize,
max: usize,
level: usize,
) -> Vec<(usize, usize, ReferenceLocation)> {
let mut children = Vec::new();
for child in &self.children {
let child_children = child.get_children(next, min, max, level + 1);
if !child_children.is_empty() {
children.extend(child_children);
}
if *next > max {
break;
}
}
children
}
}
impl VirtualVector<(usize, usize, ReferenceLocation)> for ReferencesRoot {
fn total_len(&self) -> usize {
self.total()
}
fn slice(
&mut self,
range: std::ops::Range<usize>,
) -> impl Iterator<Item = (usize, usize, ReferenceLocation)> {
let min = range.start;
let max = range.end;
let children = self.get_children(&mut 0, min, max, 0);
children.into_iter()
}
}
#[derive(Clone)]
pub enum Reference {
File {
location: ReferenceLocation,
open: RwSignal<bool>,
children: Vec<Reference>,
},
Line {
location: ReferenceLocation,
},
}
#[derive(Clone)]
pub enum ReferenceLocation {
File {
path: PathBuf,
open: RwSignal<bool>,
view_id: ViewId,
},
Line {
file_line: FileLine,
view_id: ViewId,
},
}
impl ReferenceLocation {
pub fn view_id(&self) -> ViewId {
match self {
ReferenceLocation::File { view_id, .. } => *view_id,
ReferenceLocation::Line { view_id, .. } => *view_id,
}
}
}
impl Reference {
pub fn location(&self) -> ReferenceLocation {
match self {
Reference::File { location, .. } => location.clone(),
Reference::Line { location } => location.clone(),
}
}
pub fn total_len(&self) -> usize {
match self {
Reference::File { children, .. } => {
let mut total = 1;
for child in children {
total += child.total_len()
}
total
}
Reference::Line { .. } => 1,
}
}
pub fn children(&self) -> Option<&Vec<Reference>> {
match self {
Reference::File { children, open, .. } => {
if open.get() {
return Some(children);
}
None
}
Reference::Line { .. } => None,
}
}
fn get_children(
&self,
next: &mut usize,
min: usize,
max: usize,
level: usize,
) -> Vec<(usize, usize, ReferenceLocation)> {
let mut children = Vec::new();
if *next >= min && *next < max {
children.push((*next, level, self.location()));
} else if *next >= max {
return children;
}
next.add_assign(1);
if let Some(children_tmp) = self.children() {
for child in children_tmp {
let child_children = child.get_children(next, min, max, level + 1);
if !child_children.is_empty() {
children.extend(child_children);
}
if *next > max {
break;
}
}
}
children
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/panel/style.rs | lapce-app/src/panel/style.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Serialize, Deserialize, Default)]
pub struct PanelStyle {
pub active: usize,
pub shown: bool,
pub maximized: bool,
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/panel/references_view.rs | lapce-app/src/panel/references_view.rs | use std::rc::Rc;
use floem::{View, reactive::SignalGet, views::Decorators};
use super::position::PanelPosition;
use crate::{
panel::implementation_view::common_reference_panel, window_tab::WindowTabData,
};
pub fn references_panel(
window_tab_data: Rc<WindowTabData>,
_position: PanelPosition,
) -> impl View {
common_reference_panel(window_tab_data.clone(), _position, move || {
window_tab_data.main_split.references.get()
})
.debug_name("references panel")
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/panel/debug_view.rs | lapce-app/src/panel/debug_view.rs | use std::{rc::Rc, sync::Arc};
use floem::{
View,
event::EventListener,
peniko::Color,
reactive::{
ReadSignal, RwSignal, SignalGet, SignalUpdate, SignalWith, create_rw_signal,
},
style::CursorStyle,
text::Style as FontStyle,
views::{
Decorators, container, dyn_stack, label, scroll, stack, svg, text,
virtual_stack,
},
};
use lapce_rpc::{
dap_types::{DapId, ThreadId},
terminal::TermId,
};
use super::{data::PanelSection, position::PanelPosition, view::PanelBuilder};
use crate::{
app::clickable_icon,
command::InternalCommand,
config::{LapceConfig, color::LapceColor, icon::LapceIcons},
debug::{DapVariable, RunDebugMode, StackTraceData},
editor::location::{EditorLocation, EditorPosition},
listener::Listener,
settings::checkbox,
terminal::panel::TerminalPanelData,
window_tab::WindowTabData,
};
pub fn debug_panel(
window_tab_data: Rc<WindowTabData>,
position: PanelPosition,
) -> impl View {
let config = window_tab_data.common.config;
let terminal = window_tab_data.terminal.clone();
let internal_command = window_tab_data.common.internal_command;
PanelBuilder::new(config, position)
.add_height(
"Processes",
150.0,
debug_processes(terminal.clone(), config),
window_tab_data.panel.section_open(PanelSection::Process),
)
.add(
"Variables",
variables_view(window_tab_data.clone()),
window_tab_data.panel.section_open(PanelSection::Variable),
)
.add(
"Stack Frames",
debug_stack_traces(terminal.clone(), internal_command, config),
window_tab_data.panel.section_open(PanelSection::StackFrame),
)
.add_height(
"Breakpoints",
150.0,
breakpoints_view(window_tab_data.clone()),
window_tab_data.panel.section_open(PanelSection::Breakpoint),
)
.build()
.debug_name("Debug Panel")
}
fn debug_process_icons(
terminal: TerminalPanelData,
term_id: TermId,
dap_id: DapId,
mode: RunDebugMode,
stopped: bool,
config: ReadSignal<Arc<LapceConfig>>,
) -> impl View {
let paused = move || {
let stopped = terminal
.debug
.daps
.with_untracked(|daps| daps.get(&dap_id).map(|dap| dap.stopped));
stopped.map(|stopped| stopped.get()).unwrap_or(false)
};
match mode {
RunDebugMode::Run => container(stack((
{
let terminal = terminal.clone();
clickable_icon(
|| LapceIcons::DEBUG_RESTART,
move || {
terminal.restart_run_debug(term_id);
},
|| false,
|| false,
|| "Restart",
config,
)
.style(|s| s.margin_horiz(4.0))
},
{
let terminal = terminal.clone();
clickable_icon(
|| LapceIcons::DEBUG_STOP,
move || {
terminal.stop_run_debug(term_id);
},
|| false,
move || stopped,
|| "Stop",
config,
)
.style(|s| s.margin_right(4.0))
},
{
let terminal = terminal.clone();
clickable_icon(
|| LapceIcons::CLOSE,
move || {
terminal.close_terminal(&term_id);
},
|| false,
|| false,
|| "Close",
config,
)
.style(|s| s.margin_right(4.0))
},
))),
RunDebugMode::Debug => container(stack((
{
let terminal = terminal.clone();
clickable_icon(
|| LapceIcons::DEBUG_CONTINUE,
move || {
terminal.dap_continue(term_id);
},
|| false,
move || !paused() || stopped,
|| "Continue",
config,
)
.style(|s| s.margin_horiz(6.0))
},
{
let terminal = terminal.clone();
clickable_icon(
|| LapceIcons::DEBUG_PAUSE,
move || {
terminal.dap_pause(term_id);
},
|| false,
move || paused() || stopped,
|| "Pause",
config,
)
.style(|s| s.margin_right(4.0))
},
{
let terminal = terminal.clone();
clickable_icon(
|| LapceIcons::DEBUG_STEP_OVER,
move || {
terminal.dap_step_over(term_id);
},
|| false,
move || !paused() || stopped,
|| "Step Over",
config,
)
.style(|s| s.margin_right(4.0))
},
{
let terminal = terminal.clone();
clickable_icon(
|| LapceIcons::DEBUG_STEP_INTO,
move || {
terminal.dap_step_into(term_id);
},
|| false,
move || !paused() || stopped,
|| "Step Into",
config,
)
.style(|s| s.margin_right(4.0))
},
{
let terminal = terminal.clone();
clickable_icon(
|| LapceIcons::DEBUG_STEP_OUT,
move || {
terminal.dap_step_out(term_id);
},
|| false,
move || !paused() || stopped,
|| "Step Out",
config,
)
.style(|s| s.margin_right(4.0))
},
{
let terminal = terminal.clone();
clickable_icon(
|| LapceIcons::DEBUG_RESTART,
move || {
terminal.restart_run_debug(term_id);
},
|| false,
|| false,
|| "Restart",
config,
)
.style(|s| s.margin_right(4.0))
},
{
let terminal = terminal.clone();
clickable_icon(
|| LapceIcons::DEBUG_STOP,
move || {
terminal.stop_run_debug(term_id);
},
|| false,
move || stopped,
|| "Stop",
config,
)
.style(|s| s.margin_right(4.0))
},
{
let terminal = terminal.clone();
clickable_icon(
|| LapceIcons::CLOSE,
move || {
terminal.close_terminal(&term_id);
},
|| false,
|| false,
|| "Close",
config,
)
.style(|s| s.margin_right(4.0))
},
))),
}
}
fn debug_processes(
terminal: TerminalPanelData,
config: ReadSignal<Arc<LapceConfig>>,
) -> impl View {
scroll({
let terminal = terminal.clone();
let local_terminal = terminal.clone();
dyn_stack(
move || local_terminal.run_debug_process(true),
|(term_id, p)| (*term_id, p.stopped),
move |(term_id, p)| {
let terminal = terminal.clone();
let is_active =
move || terminal.debug.active_term.get() == Some(term_id);
let local_terminal = terminal.clone();
let is_hovered = create_rw_signal(false);
stack((
{
let svg_str = match (&p.mode, p.stopped) {
(RunDebugMode::Run, false) => LapceIcons::START,
(RunDebugMode::Run, true) => LapceIcons::RUN_ERRORS,
(RunDebugMode::Debug, false) => LapceIcons::DEBUG,
(RunDebugMode::Debug, true) => {
LapceIcons::DEBUG_DISCONNECT
}
};
svg(move || config.get().ui_svg(svg_str)).style(move |s| {
let config = config.get();
let size = config.ui.icon_size() as f32;
s.size(size, size)
.margin_vert(5.0)
.margin_horiz(10.0)
.color(config.color(LapceColor::LAPCE_ICON_ACTIVE))
})
},
label(move || p.config.name.clone()).style(|s| {
s.flex_grow(1.0)
.flex_basis(0.0)
.min_width(0.0)
.text_ellipsis()
}),
debug_process_icons(
terminal.clone(),
term_id,
p.config.dap_id,
p.mode,
p.stopped,
config,
)
.style(move |s| {
s.apply_if(!is_hovered.get() && !is_active(), |s| s.hide())
}),
))
.on_click_stop(move |_| {
local_terminal.debug.active_term.set(Some(term_id));
local_terminal.focus_terminal(term_id);
})
.on_event_stop(EventListener::PointerEnter, move |_| {
is_hovered.set(true);
})
.on_event_stop(EventListener::PointerLeave, move |_| {
is_hovered.set(false);
})
.style(move |s| {
let config = config.get();
s.padding_vert(6.0)
.width_pct(100.0)
.items_center()
.apply_if(is_active(), |s| {
s.background(
config.color(LapceColor::PANEL_CURRENT_BACKGROUND),
)
})
.hover(|s| {
s.cursor(CursorStyle::Pointer).background(
(config.color(LapceColor::PANEL_HOVERED_BACKGROUND))
.multiply_alpha(0.3),
)
})
})
},
)
.style(|s| s.width_pct(100.0).flex_col())
})
}
fn variables_view(window_tab_data: Rc<WindowTabData>) -> impl View {
let terminal = window_tab_data.terminal.clone();
let local_terminal = window_tab_data.terminal.clone();
let ui_line_height = window_tab_data.common.ui_line_height;
let config = window_tab_data.common.config;
container(
scroll(
virtual_stack(
move || {
let dap = terminal.get_active_dap(true);
dap.map(|dap| {
if !dap.stopped.get() {
return DapVariable::default();
}
let process_stopped = terminal
.get_terminal(&dap.term_id)
.and_then(|t| {
t.run_debug.with(|r| r.as_ref().map(|r| r.stopped))
})
.unwrap_or(true);
if process_stopped {
return DapVariable::default();
}
dap.variables.get()
})
.unwrap_or_default()
},
|node| {
(
node.item.name().to_string(),
node.item.value().map(|v| v.to_string()),
node.item.reference(),
node.expanded,
node.level,
)
},
move |node| {
let local_terminal = local_terminal.clone();
let level = node.level;
let reference = node.item.reference();
let name = node.item.name();
let ty = node.item.ty();
let type_exists = ty.map(|ty| !ty.is_empty()).unwrap_or(false);
stack((
svg(move || {
let config = config.get();
let svg_str = match node.expanded {
true => LapceIcons::ITEM_OPENED,
false => LapceIcons::ITEM_CLOSED,
};
config.ui_svg(svg_str)
})
.style(move |s| {
let config = config.get();
let size = config.ui.icon_size() as f32;
let color = if reference > 0 {
config.color(LapceColor::LAPCE_ICON_ACTIVE)
} else {
Color::TRANSPARENT
};
s.size(size, size).margin_left(10.0).color(color)
}),
text(name),
text(": ").style(move |s| {
s.apply_if(!type_exists || reference == 0, |s| s.hide())
}),
text(node.item.ty().unwrap_or("")).style(move |s| {
s.color(config.get().style_color("type").unwrap())
.apply_if(!type_exists || reference == 0, |s| {
s.hide()
})
}),
text(format!(" = {}", node.item.value().unwrap_or("")))
.style(move |s| s.apply_if(reference > 0, |s| s.hide())),
))
.on_click_stop(move |_| {
if reference > 0 {
let dap = local_terminal.get_active_dap(false);
if let Some(dap) = dap {
let process_stopped = local_terminal
.get_terminal(&dap.term_id)
.and_then(|t| {
t.run_debug
.with(|r| r.as_ref().map(|r| r.stopped))
})
.unwrap_or(true);
if !process_stopped {
dap.toggle_expand(
node.parent.clone(),
reference,
);
}
}
}
})
.style(move |s| {
s.items_center()
.padding_right(10.0)
.padding_left((level * 10) as f32)
.min_width_pct(100.0)
.hover(|s| {
s.apply_if(reference > 0, |s| {
s.background(
config.get().color(
LapceColor::PANEL_HOVERED_BACKGROUND,
),
)
})
})
})
},
)
.item_size_fixed(move || ui_line_height.get())
.style(|s| s.flex_col().min_width_full()),
)
.style(|s| s.absolute().size_full()),
)
.style(|s| s.width_full().line_height(1.6).flex_grow(1.0).flex_basis(0))
}
fn debug_stack_frames(
dap_id: DapId,
thread_id: ThreadId,
stack_trace: StackTraceData,
stopped: RwSignal<bool>,
internal_command: Listener<InternalCommand>,
config: ReadSignal<Arc<LapceConfig>>,
) -> impl View {
let expanded = stack_trace.expanded;
stack((
container(label(move || thread_id.to_string()))
.on_click_stop(move |_| {
expanded.update(|expanded| {
*expanded = !*expanded;
});
})
.style(move |s| {
s.padding_horiz(10.0).min_width_pct(100.0).hover(move |s| {
s.cursor(CursorStyle::Pointer).background(
config.get().color(LapceColor::PANEL_HOVERED_BACKGROUND),
)
})
}),
dyn_stack(
move || {
let expanded = stack_trace.expanded.get() && stopped.get();
if expanded {
stack_trace.frames.get()
} else {
im::Vector::new()
}
},
|frame| frame.id,
move |frame| {
let full_path = frame.source.as_ref().and_then(|s| s.path.clone());
let line = frame.line.saturating_sub(1);
let col = frame.column.saturating_sub(1);
let source_path = frame
.source
.as_ref()
.and_then(|s| s.path.as_ref())
.and_then(|p| p.file_name())
.and_then(|s| s.to_str())
.unwrap_or("")
.to_string();
let has_source = !source_path.is_empty();
let source_path = format!("{source_path}:{}", frame.line);
container(stack((
label(move || frame.name.clone()).style(move |s| {
s.hover(|s| {
s.background(
config
.get()
.color(LapceColor::PANEL_HOVERED_BACKGROUND),
)
})
}),
label(move || source_path.clone()).style(move |s| {
s.margin_left(10.0)
.color(config.get().color(LapceColor::EDITOR_DIM))
.font_style(FontStyle::Italic)
.apply_if(!has_source, |s| s.hide())
}),
)))
.on_click_stop(move |_| {
if let Some(path) = full_path.clone() {
internal_command.send(InternalCommand::JumpToLocation {
location: EditorLocation {
path,
position: Some(EditorPosition::Position(
lsp_types::Position {
line: line as u32,
character: col as u32,
},
)),
scroll_offset: None,
ignore_unconfirmed: false,
same_editor_tab: false,
},
});
}
internal_command.send(InternalCommand::DapFrameScopes {
dap_id,
frame_id: frame.id,
});
})
.style(move |s| {
let config = config.get();
s.padding_left(20.0)
.padding_right(10.0)
.min_width_pct(100.0)
.apply_if(!has_source, |s| {
s.color(config.color(LapceColor::EDITOR_DIM))
})
.hover(|s| {
s.background(
config.color(LapceColor::PANEL_HOVERED_BACKGROUND),
)
.apply_if(has_source, |s| s.cursor(CursorStyle::Pointer))
})
})
},
)
.style(|s| s.flex_col().min_width_pct(100.0)),
))
.style(|s| s.flex_col().min_width_pct(100.0))
}
fn debug_stack_traces(
terminal: TerminalPanelData,
internal_command: Listener<InternalCommand>,
config: ReadSignal<Arc<LapceConfig>>,
) -> impl View {
container(
scroll({
let local_terminal = terminal.clone();
dyn_stack(
move || {
let dap = local_terminal.get_active_dap(true);
if let Some(dap) = dap {
let process_stopped = local_terminal
.get_terminal(&dap.term_id)
.and_then(|t| {
t.run_debug.with(|r| r.as_ref().map(|r| r.stopped))
})
.unwrap_or(true);
if process_stopped {
return Vec::new();
}
let main_thread = dap.thread_id.get();
let stack_traces = dap.stack_traces.get();
let mut traces = stack_traces
.into_iter()
.map(|(thread_id, stack_trace)| {
(dap.dap_id, dap.stopped, thread_id, stack_trace)
})
.collect::<Vec<_>>();
traces.sort_by_key(|(_, _, id, _)| main_thread != Some(*id));
traces
} else {
Vec::new()
}
},
|(dap_id, stopped, thread_id, _)| {
(*dap_id, *thread_id, stopped.get_untracked())
},
move |(dap_id, stopped, thread_id, stack_trace)| {
debug_stack_frames(
dap_id,
thread_id,
stack_trace,
stopped,
internal_command,
config,
)
},
)
.style(|s| s.flex_col().min_width_pct(100.0))
})
.style(|s| s.absolute().size_pct(100.0, 100.0)),
)
.style(|s| {
s.width_pct(100.0)
.line_height(1.6)
.flex_grow(1.0)
.flex_basis(0.0)
})
}
fn breakpoints_view(window_tab_data: Rc<WindowTabData>) -> impl View {
let breakpoints = window_tab_data.terminal.debug.breakpoints;
let config = window_tab_data.common.config;
let workspace = window_tab_data.common.workspace.clone();
let available_width = create_rw_signal(0.0);
let internal_command = window_tab_data.common.internal_command;
container(
scroll(
dyn_stack(
move || {
breakpoints
.get()
.into_iter()
.flat_map(|(path, breakpoints)| {
breakpoints.into_values().map(move |b| (path.clone(), b))
})
},
move |(path, breakpoint)| {
(path.clone(), breakpoint.line, breakpoint.active)
},
move |(path, breakpoint)| {
let line = breakpoint.line;
let full_path = path.clone();
let full_path_for_jump = path.clone();
let full_path_for_close = path.clone();
let path = if let Some(workspace_path) = workspace.path.as_ref()
{
path.strip_prefix(workspace_path)
.unwrap_or(&full_path)
.to_path_buf()
} else {
path
};
let file_name =
path.file_name().and_then(|s| s.to_str()).unwrap_or("");
let folder =
path.parent().and_then(|s| s.to_str()).unwrap_or("");
let folder_empty = folder.is_empty();
stack((
clickable_icon(
move || LapceIcons::CLOSE,
move || {
breakpoints.update(|breakpoints| {
if let Some(breakpoints) =
breakpoints.get_mut(&full_path_for_close)
{
breakpoints.remove(&line);
}
});
},
|| false,
|| false,
|| "Remove",
config,
)
.on_event_stop(EventListener::PointerDown, |_| {}),
checkbox(move || breakpoint.active, config)
.style(|s| {
s.margin_right(6.0).cursor(CursorStyle::Pointer)
})
.on_click_stop(move |_| {
breakpoints.update(|breakpoints| {
if let Some(breakpoints) =
breakpoints.get_mut(&full_path)
{
if let Some(breakpoint) =
breakpoints.get_mut(&line)
{
breakpoint.active = !breakpoint.active;
}
}
});
}),
text(format!("{file_name}:{}", breakpoint.line + 1)).style(
move |s| {
let size = config.get().ui.icon_size() as f32;
s.text_ellipsis().max_width(
available_width.get() as f32
- 20.0
- size
- 6.0
- size
- 8.0,
)
},
),
text(folder).style(move |s| {
s.text_ellipsis()
.flex_grow(1.0)
.flex_basis(0.0)
.color(config.get().color(LapceColor::EDITOR_DIM))
.min_width(0.0)
.margin_left(6.0)
.apply_if(folder_empty, |s| s.hide())
}),
))
.style(move |s| {
s.items_center().padding_horiz(10.0).width_pct(100.0).hover(
|s| {
s.background(
config
.get()
.color(LapceColor::PANEL_HOVERED_BACKGROUND),
)
},
)
})
.on_click_stop(move |_| {
internal_command.send(InternalCommand::JumpToLocation {
location: EditorLocation {
path: full_path_for_jump.clone(),
position: Some(EditorPosition::Line(line)),
scroll_offset: None,
ignore_unconfirmed: false,
same_editor_tab: false,
},
});
})
},
)
.style(|s| s.flex_col().line_height(1.6).width_pct(100.0)),
)
.on_resize(move |rect| {
let width = rect.width();
if available_width.get_untracked() != width {
available_width.set(width);
}
})
.style(|s| s.absolute().size_pct(100.0, 100.0)),
)
.style(|s| s.size_pct(100.0, 100.0))
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/panel/problem_view.rs | lapce-app/src/panel/problem_view.rs | use std::{path::PathBuf, rc::Rc, sync::Arc};
use floem::{
View,
peniko::Color,
reactive::{
ReadSignal, SignalGet, SignalUpdate, SignalWith, create_effect,
create_rw_signal,
},
style::{CursorStyle, Style},
views::{Decorators, container, dyn_stack, label, scroll, stack, svg},
};
use lsp_types::{DiagnosticRelatedInformation, DiagnosticSeverity};
use super::{data::PanelSection, position::PanelPosition, view::PanelBuilder};
use crate::{
command::InternalCommand,
config::{LapceConfig, color::LapceColor, icon::LapceIcons},
doc::{DiagnosticData, EditorDiagnostic},
editor::location::{EditorLocation, EditorPosition},
listener::Listener,
lsp::path_from_url,
window_tab::WindowTabData,
workspace::LapceWorkspace,
};
pub fn problem_panel(
window_tab_data: Rc<WindowTabData>,
position: PanelPosition,
) -> impl View {
let config = window_tab_data.common.config;
let is_bottom = position.is_bottom();
PanelBuilder::new(config, position)
.add_style(
"Errors",
problem_section(window_tab_data.clone(), DiagnosticSeverity::ERROR),
window_tab_data.panel.section_open(PanelSection::Error),
move |s| {
s.border_color(config.get().color(LapceColor::LAPCE_BORDER))
.apply_if(is_bottom, |s| s.border_right(1.0))
.apply_if(!is_bottom, |s| s.border_bottom(1.0))
},
)
.add(
"Warnings",
problem_section(window_tab_data.clone(), DiagnosticSeverity::WARNING),
window_tab_data.panel.section_open(PanelSection::Warn),
)
.build()
.debug_name("Problem Panel")
}
fn problem_section(
window_tab_data: Rc<WindowTabData>,
severity: DiagnosticSeverity,
) -> impl View {
let config = window_tab_data.common.config;
let main_split = window_tab_data.main_split.clone();
let internal_command = window_tab_data.common.internal_command;
container({
scroll(
dyn_stack(
move || main_split.diagnostics.get(),
|(p, _)| p.clone(),
move |(path, diagnostic_data)| {
file_view(
main_split.common.workspace.clone(),
path,
diagnostic_data,
severity,
internal_command,
config,
)
},
)
.style(|s| s.flex_col().width_pct(100.0).line_height(1.8)),
)
.style(|s| s.absolute().size_pct(100.0, 100.0))
})
.style(|s| s.size_pct(100.0, 100.0))
}
fn file_view(
workspace: Arc<LapceWorkspace>,
path: PathBuf,
diagnostic_data: DiagnosticData,
severity: DiagnosticSeverity,
internal_command: Listener<InternalCommand>,
config: ReadSignal<Arc<LapceConfig>>,
) -> impl View {
let collpased = create_rw_signal(false);
let diagnostics = create_rw_signal(im::Vector::new());
create_effect(move |_| {
let span = diagnostic_data.diagnostics_span.get();
let d = if !span.is_empty() {
span.iter()
.filter_map(|(iv, diag)| {
if diag.severity == Some(severity) {
Some(EditorDiagnostic {
range: Some((iv.start, iv.end)),
diagnostic: diag.to_owned(),
})
} else {
None
}
})
.collect::<im::Vector<EditorDiagnostic>>()
} else {
let diagnostics = diagnostic_data.diagnostics.get();
let diagnostics: im::Vector<EditorDiagnostic> = diagnostics
.into_iter()
.filter_map(|d| {
if d.severity == Some(severity) {
Some(EditorDiagnostic {
range: None,
diagnostic: d,
})
} else {
None
}
})
.collect();
diagnostics
};
diagnostics.set(d);
});
let full_path = path.clone();
let path = if let Some(workspace_path) = workspace.path.as_ref() {
path.strip_prefix(workspace_path)
.unwrap_or(&full_path)
.to_path_buf()
} else {
path
};
let style_path = path.clone();
let icon = match severity {
DiagnosticSeverity::ERROR => LapceIcons::ERROR,
_ => LapceIcons::WARNING,
};
let icon_color = move || {
let config = config.get();
match severity {
DiagnosticSeverity::ERROR => config.color(LapceColor::LAPCE_ERROR),
_ => config.color(LapceColor::LAPCE_WARN),
}
};
let file_name = path
.file_name()
.and_then(|s| s.to_str())
.unwrap_or("")
.to_string();
let folder = path
.parent()
.and_then(|s| s.to_str())
.unwrap_or("")
.to_string();
stack((
stack((
container(
stack((
label(move || file_name.clone()).style(|s| {
s.margin_right(6.0)
.max_width_pct(100.0)
.text_ellipsis()
.selectable(false)
}),
label(move || folder.clone()).style(move |s| {
s.color(config.get().color(LapceColor::EDITOR_DIM))
.min_width(0.0)
.text_ellipsis()
.selectable(false)
}),
))
.style(move |s| s.width_pct(100.0).min_width(0.0)),
)
.on_click_stop(move |_| {
collpased.update(|collpased| *collpased = !*collpased);
})
.style(move |s| {
let config = config.get();
s.width_pct(100.0)
.min_width(0.0)
.padding_left(10.0 + (config.ui.icon_size() as f32 + 6.0) * 2.0)
.padding_right(10.0)
.hover(|s| {
s.cursor(CursorStyle::Pointer).background(
config.color(LapceColor::PANEL_HOVERED_BACKGROUND),
)
})
}),
stack((
svg(move || {
config.get().ui_svg(if collpased.get() {
LapceIcons::ITEM_CLOSED
} else {
LapceIcons::ITEM_OPENED
})
})
.style(move |s| {
let config = config.get();
let size = config.ui.icon_size() as f32;
s.margin_right(6.0)
.size(size, size)
.color(config.color(LapceColor::LAPCE_ICON_ACTIVE))
}),
svg(move || config.get().file_svg(&path).0).style(move |s| {
let config = config.get();
let size = config.ui.icon_size() as f32;
let color = config.file_svg(&style_path).1;
s.min_width(size)
.size(size, size)
.apply_opt(color, Style::color)
}),
label(|| " ".to_string()).style(move |s| s.selectable(false)),
))
.style(|s| s.absolute().items_center().margin_left(10.0)),
))
.style(move |s| s.width_pct(100.0).min_width(0.0)),
dyn_stack(
move || {
if collpased.get() {
im::Vector::new()
} else {
diagnostics.get()
}
},
|d| (d.range, d.diagnostic.range),
move |d| {
item_view(
full_path.clone(),
d,
icon,
icon_color,
internal_command,
config,
)
},
)
.style(|s| s.flex_col().width_pct(100.0).min_width_pct(0.0)),
))
.style(move |s| {
s.width_pct(100.0)
.items_start()
.flex_col()
.apply_if(diagnostics.with(|d| d.is_empty()), |s| s.hide())
})
}
fn item_view(
path: PathBuf,
d: EditorDiagnostic,
icon: &'static str,
icon_color: impl Fn() -> Color + 'static,
internal_command: Listener<InternalCommand>,
config: ReadSignal<Arc<LapceConfig>>,
) -> impl View {
let related = d.diagnostic.related_information.unwrap_or_default();
let position = if let Some((start, _)) = d.range {
EditorPosition::Offset(start)
} else {
EditorPosition::Position(d.diagnostic.range.start)
};
let location = EditorLocation {
path,
position: Some(position),
scroll_offset: None,
ignore_unconfirmed: false,
same_editor_tab: false,
};
stack((
container({
stack((
label(move || d.diagnostic.message.clone()).style(move |s| {
s.width_pct(100.0)
.min_width(0.0)
.padding_left(
10.0 + (config.get().ui.icon_size() as f32 + 6.0) * 3.0,
)
.padding_right(10.0)
}),
stack((
svg(move || config.get().ui_svg(icon)).style(move |s| {
let config = config.get();
let size = config.ui.icon_size() as f32;
s.size(size, size).color(icon_color())
}),
label(|| " ".to_string()).style(move |s| s.selectable(false)),
))
.style(move |s| {
s.absolute().items_center().margin_left(
10.0 + (config.get().ui.icon_size() as f32 + 6.0) * 2.0,
)
}),
))
.style(move |s| {
s.width_pct(100.0).min_width(0.0).hover(|s| {
s.cursor(CursorStyle::Pointer).background(
config.get().color(LapceColor::PANEL_HOVERED_BACKGROUND),
)
})
})
})
.on_click_stop(move |_| {
internal_command.send(InternalCommand::JumpToLocation {
location: location.clone(),
});
})
.style(|s| s.width_pct(100.0).min_width_pct(0.0)),
related_view(related, internal_command, config),
))
.style(|s| s.width_pct(100.0).min_width_pct(0.0).flex_col())
}
fn related_view(
related: Vec<DiagnosticRelatedInformation>,
internal_command: Listener<InternalCommand>,
config: ReadSignal<Arc<LapceConfig>>,
) -> impl View {
let is_empty = related.is_empty();
stack((
dyn_stack(
move || related.clone(),
|_| 0,
move |related| {
let full_path = path_from_url(&related.location.uri);
let path = full_path
.file_name()
.and_then(|f| f.to_str())
.map(|f| {
format!(
"{f} [{}, {}]: ",
related.location.range.start.line,
related.location.range.start.character
)
})
.unwrap_or_default();
let location = EditorLocation {
path: full_path,
position: Some(EditorPosition::Position(
related.location.range.start,
)),
scroll_offset: None,
ignore_unconfirmed: false,
same_editor_tab: false,
};
let message = format!("{path}{}", related.message);
container(
label(move || message.clone())
.style(move |s| s.width_pct(100.0).min_width(0.0)),
)
.on_click_stop(move |_| {
internal_command.send(InternalCommand::JumpToLocation {
location: location.clone(),
});
})
.style(move |s| {
let config = config.get();
s.padding_left(10.0 + (config.ui.icon_size() as f32 + 6.0) * 4.0)
.padding_right(10.0)
.width_pct(100.0)
.min_width(0.0)
.hover(|s| {
s.cursor(CursorStyle::Pointer).background(
config.color(LapceColor::PANEL_HOVERED_BACKGROUND),
)
})
})
},
)
.style(|s| s.width_pct(100.0).min_width(0.0).flex_col()),
stack((
svg(move || config.get().ui_svg(LapceIcons::LINK)).style(move |s| {
let config = config.get();
let size = config.ui.icon_size() as f32;
s.size(size, size)
.color(config.color(LapceColor::EDITOR_DIM))
}),
label(|| " ".to_string()).style(move |s| s.selectable(false)),
))
.style(move |s| {
s.absolute()
.items_center()
.margin_left(10.0 + (config.get().ui.icon_size() as f32 + 6.0) * 3.0)
}),
))
.style(move |s| {
s.width_pct(100.0)
.min_width(0.0)
.items_start()
.color(config.get().color(LapceColor::EDITOR_DIM))
.apply_if(is_empty, |s| s.hide())
})
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/panel/position.rs | lapce-app/src/panel/position.rs | use serde::{Deserialize, Serialize};
#[derive(Eq, PartialEq, Hash, Clone, Copy, Debug, Serialize, Deserialize)]
pub enum PanelPosition {
LeftTop,
LeftBottom,
BottomLeft,
BottomRight,
RightTop,
RightBottom,
}
impl PanelPosition {
pub fn is_bottom(&self) -> bool {
matches!(self, PanelPosition::BottomLeft | PanelPosition::BottomRight)
}
pub fn is_right(&self) -> bool {
matches!(self, PanelPosition::RightTop | PanelPosition::RightBottom)
}
pub fn is_left(&self) -> bool {
matches!(self, PanelPosition::LeftTop | PanelPosition::LeftBottom)
}
pub fn is_first(&self) -> bool {
matches!(
self,
PanelPosition::LeftTop
| PanelPosition::BottomLeft
| PanelPosition::RightTop
)
}
pub fn peer(&self) -> PanelPosition {
match &self {
PanelPosition::LeftTop => PanelPosition::LeftBottom,
PanelPosition::LeftBottom => PanelPosition::LeftTop,
PanelPosition::BottomLeft => PanelPosition::BottomRight,
PanelPosition::BottomRight => PanelPosition::BottomLeft,
PanelPosition::RightTop => PanelPosition::RightBottom,
PanelPosition::RightBottom => PanelPosition::RightTop,
}
}
}
#[derive(Eq, PartialEq, Hash, Clone, Copy, Debug)]
pub enum PanelContainerPosition {
Left,
Bottom,
Right,
}
impl PanelContainerPosition {
pub fn is_bottom(&self) -> bool {
matches!(self, PanelContainerPosition::Bottom)
}
pub fn first(&self) -> PanelPosition {
match self {
PanelContainerPosition::Left => PanelPosition::LeftTop,
PanelContainerPosition::Bottom => PanelPosition::BottomLeft,
PanelContainerPosition::Right => PanelPosition::RightTop,
}
}
pub fn second(&self) -> PanelPosition {
match self {
PanelContainerPosition::Left => PanelPosition::LeftBottom,
PanelContainerPosition::Bottom => PanelPosition::BottomRight,
PanelContainerPosition::Right => PanelPosition::RightBottom,
}
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/panel/data.rs | lapce-app/src/panel/data.rs | use std::{rc::Rc, sync::Arc};
use floem::{
kurbo::Size,
reactive::{
Memo, RwSignal, Scope, SignalGet, SignalUpdate, SignalWith, use_context,
},
};
use serde::{Deserialize, Serialize};
use super::{
kind::PanelKind,
position::{PanelContainerPosition, PanelPosition},
style::PanelStyle,
};
use crate::{
db::LapceDb,
window_tab::{CommonData, Focus},
};
pub type PanelOrder = im::HashMap<PanelPosition, im::Vector<PanelKind>>;
pub fn default_panel_order() -> PanelOrder {
let mut order = PanelOrder::new();
order.insert(
PanelPosition::LeftTop,
im::vector![
PanelKind::FileExplorer,
PanelKind::Plugin,
PanelKind::SourceControl,
PanelKind::Debug,
],
);
order.insert(
PanelPosition::BottomLeft,
im::vector![
PanelKind::Terminal,
PanelKind::Search,
PanelKind::Problem,
PanelKind::CallHierarchy,
PanelKind::References,
PanelKind::Implementation
],
);
order.insert(
PanelPosition::RightTop,
im::vector![PanelKind::DocumentSymbol,],
);
order
}
#[derive(Clone, Copy, Serialize, Deserialize, Hash, PartialEq, Eq)]
pub enum PanelSection {
OpenEditor,
FileExplorer,
Error,
Warn,
Changes,
Installed,
Available,
Process,
Variable,
StackFrame,
Breakpoint,
}
#[derive(Clone, Serialize, Deserialize)]
pub struct PanelSize {
pub left: f64,
pub left_split: f64,
pub bottom: f64,
pub bottom_split: f64,
pub right: f64,
pub right_split: f64,
}
#[derive(Clone, Serialize, Deserialize)]
pub struct PanelInfo {
pub panels: PanelOrder,
pub styles: im::HashMap<PanelPosition, PanelStyle>,
pub size: PanelSize,
pub sections: im::HashMap<PanelSection, bool>,
}
#[derive(Clone)]
pub struct PanelData {
pub panels: RwSignal<PanelOrder>,
pub styles: RwSignal<im::HashMap<PanelPosition, PanelStyle>>,
pub size: RwSignal<PanelSize>,
pub available_size: Memo<Size>,
pub sections: RwSignal<im::HashMap<PanelSection, RwSignal<bool>>>,
pub common: Rc<CommonData>,
}
impl PanelData {
pub fn new(
cx: Scope,
panels: im::HashMap<PanelPosition, im::Vector<PanelKind>>,
available_size: Memo<Size>,
sections: im::HashMap<PanelSection, bool>,
common: Rc<CommonData>,
) -> Self {
let panels = cx.create_rw_signal(panels);
let mut styles = im::HashMap::new();
styles.insert(
PanelPosition::LeftTop,
PanelStyle {
active: 0,
shown: true,
maximized: false,
},
);
styles.insert(
PanelPosition::LeftBottom,
PanelStyle {
active: 0,
shown: false,
maximized: false,
},
);
styles.insert(
PanelPosition::BottomLeft,
PanelStyle {
active: 0,
shown: true,
maximized: false,
},
);
styles.insert(
PanelPosition::BottomRight,
PanelStyle {
active: 0,
shown: false,
maximized: false,
},
);
styles.insert(
PanelPosition::RightTop,
PanelStyle {
active: 0,
shown: false,
maximized: false,
},
);
styles.insert(
PanelPosition::RightBottom,
PanelStyle {
active: 0,
shown: false,
maximized: false,
},
);
let styles = cx.create_rw_signal(styles);
let size = cx.create_rw_signal(PanelSize {
left: 250.0,
left_split: 0.5,
bottom: 300.0,
bottom_split: 0.5,
right: 250.0,
right_split: 0.5,
});
let sections = cx.create_rw_signal(
sections
.into_iter()
.map(|(key, value)| (key, cx.create_rw_signal(value)))
.collect(),
);
Self {
panels,
styles,
size,
available_size,
sections,
common,
}
}
pub fn panel_info(&self) -> PanelInfo {
PanelInfo {
panels: self.panels.get_untracked(),
styles: self.styles.get_untracked(),
size: self.size.get_untracked(),
sections: self
.sections
.get_untracked()
.into_iter()
.map(|(key, value)| (key, value.get_untracked()))
.collect(),
}
}
pub fn is_container_shown(
&self,
position: &PanelContainerPosition,
tracked: bool,
) -> bool {
self.is_position_shown(&position.first(), tracked)
|| self.is_position_shown(&position.second(), tracked)
}
pub fn is_position_empty(
&self,
position: &PanelPosition,
tracked: bool,
) -> bool {
if tracked {
self.panels
.with(|panels| panels.get(position).map(|p| p.is_empty()))
.unwrap_or(true)
} else {
self.panels
.with_untracked(|panels| panels.get(position).map(|p| p.is_empty()))
.unwrap_or(true)
}
}
pub fn is_position_shown(
&self,
position: &PanelPosition,
tracked: bool,
) -> bool {
let styles = if tracked {
self.styles.get()
} else {
self.styles.get_untracked()
};
styles.get(position).map(|s| s.shown).unwrap_or(false)
}
pub fn panel_position(
&self,
kind: &PanelKind,
) -> Option<(usize, PanelPosition)> {
self.panels
.with_untracked(|panels| panel_position(panels, kind))
}
pub fn is_panel_visible(&self, kind: &PanelKind) -> bool {
if let Some((index, position)) = self.panel_position(kind) {
if let Some(style) = self
.styles
.with_untracked(|styles| styles.get(&position).cloned())
{
return style.active == index && style.shown;
}
}
false
}
pub fn show_panel(&self, kind: &PanelKind) {
if let Some((index, position)) = self.panel_position(kind) {
self.styles.update(|styles| {
if let Some(style) = styles.get_mut(&position) {
style.shown = true;
style.active = index;
}
});
}
}
pub fn hide_panel(&self, kind: &PanelKind) {
if let Some((_, position)) = self.panel_position(kind) {
if let Some((active_panel, _)) =
self.active_panel_at_position(&position, false)
{
if &active_panel == kind {
self.set_shown(&position, false);
let peer_position = position.peer();
if let Some(order) = self
.panels
.with_untracked(|panels| panels.get(&peer_position).cloned())
{
if order.is_empty() {
self.set_shown(&peer_position, false);
}
}
}
}
}
}
/// Get the active panel kind at that position, if any.
/// `tracked` decides whether it should track the signal or not.
pub fn active_panel_at_position(
&self,
position: &PanelPosition,
tracked: bool,
) -> Option<(PanelKind, bool)> {
let style = if tracked {
self.styles.with(|styles| styles.get(position).cloned())?
} else {
self.styles
.with_untracked(|styles| styles.get(position).cloned())?
};
let order = if tracked {
self.panels.with(|panels| panels.get(position).cloned())?
} else {
self.panels
.with_untracked(|panels| panels.get(position).cloned())?
};
order
.get(style.active)
.cloned()
.or_else(|| order.last().cloned())
.map(|p| (p, style.shown))
}
pub fn set_shown(&self, position: &PanelPosition, shown: bool) {
self.styles.update(|styles| {
if let Some(style) = styles.get_mut(position) {
style.shown = shown;
}
});
}
pub fn toggle_active_maximize(&self) {
let focus = self.common.focus.get_untracked();
if let Focus::Panel(kind) = focus {
if let Some((_, pos)) = self.panel_position(&kind) {
if pos.is_bottom() {
self.toggle_bottom_maximize();
}
}
}
}
pub fn toggle_maximize(&self, kind: &PanelKind) {
if let Some((_, p)) = self.panel_position(kind) {
if p.is_bottom() {
self.toggle_bottom_maximize();
}
}
}
pub fn toggle_bottom_maximize(&self) {
let maximized = !self.panel_bottom_maximized(false);
self.styles.update(|styles| {
if let Some(style) = styles.get_mut(&PanelPosition::BottomLeft) {
style.maximized = maximized;
}
if let Some(style) = styles.get_mut(&PanelPosition::BottomRight) {
style.maximized = maximized;
}
});
}
pub fn panel_bottom_maximized(&self, tracked: bool) -> bool {
let styles = if tracked {
self.styles.get()
} else {
self.styles.get_untracked()
};
styles
.get(&PanelPosition::BottomLeft)
.map(|p| p.maximized)
.unwrap_or(false)
|| styles
.get(&PanelPosition::BottomRight)
.map(|p| p.maximized)
.unwrap_or(false)
}
pub fn toggle_container_visual(&self, position: &PanelContainerPosition) {
let is_hidden = !self.is_container_shown(position, false);
if is_hidden {
self.styles.update(|styles| {
let style = styles.entry(position.first()).or_default();
style.shown = true;
let style = styles.entry(position.second()).or_default();
style.shown = true;
});
} else {
if let Some((kind, _)) =
self.active_panel_at_position(&position.second(), false)
{
self.hide_panel(&kind);
}
if let Some((kind, _)) =
self.active_panel_at_position(&position.first(), false)
{
self.hide_panel(&kind);
}
self.styles.update(|styles| {
let style = styles.entry(position.first()).or_default();
style.shown = false;
let style = styles.entry(position.second()).or_default();
style.shown = false;
});
}
}
pub fn move_panel_to_position(&self, kind: PanelKind, position: &PanelPosition) {
let current_position = self.panel_position(&kind);
if current_position.as_ref().map(|(_, pos)| pos) == Some(position) {
return;
}
let mut new_index_at_old_position = None;
let index = self
.panels
.try_update(|panels| {
if let Some((index, current_position)) = current_position {
if let Some(panels) = panels.get_mut(¤t_position) {
panels.remove(index);
let max_index = panels.len().saturating_sub(1);
if index > max_index {
new_index_at_old_position = Some(max_index);
}
}
}
let panels = panels.entry(*position).or_default();
panels.push_back(kind);
panels.len() - 1
})
.unwrap();
self.styles.update(|styles| {
if let Some((_, current_position)) = current_position {
if let Some(new_index) = new_index_at_old_position {
let style = styles.entry(current_position).or_default();
style.active = new_index;
}
}
let style = styles.entry(*position).or_default();
style.active = index;
style.shown = true;
});
let db: Arc<LapceDb> = use_context().unwrap();
db.save_panel_orders(self.panels.get_untracked());
}
pub fn section_open(&self, section: PanelSection) -> RwSignal<bool> {
let open = self
.sections
.with_untracked(|sections| sections.get(§ion).cloned());
if let Some(open) = open {
return open;
}
let open = self.common.scope.create_rw_signal(true);
self.sections.update(|sections| {
sections.insert(section, open);
});
open
}
}
pub fn panel_position(
order: &PanelOrder,
kind: &PanelKind,
) -> Option<(usize, PanelPosition)> {
for (pos, panels) in order.iter() {
let index = panels.iter().position(|k| k == kind);
if let Some(index) = index {
return Some((index, *pos));
}
}
None
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/panel/call_hierarchy_view.rs | lapce-app/src/panel/call_hierarchy_view.rs | use std::{ops::AddAssign, rc::Rc};
use floem::{
IntoView, View, ViewId,
reactive::{RwSignal, SignalGet, SignalUpdate, SignalWith},
style::CursorStyle,
views::{
Decorators, VirtualVector, container, empty, label, scroll, stack, svg,
virtual_stack,
},
};
use lsp_types::{CallHierarchyItem, Range};
use super::position::PanelPosition;
use crate::{
command::InternalCommand,
config::{color::LapceColor, icon::LapceIcons},
editor::location::EditorLocation,
window_tab::{CommonData, WindowTabData},
};
#[derive(Clone, Debug)]
pub struct CallHierarchyData {
pub root: RwSignal<Option<RwSignal<CallHierarchyItemData>>>,
pub common: Rc<CommonData>,
pub scroll_to_line: RwSignal<Option<f64>>,
}
#[derive(Debug, Clone)]
pub struct CallHierarchyItemData {
pub view_id: ViewId,
pub item: Rc<CallHierarchyItem>,
pub from_range: Range,
pub init: bool,
pub open: RwSignal<bool>,
pub children: RwSignal<Vec<RwSignal<CallHierarchyItemData>>>,
}
impl CallHierarchyItemData {
pub fn child_count(&self) -> usize {
let mut count = 1;
if self.open.get() {
for child in self.children.get_untracked() {
count += child.with(|x| x.child_count())
}
}
count
}
pub fn find_by_id(
root: RwSignal<CallHierarchyItemData>,
view_id: ViewId,
) -> Option<RwSignal<CallHierarchyItemData>> {
if root.get_untracked().view_id == view_id {
Some(root)
} else {
root.get_untracked()
.children
.get_untracked()
.into_iter()
.find_map(|x| Self::find_by_id(x, view_id))
}
}
}
fn get_children(
data: RwSignal<CallHierarchyItemData>,
next: &mut usize,
min: usize,
max: usize,
level: usize,
) -> Vec<(usize, usize, RwSignal<CallHierarchyItemData>)> {
let mut children = Vec::new();
if *next >= min && *next < max {
children.push((*next, level, data));
} else if *next >= max {
return children;
}
next.add_assign(1);
if data.get_untracked().open.get() {
for child in data.get().children.get_untracked() {
let child_children = get_children(child, next, min, max, level + 1);
children.extend(child_children);
if *next > max {
break;
}
}
}
children
}
pub struct VirtualList {
root: Option<RwSignal<CallHierarchyItemData>>,
}
impl VirtualList {
pub fn new(root: Option<RwSignal<CallHierarchyItemData>>) -> Self {
Self { root }
}
}
impl VirtualVector<(usize, usize, RwSignal<CallHierarchyItemData>)> for VirtualList {
fn total_len(&self) -> usize {
if let Some(root) = &self.root {
root.with(|x| x.child_count())
} else {
0
}
}
fn slice(
&mut self,
range: std::ops::Range<usize>,
) -> impl Iterator<Item = (usize, usize, RwSignal<CallHierarchyItemData>)> {
if let Some(root) = &self.root {
let min = range.start;
let max = range.end;
let children = get_children(*root, &mut 0, min, max, 0);
children.into_iter()
} else {
Vec::new().into_iter()
}
}
}
pub fn show_hierarchy_panel(
window_tab_data: Rc<WindowTabData>,
_position: PanelPosition,
) -> impl View {
let call_hierarchy_data = window_tab_data.call_hierarchy_data.clone();
let config = call_hierarchy_data.common.config;
let ui_line_height = call_hierarchy_data.common.ui_line_height;
let scroll_to_line = call_hierarchy_data.scroll_to_line;
scroll(
virtual_stack(
move || VirtualList::new(call_hierarchy_data.root.get()),
move |(_, _, item)| item.get_untracked().view_id,
move |(_, level, rw_data)| {
let data = rw_data.get_untracked();
let open = data.open;
let kind = data.item.kind;
stack((
container(
svg(move || {
let config = config.get();
let svg_str = match open.get() {
true => LapceIcons::ITEM_OPENED,
false => LapceIcons::ITEM_CLOSED,
};
config.ui_svg(svg_str)
})
.style(move |s| {
let config = config.get();
let size = config.ui.icon_size() as f32;
s.size(size, size)
.color(config.color(LapceColor::LAPCE_ICON_ACTIVE))
})
)
.style(|s| s.padding(4.0).margin_left(6.0).margin_right(2.0))
.on_click_stop({
let window_tab_data = window_tab_data.clone();
move |_x| {
open.update(|x| {
*x = !*x;
});
if !rw_data.get_untracked().init {
window_tab_data.common.internal_command.send(
InternalCommand::CallHierarchyIncoming {
item_id: rw_data.get_untracked().view_id,
},
);
}
}
}),
svg(move || {
let config = config.get();
config
.symbol_svg(&kind)
.unwrap_or_else(|| config.ui_svg(LapceIcons::FILE))
}).style(move |s| {
let config = config.get();
let size = config.ui.icon_size() as f32;
s.min_width(size)
.size(size, size)
.margin_right(5.0)
.color(config.symbol_color(&kind).unwrap_or_else(|| {
config.color(LapceColor::LAPCE_ICON_ACTIVE)
}))
}),
data.item.name.clone().into_view(),
if data.item.detail.is_some() {
label(move || {
data.item.detail.clone().unwrap_or_default().replace('\n', "↵")
}).style(move |s| s.margin_left(6.0)
.color(config.get().color(LapceColor::EDITOR_DIM))
).into_any()
} else {
empty().into_any()
},
))
.style(move |s| {
s.padding_right(5.0)
.height(ui_line_height.get())
.padding_left((level * 10) as f32)
.items_center()
.hover(|s| {
s.background(
config
.get()
.color(LapceColor::PANEL_HOVERED_BACKGROUND),
)
.cursor(CursorStyle::Pointer)
})
})
.on_click_stop({
let window_tab_data = window_tab_data.clone();
let data = rw_data;
move |_| {
if !rw_data.get_untracked().init {
window_tab_data.common.internal_command.send(
InternalCommand::CallHierarchyIncoming { item_id: rw_data.get_untracked().view_id },
);
}
let data = data.get_untracked();
if let Ok(path) = data.item.uri.to_file_path() {
window_tab_data
.common
.internal_command
.send(InternalCommand::JumpToLocation { location: EditorLocation {
path,
position: Some(crate::editor::location::EditorPosition::Position(data.from_range.start)),
scroll_offset: None,
ignore_unconfirmed: false,
same_editor_tab: false,
} });
}
}
})
},
).item_size_fixed(move || ui_line_height.get())
.style(|s| s.flex_col().absolute().min_width_full()),
)
.style(|s| s.absolute().size_full())
.scroll_to(move || {
if let Some(line) = scroll_to_line.get() {
let line_height = ui_line_height.get();
Some((0.0, line * line_height).into())
} else {
None
}
})
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/bin/lapce.rs | lapce-app/src/bin/lapce.rs | #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use lapce_app::app;
pub fn main() {
app::launch();
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/terminal/event.rs | lapce-app/src/terminal/event.rs | use std::{
collections::HashMap,
sync::{
Arc,
mpsc::{Receiver, Sender},
},
time::Instant,
};
use lapce_rpc::terminal::TermId;
use parking_lot::RwLock;
use super::raw::RawTerminal;
/// The notifications for terminals to send back to main thread
pub enum TermNotification {
SetTitle { term_id: TermId, title: String },
RequestPaint,
}
pub enum TermEvent {
NewTerminal(Arc<RwLock<RawTerminal>>),
UpdateContent(Vec<u8>),
CloseTerminal,
}
pub fn terminal_update_process(
receiver: Receiver<(TermId, TermEvent)>,
term_notification_tx: Sender<TermNotification>,
) {
let mut terminals = HashMap::new();
let mut last_redraw = Instant::now();
let mut last_event = None;
loop {
let (term_id, event) = if let Some((term_id, event)) = last_event.take() {
(term_id, event)
} else {
match receiver.recv() {
Ok((term_id, event)) => (term_id, event),
Err(_) => return,
}
};
match event {
TermEvent::CloseTerminal => {
terminals.remove(&term_id);
}
TermEvent::NewTerminal(raw) => {
terminals.insert(term_id, raw);
}
TermEvent::UpdateContent(content) => {
if let Some(raw) = terminals.get(&term_id) {
{
raw.write().update_content(content);
}
last_event = receiver.try_recv().ok();
if last_event.is_some() {
if last_redraw.elapsed().as_millis() > 10 {
last_redraw = Instant::now();
if let Err(err) = term_notification_tx
.send(TermNotification::RequestPaint)
{
tracing::error!("{:?}", err);
}
}
} else {
last_redraw = Instant::now();
if let Err(err) =
term_notification_tx.send(TermNotification::RequestPaint)
{
tracing::error!("{:?}", err);
}
}
}
}
}
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/terminal/view.rs | lapce-app/src/terminal/view.rs | use std::{sync::Arc, time::SystemTime};
use alacritty_terminal::{
grid::Dimensions,
index::Side,
selection::{Selection, SelectionType},
term::{RenderableContent, cell::Flags, test::TermSize},
};
use floem::{
Renderer, View, ViewId,
context::{EventCx, PaintCx},
event::{Event, EventPropagation},
kurbo::Stroke,
peniko::{
Color,
kurbo::{Point, Rect, Size},
},
pointer::PointerInputEvent,
prelude::SignalTrack,
reactive::{ReadSignal, RwSignal, SignalGet, SignalWith, create_effect},
text::{Attrs, AttrsList, FamilyOwned, TextLayout, Weight},
views::editor::{core::register::Clipboard, text::SystemClipboard},
};
use lapce_core::mode::Mode;
use lapce_rpc::{proxy::ProxyRpcHandler, terminal::TermId};
use lsp_types::Position;
use parking_lot::RwLock;
use regex::Regex;
use unicode_width::UnicodeWidthChar;
use super::{panel::TerminalPanelData, raw::RawTerminal};
use crate::{
command::InternalCommand,
config::{LapceConfig, color::LapceColor},
debug::RunDebugProcess,
editor::location::{EditorLocation, EditorPosition},
listener::Listener,
panel::kind::PanelKind,
window_tab::Focus,
workspace::LapceWorkspace,
};
/// Threshold used for double_click/triple_click.
const CLICK_THRESHOLD: u128 = 400;
enum TerminalViewState {
Config,
Focus(bool),
Raw(Arc<RwLock<RawTerminal>>),
}
struct TerminalLineContent<'a> {
y: f64,
bg: Vec<(usize, usize, Color)>,
underline: Vec<(usize, usize, Color, f64)>,
chars: Vec<(char, Attrs<'a>, f64, f64)>,
cursor: Option<(char, f64)>,
}
pub struct TerminalView {
id: ViewId,
term_id: TermId,
raw: Arc<RwLock<RawTerminal>>,
mode: ReadSignal<Mode>,
size: Size,
is_focused: bool,
config: ReadSignal<Arc<LapceConfig>>,
run_config: ReadSignal<Option<RunDebugProcess>>,
proxy: ProxyRpcHandler,
launch_error: RwSignal<Option<String>>,
internal_command: Listener<InternalCommand>,
workspace: Arc<LapceWorkspace>,
hyper_regs: Vec<Regex>,
previous_mouse_action: MouseAction,
current_mouse_action: MouseAction,
}
#[allow(clippy::too_many_arguments)]
pub fn terminal_view(
term_id: TermId,
raw: ReadSignal<Arc<RwLock<RawTerminal>>>,
mode: ReadSignal<Mode>,
run_config: ReadSignal<Option<RunDebugProcess>>,
terminal_panel_data: TerminalPanelData,
launch_error: RwSignal<Option<String>>,
internal_command: Listener<InternalCommand>,
workspace: Arc<LapceWorkspace>,
) -> TerminalView {
let id = ViewId::new();
create_effect(move |_| {
let raw = raw.get();
id.update_state(TerminalViewState::Raw(raw));
});
create_effect(move |_| {
launch_error.track();
id.request_paint();
});
let config = terminal_panel_data.common.config;
create_effect(move |_| {
config.with(|_c| {});
id.update_state(TerminalViewState::Config);
});
let proxy = terminal_panel_data.common.proxy.clone();
create_effect(move |last| {
let focus = terminal_panel_data.common.focus.get();
let mut is_focused = false;
if let Focus::Panel(PanelKind::Terminal) = focus {
let tab = terminal_panel_data.active_tab(true);
if let Some(tab) = tab {
let terminal = tab.active_terminal(true);
is_focused = terminal.map(|t| t.term_id) == Some(term_id);
}
}
if last != Some(is_focused) {
id.update_state(TerminalViewState::Focus(is_focused));
}
is_focused
});
// for rust
let reg = regex::Regex::new("[\\w\\\\/-]+\\.(rs)?(toml)?:\\d+(:\\d+)?").unwrap();
TerminalView {
id,
term_id,
raw: raw.get_untracked(),
mode,
config,
proxy,
run_config,
size: Size::ZERO,
is_focused: false,
launch_error,
internal_command,
workspace,
hyper_regs: vec![reg],
previous_mouse_action: Default::default(),
current_mouse_action: Default::default(),
}
}
impl TerminalView {
fn char_size(&self) -> Size {
let config = self.config.get_untracked();
let font_family = config.terminal_font_family();
let font_size = config.terminal_font_size();
let family: Vec<FamilyOwned> =
FamilyOwned::parse_list(font_family).collect();
let attrs = Attrs::new().family(&family).font_size(font_size as f32);
let attrs_list = AttrsList::new(attrs);
let mut text_layout = TextLayout::new();
text_layout.set_text("W", attrs_list, None);
text_layout.size()
}
fn terminal_size(&self) -> (usize, usize) {
let config = self.config.get_untracked();
let line_height = config.terminal_line_height() as f64;
let char_width = self.char_size().width;
let width = (self.size.width / char_width).floor() as usize;
let height = (self.size.height / line_height).floor() as usize;
(width.max(1), height.max(1))
}
fn click(&self, pos: Point) -> Option<()> {
let raw = self.raw.read();
let position = self.get_terminal_point(pos);
let start_point = raw.term.semantic_search_left(position);
let end_point = raw.term.semantic_search_right(position);
let mut selection =
Selection::new(SelectionType::Simple, start_point, Side::Left);
selection.update(end_point, Side::Right);
selection.include_all();
if let Some(selection) = selection.to_range(&raw.term) {
let content = raw.term.bounds_to_string(selection.start, selection.end);
if let Some(match_str) =
self.hyper_regs.iter().find_map(|x| x.find(&content))
{
let hyperlink = match_str.as_str();
let content: Vec<&str> = hyperlink.split(':').collect();
let (file, line, col) = (
content.first()?,
content.get(1).and_then(|x: &&str| x.parse::<u32>().ok())?,
content
.get(2)
.and_then(|x: &&str| x.parse::<u32>().ok())
.unwrap_or(0),
);
let parent_path = self.workspace.path.as_ref()?;
self.internal_command.send(InternalCommand::JumpToLocation {
location: EditorLocation {
path: parent_path.join(file),
position: Some(EditorPosition::Position(Position::new(
line.saturating_sub(1),
col.saturating_sub(1),
))),
scroll_offset: None,
ignore_unconfirmed: false,
same_editor_tab: false,
},
});
return Some(());
}
}
None
}
fn update_mouse_action_by_down(&mut self, mouse: &PointerInputEvent) {
let mut next_action = MouseAction::None;
match self.current_mouse_action {
MouseAction::None
| MouseAction::LeftDouble { .. }
| MouseAction::LeftSelect { .. }
| MouseAction::RightOnce { .. } => {
if mouse.button.is_primary() {
next_action = MouseAction::LeftDown { pos: mouse.pos };
} else if mouse.button.is_secondary() {
next_action = MouseAction::RightDown { pos: mouse.pos };
}
}
MouseAction::LeftOnce { pos, time } => {
let during_mills =
time.elapsed().map(|x| x.as_millis()).unwrap_or(u128::MAX);
match (
mouse.button.is_primary(),
mouse.pos == pos,
during_mills < CLICK_THRESHOLD,
) {
(true, true, true) => {
next_action = MouseAction::LeftOnceAndDown { pos, time };
}
(true, _, _) => {
next_action = MouseAction::LeftDown { pos: mouse.pos };
}
_ => {}
}
}
MouseAction::LeftOnceAndDown { .. }
| MouseAction::LeftDown { .. }
| MouseAction::RightDown { .. } => {}
}
self.current_mouse_action = next_action;
}
fn update_mouse_action_by_up(&mut self, mouse: &PointerInputEvent) {
let mut next_action = MouseAction::None;
match self.current_mouse_action {
MouseAction::None => {}
MouseAction::LeftDown { pos } => {
match (mouse.button.is_primary(), mouse.pos == pos) {
(true, true) => {
next_action = MouseAction::LeftOnce {
pos,
time: SystemTime::now(),
}
}
(true, false) => {
next_action = MouseAction::LeftSelect {
start_pos: pos,
end_pos: mouse.pos,
};
}
_ => {}
}
}
MouseAction::LeftOnce { .. } => {}
MouseAction::LeftSelect { .. } => {}
MouseAction::LeftOnceAndDown { pos, time } => {
let during_mills =
time.elapsed().map(|x| x.as_millis()).unwrap_or(u128::MAX);
match (
mouse.button.is_primary(),
mouse.pos == pos,
during_mills < CLICK_THRESHOLD,
) {
(true, true, true) => {
next_action = MouseAction::LeftDouble { pos };
}
(true, true, false) => {
next_action = MouseAction::LeftOnce {
pos: mouse.pos,
time: SystemTime::now(),
};
}
(true, false, _) => {
next_action = MouseAction::LeftSelect {
start_pos: pos,
end_pos: mouse.pos,
};
}
_ => {}
}
}
MouseAction::LeftDouble { .. } => {}
MouseAction::RightDown { pos } => {
if mouse.button.is_secondary() && mouse.pos == pos {
next_action = MouseAction::RightOnce { pos };
}
}
MouseAction::RightOnce { .. } => {}
}
self.previous_mouse_action = self.current_mouse_action;
self.current_mouse_action = next_action;
}
fn get_terminal_point(&self, pos: Point) -> alacritty_terminal::index::Point {
let raw = self.raw.read();
let col = (pos.x / self.char_size().width) as usize;
let line_no = pos.y as i32
/ (self.config.get().terminal_line_height() as i32)
- raw.term.grid().display_offset() as i32;
alacritty_terminal::index::Point::new(
alacritty_terminal::index::Line(line_no),
alacritty_terminal::index::Column(col),
)
}
fn paint_content(
&self,
cx: &mut PaintCx,
content: RenderableContent,
line_height: f64,
char_size: Size,
config: &LapceConfig,
) {
let term_bg = config.color(LapceColor::TERMINAL_BACKGROUND);
let font_size = config.terminal_font_size();
let font_family = config.terminal_font_family();
let family: Vec<FamilyOwned> =
FamilyOwned::parse_list(font_family).collect();
let attrs = Attrs::new().family(&family).font_size(font_size as f32);
let char_width = char_size.width;
let cursor_point = &content.cursor.point;
let mut line_content = TerminalLineContent {
y: 0.0,
bg: Vec::new(),
underline: Vec::new(),
chars: Vec::new(),
cursor: None,
};
for item in content.display_iter {
let point = item.point;
let cell = item.cell;
let inverse = cell.flags.contains(Flags::INVERSE);
let x = point.column.0 as f64 * char_width;
let y =
(point.line.0 as f64 + content.display_offset as f64) * line_height;
let char_y = y + (line_height - char_size.height) / 2.0;
if y != line_content.y {
self.paint_line_content(
cx,
&line_content,
line_height,
char_width,
config,
);
line_content.y = y;
line_content.bg.clear();
line_content.underline.clear();
line_content.chars.clear();
line_content.cursor = None;
}
let mut bg = config.terminal_get_color(&cell.bg, content.colors);
let mut fg = config.terminal_get_color(&cell.fg, content.colors);
if cell.flags.contains(Flags::DIM)
|| cell.flags.contains(Flags::DIM_BOLD)
{
fg = fg.multiply_alpha(0.66);
}
if inverse {
std::mem::swap(&mut fg, &mut bg);
}
if term_bg != bg {
let mut extend = false;
if let Some((_, end, color)) = line_content.bg.last_mut() {
if color == &bg && *end == point.column.0 {
*end += 1;
extend = true;
}
}
if !extend {
line_content
.bg
.push((point.column.0, point.column.0 + 1, bg));
}
}
if cursor_point == &point {
line_content.cursor = Some((cell.c, x));
}
let bold = cell.flags.contains(Flags::BOLD)
|| cell.flags.contains(Flags::DIM_BOLD);
if &point == cursor_point && self.is_focused {
fg = term_bg;
}
if cell.c != ' ' && cell.c != '\t' {
let mut attrs = attrs.clone().color(fg);
if bold {
attrs = attrs.weight(Weight::BOLD);
}
line_content.chars.push((cell.c, attrs, x, char_y));
}
}
self.paint_line_content(cx, &line_content, line_height, char_width, config);
}
fn paint_line_content(
&self,
cx: &mut PaintCx,
line_content: &TerminalLineContent,
line_height: f64,
char_width: f64,
config: &LapceConfig,
) {
for (start, end, bg) in &line_content.bg {
let rect = Size::new(
char_width * (end.saturating_sub(*start) as f64),
line_height,
)
.to_rect()
.with_origin(Point::new(*start as f64 * char_width, line_content.y));
cx.fill(&rect, bg, 0.0);
}
for (start, end, fg, y) in &line_content.underline {
let rect =
Size::new(char_width * (end.saturating_sub(*start) as f64), 1.0)
.to_rect()
.with_origin(Point::new(*start as f64 * char_width, y - 1.0));
cx.fill(&rect, fg, 0.0);
}
if let Some((c, x)) = line_content.cursor {
let rect =
Size::new(char_width * c.width().unwrap_or(1) as f64, line_height)
.to_rect()
.with_origin(Point::new(x, line_content.y));
let mode = self.mode.get_untracked();
let cursor_color = if mode == Mode::Terminal {
if self.run_config.with_untracked(|run_config| {
run_config.as_ref().map(|r| r.stopped).unwrap_or(false)
}) {
config.color(LapceColor::LAPCE_ERROR)
} else {
config.color(LapceColor::TERMINAL_CURSOR)
}
} else {
config.color(LapceColor::EDITOR_CARET)
};
if self.is_focused {
cx.fill(&rect, cursor_color, 0.0);
} else {
cx.stroke(&rect, cursor_color, &Stroke::new(1.0));
}
}
for (char, attr, x, y) in &line_content.chars {
let mut text_layout = TextLayout::new();
text_layout.set_text(
&char.to_string(),
AttrsList::new(attr.clone()),
None,
);
cx.draw_text(&text_layout, Point::new(*x, *y));
}
}
}
impl Drop for TerminalView {
fn drop(&mut self) {
self.proxy.terminal_close(self.term_id);
}
}
impl View for TerminalView {
fn id(&self) -> ViewId {
self.id
}
fn event_before_children(
&mut self,
_cx: &mut EventCx,
event: &Event,
) -> EventPropagation {
match event {
Event::PointerDown(e) => {
self.update_mouse_action_by_down(e);
}
Event::PointerUp(e) => {
self.update_mouse_action_by_up(e);
let mut clear_selection = false;
match self.current_mouse_action {
MouseAction::LeftOnce { pos, .. } => {
clear_selection = true;
if e.modifiers.control() && self.click(pos).is_some() {
return EventPropagation::Stop;
}
}
MouseAction::LeftSelect { start_pos, end_pos } => {
let mut selection = Selection::new(
SelectionType::Simple,
self.get_terminal_point(start_pos),
Side::Left,
);
selection
.update(self.get_terminal_point(end_pos), Side::Right);
selection.include_all();
self.raw.write().term.selection = Some(selection);
_cx.app_state_mut().request_paint(self.id);
}
MouseAction::LeftDouble { pos } => {
let position = self.get_terminal_point(pos);
let mut raw = self.raw.write();
let start_point = raw.term.semantic_search_left(position);
let end_point = raw.term.semantic_search_right(position);
let mut selection = Selection::new(
SelectionType::Simple,
start_point,
Side::Left,
);
selection.update(end_point, Side::Right);
selection.include_all();
raw.term.selection = Some(selection);
_cx.app_state_mut().request_paint(self.id);
}
MouseAction::RightOnce { pos } => {
let position = self.get_terminal_point(pos);
let raw = self.raw.read();
if let Some(selection) = &raw
.term
.selection
.as_ref()
.and_then(|x| x.to_range(&raw.term))
{
if selection.contains(position) {
let mut clipboard = SystemClipboard::new();
let content = raw.term.bounds_to_string(
selection.start,
selection.end,
);
if !content.is_empty() {
clipboard.put_string(content);
}
}
clear_selection = true;
}
}
_ => {
clear_selection = true;
}
}
if clear_selection {
self.raw.write().term.selection = None;
_cx.app_state_mut().request_paint(self.id);
}
}
_ => {}
}
EventPropagation::Continue
}
fn update(
&mut self,
cx: &mut floem::context::UpdateCx,
state: Box<dyn std::any::Any>,
) {
if let Ok(state) = state.downcast() {
match *state {
TerminalViewState::Config => {}
TerminalViewState::Focus(is_focused) => {
self.is_focused = is_focused;
}
TerminalViewState::Raw(raw) => {
self.raw = raw;
}
}
cx.app_state_mut().request_paint(self.id);
}
}
fn layout(
&mut self,
cx: &mut floem::context::LayoutCx,
) -> floem::taffy::prelude::NodeId {
cx.layout_node(self.id, false, |_cx| Vec::new())
}
fn compute_layout(
&mut self,
_cx: &mut floem::context::ComputeLayoutCx,
) -> Option<Rect> {
let layout = self.id.get_layout().unwrap_or_default();
let size = layout.size;
let size = Size::new(size.width as f64, size.height as f64);
if size.is_zero_area() {
return None;
}
if size != self.size {
self.size = size;
let (width, height) = self.terminal_size();
let term_size = TermSize::new(width, height);
self.raw.write().term.resize(term_size);
self.proxy.terminal_resize(self.term_id, width, height);
}
None
}
fn paint(&mut self, cx: &mut floem::context::PaintCx) {
let config = self.config.get_untracked();
let mode = self.mode.get_untracked();
let line_height = config.terminal_line_height() as f64;
let font_family = config.terminal_font_family();
let font_size = config.terminal_font_size();
let char_size = self.char_size();
let char_width = char_size.width;
let family: Vec<FamilyOwned> =
FamilyOwned::parse_list(font_family).collect();
let attrs = Attrs::new().family(&family).font_size(font_size as f32);
if let Some(error) = self.launch_error.get() {
let mut text_layout = TextLayout::new();
text_layout.set_text(
&format!("Terminal failed to launch. Error: {error}"),
AttrsList::new(
attrs.color(config.color(LapceColor::EDITOR_FOREGROUND)),
),
None,
);
cx.draw_text(
&text_layout,
Point::new(6.0, 0.0 + (line_height - char_size.height) / 2.0),
);
return;
}
let raw = self.raw.read();
let term = &raw.term;
let content = term.renderable_content();
// let mut search = RegexSearch::new("[\\w\\\\?]+\\.rs:\\d+:\\d+").unwrap();
// self.hyper_matches = visible_regex_match_iter(term, &mut search).collect();
if let Some(selection) = content.selection.as_ref() {
let start_line = selection.start.line.0 + content.display_offset as i32;
let start_line = if start_line < 0 {
0
} else {
start_line as usize
};
let start_col = selection.start.column.0;
let end_line = selection.end.line.0 + content.display_offset as i32;
let end_line = if end_line < 0 { 0 } else { end_line as usize };
let end_col = selection.end.column.0;
for line in start_line..end_line + 1 {
let left_col = if selection.is_block || line == start_line {
start_col
} else {
0
};
let right_col = if selection.is_block || line == end_line {
end_col + 1
} else {
term.last_column().0
};
let x0 = left_col as f64 * char_width;
let x1 = right_col as f64 * char_width;
let y0 = line as f64 * line_height;
let y1 = y0 + line_height;
cx.fill(
&Rect::new(x0, y0, x1, y1),
config.color(LapceColor::EDITOR_SELECTION),
0.0,
);
}
} else if mode != Mode::Terminal {
let y = (content.cursor.point.line.0 as f64
+ content.display_offset as f64)
* line_height;
cx.fill(
&Rect::new(0.0, y, self.size.width, y + line_height),
config.color(LapceColor::EDITOR_CURRENT_LINE),
0.0,
);
}
self.paint_content(cx, content, line_height, char_size, &config);
// if data.find.visual {
// if let Some(search_string) = data.find.search_string.as_ref() {
// if let Ok(dfas) = RegexSearch::new(®ex::escape(search_string)) {
// let mut start = alacritty_terminal::index::Point::new(
// alacritty_terminal::index::Line(
// -(content.display_offset as i32),
// ),
// alacritty_terminal::index::Column(0),
// );
// let end_line = (start.line + term.screen_lines())
// .min(term.bottommost_line());
// let mut max_lines = (end_line.0 - start.line.0) as usize;
// while let Some(m) = term.search_next(
// &dfas,
// start,
// Direction::Right,
// Side::Left,
// Some(max_lines),
// ) {
// let match_start = m.start();
// if match_start.line.0 < start.line.0
// || (match_start.line.0 == start.line.0
// && match_start.column.0 < start.column.0)
// {
// break;
// }
// let x = match_start.column.0 as f64 * char_width;
// let y = (match_start.line.0 as f64
// + content.display_offset as f64)
// * line_height;
// let rect = Rect::ZERO
// .with_origin(Point::new(x, y))
// .with_size(Size::new(
// (m.end().column.0 - m.start().column.0
// + term.grid()[*m.end()].c.width().unwrap_or(1))
// as f64
// * char_width,
// line_height,
// ));
// cx.stroke(
// &rect,
// config.get_color(LapceColor::TERMINAL_FOREGROUND),
// 1.0,
// );
// start = *m.end();
// if start.column.0 < term.last_column() {
// start.column.0 += 1;
// } else if start.line.0 < term.bottommost_line() {
// start.column.0 = 0;
// start.line.0 += 1;
// }
// max_lines = (end_line.0 - start.line.0) as usize;
// }
// }
// }
// }
}
}
#[derive(Debug, Default, Copy, Clone)]
enum MouseAction {
#[default]
None,
LeftDown {
pos: Point,
},
LeftOnce {
pos: Point,
time: SystemTime,
},
LeftSelect {
start_pos: Point,
end_pos: Point,
},
LeftOnceAndDown {
pos: Point,
time: SystemTime,
},
LeftDouble {
pos: Point,
},
RightDown {
pos: Point,
},
RightOnce {
pos: Point,
},
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/terminal/raw.rs | lapce-app/src/terminal/raw.rs | use std::sync::mpsc::Sender;
use alacritty_terminal::{
Term,
event::EventListener,
grid::Dimensions,
index::{Column, Direction, Line, Point},
term::{
cell::{Flags, LineLength},
search::{Match, RegexIter, RegexSearch},
test::TermSize,
},
vte::ansi,
};
use lapce_rpc::{proxy::ProxyRpcHandler, terminal::TermId};
use super::event::TermNotification;
pub struct EventProxy {
term_id: TermId,
proxy: ProxyRpcHandler,
term_notification_tx: Sender<TermNotification>,
}
impl EventListener for EventProxy {
fn send_event(&self, event: alacritty_terminal::event::Event) {
match event {
alacritty_terminal::event::Event::PtyWrite(s) => {
self.proxy.terminal_write(self.term_id, s);
}
alacritty_terminal::event::Event::MouseCursorDirty => {
if let Err(err) = self
.term_notification_tx
.send(TermNotification::RequestPaint)
{
tracing::error!("{:?}", err);
}
}
alacritty_terminal::event::Event::Title(s) => {
if let Err(err) =
self.term_notification_tx.send(TermNotification::SetTitle {
term_id: self.term_id,
title: s,
})
{
tracing::error!("{:?}", err);
}
}
_ => (),
}
}
}
pub struct RawTerminal {
pub parser: ansi::Processor,
pub term: Term<EventProxy>,
pub scroll_delta: f64,
}
impl RawTerminal {
pub fn new(
term_id: TermId,
proxy: ProxyRpcHandler,
term_notification_tx: Sender<TermNotification>,
) -> Self {
let config = alacritty_terminal::term::Config {
semantic_escape_chars: ",│`|\"' ()[]{}<>\t".to_string(),
..Default::default()
};
let event_proxy = EventProxy {
term_id,
proxy,
term_notification_tx,
};
let size = TermSize::new(50, 30);
let term = Term::new(config, &size, event_proxy);
let parser = ansi::Processor::new();
Self {
parser,
term,
scroll_delta: 0.0,
}
}
pub fn update_content(&mut self, content: Vec<u8>) {
for byte in content {
self.parser.advance(&mut self.term, byte);
}
}
pub fn output(&self, line_num: usize) -> Vec<String> {
let grid = self.term.grid();
let mut lines = Vec::with_capacity(5);
let mut rows = Vec::new();
for line in (grid.topmost_line().0..=grid.bottommost_line().0)
.map(Line)
.rev()
{
let row_cell = &grid[line];
if row_cell[Column(row_cell.len() - 1)]
.flags
.contains(Flags::WRAPLINE)
{
rows.push(row_cell);
} else {
if !rows.is_empty() {
let mut new_line = Vec::new();
std::mem::swap(&mut rows, &mut new_line);
let line_str: String = new_line
.into_iter()
.rev()
.flat_map(|x| {
x.into_iter().take(x.line_length().0).map(|x| x.c)
})
.collect();
lines.push(line_str);
if lines.len() >= line_num {
break;
}
}
rows.push(row_cell);
}
}
for line in &lines {
tracing::info!("{}", line);
}
lines
}
}
pub fn visible_regex_match_iter<'a, EventProxy>(
term: &'a Term<EventProxy>,
regex: &'a mut RegexSearch,
) -> impl Iterator<Item = Match> + 'a {
let viewport_start = Line(-(term.grid().display_offset() as i32));
let viewport_end = viewport_start + term.bottommost_line();
let mut start = term.line_search_left(Point::new(viewport_start, Column(0)));
let mut end = term.line_search_right(Point::new(viewport_end, Column(0)));
start.line = start.line.max(viewport_start - MAX_SEARCH_LINES);
end.line = end.line.min(viewport_end + MAX_SEARCH_LINES);
RegexIter::new(start, end, Direction::Right, term, regex)
.skip_while(move |rm| rm.end().line < viewport_start)
.take_while(move |rm| rm.start().line <= viewport_end)
}
/// todo:should be improved
pub const MAX_SEARCH_LINES: usize = 100;
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/terminal/mod.rs | lapce-app/src/terminal/mod.rs | pub mod data;
pub mod event;
pub mod panel;
pub mod raw;
pub mod tab;
pub mod view;
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/terminal/data.rs | lapce-app/src/terminal/data.rs | use std::{collections::HashMap, path::PathBuf, rc::Rc, sync::Arc};
use alacritty_terminal::{
Term,
grid::{Dimensions, Scroll},
selection::{Selection, SelectionType},
term::{TermMode, test::TermSize},
vi_mode::ViMotion,
};
use anyhow::anyhow;
use floem::{
keyboard::{Key, KeyEvent, Modifiers, NamedKey},
reactive::{RwSignal, Scope, SignalGet, SignalUpdate, SignalWith},
views::editor::text::SystemClipboard,
};
use lapce_core::{
command::{EditCommand, FocusCommand, ScrollCommand},
mode::{Mode, VisualMode},
movement::{LinePosition, Movement},
register::Clipboard,
};
use lapce_rpc::{
dap_types::RunDebugConfig,
terminal::{TermId, TerminalProfile},
};
use parking_lot::RwLock;
use url::Url;
use super::{
event::TermEvent,
raw::{EventProxy, RawTerminal},
};
use crate::{
command::{CommandExecuted, CommandKind, InternalCommand},
debug::{RunDebugMode, RunDebugProcess},
keypress::{KeyPressFocus, condition::Condition},
window_tab::CommonData,
workspace::LapceWorkspace,
};
#[derive(Clone, Debug)]
pub struct TerminalData {
pub scope: Scope,
pub term_id: TermId,
pub workspace: Arc<LapceWorkspace>,
pub title: RwSignal<String>,
pub launch_error: RwSignal<Option<String>>,
pub mode: RwSignal<Mode>,
pub visual_mode: RwSignal<VisualMode>,
pub raw: RwSignal<Arc<RwLock<RawTerminal>>>,
pub run_debug: RwSignal<Option<RunDebugProcess>>,
pub common: Rc<CommonData>,
}
impl KeyPressFocus for TerminalData {
fn get_mode(&self) -> Mode {
self.mode.get_untracked()
}
fn check_condition(&self, condition: Condition) -> bool {
matches!(condition, Condition::TerminalFocus | Condition::PanelFocus)
}
fn run_command(
&self,
command: &crate::command::LapceCommand,
count: Option<usize>,
_mods: Modifiers,
) -> crate::command::CommandExecuted {
self.common.view_id.get_untracked().request_paint();
let config = self.common.config.get_untracked();
match &command.kind {
CommandKind::Move(cmd) => {
let movement = cmd.to_movement(count);
let raw = self.raw.get_untracked();
let mut raw = raw.write();
let term = &mut raw.term;
match movement {
Movement::Left => {
term.vi_motion(ViMotion::Left);
}
Movement::Right => {
term.vi_motion(ViMotion::Right);
}
Movement::Up => {
term.vi_motion(ViMotion::Up);
}
Movement::Down => {
term.vi_motion(ViMotion::Down);
}
Movement::FirstNonBlank => {
term.vi_motion(ViMotion::FirstOccupied);
}
Movement::StartOfLine => {
term.vi_motion(ViMotion::First);
}
Movement::EndOfLine => {
term.vi_motion(ViMotion::Last);
}
Movement::WordForward => {
term.vi_motion(ViMotion::SemanticRight);
}
Movement::WordEndForward => {
term.vi_motion(ViMotion::SemanticRightEnd);
}
Movement::WordBackward => {
term.vi_motion(ViMotion::SemanticLeft);
}
Movement::Line(line) => {
match line {
LinePosition::First => {
term.scroll_display(Scroll::Top);
term.vi_mode_cursor.point.line = term.topmost_line();
}
LinePosition::Last => {
term.scroll_display(Scroll::Bottom);
term.vi_mode_cursor.point.line =
term.bottommost_line();
}
LinePosition::Line(_) => {}
};
}
_ => (),
};
}
CommandKind::Edit(cmd) => match cmd {
EditCommand::NormalMode => {
if !config.core.modal {
return CommandExecuted::Yes;
}
self.mode.set(Mode::Normal);
let raw = self.raw.get_untracked();
let mut raw = raw.write();
let term = &mut raw.term;
if !term.mode().contains(TermMode::VI) {
term.toggle_vi_mode();
}
term.selection = None;
}
EditCommand::ToggleVisualMode => {
self.toggle_visual(VisualMode::Normal);
}
EditCommand::ToggleLinewiseVisualMode => {
self.toggle_visual(VisualMode::Linewise);
}
EditCommand::ToggleBlockwiseVisualMode => {
self.toggle_visual(VisualMode::Blockwise);
}
EditCommand::InsertMode => {
self.mode.set(Mode::Terminal);
let raw = self.raw.get_untracked();
let mut raw = raw.write();
let term = &mut raw.term;
if term.mode().contains(TermMode::VI) {
term.toggle_vi_mode();
}
let scroll = alacritty_terminal::grid::Scroll::Bottom;
term.scroll_display(scroll);
term.selection = None;
}
EditCommand::ClipboardCopy => {
let mut clipboard = SystemClipboard::new();
if matches!(self.mode.get_untracked(), Mode::Visual(_)) {
self.mode.set(Mode::Normal);
}
let raw = self.raw.get_untracked();
let mut raw = raw.write();
let term = &mut raw.term;
if let Some(content) = term.selection_to_string() {
clipboard.put_string(content);
}
if self.mode.get_untracked() != Mode::Terminal {
term.selection = None;
}
}
EditCommand::ClipboardPaste => {
let mut clipboard = SystemClipboard::new();
let mut check_bracketed_paste: bool = false;
if self.mode.get_untracked() == Mode::Terminal {
let raw = self.raw.get_untracked();
let mut raw = raw.write();
let term = &mut raw.term;
term.selection = None;
if term.mode().contains(TermMode::BRACKETED_PASTE) {
check_bracketed_paste = true;
}
}
if let Some(s) = clipboard.get_string() {
if check_bracketed_paste {
self.receive_char("\x1b[200~");
self.receive_char(&s.replace('\x1b', ""));
self.receive_char("\x1b[201~");
} else {
self.receive_char(&s);
}
}
}
_ => return CommandExecuted::No,
},
CommandKind::Scroll(cmd) => match cmd {
ScrollCommand::PageUp => {
let raw = self.raw.get_untracked();
let mut raw = raw.write();
let term = &mut raw.term;
let scroll_lines = term.screen_lines() as i32 / 2;
term.vi_mode_cursor =
term.vi_mode_cursor.scroll(term, scroll_lines);
term.scroll_display(alacritty_terminal::grid::Scroll::Delta(
scroll_lines,
));
}
ScrollCommand::PageDown => {
let raw = self.raw.get_untracked();
let mut raw = raw.write();
let term = &mut raw.term;
let scroll_lines = -(term.screen_lines() as i32 / 2);
term.vi_mode_cursor =
term.vi_mode_cursor.scroll(term, scroll_lines);
term.scroll_display(alacritty_terminal::grid::Scroll::Delta(
scroll_lines,
));
}
_ => return CommandExecuted::No,
},
CommandKind::Focus(cmd) => match cmd {
FocusCommand::SplitVertical => {
self.common.internal_command.send(
InternalCommand::SplitTerminal {
term_id: self.term_id,
},
);
}
FocusCommand::SplitHorizontal => {
self.common.internal_command.send(
InternalCommand::SplitTerminal {
term_id: self.term_id,
},
);
}
FocusCommand::SplitLeft => {
self.common.internal_command.send(
InternalCommand::SplitTerminalPrevious {
term_id: self.term_id,
},
);
}
FocusCommand::SplitRight => {
self.common.internal_command.send(
InternalCommand::SplitTerminalNext {
term_id: self.term_id,
},
);
}
FocusCommand::SplitExchange => {
self.common.internal_command.send(
InternalCommand::SplitTerminalExchange {
term_id: self.term_id,
},
);
}
FocusCommand::SearchForward => {
// if let Some(search_string) = self.find.search_string.as_ref() {
// let mut raw = self.terminal.raw.lock();
// let term = &mut raw.term;
// self.terminal.search_next(
// term,
// search_string,
// Direction::Right,
// );
// }
}
FocusCommand::SearchBackward => {
// if let Some(search_string) = self.find.search_string.as_ref() {
// let mut raw = self.terminal.raw.lock();
// let term = &mut raw.term;
// self.terminal.search_next(
// term,
// search_string,
// Direction::Left,
// );
// }
}
_ => return CommandExecuted::No,
},
_ => return CommandExecuted::No,
};
CommandExecuted::Yes
}
fn receive_char(&self, c: &str) {
if self.mode.get_untracked() == Mode::Terminal {
self.common
.proxy
.terminal_write(self.term_id, c.to_string());
self.raw
.get_untracked()
.write()
.term
.scroll_display(Scroll::Bottom);
}
}
}
impl TerminalData {
pub fn new(
cx: Scope,
workspace: Arc<LapceWorkspace>,
profile: Option<TerminalProfile>,
common: Rc<CommonData>,
) -> Self {
Self::new_run_debug(cx, workspace, None, profile, common)
}
pub fn new_run_debug(
cx: Scope,
workspace: Arc<LapceWorkspace>,
run_debug: Option<RunDebugProcess>,
profile: Option<TerminalProfile>,
common: Rc<CommonData>,
) -> Self {
let cx = cx.create_child();
let term_id = TermId::next();
let title = if let Some(profile) = &profile {
cx.create_rw_signal(profile.name.to_owned())
} else {
cx.create_rw_signal(String::from("Default"))
};
let launch_error = cx.create_rw_signal(None);
let raw = Self::new_raw_terminal(
&workspace,
term_id,
run_debug.as_ref(),
profile,
common.clone(),
launch_error,
);
let run_debug = cx.create_rw_signal(run_debug);
let mode = cx.create_rw_signal(Mode::Terminal);
let visual_mode = cx.create_rw_signal(VisualMode::Normal);
let raw = cx.create_rw_signal(raw);
Self {
scope: cx,
term_id,
workspace,
raw,
title,
run_debug,
mode,
visual_mode,
common,
launch_error,
}
}
fn new_raw_terminal(
workspace: &LapceWorkspace,
term_id: TermId,
run_debug: Option<&RunDebugProcess>,
profile: Option<TerminalProfile>,
common: Rc<CommonData>,
launch_error: RwSignal<Option<String>>,
) -> Arc<RwLock<RawTerminal>> {
let raw = Arc::new(RwLock::new(RawTerminal::new(
term_id,
common.proxy.clone(),
common.term_notification_tx.clone(),
)));
let mut profile = profile.unwrap_or_default();
if profile.workdir.is_none() {
profile.workdir = url::Url::from_file_path(
workspace.path.as_ref().cloned().unwrap_or_default(),
)
.ok();
}
let exp_run_debug = run_debug
.as_ref()
.map(|run_debug| {
ExpandedRunDebug::expand(
workspace,
&run_debug.config,
run_debug.is_prelaunch,
)
})
.transpose();
let exp_run_debug = exp_run_debug.unwrap_or_else(|e| {
let r_name = run_debug
.as_ref()
.map(|r| r.config.name.as_str())
.unwrap_or("Unknown");
launch_error.set(Some(format!(
"Failed to expand variables in run debug definition {r_name}: {e}"
)));
None
});
if let Some(run_debug) = exp_run_debug {
if let Some(work_dir) = run_debug.work_dir {
profile.workdir = Some(work_dir);
}
profile.environment = run_debug.env;
profile.command = Some(run_debug.program);
profile.arguments = run_debug.args;
}
{
let raw = raw.clone();
if let Err(err) =
common.term_tx.send((term_id, TermEvent::NewTerminal(raw)))
{
tracing::error!("{:?}", err);
}
common.proxy.new_terminal(term_id, profile);
}
raw
}
pub fn send_keypress(&self, key: &KeyEvent) -> bool {
if let Some(command) = Self::resolve_key_event(key) {
self.receive_char(command);
true
} else if key.modifiers == Modifiers::ALT
&& matches!(&key.key.logical_key, Key::Character(_))
{
if let Key::Character(c) = &key.key.logical_key {
// In terminal emulators, when the Alt key is combined with another character
// (such as Alt+a), a leading ESC (Escape, ASCII code 0x1B) character is usually
// sent followed by a sequence of that character. For example,
// Alt+a sends \x1Ba.
self.receive_char("\x1b");
self.receive_char(c.as_str());
}
true
} else {
false
}
}
pub fn resolve_key_event(key: &KeyEvent) -> Option<&str> {
let key = key.clone();
// Generates a `Modifiers` value to check against.
macro_rules! modifiers {
(ctrl) => {
Modifiers::CONTROL
};
(alt) => {
Modifiers::ALT
};
(shift) => {
Modifiers::SHIFT
};
($mod:ident $(| $($mods:ident)|+)?) => {
modifiers!($mod) $(| modifiers!($($mods)|+) )?
};
}
// Generates modifier values for ANSI sequences.
macro_rules! modval {
(shift) => {
// 1
"2"
};
(alt) => {
// 2
"3"
};
(alt | shift) => {
// 1 + 2
"4"
};
(ctrl) => {
// 4
"5"
};
(ctrl | shift) => {
// 1 + 4
"6"
};
(alt | ctrl) => {
// 2 + 4
"7"
};
(alt | ctrl | shift) => {
// 1 + 2 + 4
"8"
};
}
// Generates ANSI sequences to move the cursor by one position.
macro_rules! term_sequence {
// Generate every modifier combination (except meta)
([all], $evt:ident, $no_mod:literal, $pre:literal, $post:literal) => {
{
term_sequence!([], $evt, $no_mod);
term_sequence!([shift, alt, ctrl], $evt, $pre, $post);
term_sequence!([alt | shift, ctrl | shift, alt | ctrl], $evt, $pre, $post);
term_sequence!([alt | ctrl | shift], $evt, $pre, $post);
return None;
}
};
// No modifiers
([], $evt:ident, $no_mod:literal) => {
if $evt.modifiers.is_empty() {
return Some($no_mod);
}
};
// A single modifier combination
([$($mod:ident)|+], $evt:ident, $pre:literal, $post:literal) => {
if $evt.modifiers == modifiers!($($mod)|+) {
return Some(concat!($pre, modval!($($mod)|+), $post));
}
};
// Break down multiple modifiers into a series of single combination branches
([$($($mod:ident)|+),+], $evt:ident, $pre:literal, $post:literal) => {
$(
term_sequence!([$($mod)|+], $evt, $pre, $post);
)+
};
}
match key.key.logical_key {
Key::Character(ref c) => {
if key.modifiers == Modifiers::CONTROL {
// Convert the character into its index (into a control character).
// In essence, this turns `ctrl+h` into `^h`
let str = match c.as_str() {
"@" => "\x00",
"a" => "\x01",
"b" => "\x02",
"c" => "\x03",
"d" => "\x04",
"e" => "\x05",
"f" => "\x06",
"g" => "\x07",
"h" => "\x08",
"i" => "\x09",
"j" => "\x0a",
"k" => "\x0b",
"l" => "\x0c",
"m" => "\x0d",
"n" => "\x0e",
"o" => "\x0f",
"p" => "\x10",
"q" => "\x11",
"r" => "\x12",
"s" => "\x13",
"t" => "\x14",
"u" => "\x15",
"v" => "\x16",
"w" => "\x17",
"x" => "\x18",
"y" => "\x19",
"z" => "\x1a",
"[" => "\x1b",
"\\" => "\x1c",
"]" => "\x1d",
"^" => "\x1e",
"_" => "\x1f",
_ => return None,
};
Some(str)
} else {
None
}
}
Key::Named(NamedKey::Backspace) => {
Some(if key.modifiers.control() {
"\x08" // backspace
} else if key.modifiers.alt() {
"\x1b\x7f"
} else {
"\x7f"
})
}
Key::Named(NamedKey::Tab) => Some("\x09"),
Key::Named(NamedKey::Enter) => Some("\r"),
Key::Named(NamedKey::Escape) => Some("\x1b"),
// The following either expands to `\x1b[X` or `\x1b[1;NX` where N is a modifier value
Key::Named(NamedKey::ArrowUp) => {
term_sequence!([all], key, "\x1b[A", "\x1b[1;", "A")
}
Key::Named(NamedKey::ArrowDown) => {
term_sequence!([all], key, "\x1b[B", "\x1b[1;", "B")
}
Key::Named(NamedKey::ArrowRight) => {
term_sequence!([all], key, "\x1b[C", "\x1b[1;", "C")
}
Key::Named(NamedKey::ArrowLeft) => {
term_sequence!([all], key, "\x1b[D", "\x1b[1;", "D")
}
Key::Named(NamedKey::Home) => {
term_sequence!([all], key, "\x1bOH", "\x1b[1;", "H")
}
Key::Named(NamedKey::End) => {
term_sequence!([all], key, "\x1bOF", "\x1b[1;", "F")
}
Key::Named(NamedKey::Insert) => {
term_sequence!([all], key, "\x1b[2~", "\x1b[2;", "~")
}
Key::Named(NamedKey::Delete) => {
term_sequence!([all], key, "\x1b[3~", "\x1b[3;", "~")
}
Key::Named(NamedKey::PageUp) => {
term_sequence!([all], key, "\x1b[5~", "\x1b[5;", "~")
}
Key::Named(NamedKey::PageDown) => {
term_sequence!([all], key, "\x1b[6~", "\x1b[6;", "~")
}
_ => None,
}
}
pub fn wheel_scroll(&self, delta: f64) {
let config = self.common.config.get_untracked();
let step = config.terminal_line_height() as f64;
let raw = self.raw.get_untracked();
let mut raw = raw.write();
raw.scroll_delta -= delta;
let delta = (raw.scroll_delta / step) as i32;
raw.scroll_delta -= delta as f64 * step;
if delta != 0 {
let scroll = alacritty_terminal::grid::Scroll::Delta(delta);
raw.term.scroll_display(scroll);
}
}
fn toggle_visual(&self, visual_mode: VisualMode) {
let config = self.common.config.get_untracked();
if !config.core.modal {
return;
}
match self.mode.get_untracked() {
Mode::Normal => {
self.mode.set(Mode::Visual(visual_mode));
self.visual_mode.set(visual_mode);
}
Mode::Visual(_) => {
if self.visual_mode.get_untracked() == visual_mode {
self.mode.set(Mode::Normal);
} else {
self.visual_mode.set(visual_mode);
}
}
_ => (),
}
let raw = self.raw.get_untracked();
let mut raw = raw.write();
let term = &mut raw.term;
if !term.mode().contains(TermMode::VI) {
term.toggle_vi_mode();
}
let ty = match visual_mode {
VisualMode::Normal => SelectionType::Simple,
VisualMode::Linewise => SelectionType::Lines,
VisualMode::Blockwise => SelectionType::Block,
};
let point = term.renderable_content().cursor.point;
self.toggle_selection(
term,
ty,
point,
alacritty_terminal::index::Side::Left,
);
if let Some(selection) = term.selection.as_mut() {
selection.include_all();
}
}
pub fn toggle_selection(
&self,
term: &mut Term<EventProxy>,
ty: SelectionType,
point: alacritty_terminal::index::Point,
side: alacritty_terminal::index::Side,
) {
match &mut term.selection {
Some(selection) if selection.ty == ty && !selection.is_empty() => {
term.selection = None;
}
Some(selection) if !selection.is_empty() => {
selection.ty = ty;
}
_ => self.start_selection(term, ty, point, side),
}
}
fn start_selection(
&self,
term: &mut Term<EventProxy>,
ty: SelectionType,
point: alacritty_terminal::index::Point,
side: alacritty_terminal::index::Side,
) {
term.selection = Some(Selection::new(ty, point, side));
}
pub fn new_process(&self, run_debug: Option<RunDebugProcess>) {
let (width, height) = {
let raw = self.raw.get_untracked();
let raw = raw.read();
let width = raw.term.columns();
let height = raw.term.screen_lines();
(width, height)
};
let raw = Self::new_raw_terminal(
&self.workspace,
self.term_id,
run_debug.as_ref(),
None,
self.common.clone(),
self.launch_error,
);
self.raw.set(raw);
self.run_debug.set(run_debug);
let term_size = TermSize::new(width, height);
self.raw.get_untracked().write().term.resize(term_size);
self.common
.proxy
.terminal_resize(self.term_id, width, height);
}
pub fn stop(&self) {
if let Some(dap_id) = self.run_debug.with_untracked(|x| {
if let Some(process) = x {
if !process.is_prelaunch && process.mode == RunDebugMode::Debug {
return Some(process.config.dap_id);
}
}
None
}) {
self.common.proxy.dap_stop(dap_id);
}
self.common.proxy.terminal_close(self.term_id);
}
}
/// [`RunDebugConfig`] with expanded out program/arguments/etc. Used for creating the terminal.
#[derive(Debug, Clone)]
pub struct ExpandedRunDebug {
pub work_dir: Option<Url>,
pub env: Option<HashMap<String, String>>,
pub program: String,
pub args: Option<Vec<String>>,
}
impl ExpandedRunDebug {
pub fn expand(
workspace: &LapceWorkspace,
run_debug: &RunDebugConfig,
is_prelaunch: bool,
) -> anyhow::Result<Self> {
// Get the current working directory variable, which can container ${workspace}
let work_dir = Self::expand_work_dir(workspace, run_debug);
let prelaunch = is_prelaunch
.then_some(run_debug.prelaunch.as_ref())
.flatten();
let env = run_debug.env.clone();
// TODO: replace some variables in the args
let (program, mut args) =
if let Some(debug_command) = run_debug.debug_command.as_ref() {
let mut args = debug_command.to_owned();
let command = args.first().cloned().unwrap_or_default();
if !args.is_empty() {
args.remove(0);
}
let args = if !args.is_empty() { Some(args) } else { None };
(command, args)
} else if let Some(prelaunch) = prelaunch {
(prelaunch.program.clone(), prelaunch.args.clone())
} else {
(run_debug.program.clone(), run_debug.args.clone())
};
let mut program = if program == "${lapce}" {
std::env::current_exe()
.map_err(|e| {
anyhow!(
"Failed to get current exe for ${{lapce}} run and debug: {e}"
)
})?
.to_str()
.ok_or_else(|| anyhow!("Failed to convert ${{lapce}} path to str"))?
.to_string()
} else {
program
};
if program.contains("${workspace}") {
if let Some(workspace) = workspace.path.as_ref().and_then(|x| x.to_str())
{
program = program.replace("${workspace}", workspace);
}
}
if let Some(args) = &mut args {
for arg in args {
// Replace all mentions of ${workspace} with the current workspace path
if arg.contains("${workspace}") {
if let Some(workspace) =
workspace.path.as_ref().and_then(|x| x.to_str())
{
*arg = arg.replace("${workspace}", workspace);
}
}
}
}
Ok(ExpandedRunDebug {
work_dir,
env,
program,
args,
})
}
fn expand_work_dir(
workspace: &LapceWorkspace,
run_debug: &RunDebugConfig,
) -> Option<Url> {
let path = run_debug.cwd.as_ref()?;
if path.contains("${workspace}") {
if let Some(workspace) = workspace.path.as_ref().and_then(|x| x.to_str())
{
let path = path.replace("${workspace}", workspace);
if let Ok(as_url) = Url::from_file_path(PathBuf::from(path)) {
return Some(as_url);
}
}
}
Url::from_file_path(PathBuf::from(path)).ok()
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/terminal/panel.rs | lapce-app/src/terminal/panel.rs | use std::{collections::HashMap, path::PathBuf, rc::Rc, sync::Arc};
use floem::{
ext_event::create_ext_action,
reactive::{Memo, RwSignal, Scope, SignalGet, SignalUpdate, SignalWith},
};
use lapce_core::mode::Mode;
use lapce_rpc::{
dap_types::{
self, DapId, RunDebugConfig, StackFrame, Stopped, ThreadId, Variable,
},
proxy::ProxyResponse,
terminal::{TermId, TerminalProfile},
};
use super::{data::TerminalData, tab::TerminalTabData};
use crate::{
debug::{
DapData, DapVariable, RunDebugConfigs, RunDebugData, RunDebugMode,
RunDebugProcess, ScopeOrVar,
},
id::TerminalTabId,
keypress::{EventRef, KeyPressData, KeyPressFocus, KeyPressHandle},
main_split::MainSplitData,
panel::kind::PanelKind,
window_tab::{CommonData, Focus},
workspace::LapceWorkspace,
};
pub struct TerminalTabInfo {
pub active: usize,
pub tabs: im::Vector<(RwSignal<usize>, TerminalTabData)>,
}
#[derive(Clone)]
pub struct TerminalPanelData {
pub cx: Scope,
pub workspace: Arc<LapceWorkspace>,
pub tab_info: RwSignal<TerminalTabInfo>,
pub debug: RunDebugData,
pub breakline: Memo<Option<(usize, PathBuf)>>,
pub common: Rc<CommonData>,
pub main_split: MainSplitData,
}
impl TerminalPanelData {
pub fn new(
workspace: Arc<LapceWorkspace>,
profile: Option<TerminalProfile>,
common: Rc<CommonData>,
main_split: MainSplitData,
) -> Self {
let terminal_tab =
TerminalTabData::new(workspace.clone(), profile, common.clone());
let cx = common.scope;
let tabs =
im::vector![(terminal_tab.scope.create_rw_signal(0), terminal_tab)];
let tab_info = TerminalTabInfo { active: 0, tabs };
let tab_info = cx.create_rw_signal(tab_info);
let debug = RunDebugData::new(cx, common.breakpoints);
let breakline = {
let active_term = debug.active_term;
let daps = debug.daps;
cx.create_memo(move |_| {
let active_term = active_term.get();
let active_term = match active_term {
Some(active_term) => active_term,
None => return None,
};
let term = tab_info.with_untracked(|info| {
for (_, tab) in &info.tabs {
let terminal = tab.terminals.with_untracked(|terminals| {
terminals
.iter()
.find(|(_, t)| t.term_id == active_term)
.cloned()
});
if let Some(terminal) = terminal {
return Some(terminal.1);
}
}
None
});
let term = match term {
Some(term) => term,
None => return None,
};
let stopped = term
.run_debug
.with(|run_debug| run_debug.as_ref().map(|r| r.stopped))
.unwrap_or(true);
if stopped {
return None;
}
let daps = daps.get();
let dap = daps.values().find(|d| d.term_id == active_term);
dap.and_then(|dap| dap.breakline.get())
})
};
Self {
cx,
workspace,
tab_info,
debug,
breakline,
common,
main_split,
}
}
pub fn active_tab(&self, tracked: bool) -> Option<TerminalTabData> {
if tracked {
self.tab_info.with(|info| {
info.tabs
.get(info.active)
.or_else(|| info.tabs.last())
.cloned()
.map(|(_, tab)| tab)
})
} else {
self.tab_info.with_untracked(|info| {
info.tabs
.get(info.active)
.or_else(|| info.tabs.last())
.cloned()
.map(|(_, tab)| tab)
})
}
}
pub fn key_down<'a>(
&self,
event: impl Into<EventRef<'a>> + Copy,
keypress: &KeyPressData,
) -> Option<KeyPressHandle> {
if self.tab_info.with_untracked(|info| info.tabs.is_empty()) {
self.new_tab(None);
}
let tab = self.active_tab(false);
let terminal = tab.and_then(|tab| tab.active_terminal(false));
if let Some(terminal) = terminal {
let handle = keypress.key_down(event, &terminal);
let mode = terminal.get_mode();
if !handle.handled && mode == Mode::Terminal {
if let EventRef::Keyboard(key_event) = event.into() {
if terminal.send_keypress(key_event) {
return Some(KeyPressHandle {
handled: true,
keymatch: handle.keymatch,
keypress: handle.keypress,
});
}
}
}
Some(handle)
} else {
None
}
}
pub fn new_tab(&self, profile: Option<TerminalProfile>) {
self.new_tab_run_debug(None, profile);
}
/// Create a new terminal tab with the given run debug process.
/// Errors if expanding out the run debug process failed.
pub fn new_tab_run_debug(
&self,
run_debug: Option<RunDebugProcess>,
profile: Option<TerminalProfile>,
) -> TerminalTabData {
let terminal_tab = TerminalTabData::new_run_debug(
self.workspace.clone(),
run_debug,
profile,
self.common.clone(),
);
self.tab_info.update(|info| {
info.tabs.insert(
if info.tabs.is_empty() {
0
} else {
(info.active + 1).min(info.tabs.len())
},
(terminal_tab.scope.create_rw_signal(0), terminal_tab.clone()),
);
let new_active = (info.active + 1).min(info.tabs.len() - 1);
info.active = new_active;
});
terminal_tab
}
pub fn next_tab(&self) {
self.tab_info.update(|info| {
if info.active >= info.tabs.len().saturating_sub(1) {
info.active = 0;
} else {
info.active += 1;
}
});
self.update_debug_active_term();
}
pub fn previous_tab(&self) {
self.tab_info.update(|info| {
if info.active == 0 {
info.active = info.tabs.len().saturating_sub(1);
} else {
info.active -= 1;
}
});
self.update_debug_active_term();
}
pub fn close_tab(&self, terminal_tab_id: Option<TerminalTabId>) {
if let Some(close_tab) = self
.tab_info
.try_update(|info| {
let mut close_tab = None;
if let Some(terminal_tab_id) = terminal_tab_id {
if let Some(index) =
info.tabs.iter().enumerate().find_map(|(index, (_, t))| {
if t.terminal_tab_id == terminal_tab_id {
Some(index)
} else {
None
}
})
{
close_tab = Some(
info.tabs.remove(index).1.terminals.get_untracked(),
);
}
} else {
let active = info.active.min(info.tabs.len().saturating_sub(1));
if !info.tabs.is_empty() {
info.tabs.remove(active);
}
}
let new_active = info.active.min(info.tabs.len().saturating_sub(1));
info.active = new_active;
close_tab
})
.flatten()
{
for (_, data) in close_tab {
data.stop();
}
}
self.update_debug_active_term();
}
pub fn set_title(&self, term_id: &TermId, title: &str) {
if let Some(t) = self.get_terminal(term_id) {
t.title.set(title.to_string());
}
}
pub fn get_terminal(&self, term_id: &TermId) -> Option<TerminalData> {
self.tab_info.with_untracked(|info| {
for (_, tab) in &info.tabs {
let terminal = tab.terminals.with_untracked(|terminals| {
terminals
.iter()
.find(|(_, t)| &t.term_id == term_id)
.cloned()
});
if let Some(terminal) = terminal {
return Some(terminal.1);
}
}
None
})
}
fn get_terminal_in_tab(
&self,
term_id: &TermId,
) -> Option<(usize, TerminalTabData, usize, TerminalData)> {
self.tab_info.with_untracked(|info| {
for (tab_index, (_, tab)) in info.tabs.iter().enumerate() {
let result = tab.terminals.with_untracked(|terminals| {
terminals
.iter()
.enumerate()
.find(|(_, (_, t))| &t.term_id == term_id)
.map(|(i, (_, terminal))| (i, terminal.clone()))
});
if let Some((index, terminal)) = result {
return Some((tab_index, tab.clone(), index, terminal));
}
}
None
})
}
pub fn split(&self, term_id: TermId) {
if let Some((_, tab, index, _)) = self.get_terminal_in_tab(&term_id) {
let terminal_data = TerminalData::new(
tab.scope,
self.workspace.clone(),
None,
self.common.clone(),
);
let i = terminal_data.scope.create_rw_signal(0);
tab.terminals.update(|terminals| {
terminals.insert(index + 1, (i, terminal_data));
});
}
}
pub fn split_next(&self, term_id: TermId) {
if let Some((_, tab, index, _)) = self.get_terminal_in_tab(&term_id) {
let max = tab.terminals.with_untracked(|t| t.len() - 1);
let new_index = (index + 1).min(max);
if new_index != index {
tab.active.set(new_index);
self.update_debug_active_term();
}
}
}
pub fn split_previous(&self, term_id: TermId) {
if let Some((_, tab, index, _)) = self.get_terminal_in_tab(&term_id) {
let new_index = index.saturating_sub(1);
if new_index != index {
tab.active.set(new_index);
self.update_debug_active_term();
}
}
}
pub fn split_exchange(&self, term_id: TermId) {
if let Some((_, tab, index, _)) = self.get_terminal_in_tab(&term_id) {
let max = tab.terminals.with_untracked(|t| t.len() - 1);
if index < max {
tab.terminals.update(|terminals| {
terminals.swap(index, index + 1);
});
self.update_debug_active_term();
}
}
}
pub fn close_terminal(&self, term_id: &TermId) {
if let Some((_, tab, index, _)) = self.get_terminal_in_tab(term_id) {
let active = tab.active.get_untracked();
let len = tab
.terminals
.try_update(|terminals| {
terminals.remove(index);
terminals.len()
})
.unwrap();
if len == 0 {
self.close_tab(Some(tab.terminal_tab_id));
} else {
let new_active = active.min(len.saturating_sub(1));
if new_active != active {
tab.active.set(new_active);
self.update_debug_active_term();
}
}
}
}
pub fn launch_failed(&self, term_id: &TermId, error: &str) {
if let Some(terminal) = self.get_terminal(term_id) {
terminal.launch_error.set(Some(error.to_string()));
}
}
pub fn terminal_stopped(&self, term_id: &TermId, exit_code: Option<i32>) {
if let Some(terminal) = self.get_terminal(term_id) {
if terminal.run_debug.with_untracked(|r| r.is_some()) {
let was_prelaunch = terminal
.run_debug
.try_update(|run_debug| {
if let Some(run_debug) = run_debug.as_mut() {
if run_debug.is_prelaunch
&& run_debug.config.prelaunch.is_some()
{
run_debug.is_prelaunch = false;
if run_debug.mode == RunDebugMode::Debug {
// set it to be stopped so that the dap can pick the same terminal session
run_debug.stopped = true;
}
Some(true)
} else {
run_debug.stopped = true;
Some(false)
}
} else {
None
}
})
.unwrap();
let exit_code = exit_code.unwrap_or(0);
if was_prelaunch == Some(true) && exit_code == 0 {
let run_debug = terminal.run_debug.get_untracked();
if let Some(run_debug) = run_debug {
if run_debug.mode == RunDebugMode::Debug {
self.common.proxy.dap_start(
run_debug.config,
self.debug.source_breakpoints(),
)
} else {
terminal.new_process(Some(run_debug));
}
}
}
} else {
self.close_terminal(term_id);
}
}
}
pub fn get_stopped_run_debug_terminal(
&self,
mode: &RunDebugMode,
config: &RunDebugConfig,
) -> Option<TerminalData> {
self.tab_info.with_untracked(|info| {
for (_, tab) in &info.tabs {
let terminal = tab.terminals.with_untracked(|terminals| {
for (_, terminal) in terminals {
if let Some(run_debug) =
terminal.run_debug.get_untracked().as_ref()
{
if run_debug.stopped && &run_debug.mode == mode {
match run_debug.mode {
RunDebugMode::Run => {
if run_debug.config.name == config.name {
return Some(terminal.clone());
}
}
RunDebugMode::Debug => {
if run_debug.config.dap_id == config.dap_id {
return Some(terminal.clone());
}
}
}
}
}
}
None
});
if let Some(terminal) = terminal {
return Some(terminal);
}
}
None
})
}
/// Return whether it is in debug mode.
pub fn restart_run_debug(&self, term_id: TermId) -> Option<bool> {
let (_, terminal_tab, index, terminal) =
self.get_terminal_in_tab(&term_id)?;
let mut run_debug = terminal.run_debug.get_untracked()?;
if run_debug.config.config_source.from_palette() {
if let Some(new_config) =
self.get_run_config_by_name(&run_debug.config.name)
{
run_debug.config = new_config;
}
}
let mut is_debug = false;
let new_term_id = match run_debug.mode {
RunDebugMode::Run => {
self.common.proxy.terminal_close(term_id);
let mut run_debug = run_debug;
run_debug.stopped = false;
run_debug.is_prelaunch = true;
let new_terminal = TerminalData::new_run_debug(
terminal_tab.scope,
self.workspace.clone(),
Some(run_debug),
None,
self.common.clone(),
);
let new_term_id = new_terminal.term_id;
terminal_tab.terminals.update(|terminals| {
terminals[index] =
(new_terminal.scope.create_rw_signal(0), new_terminal);
});
self.debug.active_term.set(Some(new_term_id));
new_term_id
}
RunDebugMode::Debug => {
is_debug = true;
let dap_id =
terminal.run_debug.get_untracked().as_ref()?.config.dap_id;
let daps = self.debug.daps.get_untracked();
let dap = daps.get(&dap_id)?;
self.common
.proxy
.dap_restart(dap.dap_id, self.debug.source_breakpoints());
term_id
}
};
self.focus_terminal(new_term_id);
Some(is_debug)
}
fn get_run_config_by_name(&self, name: &str) -> Option<RunDebugConfig> {
if let Some(workspace) = self.common.workspace.path.as_deref() {
let run_toml = workspace.join(".lapce").join("run.toml");
let (doc, new_doc) = self.main_split.get_doc(run_toml.clone(), None);
if !new_doc {
let content = doc.buffer.with_untracked(|b| b.to_string());
match toml::from_str::<RunDebugConfigs>(&content) {
Ok(configs) => {
return configs.configs.into_iter().find(|x| x.name == name);
}
Err(err) => {
// todo show message window
tracing::error!("deser fail {:?}", err);
}
}
}
}
None
}
pub fn focus_terminal(&self, term_id: TermId) {
if let Some((tab_index, terminal_tab, index, _terminal)) =
self.get_terminal_in_tab(&term_id)
{
self.tab_info.update(|info| {
info.active = tab_index;
});
terminal_tab.active.set(index);
self.common.focus.set(Focus::Panel(PanelKind::Terminal));
self.update_debug_active_term();
}
}
pub fn update_debug_active_term(&self) {
let tab = self.active_tab(false);
let terminal = tab.and_then(|tab| tab.active_terminal(false));
if let Some(terminal) = terminal {
let term_id = terminal.term_id;
let is_run_debug =
terminal.run_debug.with_untracked(|run| run.is_some());
let current_active = self.debug.active_term.get_untracked();
if is_run_debug {
if current_active != Some(term_id) {
self.debug.active_term.set(Some(term_id));
}
} else if let Some(active) = current_active {
if self.get_terminal(&active).is_none() {
self.debug.active_term.set(None);
}
}
} else {
self.debug.active_term.set(None);
}
}
pub fn stop_run_debug(&self, term_id: TermId) -> Option<()> {
let terminal = self.get_terminal(&term_id)?;
let run_debug = terminal.run_debug.get_untracked()?;
match run_debug.mode {
RunDebugMode::Run => {
self.common.proxy.terminal_close(term_id);
}
RunDebugMode::Debug => {
let dap_id = run_debug.config.dap_id;
let daps = self.debug.daps.get_untracked();
let dap = daps.get(&dap_id)?;
self.common.proxy.dap_stop(dap.dap_id);
}
}
self.focus_terminal(term_id);
Some(())
}
pub fn run_debug_process(
&self,
tracked: bool,
) -> Vec<(TermId, RunDebugProcess)> {
let mut processes = Vec::new();
if tracked {
self.tab_info.with(|info| {
for (_, tab) in &info.tabs {
tab.terminals.with(|terminals| {
for (_, terminal) in terminals {
if let Some(run_debug) = terminal.run_debug.get() {
processes.push((terminal.term_id, run_debug));
}
}
})
}
});
} else {
self.tab_info.with_untracked(|info| {
for (_, tab) in &info.tabs {
tab.terminals.with_untracked(|terminals| {
for (_, terminal) in terminals {
if let Some(run_debug) = terminal.run_debug.get() {
processes.push((terminal.term_id, run_debug));
}
}
})
}
});
}
processes.sort_by_key(|(_, process)| process.created);
processes
}
pub fn set_process_id(&self, term_id: &TermId, process_id: Option<u32>) {
if let Some(terminal) = self.get_terminal(term_id) {
terminal.run_debug.with_untracked(|run_debug| {
if let Some(run_debug) = run_debug.as_ref() {
if run_debug.config.debug_command.is_some() {
let dap_id = run_debug.config.dap_id;
self.common
.proxy
.dap_process_id(dap_id, process_id, *term_id);
}
}
});
}
}
pub fn dap_continued(&self, dap_id: &DapId) {
let dap = self
.debug
.daps
.with_untracked(|daps| daps.get(dap_id).cloned());
if let Some(dap) = dap {
dap.thread_id.set(None);
dap.stopped.set(false);
}
}
pub fn dap_stopped(
&self,
dap_id: &DapId,
stopped: &Stopped,
stack_frames: &HashMap<ThreadId, Vec<StackFrame>>,
variables: &[(dap_types::Scope, Vec<Variable>)],
) {
let dap = self
.debug
.daps
.with_untracked(|daps| daps.get(dap_id).cloned());
if let Some(dap) = dap {
dap.stopped(self.cx, stopped, stack_frames, variables);
}
floem::action::focus_window();
}
pub fn dap_continue(&self, term_id: TermId) -> Option<()> {
let terminal = self.get_terminal(&term_id)?;
let dap_id = terminal
.run_debug
.with_untracked(|r| r.as_ref().map(|r| r.config.dap_id))?;
let thread_id = self.debug.daps.with_untracked(|daps| {
daps.get(&dap_id)
.and_then(|dap| dap.thread_id.get_untracked())
});
let thread_id = thread_id.unwrap_or_default();
self.common.proxy.dap_continue(dap_id, thread_id);
Some(())
}
pub fn dap_pause(&self, term_id: TermId) -> Option<()> {
let terminal = self.get_terminal(&term_id)?;
let dap_id = terminal
.run_debug
.with_untracked(|r| r.as_ref().map(|r| r.config.dap_id))?;
let thread_id = self.debug.daps.with_untracked(|daps| {
daps.get(&dap_id)
.and_then(|dap| dap.thread_id.get_untracked())
});
let thread_id = thread_id.unwrap_or_default();
self.common.proxy.dap_pause(dap_id, thread_id);
Some(())
}
pub fn dap_step_over(&self, term_id: TermId) -> Option<()> {
let terminal = self.get_terminal(&term_id)?;
let dap_id = terminal
.run_debug
.with_untracked(|r| r.as_ref().map(|r| r.config.dap_id))?;
let thread_id = self.debug.daps.with_untracked(|daps| {
daps.get(&dap_id)
.and_then(|dap| dap.thread_id.get_untracked())
});
let thread_id = thread_id.unwrap_or_default();
self.common.proxy.dap_step_over(dap_id, thread_id);
Some(())
}
pub fn dap_step_into(&self, term_id: TermId) -> Option<()> {
let terminal = self.get_terminal(&term_id)?;
let dap_id = terminal
.run_debug
.with_untracked(|r| r.as_ref().map(|r| r.config.dap_id))?;
let thread_id = self.debug.daps.with_untracked(|daps| {
daps.get(&dap_id)
.and_then(|dap| dap.thread_id.get_untracked())
});
let thread_id = thread_id.unwrap_or_default();
self.common.proxy.dap_step_into(dap_id, thread_id);
Some(())
}
pub fn dap_step_out(&self, term_id: TermId) -> Option<()> {
let terminal = self.get_terminal(&term_id)?;
let dap_id = terminal
.run_debug
.with_untracked(|r| r.as_ref().map(|r| r.config.dap_id))?;
let thread_id = self.debug.daps.with_untracked(|daps| {
daps.get(&dap_id)
.and_then(|dap| dap.thread_id.get_untracked())
});
let thread_id = thread_id.unwrap_or_default();
self.common.proxy.dap_step_out(dap_id, thread_id);
Some(())
}
pub fn get_active_dap(&self, tracked: bool) -> Option<DapData> {
let active_term = if tracked {
self.debug.active_term.get()?
} else {
self.debug.active_term.get_untracked()?
};
self.get_dap(active_term, tracked)
}
pub fn get_dap(&self, term_id: TermId, tracked: bool) -> Option<DapData> {
let terminal = self.get_terminal(&term_id)?;
let dap_id = if tracked {
terminal
.run_debug
.with(|r| r.as_ref().map(|r| r.config.dap_id))?
} else {
terminal
.run_debug
.with_untracked(|r| r.as_ref().map(|r| r.config.dap_id))?
};
if tracked {
self.debug.daps.with(|daps| daps.get(&dap_id).cloned())
} else {
self.debug
.daps
.with_untracked(|daps| daps.get(&dap_id).cloned())
}
}
pub fn dap_frame_scopes(&self, dap_id: DapId, frame_id: usize) {
if let Some(dap) = self.debug.daps.get_untracked().get(&dap_id) {
let variables = dap.variables;
let send = create_ext_action(self.common.scope, move |result| {
if let Ok(ProxyResponse::DapGetScopesResponse { scopes }) = result {
variables.update(|dap_var| {
dap_var.children = scopes
.iter()
.enumerate()
.map(|(i, (scope, vars))| DapVariable {
item: ScopeOrVar::Scope(scope.to_owned()),
parent: Vec::new(),
expanded: i == 0,
read: i == 0,
children: vars
.iter()
.map(|var| DapVariable {
item: ScopeOrVar::Var(var.to_owned()),
parent: vec![scope.variables_reference],
expanded: false,
read: false,
children: Vec::new(),
children_expanded_count: 0,
})
.collect(),
children_expanded_count: if i == 0 {
vars.len()
} else {
0
},
})
.collect();
dap_var.children_expanded_count = dap_var
.children
.iter()
.map(|v| v.children_expanded_count + 1)
.sum::<usize>();
});
}
});
self.common
.proxy
.dap_get_scopes(dap_id, frame_id, move |result| {
send(result);
});
}
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/terminal/tab.rs | lapce-app/src/terminal/tab.rs | use std::{rc::Rc, sync::Arc};
use floem::reactive::{RwSignal, Scope, SignalGet, SignalWith};
use lapce_rpc::terminal::TerminalProfile;
use super::data::TerminalData;
use crate::{
debug::RunDebugProcess, id::TerminalTabId, window_tab::CommonData,
workspace::LapceWorkspace,
};
#[derive(Clone)]
pub struct TerminalTabData {
pub scope: Scope,
pub terminal_tab_id: TerminalTabId,
pub active: RwSignal<usize>,
pub terminals: RwSignal<im::Vector<(RwSignal<usize>, TerminalData)>>,
}
impl TerminalTabData {
pub fn new(
workspace: Arc<LapceWorkspace>,
profile: Option<TerminalProfile>,
common: Rc<CommonData>,
) -> Self {
TerminalTabData::new_run_debug(workspace, None, profile, common)
}
/// Create the information for a terminal tab, which can contain multiple terminals.
pub fn new_run_debug(
workspace: Arc<LapceWorkspace>,
run_debug: Option<RunDebugProcess>,
profile: Option<TerminalProfile>,
common: Rc<CommonData>,
) -> Self {
let cx = common.scope.create_child();
let terminal_data =
TerminalData::new_run_debug(cx, workspace, run_debug, profile, common);
let terminals = im::vector![(cx.create_rw_signal(0), terminal_data)];
let terminals = cx.create_rw_signal(terminals);
let active = cx.create_rw_signal(0);
let terminal_tab_id = TerminalTabId::next();
Self {
scope: cx,
terminal_tab_id,
active,
terminals,
}
}
pub fn active_terminal(&self, tracked: bool) -> Option<TerminalData> {
let active = if tracked {
self.active.get()
} else {
self.active.get_untracked()
};
if tracked {
self.terminals
.with(|t| t.get(active).or_else(|| t.last()).cloned())
.map(|(_, t)| t)
} else {
self.terminals
.with_untracked(|t| t.get(active).or_else(|| t.last()).cloned())
.map(|(_, t)| t)
}
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/config/icon.rs | lapce-app/src/config/icon.rs | pub struct LapceIcons {}
impl LapceIcons {
pub const WINDOW_CLOSE: &'static str = "window.close";
pub const WINDOW_RESTORE: &'static str = "window.restore";
pub const WINDOW_MAXIMIZE: &'static str = "window.maximize";
pub const WINDOW_MINIMIZE: &'static str = "window.minimize";
pub const LOGO: &'static str = "logo";
pub const MENU: &'static str = "menu";
pub const LINK: &'static str = "link";
pub const ERROR: &'static str = "error";
pub const ADD: &'static str = "add";
pub const CLOSE: &'static str = "close";
pub const REMOTE: &'static str = "remote";
pub const PROBLEM: &'static str = "error";
pub const DEBUG: &'static str = "debug";
pub const DEBUG_ALT: &'static str = "debug_alt";
pub const DEBUG_BREAKPOINT: &'static str = "debug_breakpoint";
pub const DEBUG_SMALL: &'static str = "debug_small";
pub const DEBUG_RESTART: &'static str = "debug_restart";
pub const DEBUG_CONTINUE: &'static str = "debug_continue";
pub const DEBUG_STEP_OVER: &'static str = "debug_step_over";
pub const DEBUG_STEP_INTO: &'static str = "debug_step_into";
pub const DEBUG_STEP_OUT: &'static str = "debug_step_out";
pub const DEBUG_PAUSE: &'static str = "debug_pause";
pub const DEBUG_STOP: &'static str = "debug_stop";
pub const DEBUG_CONSOLE: &'static str = "debug_console";
pub const DEBUG_DISCONNECT: &'static str = "debug_disconnect";
pub const START: &'static str = "start";
pub const RUN_ERRORS: &'static str = "run_errors";
pub const UNSAVED: &'static str = "unsaved";
pub const WARNING: &'static str = "warning";
pub const TERMINAL: &'static str = "terminal";
pub const SETTINGS: &'static str = "settings";
pub const LIGHTBULB: &'static str = "lightbulb";
pub const EXTENSIONS: &'static str = "extensions";
pub const KEYBOARD: &'static str = "keyboard";
pub const BREADCRUMB_SEPARATOR: &'static str = "breadcrumb_separator";
pub const SYMBOL_COLOR: &'static str = "symbol_color";
pub const TYPE_HIERARCHY: &'static str = "type_hierarchy";
pub const FILE: &'static str = "file";
pub const FILE_EXPLORER: &'static str = "file_explorer";
pub const FILE_PICKER_UP: &'static str = "file_picker_up";
pub const IMAGE_LOADING: &'static str = "image_loading";
pub const IMAGE_ERROR: &'static str = "image_error";
pub const SCM: &'static str = "scm.icon";
pub const SCM_DIFF_MODIFIED: &'static str = "scm.diff.modified";
pub const SCM_DIFF_ADDED: &'static str = "scm.diff.added";
pub const SCM_DIFF_REMOVED: &'static str = "scm.diff.removed";
pub const SCM_DIFF_RENAMED: &'static str = "scm.diff.renamed";
pub const SCM_CHANGE_ADD: &'static str = "scm.change.add";
pub const SCM_CHANGE_REMOVE: &'static str = "scm.change.remove";
pub const FOLD: &'static str = "fold";
pub const FOLD_UP: &'static str = "fold.up";
pub const FOLD_DOWN: &'static str = "fold.down";
pub const PALETTE_MENU: &'static str = "palette.menu";
pub const DROPDOWN_ARROW: &'static str = "dropdown.arrow";
pub const PANEL_FOLD_UP: &'static str = "panel.fold-up";
pub const PANEL_FOLD_DOWN: &'static str = "panel.fold-down";
pub const LOCATION_BACKWARD: &'static str = "location.backward";
pub const LOCATION_FORWARD: &'static str = "location.forward";
pub const ITEM_OPENED: &'static str = "item.opened";
pub const ITEM_CLOSED: &'static str = "item.closed";
pub const DIRECTORY_CLOSED: &'static str = "directory.closed";
pub const DIRECTORY_OPENED: &'static str = "directory.opened";
pub const PANEL_RESTORE: &'static str = "panel.restore";
pub const PANEL_MAXIMISE: &'static str = "panel.maximise";
pub const SPLIT_HORIZONTAL: &'static str = "split.horizontal";
pub const TAB_PREVIOUS: &'static str = "tab.previous";
pub const TAB_NEXT: &'static str = "tab.next";
pub const SIDEBAR_LEFT: &'static str = "sidebar.left.on";
pub const SIDEBAR_LEFT_OFF: &'static str = "sidebar.left.off";
pub const SIDEBAR_RIGHT: &'static str = "sidebar.right.on";
pub const SIDEBAR_RIGHT_OFF: &'static str = "sidebar.right.off";
pub const LAYOUT_PANEL: &'static str = "layout.panel.on";
pub const LAYOUT_PANEL_OFF: &'static str = "layout.panel.off";
pub const SEARCH: &'static str = "search.icon";
pub const SEARCH_CLEAR: &'static str = "search.clear";
pub const SEARCH_FORWARD: &'static str = "search.forward";
pub const SEARCH_BACKWARD: &'static str = "search.backward";
pub const SEARCH_CASE_SENSITIVE: &'static str = "search.case_sensitive";
pub const SEARCH_WHOLE_WORD: &'static str = "search.whole_word";
pub const SEARCH_REGEX: &'static str = "search.regex";
pub const SEARCH_REPLACE: &'static str = "search.replace";
pub const SEARCH_REPLACE_ALL: &'static str = "search.replace_all";
pub const FILE_TYPE_CODE: &'static str = "file-code";
pub const FILE_TYPE_MEDIA: &'static str = "file-media";
pub const FILE_TYPE_BINARY: &'static str = "file-binary";
pub const FILE_TYPE_ARCHIVE: &'static str = "file-zip";
pub const FILE_TYPE_SUBMODULE: &'static str = "file-submodule";
pub const FILE_TYPE_SYMLINK_FILE: &'static str = "file-symlink-file";
pub const FILE_TYPE_SYMLINK_DIRECTORY: &'static str = "file-symlink-directory";
pub const DOCUMENT_SYMBOL: &'static str = "document_symbol";
pub const REFERENCES: &'static str = "references";
pub const IMPLEMENTATION: &'static str = "implementation";
pub const SYMBOL_KIND_ARRAY: &'static str = "symbol_kind.array";
pub const SYMBOL_KIND_BOOLEAN: &'static str = "symbol_kind.boolean";
pub const SYMBOL_KIND_CLASS: &'static str = "symbol_kind.class";
pub const SYMBOL_KIND_CONSTANT: &'static str = "symbol_kind.constant";
pub const SYMBOL_KIND_ENUM_MEMBER: &'static str = "symbol_kind.enum_member";
pub const SYMBOL_KIND_ENUM: &'static str = "symbol_kind.enum";
pub const SYMBOL_KIND_EVENT: &'static str = "symbol_kind.event";
pub const SYMBOL_KIND_FIELD: &'static str = "symbol_kind.field";
pub const SYMBOL_KIND_FILE: &'static str = "symbol_kind.file";
pub const SYMBOL_KIND_FUNCTION: &'static str = "symbol_kind.function";
pub const SYMBOL_KIND_INTERFACE: &'static str = "symbol_kind.interface";
pub const SYMBOL_KIND_KEY: &'static str = "symbol_kind.key";
pub const SYMBOL_KIND_METHOD: &'static str = "symbol_kind.method";
pub const SYMBOL_KIND_NAMESPACE: &'static str = "symbol_kind.namespace";
pub const SYMBOL_KIND_NUMBER: &'static str = "symbol_kind.number";
pub const SYMBOL_KIND_OBJECT: &'static str = "symbol_kind.namespace";
pub const SYMBOL_KIND_OPERATOR: &'static str = "symbol_kind.operator";
pub const SYMBOL_KIND_PROPERTY: &'static str = "symbol_kind.property";
pub const SYMBOL_KIND_STRING: &'static str = "symbol_kind.string";
pub const SYMBOL_KIND_STRUCT: &'static str = "symbol_kind.struct";
pub const SYMBOL_KIND_TYPE_PARAMETER: &'static str =
"symbol_kind.type_parameter";
pub const SYMBOL_KIND_VARIABLE: &'static str = "symbol_kind.variable";
pub const COMPLETION_ITEM_KIND_CLASS: &'static str =
"completion_item_kind.class";
pub const COMPLETION_ITEM_KIND_CONSTANT: &'static str =
"completion_item_kind.constant";
pub const COMPLETION_ITEM_KIND_ENUM_MEMBER: &'static str =
"completion_item_kind.enum_member";
pub const COMPLETION_ITEM_KIND_ENUM: &'static str = "completion_item_kind.enum";
pub const COMPLETION_ITEM_KIND_FIELD: &'static str =
"completion_item_kind.field";
pub const COMPLETION_ITEM_KIND_FUNCTION: &'static str =
"completion_item_kind.function";
pub const COMPLETION_ITEM_KIND_INTERFACE: &'static str =
"completion_item_kind.interface";
pub const COMPLETION_ITEM_KIND_KEYWORD: &'static str =
"completion_item_kind.keyword";
pub const COMPLETION_ITEM_KIND_METHOD: &'static str =
"completion_item_kind.method";
pub const COMPLETION_ITEM_KIND_MODULE: &'static str =
"completion_item_kind.module";
pub const COMPLETION_ITEM_KIND_PROPERTY: &'static str =
"completion_item_kind.property";
pub const COMPLETION_ITEM_KIND_SNIPPET: &'static str =
"completion_item_kind.snippet";
pub const COMPLETION_ITEM_KIND_STRING: &'static str =
"completion_item_kind.string";
pub const COMPLETION_ITEM_KIND_STRUCT: &'static str =
"completion_item_kind.struct";
pub const COMPLETION_ITEM_KIND_VARIABLE: &'static str =
"completion_item_kind.variable";
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/config/svg.rs | lapce-app/src/config/svg.rs | use std::{
collections::HashMap,
fs,
path::{Path, PathBuf},
};
use include_dir::{Dir, include_dir};
use crate::config::LOGO;
const CODICONS_ICONS_DIR: Dir =
include_dir!("$CARGO_MANIFEST_DIR/../icons/codicons");
const LAPCE_ICONS_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/../icons/lapce");
#[derive(Debug, Clone)]
pub struct SvgStore {
svgs: HashMap<String, String>,
svgs_on_disk: HashMap<PathBuf, Option<String>>,
}
impl Default for SvgStore {
fn default() -> Self {
Self::new()
}
}
impl SvgStore {
fn new() -> Self {
let mut svgs = HashMap::new();
svgs.insert("lapce_logo".to_string(), LOGO.to_string());
Self {
svgs,
svgs_on_disk: HashMap::new(),
}
}
pub fn logo_svg(&self) -> String {
self.svgs.get("lapce_logo").unwrap().clone()
}
pub fn get_default_svg(&mut self, name: &str) -> String {
if !self.svgs.contains_key(name) {
let file = if name == "lapce_remote.svg" || name == "lapce_logo.svg" {
LAPCE_ICONS_DIR.get_file(name).unwrap()
} else {
CODICONS_ICONS_DIR
.get_file(name)
.unwrap_or_else(|| panic!("Failed to unwrap {name}"))
};
let content = file.contents_utf8().unwrap();
self.svgs.insert(name.to_string(), content.to_string());
}
self.svgs.get(name).unwrap().clone()
}
pub fn get_svg_on_disk(&mut self, path: &Path) -> Option<String> {
if !self.svgs_on_disk.contains_key(path) {
let svg = fs::read_to_string(path).ok();
self.svgs_on_disk.insert(path.to_path_buf(), svg);
}
self.svgs_on_disk.get(path).unwrap().clone()
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/config/editor.rs | lapce-app/src/config/editor.rs | use floem::views::editor::text::RenderWhitespace;
use serde::{Deserialize, Serialize};
use structdesc::FieldNames;
pub const SCALE_OR_SIZE_LIMIT: f64 = 5.0;
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub enum ClickMode {
#[default]
#[serde(rename = "single")]
SingleClick,
#[serde(rename = "file")]
DoubleClickFile,
#[serde(rename = "all")]
DoubleClickAll,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, PartialEq)]
#[serde(rename_all = "kebab-case")]
pub enum WrapStyle {
/// No wrapping
None,
/// Wrap at the editor width
#[default]
EditorWidth,
// /// Wrap at the wrap-column
// WrapColumn,
/// Wrap at a specific width
WrapWidth,
}
impl WrapStyle {
pub fn as_str(&self) -> &'static str {
match self {
WrapStyle::None => "none",
WrapStyle::EditorWidth => "editor-width",
// WrapStyle::WrapColumn => "wrap-column",
WrapStyle::WrapWidth => "wrap-width",
}
}
pub fn try_from_str(s: &str) -> Option<Self> {
match s {
"none" => Some(WrapStyle::None),
"editor-width" => Some(WrapStyle::EditorWidth),
// "wrap-column" => Some(WrapStyle::WrapColumn),
"wrap-width" => Some(WrapStyle::WrapWidth),
_ => None,
}
}
}
impl std::fmt::Display for WrapStyle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.as_str())?;
Ok(())
}
}
#[derive(FieldNames, Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "kebab-case")]
pub struct EditorConfig {
#[field_names(desc = "Set the editor font family")]
pub font_family: String,
#[field_names(desc = "Set the editor font size")]
font_size: usize,
#[field_names(desc = "Set the font size in the code glance")]
pub code_glance_font_size: usize,
#[field_names(
desc = "Set the editor line height. If less than 5.0, line height will be a multiple of the font size."
)]
line_height: f64,
#[field_names(
desc = "If enabled, when you input a tab character, it will insert indent that's detected based on your files."
)]
pub smart_tab: bool,
#[field_names(desc = "Set the tab width")]
pub tab_width: usize,
#[field_names(desc = "If opened editors are shown in a tab")]
pub show_tab: bool,
#[field_names(desc = "If navigation breadcrumbs are shown for the file")]
pub show_bread_crumbs: bool,
#[field_names(desc = "If the editor can scroll beyond the last line")]
pub scroll_beyond_last_line: bool,
#[field_names(
desc = "Set the minimum number of visible lines above and below the cursor"
)]
pub cursor_surrounding_lines: usize,
#[field_names(desc = "The kind of wrapping to perform")]
pub wrap_style: WrapStyle,
// #[field_names(desc = "The number of columns to wrap at")]
// pub wrap_column: usize,
#[field_names(desc = "The number of pixels to wrap at")]
pub wrap_width: usize,
#[field_names(
desc = "Show code context like functions and classes at the top of editor when scroll"
)]
pub sticky_header: bool,
#[field_names(desc = "The number of pixels to show completion")]
pub completion_width: usize,
#[field_names(
desc = "If the editor should show the documentation of the current completion item"
)]
pub completion_show_documentation: bool,
#[field_names(
desc = "Should the completion item use the `detail` field to replace the label `field`?"
)]
pub completion_item_show_detail: bool,
#[field_names(
desc = "If the editor should show the signature of the function as the parameters are being typed"
)]
pub show_signature: bool,
#[field_names(
desc = "If the signature view should put the codeblock into a label. This might not work nicely for LSPs which provide invalid code for their labels."
)]
pub signature_label_code_block: bool,
#[field_names(
desc = "Whether the editor should enable automatic closing of matching pairs"
)]
pub auto_closing_matching_pairs: bool,
#[field_names(
desc = "Whether the editor should automatically surround selected text when typing quotes or brackets"
)]
pub auto_surround: bool,
#[field_names(
desc = "How long (in ms) it should take before the hover information appears"
)]
pub hover_delay: u64,
#[field_names(
desc = "If modal mode should have relative line numbers (though, not in insert mode)"
)]
pub modal_mode_relative_line_numbers: bool,
#[field_names(
desc = "Whether it should format the document on save (if there is an available formatter)"
)]
pub format_on_save: bool,
#[field_names(
desc = "Whether newlines should be automatically converted to the current line ending"
)]
pub normalize_line_endings: bool,
#[field_names(desc = "If matching brackets are highlighted")]
pub highlight_matching_brackets: bool,
#[field_names(desc = "If scope lines are highlighted")]
pub highlight_scope_lines: bool,
#[field_names(desc = "If inlay hints should be displayed")]
pub enable_inlay_hints: bool,
#[field_names(
desc = "Set the inlay hint font family. If empty, it uses the editor font family."
)]
pub inlay_hint_font_family: String,
#[field_names(
desc = "Set the inlay hint font size. If less than 5 or greater than editor font size, it uses the editor font size."
)]
pub inlay_hint_font_size: usize,
#[field_names(desc = "If diagnostics should be displayed inline")]
pub enable_error_lens: bool,
#[field_names(
desc = "Only render the styling without displaying messages, provided that `Enable ErrorLens` is enabled"
)]
pub only_render_error_styling: bool,
#[field_names(
desc = "Whether error lens should go to the end of view line, or only to the end of the diagnostic"
)]
pub error_lens_end_of_line: bool,
#[field_names(
desc = "Whether error lens should extend over multiple lines. If false, it will have newlines stripped."
)]
pub error_lens_multiline: bool,
// TODO: Error lens but put entirely on the next line
// TODO: error lens with indentation matching.
#[field_names(
desc = "Set error lens font family. If empty, it uses the inlay hint font family."
)]
pub error_lens_font_family: String,
#[field_names(
desc = "Set the error lens font size. If 0 it uses the inlay hint font size."
)]
pub error_lens_font_size: usize,
#[field_names(
desc = "If the editor should display the completion item as phantom text"
)]
pub enable_completion_lens: bool,
#[field_names(desc = "If the editor should display inline completions")]
pub enable_inline_completion: bool,
#[field_names(
desc = "Set completion lens font family. If empty, it uses the inlay hint font family."
)]
pub completion_lens_font_family: String,
#[field_names(
desc = "Set the completion lens font size. If 0 it uses the inlay hint font size."
)]
pub completion_lens_font_size: usize,
#[field_names(
desc = "Set the cursor blink interval (in milliseconds). Set to 0 to completely disable."
)]
blink_interval: u64,
#[field_names(
desc = "Whether the multiple cursor selection is case sensitive."
)]
pub multicursor_case_sensitive: bool,
#[field_names(
desc = "Whether the multiple cursor selection only selects whole words."
)]
pub multicursor_whole_words: bool,
#[field_names(
desc = "How the editor should render whitespace characters.\nOptions: none, all, boundary, trailing."
)]
pub render_whitespace: RenderWhitespace,
#[field_names(desc = "Whether the editor show indent guide.")]
pub show_indent_guide: bool,
#[field_names(
desc = "Set the auto save delay (in milliseconds), Set to 0 to completely disable"
)]
pub autosave_interval: u64,
#[field_names(
desc = "Whether the document should be formatted when an autosave is triggered (required Format on Save)"
)]
pub format_on_autosave: bool,
#[field_names(
desc = "If enabled the cursor treats leading soft tabs as if they are hard tabs."
)]
pub atomic_soft_tabs: bool,
#[field_names(
desc = "Use a double click to interact with the file explorer.\nOptions: single (default), file or all."
)]
pub double_click: ClickMode,
#[field_names(desc = "Move the focus as you type in the global search box")]
pub move_focus_while_search: bool,
#[field_names(
desc = "Set the default number of visible lines above and below the diff block (-1 for infinite)"
)]
pub diff_context_lines: i32,
#[field_names(desc = "Whether the editor colorizes brackets")]
pub bracket_pair_colorization: bool,
#[field_names(desc = "Bracket colorization Limit")]
pub bracket_colorization_limit: u64,
#[field_names(
desc = "Glob patterns for excluding files and folders (in file explorer)"
)]
pub files_exclude: String,
}
impl EditorConfig {
pub fn font_size(&self) -> usize {
self.font_size.clamp(6, 32)
}
pub fn line_height(&self) -> usize {
let line_height = if self.line_height < SCALE_OR_SIZE_LIMIT {
self.line_height * self.font_size as f64
} else {
self.line_height
};
// Prevent overlapping lines
(line_height.round() as usize).max(self.font_size)
}
pub fn inlay_hint_font_size(&self) -> usize {
if self.inlay_hint_font_size < 5
|| self.inlay_hint_font_size > self.font_size
{
self.font_size()
} else {
self.inlay_hint_font_size
}
}
pub fn error_lens_font_size(&self) -> usize {
if self.error_lens_font_size == 0 {
self.inlay_hint_font_size()
} else {
self.error_lens_font_size
}
}
pub fn completion_lens_font_size(&self) -> usize {
if self.completion_lens_font_size == 0 {
self.inlay_hint_font_size()
} else {
self.completion_lens_font_size
}
}
/// Returns the tab width if atomic soft tabs are enabled.
pub fn atomic_soft_tab_width(&self) -> Option<usize> {
if self.atomic_soft_tabs {
Some(self.tab_width)
} else {
None
}
}
pub fn blink_interval(&self) -> u64 {
if self.blink_interval == 0 {
return 0;
}
self.blink_interval.max(200)
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/config/watcher.rs | lapce-app/src/config/watcher.rs | use std::sync::{Arc, atomic::AtomicBool, mpsc::Sender};
pub struct ConfigWatcher {
tx: Sender<()>,
delay_handler: Arc<AtomicBool>,
}
impl notify::EventHandler for ConfigWatcher {
fn handle_event(&mut self, event: notify::Result<notify::Event>) {
match event {
Ok(event) => match event.kind {
notify::EventKind::Create(_)
| notify::EventKind::Modify(_)
| notify::EventKind::Remove(_) => {
if self
.delay_handler
.compare_exchange(
false,
true,
std::sync::atomic::Ordering::Relaxed,
std::sync::atomic::Ordering::Relaxed,
)
.is_ok()
{
let config_mutex = self.delay_handler.clone();
let tx = self.tx.clone();
std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_millis(
500,
));
if let Err(err) = tx.send(()) {
tracing::error!("{:?}", err);
}
config_mutex
.store(false, std::sync::atomic::Ordering::Relaxed);
});
}
}
_ => {}
},
Err(err) => {
tracing::error!("{:?}", err);
}
}
}
}
impl ConfigWatcher {
pub fn new(tx: Sender<()>) -> Self {
Self {
tx,
delay_handler: Arc::new(AtomicBool::new(false)),
}
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/config/core.rs | lapce-app/src/config/core.rs | use serde::{Deserialize, Serialize};
use structdesc::FieldNames;
#[derive(FieldNames, Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "kebab-case")]
pub struct CoreConfig {
#[field_names(desc = "Enable modal editing (Vim like)")]
pub modal: bool,
#[field_names(desc = "Set the color theme of Lapce")]
pub color_theme: String,
#[field_names(desc = "Set the icon theme of Lapce")]
pub icon_theme: String,
#[field_names(
desc = "Enable customised titlebar and disable OS native one (Linux, BSD, Windows)"
)]
pub custom_titlebar: bool,
#[field_names(
desc = "Only allow double-click to open files in the file explorer"
)]
pub file_explorer_double_click: bool,
#[field_names(
desc = "Enable auto-reload for the plugin when its configuration changes."
)]
pub auto_reload_plugin: bool,
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/config/terminal.rs | lapce-app/src/config/terminal.rs | use std::{collections::HashMap, sync::Arc};
use floem::peniko::Color;
use serde::{Deserialize, Serialize};
use structdesc::FieldNames;
#[derive(FieldNames, Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "kebab-case")]
pub struct TerminalConfig {
#[field_names(
desc = "Set the terminal font family. If empty, it uses editor font family."
)]
pub font_family: String,
#[field_names(
desc = "Set the terminal font size, If 0, it uses editor font size."
)]
pub font_size: usize,
#[field_names(
desc = "Set the terminal line height, If 0, it uses editor line height"
)]
pub line_height: f64,
#[field_names(skip)]
pub profiles: HashMap<String, TerminalProfile>,
#[field_names(skip)]
pub default_profile: HashMap<String, String>,
#[serde(skip)]
#[field_names(skip)]
pub indexed_colors: Arc<HashMap<u8, Color>>,
}
#[derive(FieldNames, Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "kebab-case")]
pub struct TerminalProfile {
#[field_names(desc = "Command to execute when launching terminal")]
pub command: Option<String>,
#[field_names(desc = "Arguments passed to command")]
pub arguments: Option<Vec<String>>,
#[field_names(desc = "Command to execute when launching terminal")]
pub workdir: Option<std::path::PathBuf>,
#[field_names(desc = "Arguments passed to command")]
pub environment: Option<HashMap<String, String>>,
}
impl TerminalConfig {
pub fn get_indexed_colors(&mut self) {
let mut indexed_colors = HashMap::new();
// Build colors.
for r in 0..6 {
for g in 0..6 {
for b in 0..6 {
// Override colors 16..232 with the config (if present).
let index = 16 + r * 36 + g * 6 + b;
let color = Color::from_rgb8(
if r == 0 { 0 } else { r * 40 + 55 },
if g == 0 { 0 } else { g * 40 + 55 },
if b == 0 { 0 } else { b * 40 + 55 },
);
indexed_colors.insert(index, color);
}
}
}
let index: u8 = 232;
for i in 0..24 {
// Override colors 232..256 with the config (if present).
let value = i * 10 + 8;
indexed_colors.insert(index + i, Color::from_rgb8(value, value, value));
}
self.indexed_colors = Arc::new(indexed_colors);
}
pub fn get_default_profile(
&self,
) -> Option<lapce_rpc::terminal::TerminalProfile> {
let profile = self.profiles.get(
self.default_profile
.get(std::env::consts::OS)
.unwrap_or(&String::from("default")),
)?;
let workdir = if let Some(workdir) = &profile.workdir {
url::Url::parse(&workdir.display().to_string()).ok()
} else {
None
};
let profile = profile.clone();
Some(lapce_rpc::terminal::TerminalProfile {
name: std::env::consts::OS.to_string(),
command: profile.command,
arguments: profile.arguments,
workdir,
environment: profile.environment,
})
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/config/ui.rs | lapce-app/src/config/ui.rs | use floem::text::FamilyOwned;
use serde::{Deserialize, Serialize};
use structdesc::FieldNames;
#[derive(FieldNames, Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "kebab-case")]
pub struct UIConfig {
#[field_names(desc = "Set the UI scale. Defaults to 1.0")]
scale: f64,
#[field_names(
desc = "Set the UI font family. If empty, it uses system default."
)]
pub font_family: String,
#[field_names(desc = "Set the UI base font size")]
font_size: usize,
#[field_names(desc = "Set the icon size in the UI")]
icon_size: usize,
#[field_names(
desc = "Set the header height for panel header and editor tab header"
)]
header_height: usize,
#[field_names(desc = "Set the height for status line")]
status_height: usize,
#[field_names(desc = "Set the minimum width for editor tab")]
tab_min_width: usize,
#[field_names(
desc = "Set whether the editor tab separator should be full height or the height of the content"
)]
pub tab_separator_height: TabSeparatorHeight,
#[field_names(desc = "Set the width for scroll bar")]
scroll_width: usize,
#[field_names(desc = "Controls the width of drop shadow in the UI")]
drop_shadow_width: usize,
#[field_names(desc = "Controls the width of the command palette")]
palette_width: usize,
#[field_names(
desc = "Set the hover font family. If empty, it uses the UI font family"
)]
hover_font_family: String,
#[field_names(desc = "Set the hover font size. If 0, uses the UI font size")]
hover_font_size: usize,
#[field_names(desc = "Trim whitespace from search results")]
pub trim_search_results_whitespace: bool,
#[field_names(desc = "Set the line height for list items")]
list_line_height: usize,
#[field_names(desc = "Set position of the close button in editor tabs")]
pub tab_close_button: TabCloseButton,
#[field_names(desc = "Display the Open Editors section in the explorer")]
pub open_editors_visible: bool,
}
#[derive(
Debug,
Clone,
Copy,
Deserialize,
Serialize,
Default,
PartialEq,
Eq,
PartialOrd,
Ord,
strum_macros::VariantNames,
)]
pub enum TabCloseButton {
Left,
#[default]
Right,
Off,
}
#[derive(
Debug,
Clone,
Copy,
Deserialize,
Serialize,
Default,
PartialEq,
Eq,
PartialOrd,
Ord,
strum_macros::VariantNames,
)]
pub enum TabSeparatorHeight {
#[default]
Content,
Full,
}
impl UIConfig {
pub fn scale(&self) -> f64 {
self.scale.clamp(0.1, 4.0)
}
pub fn font_size(&self) -> usize {
self.font_size.clamp(6, 32)
}
pub fn font_family(&self) -> Vec<FamilyOwned> {
FamilyOwned::parse_list(&self.font_family).collect()
}
pub fn header_height(&self) -> usize {
let font_size = self.font_size();
self.header_height.max(font_size)
}
pub fn icon_size(&self) -> usize {
if self.icon_size == 0 {
self.font_size()
} else {
self.icon_size.clamp(6, 32)
}
}
pub fn status_height(&self) -> usize {
let font_size = self.font_size();
self.status_height.max(font_size)
}
pub fn palette_width(&self) -> usize {
if self.palette_width == 0 {
500
} else {
self.palette_width.max(100)
}
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/config/color_theme.rs | lapce-app/src/config/color_theme.rs | use std::{
collections::{BTreeMap, HashMap},
path::PathBuf,
str::FromStr,
};
use floem::{peniko::Color, prelude::palette::css};
use serde::{Deserialize, Serialize};
use super::color::LoadThemeError;
#[derive(Debug, Clone, Default)]
pub enum ThemeColorPreference {
#[default]
Light,
Dark,
HighContrastDark,
HighContrastLight,
}
/// Holds all the resolved theme variables
#[derive(Debug, Clone, Default)]
pub struct ThemeBaseColor(HashMap<String, Color>);
impl ThemeBaseColor {
pub fn get(&self, name: &str) -> Option<Color> {
self.0.get(name).map(ToOwned::to_owned)
}
}
pub const THEME_RECURSION_LIMIT: usize = 6;
#[derive(Debug, Clone, Default)]
pub struct ThemeColor {
pub color_preference: ThemeColorPreference,
pub base: ThemeBaseColor,
pub syntax: HashMap<String, Color>,
pub ui: HashMap<String, Color>,
}
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
pub struct ThemeBaseConfig(pub BTreeMap<String, String>);
impl ThemeBaseConfig {
/// Resolve the variables in this theme base config into the actual colors.
/// The basic idea is just: `"field`: some value` does:
/// - If the value does not start with `$`, then it is a color and we return it
/// - If the value starts with `$` then it is a variable
/// - Look it up in the current theme
/// - If not found, look it up in the default theme
/// - If not found, return `Color::HOT_PINK` as a fallback
///
/// Note that this applies even if the default theme colors have a variable.
/// This allows the default theme to have, for example, a `$uibg` variable that the current
/// them can override so that if there's ever a new ui element using that variable, the theme
/// does not have to be updated.
pub fn resolve(&self, default: Option<&ThemeBaseConfig>) -> ThemeBaseColor {
let default = default.cloned().unwrap_or_default();
let mut base = ThemeBaseColor(HashMap::new());
// We resolve all the variables to their values
for (key, value) in self.0.iter() {
match self.resolve_variable(&default, key, value, 0) {
Ok(Some(color)) => {
let color = Color::from_str(color)
.unwrap_or_else(|_| {
tracing::warn!(
"Failed to parse color theme variable for ({key}: {value})"
);
css::HOT_PINK
});
base.0.insert(key.to_string(), color);
}
Ok(None) => {
tracing::warn!(
"Failed to resolve color theme variable for ({key}: {value})"
);
}
Err(err) => {
tracing::error!(
"Failed to resolve color theme variable ({key}: {value}): {err}"
);
}
}
}
base
}
fn resolve_variable<'a>(
&'a self,
defaults: &'a ThemeBaseConfig,
key: &str,
value: &'a str,
i: usize,
) -> Result<Option<&'a str>, LoadThemeError> {
let Some(value) = value.strip_prefix('$') else {
return Ok(Some(value));
};
if i > THEME_RECURSION_LIMIT {
return Err(LoadThemeError::RecursionLimitReached {
variable_name: key.to_string(),
});
}
let target =
self.get(value)
.or_else(|| defaults.get(value))
.ok_or_else(|| LoadThemeError::VariableNotFound {
variable_name: key.to_string(),
})?;
self.resolve_variable(defaults, value, target, i + 1)
}
// Note: this returns an `&String` just to make it consistent with hashmap lookups that are
// also used via ui/syntax
pub fn get(&self, name: &str) -> Option<&String> {
self.0.get(name)
}
pub fn key_values(&self) -> BTreeMap<String, String> {
self.0.clone()
}
}
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "kebab-case", default)]
pub struct ColorThemeConfig {
#[serde(skip)]
pub path: PathBuf,
pub name: String,
pub high_contrast: Option<bool>,
pub base: ThemeBaseConfig,
pub syntax: BTreeMap<String, String>,
pub ui: BTreeMap<String, String>,
}
impl ColorThemeConfig {
fn resolve_color(
colors: &BTreeMap<String, String>,
base: &ThemeBaseColor,
default: Option<&HashMap<String, Color>>,
) -> HashMap<String, Color> {
colors
.iter()
.map(|(name, hex)| {
let color = if let Some(stripped) = hex.strip_prefix('$') {
base.get(stripped)
} else {
Color::from_str(hex).ok()
};
let color = color
.or_else(|| {
default.and_then(|default| default.get(name).cloned())
})
.unwrap_or(Color::from_rgb8(0, 0, 0));
(name.to_string(), color)
})
.collect()
}
pub(super) fn resolve_ui_color(
&self,
base: &ThemeBaseColor,
default: Option<&HashMap<String, Color>>,
) -> HashMap<String, Color> {
Self::resolve_color(&self.ui, base, default)
}
pub(super) fn resolve_syntax_color(
&self,
base: &ThemeBaseColor,
default: Option<&HashMap<String, Color>>,
) -> HashMap<String, Color> {
Self::resolve_color(&self.syntax, base, default)
}
}
#[cfg(test)]
mod tests {
use config::Config;
use floem::{peniko::Color, prelude::palette::css};
use crate::{config::LapceConfig, workspace::LapceWorkspace};
#[test]
fn test_resolve() {
// Mimicking load
let workspace = LapceWorkspace::default();
let config = LapceConfig::merge_config(&workspace, None, None);
let mut lapce_config: LapceConfig = config.try_deserialize().unwrap();
let test_theme_str = r##"
[color-theme]
name = "test"
color-preference = "dark"
[ui]
[color-theme.base]
"blah" = "#ff00ff"
"text" = "#000000"
[color-theme.syntax]
[color-theme.ui]
"lapce.error" = "#ffffff"
"editor.background" = "$blah"
"##;
println!("Test theme: {test_theme_str}");
let test_theme_cfg = Config::builder()
.add_source(config::File::from_str(
test_theme_str,
config::FileFormat::Toml,
))
.build()
.unwrap();
lapce_config.available_color_themes =
[("test".to_string(), ("test".to_string(), test_theme_cfg))]
.into_iter()
.collect();
// lapce_config.available_icon_themes = Some(vec![]);
lapce_config.core.color_theme = "test".to_string();
lapce_config.resolve_theme(&workspace);
println!("Hot Pink: {:?}", css::HOT_PINK);
// test basic override
assert_eq!(
lapce_config.color("lapce.error"),
Color::WHITE,
"Failed to get basic theme override"
);
// test that it falls through to the dark theme for unspecified color
assert_eq!(
lapce_config.color("lapce.warn"),
Color::from_rgb8(0xE5, 0xC0, 0x7B),
"Failed to get from fallback dark theme"
); // $yellow
// test that our custom variable worked
assert_eq!(
lapce_config.color("editor.background"),
Color::from_rgb8(0xFF, 0x00, 0xFF),
"Failed to get from custom variable"
);
// test that for text it now uses our redeclared variable
assert_eq!(
lapce_config.color("editor.foreground"),
Color::BLACK,
"Failed to get from custom variable circle back around"
);
// don't bother filling color/icon theme list
// don't bother with wrap style list
// don't bother with terminal colors
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/config/icon_theme.rs | lapce-app/src/config/icon_theme.rs | use std::{
ffi::OsStr,
path::{Path, PathBuf},
};
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
/// Returns the first item yielded from `items` if at least one item is yielded, all yielded items
/// are `Some`, and all yielded items compare equal, else returns `None`.
fn try_all_equal_value<T: PartialEq, I: IntoIterator<Item = Option<T>>>(
items: I,
) -> Option<T> {
let mut items = items.into_iter();
let first = items.next().flatten()?;
items.try_fold(first, |initial_item, item| {
item.and_then(|item| (item == initial_item).then_some(initial_item))
})
}
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "kebab-case", default)]
pub struct IconThemeConfig {
#[serde(skip)]
pub path: PathBuf,
pub name: String,
pub use_editor_color: Option<bool>,
pub ui: IndexMap<String, String>,
pub foldername: IndexMap<String, String>,
pub filename: IndexMap<String, String>,
pub extension: IndexMap<String, String>,
}
impl IconThemeConfig {
/// If all paths in `paths` have the same file type (as determined by the file name or
/// extension), and there is an icon associated with that file type, returns the path of the
/// icon.
pub fn resolve_path_to_icon(&self, paths: &[&Path]) -> Option<PathBuf> {
let file_names = paths
.iter()
.map(|path| path.file_name().and_then(OsStr::to_str));
let file_name_icon = try_all_equal_value(file_names)
.and_then(|file_name| self.filename.get(file_name));
file_name_icon
.or_else(|| {
let extensions = paths
.iter()
.map(|path| path.extension().and_then(OsStr::to_str));
try_all_equal_value(extensions)
.and_then(|extension| self.extension.get(extension))
})
.map(|icon| self.path.join(icon))
}
}
#[cfg(test)]
mod tests {
use super::IconThemeConfig;
use crate::config::icon_theme::try_all_equal_value;
#[test]
fn try_all_equal_value_empty_none() {
assert_eq!(Option::<u32>::None, try_all_equal_value([]));
}
#[test]
fn try_all_equal_value_any_none_none() {
assert_eq!(Option::<u32>::None, try_all_equal_value([None]));
assert_eq!(
Option::<i32>::None,
try_all_equal_value([None, Some(1), Some(1)])
);
assert_eq!(Option::<u64>::None, try_all_equal_value([Some(0), None]));
assert_eq!(
Option::<u8>::None,
try_all_equal_value([Some(3), Some(3), None, Some(3)])
);
}
#[test]
fn try_all_equal_value_any_different_none() {
assert_eq!(Option::<u32>::None, try_all_equal_value([Some(1), Some(2)]));
assert_eq!(
Option::<u128>::None,
try_all_equal_value([Some(1), Some(10), Some(1)])
);
assert_eq!(
Option::<i16>::None,
try_all_equal_value([Some(3), Some(3), Some(3), Some(3), Some(2)])
);
assert_eq!(
Option::<i64>::None,
try_all_equal_value([Some(5), Some(4), Some(4), Some(4), Some(4)])
);
assert_eq!(
Option::<i128>::None,
try_all_equal_value([Some(3), Some(0), Some(9), Some(20), Some(1)])
);
}
#[test]
fn try_all_equal_value_all_same_some() {
assert_eq!(Option::<u32>::Some(1), try_all_equal_value([Some(1)]));
assert_eq!(Option::<i16>::Some(-2), try_all_equal_value([Some(-2); 2]));
assert_eq!(Option::<i128>::Some(0), try_all_equal_value([Some(0); 3]));
assert_eq!(Option::<u8>::Some(30), try_all_equal_value([Some(30); 57]));
}
fn get_icon_theme_config() -> IconThemeConfig {
IconThemeConfig {
path: "icons".to_owned().into(),
filename: [("Makefile", "makefile.svg"), ("special.rs", "special.svg")]
.map(|(k, v)| (k.to_owned(), v.to_owned()))
.into(),
extension: [("rs", "rust.svg"), ("c", "c.svg"), ("py", "python.svg")]
.map(|(k, v)| (k.to_owned(), v.to_owned()))
.into(),
..Default::default()
}
}
#[test]
fn resolve_path_to_icon_no_paths_none() {
let icon_theme_config = get_icon_theme_config();
assert_eq!(None, icon_theme_config.resolve_path_to_icon(&[]));
}
#[test]
fn resolve_path_to_icon_different_none() {
let icon_theme_config = get_icon_theme_config();
assert_eq!(
None,
icon_theme_config
.resolve_path_to_icon(&["foo.rs", "bar.c"].map(AsRef::as_ref))
);
assert_eq!(
None,
icon_theme_config.resolve_path_to_icon(
&["/some/path/main.py", "other/path.py", "dir1/./dir2/file.rs"]
.map(AsRef::as_ref)
)
);
assert_eq!(
None,
icon_theme_config.resolve_path_to_icon(
&["/root/Makefile", "dir/dir/special.rs", "../../main.rs"]
.map(AsRef::as_ref)
)
);
assert_eq!(
None,
icon_theme_config
.resolve_path_to_icon(&["main.c", "foo.txt"].map(AsRef::as_ref))
);
}
#[test]
fn resolve_path_to_icon_no_match_none() {
let icon_theme_config = get_icon_theme_config();
assert_eq!(
None,
icon_theme_config.resolve_path_to_icon(&["foo"].map(AsRef::as_ref))
);
assert_eq!(
None,
icon_theme_config.resolve_path_to_icon(
&["/some/path/file.txt", "other/path.txt"].map(AsRef::as_ref)
)
);
assert_eq!(
None,
icon_theme_config.resolve_path_to_icon(
&["folder/file", "/home/user/file", "../../file"].map(AsRef::as_ref)
)
);
assert_eq!(
None,
icon_theme_config.resolve_path_to_icon(&[".."].map(AsRef::as_ref))
);
assert_eq!(
None,
icon_theme_config.resolve_path_to_icon(&["."].map(AsRef::as_ref))
);
}
#[test]
fn resolve_path_to_icon_file_name_match_some() {
let icon_theme_config = get_icon_theme_config();
assert_eq!(
Some("icons/makefile.svg".to_owned().into()),
icon_theme_config.resolve_path_to_icon(&["Makefile"].map(AsRef::as_ref))
);
assert_eq!(
Some("icons/makefile.svg".to_owned().into()),
icon_theme_config.resolve_path_to_icon(
&[
"baz/Makefile",
"/foo/bar/dir/Makefile",
".././/././Makefile"
]
.map(AsRef::as_ref)
)
);
assert_eq!(
Some("icons/special.svg".to_owned().into()),
icon_theme_config.resolve_path_to_icon(
&["dir/special.rs", "/dir1/dir2/..//./special.rs"]
.map(AsRef::as_ref)
)
);
}
#[test]
fn resolve_path_to_icon_extension_match_some() {
let icon_theme_config = get_icon_theme_config();
assert_eq!(
Some("icons/python.svg".to_owned().into()),
icon_theme_config
.resolve_path_to_icon(&["source.py"].map(AsRef::as_ref))
);
assert_eq!(
Some("icons/rust.svg".to_owned().into()),
icon_theme_config.resolve_path_to_icon(
&["/home/user/main.rs", "../../special.rs.rs", "special.rs"]
.map(AsRef::as_ref)
)
);
assert_eq!(
Some("icons/c.svg".to_owned().into()),
icon_theme_config.resolve_path_to_icon(
&["/dir1/Makefile.c", "../main.c"].map(AsRef::as_ref)
)
);
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/config/color.rs | lapce-app/src/config/color.rs | use std::path::PathBuf;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum LoadThemeError {
#[error("themes folder not found, possibly it could not be created")]
ThemesFolderNotFound,
#[error("theme file ({theme_name}.toml) was not found in {themes_folder:?}")]
FileNotFound {
themes_folder: PathBuf,
theme_name: String,
},
#[error("recursion limit reached for {variable_name}")]
RecursionLimitReached { variable_name: String },
#[error("variable {variable_name} not found")]
VariableNotFound { variable_name: String },
#[error("There was an error reading the theme file")]
Read(std::io::Error),
}
pub struct LapceColor {}
impl LapceColor {
pub const LAPCE_WARN: &'static str = "lapce.warn";
pub const LAPCE_ERROR: &'static str = "lapce.error";
pub const LAPCE_DROPDOWN_SHADOW: &'static str = "lapce.dropdown_shadow";
pub const LAPCE_BORDER: &'static str = "lapce.border";
pub const LAPCE_SCROLL_BAR: &'static str = "lapce.scroll_bar";
pub const LAPCE_BUTTON_PRIMARY_BACKGROUND: &'static str =
"lapce.button.primary.background";
pub const LAPCE_BUTTON_PRIMARY_FOREGROUND: &'static str =
"lapce.button.primary.foreground";
pub const LAPCE_TAB_ACTIVE_BACKGROUND: &'static str =
"lapce.tab.active.background";
pub const LAPCE_TAB_ACTIVE_FOREGROUND: &'static str =
"lapce.tab.active.foreground";
pub const LAPCE_TAB_ACTIVE_UNDERLINE: &'static str =
"lapce.tab.active.underline";
pub const LAPCE_TAB_INACTIVE_BACKGROUND: &'static str =
"lapce.tab.inactive.background";
pub const LAPCE_TAB_INACTIVE_FOREGROUND: &'static str =
"lapce.tab.inactive.foreground";
pub const LAPCE_TAB_INACTIVE_UNDERLINE: &'static str =
"lapce.tab.inactive.underline";
pub const LAPCE_TAB_SEPARATOR: &'static str = "lapce.tab.separator";
pub const LAPCE_ICON_ACTIVE: &'static str = "lapce.icon.active";
pub const LAPCE_ICON_INACTIVE: &'static str = "lapce.icon.inactive";
pub const LAPCE_REMOTE_ICON: &'static str = "lapce.remote.icon";
pub const LAPCE_REMOTE_LOCAL: &'static str = "lapce.remote.local";
pub const LAPCE_REMOTE_CONNECTED: &'static str = "lapce.remote.connected";
pub const LAPCE_REMOTE_CONNECTING: &'static str = "lapce.remote.connecting";
pub const LAPCE_REMOTE_DISCONNECTED: &'static str = "lapce.remote.disconnected";
pub const LAPCE_PLUGIN_NAME: &'static str = "lapce.plugin.name";
pub const LAPCE_PLUGIN_DESCRIPTION: &'static str = "lapce.plugin.description";
pub const LAPCE_PLUGIN_AUTHOR: &'static str = "lapce.plugin.author";
pub const EDITOR_BACKGROUND: &'static str = "editor.background";
pub const EDITOR_FOREGROUND: &'static str = "editor.foreground";
pub const EDITOR_DIM: &'static str = "editor.dim";
pub const EDITOR_FOCUS: &'static str = "editor.focus";
pub const EDITOR_CARET: &'static str = "editor.caret";
pub const EDITOR_SELECTION: &'static str = "editor.selection";
pub const EDITOR_DEBUG_BREAK_LINE: &'static str = "editor.debug_break_line";
pub const EDITOR_CURRENT_LINE: &'static str = "editor.current_line";
pub const EDITOR_LINK: &'static str = "editor.link";
pub const EDITOR_VISIBLE_WHITESPACE: &'static str = "editor.visible_whitespace";
pub const EDITOR_INDENT_GUIDE: &'static str = "editor.indent_guide";
pub const EDITOR_DRAG_DROP_BACKGROUND: &'static str =
"editor.drag_drop_background";
pub const EDITOR_STICKY_HEADER_BACKGROUND: &'static str =
"editor.sticky_header_background";
pub const EDITOR_DRAG_DROP_TAB_BACKGROUND: &'static str =
"editor.drag_drop_tab_background";
pub const INLAY_HINT_FOREGROUND: &'static str = "inlay_hint.foreground";
pub const INLAY_HINT_BACKGROUND: &'static str = "inlay_hint.background";
pub const ERROR_LENS_ERROR_FOREGROUND: &'static str =
"error_lens.error.foreground";
pub const ERROR_LENS_ERROR_BACKGROUND: &'static str =
"error_lens.error.background";
pub const ERROR_LENS_WARNING_FOREGROUND: &'static str =
"error_lens.warning.foreground";
pub const ERROR_LENS_WARNING_BACKGROUND: &'static str =
"error_lens.warning.background";
pub const ERROR_LENS_OTHER_FOREGROUND: &'static str =
"error_lens.other.foreground";
pub const ERROR_LENS_OTHER_BACKGROUND: &'static str =
"error_lens.other.background";
pub const COMPLETION_LENS_FOREGROUND: &'static str =
"completion_lens.foreground";
pub const SOURCE_CONTROL_ADDED: &'static str = "source_control.added";
pub const SOURCE_CONTROL_REMOVED: &'static str = "source_control.removed";
pub const SOURCE_CONTROL_MODIFIED: &'static str = "source_control.modified";
pub const TERMINAL_CURSOR: &'static str = "terminal.cursor";
pub const TERMINAL_BACKGROUND: &'static str = "terminal.background";
pub const TERMINAL_FOREGROUND: &'static str = "terminal.foreground";
pub const TERMINAL_RED: &'static str = "terminal.red";
pub const TERMINAL_BLUE: &'static str = "terminal.blue";
pub const TERMINAL_GREEN: &'static str = "terminal.green";
pub const TERMINAL_YELLOW: &'static str = "terminal.yellow";
pub const TERMINAL_BLACK: &'static str = "terminal.black";
pub const TERMINAL_WHITE: &'static str = "terminal.white";
pub const TERMINAL_CYAN: &'static str = "terminal.cyan";
pub const TERMINAL_MAGENTA: &'static str = "terminal.magenta";
pub const TERMINAL_BRIGHT_RED: &'static str = "terminal.bright_red";
pub const TERMINAL_BRIGHT_BLUE: &'static str = "terminal.bright_blue";
pub const TERMINAL_BRIGHT_GREEN: &'static str = "terminal.bright_green";
pub const TERMINAL_BRIGHT_YELLOW: &'static str = "terminal.bright_yellow";
pub const TERMINAL_BRIGHT_BLACK: &'static str = "terminal.bright_black";
pub const TERMINAL_BRIGHT_WHITE: &'static str = "terminal.bright_white";
pub const TERMINAL_BRIGHT_CYAN: &'static str = "terminal.bright_cyan";
pub const TERMINAL_BRIGHT_MAGENTA: &'static str = "terminal.bright_magenta";
pub const PALETTE_BACKGROUND: &'static str = "palette.background";
pub const PALETTE_FOREGROUND: &'static str = "palette.foreground";
pub const PALETTE_CURRENT_BACKGROUND: &'static str =
"palette.current.background";
pub const PALETTE_CURRENT_FOREGROUND: &'static str =
"palette.current.foreground";
pub const COMPLETION_BACKGROUND: &'static str = "completion.background";
pub const COMPLETION_CURRENT: &'static str = "completion.current";
pub const HOVER_BACKGROUND: &'static str = "hover.background";
pub const ACTIVITY_BACKGROUND: &'static str = "activity.background";
pub const ACTIVITY_CURRENT: &'static str = "activity.current";
pub const DEBUG_BREAKPOINT: &'static str = "debug.breakpoint";
pub const DEBUG_BREAKPOINT_HOVER: &'static str = "debug.breakpoint.hover";
pub const TOOLTIP_BACKGROUND: &'static str = "tooltip.background";
pub const TOOLTIP_FOREGROUND: &'static str = "tooltip.foreground";
pub const PANEL_BACKGROUND: &'static str = "panel.background";
pub const PANEL_FOREGROUND: &'static str = "panel.foreground";
pub const PANEL_FOREGROUND_DIM: &'static str = "panel.foreground.dim";
pub const PANEL_CURRENT_BACKGROUND: &'static str = "panel.current.background";
pub const PANEL_CURRENT_FOREGROUND: &'static str = "panel.current.foreground";
pub const PANEL_CURRENT_FOREGROUND_DIM: &'static str =
"panel.current.foreground.dim";
pub const PANEL_HOVERED_BACKGROUND: &'static str = "panel.hovered.background";
pub const PANEL_HOVERED_ACTIVE_BACKGROUND: &'static str =
"panel.hovered.active.background";
pub const PANEL_HOVERED_FOREGROUND: &'static str = "panel.hovered.foreground";
pub const PANEL_HOVERED_FOREGROUND_DIM: &'static str =
"panel.hovered.foreground.dim";
pub const STATUS_BACKGROUND: &'static str = "status.background";
pub const STATUS_FOREGROUND: &'static str = "status.foreground";
pub const STATUS_MODAL_NORMAL_BACKGROUND: &'static str =
"status.modal.normal.background";
pub const STATUS_MODAL_NORMAL_FOREGROUND: &'static str =
"status.modal.normal.foreground";
pub const STATUS_MODAL_INSERT_BACKGROUND: &'static str =
"status.modal.insert.background";
pub const STATUS_MODAL_INSERT_FOREGROUND: &'static str =
"status.modal.insert.foreground";
pub const STATUS_MODAL_VISUAL_BACKGROUND: &'static str =
"status.modal.visual.background";
pub const STATUS_MODAL_VISUAL_FOREGROUND: &'static str =
"status.modal.visual.foreground";
pub const STATUS_MODAL_TERMINAL_BACKGROUND: &'static str =
"status.modal.terminal.background";
pub const STATUS_MODAL_TERMINAL_FOREGROUND: &'static str =
"status.modal.terminal.foreground";
pub const MARKDOWN_BLOCKQUOTE: &'static str = "markdown.blockquote";
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/benches/visual_line.rs | lapce-app/benches/visual_line.rs | use std::{cell::RefCell, collections::HashMap, rc::Rc, sync::Arc};
use criterion::{Criterion, black_box, criterion_group, criterion_main};
use floem::{
reactive::Scope,
text::{Attrs, AttrsList, FamilyOwned, TextLayout, Wrap},
views::editor::{
layout::TextLayoutLine,
phantom_text::PhantomTextLine,
visual_line::{
ConfigId, FontSizeCacheId, LineFontSizeProvider, Lines, ResolvedWrap,
TextLayoutProvider, VLine,
},
},
};
use lapce_core::{
buffer::rope_text::{RopeText, RopeTextRef},
cursor::CursorAffinity,
};
use lapce_xi_rope::Rope;
const FONT_SIZE: usize = 12;
// TODO: use the editor data view structures!
struct TLProv<'a> {
text: &'a Rope,
phantom: HashMap<usize, PhantomTextLine>,
font_family: Vec<FamilyOwned>,
has_multiline_phantom: bool,
}
impl TextLayoutProvider for TLProv<'_> {
fn text(&self) -> Rope {
self.text.clone()
}
// An implementation relatively close to the actual new text layout impl but simplified.
// TODO(minor): It would be nice to just use the same impl as view's
fn new_text_layout(
&self,
line: usize,
font_size: usize,
wrap: ResolvedWrap,
) -> Arc<TextLayoutLine> {
let rope_text = RopeTextRef::new(self.text);
let line_content_original = rope_text.line_content(line);
// Get the line content with newline characters replaced with spaces
// and the content without the newline characters
let (line_content, _line_content_original) =
if let Some(s) = line_content_original.strip_suffix("\r\n") {
(
format!("{s} "),
&line_content_original[..line_content_original.len() - 2],
)
} else if let Some(s) = line_content_original.strip_suffix('\n') {
(
format!("{s} ",),
&line_content_original[..line_content_original.len() - 1],
)
} else {
(
line_content_original.to_string(),
&line_content_original[..],
)
};
let phantom_text = self.phantom.get(&line).cloned().unwrap_or_default();
let line_content = phantom_text.combine_with_text(&line_content);
let attrs = Attrs::new()
.family(&self.font_family)
.font_size(font_size as f32);
let mut attrs_list = AttrsList::new(attrs.clone());
// We don't do line styles, since they aren't relevant
// Apply phantom text specific styling
for (offset, size, col, phantom) in phantom_text.offset_size_iter() {
let start = col + offset;
let end = start + size;
let mut attrs = attrs.clone();
if let Some(fg) = phantom.fg {
attrs = attrs.color(fg);
}
if let Some(phantom_font_size) = phantom.font_size {
attrs = attrs.font_size(phantom_font_size.min(font_size) as f32);
}
attrs_list.add_span(start..end, attrs);
// if let Some(font_family) = phantom.font_family.clone() {
// layout_builder = layout_builder.range_attribute(
// start..end,
// TextAttribute::FontFamily(font_family),
// );
// }
}
let mut text_layout = TextLayout::new();
text_layout.set_wrap(Wrap::Word);
match wrap {
// We do not have to set the wrap mode if we do not set the width
ResolvedWrap::None => {}
ResolvedWrap::Column(_col) => todo!(),
ResolvedWrap::Width(px) => {
text_layout.set_size(px, f32::MAX);
}
}
text_layout.set_text(&line_content, attrs_list, None);
// skip phantom text background styling because it doesn't shift positions
// skip severity styling
// skip diagnostic background styling
Arc::new(TextLayoutLine {
extra_style: Vec::new(),
text: text_layout,
whitespaces: None,
indent: 0.0,
phantom_text: PhantomTextLine::default(),
})
}
fn before_phantom_col(&self, line: usize, col: usize) -> usize {
if let Some(phantom) = self.phantom.get(&line) {
phantom.before_col(col)
} else {
col
}
}
fn has_multiline_phantom(&self) -> bool {
self.has_multiline_phantom
}
}
struct TestFontSize;
impl LineFontSizeProvider for TestFontSize {
fn font_size(&self, _line: usize) -> usize {
FONT_SIZE
}
fn cache_id(&self) -> FontSizeCacheId {
0
}
}
fn make_lines(text: &Rope, wrap: ResolvedWrap, init: bool) -> (TLProv<'_>, Lines) {
make_lines_ph(text, wrap, init, HashMap::new(), false)
}
fn make_lines_ph(
text: &Rope,
wrap: ResolvedWrap,
init: bool,
ph: HashMap<usize, PhantomTextLine>,
has_multiline_phantom: bool,
) -> (TLProv<'_>, Lines) {
// let wrap = Wrap::Word;
// let r_wrap = ResolvedWrap::Width(width);
let font_sizes = TestFontSize;
let text = TLProv {
text,
phantom: ph,
font_family: Vec::new(),
has_multiline_phantom,
};
let cx = Scope::new();
let lines = Lines::new(cx, RefCell::new(Rc::new(font_sizes)));
lines.set_wrap(wrap);
if init {
lines.init_all(0, ConfigId::new(0, 0), &text, true);
}
(text, lines)
}
fn medium_rope() -> Rope {
let mut text = String::new();
// TODO: use some actual file's content.
for i in 0..3000 {
let content = if i % 2 == 0 {
"This is a roughly typical line of text\n"
} else if i % 3 == 0 {
"\n"
} else {
"A short line\n"
};
text.push_str(content);
}
Rope::from(&text)
}
fn visual_line(c: &mut Criterion) {
let text = medium_rope();
// Should be very fast because it is trivially linear and there's no multiline phantom
c.bench_function("last vline (uninit)", |b| {
let (text_prov, lines) = make_lines(&text, ResolvedWrap::None, false);
b.iter(|| {
lines.clear_last_vline();
let last_vline = lines.last_vline(&text_prov);
black_box(last_vline);
})
});
// Unrealistic since the user will very rarely have all of the lines initialized
// Should still be fast because there's no wrapping or multiline phantom text
c.bench_function("last vline (all, no wrapping)", |b| {
let (text_prov, lines) = make_lines(&text, ResolvedWrap::None, true);
b.iter(|| {
lines.clear_last_vline();
let last_vline = lines.last_vline(&text_prov);
let _val = black_box(last_vline);
})
});
// TODO: we could precompute line count on the text layout?
// Unrealistic since the user will very rarely have all of the lines initialized
// Still decently fast, though. <1ms
c.bench_function("last vline (all, wrapping)", |b| {
let width = 100.0;
let (text_prov, lines) = make_lines(&text, ResolvedWrap::Width(width), true);
b.iter(|| {
// This should clear any other caching mechanisms that get added
lines.clear_last_vline();
let last_vline = lines.last_vline(&text_prov);
let _val = black_box(last_vline);
})
});
// Q: This seems like 1/5th the cost of last vline despite only being half the lines..
c.bench_function("vline of offset (all, wrapping)", |b| {
let width = 100.0;
let (text_prov, lines) = make_lines(&text, ResolvedWrap::Width(width), true);
// Not past the middle. If we were past the middle then it'd be just benching last vline
// calculation, which is admittedly relatively similar to this.
let offset = 1450;
b.iter(|| {
// This should clear any other caching mechanisms that get added
lines.clear_last_vline();
let vline =
lines.vline_of_offset(&text_prov, offset, CursorAffinity::Backward);
let _val = black_box(vline);
})
});
c.bench_function("offset of vline (all, wrapping)", |b| {
let width = 100.0;
let (text_prov, lines) = make_lines(&text, ResolvedWrap::Width(width), true);
let vline = VLine(3300);
b.iter(|| {
// This should clear any other caching mechanisms that get added
lines.clear_last_vline();
let offset = lines.offset_of_vline(&text_prov, vline);
let _val = black_box(offset);
})
});
// TODO: when we have the reverse search of vline for offset, we should have a separate instance where the last vline isn't cached, which would give us a range of 'worst case' (never reused, have to recopmute it everytime) and 'best case' (always reused)
// TODO: bench common operations, like a single line changing or the (equivalent of) cache rev
// updating.
}
criterion_group!(benches, visual_line);
criterion_main!(benches);
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-core/build.rs | lapce-core/build.rs | use std::{env, fs, path::Path};
use anyhow::Result;
#[derive(Debug)]
struct ReleaseInfo {
version: String,
branch: String,
}
fn main() -> Result<()> {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed=../.git/HEAD");
println!("cargo:rerun-if-env-changed=CARGO_PKG_VERSION");
println!("cargo:rerun-if-env-changed=CARGO_FEATURE_DISTRIBUTION");
println!("cargo:rerun-if-env-changed=RELEASE_TAG_NAME");
let release_info = get_info()?;
// Print info to terminal during compilation
println!("cargo::warning=Compiling meta: {release_info:?}");
let meta_file = Path::new(&env::var("OUT_DIR")?).join("meta.rs");
let ReleaseInfo { version, branch } = release_info;
#[rustfmt::skip]
let meta = format!(r#"
pub const NAME: &str = "Lapce-{branch}";
pub const VERSION: &str = "{version}";
pub const RELEASE: ReleaseType = ReleaseType::{branch};
"#);
fs::write(meta_file, meta)?;
Ok(())
}
fn get_info() -> Result<ReleaseInfo> {
// CARGO_PKG_* are always available, even in build scripts
let cargo_tag = env!("CARGO_PKG_VERSION");
// For any downstream that complains about us doing magic
if env::var("CARGO_FEATURE_DISTRIBUTION").is_ok() {
return Ok(ReleaseInfo {
version: cargo_tag.to_string(),
branch: String::from("Stable"),
});
}
let release_info = {
let release_tag = env::var("RELEASE_TAG_NAME").unwrap_or_default();
if release_tag.starts_with('v') {
ReleaseInfo {
version: cargo_tag.to_string(),
branch: "Stable".to_string(),
}
} else {
#[cfg(not(debug_assertions))]
let release = "Nightly";
#[cfg(debug_assertions)]
let release = "Debug";
let tag = format!(
"{cargo_tag}+{release}.{}",
get_head().unwrap_or("unknown".to_string())
);
ReleaseInfo {
version: tag,
branch: release.to_string(),
}
}
};
Ok(release_info)
}
#[cfg(not(target_os = "linux"))]
fn get_head() -> Option<String> {
let repo = match git2::Repository::discover(format!(
"{}/..",
env::var("CARGO_MANIFEST_DIR").ok()?
)) {
Ok(v) => v,
Err(err) => {
println!("cargo::warning=Failed to obtain git repo: {err}");
return None;
}
};
let reference = match repo.head() {
Ok(v) => v,
Err(err) => {
println!("cargo::warning=Failed to obtain head: {err}");
return None;
}
};
let commit = reference.target();
println!("cargo::warning=Commit found: {commit:?}");
commit.map(|s| s.to_string().split_at(7).0.to_owned())
}
#[cfg(target_os = "linux")]
fn get_head() -> Option<String> {
let cmd = std::process::Command::new("git")
.args(["show", "--pretty=format:%h", "--no-patch"])
.output()
.ok()?;
let commit = String::from_utf8_lossy(&cmd.stdout);
let commit = commit.trim();
Some(commit.to_string())
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-core/src/lib.rs | lapce-core/src/lib.rs | #![allow(clippy::manual_clamp)]
pub mod directory;
pub mod encoding;
pub mod language;
pub mod lens;
pub mod meta;
pub mod rope_text_pos;
pub mod style;
pub mod syntax;
// This is primarily being re-exported to avoid changing every single usage
// in lapce-app. We should probably remove this at some point.
pub use floem_editor_core::*;
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-core/src/rope_text_pos.rs | lapce-core/src/rope_text_pos.rs | use floem_editor_core::buffer::rope_text::RopeText;
use lsp_types::Position;
use crate::encoding::{offset_utf8_to_utf16, offset_utf16_to_utf8};
pub trait RopeTextPosition: RopeText {
/// Converts a UTF8 offset to a UTF16 LSP position
/// Returns None if it is not a valid UTF16 offset
fn offset_to_position(&self, offset: usize) -> Position {
let (line, col) = self.offset_to_line_col(offset);
let line_offset = self.offset_of_line(line);
let utf16_col =
offset_utf8_to_utf16(self.char_indices_iter(line_offset..), col);
Position {
line: line as u32,
character: utf16_col as u32,
}
}
fn offset_of_position(&self, pos: &Position) -> usize {
let (line, column) = self.position_to_line_col(pos);
self.offset_of_line_col(line, column)
}
fn position_to_line_col(&self, pos: &Position) -> (usize, usize) {
let line = pos.line as usize;
let line_offset = self.offset_of_line(line);
let column = offset_utf16_to_utf8(
self.char_indices_iter(line_offset..),
pos.character as usize,
);
(line, column)
}
}
impl<T: RopeText> RopeTextPosition for T {}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-core/src/language.rs | lapce-core/src/language.rs | use std::{
collections::{HashMap, HashSet, hash_map::Entry},
fmt::Write,
path::Path,
str::FromStr,
};
use lapce_rpc::style::{LineStyle, Style};
use once_cell::sync::Lazy;
use regex::Regex;
use strum_macros::{AsRefStr, Display, EnumMessage, EnumString, IntoStaticStr};
use tracing::{Level, event};
use tree_sitter::{Point, TreeCursor};
use crate::{
directory::Directory,
syntax::highlight::{HighlightConfiguration, HighlightIssue},
};
#[remain::sorted]
pub enum Indent {
Space(u8),
Tab,
}
impl Indent {
const fn tab() -> &'static str {
Indent::Tab.as_str()
}
const fn space(count: u8) -> &'static str {
Indent::Space(count).as_str()
}
const fn as_str(&self) -> &'static str {
match self {
Indent::Tab => "\u{0009}",
#[allow(clippy::wildcard_in_or_patterns)]
Indent::Space(v) => match v {
2 => "\u{0020}\u{0020}",
4 => "\u{0020}\u{0020}\u{0020}\u{0020}",
8 | _ => {
"\u{0020}\u{0020}\u{0020}\u{0020}\u{0020}\u{0020}\u{0020}\u{0020}"
}
},
}
}
}
const DEFAULT_CODE_GLANCE_LIST: &[&str] = &["source_file"];
const DEFAULT_CODE_GLANCE_IGNORE_LIST: &[&str] = &["source_file"];
#[macro_export]
macro_rules! comment_properties {
() => {
CommentProperties {
single_line_start: None,
single_line_end: None,
multi_line_start: None,
multi_line_end: None,
multi_line_prefix: None,
}
};
($s:expr) => {
CommentProperties {
single_line_start: Some($s),
single_line_end: None,
multi_line_start: None,
multi_line_end: None,
multi_line_prefix: None,
}
};
($s:expr, $e:expr) => {
CommentProperties {
single_line_start: Some($s),
single_line_end: Some($e),
multi_line_start: None,
multi_line_end: None,
multi_line_prefix: None,
}
};
($sl_s:expr, $sl_e:expr, $ml_s:expr, $ml_e:expr) => {
CommentProperties {
single_line_start: Some($sl_s),
single_line_end: Some($sl_e),
multi_line_start: Some($sl_s),
multi_line_end: None,
multi_line_prefix: Some($sl_e),
}
};
}
#[derive(Eq, PartialEq, Hash, Clone, Copy, Debug, PartialOrd, Ord, Default)]
pub struct SyntaxProperties {
/// An extra check to make sure that the array elements are in the correct order.
/// If this id does not match the enum value, a panic will happen with a debug assertion message.
id: LapceLanguage,
/// All tokens that can be used for comments in language
comment: CommentProperties,
/// The indent unit.
/// " " for bash, " " for rust, for example.
indent: &'static str,
/// Filenames that belong to this language
/// `["Dockerfile"]` for Dockerfile, `[".editorconfig"]` for EditorConfig
files: &'static [&'static str],
/// File name extensions to determine the language.
/// `["py"]` for python, `["rs"]` for rust, for example.
extensions: &'static [&'static str],
/// Tree-sitter properties
tree_sitter: TreeSitterProperties,
}
#[derive(Eq, PartialEq, Hash, Clone, Copy, Debug, PartialOrd, Ord, Default)]
struct TreeSitterProperties {
/// the grammar name that's in the grammars folder
grammar: Option<&'static str>,
/// the grammar fn name
grammar_fn: Option<&'static str>,
/// the query folder name
query: Option<&'static str>,
/// Preface: Originally this feature was called "Code Lens", which is not
/// an LSP "Code Lens". It is renamed to "Code Glance", below doc text is
/// left unchanged.
///
/// Lists of tree-sitter node types that control how code lenses are built.
/// The first is a list of nodes that should be traversed and included in
/// the lens, along with their children. The second is a list of nodes that
/// should be excluded from the lens, though they will still be traversed.
/// See `walk_tree` for more details.
///
/// The tree-sitter playground may be useful when creating these lists:
/// https://tree-sitter.github.io/tree-sitter/playground
///
/// If unsure, use `DEFAULT_CODE_GLANCE_LIST` and
/// `DEFAULT_CODE_GLANCE_IGNORE_LIST`.
code_glance: (&'static [&'static str], &'static [&'static str]),
/// the tree-sitter tag names that can be put in sticky headers
sticky_headers: &'static [&'static str],
}
impl TreeSitterProperties {
const DEFAULT: Self = Self {
grammar: None,
grammar_fn: None,
query: None,
code_glance: (DEFAULT_CODE_GLANCE_LIST, DEFAULT_CODE_GLANCE_IGNORE_LIST),
sticky_headers: &[],
};
}
#[derive(Eq, PartialEq, Hash, Clone, Copy, Debug, PartialOrd, Ord, Default)]
struct CommentProperties {
/// Single line comment token used when commenting out one line.
/// "#" for python, "//" for rust for example.
single_line_start: Option<&'static str>,
single_line_end: Option<&'static str>,
/// Multi line comment token used when commenting a selection of lines.
/// "#" for python, "//" for rust for example.
multi_line_start: Option<&'static str>,
multi_line_end: Option<&'static str>,
multi_line_prefix: Option<&'static str>,
}
/// NOTE: Keep the enum variants "fieldless" so they can cast to usize as array
/// indices into the LANGUAGES array. See method `LapceLanguage::properties`.
///
/// Do not assign values to the variants because the number of variants and
/// number of elements in the LANGUAGES array change as different features
/// selected by the cargo build command.
#[derive(
Eq,
PartialEq,
Ord,
PartialOrd,
Hash,
Clone,
Copy,
Debug,
Display,
AsRefStr,
IntoStaticStr,
EnumString,
EnumMessage,
Default,
)]
#[strum(ascii_case_insensitive)]
#[remain::sorted]
pub enum LapceLanguage {
// Do not move
#[remain::unsorted]
#[default]
#[strum(message = "Plain Text")]
PlainText,
#[strum(message = "Ada")]
Ada,
#[strum(message = "Adl")]
Adl,
#[strum(message = "Agda")]
Agda,
#[strum(message = "Astro")]
Astro,
#[strum(message = "Bash")]
Bash,
#[strum(message = "Bass")]
Bass,
#[strum(message = "Beancount")]
Beancount,
#[strum(message = "Bibtex")]
Bibtex,
#[strum(message = "Bitbake")]
Bitbake,
#[strum(message = "Blade")]
Blade,
#[strum(message = "C")]
C,
#[strum(message = "Clojure")]
Clojure,
#[strum(message = "CMake")]
Cmake,
#[strum(message = "Comment")]
Comment,
#[strum(message = "C++")]
Cpp,
#[strum(message = "C#")]
Csharp,
#[strum(message = "CSS")]
Css,
#[strum(message = "Cue")]
Cue,
#[strum(message = "D")]
D,
#[strum(message = "Dart")]
Dart,
#[strum(message = "Dhall")]
Dhall,
#[strum(message = "Diff")]
Diff,
#[strum(message = "Dockerfile")]
Dockerfile,
#[strum(message = "Dot")]
Dot,
#[strum(message = "Elixir")]
Elixir,
#[strum(message = "Elm")]
Elm,
#[strum(message = "Erlang")]
Erlang,
#[strum(message = "Fish Shell")]
Fish,
#[strum(message = "Fluent")]
Fluent,
#[strum(message = "Forth")]
Forth,
#[strum(message = "Fortran")]
Fortran,
#[strum(message = "F#")]
FSharp,
#[strum(message = "Gitattributes")]
Gitattributes,
#[strum(message = "Git (commit)")]
GitCommit,
#[strum(message = "Git (config)")]
GitConfig,
#[strum(message = "Git (rebase)")]
GitRebase,
#[strum(message = "Gleam")]
Gleam,
#[strum(message = "Glimmer")]
Glimmer,
#[strum(message = "GLSL")]
Glsl,
#[strum(message = "Gn")]
Gn,
#[strum(message = "Go")]
Go,
#[strum(message = "Go (go.mod)")]
GoMod,
#[strum(message = "Go (template)")]
GoTemplate,
#[strum(message = "Go (go.work)")]
GoWork,
#[strum(message = "GraphQL")]
GraphQl,
#[strum(message = "Groovy")]
Groovy,
#[strum(message = "Hare")]
Hare,
#[strum(message = "Haskell")]
Haskell,
#[strum(message = "Haxe")]
Haxe,
#[strum(message = "HCL")]
Hcl,
#[strum(message = "Hosts file (/etc/hosts)")]
Hosts,
#[strum(message = "HTML")]
Html,
#[strum(message = "INI")]
Ini,
#[strum(message = "Java")]
Java,
#[strum(message = "JavaScript")]
Javascript,
#[strum(message = "JSDoc")]
Jsdoc,
#[strum(message = "JSON")]
Json,
#[strum(message = "JSON5")]
Json5,
#[strum(message = "Jsonnet")]
Jsonnet,
#[strum(message = "JavaScript React")]
Jsx,
#[strum(message = "Julia")]
Julia,
#[strum(message = "Just")]
Just,
#[strum(message = "KDL")]
Kdl,
#[strum(message = "Kotlin")]
Kotlin,
#[strum(message = "Kotlin Build Script")]
KotlinBuildScript,
#[strum(message = "LaTeX")]
Latex,
#[strum(message = "Linker Script")]
Ld,
#[strum(message = "LLVM")]
Llvm,
#[strum(message = "LLVM MIR")]
LlvmMir,
#[strum(message = "Log")]
Log,
#[strum(message = "Lua")]
Lua,
#[strum(message = "Makefile")]
Make,
#[strum(message = "Markdown")]
Markdown,
#[strum(serialize = "markdown.inline")]
MarkdownInline,
#[strum(message = "Meson")]
Meson,
#[strum(message = "NASM")]
Nasm,
#[strum(message = "Nix")]
Nix,
#[strum(message = "Nu (nushell)")]
Nushell,
#[strum(message = "Ocaml")]
Ocaml,
#[strum(serialize = "ocaml.interface")]
OcamlInterface,
#[strum(message = "Odin")]
Odin,
#[strum(message = "OpenCL")]
OpenCl,
#[strum(message = "Pascal")]
Pascal,
#[strum(message = "Password file (/etc/passwd)")]
Passwd,
#[strum(message = "PEM (RFC 1422)")]
Pem,
#[strum(message = "PHP")]
Php,
#[strum(message = "PKL")]
Pkl,
#[strum(message = "PowerShell")]
PowerShell,
#[strum(message = "Prisma")]
Prisma,
#[strum(message = "Proto")]
ProtoBuf,
#[strum(message = "Python")]
Python,
#[strum(message = "QL")]
Ql,
#[strum(message = "R")]
R,
#[strum(message = "RCL")]
Rcl,
#[strum(message = "RegEx")]
Regex,
#[strum(message = "REGO")]
Rego,
#[strum(message = "RON (Rust Object Notation)")]
Ron,
#[strum(message = "Rst")]
Rst,
#[strum(message = "Ruby")]
Ruby,
#[strum(message = "Rust")]
Rust,
#[strum(message = "Scala")]
Scala,
#[strum(message = "Scheme")]
Scheme,
#[strum(message = "SCSS")]
Scss,
#[strum(message = "Shell Script (POSIX)")]
ShellScript,
#[strum(message = "Smithy")]
Smithy,
#[strum(message = "SQL")]
Sql,
#[strum(message = "SSH Config")]
SshClientConfig,
#[strum(message = "Strace")]
Strace,
#[strum(message = "Svelte")]
Svelte,
#[strum(message = "Sway")]
Sway,
#[strum(message = "Swift")]
Swift,
#[strum(message = "TCL")]
Tcl,
#[strum(message = "TOML")]
Toml,
#[strum(message = "Tsx")]
Tsx,
#[strum(message = "TypeScript")]
Typescript,
#[strum(message = "Typst")]
Typst,
#[strum(message = "Verilog")]
Verilog,
#[strum(message = "Vue")]
Vue,
#[strum(message = "WASM")]
Wasm,
#[strum(message = "WGSL")]
Wgsl,
#[strum(message = "WIT")]
Wit,
#[strum(message = "XML")]
Xml,
#[strum(message = "YAML")]
Yaml,
#[strum(message = "Zig")]
Zig,
}
/// NOTE: Elements in the array must be in the same order as the enum variants of
/// `LapceLanguage` as they will be accessed using the enum variants as indices.
const LANGUAGES: &[SyntaxProperties] = &[
// Undetected/unmatched fallback or just plain file
SyntaxProperties {
id: LapceLanguage::PlainText,
indent: Indent::tab(),
files: &[],
extensions: &["txt"],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
// Languages
SyntaxProperties {
id: LapceLanguage::Ada,
indent: Indent::tab(),
files: &[],
extensions: &[],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Adl,
indent: Indent::tab(),
files: &[],
extensions: &[],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Agda,
indent: Indent::tab(),
files: &[],
extensions: &[],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Astro,
indent: Indent::tab(),
files: &[],
extensions: &[],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Bash,
indent: Indent::space(2),
files: &[],
extensions: &["bash", "sh"],
comment: comment_properties!("#"),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Bass,
indent: Indent::tab(),
files: &[],
extensions: &[],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Beancount,
indent: Indent::tab(),
files: &[],
extensions: &[],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Bibtex,
indent: Indent::tab(),
files: &[],
extensions: &[],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Bitbake,
indent: Indent::tab(),
files: &[],
extensions: &[],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Blade,
indent: Indent::tab(),
files: &[],
extensions: &[],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::C,
indent: Indent::space(4),
files: &[],
extensions: &["c", "h"],
comment: comment_properties!("//"),
tree_sitter: TreeSitterProperties {
grammar: None,
grammar_fn: None,
query: None,
code_glance: (DEFAULT_CODE_GLANCE_LIST, DEFAULT_CODE_GLANCE_IGNORE_LIST),
sticky_headers: &["function_definition", "struct_specifier"],
},
},
SyntaxProperties {
id: LapceLanguage::Clojure,
indent: Indent::space(2),
files: &[],
extensions: &[
"clj",
"edn",
"cljs",
"cljc",
"cljd",
"edn",
"bb",
"clj_kondo",
],
comment: comment_properties!(";"),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Cmake,
indent: Indent::space(2),
files: &["cmakelists"],
extensions: &["cmake"],
comment: comment_properties!("#"),
tree_sitter: TreeSitterProperties {
grammar: None,
grammar_fn: None,
query: None,
code_glance: (DEFAULT_CODE_GLANCE_LIST, DEFAULT_CODE_GLANCE_IGNORE_LIST),
sticky_headers: &["function_definition"],
},
},
SyntaxProperties {
id: LapceLanguage::Comment,
indent: Indent::tab(),
files: &[],
extensions: &[],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Cpp,
indent: Indent::space(4),
files: &[],
extensions: &["cpp", "cxx", "cc", "c++", "hpp", "hxx", "hh", "h++"],
comment: comment_properties!("//"),
tree_sitter: TreeSitterProperties {
grammar: None,
grammar_fn: None,
query: None,
code_glance: (DEFAULT_CODE_GLANCE_LIST, DEFAULT_CODE_GLANCE_IGNORE_LIST),
sticky_headers: &[
"function_definition",
"class_specifier",
"struct_specifier",
],
},
},
SyntaxProperties {
id: LapceLanguage::Csharp,
indent: Indent::space(2),
files: &[],
extensions: &["cs", "csx"],
comment: comment_properties!("#"),
tree_sitter: TreeSitterProperties {
grammar: None,
grammar_fn: None,
query: None,
code_glance: (DEFAULT_CODE_GLANCE_LIST, DEFAULT_CODE_GLANCE_IGNORE_LIST),
sticky_headers: &[
"interface_declaration",
"class_declaration",
"enum_declaration",
"struct_declaration",
"record_declaration",
"record_struct_declaration",
"namespace_declaration",
"constructor_declaration",
"destructor_declaration",
"method_declaration",
],
},
},
SyntaxProperties {
id: LapceLanguage::Css,
indent: Indent::space(2),
files: &[],
extensions: &["css"],
comment: comment_properties!("/*", "*/"),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Cue,
indent: Indent::tab(),
files: &[],
extensions: &[],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::D,
indent: Indent::space(4),
files: &[],
extensions: &["d", "di", "dlang"],
comment: CommentProperties {
single_line_start: Some("//"),
single_line_end: None,
multi_line_start: Some("/+"),
multi_line_prefix: None,
multi_line_end: Some("+/"),
},
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Dart,
indent: Indent::space(2),
files: &[],
extensions: &["dart"],
comment: CommentProperties {
single_line_start: Some("//"),
single_line_end: None,
multi_line_start: Some("/*"),
multi_line_prefix: None,
multi_line_end: Some("*/"),
},
tree_sitter: TreeSitterProperties {
grammar: None,
grammar_fn: None,
query: None,
code_glance: (
&["program", "class_definition"],
&[
"program",
"import_or_export",
"comment",
"documentation_comment",
],
),
sticky_headers: &["class_definition"],
},
},
SyntaxProperties {
id: LapceLanguage::Dhall,
indent: Indent::tab(),
files: &[],
extensions: &[],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Diff,
indent: Indent::tab(),
files: &[],
extensions: &["diff", "patch"],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Dockerfile,
indent: Indent::space(2),
files: &["Dockerfile", "Containerfile"],
extensions: &["containerfile", "dockerfile"],
comment: comment_properties!("#"),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Dot,
indent: Indent::tab(),
files: &[],
extensions: &[],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Elixir,
indent: Indent::space(2),
files: &[],
extensions: &["ex", "exs", "eex", "heex", "sface"],
comment: comment_properties!("#"),
tree_sitter: TreeSitterProperties {
grammar: None,
grammar_fn: None,
query: None,
code_glance: (DEFAULT_CODE_GLANCE_LIST, DEFAULT_CODE_GLANCE_IGNORE_LIST),
sticky_headers: &["do_block"],
},
},
SyntaxProperties {
id: LapceLanguage::Elm,
indent: Indent::space(4),
files: &[],
extensions: &["elm"],
comment: comment_properties!("#"),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Erlang,
indent: Indent::space(4),
files: &[],
extensions: &["erl", "hrl"],
comment: comment_properties!("%"),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::FSharp,
indent: Indent::tab(),
files: &[],
extensions: &[],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Fish,
indent: Indent::tab(),
files: &[],
extensions: &["fish"],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Fluent,
indent: Indent::tab(),
files: &[],
extensions: &[],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Forth,
indent: Indent::tab(),
files: &[],
extensions: &[],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Fortran,
indent: Indent::tab(),
files: &[],
extensions: &[],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Gitattributes,
indent: Indent::tab(),
files: &[],
extensions: &[],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::GitCommit,
indent: Indent::tab(),
files: &[],
extensions: &[],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::GitConfig,
indent: Indent::tab(),
files: &[".gitconfig", ".git/config"],
extensions: &[],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::GitRebase,
indent: Indent::tab(),
files: &[],
extensions: &[],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Gleam,
indent: Indent::tab(),
files: &[],
extensions: &[],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Glimmer,
indent: Indent::space(2),
files: &[],
extensions: &["hbs"],
comment: comment_properties!("{{!", "!}}"),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Glsl,
indent: Indent::space(2),
files: &[],
extensions: &[
"glsl", "cs", "vs", "gs", "fs", "csh", "vsh", "gsh", "fsh", "cshader",
"vshader", "gshader", "fshader", "comp", "vert", "geom", "frag", "tesc",
"tese", "mesh", "task", "rgen", "rint", "rahit", "rchit", "rmiss",
"rcall",
],
comment: comment_properties!("//"),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Gn,
indent: Indent::tab(),
files: &[],
extensions: &[],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Go,
indent: Indent::tab(),
files: &[],
extensions: &["go"],
comment: comment_properties!("//"),
tree_sitter: TreeSitterProperties {
grammar: None,
grammar_fn: None,
query: None,
code_glance: (
&[
"source_file",
"type_declaration",
"type_spec",
"interface_type",
"method_spec_list",
],
&["source_file", "comment", "line_comment"],
),
sticky_headers: &[],
},
},
SyntaxProperties {
id: LapceLanguage::GoMod,
indent: Indent::tab(),
files: &[],
extensions: &[],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::GoTemplate,
indent: Indent::tab(),
files: &[],
extensions: &[],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::GoWork,
indent: Indent::tab(),
files: &[],
extensions: &[],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::GraphQl,
indent: Indent::tab(),
files: &[],
extensions: &[],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Groovy,
indent: Indent::tab(),
files: &[],
extensions: &[],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Hare,
indent: Indent::space(8),
files: &[],
extensions: &["ha"],
comment: comment_properties!("//"),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Haskell,
indent: Indent::space(2),
files: &[],
extensions: &["hs"],
comment: comment_properties!("--"),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Haxe,
indent: Indent::space(2),
files: &[],
extensions: &["hx"],
comment: comment_properties!("//"),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Hcl,
indent: Indent::space(2),
files: &[],
extensions: &["hcl", "tf"],
comment: comment_properties!("//"),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Hosts,
indent: Indent::tab(),
files: &[],
extensions: &[],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Html,
indent: Indent::space(4),
files: &[],
extensions: &["html", "htm"],
comment: comment_properties!("<!--", "-->"),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Ini,
indent: Indent::tab(),
files: &[],
extensions: &[],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Java,
indent: Indent::space(4),
files: &[],
extensions: &["java"],
comment: comment_properties!("//"),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Javascript,
indent: Indent::space(2),
files: &[],
extensions: &["js", "cjs", "mjs"],
comment: comment_properties!("//"),
tree_sitter: TreeSitterProperties {
grammar: None,
grammar_fn: None,
query: None,
code_glance: (&["source_file", "program"], &["source_file"]),
sticky_headers: &[],
},
},
SyntaxProperties {
id: LapceLanguage::Jsdoc,
indent: Indent::tab(),
files: &[],
extensions: &[],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Json,
indent: Indent::space(4),
files: &[],
extensions: &["json", "har"],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Json5,
indent: Indent::tab(),
files: &[],
extensions: &[],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Jsonnet,
indent: Indent::tab(),
files: &[],
extensions: &[],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Jsx,
indent: Indent::space(2),
files: &[],
extensions: &["jsx"],
comment: comment_properties!("//"),
tree_sitter: TreeSitterProperties {
grammar: Some("javascript"),
grammar_fn: Some("javascript"),
query: Some("jsx"),
code_glance: (&["source_file", "program"], &["source_file"]),
sticky_headers: &[],
},
},
SyntaxProperties {
id: LapceLanguage::Julia,
indent: Indent::space(4),
files: &[],
extensions: &["julia", "jl"],
comment: CommentProperties {
single_line_start: Some("#"),
single_line_end: None,
multi_line_start: Some("#="),
multi_line_prefix: None,
multi_line_end: Some("=#"),
},
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Just,
indent: Indent::tab(),
files: &["justfile", "Justfile", ".justfile", ".Justfile"],
extensions: &["just"],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Kdl,
indent: Indent::tab(),
files: &[],
extensions: &[],
comment: comment_properties!(),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Kotlin,
indent: Indent::space(2),
files: &[],
extensions: &["kt"],
comment: CommentProperties {
single_line_start: Some("//"),
single_line_end: None,
multi_line_start: Some("/*"),
multi_line_prefix: None,
multi_line_end: Some("*/"),
},
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::KotlinBuildScript,
indent: Indent::space(2),
files: &[],
extensions: &["kts"],
comment: CommentProperties {
single_line_start: Some("//"),
single_line_end: None,
multi_line_start: Some("/*"),
multi_line_prefix: None,
multi_line_end: Some("*/"),
},
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Latex,
indent: Indent::space(2),
files: &[],
extensions: &["tex"],
comment: comment_properties!("%"),
tree_sitter: TreeSitterProperties::DEFAULT,
},
SyntaxProperties {
id: LapceLanguage::Ld,
indent: Indent::tab(),
files: &[],
extensions: &[],
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | true |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-core/src/style.rs | lapce-core/src/style.rs | use std::str;
use lapce_rpc::style::{LineStyle, Style};
use lapce_xi_rope::{LinesMetric, Rope, spans::Spans};
pub const SCOPES: &[&str] = &[
"constant",
"type",
"type.builtin",
"property",
"comment",
"constructor",
"function",
"label",
"keyword",
"string",
"variable",
"variable.other.member",
"operator",
"attribute",
"escape",
"embedded",
"symbol",
"punctuation",
"punctuation.special",
"punctuation.delimiter",
"text",
"text.literal",
"text.title",
"text.uri",
"text.reference",
"string.escape",
"conceal",
"none",
"tag",
"markup.bold",
"markup.italic",
"markup.list",
"markup.quote",
"markup.heading",
"markup.link.url",
"markup.link.label",
"markup.link.text",
];
pub fn line_styles(
text: &Rope,
line: usize,
styles: &Spans<Style>,
) -> Vec<LineStyle> {
let max_line = text.measure::<LinesMetric>() + 1;
if line >= max_line {
return Vec::new();
}
let start_offset = text.offset_of_line(line);
let end_offset = text.offset_of_line(line + 1);
let line_styles: Vec<LineStyle> = styles
.iter_chunks(start_offset..end_offset)
.filter_map(|(iv, style)| {
let start = iv.start();
let end = iv.end();
if start > end_offset || end < start_offset {
None
} else {
let start = start.saturating_sub(start_offset);
let end = end - start_offset;
let style = style.clone();
Some(LineStyle { start, end, style })
}
})
.collect();
line_styles
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-core/src/meta.rs | lapce-core/src/meta.rs | #[derive(strum_macros::AsRefStr, PartialEq, Eq)]
pub enum ReleaseType {
Debug,
Stable,
Nightly,
}
include!(concat!(env!("OUT_DIR"), "/meta.rs"));
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-core/src/lens.rs | lapce-core/src/lens.rs | use std::mem;
use lapce_xi_rope::{
Cursor, Delta, Interval, Metric,
interval::IntervalBounds,
tree::{DefaultMetric, Leaf, Node, NodeInfo, TreeBuilder},
};
const MIN_LEAF: usize = 5;
const MAX_LEAF: usize = 10;
pub type LensNode = Node<LensInfo>;
#[derive(Clone)]
pub struct Lens(LensNode);
#[derive(Clone, Debug)]
pub struct LensInfo(usize);
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct LensData {
len: usize,
line_height: usize,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct LensLeaf {
len: usize,
data: Vec<LensData>,
total_height: usize,
}
pub struct LensIter<'a> {
cursor: Cursor<'a, LensInfo>,
end: usize,
}
impl Lens {
pub fn len(&self) -> usize {
self.0.len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn line_of_height(&self, height: usize) -> usize {
let max_height = self.0.count::<LensMetric>(self.0.len());
if height >= max_height {
return self.0.len();
}
self.0.count_base_units::<LensMetric>(height)
}
pub fn height_of_line(&self, line: usize) -> usize {
let line = self.0.len().min(line);
self.0.count::<LensMetric>(line)
}
pub fn iter(&self) -> LensIter<'_> {
LensIter {
cursor: Cursor::new(&self.0, 0),
end: self.len(),
}
}
pub fn iter_chunks<I: IntervalBounds>(&self, range: I) -> LensIter<'_> {
let Interval { start, end } = range.into_interval(self.len());
LensIter {
cursor: Cursor::new(&self.0, start),
end,
}
}
pub fn apply_delta<M: NodeInfo>(&mut self, _delta: &Delta<M>) {}
}
impl NodeInfo for LensInfo {
type L = LensLeaf;
fn accumulate(&mut self, other: &Self) {
self.0 += other.0;
}
fn compute_info(l: &LensLeaf) -> LensInfo {
LensInfo(l.total_height)
}
}
impl Leaf for LensLeaf {
fn len(&self) -> usize {
self.len
}
fn is_ok_child(&self) -> bool {
self.data.len() >= MIN_LEAF
}
fn push_maybe_split(
&mut self,
other: &LensLeaf,
iv: Interval,
) -> Option<LensLeaf> {
let (iv_start, iv_end) = iv.start_end();
let mut accum = 0;
let mut added_len = 0;
let mut added_height = 0;
for sec in &other.data {
if accum + sec.len < iv_start {
accum += sec.len;
continue;
}
if accum + sec.len <= iv_end {
accum += sec.len;
self.data.push(LensData {
len: sec.len,
line_height: sec.line_height,
});
added_len += sec.len;
added_height += sec.len * sec.line_height;
continue;
}
let len = iv_end - (accum + sec.len);
self.data.push(LensData {
len,
line_height: sec.line_height,
});
added_len += len;
added_height += sec.len * sec.line_height;
break;
}
self.len += added_len;
self.total_height += added_height;
if self.data.len() <= MAX_LEAF {
None
} else {
let splitpoint = self.data.len() / 2; // number of spans
let new = self.data.split_off(splitpoint);
let new_len = new.iter().map(|d| d.len).sum();
let new_height = new.iter().map(|d| d.len * d.line_height).sum();
self.len -= new_len;
self.total_height -= new_height;
Some(LensLeaf {
len: new_len,
data: new,
total_height: new_height,
})
}
}
}
#[derive(Copy, Clone)]
pub struct LensMetric(());
impl Metric<LensInfo> for LensMetric {
fn measure(info: &LensInfo, _len: usize) -> usize {
info.0
}
fn to_base_units(l: &LensLeaf, in_measured_units: usize) -> usize {
if in_measured_units > l.total_height {
l.len
} else if in_measured_units == 0 {
0
} else {
let mut line = 0;
let mut accum = 0;
for data in l.data.iter() {
let leaf_height = data.line_height * data.len;
let accum_height = accum + leaf_height;
if accum_height > in_measured_units {
return line + (in_measured_units - accum) / data.line_height;
}
accum = accum_height;
line += data.len;
}
line
}
}
fn from_base_units(l: &LensLeaf, in_base_units: usize) -> usize {
let mut line = 0;
let mut accum = 0;
for data in l.data.iter() {
if in_base_units < line + data.len {
return accum + (in_base_units - line) * data.line_height;
}
accum += data.len * data.line_height;
line += data.len;
}
accum
}
fn is_boundary(_l: &LensLeaf, _offset: usize) -> bool {
true
}
fn prev(_l: &LensLeaf, offset: usize) -> Option<usize> {
if offset == 0 { None } else { Some(offset - 1) }
}
fn next(l: &LensLeaf, offset: usize) -> Option<usize> {
if offset < l.len {
Some(offset + 1)
} else {
None
}
}
fn can_fragment() -> bool {
false
}
}
impl DefaultMetric for LensInfo {
type DefaultMetric = LensBaseMetric;
}
#[derive(Copy, Clone)]
pub struct LensBaseMetric(());
impl Metric<LensInfo> for LensBaseMetric {
fn measure(_: &LensInfo, len: usize) -> usize {
len
}
fn to_base_units(_: &LensLeaf, in_measured_units: usize) -> usize {
in_measured_units
}
fn from_base_units(_: &LensLeaf, in_base_units: usize) -> usize {
in_base_units
}
fn is_boundary(l: &LensLeaf, offset: usize) -> bool {
LensMetric::is_boundary(l, offset)
}
fn prev(l: &LensLeaf, offset: usize) -> Option<usize> {
LensMetric::prev(l, offset)
}
fn next(l: &LensLeaf, offset: usize) -> Option<usize> {
LensMetric::next(l, offset)
}
fn can_fragment() -> bool {
false
}
}
pub struct LensBuilder {
b: TreeBuilder<LensInfo>,
leaf: LensLeaf,
}
impl Default for LensBuilder {
fn default() -> LensBuilder {
LensBuilder {
b: TreeBuilder::new(),
leaf: LensLeaf::default(),
}
}
}
impl LensBuilder {
pub fn new() -> LensBuilder {
LensBuilder::default()
}
pub fn add_section(&mut self, len: usize, line_height: usize) {
if self.leaf.data.len() == MAX_LEAF {
let leaf = mem::take(&mut self.leaf);
self.b.push(Node::from_leaf(leaf));
}
self.leaf.len += len;
self.leaf.total_height += len * line_height;
self.leaf.data.push(LensData { len, line_height });
}
pub fn build(mut self) -> Lens {
self.b.push(Node::from_leaf(self.leaf));
Lens(self.b.build())
}
}
impl Iterator for LensIter<'_> {
type Item = (usize, usize);
fn next(&mut self) -> Option<Self::Item> {
if self.cursor.pos() >= self.end {
return None;
}
if let Some((leaf, leaf_pos)) = self.cursor.get_leaf() {
if leaf.data.is_empty() {
return None;
}
let line = self.cursor.pos();
self.cursor.next::<LensMetric>();
let mut lines = 0;
for data in leaf.data.iter() {
if leaf_pos < data.len + lines {
return Some((line, data.line_height));
}
lines += data.len;
}
return None;
}
None
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_lens_metric() {
let mut builder = LensBuilder::new();
builder.add_section(10, 2);
builder.add_section(1, 25);
builder.add_section(20, 3);
let lens = builder.build();
assert_eq!(31, lens.len());
assert_eq!(0, lens.height_of_line(0));
assert_eq!(2, lens.height_of_line(1));
assert_eq!(20, lens.height_of_line(10));
assert_eq!(45, lens.height_of_line(11));
assert_eq!(48, lens.height_of_line(12));
assert_eq!(105, lens.height_of_line(31));
assert_eq!(105, lens.height_of_line(32));
assert_eq!(105, lens.height_of_line(62));
assert_eq!(0, lens.line_of_height(0));
assert_eq!(0, lens.line_of_height(1));
assert_eq!(1, lens.line_of_height(2));
assert_eq!(1, lens.line_of_height(3));
assert_eq!(2, lens.line_of_height(4));
assert_eq!(2, lens.line_of_height(5));
assert_eq!(3, lens.line_of_height(6));
assert_eq!(10, lens.line_of_height(20));
assert_eq!(10, lens.line_of_height(44));
assert_eq!(11, lens.line_of_height(45));
assert_eq!(11, lens.line_of_height(46));
assert_eq!(31, lens.line_of_height(105));
assert_eq!(31, lens.line_of_height(106));
}
#[test]
fn test_lens_iter() {
let mut builder = LensBuilder::new();
builder.add_section(10, 2);
builder.add_section(1, 25);
builder.add_section(2, 3);
let lens = builder.build();
let mut iter = lens.iter();
assert_eq!(Some((0, 2)), iter.next());
assert_eq!(Some((1, 2)), iter.next());
assert_eq!(Some((2, 2)), iter.next());
for _ in 0..7 {
iter.next();
}
assert_eq!(Some((10, 25)), iter.next());
assert_eq!(Some((11, 3)), iter.next());
assert_eq!(Some((12, 3)), iter.next());
assert_eq!(None, iter.next());
let mut iter = lens.iter_chunks(9..12);
assert_eq!(Some((9, 2)), iter.next());
assert_eq!(Some((10, 25)), iter.next());
assert_eq!(Some((11, 3)), iter.next());
assert_eq!(None, iter.next());
let mut iter = lens.iter_chunks(9..15);
assert_eq!(Some((9, 2)), iter.next());
assert_eq!(Some((10, 25)), iter.next());
assert_eq!(Some((11, 3)), iter.next());
assert_eq!(Some((12, 3)), iter.next());
assert_eq!(None, iter.next());
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-core/src/encoding.rs | lapce-core/src/encoding.rs | /// Convert a utf8 offset into a utf16 offset, if possible
/// `text` is what the offsets are into
pub fn offset_utf8_to_utf16(
char_indices: impl Iterator<Item = (usize, char)>,
offset: usize,
) -> usize {
if offset == 0 {
return 0;
}
let mut utf16_offset = 0;
let mut last_ich = None;
for (utf8_offset, ch) in char_indices {
last_ich = Some((utf8_offset, ch));
match utf8_offset.cmp(&offset) {
std::cmp::Ordering::Less => {}
// We found the right offset
std::cmp::Ordering::Equal => {
return utf16_offset;
}
// Implies that the offset was inside of a character
std::cmp::Ordering::Greater => return utf16_offset,
}
utf16_offset += ch.len_utf16();
}
// TODO: We could use TrustedLen when that is stabilized and it is impl'd on
// the iterators we use
// We did not find the offset. This means that it is either at the end
// or past the end.
let text_len = last_ich.map(|(i, c)| i + c.len_utf8());
if text_len == Some(offset) {
// Since the utf16 offset was being incremented each time, by now it is equivalent to the length
// but in utf16 characters
return utf16_offset;
}
utf16_offset
}
pub fn offset_utf8_to_utf16_str(text: &str, offset: usize) -> usize {
offset_utf8_to_utf16(text.char_indices(), offset)
}
/// Convert a utf16 offset into a utf8 offset, if possible
/// `char_indices` is an iterator over utf8 offsets and the characters
/// It is cloneable so that it can be iterated multiple times. Though it should be cheaply cloneable.
pub fn offset_utf16_to_utf8(
char_indices: impl Iterator<Item = (usize, char)>,
offset: usize,
) -> usize {
if offset == 0 {
return 0;
}
// We accumulate the utf16 char lens until we find the utf8 offset that matches it
// or, we find out that it went into the middle of sometext
// We also keep track of the last offset and char in order to calculate the length of the text
// if we the index was at the end of the string
let mut utf16_offset = 0;
let mut last_ich = None;
for (utf8_offset, ch) in char_indices {
last_ich = Some((utf8_offset, ch));
let ch_utf16_len = ch.len_utf16();
match utf16_offset.cmp(&offset) {
std::cmp::Ordering::Less => {}
// We found the right offset
std::cmp::Ordering::Equal => {
return utf8_offset;
}
// This implies that the offset was in the middle of a character as we skipped over it
std::cmp::Ordering::Greater => return utf8_offset,
}
utf16_offset += ch_utf16_len;
}
// We did not find the offset, this means that it was either at the end
// or past the end
// Since we've iterated over all the char indices, the utf16_offset is now the
// utf16 length
if let Some((last_utf8_offset, last_ch)) = last_ich {
last_utf8_offset + last_ch.len_utf8()
} else {
0
}
}
pub fn offset_utf16_to_utf8_str(text: &str, offset: usize) -> usize {
offset_utf16_to_utf8(text.char_indices(), offset)
}
#[cfg(test)]
mod tests {
// TODO: more tests with unicode characters
use crate::encoding::{offset_utf8_to_utf16_str, offset_utf16_to_utf8_str};
#[test]
fn utf8_to_utf16() {
let text = "hello world";
assert_eq!(offset_utf8_to_utf16_str(text, 0), 0);
assert_eq!(offset_utf8_to_utf16_str("", 0), 0);
assert_eq!(offset_utf8_to_utf16_str("", 1), 0);
assert_eq!(offset_utf8_to_utf16_str("h", 0), 0);
assert_eq!(offset_utf8_to_utf16_str("h", 1), 1);
assert_eq!(offset_utf8_to_utf16_str(text, text.len()), text.len());
assert_eq!(
offset_utf8_to_utf16_str(text, text.len() - 1),
text.len() - 1
);
assert_eq!(offset_utf8_to_utf16_str(text, text.len() + 1), text.len());
assert_eq!(offset_utf8_to_utf16_str("×", 0), 0);
assert_eq!(offset_utf8_to_utf16_str("×", 1), 1);
assert_eq!(offset_utf8_to_utf16_str("×", 2), 1);
assert_eq!(offset_utf8_to_utf16_str("a×", 0), 0);
assert_eq!(offset_utf8_to_utf16_str("a×", 1), 1);
assert_eq!(offset_utf8_to_utf16_str("a×", 2), 2);
assert_eq!(offset_utf8_to_utf16_str("a×", 3), 2);
}
#[test]
fn utf16_to_utf8() {
let text = "hello world";
assert_eq!(offset_utf16_to_utf8_str(text, 0), 0);
assert_eq!(offset_utf16_to_utf8_str("", 0), 0);
assert_eq!(offset_utf16_to_utf8_str("", 1), 0);
assert_eq!(offset_utf16_to_utf8_str("h", 0), 0);
assert_eq!(offset_utf16_to_utf8_str("h", 1), 1);
assert_eq!(offset_utf16_to_utf8_str(text, text.len()), text.len());
assert_eq!(
offset_utf16_to_utf8_str(text, text.len() - 1),
text.len() - 1
);
assert_eq!(offset_utf16_to_utf8_str(text, text.len() + 1), text.len());
assert_eq!(offset_utf16_to_utf8_str("×", 0), 0);
assert_eq!(offset_utf16_to_utf8_str("×", 1), 2);
assert_eq!(offset_utf16_to_utf8_str("a×", 0), 0);
assert_eq!(offset_utf16_to_utf8_str("a×", 1), 1);
assert_eq!(offset_utf16_to_utf8_str("a×", 2), 3);
assert_eq!(offset_utf16_to_utf8_str("×a", 1), 2);
assert_eq!(offset_utf16_to_utf8_str("×a", 2), 3);
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-core/src/directory.rs | lapce-core/src/directory.rs | use std::path::PathBuf;
use directories::{BaseDirs, ProjectDirs};
use crate::meta::NAME;
pub struct Directory {}
impl Directory {
pub fn home_dir() -> Option<PathBuf> {
BaseDirs::new().map(|d| PathBuf::from(d.home_dir()))
}
#[cfg(not(feature = "portable"))]
fn project_dirs() -> Option<ProjectDirs> {
ProjectDirs::from("dev", "lapce", NAME)
}
/// Return path adjacent to lapce executable when built as portable
#[cfg(feature = "portable")]
fn project_dirs() -> Option<ProjectDirs> {
if let Ok(current_exe) = std::env::current_exe() {
if let Some(parent) = current_exe.parent() {
return ProjectDirs::from_path(parent.join("lapce-data"));
}
unreachable!("Couldn't obtain current process parent path");
}
unreachable!("Couldn't obtain current process path");
}
// Get path of local data directory
// Local data directory differs from data directory
// on some platforms and is not transferred across
// machines
pub fn data_local_directory() -> Option<PathBuf> {
match Self::project_dirs() {
Some(dir) => {
let dir = dir.data_local_dir();
if !dir.exists() {
if let Err(err) = std::fs::create_dir_all(dir) {
tracing::error!("{:?}", err);
}
}
Some(dir.to_path_buf())
}
None => None,
}
}
/// Get the path to logs directory
/// Each log file is for individual application startup
pub fn logs_directory() -> Option<PathBuf> {
if let Some(dir) = Self::data_local_directory() {
let dir = dir.join("logs");
if !dir.exists() {
if let Err(err) = std::fs::create_dir(&dir) {
tracing::error!("{:?}", err);
}
}
Some(dir)
} else {
None
}
}
/// Get the path to cache directory
pub fn cache_directory() -> Option<PathBuf> {
if let Some(dir) = Self::data_local_directory() {
let dir = dir.join("cache");
if !dir.exists() {
if let Err(err) = std::fs::create_dir(&dir) {
tracing::error!("{:?}", err);
}
}
Some(dir)
} else {
None
}
}
/// Directory to store proxy executables used on local
/// host as well, as ones uploaded to remote host when
/// connecting
pub fn proxy_directory() -> Option<PathBuf> {
if let Some(dir) = Self::data_local_directory() {
let dir = dir.join("proxy");
if !dir.exists() {
if let Err(err) = std::fs::create_dir(&dir) {
tracing::error!("{:?}", err);
}
}
Some(dir)
} else {
None
}
}
/// Get the path to the themes folder
/// Themes are stored within as individual toml files
pub fn themes_directory() -> Option<PathBuf> {
if let Some(dir) = Self::data_local_directory() {
let dir = dir.join("themes");
if !dir.exists() {
if let Err(err) = std::fs::create_dir(&dir) {
tracing::error!("{:?}", err);
}
}
Some(dir)
} else {
None
}
}
// Get the path to plugins directory
// Each plugin has own directory that contains
// metadata file and plugin wasm
pub fn plugins_directory() -> Option<PathBuf> {
if let Some(dir) = Self::data_local_directory() {
let dir = dir.join("plugins");
if !dir.exists() {
if let Err(err) = std::fs::create_dir(&dir) {
tracing::error!("{:?}", err);
}
}
Some(dir)
} else {
None
}
}
// Config directory contain only configuration files
pub fn config_directory() -> Option<PathBuf> {
match Self::project_dirs() {
Some(dir) => {
let dir = dir.config_dir();
if !dir.exists() {
if let Err(err) = std::fs::create_dir_all(dir) {
tracing::error!("{:?}", err);
}
}
Some(dir.to_path_buf())
}
None => None,
}
}
pub fn local_socket() -> Option<PathBuf> {
Self::data_local_directory().map(|dir| dir.join("local.sock"))
}
pub fn updates_directory() -> Option<PathBuf> {
if let Some(dir) = Self::data_local_directory() {
let dir = dir.join("updates");
if !dir.exists() {
if let Err(err) = std::fs::create_dir(&dir) {
tracing::error!("{:?}", err);
}
}
Some(dir)
} else {
None
}
}
pub fn queries_directory() -> Option<PathBuf> {
if let Some(dir) = Self::config_directory() {
let dir = dir.join("queries");
if !dir.exists() {
if let Err(err) = std::fs::create_dir(&dir) {
tracing::error!("{:?}", err);
}
}
Some(dir)
} else {
None
}
}
pub fn grammars_directory() -> Option<PathBuf> {
if let Some(dir) = Self::data_local_directory() {
let dir = dir.join("grammars");
if !dir.exists() {
if let Err(err) = std::fs::create_dir(&dir) {
tracing::error!("{:?}", err);
}
}
Some(dir)
} else {
None
}
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-core/src/syntax/highlight.rs | lapce-core/src/syntax/highlight.rs | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* Much of the code in this file is modified from [helix](https://github.com/helix-editor/helix)'s implementation of their syntax highlighting, which is under the MPL.
*/
use std::{
borrow::Cow,
cell::RefCell,
collections::HashMap,
path::Path,
sync::{
Arc,
atomic::{AtomicUsize, Ordering},
},
};
use arc_swap::ArcSwap;
use lapce_xi_rope::Rope;
use once_cell::sync::Lazy;
use regex::Regex;
use tree_sitter::{
Language, Point, Query, QueryCaptures, QueryCursor, QueryMatch, Tree,
};
use super::{PARSER, util::RopeProvider};
use crate::{language::LapceLanguage, style::SCOPES};
thread_local! {
static HIGHLIGHT_CONFIGS: RefCell<HashMap<LapceLanguage, Result<Arc<HighlightConfiguration>, HighlightIssue>>> = Default::default();
}
pub fn reset_highlight_configs() {
HIGHLIGHT_CONFIGS.with_borrow_mut(|configs| {
configs.clear();
});
}
pub(crate) fn get_highlight_config(
lang: LapceLanguage,
) -> Result<Arc<HighlightConfiguration>, HighlightIssue> {
HIGHLIGHT_CONFIGS.with(|configs| {
let mut configs = configs.borrow_mut();
let config = configs
.entry(lang)
.or_insert_with(|| lang.new_highlight_config().map(Arc::new));
config.clone()
})
}
/// Indicates which highlight should be applied to a region of source code.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Highlight(pub usize);
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum HighlightIssue {
Error(String),
NotAvailable,
}
/// Represents a single step in rendering a syntax-highlighted document.
#[derive(Copy, Clone, Debug)]
pub enum HighlightEvent {
Source { start: usize, end: usize },
HighlightStart(Highlight),
HighlightEnd,
}
#[derive(Debug)]
pub(crate) struct LocalDef<'a> {
name: Cow<'a, str>,
value_range: std::ops::Range<usize>,
highlight: Option<Highlight>,
}
#[derive(Debug)]
pub(crate) struct LocalScope<'a> {
pub(crate) inherits: bool,
pub(crate) range: std::ops::Range<usize>,
pub(crate) local_defs: Vec<LocalDef<'a>>,
}
#[derive(Debug, Clone)]
pub enum InjectionLanguageMarker<'a> {
Name(Cow<'a, str>),
Filename(Cow<'a, Path>),
Shebang(String),
}
const SHEBANG: &str = r"#!\s*(?:\S*[/\\](?:env\s+(?:\-\S+\s+)*)?)?([^\s\.\d]+)";
const CANCELLATION_CHECK_INTERVAL: usize = 100;
/// Contains the data needed to highlight code written in a particular language.
///
/// This struct is immutable and can be shared between threads.
#[derive(Debug)]
pub struct HighlightConfiguration {
pub language: Language,
pub query: Query,
pub injections_query: Query,
pub combined_injections_patterns: Vec<usize>,
pub highlights_pattern_index: usize,
pub highlight_indices: ArcSwap<Vec<Option<Highlight>>>,
pub non_local_variable_patterns: Vec<bool>,
pub injection_content_capture_index: Option<u32>,
pub injection_language_capture_index: Option<u32>,
pub injection_filename_capture_index: Option<u32>,
pub injection_shebang_capture_index: Option<u32>,
pub local_scope_capture_index: Option<u32>,
pub local_def_capture_index: Option<u32>,
pub local_def_value_capture_index: Option<u32>,
pub local_ref_capture_index: Option<u32>,
}
impl HighlightConfiguration {
/// Creates a `HighlightConfiguration` for a given `Language` and set of highlighting
/// queries.
///
/// # Parameters
///
/// * `language` - The Tree-sitter `Language` that should be used for parsing.
/// * `highlights_query` - A string containing tree patterns for syntax highlighting. This
/// should be non-empty, otherwise no syntax highlights will be added.
/// * `injections_query` - A string containing tree patterns for injecting other languages
/// into the document. This can be empty if no injections are desired.
/// * `locals_query` - A string containing tree patterns for tracking local variable
/// definitions and references. This can be empty if local variable tracking is not needed.
///
/// Returns a `HighlightConfiguration` that can then be used with the `highlight` method.
pub fn new(
language: Language,
highlights_query: &str,
injection_query: &str,
locals_query: &str,
) -> Result<Self, tree_sitter::QueryError> {
// Concatenate the query strings, keeping track of the start offset of each section.
let mut query_source = String::new();
query_source.push_str(locals_query);
let highlights_query_offset = query_source.len();
query_source.push_str(highlights_query);
// Construct a single query by concatenating the three query strings, but record the
// range of pattern indices that belong to each individual string.
let query = Query::new(&language, &query_source)?;
let mut highlights_pattern_index = 0;
for i in 0..(query.pattern_count()) {
let pattern_offset = query.start_byte_for_pattern(i);
if pattern_offset < highlights_query_offset {
highlights_pattern_index += 1;
}
}
let injections_query = Query::new(&language, injection_query)?;
let combined_injections_patterns = (0..injections_query.pattern_count())
.filter(|&i| {
injections_query
.property_settings(i)
.iter()
.any(|s| &*s.key == "injection.combined")
})
.collect();
// Find all of the highlighting patterns that are disabled for nodes that
// have been identified as local variables.
let non_local_variable_patterns = (0..query.pattern_count())
.map(|i| {
query.property_predicates(i).iter().any(|(prop, positive)| {
!*positive && prop.key.as_ref() == "local"
})
})
.collect();
// Store the numeric ids for all of the special captures.
let mut injection_content_capture_index = None;
let mut injection_language_capture_index = None;
let mut injection_filename_capture_index = None;
let mut injection_shebang_capture_index = None;
let mut local_def_capture_index = None;
let mut local_def_value_capture_index = None;
let mut local_ref_capture_index = None;
let mut local_scope_capture_index = None;
for (i, name) in query.capture_names().iter().enumerate() {
let i = Some(i as u32);
match *name {
"local.definition" => local_def_capture_index = i,
"local.definition-value" => local_def_value_capture_index = i,
"local.reference" => local_ref_capture_index = i,
"local.scope" => local_scope_capture_index = i,
_ => {}
}
}
for (i, name) in injections_query.capture_names().iter().enumerate() {
let i = Some(i as u32);
match *name {
"injection.content" => injection_content_capture_index = i,
"injection.language" => injection_language_capture_index = i,
"injection.filename" => injection_filename_capture_index = i,
"injection.shebang" => injection_shebang_capture_index = i,
_ => {}
}
}
let highlight_indices: ArcSwap<Vec<_>> =
ArcSwap::from_pointee(vec![None; query.capture_names().len()]);
let conf = Self {
language,
query,
injections_query,
combined_injections_patterns,
highlights_pattern_index,
highlight_indices,
non_local_variable_patterns,
injection_content_capture_index,
injection_language_capture_index,
injection_shebang_capture_index,
injection_filename_capture_index,
local_scope_capture_index,
local_def_capture_index,
local_def_value_capture_index,
local_ref_capture_index,
};
conf.configure(SCOPES);
Ok(conf)
}
/// Get a slice containing all of the highlight names used in the configuration.
pub fn names(&self) -> &[&str] {
self.query.capture_names()
}
/// Set the list of recognized highlight names.
///
/// Tree-sitter syntax-highlighting queries specify highlights in the form of dot-separated
/// highlight names like `punctuation.bracket` and `function.method.builtin`. Consumers of
/// these queries can choose to recognize highlights with different levels of specificity.
/// For example, the string `function.builtin` will match against `function.builtin.constructor`
/// but will not match `function.method.builtin` and `function.method`.
///
/// When highlighting, results are returned as `Highlight` values, which contain the index
/// of the matched highlight this list of highlight names.
pub fn configure(&self, recognized_names: &[&str]) {
let mut capture_parts = Vec::new();
let indices: Vec<_> = self
.query
.capture_names()
.iter()
.map(move |capture_name| {
capture_parts.clear();
capture_parts.extend(capture_name.split('.'));
let mut best_index = None;
let mut best_match_len = 0;
for (i, recognized_name) in recognized_names.iter().enumerate() {
let mut len = 0;
let mut matches = true;
for (i, part) in recognized_name.split('.').enumerate() {
match capture_parts.get(i) {
Some(capture_part) if *capture_part == part => len += 1,
_ => {
matches = false;
break;
}
}
}
if matches && len > best_match_len {
best_index = Some(i);
best_match_len = len;
}
}
best_index.map(Highlight)
})
.collect();
self.highlight_indices.store(Arc::new(indices));
}
pub fn injection_pair<'a>(
&self,
query_match: &QueryMatch<'a, 'a>,
source: &'a Rope,
) -> (
Option<InjectionLanguageMarker<'a>>,
Option<tree_sitter::Node<'a>>,
) {
let mut injection_capture = None;
let mut content_node = None;
for capture in query_match.captures {
let index = Some(capture.index);
if index == self.injection_language_capture_index {
let name = source.slice_to_cow(capture.node.byte_range());
injection_capture = Some(InjectionLanguageMarker::Name(name));
} else if index == self.injection_filename_capture_index {
let name = source.slice_to_cow(capture.node.byte_range());
let path = Path::new(name.as_ref()).to_path_buf();
injection_capture =
Some(InjectionLanguageMarker::Filename(path.into()));
} else if index == self.injection_shebang_capture_index {
let node_slice = source.slice(capture.node.byte_range());
let max_line = node_slice.line_of_offset(node_slice.len());
let node_slice = if max_line > 0 {
node_slice.slice(..node_slice.offset_of_line(1))
} else {
node_slice
};
static SHEBANG_REGEX: Lazy<Regex> =
Lazy::new(|| Regex::new(SHEBANG).unwrap());
injection_capture = SHEBANG_REGEX
.captures_iter(&node_slice.slice_to_cow(..))
.map(|cap| InjectionLanguageMarker::Shebang(cap[1].to_string()))
.next()
} else if index == self.injection_content_capture_index {
content_node = Some(capture.node);
}
}
(injection_capture, content_node)
}
pub(crate) fn injection_for_match<'a>(
&self,
query: &'a Query,
query_match: &QueryMatch<'a, 'a>,
source: &'a Rope,
) -> (
Option<InjectionLanguageMarker<'a>>,
Option<tree_sitter::Node<'a>>,
IncludedChildren,
) {
let (mut injection_capture, content_node) =
self.injection_pair(query_match, source);
let mut included_children = IncludedChildren::default();
for prop in query.property_settings(query_match.pattern_index) {
match prop.key.as_ref() {
// In addition to specifying the language name via the text of a
// captured node, it can also be hard-coded via a `#set!` predicate
// that sets the injection.language key.
"injection.language" if injection_capture.is_none() => {
injection_capture = prop
.value
.as_ref()
.map(|s| InjectionLanguageMarker::Name(s.as_ref().into()));
}
// By default, injections do not include the *children* of an
// `injection.content` node - only the ranges that belong to the
// node itself. This can be changed using a `#set!` predicate that
// sets the `injection.include-children` key.
"injection.include-children" => {
included_children = IncludedChildren::All
}
// Some queries might only exclude named children but include unnamed
// children in their `injection.content` node. This can be enabled using
// a `#set!` predicate that sets the `injection.include-unnamed-children` key.
"injection.include-unnamed-children" => {
included_children = IncludedChildren::Unnamed
}
_ => {}
}
}
(injection_capture, content_node, included_children)
}
}
#[derive(Debug)]
pub(crate) struct HighlightIter<'a> {
pub(crate) source: &'a Rope,
pub(crate) byte_offset: usize,
pub(crate) cancellation_flag: Option<&'a AtomicUsize>,
pub(crate) layers: Vec<HighlightIterLayer<'a>>,
pub(crate) iter_count: usize,
pub(crate) next_event: Option<HighlightEvent>,
pub(crate) last_highlight_range: Option<(usize, usize, usize)>,
}
pub(crate) struct HighlightIterLayer<'a> {
pub(crate) _tree: Option<Tree>,
pub(crate) cursor: QueryCursor,
pub(crate) captures: RefCell<
std::iter::Peekable<QueryCaptures<'a, 'a, RopeProvider<'a>, &'a [u8]>>,
>,
pub(crate) config: &'a HighlightConfiguration,
pub(crate) highlight_end_stack: Vec<usize>,
pub(crate) scope_stack: Vec<LocalScope<'a>>,
pub(crate) depth: usize,
}
impl std::fmt::Debug for HighlightIterLayer<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("HighlightIterLayer").finish()
}
}
impl HighlightIterLayer<'_> {
// First, sort scope boundaries by their byte offset in the document. At a
// given position, emit scope endings before scope beginnings. Finally, emit
// scope boundaries from deeper layers first.
pub fn sort_key(&self) -> Option<(usize, bool, isize)> {
let depth = -(self.depth as isize);
let next_start = self
.captures
.borrow_mut()
.peek()
.map(|(m, i)| m.captures[*i].node.start_byte());
let next_end = self.highlight_end_stack.last().cloned();
match (next_start, next_end) {
(Some(start), Some(end)) => {
if start < end {
Some((start, true, depth))
} else {
Some((end, false, depth))
}
}
(Some(i), None) => Some((i, true, depth)),
(None, Some(j)) => Some((j, false, depth)),
_ => None,
}
}
}
impl HighlightIter<'_> {
fn emit_event(
&mut self,
offset: usize,
event: Option<HighlightEvent>,
) -> Option<Result<HighlightEvent, super::Error>> {
let result;
if self.byte_offset < offset {
result = Some(Ok(HighlightEvent::Source {
start: self.byte_offset,
end: offset,
}));
self.byte_offset = offset;
self.next_event = event;
} else {
result = event.map(Ok);
}
self.sort_layers();
result
}
pub(crate) fn sort_layers(&mut self) {
while !self.layers.is_empty() {
if let Some(sort_key) = self.layers[0].sort_key() {
let mut i = 0;
while i + 1 < self.layers.len() {
if let Some(next_offset) = self.layers[i + 1].sort_key() {
if next_offset < sort_key {
i += 1;
continue;
}
} else {
let layer = self.layers.remove(i + 1);
PARSER.with(|ts_parser| {
let highlighter = &mut ts_parser.borrow_mut();
highlighter.cursors.push(layer.cursor);
});
}
break;
}
if i > 0 {
self.layers[0..(i + 1)].rotate_left(1);
}
break;
} else {
let layer = self.layers.remove(0);
PARSER.with(|ts_parser| {
let highlighter = &mut ts_parser.borrow_mut();
highlighter.cursors.push(layer.cursor);
});
}
}
}
}
impl Iterator for HighlightIter<'_> {
type Item = Result<HighlightEvent, super::Error>;
fn next(&mut self) -> Option<Self::Item> {
'main: loop {
// If we've already determined the next highlight boundary, just return it.
if let Some(e) = self.next_event.take() {
return Some(Ok(e));
}
// Periodically check for cancellation, returning `Cancelled` error if the
// cancellation flag was flipped.
if let Some(cancellation_flag) = self.cancellation_flag {
self.iter_count += 1;
if self.iter_count >= CANCELLATION_CHECK_INTERVAL {
self.iter_count = 0;
if cancellation_flag.load(Ordering::Relaxed) != 0 {
return Some(Err(super::Error::Cancelled));
}
}
}
// If none of the layers have any more highlight boundaries, terminate.
if self.layers.is_empty() {
let len = self.source.len();
return if self.byte_offset < len {
let result = Some(Ok(HighlightEvent::Source {
start: self.byte_offset,
end: len,
}));
self.byte_offset = len;
result
} else {
None
};
}
// Get the next capture from whichever layer has the earliest highlight boundary.
let range;
let layer = &mut self.layers[0];
let captures = layer.captures.get_mut();
if let Some((next_match, capture_index)) = captures.peek() {
let next_capture = next_match.captures[*capture_index];
range = next_capture.node.byte_range();
// If any previous highlight ends before this node starts, then before
// processing this capture, emit the source code up until the end of the
// previous highlight, and an end event for that highlight.
if let Some(end_byte) = layer.highlight_end_stack.last().cloned() {
if end_byte <= range.start {
layer.highlight_end_stack.pop();
return self.emit_event(
end_byte,
Some(HighlightEvent::HighlightEnd),
);
}
}
}
// If there are no more captures, then emit any remaining highlight end events.
// And if there are none of those, then just advance to the end of the document.
else if let Some(end_byte) = layer.highlight_end_stack.last().cloned()
{
layer.highlight_end_stack.pop();
return self
.emit_event(end_byte, Some(HighlightEvent::HighlightEnd));
} else {
return self.emit_event(self.source.len(), None);
};
let (mut match_, capture_index) = captures.next().unwrap();
let mut capture = match_.captures[capture_index];
// Remove from the local scope stack any local scopes that have already ended.
while range.start > layer.scope_stack.last().unwrap().range.end {
layer.scope_stack.pop();
}
// If this capture is for tracking local variables, then process the
// local variable info.
let mut reference_highlight = None;
let mut definition_highlight = None;
while match_.pattern_index < layer.config.highlights_pattern_index {
// If the node represents a local scope, push a new local scope onto
// the scope stack.
if Some(capture.index) == layer.config.local_scope_capture_index {
definition_highlight = None;
let mut scope = LocalScope {
inherits: true,
range: range.clone(),
local_defs: Vec::new(),
};
for prop in
layer.config.query.property_settings(match_.pattern_index)
{
if let "local.scope-inherits" = prop.key.as_ref() {
scope.inherits = prop
.value
.as_ref()
.is_none_or(|r| r.as_ref() == "true");
}
}
layer.scope_stack.push(scope);
}
// If the node represents a definition, add a new definition to the
// local scope at the top of the scope stack.
else if Some(capture.index) == layer.config.local_def_capture_index
{
reference_highlight = None;
let scope = layer.scope_stack.last_mut().unwrap();
let mut value_range = 0..0;
for capture in match_.captures {
if Some(capture.index)
== layer.config.local_def_value_capture_index
{
value_range = capture.node.byte_range();
}
}
let name = self.source.slice_to_cow(range.clone());
scope.local_defs.push(LocalDef {
name,
value_range,
highlight: None,
});
definition_highlight =
scope.local_defs.last_mut().map(|s| &mut s.highlight);
}
// If the node represents a reference, then try to find the corresponding
// definition in the scope stack.
else if Some(capture.index) == layer.config.local_ref_capture_index
&& definition_highlight.is_none()
{
definition_highlight = None;
let name = self.source.slice_to_cow(range.clone());
for scope in layer.scope_stack.iter().rev() {
if let Some(highlight) =
scope.local_defs.iter().rev().find_map(|def| {
if def.name == name
&& range.start >= def.value_range.end
{
Some(def.highlight)
} else {
None
}
})
{
reference_highlight = highlight;
break;
}
if !scope.inherits {
break;
}
}
}
// Continue processing any additional matches for the same node.
if let Some((next_match, next_capture_index)) = captures.peek() {
let next_capture = next_match.captures[*next_capture_index];
if next_capture.node == capture.node {
capture = next_capture;
match_ = captures.next().unwrap().0;
continue;
}
}
self.sort_layers();
continue 'main;
}
// Otherwise, this capture must represent a highlight.
// If this exact range has already been highlighted by an earlier pattern, or by
// a different layer, then skip over this one.
if let Some((last_start, last_end, last_depth)) =
self.last_highlight_range
{
if range.start == last_start
&& range.end == last_end
&& layer.depth < last_depth
{
self.sort_layers();
continue 'main;
}
}
// If the current node was found to be a local variable, then skip over any
// highlighting patterns that are disabled for local variables.
if definition_highlight.is_some() || reference_highlight.is_some() {
while layer.config.non_local_variable_patterns[match_.pattern_index]
{
if let Some((next_match, next_capture_index)) = captures.peek() {
let next_capture = next_match.captures[*next_capture_index];
if next_capture.node == capture.node {
capture = next_capture;
match_ = captures.next().unwrap().0;
continue;
}
}
self.sort_layers();
continue 'main;
}
}
// Once a highlighting pattern is found for the current node, skip over
// any later highlighting patterns that also match this node. Captures
// for a given node are ordered by pattern index, so these subsequent
// captures are guaranteed to be for highlighting, not injections or
// local variables.
while let Some((next_match, next_capture_index)) = captures.peek() {
let next_capture = next_match.captures[*next_capture_index];
if next_capture.node == capture.node {
captures.next();
} else {
break;
}
}
let current_highlight =
layer.config.highlight_indices.load()[capture.index as usize];
// If this node represents a local definition, then store the current
// highlight value on the local scope entry representing this node.
if let Some(definition_highlight) = definition_highlight {
*definition_highlight = current_highlight;
}
// Emit a scope start event and push the node's end position to the stack.
if let Some(highlight) = reference_highlight.or(current_highlight) {
self.last_highlight_range =
Some((range.start, range.end, layer.depth));
layer.highlight_end_stack.push(range.end);
return self.emit_event(
range.start,
Some(HighlightEvent::HighlightStart(highlight)),
);
}
self.sort_layers();
}
}
}
#[derive(Clone, Default)]
pub(crate) enum IncludedChildren {
#[default]
None,
All,
Unnamed,
}
// Compute the ranges that should be included when parsing an injection.
// This takes into account three things:
// * `parent_ranges` - The ranges must all fall within the *current* layer's ranges.
// * `nodes` - Every injection takes place within a set of nodes. The injection ranges
// are the ranges of those nodes.
// * `includes_children` - For some injections, the content nodes' children should be
// excluded from the nested document, so that only the content nodes' *own* content
// is reparsed. For other injections, the content nodes' entire ranges should be
// reparsed, including the ranges of their children.
pub(crate) fn intersect_ranges(
parent_ranges: &[tree_sitter::Range],
nodes: &[tree_sitter::Node],
included_children: IncludedChildren,
) -> Vec<tree_sitter::Range> {
let mut cursor = nodes[0].walk();
let mut result = Vec::new();
let mut parent_range_iter = parent_ranges.iter();
let mut parent_range = parent_range_iter
.next()
.expect("Layers should only be constructed with non-empty ranges vectors");
for node in nodes.iter() {
let mut preceding_range = tree_sitter::Range {
start_byte: 0,
start_point: Point::new(0, 0),
end_byte: node.start_byte(),
end_point: node.start_position(),
};
let following_range = tree_sitter::Range {
start_byte: node.end_byte(),
start_point: node.end_position(),
end_byte: usize::MAX,
end_point: Point::new(usize::MAX, usize::MAX),
};
for excluded_range in node
.children(&mut cursor)
.filter_map(|child| match included_children {
IncludedChildren::None => Some(child.range()),
IncludedChildren::All => None,
IncludedChildren::Unnamed => {
if child.is_named() {
Some(child.range())
} else {
None
}
}
})
.chain([following_range].iter().cloned())
{
let mut range = tree_sitter::Range {
start_byte: preceding_range.end_byte,
start_point: preceding_range.end_point,
end_byte: excluded_range.start_byte,
end_point: excluded_range.start_point,
};
preceding_range = excluded_range;
if range.end_byte < parent_range.start_byte {
continue;
}
while parent_range.start_byte <= range.end_byte {
if parent_range.end_byte > range.start_byte {
if range.start_byte < parent_range.start_byte {
range.start_byte = parent_range.start_byte;
range.start_point = parent_range.start_point;
}
if parent_range.end_byte < range.end_byte {
if range.start_byte < parent_range.end_byte {
result.push(tree_sitter::Range {
start_byte: range.start_byte,
start_point: range.start_point,
end_byte: parent_range.end_byte,
end_point: parent_range.end_point,
});
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | true |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-core/src/syntax/util.rs | lapce-core/src/syntax/util.rs | use lapce_xi_rope::{Rope, rope::ChunkIter};
use tree_sitter::TextProvider;
pub struct RopeChunksIterBytes<'a> {
chunks: ChunkIter<'a>,
}
impl<'a> Iterator for RopeChunksIterBytes<'a> {
type Item = &'a [u8];
fn next(&mut self) -> Option<Self::Item> {
self.chunks.next().map(str::as_bytes)
}
}
/// This allows tree-sitter to iterate over our Rope without us having to convert it into
/// a contiguous byte-list.
pub struct RopeProvider<'a>(pub &'a Rope);
impl<'a> TextProvider<&'a [u8]> for RopeProvider<'a> {
type I = RopeChunksIterBytes<'a>;
fn text(&mut self, node: tree_sitter::Node) -> Self::I {
let start = node.start_byte();
let end = node.end_byte().min(self.0.len());
let chunks = self.0.iter_chunks(start..end);
RopeChunksIterBytes { chunks }
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-core/src/syntax/mod.rs | lapce-core/src/syntax/mod.rs | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* Much of the code in this file is modified from [helix](https://github.com/helix-editor/helix)'s implementation of their syntax highlighting, which is under the MPL.
*/
use std::{
cell::RefCell,
collections::{HashMap, HashSet, VecDeque, hash_map::Entry},
hash::{Hash, Hasher},
mem,
path::Path,
sync::{Arc, atomic::AtomicUsize},
};
use ahash::RandomState;
use floem_editor_core::util::{matching_bracket_general, matching_pair_direction};
use hashbrown::raw::RawTable;
use itertools::Itertools;
use lapce_rpc::style::{LineStyle, Style};
use lapce_xi_rope::{
Interval, Rope,
spans::{Spans, SpansBuilder},
};
use slotmap::{DefaultKey as LayerId, HopSlotMap};
use thiserror::Error;
use tree_sitter::{Node, Parser, Point, QueryCursor, Tree};
use self::{
edit::SyntaxEdit,
highlight::{
Highlight, HighlightConfiguration, HighlightEvent, HighlightIter,
HighlightIterLayer, IncludedChildren, LocalScope, get_highlight_config,
intersect_ranges,
},
util::RopeProvider,
};
use crate::{
buffer::{Buffer, rope_text::RopeText},
language::{self, LapceLanguage},
lens::{Lens, LensBuilder},
style::SCOPES,
syntax::highlight::InjectionLanguageMarker,
};
pub mod edit;
pub mod highlight;
pub mod util;
const TREE_SITTER_MATCH_LIMIT: u32 = 256;
// Uses significant portions Helix's implementation, and on tree-sitter's highlighter implementation
pub struct TsParser {
parser: tree_sitter::Parser,
pub cursors: Vec<QueryCursor>,
}
thread_local! {
pub static PARSER: RefCell<TsParser> = RefCell::new(TsParser {
parser: Parser::new(),
cursors: Vec::new(),
});
}
/// Represents the reason why syntax highlighting failed.
#[derive(Debug, Error, PartialEq, Eq)]
pub enum Error {
#[error("Cancelled")]
Cancelled,
#[error("Invalid ranges")]
InvalidRanges,
#[error("Invalid language")]
InvalidLanguage,
#[error("Unknown error")]
Unknown,
}
#[derive(Clone, Debug)]
pub enum NodeType {
LeftParen,
RightParen,
LeftBracket,
RightBracket,
LeftCurly,
RightCurly,
Pair,
Code,
Dummy,
}
#[derive(Clone, Debug)]
pub enum BracketParserMode {
Parsing,
NoParsing,
}
#[derive(Clone, Debug)]
pub struct ASTNode {
pub tt: NodeType,
pub len: usize,
pub children: Vec<ASTNode>,
pub level: usize,
}
impl ASTNode {
pub fn new() -> Self {
Self {
tt: NodeType::Dummy,
len: 0,
children: vec![],
level: 0,
}
}
pub fn new_with_type(tt: NodeType, len: usize) -> Self {
Self {
tt,
len,
children: vec![],
level: 0,
}
}
}
impl Default for ASTNode {
fn default() -> Self {
Self::new()
}
}
#[derive(Clone, Debug)]
pub struct BracketParser {
pub code: Vec<char>,
pub cur: usize,
pub ast: ASTNode,
bracket_set: HashMap<char, ASTNode>,
pub bracket_pos: HashMap<usize, Vec<LineStyle>>,
mode: BracketParserMode,
noparsing_token: Vec<char>,
pub active: bool,
pub limit: u64,
}
impl BracketParser {
pub fn new(code: String, active: bool, limit: u64) -> Self {
Self {
code: code.chars().collect(),
cur: 0,
ast: ASTNode::new(),
bracket_set: HashMap::from([
('(', ASTNode::new_with_type(NodeType::LeftParen, 1)),
(')', ASTNode::new_with_type(NodeType::RightParen, 1)),
('{', ASTNode::new_with_type(NodeType::LeftCurly, 1)),
('}', ASTNode::new_with_type(NodeType::RightCurly, 1)),
('[', ASTNode::new_with_type(NodeType::LeftBracket, 1)),
(']', ASTNode::new_with_type(NodeType::RightBracket, 1)),
]),
bracket_pos: HashMap::new(),
mode: BracketParserMode::Parsing,
noparsing_token: vec!['\'', '"', '`'],
active,
limit,
}
}
/*pub fn enable(&self) {
*(self.active.borrow_mut()) = true;
}
pub fn disable(&self) {
*(self.active.borrow_mut()) = false;
}*/
pub fn update_code(
&mut self,
code: String,
buffer: &Buffer,
syntax: Option<&Syntax>,
) {
let palette = vec![
"bracket.color.1".to_string(),
"bracket.color.2".to_string(),
"bracket.color.3".to_string(),
];
if self.active
&& code
.chars()
.fold(0, |i, c| if c == '\n' { i + 1 } else { i })
< self.limit as usize
{
self.bracket_pos = HashMap::new();
if let Some(syntax) = syntax {
if let Some(layers) = &syntax.layers {
if let Some(tree) = layers.try_tree() {
let mut walk_cursor = tree.walk();
let mut bracket_pos: HashMap<usize, Vec<LineStyle>> =
HashMap::new();
language::walk_tree_bracket_ast(
&mut walk_cursor,
&mut 0,
&mut 0,
&mut bracket_pos,
&palette,
);
self.bracket_pos = bracket_pos;
}
}
} else {
self.code = code.chars().collect();
self.cur = 0;
self.parse();
let mut pos_vec = vec![];
Self::highlight_pos(
&self.ast,
&mut pos_vec,
&mut 0usize,
&mut 0usize,
&palette,
);
if buffer.is_empty() {
return;
}
for (offset, color) in pos_vec.iter() {
let (line, col) = buffer.offset_to_line_col(*offset);
let line_style = LineStyle {
start: col,
end: col + 1,
style: Style {
fg_color: Some(color.clone()),
},
};
match self.bracket_pos.entry(line) {
Entry::Vacant(v) => _ = v.insert(vec![line_style.clone()]),
Entry::Occupied(mut o) => {
o.get_mut().push(line_style.clone())
}
}
}
}
} else {
self.bracket_pos = HashMap::new();
}
}
fn is_left(c: &char) -> bool {
if *c == '(' || *c == '{' || *c == '[' {
return true;
}
false
}
fn parse(&mut self) {
let new_ast = &mut ASTNode::new();
self.parse_bracket(0, new_ast);
self.ast = new_ast.clone();
Self::patch_len(&mut self.ast);
self.cur = 0;
}
fn parse_bracket(&mut self, level: usize, parent_node: &mut ASTNode) {
let mut counter = 0usize;
while self.cur < self.code.len() {
if self.noparsing_token.contains(&self.code[self.cur]) {
if matches!(self.mode, BracketParserMode::Parsing) {
self.mode = BracketParserMode::NoParsing;
} else {
self.mode = BracketParserMode::Parsing;
}
}
if self.bracket_set.contains_key(&self.code[self.cur])
&& matches!(self.mode, BracketParserMode::Parsing)
{
if Self::is_left(&self.code[self.cur]) {
let code_node = ASTNode::new_with_type(NodeType::Code, counter);
let left_node =
self.bracket_set.get(&self.code[self.cur]).unwrap().clone();
let mut pair_node =
ASTNode::new_with_type(NodeType::Pair, counter + 1);
pair_node.level = level;
pair_node.children.push(code_node);
pair_node.children.push(left_node);
self.cur += 1;
self.parse_bracket(level + 1, &mut pair_node);
parent_node.children.push(pair_node.clone());
counter = 0;
} else if level <= parent_node.level {
let code_node = ASTNode::new_with_type(NodeType::Code, counter);
let right_node =
self.bracket_set.get(&self.code[self.cur]).unwrap().clone();
parent_node.children.push(code_node);
parent_node.children.push(right_node);
let parent_len = parent_node.len;
parent_node.len = parent_len + counter + 1;
counter = 0;
self.cur += 1;
} else {
let code_node = ASTNode::new_with_type(NodeType::Code, counter);
let right_node =
self.bracket_set.get(&self.code[self.cur]).unwrap().clone();
parent_node.children.push(code_node);
parent_node.children.push(right_node);
let parent_len = parent_node.len;
parent_node.len = parent_len + counter + 1;
self.cur += 1;
return;
}
} else {
counter += self.code[self.cur].len_utf8();
self.cur += 1;
}
}
}
fn patch_len(ast: &mut ASTNode) {
if !ast.children.is_empty() {
let mut len = 0usize;
for n in ast.children.iter_mut() {
match n.tt {
NodeType::LeftCurly => len += 1,
NodeType::RightCurly => len += 1,
NodeType::LeftParen => len += 1,
NodeType::RightParen => len += 1,
NodeType::LeftBracket => len += 1,
NodeType::RightBracket => len += 1,
NodeType::Code => len += n.len,
NodeType::Pair => {
Self::patch_len(n);
len += n.len;
}
_ => break,
}
}
ast.len = len;
}
}
fn highlight_pos(
ast: &ASTNode,
pos_vec: &mut Vec<(usize, String)>,
index: &mut usize,
level: &mut usize,
palette: &Vec<String>,
) {
if !ast.children.is_empty() {
for n in ast.children.iter() {
match n.tt {
NodeType::LeftCurly
| NodeType::LeftParen
| NodeType::LeftBracket => {
pos_vec
.push((*index, palette[*level % palette.len()].clone()));
*level += 1;
*index += 1;
}
NodeType::RightCurly
| NodeType::RightParen
| NodeType::RightBracket => {
let (new_level, overflow) = (*level).overflowing_sub(1);
if overflow {
pos_vec.push((*index, "bracket.unpaired".to_string()));
} else {
*level = new_level;
pos_vec.push((
*index,
palette[*level % palette.len()].clone(),
));
}
*index += 1;
}
NodeType::Code => *index += n.len,
NodeType::Pair => {
Self::highlight_pos(n, pos_vec, index, level, palette)
}
_ => break,
}
}
}
}
}
#[derive(Debug, Clone)]
pub struct LanguageLayer {
// mode
// grammar
pub config: Arc<HighlightConfiguration>,
pub(crate) tree: Option<Tree>,
pub ranges: Vec<tree_sitter::Range>,
pub depth: usize,
_parent: Option<LayerId>,
rev: u64,
}
/// This PartialEq implementation only checks if that
/// two layers are theoretically identical (meaning they highlight the same text range with the same language).
/// It does not check whether the layers have the same internal treesitter
/// state.
impl PartialEq for LanguageLayer {
fn eq(&self, other: &Self) -> bool {
self.depth == other.depth
&& self.config.language == other.config.language
&& self.ranges == other.ranges
}
}
/// Hash implementation belongs to PartialEq implementation above.
/// See its documentation for details.
impl Hash for LanguageLayer {
fn hash<H: Hasher>(&self, state: &mut H) {
self.depth.hash(state);
self.config.language.hash(state);
self.ranges.hash(state);
}
}
impl LanguageLayer {
pub fn try_tree(&self) -> Option<&Tree> {
self.tree.as_ref()
}
fn parse(
&mut self,
parser: &mut Parser,
source: &Rope,
had_edits: bool,
cancellation_flag: &AtomicUsize,
) -> Result<(), Error> {
parser
.set_included_ranges(&self.ranges)
.map_err(|_| Error::InvalidRanges)?;
parser
.set_language(&self.config.language)
.map_err(|_| Error::InvalidLanguage)?;
unsafe { parser.set_cancellation_flag(Some(cancellation_flag)) };
let tree = parser
.parse_with(
&mut |byte, _| {
if byte <= source.len() {
source
.iter_chunks(byte..)
.next()
.map(|s| s.as_bytes())
.unwrap_or(&[])
} else {
&[]
}
},
had_edits.then_some(()).and(self.tree.as_ref()),
)
.ok_or(Error::Cancelled)?;
self.tree = Some(tree);
Ok(())
}
}
#[derive(Clone)]
pub struct SyntaxLayers {
layers: HopSlotMap<LayerId, LanguageLayer>,
root: LayerId,
}
impl SyntaxLayers {
pub fn new_empty(config: Arc<HighlightConfiguration>) -> SyntaxLayers {
Self::new(None, config)
}
pub fn new(
source: Option<&Rope>,
config: Arc<HighlightConfiguration>,
) -> SyntaxLayers {
let root_layer = LanguageLayer {
tree: None,
config,
depth: 0,
ranges: vec![tree_sitter::Range {
start_byte: 0,
end_byte: usize::MAX,
start_point: Point::new(0, 0),
end_point: Point::new(usize::MAX, usize::MAX),
}],
_parent: None,
rev: 0,
};
let mut layers = HopSlotMap::default();
let root = layers.insert(root_layer);
let mut syntax = SyntaxLayers { root, layers };
let cancel_flag = AtomicUsize::new(0);
if let Some(source) = source {
if let Err(err) = syntax.update(0, 0, source, None, &cancel_flag) {
tracing::error!("{:?}", err);
}
}
syntax
}
pub fn update(
&mut self,
current_rev: u64,
new_rev: u64,
source: &Rope,
syntax_edits: Option<&[SyntaxEdit]>,
cancellation_flag: &AtomicUsize,
) -> Result<(), Error> {
let mut queue = VecDeque::new();
queue.push_back(self.root);
let injection_callback = |language: &InjectionLanguageMarker| {
let language = match language {
InjectionLanguageMarker::Name(name) => {
LapceLanguage::from_name(name)
}
InjectionLanguageMarker::Filename(path) => {
LapceLanguage::from_path_raw(path)
}
InjectionLanguageMarker::Shebang(id) => LapceLanguage::from_name(id),
};
language
.map(get_highlight_config)
.unwrap_or(Err(highlight::HighlightIssue::NotAvailable))
};
let mut edits = Vec::new();
if let Some(syntax_edits) = syntax_edits {
for edit in syntax_edits {
for edit in &edit.0 {
edits.push(edit);
}
}
}
// This table allows inverse indexing of `layers`.
// That is by hashing a `Layer` you can find
// the `LayerId` of an existing equivalent `Layer` in `layers`.
//
// It is used to determine if a new layer exists for an injection
// or if an existing layer needs to be updated.
let mut layers_table = RawTable::with_capacity(self.layers.len());
let layers_hasher = RandomState::new();
// Use the edits to update all layers markers
fn point_add(a: Point, b: Point) -> Point {
if b.row > 0 {
Point::new(a.row.saturating_add(b.row), b.column)
} else {
Point::new(0, a.column.saturating_add(b.column))
}
}
fn point_sub(a: Point, b: Point) -> Point {
if a.row > b.row {
Point::new(a.row.saturating_sub(b.row), a.column)
} else {
Point::new(0, a.column.saturating_sub(b.column))
}
}
for (layer_id, layer) in self.layers.iter_mut() {
// The root layer always covers the whole range (0..usize::MAX)
if layer.depth == 0 {
continue;
}
if !edits.is_empty() {
for range in &mut layer.ranges {
// Roughly based on https://github.com/tree-sitter/tree-sitter/blob/ddeaa0c7f534268b35b4f6cb39b52df082754413/lib/src/subtree.c#L691-L720
for edit in edits.iter().rev() {
let is_pure_insertion = edit.old_end_byte == edit.start_byte;
// if edit is after range, skip
if edit.start_byte > range.end_byte {
// TODO: || (is_noop && edit.start_byte == range.end_byte)
continue;
}
// if edit is before range, shift entire range by len
if edit.old_end_byte < range.start_byte {
range.start_byte = edit.new_end_byte
+ (range.start_byte - edit.old_end_byte);
range.start_point = point_add(
edit.new_end_position,
point_sub(range.start_point, edit.old_end_position),
);
range.end_byte = edit
.new_end_byte
.saturating_add(range.end_byte - edit.old_end_byte);
range.end_point = point_add(
edit.new_end_position,
point_sub(range.end_point, edit.old_end_position),
);
}
// if the edit starts in the space before and extends into the range
else if edit.start_byte < range.start_byte {
range.start_byte = edit.new_end_byte;
range.start_point = edit.new_end_position;
range.end_byte = range
.end_byte
.saturating_sub(edit.old_end_byte)
.saturating_add(edit.new_end_byte);
range.end_point = point_add(
edit.new_end_position,
point_sub(range.end_point, edit.old_end_position),
);
}
// If the edit is an insertion at the start of the tree, shift
else if edit.start_byte == range.start_byte
&& is_pure_insertion
{
range.start_byte = edit.new_end_byte;
range.start_point = edit.new_end_position;
} else {
range.end_byte = range
.end_byte
.saturating_sub(edit.old_end_byte)
.saturating_add(edit.new_end_byte);
range.end_point = point_add(
edit.new_end_position,
point_sub(range.end_point, edit.old_end_position),
);
}
}
}
}
let hash = layers_hasher.hash_one(layer);
// Safety: insert_no_grow is unsafe because it assumes that the table
// has enough capacity to hold additional elements.
// This is always the case as we reserved enough capacity above.
unsafe { layers_table.insert_no_grow(hash, layer_id) };
}
PARSER.with(|ts_parser| {
let ts_parser = &mut ts_parser.borrow_mut();
ts_parser.parser.set_timeout_micros(1000 * 500); // half a second is pretty generours
let mut cursor = ts_parser.cursors.pop().unwrap_or_default();
// TODO: might need to set cursor range
cursor.set_byte_range(0..usize::MAX);
cursor.set_match_limit(TREE_SITTER_MATCH_LIMIT);
let mut touched = HashSet::new();
while let Some(layer_id) = queue.pop_front() {
// Mark the layer as touched
touched.insert(layer_id);
let layer = &mut self.layers[layer_id];
let had_edits = layer.rev == current_rev && syntax_edits.is_some();
// If a tree already exists, notify it of changes.
if had_edits {
if let Some(tree) = &mut layer.tree {
for edit in edits.iter() {
tree.edit(edit);
}
}
}
// Re-parse the tree.
layer.parse(
&mut ts_parser.parser,
source,
had_edits,
cancellation_flag,
)?;
layer.rev = new_rev;
// Switch to an immutable borrow.
let layer = &self.layers[layer_id];
// Process injections.
if let Some(tree) = layer.try_tree() {
let matches = cursor.matches(
&layer.config.injections_query,
tree.root_node(),
RopeProvider(source),
);
let mut combined_injections =
vec![
(None, Vec::new(), IncludedChildren::default());
layer.config.combined_injections_patterns.len()
];
let mut injections = Vec::new();
let mut last_injection_end = 0;
for mat in matches {
let (injection_capture, content_node, included_children) =
layer.config.injection_for_match(
&layer.config.injections_query,
&mat,
source,
);
// in case this is a combined injection save it for more processing later
if let Some(combined_injection_idx) = layer
.config
.combined_injections_patterns
.iter()
.position(|&pattern| pattern == mat.pattern_index)
{
let entry =
&mut combined_injections[combined_injection_idx];
if injection_capture.is_some() {
entry.0 = injection_capture;
}
if let Some(content_node) = content_node {
if content_node.start_byte() >= last_injection_end {
entry.1.push(content_node);
last_injection_end = content_node.end_byte();
}
}
entry.2 = included_children;
continue;
}
// Explicitly remove this match so that none of its other captures will remain
// in the stream of captures.
mat.remove();
// If a language is found with the given name, then add a new language layer
// to the highlighted document.
if let (Some(injection_capture), Some(content_node)) =
(injection_capture, content_node)
{
match (injection_callback)(&injection_capture) {
Ok(config) => {
let ranges = intersect_ranges(
&layer.ranges,
&[content_node],
included_children,
);
if !ranges.is_empty() {
if content_node.start_byte()
< last_injection_end
{
continue;
}
last_injection_end = content_node.end_byte();
injections.push((config, ranges));
}
}
Err(err) => {
tracing::error!("{:?}", err);
}
}
}
}
for (lang_name, content_nodes, included_children) in
combined_injections
{
if let (Some(lang_name), false) =
(lang_name, content_nodes.is_empty())
{
match (injection_callback)(&lang_name) {
Ok(config) => {
let ranges = intersect_ranges(
&layer.ranges,
&content_nodes,
included_children,
);
if !ranges.is_empty() {
injections.push((config, ranges));
}
}
Err(err) => {
tracing::error!("{:?}", err);
}
}
}
}
let depth = layer.depth + 1;
// TODO: can't inline this since matches borrows self.layers
for (config, ranges) in injections {
let new_layer = LanguageLayer {
tree: None,
config,
depth,
ranges,
_parent: Some(layer_id),
rev: 0,
};
// Find an identical existing layer
let layer = layers_table
.get(layers_hasher.hash_one(&new_layer), |&it| {
self.layers[it] == new_layer
})
.copied();
// ...or insert a new one.
let layer_id =
layer.unwrap_or_else(|| self.layers.insert(new_layer));
queue.push_back(layer_id);
}
}
// TODO: pre-process local scopes at this time, rather than highlight?
// would solve problems with locals not working across boundaries
}
// Return the cursor back in the pool.
ts_parser.cursors.push(cursor);
// Remove all untouched layers
self.layers.retain(|id, _| touched.contains(&id));
Ok(())
})
}
pub fn try_tree(&self) -> Option<&Tree> {
self.layers[self.root].try_tree()
}
/// Iterate over the highlighted regions for a given slice of source code.
pub fn highlight_iter<'a>(
&'a self,
source: &'a Rope,
range: Option<std::ops::Range<usize>>,
cancellation_flag: Option<&'a AtomicUsize>,
) -> impl Iterator<Item = Result<HighlightEvent, Error>> + 'a {
let mut layers = self
.layers
.iter()
.filter_map(|(_, layer)| {
// TODO: if range doesn't overlap layer range, skip it
// Reuse a cursor from the pool if available.
let mut cursor = PARSER.with(|ts_parser| {
let highlighter = &mut ts_parser.borrow_mut();
highlighter.cursors.pop().unwrap_or_default()
});
// The `captures` iterator borrows the `Tree` and the `QueryCursor`, which
// prevents them from being moved. But both of these values are really just
// pointers, so it's actually ok to move them.
let cursor_ref = unsafe {
mem::transmute::<
&mut tree_sitter::QueryCursor,
&mut tree_sitter::QueryCursor,
>(&mut cursor)
};
// if reusing cursors & no range this resets to whole range
cursor_ref.set_byte_range(range.clone().unwrap_or(0..usize::MAX));
cursor_ref.set_match_limit(TREE_SITTER_MATCH_LIMIT);
let mut captures = cursor_ref
.captures(
&layer.config.query,
layer.try_tree()?.root_node(),
RopeProvider(source),
)
.peekable();
// If there's no captures, skip the layer
captures.peek()?;
Some(HighlightIterLayer {
highlight_end_stack: Vec::new(),
scope_stack: vec![LocalScope {
inherits: false,
range: 0..usize::MAX,
local_defs: Vec::new(),
}],
cursor,
_tree: None,
captures: RefCell::new(captures),
config: layer.config.as_ref(), // TODO: just reuse `layer`
depth: layer.depth, // TODO: just reuse `layer`
})
})
.collect::<Vec<_>>();
layers.sort_unstable_by_key(|layer| layer.sort_key());
let mut result = HighlightIter {
source,
byte_offset: range.map_or(0, |r| r.start),
cancellation_flag,
iter_count: 0,
layers,
next_event: None,
last_highlight_range: None,
};
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | true |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-core/src/syntax/edit.rs | lapce-core/src/syntax/edit.rs | use floem_editor_core::buffer::{
InsertsValueIter,
rope_text::{RopeText, RopeTextRef},
};
use lapce_xi_rope::{
Rope, RopeDelta, RopeInfo,
delta::InsertDelta,
multiset::{CountMatcher, Subset},
};
use tree_sitter::Point;
#[derive(Clone)]
pub struct SyntaxEdit(pub(crate) Vec<tree_sitter::InputEdit>);
impl SyntaxEdit {
pub fn new(edits: Vec<tree_sitter::InputEdit>) -> Self {
Self(edits)
}
pub fn from_delta(text: &Rope, delta: RopeDelta) -> SyntaxEdit {
let (ins_delta, deletes) = delta.factor();
Self::from_factored_delta(text, &ins_delta, &deletes)
}
pub fn from_factored_delta(
text: &Rope,
ins_delta: &InsertDelta<RopeInfo>,
deletes: &Subset,
) -> SyntaxEdit {
let deletes = deletes.transform_expand(&ins_delta.inserted_subset());
let mut edits = Vec::new();
let mut insert_edits: Vec<tree_sitter::InputEdit> =
InsertsValueIter::new(ins_delta)
.map(|insert| {
let start = insert.old_offset;
let inserted = insert.node;
create_insert_edit(text, start, inserted)
})
.collect();
insert_edits.reverse();
edits.append(&mut insert_edits);
let text = ins_delta.apply(text);
let mut delete_edits: Vec<tree_sitter::InputEdit> = deletes
.range_iter(CountMatcher::NonZero)
.map(|(start, end)| create_delete_edit(&text, start, end))
.collect();
delete_edits.reverse();
edits.append(&mut delete_edits);
SyntaxEdit::new(edits)
}
}
fn point_at_offset(text: &Rope, offset: usize) -> Point {
let text = RopeTextRef::new(text);
let line = text.line_of_offset(offset);
let col = text.offset_of_line(line + 1).saturating_sub(offset);
Point::new(line, col)
}
fn traverse(point: Point, text: &str) -> Point {
let Point {
mut row,
mut column,
} = point;
for ch in text.chars() {
if ch == '\n' {
row += 1;
column = 0;
} else {
column += 1;
}
}
Point { row, column }
}
pub fn create_insert_edit(
old_text: &Rope,
start: usize,
inserted: &Rope,
) -> tree_sitter::InputEdit {
let start_position = point_at_offset(old_text, start);
tree_sitter::InputEdit {
start_byte: start,
old_end_byte: start,
new_end_byte: start + inserted.len(),
start_position,
old_end_position: start_position,
new_end_position: traverse(
start_position,
&inserted.slice_to_cow(0..inserted.len()),
),
}
}
pub fn create_delete_edit(
old_text: &Rope,
start: usize,
end: usize,
) -> tree_sitter::InputEdit {
let start_position = point_at_offset(old_text, start);
let end_position = point_at_offset(old_text, end);
tree_sitter::InputEdit {
start_byte: start,
// The old end byte position was at the end
old_end_byte: end,
// but since we're deleting everything up to it, it gets 'moved' to where we start
new_end_byte: start,
start_position,
old_end_position: end_position,
new_end_position: start_position,
}
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
lapce/lapce | https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-rpc/src/dap_types.rs | lapce-rpc/src/dap_types.rs | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* Much of the code in this file is modified from [helix](https://github.com/helix-editor/helix)'s implementation of their syntax highlighting, which is under the MPL.
*/
use std::{collections::HashMap, path::PathBuf};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use serde_json::Value;
use crate::counter::Counter;
#[derive(Eq, PartialEq, Hash, Clone, Copy, Debug, Serialize, Deserialize)]
pub struct DapId(pub u64);
impl Default for DapId {
fn default() -> Self {
Self::next()
}
}
impl DapId {
pub fn next() -> Self {
static DAP_ID_COUNTER: Counter = Counter::new();
Self(DAP_ID_COUNTER.next())
}
}
pub struct DapServer {
pub program: String,
pub args: Vec<String>,
pub cwd: Option<PathBuf>,
}
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "kebab-case")]
pub struct RunDebugProgram {
pub program: String,
pub args: Option<Vec<String>>,
}
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "kebab-case")]
pub struct RunDebugConfig {
#[serde(rename = "type")]
pub ty: Option<String>,
pub name: String,
pub program: String,
pub args: Option<Vec<String>>,
pub cwd: Option<String>,
pub env: Option<HashMap<String, String>>,
pub prelaunch: Option<RunDebugProgram>,
#[serde(skip)]
pub debug_command: Option<Vec<String>>,
#[serde(skip)]
pub dap_id: DapId,
#[serde(default)]
pub tracing_output: bool,
#[serde(default)]
pub config_source: ConfigSource,
}
#[derive(Deserialize, Serialize, Debug, Clone, Default, PartialEq, Eq)]
pub enum ConfigSource {
#[default]
Palette,
RunInTerminal,
CodeLens,
}
impl ConfigSource {
pub fn from_palette(&self) -> bool {
*self == Self::Palette
}
}
pub trait Request {
type Arguments: DeserializeOwned + Serialize;
type Result: DeserializeOwned + Serialize;
const COMMAND: &'static str;
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DapRequest {
pub seq: u64,
pub command: String,
pub arguments: Option<Value>,
}
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
pub struct DapResponse {
pub seq: u64,
pub request_seq: u64,
pub success: bool,
pub command: String,
pub message: Option<String>,
pub body: Option<Value>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[serde(tag = "event", content = "body")]
// seq is omitted as unused and is not sent by some implementations
pub enum DapEvent {
Initialized(Option<DebuggerCapabilities>),
Stopped(Stopped),
Continued(Continued),
Exited(Exited),
Terminated(Option<Terminated>),
Thread {
reason: String,
thread_id: ThreadId,
},
Output(Output),
Breakpoint {
reason: String,
breakpoint: Breakpoint,
},
Module {
reason: String,
module: Module,
},
LoadedSource {
reason: String,
source: Source,
},
Process(Process),
Capabilities(Capabilities),
Memory(Memory),
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(tag = "type", rename_all = "camelCase")]
#[allow(clippy::large_enum_variant)]
pub enum DapPayload {
Request(DapRequest),
Response(DapResponse),
Event(DapEvent),
}
#[derive(Debug)]
pub enum Initialize {}
impl Request for Initialize {
type Arguments = InitializeParams;
type Result = DebuggerCapabilities;
const COMMAND: &'static str = "initialize";
}
#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct InitializeParams {
#[serde(rename = "clientID", skip_serializing_if = "Option::is_none")]
pub client_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub client_name: Option<String>,
#[serde(rename = "adapterID")]
pub adapter_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub locale: Option<String>,
#[serde(rename = "linesStartAt1", skip_serializing_if = "Option::is_none")]
pub lines_start_at_one: Option<bool>,
#[serde(rename = "columnsStartAt1", skip_serializing_if = "Option::is_none")]
pub columns_start_at_one: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub path_format: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_variable_type: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_variable_paging: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_run_in_terminal_request: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_memory_references: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_progress_reporting: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_invalidated_event: Option<bool>,
}
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ColumnDescriptor {
pub attribute_name: String,
pub label: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub format: Option<String>,
#[serde(rename = "type", skip_serializing_if = "Option::is_none")]
pub ty: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub width: Option<usize>,
}
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ExceptionBreakpointsFilter {
pub filter: String,
pub label: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub default: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_condition: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub condition_description: Option<String>,
}
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DebuggerCapabilities {
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_configuration_done_request: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_function_breakpoints: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_conditional_breakpoints: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_hit_conditional_breakpoints: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_evaluate_for_hovers: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_step_back: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_set_variable: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_restart_frame: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_goto_targets_request: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_step_in_targets_request: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_completions_request: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_modules_request: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_restart_request: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_exception_options: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_value_formatting_options: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_exception_info_request: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub support_terminate_debuggee: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub support_suspend_debuggee: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_delayed_stack_trace_loading: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_loaded_sources_request: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_log_points: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_terminate_threads_request: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_set_expression: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_terminate_request: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_data_breakpoints: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_read_memory_request: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_write_memory_request: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_disassemble_request: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_cancel_request: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_breakpoint_locations_request: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_clipboard_context: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_stepping_granularity: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_instruction_breakpoints: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supports_exception_filter_options: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub exception_breakpoint_filters: Option<Vec<ExceptionBreakpointsFilter>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub completion_trigger_characters: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub additional_module_columns: Option<Vec<ColumnDescriptor>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supported_checksum_algorithms: Option<Vec<String>>,
}
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Stopped {
pub reason: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub thread_id: Option<ThreadId>,
#[serde(skip_serializing_if = "Option::is_none")]
pub preserve_focus_hint: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub text: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub all_threads_stopped: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub hit_breakpoint_ids: Option<Vec<usize>>,
}
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Continued {
pub thread_id: ThreadId,
#[serde(skip_serializing_if = "Option::is_none")]
pub all_threads_continued: Option<bool>,
}
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Exited {
pub exit_code: usize,
}
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Terminated {
#[serde(skip_serializing_if = "Option::is_none")]
pub restart: Option<Value>,
}
#[derive(
Debug,
Default,
Clone,
Copy,
PartialEq,
Eq,
PartialOrd,
Ord,
Hash,
Deserialize,
Serialize,
)]
pub struct ThreadId(isize);
impl std::fmt::Display for ThreadId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Thread {
pub id: ThreadId,
pub name: String,
}
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Checksum {
pub algorithm: String,
pub checksum: String,
}
#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Source {
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub path: Option<PathBuf>,
#[serde(skip_serializing_if = "Option::is_none")]
pub source_reference: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub presentation_hint: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub origin: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sources: Option<Vec<Source>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub adapter_data: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub checksums: Option<Vec<Checksum>>,
}
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Output {
pub output: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub category: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub group: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub line: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub column: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub variables_reference: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub source: Option<Source>,
#[serde(skip_serializing_if = "Option::is_none")]
pub data: Option<Value>,
}
#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SourceBreakpoint {
pub line: usize,
#[serde(skip_serializing_if = "Option::is_none")]
pub column: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub condition: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub hit_condition: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub log_message: Option<String>,
}
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Breakpoint {
#[serde(skip_serializing_if = "Option::is_none")]
pub id: Option<usize>,
pub verified: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub source: Option<Source>,
#[serde(skip_serializing_if = "Option::is_none")]
pub line: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub column: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub end_line: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub end_column: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub instruction_reference: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub offset: Option<usize>,
}
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Module {
pub id: String, // TODO: || number
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub path: Option<PathBuf>,
#[serde(skip_serializing_if = "Option::is_none")]
pub is_optimized: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub is_user_code: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub symbol_status: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub symbol_file_path: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub date_time_stamp: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub address_range: Option<String>,
}
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Process {
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub system_process_id: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub is_local_process: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub start_method: Option<String>, // TODO: use enum
#[serde(skip_serializing_if = "Option::is_none")]
pub pointer_size: Option<usize>,
}
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Capabilities {
pub capabilities: DebuggerCapabilities,
}
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Memory {
pub memory_reference: String,
pub offset: usize,
pub count: usize,
}
pub enum Launch {}
impl Request for Launch {
type Arguments = Value;
type Result = Value;
const COMMAND: &'static str = "launch";
}
#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RunInTerminalResponse {
#[serde(skip_serializing_if = "Option::is_none")]
pub process_id: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub shell_process_id: Option<u32>,
}
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RunInTerminalArguments {
#[serde(skip_serializing_if = "Option::is_none")]
pub kind: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub title: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cwd: Option<String>,
pub args: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub env: Option<HashMap<String, Option<String>>>,
}
#[derive(Debug)]
pub enum RunInTerminal {}
impl Request for RunInTerminal {
type Arguments = RunInTerminalArguments;
type Result = RunInTerminalResponse;
const COMMAND: &'static str = "runInTerminal";
}
#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SetBreakpointsArguments {
pub source: Source,
#[serde(skip_serializing_if = "Option::is_none")]
pub breakpoints: Option<Vec<SourceBreakpoint>>,
// lines is deprecated
#[serde(skip_serializing_if = "Option::is_none")]
pub source_modified: Option<bool>,
}
#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SetBreakpointsResponse {
#[serde(skip_serializing_if = "Option::is_none")]
pub breakpoints: Option<Vec<Breakpoint>>,
}
#[derive(Debug)]
pub enum SetBreakpoints {}
impl Request for SetBreakpoints {
type Arguments = SetBreakpointsArguments;
type Result = SetBreakpointsResponse;
const COMMAND: &'static str = "setBreakpoints";
}
#[derive(Debug)]
pub enum ConfigurationDone {}
impl Request for ConfigurationDone {
type Arguments = ();
type Result = ();
const COMMAND: &'static str = "configurationDone";
}
#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ContinueArguments {
pub thread_id: ThreadId,
}
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ContinueResponse {
#[serde(skip_serializing_if = "Option::is_none")]
pub all_threads_continued: Option<bool>,
}
#[derive(Debug)]
pub enum Continue {}
impl Request for Continue {
type Arguments = ContinueArguments;
type Result = ContinueResponse;
const COMMAND: &'static str = "continue";
}
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreadsResponse {
pub threads: Vec<Thread>,
}
#[derive(Debug)]
pub enum Threads {}
impl Request for Threads {
type Arguments = ();
type Result = ThreadsResponse;
const COMMAND: &'static str = "threads";
}
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StackFrame {
pub id: usize,
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub source: Option<Source>,
pub line: usize,
pub column: usize,
#[serde(skip_serializing_if = "Option::is_none")]
pub end_line: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub end_column: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub can_restart: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub instruction_pointer_reference: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub module_id: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub presentation_hint: Option<String>,
}
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StackFrameFormat {
#[serde(skip_serializing_if = "Option::is_none")]
pub parameters: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub parameter_types: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub parameter_names: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub parameter_values: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub line: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub module: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub include_all: Option<bool>,
}
#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StackTraceArguments {
pub thread_id: ThreadId,
#[serde(skip_serializing_if = "Option::is_none")]
pub start_frame: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub levels: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub format: Option<StackFrameFormat>,
}
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StackTraceResponse {
#[serde(skip_serializing_if = "Option::is_none")]
pub total_frames: Option<usize>,
pub stack_frames: Vec<StackFrame>,
}
#[derive(Debug)]
pub enum StackTrace {}
impl Request for StackTrace {
type Arguments = StackTraceArguments;
type Result = StackTraceResponse;
const COMMAND: &'static str = "stackTrace";
}
#[derive(Debug)]
pub enum Disconnect {}
impl Request for Disconnect {
type Arguments = ();
type Result = ();
const COMMAND: &'static str = "disconnect";
}
#[derive(Debug)]
pub enum Terminate {}
impl Request for Terminate {
type Arguments = ();
type Result = ();
const COMMAND: &'static str = "terminate";
}
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PauseArguments {
pub thread_id: ThreadId,
}
#[derive(Debug)]
pub enum Pause {}
impl Request for Pause {
type Arguments = PauseArguments;
type Result = ();
const COMMAND: &'static str = "pause";
}
#[derive(Default, Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Scope {
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub presentation_hint: Option<String>,
pub variables_reference: usize,
#[serde(skip_serializing_if = "Option::is_none")]
pub named_variables: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub indexed_variables: Option<usize>,
pub expensive: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub source: Option<Source>,
#[serde(skip_serializing_if = "Option::is_none")]
pub line: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub column: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub end_line: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub end_column: Option<usize>,
}
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ScopesArguments {
pub frame_id: usize,
}
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ScopesResponse {
pub scopes: Vec<Scope>,
}
#[derive(Debug)]
pub enum Scopes {}
impl Request for Scopes {
type Arguments = ScopesArguments;
type Result = ScopesResponse;
const COMMAND: &'static str = "scopes";
}
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ValueFormat {
#[serde(skip_serializing_if = "Option::is_none")]
pub hex: Option<bool>,
}
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VariablePresentationHint {
#[serde(skip_serializing_if = "Option::is_none")]
pub kind: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub attributes: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub visibility: Option<String>,
}
#[derive(Default, Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Variable {
pub name: String,
pub value: String,
#[serde(rename = "type", skip_serializing_if = "Option::is_none")]
pub ty: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub presentation_hint: Option<VariablePresentationHint>,
#[serde(skip_serializing_if = "Option::is_none")]
pub evaluate_name: Option<String>,
pub variables_reference: usize,
#[serde(skip_serializing_if = "Option::is_none")]
pub named_variables: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub indexed_variables: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub memory_reference: Option<String>,
}
#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VariablesArguments {
pub variables_reference: usize,
#[serde(skip_serializing_if = "Option::is_none")]
pub filter: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub start: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub count: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub format: Option<ValueFormat>,
}
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VariablesResponse {
pub variables: Vec<Variable>,
}
#[derive(Debug)]
pub enum Variables {}
impl Request for Variables {
type Arguments = VariablesArguments;
type Result = VariablesResponse;
const COMMAND: &'static str = "variables";
}
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NextArguments {
pub thread_id: ThreadId,
#[serde(skip_serializing_if = "Option::is_none")]
pub granularity: Option<String>,
}
#[derive(Debug)]
pub enum Next {}
impl Request for Next {
type Arguments = NextArguments;
type Result = ();
const COMMAND: &'static str = "next";
}
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StepInArguments {
pub thread_id: ThreadId,
#[serde(skip_serializing_if = "Option::is_none")]
pub target_id: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub granularity: Option<String>,
}
#[derive(Debug)]
pub enum StepIn {}
impl Request for StepIn {
type Arguments = StepInArguments;
type Result = ();
const COMMAND: &'static str = "stepIn";
}
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StepOutArguments {
pub thread_id: ThreadId,
#[serde(skip_serializing_if = "Option::is_none")]
pub granularity: Option<String>,
}
#[derive(Debug)]
pub enum StepOut {}
impl Request for StepOut {
type Arguments = StepOutArguments;
type Result = ();
const COMMAND: &'static str = "stepOut";
}
| rust | Apache-2.0 | 59ce6df700ce4efbe4498a719fe52195e083d2ee | 2026-01-04T15:32:17.267102Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.