Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[feat] add compile error tip #7

Merged
merged 4 commits into from
Apr 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/build-pkg.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ name: "build pkg"

on:
push:
tags:
- "v*"
-branches:
- release

jobs:
publish-tauri:
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
![typster](./public/imgs/app-icon.png)
![typster](./app-icon.png)

# [WIP] typster

Expand Down
Binary file modified app-icon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified src-tauri/icons/128x128.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified src-tauri/icons/[email protected]
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified src-tauri/icons/32x32.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified src-tauri/icons/Square107x107Logo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified src-tauri/icons/Square142x142Logo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified src-tauri/icons/Square150x150Logo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified src-tauri/icons/Square284x284Logo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified src-tauri/icons/Square30x30Logo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified src-tauri/icons/Square310x310Logo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified src-tauri/icons/Square44x44Logo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified src-tauri/icons/Square71x71Logo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified src-tauri/icons/Square89x89Logo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified src-tauri/icons/StoreLogo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified src-tauri/icons/icon.icns
Binary file not shown.
Binary file modified src-tauri/icons/icon.ico
Binary file not shown.
Binary file modified src-tauri/icons/icon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
177 changes: 44 additions & 133 deletions src-tauri/src/ipc/commands/typst.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use super::{Error, Result};
use crate::ipc::commands::project;
use crate::ipc::model::TypstRenderResponse;
use crate::ipc::{
TypstCompileEvent, TypstDiagnosticSeverity, TypstDocument, TypstPage, TypstSourceDiagnostic
TypstCompileEvent, TypstDiagnosticSeverity, TypstDocument, TypstPage, TypstSourceDiagnostic,
};
use crate::project::ProjectManager;
use base64::Engine;
Expand All @@ -11,6 +11,7 @@ use serde::Serialize;
use serde_repr::Serialize_repr;
use siphasher::sip128::{Hasher128, SipHasher};
use std::hash::Hash;
use std::ops::Range;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Instant;
Expand Down Expand Up @@ -72,7 +73,7 @@ pub async fn typst_slot_update<R: Runtime>(
content: String,
) -> Result<()> {
let project = project(&window, &project_manager)?;

let mut world = project.world.lock().unwrap();
let _ = world
.slot_update(&path, Some(content))
Expand All @@ -86,7 +87,7 @@ pub async fn typst_compile_doc<R: Runtime>(
project_manager: tauri::State<'_, Arc<ProjectManager<R>>>,
path: PathBuf,
content: String,
) -> Result<Vec<TypstPage>> {
) -> Result<(Vec<TypstPage>, Vec<TypstSourceDiagnostic>)> {
let project = project(&window, &project_manager)?;

let mut world = project.world.lock().unwrap();
Expand All @@ -105,7 +106,8 @@ pub async fn typst_compile_doc<R: Runtime>(
debug!("compiling {:?}: {:?}", path, project);
let now = Instant::now();
let mut tracer = Tracer::new();
let mut res: Vec<TypstPage> = Vec::new();
let mut pages: Vec<TypstPage> = Vec::new();
let mut diags: Vec<TypstSourceDiagnostic> = Vec::new();
match typst::compile(&*world, &mut tracer) {
Ok(doc) => {
let elapsed = now.elapsed();
Expand All @@ -114,31 +116,27 @@ pub async fn typst_compile_doc<R: Runtime>(
project,
elapsed.as_millis()
);
let mut idx:u32 = 0;
let mut idx: u32 = 0;
for page in &doc.pages {
let mut hasher = SipHasher::new();
page.frame.hash(&mut hasher);
let hash = hex::encode(hasher.finish128().as_bytes());
let width = page.frame.width().to_pt();
let width = page.frame.width().to_pt();
let height = page.frame.height().to_pt();
idx +=1;
let pag = TypstPage {
idx += 1;
let pag = TypstPage {
num: idx,
width,
height,
hash: hash.clone()
hash: hash.clone(),
};
res.push(pag);
pages.push(pag);
}

project.cache.write().unwrap().document = Some(doc);

}
Err(diagnostics) => {
debug!(
"compilation failed with {:?} diagnostics",
&diagnostics
);
debug!("compilation failed with {:?} diagnostics", &diagnostics);

let source = world.source(source_id);
let diagnostics: Vec<TypstSourceDiagnostic> = match source {
Expand All @@ -148,13 +146,11 @@ pub async fn typst_compile_doc<R: Runtime>(
.filter_map(|d| {
let span = source.find(d.span)?;
let range = span.range();
let start = content[..range.start].chars().count();
let size = content[range.start..range.end].chars().count();

let message = d.message.to_string();
info!("############## {}", &message);
Some(TypstSourceDiagnostic {
range: start..start + size,
pos: get_range_position(&content, range.clone()),
range,
severity: match d.severity {
Severity::Error => TypstDiagnosticSeverity::Error,
Severity::Warning => TypstDiagnosticSeverity::Warning,
Expand All @@ -167,123 +163,32 @@ pub async fn typst_compile_doc<R: Runtime>(
Err(_) => vec![],
};

info!("############## {:?}", &diagnostics);

diags = diagnostics.clone();



info!("############## {:?}", &diags);
}
}

Ok(res)
Ok((pages, diags))
}

#[tauri::command]
pub async fn typst_compile<R: Runtime>(
window: tauri::Window<R>,
project_manager: tauri::State<'_, Arc<ProjectManager<R>>>,
path: PathBuf,
content: String,
) -> Result<()> {
let project = project(&window, &project_manager)?;

let mut world = project.world.lock().unwrap();
let source_id = world
.slot_update(&path, Some(content.clone()))
.map_err(Into::<Error>::into)?;

if !world.is_main_set() {
let config = project.config.read().unwrap();
if config.apply_main(&project, &mut world).is_err() {
debug!("skipped compilation for {:?} (main not set)", project);
return Ok(());
}
}

debug!("compiling {:?}: {:?}", path, project);
let now = Instant::now();
let mut tracer = Tracer::new();
match typst::compile(&*world, &mut tracer) {
Ok(doc) => {
let elapsed = now.elapsed();
debug!(
"compilation succeeded for {:?} in {:?} ms",
project,
elapsed.as_millis()
);

let pages = doc.pages.len();

let mut hasher = SipHasher::new();
for page in &doc.pages {
page.frame.hash(&mut hasher);
}
let hash = hex::encode(hasher.finish128().as_bytes());

// Assume all pages have the same size
// TODO: Improve this?
let first_page = &doc.pages[0];
let width = first_page.frame.width();
let height = first_page.frame.height();

project.cache.write().unwrap().document = Some(doc);

let _ = window.emit(
"typst_compile",
TypstCompileEvent {
document: Some(TypstDocument {
pages,
hash,
width: width.to_pt(),
height: height.to_pt(),
}),
diagnostics: None,
},
);
pub fn get_range_position(text: &str, rang: Range<usize>) -> (usize, usize) {
let mut ln = 0;
let mut cn = 0;
let mut total: usize = 0;
for line in text.lines() {

ln += 1;
let row = line.chars().count() + 1;

if total <= rang.start && rang.start <= total + row {
cn = rang.start - total;
break;
}
Err(diagnostics) => {
debug!(
"compilation failed with {:?} diagnostics",
diagnostics.len()
);

let source = world.source(source_id);
let diagnostics: Vec<TypstSourceDiagnostic> = match source {
Ok(source) => diagnostics
.iter()
.filter(|d| d.span.id() == Some(source_id))
.filter_map(|d| {
let span = source.find(d.span)?;
let range = span.range();
let start = content[..range.start].chars().count();
let size = content[range.start..range.end].chars().count();

let message = d.message.to_string();
Some(TypstSourceDiagnostic {
range: start..start + size,
severity: match d.severity {
Severity::Error => TypstDiagnosticSeverity::Error,
Severity::Warning => TypstDiagnosticSeverity::Warning,
},
message,
hints: d.hints.iter().map(|hint| hint.to_string()).collect(),
})
})
.collect(),
Err(_) => vec![],
};

let _ = window.emit(
"typst_compile",
TypstCompileEvent {
document: None,
diagnostics: Some(diagnostics),
},
);
}
total += row;
}

Ok(())
return (ln, cn);
}

#[tauri::command]
Expand All @@ -294,17 +199,23 @@ pub async fn typst_render<R: Runtime>(
scale: f32,
nonce: u32,
) -> Result<TypstRenderResponse> {

info!("typst_render page:{} scale: {} nonce: {}", page, scale, nonce);
info!(
"typst_render page:{} scale: {} nonce: {}",
page, scale, nonce
);
let project = project_manager
.get_project(&window)
.ok_or(Error::UnknownProject)?;

let cache = project.cache.read().unwrap();

if let Some(p) = cache.document.as_ref().and_then(|doc| doc.pages.get(page-1)) {

if let Some(p) = cache
.document
.as_ref()
.and_then(|doc| doc.pages.get(page - 1))
{
let now = Instant::now();

let bmp = typst_render::render(&p.frame, scale, Color::WHITE);
if let Ok(image) = bmp.encode_png() {
let elapsed = now.elapsed();
Expand Down
1 change: 1 addition & 0 deletions src-tauri/src/ipc/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ pub struct TypstSourceDiagnostic {
pub severity: TypstDiagnosticSeverity,
pub message: String,
pub hints: Vec<String>,
pub pos:(usize, usize)
}

#[derive(Serialize, Clone, Debug)]
Expand Down
1 change: 0 additions & 1 deletion src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ async fn main() {
ipc::commands::fs_write_file_binary,
ipc::commands::fs_write_file_text,
ipc::commands::load_project_from_path,
ipc::commands::typst_compile,
ipc::commands::typst_compile_doc,
ipc::commands::typst_render,
ipc::commands::typst_autocomplete,
Expand Down
7 changes: 5 additions & 2 deletions src-tauri/tauri.conf.json
Original file line number Diff line number Diff line change
Expand Up @@ -86,11 +86,14 @@
"fullscreen": false,
"resizable": true,
"title": "typster",
"center": true,
"hiddenTitle": true,
"titleBarStyle": "Overlay",
"titleBarStyle": "Transparent",
"theme": "Light",
"width": 1200,
"height": 900
"height": 900,
"minWidth": 800,
"minHeight": 400
}
]
}
Expand Down
19 changes: 19 additions & 0 deletions src-tauri/tauri.macos.conf.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"tauri": {
"windows": [
{
"fullscreen": false,
"resizable": true,
"title": "",
"center": true,
"hiddenTitle": false,
"titleBarStyle": "Overlay",
"theme": "Light",
"width": 1200,
"height": 900,
"minWidth": 800,
"minHeight": 400
}
]
}
}
6 changes: 3 additions & 3 deletions src/components/MonacoEditor.vue
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<script setup lang="ts">
import * as monaco from "monaco-editor/esm/vs/editor/editor.api";
import { PropType, onMounted, ref, watch } from "vue";
import { TypstPage } from "../pages/typst/interface";
import { TypstCompileResult, TypstPage } from "../pages/typst/interface";
import type { editor as editorType } from "monaco-editor";
import { invoke } from "@tauri-apps/api";
import { throttle, debounce, relativePath } from './../shared/util'
Expand All @@ -23,7 +23,7 @@ const props = defineProps({

const emit = defineEmits<{
(e: 'change', text: string): void
(e: 'compiled', data: TypstPage[]): void
(e: 'compiled', data: TypstCompileResult): void
}>()


Expand Down Expand Up @@ -74,7 +74,7 @@ const handleCompile = async () => {
const content = editorModel.getValue()
const path = relativePath(props.root!, props.path!)

const pages = await invoke<TypstPage[]>('typst_compile_doc', { path, content })
const pages = await invoke<TypstCompileResult>('typst_compile_doc', { path, content })

emit('compiled', pages)
}
Expand Down
2 changes: 1 addition & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { createApp } from "vue";
import "./style/styles.css";
import "github-markdown-css";
import "ant-design-vue/dist/reset.css";
import "./style/styles.css";
import "./shared/monaco-hook";

import Antd from "ant-design-vue";
Expand Down
Loading
Loading