Skip to content

Commit

Permalink
new day new cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
0-don committed Dec 20, 2024
1 parent 1e2db9d commit afb40f0
Show file tree
Hide file tree
Showing 33 changed files with 466 additions and 212 deletions.
44 changes: 44 additions & 0 deletions src-tauri/common/src/clipboard.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
use crate::{constants::MAX_TEXT_PREVIEW, types::orm_query::ClipboardWithRelations};

pub fn trim_clipboard_data(
mut clipboards: Vec<ClipboardWithRelations>,
) -> Vec<ClipboardWithRelations> {
for clipboard in &mut clipboards {
// Trim text content
if let Some(text) = &mut clipboard.text {
text.data = truncate_text(&text.data, MAX_TEXT_PREVIEW);
}

// Trim HTML content
if let Some(html) = &mut clipboard.html {
html.data = truncate_text(&html.data, MAX_TEXT_PREVIEW);
}

// Trim RTF content
if let Some(rtf) = &mut clipboard.rtf {
rtf.data = truncate_text(&rtf.data, MAX_TEXT_PREVIEW);
}

// Remove image binary data but keep metadata
if let Some(image) = &mut clipboard.image {
image.data = Vec::new(); // Clear binary data
// Thumbnail, dimensions, size etc are preserved
}

// Clear file binary data but keep metadata
for file in &mut clipboard.files {
file.data = Vec::new(); // Clear binary data
// Name, extension, size etc are preserved
}
}

clipboards
}

fn truncate_text(text: &str, max_length: usize) -> String {
if text.len() <= max_length {
text.to_string()
} else {
format!("{}...", &text[..max_length])
}
}
1 change: 1 addition & 0 deletions src-tauri/common/src/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ pub static SETTINGS_WINDOW_X: i32 = 500;
pub static SETTINGS_WINDOW_Y: i32 = 450;

pub static MAX_IMAGE_DIMENSIONS: u32 = 1280;
pub static MAX_TEXT_PREVIEW: usize = 500; // Adjust preview length as needed

pub static DISPLAY_SCALE: f32 = 1.0;
pub static DISPLAY_SCALE_MIN: f32 = 0.5;
Expand Down
1 change: 1 addition & 0 deletions src-tauri/common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ pub mod keyboard;
pub mod language;
pub mod macros;
pub mod types;
pub mod clipboard;
pub mod constants;
15 changes: 13 additions & 2 deletions src-tauri/common/src/types/enums.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,15 @@ use sea_orm::{sea_query, EnumIter};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value as JsonValue};

#[derive(Iden, EnumIter, PartialEq, Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "lowercase")]
pub enum FolderLocation {
#[iden = "database"]
Database,
#[iden = "config"]
Config,
}

#[derive(Iden, EnumIter, PartialEq, Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "lowercase")]
pub enum Language {
Expand All @@ -21,12 +30,14 @@ pub enum Language {
pub enum ListenEvent {
#[iden = "init"]
Init,
#[iden = "set_global_hotkey_event"]
SetGlobalHotkeyEvent,
#[iden = "enable_global_hotkey_event"]
EnableGlobalHotkeyEvent,
#[iden = "change_tab"]
ChangeTab,
#[iden = "scroll_to_top"]
ScrollToTop,
#[iden = "new_clipboard"]
NewClipboard,
}

#[derive(Iden, EnumIter, PartialEq, Serialize, Deserialize, Debug, Clone)]
Expand Down
7 changes: 7 additions & 0 deletions src-tauri/common/src/types/orm_query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,13 @@ pub struct ClipboardWithRelations {
pub files: Vec<clipboard_file::Model>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClipboardsResponse {
pub clipboards: Vec<ClipboardWithRelations>,
pub total: u64,
pub has_more: bool,
}

#[derive(Debug, Clone)]
pub struct ClipboardManager {
pub clipboard_model: entity::clipboard::ActiveModel,
Expand Down
32 changes: 27 additions & 5 deletions src-tauri/src/commands/clipboard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,17 @@ extern crate alloc;
extern crate image;
use crate::{
service::clipboard::{
clear_clipboards_db, copy_clipboard_from_id, delete_clipboard_db, get_clipboard_db,
get_clipboards_db, star_clipboard_db,
clear_clipboards_db, copy_clipboard_from_id, delete_clipboard_db, get_clipboard_count_db,
get_clipboard_db, get_clipboards_db, star_clipboard_db,
},
tauri_config::config::APP,
utils::hotkey_manager::unregister_hotkeys,
};
use common::types::{enums::ClipboardType, orm_query::ClipboardWithRelations, types::CommandError};
use common::{
clipboard::trim_clipboard_data,
printlog,
types::{enums::ClipboardType, orm_query::ClipboardsResponse, types::CommandError},
};
use std::fs::File;
use tauri::Manager;

Expand All @@ -18,8 +22,26 @@ pub async fn get_clipboards(
search: Option<String>,
star: Option<bool>,
img: Option<bool>,
) -> Result<Vec<ClipboardWithRelations>, CommandError> {
Ok(get_clipboards_db(cursor, search, star, img).await?)
) -> Result<ClipboardsResponse, CommandError> {
let clipboards = get_clipboards_db(cursor, search, star, img).await?;
let total = get_clipboard_count_db().await?;

// Calculate if there are more items
let current_position = cursor.unwrap_or(0) + clipboards.len() as u64;
let has_more = current_position < total;

printlog!(
"Total: {}, Current Position: {}, Has More: {}",
total,
current_position,
has_more
);

Ok(ClipboardsResponse {
clipboards: trim_clipboard_data(clipboards),
total,
has_more,
})
}

#[tauri::command]
Expand Down
52 changes: 50 additions & 2 deletions src-tauri/src/commands/window.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@ use crate::service::{
clipboard::count_clipboards_db, settings::get_data_path, window::open_window,
};
use common::types::{
enums::WebWindow,
enums::{FolderLocation, WebWindow},
types::{CommandError, Config, DatabaseInfo},
};
use std::fs::{self, read_to_string};
use std::{
fs::{self, read_to_string},
path::PathBuf,
};
use tauri::AppHandle;
use tauri_plugin_opener::OpenerExt;

Expand Down Expand Up @@ -47,3 +50,48 @@ pub async fn get_db_path() -> Result<String, CommandError> {
let config: Config = serde_json::from_str(&read_to_string(&data_path.config_file_path)?)?;
Ok(config.db)
}

#[tauri::command]
pub async fn open_folder(location: FolderLocation) -> Result<(), CommandError> {
let data_path = get_data_path();

let path = match location {
FolderLocation::Database => {
// Get the database path from config
let config: Config =
serde_json::from_str(&read_to_string(&data_path.config_file_path)?)?;
PathBuf::from(&config.db)
.parent()
.map(|p| p.to_path_buf())
.ok_or_else(|| {
CommandError::Error("Could not get database directory".to_string())
})?
}
FolderLocation::Config => PathBuf::from(&data_path.config_path),
};

if !path.exists() {
return Err(CommandError::Error("Path does not exist".to_string()));
}

if !path.is_dir() {
return Err(CommandError::Error("Path is not a directory".to_string()));
}

#[cfg(target_os = "windows")]
{
std::process::Command::new("explorer").arg(path).spawn()?;
}

#[cfg(target_os = "macos")]
{
std::process::Command::new("open").arg(path).spawn()?;
}

#[cfg(target_os = "linux")]
{
std::process::Command::new("xdg-open").arg(path).spawn()?;
}

Ok(())
}
4 changes: 3 additions & 1 deletion src-tauri/src/events/hotkey_events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ pub fn init_hotkey_listener() {
loop {
if let Ok(event) = receiver.try_recv() {
if event.state == HotKeyState::Pressed {
printlog!("hotkey caught {:?}", event);
let hotkey = get_hotkey_store().get(&event.id).cloned();
if let Some(hotkey) = hotkey {
parse_hotkey_event(&hotkey).await;
Expand Down Expand Up @@ -75,6 +74,9 @@ pub async fn parse_hotkey_event(key: &Key) {
get_main_window()
.emit(ListenEvent::ScrollToTop.to_string().as_str(), ())
.expect("Failed to emit event");
get_main_window()
.emit(ListenEvent::Init.to_string().as_str(), ())
.expect("Failed to emit event");
}
Some(HotkeyEvent::TypeClipboard) => {
if cfg!(target_os = "linux") {
Expand Down
2 changes: 1 addition & 1 deletion src-tauri/src/events/window_events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ pub fn init_window_event_listener() {
unregister_hotkeys(false);
get_main_window()
.emit(
ListenEvent::SetGlobalHotkeyEvent.to_string().as_str(),
ListenEvent::EnableGlobalHotkeyEvent.to_string().as_str(),
false,
)
.expect("failed to emit event");
Expand Down
1 change: 1 addition & 0 deletions src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ pub fn run() {
window::get_app_version,
window::get_db_info,
window::get_db_path,
window::open_folder,
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
Expand Down
14 changes: 11 additions & 3 deletions src-tauri/src/service/clipboard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,14 @@ pub async fn load_clipboards_with_relations(
.collect()
}

pub async fn get_clipboard_count_db() -> Result<u64, DbErr> {
let db = connection::db().await?;

let count = clipboard::Entity::find().count(&db).await?;

Ok(count)
}

pub async fn insert_clipboard_db(model: ClipboardManager) -> Result<ClipboardWithRelations, DbErr> {
let db = connection::db().await?;
let clipboard = model.clipboard_model.insert(&db).await?;
Expand Down Expand Up @@ -181,7 +189,7 @@ pub async fn get_clipboards_db(
q.filter(f)
})
.offset(cursor)
.limit(10)
.limit(25)
.order_by_desc(clipboard::Column::Id);

Ok(load_clipboards_with_relations(query.all(&db).await?).await)
Expand Down Expand Up @@ -249,7 +257,7 @@ pub async fn copy_clipboard_from_index(i: u64) -> Result<Option<Model>, DbErr> {
}

pub async fn copy_clipboard_from_id(id: i32, requested_type: ClipboardType) -> Result<bool, DbErr> {
printlog!("type {:?}", requested_type);
printlog!("copy clipboard type: {:?} id:{:?}", requested_type, id);
let clipboard_data = get_clipboard_db(id).await?;
let clipboard = get_app().state::<Clipboard>();

Expand Down Expand Up @@ -290,7 +298,7 @@ pub async fn copy_clipboard_from_id(id: i32, requested_type: ClipboardType) -> R
}
.is_some();

if success {
if success && !cfg!(debug_assertions) {
get_main_window().hide().ok();
}

Expand Down
7 changes: 2 additions & 5 deletions src-tauri/src/service/window.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,7 @@ pub fn toggle_main_window() {
get_main_window().hide().expect("Failed to hide window");
unregister_hotkeys(false);
get_main_window()
.emit(
ListenEvent::SetGlobalHotkeyEvent.to_string().as_str(),
false,
)
.emit(ListenEvent::EnableGlobalHotkeyEvent.to_string().as_str(), false)
.expect("Failed to emit set global hotkey event");
} else {
position_window_near_cursor();
Expand All @@ -66,7 +63,7 @@ pub fn toggle_main_window() {

register_hotkeys(true);
get_main_window()
.emit(ListenEvent::SetGlobalHotkeyEvent.to_string().as_str(), true)
.emit(ListenEvent::EnableGlobalHotkeyEvent.to_string().as_str(), true)
.expect("Failed to emit set global hotkey event");

get_app()
Expand Down
4 changes: 2 additions & 2 deletions src-tauri/src/utils/clipboard_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,11 +60,11 @@ impl ClipboardManagerExt for ClipboardManager {
.await;

if !manager.check_if_last_is_same().await {
insert_clipboard_db(manager)
let clipboard = insert_clipboard_db(manager)
.await
.expect("Failed to insert");
get_app_window(WebWindow::Main)
.emit(ListenEvent::Init.to_string().as_str(), ())
.emit(ListenEvent::NewClipboard.to_string().as_str(), clipboard)
.expect("Failed to emit");
}
}
Expand Down
10 changes: 7 additions & 3 deletions src/components/elements/text-block.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,18 @@ interface TextBlockProps {
Icon: IconTypes;
title: string;
className?: string;
header?: JSX.Element;
}

export const TextBlock: Component<TextBlockProps> = (props) => {
return (
<div class={`mb-7 rounded-md border border-solid shadow-2xl dark:border-zinc-700 ${props.className}`}>
<div class="mb-2 flex items-center space-x-2 bg-zinc-200 px-5 pb-2.5 pt-3 dark:bg-zinc-800">
<props.Icon />
<h2 class="font-semibold">{props.title}</h2>
<div class="mb-2 flex items-center justify-between bg-zinc-200 px-5 pb-2.5 pt-3 dark:bg-zinc-800">
<div class="flex items-center gap-2">
<props.Icon />
<h2 class="font-semibold">{props.title}</h2>
</div>
<div>{props.header}</div>
</div>
{props.children}
</div>
Expand Down
12 changes: 5 additions & 7 deletions src/components/elements/toggle.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,13 @@ export const Toggle: Component<SwitchProps> = (props) => {
class="peer sr-only"
/>
<div
class={`peer relative h-4 w-11 rounded-full bg-gray-200 after:absolute after:start-[2px] after:h-4 after:w-4 after:rounded-full after:border after:border-transparent after:bg-white after:transition-all after:content-[''] peer-checked:bg-indigo-600 peer-checked:after:translate-x-[150%] peer-checked:after:border-transparent peer-focus:outline-none rtl:peer-checked:after:-translate-x-full dark:border-gray-600 ${
class={`peer relative h-4 w-11 rounded-full bg-gray-200 after:absolute after:start-[2px] after:top-0 after:h-4 after:w-4 after:rounded-full after:border after:border-transparent after:bg-white after:transition-all after:content-[''] peer-checked:bg-indigo-600 peer-checked:after:translate-x-[150%] peer-checked:after:border-transparent peer-focus:outline-none dark:border-gray-600 rtl:peer-checked:after:-translate-x-full ${
props.checked ? "dark:bg-gray-700" : "dark:bg-red-600"
} dark:bg-opacity-20 after:dark:bg-zinc-700`}
} after:z-[40] dark:bg-opacity-20 after:dark:bg-zinc-700`}
>
{props.checked ? (
<FiCheck class="absolute left-0 top-0 z-50 translate-x-[160%]" />
) : (
<VsClose class="absolute left-0 top-0 z-50" />
)}
<div class="absolute inset-0 z-[50] flex items-center justify-between px-1">
{props.checked ? <FiCheck class="ml-auto text-sm text-white" /> : <VsClose class="text-white" />}
</div>
</div>
</label>
);
Expand Down
Loading

0 comments on commit afb40f0

Please sign in to comment.