A new style desktop shell for Windows 11: menu bar, Dock, Finder, Spotlight, Control Center and Liquid Glass, in native C++.
Rust
//! TextEdit (src\textedit\main.cpp): documento .rtf ou .txt no RichEdit do Windows, com a barra de formatação do
//! Mac por cima (desenhada em Direct2D). Ctrl+N/O/S/Shift+S/Shift+T/B/I/U/W como no C++.
#![windows_subsystem = "windows"]
use comum::app2d::{self, *};
use comum::ctxmenu::{self, Item};
use comum::windows::core::*;
use comum::windows::Win32::Foundation::*;
use comum::windows::Win32::Graphics::Direct2D::Common::*;
use comum::windows::Win32::Graphics::DirectWrite::*;
use comum::windows::Win32::Storage::FileSystem::*;
use comum::windows::Win32::System::LibraryLoader::*;
use comum::windows::Win32::UI::Controls::RichEdit::*;
use comum::windows::Win32::UI::Controls::WM_MOUSELEAVE;
use comum::windows::Win32::UI::Input::KeyboardAndMouse::*;
use comum::windows::Win32::UI::Shell::*;
use comum::windows::Win32::UI::WindowsAndMessaging::*;
use comum::*;
const TBAR: f32 = 40.0;
const EM_GETMODIFY: u32 = 0x00B8;
const EM_SETMODIFY: u32 = 0x00B9;
const EM_SETRECT: u32 = 0x00B3;
const EN_CHANGE: u32 = 0x0300;
const G_TITLE: f32 = 32.0;
const G_ROW_Y: f32 = 50.0;
const G_RULER0: f32 = 68.0;
const G_RULER1: f32 = 100.0;
const STEPS: [i32; 12] = [9, 10, 11, 12, 13, 14, 18, 24, 36, 48, 64, 72];
#[derive(Clone, Copy, PartialEq)]
enum B {
Font,
Smaller,
Size,
Bigger,
Color,
Bold,
Italic,
Under,
Left,
Center,
Right,
Just,
List,
Strike,
Clear,
Style,
Spacing,
}
#[derive(Default)]
struct App {
edit: HWND,
path: String,
plain: bool,
btns: Vec<(B, RectF)>,
hover: i32,
spacing: f32,
tf: std::collections::HashMap<&'static str, IDWriteTextFormat>,
}
static A: Global<Option<App>> = Global::new(None);
fn a() -> &'static mut App {
A.get().as_mut().unwrap()
}
fn tf(n: &str) -> &'static IDWriteTextFormat {
&a().tf[n]
}
fn send(m: u32, w_: usize, l: isize) -> isize {
unsafe { SendMessageW(a().edit, m, WPARAM(w_), LPARAM(l)).0 }
}
fn cur_char() -> CHARFORMAT2W {
let mut cf = CHARFORMAT2W::default();
cf.Base.cbSize = std::mem::size_of::<CHARFORMAT2W>() as u32;
cf.Base.dwMask = CFM_ALL2;
send(EM_GETCHARFORMAT, SCF_SELECTION as usize, &mut cf as *mut _ as isize);
cf
}
fn cur_para() -> PARAFORMAT2 {
let mut pf = PARAFORMAT2::default();
pf.Base.cbSize = std::mem::size_of::<PARAFORMAT2>() as u32;
pf.Base.dwMask = PFM_ALIGNMENT | PFM_NUMBERING;
send(EM_GETPARAFORMAT, 0, &mut pf as *mut _ as isize);
pf
}
fn novo_cf(mask: CFM_MASK) -> CHARFORMAT2W {
let mut n = CHARFORMAT2W::default();
n.Base.cbSize = std::mem::size_of::<CHARFORMAT2W>() as u32;
n.Base.dwMask = mask;
n
}
fn set_char(cf: &mut CHARFORMAT2W) {
send(EM_SETCHARFORMAT, SCF_SELECTION as usize, cf as *mut _ as isize);
unsafe {
let _ = SetFocus(a().edit);
}
invalidate();
}
fn tem(cf: &CHARFORMAT2W, m: CFM_MASK, e: CFE_EFFECTS) -> bool {
(cf.Base.dwMask.0 & m.0) != 0 && (cf.Base.dwEffects.0 & e.0) != 0
}
fn toggle(m: CFM_MASK, e: CFE_EFFECTS) {
let on = tem(&cur_char(), m, e);
let mut n = novo_cf(m);
n.Base.dwEffects = if on { CFE_EFFECTS(0) } else { e };
set_char(&mut n);
}
fn set_para(pf: &mut PARAFORMAT2) {
pf.Base.cbSize = std::mem::size_of::<PARAFORMAT2>() as u32;
send(EM_SETPARAFORMAT, 0, pf as *mut _ as isize);
unsafe {
let _ = SetFocus(a().edit);
}
invalidate();
}
fn align(al: PARAFORMAT_ALIGNMENT) {
let mut pf = PARAFORMAT2::default();
pf.Base.dwMask = PFM_ALIGNMENT;
pf.Base.wAlignment = al;
set_para(&mut pf);
}
fn pt_atual() -> i32 {
let cf = cur_char();
if cf.Base.yHeight > 0 {
cf.Base.yHeight / 20
} else {
12
}
}
fn set_size(pt_: i32) {
let mut n = novo_cf(CFM_SIZE);
n.Base.yHeight = pt_ * 20;
set_char(&mut n);
}
fn size_step(delta: i32) {
let p = pt_atual();
let next = if delta > 0 { STEPS.iter().copied().find(|&s| s > p).unwrap_or(p) } else { STEPS.iter().rev().copied().find(|&s| s < p).unwrap_or(p) };
set_size(next);
}
fn apply_theme() {
let d = dark();
send(EM_SETBKGNDCOLOR, 0, if d { colorref(30, 30, 30) } else { colorref(255, 255, 255) }.0 as isize);
let mut cf = novo_cf(CFM_COLOR);
cf.Base.crTextColor = if d { colorref(235, 235, 235) } else { colorref(20, 20, 20) };
send(EM_SETCHARFORMAT, SCF_DEFAULT as usize, &mut cf as *mut _ as isize);
}
fn nome_arquivo(p: &str) -> String {
p.rsplit('\\').next().unwrap_or(p).to_string()
}
fn set_title() {
let mut n = if a().path.is_empty() { tr("Sem Título") } else { nome_arquivo(&a().path) };
if send(EM_GETMODIFY, 0, 0) != 0 {
n += &format!(" — {}", tr("Editado"));
}
unsafe {
let mut cur = [0u16; 512];
GetWindowTextW(wnd(), &mut cur);
if from_w(&cur) != n {
let t = wz(&n);
let _ = SetWindowTextW(wnd(), pc(&t));
if bar() > 0.0 {
invalidate();
}
}
}
}
unsafe extern "system" fn read_cb(c: usize, buf: *mut u8, n: i32, got: *mut i32) -> u32 {
let mut g = 0u32;
let r = ReadFile(HANDLE(c as *mut _), Some(std::slice::from_raw_parts_mut(buf, n as usize)), Some(&mut g), None);
*got = g as i32;
r.is_err() as u32
}
unsafe extern "system" fn write_cb(c: usize, buf: *mut u8, n: i32, got: *mut i32) -> u32 {
let mut g = 0u32;
let r = WriteFile(HANDLE(c as *mut _), Some(std::slice::from_raw_parts(buf, n as usize)), Some(&mut g), None);
*got = g as i32;
r.is_err() as u32
}
fn layout() {
unsafe {
let mut r = RECT::default();
let _ = GetClientRect(wnd(), &mut r);
let s_ = sc();
let gg = bar() > 0.0;
let plain = a().plain;
let top = ((if gg {
if plain {
32.0
} else {
100.0
}
} else if plain {
0.0
} else {
TBAR
}) * s_)
.round() as i32;
let _ = SetWindowPos(a().edit, None, 0, top, r.right, r.bottom - top, SWP_NOZORDER);
let m = ((if gg { 5.0 } else { 22.0 }) * s_).round() as i32;
let v = ((if gg { 3.0 } else { 14.0 }) * s_).round() as i32;
let fr = RECT { left: m, top: v, right: r.right - m, bottom: r.bottom - top - v };
send(EM_SETRECT, 0, &fr as *const _ as isize);
invalidate();
}
}
fn ext_lower(p: &str) -> String {
std::path::Path::new(p).extension().map(|x| x.to_string_lossy().to_lowercase()).unwrap_or_default()
}
fn load_file(p: &str) -> bool {
unsafe {
let w_ = wz(p);
let Ok(f) = CreateFileW(pc(&w_), FILE_GENERIC_READ.0, FILE_SHARE_READ | FILE_SHARE_WRITE, None, OPEN_EXISTING, FILE_FLAGS_AND_ATTRIBUTES(0), None) else { return false };
a().plain = ext_lower(p) != "rtf";
let mut fmt = if a().plain { SF_TEXT | SF_USECODEPAGE | (65001 << 16) } else { SF_RTF };
if a().plain {
let mut bom = [0u8; 2];
let mut n = 0u32;
let _ = ReadFile(f, Some(&mut bom), Some(&mut n), None);
if n == 2 && bom == [0xFF, 0xFE] {
fmt = SF_TEXT | SF_UNICODE;
} else {
SetFilePointer(f, 0, None, FILE_BEGIN);
}
}
send(EM_SETTEXTMODE, if a().plain { TM_PLAINTEXT.0 } else { TM_RICHTEXT.0 } as usize, 0);
let mut es = EDITSTREAM { dwCookie: f.0 as usize, dwError: 0, pfnCallback: Some(read_cb) };
send(EM_STREAMIN, fmt as usize, &mut es as *mut _ as isize);
let _ = CloseHandle(f);
a().path = p.to_string();
apply_theme();
send(EM_SETMODIFY, 0, 0);
SHAddToRecentDocs(SHARD_PATHW.0 as u32, Some(w_.as_ptr() as *const _));
layout();
set_title();
true
}
}
fn save_to(p: &str) -> bool {
unsafe {
let w_ = wz(p);
let Ok(f) = CreateFileW(pc(&w_), FILE_GENERIC_WRITE.0, FILE_SHARE_MODE(0), None, CREATE_ALWAYS, FILE_FLAGS_AND_ATTRIBUTES(0), None) else {
message_box(&tr("Não foi possível salvar o documento."), "TextEdit", MB_OK | MB_ICONERROR);
return false;
};
let rtf = ext_lower(p) == "rtf";
if !rtf {
let mut wr = 0u32;
let _ = WriteFile(f, Some(&[0xEF, 0xBB, 0xBF]), Some(&mut wr), None);
}
let mut es = EDITSTREAM { dwCookie: f.0 as usize, dwError: 0, pfnCallback: Some(write_cb) };
send(EM_STREAMOUT, if rtf { SF_RTF } else { SF_TEXT | SF_USECODEPAGE | (65001 << 16) } as usize, &mut es as *mut _ as isize);
let _ = CloseHandle(f);
a().path = p.to_string();
send(EM_SETMODIFY, 0, 0);
SHAddToRecentDocs(SHARD_PATHW.0 as u32, Some(w_.as_ptr() as *const _));
set_title();
true
}
}
fn save() -> bool {
if a().path.is_empty() {
save_as()
} else {
let p = a().path.clone();
save_to(&p)
}
}
fn save_as() -> bool {
let (rtf, txt) = (tr("Texto Formatado (RTF)"), tr("Texto Simples"));
let filtros: Vec<(&str, &str)> = if a().plain { vec![(&txt, "*.txt"), (&rtf, "*.rtf")] } else { vec![(&rtf, "*.rtf"), (&txt, "*.txt")] };
let nome = if a().path.is_empty() { tr("Sem Título") } else { nome_arquivo(&a().path) };
match pick_file(true, &filtros, Some(if a().plain { "txt" } else { "rtf" }), Some(&nome)) {
Some(p) => save_to(&p),
None => false,
}
}
fn open_dialog() {
let (d, t) = (tr("Documentos de texto"), tr("Todos"));
let Some(p) = pick_file(false, &[(&d, "*.rtf;*.txt;*.md;*.log;*.csv;*.ini;*.json"), (&t, "*.*")], None, None) else { return };
let vazio = unsafe { GetWindowTextLengthW(a().edit) } == 0;
if a().path.is_empty() && vazio {
load_file(&p);
} else {
shell_open(&exe_dir().join("WacOSTextEdit.exe").to_string_lossy(), Some(&format!("\"{p}\"")));
}
}
fn can_close() -> bool {
if send(EM_GETMODIFY, 0, 0) == 0 {
return true;
}
let n = if a().path.is_empty() { tr("Sem Título") } else { nome_arquivo(&a().path) };
let r = message_box(&cf!(tr("Deseja salvar as alterações feitas no documento “%ls”?\n\nSuas alterações serão perdidas se você não as salvar."), n), "TextEdit", MB_YESNOCANCEL | MB_ICONWARNING);
if r == IDCANCEL {
return false;
}
if r == IDYES {
return save();
}
true
}
fn edit_text() -> String {
unsafe {
let n = GetWindowTextLengthW(a().edit);
let mut b = vec![0u16; n as usize + 1];
GetWindowTextW(a().edit, &mut b);
from_w(&b)
}
}
fn toggle_plain() {
if !a().plain && message_box(&tr("Converter este documento em texto simples? Toda a formatação será perdida."), "TextEdit", MB_OKCANCEL | MB_ICONQUESTION) != IDOK {
return;
}
let t = wz(&edit_text());
unsafe {
let _ = SetWindowTextW(a().edit, w!(""));
a().plain = !a().plain;
send(EM_SETTEXTMODE, if a().plain { TM_PLAINTEXT.0 } else { TM_RICHTEXT.0 } as usize, 0);
let _ = SetWindowTextW(a().edit, pc(&t));
}
if !a().path.is_empty() {
let p = std::path::Path::new(&a().path).with_extension(if a().plain { "txt" } else { "rtf" });
a().path = p.to_string_lossy().into_owned();
}
apply_theme();
send(EM_SETMODIFY, 1, 0);
layout();
set_title();
}
fn item(label: &str, id: i32, checked: bool) -> Item {
Item::new(label, id).checked(checked)
}
fn font_menu(scr: POINT) {
let fonts = ["Helvetica", "SF Pro Text", "Arial", "Georgia", "Times New Roman", "Courier New", "Menlo", "Segoe UI", "Verdana"];
let cf = cur_char();
let cur = from_w(&cf.Base.szFaceName).to_lowercase();
let items: Vec<Item> = fonts.iter().enumerate().filter(|(_, f)| has_font(f)).map(|(i, f)| item(f, i as i32 + 1, cur == f.to_lowercase())).collect();
let c = ctxmenu::show_items(wnd(), scr, &items);
if c > 0 {
let mut n = novo_cf(CFM_FACE);
let v: Vec<u16> = fonts[c as usize - 1].encode_utf16().collect();
n.Base.szFaceName[..v.len()].copy_from_slice(&v);
set_char(&mut n);
}
}
fn color_menu(scr: POINT) {
let cols: [(&str, Option<(u8, u8, u8)>); 10] = [
("Automática", None),
("Preto", Some((0, 0, 0))),
("Cinza", Some((142, 142, 147))),
("Vermelho", Some((255, 59, 48))),
("Laranja", Some((255, 149, 0))),
("Amarelo", Some((255, 204, 0))),
("Verde", Some((52, 199, 89))),
("Azul", Some((0, 122, 255))),
("Roxo", Some((175, 82, 222))),
("Rosa", Some((255, 45, 85))),
];
let mut items = Vec::new();
for (i, (n, c)) in cols.iter().enumerate() {
let mut it = item(&tr(n), i as i32 + 1, false);
it.swatch = match c {
None => ctxmenu::SWATCH_AUTO,
Some((r, g, b)) => 0xFF000000 | (*r as u32) << 16 | (*g as u32) << 8 | *b as u32,
};
items.push(it);
if i == 0 {
items.push(Item::sep());
}
}
let c = ctxmenu::show_items(wnd(), scr, &items);
if c > 0 {
let mut n = novo_cf(CFM_COLOR);
match cols[c as usize - 1].1 {
None => n.Base.dwEffects = CFE_AUTOCOLOR,
Some((r, g, b)) => n.Base.crTextColor = colorref(r, g, b),
}
set_char(&mut n);
}
}
fn action(id: B, scr: POINT) {
match id {
B::Font => font_menu(scr),
B::Smaller => size_step(-1),
B::Bigger => size_step(1),
B::Color => color_menu(scr),
B::Bold => toggle(CFM_BOLD, CFE_BOLD),
B::Italic => toggle(CFM_ITALIC, CFE_ITALIC),
B::Under => toggle(CFM_UNDERLINE, CFE_UNDERLINE),
B::Strike => toggle(CFM_STRIKEOUT, CFE_STRIKEOUT),
B::Left => align(PFA_LEFT),
B::Center => align(PFA_CENTER),
B::Right => align(PFA_RIGHT),
B::Just => align(PFA_JUSTIFY),
B::Clear => {
let mut n = novo_cf(CFM_BOLD | CFM_ITALIC | CFM_UNDERLINE | CFM_STRIKEOUT | CFM_COLOR);
n.Base.dwEffects = CFE_AUTOCOLOR;
set_char(&mut n);
}
B::Style => {
let st = ["Normal", "Negrito", "Itálico", "Negrito Itálico"];
let cf = cur_char();
let (b, it) = (tem(&cf, CFM_BOLD, CFE_BOLD), tem(&cf, CFM_ITALIC, CFE_ITALIC));
let cur = if b && it {
4
} else if it {
3
} else if b {
2
} else {
1
};
let items: Vec<Item> = st.iter().enumerate().map(|(i, s)| item(&tr(s), i as i32 + 1, cur == i as i32 + 1)).collect();
let c = ctxmenu::show_items(wnd(), scr, &items);
if c > 0 {
let mut n = novo_cf(CFM_BOLD | CFM_ITALIC);
n.Base.dwEffects = CFE_EFFECTS(if c == 2 || c == 4 { CFE_BOLD.0 } else { 0 } | if c >= 3 { CFE_ITALIC.0 } else { 0 });
set_char(&mut n);
}
}
B::Size => {
if bar() > 0.0 {
let p = pt_atual();
let items: Vec<Item> = STEPS.iter().enumerate().map(|(i, s)| item(&s.to_string(), i as i32 + 1, *s == p)).collect();
let c = ctxmenu::show_items(wnd(), scr, &items);
if c > 0 {
set_size(STEPS[c as usize - 1]);
}
}
}
B::Spacing => {
let v = [1.0f32, 1.15, 1.5, 2.0];
let items: Vec<Item> = v.iter().enumerate().map(|(i, x)| item(&if i == 1 { format!("{x:.2}") } else { format!("{x:.1}") }, i as i32 + 1, a().spacing == *x)).collect();
let c = ctxmenu::show_items(wnd(), scr, &items);
if c > 0 {
a().spacing = v[c as usize - 1];
let mut n = PARAFORMAT2::default();
n.Base.dwMask = PFM_LINESPACING;
n.bLineSpacingRule = 5;
n.dyLineSpacing = (a().spacing * 20.0).round() as i32;
set_para(&mut n);
}
}
B::List => {
let pf = cur_para();
let mut n = PARAFORMAT2::default();
n.Base.dwMask = PFM_NUMBERING | PFM_OFFSET;
n.Base.wNumbering = if pf.Base.wNumbering.0 != 0 { PARAFORMAT_NUMBERING(0) } else { PFN_BULLET };
n.Base.dxOffset = if n.Base.wNumbering.0 != 0 { 360 } else { 0 };
set_para(&mut n);
}
}
}
fn chevron(x: f32, y: f32, c: Cor, updown: bool) {
if updown {
line(pt(x - 3.5, y - 1.5), pt(x, y - 5.0), c, 1.3);
line(pt(x, y - 5.0), pt(x + 3.5, y - 1.5), c, 1.3);
line(pt(x - 3.5, y + 1.5), pt(x, y + 5.0), c, 1.3);
line(pt(x, y + 5.0), pt(x + 3.5, y + 1.5), c, 1.3);
} else {
line(pt(x - 4.0, y - 2.0), pt(x, y + 2.0), c, 1.4);
line(pt(x, y + 2.0), pt(x + 4.0, y - 2.0), c, 1.4);
}
}
fn align_icon(cx: f32, cy: f32, kind: i32, c: Cor) {
for i in 0..4 {
let w_ = if i % 2 == 1 {
if kind == 3 {
16.0
} else {
10.0
}
} else {
16.0
};
let y = cy - 4.5 + i as f32 * 3.0;
let x0 = match kind {
1 => cx - w_ / 2.0,
2 => cx + 8.0 - w_,
_ => cx - 8.0,
};
line(pt(x0, y), pt(x0 + w_, y), c, 1.1);
}
}
fn triangulo(p: [(f32, f32); 3], c: Cor) {
unsafe {
if let Ok(g) = d2d().CreatePathGeometry() {
if let Ok(s) = g.Open() {
s.BeginFigure(pt(p[0].0, p[0].1), D2D1_FIGURE_BEGIN_FILLED);
s.AddLine(pt(p[1].0, p[1].1));
s.AddLine(pt(p[2].0, p[2].1));
s.EndFigure(D2D1_FIGURE_END_CLOSED);
let _ = s.Close();
br().SetColor(&c);
app2d::rt().FillGeometry(&g, br(), None);
}
}
}
}
fn cor_texto(cf: &CHARFORMAT2W, d: bool) -> Cor {
let c = if (cf.Base.dwEffects.0 & CFE_AUTOCOLOR.0) != 0 || (cf.Base.dwMask.0 & CFM_COLOR.0) == 0 {
if d {
0x00EBEBEB
} else {
0
}
} else {
cf.Base.crTextColor.0
};
rgb((c & 255) as i32, ((c >> 8) & 255) as i32, ((c >> 16) & 255) as i32, 1.0)
}
fn paint_golden() {
a().btns.clear();
let d = dark();
let sz = app2d::size();
let text_c = if d { rgb(235, 235, 235, 1.0) } else { rgb(29, 29, 31, 1.0) };
let pill = if d { rgb(255, 255, 255, 0.10) } else { rgb(0, 0, 0, 0.075) };
let gray = if d { rgb(160, 160, 165, 1.0) } else { rgb(120, 120, 124, 1.0) };
let sep = if d { rgb(255, 255, 255, 0.10) } else { rgb(0, 0, 0, 0.10) };
clear(if d { rgb(30, 30, 30, 1.0) } else { rgb(255, 255, 255, 1.0) });
{
let (x, cy) = (88.0, 16.0);
let ic = rf(x, cy - 8.0, x + 12.0, cy + 8.0);
fill(ic, if d { rgb(230, 230, 230, 1.0) } else { rgb(250, 250, 250, 1.0) }, 1.5);
stroke_rect(ic, if d { rgb(255, 255, 255, 0.4) } else { rgb(0, 0, 0, 0.35) }, 1.5, 0.75);
for i in 0..4 {
let y = cy - 4.5 + i as f32 * 3.0;
fill(rf(x + 2.5, y, x + 9.5, y + 0.7), rgb(120, 120, 120, 1.0), 0.0);
}
let mut t = [0u16; 512];
unsafe { GetWindowTextW(wnd(), &mut t) };
text(&from_w(&t), tf("titleg"), rf(x + 18.0, 0.0, sz.width - 20.0, G_TITLE), if d { rgb(255, 255, 255, 0.55) } else { rgb(0, 0, 0, 0.55) });
}
if a().plain {
fill(rf(0.0, G_TITLE - 0.5, sz.width, G_TITLE), sep, 0.0);
return;
}
let cf = cur_char();
let pf = cur_para();
let (y0, y1) = (G_ROW_Y - 10.0, G_ROW_Y + 10.0);
let reg = |id: B, r: RectF| a().btns.push((id, r));
{
fill(rf(8.0, y0, 93.0, y1), pill, 6.0);
let on = [tem(&cf, CFM_BOLD, CFE_BOLD), tem(&cf, CFM_ITALIC, CFE_ITALIC), tem(&cf, CFM_UNDERLINE, CFE_UNDERLINE), tem(&cf, CFM_STRIKEOUT, CFE_STRIKEOUT)];
let lab = ["B", "I", "U", "S"];
let fm = ["ctlb", "ctli", "ctl", "ctl"];
let ids = [B::Bold, B::Italic, B::Under, B::Strike];
for i in 0..4 {
let c = rf(8.0 + i as f32 * 21.25, y0, 8.0 + (i + 1) as f32 * 21.25, y1);
if on[i] {
fill(rf(c.left + 2.0, y0 + 2.0, c.right - 2.0, y1 - 2.0), if d { rgb(255, 255, 255, 0.22) } else { rgb(0, 0, 0, 0.14) }, 4.0);
}
text(lab[i], tf(fm[i]), c, text_c);
if i == 2 {
fill(rf(c.left + 7.5, G_ROW_Y + 5.5, c.right - 7.5, G_ROW_Y + 6.3), text_c, 0.0);
}
if i == 3 {
fill(rf(c.left + 6.5, G_ROW_Y + 0.2, c.right - 6.5, G_ROW_Y + 1.0), text_c, 0.0);
}
if i > 0 {
fill(rf(c.left - 0.5, y0 + 5.0, c.left, y1 - 5.0), sep, 0.0);
}
reg(ids[i], c);
}
}
{
let r = rf(99.0, y0, 118.0, y1);
fill(r, cor_texto(&cf, d), 5.0);
stroke_rect(r, sep, 5.0, 0.5);
reg(B::Color, r);
}
{
let r = rf(123.0, y0, 144.0, y1);
fill(r, if d { rgb(255, 255, 255, 0.06) } else { rgb(255, 255, 255, 1.0) }, 6.0);
stroke_rect(r, sep, 6.0, 0.75);
text("A", tf("ctli"), r, gray);
line(pt(r.left + 5.0, r.bottom - 4.0), pt(r.right - 5.0, r.top + 4.0), rgb(255, 59, 48, 1.0), 1.1);
reg(B::Clear, r);
}
let popup = |id: B, r: RectF, label: &str| {
fill(r, pill, 6.0);
text(label, tf("ctl"), rf(r.left + 10.0, r.top, r.right - 18.0, r.bottom), text_c);
chevron(r.right - 10.0, G_ROW_Y, text_c, true);
a().btns.push((id, r));
};
let face = from_w(&cf.Base.szFaceName);
popup(B::Font, rf(149.0, y0, 228.0, y1), if face.is_empty() { "Helvetica" } else { &face });
{
let (b, it) = (tem(&cf, CFM_BOLD, CFE_BOLD), tem(&cf, CFM_ITALIC, CFE_ITALIC));
let st = tr(if b && it {
"Negrito Itálico"
} else if b {
"Negrito"
} else if it {
"Itálico"
} else {
"Normal"
});
popup(B::Style, rf(234.0, y0, 312.0, y1), &st);
}
{
let r = rf(318.0, y0, 369.0, y1);
fill(r, if d { rgb(255, 255, 255, 0.06) } else { rgb(255, 255, 255, 1.0) }, 6.0);
stroke_rect(r, if d { rgb(255, 255, 255, 0.18) } else { rgb(0, 0, 0, 0.16) }, 6.0, 0.75);
text(&pt_atual().to_string(), tf("ctl"), rf(r.left + 6.0, r.top, r.right - 22.0, r.bottom), text_c);
let ar = rf(r.right - 21.0, r.top + 3.0, r.right - 3.0, r.bottom - 3.0);
fill(ar, pill, 4.0);
chevron((ar.left + ar.right) / 2.0, G_ROW_Y, text_c, false);
reg(B::Size, r);
}
{
let r = rf(374.0, y0, 469.0, y1);
fill(r, pill, 6.0);
let al = pf.Base.wAlignment;
let cur = if al == PFA_CENTER {
1
} else if al == PFA_RIGHT {
2
} else if al == PFA_JUSTIFY {
3
} else {
0
};
let ids = [B::Left, B::Center, B::Right, B::Just];
let w_ = (r.right - r.left) / 4.0;
for i in 0..4 {
let c = rf(r.left + i as f32 * w_, y0, r.left + (i + 1) as f32 * w_, y1);
let on = i == cur;
if on {
fill(c, if semaforo::aqua() { rgb(0, 136, 255, 1.0) } else { rgb(10, 132, 255, 1.0) }, 6.0);
} else if i > 0 && i != cur + 1 {
fill(rf(c.left - 0.5, y0 + 5.0, c.left, y1 - 5.0), sep, 0.0);
}
align_icon((c.left + c.right) / 2.0, G_ROW_Y, i, if on { rgb(255, 255, 255, 1.0) } else { text_c });
reg(ids[i as usize], c);
}
}
{
let r = rf(475.0, y0, 520.0, y1);
fill(r, if pf.Base.wNumbering.0 == 0 { pill } else if d { rgb(255, 255, 255, 0.22) } else { rgb(0, 0, 0, 0.14) }, 6.0);
for i in 0..3 {
let y = G_ROW_Y - 4.0 + i as f32 * 4.0;
circle(pt(r.left + 11.0, y), 1.1, text_c, true, 1.0);
line(pt(r.left + 14.5, y), pt(r.left + 23.0, y), text_c, 1.1);
}
chevron(r.right - 11.0, G_ROW_Y, text_c, false);
reg(B::List, r);
}
{
let r = rf(525.5, y0, 576.5, y1);
fill(r, pill, 6.0);
text(&format!("{:.1}", a().spacing), tf("ctl"), rf(r.left + 6.0, r.top, r.right - 22.0, r.bottom), text_c);
chevron(r.right - 11.5, G_ROW_Y, text_c, true);
reg(B::Spacing, r);
}
for (_, r) in a().btns.clone() {
bar_button(r);
}
fill(rf(0.0, G_RULER0 - 0.5, sz.width, G_RULER0), sep, 0.0);
{
let tick = if d { rgb(170, 170, 170, 1.0) } else { rgb(140, 140, 140, 1.0) };
let (x0, base) = (5.0, G_RULER1 - 13.0);
fill(rf(0.0, base, sz.width, base + 0.75), tick, 0.0);
let mut k = 0;
while x0 + k as f32 * 9.0 < sz.width {
let x = x0 + k as f32 * 9.0;
let h = if k % 8 == 0 {
9.0
} else if k % 4 == 0 {
5.0
} else {
3.0
};
fill(rf(x, base, x + 0.75, base + h), tick, 0.0);
if k % 8 == 0 {
text(&(k / 8).to_string(), tf("ruler"), rf(x + 2.0, base + 1.0, x + 30.0, base + 11.0), text_c);
}
k += 1;
}
let mk = if d { rgb(150, 150, 150, 1.0) } else { rgb(110, 110, 110, 1.0) };
let mut k = 1;
while x0 + k as f32 * 36.0 < sz.width - 20.0 && k <= 13 {
let (x, y) = (x0 + k as f32 * 36.0 + 1.0, G_RULER0 + 10.0);
triangulo([(x - 1.0, y - 5.0), (x + 5.0, y), (x - 1.0, y + 5.0)], mk);
k += 1;
}
fill(rf(x0 - 4.0, G_RULER0 + 7.0, x0 + 4.0, G_RULER0 + 8.5), mk, 0.0);
let y = G_RULER0 + 9.0;
triangulo([(x0 - 4.0, y), (x0 + 4.0, y), (x0, y + 5.0)], mk);
let x = sz.width - 10.0;
triangulo([(x - 5.0, y - 1.0), (x + 5.0, y - 1.0), (x, y + 5.0)], mk);
}
fill(rf(0.0, G_RULER1 - 0.75, sz.width, G_RULER1), sep, 0.0);
}
fn paint() {
if !begin_paint() {
return;
}
if bar() > 0.0 {
paint_golden();
end_paint();
return;
}
a().btns.clear();
let d = dark();
let sz = app2d::size();
let text_c = if d { rgb(235, 235, 235, 1.0) } else { rgb(40, 40, 42, 1.0) };
let on_c = rgb(10, 132, 255, 1.0);
clear(if d { rgb(44, 44, 46, 1.0) } else { rgb(246, 246, 246, 1.0) });
if !a().plain {
let cf = cur_char();
let pf = cur_para();
let mut x = 14.0;
let (y0, y1) = (7.0, TBAR - 7.0);
let boxf = |id: B, w_: f32, label: &str, f: &str, lit: bool, frame: bool, x: &mut f32| {
let r = rf(*x, y0, *x + w_, y1);
if frame {
fill(r, if d { rgb(66, 66, 68, 1.0) } else { rgb(255, 255, 255, 1.0) }, 5.0);
}
if lit {
fill(r, if d { rgb(10, 132, 255, 0.45) } else { rgb(10, 132, 255, 0.18) }, 5.0);
} else if a().btns.len() as i32 == a().hover {
fill(r, if d { rgb(255, 255, 255, 0.10) } else { rgb(0, 0, 0, 0.06) }, 5.0);
}
text(label, tf(f), r, if lit { if d { rgb(255, 255, 255, 1.0) } else { on_c } } else { text_c });
a().btns.push((id, r));
*x += w_ + 4.0;
};
let face = from_w(&cf.Base.szFaceName);
boxf(B::Font, 150.0, &format!("{} ⌄", if face.is_empty() { "Helvetica" } else { &face }), "btn", false, true, &mut x);
x += 6.0;
boxf(B::Smaller, 22.0, "−", "btn", false, false, &mut x);
boxf(B::Size, 34.0, &pt_atual().to_string(), "btn", false, true, &mut x);
boxf(B::Bigger, 22.0, "+", "btn", false, false, &mut x);
x += 8.0;
boxf(B::Color, 30.0, "■", "btn", false, false, &mut x);
x += 8.0;
boxf(B::Bold, 28.0, "B", "b", tem(&cf, CFM_BOLD, CFE_BOLD), false, &mut x);
boxf(B::Italic, 28.0, "I", "i", tem(&cf, CFM_ITALIC, CFE_ITALIC), false, &mut x);
boxf(B::Under, 28.0, "U", "u", tem(&cf, CFM_UNDERLINE, CFE_UNDERLINE), false, &mut x);
x += 10.0;
let al = pf.Base.wAlignment;
boxf(B::Left, 28.0, "\u{E8E4}", "icon", al == PFA_LEFT, false, &mut x);
boxf(B::Center, 28.0, "\u{E8E3}", "icon", al == PFA_CENTER, false, &mut x);
boxf(B::Right, 28.0, "\u{E8E2}", "icon", al == PFA_RIGHT, false, &mut x);
boxf(B::Just, 28.0, "≡", "btn", al == PFA_JUSTIFY, false, &mut x);
x += 10.0;
boxf(B::List, 30.0, "\u{E8FD}", "icon", pf.Base.wNumbering.0 != 0, false, &mut x);
fill(rf(0.0, TBAR - 1.0, sz.width, TBAR), if d { rgb(0, 0, 0, 0.6) } else { rgb(0, 0, 0, 0.12) }, 0.0);
}
end_paint();
}
extern "system" fn proc_(h: HWND, m: u32, w_: WPARAM, l: LPARAM) -> LRESULT {
unsafe {
let s_ = sc();
match m {
WM_PAINT => return wm_paint(h, paint),
WM_ERASEBKGND => return LRESULT(1),
WM_SIZE => {
on_size(l);
if !a().edit.0.is_null() {
layout();
}
}
WM_DPICHANGED => {
on_dpi(w_, l);
layout();
}
WM_SETFOCUS => {
if !a().edit.0.is_null() {
let _ = SetFocus(a().edit);
}
}
WM_GETMINMAXINFO => {
if bar() > 0.0 {
let mm = &mut *(l.0 as *mut MINMAXINFO);
let (mut wr, mut cr) = (RECT::default(), RECT::default());
let _ = GetWindowRect(h, &mut wr);
let _ = GetClientRect(h, &mut cr);
mm.ptMinTrackSize.x = mm.ptMinTrackSize.x.max((586.0 * s_).round() as i32 + (wr.right - wr.left) - cr.right);
mm.ptMinTrackSize.y = mm.ptMinTrackSize.y.max((200.0 * s_).round() as i32);
}
}
WM_SETTINGCHANGE => {
apply_theme();
invalidate();
let _ = comum::windows::Win32::Graphics::Gdi::InvalidateRect(a().edit, None, TRUE);
}
WM_NOTIFY => {
let n = &*(l.0 as *const comum::windows::Win32::UI::Controls::NMHDR);
if n.hwndFrom == a().edit && n.code == EN_SELCHANGE {
invalidate();
}
}
WM_COMMAND => {
if HWND(l.0 as *mut _) == a().edit && hiword(w_.0) == EN_CHANGE {
set_title();
}
}
WM_MOUSEMOVE => {
let (x, y) = (get_x_lparam(l) as f32 / s_, get_y_lparam(l) as f32 / s_);
let hv = a().btns.iter().rposition(|b| in_rect(&b.1, x, y)).map(|i| i as i32).unwrap_or(-1);
if hv != a().hover {
a().hover = hv;
invalidate();
}
let mut t = TRACKMOUSEEVENT { cbSize: std::mem::size_of::<TRACKMOUSEEVENT>() as u32, dwFlags: TME_LEAVE, hwndTrack: h, dwHoverTime: 0 };
let _ = TrackMouseEvent(&mut t);
}
WM_MOUSELEAVE => {
if a().hover >= 0 {
a().hover = -1;
invalidate();
}
}
WM_LBUTTONDOWN => {
let (x, y) = (get_x_lparam(l) as f32 / s_, get_y_lparam(l) as f32 / s_);
if let Some((id, r)) = a().btns.iter().find(|b| in_rect(&b.1, x, y)).copied() {
let scr = to_screen(h, (r.left * s_).round() as i32, (r.bottom * s_).round() as i32);
action(id, scr);
}
}
WM_CLOSE => {
if modo_foto() || can_close() {
let _ = DestroyWindow(h);
}
}
WM_DESTROY => PostQuitMessage(0),
_ => return DefWindowProcW(h, m, w_, l),
}
LRESULT(0)
}
}
fn main() {
if !app2d::init() {
std::process::exit(1);
}
*A.get() = Some(App { hover: -1, spacing: 1.0, ..Default::default() });
unsafe {
let _ = LoadLibraryW(w!("Msftedit.dll"));
}
let ic = icon_family();
use DWRITE_TEXT_ALIGNMENT_CENTER as C;
let f = |s: f32, w_: DWRITE_FONT_WEIGHT, al: DWRITE_TEXT_ALIGNMENT, fam: Option<&str>| fmt_full(s, w_, al, false, fam);
let italico = |fam: &str, s: f32| {
let t = cjk::format(dw(), fam, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_ITALIC, s, "").unwrap();
unsafe {
let _ = t.SetTextAlignment(C);
let _ = t.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
}
t
};
let n = DWRITE_FONT_WEIGHT_NORMAL;
let b = DWRITE_FONT_WEIGHT_BOLD;
let fam = family();
let t = &mut a().tf;
for (k, v) in [
("btn", f(12.5, n, C, None)),
("icon", f(13.0, n, C, Some(&ic))),
("b", f(14.0, b, C, Some("Georgia"))),
("i", italico("Georgia", 14.0)),
("u", f(14.0, n, C, Some("Georgia"))),
("titleg", f(13.0, b, DWRITE_TEXT_ALIGNMENT_LEADING, None)),
("ctl", f(12.5, n, C, None)),
("ctlb", f(12.5, b, C, None)),
("ctli", italico(&fam, 12.5)),
("ruler", f(9.5, n, DWRITE_TEXT_ALIGNMENT_LEADING, None)),
] {
t.insert(k, v);
}
set_bar_wanted(32.0);
let aq = semaforo::aqua();
let Some(h) = create_main("TextEditJanela", &tr("Sem Título"), proc_, if aq { 586 } else { 760 }, if aq { 488 } else { 860 }) else { std::process::exit(1) };
ctxmenu::init();
unsafe {
if bar() > 0.0 {
let (mut wr, mut cr) = (RECT::default(), RECT::default());
let _ = GetWindowRect(h, &mut wr);
let _ = GetClientRect(h, &mut cr);
let want = (586.0 * sc()).round() as i32;
if cr.right < want {
let _ = SetWindowPos(h, None, wr.left - (want - cr.right) / 2, wr.top, (wr.right - wr.left) + want - cr.right, wr.bottom - wr.top, SWP_NOZORDER | SWP_NOACTIVATE);
}
}
let inst = GetModuleHandleW(None).unwrap_or_default();
let st = WS_CHILD | WS_VISIBLE | WS_VSCROLL | WINDOW_STYLE((ES_MULTILINE | ES_AUTOVSCROLL | ES_NOHIDESEL | ES_WANTRETURN) as u32);
let Ok(e) = CreateWindowExW(WINDOW_EX_STYLE(0), MSFTEDIT_CLASS, w!(""), st, 0, 0, 10, 10, h, None, inst, None) else { std::process::exit(1) };
a().edit = e;
}
send(EM_SETEVENTMASK, 0, (ENM_SELCHANGE | ENM_CHANGE) as isize);
send(EM_EXLIMITTEXT, 0, 0x7FFFFFFE);
send(EM_SETTYPOGRAPHYOPTIONS, TO_ADVANCEDTYPOGRAPHY as usize, TO_ADVANCEDTYPOGRAPHY as isize);
{
let mut cf = novo_cf(CFM_FACE | CFM_SIZE);
let face: Vec<u16> = (if has_font("Helvetica") { "Helvetica" } else { "Arial" }).encode_utf16().collect();
cf.Base.szFaceName[..face.len()].copy_from_slice(&face);
cf.Base.yHeight = 12 * 20;
send(EM_SETCHARFORMAT, SCF_ALL as usize, &mut cf as *mut _ as isize);
}
apply_theme();
send(EM_SETMODIFY, 0, 0);
if let Some(p) = std::env::args().nth(1).filter(|x| !x.starts_with("--")) {
if !load_file(&p) {
message_box(&tr("Não foi possível abrir o documento."), "TextEdit", MB_OK | MB_ICONERROR);
}
}
layout();
set_title();
show(h, SW_SHOWNORMAL);
unsafe {
let _ = SetFocus(a().edit);
}
foto_timer(1500);
// atalhos (o RichEdit tem o foco: vêm pelo laço de mensagens)
unsafe {
let mut msg = MSG::default();
while GetMessageW(&mut msg, None, 0, 0).as_bool() {
if msg.message == WM_KEYDOWN && key_down(VK_CONTROL.0) {
let shift = key_down(VK_SHIFT.0);
let plain = a().plain;
let k = msg.wParam.0 as u16;
let handled = match k {
x if x == 'S' as u16 => {
if shift {
save_as();
} else {
save();
}
true
}
x if x == 'O' as u16 => {
open_dialog();
true
}
x if x == 'N' as u16 => {
shell_open(&exe_dir().join("WacOSTextEdit.exe").to_string_lossy(), None);
true
}
x if x == 'W' as u16 => {
post(wnd(), WM_CLOSE, 0, 0);
true
}
x if x == 'B' as u16 && !plain => {
toggle(CFM_BOLD, CFE_BOLD);
true
}
x if x == 'I' as u16 && !plain => {
toggle(CFM_ITALIC, CFE_ITALIC);
true
}
x if x == 'U' as u16 && !plain => {
toggle(CFM_UNDERLINE, CFE_UNDERLINE);
true
}
x if x == 'T' as u16 && shift => {
toggle_plain();
true
}
x if x == VK_OEM_PLUS.0 && !plain => {
size_step(1);
true
}
x if x == VK_OEM_MINUS.0 && !plain => {
size_step(-1);
true
}
_ => false,
};
if handled {
continue;
}
}
let _ = TranslateMessage(&msg);
DispatchMessageW(&msg);
}
}
}