168 lines
4.4 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 log::error;
use parking_lot::Mutex;
use tracing::trace;
use flowy_core::*;
2023-07-09 10:03:22 +07:00
use flowy_notification::{register_notification_sender, unregister_all_notification_sender};
use lib_dispatch::prelude::ToBytes;
use lib_dispatch::prelude::*;
2021-06-28 23:58:43 +08:00
use crate::env_serde::AppFlowyEnv;
use crate::notification::DartNotificationSender;
use crate::{
c::{extend_front_four_bytes_into_bytes, forget_rust},
model::{FFIRequest, FFIResponse},
};
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(path: *mut c_char) -> i64 {
let c_str: &CStr = unsafe { CStr::from_ptr(path) };
let path: &str = c_str.to_str().unwrap();
2021-09-05 13:50:23 +08:00
let log_crates = vec!["flowy-ffi".to_string()];
let config =
AppFlowyCoreConfig::new(path, DEFAULT_NAME.to_string()).log_filter("info", log_crates);
*APPFLOWY_CORE.0.lock() = Some(AppFlowyCore::new(config));
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,
request,
move |resp: AFPluginEventResponse| {
trace!("[FFI]: Post data to dart through {} port", port);
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
{
Ok(_success) => {
trace!("[FFI]: Post data to dart 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 backend_log(level: i64, data: *const c_char) {
let c_str = unsafe { CStr::from_ptr(data) };
let log_str = c_str.to_str().unwrap();
// Don't change the mapping relation between number and level
match level {
0 => tracing::info!("{}", log_str),
1 => tracing::debug!("{}", log_str),
2 => tracing::trace!("{}", log_str),
3 => tracing::warn!("{}", log_str),
4 => tracing::error!("{}", log_str),
_ => (),
}
}
#[no_mangle]
pub extern "C" fn set_env(data: *const c_char) {
let c_str = unsafe { CStr::from_ptr(data) };
let serde_str = c_str.to_str().unwrap();
AppFlowyEnv::parser(serde_str);
}