Implemented Expander

- Updated example to show behavior
- Created styles for Expander and ExpanderRow
- Simpler implementation of `ExpanderRow`
- Deleted `ExpanderData` and replaced it with `ExpanderRow`
- Every row can now have child rows.
- Ran cargo fmt.
- Deleted settings example
- Added expander to cosmic example
- Expander icons now render

ListBox partially implemented
This commit is contained in:
Eduardo Flores 2022-10-09 11:25:46 -07:00 committed by Michael Murphy
parent a50294676d
commit 7743d0d084
22 changed files with 1222 additions and 738 deletions

View file

@ -1,33 +1,7 @@
use cosmic::{
widget::{
button,
list_item,
list_row,
list_section,
list_view,
nav_button,
toggler,
nav_bar_style,
header_bar,
},
settings,
iced::{self, theme, Alignment, Application, Color, Command, Element, Length, Theme},
iced::widget::{
checkbox,
column,
container,
horizontal_space,
pick_list,
progress_bar,
radio,
row,
slider,
text
},
iced_lazy::responsive,
iced_winit::window::{drag, maximize, minimize},
scrollable
};
use cosmic::{iced::Application, settings};
mod window;
pub use window::*;
pub fn main() -> cosmic::iced::Result {
let mut settings = settings();
@ -36,267 +10,3 @@ pub fn main() -> cosmic::iced::Result {
// settings.window.decorations = false;
Window::run(settings)
}
#[derive(Default)]
struct Window {
page: u8,
debug: bool,
theme: Theme,
slider_value: f32,
checkbox_value: bool,
toggler_value: bool,
pick_list_selected: Option<&'static str>,
sidebar_toggled: bool,
show_minimize: bool,
show_maximize: bool,
exit: bool,
}
impl Window {
pub fn sidebar_toggled(mut self, toggled: bool) -> Self {
self.sidebar_toggled = toggled;
self
}
pub fn show_maximize(mut self, show: bool) -> Self {
self.show_maximize = show;
self
}
pub fn show_minimize(mut self, show: bool) -> Self {
self.show_minimize = show;
self
}
}
#[allow(dead_code)]
#[derive(Clone, Copy, Debug)]
enum Message {
Page(u8),
Debug(bool),
ThemeChanged(Theme),
ButtonPressed,
SliderChanged(f32),
CheckboxToggled(bool),
TogglerToggled(bool),
PickListSelected(&'static str),
Close,
ToggleSidebar,
Drag,
Minimize,
Maximize,
}
impl Application for Window {
type Executor = iced::executor::Default;
type Flags = ();
type Message = Message;
type Theme = Theme;
fn new(_flags: ()) -> (Self, Command<Self::Message>) {
let mut window = Window::default()
.sidebar_toggled(true)
.show_maximize(true)
.show_minimize(true);
window.slider_value = 50.0;
window.pick_list_selected = Some("Option 1");
(window, Command::none())
}
fn title(&self) -> String {
String::from("COSMIC Design System - Iced")
}
fn update(&mut self, message: Message) -> iced::Command<Self::Message> {
match message {
Message::Page(page) => self.page = page,
Message::Debug(debug) => self.debug = debug,
Message::ThemeChanged(theme) => self.theme = theme,
Message::ButtonPressed => {}
Message::SliderChanged(value) => self.slider_value = value,
Message::CheckboxToggled(value) => self.checkbox_value = value,
Message::TogglerToggled(value) => self.toggler_value = value,
Message::PickListSelected(value) => self.pick_list_selected = Some(value),
Message::Close => self.exit = true,
Message::ToggleSidebar => self.sidebar_toggled = !self.sidebar_toggled,
Message::Drag => return drag(),
Message::Minimize => return minimize(),
Message::Maximize => return maximize(),
}
iced::Command::none()
}
fn view(&self) -> Element<Message> {
let mut header: Element<Message, _> = header_bar()
.title(self.title())
.sidebar_active(self.sidebar_toggled)
.show_minimize(self.show_minimize)
.show_maximize(self.show_maximize)
.on_close(Message::Close)
.on_drag(Message::Drag)
.on_maximize(Message::Maximize)
.on_minimize(Message::Minimize)
.on_sidebar_toggle(Message::ToggleSidebar)
.into();
if self.debug {
header = header.explain(Color::WHITE);
}
// TODO: Adding responsive makes this regenerate on every size change, and regeneration
// involves allocations for many different items. Ideally, we could only make the nav bar
// responsive and leave the content to be sized normally.
let content = responsive(|size| {
let condensed = size.width < 900.0;
let sidebar: Element<_> = cosmic::navbar![
nav_button!("network-wireless", "Wi-Fi", condensed)
.on_press(Message::Page(0))
.style(if self.page == 0 { theme::Button::Primary } else { theme::Button::Text })
,
nav_button!("preferences-desktop", "Desktop", condensed)
.on_press(Message::Page(1))
.style(if self.page == 1 { theme::Button::Primary } else { theme::Button::Text })
,
nav_button!("system-software-update", "OS Upgrade & Recovery", condensed)
.on_press(Message::Page(2))
.style(if self.page == 2 { theme::Button::Primary } else { theme::Button::Text }),
]
.active(self.sidebar_toggled)
.condensed(condensed)
.style(theme::Container::Custom(nav_bar_style))
.into();
let choose_theme = [Theme::Light, Theme::Dark].iter().fold(
row![text("Debug theme:")].spacing(10).align_items(Alignment::Center),
|row, theme| {
row.push(radio(
format!("{:?}", theme),
*theme,
Some(self.theme),
Message::ThemeChanged,
))
},
);
let content: Element<_> = list_view!(
list_section!(
"Debug",
choose_theme,
toggler(
String::from("Debug layout"),
self.debug,
Message::Debug,
)
),
list_section!(
"Buttons",
list_row!(
button!("Primary")
.style(theme::Button::Primary)
.on_press(Message::ButtonPressed)
,
button!("Secondary")
.style(theme::Button::Secondary)
.on_press(Message::ButtonPressed)
,
button!("Positive")
.style(theme::Button::Positive)
.on_press(Message::ButtonPressed)
,
button!("Destructive")
.style(theme::Button::Destructive)
.on_press(Message::ButtonPressed)
,
button!("Text")
.style(theme::Button::Text)
.on_press(Message::ButtonPressed)
,
),
list_row!(
button!("Primary")
.style(theme::Button::Primary)
,
button!("Secondary")
.style(theme::Button::Secondary)
,
button!("Positive")
.style(theme::Button::Positive)
,
button!("Destructive")
.style(theme::Button::Destructive)
,
button!("Text")
.style(theme::Button::Text)
,
),
),
list_section!(
"Controls",
list_item!(
"Toggler",
toggler(None, self.toggler_value, Message::TogglerToggled)
),
list_item!(
"Pick List (TODO)",
pick_list(
vec![
"Option 1",
"Option 2",
"Option 3",
"Option 4",
],
self.pick_list_selected,
Message::PickListSelected
)
.padding([8, 0, 8, 16])
),
list_item!(
"Slider",
slider(0.0..=100.0, self.slider_value, Message::SliderChanged)
.width(Length::Units(250))
),
list_item!(
"Progress",
progress_bar(0.0..=100.0, self.slider_value)
.width(Length::Units(250))
.height(Length::Units(4))
),
checkbox("Checkbox", self.checkbox_value, Message::CheckboxToggled),
)
)
.into();
let mut widgets = Vec::with_capacity(2);
widgets.push(if self.debug { sidebar.explain(Color::WHITE) } else { sidebar });
widgets.push(
scrollable!(row![
horizontal_space(Length::Fill),
if self.debug { content.explain(Color::WHITE) } else { content },
horizontal_space(Length::Fill),
])
.into()
);
container(row(widgets))
.padding([16, 16])
.width(Length::Fill)
.height(Length::Fill)
.into()
}).into();
column(vec![header, content]).into()
}
fn should_exit(&self) -> bool {
self.exit
}
fn theme(&self) -> Theme {
self.theme
}
}

View file

@ -0,0 +1,307 @@
use cosmic::widget::{expander, expander_row, list_section_style, ListBox};
use cosmic::{
iced::widget::{
checkbox, column, container, horizontal_space, pick_list, progress_bar, radio, row, slider,
text,
},
iced::{self, theme, Alignment, Application, Color, Command, Element, Length, Theme},
iced_lazy::responsive,
iced_winit::window::{drag, maximize, minimize},
scrollable,
widget::{
button, header_bar, list_item, list_row, list_section, list_view, nav_bar_style,
nav_button, toggler,
},
};
#[derive(Default)]
pub struct Window {
page: u8,
debug: bool,
theme: Theme,
slider_value: f32,
checkbox_value: bool,
toggler_value: bool,
pick_list_selected: Option<&'static str>,
sidebar_toggled: bool,
show_minimize: bool,
show_maximize: bool,
exit: bool,
}
impl Window {
pub fn sidebar_toggled(mut self, toggled: bool) -> Self {
self.sidebar_toggled = toggled;
self
}
pub fn show_maximize(mut self, show: bool) -> Self {
self.show_maximize = show;
self
}
pub fn show_minimize(mut self, show: bool) -> Self {
self.show_minimize = show;
self
}
}
#[allow(dead_code)]
#[derive(Clone, Copy, Debug)]
pub enum Message {
Page(u8),
Debug(bool),
ThemeChanged(Theme),
ButtonPressed,
SliderChanged(f32),
CheckboxToggled(bool),
TogglerToggled(bool),
PickListSelected(&'static str),
RowSelected(usize),
Close,
ToggleSidebar,
Drag,
Minimize,
Maximize,
}
impl Application for Window {
type Executor = iced::executor::Default;
type Flags = ();
type Message = Message;
type Theme = Theme;
fn new(_flags: ()) -> (Self, Command<Self::Message>) {
let mut window = Window::default()
.sidebar_toggled(true)
.show_maximize(true)
.show_minimize(true);
window.slider_value = 50.0;
window.pick_list_selected = Some("Option 1");
(window, Command::none())
}
fn title(&self) -> String {
String::from("COSMIC Design System - Iced")
}
fn update(&mut self, message: Message) -> iced::Command<Self::Message> {
match message {
Message::Page(page) => self.page = page,
Message::Debug(debug) => self.debug = debug,
Message::ThemeChanged(theme) => self.theme = theme,
Message::ButtonPressed => {}
Message::SliderChanged(value) => self.slider_value = value,
Message::CheckboxToggled(value) => self.checkbox_value = value,
Message::TogglerToggled(value) => self.toggler_value = value,
Message::PickListSelected(value) => self.pick_list_selected = Some(value),
Message::Close => self.exit = true,
Message::ToggleSidebar => self.sidebar_toggled = !self.sidebar_toggled,
Message::Drag => return drag(),
Message::Minimize => return minimize(),
Message::Maximize => return maximize(),
Message::RowSelected(row) => println!("Selected row {row}"),
}
iced::Command::none()
}
fn view(&self) -> Element<Message> {
let mut header: Element<Message, _> = header_bar()
.title(self.title())
.sidebar_active(self.sidebar_toggled)
.show_minimize(self.show_minimize)
.show_maximize(self.show_maximize)
.on_close(Message::Close)
.on_drag(Message::Drag)
.on_maximize(Message::Maximize)
.on_minimize(Message::Minimize)
.on_sidebar_toggle(Message::ToggleSidebar)
.into();
if self.debug {
header = header.explain(Color::WHITE);
}
// TODO: Adding responsive makes this regenerate on every size change, and regeneration
// involves allocations for many different items. Ideally, we could only make the nav bar
// responsive and leave the content to be sized normally.
let content = responsive(|size| {
let condensed = size.width < 900.0;
let sidebar: Element<_> = cosmic::navbar![
nav_button!("network-wireless", "Wi-Fi", condensed)
.on_press(Message::Page(0))
.style(if self.page == 0 {
theme::Button::Primary
} else {
theme::Button::Text
}),
nav_button!("preferences-desktop", "Desktop", condensed)
.on_press(Message::Page(1))
.style(if self.page == 1 {
theme::Button::Primary
} else {
theme::Button::Text
}),
nav_button!("system-software-update", "OS Upgrade & Recovery", condensed)
.on_press(Message::Page(2))
.style(if self.page == 2 {
theme::Button::Primary
} else {
theme::Button::Text
}),
]
.active(self.sidebar_toggled)
.condensed(condensed)
.style(theme::Container::Custom(nav_bar_style))
.into();
let choose_theme = [Theme::Light, Theme::Dark].iter().fold(
row![text("Debug theme:")]
.spacing(10)
.align_items(Alignment::Center),
|row, theme| {
row.push(radio(
format!("{:?}", theme),
*theme,
Some(self.theme),
Message::ThemeChanged,
))
},
);
let content: Element<_> = list_view!(
list_section!(
"Debug",
choose_theme,
toggler(String::from("Debug layout"), self.debug, Message::Debug,)
),
list_section!(
"Buttons",
list_row!(
button!("Primary")
.style(theme::Button::Primary)
.on_press(Message::ButtonPressed),
button!("Secondary")
.style(theme::Button::Secondary)
.on_press(Message::ButtonPressed),
button!("Positive")
.style(theme::Button::Positive)
.on_press(Message::ButtonPressed),
button!("Destructive")
.style(theme::Button::Destructive)
.on_press(Message::ButtonPressed),
button!("Text")
.style(theme::Button::Text)
.on_press(Message::ButtonPressed),
),
list_row!(
button!("Primary").style(theme::Button::Primary),
button!("Secondary").style(theme::Button::Secondary),
button!("Positive").style(theme::Button::Positive),
button!("Destructive").style(theme::Button::Destructive),
button!("Text").style(theme::Button::Text),
),
),
list_section!(
"Controls",
list_item!(
"Toggler",
toggler(None, self.toggler_value, Message::TogglerToggled)
),
list_item!(
"Pick List (TODO)",
pick_list(
vec!["Option 1", "Option 2", "Option 3", "Option 4",],
self.pick_list_selected,
Message::PickListSelected
)
.padding([8, 0, 8, 16])
),
list_item!(
"Slider",
slider(0.0..=100.0, self.slider_value, Message::SliderChanged)
.width(Length::Units(250))
),
list_item!(
"Progress",
progress_bar(0.0..=100.0, self.slider_value)
.width(Length::Units(250))
.height(Length::Units(4))
),
checkbox("Checkbox", self.checkbox_value, Message::CheckboxToggled),
),
list_section!(
"Expander",
expander()
.title("Label")
.subtitle("Caption")
.icon(String::from("edit-paste"))
.on_row_selected(Box::new(Message::RowSelected))
.rows(vec![
expander_row()
.title("Label")
.subtitle("Caption")
.icon(String::from("help-about")),
expander_row().subtitle("Caption").title("Label"),
expander_row().title("Label")
])
),
list_section!(
"List Box",
ListBox::with_children(
vec![
cosmic::list_box_row!("Title").into(),
cosmic::list_box_row!("Title", "Subtitle").into(),
cosmic::list_box_row!("Title", "", "edit-paste").into(),
cosmic::list_box_row!("", "Subtitle", "edit-paste").into(),
cosmic::list_box_row!("Title", "Subtitle", "edit-paste").into()
],
true,
)
.style(theme::Container::Custom(list_section_style))
),
)
.into();
let mut widgets = Vec::with_capacity(2);
widgets.push(if self.debug {
sidebar.explain(Color::WHITE)
} else {
sidebar
});
widgets.push(
scrollable!(row![
horizontal_space(Length::Fill),
if self.debug {
content.explain(Color::WHITE)
} else {
content
},
horizontal_space(Length::Fill),
])
.into(),
);
container(row(widgets))
.padding([16, 16])
.width(Length::Fill)
.height(Length::Fill)
.into()
})
.into();
column(vec![header, content]).into()
}
fn should_exit(&self) -> bool {
self.exit
}
fn theme(&self) -> Theme {
self.theme
}
}

View file

@ -1,9 +0,0 @@
[package]
name = "settings"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
libcosmic = { path = "../..", features = ["debug"] }

View file

@ -1,10 +0,0 @@
use cosmic::{settings, iced::Application};
mod window;
use window::*;
fn main() -> cosmic::iced::Result {
let mut settings = settings();
settings.window.min_size = Some((600, 300));
App::run(settings)
}

View file

@ -1,150 +0,0 @@
use cosmic::{
widget::{
header_bar,
nav_bar_style
},
iced,
iced::{
Theme,
Application,
Element,
widget::{
container,
column
},
},
iced_winit::{
Command,
Length,
widget::row,
window::drag,
theme
},
nav_button,
iced_lazy::responsive
};
#[derive(Default)]
pub struct App {
page: u8,
theme: Theme,
sidebar_toggled: bool,
show_minimize: bool,
show_maximize: bool,
exit: bool,
}
impl App {
pub fn sidebar_toggled(mut self, toggled: bool) -> Self {
self.sidebar_toggled = toggled;
self
}
pub fn show_maximize(mut self, show: bool) -> Self {
self.show_maximize = show;
self
}
pub fn show_minimize(mut self, show: bool) -> Self {
self.show_minimize = show;
self
}
}
#[allow(dead_code)]
#[derive(Debug, Clone, Copy)]
pub enum AppMsg {
Close,
ToggleSidebar(bool),
Drag,
Minimize,
Maximize,
Page(u8),
}
impl Application for App {
type Executor = iced::executor::Default;
type Flags = ();
type Message = AppMsg;
type Theme = Theme;
fn new(_flags: Self::Flags) -> (Self, Command<Self::Message>) {
(
App::default()
.sidebar_toggled(true)
.show_maximize(true)
.show_minimize(true),
Command::none()
)
}
fn title(&self) -> String {
String::from("COSMIC Settings")
}
fn update(&mut self, message: Self::Message) -> Command<Self::Message> {
match message {
AppMsg::Close => self.exit = true,
AppMsg::ToggleSidebar(toggled) => self.sidebar_toggled = toggled,
AppMsg::Drag => return drag(),
AppMsg::Minimize => {},
AppMsg::Maximize => {},
AppMsg::Page(page) => self.page = page,
}
Command::none()
}
fn view(&self) -> iced::Element<Self::Message> {
let header = header_bar(
self.title().as_str(),
self.sidebar_toggled,
self.show_minimize,
self.show_maximize,
|toggled| AppMsg::ToggleSidebar(toggled),
|| AppMsg::Close,
|| AppMsg::Drag
).into();
let content = responsive(|size| {
let condensed = size.width < 900.0;
let sidebar: Element<_> = cosmic::navbar![
nav_button!("network-wireless", "Wi-Fi", condensed)
.on_press(AppMsg::Page(0))
.style(if self.page == 0 { theme::Button::Primary } else { theme::Button::Text })
,
nav_button!("preferences-desktop", "Desktop", condensed)
.on_press(AppMsg::Page(1))
.style(if self.page == 1 { theme::Button::Primary } else { theme::Button::Text })
,
nav_button!("system-software-update", "OS Upgrade & Recovery", condensed)
.on_press(AppMsg::Page(2))
.style(if self.page == 2 { theme::Button::Primary } else { theme::Button::Text }),
]
.active(self.sidebar_toggled)
.condensed(condensed)
.style(theme::Container::Custom(nav_bar_style))
.into();
let mut widgets = Vec::with_capacity(2);
widgets.push(sidebar);
container(row(widgets))
.padding([8, 8])
.width(Length::Fill)
.height(Length::Fill)
.into()
}).into();
column(vec![header, content]).into()
}
fn should_exit(&self) -> bool {
self.exit
}
fn theme(&self) -> Theme {
self.theme
}
}

View file

@ -93,7 +93,12 @@ impl<'a> TextBuffer<'a> {
self.layout_lines.clear();
for line in self.shape_lines.iter() {
let layout_i = self.layout_lines.len();
line.layout(self.font_size, self.line_width, &mut self.layout_lines, layout_i);
line.layout(
self.font_size,
self.line_width,
&mut self.layout_lines,
layout_i,
);
}
self.redraw = true;
@ -173,7 +178,7 @@ impl<'a> TextBuffer<'a> {
self.cursor.glyph -= 1;
self.redraw = true;
}
},
}
TextAction::Right => {
let line = &self.layout_lines[self.cursor.line];
if self.cursor.glyph > line.glyphs.len() {
@ -184,19 +189,19 @@ impl<'a> TextBuffer<'a> {
self.cursor.glyph += 1;
self.redraw = true;
}
},
}
TextAction::Up => {
if self.cursor.line > 0 {
self.cursor.line -= 1;
self.redraw = true;
}
},
}
TextAction::Down => {
if self.cursor.line + 1 < self.layout_lines.len() {
self.cursor.line += 1;
self.redraw = true;
}
},
}
TextAction::Backspace => {
let line = &self.layout_lines[self.cursor.line];
if self.cursor.glyph > line.glyphs.len() {
@ -210,7 +215,7 @@ impl<'a> TextBuffer<'a> {
text_line.remove(glyph.start);
self.reshape_line(line.line_i);
}
},
}
TextAction::Delete => {
let line = &self.layout_lines[self.cursor.line];
if self.cursor.glyph < line.glyphs.len() {
@ -219,7 +224,7 @@ impl<'a> TextBuffer<'a> {
text_line.remove(glyph.start);
self.reshape_line(line.line_i);
}
},
}
TextAction::Insert(character) => {
let line = &self.layout_lines[self.cursor.line];
if self.cursor.glyph >= line.glyphs.len() {
@ -229,7 +234,7 @@ impl<'a> TextBuffer<'a> {
text_line.insert(glyph.end, character);
self.cursor.glyph += 1;
self.reshape_line(line.line_i);
},
}
None => {
let text_line = &mut self.text_lines[line.line_i.get()];
text_line.push(character);
@ -244,7 +249,7 @@ impl<'a> TextBuffer<'a> {
self.cursor.glyph += 1;
self.reshape_line(line.line_i);
}
},
}
}
}
}

View file

@ -29,9 +29,7 @@ impl<'a> FontLayoutLine<'a> {
let y = bb.min.y as i32;
outline.draw(|off_x, off_y, v| {
//TODO: ensure v * 255.0 does not overflow!
let color =
((v * 255.0) as u32) << 24 |
base & 0xFFFFFF;
let color = ((v * 255.0) as u32) << 24 | base & 0xFFFFFF;
f(x + off_x as i32, y + off_y as i32, color);
});
}
@ -42,9 +40,7 @@ impl<'a> FontLayoutLine<'a> {
let y = bb.min.y;
glyph.inner.draw(|off_x, off_y, v| {
//TODO: ensure v * 255.0 does not overflow!
let color =
((v * 255.0) as u32) << 24 |
base & 0xFFFFFF;
let color = ((v * 255.0) as u32) << 24 | base & 0xFFFFFF;
f(x + off_x as i32, y + off_y as i32, color);
});
}

View file

@ -1,4 +1,4 @@
use super::{Font, FontLineIndex, FontShapeGlyph, FontShapeWord, FontShapeLine, FontShapeSpan};
use super::{Font, FontLineIndex, FontShapeGlyph, FontShapeLine, FontShapeSpan, FontShapeWord};
pub struct FontMatches<'a> {
pub fonts: Vec<Font<'a>>,
@ -22,7 +22,7 @@ impl<'a> FontMatches<'a> {
let rtl = match buffer.direction() {
rustybuzz::Direction::RightToLeft => true,
//TODO: other directions?
_ => false,
_ => false,
};
assert_eq!(rtl, span_rtl);
@ -177,7 +177,14 @@ impl<'a> FontMatches<'a> {
FontShapeWord { blank, glyphs }
}
fn shape_span(&self, line: &str, start_span: usize, end_span: usize, line_rtl: bool, span_rtl: bool) -> FontShapeSpan {
fn shape_span(
&self,
line: &str,
start_span: usize,
end_span: usize,
line_rtl: bool,
span_rtl: bool,
) -> FontShapeSpan {
let span = &line[start_span..end_span];
log::debug!(" Span {}: '{}'", if span_rtl { "RTL" } else { "LTR" }, span);
@ -251,10 +258,6 @@ impl<'a> FontMatches<'a> {
line_rtl
};
FontShapeLine {
line_i,
rtl,
spans,
}
FontShapeLine { line_i, rtl, spans }
}
}

View file

@ -39,10 +39,7 @@ impl<'a> FontShapeGlyph<'a> {
#[cfg(feature = "rusttype")]
let inner = self.font.rusttype.glyph(self.inner)
.scaled(rusttype::Scale::uniform(font_size as f32))
.positioned(rusttype::point(
x + x_offset,
y - y_offset,
));
.positioned(rusttype::point(x + x_offset, y - y_offset));
#[cfg(feature = "swash")]
let inner = CacheKey::new(
@ -79,7 +76,13 @@ pub struct FontShapeLine<'a> {
}
impl<'a> FontShapeLine<'a> {
pub fn layout(&self, font_size: i32, line_width: i32, layout_lines: &mut Vec<FontLayoutLine<'a>>, mut layout_i: usize) {
pub fn layout(
&self,
font_size: i32,
line_width: i32,
layout_lines: &mut Vec<FontLayoutLine<'a>>,
mut layout_i: usize,
) {
let mut push_line = true;
let mut glyphs = Vec::new();
@ -128,7 +131,7 @@ impl<'a> FontShapeLine<'a> {
fit_x += word_size;
}
}
if ! word_ranges.is_empty() {
if !word_ranges.is_empty() {
while fitting_end > 0 {
if span.words[fitting_end - 1].blank {
fitting_end -= 1;
@ -174,6 +177,33 @@ impl<'a> FontShapeLine<'a> {
for (range, wrap) in word_ranges {
for word in span.words[range].iter() {
let mut word_size = 0.0;
for glyph in word.glyphs.iter() {
word_size += font_size as f32 * glyph.x_advance;
}
//TODO: make wrapping optional
let wrap = if self.rtl {
x - word_size < end_x
} else {
x + word_size > end_x
};
if wrap && !glyphs.is_empty() {
let mut glyphs_swap = Vec::new();
std::mem::swap(&mut glyphs, &mut glyphs_swap);
layout_lines.insert(
layout_i,
FontLayoutLine {
line_i: self.line_i,
glyphs: glyphs_swap,
},
);
layout_i += 1;
x = start_x;
y = 0.0;
}
for glyph in word.glyphs.iter() {
let x_advance = font_size as f32 * glyph.x_advance;
let y_advance = font_size as f32 * glyph.y_advance;
@ -185,7 +215,7 @@ impl<'a> FontShapeLine<'a> {
glyphs.push(glyph.layout(font_size, x, y));
push_line = true;
if ! self.rtl {
if !self.rtl {
x += x_advance;
}
y += y_advance;
@ -195,10 +225,13 @@ impl<'a> FontShapeLine<'a> {
if wrap {
let mut glyphs_swap = Vec::new();
std::mem::swap(&mut glyphs, &mut glyphs_swap);
layout_lines.insert(layout_i, FontLayoutLine {
line_i: self.line_i,
glyphs: glyphs_swap
});
layout_lines.insert(
layout_i,
FontLayoutLine {
line_i: self.line_i,
glyphs: glyphs_swap,
},
);
layout_i += 1;
x = start_x;
@ -208,10 +241,13 @@ impl<'a> FontShapeLine<'a> {
}
if push_line {
layout_lines.insert(layout_i, FontLayoutLine {
line_i: self.line_i,
glyphs
});
layout_lines.insert(
layout_i,
FontLayoutLine {
line_i: self.line_i,
glyphs,
},
);
}
}
}

View file

@ -18,7 +18,7 @@ fn main() {
Ok((w, h)) => {
eprintln!("Display size: {}, {}", w, h);
(h as i32 / 1600) + 1
},
}
Err(err) => {
eprintln!("Failed to get display size: {}", err);
1
@ -31,8 +31,9 @@ fn main() {
1024 * display_scale as u32,
768 * display_scale as u32,
"COSMIC TEXT",
&[WindowFlag::Resizable]
).unwrap();
&[WindowFlag::Resizable],
)
.unwrap();
let font_system = FontSystem::new();
@ -122,22 +123,27 @@ fn main() {
let mut new_cursor_opt = None;
let mut line_y = line_height;
for (line_i, line) in buffer.layout_lines().iter().skip(scroll as usize).enumerate() {
for (line_i, line) in buffer
.layout_lines()
.iter()
.skip(scroll as usize)
.enumerate()
{
if line_y >= window.height() as i32 {
break;
}
if mouse_left
&& mouse_y >= line_y - font_size
&& mouse_y < line_y - font_size + line_height
&& mouse_y >= line_y - font_size
&& mouse_y < line_y - font_size + line_height
{
let new_cursor_line = line_i + scroll as usize;
let mut new_cursor_glyph = line.glyphs.len();
for (glyph_i, glyph) in line.glyphs.iter().enumerate() {
if mouse_x >= line_x + glyph.x as i32
&& mouse_x <= line_x + (glyph.x + glyph.w) as i32
&& mouse_x <= line_x + (glyph.x + glyph.w) as i32
{
new_cursor_glyph = glyph_i;
new_cursor_glyph = glyph_i;
}
}
new_cursor_opt = Some(TextCursor::new(new_cursor_line, new_cursor_glyph));
@ -181,14 +187,14 @@ fn main() {
if buffer.cursor.glyph >= line.glyphs.len() {
let x = match line.glyphs.last() {
Some(glyph) => glyph.x + glyph.w,
None => 0.0
None => 0.0,
};
window.rect(
line_x + x as i32,
line_y - font_size,
(font_size / 2) as u32,
line_height as u32,
Color::rgba(0xFF, 0xFF, 0xFF, 0x20)
Color::rgba(0xFF, 0xFF, 0xFF, 0x20),
);
} else {
let glyph = &line.glyphs[buffer.cursor.glyph];
@ -197,7 +203,7 @@ fn main() {
line_y - font_size,
glyph.w as u32,
line_height as u32,
Color::rgba(0xFF, 0xFF, 0xFF, 0x20)
Color::rgba(0xFF, 0xFF, 0xFF, 0x20),
);
let text_line = &buffer.text_lines()[line.line_i.get()];
@ -269,24 +275,26 @@ fn main() {
orbclient::K_MINUS if event.pressed && ctrl_pressed => if font_size_i > 0 {
font_size_i -= 1;
buffer.set_font_size(font_sizes[font_size_i].0 * display_scale);
},
orbclient::K_EQUALS if event.pressed && ctrl_pressed => if font_size_i + 1 < font_sizes.len() {
font_size_i += 1;
buffer.set_font_size(font_sizes[font_size_i].0 * display_scale);
},
_ => (),
}
orbclient::K_EQUALS if event.pressed && ctrl_pressed => {
if font_size_i + 1 < font_sizes.len() {
font_size_i += 1;
buffer.set_font_size(font_sizes[font_size_i].0 * display_scale);
}
}
_ => (),
}
},
EventOption::TextInput(event) if ! ctrl_pressed => {
EventOption::TextInput(event) if !ctrl_pressed => {
buffer.action(TextAction::Insert(event.character));
},
}
EventOption::Mouse(event) => {
mouse_x = event.x;
mouse_y = event.y;
if mouse_left {
rehit = true;
}
},
}
EventOption::Button(event) => {
if event.left != mouse_left {
mouse_left = event.left;
@ -297,11 +305,11 @@ fn main() {
}
EventOption::Resize(event) => {
buffer.set_line_width(event.width as i32 - line_x * 2);
},
}
EventOption::Scroll(event) => {
scroll -= event.y * 3;
buffer.redraw = true;
},
}
EventOption::Quit(_) => return,
_ => (),
}