222 lines
6.0 KiB
Rust
Raw Normal View History

2021-11-27 19:19:41 +08:00
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::sync::Arc;
use std::{ffi::CStr, os::raw::c_char};
use lazy_static::lazy_static;
use parking_lot::Mutex;
use tracing::{debug, error, info, trace, warn};
use flowy_core::config::AppFlowyCoreConfig;
use flowy_core::*;
2023-07-09 10:03:22 +07:00
use flowy_notification::{register_notification_sender, unregister_all_notification_sender};
use flowy_server_pub::AuthenticatorType;
use lib_dispatch::prelude::ToBytes;
use lib_dispatch::prelude::*;
use lib_dispatch::runtime::AFPluginRuntime;
2021-06-28 23:58:43 +08:00
use crate::appflowy_yaml::save_appflowy_cloud_config;
use crate::env_serde::AppFlowyDartConfiguration;
use crate::notification::DartNotificationSender;
use crate::{
c::{extend_front_four_bytes_into_bytes, forget_rust},
model::{FFIRequest, FFIResponse},
};
mod appflowy_yaml;
mod c;
mod env_serde;
mod model;
mod notification;
mod protobuf;
mod util;
2021-07-25 08:13:59 +08:00
feat: Customize the storage folder path (#1538) * feat: support customize folder path * feat: add l10n and optimize the logic * chore: code refactor * feat: add file read/write permission for macOS * fix: add toast for restoring path * feat: fetch apps and show them * feat: fetch apps and show them * feat: implement select document logic * feat: l10n and add select item callback * feat: add space between tile * chore: move file exporter to settings * chore: update UI * feat: support customizing folder when launching the app * feat: auto register after customizing folder * feat: l10n * feat: l10n * chore: reinitialize flowy sdk when calling init_sdk * chore: remove flowysdk const keyword to make sure it can be rebuild * chore: clear kv values when user logout * chore: replace current workspace id key in kv.db * feat: add config.name as a part of seesion_cache_key * feat: support open folder when launching * chore: fix some bugs * chore: dart fix & flutter analyze * chore: wrap 'sign up with ramdom user' as interface * feat: dismiss settings view after changing the folder * fix: read kv value after initializaing with new path * chore: remove user_id prefix from current workspace key * fix: move open latest view action to bloc * test: add test utils for integration tests * chore: move integration_test to its parent directory * test: add integration_test ci * test: switch to B from A, then switch to A again * chore: fix warings and format code and fix tests * chore: remove comment out codes * chore: rename some properties name and optimize the logic * chore: abstract logic of settings file exporter widget to cubit * chore: abstract location customizer view from file system view * chore: abstract settings page index to enum type * chore: remove the redundant underscore * test: fix integration test error * chore: enable integration test for windows and ubuntu * feat: abstract file picker as service and mock it under integration test * chore: fix bloc test Co-authored-by: nathan <nathan@appflowy.io>
2022-12-20 11:14:42 +08:00
lazy_static! {
static ref APPFLOWY_CORE: MutexAppFlowyCore = MutexAppFlowyCore::new();
feat: Customize the storage folder path (#1538) * feat: support customize folder path * feat: add l10n and optimize the logic * chore: code refactor * feat: add file read/write permission for macOS * fix: add toast for restoring path * feat: fetch apps and show them * feat: fetch apps and show them * feat: implement select document logic * feat: l10n and add select item callback * feat: add space between tile * chore: move file exporter to settings * chore: update UI * feat: support customizing folder when launching the app * feat: auto register after customizing folder * feat: l10n * feat: l10n * chore: reinitialize flowy sdk when calling init_sdk * chore: remove flowysdk const keyword to make sure it can be rebuild * chore: clear kv values when user logout * chore: replace current workspace id key in kv.db * feat: add config.name as a part of seesion_cache_key * feat: support open folder when launching * chore: fix some bugs * chore: dart fix & flutter analyze * chore: wrap 'sign up with ramdom user' as interface * feat: dismiss settings view after changing the folder * fix: read kv value after initializaing with new path * chore: remove user_id prefix from current workspace key * fix: move open latest view action to bloc * test: add test utils for integration tests * chore: move integration_test to its parent directory * test: add integration_test ci * test: switch to B from A, then switch to A again * chore: fix warings and format code and fix tests * chore: remove comment out codes * chore: rename some properties name and optimize the logic * chore: abstract logic of settings file exporter widget to cubit * chore: abstract location customizer view from file system view * chore: abstract settings page index to enum type * chore: remove the redundant underscore * test: fix integration test error * chore: enable integration test for windows and ubuntu * feat: abstract file picker as service and mock it under integration test * chore: fix bloc test Co-authored-by: nathan <nathan@appflowy.io>
2022-12-20 11:14:42 +08:00
}
struct MutexAppFlowyCore(Arc<Mutex<Option<AppFlowyCore>>>);
impl MutexAppFlowyCore {
fn new() -> Self {
Self(Arc::new(Mutex::new(None)))
}
fn dispatcher(&self) -> Option<Arc<AFPluginDispatcher>> {
let binding = self.0.lock();
let core = binding.as_ref();
core.map(|core| core.event_dispatcher.clone())
}
}
unsafe impl Sync for MutexAppFlowyCore {}
unsafe impl Send for MutexAppFlowyCore {}
#[no_mangle]
pub extern "C" fn init_sdk(_port: i64, data: *mut c_char) -> i64 {
// and sent it the `Rust's` result
// no need to convert anything :)
let c_str = unsafe { CStr::from_ptr(data) };
let serde_str = c_str.to_str().unwrap();
let configuration = AppFlowyDartConfiguration::from_str(serde_str);
configuration.write_env();
if configuration.authenticator_type == AuthenticatorType::AppFlowyCloud {
let _ = save_appflowy_cloud_config(&configuration.root, &configuration.appflowy_cloud_config);
}
2021-09-05 13:50:23 +08:00
let config = AppFlowyCoreConfig::new(
configuration.app_version,
configuration.custom_app_path,
configuration.origin_app_path,
configuration.device_id,
DEFAULT_NAME.to_string(),
feat: folder search mvp (#4665) * feat: implement folder indexer * feat: sqlite search views using fts5 * feat: add view indexing to user manager * feat: implement folder indexer * feat: add sqlite search documents * feat: add document indexing to user manager * feat: add document indexing to folder indexer * chore: update collab rev * feat: search frontend integration * refactor: search index * test: add event test * chore: fix ci * feat: initial command palette overlay impl (#4619) * chore: test search engine * chore: initial structure * chore: replace old search request * chore: enable log for lib-dispatch * chore: move search manager to core * feat: move traits and responsibility to search crate * feat: move search to search crate * feat: replace sqlite with tantivy * feat: deserialize tantivy documents * chore: fixes after rebase * chore: clean code * feat: fetch and sort results * fix: code review + cleaning * feat: support custom icons * feat: support view layout icons * feat: rename bloc and fix indexing * fix: prettify dialog * feat: score results * chore: update collab rev * feat: add recent view history to command palette * test: add integration_tests * fix: clippy changes * fix: focus traversal in cmd palette * fix: remove file after merging main * chore: code review and panic-safe * feat: index all views if index does not exist * chore: improve logic with conditional * chore: add is_empty check * chore: abstract logic from folder manager init * chore: update collab rev * chore: code review * chore: fixes after merge + update lock file * chore: revert cargo lock * fix: set icon type when removing icon * fix: code review + dependency inversion * fix: remove icon fix for not persisting icon type * test: simple tests manipulating views * test: create 100 views * fix: tauri build * chore: create 1000 views * chore: create util methods * chore: test * chore: test * chore: remove logs * chore: fix build.rs * chore: export models * chore: enable clear cache on Rust-CI * fix: navigate to newly created views * fix: force disable setting workspace listener on rebuilds * fix: remove late final * fix: missing returns * fix: localization and minor fixes * test: add index assert to large test * fix: missing section param after merging main * chore: try fix unzip file error * chore: lower the test * feat: show hint when result is in trash --------- Co-authored-by: nathan <nathan@appflowy.io> Co-authored-by: Jiraffe7 <twajxjiraffe@gmail.com> Co-authored-by: Lucas.Xu <lucas.xu@appflowy.io>
2024-03-21 17:34:53 +01:00
);
// Ensure that the database is closed before initialization. Also, verify that the init_sdk function can be called
// multiple times (is reentrant). Currently, only the database resource is exclusive.
if let Some(core) = &*APPFLOWY_CORE.0.lock() {
core.close_db();
}
let runtime = Arc::new(AFPluginRuntime::new().unwrap());
let cloned_runtime = runtime.clone();
// let isolate = allo_isolate::Isolate::new(port);
*APPFLOWY_CORE.0.lock() = runtime.block_on(async move {
Some(AppFlowyCore::new(config, cloned_runtime).await)
// isolate.post("".to_string());
});
0
}
#[no_mangle]
#[allow(clippy::let_underscore_future)]
2021-12-04 10:27:08 +08:00
pub extern "C" fn async_event(port: i64, input: *const u8, len: usize) {
let request: AFPluginRequest = FFIRequest::from_u8_pointer(input, len).into();
trace!(
"[FFI]: {} Async Event: {:?} with {} port",
&request.id,
&request.event,
port
);
2021-09-04 15:12:53 +08:00
let dispatcher = match APPFLOWY_CORE.dispatcher() {
None => {
error!("sdk not init yet.");
return;
},
Some(dispatcher) => dispatcher,
};
AFPluginDispatcher::boxed_async_send_with_callback(
dispatcher.as_ref(),
request,
feat: folder search mvp (#4665) * feat: implement folder indexer * feat: sqlite search views using fts5 * feat: add view indexing to user manager * feat: implement folder indexer * feat: add sqlite search documents * feat: add document indexing to user manager * feat: add document indexing to folder indexer * chore: update collab rev * feat: search frontend integration * refactor: search index * test: add event test * chore: fix ci * feat: initial command palette overlay impl (#4619) * chore: test search engine * chore: initial structure * chore: replace old search request * chore: enable log for lib-dispatch * chore: move search manager to core * feat: move traits and responsibility to search crate * feat: move search to search crate * feat: replace sqlite with tantivy * feat: deserialize tantivy documents * chore: fixes after rebase * chore: clean code * feat: fetch and sort results * fix: code review + cleaning * feat: support custom icons * feat: support view layout icons * feat: rename bloc and fix indexing * fix: prettify dialog * feat: score results * chore: update collab rev * feat: add recent view history to command palette * test: add integration_tests * fix: clippy changes * fix: focus traversal in cmd palette * fix: remove file after merging main * chore: code review and panic-safe * feat: index all views if index does not exist * chore: improve logic with conditional * chore: add is_empty check * chore: abstract logic from folder manager init * chore: update collab rev * chore: code review * chore: fixes after merge + update lock file * chore: revert cargo lock * fix: set icon type when removing icon * fix: code review + dependency inversion * fix: remove icon fix for not persisting icon type * test: simple tests manipulating views * test: create 100 views * fix: tauri build * chore: create 1000 views * chore: create util methods * chore: test * chore: test * chore: remove logs * chore: fix build.rs * chore: export models * chore: enable clear cache on Rust-CI * fix: navigate to newly created views * fix: force disable setting workspace listener on rebuilds * fix: remove late final * fix: missing returns * fix: localization and minor fixes * test: add index assert to large test * fix: missing section param after merging main * chore: try fix unzip file error * chore: lower the test * feat: show hint when result is in trash --------- Co-authored-by: nathan <nathan@appflowy.io> Co-authored-by: Jiraffe7 <twajxjiraffe@gmail.com> Co-authored-by: Lucas.Xu <lucas.xu@appflowy.io>
2024-03-21 17:34:53 +01:00
move |resp: AFPluginEventResponse| Box::pin(post_to_flutter(resp, port)),
);
}
#[no_mangle]
2021-12-04 10:27:08 +08:00
pub extern "C" fn sync_event(input: *const u8, len: usize) -> *const u8 {
let request: AFPluginRequest = FFIRequest::from_u8_pointer(input, len).into();
trace!("[FFI]: {} Sync Event: {:?}", &request.id, &request.event,);
2022-01-30 15:17:30 +08:00
let dispatcher = match APPFLOWY_CORE.dispatcher() {
None => {
error!("sdk not init yet.");
return forget_rust(Vec::default());
},
Some(dispatcher) => dispatcher,
};
let _response = AFPluginDispatcher::sync_send(dispatcher, request);
2021-07-03 22:24:02 +08:00
// FFIResponse { }
let response_bytes = vec![];
let result = extend_front_four_bytes_into_bytes(&response_bytes);
forget_rust(result)
2021-07-03 22:24:02 +08:00
}
2021-07-21 15:43:05 +08:00
#[no_mangle]
pub extern "C" fn set_stream_port(port: i64) -> i32 {
2023-07-09 10:03:22 +07:00
// Make sure hot reload won't register the notification sender twice
unregister_all_notification_sender();
register_notification_sender(DartNotificationSender::new(port));
0
2021-07-21 15:43:05 +08:00
}
2021-06-28 23:58:43 +08:00
#[inline(never)]
#[no_mangle]
pub extern "C" fn link_me_please() {}
2021-07-02 20:47:52 +08:00
#[inline(always)]
2022-12-01 10:59:22 +08:00
async fn post_to_flutter(response: AFPluginEventResponse, port: i64) {
let isolate = allo_isolate::Isolate::new(port);
match isolate
.catch_unwind(async {
let ffi_resp = FFIResponse::from(response);
ffi_resp.into_bytes().unwrap().to_vec()
})
.await
{
feat: folder search mvp (#4665) * feat: implement folder indexer * feat: sqlite search views using fts5 * feat: add view indexing to user manager * feat: implement folder indexer * feat: add sqlite search documents * feat: add document indexing to user manager * feat: add document indexing to folder indexer * chore: update collab rev * feat: search frontend integration * refactor: search index * test: add event test * chore: fix ci * feat: initial command palette overlay impl (#4619) * chore: test search engine * chore: initial structure * chore: replace old search request * chore: enable log for lib-dispatch * chore: move search manager to core * feat: move traits and responsibility to search crate * feat: move search to search crate * feat: replace sqlite with tantivy * feat: deserialize tantivy documents * chore: fixes after rebase * chore: clean code * feat: fetch and sort results * fix: code review + cleaning * feat: support custom icons * feat: support view layout icons * feat: rename bloc and fix indexing * fix: prettify dialog * feat: score results * chore: update collab rev * feat: add recent view history to command palette * test: add integration_tests * fix: clippy changes * fix: focus traversal in cmd palette * fix: remove file after merging main * chore: code review and panic-safe * feat: index all views if index does not exist * chore: improve logic with conditional * chore: add is_empty check * chore: abstract logic from folder manager init * chore: update collab rev * chore: code review * chore: fixes after merge + update lock file * chore: revert cargo lock * fix: set icon type when removing icon * fix: code review + dependency inversion * fix: remove icon fix for not persisting icon type * test: simple tests manipulating views * test: create 100 views * fix: tauri build * chore: create 1000 views * chore: create util methods * chore: test * chore: test * chore: remove logs * chore: fix build.rs * chore: export models * chore: enable clear cache on Rust-CI * fix: navigate to newly created views * fix: force disable setting workspace listener on rebuilds * fix: remove late final * fix: missing returns * fix: localization and minor fixes * test: add index assert to large test * fix: missing section param after merging main * chore: try fix unzip file error * chore: lower the test * feat: show hint when result is in trash --------- Co-authored-by: nathan <nathan@appflowy.io> Co-authored-by: Jiraffe7 <twajxjiraffe@gmail.com> Co-authored-by: Lucas.Xu <lucas.xu@appflowy.io>
2024-03-21 17:34:53 +01:00
Ok(_success) => {},
Err(e) => {
if let Some(msg) = e.downcast_ref::<&str>() {
error!("[FFI]: {:?}", msg);
} else {
error!("[FFI]: allo_isolate post panic");
}
},
}
2021-07-02 20:47:52 +08:00
}
#[no_mangle]
pub extern "C" fn rust_log(level: i64, data: *const c_char) {
// Check if the data pointer is not null
if data.is_null() {
error!("[flutter error]: null pointer provided to backend_log");
return;
}
let log_result = unsafe { CStr::from_ptr(data) }.to_str();
// Handle potential UTF-8 conversion error
let log_str = match log_result {
Ok(str) => str,
Err(e) => {
error!(
"[flutter error]: Failed to convert C string to Rust string: {:?}",
e
);
return;
},
};
// Simplify logging by determining the log level outside of the match
let log_level = match level {
0 => "info",
1 => "debug",
2 => "trace",
3 => "warn",
4 => "error",
_ => {
warn!("[flutter error]: Unsupported log level: {}", level);
return;
},
};
// Log the message at the appropriate level
match log_level {
"info" => info!("[Flutter]: {}", log_str),
"debug" => debug!("[Flutter]: {}", log_str),
"trace" => trace!("[Flutter]: {}", log_str),
"warn" => warn!("[Flutter]: {}", log_str),
"error" => error!("[Flutter]: {}", log_str),
_ => {
warn!("[flutter error]: Unsupported log level: {}", log_level);
},
}
}
#[no_mangle]
pub extern "C" fn set_env(_data: *const c_char) {
// Deprecated
}