A new style desktop shell for Windows 11: menu bar, Dock, Finder, Spotlight, Control Center and Liquid Glass, in native C++.
Rust
//! Pré-Visualização (src\preview\main.cpp): imagens (WIC) e PDF (Windows.Data.Pdf, páginas desenhadas numa thread),
//! zoom, girar, miniaturas do PDF, Marcar (caneta, marca-texto, retângulo, oval, seta, texto, assinatura, recortar)
//! e exportar em PNG/JPEG. Teste: --foto saida.png [arquivo] desenha fora da tela (a janela não aparece);
//! --marcar abre com a barra de marcação.
#![windows_subsystem = "windows"]
use std::collections::VecDeque;
use std::ffi::c_void;
use std::sync::atomic::{AtomicIsize, Ordering};
use std::sync::{Condvar, Mutex, OnceLock};
use comum::app2d::{self, d2d, dw, message_box, pick_file, salvar_png, screen_to_client, wheel_delta};
use comum::windows::core::*;
use comum::windows::Data::Pdf::*;
use comum::windows::Storage::Streams::InMemoryRandomAccessStream;
use comum::windows::Storage::StorageFile;
use comum::windows::Win32::Foundation::*;
use comum::windows::Win32::Graphics::Direct2D::Common::*;
use comum::windows::Win32::Graphics::Direct2D::*;
use comum::windows::Win32::Graphics::DirectWrite::*;
use comum::windows::Win32::Graphics::Dwm::*;
use comum::windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_B8G8R8A8_UNORM;
use comum::windows::Win32::Graphics::Gdi::*;
use comum::windows::Win32::Graphics::Imaging::*;
use comum::windows::Win32::System::Com::*;
use comum::windows::Win32::System::LibraryLoader::GetModuleHandleW;
use comum::windows::Win32::System::WinRT::CreateStreamOverRandomAccessStream;
use comum::windows::Win32::UI::Controls::WM_MOUSELEAVE;
use comum::windows::Win32::UI::HiDpi::*;
use comum::windows::Win32::UI::Input::KeyboardAndMouse::*;
use comum::windows::Win32::UI::Shell::*;
use comum::windows::Win32::UI::WindowsAndMessaging::*;
use comum::windows::UI::Color;
use comum::*;
const WM_PV_INFO: u32 = WM_APP + 1;
const WM_PV_PAGE: u32 = WM_APP + 2;
const WM_PV_ASK: u32 = WM_APP + 3;
const WM_PV_TEXTO: u32 = WM_APP + 9;
const TOOLH: f32 = 52.0;
const MB: f32 = 42.0;
const GAP: f32 = 18.0;
const MARGIN: f32 = 24.0;
const B_ROT: i32 = 0;
const B_OUT: i32 = 1;
const B_IN: i32 = 2;
const B_FIT: i32 = 3;
const B_PRINT: i32 = 4;
const B_MARK: i32 = 5;
const B_EXPORT: i32 = 6;
const B_SIDE: i32 = 7;
const T_PEN: i32 = 0;
const T_HILITE: i32 = 1;
const T_RECT: i32 = 2;
const T_OVAL: i32 = 3;
const T_ARROW: i32 = 4;
const T_TEXT: i32 = 5;
const T_SIGN: i32 = 6;
const T_CROP: i32 = 7;
const COLORS: [Cor; 7] = [
Cor { r: 0.0, g: 0.0, b: 0.0, a: 1.0 },
Cor { r: 1.0, g: 0.23, b: 0.19, a: 1.0 },
Cor { r: 1.0, g: 0.58, b: 0.0, a: 1.0 },
Cor { r: 1.0, g: 0.8, b: 0.0, a: 1.0 },
Cor { r: 0.2, g: 0.78, b: 0.35, a: 1.0 },
Cor { r: 0.0, g: 0.48, b: 1.0, a: 1.0 },
Cor { r: 1.0, g: 1.0, b: 1.0, a: 1.0 },
];
#[derive(Default)]
struct Page {
w: f32,
h: f32,
bmp: Option<ID2D1Bitmap>,
px: Vec<u8>,
pw: u32,
ph: u32,
rendered_w: i32,
pending: bool,
}
#[derive(Clone, Default)]
struct Ann {
page: i32,
tool: i32,
col: Cor,
pts: Vec<Ponto>,
text: String,
}
struct Btn {
glyph: u16,
id: i32,
r: RectF,
}
struct MBtn {
kind: i32,
arg: i32,
r: RectF,
}
// ---- thread do PDF
#[derive(Clone, Copy)]
struct Job {
gen: i32,
page: i32,
width: i32,
}
#[derive(Default)]
struct Fila {
jobs: VecDeque<Job>,
path: String,
gen: i32,
quit: bool,
}
struct PageResult {
gen: i32,
page: i32,
width: i32,
w: u32,
h: u32,
px: Vec<u8>,
}
struct InfoResult {
gen: i32,
sizes: Vec<(f32, f32)>,
error: String,
}
static FILA: OnceLock<(Mutex<Fila>, Condvar)> = OnceLock::new();
static JANELA: AtomicIsize = AtomicIsize::new(0);
fn fila() -> &'static (Mutex<Fila>, Condvar) {
FILA.get_or_init(|| (Mutex::new(Fila { gen: -1, ..Default::default() }), Condvar::new()))
}
struct App {
hwnd: HWND,
rt: Option<ID2D1RenderTarget>,
hrt: Option<ID2D1HwndRenderTarget>,
br: Option<ID2D1SolidColorBrush>,
wic: IWICImagingFactory,
foto: Option<String>,
foto_bmp: Option<IWICBitmap>,
foto_ticks: i32,
tf_title: IDWriteTextFormat,
tf_sub: IDWriteTextFormat,
tf_icon: IDWriteTextFormat,
tf_empty: IDWriteTextFormat,
tf_thumb: IDWriteTextFormat,
round: Option<ID2D1StrokeStyle>,
unified: bool,
tb: f32,
pages: Vec<Page>,
path: String,
error: String,
pdf: bool,
gen: i32,
fit: bool,
zoom: f32,
rot: i32,
sx: f32,
sy: f32,
drag: bool,
drag_at: POINT,
drag_sx: f32,
drag_sy: f32,
hover_btn: i32,
btns: Vec<Btn>,
side: bool,
thumb_total: f32,
thumb_scroll: f32,
thumb_hits: Vec<(i32, RectF)>,
anns: Vec<Ann>,
markup: bool,
drawing: bool,
dirty: bool,
tool: i32,
color: usize,
cur: Ann,
img_px: Vec<u8>,
img_w: u32,
img_h: u32,
sign: Vec<Vec<Ponto>>,
sign_capture: bool,
sign_from: usize,
text: HWND,
text_old: isize,
text_at: Ponto,
text_page: i32,
text_font: HFONT,
mbtns: Vec<MBtn>,
list: Vec<String>,
}
static A: Global<Option<App>> = Global::new(None);
fn a() -> &'static mut App {
A.get().as_mut().unwrap()
}
fn dark() -> bool {
app2d::dark()
}
fn sc() -> f32 {
if a().foto.is_some() {
2.0
} else {
unsafe { GetDpiForWindow(a().hwnd) as f32 / 96.0 }
}
}
fn client_px() -> (i32, i32) {
if a().foto.is_some() {
return (2000, 1400);
}
let mut r = RECT::default();
unsafe {
let _ = GetClientRect(a().hwnd, &mut r);
}
(r.right, r.bottom)
}
fn invalidate() {
unsafe {
let _ = InvalidateRect(a().hwnd, None, FALSE);
}
}
fn bitmap_props() -> D2D1_BITMAP_PROPERTIES {
D2D1_BITMAP_PROPERTIES { pixelFormat: D2D1_PIXEL_FORMAT { format: DXGI_FORMAT_B8G8R8A8_UNORM, alphaMode: D2D1_ALPHA_MODE_PREMULTIPLIED }, dpiX: 96.0, dpiY: 96.0 }
}
fn make_bitmap(rt: &ID2D1RenderTarget, w_: u32, h: u32, px: &[u8]) -> Option<ID2D1Bitmap> {
unsafe { rt.CreateBitmap(D2D_SIZE_U { width: w_, height: h }, Some(px.as_ptr() as *const c_void), w_ * 4, &bitmap_props()).ok() }
}
fn decode_stream(wic: &IWICImagingFactory, st: &IStream) -> Option<(u32, u32, Vec<u8>)> {
unsafe {
let dec = wic.CreateDecoderFromStream(st, std::ptr::null(), WICDecodeMetadataCacheOnDemand).ok()?;
let fr = dec.GetFrame(0).ok()?;
let cv = wic.CreateFormatConverter().ok()?;
cv.Initialize(&fr, &GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone, None, 0.0, WICBitmapPaletteTypeCustom).ok()?;
let (mut w_, mut h) = (0, 0);
cv.GetSize(&mut w_, &mut h).ok()?;
let mut px = vec![0u8; w_ as usize * h as usize * 4];
cv.CopyPixels(std::ptr::null(), w_ * 4, &mut px).ok()?;
Some((w_, h, px))
}
}
fn post_box<T>(m: u32, v: T) {
let h = HWND(JANELA.load(Ordering::SeqCst) as *mut c_void);
let p = Box::into_raw(Box::new(v));
unsafe {
if PostMessageW(h, m, WPARAM(0), LPARAM(p as isize)).is_err() {
drop(Box::from_raw(p));
}
}
}
fn open_pdf(path: &str) -> Result<PdfDocument> {
let file = StorageFile::GetFileFromPathAsync(&HSTRING::from(path))?.get()?;
PdfDocument::LoadFromFileAsync(&file)?.get()
}
fn render_page(wic: &IWICImagingFactory, doc: &PdfDocument, page: i32, width: i32) -> Result<Option<(u32, u32, Vec<u8>)>> {
let pg = doc.GetPage(page as u32)?;
let ms = InMemoryRandomAccessStream::new()?;
let opt = PdfPageRenderOptions::new()?;
opt.SetDestinationWidth(width as u32)?;
opt.SetBackgroundColor(Color { A: 255, R: 255, G: 255, B: 255 })?;
pg.RenderWithOptionsToStreamAsync(&ms, &opt)?.get()?;
ms.Seek(0)?;
let st: IStream = unsafe { CreateStreamOverRandomAccessStream(&ms.cast::<IUnknown>()?)? };
Ok(decode_stream(wic, &st))
}
fn pdf_thread() {
unsafe {
let _ = CoInitializeEx(None, COINIT_MULTITHREADED);
}
let Ok(wic) = (unsafe { CoCreateInstance::<_, IWICImagingFactory>(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER) }) else { return };
let mut doc: Option<PdfDocument> = None;
let mut doc_gen = -1;
loop {
let (job, path, gen) = {
let (m, cv) = fila();
let mut f = m.lock().unwrap();
while !(f.quit || !f.jobs.is_empty() || f.gen != doc_gen) {
f = cv.wait(f).unwrap();
}
if f.quit {
return;
}
let job = if f.gen == doc_gen { f.jobs.pop_front() } else { None };
(job, f.path.clone(), f.gen)
};
if gen != doc_gen {
doc_gen = gen;
doc = None;
let mut info = InfoResult { gen, sizes: Vec::new(), error: String::new() };
match open_pdf(&path) {
Ok(d) => {
let n = d.PageCount().unwrap_or(0);
for i in 0..n {
if let Ok(s) = d.GetPage(i).and_then(|p| p.Size()) {
info.sizes.push((s.Width, s.Height));
}
}
doc = Some(d);
}
Err(e) => {
let senha = e.code() == ERROR_INVALID_PASSWORD.to_hresult() || e.code().0 as u32 == 0x8007052B;
info.error = tr(if senha { "O PDF tem senha." } else { "Não foi possível abrir o PDF." });
}
}
post_box(WM_PV_INFO, info);
continue;
}
let (Some(d), Some(job)) = (&doc, job) else { continue };
if job.gen != doc_gen || job.page < 0 || job.page >= d.PageCount().unwrap_or(0) as i32 {
continue;
}
let (w_, h, px) = render_page(&wic, d, job.page, job.width).ok().flatten().unwrap_or_default();
post_box(WM_PV_PAGE, PageResult { gen: job.gen, page: job.page, width: job.width, w: w_, h, px });
}
}
fn request(page: i32, width: i32) {
let (m, cv) = fila();
let mut f = m.lock().unwrap();
let g = a().gen;
if let Some(j) = f.jobs.iter_mut().find(|j| j.page == page && j.gen == g) {
j.width = width;
return;
}
f.jobs.push_back(Job { gen: g, page, width });
cv.notify_one();
}
// ---- documento
fn ext_of(p: &str) -> String {
std::path::Path::new(p).extension().map(|e| e.to_string_lossy().to_lowercase()).unwrap_or_default()
}
fn is_pdf(p: &str) -> bool {
ext_of(p) == "pdf"
}
fn is_image(p: &str) -> bool {
["png", "jpg", "jpeg", "gif", "bmp", "tif", "tiff", "webp", "heic", "heif", "ico", "jfif", "avif", "dds", "jxr"].contains(&ext_of(p).as_str())
}
fn file_name(p: &str) -> String {
p.rsplit(['\\', '/']).next().unwrap_or(p).to_string()
}
fn set_title() {
let n = if a().path.is_empty() { tr("Pré-Visualização") } else { file_name(&a().path) };
let t = wz(&n);
unsafe {
let _ = SetWindowTextW(a().hwnd, pc(&t));
}
}
fn open(path: &str) {
let a = a();
a.pages.clear();
a.path = path.to_string();
a.error.clear();
a.gen += 1;
a.fit = true;
a.rot = 0;
a.sx = 0.0;
a.sy = 0.0;
a.pdf = is_pdf(path);
a.anns.clear();
a.dirty = false;
set_title();
if a.pdf {
a.img_px.clear();
let (m, cv) = fila();
let mut f = m.lock().unwrap();
f.jobs.clear();
f.path = path.to_string();
f.gen = a.gen;
cv.notify_one();
} else {
let p = wz(path);
let dec = unsafe { SHCreateStreamOnFileEx(pc(&p), (STGM_READ | STGM_SHARE_DENY_NONE).0, 0, FALSE, None) }.ok().and_then(|st| decode_stream(&a.wic, &st));
match (dec, a.rt.clone()) {
(Some((w_, h, px)), Some(rt)) => {
a.pages.push(Page { w: w_ as f32, h: h as f32, bmp: make_bitmap(&rt, w_, h, &px), ..Default::default() });
a.img_px = px;
a.img_w = w_;
a.img_h = h;
}
_ => a.error = tr("Não foi possível abrir este arquivo."),
}
}
if a.foto.is_none() {
let p = wz(path);
unsafe { SHAddToRecentDocs(SHARD_PATHW.0 as u32, Some(p.as_ptr() as *const c_void)) };
}
invalidate();
}
/// aberta pelo Fotos (--lista <arquivo>): ← / → andam pela biblioteca na ordem da galeria
fn load_list(file: &str) {
a().list = app2d::read_lines(std::path::Path::new(file)).into_iter().map(|l| l.trim_start_matches('\u{FEFF}').to_string()).filter(|l| !l.is_empty()).collect();
}
fn neighbor(dir: i32) {
if a().pdf || a().path.is_empty() {
return;
}
let cur = a().path.to_lowercase();
if !a().list.is_empty() {
if let Some(i) = a().list.iter().position(|x| x.to_lowercase() == cur) {
let n = a().list.len() as i32;
if n > 1 {
let p = a().list[((i as i32 + dir + n) % n) as usize].clone();
open(&p);
return;
}
}
}
let Some(folder) = std::path::Path::new(&a().path).parent().map(|p| p.to_path_buf()) else { return };
let Ok(rd) = std::fs::read_dir(&folder) else { return };
let mut files: Vec<String> = rd.flatten().filter(|e| e.file_type().map(|t| t.is_file()).unwrap_or(false)).map(|e| e.path().to_string_lossy().to_string()).filter(|p| is_image(p)).collect();
files.sort_by(|x, y| {
let (wx, wy) = (wz(x), wz(y));
unsafe { StrCmpLogicalW(pc(&wx), pc(&wy)).cmp(&0) }
});
let Some(i) = files.iter().position(|x| x.to_lowercase() == cur) else { return };
if files.len() < 2 {
return;
}
let n = files.len() as i32;
let p = files[((i as i32 + dir + n) % n) as usize].clone();
open(&p);
}
// ---- geometria
fn side_w() -> f32 {
if a().unified && a().side && a().pdf && a().pages.len() > 1 {
206.0
} else {
0.0
}
}
fn view_size() -> (f32, f32) {
let (w_, h) = client_px();
let s = sc();
(w_ as f32 / s - side_w(), h as f32 / s - a().tb)
}
fn swapped() -> bool {
!a().pdf && (a().rot & 1) == 1
}
fn fit_zoom() -> f32 {
if a().pages.is_empty() {
return 1.0;
}
let (vw, vh) = view_size();
let sw = swapped();
let max_w = a().pages.iter().map(|p| if sw { p.h } else { p.w }).fold(0.0, f32::max);
let p0 = &a().pages[0];
let first_h = if sw { p0.w } else { p0.h };
let zw = (vw - 2.0 * MARGIN) / max_w;
if a().pdf {
return zw.max(0.05);
}
let zh = (vh - 2.0 * MARGIN) / first_h;
zw.min(zh).max(0.01)
}
fn zoom() -> f32 {
if a().fit {
if a().pdf {
fit_zoom()
} else {
fit_zoom().min(1.0)
}
} else {
a().zoom
}
}
/// as páginas uma embaixo da outra: (retângulo no documento, índice), largura e altura totais
fn layout() -> (Vec<(RectF, usize)>, f32, f32) {
let z = zoom();
let mut y = MARGIN;
let mut tw = 0.0f32;
let sw = swapped();
let mut out = Vec::new();
for (i, p) in a().pages.iter().enumerate() {
let (w_, h) = (if sw { p.h } else { p.w } * z, if sw { p.w } else { p.h } * z);
out.push((rf(0.0, y, w_, y + h), i));
tw = tw.max(w_);
y += h + GAP;
}
(out, tw + 2.0 * MARGIN, y - GAP + MARGIN)
}
fn clamp_scroll() {
let (_, tw, th) = layout();
let (vw, vh) = view_size();
let a = a();
a.sx = a.sx.clamp(0.0, (tw - vw).max(0.0));
a.sy = a.sy.clamp(0.0, (th - vh).max(0.0));
}
fn current_page() -> usize {
let (pl, _, _) = layout();
let (_, vh) = view_size();
let mid = a().sy + vh / 3.0;
pl.iter().find(|p| p.0.bottom + GAP >= mid).map(|p| p.1).unwrap_or(pl.last().map(|p| p.1).unwrap_or(0))
}
fn set_zoom(z: f32, anchor: Option<POINT>) {
let old = zoom();
let z = z.clamp(0.05, 16.0);
let (vw, vh) = view_size();
let s = sc();
let (ax, ay) = match anchor {
Some(p) => (p.x as f32 / s - side_w(), p.y as f32 / s - a().tb),
None => (vw / 2.0, vh / 2.0),
};
let (cx, cy) = ((a().sx + ax) / old, (a().sy + ay) / old);
a().fit = false;
a().zoom = z;
a().sx = cx * z - ax;
a().sy = cy * z - ay;
clamp_scroll();
invalidate();
}
fn page_rect_of(p: &(RectF, usize), tw: f32, vw: f32) -> RectF {
let off_x = if tw < vw { (vw - tw) / 2.0 } else { -a().sx } + side_w();
let off_y = a().tb - a().sy;
let pw = p.0.right - p.0.left;
let l = off_x + MARGIN + (tw - 2.0 * MARGIN - pw) / 2.0;
rf(l, off_y + p.0.top, l + pw, off_y + p.0.bottom)
}
fn page_rect(idx: i32) -> Option<RectF> {
let (vw, _) = view_size();
let (pl, tw, _) = layout();
pl.iter().find(|p| p.1 as i32 == idx).map(|p| page_rect_of(p, tw, vw))
}
fn page_at(x: f32, y: f32) -> Option<(i32, Ponto)> {
let z = zoom();
(0..a().pages.len() as i32).find_map(|i| {
let r = page_rect(i)?;
in_rect(&r, x, y).then(|| (i, pt((x - r.left) / z, (y - r.top) / z)))
})
}
// ---- recursos
fn create_res() {
if a().rt.is_some() {
return;
}
unsafe {
let (w_, h) = client_px();
if a().foto.is_some() {
let (fw, fh) = (2000u32, 1400u32);
let Ok(bmp) = a().wic.CreateBitmap(fw, fh, &GUID_WICPixelFormat32bppPBGRA, WICBitmapCacheOnLoad) else { return };
let props = D2D1_RENDER_TARGET_PROPERTIES {
r#type: D2D1_RENDER_TARGET_TYPE_SOFTWARE,
pixelFormat: D2D1_PIXEL_FORMAT { format: DXGI_FORMAT_B8G8R8A8_UNORM, alphaMode: D2D1_ALPHA_MODE_PREMULTIPLIED },
dpiX: 192.0,
dpiY: 192.0,
..Default::default()
};
a().rt = d2d().CreateWicBitmapRenderTarget(&bmp, &props).ok();
a().foto_bmp = Some(bmp);
} else {
let dpi = GetDpiForWindow(a().hwnd) as f32;
let props = D2D1_RENDER_TARGET_PROPERTIES { dpiX: dpi, dpiY: dpi, ..Default::default() };
let hp = D2D1_HWND_RENDER_TARGET_PROPERTIES { hwnd: a().hwnd, pixelSize: D2D_SIZE_U { width: w_ as u32, height: h as u32 }, presentOptions: D2D1_PRESENT_OPTIONS_NONE };
if let Ok(r) = d2d().CreateHwndRenderTarget(&props, &hp) {
a().rt = r.cast().ok();
a().hrt = Some(r);
}
}
if let Some(rt) = &a().rt {
a().br = rt.CreateSolidColorBrush(&col(0.0, 0.0, 0.0, 1.0), None).ok();
}
}
}
fn drop_res() {
for p in a().pages.iter_mut() {
p.bmp = None;
p.rendered_w = 0;
}
a().br = None;
a().rt = None;
a().hrt = None;
if !a().pdf && !a().path.is_empty() {
create_res();
let (z, f, ro, sx, sy) = (a().zoom, a().fit, a().rot, a().sx, a().sy);
let p = a().path.clone();
let anns = std::mem::take(&mut a().anns);
open(&p);
let a = a();
(a.zoom, a.fit, a.rot, a.sx, a.sy, a.anns) = (z, f, ro, sx, sy, anns);
}
}
// ---- marcação
fn draw_ann(rt: &ID2D1RenderTarget, an: &Ann, r: RectF, z: f32) {
if an.pts.is_empty() {
return;
}
let mut c = an.col;
if an.tool == T_HILITE {
c.a = 0.35;
}
unsafe {
let Some(b) = brush(rt, c) else { return };
let p = |q: Ponto| pt(r.left + q.x * z, r.top + q.y * z);
let round = a().round.clone();
let wd = (if an.tool == T_HILITE {
16.0
} else if an.tool == T_SIGN {
2.2
} else {
3.0
}) * z;
if matches!(an.tool, T_PEN | T_HILITE | T_SIGN) {
if let Ok(g) = d2d().CreatePathGeometry() {
if let Ok(s) = g.Open() {
s.BeginFigure(p(an.pts[0]), D2D1_FIGURE_BEGIN_HOLLOW);
for q in &an.pts[1..] {
s.AddLine(p(*q));
}
if an.pts.len() == 1 {
s.AddLine(p(pt(an.pts[0].x + 0.1, an.pts[0].y)));
}
s.EndFigure(D2D1_FIGURE_END_OPEN);
let _ = s.Close();
rt.DrawGeometry(&g, &b, wd, round.as_ref());
}
}
} else if an.pts.len() >= 2 {
let (p0, p1) = (p(an.pts[0]), p(*an.pts.last().unwrap()));
let q = rf(p0.x.min(p1.x), p0.y.min(p1.y), p0.x.max(p1.x), p0.y.max(p1.y));
match an.tool {
T_RECT => rt.DrawRectangle(&q, &b, wd, None),
T_OVAL => rt.DrawEllipse(&ell(pt((q.left + q.right) / 2.0, (q.top + q.bottom) / 2.0), (q.right - q.left) / 2.0, (q.bottom - q.top) / 2.0), &b, wd, None),
T_ARROW => {
rt.DrawLine(p0, p1, &b, wd, round.as_ref());
let ang = (p1.y - p0.y).atan2(p1.x - p0.x);
let l = 14.0 * z;
for s in [0.5f32, -0.5] {
rt.DrawLine(p1, pt(p1.x - l * (ang + s).cos(), p1.y - l * (ang + s).sin()), &b, wd, round.as_ref());
}
}
T_CROP => {
if let Some(dim) = brush(rt, col(0.0, 0.0, 0.0, 0.45)) {
rt.FillRectangle(&rf(r.left, r.top, r.right, q.top), &dim);
rt.FillRectangle(&rf(r.left, q.bottom, r.right, r.bottom), &dim);
rt.FillRectangle(&rf(r.left, q.top, q.left, q.bottom), &dim);
rt.FillRectangle(&rf(q.right, q.top, r.right, q.bottom), &dim);
}
b.SetColor(&col(1.0, 1.0, 1.0, 1.0));
rt.DrawRectangle(&q, &b, 1.5, None);
}
_ => {}
}
}
if an.tool == T_TEXT && !an.text.is_empty() {
let n = DWRITE_FONT_WEIGHT_NORMAL;
let f = cjk::format(dw(), "Helvetica", n, DWRITE_FONT_STYLE_NORMAL, (18.0 * z).max(1.0), "").or_else(|| cjk::format(dw(), "Arial", n, DWRITE_FONT_STYLE_NORMAL, (18.0 * z).max(1.0), ""));
if let Some(f) = f {
let q = p(an.pts[0]);
rt.DrawText(&w(&an.text), &f, &rf(q.x, q.y, q.x + 4000.0, q.y + 400.0), &b, D2D1_DRAW_TEXT_OPTIONS_NONE, DWRITE_MEASURING_MODE_NATURAL);
}
}
}
}
fn reset_image_page() {
let a = a();
let Some(rt) = a.rt.clone() else { return };
let p = &mut a.pages[0];
p.w = a.img_w as f32;
p.h = a.img_h as f32;
p.bmp = make_bitmap(&rt, a.img_w, a.img_h, &a.img_px);
}
/// gira os pixels da imagem (marcar sempre trabalha na imagem já girada)
fn bake_rotation() {
let a = a();
if a.pdf || a.rot == 0 || a.img_px.is_empty() {
return;
}
for _ in 0..a.rot {
let (wd, ht) = (a.img_w as usize, a.img_h as usize);
let mut o = vec![0u8; a.img_px.len()];
for y in 0..ht {
for x in 0..wd {
let d = (x * ht + (ht - 1 - y)) * 4;
let s = (y * wd + x) * 4;
o[d..d + 4].copy_from_slice(&a.img_px[s..s + 4]);
}
}
a.img_px = o;
std::mem::swap(&mut a.img_w, &mut a.img_h);
}
a.rot = 0;
reset_image_page();
}
fn apply_crop(p: Ponto, q: Ponto) {
let a = a();
if a.pdf || a.img_px.is_empty() {
return;
}
let (iw, ih) = (a.img_w as i32, a.img_h as i32);
let x0 = (p.x.min(q.x) as i32).clamp(0, iw);
let y0 = (p.y.min(q.y) as i32).clamp(0, ih);
let x1 = (p.x.max(q.x) as i32).clamp(0, iw);
let y1 = (p.y.max(q.y) as i32).clamp(0, ih);
if x1 - x0 < 8 || y1 - y0 < 8 {
return;
}
let (wd, ht) = ((x1 - x0) as usize, (y1 - y0) as usize);
let mut o = vec![0u8; wd * ht * 4];
for y in 0..ht {
let s = ((y0 as usize + y) * a.img_w as usize + x0 as usize) * 4;
o[y * wd * 4..(y + 1) * wd * 4].copy_from_slice(&a.img_px[s..s + wd * 4]);
}
a.img_px = o;
a.img_w = wd as u32;
a.img_h = ht as u32;
for an in a.anns.iter_mut() {
for p in an.pts.iter_mut() {
p.x -= x0 as f32;
p.y -= y0 as f32;
}
}
reset_image_page();
a.dirty = true;
a.fit = true;
}
// assinatura guardada: traços normalizados (0..1 na largura do conjunto)
fn load_sign() {
a().sign = app2d::read_lines(&data_path("assinatura.txt"))
.iter()
.map(|l| {
l.split_whitespace()
.filter_map(|t| {
let (x, y) = t.split_once(',')?;
Some(pt(x.parse().ok()?, y.parse().ok()?))
})
.collect::<Vec<_>>()
})
.filter(|s| !s.is_empty())
.collect();
}
fn save_sign(strokes: &[Vec<Ponto>]) {
let (mut x0, mut y0, mut x1) = (1e9f32, 1e9f32, -1e9f32);
for p in strokes.iter().flatten() {
x0 = x0.min(p.x);
y0 = y0.min(p.y);
x1 = x1.max(p.x);
}
let wd = (x1 - x0).max(1.0);
let norm: Vec<Vec<Ponto>> = strokes.iter().map(|s| s.iter().map(|p| pt((p.x - x0) / wd, (p.y - y0) / wd)).collect()).collect();
let linhas: Vec<String> = norm.iter().map(|s| s.iter().map(|q| format!("{:.4},{:.4} ", q.x, q.y)).collect()).collect();
app2d::write_lines(&data_path("assinatura.txt"), &linhas);
a().sign = norm;
}
fn end_sign_capture() {
if !a().sign_capture {
return;
}
a().sign_capture = false;
let strokes: Vec<Vec<Ponto>> = a().anns[a().sign_from..].iter().filter(|x| x.tool == T_SIGN).map(|x| x.pts.clone()).collect();
if !strokes.is_empty() {
save_sign(&strokes);
}
}
extern "system" fn text_proc(h: HWND, m: u32, w_: WPARAM, l: LPARAM) -> LRESULT {
unsafe {
if m == WM_KEYDOWN && (w_.0 as u16 == VK_RETURN.0 || w_.0 as u16 == VK_ESCAPE.0) {
if w_.0 as u16 == VK_ESCAPE.0 {
let _ = SetWindowTextW(h, w!(""));
}
commit_text();
return LRESULT(0);
}
if m == WM_CHAR && (w_.0 == 13 || w_.0 == 27) {
return LRESULT(0);
}
if m == WM_KILLFOCUS {
let _ = PostMessageW(a().hwnd, WM_PV_TEXTO, WPARAM(0), LPARAM(0));
}
let old: WNDPROC = std::mem::transmute(a().text_old);
CallWindowProcW(old, h, m, w_, l)
}
}
fn commit_text() {
let h = a().text;
if h.0.is_null() {
return;
}
let t = unsafe {
let n = GetWindowTextLengthW(h);
let mut b = vec![0u16; n as usize + 1];
let k = GetWindowTextW(h, &mut b);
from_w(&b[..k as usize])
};
a().text = HWND::default();
unsafe {
let _ = DestroyWindow(h);
}
if !t.is_empty() && a().text_page >= 0 {
let an = Ann { page: a().text_page, tool: T_TEXT, col: COLORS[a().color], pts: vec![a().text_at], text: t };
a().anns.push(an);
a().dirty = true;
}
invalidate();
}
fn start_text(page: i32, at: Ponto, x: f32, y: f32) {
commit_text();
a().text_page = page;
a().text_at = at;
let (s, z) = (sc(), zoom());
unsafe {
if !a().text_font.is_invalid() {
let _ = DeleteObject(a().text_font);
}
a().text_font = CreateFontW(-((18.0 * z * s).round() as i32), 0, 0, 0, FW_NORMAL.0 as i32, 0, 0, 0, DEFAULT_CHARSET.0 as u32, 0, 0, CLEARTYPE_QUALITY.0 as u32, 0, w!("Arial"));
let hi: HINSTANCE = GetModuleHandleW(None).unwrap_or_default().into();
let Ok(e) = CreateWindowExW(
WINDOW_EX_STYLE(0),
w!("EDIT"),
w!(""),
WS_CHILD | WS_VISIBLE | WS_BORDER | WINDOW_STYLE(ES_AUTOHSCROLL as u32),
(x * s) as i32,
(y * s) as i32,
(320.0 * s) as i32,
(18.0 * z * s * 1.5 + 6.0) as i32,
a().hwnd,
None,
hi,
None,
) else {
return;
};
SendMessageW(e, WM_SETFONT, WPARAM(a().text_font.0 as usize), LPARAM(1));
a().text_old = SetWindowLongPtrW(e, GWLP_WNDPROC, text_proc as *const () as isize);
a().text = e;
let _ = SetFocus(e);
}
}
/// grava um bitmap WIC em PNG (com alfa) ou JPEG
fn encode(src: &IWICBitmap, out: &str, jpg: bool) -> Result<()> {
unsafe {
let wic = &a().wic;
let (mut wd, mut ht) = (0, 0);
src.GetSize(&mut wd, &mut ht)?;
let st = wic.CreateStream()?;
let p = wz(out);
st.InitializeFromFilename(pc(&p), GENERIC_WRITE.0)?;
let enc = wic.CreateEncoder(if jpg { &GUID_ContainerFormatJpeg } else { &GUID_ContainerFormatPng }, std::ptr::null())?;
enc.Initialize(&st, WICBitmapEncoderNoCache)?;
let mut fe: Option<IWICBitmapFrameEncode> = None;
enc.CreateNewFrame(&mut fe, std::ptr::null_mut())?;
let fe = fe.ok_or_else(|| Error::from(E_FAIL))?;
fe.Initialize(None)?;
let fmt = if jpg { GUID_WICPixelFormat24bppBGR } else { GUID_WICPixelFormat32bppBGRA };
fe.SetSize(wd, ht)?;
let mut f2 = fmt;
fe.SetPixelFormat(&mut f2)?;
let cv = wic.CreateFormatConverter()?;
cv.Initialize(src, &fmt, WICBitmapDitherTypeNone, None, 0.0, WICBitmapPaletteTypeCustom)?;
fe.WriteSource(&cv, std::ptr::null())?;
fe.Commit()?;
enc.Commit()
}
}
/// exporta (imagem: a imagem toda; PDF: a página atual) com a marcação, em PNG ou JPEG
fn export() {
if a().pages.is_empty() {
return;
}
let page = if a().pdf { current_page() } else { 0 };
let (wd, ht) = if a().pdf { (a().pages[page].pw, a().pages[page].ph) } else { (a().img_w, a().img_h) };
let vazio = if a().pdf { a().pages[page].px.is_empty() } else { a().img_px.is_empty() };
if vazio || wd == 0 || ht == 0 {
message_box(&tr("A página ainda está carregando."), &tr("Pré-Visualização"), MB_OK);
return;
}
if !a().pdf && a().rot != 0 {
bake_rotation();
}
let (wd, ht) = if a().pdf { (wd, ht) } else { (a().img_w, a().img_h) };
let path = a().path.clone();
let mut base = file_name(&path);
if let Some(i) = base.rfind('.') {
base.truncate(i);
}
if a().pdf {
base += &format!(" - {}", page + 1);
}
base += &tr(" (editado)");
let Some(out) = pick_file(true, &[("PNG", "*.png"), ("JPEG", "*.jpg")], Some("png"), Some(&base)) else { return };
let jpg = matches!(ext_of(&out).as_str(), "jpg" | "jpeg");
let ok = (|| -> Result<()> {
unsafe {
let wb = a().wic.CreateBitmap(wd, ht, &GUID_WICPixelFormat32bppPBGRA, WICBitmapCacheOnLoad)?;
let props = D2D1_RENDER_TARGET_PROPERTIES { pixelFormat: D2D1_PIXEL_FORMAT { format: DXGI_FORMAT_B8G8R8A8_UNORM, alphaMode: D2D1_ALPHA_MODE_PREMULTIPLIED }, dpiX: 96.0, dpiY: 96.0, ..Default::default() };
let rt = d2d().CreateWicBitmapRenderTarget(&wb, &props)?;
let rt: ID2D1RenderTarget = rt.cast()?;
let src = if a().pdf { &a().pages[page].px } else { &a().img_px };
let img = make_bitmap(&rt, wd, ht, src).ok_or_else(|| Error::from(E_FAIL))?;
rt.BeginDraw();
rt.Clear(Some(&col(1.0, 1.0, 1.0, if jpg { 1.0 } else { 0.0 })));
rt.DrawBitmap(&img, Some(&rf(0.0, 0.0, wd as f32, ht as f32)), 1.0, D2D1_BITMAP_INTERPOLATION_MODE_LINEAR, None);
let z = wd as f32 / a().pages[page].w;
for an in a().anns.clone().iter().filter(|x| x.page == page as i32) {
draw_ann(&rt, an, rf(0.0, 0.0, wd as f32, ht as f32), z);
}
rt.EndDraw(None, None)?;
encode(&wb, &out, jpg)
}
})();
if ok.is_ok() {
a().dirty = false;
} else {
message_box(&tr("Não foi possível exportar."), &tr("Pré-Visualização"), MB_OK | MB_ICONERROR);
}
}
fn set_markup(on: bool) {
if on == a().markup {
return;
}
commit_text();
end_sign_capture();
a().markup = on;
a().tb = if on { TOOLH + MB } else { TOOLH };
if on {
bake_rotation();
load_sign();
}
clamp_scroll();
invalidate();
}
// ---- desenho
fn txt(rt: &ID2D1RenderTarget, br: &ID2D1SolidColorBrush, s: &str, tf: &IDWriteTextFormat, r: RectF, clip: bool) {
unsafe { rt.DrawText(&w(s), tf, &r, br, if clip { D2D1_DRAW_TEXT_OPTIONS_CLIP } else { D2D1_DRAW_TEXT_OPTIONS_NONE }, DWRITE_MEASURING_MODE_NATURAL) }
}
fn glyph(rt: &ID2D1RenderTarget, br: &ID2D1SolidColorBrush, g: u16, r: RectF) {
unsafe { rt.DrawText(&[g], &a().tf_icon, &r, br, D2D1_DRAW_TEXT_OPTIONS_NONE, DWRITE_MEASURING_MODE_NATURAL) }
}
fn c2(dark: bool, d: Cor, l: Cor) -> Cor {
if dark {
d
} else {
l
}
}
unsafe fn paint_markup_bar(rt: &ID2D1RenderTarget, br: &ID2D1SolidColorBrush, dark: bool, wd: f32) {
a().mbtns.clear();
if !a().markup {
return;
}
br.SetColor(&c2(dark, col(0.21, 0.21, 0.22, 1.0), col(0.93, 0.93, 0.94, 1.0)));
rt.FillRectangle(&rf(0.0, TOOLH, wd, TOOLH + MB), br);
br.SetColor(&c2(dark, col(0.0, 0.0, 0.0, 0.6), col(0.0, 0.0, 0.0, 0.12)));
rt.DrawLine(pt(0.0, TOOLH + MB - 0.5), pt(wd, TOOLH + MB - 0.5), br, 1.0, None);
let tools = [(T_PEN, 0xE76D), (T_HILITE, 0xE7E6), (T_RECT, 0xE739), (T_OVAL, 0xEA3A), (T_ARROW, 0xE72A), (T_TEXT, 0xE8D2), (T_SIGN, 0xEE56), (T_CROP, 0xE7A8)];
let (mut x, cy) = (14.0, TOOLH + MB / 2.0);
for (t, g) in tools {
if t == T_CROP && a().pdf {
continue;
}
let r = rf(x, cy - 14.0, x + 32.0, cy + 14.0);
if a().tool == t {
br.SetColor(&c2(dark, col(1.0, 1.0, 1.0, 0.18), col(0.0, 0.0, 0.0, 0.10)));
rt.FillRoundedRectangle(&rr(r, 6.0, 6.0), br);
}
br.SetColor(&c2(dark, col(1.0, 1.0, 1.0, 0.85), col(0.0, 0.0, 0.0, 0.75)));
glyph(rt, br, g, r);
a().mbtns.push(MBtn { kind: 0, arg: t, r });
x += 36.0;
}
x += 14.0;
for (i, c) in COLORS.iter().enumerate() {
let ce = pt(x + 11.0, cy);
br.SetColor(c);
rt.FillEllipse(&ell(ce, 9.0, 9.0), br);
br.SetColor(&c2(dark, col(1.0, 1.0, 1.0, 0.3), col(0.0, 0.0, 0.0, 0.25)));
rt.DrawEllipse(&ell(ce, 9.0, 9.0), br, 1.0, None);
if i == a().color {
br.SetColor(&col(0.04, 0.52, 1.0, 1.0));
rt.DrawEllipse(&ell(ce, 12.5, 12.5), br, 2.0, None);
}
a().mbtns.push(MBtn { kind: 1, arg: i as i32, r: rf(x, cy - 12.0, x + 22.0, cy + 12.0) });
x += 28.0;
}
x += 14.0;
let u = rf(x, cy - 14.0, x + 32.0, cy + 14.0);
let al = if a().anns.is_empty() { 0.3 } else { 0.85 };
br.SetColor(&c2(dark, col(1.0, 1.0, 1.0, al), col(0.0, 0.0, 0.0, al - 0.1)));
glyph(rt, br, 0xE7A7, u);
a().mbtns.push(MBtn { kind: 2, arg: 0, r: u });
if a().tool == T_SIGN {
let tip = if a().sign.is_empty() || a().sign_capture { tr("Desenhe a assinatura na página; ela fica guardada.") } else { tr("Clique na página para pôr a assinatura. Botão direito: desenhar outra.") };
br.SetColor(&c2(dark, col(1.0, 1.0, 1.0, 0.55), col(0.0, 0.0, 0.0, 0.55)));
txt(rt, br, &tip, &a().tf_sub, rf(u.right + 16.0, TOOLH, wd - 100.0, TOOLH + MB), true);
}
let ok = rf(wd - 84.0, cy - 13.0, wd - 14.0, cy + 13.0);
br.SetColor(&col(0.04, 0.52, 1.0, 1.0));
rt.FillRoundedRectangle(&rr(ok, 6.0, 6.0), br);
br.SetColor(&col(1.0, 1.0, 1.0, 1.0));
txt(rt, br, "OK", &a().tf_empty, ok, false);
a().mbtns.push(MBtn { kind: 3, arg: 0, r: ok });
}
unsafe fn glass(rt: &ID2D1RenderTarget, br: &ID2D1SolidColorBrush, dark: bool, r: RectF) {
let rad = (r.bottom - r.top) / 2.0;
for k in (1..=3).rev() {
let k = k as f32;
br.SetColor(&col(0.0, 0.0, 0.0, if dark { 0.10 } else { 0.035 }));
rt.FillRoundedRectangle(&rr(rf(r.left - k * 0.5, r.top + k * 0.6, r.right + k * 0.5, r.bottom + k * 1.1), rad + k, rad + k), br);
}
br.SetColor(&c2(dark, col(0.24, 0.24, 0.245, 1.0), col(0.985, 0.985, 0.985, 1.0)));
rt.FillRoundedRectangle(&rr(r, rad, rad), br);
br.SetColor(&c2(dark, col(1.0, 1.0, 1.0, 0.13), col(0.0, 0.0, 0.0, 0.09)));
rt.DrawRoundedRectangle(&rr(rf(r.left + 0.25, r.top + 0.25, r.right - 0.25, r.bottom - 0.25), rad - 0.25, rad - 0.25), br, 0.5, None);
}
fn paint() {
create_res();
let (Some(rt), Some(br)) = (a().rt.clone(), a().br.clone()) else { return };
let dark = dark();
let (vw, vh) = view_size();
let tb = a().tb;
unsafe {
rt.BeginDraw();
rt.Clear(Some(&c2(dark, col(0.118, 0.118, 0.122, 1.0), col(0.89, 0.89, 0.90, 1.0))));
// páginas
let (pl, tw, _) = layout();
let xs = side_w();
let (z, s) = (zoom(), sc());
rt.PushAxisAlignedClip(&rf(xs, tb, xs + vw, tb + vh), D2D1_ANTIALIAS_MODE_ALIASED);
for p in &pl {
let r = page_rect_of(p, tw, vw);
if r.bottom < tb - 200.0 || r.top > tb + vh + 200.0 {
continue;
}
let idx = p.1;
if a().pdf {
// pede a página na resolução da tela (de novo se o zoom mudou bastante)
let want = 6000.min(((r.right - r.left) * s).round() as i32);
let pg = &mut a().pages[idx];
if !pg.pending && (pg.rendered_w == 0 || (pg.rendered_w - want).abs() > want / 6) {
pg.pending = true;
request(idx as i32, want);
}
br.SetColor(&col(0.0, 0.0, 0.0, 0.18));
rt.FillRectangle(&rf(r.left + 1.0, r.top + 2.0, r.right + 1.0, r.bottom + 3.0), &br);
br.SetColor(&col(1.0, 1.0, 1.0, 1.0));
rt.FillRectangle(&r, &br);
}
if let Some(bmp) = a().pages[idx].bmp.clone() {
let c = pt((r.left + r.right) / 2.0, (r.top + r.bottom) / 2.0);
let mut old = mat::ident();
rt.GetTransform(&mut old);
let mut dst = r;
let rot = a().rot;
if !a().pdf && rot != 0 {
rt.SetTransform(&mat::mul(&mat::rot(90.0 * rot as f32, c.x, c.y), &old));
if rot & 1 == 1 {
let (hw, hh) = ((r.bottom - r.top) / 2.0, (r.right - r.left) / 2.0);
dst = rf(c.x - hw, c.y - hh, c.x + hw, c.y + hh);
}
}
rt.DrawBitmap(&bmp, Some(&dst), 1.0, D2D1_BITMAP_INTERPOLATION_MODE_LINEAR, None);
rt.SetTransform(&old);
}
for an in a().anns.clone().iter().filter(|x| x.page == idx as i32) {
draw_ann(&rt, an, r, z);
}
if a().drawing && a().cur.page == idx as i32 {
let c = a().cur.clone();
draw_ann(&rt, &c, r, z);
}
}
rt.PopAxisAlignedClip();
a().thumb_hits.clear();
if xs > 0.0 {
// coluna das miniaturas
let side_c = c2(dark, col(0.17, 0.165, 0.16, 1.0), col(0.93, 0.93, 0.925, 1.0));
br.SetColor(&side_c);
rt.FillRectangle(&rf(0.0, 0.0, xs, tb + vh), &br);
br.SetColor(&c2(dark, col(0.0, 0.0, 0.0, 0.5), col(0.0, 0.0, 0.0, 0.10)));
rt.FillRectangle(&rf(xs - 0.5, 0.0, xs, tb + vh), &br);
rt.PushAxisAlignedClip(&rf(0.0, TOOLH, xs, tb + vh), D2D1_ANTIALIAS_MODE_ALIASED);
let cur = current_page();
let mut y = TOOLH + 8.0 - a().thumb_scroll;
let tw2 = xs - 62.0;
for i in 0..a().pages.len() {
let (pw, ph) = (a().pages[i].w, a().pages[i].h);
let th2 = if pw > 0.0 { tw2 * ph / pw } else { tw2 * 1.3 };
let pr = rf((xs - tw2) / 2.0, y + 8.0, (xs + tw2) / 2.0, y + 8.0 + th2);
let cell = rf(14.0, y, xs - 14.0, pr.bottom + 26.0);
if cell.bottom > TOOLH && cell.top < tb + vh {
if i == cur {
br.SetColor(&c2(dark, col(0.33, 0.42, 0.58, 0.85), col(0.55, 0.64, 0.78, 0.85)));
rt.FillRoundedRectangle(&rr(rf(cell.left, cell.top, cell.right, pr.bottom + 8.0), 8.0, 8.0), &br);
}
br.SetColor(&col(0.0, 0.0, 0.0, 0.15));
rt.FillRectangle(&rf(pr.left + 0.5, pr.top + 1.0, pr.right + 0.5, pr.bottom + 1.5), &br);
br.SetColor(&col(1.0, 1.0, 1.0, 1.0));
rt.FillRectangle(&pr, &br);
let pg = &mut a().pages[i];
if let Some(b) = &pg.bmp {
rt.DrawBitmap(b, Some(&pr), 1.0, D2D1_BITMAP_INTERPOLATION_MODE_LINEAR, None);
} else if !pg.pending && pg.rendered_w == 0 {
// a miniatura também serve de primeira imagem
pg.pending = true;
request(i as i32, (tw2 * 2.0 * s).round() as i32);
}
br.SetColor(&c2(dark, col(1.0, 1.0, 1.0, 0.75), col(0.0, 0.0, 0.0, 0.7)));
txt(&rt, &br, &(i + 1).to_string(), &a().tf_thumb, rf(cell.left, pr.bottom + 8.0, cell.right, pr.bottom + 24.0), false);
}
a().thumb_hits.push((i as i32, cell));
y = pr.bottom + 34.0;
}
a().thumb_total = y + a().thumb_scroll - TOOLH;
rt.PopAxisAlignedClip();
}
if a().pages.is_empty() {
let t = if !a().error.is_empty() {
a().error.clone()
} else if a().path.is_empty() {
tr("Abra uma imagem ou um PDF (Ctrl+O) ou solte um arquivo aqui.")
} else {
tr("Abrindo…")
};
br.SetColor(&c2(dark, col(1.0, 1.0, 1.0, 0.5), col(0.0, 0.0, 0.0, 0.5)));
txt(&rt, &br, &t, &a().tf_empty, rf(xs + 20.0, tb, xs + vw - 20.0, tb + vh), false);
}
// barra de ferramentas (a janela toda; com a coluna, ela fica atrás só do conteúdo)
let wd = vw + xs;
br.SetColor(&c2(dark, col(0.17, 0.17, 0.18, 1.0), col(0.965, 0.965, 0.965, 1.0)));
rt.FillRectangle(&rf(xs, 0.0, wd, TOOLH), &br);
if xs > 0.0 {
br.SetColor(&c2(dark, col(0.17, 0.165, 0.16, 1.0), col(0.93, 0.93, 0.925, 1.0)));
rt.FillRectangle(&rf(0.0, 0.0, xs - 0.5, TOOLH), &br);
}
br.SetColor(&c2(dark, col(0.0, 0.0, 0.0, 0.6), col(0.0, 0.0, 0.0, 0.14)));
rt.DrawLine(pt(0.0, TOOLH - 0.5), pt(wd, TOOLH - 0.5), &br, 1.0, None);
let name = if a().path.is_empty() { tr("Pré-Visualização") } else { file_name(&a().path) };
let mut sub = String::new();
if !a().pages.is_empty() {
sub = if a().pdf { cf!(tr("Página %d de %d"), current_page() as i32 + 1, a().pages.len() as i32) } else { format!("{} × {}", a().pages[0].w as i32, a().pages[0].h as i32) };
sub += &format!(" {}%", (zoom() * 100.0).round() as i32);
}
// botões à direita
let empty = a().pages.is_empty();
let pdf = a().pdf;
a().btns = [(0xE70F, B_MARK), (0xE78C, B_EXPORT), (0xE7AD, B_ROT), (0xE71F, B_OUT), (0xE8A3, B_IN), (0xE9A6, B_FIT), (0xE749, B_PRINT)].iter().map(|&(g, id)| Btn { glyph: g, id, r: rf(0.0, 0.0, 0.0, 0.0) }).collect();
let mut bx = wd - 14.0;
let markup = a().markup;
let hover = a().hover_btn;
if a().unified {
// macOS 27: da direita para a esquerda imprimir, exportar, girar, marcar (redondos) e a cápsula −/ajustar/+
bx = wd - 8.0;
for k in [6usize, 1, 2, 0] {
let r = rf(bx - 36.0, 8.0, bx, 44.0);
a().btns[k].r = r;
glass(&rt, &br, dark, r);
bx -= 44.0;
}
let cap = rf(bx - 108.0, 8.0, bx, 44.0);
glass(&rt, &br, dark, cap);
a().btns[3].r = rf(cap.left + 2.0, 8.0, cap.left + 36.0, 44.0);
a().btns[5].r = rf(cap.left + 37.0, 8.0, cap.left + 71.0, 44.0);
a().btns[4].r = rf(cap.left + 72.0, 8.0, cap.left + 106.0, 44.0);
bx = cap.left - 8.0;
if pdf && a().pages.len() > 1 {
let sx = if xs > 0.0 { xs - 58.0 } else { 84.0 };
let r = rf(sx, 8.0, sx + 50.0, 44.0);
a().btns.push(Btn { glyph: 0xE8A0, id: B_SIDE, r });
glass(&rt, &br, dark, r);
}
for i in 0..a().btns.len() {
let (id, r, g) = (a().btns[i].id, a().btns[i].r, a().btns[i].glyph);
if i as i32 == hover || (id == B_MARK && markup) {
br.SetColor(&c2(dark, col(1.0, 1.0, 1.0, 0.12), col(0.0, 0.0, 0.0, 0.06)));
rt.FillRoundedRectangle(&rr(r, 18.0, 18.0), &br);
}
let off = (id == B_ROT && pdf) || empty;
br.SetColor(&c2(dark, col(1.0, 1.0, 1.0, if off { 0.3 } else { 0.88 }), col(0.0, 0.0, 0.0, if off { 0.25 } else { 0.8 })));
if id == B_SIDE {
let (cx, cy) = (r.left + 19.0, 26.0);
rt.DrawRoundedRectangle(&rr(rf(cx - 8.0, cy - 6.5, cx + 8.0, cy + 6.5), 2.5, 2.5), &br, 1.3, None);
rt.DrawLine(pt(cx - 3.0, cy - 6.0), pt(cx - 3.0, cy + 6.0), &br, 1.3, None);
rt.DrawLine(pt(r.right - 17.0, cy - 1.5), pt(r.right - 14.0, cy + 1.5), &br, 1.3, None);
rt.DrawLine(pt(r.right - 14.0, cy + 1.5), pt(r.right - 11.0, cy - 1.5), &br, 1.3, None);
continue;
}
glyph(&rt, &br, g, r);
}
} else {
for i in (0..a().btns.len()).rev() {
let r = rf(bx - 34.0, TOOLH / 2.0 - 15.0, bx, TOOLH / 2.0 + 15.0);
a().btns[i].r = r;
bx -= 38.0;
let id = a().btns[i].id;
if i as i32 == hover || (id == B_MARK && markup) {
br.SetColor(&c2(dark, col(1.0, 1.0, 1.0, 0.12), col(0.0, 0.0, 0.0, 0.07)));
rt.FillRoundedRectangle(&rr(r, 7.0, 7.0), &br);
}
let off = (id == B_ROT && pdf) || empty;
br.SetColor(&c2(dark, col(1.0, 1.0, 1.0, if off { 0.3 } else { 0.82 }), col(0.0, 0.0, 0.0, if off { 0.25 } else { 0.72 })));
glyph(&rt, &br, a().btns[i].glyph, r);
}
}
br.SetColor(&c2(dark, col(1.0, 1.0, 1.0, 0.92), col(0.0, 0.0, 0.0, 0.88)));
let tx = if a().unified {
if xs > 0.0 {
xs + 12.0
} else if pdf && a().pages.len() > 1 {
146.0
} else {
96.0
}
} else {
16.0
};
txt(&rt, &br, &name, &a().tf_title, rf(tx, 8.0, bx - 10.0, 28.0), true);
br.SetColor(&c2(dark, col(1.0, 1.0, 1.0, 0.5), col(0.0, 0.0, 0.0, 0.5)));
txt(&rt, &br, &sub, &a().tf_sub, rf(tx, 28.0, bx - 10.0, 46.0), true);
if a().unified && a().foto.is_some() {
// no --foto não há a WacOSWindow.dll: os três botões vão desenhados aqui, onde ela os poria
for (k, c) in semaforo::pick([col(1.0, 0.373, 0.345, 1.0), col(0.996, 0.737, 0.180, 1.0), col(0.157, 0.784, 0.251, 1.0)], semaforo::Kind::Fill).iter().enumerate() {
let ce = pt(26.0 + 23.0 * k as f32, 26.0);
br.SetColor(c);
rt.FillEllipse(&ell(ce, 7.0, 7.0), &br);
}
}
paint_markup_bar(&rt, &br, dark, wd);
if let Err(e) = rt.EndDraw(None, None) {
if e.code() == D2DERR_RECREATE_TARGET {
drop_res();
}
}
}
}
fn scroll(dx: f32, dy: f32) {
a().sx += dx;
a().sy += dy;
clamp_scroll();
invalidate();
}
fn go_page(i: i32) {
let (pl, _, _) = layout();
if pl.is_empty() {
return;
}
let i = i.clamp(0, pl.len() as i32 - 1) as usize;
a().sy = pl[i].0.top - MARGIN / 2.0;
clamp_scroll();
invalidate();
}
fn open_dialog() {
let f = tr("Imagens e PDF");
let t = tr("Todos");
if let Some(p) = pick_file(false, &[(&f, "*.pdf;*.png;*.jpg;*.jpeg;*.gif;*.bmp;*.tif;*.tiff;*.webp;*.heic;*.ico"), (&t, "*.*")], None, None) {
open(&p);
}
}
fn action(id: i32) {
if id == B_SIDE {
a().side = !a().side;
clamp_scroll();
invalidate();
return;
}
if a().pages.is_empty() {
return;
}
match id {
B_ROT => {
if !a().pdf {
a().rot = (a().rot + 3) % 4;
clamp_scroll();
invalidate();
}
}
B_OUT => set_zoom(zoom() / 1.25, None),
B_IN => set_zoom(zoom() * 1.25, None),
B_FIT => {
a().fit = true;
a().sx = 0.0;
a().sy = 0.0;
clamp_scroll();
invalidate();
}
B_PRINT => imprimir(),
B_MARK => set_markup(!a().markup),
B_EXPORT => export(),
_ => {}
}
}
// Imprimir pelo próprio Pré-Visualização. Antes ia pelo verbo "print" do Windows, que não faz nada quando o leitor
// de PDF padrão não tem esse verbo (o próprio WacOS, o Edge em alguns PCs) (#455).
fn imprime_pagina(dc: HDC, mut px: Vec<u8>, w_: u32, h: u32) {
use comum::windows::Win32::Graphics::Gdi::*;
if w_ == 0 || h == 0 || px.len() < (w_ * h * 4) as usize {
return;
}
for c in px.chunks_exact_mut(4) {
// pré-multiplicado: o transparente sai branco no papel, não preto
let f = 255 - c[3];
for k in 0..3 {
c[k] = c[k].saturating_add(f);
}
}
unsafe {
let pw = GetDeviceCaps(dc, HORZRES);
let ph = GetDeviceCaps(dc, VERTRES);
let s_ = (pw as f64 / w_ as f64).min(ph as f64 / h as f64);
let (dw, dh) = ((w_ as f64 * s_) as i32, (h as f64 * s_) as i32);
let mut bi = BITMAPINFO::default();
bi.bmiHeader.biSize = std::mem::size_of::<BITMAPINFOHEADER>() as u32;
bi.bmiHeader.biWidth = w_ as i32;
bi.bmiHeader.biHeight = -(h as i32);
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biBitCount = 32;
bi.bmiHeader.biCompression = BI_RGB.0;
SetStretchBltMode(dc, HALFTONE);
let _ = SetBrushOrgEx(dc, 0, 0, None);
StretchDIBits(dc, (pw - dw) / 2, (ph - dh) / 2, dw, dh, 0, 0, w_ as i32, h as i32, Some(px.as_ptr() as *const c_void), &bi, DIB_RGB_COLORS, SRCCOPY);
}
}
fn imprimir() {
use comum::windows::Win32::Storage::Xps::*;
use comum::windows::Win32::UI::Controls::Dialogs::*;
let app = a();
if !app.pdf && app.img_px.is_empty() {
let p = wz(&app.path);
unsafe {
ShellExecuteW(app.hwnd, w!("print"), pc(&p), None, None, SW_SHOWNORMAL);
}
return;
}
if !app.pdf && app.rot != 0 {
bake_rotation();
}
let app = a();
let total = app.pages.len().max(1) as u32;
let mut faixas = [PRINTPAGERANGE::default(); 16];
let mut pd = PRINTDLGEXW::default();
pd.lStructSize = std::mem::size_of::<PRINTDLGEXW>() as u32;
pd.hwndOwner = app.hwnd;
pd.Flags = PD_RETURNDC | PD_NOSELECTION | PD_NOCURRENTPAGE | if app.pdf { PRINTDLGEX_FLAGS(0) } else { PD_NOPAGENUMS };
pd.nStartPage = START_PAGE_GENERAL;
pd.nCopies = 1;
pd.nMinPage = 1;
pd.nMaxPage = total;
pd.nMaxPageRanges = 16;
pd.lpPageRanges = faixas.as_mut_ptr();
let ok = unsafe { PrintDlgExW(&mut pd) }.is_ok() && pd.dwResultAction == PD_RESULT_PRINT && !pd.hDC.is_invalid();
unsafe {
if !pd.hDevMode.is_invalid() {
let _ = comum::windows::Win32::Foundation::GlobalFree(pd.hDevMode);
}
if !pd.hDevNames.is_invalid() {
let _ = comum::windows::Win32::Foundation::GlobalFree(pd.hDevNames);
}
}
if !ok {
if !pd.hDC.is_invalid() {
unsafe {
let _ = DeleteDC(pd.hDC);
}
}
return;
}
let mut paginas: Vec<u32> = Vec::new();
if app.pdf && (pd.Flags & PD_PAGENUMS).0 != 0 {
for f in &faixas[..pd.nPageRanges as usize] {
for n in f.nFromPage.max(1)..=f.nToPage.min(total) {
paginas.push(n - 1);
}
}
} else {
paginas = (0..total).collect();
}
let dc = pd.hDC.0 as isize;
let path = app.path.clone();
let nome = path.rsplit(['\\', '/']).next().unwrap_or("").to_string();
let pdf = app.pdf;
let img = if pdf { Vec::new() } else { app.img_px.clone() };
let (iw, ih) = (app.img_w, app.img_h);
std::thread::spawn(move || {
let dc = HDC(dc as *mut c_void);
unsafe {
let _ = CoInitializeEx(None, COINIT_MULTITHREADED);
let wn = wz(&nome);
let di = DOCINFOW { cbSize: std::mem::size_of::<DOCINFOW>() as i32, lpszDocName: pc(&wn), ..Default::default() };
if StartDocW(dc, &di) <= 0 {
let _ = DeleteDC(dc);
return;
}
if !pdf {
StartPage(dc);
imprime_pagina(dc, img, iw, ih);
EndPage(dc);
} else if let (Ok(wic), Ok(doc)) = (CoCreateInstance::<_, IWICImagingFactory>(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER), open_pdf(&path)) {
let larg = GetDeviceCaps(dc, HORZRES).max(1);
let n = doc.PageCount().unwrap_or(0);
for i in paginas {
if i >= n {
break;
}
// até ~300 ppp da página (a resolução da impressora pode passar disso e gastar muita memória)
let lp = doc.GetPage(i).and_then(|p| p.Size()).map(|s| (s.Width / 72.0 * 300.0) as i32).unwrap_or(larg);
let w_ = larg.min(lp).max(1);
if let Ok(Some((pw, ph, px))) = render_page(&wic, &doc, i as i32, w_) {
StartPage(dc);
imprime_pagina(dc, px, pw, ph);
EndPage(dc);
}
}
}
EndDoc(dc);
let _ = DeleteDC(dc);
}
});
}
fn hit(r: &RectF, x: f32, y: f32) -> bool {
x >= r.left && x < r.right && y >= r.top && y < r.bottom
}
/// --foto: desenha até as páginas chegarem (ou 8 s), salva e fecha
fn foto_check() {
a().foto_ticks += 1;
paint();
let a_ = a();
let pronto = !a_.error.is_empty() || (!a_.pages.is_empty() && a_.pages.iter().all(|p| !p.pending) && (!a_.pdf || a_.pages.first().map(|p| p.bmp.is_some()).unwrap_or(false))) || (!a_.pdf && a_.path.is_empty());
if !pronto && a_.foto_ticks < 27 {
return;
}
paint();
let p = a().foto.clone().unwrap();
if let Some(b) = a().foto_bmp.clone() {
println!("foto: {p} {:?}", salvar_png(&b, &p));
}
unsafe {
let _ = DestroyWindow(a().hwnd);
}
}
extern "system" fn wnd_proc(h: HWND, m: u32, w_: WPARAM, l: LPARAM) -> LRESULT {
unsafe {
if A.get().is_none() {
return DefWindowProcW(h, m, w_, l);
}
if a().unified && m == WM_NCCALCSIZE && w_.0 != 0 {
// macOS 27: sem a barra de cima do Windows (as bordas ficam)
let p = &mut *(l.0 as *mut NCCALCSIZE_PARAMS);
let top = p.rgrc[0].top;
let r = DefWindowProcW(h, m, w_, l);
p.rgrc[0].top = top;
if IsZoomed(h).as_bool() {
let dpi = GetDpiForWindow(h);
p.rgrc[0].top += GetSystemMetricsForDpi(SM_CYFRAME, dpi) + GetSystemMetricsForDpi(SM_CXPADDEDBORDER, dpi);
}
return r;
}
if a().unified && m == WM_NCHITTEST {
// arrasta pela barra, menos pelos botões
let r = DefWindowProcW(h, m, w_, l);
if r.0 != HTCLIENT as isize {
return r;
}
let p = screen_to_client(h, l);
let s = sc();
let (x, y) = (p.x as f32 / s, p.y as f32 / s);
if !IsZoomed(h).as_bool() && p.y < (5.0 * s) as i32 {
return LRESULT(HTTOP as isize);
}
if y >= TOOLH || x < 84.0 || a().btns.iter().any(|b| hit(&b.r, x, y)) {
return LRESULT(HTCLIENT as isize);
}
return LRESULT(HTCAPTION as isize);
}
match m {
WM_PAINT => {
let mut ps = PAINTSTRUCT::default();
BeginPaint(h, &mut ps);
if a().foto.is_none() {
paint();
}
let _ = EndPaint(h, &ps);
}
WM_ERASEBKGND => return LRESULT(1),
WM_SIZE => {
if let Some(r) = &a().hrt {
let _ = r.Resize(&D2D_SIZE_U { width: loword(l.0 as usize), height: hiword(l.0 as usize) });
}
clamp_scroll();
invalidate();
}
WM_DPICHANGED => {
let r = &*(l.0 as *const RECT);
let _ = SetWindowPos(h, None, r.left, r.top, r.right - r.left, r.bottom - r.top, SWP_NOZORDER | SWP_NOACTIVATE);
if let Some(rt) = &a().hrt {
rt.SetDpi(hiword(w_.0) as f32, hiword(w_.0) as f32);
}
invalidate();
}
WM_SETTINGCHANGE => invalidate(),
WM_TIMER if w_.0 == 7 => foto_check(),
WM_PV_ASK => open_dialog(),
WM_PV_INFO => {
let info = Box::from_raw(l.0 as *mut InfoResult);
if info.gen == a().gen {
a().error = info.error;
for (pw, ph) in info.sizes {
a().pages.push(Page { w: pw, h: ph, ..Default::default() });
}
invalidate();
}
}
WM_PV_PAGE => {
let r = Box::from_raw(l.0 as *mut PageResult);
if r.gen == a().gen && (r.page as usize) < a().pages.len() {
if let Some(rt) = a().rt.clone() {
let p = &mut a().pages[r.page as usize];
p.pending = false;
if !r.px.is_empty() {
if let Some(b) = make_bitmap(&rt, r.w, r.h, &r.px) {
p.bmp = Some(b);
p.rendered_w = r.width;
p.pw = r.w;
p.ph = r.h;
p.px = r.px;
}
}
invalidate();
}
}
}
WM_MOUSEWHEEL | WM_MOUSEHWHEEL => {
let d = wheel_delta(w_) / 120.0;
let keys = loword(w_.0) as u32;
let p = screen_to_client(h, l);
if m == WM_MOUSEWHEEL && keys & 0x0008 != 0 {
set_zoom(zoom() * 1.15f32.powf(d), Some(p));
} else if (p.x as f32 / sc()) < side_w() {
// a coluna rola sozinha
a().thumb_scroll = (a().thumb_scroll - d * 80.0).clamp(0.0, (a().thumb_total - view_size().1).max(0.0));
invalidate();
} else if m == WM_MOUSEHWHEEL || keys & 0x0004 != 0 {
scroll(if m == WM_MOUSEHWHEEL { d * 60.0 } else { -d * 60.0 }, 0.0);
} else {
scroll(0.0, -d * 80.0);
}
}
WM_LBUTTONDOWN => {
let s = sc();
let (x, y) = (get_x_lparam(l) as f32 / s, get_y_lparam(l) as f32 / s);
if let Some(id) = a().btns.iter().find(|b| hit(&b.r, x, y)).map(|b| b.id) {
action(id);
return LRESULT(0);
}
if x < side_w() && y > TOOLH {
if let Some(i) = a().thumb_hits.iter().find(|t| y >= t.1.top && y < t.1.bottom).map(|t| t.0) {
go_page(i);
}
return LRESULT(0);
}
if let Some((kind, arg)) = a().mbtns.iter().find(|b| hit(&b.r, x, y)).map(|b| (b.kind, b.arg)) {
commit_text();
match kind {
0 => {
if a().tool == T_SIGN && arg != T_SIGN {
end_sign_capture();
}
a().tool = arg;
}
1 => a().color = arg as usize,
2 => {
if a().anns.pop().is_some() {
a().dirty = true;
}
}
_ => set_markup(false),
}
invalidate();
return LRESULT(0);
}
if a().markup && y > a().tb {
commit_text();
let Some((pg, at)) = page_at(x, y) else { return LRESULT(0) };
let tool = a().tool;
if tool == T_TEXT {
start_text(pg, at, x, y - 10.0);
return LRESULT(0);
}
if tool == T_SIGN && !a().sign.is_empty() && !a().sign_capture {
// põe a assinatura guardada (180 unidades de largura)
let sw = 180.0 * if a().pdf { 1.0 } else { (a().pages[pg as usize].w / 900.0).max(1.0) };
for s_ in a().sign.clone() {
let pts = s_.iter().map(|q| pt(at.x + q.x * sw, at.y + q.y * sw - sw * 0.15)).collect();
a().anns.push(Ann { page: pg, tool: T_SIGN, col: COLORS[0], pts, text: String::new() });
}
a().dirty = true;
invalidate();
return LRESULT(0);
}
if tool == T_SIGN && !a().sign_capture {
a().sign_capture = true;
a().sign_from = a().anns.len();
}
let c = if tool == T_SIGN {
COLORS[0]
} else if tool == T_HILITE && a().color == 0 {
COLORS[3]
} else {
COLORS[a().color]
};
let mut pts = vec![at];
if !matches!(tool, T_PEN | T_HILITE | T_SIGN) {
pts.push(at);
}
a().cur = Ann { page: pg, tool, col: c, pts, text: String::new() };
a().drawing = true;
SetCapture(h);
return LRESULT(0);
}
if y > a().tb {
a().drag = true;
a().drag_at = POINT { x: get_x_lparam(l), y: get_y_lparam(l) };
a().drag_sx = a().sx;
a().drag_sy = a().sy;
SetCapture(h);
}
}
WM_MOUSEMOVE => {
let s = sc();
let (x, y) = (get_x_lparam(l) as f32 / s, get_y_lparam(l) as f32 / s);
if a().drawing {
let z = zoom();
let pg = a().cur.page;
if let Some(r) = page_rect(pg) {
let (pw, ph) = (a().pages[pg as usize].w, a().pages[pg as usize].h);
let q = pt(((x - r.left) / z).clamp(0.0, pw), ((y - r.top) / z).clamp(0.0, ph));
let c = &mut a().cur;
if matches!(c.tool, T_PEN | T_HILITE | T_SIGN) {
c.pts.push(q);
} else {
*c.pts.last_mut().unwrap() = q;
}
}
invalidate();
return LRESULT(0);
}
if a().drag {
a().sx = a().drag_sx - (get_x_lparam(l) - a().drag_at.x) as f32 / s;
a().sy = a().drag_sy - (get_y_lparam(l) - a().drag_at.y) as f32 / s;
clamp_scroll();
invalidate();
return LRESULT(0);
}
let hv = a().btns.iter().rposition(|b| hit(&b.r, x, y)).map(|i| i as i32).unwrap_or(-1);
if hv != a().hover_btn {
a().hover_btn = 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_btn >= 0 {
a().hover_btn = -1;
invalidate();
}
}
WM_LBUTTONUP => {
if a().drawing {
a().drawing = false;
let _ = ReleaseCapture();
let c = std::mem::take(&mut a().cur);
if c.tool == T_CROP {
if c.pts.len() >= 2 {
apply_crop(c.pts[0], *c.pts.last().unwrap());
}
} else {
a().anns.push(c);
a().dirty = true;
}
invalidate();
return LRESULT(0);
}
if a().drag {
a().drag = false;
let _ = ReleaseCapture();
}
}
WM_RBUTTONUP => {
// assinatura: botão direito desenha outra
if a().markup && a().tool == T_SIGN {
a().sign.clear();
a().sign_capture = false;
invalidate();
}
}
WM_PV_TEXTO => {
if !a().text.0.is_null() && GetFocus() != a().text {
commit_text();
}
}
WM_LBUTTONDBLCLK => {
// duplo clique na página: alterna entre ajustar e tamanho real
if get_y_lparam(l) as f32 / sc() <= a().tb || a().markup {
return LRESULT(0);
}
if a().fit {
set_zoom(1.0, Some(POINT { x: get_x_lparam(l), y: get_y_lparam(l) }));
} else {
action(B_FIT);
}
}
WM_SETCURSOR => {
if loword(l.0 as usize) == HTCLIENT {
let mut p = POINT::default();
let _ = GetCursorPos(&mut p);
let _ = ScreenToClient(h, &mut p);
let c = if p.y as f32 / sc() > a().tb && !a().pages.is_empty() {
if a().markup {
if a().tool == T_TEXT {
IDC_IBEAM
} else {
IDC_CROSS
}
} else {
IDC_HAND
}
} else {
IDC_ARROW
};
SetCursor(LoadCursorW(None, c).unwrap_or_default());
return LRESULT(1);
}
return DefWindowProcW(h, m, w_, l);
}
WM_KEYDOWN => {
let k = w_.0 as u16;
let (_, vh) = view_size();
if app2d::key_down(VK_CONTROL.0) {
match k {
0x4F => open_dialog(),
0x53 => export(),
0x5A => {
if a().markup && a().anns.pop().is_some() {
a().dirty = true;
invalidate();
}
}
0x41 if app2d::key_down(VK_SHIFT.0) => set_markup(!a().markup),
0x57 => {
let _ = PostMessageW(h, WM_CLOSE, WPARAM(0), LPARAM(0));
}
0x50 => action(B_PRINT),
0x52 => {
if !a().pdf {
a().rot = (a().rot + 1) % 4;
clamp_scroll();
invalidate();
}
}
0x4C => action(B_ROT),
_ if k == VK_OEM_PLUS.0 || k == VK_ADD.0 => action(B_IN),
_ if k == VK_OEM_MINUS.0 || k == VK_SUBTRACT.0 => action(B_OUT),
_ if k == 0x30 || k == VK_NUMPAD0.0 => set_zoom(1.0, None),
0x39 => action(B_FIT),
_ => {}
}
return LRESULT(0);
}
let pdf = a().pdf;
match VIRTUAL_KEY(k) {
VK_LEFT => {
if pdf {
scroll(-60.0, 0.0)
} else {
neighbor(-1)
}
}
VK_RIGHT => {
if pdf {
scroll(60.0, 0.0)
} else {
neighbor(1)
}
}
VK_UP => scroll(0.0, -60.0),
VK_DOWN => scroll(0.0, 60.0),
VK_SPACE => scroll(0.0, if app2d::key_down(VK_SHIFT.0) { -vh * 0.9 } else { vh * 0.9 }),
VK_PRIOR => {
if pdf {
go_page(current_page() as i32 - 1)
} else {
scroll(0.0, -vh * 0.9)
}
}
VK_NEXT => {
if pdf {
go_page(current_page() as i32 + 1)
} else {
scroll(0.0, vh * 0.9)
}
}
VK_HOME => go_page(0),
VK_END => go_page(a().pages.len() as i32 - 1),
VK_ESCAPE => {
if !a().fit {
action(B_FIT)
}
}
_ => {}
}
}
WM_DROPFILES => {
let hd = HDROP(w_.0 as *mut c_void);
let mut b = [0u16; 520];
let n = DragQueryFileW(hd, 0, Some(&mut b));
if n > 0 {
open(&from_w(&b[..n as usize]));
}
DragFinish(hd);
}
WM_CLOSE => {
if a().dirty && !a().anns.is_empty() {
let r = message_box(&tr("Exportar a marcação antes de fechar?"), &tr("Pré-Visualização"), MB_YESNOCANCEL | MB_ICONWARNING);
if r == IDCANCEL {
return LRESULT(0);
}
if r == IDYES {
export();
if a().dirty {
return LRESULT(0);
}
}
}
let _ = DestroyWindow(h);
}
WM_DESTROY => {
let (mx, cv) = fila();
mx.lock().unwrap().quit = true;
cv.notify_all();
PostQuitMessage(0);
}
_ => return DefWindowProcW(h, m, w_, l),
}
LRESULT(0)
}
}
fn fmt(fam: &str, size: f32, wt: DWRITE_FONT_WEIGHT, al: DWRITE_TEXT_ALIGNMENT, pa: DWRITE_PARAGRAPH_ALIGNMENT) -> IDWriteTextFormat {
let f = cjk::format(dw(), fam, wt, DWRITE_FONT_STYLE_NORMAL, size, "").or_else(|| cjk::format(dw(), "Segoe UI", wt, DWRITE_FONT_STYLE_NORMAL, size, "")).expect("fonte");
unsafe {
let _ = f.SetTextAlignment(al);
let _ = f.SetParagraphAlignment(pa);
let _ = f.SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP);
}
f
}
fn main() {
if !app2d::init() {
std::process::exit(1);
}
let foto = arg_valor("--foto");
let fam = ["SF Pro Text", "Inter"].into_iter().find(|f| app2d::has_font(f)).unwrap_or("Segoe UI");
let (lead, cen) = (DWRITE_TEXT_ALIGNMENT_LEADING, DWRITE_TEXT_ALIGNMENT_CENTER);
let pc_ = DWRITE_PARAGRAPH_ALIGNMENT_CENTER;
let tf_title = fmt(fam, 13.0, DWRITE_FONT_WEIGHT_SEMI_BOLD, lead, pc_);
let tf_empty = fmt(fam, 14.0, DWRITE_FONT_WEIGHT_NORMAL, cen, pc_);
unsafe {
let _ = tf_empty.SetWordWrapping(DWRITE_WORD_WRAPPING_WRAP);
if let Ok(e) = dw().CreateEllipsisTrimmingSign(&tf_title) {
let t = DWRITE_TRIMMING { granularity: DWRITE_TRIMMING_GRANULARITY_CHARACTER, delimiter: 0, delimiterCount: 0 };
let _ = tf_title.SetTrimming(&t, &e);
}
}
let Ok(wic) = (unsafe { CoCreateInstance::<_, IWICImagingFactory>(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER) }) else { std::process::exit(1) };
let round = unsafe {
let sp = D2D1_STROKE_STYLE_PROPERTIES { startCap: D2D1_CAP_STYLE_ROUND, endCap: D2D1_CAP_STYLE_ROUND, dashCap: D2D1_CAP_STYLE_ROUND, lineJoin: D2D1_LINE_JOIN_ROUND, miterLimit: 10.0, ..Default::default() };
d2d().CreateStrokeStyle(&sp, None).ok()
};
*A.get() = Some(App {
hwnd: HWND::default(),
rt: None,
hrt: None,
br: None,
wic,
foto: foto.clone(),
foto_bmp: None,
foto_ticks: 0,
tf_sub: fmt(fam, 11.0, DWRITE_FONT_WEIGHT_NORMAL, lead, pc_),
tf_thumb: fmt(fam, 11.0, DWRITE_FONT_WEIGHT_NORMAL, cen, pc_),
tf_icon: fmt(if app2d::has_font("Segoe Fluent Icons") { "Segoe Fluent Icons" } else { "Segoe MDL2 Assets" }, 15.0, DWRITE_FONT_WEIGHT_NORMAL, cen, pc_),
tf_title,
tf_empty,
round,
unified: false,
tb: TOOLH,
pages: Vec::new(),
path: String::new(),
error: String::new(),
pdf: false,
gen: 0,
fit: true,
zoom: 1.0,
rot: 0,
sx: 0.0,
sy: 0.0,
drag: false,
drag_at: POINT::default(),
drag_sx: 0.0,
drag_sy: 0.0,
hover_btn: -1,
btns: Vec::new(),
side: true,
thumb_total: 0.0,
thumb_scroll: 0.0,
thumb_hits: Vec::new(),
anns: Vec::new(),
markup: false,
drawing: false,
dirty: false,
tool: T_PEN,
color: 1,
cur: Ann::default(),
img_px: Vec::new(),
img_w: 0,
img_h: 0,
sign: Vec::new(),
sign_capture: false,
sign_from: 0,
text: HWND::default(),
text_old: 0,
text_at: pt(0.0, 0.0),
text_page: -1,
text_font: HFONT::default(),
mbtns: Vec::new(),
list: Vec::new(),
});
unsafe {
let hi: HINSTANCE = GetModuleHandleW(None).unwrap_or_default().into();
let wc = WNDCLASSEXW {
cbSize: std::mem::size_of::<WNDCLASSEXW>() as u32,
style: CS_DBLCLKS,
lpfnWndProc: Some(wnd_proc),
hInstance: hi,
hCursor: LoadCursorW(None, IDC_ARROW).unwrap_or_default(),
hIcon: LoadIconW(hi, PCWSTR(1 as *const u16)).unwrap_or_default(),
lpszClassName: w!("PreVisualizacaoJanela"),
..Default::default()
};
RegisterClassExW(&wc);
// tamanho: 70% x 80% da área de trabalho, no meio (no --foto, 1000 x 700)
let mut mi = MONITORINFO { cbSize: std::mem::size_of::<MONITORINFO>() as u32, ..Default::default() };
let mut c = POINT::default();
let _ = GetCursorPos(&mut c);
let _ = GetMonitorInfoW(MonitorFromPoint(c, MONITOR_DEFAULTTOPRIMARY), &mut mi);
let wk = mi.rcWork;
let (ww, hh) = if foto.is_some() { (1000, 700) } else { (1400.min((wk.right - wk.left) * 7 / 10), (wk.bottom - wk.top) * 8 / 10) };
let mac = if foto.is_some() { false } else { barramac::ligar() };
let titulo = wz(&tr("Pré-Visualização"));
let estilo = if foto.is_some() { WS_POPUP } else { WS_OVERLAPPEDWINDOW };
let Ok(h) = CreateWindowExW(WS_EX_ACCEPTFILES, w!("PreVisualizacaoJanela"), pc(&titulo), estilo, wk.left + (wk.right - wk.left - ww) / 2, wk.top + (wk.bottom - wk.top - hh) / 2, ww, hh, None, None, hi, None) else {
std::process::exit(1)
};
a().hwnd = h;
app2d::s().wnd = h;
JANELA.store(h.0 as isize, Ordering::SeqCst);
let dk = BOOL::from(dark());
let _ = DwmSetWindowAttribute(h, DWMWINDOWATTRIBUTE(20), &dk as *const _ as *const c_void, 4);
if (mac || foto.is_some()) && semaforo::aqua() {
// macOS 27: barra unificada (a DLL só desenha os três botões)
a().unified = true;
if foto.is_none() {
let _ = SetPropW(h, w!("WacOSBarraUnificada"), HANDLE(52 as *mut c_void));
let _ = SetWindowPos(h, None, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
}
}
std::thread::spawn(pdf_thread);
if let Some(lista) = arg_valor("--lista") {
load_list(&lista);
let _ = std::fs::remove_file(&lista);
}
create_res();
if foto.is_none() {
let _ = ShowWindow(h, SW_SHOWNORMAL);
let _ = UpdateWindow(h);
}
// o arquivo: o primeiro argumento que não é opção nem valor de opção
let args: Vec<String> = std::env::args().skip(1).collect();
let mut arq = None;
let mut i = 0;
while i < args.len() {
if matches!(args[i].as_str(), "--foto" | "--lista") {
i += 2;
continue;
}
if !args[i].starts_with("--") {
arq = Some(args[i].clone());
break;
}
i += 1;
}
match arq {
Some(p) => open(&p),
None if foto.is_none() => {
let _ = PostMessageW(h, WM_PV_ASK, WPARAM(0), LPARAM(0));
}
None => {}
}
if foto.is_some() {
if tem_arg("--marcar") {
set_markup(true);
// um exemplo de cada traço, para a foto
if !a().pages.is_empty() {
let (pw, ph) = (a().pages[0].w, a().pages[0].h);
let r = |x: f32, y: f32| pt(pw * x, ph * y);
let ex = [(T_RECT, 1, vec![r(0.1, 0.1), r(0.45, 0.4)]), (T_OVAL, 5, vec![r(0.55, 0.15), r(0.9, 0.45)]), (T_ARROW, 4, vec![r(0.2, 0.8), r(0.6, 0.55)]), (T_PEN, 2, (0..40).map(|k| r(0.1 + k as f32 * 0.02, 0.7 + (k as f32 * 0.4).sin() * 0.05)).collect())];
for (t, c, pts) in ex {
a().anns.push(Ann { page: 0, tool: t, col: COLORS[c], pts, text: String::new() });
}
a().anns.push(Ann { page: 0, tool: T_TEXT, col: COLORS[0], pts: vec![r(0.55, 0.75)], text: "Rust".into() });
}
}
SetTimer(h, 7, 300, None);
}
let mut msg = MSG::default();
while GetMessageW(&mut msg, None, 0, 0).as_bool() {
let _ = TranslateMessage(&msg);
DispatchMessageW(&msg);
}
}
}