From bab373ba35bbd397ab1ec9be770d98719e359a8a Mon Sep 17 00:00:00 2001 From: appflowy Date: Fri, 16 Jul 2021 23:18:12 +0800 Subject: [PATCH 01/30] extract tester as trait --- .../flowy-workspace/errors.pbenum.dart | 2 + .../flowy-workspace/errors.pbjson.dart | 3 +- .../flowy-workspace/event.pbenum.dart | 2 + .../flowy-workspace/event.pbjson.dart | 3 +- rust-lib/dart-ffi/src/lib.rs | 2 +- rust-lib/flowy-derive/tests/progress.rs | 2 +- rust-lib/flowy-dispatch/src/dispatch.rs | 14 +- .../flowy-dispatch/src/request/payload.rs | 11 +- rust-lib/flowy-dispatch/tests/api/module.rs | 2 +- rust-lib/flowy-sdk/src/module.rs | 13 +- rust-lib/flowy-test/src/builder.rs | 82 ++++++ rust-lib/flowy-test/src/helper.rs | 43 +++ rust-lib/flowy-test/src/lib.rs | 248 +----------------- rust-lib/flowy-test/src/tester.rs | 176 +++++++++++++ .../flowy-user/src/handlers/auth_handler.rs | 4 +- .../flowy-user/src/handlers/user_handler.rs | 6 +- .../src/services/user_session/user_server.rs | 3 +- .../src/services/user_session/user_session.rs | 112 ++++---- rust-lib/flowy-user/tests/event/helper.rs | 2 +- rust-lib/flowy-user/tests/event/main.rs | 2 +- .../tests/event/user_status_test.rs | 2 +- ...ser_detail_test.rs => user_update_test.rs} | 0 .../src/entities/workspace/mod.rs | 2 + .../workspace/workspace_user_detail.rs | 6 + rust-lib/flowy-workspace/src/errors.rs | 3 + rust-lib/flowy-workspace/src/event.rs | 4 + rust-lib/flowy-workspace/src/module.rs | 2 +- .../src/protobuf/model/errors.rs | 60 +++-- .../src/protobuf/model/event.rs | 17 +- .../src/protobuf/proto/errors.proto | 1 + .../src/protobuf/proto/event.proto | 1 + .../flowy-workspace/tests/event/helper.rs | 2 +- 32 files changed, 462 insertions(+), 370 deletions(-) create mode 100644 rust-lib/flowy-test/src/builder.rs create mode 100644 rust-lib/flowy-test/src/helper.rs create mode 100644 rust-lib/flowy-test/src/tester.rs rename rust-lib/flowy-user/tests/event/{user_detail_test.rs => user_update_test.rs} (100%) create mode 100644 rust-lib/flowy-workspace/src/entities/workspace/workspace_user_detail.rs diff --git a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/errors.pbenum.dart b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/errors.pbenum.dart index 37693a76d2..ec32d54844 100644 --- a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/errors.pbenum.dart +++ b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/errors.pbenum.dart @@ -18,6 +18,7 @@ class WorkspaceErrorCode extends $pb.ProtobufEnum { static const WorkspaceErrorCode DatabaseConnectionFail = WorkspaceErrorCode._(5, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'DatabaseConnectionFail'); static const WorkspaceErrorCode DatabaseInternalError = WorkspaceErrorCode._(6, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'DatabaseInternalError'); static const WorkspaceErrorCode UserInternalError = WorkspaceErrorCode._(10, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'UserInternalError'); + static const WorkspaceErrorCode UserNotLoginYet = WorkspaceErrorCode._(11, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'UserNotLoginYet'); static const $core.List values = [ Unknown, @@ -28,6 +29,7 @@ class WorkspaceErrorCode extends $pb.ProtobufEnum { DatabaseConnectionFail, DatabaseInternalError, UserInternalError, + UserNotLoginYet, ]; static final $core.Map<$core.int, WorkspaceErrorCode> _byValue = $pb.ProtobufEnum.initByValue(values); diff --git a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/errors.pbjson.dart b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/errors.pbjson.dart index e2ce8025a2..7bb4fc0447 100644 --- a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/errors.pbjson.dart +++ b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/errors.pbjson.dart @@ -20,11 +20,12 @@ const WorkspaceErrorCode$json = const { const {'1': 'DatabaseConnectionFail', '2': 5}, const {'1': 'DatabaseInternalError', '2': 6}, const {'1': 'UserInternalError', '2': 10}, + const {'1': 'UserNotLoginYet', '2': 11}, ], }; /// Descriptor for `WorkspaceErrorCode`. Decode as a `google.protobuf.EnumDescriptorProto`. -final $typed_data.Uint8List workspaceErrorCodeDescriptor = $convert.base64Decode('ChJXb3Jrc3BhY2VFcnJvckNvZGUSCwoHVW5rbm93bhAAEhgKFFdvcmtzcGFjZU5hbWVJbnZhbGlkEAESFgoSV29ya3NwYWNlSWRJbnZhbGlkEAISGAoUQXBwQ29sb3JTdHlsZUludmFsaWQQAxIQCgxBcHBJZEludmFsaWQQBBIaChZEYXRhYmFzZUNvbm5lY3Rpb25GYWlsEAUSGQoVRGF0YWJhc2VJbnRlcm5hbEVycm9yEAYSFQoRVXNlckludGVybmFsRXJyb3IQCg=='); +final $typed_data.Uint8List workspaceErrorCodeDescriptor = $convert.base64Decode('ChJXb3Jrc3BhY2VFcnJvckNvZGUSCwoHVW5rbm93bhAAEhgKFFdvcmtzcGFjZU5hbWVJbnZhbGlkEAESFgoSV29ya3NwYWNlSWRJbnZhbGlkEAISGAoUQXBwQ29sb3JTdHlsZUludmFsaWQQAxIQCgxBcHBJZEludmFsaWQQBBIaChZEYXRhYmFzZUNvbm5lY3Rpb25GYWlsEAUSGQoVRGF0YWJhc2VJbnRlcm5hbEVycm9yEAYSFQoRVXNlckludGVybmFsRXJyb3IQChITCg9Vc2VyTm90TG9naW5ZZXQQCw=='); @$core.Deprecated('Use workspaceErrorDescriptor instead') const WorkspaceError$json = const { '1': 'WorkspaceError', diff --git a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/event.pbenum.dart b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/event.pbenum.dart index 343c57dc50..1d9502e8d9 100644 --- a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/event.pbenum.dart +++ b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/event.pbenum.dart @@ -11,9 +11,11 @@ import 'package:protobuf/protobuf.dart' as $pb; class WorkspaceEvent extends $pb.ProtobufEnum { static const WorkspaceEvent CreateWorkspace = WorkspaceEvent._(0, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'CreateWorkspace'); + static const WorkspaceEvent GetWorkspaceUserDetail = WorkspaceEvent._(100, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'GetWorkspaceUserDetail'); static const $core.List values = [ CreateWorkspace, + GetWorkspaceUserDetail, ]; static final $core.Map<$core.int, WorkspaceEvent> _byValue = $pb.ProtobufEnum.initByValue(values); diff --git a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/event.pbjson.dart b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/event.pbjson.dart index 5f2eac2e84..7466b2d76b 100644 --- a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/event.pbjson.dart +++ b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/event.pbjson.dart @@ -13,8 +13,9 @@ const WorkspaceEvent$json = const { '1': 'WorkspaceEvent', '2': const [ const {'1': 'CreateWorkspace', '2': 0}, + const {'1': 'GetWorkspaceUserDetail', '2': 100}, ], }; /// Descriptor for `WorkspaceEvent`. Decode as a `google.protobuf.EnumDescriptorProto`. -final $typed_data.Uint8List workspaceEventDescriptor = $convert.base64Decode('Cg5Xb3Jrc3BhY2VFdmVudBITCg9DcmVhdGVXb3Jrc3BhY2UQAA=='); +final $typed_data.Uint8List workspaceEventDescriptor = $convert.base64Decode('Cg5Xb3Jrc3BhY2VFdmVudBITCg9DcmVhdGVXb3Jrc3BhY2UQABIaChZHZXRXb3Jrc3BhY2VVc2VyRGV0YWlsEGQ='); diff --git a/rust-lib/dart-ffi/src/lib.rs b/rust-lib/dart-ffi/src/lib.rs index 9a04592458..5c7f0b28c0 100644 --- a/rust-lib/dart-ffi/src/lib.rs +++ b/rust-lib/dart-ffi/src/lib.rs @@ -40,7 +40,7 @@ pub extern "C" fn async_command(port: i64, input: *const u8, len: usize) { port ); - let _ = EventDispatch::async_send(request, move |resp: EventResponse| { + let _ = EventDispatch::async_send_with_callback(request, move |resp: EventResponse| { log::trace!("[FFI]: Post data to dart through {} port", port); Box::pin(post_to_flutter(resp, port)) }); diff --git a/rust-lib/flowy-derive/tests/progress.rs b/rust-lib/flowy-derive/tests/progress.rs index 6f1f5b1b9e..c4380d6778 100644 --- a/rust-lib/flowy-derive/tests/progress.rs +++ b/rust-lib/flowy-derive/tests/progress.rs @@ -1,5 +1,5 @@ #[tokio::test] async fn tests() { - let t = trybuild::TestCases::new(); + let _t = trybuild::TestCases::new(); // t.pass("tests/protobuf_enum.rs"); } diff --git a/rust-lib/flowy-dispatch/src/dispatch.rs b/rust-lib/flowy-dispatch/src/dispatch.rs index d2cc1a58bf..9ca27d40dd 100644 --- a/rust-lib/flowy-dispatch/src/dispatch.rs +++ b/rust-lib/flowy-dispatch/src/dispatch.rs @@ -38,7 +38,17 @@ impl EventDispatch { *(EVENT_DISPATCH.write().unwrap()) = Some(dispatch); } - pub fn async_send(request: Req, callback: Callback) -> DispatchFuture + pub fn async_send(request: Req) -> DispatchFuture + where + Req: std::convert::Into, + { + EventDispatch::async_send_with_callback(request, |_| Box::pin(async {})) + } + + pub fn async_send_with_callback( + request: Req, + callback: Callback, + ) -> DispatchFuture where Req: std::convert::Into, Callback: FnOnce(EventResponse) -> BoxFuture<'static, ()> + 'static + Send + Sync, @@ -83,7 +93,7 @@ impl EventDispatch { pub fn sync_send(request: ModuleRequest) -> EventResponse { futures::executor::block_on(async { - EventDispatch::async_send(request, |_| Box::pin(async {})).await + EventDispatch::async_send_with_callback(request, |_| Box::pin(async {})).await }) } } diff --git a/rust-lib/flowy-dispatch/src/request/payload.rs b/rust-lib/flowy-dispatch/src/request/payload.rs index 049d1d93e8..2efbed6538 100644 --- a/rust-lib/flowy-dispatch/src/request/payload.rs +++ b/rust-lib/flowy-dispatch/src/request/payload.rs @@ -1,3 +1,4 @@ +use crate::byte_trait::ToBytes; use bytes::Bytes; use std::{fmt, fmt::Formatter}; @@ -48,16 +49,6 @@ impl std::convert::Into for Vec { fn into(self) -> Payload { Payload::Bytes(self) } } -// = note: conflicting implementation in crate `core`: -// - impl TryInto for T where U: TryFrom; -// -// impl std::convert::TryInto for Vec { -// type Error = String; -// fn try_into(self) -> Result { -// Ok(Payload::Bytes(self)) -// } -// } - impl std::convert::Into for &str { fn into(self) -> Payload { self.to_string().into() } } diff --git a/rust-lib/flowy-dispatch/tests/api/module.rs b/rust-lib/flowy-dispatch/tests/api/module.rs index be6b98ef64..65d1b12a52 100644 --- a/rust-lib/flowy-dispatch/tests/api/module.rs +++ b/rust-lib/flowy-dispatch/tests/api/module.rs @@ -10,7 +10,7 @@ async fn test_init() { init_dispatch(|| vec![Module::new().event(event, hello)]); let request = ModuleRequest::new(event); - let _ = EventDispatch::async_send(request, |resp| { + let _ = EventDispatch::async_send_with_callback(request, |resp| { Box::pin(async move { dbg!(&resp); }) diff --git a/rust-lib/flowy-sdk/src/module.rs b/rust-lib/flowy-sdk/src/module.rs index ea427381ed..d337e37e9f 100644 --- a/rust-lib/flowy-sdk/src/module.rs +++ b/rust-lib/flowy-sdk/src/module.rs @@ -3,7 +3,7 @@ use flowy_user::prelude::*; use crate::flowy_server::{ArcFlowyServer, MockFlowyServer}; use flowy_database::DBConnection; -use flowy_user::errors::UserError; + use flowy_workspace::prelude::*; use std::sync::Arc; @@ -11,7 +11,7 @@ pub struct ModuleConfig { pub root: String, } -pub fn build_modules(config: ModuleConfig, server: ArcFlowyServer) -> Vec { +pub fn build_modules(config: ModuleConfig, _server: ArcFlowyServer) -> Vec { let user_session = Arc::new( UserSessionBuilder::new() .root_dir(&config.root) @@ -33,14 +33,15 @@ pub struct WorkspaceUserImpl { } impl WorkspaceUser for WorkspaceUserImpl { - fn set_current_workspace(&self, id: &str) { unimplemented!() } + fn set_current_workspace(&self, id: &str) { UserSession::set_current_workspace(id); } fn get_current_workspace(&self) -> Result { - self.user_session.get_current_workspace().map_err(|e| { - ErrorBuilder::new(WorkspaceErrorCode::UserInternalError) + let user_detail = self.user_session.user_detail().map_err(|e| { + ErrorBuilder::new(WorkspaceErrorCode::UserNotLoginYet) .error(e) .build() - }) + })?; + Ok(user_detail.id) } fn db_connection(&self) -> Result { diff --git a/rust-lib/flowy-test/src/builder.rs b/rust-lib/flowy-test/src/builder.rs new file mode 100644 index 0000000000..a100872fa0 --- /dev/null +++ b/rust-lib/flowy-test/src/builder.rs @@ -0,0 +1,82 @@ +use crate::{helper::new_user_after_login, init_sdk, tester::Tester}; +use flowy_dispatch::prelude::{EventDispatch, FromBytes, ModuleRequest, ToBytes}; +use flowy_user::{entities::UserDetail, event::UserEvent::SignOut}; +use std::{ + fmt::{Debug, Display}, + hash::Hash, +}; + +pub struct TestBuilder { + login: Option, + inner: Option>, + pub user_detail: Option, +} + +impl TestBuilder +where + Error: FromBytes + Debug, +{ + pub fn new() -> Self { + TestBuilder:: { + login: None, + inner: None, + user_detail: None, + } + } + + pub fn login(mut self) -> Self { + let user_detail = new_user_after_login(); + self.user_detail = Some(user_detail); + self + } + + pub fn logout(self) -> Self { + init_sdk(); + let _ = EventDispatch::sync_send(ModuleRequest::new(SignOut)); + self + } + + pub fn event(mut self, event: E) -> Self + where + E: Eq + Hash + Debug + Clone + Display, + { + self.inner = Some(Tester::::new(event)); + self + } + + pub fn request

(mut self, request: P) -> Self + where + P: ToBytes, + { + self.inner.as_mut().unwrap().set_request(request); + self + } + + pub fn sync_send(mut self) -> Self { + self.inner.as_mut().unwrap().sync_send(); + self + } + + pub fn parse(mut self) -> R + where + R: FromBytes, + { + let inner = self.inner.take().unwrap(); + inner.parse::() + } + + pub fn error(mut self) -> Error { + let inner = self.inner.take().unwrap(); + inner.error() + } + + pub fn assert_error(mut self) -> Self { + self.inner.as_mut().unwrap().assert_error(); + self + } + + pub fn assert_success(mut self) -> Self { + self.inner.as_mut().unwrap().assert_success(); + self + } +} diff --git a/rust-lib/flowy-test/src/helper.rs b/rust-lib/flowy-test/src/helper.rs new file mode 100644 index 0000000000..2ea710e809 --- /dev/null +++ b/rust-lib/flowy-test/src/helper.rs @@ -0,0 +1,43 @@ +use crate::{init_sdk, tester::Tester}; +use flowy_dispatch::prelude::*; +use flowy_user::{ + entities::{SignInRequest, UserDetail}, + errors::UserError, + event::UserEvent::{SignIn, SignOut}, +}; +use std::{fs, path::PathBuf}; + +pub fn root_dir() -> String { + // https://doc.rust-lang.org/cargo/reference/environment-variables.html + let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap_or("./".to_owned()); + let mut path_buf = fs::canonicalize(&PathBuf::from(&manifest_dir)).unwrap(); + path_buf.pop(); // rust-lib + path_buf.push("flowy-test"); + path_buf.push("temp"); + path_buf.push("flowy"); + + let root_dir = path_buf.to_str().unwrap().to_string(); + if !std::path::Path::new(&root_dir).exists() { + std::fs::create_dir_all(&root_dir).unwrap(); + } + root_dir +} + +pub fn new_user_after_login() -> UserDetail { + init_sdk(); + let _ = EventDispatch::sync_send(ModuleRequest::new(SignOut)); + let request = SignInRequest { + email: valid_email(), + password: valid_password(), + }; + + let mut tester = Tester::::new(SignIn); + tester.set_request(request); + tester.sync_send(); + + tester.parse::() +} + +pub(crate) fn valid_email() -> String { "annie@appflowy.io".to_string() } + +pub(crate) fn valid_password() -> String { "HelloWorld!123".to_string() } diff --git a/rust-lib/flowy-test/src/lib.rs b/rust-lib/flowy-test/src/lib.rs index 9c89eafc34..ebe11e7a66 100644 --- a/rust-lib/flowy-test/src/lib.rs +++ b/rust-lib/flowy-test/src/lib.rs @@ -1,25 +1,14 @@ -use flowy_dispatch::prelude::*; -pub use flowy_sdk::*; -use flowy_user::{ - errors::UserError, - event::UserEvent::{SignIn, SignOut}, - prelude::*, -}; -use std::{ - convert::TryFrom, - fmt::{Debug, Display}, - fs, - hash::Hash, - marker::PhantomData, - path::PathBuf, - sync::Once, - thread, -}; +mod builder; +mod helper; +mod tester; + +use crate::helper::root_dir; +use flowy_sdk::FlowySDK; +use std::{sync::Once, thread}; pub mod prelude { - pub use crate::Tester; + pub use crate::{builder::TestBuilder, tester::Tester}; pub use flowy_dispatch::prelude::*; - pub use std::convert::TryFrom; } static INIT: Once = Once::new(); @@ -30,224 +19,3 @@ pub fn init_sdk() { FlowySDK::new(&root_dir).construct(); }); } - -fn root_dir() -> String { - // https://doc.rust-lang.org/cargo/reference/environment-variables.html - let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap_or("./".to_owned()); - let mut path_buf = fs::canonicalize(&PathBuf::from(&manifest_dir)).unwrap(); - path_buf.pop(); // rust-lib - path_buf.push("flowy-test"); - path_buf.push("temp"); - path_buf.push("flowy"); - - let root_dir = path_buf.to_str().unwrap().to_string(); - if !std::path::Path::new(&root_dir).exists() { - std::fs::create_dir_all(&root_dir).unwrap(); - } - root_dir -} - -pub struct TestBuilder { - login: Option, - inner: Option>, - pub user_detail: Option, -} - -impl TestBuilder -where - Error: FromBytes + Debug, -{ - pub fn new() -> Self { - TestBuilder:: { - login: None, - inner: None, - user_detail: None, - } - } - - pub fn login(mut self) -> Self { - let user_detail = new_user_after_login(); - self.user_detail = Some(user_detail); - self - } - - pub fn logout(self) -> Self { - init_sdk(); - let _ = EventDispatch::sync_send(ModuleRequest::new(SignOut)); - self - } - - pub fn event(mut self, event: E) -> Self - where - E: Eq + Hash + Debug + Clone + Display, - { - self.inner = Some(Tester::::new(event)); - self - } - - pub fn request

(mut self, request: P) -> Self - where - P: ToBytes, - { - let mut inner = self.inner.unwrap(); - self.inner = Some(inner.request(request)); - self - } - - pub fn sync_send(mut self) -> Self { - let inner = self.inner.take().unwrap(); - self.inner = Some(inner.sync_send()); - self - } - - pub fn parse(mut self) -> R - where - R: FromBytes, - { - let inner = self.inner.take().unwrap(); - inner.parse::() - } - - pub fn error(mut self) -> Error { - let inner = self.inner.take().unwrap(); - inner.error() - } - - pub fn assert_error(mut self) -> Self { - let inner = self.inner.take().unwrap(); - self.inner = Some(inner.assert_error()); - self - } - - pub fn assert_success(mut self) -> Self { - let inner = self.inner.take().unwrap(); - self.inner = Some(inner.assert_success()); - self - } -} - -pub struct Tester { - inner_request: Option, - assert_status_code: Option, - response: Option, - err_phantom: PhantomData, - user_detail: Option, -} - -impl Tester -where - Error: FromBytes + Debug, -{ - pub fn new(event: E) -> Self - where - E: Eq + Hash + Debug + Clone + Display, - { - init_sdk(); - log::trace!( - "{:?} thread started: thread_id= {}", - thread::current(), - thread_id::get() - ); - - Self { - inner_request: Some(ModuleRequest::new(event)), - assert_status_code: None, - response: None, - err_phantom: PhantomData, - user_detail: None, - } - } - - pub fn request

(mut self, request: P) -> Self - where - P: ToBytes, - { - let mut inner_request = self.inner_request.take().unwrap(); - let bytes = request.into_bytes().unwrap(); - inner_request = inner_request.payload(bytes); - self.inner_request = Some(inner_request); - self - } - - pub fn assert_status_code(mut self, status_code: StatusCode) -> Self { - self.assert_status_code = Some(status_code); - self - } - - pub fn assert_error(mut self) -> Self { - self.assert_status_code = Some(StatusCode::Err); - self - } - - pub fn assert_success(mut self) -> Self { - self.assert_status_code = Some(StatusCode::Ok); - self - } - - pub async fn async_send(mut self) -> Self { - assert_eq!(self.inner_request.is_some(), true, "must set event"); - - let resp = - EventDispatch::async_send(self.inner_request.take().unwrap(), |_| Box::pin(async {})) - .await; - check(&resp, &self.assert_status_code); - self.response = Some(resp); - self - } - - pub fn sync_send(mut self) -> Self { - let resp = EventDispatch::sync_send(self.inner_request.take().unwrap()); - check(&resp, &self.assert_status_code); - self.response = Some(resp); - self - } - - pub fn parse(self) -> R - where - R: FromBytes, - { - let response = self.response.unwrap(); - match response.parse::() { - Ok(Ok(data)) => data, - Ok(Err(e)) => panic!("parse failed: {:?}", e), - Err(e) => panic!("Internal error: {:?}", e), - } - } - - pub fn error(self) -> Error { - let response = self.response.unwrap(); - assert_eq!(response.status_code, StatusCode::Err); - >::try_from(response.payload) - .unwrap() - .into_inner() - } -} - -fn check(response: &EventResponse, status_code: &Option) { - if let Some(ref status_code) = status_code { - if &response.status_code != status_code { - eprintln!("{:#?}", response); - } - assert_eq!(&response.status_code, status_code) - } -} - -fn new_user_after_login() -> UserDetail { - init_sdk(); - let _ = EventDispatch::sync_send(ModuleRequest::new(SignOut)); - let request = SignInRequest { - email: valid_email(), - password: valid_password(), - }; - - let user_detail = Tester::::new(SignIn) - .request(request) - .sync_send() - .parse::(); - - user_detail -} - -pub(crate) fn valid_email() -> String { "annie@appflowy.io".to_string() } - -pub(crate) fn valid_password() -> String { "HelloWorld!123".to_string() } diff --git a/rust-lib/flowy-test/src/tester.rs b/rust-lib/flowy-test/src/tester.rs new file mode 100644 index 0000000000..faf8268058 --- /dev/null +++ b/rust-lib/flowy-test/src/tester.rs @@ -0,0 +1,176 @@ +use crate::init_sdk; +use flowy_dispatch::prelude::*; +pub use flowy_sdk::*; +use flowy_user::prelude::*; +use std::{ + convert::TryFrom, + fmt::{Debug, Display}, + hash::Hash, + marker::PhantomData, + thread, +}; + +pub struct Tester { + inner_request: Option, + assert_status_code: Option, + response: Option, + err_phantom: PhantomData, + user_detail: Option, +} + +impl Tester +where + Error: FromBytes + Debug, +{ + pub fn new(event: E) -> Self + where + E: Eq + Hash + Debug + Clone + Display, + { + init_sdk(); + log::trace!( + "{:?} thread started: thread_id= {}", + thread::current(), + thread_id::get() + ); + + Self { + inner_request: Some(ModuleRequest::new(event)), + assert_status_code: None, + response: None, + err_phantom: PhantomData, + user_detail: None, + } + } + + pub fn set_request

(&mut self, request: P) + where + P: ToBytes, + { + let mut inner_request = self.inner_request.take().unwrap(); + let bytes = request.into_bytes().unwrap(); + inner_request = inner_request.payload(bytes); + self.inner_request = Some(inner_request); + } + + pub fn assert_error(&mut self) { self.assert_status_code = Some(StatusCode::Err); } + + pub fn assert_success(&mut self) { self.assert_status_code = Some(StatusCode::Ok); } + + pub async fn async_send(&mut self) { + assert_eq!(self.inner_request.is_some(), true, "must set event"); + + let resp = EventDispatch::async_send(self.inner_request.take().unwrap()).await; + self.response = Some(resp); + } + + pub fn sync_send(&mut self) { + let resp = EventDispatch::sync_send(self.inner_request.take().unwrap()); + self.response = Some(resp); + } + + pub fn parse(self) -> R + where + R: FromBytes, + { + let response = self.response.unwrap(); + match response.parse::() { + Ok(Ok(data)) => data, + Ok(Err(e)) => panic!("parse failed: {:?}", e), + Err(e) => panic!("Internal error: {:?}", e), + } + } + + pub fn error(self) -> Error { + let response = self.response.unwrap(); + assert_eq!(response.status_code, StatusCode::Err); + >::try_from(response.payload) + .unwrap() + .into_inner() + } +} + +pub struct RandomUserTester { + context: TesterContext, + err_phantom: PhantomData, +} + +impl RandomUserTester +where + Error: FromBytes + Debug, +{ + pub fn new() -> Self { + Self { + context: TesterContext::default(), + err_phantom: PhantomData, + } + } +} + +impl TesterTrait for RandomUserTester +where + Error: FromBytes + Debug, +{ + type Error = Error; + + fn context(&mut self) -> &mut TesterContext { &mut self.context } +} + +pub struct TesterContext { + request: Option, + status_code: StatusCode, + response: Option, +} + +impl std::default::Default for TesterContext { + fn default() -> Self { + Self { + request: None, + status_code: StatusCode::Ok, + response: None, + } + } +} + +pub trait TesterTrait { + type Error: FromBytes + Debug; + + fn context(&mut self) -> &mut TesterContext; + + fn assert_error(&mut self) { self.context().status_code = StatusCode::Err; } + + fn assert_success(&mut self) { self.context().status_code = StatusCode::Ok; } + + fn set_payload

(&mut self, payload: P) + where + P: ToBytes, + { + let bytes = payload.into_bytes().unwrap(); + let mut module_request = self.context().request.take().unwrap(); + self.context().request = Some(module_request.payload(bytes)); + } + + fn sync_send(&mut self) { + let resp = EventDispatch::sync_send(self.context().request.take().unwrap()); + self.context().response = Some(resp); + } + + fn parse(&mut self) -> R + where + R: FromBytes, + { + let response = self.context().response.clone().unwrap(); + match response.parse::() { + Ok(Ok(data)) => data, + Ok(Err(e)) => panic!("parse failed: {:?}", e), + Err(e) => panic!("Internal error: {:?}", e), + } + } + + fn error(&mut self) -> Self::Error { + let response = self.context().response.clone().unwrap(); + assert_eq!(response.status_code, StatusCode::Err); + >::try_from(response.payload) + .unwrap() + .into_inner() + } +} diff --git a/rust-lib/flowy-user/src/handlers/auth_handler.rs b/rust-lib/flowy-user/src/handlers/auth_handler.rs index 601d8b6f09..03d2be363b 100644 --- a/rust-lib/flowy-user/src/handlers/auth_handler.rs +++ b/rust-lib/flowy-user/src/handlers/auth_handler.rs @@ -15,7 +15,7 @@ pub async fn user_sign_in_handler( session: ModuleData>, ) -> ResponseResult { let params: SignInParams = data.into_inner().try_into()?; - let user = session.sign_in(params).await?; + let user = session.sign_in(params)?; let user_detail = UserDetail::from(user); response_ok(user_detail) } @@ -33,7 +33,7 @@ pub async fn user_sign_up_handler( session: ModuleData>, ) -> ResponseResult { let params: SignUpParams = data.into_inner().try_into()?; - let user = session.sign_up(params).await?; + let user = session.sign_up(params)?; let user_detail = UserDetail::from(user); response_ok(user_detail) } diff --git a/rust-lib/flowy-user/src/handlers/user_handler.rs b/rust-lib/flowy-user/src/handlers/user_handler.rs index 34b627e2a0..7cb31b3d88 100644 --- a/rust-lib/flowy-user/src/handlers/user_handler.rs +++ b/rust-lib/flowy-user/src/handlers/user_handler.rs @@ -5,12 +5,12 @@ use std::{convert::TryInto, sync::Arc}; pub async fn user_get_status_handler( session: ModuleData>, ) -> ResponseResult { - let user_detail = session.current_user_detail()?; + let user_detail = session.user_detail()?; response_ok(user_detail) } pub async fn sign_out_handler(session: ModuleData>) -> Result<(), UserError> { - let _ = session.sign_out().await?; + let _ = session.sign_out()?; Ok(()) } @@ -19,6 +19,6 @@ pub async fn update_user_handler( session: ModuleData>, ) -> ResponseResult { let params: UpdateUserParams = data.into_inner().try_into()?; - let user_detail = session.update_user(params).await?; + let user_detail = session.update_user(params)?; response_ok(user_detail) } diff --git a/rust-lib/flowy-user/src/services/user_session/user_server.rs b/rust-lib/flowy-user/src/services/user_session/user_server.rs index ef9636adab..e54bd48217 100644 --- a/rust-lib/flowy-user/src/services/user_session/user_server.rs +++ b/rust-lib/flowy-user/src/services/user_session/user_server.rs @@ -1,9 +1,8 @@ use crate::{ entities::{SignInParams, SignUpParams, UserDetail}, - errors::{ErrorBuilder, UserError, UserErrorCode}, + errors::UserError, sql_tables::User, }; -use flowy_infra::uuid; pub trait UserServer { fn sign_up(&self, params: SignUpParams) -> Result; diff --git a/rust-lib/flowy-user/src/services/user_session/user_session.rs b/rust-lib/flowy-user/src/services/user_session/user_session.rs index 97f7fa8d82..3f9413e46d 100644 --- a/rust-lib/flowy-user/src/services/user_session/user_session.rs +++ b/rust-lib/flowy-user/src/services/user_session/user_session.rs @@ -10,14 +10,13 @@ use lazy_static::lazy_static; use std::sync::{Arc, RwLock}; use crate::{ - entities::{SignInParams, SignUpParams, UpdateUserParams, UserDetail}, + entities::{SignInParams, SignUpParams, UpdateUserParams, UpdateUserRequest, UserDetail}, errors::{ErrorBuilder, UserError, UserErrorCode}, - event::UserEvent::GetStatus, + event::UserEvent::*, services::user_session::{database::UserDB, user_server::UserServer}, sql_tables::{User, UserChangeset}, }; -use flowy_dispatch::prelude::{Data, EventDispatch, ModuleRequest}; -use std::convert::TryFrom; +use flowy_dispatch::prelude::{EventDispatch, ModuleRequest, ToBytes}; pub struct UserSessionConfig { root_dir: String, @@ -50,20 +49,25 @@ impl UserSession { } } - pub async fn sign_in(&self, params: SignInParams) -> Result { + pub fn get_db_connection(&self) -> Result { + let user_id = get_current_user_id()?; + self.database.get_connection(&user_id) + } + + pub fn sign_in(&self, params: SignInParams) -> Result { let user = self.server.sign_in(params)?; let _ = set_current_user_id(Some(user.id.clone()))?; self.save_user(user) } - pub async fn sign_up(&self, params: SignUpParams) -> Result { + pub fn sign_up(&self, params: SignUpParams) -> Result { let user = self.server.sign_up(params)?; let _ = set_current_user_id(Some(user.id.clone()))?; self.save_user(user) } - pub async fn sign_out(&self) -> Result<(), UserError> { - let user_id = self.current_user_id()?; + pub fn sign_out(&self) -> Result<(), UserError> { + let user_id = current_user_id()?; let conn = self.get_db_connection()?; let _ = diesel::delete(dsl::user_table.filter(dsl::id.eq(&user_id))).execute(&*conn)?; @@ -77,17 +81,26 @@ impl UserSession { Ok(()) } - pub async fn update_user(&self, params: UpdateUserParams) -> Result { + fn save_user(&self, user: User) -> Result { + let conn = self.get_db_connection()?; + let _ = diesel::insert_into(user_table::table) + .values(user.clone()) + .execute(&*conn)?; + + Ok(user) + } + + pub fn update_user(&self, params: UpdateUserParams) -> Result { let changeset = UserChangeset::new(params); let conn = self.get_db_connection()?; diesel_update_table!(user_table, changeset, conn); - let user_detail = self.current_user_detail()?; + let user_detail = self.user_detail()?; Ok(user_detail) } - pub fn current_user_detail(&self) -> Result { - let user_id = self.current_user_id()?; + pub fn user_detail(&self) -> Result { + let user_id = current_user_id()?; let conn = self.get_db_connection()?; let user = dsl::user_table @@ -105,60 +118,35 @@ impl UserSession { Ok(UserDetail::from(user)) } - - pub fn get_db_connection(&self) -> Result { - let user_id = get_current_user_id()?; - self.database.get_connection(&user_id) - } - - pub fn set_current_workspace() { - unimplemented!() - - // let request = SignInRequest { - // email: valid_email(), - // password: valid_password(), - // }; - // - // let user_detail = Tester::::new(SignIn) - // .request(request) - // .sync_send() - // .parse::(); - // - // user_detail - } - - #[allow(dead_code)] - pub fn get_current_workspace(&self) -> Result { - // let response = EventDispatch::sync_send(ModuleRequest::new(GetStatus)); - // let user_detail = - // >::try_from(response.payload).unwrap().into_inner(); - let user_id = get_current_user_id()?; - let conn = self.get_db_connection()?; - - let workspace = dsl::user_table - .filter(user_table::id.eq(&user_id)) - .select(user_table::workspace) - .first::(&*conn)?; - - Ok(workspace) - } } impl UserSession { - fn save_user(&self, user: User) -> Result { - let conn = self.get_db_connection()?; - let _ = diesel::insert_into(user_table::table) - .values(user.clone()) - .execute(&*conn)?; - - Ok(user) - } - - fn current_user_id(&self) -> Result { - match KVStore::get_str(USER_ID_DISK_CACHE_KEY) { - None => Err(ErrorBuilder::new(UserErrorCode::UserNotLoginYet).build()), - Some(user_id) => Ok(user_id), + pub async fn set_current_workspace(workspace: &str) -> Result<(), UserError> { + let user_id = current_user_id()?; + let payload: Vec = UpdateUserRequest { + id: user_id, + name: None, + email: None, + workspace: Some(workspace.to_owned()), + password: None, } + .into_bytes() + .unwrap(); + + let request = ModuleRequest::new(UpdateUser).payload(payload); + let _user_detail = EventDispatch::async_send(request) + .await + .parse::() + .unwrap() + .unwrap(); + Ok(()) + } +} + +fn current_user_id() -> Result { + match KVStore::get_str(USER_ID_DISK_CACHE_KEY) { + None => Err(ErrorBuilder::new(UserErrorCode::UserNotLoginYet).build()), + Some(user_id) => Ok(user_id), } } diff --git a/rust-lib/flowy-user/tests/event/helper.rs b/rust-lib/flowy-user/tests/event/helper.rs index 0fea574637..692d6c2d42 100644 --- a/rust-lib/flowy-user/tests/event/helper.rs +++ b/rust-lib/flowy-user/tests/event/helper.rs @@ -1,4 +1,4 @@ -use flowy_test::{TestBuilder, Tester}; +use flowy_test::prelude::TestBuilder; use flowy_user::errors::UserError; pub type UserTestBuilder = TestBuilder; diff --git a/rust-lib/flowy-user/tests/event/main.rs b/rust-lib/flowy-user/tests/event/main.rs index ce3c9fb1cd..c5c296acab 100644 --- a/rust-lib/flowy-user/tests/event/main.rs +++ b/rust-lib/flowy-user/tests/event/main.rs @@ -1,5 +1,5 @@ mod helper; mod sign_in_test; mod sign_up_test; -mod user_detail_test; mod user_status_test; +mod user_update_test; diff --git a/rust-lib/flowy-user/tests/event/user_status_test.rs b/rust-lib/flowy-user/tests/event/user_status_test.rs index 62655f37bc..4b2f778f00 100644 --- a/rust-lib/flowy-user/tests/event/user_status_test.rs +++ b/rust-lib/flowy-user/tests/event/user_status_test.rs @@ -1,5 +1,5 @@ use crate::helper::*; -use flowy_user::{errors::UserErrorCode, event::UserEvent::*, prelude::*}; +use flowy_user::{event::UserEvent::*, prelude::*}; use serial_test::*; #[test] diff --git a/rust-lib/flowy-user/tests/event/user_detail_test.rs b/rust-lib/flowy-user/tests/event/user_update_test.rs similarity index 100% rename from rust-lib/flowy-user/tests/event/user_detail_test.rs rename to rust-lib/flowy-user/tests/event/user_update_test.rs diff --git a/rust-lib/flowy-workspace/src/entities/workspace/mod.rs b/rust-lib/flowy-workspace/src/entities/workspace/mod.rs index 8c44c9cd11..39e3f34656 100644 --- a/rust-lib/flowy-workspace/src/entities/workspace/mod.rs +++ b/rust-lib/flowy-workspace/src/entities/workspace/mod.rs @@ -1,8 +1,10 @@ pub use workspace_create::*; pub use workspace_query::*; pub use workspace_update::*; +pub use workspace_user_detail::*; pub(crate) mod parser; mod workspace_create; mod workspace_query; mod workspace_update; +mod workspace_user_detail; diff --git a/rust-lib/flowy-workspace/src/entities/workspace/workspace_user_detail.rs b/rust-lib/flowy-workspace/src/entities/workspace/workspace_user_detail.rs new file mode 100644 index 0000000000..6d9b69a7d0 --- /dev/null +++ b/rust-lib/flowy-workspace/src/entities/workspace/workspace_user_detail.rs @@ -0,0 +1,6 @@ +pub struct WorkspaceUserQueryRequest { + fetch_owner: bool, + fetch_all: bool, +} + +pub struct WorkspaceUserDetail {} diff --git a/rust-lib/flowy-workspace/src/errors.rs b/rust-lib/flowy-workspace/src/errors.rs index d9b5d71074..a3359375f5 100644 --- a/rust-lib/flowy-workspace/src/errors.rs +++ b/rust-lib/flowy-workspace/src/errors.rs @@ -46,6 +46,9 @@ pub enum WorkspaceErrorCode { #[display(fmt = "User internal error")] UserInternalError = 10, + + #[display(fmt = "User not login yet")] + UserNotLoginYet = 11, } impl std::default::Default for WorkspaceErrorCode { diff --git a/rust-lib/flowy-workspace/src/event.rs b/rust-lib/flowy-workspace/src/event.rs index f19ab12980..b8072ce17a 100644 --- a/rust-lib/flowy-workspace/src/event.rs +++ b/rust-lib/flowy-workspace/src/event.rs @@ -7,4 +7,8 @@ pub enum WorkspaceEvent { #[display(fmt = "Create workspace")] #[event(input = "CreateSpaceRequest", output = "WorkspaceDetail")] CreateWorkspace = 0, + + #[display(fmt = "Get workspace user")] + #[event(output = "UserDetail")] + GetWorkspaceUserDetail = 100, } diff --git a/rust-lib/flowy-workspace/src/module.rs b/rust-lib/flowy-workspace/src/module.rs index 40c060c060..4dc6f0bfdd 100644 --- a/rust-lib/flowy-workspace/src/module.rs +++ b/rust-lib/flowy-workspace/src/module.rs @@ -6,7 +6,7 @@ use crate::{ handlers::create_workspace, services::{AppController, WorkspaceController}, }; -use flowy_database::{DBConnection, UserDatabaseConnection}; +use flowy_database::DBConnection; use std::sync::Arc; pub trait WorkspaceUser: Send + Sync { diff --git a/rust-lib/flowy-workspace/src/protobuf/model/errors.rs b/rust-lib/flowy-workspace/src/protobuf/model/errors.rs index 2ac71808cd..33a4dd78a1 100644 --- a/rust-lib/flowy-workspace/src/protobuf/model/errors.rs +++ b/rust-lib/flowy-workspace/src/protobuf/model/errors.rs @@ -223,6 +223,7 @@ pub enum WorkspaceErrorCode { DatabaseConnectionFail = 5, DatabaseInternalError = 6, UserInternalError = 10, + UserNotLoginYet = 11, } impl ::protobuf::ProtobufEnum for WorkspaceErrorCode { @@ -240,6 +241,7 @@ impl ::protobuf::ProtobufEnum for WorkspaceErrorCode { 5 => ::std::option::Option::Some(WorkspaceErrorCode::DatabaseConnectionFail), 6 => ::std::option::Option::Some(WorkspaceErrorCode::DatabaseInternalError), 10 => ::std::option::Option::Some(WorkspaceErrorCode::UserInternalError), + 11 => ::std::option::Option::Some(WorkspaceErrorCode::UserNotLoginYet), _ => ::std::option::Option::None } } @@ -254,6 +256,7 @@ impl ::protobuf::ProtobufEnum for WorkspaceErrorCode { WorkspaceErrorCode::DatabaseConnectionFail, WorkspaceErrorCode::DatabaseInternalError, WorkspaceErrorCode::UserInternalError, + WorkspaceErrorCode::UserNotLoginYet, ]; values } @@ -284,36 +287,39 @@ impl ::protobuf::reflect::ProtobufValue for WorkspaceErrorCode { static file_descriptor_proto_data: &'static [u8] = b"\ \n\x0cerrors.proto\"K\n\x0eWorkspaceError\x12'\n\x04code\x18\x01\x20\x01\ (\x0e2\x13.WorkspaceErrorCodeR\x04code\x12\x10\n\x03msg\x18\x02\x20\x01(\ - \tR\x03msg*\xcd\x01\n\x12WorkspaceErrorCode\x12\x0b\n\x07Unknown\x10\0\ + \tR\x03msg*\xe2\x01\n\x12WorkspaceErrorCode\x12\x0b\n\x07Unknown\x10\0\ \x12\x18\n\x14WorkspaceNameInvalid\x10\x01\x12\x16\n\x12WorkspaceIdInval\ id\x10\x02\x12\x18\n\x14AppColorStyleInvalid\x10\x03\x12\x10\n\x0cAppIdI\ nvalid\x10\x04\x12\x1a\n\x16DatabaseConnectionFail\x10\x05\x12\x19\n\x15\ - DatabaseInternalError\x10\x06\x12\x15\n\x11UserInternalError\x10\nJ\xf8\ - \x03\n\x06\x12\x04\0\0\x0f\x01\n\x08\n\x01\x0c\x12\x03\0\0\x12\n\n\n\x02\ - \x04\0\x12\x04\x02\0\x05\x01\n\n\n\x03\x04\0\x01\x12\x03\x02\x08\x16\n\ - \x0b\n\x04\x04\0\x02\0\x12\x03\x03\x04\x20\n\x0c\n\x05\x04\0\x02\0\x06\ - \x12\x03\x03\x04\x16\n\x0c\n\x05\x04\0\x02\0\x01\x12\x03\x03\x17\x1b\n\ - \x0c\n\x05\x04\0\x02\0\x03\x12\x03\x03\x1e\x1f\n\x0b\n\x04\x04\0\x02\x01\ - \x12\x03\x04\x04\x13\n\x0c\n\x05\x04\0\x02\x01\x05\x12\x03\x04\x04\n\n\ - \x0c\n\x05\x04\0\x02\x01\x01\x12\x03\x04\x0b\x0e\n\x0c\n\x05\x04\0\x02\ - \x01\x03\x12\x03\x04\x11\x12\n\n\n\x02\x05\0\x12\x04\x06\0\x0f\x01\n\n\n\ - \x03\x05\0\x01\x12\x03\x06\x05\x17\n\x0b\n\x04\x05\0\x02\0\x12\x03\x07\ - \x04\x10\n\x0c\n\x05\x05\0\x02\0\x01\x12\x03\x07\x04\x0b\n\x0c\n\x05\x05\ - \0\x02\0\x02\x12\x03\x07\x0e\x0f\n\x0b\n\x04\x05\0\x02\x01\x12\x03\x08\ - \x04\x1d\n\x0c\n\x05\x05\0\x02\x01\x01\x12\x03\x08\x04\x18\n\x0c\n\x05\ - \x05\0\x02\x01\x02\x12\x03\x08\x1b\x1c\n\x0b\n\x04\x05\0\x02\x02\x12\x03\ - \t\x04\x1b\n\x0c\n\x05\x05\0\x02\x02\x01\x12\x03\t\x04\x16\n\x0c\n\x05\ - \x05\0\x02\x02\x02\x12\x03\t\x19\x1a\n\x0b\n\x04\x05\0\x02\x03\x12\x03\n\ - \x04\x1d\n\x0c\n\x05\x05\0\x02\x03\x01\x12\x03\n\x04\x18\n\x0c\n\x05\x05\ - \0\x02\x03\x02\x12\x03\n\x1b\x1c\n\x0b\n\x04\x05\0\x02\x04\x12\x03\x0b\ - \x04\x15\n\x0c\n\x05\x05\0\x02\x04\x01\x12\x03\x0b\x04\x10\n\x0c\n\x05\ - \x05\0\x02\x04\x02\x12\x03\x0b\x13\x14\n\x0b\n\x04\x05\0\x02\x05\x12\x03\ - \x0c\x04\x1f\n\x0c\n\x05\x05\0\x02\x05\x01\x12\x03\x0c\x04\x1a\n\x0c\n\ - \x05\x05\0\x02\x05\x02\x12\x03\x0c\x1d\x1e\n\x0b\n\x04\x05\0\x02\x06\x12\ - \x03\r\x04\x1e\n\x0c\n\x05\x05\0\x02\x06\x01\x12\x03\r\x04\x19\n\x0c\n\ - \x05\x05\0\x02\x06\x02\x12\x03\r\x1c\x1d\n\x0b\n\x04\x05\0\x02\x07\x12\ - \x03\x0e\x04\x1b\n\x0c\n\x05\x05\0\x02\x07\x01\x12\x03\x0e\x04\x15\n\x0c\ - \n\x05\x05\0\x02\x07\x02\x12\x03\x0e\x18\x1ab\x06proto3\ + DatabaseInternalError\x10\x06\x12\x15\n\x11UserInternalError\x10\n\x12\ + \x13\n\x0fUserNotLoginYet\x10\x0bJ\xa1\x04\n\x06\x12\x04\0\0\x10\x01\n\ + \x08\n\x01\x0c\x12\x03\0\0\x12\n\n\n\x02\x04\0\x12\x04\x02\0\x05\x01\n\n\ + \n\x03\x04\0\x01\x12\x03\x02\x08\x16\n\x0b\n\x04\x04\0\x02\0\x12\x03\x03\ + \x04\x20\n\x0c\n\x05\x04\0\x02\0\x06\x12\x03\x03\x04\x16\n\x0c\n\x05\x04\ + \0\x02\0\x01\x12\x03\x03\x17\x1b\n\x0c\n\x05\x04\0\x02\0\x03\x12\x03\x03\ + \x1e\x1f\n\x0b\n\x04\x04\0\x02\x01\x12\x03\x04\x04\x13\n\x0c\n\x05\x04\0\ + \x02\x01\x05\x12\x03\x04\x04\n\n\x0c\n\x05\x04\0\x02\x01\x01\x12\x03\x04\ + \x0b\x0e\n\x0c\n\x05\x04\0\x02\x01\x03\x12\x03\x04\x11\x12\n\n\n\x02\x05\ + \0\x12\x04\x06\0\x10\x01\n\n\n\x03\x05\0\x01\x12\x03\x06\x05\x17\n\x0b\n\ + \x04\x05\0\x02\0\x12\x03\x07\x04\x10\n\x0c\n\x05\x05\0\x02\0\x01\x12\x03\ + \x07\x04\x0b\n\x0c\n\x05\x05\0\x02\0\x02\x12\x03\x07\x0e\x0f\n\x0b\n\x04\ + \x05\0\x02\x01\x12\x03\x08\x04\x1d\n\x0c\n\x05\x05\0\x02\x01\x01\x12\x03\ + \x08\x04\x18\n\x0c\n\x05\x05\0\x02\x01\x02\x12\x03\x08\x1b\x1c\n\x0b\n\ + \x04\x05\0\x02\x02\x12\x03\t\x04\x1b\n\x0c\n\x05\x05\0\x02\x02\x01\x12\ + \x03\t\x04\x16\n\x0c\n\x05\x05\0\x02\x02\x02\x12\x03\t\x19\x1a\n\x0b\n\ + \x04\x05\0\x02\x03\x12\x03\n\x04\x1d\n\x0c\n\x05\x05\0\x02\x03\x01\x12\ + \x03\n\x04\x18\n\x0c\n\x05\x05\0\x02\x03\x02\x12\x03\n\x1b\x1c\n\x0b\n\ + \x04\x05\0\x02\x04\x12\x03\x0b\x04\x15\n\x0c\n\x05\x05\0\x02\x04\x01\x12\ + \x03\x0b\x04\x10\n\x0c\n\x05\x05\0\x02\x04\x02\x12\x03\x0b\x13\x14\n\x0b\ + \n\x04\x05\0\x02\x05\x12\x03\x0c\x04\x1f\n\x0c\n\x05\x05\0\x02\x05\x01\ + \x12\x03\x0c\x04\x1a\n\x0c\n\x05\x05\0\x02\x05\x02\x12\x03\x0c\x1d\x1e\n\ + \x0b\n\x04\x05\0\x02\x06\x12\x03\r\x04\x1e\n\x0c\n\x05\x05\0\x02\x06\x01\ + \x12\x03\r\x04\x19\n\x0c\n\x05\x05\0\x02\x06\x02\x12\x03\r\x1c\x1d\n\x0b\ + \n\x04\x05\0\x02\x07\x12\x03\x0e\x04\x1b\n\x0c\n\x05\x05\0\x02\x07\x01\ + \x12\x03\x0e\x04\x15\n\x0c\n\x05\x05\0\x02\x07\x02\x12\x03\x0e\x18\x1a\n\ + \x0b\n\x04\x05\0\x02\x08\x12\x03\x0f\x04\x19\n\x0c\n\x05\x05\0\x02\x08\ + \x01\x12\x03\x0f\x04\x13\n\x0c\n\x05\x05\0\x02\x08\x02\x12\x03\x0f\x16\ + \x18b\x06proto3\ "; static file_descriptor_proto_lazy: ::protobuf::rt::LazyV2<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::rt::LazyV2::INIT; diff --git a/rust-lib/flowy-workspace/src/protobuf/model/event.rs b/rust-lib/flowy-workspace/src/protobuf/model/event.rs index 07e5844a3c..d4836dbaee 100644 --- a/rust-lib/flowy-workspace/src/protobuf/model/event.rs +++ b/rust-lib/flowy-workspace/src/protobuf/model/event.rs @@ -26,6 +26,7 @@ #[derive(Clone,PartialEq,Eq,Debug,Hash)] pub enum WorkspaceEvent { CreateWorkspace = 0, + GetWorkspaceUserDetail = 100, } impl ::protobuf::ProtobufEnum for WorkspaceEvent { @@ -36,6 +37,7 @@ impl ::protobuf::ProtobufEnum for WorkspaceEvent { fn from_i32(value: i32) -> ::std::option::Option { match value { 0 => ::std::option::Option::Some(WorkspaceEvent::CreateWorkspace), + 100 => ::std::option::Option::Some(WorkspaceEvent::GetWorkspaceUserDetail), _ => ::std::option::Option::None } } @@ -43,6 +45,7 @@ impl ::protobuf::ProtobufEnum for WorkspaceEvent { fn values() -> &'static [Self] { static values: &'static [WorkspaceEvent] = &[ WorkspaceEvent::CreateWorkspace, + WorkspaceEvent::GetWorkspaceUserDetail, ]; values } @@ -71,12 +74,14 @@ impl ::protobuf::reflect::ProtobufValue for WorkspaceEvent { } static file_descriptor_proto_data: &'static [u8] = b"\ - \n\x0bevent.proto*%\n\x0eWorkspaceEvent\x12\x13\n\x0fCreateWorkspace\x10\ - \0JS\n\x06\x12\x04\0\0\x04\x01\n\x08\n\x01\x0c\x12\x03\0\0\x12\n\n\n\x02\ - \x05\0\x12\x04\x02\0\x04\x01\n\n\n\x03\x05\0\x01\x12\x03\x02\x05\x13\n\ - \x0b\n\x04\x05\0\x02\0\x12\x03\x03\x04\x18\n\x0c\n\x05\x05\0\x02\0\x01\ - \x12\x03\x03\x04\x13\n\x0c\n\x05\x05\0\x02\0\x02\x12\x03\x03\x16\x17b\ - \x06proto3\ + \n\x0bevent.proto*A\n\x0eWorkspaceEvent\x12\x13\n\x0fCreateWorkspace\x10\ + \0\x12\x1a\n\x16GetWorkspaceUserDetail\x10dJ|\n\x06\x12\x04\0\0\x05\x01\ + \n\x08\n\x01\x0c\x12\x03\0\0\x12\n\n\n\x02\x05\0\x12\x04\x02\0\x05\x01\n\ + \n\n\x03\x05\0\x01\x12\x03\x02\x05\x13\n\x0b\n\x04\x05\0\x02\0\x12\x03\ + \x03\x04\x18\n\x0c\n\x05\x05\0\x02\0\x01\x12\x03\x03\x04\x13\n\x0c\n\x05\ + \x05\0\x02\0\x02\x12\x03\x03\x16\x17\n\x0b\n\x04\x05\0\x02\x01\x12\x03\ + \x04\x04!\n\x0c\n\x05\x05\0\x02\x01\x01\x12\x03\x04\x04\x1a\n\x0c\n\x05\ + \x05\0\x02\x01\x02\x12\x03\x04\x1d\x20b\x06proto3\ "; static file_descriptor_proto_lazy: ::protobuf::rt::LazyV2<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::rt::LazyV2::INIT; diff --git a/rust-lib/flowy-workspace/src/protobuf/proto/errors.proto b/rust-lib/flowy-workspace/src/protobuf/proto/errors.proto index bab7a7c5e8..6b6af8b844 100644 --- a/rust-lib/flowy-workspace/src/protobuf/proto/errors.proto +++ b/rust-lib/flowy-workspace/src/protobuf/proto/errors.proto @@ -13,4 +13,5 @@ enum WorkspaceErrorCode { DatabaseConnectionFail = 5; DatabaseInternalError = 6; UserInternalError = 10; + UserNotLoginYet = 11; } diff --git a/rust-lib/flowy-workspace/src/protobuf/proto/event.proto b/rust-lib/flowy-workspace/src/protobuf/proto/event.proto index 1b4bcac07f..5d5a85f570 100644 --- a/rust-lib/flowy-workspace/src/protobuf/proto/event.proto +++ b/rust-lib/flowy-workspace/src/protobuf/proto/event.proto @@ -2,4 +2,5 @@ syntax = "proto3"; enum WorkspaceEvent { CreateWorkspace = 0; + GetWorkspaceUserDetail = 100; } diff --git a/rust-lib/flowy-workspace/tests/event/helper.rs b/rust-lib/flowy-workspace/tests/event/helper.rs index 58ad37b28d..c4ecbb3435 100644 --- a/rust-lib/flowy-workspace/tests/event/helper.rs +++ b/rust-lib/flowy-workspace/tests/event/helper.rs @@ -1,4 +1,4 @@ -use flowy_test::TestBuilder; +use flowy_test::prelude::TestBuilder; use flowy_workspace::errors::WorkspaceError; pub type WorkspaceTestBuilder = TestBuilder; From 0716556750944c218615a3019878767e41180e84 Mon Sep 17 00:00:00 2001 From: Jaylen Bian Date: Sat, 17 Jul 2021 00:37:47 +0800 Subject: [PATCH 02/30] [infra_ui] Migrate infra_ui from package to plugin --- app_flowy/packages/flowy_infra_ui/.gitignore | 72 +---- app_flowy/packages/flowy_infra_ui/.metadata | 4 +- app_flowy/packages/flowy_infra_ui/README.md | 44 +--- .../flowy_infra_ui/android/.gitignore | 8 + .../flowy_infra_ui/android/build.gradle | 50 ++++ .../flowy_infra_ui/android/gradle.properties | 3 + .../gradle/wrapper/gradle-wrapper.properties | 5 + .../flowy_infra_ui/android/settings.gradle | 1 + .../android/src/main/AndroidManifest.xml | 3 + .../flowy_infra_ui/FlowyInfraUiPlugin.kt | 35 +++ .../packages/flowy_infra_ui/example/README.md | 4 +- .../example/android/app/build.gradle | 2 +- .../android/app/src/debug/AndroidManifest.xml | 2 +- .../android/app/src/main/AndroidManifest.xml | 4 +- .../MainActivity.kt | 2 +- .../app/src/profile/AndroidManifest.xml | 2 +- .../example/ios/Flutter/Debug.xcconfig | 1 + .../example/ios/Flutter/Release.xcconfig | 1 + .../flowy_infra_ui/example/ios/Podfile | 41 +++ .../flowy_infra_ui/example/ios/Podfile.lock | 22 ++ .../ios/Runner.xcodeproj/project.pbxproj | 75 +++++- .../contents.xcworkspacedata | 3 + .../example/ios/Runner/Info.plist | 2 +- .../macos/Flutter/Flutter-Debug.xcconfig | 1 + .../macos/Flutter/Flutter-Release.xcconfig | 1 + .../Flutter/GeneratedPluginRegistrant.swift | 2 + .../flowy_infra_ui/example/macos/Podfile | 40 +++ .../macos/Runner.xcodeproj/project.pbxproj | 6 +- .../xcshareddata/xcschemes/Runner.xcscheme | 8 +- .../macos/Runner/Configs/AppInfo.xcconfig | 4 +- .../flowy_infra_ui/example/pubspec.lock | 14 +- .../flowy_infra_ui/example/pubspec.yaml | 55 +--- .../example/test/widget_test.dart | 25 +- .../flowy_infra_ui/example/web/index.html | 6 +- .../flowy_infra_ui/example/web/manifest.json | 6 +- .../flowy_infra_ui/example/windows/.gitignore | 17 ++ .../example/windows/CMakeLists.txt | 95 +++++++ .../example/windows/flutter/CMakeLists.txt | 103 ++++++++ .../flutter/generated_plugin_registrant.cc | 12 + .../flutter/generated_plugin_registrant.h | 13 + .../windows/flutter/generated_plugins.cmake | 16 ++ .../example/windows/runner/CMakeLists.txt | 17 ++ .../example/windows/runner/Runner.rc | 121 +++++++++ .../example/windows/runner/flutter_window.cpp | 61 +++++ .../example/windows/runner/flutter_window.h | 33 +++ .../example/windows/runner/main.cpp | 43 +++ .../example/windows/runner/resource.h | 16 ++ .../windows/runner/resources/app_icon.ico | Bin 0 -> 33772 bytes .../windows/runner/runner.exe.manifest | 20 ++ .../example/windows/runner/utils.cpp | 64 +++++ .../example/windows/runner/utils.h | 19 ++ .../example/windows/runner/win32_window.cpp | 245 ++++++++++++++++++ .../example/windows/runner/win32_window.h | 98 +++++++ .../packages/flowy_infra_ui/ios/.gitignore | 38 +++ .../flowy_infra_ui/ios/Assets/.gitkeep | 0 .../ios/Classes/FlowyInfraUiPlugin.h | 4 + .../ios/Classes/FlowyInfraUiPlugin.m | 15 ++ .../ios/Classes/SwiftFlowyInfraUiPlugin.swift | 14 + .../flowy_infra_ui/ios/flowy_infra_ui.podspec | 23 ++ .../flowy_infra_ui/lib/flowy_infra_ui.dart | 13 + .../lib/flowy_infra_ui_web.dart | 44 ++++ .../macos/Classes/FlowyInfraUiPlugin.swift | 19 ++ .../macos/flowy_infra_ui.podspec | 22 ++ .../packages/flowy_infra_ui/pubspec.lock | 14 +- .../packages/flowy_infra_ui/pubspec.yaml | 58 ++--- .../test/flowy_infra_ui_test.dart | 23 ++ .../flowy_infra_ui/test/flowy_ui_test.dart | 1 - .../flowy_infra_ui/windows/.gitignore | 17 ++ .../flowy_infra_ui/windows/CMakeLists.txt | 24 ++ .../windows/flowy_infra_ui_plugin.cpp | 82 ++++++ .../flowy_infra_ui/flowy_infra_ui_plugin.h | 23 ++ 71 files changed, 1744 insertions(+), 237 deletions(-) create mode 100644 app_flowy/packages/flowy_infra_ui/android/.gitignore create mode 100644 app_flowy/packages/flowy_infra_ui/android/build.gradle create mode 100644 app_flowy/packages/flowy_infra_ui/android/gradle.properties create mode 100644 app_flowy/packages/flowy_infra_ui/android/gradle/wrapper/gradle-wrapper.properties create mode 100644 app_flowy/packages/flowy_infra_ui/android/settings.gradle create mode 100644 app_flowy/packages/flowy_infra_ui/android/src/main/AndroidManifest.xml create mode 100644 app_flowy/packages/flowy_infra_ui/android/src/main/kotlin/com/example/flowy_infra_ui/FlowyInfraUiPlugin.kt rename app_flowy/packages/flowy_infra_ui/example/android/app/src/main/kotlin/com/example/{example => flowy_infra_ui_example}/MainActivity.kt (69%) create mode 100644 app_flowy/packages/flowy_infra_ui/example/ios/Podfile create mode 100644 app_flowy/packages/flowy_infra_ui/example/ios/Podfile.lock create mode 100644 app_flowy/packages/flowy_infra_ui/example/macos/Podfile create mode 100644 app_flowy/packages/flowy_infra_ui/example/windows/.gitignore create mode 100644 app_flowy/packages/flowy_infra_ui/example/windows/CMakeLists.txt create mode 100644 app_flowy/packages/flowy_infra_ui/example/windows/flutter/CMakeLists.txt create mode 100644 app_flowy/packages/flowy_infra_ui/example/windows/flutter/generated_plugin_registrant.cc create mode 100644 app_flowy/packages/flowy_infra_ui/example/windows/flutter/generated_plugin_registrant.h create mode 100644 app_flowy/packages/flowy_infra_ui/example/windows/flutter/generated_plugins.cmake create mode 100644 app_flowy/packages/flowy_infra_ui/example/windows/runner/CMakeLists.txt create mode 100644 app_flowy/packages/flowy_infra_ui/example/windows/runner/Runner.rc create mode 100644 app_flowy/packages/flowy_infra_ui/example/windows/runner/flutter_window.cpp create mode 100644 app_flowy/packages/flowy_infra_ui/example/windows/runner/flutter_window.h create mode 100644 app_flowy/packages/flowy_infra_ui/example/windows/runner/main.cpp create mode 100644 app_flowy/packages/flowy_infra_ui/example/windows/runner/resource.h create mode 100644 app_flowy/packages/flowy_infra_ui/example/windows/runner/resources/app_icon.ico create mode 100644 app_flowy/packages/flowy_infra_ui/example/windows/runner/runner.exe.manifest create mode 100644 app_flowy/packages/flowy_infra_ui/example/windows/runner/utils.cpp create mode 100644 app_flowy/packages/flowy_infra_ui/example/windows/runner/utils.h create mode 100644 app_flowy/packages/flowy_infra_ui/example/windows/runner/win32_window.cpp create mode 100644 app_flowy/packages/flowy_infra_ui/example/windows/runner/win32_window.h create mode 100644 app_flowy/packages/flowy_infra_ui/ios/.gitignore create mode 100644 app_flowy/packages/flowy_infra_ui/ios/Assets/.gitkeep create mode 100644 app_flowy/packages/flowy_infra_ui/ios/Classes/FlowyInfraUiPlugin.h create mode 100644 app_flowy/packages/flowy_infra_ui/ios/Classes/FlowyInfraUiPlugin.m create mode 100644 app_flowy/packages/flowy_infra_ui/ios/Classes/SwiftFlowyInfraUiPlugin.swift create mode 100644 app_flowy/packages/flowy_infra_ui/ios/flowy_infra_ui.podspec create mode 100644 app_flowy/packages/flowy_infra_ui/lib/flowy_infra_ui.dart create mode 100644 app_flowy/packages/flowy_infra_ui/lib/flowy_infra_ui_web.dart create mode 100644 app_flowy/packages/flowy_infra_ui/macos/Classes/FlowyInfraUiPlugin.swift create mode 100644 app_flowy/packages/flowy_infra_ui/macos/flowy_infra_ui.podspec create mode 100644 app_flowy/packages/flowy_infra_ui/test/flowy_infra_ui_test.dart delete mode 100644 app_flowy/packages/flowy_infra_ui/test/flowy_ui_test.dart create mode 100644 app_flowy/packages/flowy_infra_ui/windows/.gitignore create mode 100644 app_flowy/packages/flowy_infra_ui/windows/CMakeLists.txt create mode 100644 app_flowy/packages/flowy_infra_ui/windows/flowy_infra_ui_plugin.cpp create mode 100644 app_flowy/packages/flowy_infra_ui/windows/include/flowy_infra_ui/flowy_infra_ui_plugin.h diff --git a/app_flowy/packages/flowy_infra_ui/.gitignore b/app_flowy/packages/flowy_infra_ui/.gitignore index a247422ef7..e9dc58d3d6 100644 --- a/app_flowy/packages/flowy_infra_ui/.gitignore +++ b/app_flowy/packages/flowy_infra_ui/.gitignore @@ -1,75 +1,7 @@ -# Miscellaneous -*.class -*.log -*.pyc -*.swp .DS_Store -.atom/ -.buildlog/ -.history -.svn/ - -# IntelliJ related -*.iml -*.ipr -*.iws -.idea/ - -# The .vscode folder contains launch configuration and tasks you configure in -# VS Code which you may wish to be included in version control, so this line -# is commented out by default. -#.vscode/ - -# Flutter/Dart/Pub related -**/doc/api/ .dart_tool/ -.flutter-plugins -.flutter-plugins-dependencies + .packages -.pub-cache/ .pub/ + build/ - -# Android related -**/android/**/gradle-wrapper.jar -**/android/.gradle -**/android/captures/ -**/android/gradlew -**/android/gradlew.bat -**/android/local.properties -**/android/**/GeneratedPluginRegistrant.java - -# iOS/XCode related -**/ios/**/*.mode1v3 -**/ios/**/*.mode2v3 -**/ios/**/*.moved-aside -**/ios/**/*.pbxuser -**/ios/**/*.perspectivev3 -**/ios/**/*sync/ -**/ios/**/.sconsign.dblite -**/ios/**/.tags* -**/ios/**/.vagrant/ -**/ios/**/DerivedData/ -**/ios/**/Icon? -**/ios/**/Pods/ -**/ios/**/.symlinks/ -**/ios/**/profile -**/ios/**/xcuserdata -**/ios/.generated/ -**/ios/Flutter/App.framework -**/ios/Flutter/Flutter.framework -**/ios/Flutter/Flutter.podspec -**/ios/Flutter/Generated.xcconfig -**/ios/Flutter/ephemeral -**/ios/Flutter/app.flx -**/ios/Flutter/app.zip -**/ios/Flutter/flutter_assets/ -**/ios/Flutter/flutter_export_environment.sh -**/ios/ServiceDefinitions.json -**/ios/Runner/GeneratedPluginRegistrant.* - -# Exceptions to above rules. -!**/ios/**/default.mode1v3 -!**/ios/**/default.mode2v3 -!**/ios/**/default.pbxuser -!**/ios/**/default.perspectivev3 diff --git a/app_flowy/packages/flowy_infra_ui/.metadata b/app_flowy/packages/flowy_infra_ui/.metadata index f323c72cb1..505610f134 100644 --- a/app_flowy/packages/flowy_infra_ui/.metadata +++ b/app_flowy/packages/flowy_infra_ui/.metadata @@ -4,7 +4,7 @@ # This file should be version controlled and should not be manually edited. version: - revision: 96bbcd006fafade4ad7a4abde77cec32df6846ea + revision: fa5883b78e566877613ad1ccb48dd92075cb5c23 channel: dev -project_type: package +project_type: plugin diff --git a/app_flowy/packages/flowy_infra_ui/README.md b/app_flowy/packages/flowy_infra_ui/README.md index 8b55e735b5..2644e9ffa9 100644 --- a/app_flowy/packages/flowy_infra_ui/README.md +++ b/app_flowy/packages/flowy_infra_ui/README.md @@ -1,39 +1,15 @@ - +## Getting Started -TODO: Put a short description of the package here that helps potential users -know whether this package might be useful for them. +This project is a starting point for a Flutter +[plug-in package](https://flutter.dev/developing-packages/), +a specialized package that includes platform-specific implementation code for +Android and/or iOS. -## Features +For help getting started with Flutter, view our +[online documentation](https://flutter.dev/docs), which offers tutorials, +samples, guidance on mobile development, and a full API reference. -TODO: List what your package can do. Maybe include images, gifs, or videos. - -## Getting started - -TODO: List prerequisites and provide or point to information on how to -start using the package. - -## Usage - -TODO: Include short and useful examples for package users. Add longer examples -to `/example` folder. - -```dart -const like = 'sample'; -``` - -## Additional information - -TODO: Tell users more about the package: where to find more information, how to -contribute to the package, how to file issues, what response they can expect -from the package authors, and more. diff --git a/app_flowy/packages/flowy_infra_ui/android/.gitignore b/app_flowy/packages/flowy_infra_ui/android/.gitignore new file mode 100644 index 0000000000..c6cbe562a4 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/android/.gitignore @@ -0,0 +1,8 @@ +*.iml +.gradle +/local.properties +/.idea/workspace.xml +/.idea/libraries +.DS_Store +/build +/captures diff --git a/app_flowy/packages/flowy_infra_ui/android/build.gradle b/app_flowy/packages/flowy_infra_ui/android/build.gradle new file mode 100644 index 0000000000..f1e1c9e76e --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/android/build.gradle @@ -0,0 +1,50 @@ +group 'com.example.flowy_infra_ui' +version '1.0-SNAPSHOT' + +buildscript { + ext.kotlin_version = '1.3.50' + repositories { + google() + mavenCentral() + } + + dependencies { + classpath 'com.android.tools.build:gradle:4.1.0' + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + } +} + +rootProject.allprojects { + repositories { + google() + mavenCentral() + } +} + +apply plugin: 'com.android.library' +apply plugin: 'kotlin-android' + +android { + compileSdkVersion 30 + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + kotlinOptions { + jvmTarget = '1.8' + } + + sourceSets { + main.java.srcDirs += 'src/main/kotlin' + } + + defaultConfig { + minSdkVersion 16 + } +} + +dependencies { + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" +} diff --git a/app_flowy/packages/flowy_infra_ui/android/gradle.properties b/app_flowy/packages/flowy_infra_ui/android/gradle.properties new file mode 100644 index 0000000000..94adc3a3f9 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/android/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx1536M +android.useAndroidX=true +android.enableJetifier=true diff --git a/app_flowy/packages/flowy_infra_ui/android/gradle/wrapper/gradle-wrapper.properties b/app_flowy/packages/flowy_infra_ui/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000..3c9d0852bf --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-all.zip diff --git a/app_flowy/packages/flowy_infra_ui/android/settings.gradle b/app_flowy/packages/flowy_infra_ui/android/settings.gradle new file mode 100644 index 0000000000..0dc790b56b --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/android/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'flowy_infra_ui' diff --git a/app_flowy/packages/flowy_infra_ui/android/src/main/AndroidManifest.xml b/app_flowy/packages/flowy_infra_ui/android/src/main/AndroidManifest.xml new file mode 100644 index 0000000000..f93233246e --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/android/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + diff --git a/app_flowy/packages/flowy_infra_ui/android/src/main/kotlin/com/example/flowy_infra_ui/FlowyInfraUiPlugin.kt b/app_flowy/packages/flowy_infra_ui/android/src/main/kotlin/com/example/flowy_infra_ui/FlowyInfraUiPlugin.kt new file mode 100644 index 0000000000..5d98dd8f10 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/android/src/main/kotlin/com/example/flowy_infra_ui/FlowyInfraUiPlugin.kt @@ -0,0 +1,35 @@ +package com.example.flowy_infra_ui + +import androidx.annotation.NonNull + +import io.flutter.embedding.engine.plugins.FlutterPlugin +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import io.flutter.plugin.common.MethodChannel.MethodCallHandler +import io.flutter.plugin.common.MethodChannel.Result + +/** FlowyInfraUiPlugin */ +class FlowyInfraUiPlugin: FlutterPlugin, MethodCallHandler { + /// The MethodChannel that will the communication between Flutter and native Android + /// + /// This local reference serves to register the plugin with the Flutter Engine and unregister it + /// when the Flutter Engine is detached from the Activity + private lateinit var channel : MethodChannel + + override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { + channel = MethodChannel(flutterPluginBinding.binaryMessenger, "flowy_infra_ui") + channel.setMethodCallHandler(this) + } + + override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) { + if (call.method == "getPlatformVersion") { + result.success("Android ${android.os.Build.VERSION.RELEASE}") + } else { + result.notImplemented() + } + } + + override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) { + channel.setMethodCallHandler(null) + } +} diff --git a/app_flowy/packages/flowy_infra_ui/example/README.md b/app_flowy/packages/flowy_infra_ui/example/README.md index a135626028..7bc0ab05f6 100644 --- a/app_flowy/packages/flowy_infra_ui/example/README.md +++ b/app_flowy/packages/flowy_infra_ui/example/README.md @@ -1,6 +1,6 @@ -# example +# flowy_infra_ui_example -A new Flutter project. +Demonstrates how to use the flowy_infra_ui plugin. ## Getting Started diff --git a/app_flowy/packages/flowy_infra_ui/example/android/app/build.gradle b/app_flowy/packages/flowy_infra_ui/example/android/app/build.gradle index 56bfa9b78f..7530664892 100644 --- a/app_flowy/packages/flowy_infra_ui/example/android/app/build.gradle +++ b/app_flowy/packages/flowy_infra_ui/example/android/app/build.gradle @@ -43,7 +43,7 @@ android { defaultConfig { // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). - applicationId "com.example.example" + applicationId "com.example.flowy_infra_ui_example" minSdkVersion 16 targetSdkVersion 30 versionCode flutterVersionCode.toInteger() diff --git a/app_flowy/packages/flowy_infra_ui/example/android/app/src/debug/AndroidManifest.xml b/app_flowy/packages/flowy_infra_ui/example/android/app/src/debug/AndroidManifest.xml index c208884f30..26ef01e2ad 100644 --- a/app_flowy/packages/flowy_infra_ui/example/android/app/src/debug/AndroidManifest.xml +++ b/app_flowy/packages/flowy_infra_ui/example/android/app/src/debug/AndroidManifest.xml @@ -1,5 +1,5 @@ + package="com.example.flowy_infra_ui_example"> diff --git a/app_flowy/packages/flowy_infra_ui/example/android/app/src/main/AndroidManifest.xml b/app_flowy/packages/flowy_infra_ui/example/android/app/src/main/AndroidManifest.xml index 34dd77efb2..48bd1e58f9 100644 --- a/app_flowy/packages/flowy_infra_ui/example/android/app/src/main/AndroidManifest.xml +++ b/app_flowy/packages/flowy_infra_ui/example/android/app/src/main/AndroidManifest.xml @@ -1,7 +1,7 @@ + package="com.example.flowy_infra_ui_example"> + package="com.example.flowy_infra_ui_example"> diff --git a/app_flowy/packages/flowy_infra_ui/example/ios/Flutter/Debug.xcconfig b/app_flowy/packages/flowy_infra_ui/example/ios/Flutter/Debug.xcconfig index 592ceee85b..ec97fc6f30 100644 --- a/app_flowy/packages/flowy_infra_ui/example/ios/Flutter/Debug.xcconfig +++ b/app_flowy/packages/flowy_infra_ui/example/ios/Flutter/Debug.xcconfig @@ -1 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" #include "Generated.xcconfig" diff --git a/app_flowy/packages/flowy_infra_ui/example/ios/Flutter/Release.xcconfig b/app_flowy/packages/flowy_infra_ui/example/ios/Flutter/Release.xcconfig index 592ceee85b..c4855bfe20 100644 --- a/app_flowy/packages/flowy_infra_ui/example/ios/Flutter/Release.xcconfig +++ b/app_flowy/packages/flowy_infra_ui/example/ios/Flutter/Release.xcconfig @@ -1 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" #include "Generated.xcconfig" diff --git a/app_flowy/packages/flowy_infra_ui/example/ios/Podfile b/app_flowy/packages/flowy_infra_ui/example/ios/Podfile new file mode 100644 index 0000000000..1e8c3c90a5 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/example/ios/Podfile @@ -0,0 +1,41 @@ +# Uncomment this line to define a global platform for your project +# platform :ios, '9.0' + +# CocoaPods analytics sends network stats synchronously affecting flutter build latency. +ENV['COCOAPODS_DISABLE_STATS'] = 'true' + +project 'Runner', { + 'Debug' => :debug, + 'Profile' => :release, + 'Release' => :release, +} + +def flutter_root + generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) + unless File.exist?(generated_xcode_build_settings_path) + raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" + end + + File.foreach(generated_xcode_build_settings_path) do |line| + matches = line.match(/FLUTTER_ROOT\=(.*)/) + return matches[1].strip if matches + end + raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" +end + +require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) + +flutter_ios_podfile_setup + +target 'Runner' do + use_frameworks! + use_modular_headers! + + flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) +end + +post_install do |installer| + installer.pods_project.targets.each do |target| + flutter_additional_ios_build_settings(target) + end +end diff --git a/app_flowy/packages/flowy_infra_ui/example/ios/Podfile.lock b/app_flowy/packages/flowy_infra_ui/example/ios/Podfile.lock new file mode 100644 index 0000000000..c5a50f2dc9 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/example/ios/Podfile.lock @@ -0,0 +1,22 @@ +PODS: + - flowy_infra_ui (0.0.1): + - Flutter + - Flutter (1.0.0) + +DEPENDENCIES: + - flowy_infra_ui (from `.symlinks/plugins/flowy_infra_ui/ios`) + - Flutter (from `Flutter`) + +EXTERNAL SOURCES: + flowy_infra_ui: + :path: ".symlinks/plugins/flowy_infra_ui/ios" + Flutter: + :path: Flutter + +SPEC CHECKSUMS: + flowy_infra_ui: 146c88346fd55d2ee6a41ae35059a5bf095cfbb3 + Flutter: 434fef37c0980e73bb6479ef766c45957d4b510c + +PODFILE CHECKSUM: aafe91acc616949ddb318b77800a7f51bffa2a4c + +COCOAPODS: 1.9.3 diff --git a/app_flowy/packages/flowy_infra_ui/example/ios/Runner.xcodeproj/project.pbxproj b/app_flowy/packages/flowy_infra_ui/example/ios/Runner.xcodeproj/project.pbxproj index c6759a6e8f..eb8f7f7e87 100644 --- a/app_flowy/packages/flowy_infra_ui/example/ios/Runner.xcodeproj/project.pbxproj +++ b/app_flowy/packages/flowy_infra_ui/example/ios/Runner.xcodeproj/project.pbxproj @@ -9,6 +9,7 @@ /* Begin PBXBuildFile section */ 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; + 73D88840D6ADB1B9C000C539 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CA749E34E8D549849F119B5B /* Pods_Runner.framework */; }; 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; @@ -32,6 +33,7 @@ 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; + 3CA8F348EBCAB0B9417EC70D /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; @@ -42,6 +44,9 @@ 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + BD462F555277405D97D69F24 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; + C010FCE60C748638851A2DFA /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; + CA749E34E8D549849F119B5B /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -49,12 +54,32 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 73D88840D6ADB1B9C000C539 /* Pods_Runner.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 2A04BAC54BC6D85A998F0000 /* Frameworks */ = { + isa = PBXGroup; + children = ( + CA749E34E8D549849F119B5B /* Pods_Runner.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + 8F8024933033E730415889FC /* Pods */ = { + isa = PBXGroup; + children = ( + C010FCE60C748638851A2DFA /* Pods-Runner.debug.xcconfig */, + BD462F555277405D97D69F24 /* Pods-Runner.release.xcconfig */, + 3CA8F348EBCAB0B9417EC70D /* Pods-Runner.profile.xcconfig */, + ); + name = Pods; + path = Pods; + sourceTree = ""; + }; 9740EEB11CF90186004384FC /* Flutter */ = { isa = PBXGroup; children = ( @@ -72,6 +97,8 @@ 9740EEB11CF90186004384FC /* Flutter */, 97C146F01CF9000F007C117D /* Runner */, 97C146EF1CF9000F007C117D /* Products */, + 8F8024933033E730415889FC /* Pods */, + 2A04BAC54BC6D85A998F0000 /* Frameworks */, ); sourceTree = ""; }; @@ -105,12 +132,14 @@ isa = PBXNativeTarget; buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( + 653DE1EFE700467C4AF71781 /* [CP] Check Pods Manifest.lock */, 9740EEB61CF901F6004384FC /* Run Script */, 97C146EA1CF9000F007C117D /* Sources */, 97C146EB1CF9000F007C117D /* Frameworks */, 97C146EC1CF9000F007C117D /* Resources */, 9705A1C41CF9048500538489 /* Embed Frameworks */, 3B06AD1E1E4923F5004D2608 /* Thin Binary */, + C71338FE5F010950C936DB01 /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); @@ -183,6 +212,28 @@ shellPath = /bin/sh; shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; }; + 653DE1EFE700467C4AF71781 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; 9740EEB61CF901F6004384FC /* Run Script */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; @@ -197,6 +248,24 @@ shellPath = /bin/sh; shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; }; + C71338FE5F010950C936DB01 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh", + "${BUILT_PRODUCTS_DIR}/flowy_infra_ui/flowy_infra_ui.framework", + ); + name = "[CP] Embed Pods Frameworks"; + outputPaths = ( + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/flowy_infra_ui.framework", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ @@ -291,7 +360,7 @@ ENABLE_BITCODE = NO; INFOPLIST_FILE = Runner/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; - PRODUCT_BUNDLE_IDENTIFIER = com.example.example; + PRODUCT_BUNDLE_IDENTIFIER = com.example.flowyInfraUiExample; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_VERSION = 5.0; @@ -415,7 +484,7 @@ ENABLE_BITCODE = NO; INFOPLIST_FILE = Runner/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; - PRODUCT_BUNDLE_IDENTIFIER = com.example.example; + PRODUCT_BUNDLE_IDENTIFIER = com.example.flowyInfraUiExample; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; @@ -434,7 +503,7 @@ ENABLE_BITCODE = NO; INFOPLIST_FILE = Runner/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; - PRODUCT_BUNDLE_IDENTIFIER = com.example.example; + PRODUCT_BUNDLE_IDENTIFIER = com.example.flowyInfraUiExample; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_VERSION = 5.0; diff --git a/app_flowy/packages/flowy_infra_ui/example/ios/Runner.xcworkspace/contents.xcworkspacedata b/app_flowy/packages/flowy_infra_ui/example/ios/Runner.xcworkspace/contents.xcworkspacedata index 1d526a16ed..21a3cc14c7 100644 --- a/app_flowy/packages/flowy_infra_ui/example/ios/Runner.xcworkspace/contents.xcworkspacedata +++ b/app_flowy/packages/flowy_infra_ui/example/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -4,4 +4,7 @@ + + diff --git a/app_flowy/packages/flowy_infra_ui/example/ios/Runner/Info.plist b/app_flowy/packages/flowy_infra_ui/example/ios/Runner/Info.plist index a060db61e4..78bd1d1d6c 100644 --- a/app_flowy/packages/flowy_infra_ui/example/ios/Runner/Info.plist +++ b/app_flowy/packages/flowy_infra_ui/example/ios/Runner/Info.plist @@ -11,7 +11,7 @@ CFBundleInfoDictionaryVersion 6.0 CFBundleName - example + flowy_infra_ui_example CFBundlePackageType APPL CFBundleShortVersionString diff --git a/app_flowy/packages/flowy_infra_ui/example/macos/Flutter/Flutter-Debug.xcconfig b/app_flowy/packages/flowy_infra_ui/example/macos/Flutter/Flutter-Debug.xcconfig index c2efd0b608..4b81f9b2d2 100644 --- a/app_flowy/packages/flowy_infra_ui/example/macos/Flutter/Flutter-Debug.xcconfig +++ b/app_flowy/packages/flowy_infra_ui/example/macos/Flutter/Flutter-Debug.xcconfig @@ -1 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" #include "ephemeral/Flutter-Generated.xcconfig" diff --git a/app_flowy/packages/flowy_infra_ui/example/macos/Flutter/Flutter-Release.xcconfig b/app_flowy/packages/flowy_infra_ui/example/macos/Flutter/Flutter-Release.xcconfig index c2efd0b608..5caa9d1579 100644 --- a/app_flowy/packages/flowy_infra_ui/example/macos/Flutter/Flutter-Release.xcconfig +++ b/app_flowy/packages/flowy_infra_ui/example/macos/Flutter/Flutter-Release.xcconfig @@ -1 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" #include "ephemeral/Flutter-Generated.xcconfig" diff --git a/app_flowy/packages/flowy_infra_ui/example/macos/Flutter/GeneratedPluginRegistrant.swift b/app_flowy/packages/flowy_infra_ui/example/macos/Flutter/GeneratedPluginRegistrant.swift index cccf817a52..fe63258f95 100644 --- a/app_flowy/packages/flowy_infra_ui/example/macos/Flutter/GeneratedPluginRegistrant.swift +++ b/app_flowy/packages/flowy_infra_ui/example/macos/Flutter/GeneratedPluginRegistrant.swift @@ -5,6 +5,8 @@ import FlutterMacOS import Foundation +import flowy_infra_ui func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + FlowyInfraUiPlugin.register(with: registry.registrar(forPlugin: "FlowyInfraUiPlugin")) } diff --git a/app_flowy/packages/flowy_infra_ui/example/macos/Podfile b/app_flowy/packages/flowy_infra_ui/example/macos/Podfile new file mode 100644 index 0000000000..dade8dfad0 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/example/macos/Podfile @@ -0,0 +1,40 @@ +platform :osx, '10.11' + +# CocoaPods analytics sends network stats synchronously affecting flutter build latency. +ENV['COCOAPODS_DISABLE_STATS'] = 'true' + +project 'Runner', { + 'Debug' => :debug, + 'Profile' => :release, + 'Release' => :release, +} + +def flutter_root + generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'ephemeral', 'Flutter-Generated.xcconfig'), __FILE__) + unless File.exist?(generated_xcode_build_settings_path) + raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure \"flutter pub get\" is executed first" + end + + File.foreach(generated_xcode_build_settings_path) do |line| + matches = line.match(/FLUTTER_ROOT\=(.*)/) + return matches[1].strip if matches + end + raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Flutter-Generated.xcconfig, then run \"flutter pub get\"" +end + +require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) + +flutter_macos_podfile_setup + +target 'Runner' do + use_frameworks! + use_modular_headers! + + flutter_install_all_macos_pods File.dirname(File.realpath(__FILE__)) +end + +post_install do |installer| + installer.pods_project.targets.each do |target| + flutter_additional_macos_build_settings(target) + end +end diff --git a/app_flowy/packages/flowy_infra_ui/example/macos/Runner.xcodeproj/project.pbxproj b/app_flowy/packages/flowy_infra_ui/example/macos/Runner.xcodeproj/project.pbxproj index cc89c87828..547137744c 100644 --- a/app_flowy/packages/flowy_infra_ui/example/macos/Runner.xcodeproj/project.pbxproj +++ b/app_flowy/packages/flowy_infra_ui/example/macos/Runner.xcodeproj/project.pbxproj @@ -54,7 +54,7 @@ /* Begin PBXFileReference section */ 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; - 33CC10ED2044A3C60003C045 /* example.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "example.app"; sourceTree = BUILT_PRODUCTS_DIR; }; + 33CC10ED2044A3C60003C045 /* flowy_infra_ui_example.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "flowy_infra_ui_example.app"; sourceTree = BUILT_PRODUCTS_DIR; }; 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = ""; }; 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; @@ -105,7 +105,7 @@ 33CC10EE2044A3C60003C045 /* Products */ = { isa = PBXGroup; children = ( - 33CC10ED2044A3C60003C045 /* example.app */, + 33CC10ED2044A3C60003C045 /* flowy_infra_ui_example.app */, ); name = Products; sourceTree = ""; @@ -172,7 +172,7 @@ ); name = Runner; productName = Runner; - productReference = 33CC10ED2044A3C60003C045 /* example.app */; + productReference = 33CC10ED2044A3C60003C045 /* flowy_infra_ui_example.app */; productType = "com.apple.product-type.application"; }; /* End PBXNativeTarget section */ diff --git a/app_flowy/packages/flowy_infra_ui/example/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/app_flowy/packages/flowy_infra_ui/example/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index ae8ff59d97..9420dfd1a6 100644 --- a/app_flowy/packages/flowy_infra_ui/example/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/app_flowy/packages/flowy_infra_ui/example/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -15,7 +15,7 @@ @@ -31,7 +31,7 @@ @@ -54,7 +54,7 @@ @@ -73,7 +73,7 @@ diff --git a/app_flowy/packages/flowy_infra_ui/example/macos/Runner/Configs/AppInfo.xcconfig b/app_flowy/packages/flowy_infra_ui/example/macos/Runner/Configs/AppInfo.xcconfig index cf9be60ca4..76ad650b99 100644 --- a/app_flowy/packages/flowy_infra_ui/example/macos/Runner/Configs/AppInfo.xcconfig +++ b/app_flowy/packages/flowy_infra_ui/example/macos/Runner/Configs/AppInfo.xcconfig @@ -5,10 +5,10 @@ // 'flutter create' template. // The application's name. By default this is also the title of the Flutter window. -PRODUCT_NAME = example +PRODUCT_NAME = flowy_infra_ui_example // The application's bundle identifier -PRODUCT_BUNDLE_IDENTIFIER = com.example.example +PRODUCT_BUNDLE_IDENTIFIER = com.example.flowyInfraUiExample // The copyright displayed in application information PRODUCT_COPYRIGHT = Copyright © 2021 com.example. All rights reserved. diff --git a/app_flowy/packages/flowy_infra_ui/example/pubspec.lock b/app_flowy/packages/flowy_infra_ui/example/pubspec.lock index 510052ef08..c05870c42c 100644 --- a/app_flowy/packages/flowy_infra_ui/example/pubspec.lock +++ b/app_flowy/packages/flowy_infra_ui/example/pubspec.lock @@ -116,6 +116,18 @@ packages: description: flutter source: sdk version: "0.0.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + js: + dependency: transitive + description: + name: js + url: "https://pub.dartlang.org" + source: hosted + version: "0.6.3" lint: dependency: transitive description: @@ -263,4 +275,4 @@ packages: version: "2.1.0" sdks: dart: ">=2.12.0 <3.0.0" - flutter: ">=1.17.0" + flutter: ">=1.20.0" diff --git a/app_flowy/packages/flowy_infra_ui/example/pubspec.yaml b/app_flowy/packages/flowy_infra_ui/example/pubspec.yaml index 3440f8d831..901200091e 100644 --- a/app_flowy/packages/flowy_infra_ui/example/pubspec.yaml +++ b/app_flowy/packages/flowy_infra_ui/example/pubspec.yaml @@ -1,8 +1,7 @@ -name: example -description: A new Flutter project. +name: flowy_infra_ui_example +description: Demonstrates how to use the flowy_infra_ui plugin. -publish_to: 'none' -version: 1.0.0+1 +publish_to: 'none' # Remove this line if you wish to publish to pub.dev environment: sdk: ">=2.12.0 <3.0.0" @@ -11,59 +10,17 @@ dependencies: flutter: sdk: flutter - cupertino_icons: ^1.0.2 flowy_infra_ui: path: ../ + cupertino_icons: ^1.0.2 + dev_dependencies: flutter_test: sdk: flutter - # The "flutter_lints" package below contains a set of recommended lints to - # encourage good coding practices. The lint set provided by the package is - # activated in the `analysis_options.yaml` file located at the root of your - # package. See that file for information about deactivating specific lint - # rules and activating additional ones. flutter_lints: ^1.0.0 -# For information on the generic Dart part of this file, see the -# following page: https://dart.dev/tools/pub/pubspec - -# The following section is specific to Flutter. flutter: - # The following line ensures that the Material Icons font is - # included with your application, so that you can use the icons in - # the material Icons class. - uses-material-design: true - - # To add assets to your application, add an assets section, like this: - # assets: - # - images/a_dot_burr.jpeg - # - images/a_dot_ham.jpeg - - # An image asset can refer to one or more resolution-specific "variants", see - # https://flutter.dev/assets-and-images/#resolution-aware. - - # For details regarding adding assets from package dependencies, see - # https://flutter.dev/assets-and-images/#from-packages - - # To add custom fonts to your application, add a fonts section here, - # in this "flutter" section. Each entry in this list should have a - # "family" key with the font family name, and a "fonts" key with a - # list giving the asset and other descriptors for the font. For - # example: - # fonts: - # - family: Schyler - # fonts: - # - asset: fonts/Schyler-Regular.ttf - # - asset: fonts/Schyler-Italic.ttf - # style: italic - # - family: Trajan Pro - # fonts: - # - asset: fonts/TrajanPro.ttf - # - asset: fonts/TrajanPro_Bold.ttf - # weight: 700 - # - # For details regarding fonts from package dependencies, - # see https://flutter.dev/custom-fonts/#from-packages + uses-material-design: true \ No newline at end of file diff --git a/app_flowy/packages/flowy_infra_ui/example/test/widget_test.dart b/app_flowy/packages/flowy_infra_ui/example/test/widget_test.dart index ceaa592386..1d7ea5f43e 100644 --- a/app_flowy/packages/flowy_infra_ui/example/test/widget_test.dart +++ b/app_flowy/packages/flowy_infra_ui/example/test/widget_test.dart @@ -8,23 +8,20 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:example/main.dart'; +import 'package:flowy_infra_ui_example/main.dart'; void main() { - testWidgets('Counter increments smoke test', (WidgetTester tester) async { + testWidgets('Verify Platform version', (WidgetTester tester) async { // Build our app and trigger a frame. - await tester.pumpWidget(const ExampleApp()); + await tester.pumpWidget(const MyApp()); - // Verify that our counter starts at 0. - expect(find.text('0'), findsOneWidget); - expect(find.text('1'), findsNothing); - - // Tap the '+' icon and trigger a frame. - await tester.tap(find.byIcon(Icons.add)); - await tester.pump(); - - // Verify that our counter has incremented. - expect(find.text('0'), findsNothing); - expect(find.text('1'), findsOneWidget); + // Verify that platform version is retrieved. + expect( + find.byWidgetPredicate( + (Widget widget) => widget is Text && + widget.data!.startsWith('Running on:'), + ), + findsOneWidget, + ); }); } diff --git a/app_flowy/packages/flowy_infra_ui/example/web/index.html b/app_flowy/packages/flowy_infra_ui/example/web/index.html index eed169dc70..dda953d8dd 100644 --- a/app_flowy/packages/flowy_infra_ui/example/web/index.html +++ b/app_flowy/packages/flowy_infra_ui/example/web/index.html @@ -18,15 +18,15 @@ - + - + - example + flowy_infra_ui_example diff --git a/app_flowy/packages/flowy_infra_ui/example/web/manifest.json b/app_flowy/packages/flowy_infra_ui/example/web/manifest.json index 8c012917da..5c3b6fad3c 100644 --- a/app_flowy/packages/flowy_infra_ui/example/web/manifest.json +++ b/app_flowy/packages/flowy_infra_ui/example/web/manifest.json @@ -1,11 +1,11 @@ { - "name": "example", - "short_name": "example", + "name": "flowy_infra_ui_example", + "short_name": "flowy_infra_ui_example", "start_url": ".", "display": "standalone", "background_color": "#0175C2", "theme_color": "#0175C2", - "description": "A new Flutter project.", + "description": "Demonstrates how to use the flowy_infra_ui plugin.", "orientation": "portrait-primary", "prefer_related_applications": false, "icons": [ diff --git a/app_flowy/packages/flowy_infra_ui/example/windows/.gitignore b/app_flowy/packages/flowy_infra_ui/example/windows/.gitignore new file mode 100644 index 0000000000..d492d0d98c --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/example/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/app_flowy/packages/flowy_infra_ui/example/windows/CMakeLists.txt b/app_flowy/packages/flowy_infra_ui/example/windows/CMakeLists.txt new file mode 100644 index 0000000000..50d22a91d1 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/example/windows/CMakeLists.txt @@ -0,0 +1,95 @@ +cmake_minimum_required(VERSION 3.15) +project(flowy_infra_ui_example LANGUAGES CXX) + +set(BINARY_NAME "flowy_infra_ui_example") + +cmake_policy(SET CMP0063 NEW) + +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Configure build options. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() + +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") + +# Flutter library and tool build rules. +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build +add_subdirectory("runner") + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/app_flowy/packages/flowy_infra_ui/example/windows/flutter/CMakeLists.txt b/app_flowy/packages/flowy_infra_ui/example/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000000..b02c5485c9 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/example/windows/flutter/CMakeLists.txt @@ -0,0 +1,103 @@ +cmake_minimum_required(VERSION 3.15) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + windows-x64 $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/app_flowy/packages/flowy_infra_ui/example/windows/flutter/generated_plugin_registrant.cc b/app_flowy/packages/flowy_infra_ui/example/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000000..eb5983d9f8 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/example/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,12 @@ +// +// Generated file. Do not edit. +// + +#include "generated_plugin_registrant.h" + +#include + +void RegisterPlugins(flutter::PluginRegistry* registry) { + FlowyInfraUiPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FlowyInfraUiPlugin")); +} diff --git a/app_flowy/packages/flowy_infra_ui/example/windows/flutter/generated_plugin_registrant.h b/app_flowy/packages/flowy_infra_ui/example/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000000..9846246b4d --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/example/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,13 @@ +// +// Generated file. Do not edit. +// + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/app_flowy/packages/flowy_infra_ui/example/windows/flutter/generated_plugins.cmake b/app_flowy/packages/flowy_infra_ui/example/windows/flutter/generated_plugins.cmake new file mode 100644 index 0000000000..c82a15ca3f --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/example/windows/flutter/generated_plugins.cmake @@ -0,0 +1,16 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + flowy_infra_ui +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) diff --git a/app_flowy/packages/flowy_infra_ui/example/windows/runner/CMakeLists.txt b/app_flowy/packages/flowy_infra_ui/example/windows/runner/CMakeLists.txt new file mode 100644 index 0000000000..0b899a0bcf --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/example/windows/runner/CMakeLists.txt @@ -0,0 +1,17 @@ +cmake_minimum_required(VERSION 3.15) +project(runner LANGUAGES CXX) + +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) +apply_standard_settings(${BINARY_NAME}) +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/app_flowy/packages/flowy_infra_ui/example/windows/runner/Runner.rc b/app_flowy/packages/flowy_infra_ui/example/windows/runner/Runner.rc new file mode 100644 index 0000000000..7db52c01ae --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/example/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#ifdef FLUTTER_BUILD_NUMBER +#define VERSION_AS_NUMBER FLUTTER_BUILD_NUMBER +#else +#define VERSION_AS_NUMBER 1,0,0 +#endif + +#ifdef FLUTTER_BUILD_NAME +#define VERSION_AS_STRING #FLUTTER_BUILD_NAME +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "com.example" "\0" + VALUE "FileDescription", "Demonstrates how to use the flowy_infra_ui plugin." "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "flowy_infra_ui_example" "\0" + VALUE "LegalCopyright", "Copyright (C) 2021 com.example. All rights reserved." "\0" + VALUE "OriginalFilename", "flowy_infra_ui_example.exe" "\0" + VALUE "ProductName", "flowy_infra_ui_example" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/app_flowy/packages/flowy_infra_ui/example/windows/runner/flutter_window.cpp b/app_flowy/packages/flowy_infra_ui/example/windows/runner/flutter_window.cpp new file mode 100644 index 0000000000..b43b9095ea --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/example/windows/runner/flutter_window.cpp @@ -0,0 +1,61 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/app_flowy/packages/flowy_infra_ui/example/windows/runner/flutter_window.h b/app_flowy/packages/flowy_infra_ui/example/windows/runner/flutter_window.h new file mode 100644 index 0000000000..6da0652f05 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/example/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/app_flowy/packages/flowy_infra_ui/example/windows/runner/main.cpp b/app_flowy/packages/flowy_infra_ui/example/windows/runner/main.cpp new file mode 100644 index 0000000000..a1b7c151e3 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/example/windows/runner/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.CreateAndShow(L"flowy_infra_ui_example", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/app_flowy/packages/flowy_infra_ui/example/windows/runner/resource.h b/app_flowy/packages/flowy_infra_ui/example/windows/runner/resource.h new file mode 100644 index 0000000000..66a65d1e4a --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/example/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/app_flowy/packages/flowy_infra_ui/example/windows/runner/resources/app_icon.ico b/app_flowy/packages/flowy_infra_ui/example/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000000000000000000000000000000000000..c04e20caf6370ebb9253ad831cc31de4a9c965f6 GIT binary patch literal 33772 zcmeHQc|26z|35SKE&G-*mXah&B~fFkXr)DEO&hIfqby^T&>|8^_Ub8Vp#`BLl3lbZ zvPO!8k!2X>cg~Elr=IVxo~J*a`+9wR=A83c-k-DFd(XM&UI1VKCqM@V;DDtJ09WB} zRaHKiW(GT00brH|0EeTeKVbpbGZg?nK6-j827q-+NFM34gXjqWxJ*a#{b_apGN<-L_m3#8Z26atkEn& ze87Bvv^6vVmM+p+cQ~{u%=NJF>#(d;8{7Q{^rWKWNtf14H}>#&y7$lqmY6xmZryI& z($uy?c5-+cPnt2%)R&(KIWEXww>Cnz{OUpT>W$CbO$h1= z#4BPMkFG1Y)x}Ui+WXr?Z!w!t_hjRq8qTaWpu}FH{MsHlU{>;08goVLm{V<&`itk~ zE_Ys=D(hjiy+5=?=$HGii=Y5)jMe9|wWoD_K07(}edAxh`~LBorOJ!Cf@f{_gNCC| z%{*04ViE!#>@hc1t5bb+NO>ncf@@Dv01K!NxH$3Eg1%)|wLyMDF8^d44lV!_Sr}iEWefOaL z8f?ud3Q%Sen39u|%00W<#!E=-RpGa+H8}{ulxVl4mwpjaU+%2pzmi{3HM)%8vb*~-M9rPUAfGCSos8GUXp02|o~0BTV2l#`>>aFV&_P$ejS;nGwSVP8 zMbOaG7<7eKD>c12VdGH;?2@q7535sa7MN*L@&!m?L`ASG%boY7(&L5imY#EQ$KrBB z4@_tfP5m50(T--qv1BJcD&aiH#b-QC>8#7Fx@3yXlonJI#aEIi=8&ChiVpc#N=5le zM*?rDIdcpawoc5kizv$GEjnveyrp3sY>+5_R5;>`>erS%JolimF=A^EIsAK zsPoVyyUHCgf0aYr&alx`<)eb6Be$m&`JYSuBu=p8j%QlNNp$-5C{b4#RubPb|CAIS zGE=9OFLP7?Hgc{?k45)84biT0k&-C6C%Q}aI~q<(7BL`C#<6HyxaR%!dFx7*o^laG z=!GBF^cwK$IA(sn9y6>60Rw{mYRYkp%$jH z*xQM~+bp)G$_RhtFPYx2HTsWk80+p(uqv9@I9)y{b$7NK53rYL$ezbmRjdXS?V}fj zWxX_feWoLFNm3MG7pMUuFPs$qrQWO9!l2B(SIuy2}S|lHNbHzoE+M2|Zxhjq9+Ws8c{*}x^VAib7SbxJ*Q3EnY5lgI9 z=U^f3IW6T=TWaVj+2N%K3<%Un;CF(wUp`TC&Y|ZjyFu6co^uqDDB#EP?DV5v_dw~E zIRK*BoY9y-G_ToU2V_XCX4nJ32~`czdjT!zwme zGgJ0nOk3U4@IE5JwtM}pwimLjk{ln^*4HMU%Fl4~n(cnsLB}Ja-jUM>xIB%aY;Nq8 z)Fp8dv1tkqKanv<68o@cN|%thj$+f;zGSO7H#b+eMAV8xH$hLggtt?O?;oYEgbq@= zV(u9bbd12^%;?nyk6&$GPI%|+<_mEpJGNfl*`!KV;VfmZWw{n{rnZ51?}FDh8we_L z8OI9nE31skDqJ5Oa_ybn7|5@ui>aC`s34p4ZEu6-s!%{uU45$Zd1=p$^^dZBh zu<*pDDPLW+c>iWO$&Z_*{VSQKg7=YEpS3PssPn1U!lSm6eZIho*{@&20e4Y_lRklKDTUCKI%o4Pc<|G^Xgu$J^Q|B87U;`c1zGwf^-zH*VQ^x+i^OUWE0yd z;{FJq)2w!%`x7yg@>uGFFf-XJl4H`YtUG%0slGKOlXV`q?RP>AEWg#x!b{0RicxGhS!3$p7 zij;{gm!_u@D4$Ox%>>bPtLJ> zwKtYz?T_DR1jN>DkkfGU^<#6sGz|~p*I{y`aZ>^Di#TC|Z!7j_O1=Wo8thuit?WxR zh9_S>kw^{V^|g}HRUF=dcq>?q(pHxw!8rx4dC6vbQVmIhmICF#zU!HkHpQ>9S%Uo( zMw{eC+`&pb=GZRou|3;Po1}m46H6NGd$t<2mQh}kaK-WFfmj_66_17BX0|j-E2fe3Jat}ijpc53 zJV$$;PC<5aW`{*^Z6e5##^`Ed#a0nwJDT#Qq~^e8^JTA=z^Kl>La|(UQ!bI@#ge{Dzz@61p-I)kc2?ZxFt^QQ}f%ldLjO*GPj(5)V9IyuUakJX=~GnTgZ4$5!3E=V#t`yOG4U z(gphZB6u2zsj=qNFLYShhg$}lNpO`P9xOSnO*$@@UdMYES*{jJVj|9z-}F^riksLK zbsU+4-{281P9e2UjY6tse^&a)WM1MFw;p#_dHhWI7p&U*9TR0zKdVuQed%6{otTsq z$f~S!;wg#Bd9kez=Br{m|66Wv z#g1xMup<0)H;c2ZO6su_ii&m8j&+jJz4iKnGZ&wxoQX|5a>v&_e#6WA!MB_4asTxLRGQCC5cI(em z%$ZfeqP>!*q5kU>a+BO&ln=4Jm>Ef(QE8o&RgLkk%2}4Tf}U%IFP&uS7}&|Q-)`5< z+e>;s#4cJ-z%&-^&!xsYx777Wt(wZY9(3(avmr|gRe4cD+a8&!LY`1^T?7x{E<=kdY9NYw>A;FtTvQ=Y&1M%lyZPl$ss1oY^Sl8we}n}Aob#6 zl4jERwnt9BlSoWb@3HxYgga(752Vu6Y)k4yk9u~Kw>cA5&LHcrvn1Y-HoIuFWg~}4 zEw4bR`mXZQIyOAzo)FYqg?$5W<;^+XX%Uz61{-L6@eP|lLH%|w?g=rFc;OvEW;^qh z&iYXGhVt(G-q<+_j}CTbPS_=K>RKN0&;dubh0NxJyDOHFF;<1k!{k#7b{|Qok9hac z;gHz}6>H6C6RnB`Tt#oaSrX0p-j-oRJ;_WvS-qS--P*8}V943RT6kou-G=A+7QPGQ z!ze^UGxtW3FC0$|(lY9^L!Lx^?Q8cny(rR`es5U;-xBhphF%_WNu|aO<+e9%6LuZq zt(0PoagJG<%hyuf;te}n+qIl_Ej;czWdc{LX^pS>77s9t*2b4s5dvP_!L^3cwlc)E!(!kGrg~FescVT zZCLeua3f4;d;Tk4iXzt}g}O@nlK3?_o91_~@UMIl?@77Qc$IAlLE95#Z=TES>2E%z zxUKpK{_HvGF;5%Q7n&vA?`{%8ohlYT_?(3A$cZSi)MvIJygXD}TS-3UwyUxGLGiJP znblO~G|*uA^|ac8E-w#}uBtg|s_~s&t>-g0X%zIZ@;o_wNMr_;{KDg^O=rg`fhDZu zFp(VKd1Edj%F zWHPl+)FGj%J1BO3bOHVfH^3d1F{)*PL&sRX`~(-Zy3&9UQX)Z;c51tvaI2E*E7!)q zcz|{vpK7bjxix(k&6=OEIBJC!9lTkUbgg?4-yE{9+pFS)$Ar@vrIf`D0Bnsed(Cf? zObt2CJ>BKOl>q8PyFO6w)+6Iz`LW%T5^R`U_NIW0r1dWv6OY=TVF?N=EfA(k(~7VBW(S;Tu5m4Lg8emDG-(mOSSs=M9Q&N8jc^Y4&9RqIsk(yO_P(mcCr}rCs%1MW1VBrn=0-oQN(Xj!k%iKV zb%ricBF3G4S1;+8lzg5PbZ|$Se$)I=PwiK=cDpHYdov2QO1_a-*dL4KUi|g&oh>(* zq$<`dQ^fat`+VW?m)?_KLn&mp^-@d=&7yGDt<=XwZZC=1scwxO2^RRI7n@g-1o8ps z)&+et_~)vr8aIF1VY1Qrq~Xe``KJrQSnAZ{CSq3yP;V*JC;mmCT6oRLSs7=GA?@6g zUooM}@tKtx(^|aKK8vbaHlUQqwE0}>j&~YlN3H#vKGm@u)xxS?n9XrOWUfCRa< z`20Fld2f&;gg7zpo{Adh+mqNntMc-D$N^yWZAZRI+u1T1zWHPxk{+?vcS1D>08>@6 zLhE@`gt1Y9mAK6Z4p|u(5I%EkfU7rKFSM=E4?VG9tI;a*@?6!ey{lzN5=Y-!$WFSe z&2dtO>^0@V4WRc#L&P%R(?@KfSblMS+N+?xUN$u3K4Ys%OmEh+tq}fnU}i>6YHM?< zlnL2gl~sF!j!Y4E;j3eIU-lfa`RsOL*Tt<%EFC0gPzoHfNWAfKFIKZN8}w~(Yi~=q z>=VNLO2|CjkxP}RkutxjV#4fWYR1KNrPYq5ha9Wl+u>ipsk*I(HS@iLnmGH9MFlTU zaFZ*KSR0px>o+pL7BbhB2EC1%PJ{67_ z#kY&#O4@P=OV#-79y_W>Gv2dxL*@G7%LksNSqgId9v;2xJ zrh8uR!F-eU$NMx@S*+sk=C~Dxr9Qn7TfWnTupuHKuQ$;gGiBcU>GF5sWx(~4IP3`f zWE;YFO*?jGwYh%C3X<>RKHC-DZ!*r;cIr}GLOno^3U4tFSSoJp%oHPiSa%nh=Zgn% z14+8v@ygy0>UgEN1bczD6wK45%M>psM)y^)IfG*>3ItX|TzV*0i%@>L(VN!zdKb8S?Qf7BhjNpziA zR}?={-eu>9JDcl*R=OP9B8N$IcCETXah9SUDhr{yrld{G;PnCWRsPD7!eOOFBTWUQ=LrA_~)mFf&!zJX!Oc-_=kT<}m|K52 z)M=G#;p;Rdb@~h5D{q^K;^fX-m5V}L%!wVC2iZ1uu401Ll}#rocTeK|7FAeBRhNdQ zCc2d^aQnQp=MpOmak60N$OgS}a;p(l9CL`o4r(e-nN}mQ?M&isv-P&d$!8|1D1I(3-z!wi zTgoo)*Mv`gC?~bm?S|@}I|m-E2yqPEvYybiD5azInexpK8?9q*$9Yy9-t%5jU8~ym zgZDx>!@ujQ=|HJnwp^wv-FdD{RtzO9SnyfB{mH_(c!jHL*$>0o-(h(eqe*ZwF6Lvu z{7rkk%PEqaA>o+f{H02tzZ@TWy&su?VNw43! z-X+rN`6llvpUms3ZiSt)JMeztB~>9{J8SPmYs&qohxdYFi!ra8KR$35Zp9oR)eFC4 zE;P31#3V)n`w$fZ|4X-|%MX`xZDM~gJyl2W;O$H25*=+1S#%|53>|LyH za@yh+;325%Gq3;J&a)?%7X%t@WXcWL*BaaR*7UEZad4I8iDt7^R_Fd`XeUo256;sAo2F!HcIQKk;h})QxEsPE5BcKc7WyerTchgKmrfRX z!x#H_%cL#B9TWAqkA4I$R^8{%do3Y*&(;WFmJ zU7Dih{t1<{($VtJRl9|&EB?|cJ)xse!;}>6mSO$o5XIx@V|AA8ZcoD88ZM?C*;{|f zZVmf94_l1OmaICt`2sTyG!$^UeTHx9YuUP!omj(r|7zpm5475|yXI=rR>>fteLI+| z)MoiGho0oEt=*J(;?VY0QzwCqw@cVm?d7Y!z0A@u#H?sCJ*ecvyhj& z-F77lO;SH^dmf?L>3i>?Z*U}Em4ZYV_CjgfvzYsRZ+1B!Uo6H6mbS<-FFL`ytqvb& zE7+)2ahv-~dz(Hs+f})z{*4|{)b=2!RZK;PWwOnO=hG7xG`JU5>bAvUbdYd_CjvtHBHgtGdlO+s^9ca^Bv3`t@VRX2_AD$Ckg36OcQRF zXD6QtGfHdw*hx~V(MV-;;ZZF#dJ-piEF+s27z4X1qi5$!o~xBnvf=uopcn7ftfsZc zy@(PuOk`4GL_n(H9(E2)VUjqRCk9kR?w)v@xO6Jm_Mx})&WGEl=GS0#)0FAq^J*o! zAClhvoTsNP*-b~rN{8Yym3g{01}Ep^^Omf=SKqvN?{Q*C4HNNAcrowIa^mf+3PRy! z*_G-|3i8a;+q;iP@~Of_$(vtFkB8yOyWt2*K)vAn9El>=D;A$CEx6b*XF@4y_6M+2 zpeW`RHoI_p(B{%(&jTHI->hmNmZjHUj<@;7w0mx3&koy!2$@cfX{sN19Y}euYJFn& z1?)+?HCkD0MRI$~uB2UWri})0bru_B;klFdwsLc!ne4YUE;t41JqfG# zZJq6%vbsdx!wYeE<~?>o4V`A3?lN%MnKQ`z=uUivQN^vzJ|C;sdQ37Qn?;lpzg})y z)_2~rUdH}zNwX;Tp0tJ78+&I=IwOQ-fl30R79O8@?Ub8IIA(6I`yHn%lARVL`%b8+ z4$8D-|MZZWxc_)vu6@VZN!HsI$*2NOV&uMxBNzIbRgy%ob_ zhwEH{J9r$!dEix9XM7n&c{S(h>nGm?el;gaX0@|QnzFD@bne`el^CO$yXC?BDJ|Qg z+y$GRoR`?ST1z^e*>;!IS@5Ovb7*RlN>BV_UC!7E_F;N#ky%1J{+iixp(dUJj93aK zzHNN>R-oN7>kykHClPnoPTIj7zc6KM(Pnlb(|s??)SMb)4!sMHU^-ntJwY5Big7xv zb1Ew`Xj;|D2kzGja*C$eS44(d&RMU~c_Y14V9_TLTz0J#uHlsx`S6{nhsA0dWZ#cG zJ?`fO50E>*X4TQLv#nl%3GOk*UkAgt=IY+u0LNXqeln3Z zv$~&Li`ZJOKkFuS)dJRA>)b_Da%Q~axwA_8zNK{BH{#}#m}zGcuckz}riDE-z_Ms> zR8-EqAMcfyGJCtvTpaUVQtajhUS%c@Yj}&6Zz;-M7MZzqv3kA7{SuW$oW#=0az2wQ zg-WG@Vb4|D`pl~Il54N7Hmsauc_ne-a!o5#j3WaBBh@Wuefb!QJIOn5;d)%A#s+5% zuD$H=VNux9bE-}1&bcYGZ+>1Fo;3Z@e&zX^n!?JK*adSbONm$XW9z;Q^L>9U!}Toj2WdafJ%oL#h|yWWwyAGxzfrAWdDTtaKl zK4`5tDpPg5>z$MNv=X0LZ0d6l%D{(D8oT@+w0?ce$DZ6pv>{1&Ok67Ix1 zH}3=IEhPJEhItCC8E=`T`N5(k?G=B4+xzZ?<4!~ ze~z6Wk9!CHTI(0rLJ4{JU?E-puc;xusR?>G?;4vt;q~iI9=kDL=z0Rr%O$vU`30X$ zDZRFyZ`(omOy@u|i6h;wtJlP;+}$|Ak|k2dea7n?U1*$T!sXqqOjq^NxLPMmk~&qI zYg0W?yK8T(6+Ea+$YyspKK?kP$+B`~t3^Pib_`!6xCs32!i@pqXfFV6PmBIR<-QW= zN8L{pt0Vap0x`Gzn#E@zh@H)0FfVfA_Iu4fjYZ+umO1LXIbVc$pY+E234u)ttcrl$ z>s92z4vT%n6cMb>=XT6;l0+9e(|CZG)$@C7t7Z7Ez@a)h)!hyuV&B5K%%)P5?Lk|C zZZSVzdXp{@OXSP0hoU-gF8s8Um(#xzjP2Vem zec#-^JqTa&Y#QJ>-FBxd7tf`XB6e^JPUgagB8iBSEps;92KG`!#mvVcPQ5yNC-GEG zTiHEDYfH+0O15}r^+ z#jxj=@x8iNHWALe!P3R67TwmhItn**0JwnzSV2O&KE8KcT+0hWH^OPD1pwiuyx=b@ zNf5Jh0{9X)8;~Es)$t@%(3!OnbY+`@?i{mGX7Yy}8T_*0a6g;kaFPq;*=px5EhO{Cp%1kI<0?*|h8v!6WnO3cCJRF2-CRrU3JiLJnj@6;L)!0kWYAc_}F{2P))3HmCrz zQ&N&gE70;`!6*eJ4^1IR{f6j4(-l&X!tjHxkbHA^Zhrnhr9g{exN|xrS`5Pq=#Xf& zG%P=#ra-TyVFfgW%cZo5OSIwFL9WtXAlFOa+ubmI5t*3=g#Y zF%;70p5;{ZeFL}&}yOY1N1*Q;*<(kTB!7vM$QokF)yr2FlIU@$Ph58$Bz z0J?xQG=MlS4L6jA22eS42g|9*9pX@$#*sUeM(z+t?hr@r5J&D1rx}2pW&m*_`VDCW zUYY@v-;bAO0HqoAgbbiGGC<=ryf96}3pouhy3XJrX+!!u*O_>Si38V{uJmQ&USptX zKp#l(?>%^7;2%h(q@YWS#9;a!JhKlkR#Vd)ERILlgu!Hr@jA@V;sk4BJ-H#p*4EqC zDGjC*tl=@3Oi6)Bn^QwFpul18fpkbpg0+peH$xyPBqb%`$OUhPKyWb32o7clB*9Z< zN=i~NLjavrLtwgJ01bufP+>p-jR2I95|TpmKpQL2!oV>g(4RvS2pK4*ou%m(h6r3A zX#s&`9LU1ZG&;{CkOK!4fLDTnBys`M!vuz>Q&9OZ0hGQl!~!jSDg|~s*w52opC{sB ze|Cf2luD(*G13LcOAGA!s2FjSK8&IE5#W%J25w!vM0^VyQM!t)inj&RTiJ!wXzFgz z3^IqzB7I0L$llljsGq})thBy9UOyjtFO_*hYM_sgcMk>44jeH0V1FDyELc{S1F-;A zS;T^k^~4biG&V*Irq}O;e}j$$+E_#G?HKIn05iP3j|87TkGK~SqG!-KBg5+mN(aLm z8ybhIM`%C19UX$H$KY6JgXbY$0AT%rEpHC;u`rQ$Y=rxUdsc5*Kvc8jaYaO$^)cI6){P6K0r)I6DY4Wr4&B zLQUBraey#0HV|&c4v7PVo3n$zHj99(TZO^3?Ly%C4nYvJTL9eLBLHsM3WKKD>5!B` zQ=BsR3aR6PD(Fa>327E2HAu5TM~Wusc!)>~(gM)+3~m;92Jd;FnSib=M5d6;;5{%R zb4V7DEJ0V!CP-F*oU?gkc>ksUtAYP&V4ND5J>J2^jt*vcFflQWCrB&fLdT%O59PVJ zhid#toR=FNgD!q3&r8#wEBr`!wzvQu5zX?Q>nlSJ4i@WC*CN*-xU66F^V5crWevQ9gsq$I@z1o(a=k7LL~ z7m_~`o;_Ozha1$8Q}{WBehvAlO4EL60y5}8GDrZ< zXh&F}71JbW2A~8KfEWj&UWV#4+Z4p`b{uAj4&WC zha`}X@3~+Iz^WRlOHU&KngK>#j}+_o@LdBC1H-`gT+krWX3-;!)6?{FBp~%20a}FL zFP9%Emqcwa#(`=G>BBZ0qZDQhmZKJg_g8<=bBFKWr!dyg(YkpE+|R*SGpDVU!+VlU zFC54^DLv}`qa%49T>nNiA9Q7Ips#!Xx90tCU2gvK`(F+GPcL=J^>No{)~we#o@&mUb6c$ zCc*<|NJBk-#+{j9xkQ&ujB zI~`#kN~7W!f*-}wkG~Ld!JqZ@tK}eeSnsS5J1fMFXm|`LJx&}5`@dK3W^7#Wnm+_P zBZkp&j1fa2Y=eIjJ0}gh85jt43kaIXXv?xmo@eHrka!Z|vQv12HN#+!I5E z`(fbuW>gFiJL|uXJ!vKt#z3e3HlVdboH7;e#i3(2<)Fg-I@BR!qY#eof3MFZ&*Y@l zI|KJf&ge@p2Dq09Vu$$Qxb7!}{m-iRk@!)%KL)txi3;~Z4Pb}u@GsW;ELiWeG9V51 znX#}B&4Y2E7-H=OpNE@q{%hFLxwIpBF2t{vPREa8_{linXT;#1vMRWjOzLOP$-hf( z>=?$0;~~PnkqY;~K{EM6Vo-T(0K{A0}VUGmu*hR z{tw3hvBN%N3G3Yw`X5Te+F{J`(3w1s3-+1EbnFQKcrgrX1Jqvs@ADGe%M0s$EbK$$ zK)=y=upBc6SjGYAACCcI=Y*6Fi8_jgwZlLxD26fnQfJmb8^gHRN5(TemhX@0e=vr> zg`W}6U>x6VhoA3DqsGGD9uL1DhB3!OXO=k}59TqD@(0Nb{)Ut_luTioK_>7wjc!5C zIr@w}b`Fez3)0wQfKl&bae7;PcTA7%?f2xucM0G)wt_KO!Ewx>F~;=BI0j=Fb4>pp zv}0R^xM4eti~+^+gE$6b81p(kwzuDti(-K9bc|?+pJEl@H+jSYuxZQV8rl8 zjp@M{#%qItIUFN~KcO9Hed*`$5A-2~pAo~K&<-Q+`9`$CK>rzqAI4w~$F%vs9s{~x zg4BP%Gy*@m?;D6=SRX?888Q6peF@_4Z->8wAH~Cn!R$|Hhq2cIzFYqT_+cDourHbY z0qroxJnrZ4Gh+Ay+F`_c%+KRT>y3qw{)89?=hJ@=KO=@ep)aBJ$c!JHfBMJpsP*3G za7|)VJJ8B;4?n{~ldJF7%jmb`-ftIvNd~ekoufG(`K(3=LNc;HBY& z(lp#q8XAD#cIf}k49zX_i`*fO+#!zKA&%T3j@%)R+#yag067CU%yUEe47>wzGU8^` z1EXFT^@I!{J!F8!X?S6ph8J=gUi5tl93*W>7}_uR<2N2~e}FaG?}KPyugQ=-OGEZs z!GBoyYY+H*ANn4?Z)X4l+7H%`17i5~zRlRIX?t)6_eu=g2Q`3WBhxSUeea+M-S?RL zX9oBGKn%a!H+*hx4d2(I!gsi+@SQK%<{X22M~2tMulJoa)0*+z9=-YO+;DFEm5eE1U9b^B(Z}2^9!Qk`!A$wUE z7$Ar5?NRg2&G!AZqnmE64eh^Anss3i!{}%6@Et+4rr!=}!SBF8eZ2*J3ujCWbl;3; z48H~goPSv(8X61fKKdpP!Z7$88NL^Z?j`!^*I?-P4X^pMxyWz~@$(UeAcTSDd(`vO z{~rc;9|GfMJcApU3k}22a!&)k4{CU!e_ny^Y3cO;tOvOMKEyWz!vG(Kp*;hB?d|R3`2X~=5a6#^o5@qn?J-bI8Ppip{-yG z!k|VcGsq!jF~}7DMr49Wap-s&>o=U^T0!Lcy}!(bhtYsPQy z4|EJe{12QL#=c(suQ89Mhw9<`bui%nx7Nep`C&*M3~vMEACmcRYYRGtANq$F%zh&V zc)cEVeHz*Z1N)L7k-(k3np#{GcDh2Q@ya0YHl*n7fl*ZPAsbU-a94MYYtA#&!c`xGIaV;yzsmrjfieTEtqB_WgZp2*NplHx=$O{M~2#i_vJ{ps-NgK zQsxKK_CBM2PP_je+Xft`(vYfXXgIUr{=PA=7a8`2EHk)Ym2QKIforz# tySWtj{oF3N9@_;i*Fv5S)9x^z=nlWP>jpp-9)52ZmLVA=i*%6g{{fxOO~wEK literal 0 HcmV?d00001 diff --git a/app_flowy/packages/flowy_infra_ui/example/windows/runner/runner.exe.manifest b/app_flowy/packages/flowy_infra_ui/example/windows/runner/runner.exe.manifest new file mode 100644 index 0000000000..c977c4a425 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/example/windows/runner/runner.exe.manifest @@ -0,0 +1,20 @@ + + + + + PerMonitorV2 + + + + + + + + + + + + + + + diff --git a/app_flowy/packages/flowy_infra_ui/example/windows/runner/utils.cpp b/app_flowy/packages/flowy_infra_ui/example/windows/runner/utils.cpp new file mode 100644 index 0000000000..d19bdbbcc3 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/example/windows/runner/utils.cpp @@ -0,0 +1,64 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, nullptr, 0, nullptr, nullptr); + if (target_length == 0) { + return std::string(); + } + std::string utf8_string; + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, utf8_string.data(), + target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/app_flowy/packages/flowy_infra_ui/example/windows/runner/utils.h b/app_flowy/packages/flowy_infra_ui/example/windows/runner/utils.h new file mode 100644 index 0000000000..3879d54755 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/example/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/app_flowy/packages/flowy_infra_ui/example/windows/runner/win32_window.cpp b/app_flowy/packages/flowy_infra_ui/example/windows/runner/win32_window.cpp new file mode 100644 index 0000000000..c10f08dc7d --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/example/windows/runner/win32_window.cpp @@ -0,0 +1,245 @@ +#include "win32_window.h" + +#include + +#include "resource.h" + +namespace { + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + FreeLibrary(user32_module); + } +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::CreateAndShow(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW | WS_VISIBLE, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + return OnCreate(); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} diff --git a/app_flowy/packages/flowy_infra_ui/example/windows/runner/win32_window.h b/app_flowy/packages/flowy_infra_ui/example/windows/runner/win32_window.h new file mode 100644 index 0000000000..17ba431125 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/example/windows/runner/win32_window.h @@ -0,0 +1,98 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates and shows a win32 window with |title| and position and size using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size to will treat the width height passed in to this function + // as logical pixels and scale to appropriate for the default monitor. Returns + // true if the window was created successfully. + bool CreateAndShow(const std::wstring& title, + const Point& origin, + const Size& size); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responsponds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_ diff --git a/app_flowy/packages/flowy_infra_ui/ios/.gitignore b/app_flowy/packages/flowy_infra_ui/ios/.gitignore new file mode 100644 index 0000000000..0c885071e3 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/ios/.gitignore @@ -0,0 +1,38 @@ +.idea/ +.vagrant/ +.sconsign.dblite +.svn/ + +.DS_Store +*.swp +profile + +DerivedData/ +build/ +GeneratedPluginRegistrant.h +GeneratedPluginRegistrant.m + +.generated/ + +*.pbxuser +*.mode1v3 +*.mode2v3 +*.perspectivev3 + +!default.pbxuser +!default.mode1v3 +!default.mode2v3 +!default.perspectivev3 + +xcuserdata + +*.moved-aside + +*.pyc +*sync/ +Icon? +.tags* + +/Flutter/Generated.xcconfig +/Flutter/ephemeral/ +/Flutter/flutter_export_environment.sh \ No newline at end of file diff --git a/app_flowy/packages/flowy_infra_ui/ios/Assets/.gitkeep b/app_flowy/packages/flowy_infra_ui/ios/Assets/.gitkeep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/app_flowy/packages/flowy_infra_ui/ios/Classes/FlowyInfraUiPlugin.h b/app_flowy/packages/flowy_infra_ui/ios/Classes/FlowyInfraUiPlugin.h new file mode 100644 index 0000000000..9f353812ba --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/ios/Classes/FlowyInfraUiPlugin.h @@ -0,0 +1,4 @@ +#import + +@interface FlowyInfraUiPlugin : NSObject +@end diff --git a/app_flowy/packages/flowy_infra_ui/ios/Classes/FlowyInfraUiPlugin.m b/app_flowy/packages/flowy_infra_ui/ios/Classes/FlowyInfraUiPlugin.m new file mode 100644 index 0000000000..6609bdcf24 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/ios/Classes/FlowyInfraUiPlugin.m @@ -0,0 +1,15 @@ +#import "FlowyInfraUiPlugin.h" +#if __has_include() +#import +#else +// Support project import fallback if the generated compatibility header +// is not copied when this plugin is created as a library. +// https://forums.swift.org/t/swift-static-libraries-dont-copy-generated-objective-c-header/19816 +#import "flowy_infra_ui-Swift.h" +#endif + +@implementation FlowyInfraUiPlugin ++ (void)registerWithRegistrar:(NSObject*)registrar { + [SwiftFlowyInfraUiPlugin registerWithRegistrar:registrar]; +} +@end diff --git a/app_flowy/packages/flowy_infra_ui/ios/Classes/SwiftFlowyInfraUiPlugin.swift b/app_flowy/packages/flowy_infra_ui/ios/Classes/SwiftFlowyInfraUiPlugin.swift new file mode 100644 index 0000000000..5459739470 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/ios/Classes/SwiftFlowyInfraUiPlugin.swift @@ -0,0 +1,14 @@ +import Flutter +import UIKit + +public class SwiftFlowyInfraUiPlugin: NSObject, FlutterPlugin { + public static func register(with registrar: FlutterPluginRegistrar) { + let channel = FlutterMethodChannel(name: "flowy_infra_ui", binaryMessenger: registrar.messenger()) + let instance = SwiftFlowyInfraUiPlugin() + registrar.addMethodCallDelegate(instance, channel: channel) + } + + public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { + result("iOS " + UIDevice.current.systemVersion) + } +} diff --git a/app_flowy/packages/flowy_infra_ui/ios/flowy_infra_ui.podspec b/app_flowy/packages/flowy_infra_ui/ios/flowy_infra_ui.podspec new file mode 100644 index 0000000000..767ae7c3cd --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/ios/flowy_infra_ui.podspec @@ -0,0 +1,23 @@ +# +# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html. +# Run `pod lib lint flowy_infra_ui.podspec` to validate before publishing. +# +Pod::Spec.new do |s| + s.name = 'flowy_infra_ui' + s.version = '0.0.1' + s.summary = 'A new flutter plugin project.' + s.description = <<-DESC +A new flutter plugin project. + DESC + s.homepage = 'http://example.com' + s.license = { :file => '../LICENSE' } + s.author = { 'Your Company' => 'email@example.com' } + s.source = { :path => '.' } + s.source_files = 'Classes/**/*' + s.dependency 'Flutter' + s.platform = :ios, '8.0' + + # Flutter.framework does not contain a i386 slice. + s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386' } + s.swift_version = '5.0' +end diff --git a/app_flowy/packages/flowy_infra_ui/lib/flowy_infra_ui.dart b/app_flowy/packages/flowy_infra_ui/lib/flowy_infra_ui.dart new file mode 100644 index 0000000000..2efe27d245 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/lib/flowy_infra_ui.dart @@ -0,0 +1,13 @@ + +import 'dart:async'; + +import 'package:flutter/services.dart'; + +class FlowyInfraUi { + static const MethodChannel _channel = MethodChannel('flowy_infra_ui'); + + static Future get platformVersion async { + final String? version = await _channel.invokeMethod('getPlatformVersion'); + return version; + } +} diff --git a/app_flowy/packages/flowy_infra_ui/lib/flowy_infra_ui_web.dart b/app_flowy/packages/flowy_infra_ui/lib/flowy_infra_ui_web.dart new file mode 100644 index 0000000000..f9d9035149 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/lib/flowy_infra_ui_web.dart @@ -0,0 +1,44 @@ +import 'dart:async'; +// In order to *not* need this ignore, consider extracting the "web" version +// of your plugin as a separate package, instead of inlining it in the same +// package as the core of your plugin. +// ignore: avoid_web_libraries_in_flutter +import 'dart:html' as html show window; + +import 'package:flutter/services.dart'; +import 'package:flutter_web_plugins/flutter_web_plugins.dart'; + +/// A web implementation of the FlowyInfraUi plugin. +class FlowyInfraUiWeb { + static void registerWith(Registrar registrar) { + final MethodChannel channel = MethodChannel( + 'flowy_infra_ui', + const StandardMethodCodec(), + registrar, + ); + + final pluginInstance = FlowyInfraUiWeb(); + channel.setMethodCallHandler(pluginInstance.handleMethodCall); + } + + /// Handles method calls over the MethodChannel of this plugin. + /// Note: Check the "federated" architecture for a new way of doing this: + /// https://flutter.dev/go/federated-plugins + Future handleMethodCall(MethodCall call) async { + switch (call.method) { + case 'getPlatformVersion': + return getPlatformVersion(); + default: + throw PlatformException( + code: 'Unimplemented', + details: 'flowy_infra_ui for web doesn\'t implement \'${call.method}\'', + ); + } + } + + /// Returns a [String] containing the version of the platform. + Future getPlatformVersion() { + final version = html.window.navigator.userAgent; + return Future.value(version); + } +} diff --git a/app_flowy/packages/flowy_infra_ui/macos/Classes/FlowyInfraUiPlugin.swift b/app_flowy/packages/flowy_infra_ui/macos/Classes/FlowyInfraUiPlugin.swift new file mode 100644 index 0000000000..b0fcc26b21 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/macos/Classes/FlowyInfraUiPlugin.swift @@ -0,0 +1,19 @@ +import Cocoa +import FlutterMacOS + +public class FlowyInfraUiPlugin: NSObject, FlutterPlugin { + public static func register(with registrar: FlutterPluginRegistrar) { + let channel = FlutterMethodChannel(name: "flowy_infra_ui", binaryMessenger: registrar.messenger) + let instance = FlowyInfraUiPlugin() + registrar.addMethodCallDelegate(instance, channel: channel) + } + + public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { + switch call.method { + case "getPlatformVersion": + result("macOS " + ProcessInfo.processInfo.operatingSystemVersionString) + default: + result(FlutterMethodNotImplemented) + } + } +} diff --git a/app_flowy/packages/flowy_infra_ui/macos/flowy_infra_ui.podspec b/app_flowy/packages/flowy_infra_ui/macos/flowy_infra_ui.podspec new file mode 100644 index 0000000000..2dd79403f1 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/macos/flowy_infra_ui.podspec @@ -0,0 +1,22 @@ +# +# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html. +# Run `pod lib lint flowy_infra_ui.podspec` to validate before publishing. +# +Pod::Spec.new do |s| + s.name = 'flowy_infra_ui' + s.version = '0.0.1' + s.summary = 'A new flutter plugin project.' + s.description = <<-DESC +A new flutter plugin project. + DESC + s.homepage = 'http://example.com' + s.license = { :file => '../LICENSE' } + s.author = { 'Your Company' => 'email@example.com' } + s.source = { :path => '.' } + s.source_files = 'Classes/**/*' + s.dependency 'FlutterMacOS' + + s.platform = :osx, '10.11' + s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' } + s.swift_version = '5.0' +end diff --git a/app_flowy/packages/flowy_infra_ui/pubspec.lock b/app_flowy/packages/flowy_infra_ui/pubspec.lock index 87940a591f..cff84ae06e 100644 --- a/app_flowy/packages/flowy_infra_ui/pubspec.lock +++ b/app_flowy/packages/flowy_infra_ui/pubspec.lock @@ -102,6 +102,18 @@ packages: description: flutter source: sdk version: "0.0.0" + flutter_web_plugins: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + js: + dependency: transitive + description: + name: js + url: "https://pub.dartlang.org" + source: hosted + version: "0.6.3" lint: dependency: transitive description: @@ -249,4 +261,4 @@ packages: version: "2.1.0" sdks: dart: ">=2.12.0 <3.0.0" - flutter: ">=1.17.0" + flutter: ">=1.20.0" diff --git a/app_flowy/packages/flowy_infra_ui/pubspec.yaml b/app_flowy/packages/flowy_infra_ui/pubspec.yaml index bc7007349b..d1af8afe3d 100644 --- a/app_flowy/packages/flowy_infra_ui/pubspec.yaml +++ b/app_flowy/packages/flowy_infra_ui/pubspec.yaml @@ -1,22 +1,26 @@ name: flowy_infra_ui -description: A new Flutter package project. +description: A new flutter plugin project. version: 0.0.1 homepage: publish_to: 'none' environment: sdk: ">=2.12.0 <3.0.0" - flutter: ">=1.17.0" + flutter: ">=1.20.0" dependencies: flutter: sdk: flutter + flutter_web_plugins: + sdk: flutter + # Thirdparty packages textstyle_extensions: '2.0.0-nullsafety' dartz: '0.10.0-nullsafety.2' provider: ^5.0.0 styled_widget: '>=0.3.1' equatable: '>=2.0.2' animations: ^2.0.0 + # Flowy packages flowy_infra: path: ../flowy_infra @@ -24,41 +28,19 @@ dev_dependencies: flutter_test: sdk: flutter flutter_lints: ^1.0.0 - -# For information on the generic Dart part of this file, see the -# following page: https://dart.dev/tools/pub/pubspec - -# The following section is specific to Flutter. flutter: - - # To add assets to your package, add an assets section, like this: - # assets: - # - images/a_dot_burr.jpeg - # - images/a_dot_ham.jpeg - # - # For details regarding assets in packages, see - # https://flutter.dev/assets-and-images/#from-packages - # - # An image asset can refer to one or more resolution-specific "variants", see - # https://flutter.dev/assets-and-images/#resolution-aware. - - # To add custom fonts to your package, add a fonts section here, - # in this "flutter" section. Each entry in this list should have a - # "family" key with the font family name, and a "fonts" key with a - # list giving the asset and other descriptors for the font. For - # example: - # fonts: - # - family: Schyler - # fonts: - # - asset: fonts/Schyler-Regular.ttf - # - asset: fonts/Schyler-Italic.ttf - # style: italic - # - family: Trajan Pro - # fonts: - # - asset: fonts/TrajanPro.ttf - # - asset: fonts/TrajanPro_Bold.ttf - # weight: 700 - # - # For details regarding fonts in packages, see - # https://flutter.dev/custom-fonts/#from-packages + plugin: + platforms: + android: + package: com.example.flowy_infra_ui + pluginClass: FlowyInfraUiPlugin + ios: + pluginClass: FlowyInfraUiPlugin + macos: + pluginClass: FlowyInfraUiPlugin + windows: + pluginClass: FlowyInfraUiPlugin + web: + pluginClass: FlowyInfraUiWeb + fileName: flowy_infra_ui_web.dart \ No newline at end of file diff --git a/app_flowy/packages/flowy_infra_ui/test/flowy_infra_ui_test.dart b/app_flowy/packages/flowy_infra_ui/test/flowy_infra_ui_test.dart new file mode 100644 index 0000000000..c7e2a4cf99 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/test/flowy_infra_ui_test.dart @@ -0,0 +1,23 @@ +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:flowy_infra_ui/flowy_infra_ui.dart'; + +void main() { + const MethodChannel channel = MethodChannel('flowy_infra_ui'); + + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() { + channel.setMockMethodCallHandler((MethodCall methodCall) async { + return '42'; + }); + }); + + tearDown(() { + channel.setMockMethodCallHandler(null); + }); + + test('getPlatformVersion', () async { + expect(await FlowyInfraUi.platformVersion, '42'); + }); +} diff --git a/app_flowy/packages/flowy_infra_ui/test/flowy_ui_test.dart b/app_flowy/packages/flowy_infra_ui/test/flowy_ui_test.dart deleted file mode 100644 index 8b13789179..0000000000 --- a/app_flowy/packages/flowy_infra_ui/test/flowy_ui_test.dart +++ /dev/null @@ -1 +0,0 @@ - diff --git a/app_flowy/packages/flowy_infra_ui/windows/.gitignore b/app_flowy/packages/flowy_infra_ui/windows/.gitignore new file mode 100644 index 0000000000..b3eb2be169 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/app_flowy/packages/flowy_infra_ui/windows/CMakeLists.txt b/app_flowy/packages/flowy_infra_ui/windows/CMakeLists.txt new file mode 100644 index 0000000000..27ce69d238 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/windows/CMakeLists.txt @@ -0,0 +1,24 @@ +cmake_minimum_required(VERSION 3.15) +set(PROJECT_NAME "flowy_infra_ui") +project(${PROJECT_NAME} LANGUAGES CXX) + +# This value is used when generating builds using this plugin, so it must +# not be changed +set(PLUGIN_NAME "flowy_infra_ui_plugin") + +add_library(${PLUGIN_NAME} SHARED + "flowy_infra_ui_plugin.cpp" +) +apply_standard_settings(${PLUGIN_NAME}) +set_target_properties(${PLUGIN_NAME} PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL) +target_include_directories(${PLUGIN_NAME} INTERFACE + "${CMAKE_CURRENT_SOURCE_DIR}/include") +target_link_libraries(${PLUGIN_NAME} PRIVATE flutter flutter_wrapper_plugin) + +# List of absolute paths to libraries that should be bundled with the plugin +set(flowy_infra_ui_bundled_libraries + "" + PARENT_SCOPE +) diff --git a/app_flowy/packages/flowy_infra_ui/windows/flowy_infra_ui_plugin.cpp b/app_flowy/packages/flowy_infra_ui/windows/flowy_infra_ui_plugin.cpp new file mode 100644 index 0000000000..f4329eacf4 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/windows/flowy_infra_ui_plugin.cpp @@ -0,0 +1,82 @@ +#include "include/flowy_infra_ui/flowy_infra_ui_plugin.h" + +// This must be included before many other Windows headers. +#include + +// For getPlatformVersion; remove unless needed for your plugin implementation. +#include + +#include +#include +#include + +#include +#include +#include + +namespace { + +class FlowyInfraUiPlugin : public flutter::Plugin { + public: + static void RegisterWithRegistrar(flutter::PluginRegistrarWindows *registrar); + + FlowyInfraUiPlugin(); + + virtual ~FlowyInfraUiPlugin(); + + private: + // Called when a method is called on this plugin's channel from Dart. + void HandleMethodCall( + const flutter::MethodCall &method_call, + std::unique_ptr> result); +}; + +// static +void FlowyInfraUiPlugin::RegisterWithRegistrar( + flutter::PluginRegistrarWindows *registrar) { + auto channel = + std::make_unique>( + registrar->messenger(), "flowy_infra_ui", + &flutter::StandardMethodCodec::GetInstance()); + + auto plugin = std::make_unique(); + + channel->SetMethodCallHandler( + [plugin_pointer = plugin.get()](const auto &call, auto result) { + plugin_pointer->HandleMethodCall(call, std::move(result)); + }); + + registrar->AddPlugin(std::move(plugin)); +} + +FlowyInfraUiPlugin::FlowyInfraUiPlugin() {} + +FlowyInfraUiPlugin::~FlowyInfraUiPlugin() {} + +void FlowyInfraUiPlugin::HandleMethodCall( + const flutter::MethodCall &method_call, + std::unique_ptr> result) { + if (method_call.method_name().compare("getPlatformVersion") == 0) { + std::ostringstream version_stream; + version_stream << "Windows "; + if (IsWindows10OrGreater()) { + version_stream << "10+"; + } else if (IsWindows8OrGreater()) { + version_stream << "8"; + } else if (IsWindows7OrGreater()) { + version_stream << "7"; + } + result->Success(flutter::EncodableValue(version_stream.str())); + } else { + result->NotImplemented(); + } +} + +} // namespace + +void FlowyInfraUiPluginRegisterWithRegistrar( + FlutterDesktopPluginRegistrarRef registrar) { + FlowyInfraUiPlugin::RegisterWithRegistrar( + flutter::PluginRegistrarManager::GetInstance() + ->GetRegistrar(registrar)); +} diff --git a/app_flowy/packages/flowy_infra_ui/windows/include/flowy_infra_ui/flowy_infra_ui_plugin.h b/app_flowy/packages/flowy_infra_ui/windows/include/flowy_infra_ui/flowy_infra_ui_plugin.h new file mode 100644 index 0000000000..cdd90185ab --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/windows/include/flowy_infra_ui/flowy_infra_ui_plugin.h @@ -0,0 +1,23 @@ +#ifndef FLUTTER_PLUGIN_FLOWY_INFRA_UI_PLUGIN_H_ +#define FLUTTER_PLUGIN_FLOWY_INFRA_UI_PLUGIN_H_ + +#include + +#ifdef FLUTTER_PLUGIN_IMPL +#define FLUTTER_PLUGIN_EXPORT __declspec(dllexport) +#else +#define FLUTTER_PLUGIN_EXPORT __declspec(dllimport) +#endif + +#if defined(__cplusplus) +extern "C" { +#endif + +FLUTTER_PLUGIN_EXPORT void FlowyInfraUiPluginRegisterWithRegistrar( + FlutterDesktopPluginRegistrarRef registrar); + +#if defined(__cplusplus) +} // extern "C" +#endif + +#endif // FLUTTER_PLUGIN_FLOWY_INFRA_UI_PLUGIN_H_ From ffc4a67e2e053dc016ad21aa498d80eafdb4cb76 Mon Sep 17 00:00:00 2001 From: appflowy Date: Sat, 17 Jul 2021 07:46:16 +0800 Subject: [PATCH 03/30] fix flutter warnings --- app_flowy/macos/Flutter/GeneratedPluginRegistrant.swift | 2 ++ app_flowy/packages/flowy_infra_ui/example/lib/main.dart | 2 +- app_flowy/packages/flowy_infra_ui/example/pubspec.lock | 8 ++++---- .../packages/flowy_infra_ui/example/test/widget_test.dart | 6 +++--- app_flowy/packages/flowy_infra_ui/pubspec.lock | 8 ++++---- 5 files changed, 14 insertions(+), 12 deletions(-) diff --git a/app_flowy/macos/Flutter/GeneratedPluginRegistrant.swift b/app_flowy/macos/Flutter/GeneratedPluginRegistrant.swift index dc3b203eab..277667927e 100644 --- a/app_flowy/macos/Flutter/GeneratedPluginRegistrant.swift +++ b/app_flowy/macos/Flutter/GeneratedPluginRegistrant.swift @@ -6,6 +6,7 @@ import FlutterMacOS import Foundation import flowy_editor +import flowy_infra_ui import flowy_sdk import path_provider_macos import url_launcher_macos @@ -13,6 +14,7 @@ import window_size func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { FlowyEditorPlugin.register(with: registry.registrar(forPlugin: "FlowyEditorPlugin")) + FlowyInfraUiPlugin.register(with: registry.registrar(forPlugin: "FlowyInfraUiPlugin")) FlowySdkPlugin.register(with: registry.registrar(forPlugin: "FlowySdkPlugin")) PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin")) UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin")) diff --git a/app_flowy/packages/flowy_infra_ui/example/lib/main.dart b/app_flowy/packages/flowy_infra_ui/example/lib/main.dart index b31b2dcf48..9cc621647d 100644 --- a/app_flowy/packages/flowy_infra_ui/example/lib/main.dart +++ b/app_flowy/packages/flowy_infra_ui/example/lib/main.dart @@ -9,6 +9,6 @@ class ExampleApp extends StatelessWidget { @override Widget build(BuildContext context) { - return MaterialApp(); + return const MaterialApp(); } } diff --git a/app_flowy/packages/flowy_infra_ui/example/pubspec.lock b/app_flowy/packages/flowy_infra_ui/example/pubspec.lock index c05870c42c..999a86c0e7 100644 --- a/app_flowy/packages/flowy_infra_ui/example/pubspec.lock +++ b/app_flowy/packages/flowy_infra_ui/example/pubspec.lock @@ -14,7 +14,7 @@ packages: name: async url: "https://pub.dartlang.org" source: hosted - version: "2.6.1" + version: "2.7.0" boolean_selector: dependency: transitive description: @@ -35,7 +35,7 @@ packages: name: charcode url: "https://pub.dartlang.org" source: hosted - version: "1.2.0" + version: "1.3.1" clock: dependency: transitive description: @@ -162,7 +162,7 @@ packages: name: meta url: "https://pub.dartlang.org" source: hosted - version: "1.3.0" + version: "1.4.0" nested: dependency: transitive description: @@ -237,7 +237,7 @@ packages: name: test_api url: "https://pub.dartlang.org" source: hosted - version: "0.3.0" + version: "0.4.1" textstyle_extensions: dependency: transitive description: diff --git a/app_flowy/packages/flowy_infra_ui/example/test/widget_test.dart b/app_flowy/packages/flowy_infra_ui/example/test/widget_test.dart index 1d7ea5f43e..09c1545e57 100644 --- a/app_flowy/packages/flowy_infra_ui/example/test/widget_test.dart +++ b/app_flowy/packages/flowy_infra_ui/example/test/widget_test.dart @@ -13,13 +13,13 @@ import 'package:flowy_infra_ui_example/main.dart'; void main() { testWidgets('Verify Platform version', (WidgetTester tester) async { // Build our app and trigger a frame. - await tester.pumpWidget(const MyApp()); + await tester.pumpWidget(const ExampleApp()); // Verify that platform version is retrieved. expect( find.byWidgetPredicate( - (Widget widget) => widget is Text && - widget.data!.startsWith('Running on:'), + (Widget widget) => + widget is Text && widget.data!.startsWith('Running on:'), ), findsOneWidget, ); diff --git a/app_flowy/packages/flowy_infra_ui/pubspec.lock b/app_flowy/packages/flowy_infra_ui/pubspec.lock index cff84ae06e..db0559ecf9 100644 --- a/app_flowy/packages/flowy_infra_ui/pubspec.lock +++ b/app_flowy/packages/flowy_infra_ui/pubspec.lock @@ -14,7 +14,7 @@ packages: name: async url: "https://pub.dartlang.org" source: hosted - version: "2.6.1" + version: "2.7.0" boolean_selector: dependency: transitive description: @@ -35,7 +35,7 @@ packages: name: charcode url: "https://pub.dartlang.org" source: hosted - version: "1.2.0" + version: "1.3.1" clock: dependency: transitive description: @@ -148,7 +148,7 @@ packages: name: meta url: "https://pub.dartlang.org" source: hosted - version: "1.3.0" + version: "1.4.0" nested: dependency: transitive description: @@ -223,7 +223,7 @@ packages: name: test_api url: "https://pub.dartlang.org" source: hosted - version: "0.3.0" + version: "0.4.1" textstyle_extensions: dependency: "direct main" description: From ce6412722f5489de0d26b3ac441e3a4169af21b1 Mon Sep 17 00:00:00 2001 From: appflowy Date: Sat, 17 Jul 2021 08:24:17 +0800 Subject: [PATCH 04/30] refactor build with generic tester --- .idea/appflowy_client.iml | 3 + rust-lib/flowy-sdk/src/lib.rs | 2 +- rust-lib/flowy-test/Cargo.toml | 1 + rust-lib/flowy-test/src/builder.rs | 134 +++++++++++++----- rust-lib/flowy-test/src/helper.rs | 22 --- rust-lib/flowy-test/src/lib.rs | 10 +- rust-lib/flowy-test/src/tester.rs | 66 +++++---- rust-lib/flowy-user/tests/event/helper.rs | 5 +- .../flowy-user/tests/event/sign_in_test.rs | 1 - .../flowy-user/tests/event/sign_up_test.rs | 1 - .../flowy-workspace/tests/event/helper.rs | 5 +- 11 files changed, 149 insertions(+), 101 deletions(-) diff --git a/.idea/appflowy_client.iml b/.idea/appflowy_client.iml index f33c861988..5c6b5b4d21 100644 --- a/.idea/appflowy_client.iml +++ b/.idea/appflowy_client.iml @@ -83,6 +83,9 @@ + + + diff --git a/rust-lib/flowy-sdk/src/lib.rs b/rust-lib/flowy-sdk/src/lib.rs index db7265177e..32595e2424 100644 --- a/rust-lib/flowy-sdk/src/lib.rs +++ b/rust-lib/flowy-sdk/src/lib.rs @@ -29,7 +29,7 @@ impl FlowySDK { FlowySDK::init_log(&self.root); tracing::info!("🔥 Root path: {}", self.root); - flowy_infra::kv::KVStore::init(&self.root); + let _ = flowy_infra::kv::KVStore::init(&self.root); FlowySDK::init_modules(&self.root, self.server); } diff --git a/rust-lib/flowy-test/Cargo.toml b/rust-lib/flowy-test/Cargo.toml index fc28e6525f..fb52d19629 100644 --- a/rust-lib/flowy-test/Cargo.toml +++ b/rust-lib/flowy-test/Cargo.toml @@ -9,6 +9,7 @@ edition = "2018" flowy-sdk = { path = "../flowy-sdk"} flowy-dispatch = { path = "../flowy-dispatch"} flowy-user = { path = "../flowy-user"} +flowy-workspace = { path = "../flowy-workspace"} serde = { version = "1.0", features = ["derive"] } bincode = { version = "1.3"} diff --git a/rust-lib/flowy-test/src/builder.rs b/rust-lib/flowy-test/src/builder.rs index a100872fa0..271971cc80 100644 --- a/rust-lib/flowy-test/src/builder.rs +++ b/rust-lib/flowy-test/src/builder.rs @@ -1,46 +1,52 @@ -use crate::{helper::new_user_after_login, init_sdk, tester::Tester}; -use flowy_dispatch::prelude::{EventDispatch, FromBytes, ModuleRequest, ToBytes}; -use flowy_user::{entities::UserDetail, event::UserEvent::SignOut}; +use flowy_dispatch::prelude::{FromBytes, ToBytes}; +use flowy_user::entities::UserDetail; use std::{ fmt::{Debug, Display}, hash::Hash, }; -pub struct TestBuilder { - login: Option, - inner: Option>, - pub user_detail: Option, -} +use crate::tester::{TesterContext, TesterTrait}; +use flowy_user::errors::UserError; +use flowy_workspace::errors::WorkspaceError; +use std::marker::PhantomData; -impl TestBuilder -where - Error: FromBytes + Debug, -{ +pub type WorkspaceTestBuilder = TestBuilder>; +impl WorkspaceTestBuilder { pub fn new() -> Self { - TestBuilder:: { - login: None, - inner: None, + Self { + tester: Box::new(FixedUserTester::::new()), user_detail: None, } } +} +pub type UserTestBuilder = TestBuilder>; +impl UserTestBuilder { + pub fn new() -> Self { + Self { + tester: Box::new(RandomUserTester::::new()), + user_detail: None, + } + } +} + +pub struct TestBuilder { + pub tester: Box, + pub user_detail: Option, +} + +impl TestBuilder +where + T: TesterTrait, +{ pub fn login(mut self) -> Self { - let user_detail = new_user_after_login(); + let user_detail = self.tester.login(); self.user_detail = Some(user_detail); self } pub fn logout(self) -> Self { - init_sdk(); - let _ = EventDispatch::sync_send(ModuleRequest::new(SignOut)); - self - } - - pub fn event(mut self, event: E) -> Self - where - E: Eq + Hash + Debug + Clone + Display, - { - self.inner = Some(Tester::::new(event)); + self.tester.logout(); self } @@ -48,12 +54,20 @@ where where P: ToBytes, { - self.inner.as_mut().unwrap().set_request(request); + self.tester.set_payload(request); + self + } + + pub fn event(mut self, event: E) -> Self + where + E: Eq + Hash + Debug + Clone + Display, + { + self.tester.set_event(event); self } pub fn sync_send(mut self) -> Self { - self.inner.as_mut().unwrap().sync_send(); + self.tester.sync_send(); self } @@ -61,22 +75,70 @@ where where R: FromBytes, { - let inner = self.inner.take().unwrap(); - inner.parse::() + self.tester.parse::() } - pub fn error(mut self) -> Error { - let inner = self.inner.take().unwrap(); - inner.error() - } + pub fn error(mut self) -> ::Error { self.tester.error() } pub fn assert_error(mut self) -> Self { - self.inner.as_mut().unwrap().assert_error(); + self.tester.assert_error(); self } pub fn assert_success(mut self) -> Self { - self.inner.as_mut().unwrap().assert_success(); + self.tester.assert_success(); self } } + +pub struct RandomUserTester { + context: TesterContext, + err_phantom: PhantomData, +} + +impl RandomUserTester +where + Error: FromBytes + Debug, +{ + pub fn new() -> Self { + Self { + context: TesterContext::default(), + err_phantom: PhantomData, + } + } +} + +impl TesterTrait for RandomUserTester +where + Error: FromBytes + Debug, +{ + type Error = Error; + + fn context(&mut self) -> &mut TesterContext { &mut self.context } +} + +pub struct FixedUserTester { + context: TesterContext, + err_phantom: PhantomData, +} + +impl FixedUserTester +where + Error: FromBytes + Debug, +{ + pub fn new() -> Self { + Self { + context: TesterContext::default(), + err_phantom: PhantomData, + } + } +} + +impl TesterTrait for FixedUserTester +where + Error: FromBytes + Debug, +{ + type Error = Error; + + fn context(&mut self) -> &mut TesterContext { &mut self.context } +} diff --git a/rust-lib/flowy-test/src/helper.rs b/rust-lib/flowy-test/src/helper.rs index 2ea710e809..88298e0a69 100644 --- a/rust-lib/flowy-test/src/helper.rs +++ b/rust-lib/flowy-test/src/helper.rs @@ -1,10 +1,3 @@ -use crate::{init_sdk, tester::Tester}; -use flowy_dispatch::prelude::*; -use flowy_user::{ - entities::{SignInRequest, UserDetail}, - errors::UserError, - event::UserEvent::{SignIn, SignOut}, -}; use std::{fs, path::PathBuf}; pub fn root_dir() -> String { @@ -23,21 +16,6 @@ pub fn root_dir() -> String { root_dir } -pub fn new_user_after_login() -> UserDetail { - init_sdk(); - let _ = EventDispatch::sync_send(ModuleRequest::new(SignOut)); - let request = SignInRequest { - email: valid_email(), - password: valid_password(), - }; - - let mut tester = Tester::::new(SignIn); - tester.set_request(request); - tester.sync_send(); - - tester.parse::() -} - pub(crate) fn valid_email() -> String { "annie@appflowy.io".to_string() } pub(crate) fn valid_password() -> String { "HelloWorld!123".to_string() } diff --git a/rust-lib/flowy-test/src/lib.rs b/rust-lib/flowy-test/src/lib.rs index ebe11e7a66..b67859f336 100644 --- a/rust-lib/flowy-test/src/lib.rs +++ b/rust-lib/flowy-test/src/lib.rs @@ -1,13 +1,17 @@ -mod builder; +pub mod builder; mod helper; mod tester; use crate::helper::root_dir; use flowy_sdk::FlowySDK; -use std::{sync::Once, thread}; +use std::sync::Once; pub mod prelude { - pub use crate::{builder::TestBuilder, tester::Tester}; + pub use crate::{ + builder::{TestBuilder, *}, + helper::*, + tester::Tester, + }; pub use flowy_dispatch::prelude::*; } diff --git a/rust-lib/flowy-test/src/tester.rs b/rust-lib/flowy-test/src/tester.rs index faf8268058..a3807c572f 100644 --- a/rust-lib/flowy-test/src/tester.rs +++ b/rust-lib/flowy-test/src/tester.rs @@ -1,7 +1,14 @@ -use crate::init_sdk; +use crate::{ + helper::{valid_email, valid_password}, + init_sdk, +}; use flowy_dispatch::prelude::*; pub use flowy_sdk::*; -use flowy_user::prelude::*; +use flowy_user::{ + errors::UserError, + event::UserEvent::{SignIn, SignOut}, + prelude::*, +}; use std::{ convert::TryFrom, fmt::{Debug, Display}, @@ -89,32 +96,6 @@ where } } -pub struct RandomUserTester { - context: TesterContext, - err_phantom: PhantomData, -} - -impl RandomUserTester -where - Error: FromBytes + Debug, -{ - pub fn new() -> Self { - Self { - context: TesterContext::default(), - err_phantom: PhantomData, - } - } -} - -impl TesterTrait for RandomUserTester -where - Error: FromBytes + Debug, -{ - type Error = Error; - - fn context(&mut self) -> &mut TesterContext { &mut self.context } -} - pub struct TesterContext { request: Option, status_code: StatusCode, @@ -140,12 +121,20 @@ pub trait TesterTrait { fn assert_success(&mut self) { self.context().status_code = StatusCode::Ok; } + fn set_event(&mut self, event: E) + where + E: Eq + Hash + Debug + Clone + Display, + { + init_sdk(); + self.context().request = Some(ModuleRequest::new(event)); + } + fn set_payload

(&mut self, payload: P) where P: ToBytes, { let bytes = payload.into_bytes().unwrap(); - let mut module_request = self.context().request.take().unwrap(); + let module_request = self.context().request.take().unwrap(); self.context().request = Some(module_request.payload(bytes)); } @@ -173,4 +162,23 @@ pub trait TesterTrait { .unwrap() .into_inner() } + + fn login(&self) -> UserDetail { + init_sdk(); + let _ = EventDispatch::sync_send(ModuleRequest::new(SignOut)); + let request = SignInRequest { + email: valid_email(), + password: valid_password(), + }; + + let mut tester = Tester::::new(SignIn); + tester.set_request(request); + tester.sync_send(); + tester.parse::() + } + + fn logout(&self) { + init_sdk(); + let _ = EventDispatch::sync_send(ModuleRequest::new(SignOut)); + } } diff --git a/rust-lib/flowy-user/tests/event/helper.rs b/rust-lib/flowy-user/tests/event/helper.rs index 692d6c2d42..c415725bf6 100644 --- a/rust-lib/flowy-user/tests/event/helper.rs +++ b/rust-lib/flowy-user/tests/event/helper.rs @@ -1,7 +1,4 @@ -use flowy_test::prelude::TestBuilder; -use flowy_user::errors::UserError; - -pub type UserTestBuilder = TestBuilder; +pub use flowy_test::builder::UserTestBuilder; pub(crate) fn invalid_email_test_case() -> Vec { // https://gist.github.com/cjaoude/fd9910626629b53c4d25 diff --git a/rust-lib/flowy-user/tests/event/sign_in_test.rs b/rust-lib/flowy-user/tests/event/sign_in_test.rs index 67817f874c..2d2793354d 100644 --- a/rust-lib/flowy-user/tests/event/sign_in_test.rs +++ b/rust-lib/flowy-user/tests/event/sign_in_test.rs @@ -1,5 +1,4 @@ use crate::helper::*; - use flowy_user::{errors::UserErrorCode, event::UserEvent::*, prelude::*}; use serial_test::*; diff --git a/rust-lib/flowy-user/tests/event/sign_up_test.rs b/rust-lib/flowy-user/tests/event/sign_up_test.rs index e08b5dd061..9a1427491d 100644 --- a/rust-lib/flowy-user/tests/event/sign_up_test.rs +++ b/rust-lib/flowy-user/tests/event/sign_up_test.rs @@ -1,5 +1,4 @@ use crate::helper::*; - use flowy_user::{errors::*, event::UserEvent::*, prelude::*}; use serial_test::*; diff --git a/rust-lib/flowy-workspace/tests/event/helper.rs b/rust-lib/flowy-workspace/tests/event/helper.rs index c4ecbb3435..9631890bfa 100644 --- a/rust-lib/flowy-workspace/tests/event/helper.rs +++ b/rust-lib/flowy-workspace/tests/event/helper.rs @@ -1,7 +1,4 @@ -use flowy_test::prelude::TestBuilder; -use flowy_workspace::errors::WorkspaceError; - -pub type WorkspaceTestBuilder = TestBuilder; +pub use flowy_test::builder::WorkspaceTestBuilder; pub(crate) fn invalid_workspace_name_test_case() -> Vec { vec!["", "1234".repeat(100).as_str()] From 848975e7f472501ba7cc34b27864eaae275ceee3 Mon Sep 17 00:00:00 2001 From: appflowy Date: Sat, 17 Jul 2021 10:26:05 +0800 Subject: [PATCH 05/30] enable test with single user id --- rust-lib/flowy-sdk/src/flowy_server.rs | 11 +- rust-lib/flowy-sdk/src/lib.rs | 16 +- rust-lib/flowy-sdk/src/module.rs | 4 +- rust-lib/flowy-test/Cargo.toml | 1 + rust-lib/flowy-test/src/builder.rs | 15 +- rust-lib/flowy-test/src/helper.rs | 7 +- rust-lib/flowy-test/src/lib.rs | 7 +- rust-lib/flowy-test/src/tester.rs | 148 ++++++------------ .../src/services/user_session/user_session.rs | 2 +- rust-lib/flowy-user/tests/event/helper.rs | 6 +- .../flowy-user/tests/event/sign_in_test.rs | 4 +- .../flowy-user/tests/event/sign_up_test.rs | 4 +- .../tests/event/user_status_test.rs | 2 +- .../tests/event/workspace_test.rs | 1 + 14 files changed, 89 insertions(+), 139 deletions(-) diff --git a/rust-lib/flowy-sdk/src/flowy_server.rs b/rust-lib/flowy-sdk/src/flowy_server.rs index 1ca319b6b9..ef13e4f9a7 100644 --- a/rust-lib/flowy-sdk/src/flowy_server.rs +++ b/rust-lib/flowy-sdk/src/flowy_server.rs @@ -10,14 +10,13 @@ pub type ArcFlowyServer = std::sync::Arc; pub trait FlowyServer: UserServer {} -pub struct MockFlowyServer {} +pub struct FlowyServerMocker {} -impl FlowyServer for MockFlowyServer {} +impl FlowyServer for FlowyServerMocker {} -impl UserServer for MockFlowyServer { +impl UserServer for FlowyServerMocker { fn sign_up(&self, params: SignUpParams) -> Result { - // let user_id = "9527".to_owned(); - let user_id = uuid(); + let user_id = params.email.clone(); Ok(User::new( user_id, params.name, @@ -27,7 +26,7 @@ impl UserServer for MockFlowyServer { } fn sign_in(&self, params: SignInParams) -> Result { - let user_id = uuid(); + let user_id = params.email.clone(); Ok(User::new( user_id, "".to_owned(), diff --git a/rust-lib/flowy-sdk/src/lib.rs b/rust-lib/flowy-sdk/src/lib.rs index 32595e2424..b0d93a4e97 100644 --- a/rust-lib/flowy-sdk/src/lib.rs +++ b/rust-lib/flowy-sdk/src/lib.rs @@ -1,7 +1,7 @@ mod flowy_server; pub mod module; -use crate::flowy_server::{ArcFlowyServer, MockFlowyServer}; +pub use crate::flowy_server::{ArcFlowyServer, FlowyServerMocker}; use flowy_dispatch::prelude::*; use module::build_modules; pub use module::*; @@ -18,19 +18,21 @@ pub struct FlowySDK { impl FlowySDK { pub fn new(root: &str) -> Self { - let server = Arc::new(MockFlowyServer {}); + let server = Arc::new(FlowyServerMocker {}); Self { root: root.to_owned(), server, } } - pub fn construct(self) { - FlowySDK::init_log(&self.root); + pub fn construct(self) { FlowySDK::construct_with(&self.root, self.server.clone()) } - tracing::info!("🔥 Root path: {}", self.root); - let _ = flowy_infra::kv::KVStore::init(&self.root); - FlowySDK::init_modules(&self.root, self.server); + pub fn construct_with(root: &str, server: ArcFlowyServer) { + FlowySDK::init_log(root); + + tracing::info!("🔥 Root path: {}", root); + let _ = flowy_infra::kv::KVStore::init(root); + FlowySDK::init_modules(root, server); } fn init_log(directory: &str) { diff --git a/rust-lib/flowy-sdk/src/module.rs b/rust-lib/flowy-sdk/src/module.rs index d337e37e9f..ed0afda2f2 100644 --- a/rust-lib/flowy-sdk/src/module.rs +++ b/rust-lib/flowy-sdk/src/module.rs @@ -1,7 +1,7 @@ use flowy_dispatch::prelude::Module; use flowy_user::prelude::*; -use crate::flowy_server::{ArcFlowyServer, MockFlowyServer}; +use crate::flowy_server::{ArcFlowyServer, FlowyServerMocker}; use flowy_database::DBConnection; use flowy_workspace::prelude::*; @@ -15,7 +15,7 @@ pub fn build_modules(config: ModuleConfig, _server: ArcFlowyServer) -> Vec &mut TesterContext { &mut self.context } + fn mut_context(&mut self) -> &mut TesterContext { &mut self.context } + + fn context(&self) -> &TesterContext { &self.context } } pub struct FixedUserTester { @@ -128,7 +133,7 @@ where { pub fn new() -> Self { Self { - context: TesterContext::default(), + context: TesterContext::new(valid_email()), err_phantom: PhantomData, } } @@ -140,5 +145,7 @@ where { type Error = Error; - fn context(&mut self) -> &mut TesterContext { &mut self.context } + fn mut_context(&mut self) -> &mut TesterContext { &mut self.context } + + fn context(&self) -> &TesterContext { &self.context } } diff --git a/rust-lib/flowy-test/src/helper.rs b/rust-lib/flowy-test/src/helper.rs index 88298e0a69..f13adeba12 100644 --- a/rust-lib/flowy-test/src/helper.rs +++ b/rust-lib/flowy-test/src/helper.rs @@ -1,3 +1,4 @@ +use flowy_infra::uuid; use std::{fs, path::PathBuf}; pub fn root_dir() -> String { @@ -16,6 +17,8 @@ pub fn root_dir() -> String { root_dir } -pub(crate) fn valid_email() -> String { "annie@appflowy.io".to_string() } +pub fn random_valid_email() -> String { format!("{}@appflowy.io", uuid()) } -pub(crate) fn valid_password() -> String { "HelloWorld!123".to_string() } +pub fn valid_email() -> String { "annie@appflowy.io".to_string() } + +pub fn valid_password() -> String { "HelloWorld!123".to_string() } diff --git a/rust-lib/flowy-test/src/lib.rs b/rust-lib/flowy-test/src/lib.rs index b67859f336..15187a56c5 100644 --- a/rust-lib/flowy-test/src/lib.rs +++ b/rust-lib/flowy-test/src/lib.rs @@ -3,23 +3,22 @@ mod helper; mod tester; use crate::helper::root_dir; -use flowy_sdk::FlowySDK; +use flowy_sdk::{ArcFlowyServer, FlowySDK}; use std::sync::Once; pub mod prelude { pub use crate::{ builder::{TestBuilder, *}, helper::*, - tester::Tester, }; pub use flowy_dispatch::prelude::*; } static INIT: Once = Once::new(); -pub fn init_sdk() { +pub fn init_test_sdk(server: ArcFlowyServer) { let root_dir = root_dir(); INIT.call_once(|| { - FlowySDK::new(&root_dir).construct(); + FlowySDK::construct_with(&root_dir, server); }); } diff --git a/rust-lib/flowy-test/src/tester.rs b/rust-lib/flowy-test/src/tester.rs index a3807c572f..dc505c36c2 100644 --- a/rust-lib/flowy-test/src/tester.rs +++ b/rust-lib/flowy-test/src/tester.rs @@ -1,6 +1,6 @@ use crate::{ - helper::{valid_email, valid_password}, - init_sdk, + helper::{random_valid_email, valid_password}, + init_test_sdk, }; use flowy_dispatch::prelude::*; pub use flowy_sdk::*; @@ -13,93 +13,24 @@ use std::{ convert::TryFrom, fmt::{Debug, Display}, hash::Hash, - marker::PhantomData, + sync::Arc, thread, }; -pub struct Tester { - inner_request: Option, - assert_status_code: Option, - response: Option, - err_phantom: PhantomData, - user_detail: Option, -} - -impl Tester -where - Error: FromBytes + Debug, -{ - pub fn new(event: E) -> Self - where - E: Eq + Hash + Debug + Clone + Display, - { - init_sdk(); - log::trace!( - "{:?} thread started: thread_id= {}", - thread::current(), - thread_id::get() - ); - - Self { - inner_request: Some(ModuleRequest::new(event)), - assert_status_code: None, - response: None, - err_phantom: PhantomData, - user_detail: None, - } - } - - pub fn set_request

(&mut self, request: P) - where - P: ToBytes, - { - let mut inner_request = self.inner_request.take().unwrap(); - let bytes = request.into_bytes().unwrap(); - inner_request = inner_request.payload(bytes); - self.inner_request = Some(inner_request); - } - - pub fn assert_error(&mut self) { self.assert_status_code = Some(StatusCode::Err); } - - pub fn assert_success(&mut self) { self.assert_status_code = Some(StatusCode::Ok); } - - pub async fn async_send(&mut self) { - assert_eq!(self.inner_request.is_some(), true, "must set event"); - - let resp = EventDispatch::async_send(self.inner_request.take().unwrap()).await; - self.response = Some(resp); - } - - pub fn sync_send(&mut self) { - let resp = EventDispatch::sync_send(self.inner_request.take().unwrap()); - self.response = Some(resp); - } - - pub fn parse(self) -> R - where - R: FromBytes, - { - let response = self.response.unwrap(); - match response.parse::() { - Ok(Ok(data)) => data, - Ok(Err(e)) => panic!("parse failed: {:?}", e), - Err(e) => panic!("Internal error: {:?}", e), - } - } - - pub fn error(self) -> Error { - let response = self.response.unwrap(); - assert_eq!(response.status_code, StatusCode::Err); - >::try_from(response.payload) - .unwrap() - .into_inner() - } -} - pub struct TesterContext { request: Option, - status_code: StatusCode, response: Option, + status_code: StatusCode, + server: ArcFlowyServer, + user_email: String, +} + +impl TesterContext { + pub fn new(email: String) -> Self { + let mut ctx = TesterContext::default(); + ctx.user_email = email; + ctx + } } impl std::default::Default for TesterContext { @@ -108,6 +39,8 @@ impl std::default::Default for TesterContext { request: None, status_code: StatusCode::Ok, response: None, + server: Arc::new(FlowyServerMocker {}), + user_email: random_valid_email(), } } } @@ -115,18 +48,20 @@ impl std::default::Default for TesterContext { pub trait TesterTrait { type Error: FromBytes + Debug; - fn context(&mut self) -> &mut TesterContext; + fn mut_context(&mut self) -> &mut TesterContext; - fn assert_error(&mut self) { self.context().status_code = StatusCode::Err; } + fn context(&self) -> &TesterContext; - fn assert_success(&mut self) { self.context().status_code = StatusCode::Ok; } + fn assert_error(&mut self) { self.mut_context().status_code = StatusCode::Err; } + + fn assert_success(&mut self) { self.mut_context().status_code = StatusCode::Ok; } fn set_event(&mut self, event: E) where E: Eq + Hash + Debug + Clone + Display, { - init_sdk(); - self.context().request = Some(ModuleRequest::new(event)); + init_test_sdk(self.context().server.clone()); + self.mut_context().request = Some(ModuleRequest::new(event)); } fn set_payload

(&mut self, payload: P) @@ -134,20 +69,20 @@ pub trait TesterTrait { P: ToBytes, { let bytes = payload.into_bytes().unwrap(); - let module_request = self.context().request.take().unwrap(); - self.context().request = Some(module_request.payload(bytes)); + let module_request = self.mut_context().request.take().unwrap(); + self.mut_context().request = Some(module_request.payload(bytes)); } fn sync_send(&mut self) { - let resp = EventDispatch::sync_send(self.context().request.take().unwrap()); - self.context().response = Some(resp); + let resp = EventDispatch::sync_send(self.mut_context().request.take().unwrap()); + self.mut_context().response = Some(resp); } fn parse(&mut self) -> R where R: FromBytes, { - let response = self.context().response.clone().unwrap(); + let response = self.mut_context().response.clone().unwrap(); match response.parse::() { Ok(Ok(data)) => data, Ok(Err(e)) => panic!("parse failed: {:?}", e), @@ -156,7 +91,7 @@ pub trait TesterTrait { } fn error(&mut self) -> Self::Error { - let response = self.context().response.clone().unwrap(); + let response = self.mut_context().response.clone().unwrap(); assert_eq!(response.status_code, StatusCode::Err); >::try_from(response.payload) .unwrap() @@ -164,21 +99,26 @@ pub trait TesterTrait { } fn login(&self) -> UserDetail { - init_sdk(); - let _ = EventDispatch::sync_send(ModuleRequest::new(SignOut)); - let request = SignInRequest { - email: valid_email(), + init_test_sdk(self.context().server.clone()); + self.logout(); + let payload = SignInRequest { + email: self.context().user_email.clone(), password: valid_password(), - }; + } + .into_bytes() + .unwrap(); - let mut tester = Tester::::new(SignIn); - tester.set_request(request); - tester.sync_send(); - tester.parse::() + let request = ModuleRequest::new(SignIn).payload(payload); + let user_detail = EventDispatch::sync_send(request) + .parse::() + .unwrap() + .unwrap(); + + user_detail } fn logout(&self) { - init_sdk(); + init_test_sdk(self.context().server.clone()); let _ = EventDispatch::sync_send(ModuleRequest::new(SignOut)); } } diff --git a/rust-lib/flowy-user/src/services/user_session/user_session.rs b/rust-lib/flowy-user/src/services/user_session/user_session.rs index 3f9413e46d..4437f804f2 100644 --- a/rust-lib/flowy-user/src/services/user_session/user_session.rs +++ b/rust-lib/flowy-user/src/services/user_session/user_session.rs @@ -143,7 +143,7 @@ impl UserSession { } } -fn current_user_id() -> Result { +pub fn current_user_id() -> Result { match KVStore::get_str(USER_ID_DISK_CACHE_KEY) { None => Err(ErrorBuilder::new(UserErrorCode::UserNotLoginYet).build()), Some(user_id) => Ok(user_id), diff --git a/rust-lib/flowy-user/tests/event/helper.rs b/rust-lib/flowy-user/tests/event/helper.rs index c415725bf6..ba0d12ece5 100644 --- a/rust-lib/flowy-user/tests/event/helper.rs +++ b/rust-lib/flowy-user/tests/event/helper.rs @@ -1,5 +1,7 @@ pub use flowy_test::builder::UserTestBuilder; +pub use flowy_test::prelude::{random_valid_email, valid_password}; + pub(crate) fn invalid_email_test_case() -> Vec { // https://gist.github.com/cjaoude/fd9910626629b53c4d25 vec![ @@ -35,8 +37,4 @@ pub(crate) fn invalid_password_test_case() -> Vec { .collect::>() } -pub(crate) fn valid_email() -> String { "annie@appflowy.io".to_string() } - -pub(crate) fn valid_password() -> String { "HelloWorld!123".to_string() } - pub(crate) fn valid_name() -> String { "AppFlowy".to_string() } diff --git a/rust-lib/flowy-user/tests/event/sign_in_test.rs b/rust-lib/flowy-user/tests/event/sign_in_test.rs index 2d2793354d..eaacf915de 100644 --- a/rust-lib/flowy-user/tests/event/sign_in_test.rs +++ b/rust-lib/flowy-user/tests/event/sign_in_test.rs @@ -6,7 +6,7 @@ use serial_test::*; #[serial] fn sign_in_success() { let request = SignInRequest { - email: valid_email(), + email: random_valid_email(), password: valid_password(), }; @@ -43,7 +43,7 @@ fn sign_in_with_invalid_email() { fn sign_in_with_invalid_password() { for password in invalid_password_test_case() { let request = SignInRequest { - email: valid_email(), + email: random_valid_email(), password, }; diff --git a/rust-lib/flowy-user/tests/event/sign_up_test.rs b/rust-lib/flowy-user/tests/event/sign_up_test.rs index 9a1427491d..7c9ed4d9e4 100644 --- a/rust-lib/flowy-user/tests/event/sign_up_test.rs +++ b/rust-lib/flowy-user/tests/event/sign_up_test.rs @@ -7,7 +7,7 @@ use serial_test::*; fn sign_up_success() { let _ = UserTestBuilder::new().event(SignOut).sync_send(); let request = SignUpRequest { - email: valid_email(), + email: random_valid_email(), name: valid_name(), password: valid_password(), }; @@ -44,7 +44,7 @@ fn sign_up_with_invalid_email() { fn sign_up_with_invalid_password() { for password in invalid_password_test_case() { let request = SignUpRequest { - email: valid_email(), + email: random_valid_email(), name: valid_name(), password, }; diff --git a/rust-lib/flowy-user/tests/event/user_status_test.rs b/rust-lib/flowy-user/tests/event/user_status_test.rs index 4b2f778f00..ee5e56345d 100644 --- a/rust-lib/flowy-user/tests/event/user_status_test.rs +++ b/rust-lib/flowy-user/tests/event/user_status_test.rs @@ -17,7 +17,7 @@ fn user_status_get_failed_before_login() { #[serial] fn user_status_get_success_after_login() { let request = SignInRequest { - email: valid_email(), + email: random_valid_email(), password: valid_password(), }; diff --git a/rust-lib/flowy-workspace/tests/event/workspace_test.rs b/rust-lib/flowy-workspace/tests/event/workspace_test.rs index 8c00414098..e23fc48d81 100644 --- a/rust-lib/flowy-workspace/tests/event/workspace_test.rs +++ b/rust-lib/flowy-workspace/tests/event/workspace_test.rs @@ -13,6 +13,7 @@ fn workspace_create_success() { }; let response = WorkspaceTestBuilder::new() + .login() .event(CreateWorkspace) .request(request) .sync_send() From a63d5f5eafa04db177307e910cd5cf3fd321b2a0 Mon Sep 17 00:00:00 2001 From: appflowy Date: Sun, 18 Jul 2021 09:03:21 +0800 Subject: [PATCH 06/30] support multi user db initialize --- rust-lib/flowy-user/Cargo.toml | 4 + .../src/services/user_session/database.rs | 68 ++--- .../src/services/user_session/user_session.rs | 2 +- .../flowy-user/tests/event/sign_in_test.rs | 232 +++++++++++++++ .../flowy-user/tests/event/sign_up_test.rs | 127 ++++---- .../tests/event/user_status_test.rs | 72 ++--- .../tests/event/user_update_test.rs | 280 +++++++++--------- 7 files changed, 509 insertions(+), 276 deletions(-) diff --git a/rust-lib/flowy-user/Cargo.toml b/rust-lib/flowy-user/Cargo.toml index 44dffac38f..db0be3480b 100644 --- a/rust-lib/flowy-user/Cargo.toml +++ b/rust-lib/flowy-user/Cargo.toml @@ -26,6 +26,10 @@ lazy_static = "1.4.0" fancy-regex = "0.5.0" diesel = {version = "1.4.7", features = ["sqlite"]} diesel_derives = {version = "1.4.1", features = ["sqlite"]} +thread_local = "1.1.3" +thread-id = "3.3.0" +once_cell = "1.7.2" +parking_lot = "0.11" [dev-dependencies] quickcheck = "0.9.2" diff --git a/rust-lib/flowy-user/src/services/user_session/database.rs b/rust-lib/flowy-user/src/services/user_session/database.rs index 135937459b..77b621c6d5 100644 --- a/rust-lib/flowy-user/src/services/user_session/database.rs +++ b/rust-lib/flowy-user/src/services/user_session/database.rs @@ -1,8 +1,11 @@ use crate::errors::{ErrorBuilder, UserError, UserErrorCode}; use flowy_database::{DBConnection, Database}; use lazy_static::lazy_static; +use once_cell::sync::Lazy; +use parking_lot::Mutex; use std::{ cell::RefCell, + collections::HashMap, sync::{ atomic::{AtomicBool, Ordering}, RwLock, @@ -25,7 +28,8 @@ impl UserDB { } fn open_user_db(&self, user_id: &str) -> Result<(), UserError> { - INIT_FLAG.store(true, Ordering::SeqCst); + set_user_db_init(true, user_id); + let dir = format!("{}/{}", self.db_dir, user_id); let db = flowy_database::init(&dir).map_err(|e| { ErrorBuilder::new(UserErrorCode::DatabaseInitFailed) @@ -33,58 +37,41 @@ impl UserDB { .build() })?; - let mut user_db = DB.write().map_err(|e| { + let mut db_map = DB_MAP.write().map_err(|e| { ErrorBuilder::new(UserErrorCode::DatabaseWriteLocked) .error(e) .build() })?; - *(user_db) = Some(db); - set_user_id(Some(user_id.to_owned())); + db_map.insert(user_id.to_owned(), db); Ok(()) } - pub(crate) fn close_user_db(&self) -> Result<(), UserError> { - INIT_FLAG.store(false, Ordering::SeqCst); + pub(crate) fn close_user_db(&self, user_id: &str) -> Result<(), UserError> { + set_user_db_init(false, user_id); - let mut write_guard = DB.write().map_err(|e| { + let mut db_map = DB_MAP.write().map_err(|e| { ErrorBuilder::new(UserErrorCode::DatabaseWriteLocked) .msg(format!("Close user db failed. {:?}", e)) .build() })?; - *write_guard = None; - set_user_id(None); - + db_map.remove(user_id); Ok(()) } pub(crate) fn get_connection(&self, user_id: &str) -> Result { - if !INIT_FLAG.load(Ordering::SeqCst) { + if !is_user_db_init(user_id) { let _ = self.open_user_db(user_id); } - let thread_user_id = get_user_id(); - if thread_user_id.is_some() { - if thread_user_id != Some(user_id.to_owned()) { - let msg = format!( - "Database owner does not match. origin: {:?}, current: {}", - thread_user_id, user_id - ); - log::error!("{}", msg); - - return Err(ErrorBuilder::new(UserErrorCode::DatabaseUserDidNotMatch) - .msg(msg) - .build()); - } - } - - let read_guard = DB.read().map_err(|e| { + let db_map = DB_MAP.read().map_err(|e| { ErrorBuilder::new(UserErrorCode::DatabaseReadLocked) .error(e) .build() })?; - match read_guard.as_ref() { + + match db_map.get(user_id) { None => Err(ErrorBuilder::new(UserErrorCode::DatabaseInitFailed) .msg("Database is not initialization") .build()), @@ -93,17 +80,24 @@ impl UserDB { } } -thread_local! { - static USER_ID: RefCell> = RefCell::new(None); +lazy_static! { + static ref DB_MAP: RwLock> = RwLock::new(HashMap::new()); } -fn set_user_id(user_id: Option) { - USER_ID.with(|id| { - *id.borrow_mut() = user_id; - }); -} -fn get_user_id() -> Option { USER_ID.with(|id| id.borrow().clone()) } -static INIT_FLAG: AtomicBool = AtomicBool::new(false); +static INIT_FLAG_MAP: Lazy>> = Lazy::new(|| Mutex::new(HashMap::new())); +fn set_user_db_init(is_init: bool, user_id: &str) { + INIT_FLAG_MAP + .lock() + .entry(user_id.to_owned()) + .or_insert_with(|| is_init); +} + +fn is_user_db_init(user_id: &str) -> bool { + match INIT_FLAG_MAP.lock().get(user_id) { + None => false, + Some(flag) => flag.clone(), + } +} #[cfg(test)] mod tests { diff --git a/rust-lib/flowy-user/src/services/user_session/user_session.rs b/rust-lib/flowy-user/src/services/user_session/user_session.rs index 4437f804f2..07b4898f8a 100644 --- a/rust-lib/flowy-user/src/services/user_session/user_session.rs +++ b/rust-lib/flowy-user/src/services/user_session/user_session.rs @@ -75,7 +75,7 @@ impl UserSession { Ok(_) => {}, Err(_) => {}, } - let _ = self.database.close_user_db()?; + let _ = self.database.close_user_db(&user_id)?; let _ = set_current_user_id(None)?; Ok(()) diff --git a/rust-lib/flowy-user/tests/event/sign_in_test.rs b/rust-lib/flowy-user/tests/event/sign_in_test.rs index eaacf915de..d29ff80df4 100644 --- a/rust-lib/flowy-user/tests/event/sign_in_test.rs +++ b/rust-lib/flowy-user/tests/event/sign_in_test.rs @@ -20,6 +20,7 @@ fn sign_in_success() { } #[test] +#[serial] fn sign_in_with_invalid_email() { for email in invalid_email_test_case() { let request = SignInRequest { @@ -40,6 +41,7 @@ fn sign_in_with_invalid_email() { } #[test] +#[serial] fn sign_in_with_invalid_password() { for password in invalid_password_test_case() { let request = SignInRequest { @@ -58,3 +60,233 @@ fn sign_in_with_invalid_password() { ); } } + +#[test] +#[serial] +fn sign_up_success() { + let _ = UserTestBuilder::new().event(SignOut).sync_send(); + let request = SignUpRequest { + email: random_valid_email(), + name: valid_name(), + password: valid_password(), + }; + + let _response = UserTestBuilder::new() + .logout() + .event(SignUp) + .request(request) + .sync_send(); +} + +#[test] +#[serial] +fn sign_up_with_invalid_email() { + for email in invalid_email_test_case() { + let request = SignUpRequest { + email: email.to_string(), + name: valid_name(), + password: valid_password(), + }; + + assert_eq!( + UserTestBuilder::new() + .event(SignUp) + .request(request) + .sync_send() + .error() + .code, + UserErrorCode::EmailInvalid + ); + } +} +#[test] +#[serial] +fn sign_up_with_invalid_password() { + for password in invalid_password_test_case() { + let request = SignUpRequest { + email: random_valid_email(), + name: valid_name(), + password, + }; + + assert_eq!( + UserTestBuilder::new() + .event(SignUp) + .request(request) + .sync_send() + .error() + .code, + UserErrorCode::PasswordInvalid + ); + } +} + +#[test] +#[should_panic] +#[serial] +fn user_status_get_failed_before_login() { + let _ = UserTestBuilder::new() + .logout() + .event(GetStatus) + .sync_send() + .parse::(); +} + +#[test] +#[serial] +fn user_status_get_success_after_login() { + let request = SignInRequest { + email: random_valid_email(), + password: valid_password(), + }; + + let response = UserTestBuilder::new() + .logout() + .event(SignIn) + .request(request) + .sync_send() + .parse::(); + dbg!(&response); + + let _ = UserTestBuilder::new() + .event(GetStatus) + .sync_send() + .parse::(); +} + +#[test] +#[serial] +fn user_update_with_name() { + let user_detail = UserTestBuilder::new().login().user_detail.unwrap(); + let new_name = "hello_world".to_owned(); + let request = UpdateUserRequest { + id: user_detail.id.clone(), + name: Some(new_name.clone()), + email: None, + workspace: None, + password: None, + }; + + let user_detail = UserTestBuilder::new() + .event(UpdateUser) + .request(request) + .sync_send() + .parse::(); + + assert_eq!(user_detail.name, new_name,); +} + +#[test] +#[serial] +fn user_update_with_email() { + let user_detail = UserTestBuilder::new().login().user_detail.unwrap(); + let new_email = "123@gmai.com".to_owned(); + let request = UpdateUserRequest { + id: user_detail.id.clone(), + name: None, + email: Some(new_email.clone()), + workspace: None, + password: None, + }; + + let user_detail = UserTestBuilder::new() + .event(UpdateUser) + .request(request) + .sync_send() + .parse::(); + + assert_eq!(user_detail.email, new_email,); +} + +#[test] +#[serial] +fn user_update_with_password() { + let user_detail = UserTestBuilder::new().login().user_detail.unwrap(); + let new_password = "H123world!".to_owned(); + let request = UpdateUserRequest { + id: user_detail.id.clone(), + name: None, + email: None, + workspace: None, + password: Some(new_password.clone()), + }; + + let _ = UserTestBuilder::new() + .event(UpdateUser) + .request(request) + .sync_send() + .assert_success(); +} + +#[test] +#[serial] +fn user_update_with_invalid_email() { + let user_detail = UserTestBuilder::new().login().user_detail.unwrap(); + for email in invalid_email_test_case() { + let request = UpdateUserRequest { + id: user_detail.id.clone(), + name: None, + email: Some(email), + workspace: None, + password: None, + }; + + assert_eq!( + UserTestBuilder::new() + .event(UpdateUser) + .request(request) + .sync_send() + .error() + .code, + UserErrorCode::EmailInvalid + ); + } +} + +#[test] +#[serial] +fn user_update_with_invalid_password() { + let user_detail = UserTestBuilder::new().login().user_detail.unwrap(); + for password in invalid_password_test_case() { + let request = UpdateUserRequest { + id: user_detail.id.clone(), + name: None, + email: None, + workspace: None, + password: Some(password), + }; + + assert_eq!( + UserTestBuilder::new() + .event(UpdateUser) + .request(request) + .sync_send() + .error() + .code, + UserErrorCode::PasswordInvalid + ); + } +} + +#[test] +#[serial] +fn user_update_with_invalid_name() { + let user_detail = UserTestBuilder::new().login().user_detail.unwrap(); + let request = UpdateUserRequest { + id: user_detail.id.clone(), + name: Some("".to_string()), + email: None, + workspace: None, + password: None, + }; + + assert_eq!( + UserTestBuilder::new() + .event(UpdateUser) + .request(request) + .sync_send() + .error() + .code, + UserErrorCode::UserNameInvalid + ); +} diff --git a/rust-lib/flowy-user/tests/event/sign_up_test.rs b/rust-lib/flowy-user/tests/event/sign_up_test.rs index 7c9ed4d9e4..e023d80bf7 100644 --- a/rust-lib/flowy-user/tests/event/sign_up_test.rs +++ b/rust-lib/flowy-user/tests/event/sign_up_test.rs @@ -1,62 +1,65 @@ -use crate::helper::*; -use flowy_user::{errors::*, event::UserEvent::*, prelude::*}; -use serial_test::*; - -#[test] -#[serial] -fn sign_up_success() { - let _ = UserTestBuilder::new().event(SignOut).sync_send(); - let request = SignUpRequest { - email: random_valid_email(), - name: valid_name(), - password: valid_password(), - }; - - let _response = UserTestBuilder::new() - .event(SignUp) - .request(request) - .sync_send(); - // .parse::(); - // dbg!(&response); -} - -#[test] -fn sign_up_with_invalid_email() { - for email in invalid_email_test_case() { - let request = SignUpRequest { - email: email.to_string(), - name: valid_name(), - password: valid_password(), - }; - - assert_eq!( - UserTestBuilder::new() - .event(SignUp) - .request(request) - .sync_send() - .error() - .code, - UserErrorCode::EmailInvalid - ); - } -} -#[test] -fn sign_up_with_invalid_password() { - for password in invalid_password_test_case() { - let request = SignUpRequest { - email: random_valid_email(), - name: valid_name(), - password, - }; - - assert_eq!( - UserTestBuilder::new() - .event(SignUp) - .request(request) - .sync_send() - .error() - .code, - UserErrorCode::PasswordInvalid - ); - } -} +// use crate::helper::*; +// use flowy_user::{errors::*, event::UserEvent::*, prelude::*}; +// use serial_test::*; +// +// #[test] +// #[serial] +// fn sign_up_success() { +// let _ = UserTestBuilder::new().event(SignOut).sync_send(); +// let request = SignUpRequest { +// email: random_valid_email(), +// name: valid_name(), +// password: valid_password(), +// }; +// +// let _response = UserTestBuilder::new() +// .logout() +// .event(SignUp) +// .request(request) +// .sync_send(); +// // .parse::(); +// // dbg!(&response); +// } +// +// #[test] +// #[serial] +// fn sign_up_with_invalid_email() { +// for email in invalid_email_test_case() { +// let request = SignUpRequest { +// email: email.to_string(), +// name: valid_name(), +// password: valid_password(), +// }; +// +// assert_eq!( +// UserTestBuilder::new() +// .event(SignUp) +// .request(request) +// .sync_send() +// .error() +// .code, +// UserErrorCode::EmailInvalid +// ); +// } +// } +// #[test] +// #[serial] +// fn sign_up_with_invalid_password() { +// for password in invalid_password_test_case() { +// let request = SignUpRequest { +// email: random_valid_email(), +// name: valid_name(), +// password, +// }; +// +// assert_eq!( +// UserTestBuilder::new() +// .event(SignUp) +// .request(request) +// .sync_send() +// .error() +// .code, +// UserErrorCode::PasswordInvalid +// ); +// } +// } diff --git a/rust-lib/flowy-user/tests/event/user_status_test.rs b/rust-lib/flowy-user/tests/event/user_status_test.rs index ee5e56345d..a6350b1fc7 100644 --- a/rust-lib/flowy-user/tests/event/user_status_test.rs +++ b/rust-lib/flowy-user/tests/event/user_status_test.rs @@ -1,36 +1,36 @@ -use crate::helper::*; -use flowy_user::{event::UserEvent::*, prelude::*}; -use serial_test::*; - -#[test] -#[should_panic] -#[serial] -fn user_status_get_failed_before_login() { - let _ = UserTestBuilder::new() - .logout() - .event(GetStatus) - .sync_send() - .parse::(); -} - -#[test] -#[serial] -fn user_status_get_success_after_login() { - let request = SignInRequest { - email: random_valid_email(), - password: valid_password(), - }; - - let response = UserTestBuilder::new() - .logout() - .event(SignIn) - .request(request) - .sync_send() - .parse::(); - dbg!(&response); - - let _ = UserTestBuilder::new() - .event(GetStatus) - .sync_send() - .parse::(); -} +// use crate::helper::*; +// use flowy_user::{event::UserEvent::*, prelude::*}; +// use serial_test::*; +// +// #[test] +// #[should_panic] +// #[serial] +// fn user_status_get_failed_before_login() { +// let _ = UserTestBuilder::new() +// .logout() +// .event(GetStatus) +// .sync_send() +// .parse::(); +// } +// +// #[test] +// #[serial] +// fn user_status_get_success_after_login() { +// let request = SignInRequest { +// email: random_valid_email(), +// password: valid_password(), +// }; +// +// let response = UserTestBuilder::new() +// .logout() +// .event(SignIn) +// .request(request) +// .sync_send() +// .parse::(); +// dbg!(&response); +// +// let _ = UserTestBuilder::new() +// .event(GetStatus) +// .sync_send() +// .parse::(); +// } diff --git a/rust-lib/flowy-user/tests/event/user_update_test.rs b/rust-lib/flowy-user/tests/event/user_update_test.rs index cd113e4fbf..7dc83bfca4 100644 --- a/rust-lib/flowy-user/tests/event/user_update_test.rs +++ b/rust-lib/flowy-user/tests/event/user_update_test.rs @@ -1,140 +1,140 @@ -use crate::helper::*; -use flowy_user::{errors::UserErrorCode, event::UserEvent::*, prelude::*}; -use serial_test::*; - -#[test] -#[serial] -fn user_update_with_name() { - let user_detail = UserTestBuilder::new().login().user_detail.unwrap(); - let new_name = "hello_world".to_owned(); - let request = UpdateUserRequest { - id: user_detail.id.clone(), - name: Some(new_name.clone()), - email: None, - workspace: None, - password: None, - }; - - let user_detail = UserTestBuilder::new() - .event(UpdateUser) - .request(request) - .sync_send() - .parse::(); - - assert_eq!(user_detail.name, new_name,); -} - -#[test] -#[serial] -fn user_update_with_email() { - let user_detail = UserTestBuilder::new().login().user_detail.unwrap(); - let new_email = "123@gmai.com".to_owned(); - let request = UpdateUserRequest { - id: user_detail.id.clone(), - name: None, - email: Some(new_email.clone()), - workspace: None, - password: None, - }; - - let user_detail = UserTestBuilder::new() - .event(UpdateUser) - .request(request) - .sync_send() - .parse::(); - - assert_eq!(user_detail.email, new_email,); -} - -#[test] -#[serial] -fn user_update_with_password() { - let user_detail = UserTestBuilder::new().login().user_detail.unwrap(); - let new_password = "H123world!".to_owned(); - let request = UpdateUserRequest { - id: user_detail.id.clone(), - name: None, - email: None, - workspace: None, - password: Some(new_password.clone()), - }; - - let _ = UserTestBuilder::new() - .event(UpdateUser) - .request(request) - .sync_send() - .assert_success(); -} - -#[test] -#[serial] -fn user_update_with_invalid_email() { - let user_detail = UserTestBuilder::new().login().user_detail.unwrap(); - for email in invalid_email_test_case() { - let request = UpdateUserRequest { - id: user_detail.id.clone(), - name: None, - email: Some(email), - workspace: None, - password: None, - }; - - assert_eq!( - UserTestBuilder::new() - .event(UpdateUser) - .request(request) - .sync_send() - .error() - .code, - UserErrorCode::EmailInvalid - ); - } -} - -#[test] -#[serial] -fn user_update_with_invalid_password() { - let user_detail = UserTestBuilder::new().login().user_detail.unwrap(); - for password in invalid_password_test_case() { - let request = UpdateUserRequest { - id: user_detail.id.clone(), - name: None, - email: None, - workspace: None, - password: Some(password), - }; - - assert_eq!( - UserTestBuilder::new() - .event(UpdateUser) - .request(request) - .sync_send() - .error() - .code, - UserErrorCode::PasswordInvalid - ); - } -} - -#[test] -#[serial] -fn user_update_with_invalid_name() { - let user_detail = UserTestBuilder::new().login().user_detail.unwrap(); - let request = UpdateUserRequest { - id: user_detail.id.clone(), - name: Some("".to_string()), - email: None, - workspace: None, - password: None, - }; - - assert_eq!( - UserTestBuilder::new() - .event(UpdateUser) - .request(request) - .sync_send() - .error() - .code, - UserErrorCode::UserNameInvalid - ); -} +// use crate::helper::*; +// use flowy_user::{errors::UserErrorCode, event::UserEvent::*, prelude::*}; +// use serial_test::*; +// +// #[test] +// #[serial] +// fn user_update_with_name() { +// let user_detail = UserTestBuilder::new().login().user_detail.unwrap(); +// let new_name = "hello_world".to_owned(); +// let request = UpdateUserRequest { +// id: user_detail.id.clone(), +// name: Some(new_name.clone()), +// email: None, +// workspace: None, +// password: None, +// }; +// +// let user_detail = UserTestBuilder::new() +// .event(UpdateUser) +// .request(request) +// .sync_send() +// .parse::(); +// +// assert_eq!(user_detail.name, new_name,); +// } +// +// #[test] +// #[serial] +// fn user_update_with_email() { +// let user_detail = UserTestBuilder::new().login().user_detail.unwrap(); +// let new_email = "123@gmai.com".to_owned(); +// let request = UpdateUserRequest { +// id: user_detail.id.clone(), +// name: None, +// email: Some(new_email.clone()), +// workspace: None, +// password: None, +// }; +// +// let user_detail = UserTestBuilder::new() +// .event(UpdateUser) +// .request(request) +// .sync_send() +// .parse::(); +// +// assert_eq!(user_detail.email, new_email,); +// } +// +// #[test] +// #[serial] +// fn user_update_with_password() { +// let user_detail = UserTestBuilder::new().login().user_detail.unwrap(); +// let new_password = "H123world!".to_owned(); +// let request = UpdateUserRequest { +// id: user_detail.id.clone(), +// name: None, +// email: None, +// workspace: None, +// password: Some(new_password.clone()), +// }; +// +// let _ = UserTestBuilder::new() +// .event(UpdateUser) +// .request(request) +// .sync_send() +// .assert_success(); +// } +// +// #[test] +// #[serial] +// fn user_update_with_invalid_email() { +// let user_detail = UserTestBuilder::new().login().user_detail.unwrap(); +// for email in invalid_email_test_case() { +// let request = UpdateUserRequest { +// id: user_detail.id.clone(), +// name: None, +// email: Some(email), +// workspace: None, +// password: None, +// }; +// +// assert_eq!( +// UserTestBuilder::new() +// .event(UpdateUser) +// .request(request) +// .sync_send() +// .error() +// .code, +// UserErrorCode::EmailInvalid +// ); +// } +// } +// +// #[test] +// #[serial] +// fn user_update_with_invalid_password() { +// let user_detail = UserTestBuilder::new().login().user_detail.unwrap(); +// for password in invalid_password_test_case() { +// let request = UpdateUserRequest { +// id: user_detail.id.clone(), +// name: None, +// email: None, +// workspace: None, +// password: Some(password), +// }; +// +// assert_eq!( +// UserTestBuilder::new() +// .event(UpdateUser) +// .request(request) +// .sync_send() +// .error() +// .code, +// UserErrorCode::PasswordInvalid +// ); +// } +// } +// +// #[test] +// #[serial] +// fn user_update_with_invalid_name() { +// let user_detail = UserTestBuilder::new().login().user_detail.unwrap(); +// let request = UpdateUserRequest { +// id: user_detail.id.clone(), +// name: Some("".to_string()), +// email: None, +// workspace: None, +// password: None, +// }; +// +// assert_eq!( +// UserTestBuilder::new() +// .event(UpdateUser) +// .request(request) +// .sync_send() +// .error() +// .code, +// UserErrorCode::UserNameInvalid +// ); +// } From 4364f59e39f69b8611bf3f9aa0d0b54e5b4f8830 Mon Sep 17 00:00:00 2001 From: Jaylen Bian Date: Fri, 16 Jul 2021 16:12:54 +0800 Subject: [PATCH 07/30] [infra_ui][keyboard] (WIP) Add demo proj for infra ui --- .../example/lib/home/demo_item.dart | 17 ++++++++ .../example/lib/home/home_screen.dart | 43 +++++++++++++++++++ .../flowy_infra_ui/example/lib/main.dart | 8 ++++ .../flowy_infra_ui/example/pubspec.lock | 2 +- .../flowy_infra_ui/example/pubspec.yaml | 5 +++ .../lib/src/overlay/overlay_widget.dart | 12 ++++++ 6 files changed, 86 insertions(+), 1 deletion(-) create mode 100644 app_flowy/packages/flowy_infra_ui/example/lib/home/demo_item.dart create mode 100644 app_flowy/packages/flowy_infra_ui/example/lib/home/home_screen.dart create mode 100644 app_flowy/packages/flowy_infra_ui/lib/src/overlay/overlay_widget.dart diff --git a/app_flowy/packages/flowy_infra_ui/example/lib/home/demo_item.dart b/app_flowy/packages/flowy_infra_ui/example/lib/home/demo_item.dart new file mode 100644 index 0000000000..da6051f1c7 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/example/lib/home/demo_item.dart @@ -0,0 +1,17 @@ +import 'package:flutter/material.dart'; + +abstract class ListItem {} + +abstract class DemoItem extends ListItem { + String buildTitle(); + + void handleTap(); +} + +class SectionHeaderItem extends ListItem { + SectionHeaderItem(this.title); + + final String title; + + Widget buildWidget(BuildContext context) => Text(title); +} diff --git a/app_flowy/packages/flowy_infra_ui/example/lib/home/home_screen.dart b/app_flowy/packages/flowy_infra_ui/example/lib/home/home_screen.dart new file mode 100644 index 0000000000..7f0ca3fb6b --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/example/lib/home/home_screen.dart @@ -0,0 +1,43 @@ +import 'package:example/home/demo_item.dart'; +import 'package:flutter/material.dart'; + +class HomeScreen extends StatelessWidget { + const HomeScreen({Key? key}) : super(key: key); + + static List items = [ + SectionHeaderItem('Widget Demos'), + ]; + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text('Demos'), + ), + body: ListView.builder( + itemCount: items.length, + itemBuilder: (context, index) { + final item = items[index]; + if (item is SectionHeaderItem) { + return Container( + constraints: const BoxConstraints(maxHeight: 48.0), + color: Colors.grey[300], + alignment: Alignment.center, + child: ListTile( + title: Text(item.title), + ), + ); + } else if (item is DemoItem) { + return ListTile( + title: Text(item.buildTitle()), + onTap: item.handleTap, + ); + } + return const ListTile( + title: Text('Unknow.'), + ); + }, + ), + ); + } +} diff --git a/app_flowy/packages/flowy_infra_ui/example/lib/main.dart b/app_flowy/packages/flowy_infra_ui/example/lib/main.dart index 9cc621647d..fcaec37764 100644 --- a/app_flowy/packages/flowy_infra_ui/example/lib/main.dart +++ b/app_flowy/packages/flowy_infra_ui/example/lib/main.dart @@ -1,3 +1,4 @@ +import 'package:example/home/home_screen.dart'; import 'package:flutter/material.dart'; void main() { @@ -9,6 +10,13 @@ class ExampleApp extends StatelessWidget { @override Widget build(BuildContext context) { +<<<<<<< HEAD return const MaterialApp(); +======= + return const MaterialApp( + title: "Flowy Infra Title", + home: HomeScreen(), + ); +>>>>>>> [infra_ui][keyboard] (WIP) Add demo proj for infra ui } } diff --git a/app_flowy/packages/flowy_infra_ui/example/pubspec.lock b/app_flowy/packages/flowy_infra_ui/example/pubspec.lock index 999a86c0e7..bf24d5be0c 100644 --- a/app_flowy/packages/flowy_infra_ui/example/pubspec.lock +++ b/app_flowy/packages/flowy_infra_ui/example/pubspec.lock @@ -178,7 +178,7 @@ packages: source: hosted version: "1.8.0" provider: - dependency: transitive + dependency: "direct main" description: name: provider url: "https://pub.dartlang.org" diff --git a/app_flowy/packages/flowy_infra_ui/example/pubspec.yaml b/app_flowy/packages/flowy_infra_ui/example/pubspec.yaml index 901200091e..09ad328ffb 100644 --- a/app_flowy/packages/flowy_infra_ui/example/pubspec.yaml +++ b/app_flowy/packages/flowy_infra_ui/example/pubspec.yaml @@ -10,6 +10,11 @@ dependencies: flutter: sdk: flutter +<<<<<<< HEAD +======= + cupertino_icons: ^1.0.2 + provider: ^5.0.0 +>>>>>>> [infra_ui][keyboard] (WIP) Add demo proj for infra ui flowy_infra_ui: path: ../ diff --git a/app_flowy/packages/flowy_infra_ui/lib/src/overlay/overlay_widget.dart b/app_flowy/packages/flowy_infra_ui/lib/src/overlay/overlay_widget.dart new file mode 100644 index 0000000000..543818fc5c --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/lib/src/overlay/overlay_widget.dart @@ -0,0 +1,12 @@ +import 'package:flutter/material.dart'; + +class Overlay extends StatelessWidget { + const Overlay({Key? key}) : super(key: key); + + final bool safeAreaEnabled; + + @override + Widget build(BuildContext context) { + return Container(); + } +} From be4f6a8250984ee79dd9486320b50471ad594c5f Mon Sep 17 00:00:00 2001 From: Jaylen Bian Date: Sat, 17 Jul 2021 00:08:54 +0800 Subject: [PATCH 08/30] [infra_ui][keyboard] Add keyboard demo entrance --- .../example/lib/home/demo_item.dart | 2 +- .../example/lib/home/home_screen.dart | 6 +- .../example/lib/keyboard/keyboard_screen.dart | 57 +++++++++++++++++++ 3 files changed, 62 insertions(+), 3 deletions(-) create mode 100644 app_flowy/packages/flowy_infra_ui/example/lib/keyboard/keyboard_screen.dart diff --git a/app_flowy/packages/flowy_infra_ui/example/lib/home/demo_item.dart b/app_flowy/packages/flowy_infra_ui/example/lib/home/demo_item.dart index da6051f1c7..361e234231 100644 --- a/app_flowy/packages/flowy_infra_ui/example/lib/home/demo_item.dart +++ b/app_flowy/packages/flowy_infra_ui/example/lib/home/demo_item.dart @@ -5,7 +5,7 @@ abstract class ListItem {} abstract class DemoItem extends ListItem { String buildTitle(); - void handleTap(); + void handleTap(BuildContext context); } class SectionHeaderItem extends ListItem { diff --git a/app_flowy/packages/flowy_infra_ui/example/lib/home/home_screen.dart b/app_flowy/packages/flowy_infra_ui/example/lib/home/home_screen.dart index 7f0ca3fb6b..ca9e17d8c1 100644 --- a/app_flowy/packages/flowy_infra_ui/example/lib/home/home_screen.dart +++ b/app_flowy/packages/flowy_infra_ui/example/lib/home/home_screen.dart @@ -1,11 +1,13 @@ -import 'package:example/home/demo_item.dart'; +import 'package:example/keyboard/keyboard_screen.dart'; import 'package:flutter/material.dart'; +import 'demo_item.dart'; class HomeScreen extends StatelessWidget { const HomeScreen({Key? key}) : super(key: key); static List items = [ SectionHeaderItem('Widget Demos'), + KeyboardItem(), ]; @override @@ -30,7 +32,7 @@ class HomeScreen extends StatelessWidget { } else if (item is DemoItem) { return ListTile( title: Text(item.buildTitle()), - onTap: item.handleTap, + onTap: () => item.handleTap(context), ); } return const ListTile( diff --git a/app_flowy/packages/flowy_infra_ui/example/lib/keyboard/keyboard_screen.dart b/app_flowy/packages/flowy_infra_ui/example/lib/keyboard/keyboard_screen.dart new file mode 100644 index 0000000000..c459f61668 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/example/lib/keyboard/keyboard_screen.dart @@ -0,0 +1,57 @@ +import 'package:flutter/material.dart'; +import '../home/demo_item.dart'; + +class KeyboardItem extends DemoItem { + @override + String buildTitle() => 'Keyboard Listener'; + + @override + void handleTap(BuildContext context) { + Navigator.of(context).push( + MaterialPageRoute( + builder: (context) { + return const KeyboardScreen(); + }, + ), + ); + } +} + +class KeyboardScreen extends StatefulWidget { + const KeyboardScreen({Key? key}) : super(key: key); + + @override + _KeyboardScreenState createState() => _KeyboardScreenState(); +} + +class _KeyboardScreenState extends State { + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text('Keyboard Visibility Demo'), + ), + body: GestureDetector( + onTap: () => _dismissKeyboard(context), + behavior: HitTestBehavior.translucent, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 36), + child: Center( + child: TextField( + style: const TextStyle(fontSize: 20), + controller: TextEditingController(text: 'Test'), + ), + ), + ), + ), + ); + } + + void _dismissKeyboard(BuildContext context) { + final currentFocus = FocusScope.of(context); + + if (!currentFocus.hasPrimaryFocus && currentFocus.hasFocus) { + FocusManager.instance.primaryFocus?.unfocus(); + } + } +} From 1ee5511046a6089937b8b8eda4b5164ce96918b6 Mon Sep 17 00:00:00 2001 From: Jaylen Bian Date: Sat, 17 Jul 2021 00:42:22 +0800 Subject: [PATCH 09/30] [infra_ui][keyboard] Bump infra_ui to 1.20.0 and fix compiling issues --- .../flowy_infra_ui/example/lib/home/home_screen.dart | 2 +- app_flowy/packages/flowy_infra_ui/example/lib/main.dart | 2 +- .../packages/flowy_infra_ui/example/test/widget_test.dart | 4 ++++ .../flowy_infra_ui/lib/src/overlay/overlay_widget.dart | 5 ++++- 4 files changed, 10 insertions(+), 3 deletions(-) diff --git a/app_flowy/packages/flowy_infra_ui/example/lib/home/home_screen.dart b/app_flowy/packages/flowy_infra_ui/example/lib/home/home_screen.dart index ca9e17d8c1..a6b4087417 100644 --- a/app_flowy/packages/flowy_infra_ui/example/lib/home/home_screen.dart +++ b/app_flowy/packages/flowy_infra_ui/example/lib/home/home_screen.dart @@ -1,5 +1,5 @@ -import 'package:example/keyboard/keyboard_screen.dart'; import 'package:flutter/material.dart'; +import '../keyboard/keyboard_screen.dart'; import 'demo_item.dart'; class HomeScreen extends StatelessWidget { diff --git a/app_flowy/packages/flowy_infra_ui/example/lib/main.dart b/app_flowy/packages/flowy_infra_ui/example/lib/main.dart index fcaec37764..35d08970a2 100644 --- a/app_flowy/packages/flowy_infra_ui/example/lib/main.dart +++ b/app_flowy/packages/flowy_infra_ui/example/lib/main.dart @@ -1,5 +1,5 @@ -import 'package:example/home/home_screen.dart'; import 'package:flutter/material.dart'; +import '../home/home_screen.dart'; void main() { runApp(const ExampleApp()); diff --git a/app_flowy/packages/flowy_infra_ui/example/test/widget_test.dart b/app_flowy/packages/flowy_infra_ui/example/test/widget_test.dart index 09c1545e57..198cf4618d 100644 --- a/app_flowy/packages/flowy_infra_ui/example/test/widget_test.dart +++ b/app_flowy/packages/flowy_infra_ui/example/test/widget_test.dart @@ -18,8 +18,12 @@ void main() { // Verify that platform version is retrieved. expect( find.byWidgetPredicate( +<<<<<<< HEAD (Widget widget) => widget is Text && widget.data!.startsWith('Running on:'), +======= + (Widget widget) => widget is Text && widget.data!.startsWith('Running on:'), +>>>>>>> [infra_ui][keyboard] Bump infra_ui to 1.20.0 and fix compiling issues ), findsOneWidget, ); diff --git a/app_flowy/packages/flowy_infra_ui/lib/src/overlay/overlay_widget.dart b/app_flowy/packages/flowy_infra_ui/lib/src/overlay/overlay_widget.dart index 543818fc5c..8d7b427e9b 100644 --- a/app_flowy/packages/flowy_infra_ui/lib/src/overlay/overlay_widget.dart +++ b/app_flowy/packages/flowy_infra_ui/lib/src/overlay/overlay_widget.dart @@ -1,7 +1,10 @@ import 'package:flutter/material.dart'; class Overlay extends StatelessWidget { - const Overlay({Key? key}) : super(key: key); + const Overlay({ + Key? key, + this.safeAreaEnabled = true, + }) : super(key: key); final bool safeAreaEnabled; From b257ca11d0a54586607465545afb38eda92efec6 Mon Sep 17 00:00:00 2001 From: Jaylen Bian Date: Sat, 17 Jul 2021 10:05:18 +0800 Subject: [PATCH 10/30] [infra_ui][keyboard] Change ios plugin to swift and impl ios-side impl --- .../Classes/Event/KeyboardEventHandler.swift | 85 +++++++++++++++++++ .../ios/Classes/SwiftFlowyInfraUiPlugin.swift | 36 ++++++-- 2 files changed, 113 insertions(+), 8 deletions(-) create mode 100644 app_flowy/packages/flowy_infra_ui/ios/Classes/Event/KeyboardEventHandler.swift diff --git a/app_flowy/packages/flowy_infra_ui/ios/Classes/Event/KeyboardEventHandler.swift b/app_flowy/packages/flowy_infra_ui/ios/Classes/Event/KeyboardEventHandler.swift new file mode 100644 index 0000000000..6f7e1f4b25 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/ios/Classes/Event/KeyboardEventHandler.swift @@ -0,0 +1,85 @@ +// +// KeyboardEventHandler.swift +// flowy_infra_ui +// +// Created by Jaylen Bian on 7/17/21. +// + +class KeyboardEventHandler: NSObject, FlutterStreamHandler { + + var isKeyboardShow: Bool = false + var eventSink: FlutterEventSink? + + override init() { + super.init() + + NotificationCenter.default.addObserver( + self, + selector: #selector(handleKeyboardWillShow), + name: UIApplication.keyboardWillShowNotification, + object: nil) + NotificationCenter.default.addObserver( + self, + selector: #selector(handleKeyboardDidShow), + name: UIApplication.keyboardDidShowNotification, + object: nil) + NotificationCenter.default.addObserver( + self, + selector: #selector(handleKeyboardWillHide), + name: UIApplication.keyboardWillHideNotification, + object: nil) + NotificationCenter.default.addObserver( + self, + selector: #selector(handleKeyboardDidHide), + name: UIApplication.keyboardDidHideNotification, + object: nil) + } + + func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { + eventSink = events + return nil + } + + func onCancel(withArguments arguments: Any?) -> FlutterError? { + eventSink = nil + return nil + } + + // MARK: Helper + + @objc + private func handleKeyboardWillShow() { + guard !isKeyboardShow else { + return + } + isKeyboardShow = true + eventSink?(NSNumber(booleanLiteral: true)) + } + + @objc + private func handleKeyboardDidShow() { + guard !isKeyboardShow else { + return + } + isKeyboardShow = true + eventSink?(NSNumber(booleanLiteral: true)) + } + + @objc + private func handleKeyboardWillHide() { + guard isKeyboardShow else { + return + } + isKeyboardShow = false + eventSink?(NSNumber(booleanLiteral: false)) + } + + @objc + private func handleKeyboardDidHide() { + guard isKeyboardShow else { + return + } + isKeyboardShow = false + eventSink?(NSNumber(booleanLiteral: false)) + } +} diff --git a/app_flowy/packages/flowy_infra_ui/ios/Classes/SwiftFlowyInfraUiPlugin.swift b/app_flowy/packages/flowy_infra_ui/ios/Classes/SwiftFlowyInfraUiPlugin.swift index 5459739470..f8e62efe14 100644 --- a/app_flowy/packages/flowy_infra_ui/ios/Classes/SwiftFlowyInfraUiPlugin.swift +++ b/app_flowy/packages/flowy_infra_ui/ios/Classes/SwiftFlowyInfraUiPlugin.swift @@ -2,13 +2,33 @@ import Flutter import UIKit public class SwiftFlowyInfraUiPlugin: NSObject, FlutterPlugin { - public static func register(with registrar: FlutterPluginRegistrar) { - let channel = FlutterMethodChannel(name: "flowy_infra_ui", binaryMessenger: registrar.messenger()) - let instance = SwiftFlowyInfraUiPlugin() - registrar.addMethodCallDelegate(instance, channel: channel) - } - public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { - result("iOS " + UIDevice.current.systemVersion) - } + enum Constant { + static let infraUIMethodChannelName = "flowy_infra_ui_method" + static let infraUIKeyboardEventChannelName = "flowy_infra_ui_event/keyboard" + } + + public static func register(with registrar: FlutterPluginRegistrar) { + let instance = SwiftFlowyInfraUiPlugin() + + let methodChannel = FlutterMethodChannel( + name: Constant.infraUIMethodChannelName, + binaryMessenger: registrar.messenger()) + registrar.addMethodCallDelegate(instance, channel: methodChannel) + + let keyboardEventChannel = FlutterEventChannel( + name: Constant.infraUIKeyboardEventChannelName, + binaryMessenger: registrar.messenger()) + keyboardEventChannel.setStreamHandler(KeyboardEventHandler()) + } + + // MARK: - Method Channel + + public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { + switch call.method { + default: + assertionFailure("Unsupported method \(call.method)") + } + } + } From b227a19c59d00126dece695c959339da85151402 Mon Sep 17 00:00:00 2001 From: Jaylen Bian Date: Sat, 17 Jul 2021 10:07:58 +0800 Subject: [PATCH 11/30] [infra_ui][keyboard] Change android plugin to java --- .../flowy_infra_ui/android/build.gradle | 17 +-------- .../flowy_infra_ui/FlowyInfraUiPlugin.java | 38 +++++++++++++++++++ .../flowy_infra_ui/FlowyInfraUiPlugin.kt | 35 ----------------- .../flowy_infra_ui_example/MainActivity.java | 6 +++ 4 files changed, 45 insertions(+), 51 deletions(-) create mode 100644 app_flowy/packages/flowy_infra_ui/android/src/main/java/com/example/flowy_infra_ui/FlowyInfraUiPlugin.java delete mode 100644 app_flowy/packages/flowy_infra_ui/android/src/main/kotlin/com/example/flowy_infra_ui/FlowyInfraUiPlugin.kt create mode 100644 app_flowy/packages/flowy_infra_ui/example/android/app/src/main/java/com/example/flowy_infra_ui_example/MainActivity.java diff --git a/app_flowy/packages/flowy_infra_ui/android/build.gradle b/app_flowy/packages/flowy_infra_ui/android/build.gradle index f1e1c9e76e..ab675678b5 100644 --- a/app_flowy/packages/flowy_infra_ui/android/build.gradle +++ b/app_flowy/packages/flowy_infra_ui/android/build.gradle @@ -1,8 +1,7 @@ group 'com.example.flowy_infra_ui' -version '1.0-SNAPSHOT' +version '1.0' buildscript { - ext.kotlin_version = '1.3.50' repositories { google() mavenCentral() @@ -10,7 +9,6 @@ buildscript { dependencies { classpath 'com.android.tools.build:gradle:4.1.0' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } @@ -22,7 +20,6 @@ rootProject.allprojects { } apply plugin: 'com.android.library' -apply plugin: 'kotlin-android' android { compileSdkVersion 30 @@ -32,19 +29,7 @@ android { targetCompatibility JavaVersion.VERSION_1_8 } - kotlinOptions { - jvmTarget = '1.8' - } - - sourceSets { - main.java.srcDirs += 'src/main/kotlin' - } - defaultConfig { minSdkVersion 16 } } - -dependencies { - implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" -} diff --git a/app_flowy/packages/flowy_infra_ui/android/src/main/java/com/example/flowy_infra_ui/FlowyInfraUiPlugin.java b/app_flowy/packages/flowy_infra_ui/android/src/main/java/com/example/flowy_infra_ui/FlowyInfraUiPlugin.java new file mode 100644 index 0000000000..9211fe6f4c --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/android/src/main/java/com/example/flowy_infra_ui/FlowyInfraUiPlugin.java @@ -0,0 +1,38 @@ +package com.example.flowy_infra_ui; + +import androidx.annotation.NonNull; + +import io.flutter.embedding.engine.plugins.FlutterPlugin; +import io.flutter.plugin.common.MethodCall; +import io.flutter.plugin.common.MethodChannel; +import io.flutter.plugin.common.MethodChannel.MethodCallHandler; +import io.flutter.plugin.common.MethodChannel.Result; + +/** FlowyInfraUiPlugin */ +public class FlowyInfraUiPlugin implements FlutterPlugin, MethodCallHandler { + /// The MethodChannel that will the communication between Flutter and native Android + /// + /// This local reference serves to register the plugin with the Flutter Engine and unregister it + /// when the Flutter Engine is detached from the Activity + private MethodChannel channel; + + @Override + public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) { + channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "flowy_infra_ui"); + channel.setMethodCallHandler(this); + } + + @Override + public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) { + if (call.method.equals("getPlatformVersion")) { + result.success("Android " + android.os.Build.VERSION.RELEASE); + } else { + result.notImplemented(); + } + } + + @Override + public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) { + channel.setMethodCallHandler(null); + } +} diff --git a/app_flowy/packages/flowy_infra_ui/android/src/main/kotlin/com/example/flowy_infra_ui/FlowyInfraUiPlugin.kt b/app_flowy/packages/flowy_infra_ui/android/src/main/kotlin/com/example/flowy_infra_ui/FlowyInfraUiPlugin.kt deleted file mode 100644 index 5d98dd8f10..0000000000 --- a/app_flowy/packages/flowy_infra_ui/android/src/main/kotlin/com/example/flowy_infra_ui/FlowyInfraUiPlugin.kt +++ /dev/null @@ -1,35 +0,0 @@ -package com.example.flowy_infra_ui - -import androidx.annotation.NonNull - -import io.flutter.embedding.engine.plugins.FlutterPlugin -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel -import io.flutter.plugin.common.MethodChannel.MethodCallHandler -import io.flutter.plugin.common.MethodChannel.Result - -/** FlowyInfraUiPlugin */ -class FlowyInfraUiPlugin: FlutterPlugin, MethodCallHandler { - /// The MethodChannel that will the communication between Flutter and native Android - /// - /// This local reference serves to register the plugin with the Flutter Engine and unregister it - /// when the Flutter Engine is detached from the Activity - private lateinit var channel : MethodChannel - - override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { - channel = MethodChannel(flutterPluginBinding.binaryMessenger, "flowy_infra_ui") - channel.setMethodCallHandler(this) - } - - override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) { - if (call.method == "getPlatformVersion") { - result.success("Android ${android.os.Build.VERSION.RELEASE}") - } else { - result.notImplemented() - } - } - - override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) { - channel.setMethodCallHandler(null) - } -} diff --git a/app_flowy/packages/flowy_infra_ui/example/android/app/src/main/java/com/example/flowy_infra_ui_example/MainActivity.java b/app_flowy/packages/flowy_infra_ui/example/android/app/src/main/java/com/example/flowy_infra_ui_example/MainActivity.java new file mode 100644 index 0000000000..5f08c1b321 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/example/android/app/src/main/java/com/example/flowy_infra_ui_example/MainActivity.java @@ -0,0 +1,6 @@ +package com.example.flowy_infra_ui_example; + +import io.flutter.embedding.android.FlutterActivity; + +public class MainActivity extends FlutterActivity { +} From 915975d522094be726d4566c971220185dbacf58 Mon Sep 17 00:00:00 2001 From: Jaylen Bian Date: Sun, 18 Jul 2021 00:23:14 +0800 Subject: [PATCH 12/30] [infra_ui][keyboard] Impl android support for keyboard --- .../flowy_infra_ui/android/build.gradle | 5 +- .../flowy_infra_ui/FlowyInfraUiPlugin.java | 71 +++++++++++++++---- .../event/KeyboardEventHandler.java | 53 ++++++++++++++ .../example/android/app/build.gradle | 2 +- .../flowy_infra_ui_example/MainActivity.java | 1 + .../flowy_infra_ui_example/MainActivity.kt | 6 -- .../example/android/build.gradle | 2 +- .../gradle/wrapper/gradle-wrapper.properties | 4 +- .../ios/Classes/SwiftFlowyInfraUiPlugin.swift | 6 +- 9 files changed, 122 insertions(+), 28 deletions(-) create mode 100644 app_flowy/packages/flowy_infra_ui/android/src/main/java/com/example/flowy_infra_ui/event/KeyboardEventHandler.java delete mode 100644 app_flowy/packages/flowy_infra_ui/example/android/app/src/main/kotlin/com/example/flowy_infra_ui_example/MainActivity.kt diff --git a/app_flowy/packages/flowy_infra_ui/android/build.gradle b/app_flowy/packages/flowy_infra_ui/android/build.gradle index ab675678b5..76e9272bbf 100644 --- a/app_flowy/packages/flowy_infra_ui/android/build.gradle +++ b/app_flowy/packages/flowy_infra_ui/android/build.gradle @@ -28,8 +28,7 @@ android { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } - - defaultConfig { - minSdkVersion 16 + dependencies { + implementation "androidx.core:core:1.5.0-rc01" } } diff --git a/app_flowy/packages/flowy_infra_ui/android/src/main/java/com/example/flowy_infra_ui/FlowyInfraUiPlugin.java b/app_flowy/packages/flowy_infra_ui/android/src/main/java/com/example/flowy_infra_ui/FlowyInfraUiPlugin.java index 9211fe6f4c..62270ab6ef 100644 --- a/app_flowy/packages/flowy_infra_ui/android/src/main/java/com/example/flowy_infra_ui/FlowyInfraUiPlugin.java +++ b/app_flowy/packages/flowy_infra_ui/android/src/main/java/com/example/flowy_infra_ui/FlowyInfraUiPlugin.java @@ -1,38 +1,81 @@ package com.example.flowy_infra_ui; +import android.app.Activity; + import androidx.annotation.NonNull; +import com.example.flowy_infra_ui.event.KeyboardEventHandler; + import io.flutter.embedding.engine.plugins.FlutterPlugin; +import io.flutter.embedding.engine.plugins.activity.ActivityAware; +import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; +import io.flutter.plugin.common.EventChannel; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugin.common.MethodChannel.MethodCallHandler; import io.flutter.plugin.common.MethodChannel.Result; /** FlowyInfraUiPlugin */ -public class FlowyInfraUiPlugin implements FlutterPlugin, MethodCallHandler { - /// The MethodChannel that will the communication between Flutter and native Android - /// - /// This local reference serves to register the plugin with the Flutter Engine and unregister it - /// when the Flutter Engine is detached from the Activity - private MethodChannel channel; +public class FlowyInfraUiPlugin implements FlutterPlugin, ActivityAware, MethodCallHandler { + + // MARK: - Constant + public static final String INFRA_UI_METHOD_CHANNEL_NAME = "flowy_infra_ui_method"; + public static final String INFRA_UI_KEYBOARD_EVENT_CHANNEL_NAME = "flowy_infra_ui_event/keyboard"; + + public static final String INFRA_UI_METHOD_GET_PLATFORM_VERSION = "getPlatformVersion"; + + // Method Channel + private MethodChannel methodChannel; + // Event Channel + private KeyboardEventHandler keyboardEventHandler = new KeyboardEventHandler(); @Override public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) { - channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "flowy_infra_ui"); - channel.setMethodCallHandler(this); + methodChannel = new MethodChannel( + flutterPluginBinding.getBinaryMessenger(), + INFRA_UI_METHOD_CHANNEL_NAME); + methodChannel.setMethodCallHandler(this); + + final EventChannel keyboardEventChannel = new EventChannel( + flutterPluginBinding.getBinaryMessenger(), + INFRA_UI_KEYBOARD_EVENT_CHANNEL_NAME); + keyboardEventChannel.setStreamHandler(keyboardEventHandler); } + @Override + public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) { + methodChannel.setMethodCallHandler(null); + keyboardEventHandler.cancelObserveKeyboardAction(); + } + + @Override + public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) { + keyboardEventHandler.observeKeyboardAction(binding.getActivity()); + } + + @Override + public void onDetachedFromActivityForConfigChanges() { + keyboardEventHandler.cancelObserveKeyboardAction(); + } + + @Override + public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) { + keyboardEventHandler.observeKeyboardAction(binding.getActivity()); + } + + @Override + public void onDetachedFromActivity() { + keyboardEventHandler.cancelObserveKeyboardAction(); + } + + // MARK: - Method Channel + @Override public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) { - if (call.method.equals("getPlatformVersion")) { + if (call.method.equals(INFRA_UI_METHOD_GET_PLATFORM_VERSION)) { result.success("Android " + android.os.Build.VERSION.RELEASE); } else { result.notImplemented(); } } - - @Override - public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) { - channel.setMethodCallHandler(null); - } } diff --git a/app_flowy/packages/flowy_infra_ui/android/src/main/java/com/example/flowy_infra_ui/event/KeyboardEventHandler.java b/app_flowy/packages/flowy_infra_ui/android/src/main/java/com/example/flowy_infra_ui/event/KeyboardEventHandler.java new file mode 100644 index 0000000000..6462aa6a93 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/android/src/main/java/com/example/flowy_infra_ui/event/KeyboardEventHandler.java @@ -0,0 +1,53 @@ +package com.example.flowy_infra_ui.event; + +import android.app.Activity; +import android.os.Build; +import android.view.View; + +import androidx.annotation.RequiresApi; +import androidx.core.view.OnApplyWindowInsetsListener; +import androidx.core.view.ViewCompat; +import androidx.core.view.WindowInsetsCompat; + +import io.flutter.plugin.common.EventChannel; + +public class KeyboardEventHandler implements EventChannel.StreamHandler { + private EventChannel.EventSink eventSink; + private View rootView; + private boolean isKeyboardShow = false; + + @Override + public void onListen(Object arguments, EventChannel.EventSink events) { + eventSink = events; + } + + @Override + public void onCancel(Object arguments) { + eventSink = null; + } + + // MARK: - Helper + + @RequiresApi(Build.VERSION_CODES.R) + public void observeKeyboardAction(Activity activity) { + rootView = activity.findViewById(android.R.id.content); + + ViewCompat.setOnApplyWindowInsetsListener(rootView, new OnApplyWindowInsetsListener() { + @Override + public WindowInsetsCompat onApplyWindowInsets(View view, WindowInsetsCompat insets) { + isKeyboardShow = insets.isVisible(WindowInsetsCompat.Type.ime()); + if (eventSink != null) { + eventSink.success(isKeyboardShow); + } + return insets; + } + }); + } + + public void cancelObserveKeyboardAction() { + if (rootView != null) { + ViewCompat.setOnApplyWindowInsetsListener(rootView, null); + rootView = null; + } + } +} diff --git a/app_flowy/packages/flowy_infra_ui/example/android/app/build.gradle b/app_flowy/packages/flowy_infra_ui/example/android/app/build.gradle index 7530664892..7356196bc3 100644 --- a/app_flowy/packages/flowy_infra_ui/example/android/app/build.gradle +++ b/app_flowy/packages/flowy_infra_ui/example/android/app/build.gradle @@ -26,7 +26,6 @@ apply plugin: 'kotlin-android' apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" android { - compileSdkVersion 30 compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 @@ -57,6 +56,7 @@ android { signingConfig signingConfigs.debug } } + compileSdkVersion 30 } flutter { diff --git a/app_flowy/packages/flowy_infra_ui/example/android/app/src/main/java/com/example/flowy_infra_ui_example/MainActivity.java b/app_flowy/packages/flowy_infra_ui/example/android/app/src/main/java/com/example/flowy_infra_ui_example/MainActivity.java index 5f08c1b321..8adb012232 100644 --- a/app_flowy/packages/flowy_infra_ui/example/android/app/src/main/java/com/example/flowy_infra_ui_example/MainActivity.java +++ b/app_flowy/packages/flowy_infra_ui/example/android/app/src/main/java/com/example/flowy_infra_ui_example/MainActivity.java @@ -3,4 +3,5 @@ package com.example.flowy_infra_ui_example; import io.flutter.embedding.android.FlutterActivity; public class MainActivity extends FlutterActivity { + } diff --git a/app_flowy/packages/flowy_infra_ui/example/android/app/src/main/kotlin/com/example/flowy_infra_ui_example/MainActivity.kt b/app_flowy/packages/flowy_infra_ui/example/android/app/src/main/kotlin/com/example/flowy_infra_ui_example/MainActivity.kt deleted file mode 100644 index 6c4bb00d45..0000000000 --- a/app_flowy/packages/flowy_infra_ui/example/android/app/src/main/kotlin/com/example/flowy_infra_ui_example/MainActivity.kt +++ /dev/null @@ -1,6 +0,0 @@ -package com.example.flowy_infra_ui_example - -import io.flutter.embedding.android.FlutterActivity - -class MainActivity: FlutterActivity() { -} diff --git a/app_flowy/packages/flowy_infra_ui/example/android/build.gradle b/app_flowy/packages/flowy_infra_ui/example/android/build.gradle index ed45c65885..3dd86e4db3 100644 --- a/app_flowy/packages/flowy_infra_ui/example/android/build.gradle +++ b/app_flowy/packages/flowy_infra_ui/example/android/build.gradle @@ -6,7 +6,7 @@ buildscript { } dependencies { - classpath 'com.android.tools.build:gradle:4.1.0' + classpath 'com.android.tools.build:gradle:4.1.1' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } diff --git a/app_flowy/packages/flowy_infra_ui/example/android/gradle/wrapper/gradle-wrapper.properties b/app_flowy/packages/flowy_infra_ui/example/android/gradle/wrapper/gradle-wrapper.properties index bc6a58afdd..b3e9099d2a 100644 --- a/app_flowy/packages/flowy_infra_ui/example/android/gradle/wrapper/gradle-wrapper.properties +++ b/app_flowy/packages/flowy_infra_ui/example/android/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ -#Fri Jun 23 08:50:38 CEST 2017 +#Sat Jul 17 23:27:26 CST 2021 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-7.1.1-bin.zip diff --git a/app_flowy/packages/flowy_infra_ui/ios/Classes/SwiftFlowyInfraUiPlugin.swift b/app_flowy/packages/flowy_infra_ui/ios/Classes/SwiftFlowyInfraUiPlugin.swift index f8e62efe14..39b9a47a04 100644 --- a/app_flowy/packages/flowy_infra_ui/ios/Classes/SwiftFlowyInfraUiPlugin.swift +++ b/app_flowy/packages/flowy_infra_ui/ios/Classes/SwiftFlowyInfraUiPlugin.swift @@ -6,6 +6,8 @@ public class SwiftFlowyInfraUiPlugin: NSObject, FlutterPlugin { enum Constant { static let infraUIMethodChannelName = "flowy_infra_ui_method" static let infraUIKeyboardEventChannelName = "flowy_infra_ui_event/keyboard" + + static let infraUIMethodGetPlatformVersion = "getPlatformVersion" } public static func register(with registrar: FlutterPluginRegistrar) { @@ -26,8 +28,10 @@ public class SwiftFlowyInfraUiPlugin: NSObject, FlutterPlugin { public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { switch call.method { + case Constant.infraUIMethodGetPlatformVersion: + result("iOS " + UIDevice.current.systemVersion) default: - assertionFailure("Unsupported method \(call.method)") + result(FlutterMethodNotImplemented) } } From e41579bc652d2cfac62897eb747abda89b5fab83 Mon Sep 17 00:00:00 2001 From: Jaylen Bian Date: Sun, 18 Jul 2021 10:55:18 +0800 Subject: [PATCH 13/30] [infra_ui][focus] Impl auto unfocus widget for infra ui --- .../flowy_infra_ui/.vscode/launch.json | 11 ++++++ .../flowy_infra_ui/android/.classpath | 6 ++++ .../packages/flowy_infra_ui/android/.project | 34 +++++++++++++++++++ .../org.eclipse.buildship.core.prefs | 2 ++ .../flowy_infra_ui/example/android/.project | 28 +++++++++++++++ .../org.eclipse.buildship.core.prefs | 13 +++++++ .../example/android/app/.classpath | 6 ++++ .../example/android/app/.project | 34 +++++++++++++++++++ .../org.eclipse.buildship.core.prefs | 2 ++ .../lib/src/focus/auto_unfocus_overlay.dart | 26 ++++++++++++++ .../lib/src/keyboard/keyboard_.dart | 0 11 files changed, 162 insertions(+) create mode 100644 app_flowy/packages/flowy_infra_ui/.vscode/launch.json create mode 100644 app_flowy/packages/flowy_infra_ui/android/.classpath create mode 100644 app_flowy/packages/flowy_infra_ui/android/.project create mode 100644 app_flowy/packages/flowy_infra_ui/android/.settings/org.eclipse.buildship.core.prefs create mode 100644 app_flowy/packages/flowy_infra_ui/example/android/.project create mode 100644 app_flowy/packages/flowy_infra_ui/example/android/.settings/org.eclipse.buildship.core.prefs create mode 100644 app_flowy/packages/flowy_infra_ui/example/android/app/.classpath create mode 100644 app_flowy/packages/flowy_infra_ui/example/android/app/.project create mode 100644 app_flowy/packages/flowy_infra_ui/example/android/app/.settings/org.eclipse.buildship.core.prefs create mode 100644 app_flowy/packages/flowy_infra_ui/lib/src/focus/auto_unfocus_overlay.dart create mode 100644 app_flowy/packages/flowy_infra_ui/lib/src/keyboard/keyboard_.dart diff --git a/app_flowy/packages/flowy_infra_ui/.vscode/launch.json b/app_flowy/packages/flowy_infra_ui/.vscode/launch.json new file mode 100644 index 0000000000..ba345105b4 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/.vscode/launch.json @@ -0,0 +1,11 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Infra UI Example", + "type": "dart", + "request": "launch", + "program": "example/lib/main.dart" + }, + ] +} \ No newline at end of file diff --git a/app_flowy/packages/flowy_infra_ui/android/.classpath b/app_flowy/packages/flowy_infra_ui/android/.classpath new file mode 100644 index 0000000000..4a04201ca2 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/android/.classpath @@ -0,0 +1,6 @@ + + + + + + diff --git a/app_flowy/packages/flowy_infra_ui/android/.project b/app_flowy/packages/flowy_infra_ui/android/.project new file mode 100644 index 0000000000..77aded223a --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/android/.project @@ -0,0 +1,34 @@ + + + flowy_infra_ui + Project flowy_infra_ui created by Buildship. + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.buildship.core.gradleprojectbuilder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.buildship.core.gradleprojectnature + + + + 1626576261667 + + 30 + + org.eclipse.core.resources.regexFilterMatcher + node_modules|.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__ + + + + diff --git a/app_flowy/packages/flowy_infra_ui/android/.settings/org.eclipse.buildship.core.prefs b/app_flowy/packages/flowy_infra_ui/android/.settings/org.eclipse.buildship.core.prefs new file mode 100644 index 0000000000..e8895216fd --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/android/.settings/org.eclipse.buildship.core.prefs @@ -0,0 +1,2 @@ +connection.project.dir= +eclipse.preferences.version=1 diff --git a/app_flowy/packages/flowy_infra_ui/example/android/.project b/app_flowy/packages/flowy_infra_ui/example/android/.project new file mode 100644 index 0000000000..b06fea48c8 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/example/android/.project @@ -0,0 +1,28 @@ + + + android + Project android created by Buildship. + + + + + org.eclipse.buildship.core.gradleprojectbuilder + + + + + + org.eclipse.buildship.core.gradleprojectnature + + + + 1626576261654 + + 30 + + org.eclipse.core.resources.regexFilterMatcher + node_modules|.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__ + + + + diff --git a/app_flowy/packages/flowy_infra_ui/example/android/.settings/org.eclipse.buildship.core.prefs b/app_flowy/packages/flowy_infra_ui/example/android/.settings/org.eclipse.buildship.core.prefs new file mode 100644 index 0000000000..25e4212285 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/example/android/.settings/org.eclipse.buildship.core.prefs @@ -0,0 +1,13 @@ +arguments= +auto.sync=false +build.scans.enabled=false +connection.gradle.distribution=GRADLE_DISTRIBUTION(WRAPPER) +connection.project.dir= +eclipse.preferences.version=1 +gradle.user.home= +java.home=/Library/Java/JavaVirtualMachines/jdk11.0.5-zulu.jdk/Contents/Home +jvm.arguments= +offline.mode=false +override.workspace.settings=true +show.console.view=true +show.executions.view=true diff --git a/app_flowy/packages/flowy_infra_ui/example/android/app/.classpath b/app_flowy/packages/flowy_infra_ui/example/android/app/.classpath new file mode 100644 index 0000000000..4a04201ca2 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/example/android/app/.classpath @@ -0,0 +1,6 @@ + + + + + + diff --git a/app_flowy/packages/flowy_infra_ui/example/android/app/.project b/app_flowy/packages/flowy_infra_ui/example/android/app/.project new file mode 100644 index 0000000000..df522843d5 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/example/android/app/.project @@ -0,0 +1,34 @@ + + + app + Project app created by Buildship. + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.buildship.core.gradleprojectbuilder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.buildship.core.gradleprojectnature + + + + 1626576261660 + + 30 + + org.eclipse.core.resources.regexFilterMatcher + node_modules|.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__ + + + + diff --git a/app_flowy/packages/flowy_infra_ui/example/android/app/.settings/org.eclipse.buildship.core.prefs b/app_flowy/packages/flowy_infra_ui/example/android/app/.settings/org.eclipse.buildship.core.prefs new file mode 100644 index 0000000000..b1886adb46 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/example/android/app/.settings/org.eclipse.buildship.core.prefs @@ -0,0 +1,2 @@ +connection.project.dir=.. +eclipse.preferences.version=1 diff --git a/app_flowy/packages/flowy_infra_ui/lib/src/focus/auto_unfocus_overlay.dart b/app_flowy/packages/flowy_infra_ui/lib/src/focus/auto_unfocus_overlay.dart new file mode 100644 index 0000000000..45faebc07d --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/lib/src/focus/auto_unfocus_overlay.dart @@ -0,0 +1,26 @@ +import 'package:flutter/material.dart'; + +class AutoUnfocus extends StatelessWidget { + const AutoUnfocus({ + Key? key, + required this.child, + }) : super(key: key); + + final Widget child; + + @override + Widget build(BuildContext context) { + return GestureDetector( + onTap: () => _unfocusWidget(context), + child: child, + ); + } + + void _unfocusWidget(BuildContext context) { + final focusing = FocusScope.of(context); + + if (!focusing.hasPrimaryFocus && focusing.hasFocus) { + FocusManager.instance.primaryFocus?.unfocus(); + } + } +} diff --git a/app_flowy/packages/flowy_infra_ui/lib/src/keyboard/keyboard_.dart b/app_flowy/packages/flowy_infra_ui/lib/src/keyboard/keyboard_.dart new file mode 100644 index 0000000000..e69de29bb2 From fa7be4bea77028124978f6aa18bf7194887b9f22 Mon Sep 17 00:00:00 2001 From: Jaylen Bian Date: Sun, 18 Jul 2021 12:05:09 +0800 Subject: [PATCH 14/30] [infra_ui][keyboard] Impl keyboard platform interface --- .../keyboard_platform_interface/.gitignore | 75 ++++++++ .../keyboard_platform_interface/.metadata | 10 ++ .../keyboard_platform_interface/CHANGELOG.md | 3 + .../keyboard_platform_interface/LICENSE | 1 + .../keyboard_platform_interface/README.md | 14 ++ .../analysis_options.yaml | 4 + .../lib/keyboard_platform_interface.dart | 23 +++ .../lib/src/method_channel_keyboard.dart | 17 ++ .../keyboard_platform_interface/pubspec.lock | 168 ++++++++++++++++++ .../keyboard_platform_interface/pubspec.yaml | 21 +++ .../keyboard_platform_interface_test.dart | 5 + 11 files changed, 341 insertions(+) create mode 100644 app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/.gitignore create mode 100644 app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/.metadata create mode 100644 app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/CHANGELOG.md create mode 100644 app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/LICENSE create mode 100644 app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/README.md create mode 100644 app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/analysis_options.yaml create mode 100644 app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/lib/keyboard_platform_interface.dart create mode 100644 app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/lib/src/method_channel_keyboard.dart create mode 100644 app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/pubspec.lock create mode 100644 app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/pubspec.yaml create mode 100644 app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/test/keyboard_platform_interface_test.dart diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/.gitignore b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/.gitignore new file mode 100644 index 0000000000..a247422ef7 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/.gitignore @@ -0,0 +1,75 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.packages +.pub-cache/ +.pub/ +build/ + +# Android related +**/android/**/gradle-wrapper.jar +**/android/.gradle +**/android/captures/ +**/android/gradlew +**/android/gradlew.bat +**/android/local.properties +**/android/**/GeneratedPluginRegistrant.java + +# iOS/XCode related +**/ios/**/*.mode1v3 +**/ios/**/*.mode2v3 +**/ios/**/*.moved-aside +**/ios/**/*.pbxuser +**/ios/**/*.perspectivev3 +**/ios/**/*sync/ +**/ios/**/.sconsign.dblite +**/ios/**/.tags* +**/ios/**/.vagrant/ +**/ios/**/DerivedData/ +**/ios/**/Icon? +**/ios/**/Pods/ +**/ios/**/.symlinks/ +**/ios/**/profile +**/ios/**/xcuserdata +**/ios/.generated/ +**/ios/Flutter/App.framework +**/ios/Flutter/Flutter.framework +**/ios/Flutter/Flutter.podspec +**/ios/Flutter/Generated.xcconfig +**/ios/Flutter/ephemeral +**/ios/Flutter/app.flx +**/ios/Flutter/app.zip +**/ios/Flutter/flutter_assets/ +**/ios/Flutter/flutter_export_environment.sh +**/ios/ServiceDefinitions.json +**/ios/Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!**/ios/**/default.mode1v3 +!**/ios/**/default.mode2v3 +!**/ios/**/default.pbxuser +!**/ios/**/default.perspectivev3 diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/.metadata b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/.metadata new file mode 100644 index 0000000000..f46c92994f --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/.metadata @@ -0,0 +1,10 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: fa5883b78e566877613ad1ccb48dd92075cb5c23 + channel: dev + +project_type: package diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/CHANGELOG.md b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/CHANGELOG.md new file mode 100644 index 0000000000..41cc7d8192 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/CHANGELOG.md @@ -0,0 +1,3 @@ +## 0.0.1 + +* TODO: Describe initial release. diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/LICENSE b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/LICENSE new file mode 100644 index 0000000000..ba75c69f7f --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/LICENSE @@ -0,0 +1 @@ +TODO: Add your license here. diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/README.md b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/README.md new file mode 100644 index 0000000000..19f51139a6 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/README.md @@ -0,0 +1,14 @@ +# keyboard_platform_interface + +A new Flutter package project. + +## Getting Started + +This project is a starting point for a Dart +[package](https://flutter.dev/developing-packages/), +a library module containing code that can be shared easily across +multiple Flutter or Dart projects. + +For help getting started with Flutter, view our +[online documentation](https://flutter.dev/docs), which offers tutorials, +samples, guidance on mobile development, and a full API reference. diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/analysis_options.yaml b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/analysis_options.yaml new file mode 100644 index 0000000000..a5744c1cfb --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/analysis_options.yaml @@ -0,0 +1,4 @@ +include: package:flutter_lints/flutter.yaml + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/lib/keyboard_platform_interface.dart b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/lib/keyboard_platform_interface.dart new file mode 100644 index 0000000000..2fd5a82661 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/lib/keyboard_platform_interface.dart @@ -0,0 +1,23 @@ +library keyboard_platform_interface; + +import 'package:plugin_platform_interface/plugin_platform_interface.dart'; +import 'src/method_channel_keyboard.dart'; + +abstract class KeyboardPlatform extends PlatformInterface { + KeyboardPlatform() : super(token: _token); + + static final Object _token = Object(); + + static KeyboardPlatform _instance = MethodChannelKeyboard(); + + static KeyboardPlatform get instance => _instance; + + static set instance(KeyboardPlatform instance) { + PlatformInterface.verifyToken(instance, _token); + _instance = instance; + } + + Stream get onKeyboardChange { + throw UnimplementedError('`onKeyboardChange` should be overrided by subclass.'); + } +} diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/lib/src/method_channel_keyboard.dart b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/lib/src/method_channel_keyboard.dart new file mode 100644 index 0000000000..f543df69fd --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/lib/src/method_channel_keyboard.dart @@ -0,0 +1,17 @@ +import 'dart:html'; + +import 'package:flutter/services.dart'; + +import '../keyboard_platform_interface.dart'; + +// ignore: constant_identifier_names +const INFRA_UI_KEYBOARD_EVENT_CHANNEL_NAME = "flowy_infra_ui_event/keyboard"; + +class MethodChannelKeyboard extends KeyboardPlatform { + final EventChannel _keyboardChannel = const EventChannel(INFRA_UI_KEYBOARD_EVENT_CHANNEL_NAME); + + late final Stream _onKeyboardChange = _keyboardChannel.receiveBroadcastStream().map((event) => event as bool); + + @override + Stream get onKeyboardChange => _onKeyboardChange; +} diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/pubspec.lock b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/pubspec.lock new file mode 100644 index 0000000000..a2ed8a8fe8 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/pubspec.lock @@ -0,0 +1,168 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + async: + dependency: transitive + description: + name: async + url: "https://pub.dartlang.org" + source: hosted + version: "2.6.1" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.0" + characters: + dependency: transitive + description: + name: characters + url: "https://pub.dartlang.org" + source: hosted + version: "1.1.0" + charcode: + dependency: transitive + description: + name: charcode + url: "https://pub.dartlang.org" + source: hosted + version: "1.2.0" + clock: + dependency: transitive + description: + name: clock + url: "https://pub.dartlang.org" + source: hosted + version: "1.1.0" + collection: + dependency: transitive + description: + name: collection + url: "https://pub.dartlang.org" + source: hosted + version: "1.15.0" + fake_async: + dependency: transitive + description: + name: fake_async + url: "https://pub.dartlang.org" + source: hosted + version: "1.2.0" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.4" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + lints: + dependency: transitive + description: + name: lints + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.1" + matcher: + dependency: transitive + description: + name: matcher + url: "https://pub.dartlang.org" + source: hosted + version: "0.12.10" + meta: + dependency: transitive + description: + name: meta + url: "https://pub.dartlang.org" + source: hosted + version: "1.3.0" + path: + dependency: transitive + description: + name: path + url: "https://pub.dartlang.org" + source: hosted + version: "1.8.0" + plugin_platform_interface: + dependency: "direct main" + description: + name: plugin_platform_interface + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.1" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.99" + source_span: + dependency: transitive + description: + name: source_span + url: "https://pub.dartlang.org" + source: hosted + version: "1.8.1" + stack_trace: + dependency: transitive + description: + name: stack_trace + url: "https://pub.dartlang.org" + source: hosted + version: "1.10.0" + stream_channel: + dependency: transitive + description: + name: stream_channel + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.0" + string_scanner: + dependency: transitive + description: + name: string_scanner + url: "https://pub.dartlang.org" + source: hosted + version: "1.1.0" + term_glyph: + dependency: transitive + description: + name: term_glyph + url: "https://pub.dartlang.org" + source: hosted + version: "1.2.0" + test_api: + dependency: transitive + description: + name: test_api + url: "https://pub.dartlang.org" + source: hosted + version: "0.3.0" + typed_data: + dependency: transitive + description: + name: typed_data + url: "https://pub.dartlang.org" + source: hosted + version: "1.3.0" + vector_math: + dependency: transitive + description: + name: vector_math + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.0" +sdks: + dart: ">=2.12.0 <3.0.0" + flutter: ">=1.17.0" diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/pubspec.yaml b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/pubspec.yaml new file mode 100644 index 0000000000..800a97c674 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/pubspec.yaml @@ -0,0 +1,21 @@ +name: keyboard_platform_interface +description: A new Flutter package project. +version: 0.0.1 +homepage: + +environment: + sdk: ">=2.12.0 <3.0.0" + flutter: ">=1.17.0" + +dependencies: + flutter: + sdk: flutter + + plugin_platform_interface: ^2.0.0 + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^1.0.0 + +flutter: diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/test/keyboard_platform_interface_test.dart b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/test/keyboard_platform_interface_test.dart new file mode 100644 index 0000000000..815becdd47 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/test/keyboard_platform_interface_test.dart @@ -0,0 +1,5 @@ +import 'package:flutter_test/flutter_test.dart'; + +import 'package:keyboard_platform_interface/keyboard_platform_interface.dart'; + +void main() {} From cb3ed0a3086289872450359a1b0786c8eeb1ee26 Mon Sep 17 00:00:00 2001 From: Jaylen Bian Date: Sun, 18 Jul 2021 12:12:48 +0800 Subject: [PATCH 15/30] [infra_ui][keyboard] Impl keyboard_web for flutter federated platform interface --- .../keyboard_web/.gitignore | 75 +++++++ .../platform_interface/keyboard_web/.metadata | 10 + .../keyboard_web/CHANGELOG.md | 3 + .../platform_interface/keyboard_web/LICENSE | 1 + .../platform_interface/keyboard_web/README.md | 14 ++ .../keyboard_web/analysis_options.yaml | 4 + .../keyboard_web/lib/keyboard_web.dart | 7 + .../keyboard_web/pubspec.lock | 187 ++++++++++++++++++ .../keyboard_web/pubspec.yaml | 27 +++ .../keyboard_web/test/keyboard_web_test.dart | 12 ++ 10 files changed, 340 insertions(+) create mode 100644 app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/.gitignore create mode 100644 app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/.metadata create mode 100644 app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/CHANGELOG.md create mode 100644 app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/LICENSE create mode 100644 app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/README.md create mode 100644 app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/analysis_options.yaml create mode 100644 app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/lib/keyboard_web.dart create mode 100644 app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/pubspec.lock create mode 100644 app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/pubspec.yaml create mode 100644 app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/test/keyboard_web_test.dart diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/.gitignore b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/.gitignore new file mode 100644 index 0000000000..a247422ef7 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/.gitignore @@ -0,0 +1,75 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.packages +.pub-cache/ +.pub/ +build/ + +# Android related +**/android/**/gradle-wrapper.jar +**/android/.gradle +**/android/captures/ +**/android/gradlew +**/android/gradlew.bat +**/android/local.properties +**/android/**/GeneratedPluginRegistrant.java + +# iOS/XCode related +**/ios/**/*.mode1v3 +**/ios/**/*.mode2v3 +**/ios/**/*.moved-aside +**/ios/**/*.pbxuser +**/ios/**/*.perspectivev3 +**/ios/**/*sync/ +**/ios/**/.sconsign.dblite +**/ios/**/.tags* +**/ios/**/.vagrant/ +**/ios/**/DerivedData/ +**/ios/**/Icon? +**/ios/**/Pods/ +**/ios/**/.symlinks/ +**/ios/**/profile +**/ios/**/xcuserdata +**/ios/.generated/ +**/ios/Flutter/App.framework +**/ios/Flutter/Flutter.framework +**/ios/Flutter/Flutter.podspec +**/ios/Flutter/Generated.xcconfig +**/ios/Flutter/ephemeral +**/ios/Flutter/app.flx +**/ios/Flutter/app.zip +**/ios/Flutter/flutter_assets/ +**/ios/Flutter/flutter_export_environment.sh +**/ios/ServiceDefinitions.json +**/ios/Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!**/ios/**/default.mode1v3 +!**/ios/**/default.mode2v3 +!**/ios/**/default.pbxuser +!**/ios/**/default.perspectivev3 diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/.metadata b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/.metadata new file mode 100644 index 0000000000..f46c92994f --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/.metadata @@ -0,0 +1,10 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: fa5883b78e566877613ad1ccb48dd92075cb5c23 + channel: dev + +project_type: package diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/CHANGELOG.md b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/CHANGELOG.md new file mode 100644 index 0000000000..41cc7d8192 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/CHANGELOG.md @@ -0,0 +1,3 @@ +## 0.0.1 + +* TODO: Describe initial release. diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/LICENSE b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/LICENSE new file mode 100644 index 0000000000..ba75c69f7f --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/LICENSE @@ -0,0 +1 @@ +TODO: Add your license here. diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/README.md b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/README.md new file mode 100644 index 0000000000..94b4102a22 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/README.md @@ -0,0 +1,14 @@ +# keyboard_web + +A new Flutter package project. + +## Getting Started + +This project is a starting point for a Dart +[package](https://flutter.dev/developing-packages/), +a library module containing code that can be shared easily across +multiple Flutter or Dart projects. + +For help getting started with Flutter, view our +[online documentation](https://flutter.dev/docs), which offers tutorials, +samples, guidance on mobile development, and a full API reference. diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/analysis_options.yaml b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/analysis_options.yaml new file mode 100644 index 0000000000..a5744c1cfb --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/analysis_options.yaml @@ -0,0 +1,4 @@ +include: package:flutter_lints/flutter.yaml + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/lib/keyboard_web.dart b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/lib/keyboard_web.dart new file mode 100644 index 0000000000..ca61d9ed4a --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/lib/keyboard_web.dart @@ -0,0 +1,7 @@ +library keyboard_web; + +/// A Calculator. +class Calculator { + /// Returns [value] plus 1. + int addOne(int value) => value + 1; +} diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/pubspec.lock b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/pubspec.lock new file mode 100644 index 0000000000..4508a8bebb --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/pubspec.lock @@ -0,0 +1,187 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + async: + dependency: transitive + description: + name: async + url: "https://pub.dartlang.org" + source: hosted + version: "2.6.1" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.0" + characters: + dependency: transitive + description: + name: characters + url: "https://pub.dartlang.org" + source: hosted + version: "1.1.0" + charcode: + dependency: transitive + description: + name: charcode + url: "https://pub.dartlang.org" + source: hosted + version: "1.2.0" + clock: + dependency: transitive + description: + name: clock + url: "https://pub.dartlang.org" + source: hosted + version: "1.1.0" + collection: + dependency: transitive + description: + name: collection + url: "https://pub.dartlang.org" + source: hosted + version: "1.15.0" + fake_async: + dependency: transitive + description: + name: fake_async + url: "https://pub.dartlang.org" + source: hosted + version: "1.2.0" + flutter: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.4" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + flutter_web_plugins: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + js: + dependency: transitive + description: + name: js + url: "https://pub.dartlang.org" + source: hosted + version: "0.6.3" + keyboard_platform_interface: + dependency: "direct main" + description: + path: "../keyboard_platform_interface" + relative: true + source: path + version: "0.0.1" + lints: + dependency: transitive + description: + name: lints + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.1" + matcher: + dependency: transitive + description: + name: matcher + url: "https://pub.dartlang.org" + source: hosted + version: "0.12.10" + meta: + dependency: transitive + description: + name: meta + url: "https://pub.dartlang.org" + source: hosted + version: "1.3.0" + path: + dependency: transitive + description: + name: path + url: "https://pub.dartlang.org" + source: hosted + version: "1.8.0" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.1" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.99" + source_span: + dependency: transitive + description: + name: source_span + url: "https://pub.dartlang.org" + source: hosted + version: "1.8.1" + stack_trace: + dependency: transitive + description: + name: stack_trace + url: "https://pub.dartlang.org" + source: hosted + version: "1.10.0" + stream_channel: + dependency: transitive + description: + name: stream_channel + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.0" + string_scanner: + dependency: transitive + description: + name: string_scanner + url: "https://pub.dartlang.org" + source: hosted + version: "1.1.0" + term_glyph: + dependency: transitive + description: + name: term_glyph + url: "https://pub.dartlang.org" + source: hosted + version: "1.2.0" + test_api: + dependency: transitive + description: + name: test_api + url: "https://pub.dartlang.org" + source: hosted + version: "0.3.0" + typed_data: + dependency: transitive + description: + name: typed_data + url: "https://pub.dartlang.org" + source: hosted + version: "1.3.0" + vector_math: + dependency: transitive + description: + name: vector_math + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.0" +sdks: + dart: ">=2.12.0 <3.0.0" + flutter: ">=1.17.0" diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/pubspec.yaml b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/pubspec.yaml new file mode 100644 index 0000000000..8e1fa906cb --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/pubspec.yaml @@ -0,0 +1,27 @@ +name: keyboard_web +description: A new Flutter package project. +version: 0.0.1 +homepage: + +environment: + sdk: ">=2.12.0 <3.0.0" + flutter: ">=1.17.0" + +dependencies: + flutter_web_plugins: + sdk: flutter + + keyboard_platform_interface: + path: ../keyboard_platform_interface + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^1.0.0 + +flutter: + plugin: + platforms: + web: + pluginClass: KeyboardPlugin + fileName: keyboard_web \ No newline at end of file diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/test/keyboard_web_test.dart b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/test/keyboard_web_test.dart new file mode 100644 index 0000000000..095c2544ca --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/test/keyboard_web_test.dart @@ -0,0 +1,12 @@ +import 'package:flutter_test/flutter_test.dart'; + +import 'package:keyboard_web/keyboard_web.dart'; + +void main() { + test('adds one to input values', () { + final calculator = Calculator(); + expect(calculator.addOne(2), 3); + expect(calculator.addOne(-7), -6); + expect(calculator.addOne(0), 1); + }); +} From 5e6c0142260df864c602538b69c5ccfa3ccd928c Mon Sep 17 00:00:00 2001 From: Jaylen Bian Date: Sun, 18 Jul 2021 13:07:32 +0800 Subject: [PATCH 16/30] [infra_ui] Refactor platform interface to infra_ui scope and remove keyboard interface --- .../Flutter/GeneratedPluginRegistrant.swift | 2 +- .../flowy_infra_ui/example/pubspec.lock | 21 +++++++++++++++ .../flutter/generated_plugin_registrant.cc | 6 ++--- .../.gitignore | 0 .../.metadata | 0 .../CHANGELOG.md | 0 .../LICENSE | 0 .../README.md | 2 +- .../analysis_options.yaml | 0 .../flowy_infra_ui_platform_interface.dart | 27 +++++++++++++++++++ .../src/method_channel_flowy_infra_ui.dart | 26 ++++++++++++++++++ .../pubspec.lock | 0 .../pubspec.yaml | 6 ++--- ...lowy_infra_ui_platform_interface_test.dart | 5 ++++ .../.gitignore | 0 .../.metadata | 0 .../CHANGELOG.md | 0 .../LICENSE | 0 .../README.md | 2 +- .../analysis_options.yaml | 0 .../lib/flowy_infra_ui_web.dart | 23 ++++++++++++++++ .../pubspec.lock | 14 +++++----- .../pubspec.yaml | 11 ++++---- .../test/flowy_infra_ui_web_test.dart | 5 ++++ .../lib/keyboard_platform_interface.dart | 23 ---------------- .../lib/src/method_channel_keyboard.dart | 17 ------------ .../keyboard_platform_interface_test.dart | 5 ---- .../keyboard_web/lib/keyboard_web.dart | 7 ----- .../keyboard_web/test/keyboard_web_test.dart | 12 --------- .../packages/flowy_infra_ui/pubspec.lock | 23 +++++++++++++++- .../packages/flowy_infra_ui/pubspec.yaml | 21 +++++++++------ 31 files changed, 164 insertions(+), 94 deletions(-) rename app_flowy/packages/flowy_infra_ui/{platform_interface/keyboard_platform_interface => flowy_infra_ui_platform_interface}/.gitignore (100%) rename app_flowy/packages/flowy_infra_ui/{platform_interface/keyboard_platform_interface => flowy_infra_ui_platform_interface}/.metadata (100%) rename app_flowy/packages/flowy_infra_ui/{platform_interface/keyboard_platform_interface => flowy_infra_ui_platform_interface}/CHANGELOG.md (100%) rename app_flowy/packages/flowy_infra_ui/{platform_interface/keyboard_platform_interface => flowy_infra_ui_platform_interface}/LICENSE (100%) rename app_flowy/packages/flowy_infra_ui/{platform_interface/keyboard_platform_interface => flowy_infra_ui_platform_interface}/README.md (92%) rename app_flowy/packages/flowy_infra_ui/{platform_interface/keyboard_platform_interface => flowy_infra_ui_platform_interface}/analysis_options.yaml (100%) create mode 100644 app_flowy/packages/flowy_infra_ui/flowy_infra_ui_platform_interface/lib/flowy_infra_ui_platform_interface.dart create mode 100644 app_flowy/packages/flowy_infra_ui/flowy_infra_ui_platform_interface/lib/src/method_channel_flowy_infra_ui.dart rename app_flowy/packages/flowy_infra_ui/{platform_interface/keyboard_platform_interface => flowy_infra_ui_platform_interface}/pubspec.lock (100%) rename app_flowy/packages/flowy_infra_ui/{platform_interface/keyboard_platform_interface => flowy_infra_ui_platform_interface}/pubspec.yaml (85%) create mode 100644 app_flowy/packages/flowy_infra_ui/flowy_infra_ui_platform_interface/test/flowy_infra_ui_platform_interface_test.dart rename app_flowy/packages/flowy_infra_ui/{platform_interface/keyboard_web => flowy_infra_ui_web}/.gitignore (100%) rename app_flowy/packages/flowy_infra_ui/{platform_interface/keyboard_web => flowy_infra_ui_web}/.metadata (100%) rename app_flowy/packages/flowy_infra_ui/{platform_interface/keyboard_web => flowy_infra_ui_web}/CHANGELOG.md (100%) rename app_flowy/packages/flowy_infra_ui/{platform_interface/keyboard_web => flowy_infra_ui_web}/LICENSE (100%) rename app_flowy/packages/flowy_infra_ui/{platform_interface/keyboard_web => flowy_infra_ui_web}/README.md (95%) rename app_flowy/packages/flowy_infra_ui/{platform_interface/keyboard_web => flowy_infra_ui_web}/analysis_options.yaml (100%) create mode 100644 app_flowy/packages/flowy_infra_ui/flowy_infra_ui_web/lib/flowy_infra_ui_web.dart rename app_flowy/packages/flowy_infra_ui/{platform_interface/keyboard_web => flowy_infra_ui_web}/pubspec.lock (97%) rename app_flowy/packages/flowy_infra_ui/{platform_interface/keyboard_web => flowy_infra_ui_web}/pubspec.yaml (59%) create mode 100644 app_flowy/packages/flowy_infra_ui/flowy_infra_ui_web/test/flowy_infra_ui_web_test.dart delete mode 100644 app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/lib/keyboard_platform_interface.dart delete mode 100644 app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/lib/src/method_channel_keyboard.dart delete mode 100644 app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/test/keyboard_platform_interface_test.dart delete mode 100644 app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/lib/keyboard_web.dart delete mode 100644 app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/test/keyboard_web_test.dart diff --git a/app_flowy/packages/flowy_infra_ui/example/macos/Flutter/GeneratedPluginRegistrant.swift b/app_flowy/packages/flowy_infra_ui/example/macos/Flutter/GeneratedPluginRegistrant.swift index fe63258f95..0c920d5387 100644 --- a/app_flowy/packages/flowy_infra_ui/example/macos/Flutter/GeneratedPluginRegistrant.swift +++ b/app_flowy/packages/flowy_infra_ui/example/macos/Flutter/GeneratedPluginRegistrant.swift @@ -8,5 +8,5 @@ import Foundation import flowy_infra_ui func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { - FlowyInfraUiPlugin.register(with: registry.registrar(forPlugin: "FlowyInfraUiPlugin")) + FlowyInfraUIPlugin.register(with: registry.registrar(forPlugin: "FlowyInfraUIPlugin")) } diff --git a/app_flowy/packages/flowy_infra_ui/example/pubspec.lock b/app_flowy/packages/flowy_infra_ui/example/pubspec.lock index bf24d5be0c..7b3e7031d3 100644 --- a/app_flowy/packages/flowy_infra_ui/example/pubspec.lock +++ b/app_flowy/packages/flowy_infra_ui/example/pubspec.lock @@ -99,6 +99,20 @@ packages: relative: true source: path version: "0.0.1" + flowy_infra_ui_platform_interface: + dependency: transitive + description: + path: "../flowy_infra_ui_platform_interface" + relative: true + source: path + version: "0.0.1" + flowy_infra_ui_web: + dependency: transitive + description: + path: "../flowy_infra_ui_web" + relative: true + source: path + version: "0.0.1" flutter: dependency: "direct main" description: flutter @@ -177,6 +191,13 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "1.8.0" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.1" provider: dependency: "direct main" description: diff --git a/app_flowy/packages/flowy_infra_ui/example/windows/flutter/generated_plugin_registrant.cc b/app_flowy/packages/flowy_infra_ui/example/windows/flutter/generated_plugin_registrant.cc index eb5983d9f8..0f8fb4aef5 100644 --- a/app_flowy/packages/flowy_infra_ui/example/windows/flutter/generated_plugin_registrant.cc +++ b/app_flowy/packages/flowy_infra_ui/example/windows/flutter/generated_plugin_registrant.cc @@ -4,9 +4,9 @@ #include "generated_plugin_registrant.h" -#include +#include void RegisterPlugins(flutter::PluginRegistry* registry) { - FlowyInfraUiPluginRegisterWithRegistrar( - registry->GetRegistrarForPlugin("FlowyInfraUiPlugin")); + FlowyInfraUIPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FlowyInfraUIPlugin")); } diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/.gitignore b/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_platform_interface/.gitignore similarity index 100% rename from app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/.gitignore rename to app_flowy/packages/flowy_infra_ui/flowy_infra_ui_platform_interface/.gitignore diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/.metadata b/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_platform_interface/.metadata similarity index 100% rename from app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/.metadata rename to app_flowy/packages/flowy_infra_ui/flowy_infra_ui_platform_interface/.metadata diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/CHANGELOG.md b/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_platform_interface/CHANGELOG.md similarity index 100% rename from app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/CHANGELOG.md rename to app_flowy/packages/flowy_infra_ui/flowy_infra_ui_platform_interface/CHANGELOG.md diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/LICENSE b/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_platform_interface/LICENSE similarity index 100% rename from app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/LICENSE rename to app_flowy/packages/flowy_infra_ui/flowy_infra_ui_platform_interface/LICENSE diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/README.md b/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_platform_interface/README.md similarity index 92% rename from app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/README.md rename to app_flowy/packages/flowy_infra_ui/flowy_infra_ui_platform_interface/README.md index 19f51139a6..d4b7622cef 100644 --- a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/README.md +++ b/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_platform_interface/README.md @@ -1,4 +1,4 @@ -# keyboard_platform_interface +# flowy_infra_ui_platform_interface A new Flutter package project. diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/analysis_options.yaml b/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_platform_interface/analysis_options.yaml similarity index 100% rename from app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/analysis_options.yaml rename to app_flowy/packages/flowy_infra_ui/flowy_infra_ui_platform_interface/analysis_options.yaml diff --git a/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_platform_interface/lib/flowy_infra_ui_platform_interface.dart b/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_platform_interface/lib/flowy_infra_ui_platform_interface.dart new file mode 100644 index 0000000000..32ac147886 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_platform_interface/lib/flowy_infra_ui_platform_interface.dart @@ -0,0 +1,27 @@ +library flowy_infra_ui_platform_interface; + +import 'package:plugin_platform_interface/plugin_platform_interface.dart'; +import 'src/method_channel_flowy_infra_ui.dart'; + +abstract class FlowyInfraUIPlatform extends PlatformInterface { + FlowyInfraUIPlatform() : super(token: _token); + + static final Object _token = Object(); + + static FlowyInfraUIPlatform _instance = MethodChannelFlowyInfraUI(); + + static FlowyInfraUIPlatform get instance => _instance; + + static set instance(FlowyInfraUIPlatform instance) { + PlatformInterface.verifyToken(instance, _token); + _instance = instance; + } + + Stream get onKeyboardVisibilityChange { + throw UnimplementedError('`onKeyboardChange` should be overrided by subclass.'); + } + + Future getPlatformVersion() { + throw UnimplementedError('`getPlatformVersion` should be overrided by subclass.'); + } +} diff --git a/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_platform_interface/lib/src/method_channel_flowy_infra_ui.dart b/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_platform_interface/lib/src/method_channel_flowy_infra_ui.dart new file mode 100644 index 0000000000..067636ad8b --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_platform_interface/lib/src/method_channel_flowy_infra_ui.dart @@ -0,0 +1,26 @@ +import 'package:flowy_infra_ui_platform_interface/flowy_infra_ui_platform_interface.dart'; +import 'package:flutter/services.dart'; + +import '../flowy_infra_ui_platform_interface.dart'; + +// ignore: constant_identifier_names +const INFRA_UI_METHOD_CHANNEL_NAME = 'flowy_infra_ui_method'; +const INFRA_UI_KEYBOARD_EVENT_CHANNEL_NAME = 'flowy_infra_ui_event/keyboard'; +const INFRA_UI_METHOD_GET_PLATFORM_VERSION = 'getPlatformVersion'; + +class MethodChannelFlowyInfraUI extends FlowyInfraUIPlatform { + final MethodChannel _methodChannel = const MethodChannel(INFRA_UI_METHOD_CHANNEL_NAME); + final EventChannel _keyboardChannel = const EventChannel(INFRA_UI_KEYBOARD_EVENT_CHANNEL_NAME); + + late final Stream _onKeyboardVisibilityChange = + _keyboardChannel.receiveBroadcastStream().map((event) => event as bool); + + @override + Stream get onKeyboardVisibilityChange => _onKeyboardVisibilityChange; + + @override + Future getPlatformVersion() async { + String? version = await _methodChannel.invokeMethod(INFRA_UI_METHOD_GET_PLATFORM_VERSION); + return version ?? 'unknow'; + } +} diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/pubspec.lock b/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_platform_interface/pubspec.lock similarity index 100% rename from app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/pubspec.lock rename to app_flowy/packages/flowy_infra_ui/flowy_infra_ui_platform_interface/pubspec.lock diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/pubspec.yaml b/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_platform_interface/pubspec.yaml similarity index 85% rename from app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/pubspec.yaml rename to app_flowy/packages/flowy_infra_ui/flowy_infra_ui_platform_interface/pubspec.yaml index 800a97c674..0b5f8eb74b 100644 --- a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/pubspec.yaml +++ b/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_platform_interface/pubspec.yaml @@ -1,4 +1,4 @@ -name: keyboard_platform_interface +name: flowy_infra_ui_platform_interface description: A new Flutter package project. version: 0.0.1 homepage: @@ -10,7 +10,7 @@ environment: dependencies: flutter: sdk: flutter - + plugin_platform_interface: ^2.0.0 dev_dependencies: @@ -18,4 +18,4 @@ dev_dependencies: sdk: flutter flutter_lints: ^1.0.0 -flutter: +flutter: \ No newline at end of file diff --git a/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_platform_interface/test/flowy_infra_ui_platform_interface_test.dart b/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_platform_interface/test/flowy_infra_ui_platform_interface_test.dart new file mode 100644 index 0000000000..b351001e1a --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_platform_interface/test/flowy_infra_ui_platform_interface_test.dart @@ -0,0 +1,5 @@ +import 'package:flutter_test/flutter_test.dart'; + +import 'package:flowy_infra_ui_platform_interface/flowy_infra_ui_platform_interface.dart'; + +void main() {} diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/.gitignore b/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_web/.gitignore similarity index 100% rename from app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/.gitignore rename to app_flowy/packages/flowy_infra_ui/flowy_infra_ui_web/.gitignore diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/.metadata b/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_web/.metadata similarity index 100% rename from app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/.metadata rename to app_flowy/packages/flowy_infra_ui/flowy_infra_ui_web/.metadata diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/CHANGELOG.md b/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_web/CHANGELOG.md similarity index 100% rename from app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/CHANGELOG.md rename to app_flowy/packages/flowy_infra_ui/flowy_infra_ui_web/CHANGELOG.md diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/LICENSE b/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_web/LICENSE similarity index 100% rename from app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/LICENSE rename to app_flowy/packages/flowy_infra_ui/flowy_infra_ui_web/LICENSE diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/README.md b/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_web/README.md similarity index 95% rename from app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/README.md rename to app_flowy/packages/flowy_infra_ui/flowy_infra_ui_web/README.md index 94b4102a22..b552d83994 100644 --- a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/README.md +++ b/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_web/README.md @@ -1,4 +1,4 @@ -# keyboard_web +# flowy_infra_ui_web A new Flutter package project. diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/analysis_options.yaml b/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_web/analysis_options.yaml similarity index 100% rename from app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/analysis_options.yaml rename to app_flowy/packages/flowy_infra_ui/flowy_infra_ui_web/analysis_options.yaml diff --git a/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_web/lib/flowy_infra_ui_web.dart b/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_web/lib/flowy_infra_ui_web.dart new file mode 100644 index 0000000000..98a7864942 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_web/lib/flowy_infra_ui_web.dart @@ -0,0 +1,23 @@ +library flowy_infra_ui_web; + +import 'package:flowy_infra_ui_platform_interface/flowy_infra_ui_platform_interface.dart'; +import 'package:flutter_web_plugins/flutter_web_plugins.dart'; + +class FlowyInfraUIPlugin extends FlowyInfraUIPlatform { + static void registerWith(Registrar registrar) { + FlowyInfraUIPlatform.instance = FlowyInfraUIPlugin(); + } + + // MARK: - Keyboard + + @override + Stream get onKeyboardVisibilityChange async* { + // suppose that keyboard won't show in web side + yield false; + } + + @override + Future getPlatformVersion() async { + return 'Web: unknow version'; + } +} diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/pubspec.lock b/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_web/pubspec.lock similarity index 97% rename from app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/pubspec.lock rename to app_flowy/packages/flowy_infra_ui/flowy_infra_ui_web/pubspec.lock index 4508a8bebb..804b67b5b9 100644 --- a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/pubspec.lock +++ b/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_web/pubspec.lock @@ -50,6 +50,13 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "1.2.0" + flowy_infra_ui_platform_interface: + dependency: "direct main" + description: + path: "../flowy_infra_ui_platform_interface" + relative: true + source: path + version: "0.0.1" flutter: dependency: transitive description: flutter @@ -79,13 +86,6 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "0.6.3" - keyboard_platform_interface: - dependency: "direct main" - description: - path: "../keyboard_platform_interface" - relative: true - source: path - version: "0.0.1" lints: dependency: transitive description: diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/pubspec.yaml b/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_web/pubspec.yaml similarity index 59% rename from app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/pubspec.yaml rename to app_flowy/packages/flowy_infra_ui/flowy_infra_ui_web/pubspec.yaml index 8e1fa906cb..03600f2e5a 100644 --- a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/pubspec.yaml +++ b/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_web/pubspec.yaml @@ -1,7 +1,8 @@ -name: keyboard_web +name: flowy_infra_ui_web description: A new Flutter package project. version: 0.0.1 homepage: +publish_to: none environment: sdk: ">=2.12.0 <3.0.0" @@ -11,8 +12,8 @@ dependencies: flutter_web_plugins: sdk: flutter - keyboard_platform_interface: - path: ../keyboard_platform_interface + flowy_infra_ui_platform_interface: + path: ../flowy_infra_ui_platform_interface dev_dependencies: flutter_test: @@ -23,5 +24,5 @@ flutter: plugin: platforms: web: - pluginClass: KeyboardPlugin - fileName: keyboard_web \ No newline at end of file + pluginClass: FlowyInfraUIPlugin + fileName: flowy_infra_ui_web.dart \ No newline at end of file diff --git a/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_web/test/flowy_infra_ui_web_test.dart b/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_web/test/flowy_infra_ui_web_test.dart new file mode 100644 index 0000000000..a9de9b8be5 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_web/test/flowy_infra_ui_web_test.dart @@ -0,0 +1,5 @@ +import 'package:flutter_test/flutter_test.dart'; + +import 'package:flowy_infra_ui_web/flowy_infra_ui_web.dart'; + +void main() {} diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/lib/keyboard_platform_interface.dart b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/lib/keyboard_platform_interface.dart deleted file mode 100644 index 2fd5a82661..0000000000 --- a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/lib/keyboard_platform_interface.dart +++ /dev/null @@ -1,23 +0,0 @@ -library keyboard_platform_interface; - -import 'package:plugin_platform_interface/plugin_platform_interface.dart'; -import 'src/method_channel_keyboard.dart'; - -abstract class KeyboardPlatform extends PlatformInterface { - KeyboardPlatform() : super(token: _token); - - static final Object _token = Object(); - - static KeyboardPlatform _instance = MethodChannelKeyboard(); - - static KeyboardPlatform get instance => _instance; - - static set instance(KeyboardPlatform instance) { - PlatformInterface.verifyToken(instance, _token); - _instance = instance; - } - - Stream get onKeyboardChange { - throw UnimplementedError('`onKeyboardChange` should be overrided by subclass.'); - } -} diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/lib/src/method_channel_keyboard.dart b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/lib/src/method_channel_keyboard.dart deleted file mode 100644 index f543df69fd..0000000000 --- a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/lib/src/method_channel_keyboard.dart +++ /dev/null @@ -1,17 +0,0 @@ -import 'dart:html'; - -import 'package:flutter/services.dart'; - -import '../keyboard_platform_interface.dart'; - -// ignore: constant_identifier_names -const INFRA_UI_KEYBOARD_EVENT_CHANNEL_NAME = "flowy_infra_ui_event/keyboard"; - -class MethodChannelKeyboard extends KeyboardPlatform { - final EventChannel _keyboardChannel = const EventChannel(INFRA_UI_KEYBOARD_EVENT_CHANNEL_NAME); - - late final Stream _onKeyboardChange = _keyboardChannel.receiveBroadcastStream().map((event) => event as bool); - - @override - Stream get onKeyboardChange => _onKeyboardChange; -} diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/test/keyboard_platform_interface_test.dart b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/test/keyboard_platform_interface_test.dart deleted file mode 100644 index 815becdd47..0000000000 --- a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_platform_interface/test/keyboard_platform_interface_test.dart +++ /dev/null @@ -1,5 +0,0 @@ -import 'package:flutter_test/flutter_test.dart'; - -import 'package:keyboard_platform_interface/keyboard_platform_interface.dart'; - -void main() {} diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/lib/keyboard_web.dart b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/lib/keyboard_web.dart deleted file mode 100644 index ca61d9ed4a..0000000000 --- a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/lib/keyboard_web.dart +++ /dev/null @@ -1,7 +0,0 @@ -library keyboard_web; - -/// A Calculator. -class Calculator { - /// Returns [value] plus 1. - int addOne(int value) => value + 1; -} diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/test/keyboard_web_test.dart b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/test/keyboard_web_test.dart deleted file mode 100644 index 095c2544ca..0000000000 --- a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/test/keyboard_web_test.dart +++ /dev/null @@ -1,12 +0,0 @@ -import 'package:flutter_test/flutter_test.dart'; - -import 'package:keyboard_web/keyboard_web.dart'; - -void main() { - test('adds one to input values', () { - final calculator = Calculator(); - expect(calculator.addOne(2), 3); - expect(calculator.addOne(-7), -6); - expect(calculator.addOne(0), 1); - }); -} diff --git a/app_flowy/packages/flowy_infra_ui/pubspec.lock b/app_flowy/packages/flowy_infra_ui/pubspec.lock index db0559ecf9..9b2f5e6a79 100644 --- a/app_flowy/packages/flowy_infra_ui/pubspec.lock +++ b/app_flowy/packages/flowy_infra_ui/pubspec.lock @@ -85,6 +85,20 @@ packages: relative: true source: path version: "0.0.1" + flowy_infra_ui_platform_interface: + dependency: "direct main" + description: + path: flowy_infra_ui_platform_interface + relative: true + source: path + version: "0.0.1" + flowy_infra_ui_web: + dependency: "direct main" + description: + path: flowy_infra_ui_web + relative: true + source: path + version: "0.0.1" flutter: dependency: "direct main" description: flutter @@ -103,7 +117,7 @@ packages: source: sdk version: "0.0.0" flutter_web_plugins: - dependency: "direct main" + dependency: transitive description: flutter source: sdk version: "0.0.0" @@ -163,6 +177,13 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "1.8.0" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.1" provider: dependency: "direct main" description: diff --git a/app_flowy/packages/flowy_infra_ui/pubspec.yaml b/app_flowy/packages/flowy_infra_ui/pubspec.yaml index d1af8afe3d..fec0ebe4a1 100644 --- a/app_flowy/packages/flowy_infra_ui/pubspec.yaml +++ b/app_flowy/packages/flowy_infra_ui/pubspec.yaml @@ -11,8 +11,7 @@ environment: dependencies: flutter: sdk: flutter - flutter_web_plugins: - sdk: flutter + # Thirdparty packages textstyle_extensions: '2.0.0-nullsafety' dartz: '0.10.0-nullsafety.2' @@ -20,6 +19,13 @@ dependencies: styled_widget: '>=0.3.1' equatable: '>=2.0.2' animations: ^2.0.0 + + # Federated Platform Interface + flowy_infra_ui_platform_interface: + path: flowy_infra_ui_platform_interface + flowy_infra_ui_web: + path: flowy_infra_ui_web + # Flowy packages flowy_infra: path: ../flowy_infra @@ -34,13 +40,12 @@ flutter: platforms: android: package: com.example.flowy_infra_ui - pluginClass: FlowyInfraUiPlugin + pluginClass: FlowyInfraUIPlugin ios: - pluginClass: FlowyInfraUiPlugin + pluginClass: FlowyInfraUIPlugin macos: - pluginClass: FlowyInfraUiPlugin + pluginClass: FlowyInfraUIPlugin windows: - pluginClass: FlowyInfraUiPlugin + pluginClass: FlowyInfraUIPlugin web: - pluginClass: FlowyInfraUiWeb - fileName: flowy_infra_ui_web.dart \ No newline at end of file + default_package: flowy_infra_ui_web \ No newline at end of file From 54fd7448995a680b947e4aaae39b500d7b640881 Mon Sep 17 00:00:00 2001 From: Jaylen Bian Date: Sun, 18 Jul 2021 14:14:05 +0800 Subject: [PATCH 17/30] [infra_ui] Integrate keyboard detector to example proj --- .../flowy_infra_ui/FlowyInfraUiPlugin.java | 4 +- .../flowy_infra_ui/FlowyInfraUiPlugin.kt | 35 +++++++++ .../flowy_infra_ui_example/MainActivity.kt | 6 ++ .../flowy_infra_ui/example/ios/Podfile.lock | 22 ------ .../ios/Runner.xcodeproj/project.pbxproj | 69 ------------------ .../contents.xcworkspacedata | 3 - .../example/lib/keyboard/keyboard_screen.dart | 31 +++++--- .../flowy_infra_ui/example/pubspec.lock | 2 +- .../flowy_infra_ui/example/pubspec.yaml | 3 + .../example/test/widget_test.dart | 5 -- .../src/method_channel_flowy_infra_ui.dart | 2 +- .../lib/flowy_infra_ui_web.dart | 4 +- .../ios/Classes/FlowyInfraUIPlugin.h | 4 + ...wyInfraUiPlugin.m => FlowyInfraUIPlugin.m} | 6 +- .../ios/Classes/FlowyInfraUiPlugin.h | 4 - ...in.swift => SwiftFlowyInfraUIPlugin.swift} | 4 +- .../flowy_infra_ui/lib/flowy_infra_ui.dart | 15 +--- .../lib/flowy_infra_ui_web.dart | 46 +----------- .../lib/src/keyboard/keyboard_.dart | 0 .../keyboard_visibility_detector.dart | 73 +++++++++++++++++++ .../macos/Classes/FlowyInfraUiPlugin.swift | 4 +- .../keyboard_web/lib/keyboard_web.dart | 16 ++++ .../windows/flowy_infra_ui_plugin.cpp | 20 ++--- .../flowy_infra_ui/flowy_infra_ui_plugin.h | 2 +- 24 files changed, 188 insertions(+), 192 deletions(-) create mode 100644 app_flowy/packages/flowy_infra_ui/android/src/main/kotlin/com/example/flowy_infra_ui/FlowyInfraUiPlugin.kt create mode 100644 app_flowy/packages/flowy_infra_ui/example/android/app/src/main/kotlin/com/example/flowy_infra_ui_example/MainActivity.kt delete mode 100644 app_flowy/packages/flowy_infra_ui/example/ios/Podfile.lock create mode 100644 app_flowy/packages/flowy_infra_ui/ios/Classes/FlowyInfraUIPlugin.h rename app_flowy/packages/flowy_infra_ui/ios/Classes/{FlowyInfraUiPlugin.m => FlowyInfraUIPlugin.m} (78%) delete mode 100644 app_flowy/packages/flowy_infra_ui/ios/Classes/FlowyInfraUiPlugin.h rename app_flowy/packages/flowy_infra_ui/ios/Classes/{SwiftFlowyInfraUiPlugin.swift => SwiftFlowyInfraUIPlugin.swift} (91%) delete mode 100644 app_flowy/packages/flowy_infra_ui/lib/src/keyboard/keyboard_.dart create mode 100644 app_flowy/packages/flowy_infra_ui/lib/src/keyboard/keyboard_visibility_detector.dart create mode 100644 app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/lib/keyboard_web.dart diff --git a/app_flowy/packages/flowy_infra_ui/android/src/main/java/com/example/flowy_infra_ui/FlowyInfraUiPlugin.java b/app_flowy/packages/flowy_infra_ui/android/src/main/java/com/example/flowy_infra_ui/FlowyInfraUiPlugin.java index 62270ab6ef..e93c990e62 100644 --- a/app_flowy/packages/flowy_infra_ui/android/src/main/java/com/example/flowy_infra_ui/FlowyInfraUiPlugin.java +++ b/app_flowy/packages/flowy_infra_ui/android/src/main/java/com/example/flowy_infra_ui/FlowyInfraUiPlugin.java @@ -15,8 +15,8 @@ import io.flutter.plugin.common.MethodChannel; import io.flutter.plugin.common.MethodChannel.MethodCallHandler; import io.flutter.plugin.common.MethodChannel.Result; -/** FlowyInfraUiPlugin */ -public class FlowyInfraUiPlugin implements FlutterPlugin, ActivityAware, MethodCallHandler { +/** FlowyInfraUIPlugin */ +public class FlowyInfraUIPlugin implements FlutterPlugin, ActivityAware, MethodCallHandler { // MARK: - Constant public static final String INFRA_UI_METHOD_CHANNEL_NAME = "flowy_infra_ui_method"; diff --git a/app_flowy/packages/flowy_infra_ui/android/src/main/kotlin/com/example/flowy_infra_ui/FlowyInfraUiPlugin.kt b/app_flowy/packages/flowy_infra_ui/android/src/main/kotlin/com/example/flowy_infra_ui/FlowyInfraUiPlugin.kt new file mode 100644 index 0000000000..5d98dd8f10 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/android/src/main/kotlin/com/example/flowy_infra_ui/FlowyInfraUiPlugin.kt @@ -0,0 +1,35 @@ +package com.example.flowy_infra_ui + +import androidx.annotation.NonNull + +import io.flutter.embedding.engine.plugins.FlutterPlugin +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import io.flutter.plugin.common.MethodChannel.MethodCallHandler +import io.flutter.plugin.common.MethodChannel.Result + +/** FlowyInfraUiPlugin */ +class FlowyInfraUiPlugin: FlutterPlugin, MethodCallHandler { + /// The MethodChannel that will the communication between Flutter and native Android + /// + /// This local reference serves to register the plugin with the Flutter Engine and unregister it + /// when the Flutter Engine is detached from the Activity + private lateinit var channel : MethodChannel + + override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { + channel = MethodChannel(flutterPluginBinding.binaryMessenger, "flowy_infra_ui") + channel.setMethodCallHandler(this) + } + + override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) { + if (call.method == "getPlatformVersion") { + result.success("Android ${android.os.Build.VERSION.RELEASE}") + } else { + result.notImplemented() + } + } + + override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) { + channel.setMethodCallHandler(null) + } +} diff --git a/app_flowy/packages/flowy_infra_ui/example/android/app/src/main/kotlin/com/example/flowy_infra_ui_example/MainActivity.kt b/app_flowy/packages/flowy_infra_ui/example/android/app/src/main/kotlin/com/example/flowy_infra_ui_example/MainActivity.kt new file mode 100644 index 0000000000..6c4bb00d45 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/example/android/app/src/main/kotlin/com/example/flowy_infra_ui_example/MainActivity.kt @@ -0,0 +1,6 @@ +package com.example.flowy_infra_ui_example + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity: FlutterActivity() { +} diff --git a/app_flowy/packages/flowy_infra_ui/example/ios/Podfile.lock b/app_flowy/packages/flowy_infra_ui/example/ios/Podfile.lock deleted file mode 100644 index c5a50f2dc9..0000000000 --- a/app_flowy/packages/flowy_infra_ui/example/ios/Podfile.lock +++ /dev/null @@ -1,22 +0,0 @@ -PODS: - - flowy_infra_ui (0.0.1): - - Flutter - - Flutter (1.0.0) - -DEPENDENCIES: - - flowy_infra_ui (from `.symlinks/plugins/flowy_infra_ui/ios`) - - Flutter (from `Flutter`) - -EXTERNAL SOURCES: - flowy_infra_ui: - :path: ".symlinks/plugins/flowy_infra_ui/ios" - Flutter: - :path: Flutter - -SPEC CHECKSUMS: - flowy_infra_ui: 146c88346fd55d2ee6a41ae35059a5bf095cfbb3 - Flutter: 434fef37c0980e73bb6479ef766c45957d4b510c - -PODFILE CHECKSUM: aafe91acc616949ddb318b77800a7f51bffa2a4c - -COCOAPODS: 1.9.3 diff --git a/app_flowy/packages/flowy_infra_ui/example/ios/Runner.xcodeproj/project.pbxproj b/app_flowy/packages/flowy_infra_ui/example/ios/Runner.xcodeproj/project.pbxproj index eb8f7f7e87..6eb94532cf 100644 --- a/app_flowy/packages/flowy_infra_ui/example/ios/Runner.xcodeproj/project.pbxproj +++ b/app_flowy/packages/flowy_infra_ui/example/ios/Runner.xcodeproj/project.pbxproj @@ -9,7 +9,6 @@ /* Begin PBXBuildFile section */ 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; - 73D88840D6ADB1B9C000C539 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CA749E34E8D549849F119B5B /* Pods_Runner.framework */; }; 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; @@ -33,7 +32,6 @@ 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; - 3CA8F348EBCAB0B9417EC70D /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; @@ -44,9 +42,6 @@ 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - BD462F555277405D97D69F24 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; - C010FCE60C748638851A2DFA /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; - CA749E34E8D549849F119B5B /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -54,32 +49,12 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 73D88840D6ADB1B9C000C539 /* Pods_Runner.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 2A04BAC54BC6D85A998F0000 /* Frameworks */ = { - isa = PBXGroup; - children = ( - CA749E34E8D549849F119B5B /* Pods_Runner.framework */, - ); - name = Frameworks; - sourceTree = ""; - }; - 8F8024933033E730415889FC /* Pods */ = { - isa = PBXGroup; - children = ( - C010FCE60C748638851A2DFA /* Pods-Runner.debug.xcconfig */, - BD462F555277405D97D69F24 /* Pods-Runner.release.xcconfig */, - 3CA8F348EBCAB0B9417EC70D /* Pods-Runner.profile.xcconfig */, - ); - name = Pods; - path = Pods; - sourceTree = ""; - }; 9740EEB11CF90186004384FC /* Flutter */ = { isa = PBXGroup; children = ( @@ -97,8 +72,6 @@ 9740EEB11CF90186004384FC /* Flutter */, 97C146F01CF9000F007C117D /* Runner */, 97C146EF1CF9000F007C117D /* Products */, - 8F8024933033E730415889FC /* Pods */, - 2A04BAC54BC6D85A998F0000 /* Frameworks */, ); sourceTree = ""; }; @@ -132,14 +105,12 @@ isa = PBXNativeTarget; buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( - 653DE1EFE700467C4AF71781 /* [CP] Check Pods Manifest.lock */, 9740EEB61CF901F6004384FC /* Run Script */, 97C146EA1CF9000F007C117D /* Sources */, 97C146EB1CF9000F007C117D /* Frameworks */, 97C146EC1CF9000F007C117D /* Resources */, 9705A1C41CF9048500538489 /* Embed Frameworks */, 3B06AD1E1E4923F5004D2608 /* Thin Binary */, - C71338FE5F010950C936DB01 /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); @@ -212,28 +183,6 @@ shellPath = /bin/sh; shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; }; - 653DE1EFE700467C4AF71781 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; 9740EEB61CF901F6004384FC /* Run Script */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; @@ -248,24 +197,6 @@ shellPath = /bin/sh; shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; }; - C71338FE5F010950C936DB01 /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh", - "${BUILT_PRODUCTS_DIR}/flowy_infra_ui/flowy_infra_ui.framework", - ); - name = "[CP] Embed Pods Frameworks"; - outputPaths = ( - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/flowy_infra_ui.framework", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ diff --git a/app_flowy/packages/flowy_infra_ui/example/ios/Runner.xcworkspace/contents.xcworkspacedata b/app_flowy/packages/flowy_infra_ui/example/ios/Runner.xcworkspace/contents.xcworkspacedata index 21a3cc14c7..1d526a16ed 100644 --- a/app_flowy/packages/flowy_infra_ui/example/ios/Runner.xcworkspace/contents.xcworkspacedata +++ b/app_flowy/packages/flowy_infra_ui/example/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -4,7 +4,4 @@ - - diff --git a/app_flowy/packages/flowy_infra_ui/example/lib/keyboard/keyboard_screen.dart b/app_flowy/packages/flowy_infra_ui/example/lib/keyboard/keyboard_screen.dart index c459f61668..dcd11fe0e2 100644 --- a/app_flowy/packages/flowy_infra_ui/example/lib/keyboard/keyboard_screen.dart +++ b/app_flowy/packages/flowy_infra_ui/example/lib/keyboard/keyboard_screen.dart @@ -1,3 +1,4 @@ +import 'package:flowy_infra_ui/flowy_infra_ui_web.dart'; import 'package:flutter/material.dart'; import '../home/demo_item.dart'; @@ -25,21 +26,33 @@ class KeyboardScreen extends StatefulWidget { } class _KeyboardScreenState extends State { + bool _isKeyboardVisible = false; + @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Keyboard Visibility Demo'), ), - body: GestureDetector( - onTap: () => _dismissKeyboard(context), - behavior: HitTestBehavior.translucent, - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 36), - child: Center( - child: TextField( - style: const TextStyle(fontSize: 20), - controller: TextEditingController(text: 'Test'), + body: KeyboardVisibilityDetector( + onKeyboardVisibilityChange: (isKeyboardVisible) { + setState(() => _isKeyboardVisible = isKeyboardVisible); + }, + child: GestureDetector( + onTap: () => _dismissKeyboard(context), + behavior: HitTestBehavior.translucent, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 36), + child: Center( + child: Column( + children: [ + Text('Keyboard Visible: $_isKeyboardVisible'), + TextField( + style: const TextStyle(fontSize: 20), + controller: TextEditingController(text: 'Test'), + ), + ], + ), ), ), ), diff --git a/app_flowy/packages/flowy_infra_ui/example/pubspec.lock b/app_flowy/packages/flowy_infra_ui/example/pubspec.lock index 7b3e7031d3..48fb2300d9 100644 --- a/app_flowy/packages/flowy_infra_ui/example/pubspec.lock +++ b/app_flowy/packages/flowy_infra_ui/example/pubspec.lock @@ -199,7 +199,7 @@ packages: source: hosted version: "2.0.1" provider: - dependency: "direct main" + dependency: transitive description: name: provider url: "https://pub.dartlang.org" diff --git a/app_flowy/packages/flowy_infra_ui/example/pubspec.yaml b/app_flowy/packages/flowy_infra_ui/example/pubspec.yaml index 09ad328ffb..4b3c5ac678 100644 --- a/app_flowy/packages/flowy_infra_ui/example/pubspec.yaml +++ b/app_flowy/packages/flowy_infra_ui/example/pubspec.yaml @@ -13,8 +13,11 @@ dependencies: <<<<<<< HEAD ======= cupertino_icons: ^1.0.2 +<<<<<<< HEAD provider: ^5.0.0 >>>>>>> [infra_ui][keyboard] (WIP) Add demo proj for infra ui +======= +>>>>>>> [infra_ui] Integrate keyboard detector to example proj flowy_infra_ui: path: ../ diff --git a/app_flowy/packages/flowy_infra_ui/example/test/widget_test.dart b/app_flowy/packages/flowy_infra_ui/example/test/widget_test.dart index 198cf4618d..1550d94848 100644 --- a/app_flowy/packages/flowy_infra_ui/example/test/widget_test.dart +++ b/app_flowy/packages/flowy_infra_ui/example/test/widget_test.dart @@ -18,12 +18,7 @@ void main() { // Verify that platform version is retrieved. expect( find.byWidgetPredicate( -<<<<<<< HEAD - (Widget widget) => - widget is Text && widget.data!.startsWith('Running on:'), -======= (Widget widget) => widget is Text && widget.data!.startsWith('Running on:'), ->>>>>>> [infra_ui][keyboard] Bump infra_ui to 1.20.0 and fix compiling issues ), findsOneWidget, ); diff --git a/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_platform_interface/lib/src/method_channel_flowy_infra_ui.dart b/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_platform_interface/lib/src/method_channel_flowy_infra_ui.dart index 067636ad8b..ad8051f515 100644 --- a/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_platform_interface/lib/src/method_channel_flowy_infra_ui.dart +++ b/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_platform_interface/lib/src/method_channel_flowy_infra_ui.dart @@ -3,7 +3,7 @@ import 'package:flutter/services.dart'; import '../flowy_infra_ui_platform_interface.dart'; -// ignore: constant_identifier_names +// ignore_for_file: constant_identifier_names const INFRA_UI_METHOD_CHANNEL_NAME = 'flowy_infra_ui_method'; const INFRA_UI_KEYBOARD_EVENT_CHANNEL_NAME = 'flowy_infra_ui_event/keyboard'; const INFRA_UI_METHOD_GET_PLATFORM_VERSION = 'getPlatformVersion'; diff --git a/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_web/lib/flowy_infra_ui_web.dart b/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_web/lib/flowy_infra_ui_web.dart index 98a7864942..e3bd3a2fe0 100644 --- a/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_web/lib/flowy_infra_ui_web.dart +++ b/app_flowy/packages/flowy_infra_ui/flowy_infra_ui_web/lib/flowy_infra_ui_web.dart @@ -1,5 +1,6 @@ library flowy_infra_ui_web; +import 'dart:html' as html show window; import 'package:flowy_infra_ui_platform_interface/flowy_infra_ui_platform_interface.dart'; import 'package:flutter_web_plugins/flutter_web_plugins.dart'; @@ -18,6 +19,7 @@ class FlowyInfraUIPlugin extends FlowyInfraUIPlatform { @override Future getPlatformVersion() async { - return 'Web: unknow version'; + final version = html.window.navigator.userAgent; + return Future.value(version); } } diff --git a/app_flowy/packages/flowy_infra_ui/ios/Classes/FlowyInfraUIPlugin.h b/app_flowy/packages/flowy_infra_ui/ios/Classes/FlowyInfraUIPlugin.h new file mode 100644 index 0000000000..51f5d35106 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/ios/Classes/FlowyInfraUIPlugin.h @@ -0,0 +1,4 @@ +#import + +@interface FlowyInfraUIPlugin : NSObject +@end diff --git a/app_flowy/packages/flowy_infra_ui/ios/Classes/FlowyInfraUiPlugin.m b/app_flowy/packages/flowy_infra_ui/ios/Classes/FlowyInfraUIPlugin.m similarity index 78% rename from app_flowy/packages/flowy_infra_ui/ios/Classes/FlowyInfraUiPlugin.m rename to app_flowy/packages/flowy_infra_ui/ios/Classes/FlowyInfraUIPlugin.m index 6609bdcf24..58f19ce516 100644 --- a/app_flowy/packages/flowy_infra_ui/ios/Classes/FlowyInfraUiPlugin.m +++ b/app_flowy/packages/flowy_infra_ui/ios/Classes/FlowyInfraUIPlugin.m @@ -1,4 +1,4 @@ -#import "FlowyInfraUiPlugin.h" +#import "FlowyInfraUIPlugin.h" #if __has_include() #import #else @@ -8,8 +8,8 @@ #import "flowy_infra_ui-Swift.h" #endif -@implementation FlowyInfraUiPlugin +@implementation FlowyInfraUIPlugin + (void)registerWithRegistrar:(NSObject*)registrar { - [SwiftFlowyInfraUiPlugin registerWithRegistrar:registrar]; + [SwiftFlowyInfraUIPlugin registerWithRegistrar:registrar]; } @end diff --git a/app_flowy/packages/flowy_infra_ui/ios/Classes/FlowyInfraUiPlugin.h b/app_flowy/packages/flowy_infra_ui/ios/Classes/FlowyInfraUiPlugin.h deleted file mode 100644 index 9f353812ba..0000000000 --- a/app_flowy/packages/flowy_infra_ui/ios/Classes/FlowyInfraUiPlugin.h +++ /dev/null @@ -1,4 +0,0 @@ -#import - -@interface FlowyInfraUiPlugin : NSObject -@end diff --git a/app_flowy/packages/flowy_infra_ui/ios/Classes/SwiftFlowyInfraUiPlugin.swift b/app_flowy/packages/flowy_infra_ui/ios/Classes/SwiftFlowyInfraUIPlugin.swift similarity index 91% rename from app_flowy/packages/flowy_infra_ui/ios/Classes/SwiftFlowyInfraUiPlugin.swift rename to app_flowy/packages/flowy_infra_ui/ios/Classes/SwiftFlowyInfraUIPlugin.swift index 39b9a47a04..641a0e53c2 100644 --- a/app_flowy/packages/flowy_infra_ui/ios/Classes/SwiftFlowyInfraUiPlugin.swift +++ b/app_flowy/packages/flowy_infra_ui/ios/Classes/SwiftFlowyInfraUIPlugin.swift @@ -1,7 +1,7 @@ import Flutter import UIKit -public class SwiftFlowyInfraUiPlugin: NSObject, FlutterPlugin { +public class SwiftFlowyInfraUIPlugin: NSObject, FlutterPlugin { enum Constant { static let infraUIMethodChannelName = "flowy_infra_ui_method" @@ -11,7 +11,7 @@ public class SwiftFlowyInfraUiPlugin: NSObject, FlutterPlugin { } public static func register(with registrar: FlutterPluginRegistrar) { - let instance = SwiftFlowyInfraUiPlugin() + let instance = SwiftFlowyInfraUIPlugin() let methodChannel = FlutterMethodChannel( name: Constant.infraUIMethodChannelName, diff --git a/app_flowy/packages/flowy_infra_ui/lib/flowy_infra_ui.dart b/app_flowy/packages/flowy_infra_ui/lib/flowy_infra_ui.dart index 2efe27d245..36a2148c07 100644 --- a/app_flowy/packages/flowy_infra_ui/lib/flowy_infra_ui.dart +++ b/app_flowy/packages/flowy_infra_ui/lib/flowy_infra_ui.dart @@ -1,13 +1,2 @@ - -import 'dart:async'; - -import 'package:flutter/services.dart'; - -class FlowyInfraUi { - static const MethodChannel _channel = MethodChannel('flowy_infra_ui'); - - static Future get platformVersion async { - final String? version = await _channel.invokeMethod('getPlatformVersion'); - return version; - } -} +// Keyboard +export 'src/keyboard/keyboard_visibility_detector.dart'; diff --git a/app_flowy/packages/flowy_infra_ui/lib/flowy_infra_ui_web.dart b/app_flowy/packages/flowy_infra_ui/lib/flowy_infra_ui_web.dart index f9d9035149..36a2148c07 100644 --- a/app_flowy/packages/flowy_infra_ui/lib/flowy_infra_ui_web.dart +++ b/app_flowy/packages/flowy_infra_ui/lib/flowy_infra_ui_web.dart @@ -1,44 +1,2 @@ -import 'dart:async'; -// In order to *not* need this ignore, consider extracting the "web" version -// of your plugin as a separate package, instead of inlining it in the same -// package as the core of your plugin. -// ignore: avoid_web_libraries_in_flutter -import 'dart:html' as html show window; - -import 'package:flutter/services.dart'; -import 'package:flutter_web_plugins/flutter_web_plugins.dart'; - -/// A web implementation of the FlowyInfraUi plugin. -class FlowyInfraUiWeb { - static void registerWith(Registrar registrar) { - final MethodChannel channel = MethodChannel( - 'flowy_infra_ui', - const StandardMethodCodec(), - registrar, - ); - - final pluginInstance = FlowyInfraUiWeb(); - channel.setMethodCallHandler(pluginInstance.handleMethodCall); - } - - /// Handles method calls over the MethodChannel of this plugin. - /// Note: Check the "federated" architecture for a new way of doing this: - /// https://flutter.dev/go/federated-plugins - Future handleMethodCall(MethodCall call) async { - switch (call.method) { - case 'getPlatformVersion': - return getPlatformVersion(); - default: - throw PlatformException( - code: 'Unimplemented', - details: 'flowy_infra_ui for web doesn\'t implement \'${call.method}\'', - ); - } - } - - /// Returns a [String] containing the version of the platform. - Future getPlatformVersion() { - final version = html.window.navigator.userAgent; - return Future.value(version); - } -} +// Keyboard +export 'src/keyboard/keyboard_visibility_detector.dart'; diff --git a/app_flowy/packages/flowy_infra_ui/lib/src/keyboard/keyboard_.dart b/app_flowy/packages/flowy_infra_ui/lib/src/keyboard/keyboard_.dart deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/app_flowy/packages/flowy_infra_ui/lib/src/keyboard/keyboard_visibility_detector.dart b/app_flowy/packages/flowy_infra_ui/lib/src/keyboard/keyboard_visibility_detector.dart new file mode 100644 index 0000000000..7521435310 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/lib/src/keyboard/keyboard_visibility_detector.dart @@ -0,0 +1,73 @@ +import 'dart:async'; + +import 'package:flowy_infra_ui_platform_interface/flowy_infra_ui_platform_interface.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class KeyboardVisibilityDetector extends StatefulWidget { + const KeyboardVisibilityDetector({ + Key? key, + required this.child, + this.onKeyboardVisibilityChange, + }) : super(key: key); + + final Widget child; + final void Function(bool)? onKeyboardVisibilityChange; + + static bool isKeyboardVisible(BuildContext context) { + return context.read<_KeyboardVisibilityDetectorInheritedWidget>().isKeyboardVisible; + } + + @override + _KeyboardVisibilityDetectorState createState() => _KeyboardVisibilityDetectorState(); +} + +class _KeyboardVisibilityDetectorState extends State { + FlowyInfraUIPlatform get _platform => FlowyInfraUIPlatform.instance; + + bool isObserving = false; + bool isKeyboardVisible = false; + late StreamSubscription _keyboardSubscription; + + @override + void initState() { + super.initState(); + _keyboardSubscription = _platform.onKeyboardVisibilityChange.listen((newValue) { + setState(() { + isKeyboardVisible = newValue; + if (widget.onKeyboardVisibilityChange != null) { + widget.onKeyboardVisibilityChange!(newValue); + } + }); + }); + } + + @override + void dispose() { + _keyboardSubscription.cancel(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return _KeyboardVisibilityDetectorInheritedWidget( + isKeyboardVisible: isKeyboardVisible, + child: widget.child, + ); + } +} + +class _KeyboardVisibilityDetectorInheritedWidget extends InheritedWidget { + const _KeyboardVisibilityDetectorInheritedWidget({ + Key? key, + required this.isKeyboardVisible, + required Widget child, + }) : super(key: key, child: child); + + final bool isKeyboardVisible; + + @override + bool updateShouldNotify(_KeyboardVisibilityDetectorInheritedWidget oldWidget) { + return isKeyboardVisible != oldWidget.isKeyboardVisible; + } +} diff --git a/app_flowy/packages/flowy_infra_ui/macos/Classes/FlowyInfraUiPlugin.swift b/app_flowy/packages/flowy_infra_ui/macos/Classes/FlowyInfraUiPlugin.swift index b0fcc26b21..a18610dede 100644 --- a/app_flowy/packages/flowy_infra_ui/macos/Classes/FlowyInfraUiPlugin.swift +++ b/app_flowy/packages/flowy_infra_ui/macos/Classes/FlowyInfraUiPlugin.swift @@ -1,10 +1,10 @@ import Cocoa import FlutterMacOS -public class FlowyInfraUiPlugin: NSObject, FlutterPlugin { +public class FlowyInfraUIPlugin: NSObject, FlutterPlugin { public static func register(with registrar: FlutterPluginRegistrar) { let channel = FlutterMethodChannel(name: "flowy_infra_ui", binaryMessenger: registrar.messenger) - let instance = FlowyInfraUiPlugin() + let instance = FlowyInfraUIPlugin() registrar.addMethodCallDelegate(instance, channel: channel) } diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/lib/keyboard_web.dart b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/lib/keyboard_web.dart new file mode 100644 index 0000000000..30e6eabb1d --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/lib/keyboard_web.dart @@ -0,0 +1,16 @@ +library keyboard_web; + +import 'package:flutter_web_plugins/flutter_web_plugins.dart'; +import 'package:keyboard_platform_interface/keyboard_platform_interface.dart'; + +class KeyboardPlugin extends KeyboardPlatform { + static void registerWith(Registrar registrar) { + KeyboardPlatform.instance = KeyboardPlugin(); + } + + @override + Stream get onKeyboardChange async* { + // suppose that keyboard won't show in web side + yield false; + } +} diff --git a/app_flowy/packages/flowy_infra_ui/windows/flowy_infra_ui_plugin.cpp b/app_flowy/packages/flowy_infra_ui/windows/flowy_infra_ui_plugin.cpp index f4329eacf4..4de31d554f 100644 --- a/app_flowy/packages/flowy_infra_ui/windows/flowy_infra_ui_plugin.cpp +++ b/app_flowy/packages/flowy_infra_ui/windows/flowy_infra_ui_plugin.cpp @@ -16,13 +16,13 @@ namespace { -class FlowyInfraUiPlugin : public flutter::Plugin { +class FlowyInfraUIPlugin : public flutter::Plugin { public: static void RegisterWithRegistrar(flutter::PluginRegistrarWindows *registrar); - FlowyInfraUiPlugin(); + FlowyInfraUIPlugin(); - virtual ~FlowyInfraUiPlugin(); + virtual ~FlowyInfraUIPlugin(); private: // Called when a method is called on this plugin's channel from Dart. @@ -32,14 +32,14 @@ class FlowyInfraUiPlugin : public flutter::Plugin { }; // static -void FlowyInfraUiPlugin::RegisterWithRegistrar( +void FlowyInfraUIPlugin::RegisterWithRegistrar( flutter::PluginRegistrarWindows *registrar) { auto channel = std::make_unique>( registrar->messenger(), "flowy_infra_ui", &flutter::StandardMethodCodec::GetInstance()); - auto plugin = std::make_unique(); + auto plugin = std::make_unique(); channel->SetMethodCallHandler( [plugin_pointer = plugin.get()](const auto &call, auto result) { @@ -49,11 +49,11 @@ void FlowyInfraUiPlugin::RegisterWithRegistrar( registrar->AddPlugin(std::move(plugin)); } -FlowyInfraUiPlugin::FlowyInfraUiPlugin() {} +FlowyInfraUIPlugin::FlowyInfraUIPlugin() {} -FlowyInfraUiPlugin::~FlowyInfraUiPlugin() {} +FlowyInfraUIPlugin::~FlowyInfraUIPlugin() {} -void FlowyInfraUiPlugin::HandleMethodCall( +void FlowyInfraUIPlugin::HandleMethodCall( const flutter::MethodCall &method_call, std::unique_ptr> result) { if (method_call.method_name().compare("getPlatformVersion") == 0) { @@ -74,9 +74,9 @@ void FlowyInfraUiPlugin::HandleMethodCall( } // namespace -void FlowyInfraUiPluginRegisterWithRegistrar( +void FlowyInfraUIPluginRegisterWithRegistrar( FlutterDesktopPluginRegistrarRef registrar) { - FlowyInfraUiPlugin::RegisterWithRegistrar( + FlowyInfraUIPlugin::RegisterWithRegistrar( flutter::PluginRegistrarManager::GetInstance() ->GetRegistrar(registrar)); } diff --git a/app_flowy/packages/flowy_infra_ui/windows/include/flowy_infra_ui/flowy_infra_ui_plugin.h b/app_flowy/packages/flowy_infra_ui/windows/include/flowy_infra_ui/flowy_infra_ui_plugin.h index cdd90185ab..475039941f 100644 --- a/app_flowy/packages/flowy_infra_ui/windows/include/flowy_infra_ui/flowy_infra_ui_plugin.h +++ b/app_flowy/packages/flowy_infra_ui/windows/include/flowy_infra_ui/flowy_infra_ui_plugin.h @@ -13,7 +13,7 @@ extern "C" { #endif -FLUTTER_PLUGIN_EXPORT void FlowyInfraUiPluginRegisterWithRegistrar( +FLUTTER_PLUGIN_EXPORT void FlowyInfraUIPluginRegisterWithRegistrar( FlutterDesktopPluginRegistrarRef registrar); #if defined(__cplusplus) From a427bb94d6863d9ddf10fa2dae05ff6286ebb5d6 Mon Sep 17 00:00:00 2001 From: Jaylen Bian Date: Sun, 18 Jul 2021 14:18:08 +0800 Subject: [PATCH 18/30] [infra_ui][keyboard] Update ios example proj to fix compiling issue --- .../com/example/example/MainActivity.kt | 6 ++ .../flowy_infra_ui/example/ios/Podfile.lock | 22 ++++++ .../ios/Runner.xcodeproj/project.pbxproj | 69 +++++++++++++++++++ .../contents.xcworkspacedata | 3 + .../example/lib/keyboard/keyboard_screen.dart | 9 ++- 5 files changed, 108 insertions(+), 1 deletion(-) create mode 100644 app_flowy/packages/flowy_infra_ui/example/android/app/src/main/kotlin/com/example/example/MainActivity.kt create mode 100644 app_flowy/packages/flowy_infra_ui/example/ios/Podfile.lock diff --git a/app_flowy/packages/flowy_infra_ui/example/android/app/src/main/kotlin/com/example/example/MainActivity.kt b/app_flowy/packages/flowy_infra_ui/example/android/app/src/main/kotlin/com/example/example/MainActivity.kt new file mode 100644 index 0000000000..e793a000d6 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/example/android/app/src/main/kotlin/com/example/example/MainActivity.kt @@ -0,0 +1,6 @@ +package com.example.example + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity: FlutterActivity() { +} diff --git a/app_flowy/packages/flowy_infra_ui/example/ios/Podfile.lock b/app_flowy/packages/flowy_infra_ui/example/ios/Podfile.lock new file mode 100644 index 0000000000..c5a50f2dc9 --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/example/ios/Podfile.lock @@ -0,0 +1,22 @@ +PODS: + - flowy_infra_ui (0.0.1): + - Flutter + - Flutter (1.0.0) + +DEPENDENCIES: + - flowy_infra_ui (from `.symlinks/plugins/flowy_infra_ui/ios`) + - Flutter (from `Flutter`) + +EXTERNAL SOURCES: + flowy_infra_ui: + :path: ".symlinks/plugins/flowy_infra_ui/ios" + Flutter: + :path: Flutter + +SPEC CHECKSUMS: + flowy_infra_ui: 146c88346fd55d2ee6a41ae35059a5bf095cfbb3 + Flutter: 434fef37c0980e73bb6479ef766c45957d4b510c + +PODFILE CHECKSUM: aafe91acc616949ddb318b77800a7f51bffa2a4c + +COCOAPODS: 1.9.3 diff --git a/app_flowy/packages/flowy_infra_ui/example/ios/Runner.xcodeproj/project.pbxproj b/app_flowy/packages/flowy_infra_ui/example/ios/Runner.xcodeproj/project.pbxproj index 6eb94532cf..bc3ced26c4 100644 --- a/app_flowy/packages/flowy_infra_ui/example/ios/Runner.xcodeproj/project.pbxproj +++ b/app_flowy/packages/flowy_infra_ui/example/ios/Runner.xcodeproj/project.pbxproj @@ -13,6 +13,7 @@ 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; + B061A1718EA00FC8FD116CB3 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 609D91DEF4C1832DC41DF975 /* Pods_Runner.framework */; }; /* End PBXBuildFile section */ /* Begin PBXCopyFilesBuildPhase section */ @@ -31,7 +32,9 @@ /* Begin PBXFileReference section */ 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; + 330E5DF8FFAD644160722BE7 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; + 609D91DEF4C1832DC41DF975 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; @@ -42,6 +45,8 @@ 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + E433772F3E94B24F3479C2F9 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; + F09BA83EC3ECFDE285785DB2 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -49,12 +54,32 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + B061A1718EA00FC8FD116CB3 /* Pods_Runner.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 35285CDC74580BB1F9C79F75 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 609D91DEF4C1832DC41DF975 /* Pods_Runner.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + 6F690F158B0591DDAF4BC371 /* Pods */ = { + isa = PBXGroup; + children = ( + 330E5DF8FFAD644160722BE7 /* Pods-Runner.debug.xcconfig */, + F09BA83EC3ECFDE285785DB2 /* Pods-Runner.release.xcconfig */, + E433772F3E94B24F3479C2F9 /* Pods-Runner.profile.xcconfig */, + ); + name = Pods; + path = Pods; + sourceTree = ""; + }; 9740EEB11CF90186004384FC /* Flutter */ = { isa = PBXGroup; children = ( @@ -72,6 +97,8 @@ 9740EEB11CF90186004384FC /* Flutter */, 97C146F01CF9000F007C117D /* Runner */, 97C146EF1CF9000F007C117D /* Products */, + 6F690F158B0591DDAF4BC371 /* Pods */, + 35285CDC74580BB1F9C79F75 /* Frameworks */, ); sourceTree = ""; }; @@ -105,12 +132,14 @@ isa = PBXNativeTarget; buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( + DA35FF5721D34BC0BE4E1DD5 /* [CP] Check Pods Manifest.lock */, 9740EEB61CF901F6004384FC /* Run Script */, 97C146EA1CF9000F007C117D /* Sources */, 97C146EB1CF9000F007C117D /* Frameworks */, 97C146EC1CF9000F007C117D /* Resources */, 9705A1C41CF9048500538489 /* Embed Frameworks */, 3B06AD1E1E4923F5004D2608 /* Thin Binary */, + 8A9E1CD9725728F74665B246 /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); @@ -183,6 +212,24 @@ shellPath = /bin/sh; shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; }; + 8A9E1CD9725728F74665B246 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh", + "${BUILT_PRODUCTS_DIR}/flowy_infra_ui/flowy_infra_ui.framework", + ); + name = "[CP] Embed Pods Frameworks"; + outputPaths = ( + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/flowy_infra_ui.framework", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; 9740EEB61CF901F6004384FC /* Run Script */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; @@ -197,6 +244,28 @@ shellPath = /bin/sh; shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; }; + DA35FF5721D34BC0BE4E1DD5 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ diff --git a/app_flowy/packages/flowy_infra_ui/example/ios/Runner.xcworkspace/contents.xcworkspacedata b/app_flowy/packages/flowy_infra_ui/example/ios/Runner.xcworkspace/contents.xcworkspacedata index 1d526a16ed..21a3cc14c7 100644 --- a/app_flowy/packages/flowy_infra_ui/example/ios/Runner.xcworkspace/contents.xcworkspacedata +++ b/app_flowy/packages/flowy_infra_ui/example/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -4,4 +4,7 @@ + + diff --git a/app_flowy/packages/flowy_infra_ui/example/lib/keyboard/keyboard_screen.dart b/app_flowy/packages/flowy_infra_ui/example/lib/keyboard/keyboard_screen.dart index dcd11fe0e2..780e89befc 100644 --- a/app_flowy/packages/flowy_infra_ui/example/lib/keyboard/keyboard_screen.dart +++ b/app_flowy/packages/flowy_infra_ui/example/lib/keyboard/keyboard_screen.dart @@ -45,8 +45,15 @@ class _KeyboardScreenState extends State { padding: const EdgeInsets.symmetric(horizontal: 36), child: Center( child: Column( + mainAxisAlignment: MainAxisAlignment.center, children: [ - Text('Keyboard Visible: $_isKeyboardVisible'), + Padding( + padding: const EdgeInsets.symmetric(vertical: 12.0), + child: Text( + 'Keyboard Visible: $_isKeyboardVisible', + style: const TextStyle(fontSize: 24.0), + ), + ), TextField( style: const TextStyle(fontSize: 20), controller: TextEditingController(text: 'Test'), From 84931e7cc63447a0523f0f85ff4a38271576ecca Mon Sep 17 00:00:00 2001 From: Jaylen Bian Date: Sun, 18 Jul 2021 17:01:15 +0800 Subject: [PATCH 19/30] [infra_ui][keyboard] Update example proj --- .../example/lib/keyboard/keyboard_screen.dart | 3 +- .../flowy_infra_ui/example/lib/main.dart | 6 +- .../flowy_infra_ui/example/macos/Podfile.lock | 22 +++++++ .../macos/Runner.xcodeproj/project.pbxproj | 62 ++++++++++++++++++- .../contents.xcworkspacedata | 3 + .../flowy_infra_ui/example/pubspec.lock | 8 +-- .../flowy_infra_ui/example/pubspec.yaml | 8 --- .../keyboard_visibility_detector.dart | 5 -- .../packages/flowy_infra_ui/pubspec.lock | 8 +-- 9 files changed, 97 insertions(+), 28 deletions(-) create mode 100644 app_flowy/packages/flowy_infra_ui/example/macos/Podfile.lock diff --git a/app_flowy/packages/flowy_infra_ui/example/lib/keyboard/keyboard_screen.dart b/app_flowy/packages/flowy_infra_ui/example/lib/keyboard/keyboard_screen.dart index 780e89befc..28aa027b49 100644 --- a/app_flowy/packages/flowy_infra_ui/example/lib/keyboard/keyboard_screen.dart +++ b/app_flowy/packages/flowy_infra_ui/example/lib/keyboard/keyboard_screen.dart @@ -27,6 +27,7 @@ class KeyboardScreen extends StatefulWidget { class _KeyboardScreenState extends State { bool _isKeyboardVisible = false; + final TextEditingController _controller = TextEditingController(text: 'Hello Flowy'); @override Widget build(BuildContext context) { @@ -56,7 +57,7 @@ class _KeyboardScreenState extends State { ), TextField( style: const TextStyle(fontSize: 20), - controller: TextEditingController(text: 'Test'), + controller: _controller, ), ], ), diff --git a/app_flowy/packages/flowy_infra_ui/example/lib/main.dart b/app_flowy/packages/flowy_infra_ui/example/lib/main.dart index 35d08970a2..1c3b2a41f4 100644 --- a/app_flowy/packages/flowy_infra_ui/example/lib/main.dart +++ b/app_flowy/packages/flowy_infra_ui/example/lib/main.dart @@ -1,5 +1,5 @@ import 'package:flutter/material.dart'; -import '../home/home_screen.dart'; +import 'home/home_screen.dart'; void main() { runApp(const ExampleApp()); @@ -10,13 +10,9 @@ class ExampleApp extends StatelessWidget { @override Widget build(BuildContext context) { -<<<<<<< HEAD - return const MaterialApp(); -======= return const MaterialApp( title: "Flowy Infra Title", home: HomeScreen(), ); ->>>>>>> [infra_ui][keyboard] (WIP) Add demo proj for infra ui } } diff --git a/app_flowy/packages/flowy_infra_ui/example/macos/Podfile.lock b/app_flowy/packages/flowy_infra_ui/example/macos/Podfile.lock new file mode 100644 index 0000000000..b0a2e1ef3a --- /dev/null +++ b/app_flowy/packages/flowy_infra_ui/example/macos/Podfile.lock @@ -0,0 +1,22 @@ +PODS: + - flowy_infra_ui (0.0.1): + - FlutterMacOS + - FlutterMacOS (1.0.0) + +DEPENDENCIES: + - flowy_infra_ui (from `Flutter/ephemeral/.symlinks/plugins/flowy_infra_ui/macos`) + - FlutterMacOS (from `Flutter/ephemeral`) + +EXTERNAL SOURCES: + flowy_infra_ui: + :path: Flutter/ephemeral/.symlinks/plugins/flowy_infra_ui/macos + FlutterMacOS: + :path: Flutter/ephemeral + +SPEC CHECKSUMS: + flowy_infra_ui: 9d5021b1610fe0476eb1191bf7cd41c4a4138d8f + FlutterMacOS: 57701585bf7de1b3fc2bb61f6378d73bbdea8424 + +PODFILE CHECKSUM: 6eac6b3292e5142cfc23bdeb71848a40ec51c14c + +COCOAPODS: 1.9.3 diff --git a/app_flowy/packages/flowy_infra_ui/example/macos/Runner.xcodeproj/project.pbxproj b/app_flowy/packages/flowy_infra_ui/example/macos/Runner.xcodeproj/project.pbxproj index 547137744c..57fa2942d0 100644 --- a/app_flowy/packages/flowy_infra_ui/example/macos/Runner.xcodeproj/project.pbxproj +++ b/app_flowy/packages/flowy_infra_ui/example/macos/Runner.xcodeproj/project.pbxproj @@ -26,6 +26,7 @@ 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; + 7912A075158F80106DD95645 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C0464B205D770E7A68F28B6D /* Pods_Runner.framework */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -52,9 +53,10 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ + 2D5900421C18B1A15A65A9EC /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; - 33CC10ED2044A3C60003C045 /* flowy_infra_ui_example.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "flowy_infra_ui_example.app"; sourceTree = BUILT_PRODUCTS_DIR; }; + 33CC10ED2044A3C60003C045 /* flowy_infra_ui_example.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = flowy_infra_ui_example.app; sourceTree = BUILT_PRODUCTS_DIR; }; 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = ""; }; 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; @@ -68,6 +70,9 @@ 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; + 97A4E031C17F0C7BEEE33734 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; + AB3F9417FEFE6929B49F80FE /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; + C0464B205D770E7A68F28B6D /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -75,6 +80,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 7912A075158F80106DD95645 /* Pods_Runner.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -99,6 +105,7 @@ 33CEB47122A05771004F2AC0 /* Flutter */, 33CC10EE2044A3C60003C045 /* Products */, D73912EC22F37F3D000D13A0 /* Frameworks */, + A750A856115646FFDA1D1478 /* Pods */, ); sourceTree = ""; }; @@ -145,9 +152,21 @@ path = Runner; sourceTree = ""; }; + A750A856115646FFDA1D1478 /* Pods */ = { + isa = PBXGroup; + children = ( + 97A4E031C17F0C7BEEE33734 /* Pods-Runner.debug.xcconfig */, + 2D5900421C18B1A15A65A9EC /* Pods-Runner.release.xcconfig */, + AB3F9417FEFE6929B49F80FE /* Pods-Runner.profile.xcconfig */, + ); + name = Pods; + path = Pods; + sourceTree = ""; + }; D73912EC22F37F3D000D13A0 /* Frameworks */ = { isa = PBXGroup; children = ( + C0464B205D770E7A68F28B6D /* Pods_Runner.framework */, ); name = Frameworks; sourceTree = ""; @@ -159,11 +178,13 @@ isa = PBXNativeTarget; buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( + 2FBE5781370B1EF78F66CD14 /* [CP] Check Pods Manifest.lock */, 33CC10E92044A3C60003C045 /* Sources */, 33CC10EA2044A3C60003C045 /* Frameworks */, 33CC10EB2044A3C60003C045 /* Resources */, 33CC110E2044A8840003C045 /* Bundle Framework */, 3399D490228B24CF009A79C7 /* ShellScript */, + 196EE237C3BE7811FE50A841 /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); @@ -233,6 +254,45 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ + 196EE237C3BE7811FE50A841 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-input-files.xcfilelist", + ); + name = "[CP] Embed Pods Frameworks"; + outputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-output-files.xcfilelist", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + 2FBE5781370B1EF78F66CD14 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; 3399D490228B24CF009A79C7 /* ShellScript */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; diff --git a/app_flowy/packages/flowy_infra_ui/example/macos/Runner.xcworkspace/contents.xcworkspacedata b/app_flowy/packages/flowy_infra_ui/example/macos/Runner.xcworkspace/contents.xcworkspacedata index 1d526a16ed..21a3cc14c7 100644 --- a/app_flowy/packages/flowy_infra_ui/example/macos/Runner.xcworkspace/contents.xcworkspacedata +++ b/app_flowy/packages/flowy_infra_ui/example/macos/Runner.xcworkspace/contents.xcworkspacedata @@ -4,4 +4,7 @@ + + diff --git a/app_flowy/packages/flowy_infra_ui/example/pubspec.lock b/app_flowy/packages/flowy_infra_ui/example/pubspec.lock index 48fb2300d9..c2685ea99f 100644 --- a/app_flowy/packages/flowy_infra_ui/example/pubspec.lock +++ b/app_flowy/packages/flowy_infra_ui/example/pubspec.lock @@ -14,7 +14,7 @@ packages: name: async url: "https://pub.dartlang.org" source: hosted - version: "2.7.0" + version: "2.6.1" boolean_selector: dependency: transitive description: @@ -35,7 +35,7 @@ packages: name: charcode url: "https://pub.dartlang.org" source: hosted - version: "1.3.1" + version: "1.2.0" clock: dependency: transitive description: @@ -176,7 +176,7 @@ packages: name: meta url: "https://pub.dartlang.org" source: hosted - version: "1.4.0" + version: "1.3.0" nested: dependency: transitive description: @@ -258,7 +258,7 @@ packages: name: test_api url: "https://pub.dartlang.org" source: hosted - version: "0.4.1" + version: "0.3.0" textstyle_extensions: dependency: transitive description: diff --git a/app_flowy/packages/flowy_infra_ui/example/pubspec.yaml b/app_flowy/packages/flowy_infra_ui/example/pubspec.yaml index 4b3c5ac678..901200091e 100644 --- a/app_flowy/packages/flowy_infra_ui/example/pubspec.yaml +++ b/app_flowy/packages/flowy_infra_ui/example/pubspec.yaml @@ -10,14 +10,6 @@ dependencies: flutter: sdk: flutter -<<<<<<< HEAD -======= - cupertino_icons: ^1.0.2 -<<<<<<< HEAD - provider: ^5.0.0 ->>>>>>> [infra_ui][keyboard] (WIP) Add demo proj for infra ui -======= ->>>>>>> [infra_ui] Integrate keyboard detector to example proj flowy_infra_ui: path: ../ diff --git a/app_flowy/packages/flowy_infra_ui/lib/src/keyboard/keyboard_visibility_detector.dart b/app_flowy/packages/flowy_infra_ui/lib/src/keyboard/keyboard_visibility_detector.dart index 7521435310..b4d084acc0 100644 --- a/app_flowy/packages/flowy_infra_ui/lib/src/keyboard/keyboard_visibility_detector.dart +++ b/app_flowy/packages/flowy_infra_ui/lib/src/keyboard/keyboard_visibility_detector.dart @@ -2,7 +2,6 @@ import 'dart:async'; import 'package:flowy_infra_ui_platform_interface/flowy_infra_ui_platform_interface.dart'; import 'package:flutter/material.dart'; -import 'package:provider/provider.dart'; class KeyboardVisibilityDetector extends StatefulWidget { const KeyboardVisibilityDetector({ @@ -14,10 +13,6 @@ class KeyboardVisibilityDetector extends StatefulWidget { final Widget child; final void Function(bool)? onKeyboardVisibilityChange; - static bool isKeyboardVisible(BuildContext context) { - return context.read<_KeyboardVisibilityDetectorInheritedWidget>().isKeyboardVisible; - } - @override _KeyboardVisibilityDetectorState createState() => _KeyboardVisibilityDetectorState(); } diff --git a/app_flowy/packages/flowy_infra_ui/pubspec.lock b/app_flowy/packages/flowy_infra_ui/pubspec.lock index 9b2f5e6a79..98f80cfe2a 100644 --- a/app_flowy/packages/flowy_infra_ui/pubspec.lock +++ b/app_flowy/packages/flowy_infra_ui/pubspec.lock @@ -14,7 +14,7 @@ packages: name: async url: "https://pub.dartlang.org" source: hosted - version: "2.7.0" + version: "2.6.1" boolean_selector: dependency: transitive description: @@ -35,7 +35,7 @@ packages: name: charcode url: "https://pub.dartlang.org" source: hosted - version: "1.3.1" + version: "1.2.0" clock: dependency: transitive description: @@ -162,7 +162,7 @@ packages: name: meta url: "https://pub.dartlang.org" source: hosted - version: "1.4.0" + version: "1.3.0" nested: dependency: transitive description: @@ -244,7 +244,7 @@ packages: name: test_api url: "https://pub.dartlang.org" source: hosted - version: "0.4.1" + version: "0.3.0" textstyle_extensions: dependency: "direct main" description: From e1f73f5246a353f03527a4b37a76f1d9b258adef Mon Sep 17 00:00:00 2001 From: appflowy Date: Sun, 18 Jul 2021 23:56:36 +0800 Subject: [PATCH 20/30] find out how to nested the future into handler --- .idea/appflowy_client.iml | 3 + app_flowy/macos/Podfile.lock | 6 + rust-lib/flowy-sdk/Cargo.toml | 1 + rust-lib/flowy-sdk/src/module.rs | 22 +++- .../src/services/user_session/database.rs | 21 ++-- .../src/services/user_session/user_session.rs | 106 ++++++++---------- rust-lib/flowy-workspace/Cargo.toml | 2 + .../src/handlers/workspace_handler.rs | 9 +- rust-lib/flowy-workspace/src/module.rs | 3 +- .../src/services/workspace_controller.rs | 21 +++- 10 files changed, 114 insertions(+), 80 deletions(-) diff --git a/.idea/appflowy_client.iml b/.idea/appflowy_client.iml index 5c6b5b4d21..fbd3a47727 100644 --- a/.idea/appflowy_client.iml +++ b/.idea/appflowy_client.iml @@ -86,6 +86,9 @@ + + + diff --git a/app_flowy/macos/Podfile.lock b/app_flowy/macos/Podfile.lock index 8aca69f25a..54e66df1b4 100644 --- a/app_flowy/macos/Podfile.lock +++ b/app_flowy/macos/Podfile.lock @@ -1,6 +1,8 @@ PODS: - flowy_editor (0.0.1): - FlutterMacOS + - flowy_infra_ui (0.0.1): + - FlutterMacOS - flowy_sdk (0.0.1): - FlutterMacOS - FlutterMacOS (1.0.0) @@ -13,6 +15,7 @@ PODS: DEPENDENCIES: - flowy_editor (from `Flutter/ephemeral/.symlinks/plugins/flowy_editor/macos`) + - flowy_infra_ui (from `Flutter/ephemeral/.symlinks/plugins/flowy_infra_ui/macos`) - flowy_sdk (from `Flutter/ephemeral/.symlinks/plugins/flowy_sdk/macos`) - FlutterMacOS (from `Flutter/ephemeral`) - path_provider_macos (from `Flutter/ephemeral/.symlinks/plugins/path_provider_macos/macos`) @@ -22,6 +25,8 @@ DEPENDENCIES: EXTERNAL SOURCES: flowy_editor: :path: Flutter/ephemeral/.symlinks/plugins/flowy_editor/macos + flowy_infra_ui: + :path: Flutter/ephemeral/.symlinks/plugins/flowy_infra_ui/macos flowy_sdk: :path: Flutter/ephemeral/.symlinks/plugins/flowy_sdk/macos FlutterMacOS: @@ -35,6 +40,7 @@ EXTERNAL SOURCES: SPEC CHECKSUMS: flowy_editor: 26060a984848e6afac1f6a4455511f4114119d8d + flowy_infra_ui: 9d5021b1610fe0476eb1191bf7cd41c4a4138d8f flowy_sdk: c302ac0a22dea596db0df8073b9637b2bf2ff6fd FlutterMacOS: 57701585bf7de1b3fc2bb61f6378d73bbdea8424 path_provider_macos: a0a3fd666cb7cd0448e936fb4abad4052961002b diff --git a/rust-lib/flowy-sdk/Cargo.toml b/rust-lib/flowy-sdk/Cargo.toml index 9be05f9cf8..6150dd01a3 100644 --- a/rust-lib/flowy-sdk/Cargo.toml +++ b/rust-lib/flowy-sdk/Cargo.toml @@ -15,6 +15,7 @@ flowy-workspace = { path = "../flowy-workspace" } flowy-database = { path = "../flowy-database" } tracing = { version = "0.1" } log = "0.4.14" +futures-core = { version = "0.3", default-features = false } [dev-dependencies] serde = { version = "1.0", features = ["derive"] } diff --git a/rust-lib/flowy-sdk/src/module.rs b/rust-lib/flowy-sdk/src/module.rs index ed0afda2f2..b13c3e336a 100644 --- a/rust-lib/flowy-sdk/src/module.rs +++ b/rust-lib/flowy-sdk/src/module.rs @@ -1,11 +1,10 @@ -use flowy_dispatch::prelude::Module; -use flowy_user::prelude::*; - use crate::flowy_server::{ArcFlowyServer, FlowyServerMocker}; use flowy_database::DBConnection; - +use flowy_dispatch::prelude::Module; +use flowy_user::{errors::UserError, prelude::*}; use flowy_workspace::prelude::*; -use std::sync::Arc; +use futures_core::future::BoxFuture; +use std::{pin::Pin, sync::Arc}; pub struct ModuleConfig { pub root: String, @@ -33,7 +32,18 @@ pub struct WorkspaceUserImpl { } impl WorkspaceUser for WorkspaceUserImpl { - fn set_current_workspace(&self, id: &str) { UserSession::set_current_workspace(id); } + fn set_current_workspace(&self, workspace_id: &str) -> BoxFuture<()> { + let user_session = self.user_session.clone(); + let workspace_id = workspace_id.to_owned(); + Box::pin(async move { + match user_session.set_current_workspace(&workspace_id).await { + Ok(_) => {}, + Err(e) => { + log::error!("Set current workspace error: {:?}", e); + }, + } + }) + } fn get_current_workspace(&self) -> Result { let user_detail = self.user_session.user_detail().map_err(|e| { diff --git a/rust-lib/flowy-user/src/services/user_session/database.rs b/rust-lib/flowy-user/src/services/user_session/database.rs index 77b621c6d5..6103ec4e1c 100644 --- a/rust-lib/flowy-user/src/services/user_session/database.rs +++ b/rust-lib/flowy-user/src/services/user_session/database.rs @@ -28,7 +28,11 @@ impl UserDB { } fn open_user_db(&self, user_id: &str) -> Result<(), UserError> { - set_user_db_init(true, user_id); + if user_id.is_empty() { + return Err(ErrorBuilder::new(UserErrorCode::DatabaseInitFailed) + .msg("user id is empty") + .build()); + } let dir = format!("{}/{}", self.db_dir, user_id); let db = flowy_database::init(&dir).map_err(|e| { @@ -48,21 +52,20 @@ impl UserDB { } pub(crate) fn close_user_db(&self, user_id: &str) -> Result<(), UserError> { - set_user_db_init(false, user_id); - let mut db_map = DB_MAP.write().map_err(|e| { ErrorBuilder::new(UserErrorCode::DatabaseWriteLocked) .msg(format!("Close user db failed. {:?}", e)) .build() })?; - + set_user_db_init(false, user_id); db_map.remove(user_id); Ok(()) } pub(crate) fn get_connection(&self, user_id: &str) -> Result { if !is_user_db_init(user_id) { - let _ = self.open_user_db(user_id); + let _ = self.open_user_db(user_id)?; + set_user_db_init(true, user_id); } let db_map = DB_MAP.read().map_err(|e| { @@ -73,7 +76,7 @@ impl UserDB { match db_map.get(user_id) { None => Err(ErrorBuilder::new(UserErrorCode::DatabaseInitFailed) - .msg("Database is not initialization") + .msg("Get connection failed. The database is not initialization") .build()), Some(database) => Ok(database.get_connection()?), } @@ -86,10 +89,8 @@ lazy_static! { static INIT_FLAG_MAP: Lazy>> = Lazy::new(|| Mutex::new(HashMap::new())); fn set_user_db_init(is_init: bool, user_id: &str) { - INIT_FLAG_MAP - .lock() - .entry(user_id.to_owned()) - .or_insert_with(|| is_init); + let mut flag_map = INIT_FLAG_MAP.lock(); + flag_map.insert(user_id.to_owned(), is_init); } fn is_user_db_init(user_id: &str) -> bool { diff --git a/rust-lib/flowy-user/src/services/user_session/user_session.rs b/rust-lib/flowy-user/src/services/user_session/user_session.rs index 07b4898f8a..18f4621e59 100644 --- a/rust-lib/flowy-user/src/services/user_session/user_session.rs +++ b/rust-lib/flowy-user/src/services/user_session/user_session.rs @@ -34,6 +34,7 @@ pub struct UserSession { database: UserDB, config: UserSessionConfig, server: Arc, + user_id: RwLock>, } impl UserSession { @@ -46,28 +47,30 @@ impl UserSession { database: db, config, server, + user_id: RwLock::new(None), } } pub fn get_db_connection(&self) -> Result { - let user_id = get_current_user_id()?; + let user_id = self.get_user_id()?; self.database.get_connection(&user_id) } pub fn sign_in(&self, params: SignInParams) -> Result { let user = self.server.sign_in(params)?; - let _ = set_current_user_id(Some(user.id.clone()))?; + let _ = self.set_user_id(Some(user.id.clone()))?; + self.save_user(user) } pub fn sign_up(&self, params: SignUpParams) -> Result { let user = self.server.sign_up(params)?; - let _ = set_current_user_id(Some(user.id.clone()))?; + let _ = self.set_user_id(Some(user.id.clone()))?; self.save_user(user) } pub fn sign_out(&self) -> Result<(), UserError> { - let user_id = current_user_id()?; + let user_id = self.get_user_id()?; let conn = self.get_db_connection()?; let _ = diesel::delete(dsl::user_table.filter(dsl::id.eq(&user_id))).execute(&*conn)?; @@ -76,7 +79,7 @@ impl UserSession { Err(_) => {}, } let _ = self.database.close_user_db(&user_id)?; - let _ = set_current_user_id(None)?; + let _ = self.set_user_id(None)?; Ok(()) } @@ -100,7 +103,7 @@ impl UserSession { } pub fn user_detail(&self) -> Result { - let user_id = current_user_id()?; + let user_id = self.get_user_id()?; let conn = self.get_db_connection()?; let user = dsl::user_table @@ -118,16 +121,49 @@ impl UserSession { Ok(UserDetail::from(user)) } -} -impl UserSession { - pub async fn set_current_workspace(workspace: &str) -> Result<(), UserError> { - let user_id = current_user_id()?; + pub fn set_user_id(&self, user_id: Option) -> Result<(), UserError> { + log::trace!("Set user id: {:?}", user_id); + KVStore::set_str(USER_ID_CACHE_KEY, user_id.clone().unwrap_or("".to_owned())); + match self.user_id.write() { + Ok(mut write_guard) => { + *write_guard = user_id; + Ok(()) + }, + Err(e) => Err(ErrorBuilder::new(UserErrorCode::WriteCurrentIdFailed) + .error(e) + .build()), + } + } + + pub fn get_user_id(&self) -> Result { + let read_guard = self.user_id.read().map_err(|e| { + ErrorBuilder::new(UserErrorCode::ReadCurrentIdFailed) + .error(e) + .build() + })?; + + let mut user_id = (*read_guard).clone(); + drop(read_guard); + + if user_id.is_none() { + user_id = KVStore::get_str(USER_ID_CACHE_KEY); + self.set_user_id(user_id.clone()); + } + + match user_id { + None => Err(ErrorBuilder::new(UserErrorCode::UserNotLoginYet).build()), + Some(user_id) => Ok(user_id), + } + } + + pub async fn set_current_workspace(&self, workspace_id: &str) -> Result<(), UserError> { + let user_id = self.get_user_id()?; let payload: Vec = UpdateUserRequest { id: user_id, name: None, email: None, - workspace: Some(workspace.to_owned()), + workspace: Some(workspace_id.to_owned()), password: None, } .into_bytes() @@ -144,7 +180,7 @@ impl UserSession { } pub fn current_user_id() -> Result { - match KVStore::get_str(USER_ID_DISK_CACHE_KEY) { + match KVStore::get_str(USER_ID_CACHE_KEY) { None => Err(ErrorBuilder::new(UserErrorCode::UserNotLoginYet).build()), Some(user_id) => Ok(user_id), } @@ -156,48 +192,4 @@ impl UserDatabaseConnection for UserSession { } } -const USER_ID_DISK_CACHE_KEY: &str = "user_id"; -lazy_static! { - pub static ref CURRENT_USER_ID: RwLock> = RwLock::new(None); -} - -pub(crate) fn get_current_user_id() -> Result { - let read_guard = CURRENT_USER_ID.read().map_err(|e| { - ErrorBuilder::new(UserErrorCode::ReadCurrentIdFailed) - .error(e) - .build() - })?; - - let mut user_id = (*read_guard).clone(); - // explicitly drop the read_guard in case of dead lock - drop(read_guard); - - if user_id.is_none() { - user_id = KVStore::get_str(USER_ID_DISK_CACHE_KEY); - *(CURRENT_USER_ID.write().unwrap()) = user_id.clone(); - } - - if user_id.is_none() { - return Err(ErrorBuilder::new(UserErrorCode::UserNotLoginYet).build()); - } - - match user_id { - None => Err(ErrorBuilder::new(UserErrorCode::UserNotLoginYet).build()), - Some(user_id) => Ok(user_id), - } -} - -pub(crate) fn set_current_user_id(user_id: Option) -> Result<(), UserError> { - KVStore::set_str( - USER_ID_DISK_CACHE_KEY, - user_id.clone().unwrap_or("".to_owned()), - ); - - let mut current_user_id = CURRENT_USER_ID.write().map_err(|e| { - ErrorBuilder::new(UserErrorCode::WriteCurrentIdFailed) - .error(e) - .build() - })?; - *current_user_id = user_id; - Ok(()) -} +const USER_ID_CACHE_KEY: &str = "user_id"; diff --git a/rust-lib/flowy-workspace/Cargo.toml b/rust-lib/flowy-workspace/Cargo.toml index 4610dcdcf7..3ec792721b 100644 --- a/rust-lib/flowy-workspace/Cargo.toml +++ b/rust-lib/flowy-workspace/Cargo.toml @@ -16,6 +16,8 @@ protobuf = {version = "2.18.0"} log = "0.4.14" diesel = {version = "1.4.7", features = ["sqlite"]} diesel_derives = {version = "1.4.1", features = ["sqlite"]} +futures-core = { version = "0.3", default-features = false } +pin-project = "1.0.0" lazy_static = "1.4.0" serde = { version = "1.0", features = ["derive"] } diff --git a/rust-lib/flowy-workspace/src/handlers/workspace_handler.rs b/rust-lib/flowy-workspace/src/handlers/workspace_handler.rs index 4faf654c21..1f519190a2 100644 --- a/rust-lib/flowy-workspace/src/handlers/workspace_handler.rs +++ b/rust-lib/flowy-workspace/src/handlers/workspace_handler.rs @@ -1,16 +1,17 @@ use crate::{ entities::workspace::{CreateWorkspaceParams, CreateWorkspaceRequest, WorkspaceDetail}, errors::WorkspaceError, - services::WorkspaceController, + services::{save_workspace, WorkspaceController}, }; -use flowy_dispatch::prelude::{response_ok, Data, ModuleData, ResponseResult}; -use std::{convert::TryInto, sync::Arc}; +use flowy_dispatch::prelude::{response_ok, Data, EventResponse, ModuleData, ResponseResult}; +use std::{convert::TryInto, pin::Pin, sync::Arc}; pub async fn create_workspace( data: Data, controller: ModuleData>, ) -> ResponseResult { + let controller = controller.get_ref().clone(); let params: CreateWorkspaceParams = data.into_inner().try_into()?; - let detail = controller.save_workspace(params)?; + let detail = save_workspace(controller, params).await?; response_ok(detail) } diff --git a/rust-lib/flowy-workspace/src/module.rs b/rust-lib/flowy-workspace/src/module.rs index 4dc6f0bfdd..9d1e67fec8 100644 --- a/rust-lib/flowy-workspace/src/module.rs +++ b/rust-lib/flowy-workspace/src/module.rs @@ -7,10 +7,11 @@ use crate::{ services::{AppController, WorkspaceController}, }; use flowy_database::DBConnection; +use futures_core::future::BoxFuture; use std::sync::Arc; pub trait WorkspaceUser: Send + Sync { - fn set_current_workspace(&self, id: &str); + fn set_current_workspace(&self, id: &str) -> BoxFuture<()>; fn get_current_workspace(&self) -> Result; fn db_connection(&self) -> Result; } diff --git a/rust-lib/flowy-workspace/src/services/workspace_controller.rs b/rust-lib/flowy-workspace/src/services/workspace_controller.rs index 568cdc06bd..28b7b0af7a 100644 --- a/rust-lib/flowy-workspace/src/services/workspace_controller.rs +++ b/rust-lib/flowy-workspace/src/services/workspace_controller.rs @@ -1,15 +1,16 @@ use crate::{entities::workspace::*, errors::*, module::WorkspaceUser, sql_tables::workspace::*}; use flowy_database::{prelude::*, schema::workspace_table}; +use futures_core::future::BoxFuture; use std::sync::Arc; pub struct WorkspaceController { - pub(crate) user: Arc, + pub user: Arc, } impl WorkspaceController { pub fn new(user: Arc) -> Self { Self { user } } - pub fn save_workspace( + pub async fn save_workspace( &self, params: CreateWorkspaceParams, ) -> Result { @@ -34,3 +35,19 @@ impl WorkspaceController { Ok(()) } } + +pub async fn save_workspace( + controller: Arc, + params: CreateWorkspaceParams, +) -> Result { + let workspace = Workspace::new(params); + let detail: WorkspaceDetail = workspace.clone().into(); + + let _ = diesel::insert_into(workspace_table::table) + .values(workspace) + .execute(&*(controller.user.db_connection()?))?; + + // set_current_workspace(controller.clone(), &detail.id).await; + + Ok(detail) +} From 602018765d0df7556a11cfc4900e804215b86797 Mon Sep 17 00:00:00 2001 From: appflowy Date: Mon, 19 Jul 2021 11:32:33 +0800 Subject: [PATCH 21/30] generic DispatchFuture and mark async_send with sync trait --- .../Flutter/GeneratedPluginRegistrant.swift | 2 +- app_flowy/pubspec.lock | 14 ++++++++ rust-lib/.gitignore | 4 ++- rust-lib/flowy-dispatch/src/dispatch.rs | 17 ++++++---- rust-lib/flowy-dispatch/src/lib.rs | 3 ++ rust-lib/flowy-dispatch/src/macros.rs | 8 +++++ rust-lib/flowy-sdk/src/flowy_server.rs | 1 - rust-lib/flowy-sdk/src/module.rs | 34 +++++++++++-------- rust-lib/flowy-test/src/builder.rs | 5 +-- rust-lib/flowy-test/src/tester.rs | 1 - .../flowy-user/src/entities/user_update.rs | 29 ++++++++++++++++ .../src/services/user_session/database.rs | 9 +---- .../src/services/user_session/user_session.rs | 15 +++----- .../src/handlers/workspace_handler.rs | 18 +++++++--- rust-lib/flowy-workspace/src/lib.rs | 3 ++ rust-lib/flowy-workspace/src/module.rs | 9 ++--- .../src/services/workspace_controller.rs | 23 ++----------- .../tests/event/workspace_test.rs | 1 - 18 files changed, 122 insertions(+), 74 deletions(-) create mode 100644 rust-lib/flowy-dispatch/src/macros.rs diff --git a/app_flowy/macos/Flutter/GeneratedPluginRegistrant.swift b/app_flowy/macos/Flutter/GeneratedPluginRegistrant.swift index 277667927e..f0757e328c 100644 --- a/app_flowy/macos/Flutter/GeneratedPluginRegistrant.swift +++ b/app_flowy/macos/Flutter/GeneratedPluginRegistrant.swift @@ -14,7 +14,7 @@ import window_size func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { FlowyEditorPlugin.register(with: registry.registrar(forPlugin: "FlowyEditorPlugin")) - FlowyInfraUiPlugin.register(with: registry.registrar(forPlugin: "FlowyInfraUiPlugin")) + FlowyInfraUIPlugin.register(with: registry.registrar(forPlugin: "FlowyInfraUIPlugin")) FlowySdkPlugin.register(with: registry.registrar(forPlugin: "FlowySdkPlugin")) PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin")) UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin")) diff --git a/app_flowy/pubspec.lock b/app_flowy/pubspec.lock index f8627b337e..58a8783ca8 100644 --- a/app_flowy/pubspec.lock +++ b/app_flowy/pubspec.lock @@ -253,6 +253,20 @@ packages: relative: true source: path version: "0.0.1" + flowy_infra_ui_platform_interface: + dependency: transitive + description: + path: "packages/flowy_infra_ui/flowy_infra_ui_platform_interface" + relative: true + source: path + version: "0.0.1" + flowy_infra_ui_web: + dependency: transitive + description: + path: "packages/flowy_infra_ui/flowy_infra_ui_web" + relative: true + source: path + version: "0.0.1" flowy_sdk: dependency: "direct main" description: diff --git a/rust-lib/.gitignore b/rust-lib/.gitignore index e2b01170f3..3ec66f140b 100644 --- a/rust-lib/.gitignore +++ b/rust-lib/.gitignore @@ -10,4 +10,6 @@ Cargo.lock **/*.rs.bk **/**/*.log* **/**/temp -bin/ \ No newline at end of file +bin/ + +.idea \ No newline at end of file diff --git a/rust-lib/flowy-dispatch/src/dispatch.rs b/rust-lib/flowy-dispatch/src/dispatch.rs index 9ca27d40dd..435a4aca9b 100644 --- a/rust-lib/flowy-dispatch/src/dispatch.rs +++ b/rust-lib/flowy-dispatch/src/dispatch.rs @@ -1,7 +1,7 @@ use crate::{ errors::{DispatchError, Error, InternalError}, module::{as_module_map, Module, ModuleMap, ModuleRequest}, - response::EventResponse, + response::{EventResponse, Responder}, service::{Service, ServiceFactory}, util::tokio_default_runtime, }; @@ -38,7 +38,7 @@ impl EventDispatch { *(EVENT_DISPATCH.write().unwrap()) = Some(dispatch); } - pub fn async_send(request: Req) -> DispatchFuture + pub fn async_send(request: Req) -> DispatchFuture where Req: std::convert::Into, { @@ -48,7 +48,7 @@ impl EventDispatch { pub fn async_send_with_callback( request: Req, callback: Callback, - ) -> DispatchFuture + ) -> DispatchFuture where Req: std::convert::Into, Callback: FnOnce(EventResponse) -> BoxFuture<'static, ()> + 'static + Send + Sync, @@ -99,13 +99,16 @@ impl EventDispatch { } #[pin_project] -pub struct DispatchFuture { +pub struct DispatchFuture { #[pin] - fut: BoxFuture<'static, EventResponse>, + pub fut: Pin + Sync + Send>>, } -impl Future for DispatchFuture { - type Output = EventResponse; +impl Future for DispatchFuture +where + T: Responder + Send + Sync, +{ + type Output = T; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let this = self.as_mut().project(); diff --git a/rust-lib/flowy-dispatch/src/lib.rs b/rust-lib/flowy-dispatch/src/lib.rs index 744f7abc0e..5e0da9ac9a 100644 --- a/rust-lib/flowy-dispatch/src/lib.rs +++ b/rust-lib/flowy-dispatch/src/lib.rs @@ -12,6 +12,9 @@ mod data; mod dispatch; mod system; +#[macro_use] +pub mod macros; + pub use errors::Error; pub mod prelude { diff --git a/rust-lib/flowy-dispatch/src/macros.rs b/rust-lib/flowy-dispatch/src/macros.rs new file mode 100644 index 0000000000..c8fb5eb832 --- /dev/null +++ b/rust-lib/flowy-dispatch/src/macros.rs @@ -0,0 +1,8 @@ +#[macro_export] +macro_rules! dispatch_future { + ($fut:expr) => { + DispatchFuture { + fut: Box::pin(async move { $fut.await }), + } + }; +} diff --git a/rust-lib/flowy-sdk/src/flowy_server.rs b/rust-lib/flowy-sdk/src/flowy_server.rs index ef13e4f9a7..1db12a4f19 100644 --- a/rust-lib/flowy-sdk/src/flowy_server.rs +++ b/rust-lib/flowy-sdk/src/flowy_server.rs @@ -1,4 +1,3 @@ -use flowy_infra::uuid; use flowy_user::{ entities::{SignInParams, SignUpParams, UserDetail}, errors::{ErrorBuilder, UserError, UserErrorCode}, diff --git a/rust-lib/flowy-sdk/src/module.rs b/rust-lib/flowy-sdk/src/module.rs index b13c3e336a..e0a809a4c1 100644 --- a/rust-lib/flowy-sdk/src/module.rs +++ b/rust-lib/flowy-sdk/src/module.rs @@ -1,10 +1,10 @@ use crate::flowy_server::{ArcFlowyServer, FlowyServerMocker}; use flowy_database::DBConnection; -use flowy_dispatch::prelude::Module; -use flowy_user::{errors::UserError, prelude::*}; +use flowy_dispatch::prelude::{DispatchFuture, Module}; +use flowy_user::prelude::*; use flowy_workspace::prelude::*; -use futures_core::future::BoxFuture; -use std::{pin::Pin, sync::Arc}; + +use std::sync::Arc; pub struct ModuleConfig { pub root: String, @@ -32,20 +32,26 @@ pub struct WorkspaceUserImpl { } impl WorkspaceUser for WorkspaceUserImpl { - fn set_current_workspace(&self, workspace_id: &str) -> BoxFuture<()> { + fn set_workspace(&self, workspace_id: &str) -> DispatchFuture> { let user_session = self.user_session.clone(); let workspace_id = workspace_id.to_owned(); - Box::pin(async move { - match user_session.set_current_workspace(&workspace_id).await { - Ok(_) => {}, - Err(e) => { - log::error!("Set current workspace error: {:?}", e); - }, - } - }) + DispatchFuture { + fut: Box::pin(async move { + let _ = user_session + .set_current_workspace(&workspace_id) + .await + .map_err(|e| { + ErrorBuilder::new(WorkspaceErrorCode::UserInternalError) + .error(e) + .build() + }); + + Ok(()) + }), + } } - fn get_current_workspace(&self) -> Result { + fn get_workspace(&self) -> Result { let user_detail = self.user_session.user_detail().map_err(|e| { ErrorBuilder::new(WorkspaceErrorCode::UserNotLoginYet) .error(e) diff --git a/rust-lib/flowy-test/src/builder.rs b/rust-lib/flowy-test/src/builder.rs index 65bb7d4b42..1e47ce16f5 100644 --- a/rust-lib/flowy-test/src/builder.rs +++ b/rust-lib/flowy-test/src/builder.rs @@ -16,10 +16,11 @@ use std::marker::PhantomData; pub type WorkspaceTestBuilder = TestBuilder>; impl WorkspaceTestBuilder { pub fn new() -> Self { - Self { + let builder = Self { tester: Box::new(FixedUserTester::::new()), user_detail: None, - } + }; + builder.login() } } diff --git a/rust-lib/flowy-test/src/tester.rs b/rust-lib/flowy-test/src/tester.rs index dc505c36c2..2d450f0209 100644 --- a/rust-lib/flowy-test/src/tester.rs +++ b/rust-lib/flowy-test/src/tester.rs @@ -14,7 +14,6 @@ use std::{ fmt::{Debug, Display}, hash::Hash, sync::Arc, - thread, }; pub struct TesterContext { diff --git a/rust-lib/flowy-user/src/entities/user_update.rs b/rust-lib/flowy-user/src/entities/user_update.rs index 5d8a2da342..ab072bd22f 100644 --- a/rust-lib/flowy-user/src/entities/user_update.rs +++ b/rust-lib/flowy-user/src/entities/user_update.rs @@ -23,6 +23,35 @@ pub struct UpdateUserRequest { pub password: Option, } +impl UpdateUserRequest { + pub fn new(id: &str) -> Self { + Self { + id: id.to_owned(), + ..Default::default() + } + } + + pub fn name(mut self, name: &str) -> Self { + self.name = Some(name.to_owned()); + self + } + + pub fn email(mut self, email: &str) -> Self { + self.email = Some(email.to_owned()); + self + } + + pub fn workspace(mut self, workspace: &str) -> Self { + self.workspace = Some(workspace.to_owned()); + self + } + + pub fn password(mut self, password: &str) -> Self { + self.password = Some(password.to_owned()); + self + } +} + pub struct UpdateUserParams { pub id: String, pub name: Option, diff --git a/rust-lib/flowy-user/src/services/user_session/database.rs b/rust-lib/flowy-user/src/services/user_session/database.rs index 6103ec4e1c..6365868c31 100644 --- a/rust-lib/flowy-user/src/services/user_session/database.rs +++ b/rust-lib/flowy-user/src/services/user_session/database.rs @@ -3,14 +3,7 @@ use flowy_database::{DBConnection, Database}; use lazy_static::lazy_static; use once_cell::sync::Lazy; use parking_lot::Mutex; -use std::{ - cell::RefCell, - collections::HashMap, - sync::{ - atomic::{AtomicBool, Ordering}, - RwLock, - }, -}; +use std::{collections::HashMap, sync::RwLock}; lazy_static! { static ref DB: RwLock> = RwLock::new(None); diff --git a/rust-lib/flowy-user/src/services/user_session/user_session.rs b/rust-lib/flowy-user/src/services/user_session/user_session.rs index 18f4621e59..475a955bb0 100644 --- a/rust-lib/flowy-user/src/services/user_session/user_session.rs +++ b/rust-lib/flowy-user/src/services/user_session/user_session.rs @@ -6,7 +6,7 @@ use flowy_database::{ UserDatabaseConnection, }; use flowy_infra::kv::KVStore; -use lazy_static::lazy_static; + use std::sync::{Arc, RwLock}; use crate::{ @@ -159,15 +159,10 @@ impl UserSession { pub async fn set_current_workspace(&self, workspace_id: &str) -> Result<(), UserError> { let user_id = self.get_user_id()?; - let payload: Vec = UpdateUserRequest { - id: user_id, - name: None, - email: None, - workspace: Some(workspace_id.to_owned()), - password: None, - } - .into_bytes() - .unwrap(); + let payload: Vec = UpdateUserRequest::new(&user_id) + .workspace(workspace_id) + .into_bytes() + .unwrap(); let request = ModuleRequest::new(UpdateUser).payload(payload); let _user_detail = EventDispatch::async_send(request) diff --git a/rust-lib/flowy-workspace/src/handlers/workspace_handler.rs b/rust-lib/flowy-workspace/src/handlers/workspace_handler.rs index 1f519190a2..e15ca53d9e 100644 --- a/rust-lib/flowy-workspace/src/handlers/workspace_handler.rs +++ b/rust-lib/flowy-workspace/src/handlers/workspace_handler.rs @@ -1,10 +1,10 @@ use crate::{ entities::workspace::{CreateWorkspaceParams, CreateWorkspaceRequest, WorkspaceDetail}, errors::WorkspaceError, - services::{save_workspace, WorkspaceController}, + services::WorkspaceController, }; -use flowy_dispatch::prelude::{response_ok, Data, EventResponse, ModuleData, ResponseResult}; -use std::{convert::TryInto, pin::Pin, sync::Arc}; +use flowy_dispatch::prelude::{response_ok, Data, ModuleData, ResponseResult}; +use std::{convert::TryInto, sync::Arc}; pub async fn create_workspace( data: Data, @@ -12,6 +12,16 @@ pub async fn create_workspace( ) -> ResponseResult { let controller = controller.get_ref().clone(); let params: CreateWorkspaceParams = data.into_inner().try_into()?; - let detail = save_workspace(controller, params).await?; + let detail = controller.save_workspace(params).await?; + response_ok(detail) +} + +pub async fn workspace_user( + data: Data, + controller: ModuleData>, +) -> ResponseResult { + let controller = controller.get_ref().clone(); + let params: CreateWorkspaceParams = data.into_inner().try_into()?; + let detail = controller.save_workspace(params).await?; response_ok(detail) } diff --git a/rust-lib/flowy-workspace/src/lib.rs b/rust-lib/flowy-workspace/src/lib.rs index 6b5878e12f..111c190399 100644 --- a/rust-lib/flowy-workspace/src/lib.rs +++ b/rust-lib/flowy-workspace/src/lib.rs @@ -13,6 +13,9 @@ mod services; #[macro_use] extern crate flowy_database; +#[macro_use] +extern crate flowy_dispatch; + pub mod prelude { pub use crate::{errors::*, module::*, services::*}; } diff --git a/rust-lib/flowy-workspace/src/module.rs b/rust-lib/flowy-workspace/src/module.rs index 9d1e67fec8..e82a48515c 100644 --- a/rust-lib/flowy-workspace/src/module.rs +++ b/rust-lib/flowy-workspace/src/module.rs @@ -3,16 +3,16 @@ use flowy_dispatch::prelude::*; use crate::{ errors::WorkspaceError, event::WorkspaceEvent, - handlers::create_workspace, services::{AppController, WorkspaceController}, }; use flowy_database::DBConnection; -use futures_core::future::BoxFuture; + +use crate::handlers::*; use std::sync::Arc; pub trait WorkspaceUser: Send + Sync { - fn set_current_workspace(&self, id: &str) -> BoxFuture<()>; - fn get_current_workspace(&self) -> Result; + fn set_workspace(&self, id: &str) -> DispatchFuture>; + fn get_workspace(&self) -> Result; fn db_connection(&self) -> Result; } @@ -25,4 +25,5 @@ pub fn create(user: Arc) -> Module { .data(workspace_controller) .data(app_controller) .event(WorkspaceEvent::CreateWorkspace, create_workspace) + .event(WorkspaceEvent::GetWorkspaceUserDetail, workspace_user) } diff --git a/rust-lib/flowy-workspace/src/services/workspace_controller.rs b/rust-lib/flowy-workspace/src/services/workspace_controller.rs index 28b7b0af7a..dad0a817c0 100644 --- a/rust-lib/flowy-workspace/src/services/workspace_controller.rs +++ b/rust-lib/flowy-workspace/src/services/workspace_controller.rs @@ -1,6 +1,6 @@ use crate::{entities::workspace::*, errors::*, module::WorkspaceUser, sql_tables::workspace::*}; use flowy_database::{prelude::*, schema::workspace_table}; -use futures_core::future::BoxFuture; + use std::sync::Arc; pub struct WorkspaceController { @@ -15,14 +15,13 @@ impl WorkspaceController { params: CreateWorkspaceParams, ) -> Result { let workspace = Workspace::new(params); - let conn = self.user.db_connection()?; let detail: WorkspaceDetail = workspace.clone().into(); let _ = diesel::insert_into(workspace_table::table) .values(workspace) - .execute(&*conn)?; + .execute(&*(self.user.db_connection()?))?; - self.user.set_current_workspace(&detail.id); + let _ = self.user.set_workspace(&detail.id).await?; Ok(detail) } @@ -35,19 +34,3 @@ impl WorkspaceController { Ok(()) } } - -pub async fn save_workspace( - controller: Arc, - params: CreateWorkspaceParams, -) -> Result { - let workspace = Workspace::new(params); - let detail: WorkspaceDetail = workspace.clone().into(); - - let _ = diesel::insert_into(workspace_table::table) - .values(workspace) - .execute(&*(controller.user.db_connection()?))?; - - // set_current_workspace(controller.clone(), &detail.id).await; - - Ok(detail) -} diff --git a/rust-lib/flowy-workspace/tests/event/workspace_test.rs b/rust-lib/flowy-workspace/tests/event/workspace_test.rs index e23fc48d81..8c00414098 100644 --- a/rust-lib/flowy-workspace/tests/event/workspace_test.rs +++ b/rust-lib/flowy-workspace/tests/event/workspace_test.rs @@ -13,7 +13,6 @@ fn workspace_create_success() { }; let response = WorkspaceTestBuilder::new() - .login() .event(CreateWorkspace) .request(request) .sync_send() From 06be0a562c692c1086819ab9b5c1c6b5433d6ac5 Mon Sep 17 00:00:00 2001 From: appflowy Date: Mon, 19 Jul 2021 11:36:30 +0800 Subject: [PATCH 22/30] add clion config files --- .idea/dataSources.xml | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 .idea/dataSources.xml diff --git a/.idea/dataSources.xml b/.idea/dataSources.xml new file mode 100644 index 0000000000..7f5b513827 --- /dev/null +++ b/.idea/dataSources.xml @@ -0,0 +1,12 @@ + + + + + sqlite.xerial + true + org.sqlite.JDBC + jdbc:sqlite:$PROJECT_DIR$/rust-lib/flowy-test/temp/flowy/annie@appflowy.io/flowy-database.db + $ProjectFileDir$ + + + \ No newline at end of file From ef4c4180e2d517d74be7b727cebac2a85e825105 Mon Sep 17 00:00:00 2001 From: appflowy Date: Mon, 19 Jul 2021 16:15:20 +0800 Subject: [PATCH 23/30] fix sqlite database is lock issue by setting busy_timeout and wal mode --- .../protobuf/flowy-user/errors.pbenum.dart | 20 +- .../protobuf/flowy-user/errors.pbjson.dart | 12 +- .../flowy-workspace/errors.pbenum.dart | 4 +- .../flowy-workspace/errors.pbjson.dart | 4 +- .../flowy-workspace/event.pbenum.dart | 4 +- .../flowy-workspace/event.pbjson.dart | 4 +- .../protobuf/flowy-workspace/protobuf.dart | 1 + .../workspace_user_detail.pb.dart | 137 +++++ .../workspace_user_detail.pbenum.dart | 7 + .../workspace_user_detail.pbjson.dart | 32 ++ .../workspace_user_detail.pbserver.dart | 9 + .../src/derive_cache/derive_cache.rs | 2 + rust-lib/flowy-dispatch/src/dispatch.rs | 4 +- rust-lib/flowy-infra/src/kv/kv.rs | 15 +- rust-lib/flowy-sdk/src/deps_resolve/mod.rs | 3 + .../src/deps_resolve/workspace_user_impl.rs | 63 +++ rust-lib/flowy-sdk/src/lib.rs | 7 +- rust-lib/flowy-sdk/src/module.rs | 44 +- rust-lib/flowy-sqlite/src/conn_ext.rs | 30 ++ rust-lib/flowy-sqlite/src/lib.rs | 3 + rust-lib/flowy-sqlite/src/pool.rs | 51 +- rust-lib/flowy-sqlite/src/pragma.rs | 186 +++++++ rust-lib/flowy-test/src/builder.rs | 17 +- rust-lib/flowy-test/src/tester.rs | 14 +- rust-lib/flowy-user/src/errors.rs | 14 +- .../flowy-user/src/protobuf/model/errors.rs | 120 ++--- .../src/protobuf/proto/errors.proto | 10 +- .../src/services/user_session/database.rs | 13 +- .../src/services/user_session/user_session.rs | 24 +- .../flowy-user/tests/event/sign_in_test.rs | 230 --------- .../flowy-user/tests/event/sign_up_test.rs | 130 ++--- .../tests/event/user_status_test.rs | 72 +-- .../tests/event/user_update_test.rs | 280 +++++------ .../workspace/workspace_user_detail.rs | 22 +- rust-lib/flowy-workspace/src/errors.rs | 12 +- rust-lib/flowy-workspace/src/event.rs | 8 +- .../src/handlers/workspace_handler.rs | 19 +- rust-lib/flowy-workspace/src/module.rs | 8 +- .../src/protobuf/model/errors.rs | 16 +- .../src/protobuf/model/event.rs | 22 +- .../flowy-workspace/src/protobuf/model/mod.rs | 3 + .../protobuf/model/workspace_user_detail.rs | 476 ++++++++++++++++++ .../src/protobuf/proto/errors.proto | 2 +- .../src/protobuf/proto/event.proto | 2 +- .../proto/workspace_user_detail.proto | 11 + .../src/services/workspace_controller.rs | 32 +- .../tests/event/workspace_test.rs | 23 +- scripts/flowy-tool/Cargo.toml | 3 +- scripts/flowy-tool/src/proto/ast.rs | 1 + scripts/flowy-tool/src/proto/proto_info.rs | 2 + scripts/flowy-tool/src/util/file.rs | 11 + 51 files changed, 1539 insertions(+), 700 deletions(-) create mode 100644 app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/workspace_user_detail.pb.dart create mode 100644 app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/workspace_user_detail.pbenum.dart create mode 100644 app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/workspace_user_detail.pbjson.dart create mode 100644 app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/workspace_user_detail.pbserver.dart create mode 100644 rust-lib/flowy-sdk/src/deps_resolve/mod.rs create mode 100644 rust-lib/flowy-sdk/src/deps_resolve/workspace_user_impl.rs create mode 100644 rust-lib/flowy-sqlite/src/conn_ext.rs create mode 100644 rust-lib/flowy-sqlite/src/pragma.rs create mode 100644 rust-lib/flowy-workspace/src/protobuf/model/workspace_user_detail.rs create mode 100644 rust-lib/flowy-workspace/src/protobuf/proto/workspace_user_detail.proto diff --git a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-user/errors.pbenum.dart b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-user/errors.pbenum.dart index 9b07cc71c3..3743123065 100644 --- a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-user/errors.pbenum.dart +++ b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-user/errors.pbenum.dart @@ -11,11 +11,11 @@ import 'package:protobuf/protobuf.dart' as $pb; class UserErrorCode extends $pb.ProtobufEnum { static const UserErrorCode Unknown = UserErrorCode._(0, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'Unknown'); - static const UserErrorCode DatabaseInitFailed = UserErrorCode._(1, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'DatabaseInitFailed'); - static const UserErrorCode DatabaseWriteLocked = UserErrorCode._(2, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'DatabaseWriteLocked'); - static const UserErrorCode DatabaseReadLocked = UserErrorCode._(3, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'DatabaseReadLocked'); - static const UserErrorCode DatabaseUserDidNotMatch = UserErrorCode._(4, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'DatabaseUserDidNotMatch'); - static const UserErrorCode DatabaseInternalError = UserErrorCode._(5, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'DatabaseInternalError'); + static const UserErrorCode UserDatabaseInitFailed = UserErrorCode._(1, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'UserDatabaseInitFailed'); + static const UserErrorCode UserDatabaseWriteLocked = UserErrorCode._(2, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'UserDatabaseWriteLocked'); + static const UserErrorCode UserDatabaseReadLocked = UserErrorCode._(3, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'UserDatabaseReadLocked'); + static const UserErrorCode UserDatabaseDidNotMatch = UserErrorCode._(4, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'UserDatabaseDidNotMatch'); + static const UserErrorCode UserDatabaseInternalError = UserErrorCode._(5, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'UserDatabaseInternalError'); static const UserErrorCode UserNotLoginYet = UserErrorCode._(10, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'UserNotLoginYet'); static const UserErrorCode ReadCurrentIdFailed = UserErrorCode._(11, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'ReadCurrentIdFailed'); static const UserErrorCode WriteCurrentIdFailed = UserErrorCode._(12, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'WriteCurrentIdFailed'); @@ -27,11 +27,11 @@ class UserErrorCode extends $pb.ProtobufEnum { static const $core.List values = [ Unknown, - DatabaseInitFailed, - DatabaseWriteLocked, - DatabaseReadLocked, - DatabaseUserDidNotMatch, - DatabaseInternalError, + UserDatabaseInitFailed, + UserDatabaseWriteLocked, + UserDatabaseReadLocked, + UserDatabaseDidNotMatch, + UserDatabaseInternalError, UserNotLoginYet, ReadCurrentIdFailed, WriteCurrentIdFailed, diff --git a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-user/errors.pbjson.dart b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-user/errors.pbjson.dart index 217cb44134..1e2eb92c66 100644 --- a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-user/errors.pbjson.dart +++ b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-user/errors.pbjson.dart @@ -13,11 +13,11 @@ const UserErrorCode$json = const { '1': 'UserErrorCode', '2': const [ const {'1': 'Unknown', '2': 0}, - const {'1': 'DatabaseInitFailed', '2': 1}, - const {'1': 'DatabaseWriteLocked', '2': 2}, - const {'1': 'DatabaseReadLocked', '2': 3}, - const {'1': 'DatabaseUserDidNotMatch', '2': 4}, - const {'1': 'DatabaseInternalError', '2': 5}, + const {'1': 'UserDatabaseInitFailed', '2': 1}, + const {'1': 'UserDatabaseWriteLocked', '2': 2}, + const {'1': 'UserDatabaseReadLocked', '2': 3}, + const {'1': 'UserDatabaseDidNotMatch', '2': 4}, + const {'1': 'UserDatabaseInternalError', '2': 5}, const {'1': 'UserNotLoginYet', '2': 10}, const {'1': 'ReadCurrentIdFailed', '2': 11}, const {'1': 'WriteCurrentIdFailed', '2': 12}, @@ -30,7 +30,7 @@ const UserErrorCode$json = const { }; /// Descriptor for `UserErrorCode`. Decode as a `google.protobuf.EnumDescriptorProto`. -final $typed_data.Uint8List userErrorCodeDescriptor = $convert.base64Decode('Cg1Vc2VyRXJyb3JDb2RlEgsKB1Vua25vd24QABIWChJEYXRhYmFzZUluaXRGYWlsZWQQARIXChNEYXRhYmFzZVdyaXRlTG9ja2VkEAISFgoSRGF0YWJhc2VSZWFkTG9ja2VkEAMSGwoXRGF0YWJhc2VVc2VyRGlkTm90TWF0Y2gQBBIZChVEYXRhYmFzZUludGVybmFsRXJyb3IQBRITCg9Vc2VyTm90TG9naW5ZZXQQChIXChNSZWFkQ3VycmVudElkRmFpbGVkEAsSGAoUV3JpdGVDdXJyZW50SWRGYWlsZWQQDBIQCgxFbWFpbEludmFsaWQQFBITCg9QYXNzd29yZEludmFsaWQQFRITCg9Vc2VyTmFtZUludmFsaWQQFhIYChRVc2VyV29ya3NwYWNlSW52YWxpZBAXEhEKDVVzZXJJZEludmFsaWQQGA=='); +final $typed_data.Uint8List userErrorCodeDescriptor = $convert.base64Decode('Cg1Vc2VyRXJyb3JDb2RlEgsKB1Vua25vd24QABIaChZVc2VyRGF0YWJhc2VJbml0RmFpbGVkEAESGwoXVXNlckRhdGFiYXNlV3JpdGVMb2NrZWQQAhIaChZVc2VyRGF0YWJhc2VSZWFkTG9ja2VkEAMSGwoXVXNlckRhdGFiYXNlRGlkTm90TWF0Y2gQBBIdChlVc2VyRGF0YWJhc2VJbnRlcm5hbEVycm9yEAUSEwoPVXNlck5vdExvZ2luWWV0EAoSFwoTUmVhZEN1cnJlbnRJZEZhaWxlZBALEhgKFFdyaXRlQ3VycmVudElkRmFpbGVkEAwSEAoMRW1haWxJbnZhbGlkEBQSEwoPUGFzc3dvcmRJbnZhbGlkEBUSEwoPVXNlck5hbWVJbnZhbGlkEBYSGAoUVXNlcldvcmtzcGFjZUludmFsaWQQFxIRCg1Vc2VySWRJbnZhbGlkEBg='); @$core.Deprecated('Use userErrorDescriptor instead') const UserError$json = const { '1': 'UserError', diff --git a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/errors.pbenum.dart b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/errors.pbenum.dart index ec32d54844..40189fb948 100644 --- a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/errors.pbenum.dart +++ b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/errors.pbenum.dart @@ -16,7 +16,7 @@ class WorkspaceErrorCode extends $pb.ProtobufEnum { static const WorkspaceErrorCode AppColorStyleInvalid = WorkspaceErrorCode._(3, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'AppColorStyleInvalid'); static const WorkspaceErrorCode AppIdInvalid = WorkspaceErrorCode._(4, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'AppIdInvalid'); static const WorkspaceErrorCode DatabaseConnectionFail = WorkspaceErrorCode._(5, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'DatabaseConnectionFail'); - static const WorkspaceErrorCode DatabaseInternalError = WorkspaceErrorCode._(6, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'DatabaseInternalError'); + static const WorkspaceErrorCode WorkspaceDatabaseError = WorkspaceErrorCode._(6, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'WorkspaceDatabaseError'); static const WorkspaceErrorCode UserInternalError = WorkspaceErrorCode._(10, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'UserInternalError'); static const WorkspaceErrorCode UserNotLoginYet = WorkspaceErrorCode._(11, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'UserNotLoginYet'); @@ -27,7 +27,7 @@ class WorkspaceErrorCode extends $pb.ProtobufEnum { AppColorStyleInvalid, AppIdInvalid, DatabaseConnectionFail, - DatabaseInternalError, + WorkspaceDatabaseError, UserInternalError, UserNotLoginYet, ]; diff --git a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/errors.pbjson.dart b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/errors.pbjson.dart index 7bb4fc0447..b855710f36 100644 --- a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/errors.pbjson.dart +++ b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/errors.pbjson.dart @@ -18,14 +18,14 @@ const WorkspaceErrorCode$json = const { const {'1': 'AppColorStyleInvalid', '2': 3}, const {'1': 'AppIdInvalid', '2': 4}, const {'1': 'DatabaseConnectionFail', '2': 5}, - const {'1': 'DatabaseInternalError', '2': 6}, + const {'1': 'WorkspaceDatabaseError', '2': 6}, const {'1': 'UserInternalError', '2': 10}, const {'1': 'UserNotLoginYet', '2': 11}, ], }; /// Descriptor for `WorkspaceErrorCode`. Decode as a `google.protobuf.EnumDescriptorProto`. -final $typed_data.Uint8List workspaceErrorCodeDescriptor = $convert.base64Decode('ChJXb3Jrc3BhY2VFcnJvckNvZGUSCwoHVW5rbm93bhAAEhgKFFdvcmtzcGFjZU5hbWVJbnZhbGlkEAESFgoSV29ya3NwYWNlSWRJbnZhbGlkEAISGAoUQXBwQ29sb3JTdHlsZUludmFsaWQQAxIQCgxBcHBJZEludmFsaWQQBBIaChZEYXRhYmFzZUNvbm5lY3Rpb25GYWlsEAUSGQoVRGF0YWJhc2VJbnRlcm5hbEVycm9yEAYSFQoRVXNlckludGVybmFsRXJyb3IQChITCg9Vc2VyTm90TG9naW5ZZXQQCw=='); +final $typed_data.Uint8List workspaceErrorCodeDescriptor = $convert.base64Decode('ChJXb3Jrc3BhY2VFcnJvckNvZGUSCwoHVW5rbm93bhAAEhgKFFdvcmtzcGFjZU5hbWVJbnZhbGlkEAESFgoSV29ya3NwYWNlSWRJbnZhbGlkEAISGAoUQXBwQ29sb3JTdHlsZUludmFsaWQQAxIQCgxBcHBJZEludmFsaWQQBBIaChZEYXRhYmFzZUNvbm5lY3Rpb25GYWlsEAUSGgoWV29ya3NwYWNlRGF0YWJhc2VFcnJvchAGEhUKEVVzZXJJbnRlcm5hbEVycm9yEAoSEwoPVXNlck5vdExvZ2luWWV0EAs='); @$core.Deprecated('Use workspaceErrorDescriptor instead') const WorkspaceError$json = const { '1': 'WorkspaceError', diff --git a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/event.pbenum.dart b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/event.pbenum.dart index 1d9502e8d9..02c50ad27f 100644 --- a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/event.pbenum.dart +++ b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/event.pbenum.dart @@ -11,11 +11,11 @@ import 'package:protobuf/protobuf.dart' as $pb; class WorkspaceEvent extends $pb.ProtobufEnum { static const WorkspaceEvent CreateWorkspace = WorkspaceEvent._(0, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'CreateWorkspace'); - static const WorkspaceEvent GetWorkspaceUserDetail = WorkspaceEvent._(100, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'GetWorkspaceUserDetail'); + static const WorkspaceEvent GetWorkspaceDetail = WorkspaceEvent._(1, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'GetWorkspaceDetail'); static const $core.List values = [ CreateWorkspace, - GetWorkspaceUserDetail, + GetWorkspaceDetail, ]; static final $core.Map<$core.int, WorkspaceEvent> _byValue = $pb.ProtobufEnum.initByValue(values); diff --git a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/event.pbjson.dart b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/event.pbjson.dart index 7466b2d76b..86296a37ea 100644 --- a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/event.pbjson.dart +++ b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/event.pbjson.dart @@ -13,9 +13,9 @@ const WorkspaceEvent$json = const { '1': 'WorkspaceEvent', '2': const [ const {'1': 'CreateWorkspace', '2': 0}, - const {'1': 'GetWorkspaceUserDetail', '2': 100}, + const {'1': 'GetWorkspaceDetail', '2': 1}, ], }; /// Descriptor for `WorkspaceEvent`. Decode as a `google.protobuf.EnumDescriptorProto`. -final $typed_data.Uint8List workspaceEventDescriptor = $convert.base64Decode('Cg5Xb3Jrc3BhY2VFdmVudBITCg9DcmVhdGVXb3Jrc3BhY2UQABIaChZHZXRXb3Jrc3BhY2VVc2VyRGV0YWlsEGQ='); +final $typed_data.Uint8List workspaceEventDescriptor = $convert.base64Decode('Cg5Xb3Jrc3BhY2VFdmVudBITCg9DcmVhdGVXb3Jrc3BhY2UQABIWChJHZXRXb3Jrc3BhY2VEZXRhaWwQAQ=='); diff --git a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/protobuf.dart b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/protobuf.dart index c2b727a826..cee28e7715 100644 --- a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/protobuf.dart +++ b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/protobuf.dart @@ -3,5 +3,6 @@ export './errors.pb.dart'; export './workspace_update.pb.dart'; export './app_create.pb.dart'; export './event.pb.dart'; +export './workspace_user_detail.pb.dart'; export './workspace_create.pb.dart'; export './app_update.pb.dart'; diff --git a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/workspace_user_detail.pb.dart b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/workspace_user_detail.pb.dart new file mode 100644 index 0000000000..94f2b8bc49 --- /dev/null +++ b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/workspace_user_detail.pb.dart @@ -0,0 +1,137 @@ +/// +// Generated code. Do not modify. +// source: workspace_user_detail.proto +// +// @dart = 2.12 +// ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields + +import 'dart:core' as $core; + +import 'package:protobuf/protobuf.dart' as $pb; + +import 'workspace_create.pb.dart' as $0; + +class UserWorkspace extends $pb.GeneratedMessage { + static final $pb.BuilderInfo _i = $pb.BuilderInfo(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'UserWorkspace', createEmptyInstance: create) + ..aOS(1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'owner') + ..aOS(2, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'workspaceId') + ..hasRequiredFields = false + ; + + UserWorkspace._() : super(); + factory UserWorkspace({ + $core.String? owner, + $core.String? workspaceId, + }) { + final _result = create(); + if (owner != null) { + _result.owner = owner; + } + if (workspaceId != null) { + _result.workspaceId = workspaceId; + } + return _result; + } + factory UserWorkspace.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); + factory UserWorkspace.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); + @$core.Deprecated( + 'Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' + 'Will be removed in next major version') + UserWorkspace clone() => UserWorkspace()..mergeFromMessage(this); + @$core.Deprecated( + 'Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' + 'Will be removed in next major version') + UserWorkspace copyWith(void Function(UserWorkspace) updates) => super.copyWith((message) => updates(message as UserWorkspace)) as UserWorkspace; // ignore: deprecated_member_use + $pb.BuilderInfo get info_ => _i; + @$core.pragma('dart2js:noInline') + static UserWorkspace create() => UserWorkspace._(); + UserWorkspace createEmptyInstance() => create(); + static $pb.PbList createRepeated() => $pb.PbList(); + @$core.pragma('dart2js:noInline') + static UserWorkspace getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static UserWorkspace? _defaultInstance; + + @$pb.TagNumber(1) + $core.String get owner => $_getSZ(0); + @$pb.TagNumber(1) + set owner($core.String v) { $_setString(0, v); } + @$pb.TagNumber(1) + $core.bool hasOwner() => $_has(0); + @$pb.TagNumber(1) + void clearOwner() => clearField(1); + + @$pb.TagNumber(2) + $core.String get workspaceId => $_getSZ(1); + @$pb.TagNumber(2) + set workspaceId($core.String v) { $_setString(1, v); } + @$pb.TagNumber(2) + $core.bool hasWorkspaceId() => $_has(1); + @$pb.TagNumber(2) + void clearWorkspaceId() => clearField(2); +} + +class UserWorkspaceDetail extends $pb.GeneratedMessage { + static final $pb.BuilderInfo _i = $pb.BuilderInfo(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'UserWorkspaceDetail', createEmptyInstance: create) + ..aOS(1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'owner') + ..aOM<$0.WorkspaceDetail>(2, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'workspace', subBuilder: $0.WorkspaceDetail.create) + ..hasRequiredFields = false + ; + + UserWorkspaceDetail._() : super(); + factory UserWorkspaceDetail({ + $core.String? owner, + $0.WorkspaceDetail? workspace, + }) { + final _result = create(); + if (owner != null) { + _result.owner = owner; + } + if (workspace != null) { + _result.workspace = workspace; + } + return _result; + } + factory UserWorkspaceDetail.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); + factory UserWorkspaceDetail.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); + @$core.Deprecated( + 'Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' + 'Will be removed in next major version') + UserWorkspaceDetail clone() => UserWorkspaceDetail()..mergeFromMessage(this); + @$core.Deprecated( + 'Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' + 'Will be removed in next major version') + UserWorkspaceDetail copyWith(void Function(UserWorkspaceDetail) updates) => super.copyWith((message) => updates(message as UserWorkspaceDetail)) as UserWorkspaceDetail; // ignore: deprecated_member_use + $pb.BuilderInfo get info_ => _i; + @$core.pragma('dart2js:noInline') + static UserWorkspaceDetail create() => UserWorkspaceDetail._(); + UserWorkspaceDetail createEmptyInstance() => create(); + static $pb.PbList createRepeated() => $pb.PbList(); + @$core.pragma('dart2js:noInline') + static UserWorkspaceDetail getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static UserWorkspaceDetail? _defaultInstance; + + @$pb.TagNumber(1) + $core.String get owner => $_getSZ(0); + @$pb.TagNumber(1) + set owner($core.String v) { $_setString(0, v); } + @$pb.TagNumber(1) + $core.bool hasOwner() => $_has(0); + @$pb.TagNumber(1) + void clearOwner() => clearField(1); + + @$pb.TagNumber(2) + $0.WorkspaceDetail get workspace => $_getN(1); + @$pb.TagNumber(2) + set workspace($0.WorkspaceDetail v) { setField(2, v); } + @$pb.TagNumber(2) + $core.bool hasWorkspace() => $_has(1); + @$pb.TagNumber(2) + void clearWorkspace() => clearField(2); + @$pb.TagNumber(2) + $0.WorkspaceDetail ensureWorkspace() => $_ensure(1); +} + diff --git a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/workspace_user_detail.pbenum.dart b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/workspace_user_detail.pbenum.dart new file mode 100644 index 0000000000..ca5e23ef81 --- /dev/null +++ b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/workspace_user_detail.pbenum.dart @@ -0,0 +1,7 @@ +/// +// Generated code. Do not modify. +// source: workspace_user_detail.proto +// +// @dart = 2.12 +// ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields + diff --git a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/workspace_user_detail.pbjson.dart b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/workspace_user_detail.pbjson.dart new file mode 100644 index 0000000000..10d0b093c9 --- /dev/null +++ b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/workspace_user_detail.pbjson.dart @@ -0,0 +1,32 @@ +/// +// Generated code. Do not modify. +// source: workspace_user_detail.proto +// +// @dart = 2.12 +// ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields,deprecated_member_use_from_same_package + +import 'dart:core' as $core; +import 'dart:convert' as $convert; +import 'dart:typed_data' as $typed_data; +@$core.Deprecated('Use userWorkspaceDescriptor instead') +const UserWorkspace$json = const { + '1': 'UserWorkspace', + '2': const [ + const {'1': 'owner', '3': 1, '4': 1, '5': 9, '10': 'owner'}, + const {'1': 'workspace_id', '3': 2, '4': 1, '5': 9, '10': 'workspaceId'}, + ], +}; + +/// Descriptor for `UserWorkspace`. Decode as a `google.protobuf.DescriptorProto`. +final $typed_data.Uint8List userWorkspaceDescriptor = $convert.base64Decode('Cg1Vc2VyV29ya3NwYWNlEhQKBW93bmVyGAEgASgJUgVvd25lchIhCgx3b3Jrc3BhY2VfaWQYAiABKAlSC3dvcmtzcGFjZUlk'); +@$core.Deprecated('Use userWorkspaceDetailDescriptor instead') +const UserWorkspaceDetail$json = const { + '1': 'UserWorkspaceDetail', + '2': const [ + const {'1': 'owner', '3': 1, '4': 1, '5': 9, '10': 'owner'}, + const {'1': 'workspace', '3': 2, '4': 1, '5': 11, '6': '.WorkspaceDetail', '10': 'workspace'}, + ], +}; + +/// Descriptor for `UserWorkspaceDetail`. Decode as a `google.protobuf.DescriptorProto`. +final $typed_data.Uint8List userWorkspaceDetailDescriptor = $convert.base64Decode('ChNVc2VyV29ya3NwYWNlRGV0YWlsEhQKBW93bmVyGAEgASgJUgVvd25lchIuCgl3b3Jrc3BhY2UYAiABKAsyEC5Xb3Jrc3BhY2VEZXRhaWxSCXdvcmtzcGFjZQ=='); diff --git a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/workspace_user_detail.pbserver.dart b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/workspace_user_detail.pbserver.dart new file mode 100644 index 0000000000..8fc33d92ca --- /dev/null +++ b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/workspace_user_detail.pbserver.dart @@ -0,0 +1,9 @@ +/// +// Generated code. Do not modify. +// source: workspace_user_detail.proto +// +// @dart = 2.12 +// ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields,deprecated_member_use_from_same_package + +export 'workspace_user_detail.pb.dart'; + diff --git a/rust-lib/flowy-derive/src/derive_cache/derive_cache.rs b/rust-lib/flowy-derive/src/derive_cache/derive_cache.rs index c0efa13115..088c2ee0c3 100644 --- a/rust-lib/flowy-derive/src/derive_cache/derive_cache.rs +++ b/rust-lib/flowy-derive/src/derive_cache/derive_cache.rs @@ -23,6 +23,8 @@ pub fn category_from_str(type_str: &str) -> TypeCategory { | "UpdateWorkspaceRequest" | "CreateWorkspaceRequest" | "WorkspaceDetail" + | "UserWorkspace" + | "UserWorkspaceDetail" | "WorkspaceError" | "FFIRequest" | "FFIResponse" diff --git a/rust-lib/flowy-dispatch/src/dispatch.rs b/rust-lib/flowy-dispatch/src/dispatch.rs index 435a4aca9b..308ba1f164 100644 --- a/rust-lib/flowy-dispatch/src/dispatch.rs +++ b/rust-lib/flowy-dispatch/src/dispatch.rs @@ -99,14 +99,14 @@ impl EventDispatch { } #[pin_project] -pub struct DispatchFuture { +pub struct DispatchFuture { #[pin] pub fut: Pin + Sync + Send>>, } impl Future for DispatchFuture where - T: Responder + Send + Sync, + T: Send + Sync, { type Output = T; diff --git a/rust-lib/flowy-infra/src/kv/kv.rs b/rust-lib/flowy-infra/src/kv/kv.rs index cadc0032b8..36bc30ecc1 100644 --- a/rust-lib/flowy-infra/src/kv/kv.rs +++ b/rust-lib/flowy-infra/src/kv/kv.rs @@ -18,22 +18,21 @@ pub struct KVStore { impl KVStore { fn new() -> Self { KVStore { database: None } } - pub fn set(item: KeyValue) -> Result<(), String> { - let conn = get_connection()?; + fn set(item: KeyValue) -> Result<(), String> { let _ = diesel::replace_into(kv_table::table) .values(&item) - .execute(&*conn) - .map_err(|e| format!("{:?}", e))?; + .execute(&*(get_connection()?)) + .map_err(|e| format!("KV set error: {:?}", e))?; Ok(()) } - pub fn get(key: &str) -> Result { + fn get(key: &str) -> Result { let conn = get_connection()?; let item = dsl::kv_table .filter(kv_table::key.eq(key)) .first::(&*conn) - .map_err(|e| format!("{:?}", e))?; + .map_err(|e| format!("KV get error: {:?}", e))?; Ok(item) } @@ -43,7 +42,7 @@ impl KVStore { let sql = dsl::kv_table.filter(kv_table::key.eq(key)); let _ = diesel::delete(sql) .execute(&*conn) - .map_err(|e| format!("{:?}", e))?; + .map_err(|e| format!("KV remove error: {:?}", e))?; Ok(()) } @@ -125,7 +124,7 @@ fn get_connection() -> Result { .as_ref() .expect("KVStore is not init") .get_connection() - .map_err(|e| format!("{:?}", e))?; + .map_err(|e| format!("KVStore error: {:?}", e))?; Ok(conn) }, Err(e) => { diff --git a/rust-lib/flowy-sdk/src/deps_resolve/mod.rs b/rust-lib/flowy-sdk/src/deps_resolve/mod.rs new file mode 100644 index 0000000000..a49be3ee06 --- /dev/null +++ b/rust-lib/flowy-sdk/src/deps_resolve/mod.rs @@ -0,0 +1,3 @@ +mod workspace_user_impl; + +pub use workspace_user_impl::*; diff --git a/rust-lib/flowy-sdk/src/deps_resolve/workspace_user_impl.rs b/rust-lib/flowy-sdk/src/deps_resolve/workspace_user_impl.rs new file mode 100644 index 0000000000..df069a33a5 --- /dev/null +++ b/rust-lib/flowy-sdk/src/deps_resolve/workspace_user_impl.rs @@ -0,0 +1,63 @@ +use flowy_database::DBConnection; +use flowy_dispatch::prelude::DispatchFuture; +use flowy_user::prelude::UserSession; +use flowy_workspace::{ + entities::workspace::UserWorkspace, + errors::{ErrorBuilder, WorkspaceError, WorkspaceErrorCode}, + module::WorkspaceUser, +}; +use std::sync::Arc; + +pub struct WorkspaceUserImpl { + pub(crate) user_session: Arc, +} + +impl WorkspaceUser for WorkspaceUserImpl { + fn set_cur_workspace_id( + &self, + workspace_id: &str, + ) -> DispatchFuture> { + let user_session = self.user_session.clone(); + let workspace_id = workspace_id.to_owned(); + DispatchFuture { + fut: Box::pin(async move { + let _ = user_session + .set_current_workspace(&workspace_id) + .await + .map_err(|e| { + ErrorBuilder::new(WorkspaceErrorCode::UserInternalError) + .error(e) + .build() + }); + + Ok(()) + }), + } + } + + fn get_cur_workspace(&self) -> DispatchFuture> { + let user_session = self.user_session.clone(); + DispatchFuture { + fut: Box::pin(async move { + let user_detail = user_session.user_detail().map_err(|e| { + ErrorBuilder::new(WorkspaceErrorCode::UserNotLoginYet) + .error(e) + .build() + })?; + + Ok(UserWorkspace { + owner: user_detail.email, + workspace_id: user_detail.workspace, + }) + }), + } + } + + fn db_connection(&self) -> Result { + self.user_session.get_db_connection().map_err(|e| { + ErrorBuilder::new(WorkspaceErrorCode::DatabaseConnectionFail) + .error(e) + .build() + }) + } +} diff --git a/rust-lib/flowy-sdk/src/lib.rs b/rust-lib/flowy-sdk/src/lib.rs index b0d93a4e97..0c73248108 100644 --- a/rust-lib/flowy-sdk/src/lib.rs +++ b/rust-lib/flowy-sdk/src/lib.rs @@ -1,7 +1,9 @@ +mod deps_resolve; mod flowy_server; pub mod module; pub use crate::flowy_server::{ArcFlowyServer, FlowyServerMocker}; +use deps_resolve::*; use flowy_dispatch::prelude::*; use module::build_modules; pub use module::*; @@ -31,7 +33,10 @@ impl FlowySDK { FlowySDK::init_log(root); tracing::info!("🔥 Root path: {}", root); - let _ = flowy_infra::kv::KVStore::init(root); + match flowy_infra::kv::KVStore::init(root) { + Ok(_) => {}, + Err(e) => tracing::error!("Init kv store failedL: {}", e), + } FlowySDK::init_modules(root, server); } diff --git a/rust-lib/flowy-sdk/src/module.rs b/rust-lib/flowy-sdk/src/module.rs index e0a809a4c1..7fceeefb2e 100644 --- a/rust-lib/flowy-sdk/src/module.rs +++ b/rust-lib/flowy-sdk/src/module.rs @@ -4,6 +4,8 @@ use flowy_dispatch::prelude::{DispatchFuture, Module}; use flowy_user::prelude::*; use flowy_workspace::prelude::*; +use crate::deps_resolve::WorkspaceUserImpl; +use flowy_workspace::entities::workspace::UserWorkspace; use std::sync::Arc; pub struct ModuleConfig { @@ -26,45 +28,3 @@ pub fn build_modules(config: ModuleConfig, _server: ArcFlowyServer) -> Vec, -} - -impl WorkspaceUser for WorkspaceUserImpl { - fn set_workspace(&self, workspace_id: &str) -> DispatchFuture> { - let user_session = self.user_session.clone(); - let workspace_id = workspace_id.to_owned(); - DispatchFuture { - fut: Box::pin(async move { - let _ = user_session - .set_current_workspace(&workspace_id) - .await - .map_err(|e| { - ErrorBuilder::new(WorkspaceErrorCode::UserInternalError) - .error(e) - .build() - }); - - Ok(()) - }), - } - } - - fn get_workspace(&self) -> Result { - let user_detail = self.user_session.user_detail().map_err(|e| { - ErrorBuilder::new(WorkspaceErrorCode::UserNotLoginYet) - .error(e) - .build() - })?; - Ok(user_detail.id) - } - - fn db_connection(&self) -> Result { - self.user_session.get_db_connection().map_err(|e| { - ErrorBuilder::new(WorkspaceErrorCode::DatabaseConnectionFail) - .error(e) - .build() - }) - } -} diff --git a/rust-lib/flowy-sqlite/src/conn_ext.rs b/rust-lib/flowy-sqlite/src/conn_ext.rs new file mode 100644 index 0000000000..2a39839178 --- /dev/null +++ b/rust-lib/flowy-sqlite/src/conn_ext.rs @@ -0,0 +1,30 @@ +use crate::errors::*; +use diesel::{ + dsl::sql, + expression::SqlLiteral, + query_dsl::LoadQuery, + Connection, + RunQueryDsl, + SqliteConnection, +}; + +pub trait ConnectionExtension: Connection { + fn query(&self, query: &str) -> Result + where + SqlLiteral: LoadQuery; + + fn exec(&self, query: impl AsRef) -> Result; +} + +impl ConnectionExtension for SqliteConnection { + fn query(&self, query: &str) -> Result + where + SqlLiteral: LoadQuery, + { + Ok(sql::(query).get_result(self)?) + } + + fn exec(&self, query: impl AsRef) -> Result { + Ok(SqliteConnection::execute(self, query.as_ref())?) + } +} diff --git a/rust-lib/flowy-sqlite/src/lib.rs b/rust-lib/flowy-sqlite/src/lib.rs index b631cf95b6..f6d5cbfd8d 100644 --- a/rust-lib/flowy-sqlite/src/lib.rs +++ b/rust-lib/flowy-sqlite/src/lib.rs @@ -1,7 +1,10 @@ +mod conn_ext; mod database; #[allow(deprecated, clippy::large_enum_variant)] mod errors; mod pool; +mod pragma; + pub use database::*; pub use pool::*; diff --git a/rust-lib/flowy-sqlite/src/pool.rs b/rust-lib/flowy-sqlite/src/pool.rs index ebc010eab1..f9f8646d58 100644 --- a/rust-lib/flowy-sqlite/src/pool.rs +++ b/rust-lib/flowy-sqlite/src/pool.rs @@ -1,6 +1,6 @@ -use crate::errors::*; +use crate::{conn_ext::*, errors::*, pragma::*}; use diesel::{connection::Connection, SqliteConnection}; -use r2d2::{ManageConnection, Pool}; +use r2d2::{CustomizeConnection, ManageConnection, Pool}; use scheduled_thread_pool::ScheduledThreadPool; use std::{ sync::{ @@ -34,10 +34,12 @@ impl ConnectionPool { let manager = ConnectionManager::new(uri); let thread_pool = DB_POOL.clone(); let config = Arc::new(config); + let customizer_config = DatabaseCustomizerConfig::default(); let pool = r2d2::Pool::builder() .thread_pool(thread_pool) .min_idle(Some(config.min_idle)) + .connection_customizer(Box::new(DatabaseCustomizer::new(customizer_config))) .max_size(config.max_size) .max_lifetime(None) .connection_timeout(config.connection_timeout) @@ -127,3 +129,48 @@ impl ManageConnection for ConnectionManager { impl ConnectionManager { pub fn new>(uri: S) -> Self { ConnectionManager { db_uri: uri.into() } } } + +#[derive(Debug)] +pub struct DatabaseCustomizerConfig { + pub(crate) journal_mode: SQLiteJournalMode, + pub(crate) synchronous: SQLiteSynchronous, + pub(crate) busy_timeout: i32, + pub(crate) secure_delete: bool, +} + +impl Default for DatabaseCustomizerConfig { + fn default() -> Self { + Self { + journal_mode: SQLiteJournalMode::WAL, + synchronous: SQLiteSynchronous::NORMAL, + busy_timeout: 5000, + secure_delete: true, + } + } +} + +#[derive(Debug)] +struct DatabaseCustomizer { + config: DatabaseCustomizerConfig, +} + +impl DatabaseCustomizer { + fn new(config: DatabaseCustomizerConfig) -> Self + where + Self: Sized, + { + Self { config } + } +} + +impl CustomizeConnection for DatabaseCustomizer { + fn on_acquire(&self, conn: &mut SqliteConnection) -> Result<()> { + conn.pragma_set_busy_timeout(self.config.busy_timeout)?; + if self.config.journal_mode != SQLiteJournalMode::WAL { + conn.pragma_set_journal_mode(self.config.journal_mode, None)?; + } + conn.pragma_set_synchronous(self.config.synchronous, None)?; + + Ok(()) + } +} diff --git a/rust-lib/flowy-sqlite/src/pragma.rs b/rust-lib/flowy-sqlite/src/pragma.rs new file mode 100644 index 0000000000..48c3df487c --- /dev/null +++ b/rust-lib/flowy-sqlite/src/pragma.rs @@ -0,0 +1,186 @@ +use crate::errors::{Error, Result}; +use diesel::{ + expression::SqlLiteral, + query_dsl::load_dsl::LoadQuery, + sql_types::{Integer, Text}, + SqliteConnection, +}; + +use crate::conn_ext::ConnectionExtension; +use std::{ + convert::{TryFrom, TryInto}, + fmt, + str::FromStr, +}; + +pub trait PragmaExtension: ConnectionExtension { + fn pragma(&self, key: &str, val: D, schema: Option<&str>) -> Result<()> { + let query = match schema { + Some(schema) => format!("PRAGMA {}.{} = '{}'", schema, key, val), + None => format!("PRAGMA {} = '{}'", key, val), + }; + log::trace!("SQLITE {}", query); + self.exec(&query)?; + Ok(()) + } + + fn pragma_ret( + &self, + key: &str, + val: D, + schema: Option<&str>, + ) -> Result + where + SqlLiteral: LoadQuery, + { + let query = match schema { + Some(schema) => format!("PRAGMA {}.{} = '{}'", schema, key, val), + None => format!("PRAGMA {} = '{}'", key, val), + }; + log::trace!("SQLITE {}", query); + Ok(self.query::(&query)?) + } + + fn pragma_get(&self, key: &str, schema: Option<&str>) -> Result + where + SqlLiteral: LoadQuery, + { + let query = match schema { + Some(schema) => format!("PRAGMA {}.{}", schema, key), + None => format!("PRAGMA {}", key), + }; + log::trace!("SQLITE {}", query); + Ok(self.query::(&query)?) + } + + fn pragma_set_busy_timeout(&self, timeout_ms: i32) -> Result { + self.pragma_ret::("busy_timeout", timeout_ms, None) + } + + fn pragma_get_busy_timeout(&self) -> Result { + self.pragma_get::("busy_timeout", None) + } + + fn pragma_set_journal_mode( + &self, + mode: SQLiteJournalMode, + schema: Option<&str>, + ) -> Result { + self.pragma_ret::("journal_mode", mode, schema) + } + + fn pragma_get_journal_mode(&self, schema: Option<&str>) -> Result { + Ok(self + .pragma_get::("journal_mode", schema)? + .parse()?) + } + + fn pragma_set_synchronous( + &self, + synchronous: SQLiteSynchronous, + schema: Option<&str>, + ) -> Result<()> { + self.pragma("synchronous", synchronous as u8, schema) + } + + fn pragma_get_synchronous(&self, schema: Option<&str>) -> Result { + Ok(self + .pragma_get::("synchronous", schema)? + .try_into()?) + } +} +impl PragmaExtension for SqliteConnection {} + +#[derive(Debug, PartialEq, Eq, Clone, Copy)] +pub enum SQLiteJournalMode { + DELETE, + TRUNCATE, + PERSIST, + MEMORY, + WAL, + OFF, +} + +impl fmt::Display for SQLiteJournalMode { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "{}", + match self { + Self::DELETE => "DELETE", + Self::TRUNCATE => "TRUNCATE", + Self::PERSIST => "PERSIST", + Self::MEMORY => "MEMORY", + Self::WAL => "WAL", + Self::OFF => "OFF", + } + ) + } +} + +impl FromStr for SQLiteJournalMode { + type Err = Error; + + fn from_str(s: &str) -> Result { + match s.to_uppercase().as_ref() { + "DELETE" => Ok(Self::DELETE), + "TRUNCATE" => Ok(Self::TRUNCATE), + "PERSIST" => Ok(Self::PERSIST), + "MEMORY" => Ok(Self::MEMORY), + "WAL" => Ok(Self::WAL), + "OFF" => Ok(Self::OFF), + _ => Err(format!("Unknown value {} for JournalMode", s).into()), + } + } +} + +#[derive(Debug, PartialEq, Eq, Clone, Copy)] +pub enum SQLiteSynchronous { + EXTRA = 3, + FULL = 2, + NORMAL = 1, + OFF = 0, +} + +impl fmt::Display for SQLiteSynchronous { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "{}", + match self { + Self::OFF => "OFF", + Self::NORMAL => "NORMAL", + Self::FULL => "FULL", + Self::EXTRA => "EXTRA", + } + ) + } +} + +impl TryFrom for SQLiteSynchronous { + type Error = Error; + + fn try_from(v: i32) -> Result { + match v { + 0 => Ok(Self::OFF), + 1 => Ok(Self::NORMAL), + 2 => Ok(Self::FULL), + 3 => Ok(Self::EXTRA), + _ => Err(format!("Unknown value {} for Synchronous", v).into()), + } + } +} + +impl FromStr for SQLiteSynchronous { + type Err = Error; + + fn from_str(s: &str) -> Result { + match s.to_uppercase().as_ref() { + "0" | "OFF" => Ok(Self::OFF), + "1" | "NORMAL" => Ok(Self::NORMAL), + "2" | "FULL" => Ok(Self::FULL), + "3" | "EXTRA" => Ok(Self::EXTRA), + _ => Err(format!("Unknown value {} for Synchronous", s).into()), + } + } +} diff --git a/rust-lib/flowy-test/src/builder.rs b/rust-lib/flowy-test/src/builder.rs index 1e47ce16f5..8c89780c07 100644 --- a/rust-lib/flowy-test/src/builder.rs +++ b/rust-lib/flowy-test/src/builder.rs @@ -20,18 +20,23 @@ impl WorkspaceTestBuilder { tester: Box::new(FixedUserTester::::new()), user_detail: None, }; - builder.login() + + builder.login_if_need() } } pub type UserTestBuilder = TestBuilder>; impl UserTestBuilder { pub fn new() -> Self { - Self { + let builder = Self { tester: Box::new(RandomUserTester::::new()), user_detail: None, - } + }; + + builder } + + pub fn reset(mut self) -> Self { self.logout().login() } } pub struct TestBuilder { @@ -49,6 +54,12 @@ where self } + pub fn login_if_need(mut self) -> Self { + let user_detail = self.tester.login_if_need(); + self.user_detail = Some(user_detail); + self + } + pub fn logout(self) -> Self { self.tester.logout(); self diff --git a/rust-lib/flowy-test/src/tester.rs b/rust-lib/flowy-test/src/tester.rs index 2d450f0209..5330ffc92e 100644 --- a/rust-lib/flowy-test/src/tester.rs +++ b/rust-lib/flowy-test/src/tester.rs @@ -6,7 +6,7 @@ use flowy_dispatch::prelude::*; pub use flowy_sdk::*; use flowy_user::{ errors::UserError, - event::UserEvent::{SignIn, SignOut}, + event::UserEvent::{GetStatus, SignIn, SignOut}, prelude::*, }; use std::{ @@ -99,7 +99,6 @@ pub trait TesterTrait { fn login(&self) -> UserDetail { init_test_sdk(self.context().server.clone()); - self.logout(); let payload = SignInRequest { email: self.context().user_email.clone(), password: valid_password(), @@ -116,6 +115,17 @@ pub trait TesterTrait { user_detail } + fn login_if_need(&self) -> UserDetail { + init_test_sdk(self.context().server.clone()); + match EventDispatch::sync_send(ModuleRequest::new(GetStatus)) + .parse::() + .unwrap() + { + Ok(user_detail) => user_detail, + Err(e) => self.login(), + } + } + fn logout(&self) { init_test_sdk(self.context().server.clone()); let _ = EventDispatch::sync_send(ModuleRequest::new(SignOut)); diff --git a/rust-lib/flowy-user/src/errors.rs b/rust-lib/flowy-user/src/errors.rs index b2ff67213b..b466090fc9 100644 --- a/rust-lib/flowy-user/src/errors.rs +++ b/rust-lib/flowy-user/src/errors.rs @@ -26,15 +26,15 @@ pub enum UserErrorCode { #[display(fmt = "Unknown")] Unknown = 0, #[display(fmt = "Database init failed")] - DatabaseInitFailed = 1, + UserDatabaseInitFailed = 1, #[display(fmt = "Get database write lock failed")] - DatabaseWriteLocked = 2, + UserDatabaseWriteLocked = 2, #[display(fmt = "Get database read lock failed")] - DatabaseReadLocked = 3, + UserDatabaseReadLocked = 3, #[display(fmt = "Opening database is not belonging to the current user")] - DatabaseUserDidNotMatch = 4, + UserDatabaseDidNotMatch = 4, #[display(fmt = "Database internal error")] - DatabaseInternalError = 5, + UserDatabaseInternalError = 5, #[display(fmt = "User not login yet")] UserNotLoginYet = 10, @@ -61,7 +61,7 @@ impl std::default::Default for UserErrorCode { impl std::convert::From for UserError { fn from(error: flowy_database::result::Error) -> Self { - ErrorBuilder::new(UserErrorCode::DatabaseInternalError) + ErrorBuilder::new(UserErrorCode::UserDatabaseInternalError) .error(error) .build() } @@ -69,7 +69,7 @@ impl std::convert::From for UserError { impl std::convert::From for UserError { fn from(error: flowy_sqlite::Error) -> Self { - ErrorBuilder::new(UserErrorCode::DatabaseInternalError) + ErrorBuilder::new(UserErrorCode::UserDatabaseInternalError) .error(error) .build() } diff --git a/rust-lib/flowy-user/src/protobuf/model/errors.rs b/rust-lib/flowy-user/src/protobuf/model/errors.rs index 56637c911d..ef1ed3e7b4 100644 --- a/rust-lib/flowy-user/src/protobuf/model/errors.rs +++ b/rust-lib/flowy-user/src/protobuf/model/errors.rs @@ -216,11 +216,11 @@ impl ::protobuf::reflect::ProtobufValue for UserError { #[derive(Clone,PartialEq,Eq,Debug,Hash)] pub enum UserErrorCode { Unknown = 0, - DatabaseInitFailed = 1, - DatabaseWriteLocked = 2, - DatabaseReadLocked = 3, - DatabaseUserDidNotMatch = 4, - DatabaseInternalError = 5, + UserDatabaseInitFailed = 1, + UserDatabaseWriteLocked = 2, + UserDatabaseReadLocked = 3, + UserDatabaseDidNotMatch = 4, + UserDatabaseInternalError = 5, UserNotLoginYet = 10, ReadCurrentIdFailed = 11, WriteCurrentIdFailed = 12, @@ -239,11 +239,11 @@ impl ::protobuf::ProtobufEnum for UserErrorCode { fn from_i32(value: i32) -> ::std::option::Option { match value { 0 => ::std::option::Option::Some(UserErrorCode::Unknown), - 1 => ::std::option::Option::Some(UserErrorCode::DatabaseInitFailed), - 2 => ::std::option::Option::Some(UserErrorCode::DatabaseWriteLocked), - 3 => ::std::option::Option::Some(UserErrorCode::DatabaseReadLocked), - 4 => ::std::option::Option::Some(UserErrorCode::DatabaseUserDidNotMatch), - 5 => ::std::option::Option::Some(UserErrorCode::DatabaseInternalError), + 1 => ::std::option::Option::Some(UserErrorCode::UserDatabaseInitFailed), + 2 => ::std::option::Option::Some(UserErrorCode::UserDatabaseWriteLocked), + 3 => ::std::option::Option::Some(UserErrorCode::UserDatabaseReadLocked), + 4 => ::std::option::Option::Some(UserErrorCode::UserDatabaseDidNotMatch), + 5 => ::std::option::Option::Some(UserErrorCode::UserDatabaseInternalError), 10 => ::std::option::Option::Some(UserErrorCode::UserNotLoginYet), 11 => ::std::option::Option::Some(UserErrorCode::ReadCurrentIdFailed), 12 => ::std::option::Option::Some(UserErrorCode::WriteCurrentIdFailed), @@ -259,11 +259,11 @@ impl ::protobuf::ProtobufEnum for UserErrorCode { fn values() -> &'static [Self] { static values: &'static [UserErrorCode] = &[ UserErrorCode::Unknown, - UserErrorCode::DatabaseInitFailed, - UserErrorCode::DatabaseWriteLocked, - UserErrorCode::DatabaseReadLocked, - UserErrorCode::DatabaseUserDidNotMatch, - UserErrorCode::DatabaseInternalError, + UserErrorCode::UserDatabaseInitFailed, + UserErrorCode::UserDatabaseWriteLocked, + UserErrorCode::UserDatabaseReadLocked, + UserErrorCode::UserDatabaseDidNotMatch, + UserErrorCode::UserDatabaseInternalError, UserErrorCode::UserNotLoginYet, UserErrorCode::ReadCurrentIdFailed, UserErrorCode::WriteCurrentIdFailed, @@ -302,51 +302,51 @@ impl ::protobuf::reflect::ProtobufValue for UserErrorCode { static file_descriptor_proto_data: &'static [u8] = b"\ \n\x0cerrors.proto\"A\n\tUserError\x12\"\n\x04code\x18\x01\x20\x01(\x0e2\ \x0e.UserErrorCodeR\x04code\x12\x10\n\x03msg\x18\x02\x20\x01(\tR\x03msg*\ - \xce\x02\n\rUserErrorCode\x12\x0b\n\x07Unknown\x10\0\x12\x16\n\x12Databa\ - seInitFailed\x10\x01\x12\x17\n\x13DatabaseWriteLocked\x10\x02\x12\x16\n\ - \x12DatabaseReadLocked\x10\x03\x12\x1b\n\x17DatabaseUserDidNotMatch\x10\ - \x04\x12\x19\n\x15DatabaseInternalError\x10\x05\x12\x13\n\x0fUserNotLogi\ - nYet\x10\n\x12\x17\n\x13ReadCurrentIdFailed\x10\x0b\x12\x18\n\x14WriteCu\ - rrentIdFailed\x10\x0c\x12\x10\n\x0cEmailInvalid\x10\x14\x12\x13\n\x0fPas\ - swordInvalid\x10\x15\x12\x13\n\x0fUserNameInvalid\x10\x16\x12\x18\n\x14U\ - serWorkspaceInvalid\x10\x17\x12\x11\n\rUserIdInvalid\x10\x18J\xee\x05\n\ - \x06\x12\x04\0\0\x15\x01\n\x08\n\x01\x0c\x12\x03\0\0\x12\n\n\n\x02\x04\0\ - \x12\x04\x02\0\x05\x01\n\n\n\x03\x04\0\x01\x12\x03\x02\x08\x11\n\x0b\n\ - \x04\x04\0\x02\0\x12\x03\x03\x04\x1b\n\x0c\n\x05\x04\0\x02\0\x06\x12\x03\ - \x03\x04\x11\n\x0c\n\x05\x04\0\x02\0\x01\x12\x03\x03\x12\x16\n\x0c\n\x05\ - \x04\0\x02\0\x03\x12\x03\x03\x19\x1a\n\x0b\n\x04\x04\0\x02\x01\x12\x03\ - \x04\x04\x13\n\x0c\n\x05\x04\0\x02\x01\x05\x12\x03\x04\x04\n\n\x0c\n\x05\ - \x04\0\x02\x01\x01\x12\x03\x04\x0b\x0e\n\x0c\n\x05\x04\0\x02\x01\x03\x12\ - \x03\x04\x11\x12\n\n\n\x02\x05\0\x12\x04\x06\0\x15\x01\n\n\n\x03\x05\0\ - \x01\x12\x03\x06\x05\x12\n\x0b\n\x04\x05\0\x02\0\x12\x03\x07\x04\x10\n\ - \x0c\n\x05\x05\0\x02\0\x01\x12\x03\x07\x04\x0b\n\x0c\n\x05\x05\0\x02\0\ - \x02\x12\x03\x07\x0e\x0f\n\x0b\n\x04\x05\0\x02\x01\x12\x03\x08\x04\x1b\n\ - \x0c\n\x05\x05\0\x02\x01\x01\x12\x03\x08\x04\x16\n\x0c\n\x05\x05\0\x02\ - \x01\x02\x12\x03\x08\x19\x1a\n\x0b\n\x04\x05\0\x02\x02\x12\x03\t\x04\x1c\ - \n\x0c\n\x05\x05\0\x02\x02\x01\x12\x03\t\x04\x17\n\x0c\n\x05\x05\0\x02\ - \x02\x02\x12\x03\t\x1a\x1b\n\x0b\n\x04\x05\0\x02\x03\x12\x03\n\x04\x1b\n\ - \x0c\n\x05\x05\0\x02\x03\x01\x12\x03\n\x04\x16\n\x0c\n\x05\x05\0\x02\x03\ - \x02\x12\x03\n\x19\x1a\n\x0b\n\x04\x05\0\x02\x04\x12\x03\x0b\x04\x20\n\ - \x0c\n\x05\x05\0\x02\x04\x01\x12\x03\x0b\x04\x1b\n\x0c\n\x05\x05\0\x02\ - \x04\x02\x12\x03\x0b\x1e\x1f\n\x0b\n\x04\x05\0\x02\x05\x12\x03\x0c\x04\ - \x1e\n\x0c\n\x05\x05\0\x02\x05\x01\x12\x03\x0c\x04\x19\n\x0c\n\x05\x05\0\ - \x02\x05\x02\x12\x03\x0c\x1c\x1d\n\x0b\n\x04\x05\0\x02\x06\x12\x03\r\x04\ - \x19\n\x0c\n\x05\x05\0\x02\x06\x01\x12\x03\r\x04\x13\n\x0c\n\x05\x05\0\ - \x02\x06\x02\x12\x03\r\x16\x18\n\x0b\n\x04\x05\0\x02\x07\x12\x03\x0e\x04\ - \x1d\n\x0c\n\x05\x05\0\x02\x07\x01\x12\x03\x0e\x04\x17\n\x0c\n\x05\x05\0\ - \x02\x07\x02\x12\x03\x0e\x1a\x1c\n\x0b\n\x04\x05\0\x02\x08\x12\x03\x0f\ - \x04\x1e\n\x0c\n\x05\x05\0\x02\x08\x01\x12\x03\x0f\x04\x18\n\x0c\n\x05\ - \x05\0\x02\x08\x02\x12\x03\x0f\x1b\x1d\n\x0b\n\x04\x05\0\x02\t\x12\x03\ - \x10\x04\x16\n\x0c\n\x05\x05\0\x02\t\x01\x12\x03\x10\x04\x10\n\x0c\n\x05\ - \x05\0\x02\t\x02\x12\x03\x10\x13\x15\n\x0b\n\x04\x05\0\x02\n\x12\x03\x11\ - \x04\x19\n\x0c\n\x05\x05\0\x02\n\x01\x12\x03\x11\x04\x13\n\x0c\n\x05\x05\ - \0\x02\n\x02\x12\x03\x11\x16\x18\n\x0b\n\x04\x05\0\x02\x0b\x12\x03\x12\ - \x04\x19\n\x0c\n\x05\x05\0\x02\x0b\x01\x12\x03\x12\x04\x13\n\x0c\n\x05\ - \x05\0\x02\x0b\x02\x12\x03\x12\x16\x18\n\x0b\n\x04\x05\0\x02\x0c\x12\x03\ - \x13\x04\x1e\n\x0c\n\x05\x05\0\x02\x0c\x01\x12\x03\x13\x04\x18\n\x0c\n\ - \x05\x05\0\x02\x0c\x02\x12\x03\x13\x1b\x1d\n\x0b\n\x04\x05\0\x02\r\x12\ - \x03\x14\x04\x17\n\x0c\n\x05\x05\0\x02\r\x01\x12\x03\x14\x04\x11\n\x0c\n\ - \x05\x05\0\x02\r\x02\x12\x03\x14\x14\x16b\x06proto3\ + \xde\x02\n\rUserErrorCode\x12\x0b\n\x07Unknown\x10\0\x12\x1a\n\x16UserDa\ + tabaseInitFailed\x10\x01\x12\x1b\n\x17UserDatabaseWriteLocked\x10\x02\ + \x12\x1a\n\x16UserDatabaseReadLocked\x10\x03\x12\x1b\n\x17UserDatabaseDi\ + dNotMatch\x10\x04\x12\x1d\n\x19UserDatabaseInternalError\x10\x05\x12\x13\ + \n\x0fUserNotLoginYet\x10\n\x12\x17\n\x13ReadCurrentIdFailed\x10\x0b\x12\ + \x18\n\x14WriteCurrentIdFailed\x10\x0c\x12\x10\n\x0cEmailInvalid\x10\x14\ + \x12\x13\n\x0fPasswordInvalid\x10\x15\x12\x13\n\x0fUserNameInvalid\x10\ + \x16\x12\x18\n\x14UserWorkspaceInvalid\x10\x17\x12\x11\n\rUserIdInvalid\ + \x10\x18J\xee\x05\n\x06\x12\x04\0\0\x15\x01\n\x08\n\x01\x0c\x12\x03\0\0\ + \x12\n\n\n\x02\x04\0\x12\x04\x02\0\x05\x01\n\n\n\x03\x04\0\x01\x12\x03\ + \x02\x08\x11\n\x0b\n\x04\x04\0\x02\0\x12\x03\x03\x04\x1b\n\x0c\n\x05\x04\ + \0\x02\0\x06\x12\x03\x03\x04\x11\n\x0c\n\x05\x04\0\x02\0\x01\x12\x03\x03\ + \x12\x16\n\x0c\n\x05\x04\0\x02\0\x03\x12\x03\x03\x19\x1a\n\x0b\n\x04\x04\ + \0\x02\x01\x12\x03\x04\x04\x13\n\x0c\n\x05\x04\0\x02\x01\x05\x12\x03\x04\ + \x04\n\n\x0c\n\x05\x04\0\x02\x01\x01\x12\x03\x04\x0b\x0e\n\x0c\n\x05\x04\ + \0\x02\x01\x03\x12\x03\x04\x11\x12\n\n\n\x02\x05\0\x12\x04\x06\0\x15\x01\ + \n\n\n\x03\x05\0\x01\x12\x03\x06\x05\x12\n\x0b\n\x04\x05\0\x02\0\x12\x03\ + \x07\x04\x10\n\x0c\n\x05\x05\0\x02\0\x01\x12\x03\x07\x04\x0b\n\x0c\n\x05\ + \x05\0\x02\0\x02\x12\x03\x07\x0e\x0f\n\x0b\n\x04\x05\0\x02\x01\x12\x03\ + \x08\x04\x1f\n\x0c\n\x05\x05\0\x02\x01\x01\x12\x03\x08\x04\x1a\n\x0c\n\ + \x05\x05\0\x02\x01\x02\x12\x03\x08\x1d\x1e\n\x0b\n\x04\x05\0\x02\x02\x12\ + \x03\t\x04\x20\n\x0c\n\x05\x05\0\x02\x02\x01\x12\x03\t\x04\x1b\n\x0c\n\ + \x05\x05\0\x02\x02\x02\x12\x03\t\x1e\x1f\n\x0b\n\x04\x05\0\x02\x03\x12\ + \x03\n\x04\x1f\n\x0c\n\x05\x05\0\x02\x03\x01\x12\x03\n\x04\x1a\n\x0c\n\ + \x05\x05\0\x02\x03\x02\x12\x03\n\x1d\x1e\n\x0b\n\x04\x05\0\x02\x04\x12\ + \x03\x0b\x04\x20\n\x0c\n\x05\x05\0\x02\x04\x01\x12\x03\x0b\x04\x1b\n\x0c\ + \n\x05\x05\0\x02\x04\x02\x12\x03\x0b\x1e\x1f\n\x0b\n\x04\x05\0\x02\x05\ + \x12\x03\x0c\x04\"\n\x0c\n\x05\x05\0\x02\x05\x01\x12\x03\x0c\x04\x1d\n\ + \x0c\n\x05\x05\0\x02\x05\x02\x12\x03\x0c\x20!\n\x0b\n\x04\x05\0\x02\x06\ + \x12\x03\r\x04\x19\n\x0c\n\x05\x05\0\x02\x06\x01\x12\x03\r\x04\x13\n\x0c\ + \n\x05\x05\0\x02\x06\x02\x12\x03\r\x16\x18\n\x0b\n\x04\x05\0\x02\x07\x12\ + \x03\x0e\x04\x1d\n\x0c\n\x05\x05\0\x02\x07\x01\x12\x03\x0e\x04\x17\n\x0c\ + \n\x05\x05\0\x02\x07\x02\x12\x03\x0e\x1a\x1c\n\x0b\n\x04\x05\0\x02\x08\ + \x12\x03\x0f\x04\x1e\n\x0c\n\x05\x05\0\x02\x08\x01\x12\x03\x0f\x04\x18\n\ + \x0c\n\x05\x05\0\x02\x08\x02\x12\x03\x0f\x1b\x1d\n\x0b\n\x04\x05\0\x02\t\ + \x12\x03\x10\x04\x16\n\x0c\n\x05\x05\0\x02\t\x01\x12\x03\x10\x04\x10\n\ + \x0c\n\x05\x05\0\x02\t\x02\x12\x03\x10\x13\x15\n\x0b\n\x04\x05\0\x02\n\ + \x12\x03\x11\x04\x19\n\x0c\n\x05\x05\0\x02\n\x01\x12\x03\x11\x04\x13\n\ + \x0c\n\x05\x05\0\x02\n\x02\x12\x03\x11\x16\x18\n\x0b\n\x04\x05\0\x02\x0b\ + \x12\x03\x12\x04\x19\n\x0c\n\x05\x05\0\x02\x0b\x01\x12\x03\x12\x04\x13\n\ + \x0c\n\x05\x05\0\x02\x0b\x02\x12\x03\x12\x16\x18\n\x0b\n\x04\x05\0\x02\ + \x0c\x12\x03\x13\x04\x1e\n\x0c\n\x05\x05\0\x02\x0c\x01\x12\x03\x13\x04\ + \x18\n\x0c\n\x05\x05\0\x02\x0c\x02\x12\x03\x13\x1b\x1d\n\x0b\n\x04\x05\0\ + \x02\r\x12\x03\x14\x04\x17\n\x0c\n\x05\x05\0\x02\r\x01\x12\x03\x14\x04\ + \x11\n\x0c\n\x05\x05\0\x02\r\x02\x12\x03\x14\x14\x16b\x06proto3\ "; static file_descriptor_proto_lazy: ::protobuf::rt::LazyV2<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::rt::LazyV2::INIT; diff --git a/rust-lib/flowy-user/src/protobuf/proto/errors.proto b/rust-lib/flowy-user/src/protobuf/proto/errors.proto index 0d880f5fa1..9a53106237 100644 --- a/rust-lib/flowy-user/src/protobuf/proto/errors.proto +++ b/rust-lib/flowy-user/src/protobuf/proto/errors.proto @@ -6,11 +6,11 @@ message UserError { } enum UserErrorCode { Unknown = 0; - DatabaseInitFailed = 1; - DatabaseWriteLocked = 2; - DatabaseReadLocked = 3; - DatabaseUserDidNotMatch = 4; - DatabaseInternalError = 5; + UserDatabaseInitFailed = 1; + UserDatabaseWriteLocked = 2; + UserDatabaseReadLocked = 3; + UserDatabaseDidNotMatch = 4; + UserDatabaseInternalError = 5; UserNotLoginYet = 10; ReadCurrentIdFailed = 11; WriteCurrentIdFailed = 12; diff --git a/rust-lib/flowy-user/src/services/user_session/database.rs b/rust-lib/flowy-user/src/services/user_session/database.rs index 6365868c31..f286957b99 100644 --- a/rust-lib/flowy-user/src/services/user_session/database.rs +++ b/rust-lib/flowy-user/src/services/user_session/database.rs @@ -22,20 +22,21 @@ impl UserDB { fn open_user_db(&self, user_id: &str) -> Result<(), UserError> { if user_id.is_empty() { - return Err(ErrorBuilder::new(UserErrorCode::DatabaseInitFailed) + return Err(ErrorBuilder::new(UserErrorCode::UserDatabaseInitFailed) .msg("user id is empty") .build()); } let dir = format!("{}/{}", self.db_dir, user_id); let db = flowy_database::init(&dir).map_err(|e| { - ErrorBuilder::new(UserErrorCode::DatabaseInitFailed) + log::error!("flowy_database::init failed, {:?}", e); + ErrorBuilder::new(UserErrorCode::UserDatabaseInitFailed) .error(e) .build() })?; let mut db_map = DB_MAP.write().map_err(|e| { - ErrorBuilder::new(UserErrorCode::DatabaseWriteLocked) + ErrorBuilder::new(UserErrorCode::UserDatabaseWriteLocked) .error(e) .build() })?; @@ -46,7 +47,7 @@ impl UserDB { pub(crate) fn close_user_db(&self, user_id: &str) -> Result<(), UserError> { let mut db_map = DB_MAP.write().map_err(|e| { - ErrorBuilder::new(UserErrorCode::DatabaseWriteLocked) + ErrorBuilder::new(UserErrorCode::UserDatabaseWriteLocked) .msg(format!("Close user db failed. {:?}", e)) .build() })?; @@ -62,13 +63,13 @@ impl UserDB { } let db_map = DB_MAP.read().map_err(|e| { - ErrorBuilder::new(UserErrorCode::DatabaseReadLocked) + ErrorBuilder::new(UserErrorCode::UserDatabaseReadLocked) .error(e) .build() })?; match db_map.get(user_id) { - None => Err(ErrorBuilder::new(UserErrorCode::DatabaseInitFailed) + None => Err(ErrorBuilder::new(UserErrorCode::UserDatabaseInitFailed) .msg("Get connection failed. The database is not initialization") .build()), Some(database) => Ok(database.get_connection()?), diff --git a/rust-lib/flowy-user/src/services/user_session/user_session.rs b/rust-lib/flowy-user/src/services/user_session/user_session.rs index 475a955bb0..64aa629fb0 100644 --- a/rust-lib/flowy-user/src/services/user_session/user_session.rs +++ b/rust-lib/flowy-user/src/services/user_session/user_session.rs @@ -104,11 +104,9 @@ impl UserSession { pub fn user_detail(&self) -> Result { let user_id = self.get_user_id()?; - let conn = self.get_db_connection()?; - let user = dsl::user_table .filter(user_table::id.eq(&user_id)) - .first::(&*conn)?; + .first::(&*(self.get_db_connection()?))?; match self.server.get_user_info(&user_id) { Ok(_user_detail) => { @@ -137,14 +135,15 @@ impl UserSession { } pub fn get_user_id(&self) -> Result { - let read_guard = self.user_id.read().map_err(|e| { - ErrorBuilder::new(UserErrorCode::ReadCurrentIdFailed) - .error(e) - .build() - })?; + let mut user_id = { + let read_guard = self.user_id.read().map_err(|e| { + ErrorBuilder::new(UserErrorCode::ReadCurrentIdFailed) + .error(e) + .build() + })?; - let mut user_id = (*read_guard).clone(); - drop(read_guard); + (*read_guard).clone() + }; if user_id.is_none() { user_id = KVStore::get_str(USER_ID_CACHE_KEY); @@ -165,11 +164,10 @@ impl UserSession { .unwrap(); let request = ModuleRequest::new(UpdateUser).payload(payload); - let _user_detail = EventDispatch::async_send(request) + let _ = EventDispatch::async_send(request) .await .parse::() - .unwrap() - .unwrap(); + .unwrap()?; Ok(()) } } diff --git a/rust-lib/flowy-user/tests/event/sign_in_test.rs b/rust-lib/flowy-user/tests/event/sign_in_test.rs index d29ff80df4..a3a28a33f7 100644 --- a/rust-lib/flowy-user/tests/event/sign_in_test.rs +++ b/rust-lib/flowy-user/tests/event/sign_in_test.rs @@ -60,233 +60,3 @@ fn sign_in_with_invalid_password() { ); } } - -#[test] -#[serial] -fn sign_up_success() { - let _ = UserTestBuilder::new().event(SignOut).sync_send(); - let request = SignUpRequest { - email: random_valid_email(), - name: valid_name(), - password: valid_password(), - }; - - let _response = UserTestBuilder::new() - .logout() - .event(SignUp) - .request(request) - .sync_send(); -} - -#[test] -#[serial] -fn sign_up_with_invalid_email() { - for email in invalid_email_test_case() { - let request = SignUpRequest { - email: email.to_string(), - name: valid_name(), - password: valid_password(), - }; - - assert_eq!( - UserTestBuilder::new() - .event(SignUp) - .request(request) - .sync_send() - .error() - .code, - UserErrorCode::EmailInvalid - ); - } -} -#[test] -#[serial] -fn sign_up_with_invalid_password() { - for password in invalid_password_test_case() { - let request = SignUpRequest { - email: random_valid_email(), - name: valid_name(), - password, - }; - - assert_eq!( - UserTestBuilder::new() - .event(SignUp) - .request(request) - .sync_send() - .error() - .code, - UserErrorCode::PasswordInvalid - ); - } -} - -#[test] -#[should_panic] -#[serial] -fn user_status_get_failed_before_login() { - let _ = UserTestBuilder::new() - .logout() - .event(GetStatus) - .sync_send() - .parse::(); -} - -#[test] -#[serial] -fn user_status_get_success_after_login() { - let request = SignInRequest { - email: random_valid_email(), - password: valid_password(), - }; - - let response = UserTestBuilder::new() - .logout() - .event(SignIn) - .request(request) - .sync_send() - .parse::(); - dbg!(&response); - - let _ = UserTestBuilder::new() - .event(GetStatus) - .sync_send() - .parse::(); -} - -#[test] -#[serial] -fn user_update_with_name() { - let user_detail = UserTestBuilder::new().login().user_detail.unwrap(); - let new_name = "hello_world".to_owned(); - let request = UpdateUserRequest { - id: user_detail.id.clone(), - name: Some(new_name.clone()), - email: None, - workspace: None, - password: None, - }; - - let user_detail = UserTestBuilder::new() - .event(UpdateUser) - .request(request) - .sync_send() - .parse::(); - - assert_eq!(user_detail.name, new_name,); -} - -#[test] -#[serial] -fn user_update_with_email() { - let user_detail = UserTestBuilder::new().login().user_detail.unwrap(); - let new_email = "123@gmai.com".to_owned(); - let request = UpdateUserRequest { - id: user_detail.id.clone(), - name: None, - email: Some(new_email.clone()), - workspace: None, - password: None, - }; - - let user_detail = UserTestBuilder::new() - .event(UpdateUser) - .request(request) - .sync_send() - .parse::(); - - assert_eq!(user_detail.email, new_email,); -} - -#[test] -#[serial] -fn user_update_with_password() { - let user_detail = UserTestBuilder::new().login().user_detail.unwrap(); - let new_password = "H123world!".to_owned(); - let request = UpdateUserRequest { - id: user_detail.id.clone(), - name: None, - email: None, - workspace: None, - password: Some(new_password.clone()), - }; - - let _ = UserTestBuilder::new() - .event(UpdateUser) - .request(request) - .sync_send() - .assert_success(); -} - -#[test] -#[serial] -fn user_update_with_invalid_email() { - let user_detail = UserTestBuilder::new().login().user_detail.unwrap(); - for email in invalid_email_test_case() { - let request = UpdateUserRequest { - id: user_detail.id.clone(), - name: None, - email: Some(email), - workspace: None, - password: None, - }; - - assert_eq!( - UserTestBuilder::new() - .event(UpdateUser) - .request(request) - .sync_send() - .error() - .code, - UserErrorCode::EmailInvalid - ); - } -} - -#[test] -#[serial] -fn user_update_with_invalid_password() { - let user_detail = UserTestBuilder::new().login().user_detail.unwrap(); - for password in invalid_password_test_case() { - let request = UpdateUserRequest { - id: user_detail.id.clone(), - name: None, - email: None, - workspace: None, - password: Some(password), - }; - - assert_eq!( - UserTestBuilder::new() - .event(UpdateUser) - .request(request) - .sync_send() - .error() - .code, - UserErrorCode::PasswordInvalid - ); - } -} - -#[test] -#[serial] -fn user_update_with_invalid_name() { - let user_detail = UserTestBuilder::new().login().user_detail.unwrap(); - let request = UpdateUserRequest { - id: user_detail.id.clone(), - name: Some("".to_string()), - email: None, - workspace: None, - password: None, - }; - - assert_eq!( - UserTestBuilder::new() - .event(UpdateUser) - .request(request) - .sync_send() - .error() - .code, - UserErrorCode::UserNameInvalid - ); -} diff --git a/rust-lib/flowy-user/tests/event/sign_up_test.rs b/rust-lib/flowy-user/tests/event/sign_up_test.rs index e023d80bf7..2122828e4d 100644 --- a/rust-lib/flowy-user/tests/event/sign_up_test.rs +++ b/rust-lib/flowy-user/tests/event/sign_up_test.rs @@ -1,65 +1,65 @@ -// use crate::helper::*; -// use flowy_user::{errors::*, event::UserEvent::*, prelude::*}; -// use serial_test::*; -// -// #[test] -// #[serial] -// fn sign_up_success() { -// let _ = UserTestBuilder::new().event(SignOut).sync_send(); -// let request = SignUpRequest { -// email: random_valid_email(), -// name: valid_name(), -// password: valid_password(), -// }; -// -// let _response = UserTestBuilder::new() -// .logout() -// .event(SignUp) -// .request(request) -// .sync_send(); -// // .parse::(); -// // dbg!(&response); -// } -// -// #[test] -// #[serial] -// fn sign_up_with_invalid_email() { -// for email in invalid_email_test_case() { -// let request = SignUpRequest { -// email: email.to_string(), -// name: valid_name(), -// password: valid_password(), -// }; -// -// assert_eq!( -// UserTestBuilder::new() -// .event(SignUp) -// .request(request) -// .sync_send() -// .error() -// .code, -// UserErrorCode::EmailInvalid -// ); -// } -// } -// #[test] -// #[serial] -// fn sign_up_with_invalid_password() { -// for password in invalid_password_test_case() { -// let request = SignUpRequest { -// email: random_valid_email(), -// name: valid_name(), -// password, -// }; -// -// assert_eq!( -// UserTestBuilder::new() -// .event(SignUp) -// .request(request) -// .sync_send() -// .error() -// .code, -// UserErrorCode::PasswordInvalid -// ); -// } -// } +use crate::helper::*; +use flowy_user::{errors::*, event::UserEvent::*, prelude::*}; +use serial_test::*; + +#[test] +#[serial] +fn sign_up_success() { + let _ = UserTestBuilder::new().event(SignOut).sync_send(); + let request = SignUpRequest { + email: random_valid_email(), + name: valid_name(), + password: valid_password(), + }; + + let _response = UserTestBuilder::new() + .logout() + .event(SignUp) + .request(request) + .sync_send(); + // .parse::(); + // dbg!(&response); +} + +#[test] +#[serial] +fn sign_up_with_invalid_email() { + for email in invalid_email_test_case() { + let request = SignUpRequest { + email: email.to_string(), + name: valid_name(), + password: valid_password(), + }; + + assert_eq!( + UserTestBuilder::new() + .event(SignUp) + .request(request) + .sync_send() + .error() + .code, + UserErrorCode::EmailInvalid + ); + } +} +#[test] +#[serial] +fn sign_up_with_invalid_password() { + for password in invalid_password_test_case() { + let request = SignUpRequest { + email: random_valid_email(), + name: valid_name(), + password, + }; + + assert_eq!( + UserTestBuilder::new() + .event(SignUp) + .request(request) + .sync_send() + .error() + .code, + UserErrorCode::PasswordInvalid + ); + } +} diff --git a/rust-lib/flowy-user/tests/event/user_status_test.rs b/rust-lib/flowy-user/tests/event/user_status_test.rs index a6350b1fc7..ee5e56345d 100644 --- a/rust-lib/flowy-user/tests/event/user_status_test.rs +++ b/rust-lib/flowy-user/tests/event/user_status_test.rs @@ -1,36 +1,36 @@ -// use crate::helper::*; -// use flowy_user::{event::UserEvent::*, prelude::*}; -// use serial_test::*; -// -// #[test] -// #[should_panic] -// #[serial] -// fn user_status_get_failed_before_login() { -// let _ = UserTestBuilder::new() -// .logout() -// .event(GetStatus) -// .sync_send() -// .parse::(); -// } -// -// #[test] -// #[serial] -// fn user_status_get_success_after_login() { -// let request = SignInRequest { -// email: random_valid_email(), -// password: valid_password(), -// }; -// -// let response = UserTestBuilder::new() -// .logout() -// .event(SignIn) -// .request(request) -// .sync_send() -// .parse::(); -// dbg!(&response); -// -// let _ = UserTestBuilder::new() -// .event(GetStatus) -// .sync_send() -// .parse::(); -// } +use crate::helper::*; +use flowy_user::{event::UserEvent::*, prelude::*}; +use serial_test::*; + +#[test] +#[should_panic] +#[serial] +fn user_status_get_failed_before_login() { + let _ = UserTestBuilder::new() + .logout() + .event(GetStatus) + .sync_send() + .parse::(); +} + +#[test] +#[serial] +fn user_status_get_success_after_login() { + let request = SignInRequest { + email: random_valid_email(), + password: valid_password(), + }; + + let response = UserTestBuilder::new() + .logout() + .event(SignIn) + .request(request) + .sync_send() + .parse::(); + dbg!(&response); + + let _ = UserTestBuilder::new() + .event(GetStatus) + .sync_send() + .parse::(); +} diff --git a/rust-lib/flowy-user/tests/event/user_update_test.rs b/rust-lib/flowy-user/tests/event/user_update_test.rs index 7dc83bfca4..78c9ca332f 100644 --- a/rust-lib/flowy-user/tests/event/user_update_test.rs +++ b/rust-lib/flowy-user/tests/event/user_update_test.rs @@ -1,140 +1,140 @@ -// use crate::helper::*; -// use flowy_user::{errors::UserErrorCode, event::UserEvent::*, prelude::*}; -// use serial_test::*; -// -// #[test] -// #[serial] -// fn user_update_with_name() { -// let user_detail = UserTestBuilder::new().login().user_detail.unwrap(); -// let new_name = "hello_world".to_owned(); -// let request = UpdateUserRequest { -// id: user_detail.id.clone(), -// name: Some(new_name.clone()), -// email: None, -// workspace: None, -// password: None, -// }; -// -// let user_detail = UserTestBuilder::new() -// .event(UpdateUser) -// .request(request) -// .sync_send() -// .parse::(); -// -// assert_eq!(user_detail.name, new_name,); -// } -// -// #[test] -// #[serial] -// fn user_update_with_email() { -// let user_detail = UserTestBuilder::new().login().user_detail.unwrap(); -// let new_email = "123@gmai.com".to_owned(); -// let request = UpdateUserRequest { -// id: user_detail.id.clone(), -// name: None, -// email: Some(new_email.clone()), -// workspace: None, -// password: None, -// }; -// -// let user_detail = UserTestBuilder::new() -// .event(UpdateUser) -// .request(request) -// .sync_send() -// .parse::(); -// -// assert_eq!(user_detail.email, new_email,); -// } -// -// #[test] -// #[serial] -// fn user_update_with_password() { -// let user_detail = UserTestBuilder::new().login().user_detail.unwrap(); -// let new_password = "H123world!".to_owned(); -// let request = UpdateUserRequest { -// id: user_detail.id.clone(), -// name: None, -// email: None, -// workspace: None, -// password: Some(new_password.clone()), -// }; -// -// let _ = UserTestBuilder::new() -// .event(UpdateUser) -// .request(request) -// .sync_send() -// .assert_success(); -// } -// -// #[test] -// #[serial] -// fn user_update_with_invalid_email() { -// let user_detail = UserTestBuilder::new().login().user_detail.unwrap(); -// for email in invalid_email_test_case() { -// let request = UpdateUserRequest { -// id: user_detail.id.clone(), -// name: None, -// email: Some(email), -// workspace: None, -// password: None, -// }; -// -// assert_eq!( -// UserTestBuilder::new() -// .event(UpdateUser) -// .request(request) -// .sync_send() -// .error() -// .code, -// UserErrorCode::EmailInvalid -// ); -// } -// } -// -// #[test] -// #[serial] -// fn user_update_with_invalid_password() { -// let user_detail = UserTestBuilder::new().login().user_detail.unwrap(); -// for password in invalid_password_test_case() { -// let request = UpdateUserRequest { -// id: user_detail.id.clone(), -// name: None, -// email: None, -// workspace: None, -// password: Some(password), -// }; -// -// assert_eq!( -// UserTestBuilder::new() -// .event(UpdateUser) -// .request(request) -// .sync_send() -// .error() -// .code, -// UserErrorCode::PasswordInvalid -// ); -// } -// } -// -// #[test] -// #[serial] -// fn user_update_with_invalid_name() { -// let user_detail = UserTestBuilder::new().login().user_detail.unwrap(); -// let request = UpdateUserRequest { -// id: user_detail.id.clone(), -// name: Some("".to_string()), -// email: None, -// workspace: None, -// password: None, -// }; -// -// assert_eq!( -// UserTestBuilder::new() -// .event(UpdateUser) -// .request(request) -// .sync_send() -// .error() -// .code, -// UserErrorCode::UserNameInvalid -// ); -// } +use crate::helper::*; +use flowy_user::{errors::UserErrorCode, event::UserEvent::*, prelude::*}; +use serial_test::*; + +#[test] +#[serial] +fn user_update_with_name() { + let user_detail = UserTestBuilder::new().reset().user_detail.unwrap(); + let new_name = "hello_world".to_owned(); + let request = UpdateUserRequest { + id: user_detail.id.clone(), + name: Some(new_name.clone()), + email: None, + workspace: None, + password: None, + }; + + let user_detail = UserTestBuilder::new() + .event(UpdateUser) + .request(request) + .sync_send() + .parse::(); + + assert_eq!(user_detail.name, new_name,); +} + +#[test] +#[serial] +fn user_update_with_email() { + let user_detail = UserTestBuilder::new().reset().user_detail.unwrap(); + let new_email = "123@gmai.com".to_owned(); + let request = UpdateUserRequest { + id: user_detail.id.clone(), + name: None, + email: Some(new_email.clone()), + workspace: None, + password: None, + }; + + let user_detail = UserTestBuilder::new() + .event(UpdateUser) + .request(request) + .sync_send() + .parse::(); + + assert_eq!(user_detail.email, new_email,); +} + +#[test] +#[serial] +fn user_update_with_password() { + let user_detail = UserTestBuilder::new().reset().user_detail.unwrap(); + let new_password = "H123world!".to_owned(); + let request = UpdateUserRequest { + id: user_detail.id.clone(), + name: None, + email: None, + workspace: None, + password: Some(new_password.clone()), + }; + + let _ = UserTestBuilder::new() + .event(UpdateUser) + .request(request) + .sync_send() + .assert_success(); +} + +#[test] +#[serial] +fn user_update_with_invalid_email() { + let user_detail = UserTestBuilder::new().reset().user_detail.unwrap(); + for email in invalid_email_test_case() { + let request = UpdateUserRequest { + id: user_detail.id.clone(), + name: None, + email: Some(email), + workspace: None, + password: None, + }; + + assert_eq!( + UserTestBuilder::new() + .event(UpdateUser) + .request(request) + .sync_send() + .error() + .code, + UserErrorCode::EmailInvalid + ); + } +} + +#[test] +#[serial] +fn user_update_with_invalid_password() { + let user_detail = UserTestBuilder::new().reset().user_detail.unwrap(); + for password in invalid_password_test_case() { + let request = UpdateUserRequest { + id: user_detail.id.clone(), + name: None, + email: None, + workspace: None, + password: Some(password), + }; + + assert_eq!( + UserTestBuilder::new() + .event(UpdateUser) + .request(request) + .sync_send() + .error() + .code, + UserErrorCode::PasswordInvalid + ); + } +} + +#[test] +#[serial] +fn user_update_with_invalid_name() { + let user_detail = UserTestBuilder::new().reset().user_detail.unwrap(); + let request = UpdateUserRequest { + id: user_detail.id.clone(), + name: Some("".to_string()), + email: None, + workspace: None, + password: None, + }; + + assert_eq!( + UserTestBuilder::new() + .event(UpdateUser) + .request(request) + .sync_send() + .error() + .code, + UserErrorCode::UserNameInvalid + ); +} diff --git a/rust-lib/flowy-workspace/src/entities/workspace/workspace_user_detail.rs b/rust-lib/flowy-workspace/src/entities/workspace/workspace_user_detail.rs index 6d9b69a7d0..efe9a30b65 100644 --- a/rust-lib/flowy-workspace/src/entities/workspace/workspace_user_detail.rs +++ b/rust-lib/flowy-workspace/src/entities/workspace/workspace_user_detail.rs @@ -1,6 +1,20 @@ -pub struct WorkspaceUserQueryRequest { - fetch_owner: bool, - fetch_all: bool, +use crate::entities::workspace::WorkspaceDetail; +use flowy_derive::ProtoBuf; + +#[derive(ProtoBuf, Default, Debug)] +pub struct UserWorkspace { + #[pb(index = 1)] + pub owner: String, + + #[pb(index = 2)] + pub workspace_id: String, } -pub struct WorkspaceUserDetail {} +#[derive(ProtoBuf, Default, Debug)] +pub struct UserWorkspaceDetail { + #[pb(index = 1)] + pub owner: String, + + #[pb(index = 2)] + pub workspace: WorkspaceDetail, +} diff --git a/rust-lib/flowy-workspace/src/errors.rs b/rust-lib/flowy-workspace/src/errors.rs index a3359375f5..a0eb1e50c7 100644 --- a/rust-lib/flowy-workspace/src/errors.rs +++ b/rust-lib/flowy-workspace/src/errors.rs @@ -42,7 +42,7 @@ pub enum WorkspaceErrorCode { DatabaseConnectionFail = 5, #[display(fmt = "Database internal error")] - DatabaseInternalError = 6, + WorkspaceDatabaseError = 6, #[display(fmt = "User internal error")] UserInternalError = 10, @@ -57,15 +57,7 @@ impl std::default::Default for WorkspaceErrorCode { impl std::convert::From for WorkspaceError { fn from(error: flowy_database::result::Error) -> Self { - ErrorBuilder::new(WorkspaceErrorCode::DatabaseInternalError) - .error(error) - .build() - } -} - -impl std::convert::From for WorkspaceError { - fn from(error: flowy_sqlite::Error) -> Self { - ErrorBuilder::new(WorkspaceErrorCode::DatabaseInternalError) + ErrorBuilder::new(WorkspaceErrorCode::WorkspaceDatabaseError) .error(error) .build() } diff --git a/rust-lib/flowy-workspace/src/event.rs b/rust-lib/flowy-workspace/src/event.rs index b8072ce17a..8a45318ac2 100644 --- a/rust-lib/flowy-workspace/src/event.rs +++ b/rust-lib/flowy-workspace/src/event.rs @@ -6,9 +6,9 @@ use flowy_derive::{Flowy_Event, ProtoBuf_Enum}; pub enum WorkspaceEvent { #[display(fmt = "Create workspace")] #[event(input = "CreateSpaceRequest", output = "WorkspaceDetail")] - CreateWorkspace = 0, + CreateWorkspace = 0, - #[display(fmt = "Get workspace user")] - #[event(output = "UserDetail")] - GetWorkspaceUserDetail = 100, + #[display(fmt = "Get user's workspace detail")] + #[event(output = "UserWorkspaceDetail")] + GetWorkspaceDetail = 1, } diff --git a/rust-lib/flowy-workspace/src/handlers/workspace_handler.rs b/rust-lib/flowy-workspace/src/handlers/workspace_handler.rs index e15ca53d9e..b19d7258a0 100644 --- a/rust-lib/flowy-workspace/src/handlers/workspace_handler.rs +++ b/rust-lib/flowy-workspace/src/handlers/workspace_handler.rs @@ -1,5 +1,11 @@ use crate::{ - entities::workspace::{CreateWorkspaceParams, CreateWorkspaceRequest, WorkspaceDetail}, + entities::workspace::{ + CreateWorkspaceParams, + CreateWorkspaceRequest, + UserWorkspace, + UserWorkspaceDetail, + WorkspaceDetail, + }, errors::WorkspaceError, services::WorkspaceController, }; @@ -16,12 +22,9 @@ pub async fn create_workspace( response_ok(detail) } -pub async fn workspace_user( - data: Data, +pub async fn get_workspace_detail( controller: ModuleData>, -) -> ResponseResult { - let controller = controller.get_ref().clone(); - let params: CreateWorkspaceParams = data.into_inner().try_into()?; - let detail = controller.save_workspace(params).await?; - response_ok(detail) +) -> ResponseResult { + let user_workspace = controller.get_user_workspace_detail().await?; + response_ok(user_workspace) } diff --git a/rust-lib/flowy-workspace/src/module.rs b/rust-lib/flowy-workspace/src/module.rs index e82a48515c..4033730c0f 100644 --- a/rust-lib/flowy-workspace/src/module.rs +++ b/rust-lib/flowy-workspace/src/module.rs @@ -7,12 +7,12 @@ use crate::{ }; use flowy_database::DBConnection; -use crate::handlers::*; +use crate::{entities::workspace::UserWorkspace, handlers::*}; use std::sync::Arc; pub trait WorkspaceUser: Send + Sync { - fn set_workspace(&self, id: &str) -> DispatchFuture>; - fn get_workspace(&self) -> Result; + fn set_cur_workspace_id(&self, id: &str) -> DispatchFuture>; + fn get_cur_workspace(&self) -> DispatchFuture>; fn db_connection(&self) -> Result; } @@ -25,5 +25,5 @@ pub fn create(user: Arc) -> Module { .data(workspace_controller) .data(app_controller) .event(WorkspaceEvent::CreateWorkspace, create_workspace) - .event(WorkspaceEvent::GetWorkspaceUserDetail, workspace_user) + .event(WorkspaceEvent::GetWorkspaceDetail, get_workspace_detail) } diff --git a/rust-lib/flowy-workspace/src/protobuf/model/errors.rs b/rust-lib/flowy-workspace/src/protobuf/model/errors.rs index 33a4dd78a1..eda3e0c478 100644 --- a/rust-lib/flowy-workspace/src/protobuf/model/errors.rs +++ b/rust-lib/flowy-workspace/src/protobuf/model/errors.rs @@ -221,7 +221,7 @@ pub enum WorkspaceErrorCode { AppColorStyleInvalid = 3, AppIdInvalid = 4, DatabaseConnectionFail = 5, - DatabaseInternalError = 6, + WorkspaceDatabaseError = 6, UserInternalError = 10, UserNotLoginYet = 11, } @@ -239,7 +239,7 @@ impl ::protobuf::ProtobufEnum for WorkspaceErrorCode { 3 => ::std::option::Option::Some(WorkspaceErrorCode::AppColorStyleInvalid), 4 => ::std::option::Option::Some(WorkspaceErrorCode::AppIdInvalid), 5 => ::std::option::Option::Some(WorkspaceErrorCode::DatabaseConnectionFail), - 6 => ::std::option::Option::Some(WorkspaceErrorCode::DatabaseInternalError), + 6 => ::std::option::Option::Some(WorkspaceErrorCode::WorkspaceDatabaseError), 10 => ::std::option::Option::Some(WorkspaceErrorCode::UserInternalError), 11 => ::std::option::Option::Some(WorkspaceErrorCode::UserNotLoginYet), _ => ::std::option::Option::None @@ -254,7 +254,7 @@ impl ::protobuf::ProtobufEnum for WorkspaceErrorCode { WorkspaceErrorCode::AppColorStyleInvalid, WorkspaceErrorCode::AppIdInvalid, WorkspaceErrorCode::DatabaseConnectionFail, - WorkspaceErrorCode::DatabaseInternalError, + WorkspaceErrorCode::WorkspaceDatabaseError, WorkspaceErrorCode::UserInternalError, WorkspaceErrorCode::UserNotLoginYet, ]; @@ -287,11 +287,11 @@ impl ::protobuf::reflect::ProtobufValue for WorkspaceErrorCode { static file_descriptor_proto_data: &'static [u8] = b"\ \n\x0cerrors.proto\"K\n\x0eWorkspaceError\x12'\n\x04code\x18\x01\x20\x01\ (\x0e2\x13.WorkspaceErrorCodeR\x04code\x12\x10\n\x03msg\x18\x02\x20\x01(\ - \tR\x03msg*\xe2\x01\n\x12WorkspaceErrorCode\x12\x0b\n\x07Unknown\x10\0\ + \tR\x03msg*\xe3\x01\n\x12WorkspaceErrorCode\x12\x0b\n\x07Unknown\x10\0\ \x12\x18\n\x14WorkspaceNameInvalid\x10\x01\x12\x16\n\x12WorkspaceIdInval\ id\x10\x02\x12\x18\n\x14AppColorStyleInvalid\x10\x03\x12\x10\n\x0cAppIdI\ - nvalid\x10\x04\x12\x1a\n\x16DatabaseConnectionFail\x10\x05\x12\x19\n\x15\ - DatabaseInternalError\x10\x06\x12\x15\n\x11UserInternalError\x10\n\x12\ + nvalid\x10\x04\x12\x1a\n\x16DatabaseConnectionFail\x10\x05\x12\x1a\n\x16\ + WorkspaceDatabaseError\x10\x06\x12\x15\n\x11UserInternalError\x10\n\x12\ \x13\n\x0fUserNotLoginYet\x10\x0bJ\xa1\x04\n\x06\x12\x04\0\0\x10\x01\n\ \x08\n\x01\x0c\x12\x03\0\0\x12\n\n\n\x02\x04\0\x12\x04\x02\0\x05\x01\n\n\ \n\x03\x04\0\x01\x12\x03\x02\x08\x16\n\x0b\n\x04\x04\0\x02\0\x12\x03\x03\ @@ -313,8 +313,8 @@ static file_descriptor_proto_data: &'static [u8] = b"\ \x03\x0b\x04\x10\n\x0c\n\x05\x05\0\x02\x04\x02\x12\x03\x0b\x13\x14\n\x0b\ \n\x04\x05\0\x02\x05\x12\x03\x0c\x04\x1f\n\x0c\n\x05\x05\0\x02\x05\x01\ \x12\x03\x0c\x04\x1a\n\x0c\n\x05\x05\0\x02\x05\x02\x12\x03\x0c\x1d\x1e\n\ - \x0b\n\x04\x05\0\x02\x06\x12\x03\r\x04\x1e\n\x0c\n\x05\x05\0\x02\x06\x01\ - \x12\x03\r\x04\x19\n\x0c\n\x05\x05\0\x02\x06\x02\x12\x03\r\x1c\x1d\n\x0b\ + \x0b\n\x04\x05\0\x02\x06\x12\x03\r\x04\x1f\n\x0c\n\x05\x05\0\x02\x06\x01\ + \x12\x03\r\x04\x1a\n\x0c\n\x05\x05\0\x02\x06\x02\x12\x03\r\x1d\x1e\n\x0b\ \n\x04\x05\0\x02\x07\x12\x03\x0e\x04\x1b\n\x0c\n\x05\x05\0\x02\x07\x01\ \x12\x03\x0e\x04\x15\n\x0c\n\x05\x05\0\x02\x07\x02\x12\x03\x0e\x18\x1a\n\ \x0b\n\x04\x05\0\x02\x08\x12\x03\x0f\x04\x19\n\x0c\n\x05\x05\0\x02\x08\ diff --git a/rust-lib/flowy-workspace/src/protobuf/model/event.rs b/rust-lib/flowy-workspace/src/protobuf/model/event.rs index d4836dbaee..4e3e978ea5 100644 --- a/rust-lib/flowy-workspace/src/protobuf/model/event.rs +++ b/rust-lib/flowy-workspace/src/protobuf/model/event.rs @@ -26,7 +26,7 @@ #[derive(Clone,PartialEq,Eq,Debug,Hash)] pub enum WorkspaceEvent { CreateWorkspace = 0, - GetWorkspaceUserDetail = 100, + GetWorkspaceDetail = 1, } impl ::protobuf::ProtobufEnum for WorkspaceEvent { @@ -37,7 +37,7 @@ impl ::protobuf::ProtobufEnum for WorkspaceEvent { fn from_i32(value: i32) -> ::std::option::Option { match value { 0 => ::std::option::Option::Some(WorkspaceEvent::CreateWorkspace), - 100 => ::std::option::Option::Some(WorkspaceEvent::GetWorkspaceUserDetail), + 1 => ::std::option::Option::Some(WorkspaceEvent::GetWorkspaceDetail), _ => ::std::option::Option::None } } @@ -45,7 +45,7 @@ impl ::protobuf::ProtobufEnum for WorkspaceEvent { fn values() -> &'static [Self] { static values: &'static [WorkspaceEvent] = &[ WorkspaceEvent::CreateWorkspace, - WorkspaceEvent::GetWorkspaceUserDetail, + WorkspaceEvent::GetWorkspaceDetail, ]; values } @@ -74,14 +74,14 @@ impl ::protobuf::reflect::ProtobufValue for WorkspaceEvent { } static file_descriptor_proto_data: &'static [u8] = b"\ - \n\x0bevent.proto*A\n\x0eWorkspaceEvent\x12\x13\n\x0fCreateWorkspace\x10\ - \0\x12\x1a\n\x16GetWorkspaceUserDetail\x10dJ|\n\x06\x12\x04\0\0\x05\x01\ - \n\x08\n\x01\x0c\x12\x03\0\0\x12\n\n\n\x02\x05\0\x12\x04\x02\0\x05\x01\n\ - \n\n\x03\x05\0\x01\x12\x03\x02\x05\x13\n\x0b\n\x04\x05\0\x02\0\x12\x03\ - \x03\x04\x18\n\x0c\n\x05\x05\0\x02\0\x01\x12\x03\x03\x04\x13\n\x0c\n\x05\ - \x05\0\x02\0\x02\x12\x03\x03\x16\x17\n\x0b\n\x04\x05\0\x02\x01\x12\x03\ - \x04\x04!\n\x0c\n\x05\x05\0\x02\x01\x01\x12\x03\x04\x04\x1a\n\x0c\n\x05\ - \x05\0\x02\x01\x02\x12\x03\x04\x1d\x20b\x06proto3\ + \n\x0bevent.proto*=\n\x0eWorkspaceEvent\x12\x13\n\x0fCreateWorkspace\x10\ + \0\x12\x16\n\x12GetWorkspaceDetail\x10\x01J|\n\x06\x12\x04\0\0\x05\x01\n\ + \x08\n\x01\x0c\x12\x03\0\0\x12\n\n\n\x02\x05\0\x12\x04\x02\0\x05\x01\n\n\ + \n\x03\x05\0\x01\x12\x03\x02\x05\x13\n\x0b\n\x04\x05\0\x02\0\x12\x03\x03\ + \x04\x18\n\x0c\n\x05\x05\0\x02\0\x01\x12\x03\x03\x04\x13\n\x0c\n\x05\x05\ + \0\x02\0\x02\x12\x03\x03\x16\x17\n\x0b\n\x04\x05\0\x02\x01\x12\x03\x04\ + \x04\x1b\n\x0c\n\x05\x05\0\x02\x01\x01\x12\x03\x04\x04\x16\n\x0c\n\x05\ + \x05\0\x02\x01\x02\x12\x03\x04\x19\x1ab\x06proto3\ "; static file_descriptor_proto_lazy: ::protobuf::rt::LazyV2<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::rt::LazyV2::INIT; diff --git a/rust-lib/flowy-workspace/src/protobuf/model/mod.rs b/rust-lib/flowy-workspace/src/protobuf/model/mod.rs index ed856a9b17..1d98328c6d 100644 --- a/rust-lib/flowy-workspace/src/protobuf/model/mod.rs +++ b/rust-lib/flowy-workspace/src/protobuf/model/mod.rs @@ -12,6 +12,9 @@ pub use app_create::*; mod event; pub use event::*; +mod workspace_user_detail; +pub use workspace_user_detail::*; + mod workspace_create; pub use workspace_create::*; diff --git a/rust-lib/flowy-workspace/src/protobuf/model/workspace_user_detail.rs b/rust-lib/flowy-workspace/src/protobuf/model/workspace_user_detail.rs new file mode 100644 index 0000000000..06507aa745 --- /dev/null +++ b/rust-lib/flowy-workspace/src/protobuf/model/workspace_user_detail.rs @@ -0,0 +1,476 @@ +// This file is generated by rust-protobuf 2.22.1. Do not edit +// @generated + +// https://github.com/rust-lang/rust-clippy/issues/702 +#![allow(unknown_lints)] +#![allow(clippy::all)] + +#![allow(unused_attributes)] +#![cfg_attr(rustfmt, rustfmt::skip)] + +#![allow(box_pointers)] +#![allow(dead_code)] +#![allow(missing_docs)] +#![allow(non_camel_case_types)] +#![allow(non_snake_case)] +#![allow(non_upper_case_globals)] +#![allow(trivial_casts)] +#![allow(unused_imports)] +#![allow(unused_results)] +//! Generated file from `workspace_user_detail.proto` + +/// Generated files are compatible only with the same version +/// of protobuf runtime. +// const _PROTOBUF_VERSION_CHECK: () = ::protobuf::VERSION_2_22_1; + +#[derive(PartialEq,Clone,Default)] +pub struct UserWorkspace { + // message fields + pub owner: ::std::string::String, + pub workspace_id: ::std::string::String, + // special fields + pub unknown_fields: ::protobuf::UnknownFields, + pub cached_size: ::protobuf::CachedSize, +} + +impl<'a> ::std::default::Default for &'a UserWorkspace { + fn default() -> &'a UserWorkspace { + ::default_instance() + } +} + +impl UserWorkspace { + pub fn new() -> UserWorkspace { + ::std::default::Default::default() + } + + // string owner = 1; + + + pub fn get_owner(&self) -> &str { + &self.owner + } + pub fn clear_owner(&mut self) { + self.owner.clear(); + } + + // Param is passed by value, moved + pub fn set_owner(&mut self, v: ::std::string::String) { + self.owner = v; + } + + // Mutable pointer to the field. + // If field is not initialized, it is initialized with default value first. + pub fn mut_owner(&mut self) -> &mut ::std::string::String { + &mut self.owner + } + + // Take field + pub fn take_owner(&mut self) -> ::std::string::String { + ::std::mem::replace(&mut self.owner, ::std::string::String::new()) + } + + // string workspace_id = 2; + + + pub fn get_workspace_id(&self) -> &str { + &self.workspace_id + } + pub fn clear_workspace_id(&mut self) { + self.workspace_id.clear(); + } + + // Param is passed by value, moved + pub fn set_workspace_id(&mut self, v: ::std::string::String) { + self.workspace_id = v; + } + + // Mutable pointer to the field. + // If field is not initialized, it is initialized with default value first. + pub fn mut_workspace_id(&mut self) -> &mut ::std::string::String { + &mut self.workspace_id + } + + // Take field + pub fn take_workspace_id(&mut self) -> ::std::string::String { + ::std::mem::replace(&mut self.workspace_id, ::std::string::String::new()) + } +} + +impl ::protobuf::Message for UserWorkspace { + fn is_initialized(&self) -> bool { + true + } + + fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream<'_>) -> ::protobuf::ProtobufResult<()> { + while !is.eof()? { + let (field_number, wire_type) = is.read_tag_unpack()?; + match field_number { + 1 => { + ::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.owner)?; + }, + 2 => { + ::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.workspace_id)?; + }, + _ => { + ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + }, + }; + } + ::std::result::Result::Ok(()) + } + + // Compute sizes of nested messages + #[allow(unused_variables)] + fn compute_size(&self) -> u32 { + let mut my_size = 0; + if !self.owner.is_empty() { + my_size += ::protobuf::rt::string_size(1, &self.owner); + } + if !self.workspace_id.is_empty() { + my_size += ::protobuf::rt::string_size(2, &self.workspace_id); + } + my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); + self.cached_size.set(my_size); + my_size + } + + fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::ProtobufResult<()> { + if !self.owner.is_empty() { + os.write_string(1, &self.owner)?; + } + if !self.workspace_id.is_empty() { + os.write_string(2, &self.workspace_id)?; + } + os.write_unknown_fields(self.get_unknown_fields())?; + ::std::result::Result::Ok(()) + } + + fn get_cached_size(&self) -> u32 { + self.cached_size.get() + } + + fn get_unknown_fields(&self) -> &::protobuf::UnknownFields { + &self.unknown_fields + } + + fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields { + &mut self.unknown_fields + } + + fn as_any(&self) -> &dyn (::std::any::Any) { + self as &dyn (::std::any::Any) + } + fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { + self as &mut dyn (::std::any::Any) + } + fn into_any(self: ::std::boxed::Box) -> ::std::boxed::Box { + self + } + + fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor { + Self::descriptor_static() + } + + fn new() -> UserWorkspace { + UserWorkspace::new() + } + + fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { + static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT; + descriptor.get(|| { + let mut fields = ::std::vec::Vec::new(); + fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( + "owner", + |m: &UserWorkspace| { &m.owner }, + |m: &mut UserWorkspace| { &mut m.owner }, + )); + fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( + "workspace_id", + |m: &UserWorkspace| { &m.workspace_id }, + |m: &mut UserWorkspace| { &mut m.workspace_id }, + )); + ::protobuf::reflect::MessageDescriptor::new_pb_name::( + "UserWorkspace", + fields, + file_descriptor_proto() + ) + }) + } + + fn default_instance() -> &'static UserWorkspace { + static instance: ::protobuf::rt::LazyV2 = ::protobuf::rt::LazyV2::INIT; + instance.get(UserWorkspace::new) + } +} + +impl ::protobuf::Clear for UserWorkspace { + fn clear(&mut self) { + self.owner.clear(); + self.workspace_id.clear(); + self.unknown_fields.clear(); + } +} + +impl ::std::fmt::Debug for UserWorkspace { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + ::protobuf::text_format::fmt(self, f) + } +} + +impl ::protobuf::reflect::ProtobufValue for UserWorkspace { + fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef { + ::protobuf::reflect::ReflectValueRef::Message(self) + } +} + +#[derive(PartialEq,Clone,Default)] +pub struct UserWorkspaceDetail { + // message fields + pub owner: ::std::string::String, + pub workspace: ::protobuf::SingularPtrField, + // special fields + pub unknown_fields: ::protobuf::UnknownFields, + pub cached_size: ::protobuf::CachedSize, +} + +impl<'a> ::std::default::Default for &'a UserWorkspaceDetail { + fn default() -> &'a UserWorkspaceDetail { + ::default_instance() + } +} + +impl UserWorkspaceDetail { + pub fn new() -> UserWorkspaceDetail { + ::std::default::Default::default() + } + + // string owner = 1; + + + pub fn get_owner(&self) -> &str { + &self.owner + } + pub fn clear_owner(&mut self) { + self.owner.clear(); + } + + // Param is passed by value, moved + pub fn set_owner(&mut self, v: ::std::string::String) { + self.owner = v; + } + + // Mutable pointer to the field. + // If field is not initialized, it is initialized with default value first. + pub fn mut_owner(&mut self) -> &mut ::std::string::String { + &mut self.owner + } + + // Take field + pub fn take_owner(&mut self) -> ::std::string::String { + ::std::mem::replace(&mut self.owner, ::std::string::String::new()) + } + + // .WorkspaceDetail workspace = 2; + + + pub fn get_workspace(&self) -> &super::workspace_create::WorkspaceDetail { + self.workspace.as_ref().unwrap_or_else(|| ::default_instance()) + } + pub fn clear_workspace(&mut self) { + self.workspace.clear(); + } + + pub fn has_workspace(&self) -> bool { + self.workspace.is_some() + } + + // Param is passed by value, moved + pub fn set_workspace(&mut self, v: super::workspace_create::WorkspaceDetail) { + self.workspace = ::protobuf::SingularPtrField::some(v); + } + + // Mutable pointer to the field. + // If field is not initialized, it is initialized with default value first. + pub fn mut_workspace(&mut self) -> &mut super::workspace_create::WorkspaceDetail { + if self.workspace.is_none() { + self.workspace.set_default(); + } + self.workspace.as_mut().unwrap() + } + + // Take field + pub fn take_workspace(&mut self) -> super::workspace_create::WorkspaceDetail { + self.workspace.take().unwrap_or_else(|| super::workspace_create::WorkspaceDetail::new()) + } +} + +impl ::protobuf::Message for UserWorkspaceDetail { + fn is_initialized(&self) -> bool { + for v in &self.workspace { + if !v.is_initialized() { + return false; + } + }; + true + } + + fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream<'_>) -> ::protobuf::ProtobufResult<()> { + while !is.eof()? { + let (field_number, wire_type) = is.read_tag_unpack()?; + match field_number { + 1 => { + ::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.owner)?; + }, + 2 => { + ::protobuf::rt::read_singular_message_into(wire_type, is, &mut self.workspace)?; + }, + _ => { + ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + }, + }; + } + ::std::result::Result::Ok(()) + } + + // Compute sizes of nested messages + #[allow(unused_variables)] + fn compute_size(&self) -> u32 { + let mut my_size = 0; + if !self.owner.is_empty() { + my_size += ::protobuf::rt::string_size(1, &self.owner); + } + if let Some(ref v) = self.workspace.as_ref() { + let len = v.compute_size(); + my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len; + } + my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); + self.cached_size.set(my_size); + my_size + } + + fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::ProtobufResult<()> { + if !self.owner.is_empty() { + os.write_string(1, &self.owner)?; + } + if let Some(ref v) = self.workspace.as_ref() { + os.write_tag(2, ::protobuf::wire_format::WireTypeLengthDelimited)?; + os.write_raw_varint32(v.get_cached_size())?; + v.write_to_with_cached_sizes(os)?; + } + os.write_unknown_fields(self.get_unknown_fields())?; + ::std::result::Result::Ok(()) + } + + fn get_cached_size(&self) -> u32 { + self.cached_size.get() + } + + fn get_unknown_fields(&self) -> &::protobuf::UnknownFields { + &self.unknown_fields + } + + fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields { + &mut self.unknown_fields + } + + fn as_any(&self) -> &dyn (::std::any::Any) { + self as &dyn (::std::any::Any) + } + fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { + self as &mut dyn (::std::any::Any) + } + fn into_any(self: ::std::boxed::Box) -> ::std::boxed::Box { + self + } + + fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor { + Self::descriptor_static() + } + + fn new() -> UserWorkspaceDetail { + UserWorkspaceDetail::new() + } + + fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { + static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT; + descriptor.get(|| { + let mut fields = ::std::vec::Vec::new(); + fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( + "owner", + |m: &UserWorkspaceDetail| { &m.owner }, + |m: &mut UserWorkspaceDetail| { &mut m.owner }, + )); + fields.push(::protobuf::reflect::accessor::make_singular_ptr_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage>( + "workspace", + |m: &UserWorkspaceDetail| { &m.workspace }, + |m: &mut UserWorkspaceDetail| { &mut m.workspace }, + )); + ::protobuf::reflect::MessageDescriptor::new_pb_name::( + "UserWorkspaceDetail", + fields, + file_descriptor_proto() + ) + }) + } + + fn default_instance() -> &'static UserWorkspaceDetail { + static instance: ::protobuf::rt::LazyV2 = ::protobuf::rt::LazyV2::INIT; + instance.get(UserWorkspaceDetail::new) + } +} + +impl ::protobuf::Clear for UserWorkspaceDetail { + fn clear(&mut self) { + self.owner.clear(); + self.workspace.clear(); + self.unknown_fields.clear(); + } +} + +impl ::std::fmt::Debug for UserWorkspaceDetail { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + ::protobuf::text_format::fmt(self, f) + } +} + +impl ::protobuf::reflect::ProtobufValue for UserWorkspaceDetail { + fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef { + ::protobuf::reflect::ReflectValueRef::Message(self) + } +} + +static file_descriptor_proto_data: &'static [u8] = b"\ + \n\x1bworkspace_user_detail.proto\x1a\x16workspace_create.proto\"H\n\rUs\ + erWorkspace\x12\x14\n\x05owner\x18\x01\x20\x01(\tR\x05owner\x12!\n\x0cwo\ + rkspace_id\x18\x02\x20\x01(\tR\x0bworkspaceId\"[\n\x13UserWorkspaceDetai\ + l\x12\x14\n\x05owner\x18\x01\x20\x01(\tR\x05owner\x12.\n\tworkspace\x18\ + \x02\x20\x01(\x0b2\x10.WorkspaceDetailR\tworkspaceJ\xa9\x02\n\x06\x12\ + \x04\0\0\n\x01\n\x08\n\x01\x0c\x12\x03\0\0\x12\n\t\n\x02\x03\0\x12\x03\ + \x01\0\x20\n\n\n\x02\x04\0\x12\x04\x03\0\x06\x01\n\n\n\x03\x04\0\x01\x12\ + \x03\x03\x08\x15\n\x0b\n\x04\x04\0\x02\0\x12\x03\x04\x04\x15\n\x0c\n\x05\ + \x04\0\x02\0\x05\x12\x03\x04\x04\n\n\x0c\n\x05\x04\0\x02\0\x01\x12\x03\ + \x04\x0b\x10\n\x0c\n\x05\x04\0\x02\0\x03\x12\x03\x04\x13\x14\n\x0b\n\x04\ + \x04\0\x02\x01\x12\x03\x05\x04\x1c\n\x0c\n\x05\x04\0\x02\x01\x05\x12\x03\ + \x05\x04\n\n\x0c\n\x05\x04\0\x02\x01\x01\x12\x03\x05\x0b\x17\n\x0c\n\x05\ + \x04\0\x02\x01\x03\x12\x03\x05\x1a\x1b\n\n\n\x02\x04\x01\x12\x04\x07\0\n\ + \x01\n\n\n\x03\x04\x01\x01\x12\x03\x07\x08\x1b\n\x0b\n\x04\x04\x01\x02\0\ + \x12\x03\x08\x04\x15\n\x0c\n\x05\x04\x01\x02\0\x05\x12\x03\x08\x04\n\n\ + \x0c\n\x05\x04\x01\x02\0\x01\x12\x03\x08\x0b\x10\n\x0c\n\x05\x04\x01\x02\ + \0\x03\x12\x03\x08\x13\x14\n\x0b\n\x04\x04\x01\x02\x01\x12\x03\t\x04\"\n\ + \x0c\n\x05\x04\x01\x02\x01\x06\x12\x03\t\x04\x13\n\x0c\n\x05\x04\x01\x02\ + \x01\x01\x12\x03\t\x14\x1d\n\x0c\n\x05\x04\x01\x02\x01\x03\x12\x03\t\x20\ + !b\x06proto3\ +"; + +static file_descriptor_proto_lazy: ::protobuf::rt::LazyV2<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::rt::LazyV2::INIT; + +fn parse_descriptor_proto() -> ::protobuf::descriptor::FileDescriptorProto { + ::protobuf::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() +} + +pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto { + file_descriptor_proto_lazy.get(|| { + parse_descriptor_proto() + }) +} diff --git a/rust-lib/flowy-workspace/src/protobuf/proto/errors.proto b/rust-lib/flowy-workspace/src/protobuf/proto/errors.proto index 6b6af8b844..478a1c052b 100644 --- a/rust-lib/flowy-workspace/src/protobuf/proto/errors.proto +++ b/rust-lib/flowy-workspace/src/protobuf/proto/errors.proto @@ -11,7 +11,7 @@ enum WorkspaceErrorCode { AppColorStyleInvalid = 3; AppIdInvalid = 4; DatabaseConnectionFail = 5; - DatabaseInternalError = 6; + WorkspaceDatabaseError = 6; UserInternalError = 10; UserNotLoginYet = 11; } diff --git a/rust-lib/flowy-workspace/src/protobuf/proto/event.proto b/rust-lib/flowy-workspace/src/protobuf/proto/event.proto index 5d5a85f570..0ccba3d647 100644 --- a/rust-lib/flowy-workspace/src/protobuf/proto/event.proto +++ b/rust-lib/flowy-workspace/src/protobuf/proto/event.proto @@ -2,5 +2,5 @@ syntax = "proto3"; enum WorkspaceEvent { CreateWorkspace = 0; - GetWorkspaceUserDetail = 100; + GetWorkspaceDetail = 1; } diff --git a/rust-lib/flowy-workspace/src/protobuf/proto/workspace_user_detail.proto b/rust-lib/flowy-workspace/src/protobuf/proto/workspace_user_detail.proto new file mode 100644 index 0000000000..14036d8d00 --- /dev/null +++ b/rust-lib/flowy-workspace/src/protobuf/proto/workspace_user_detail.proto @@ -0,0 +1,11 @@ +syntax = "proto3"; +import "workspace_create.proto"; + +message UserWorkspace { + string owner = 1; + string workspace_id = 2; +} +message UserWorkspaceDetail { + string owner = 1; + WorkspaceDetail workspace = 2; +} diff --git a/rust-lib/flowy-workspace/src/services/workspace_controller.rs b/rust-lib/flowy-workspace/src/services/workspace_controller.rs index dad0a817c0..5fdf48e2b1 100644 --- a/rust-lib/flowy-workspace/src/services/workspace_controller.rs +++ b/rust-lib/flowy-workspace/src/services/workspace_controller.rs @@ -1,6 +1,8 @@ use crate::{entities::workspace::*, errors::*, module::WorkspaceUser, sql_tables::workspace::*}; use flowy_database::{prelude::*, schema::workspace_table}; +use flowy_database::schema::workspace_table::dsl; +use flowy_dispatch::prelude::DispatchFuture; use std::sync::Arc; pub struct WorkspaceController { @@ -21,11 +23,29 @@ impl WorkspaceController { .values(workspace) .execute(&*(self.user.db_connection()?))?; - let _ = self.user.set_workspace(&detail.id).await?; + let _ = self.user.set_cur_workspace_id(&detail.id).await?; Ok(detail) } + pub fn get_workspace( + &self, + workspace_id: &str, + ) -> DispatchFuture> { + let user = self.user.clone(); + let workspace_id = workspace_id.to_owned(); + DispatchFuture { + fut: Box::pin(async move { + let workspace = dsl::workspace_table + .filter(workspace_table::id.eq(&workspace_id)) + .first::(&*(user.db_connection()?))?; + + // TODO: fetch workspace from remote server + Ok(workspace) + }), + } + } + pub fn update_workspace(&self, params: UpdateWorkspaceParams) -> Result<(), WorkspaceError> { let changeset = WorkspaceChangeset::new(params); let conn = self.user.db_connection()?; @@ -33,4 +53,14 @@ impl WorkspaceController { Ok(()) } + + pub async fn get_user_workspace_detail(&self) -> Result { + let user_workspace = self.user.get_cur_workspace().await?; + let workspace = self.get_workspace(&user_workspace.workspace_id).await?; + + Ok(UserWorkspaceDetail { + owner: user_workspace.owner, + workspace: workspace.into(), + }) + } } diff --git a/rust-lib/flowy-workspace/tests/event/workspace_test.rs b/rust-lib/flowy-workspace/tests/event/workspace_test.rs index 8c00414098..2c0ffc6855 100644 --- a/rust-lib/flowy-workspace/tests/event/workspace_test.rs +++ b/rust-lib/flowy-workspace/tests/event/workspace_test.rs @@ -1,6 +1,6 @@ use crate::helper::*; use flowy_workspace::{ - entities::workspace::{CreateWorkspaceRequest, WorkspaceDetail}, + entities::workspace::{CreateWorkspaceRequest, UserWorkspaceDetail, WorkspaceDetail}, event::WorkspaceEvent::*, prelude::*, }; @@ -20,6 +20,27 @@ fn workspace_create_success() { dbg!(&response); } +#[test] +fn workspace_get_detail_success() { + let request = CreateWorkspaceRequest { + name: "Team A".to_owned(), + desc: "Team A Description".to_owned(), + }; + + let workspace = WorkspaceTestBuilder::new() + .event(CreateWorkspace) + .request(request) + .sync_send() + .parse::(); + + let user_workspace = WorkspaceTestBuilder::new() + .event(GetWorkspaceDetail) + .sync_send() + .parse::(); + + assert_eq!(workspace.name, user_workspace.workspace.name); +} + #[test] fn workspace_create_with_invalid_name_test() { for name in invalid_workspace_name_test_case() { diff --git a/scripts/flowy-tool/Cargo.toml b/scripts/flowy-tool/Cargo.toml index 25ce86882d..efef3f7a1b 100644 --- a/scripts/flowy-tool/Cargo.toml +++ b/scripts/flowy-tool/Cargo.toml @@ -22,4 +22,5 @@ phf = { version = "0.8.0", features = ["macros"] } similar = "1.2.2" dialoguer = "0.8.0" toml = "0.5.8" -serde = { version = "1.0", features = ["derive"] } \ No newline at end of file +serde = { version = "1.0", features = ["derive"] } +pathdiff = "0.2.0" \ No newline at end of file diff --git a/scripts/flowy-tool/src/proto/ast.rs b/scripts/flowy-tool/src/proto/ast.rs index bf780bb1d9..ab4722897f 100644 --- a/scripts/flowy-tool/src/proto/ast.rs +++ b/scripts/flowy-tool/src/proto/ast.rs @@ -78,6 +78,7 @@ fn parse_files_protobuf(proto_crate_path: &str, proto_output_dir: &str) -> Vec

, pub enums: Vec, @@ -121,6 +122,7 @@ impl FlutterProtobufInfo { model_dir } + #[allow(dead_code)] pub fn mod_file_path(&self) -> String { let mod_file_path = format!("{}/protobuf.dart", self.package_path); mod_file_path diff --git a/scripts/flowy-tool/src/util/file.rs b/scripts/flowy-tool/src/util/file.rs index 1719631560..b752866200 100644 --- a/scripts/flowy-tool/src/util/file.rs +++ b/scripts/flowy-tool/src/util/file.rs @@ -154,3 +154,14 @@ where path_and_name(path, name); } } + +#[allow(dead_code)] +pub fn suffix_relative_to_path(path: &str, base: &str) -> String { + let base = Path::new(base); + let path = Path::new(path); + path.strip_prefix(base) + .unwrap() + .to_str() + .unwrap() + .to_owned() +} From 379a0555f02befddcc1f17ff7454685f91ebef0f Mon Sep 17 00:00:00 2001 From: appflowy Date: Mon, 19 Jul 2021 17:27:04 +0800 Subject: [PATCH 24/30] rm idea folder --- .idea/.gitignore | 8 - .idea/appflowy_client.iml | 98 -- .idea/dataSources.xml | 12 - .idea/inspectionProfiles/Project_Default.xml | 10 - .idea/libraries/Dart_Packages.xml | 1056 ------------------ .idea/libraries/Dart_SDK.xml | 28 - .idea/modules.xml | 8 - .idea/vcs.xml | 6 - 8 files changed, 1226 deletions(-) delete mode 100644 .idea/.gitignore delete mode 100644 .idea/appflowy_client.iml delete mode 100644 .idea/dataSources.xml delete mode 100644 .idea/inspectionProfiles/Project_Default.xml delete mode 100644 .idea/libraries/Dart_Packages.xml delete mode 100644 .idea/libraries/Dart_SDK.xml delete mode 100644 .idea/modules.xml delete mode 100644 .idea/vcs.xml diff --git a/.idea/.gitignore b/.idea/.gitignore deleted file mode 100644 index 73f69e0958..0000000000 --- a/.idea/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -# Default ignored files -/shelf/ -/workspace.xml -# Datasource local storage ignored files -/dataSources/ -/dataSources.local.xml -# Editor-based HTTP Client requests -/httpRequests/ diff --git a/.idea/appflowy_client.iml b/.idea/appflowy_client.iml deleted file mode 100644 index fbd3a47727..0000000000 --- a/.idea/appflowy_client.iml +++ /dev/null @@ -1,98 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/dataSources.xml b/.idea/dataSources.xml deleted file mode 100644 index 7f5b513827..0000000000 --- a/.idea/dataSources.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - sqlite.xerial - true - org.sqlite.JDBC - jdbc:sqlite:$PROJECT_DIR$/rust-lib/flowy-test/temp/flowy/annie@appflowy.io/flowy-database.db - $ProjectFileDir$ - - - \ No newline at end of file diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml deleted file mode 100644 index e29848431e..0000000000 --- a/.idea/inspectionProfiles/Project_Default.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - \ No newline at end of file diff --git a/.idea/libraries/Dart_Packages.xml b/.idea/libraries/Dart_Packages.xml deleted file mode 100644 index c1ba66c5f7..0000000000 --- a/.idea/libraries/Dart_Packages.xml +++ /dev/null @@ -1,1056 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/libraries/Dart_SDK.xml b/.idea/libraries/Dart_SDK.xml deleted file mode 100644 index 6068110626..0000000000 --- a/.idea/libraries/Dart_SDK.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml deleted file mode 100644 index facec90f25..0000000000 --- a/.idea/modules.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml deleted file mode 100644 index 94a25f7f4c..0000000000 --- a/.idea/vcs.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file From ccd361a0489be9989ab2711c5a2f82a47758031e Mon Sep 17 00:00:00 2001 From: appflowy Date: Mon, 19 Jul 2021 17:27:42 +0800 Subject: [PATCH 25/30] ignore .idea folder --- .gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 65c89d2991..1ebe369c09 100644 --- a/.gitignore +++ b/.gitignore @@ -9,4 +9,5 @@ Cargo.lock # These are backup files generated by rustfmt **/*.rs.bk **/target/ -**/*.db \ No newline at end of file +**/*.db +.idea/ \ No newline at end of file From 7e9a68f9fd3c82611a8d1055a458cce5d19ce695 Mon Sep 17 00:00:00 2001 From: appflowy Date: Mon, 19 Jul 2021 17:29:18 +0800 Subject: [PATCH 26/30] rm rust-lib .idea foler and ignore it --- rust-lib/.gitignore | 2 +- rust-lib/.idea/.gitignore | 8 -------- rust-lib/.idea/modules.xml | 8 -------- rust-lib/.idea/rust-lib.iml | 20 -------------------- rust-lib/.idea/vcs.xml | 6 ------ 5 files changed, 1 insertion(+), 43 deletions(-) delete mode 100644 rust-lib/.idea/.gitignore delete mode 100644 rust-lib/.idea/modules.xml delete mode 100644 rust-lib/.idea/rust-lib.iml delete mode 100644 rust-lib/.idea/vcs.xml diff --git a/rust-lib/.gitignore b/rust-lib/.gitignore index 3ec66f140b..a42aa3663e 100644 --- a/rust-lib/.gitignore +++ b/rust-lib/.gitignore @@ -12,4 +12,4 @@ Cargo.lock **/**/temp bin/ -.idea \ No newline at end of file +.idea/ \ No newline at end of file diff --git a/rust-lib/.idea/.gitignore b/rust-lib/.idea/.gitignore deleted file mode 100644 index 73f69e0958..0000000000 --- a/rust-lib/.idea/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -# Default ignored files -/shelf/ -/workspace.xml -# Datasource local storage ignored files -/dataSources/ -/dataSources.local.xml -# Editor-based HTTP Client requests -/httpRequests/ diff --git a/rust-lib/.idea/modules.xml b/rust-lib/.idea/modules.xml deleted file mode 100644 index 332e83b7bd..0000000000 --- a/rust-lib/.idea/modules.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/rust-lib/.idea/rust-lib.iml b/rust-lib/.idea/rust-lib.iml deleted file mode 100644 index 257d037616..0000000000 --- a/rust-lib/.idea/rust-lib.iml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/rust-lib/.idea/vcs.xml b/rust-lib/.idea/vcs.xml deleted file mode 100644 index 6c0b863585..0000000000 --- a/rust-lib/.idea/vcs.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file From 139222ddcbfd7c9d6eb4f16014d4636d50ff1e8b Mon Sep 17 00:00:00 2001 From: appflowy Date: Mon, 19 Jul 2021 17:37:58 +0800 Subject: [PATCH 27/30] rename all sql table struct with Table signature --- rust-lib/flowy-sdk/src/flowy_server.rs | 10 +++++----- .../flowy-user/src/entities/user_detail.rs | 6 +++--- .../src/services/user_session/user_server.rs | 6 +++--- .../src/services/user_session/user_session.rs | 12 ++++++------ rust-lib/flowy-user/src/sql_tables/user.rs | 10 +++++----- .../src/services/app_controller.rs | 4 ++-- .../src/services/workspace_controller.rs | 8 ++++---- .../flowy-workspace/src/sql_tables/app/app.rs | 16 ++++++++-------- .../src/sql_tables/workspace/workspace.rs | 18 +++++++++--------- 9 files changed, 45 insertions(+), 45 deletions(-) diff --git a/rust-lib/flowy-sdk/src/flowy_server.rs b/rust-lib/flowy-sdk/src/flowy_server.rs index 1db12a4f19..bcf6202d79 100644 --- a/rust-lib/flowy-sdk/src/flowy_server.rs +++ b/rust-lib/flowy-sdk/src/flowy_server.rs @@ -2,7 +2,7 @@ use flowy_user::{ entities::{SignInParams, SignUpParams, UserDetail}, errors::{ErrorBuilder, UserError, UserErrorCode}, prelude::UserServer, - sql_tables::User, + sql_tables::UserTable, }; pub type ArcFlowyServer = std::sync::Arc; @@ -14,9 +14,9 @@ pub struct FlowyServerMocker {} impl FlowyServer for FlowyServerMocker {} impl UserServer for FlowyServerMocker { - fn sign_up(&self, params: SignUpParams) -> Result { + fn sign_up(&self, params: SignUpParams) -> Result { let user_id = params.email.clone(); - Ok(User::new( + Ok(UserTable::new( user_id, params.name, params.email, @@ -24,9 +24,9 @@ impl UserServer for FlowyServerMocker { )) } - fn sign_in(&self, params: SignInParams) -> Result { + fn sign_in(&self, params: SignInParams) -> Result { let user_id = params.email.clone(); - Ok(User::new( + Ok(UserTable::new( user_id, "".to_owned(), params.email, diff --git a/rust-lib/flowy-user/src/entities/user_detail.rs b/rust-lib/flowy-user/src/entities/user_detail.rs index e59a421a7a..eaf1e4e99a 100644 --- a/rust-lib/flowy-user/src/entities/user_detail.rs +++ b/rust-lib/flowy-user/src/entities/user_detail.rs @@ -29,9 +29,9 @@ pub struct UserDetail { pub workspace: String, } -use crate::sql_tables::User; -impl std::convert::From for UserDetail { - fn from(user: User) -> Self { +use crate::sql_tables::UserTable; +impl std::convert::From for UserDetail { + fn from(user: UserTable) -> Self { UserDetail { id: user.id, email: user.email, diff --git a/rust-lib/flowy-user/src/services/user_session/user_server.rs b/rust-lib/flowy-user/src/services/user_session/user_server.rs index e54bd48217..c5c7f3aac9 100644 --- a/rust-lib/flowy-user/src/services/user_session/user_server.rs +++ b/rust-lib/flowy-user/src/services/user_session/user_server.rs @@ -1,12 +1,12 @@ use crate::{ entities::{SignInParams, SignUpParams, UserDetail}, errors::UserError, - sql_tables::User, + sql_tables::UserTable, }; pub trait UserServer { - fn sign_up(&self, params: SignUpParams) -> Result; - fn sign_in(&self, params: SignInParams) -> Result; + fn sign_up(&self, params: SignUpParams) -> Result; + fn sign_in(&self, params: SignInParams) -> Result; fn get_user_info(&self, user_id: &str) -> Result; fn sign_out(&self, user_id: &str) -> Result<(), UserError>; } diff --git a/rust-lib/flowy-user/src/services/user_session/user_session.rs b/rust-lib/flowy-user/src/services/user_session/user_session.rs index 64aa629fb0..e4a8dc663a 100644 --- a/rust-lib/flowy-user/src/services/user_session/user_session.rs +++ b/rust-lib/flowy-user/src/services/user_session/user_session.rs @@ -14,7 +14,7 @@ use crate::{ errors::{ErrorBuilder, UserError, UserErrorCode}, event::UserEvent::*, services::user_session::{database::UserDB, user_server::UserServer}, - sql_tables::{User, UserChangeset}, + sql_tables::{UserTable, UserTableChangeset}, }; use flowy_dispatch::prelude::{EventDispatch, ModuleRequest, ToBytes}; @@ -56,14 +56,14 @@ impl UserSession { self.database.get_connection(&user_id) } - pub fn sign_in(&self, params: SignInParams) -> Result { + pub fn sign_in(&self, params: SignInParams) -> Result { let user = self.server.sign_in(params)?; let _ = self.set_user_id(Some(user.id.clone()))?; self.save_user(user) } - pub fn sign_up(&self, params: SignUpParams) -> Result { + pub fn sign_up(&self, params: SignUpParams) -> Result { let user = self.server.sign_up(params)?; let _ = self.set_user_id(Some(user.id.clone()))?; self.save_user(user) @@ -84,7 +84,7 @@ impl UserSession { Ok(()) } - fn save_user(&self, user: User) -> Result { + fn save_user(&self, user: UserTable) -> Result { let conn = self.get_db_connection()?; let _ = diesel::insert_into(user_table::table) .values(user.clone()) @@ -94,7 +94,7 @@ impl UserSession { } pub fn update_user(&self, params: UpdateUserParams) -> Result { - let changeset = UserChangeset::new(params); + let changeset = UserTableChangeset::new(params); let conn = self.get_db_connection()?; diesel_update_table!(user_table, changeset, conn); @@ -106,7 +106,7 @@ impl UserSession { let user_id = self.get_user_id()?; let user = dsl::user_table .filter(user_table::id.eq(&user_id)) - .first::(&*(self.get_db_connection()?))?; + .first::(&*(self.get_db_connection()?))?; match self.server.get_user_info(&user_id) { Ok(_user_detail) => { diff --git a/rust-lib/flowy-user/src/sql_tables/user.rs b/rust-lib/flowy-user/src/sql_tables/user.rs index 826837e09d..7b2d7e9b62 100644 --- a/rust-lib/flowy-user/src/sql_tables/user.rs +++ b/rust-lib/flowy-user/src/sql_tables/user.rs @@ -3,7 +3,7 @@ use flowy_database::schema::user_table; #[derive(Clone, Default, Queryable, Identifiable, Insertable)] #[table_name = "user_table"] -pub struct User { +pub struct UserTable { pub(crate) id: String, pub(crate) name: String, pub(crate) password: String, @@ -11,7 +11,7 @@ pub struct User { pub(crate) workspace: String, } -impl User { +impl UserTable { pub fn new(id: String, name: String, email: String, password: String) -> Self { Self { id, @@ -30,7 +30,7 @@ impl User { #[derive(AsChangeset, Identifiable, Default, Debug)] #[table_name = "user_table"] -pub struct UserChangeset { +pub struct UserTableChangeset { pub id: String, pub workspace: Option, pub name: Option, @@ -38,9 +38,9 @@ pub struct UserChangeset { pub password: Option, } -impl UserChangeset { +impl UserTableChangeset { pub fn new(params: UpdateUserParams) -> Self { - UserChangeset { + UserTableChangeset { id: params.id, workspace: params.workspace, name: params.name, diff --git a/rust-lib/flowy-workspace/src/services/app_controller.rs b/rust-lib/flowy-workspace/src/services/app_controller.rs index cfa5327574..0c7636abcf 100644 --- a/rust-lib/flowy-workspace/src/services/app_controller.rs +++ b/rust-lib/flowy-workspace/src/services/app_controller.rs @@ -15,7 +15,7 @@ impl AppController { pub fn new(user: Arc) -> Self { Self { user } } pub fn save_app(&self, params: CreateAppParams) -> Result { - let app = App::new(params); + let app = AppTable::new(params); let conn = self.user.db_connection()?; let detail: AppDetail = app.clone().into(); @@ -26,7 +26,7 @@ impl AppController { } pub fn update_app(&self, params: UpdateAppParams) -> Result<(), WorkspaceError> { - let changeset = AppChangeset::new(params); + let changeset = AppTableChangeset::new(params); let conn = self.user.db_connection()?; diesel_update_table!(app_table, changeset, conn); Ok(()) diff --git a/rust-lib/flowy-workspace/src/services/workspace_controller.rs b/rust-lib/flowy-workspace/src/services/workspace_controller.rs index 5fdf48e2b1..8b5fadfdd4 100644 --- a/rust-lib/flowy-workspace/src/services/workspace_controller.rs +++ b/rust-lib/flowy-workspace/src/services/workspace_controller.rs @@ -16,7 +16,7 @@ impl WorkspaceController { &self, params: CreateWorkspaceParams, ) -> Result { - let workspace = Workspace::new(params); + let workspace = WorkspaceTable::new(params); let detail: WorkspaceDetail = workspace.clone().into(); let _ = diesel::insert_into(workspace_table::table) @@ -31,14 +31,14 @@ impl WorkspaceController { pub fn get_workspace( &self, workspace_id: &str, - ) -> DispatchFuture> { + ) -> DispatchFuture> { let user = self.user.clone(); let workspace_id = workspace_id.to_owned(); DispatchFuture { fut: Box::pin(async move { let workspace = dsl::workspace_table .filter(workspace_table::id.eq(&workspace_id)) - .first::(&*(user.db_connection()?))?; + .first::(&*(user.db_connection()?))?; // TODO: fetch workspace from remote server Ok(workspace) @@ -47,7 +47,7 @@ impl WorkspaceController { } pub fn update_workspace(&self, params: UpdateWorkspaceParams) -> Result<(), WorkspaceError> { - let changeset = WorkspaceChangeset::new(params); + let changeset = WorkspaceTableChangeset::new(params); let conn = self.user.db_connection()?; diesel_update_table!(workspace_table, changeset, conn); diff --git a/rust-lib/flowy-workspace/src/sql_tables/app/app.rs b/rust-lib/flowy-workspace/src/sql_tables/app/app.rs index 1354fad323..89b4b08f80 100644 --- a/rust-lib/flowy-workspace/src/sql_tables/app/app.rs +++ b/rust-lib/flowy-workspace/src/sql_tables/app/app.rs @@ -1,7 +1,7 @@ use crate::{ entities::app::{AppDetail, ColorStyle, CreateAppParams, UpdateAppParams}, impl_sql_binary_expression, - sql_tables::workspace::Workspace, + sql_tables::workspace::WorkspaceTable, }; use diesel::sql_types::Binary; use flowy_database::schema::app_table; @@ -20,10 +20,10 @@ use std::convert::TryInto; Insertable, Associations, )] -#[belongs_to(Workspace, foreign_key = "workspace_id")] +#[belongs_to(WorkspaceTable, foreign_key = "workspace_id")] #[table_name = "app_table"] #[serde(tag = "type")] -pub(crate) struct App { +pub(crate) struct AppTable { pub id: String, pub workspace_id: String, // equal to #[belongs_to(Workspace, foreign_key = "workspace_id")]. pub name: String, @@ -35,7 +35,7 @@ pub(crate) struct App { pub version: i64, } -impl App { +impl AppTable { pub fn new(params: CreateAppParams) -> Self { let app_id = uuid(); let time = timestamp(); @@ -87,16 +87,16 @@ impl_sql_binary_expression!(ColorStyleCol); #[derive(AsChangeset, Identifiable, Default, Debug)] #[table_name = "app_table"] -pub struct AppChangeset { +pub struct AppTableChangeset { pub id: String, pub workspace_id: Option, pub name: Option, pub desc: Option, } -impl AppChangeset { +impl AppTableChangeset { pub fn new(params: UpdateAppParams) -> Self { - AppChangeset { + AppTableChangeset { id: params.app_id, workspace_id: params.workspace_id, name: params.name, @@ -105,7 +105,7 @@ impl AppChangeset { } } -impl std::convert::Into for App { +impl std::convert::Into for AppTable { fn into(self) -> AppDetail { AppDetail { id: self.id, diff --git a/rust-lib/flowy-workspace/src/sql_tables/workspace/workspace.rs b/rust-lib/flowy-workspace/src/sql_tables/workspace/workspace.rs index 5ec20f2c20..2786b90938 100644 --- a/rust-lib/flowy-workspace/src/sql_tables/workspace/workspace.rs +++ b/rust-lib/flowy-workspace/src/sql_tables/workspace/workspace.rs @@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize}; #[derive(PartialEq, Clone, Serialize, Deserialize, Debug, Queryable, Identifiable, Insertable)] #[table_name = "workspace_table"] #[serde(tag = "type")] -pub struct Workspace { +pub struct WorkspaceTable { pub id: String, pub name: String, pub desc: String, @@ -16,20 +16,20 @@ pub struct Workspace { pub version: i64, } -impl Workspace { +impl WorkspaceTable { #[allow(dead_code)] pub fn new(params: CreateWorkspaceParams) -> Self { - let mut workspace = Workspace::default(); + let mut workspace = WorkspaceTable::default(); workspace.name = params.name; workspace.desc = params.desc; workspace } } -impl std::default::Default for Workspace { +impl std::default::Default for WorkspaceTable { fn default() -> Self { let time = timestamp(); - Workspace { + WorkspaceTable { id: uuid(), name: String::default(), desc: String::default(), @@ -43,15 +43,15 @@ impl std::default::Default for Workspace { #[derive(AsChangeset, Identifiable, Clone, Default, Debug)] #[table_name = "workspace_table"] -pub struct WorkspaceChangeset { +pub struct WorkspaceTableChangeset { pub id: String, pub name: Option, pub desc: Option, } -impl WorkspaceChangeset { +impl WorkspaceTableChangeset { pub fn new(params: UpdateWorkspaceParams) -> Self { - WorkspaceChangeset { + WorkspaceTableChangeset { id: params.id, name: params.name, desc: params.desc, @@ -59,7 +59,7 @@ impl WorkspaceChangeset { } } -impl std::convert::Into for Workspace { +impl std::convert::Into for WorkspaceTable { fn into(self) -> WorkspaceDetail { WorkspaceDetail { id: self.id, From 55fad84590725d28ef6ca7f559f476c7208321ba Mon Sep 17 00:00:00 2001 From: appflowy Date: Mon, 19 Jul 2021 21:05:49 +0800 Subject: [PATCH 28/30] add create app test & create default workspace when user login at first time --- .../protobuf/flowy-user/errors.pbenum.dart | 2 + .../protobuf/flowy-user/errors.pbjson.dart | 3 +- .../flowy-workspace/event.pbenum.dart | 2 + .../flowy-workspace/event.pbjson.dart | 3 +- rust-lib/flowy-dispatch/src/dispatch.rs | 2 +- .../flowy-dispatch/src/request/payload.rs | 1 - rust-lib/flowy-sdk/src/flowy_server.rs | 39 ++++++++- rust-lib/flowy-sdk/src/lib.rs | 1 - rust-lib/flowy-sdk/src/module.rs | 4 +- rust-lib/flowy-sqlite/src/pool.rs | 2 +- rust-lib/flowy-test/src/builder.rs | 15 ++-- rust-lib/flowy-user/src/errors.rs | 33 +++++++- .../flowy-user/src/handlers/auth_handler.rs | 4 +- .../flowy-user/src/protobuf/model/errors.rs | 82 ++++++++++--------- .../src/protobuf/proto/errors.proto | 1 + .../src/services/user_session/user_server.rs | 13 ++- .../src/services/user_session/user_session.rs | 37 +++++++-- .../flowy-user/tests/event/sign_up_test.rs | 3 - .../tests/event/user_status_test.rs | 7 +- rust-lib/flowy-workspace/src/event.rs | 4 + rust-lib/flowy-workspace/src/module.rs | 1 + .../src/protobuf/model/event.rs | 22 +++-- .../src/protobuf/proto/event.proto | 1 + .../flowy-workspace/tests/event/app_test.rs | 48 +++++++---- .../tests/event/workspace_test.rs | 49 +++++++---- 25 files changed, 266 insertions(+), 113 deletions(-) diff --git a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-user/errors.pbenum.dart b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-user/errors.pbenum.dart index 3743123065..28205f8984 100644 --- a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-user/errors.pbenum.dart +++ b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-user/errors.pbenum.dart @@ -24,6 +24,7 @@ class UserErrorCode extends $pb.ProtobufEnum { static const UserErrorCode UserNameInvalid = UserErrorCode._(22, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'UserNameInvalid'); static const UserErrorCode UserWorkspaceInvalid = UserErrorCode._(23, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'UserWorkspaceInvalid'); static const UserErrorCode UserIdInvalid = UserErrorCode._(24, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'UserIdInvalid'); + static const UserErrorCode CreateDefaultWorkspaceFailed = UserErrorCode._(25, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'CreateDefaultWorkspaceFailed'); static const $core.List values = [ Unknown, @@ -40,6 +41,7 @@ class UserErrorCode extends $pb.ProtobufEnum { UserNameInvalid, UserWorkspaceInvalid, UserIdInvalid, + CreateDefaultWorkspaceFailed, ]; static final $core.Map<$core.int, UserErrorCode> _byValue = $pb.ProtobufEnum.initByValue(values); diff --git a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-user/errors.pbjson.dart b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-user/errors.pbjson.dart index 1e2eb92c66..70e80819c6 100644 --- a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-user/errors.pbjson.dart +++ b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-user/errors.pbjson.dart @@ -26,11 +26,12 @@ const UserErrorCode$json = const { const {'1': 'UserNameInvalid', '2': 22}, const {'1': 'UserWorkspaceInvalid', '2': 23}, const {'1': 'UserIdInvalid', '2': 24}, + const {'1': 'CreateDefaultWorkspaceFailed', '2': 25}, ], }; /// Descriptor for `UserErrorCode`. Decode as a `google.protobuf.EnumDescriptorProto`. -final $typed_data.Uint8List userErrorCodeDescriptor = $convert.base64Decode('Cg1Vc2VyRXJyb3JDb2RlEgsKB1Vua25vd24QABIaChZVc2VyRGF0YWJhc2VJbml0RmFpbGVkEAESGwoXVXNlckRhdGFiYXNlV3JpdGVMb2NrZWQQAhIaChZVc2VyRGF0YWJhc2VSZWFkTG9ja2VkEAMSGwoXVXNlckRhdGFiYXNlRGlkTm90TWF0Y2gQBBIdChlVc2VyRGF0YWJhc2VJbnRlcm5hbEVycm9yEAUSEwoPVXNlck5vdExvZ2luWWV0EAoSFwoTUmVhZEN1cnJlbnRJZEZhaWxlZBALEhgKFFdyaXRlQ3VycmVudElkRmFpbGVkEAwSEAoMRW1haWxJbnZhbGlkEBQSEwoPUGFzc3dvcmRJbnZhbGlkEBUSEwoPVXNlck5hbWVJbnZhbGlkEBYSGAoUVXNlcldvcmtzcGFjZUludmFsaWQQFxIRCg1Vc2VySWRJbnZhbGlkEBg='); +final $typed_data.Uint8List userErrorCodeDescriptor = $convert.base64Decode('Cg1Vc2VyRXJyb3JDb2RlEgsKB1Vua25vd24QABIaChZVc2VyRGF0YWJhc2VJbml0RmFpbGVkEAESGwoXVXNlckRhdGFiYXNlV3JpdGVMb2NrZWQQAhIaChZVc2VyRGF0YWJhc2VSZWFkTG9ja2VkEAMSGwoXVXNlckRhdGFiYXNlRGlkTm90TWF0Y2gQBBIdChlVc2VyRGF0YWJhc2VJbnRlcm5hbEVycm9yEAUSEwoPVXNlck5vdExvZ2luWWV0EAoSFwoTUmVhZEN1cnJlbnRJZEZhaWxlZBALEhgKFFdyaXRlQ3VycmVudElkRmFpbGVkEAwSEAoMRW1haWxJbnZhbGlkEBQSEwoPUGFzc3dvcmRJbnZhbGlkEBUSEwoPVXNlck5hbWVJbnZhbGlkEBYSGAoUVXNlcldvcmtzcGFjZUludmFsaWQQFxIRCg1Vc2VySWRJbnZhbGlkEBgSIAocQ3JlYXRlRGVmYXVsdFdvcmtzcGFjZUZhaWxlZBAZ'); @$core.Deprecated('Use userErrorDescriptor instead') const UserError$json = const { '1': 'UserError', diff --git a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/event.pbenum.dart b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/event.pbenum.dart index 02c50ad27f..e4f5d77688 100644 --- a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/event.pbenum.dart +++ b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/event.pbenum.dart @@ -12,10 +12,12 @@ import 'package:protobuf/protobuf.dart' as $pb; class WorkspaceEvent extends $pb.ProtobufEnum { static const WorkspaceEvent CreateWorkspace = WorkspaceEvent._(0, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'CreateWorkspace'); static const WorkspaceEvent GetWorkspaceDetail = WorkspaceEvent._(1, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'GetWorkspaceDetail'); + static const WorkspaceEvent CreateApp = WorkspaceEvent._(101, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'CreateApp'); static const $core.List values = [ CreateWorkspace, GetWorkspaceDetail, + CreateApp, ]; static final $core.Map<$core.int, WorkspaceEvent> _byValue = $pb.ProtobufEnum.initByValue(values); diff --git a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/event.pbjson.dart b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/event.pbjson.dart index 86296a37ea..4cb911eaf0 100644 --- a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/event.pbjson.dart +++ b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/event.pbjson.dart @@ -14,8 +14,9 @@ const WorkspaceEvent$json = const { '2': const [ const {'1': 'CreateWorkspace', '2': 0}, const {'1': 'GetWorkspaceDetail', '2': 1}, + const {'1': 'CreateApp', '2': 101}, ], }; /// Descriptor for `WorkspaceEvent`. Decode as a `google.protobuf.EnumDescriptorProto`. -final $typed_data.Uint8List workspaceEventDescriptor = $convert.base64Decode('Cg5Xb3Jrc3BhY2VFdmVudBITCg9DcmVhdGVXb3Jrc3BhY2UQABIWChJHZXRXb3Jrc3BhY2VEZXRhaWwQAQ=='); +final $typed_data.Uint8List workspaceEventDescriptor = $convert.base64Decode('Cg5Xb3Jrc3BhY2VFdmVudBITCg9DcmVhdGVXb3Jrc3BhY2UQABIWChJHZXRXb3Jrc3BhY2VEZXRhaWwQARINCglDcmVhdGVBcHAQZQ=='); diff --git a/rust-lib/flowy-dispatch/src/dispatch.rs b/rust-lib/flowy-dispatch/src/dispatch.rs index 308ba1f164..aac9c410a7 100644 --- a/rust-lib/flowy-dispatch/src/dispatch.rs +++ b/rust-lib/flowy-dispatch/src/dispatch.rs @@ -1,7 +1,7 @@ use crate::{ errors::{DispatchError, Error, InternalError}, module::{as_module_map, Module, ModuleMap, ModuleRequest}, - response::{EventResponse, Responder}, + response::EventResponse, service::{Service, ServiceFactory}, util::tokio_default_runtime, }; diff --git a/rust-lib/flowy-dispatch/src/request/payload.rs b/rust-lib/flowy-dispatch/src/request/payload.rs index 2efbed6538..374d3af999 100644 --- a/rust-lib/flowy-dispatch/src/request/payload.rs +++ b/rust-lib/flowy-dispatch/src/request/payload.rs @@ -1,4 +1,3 @@ -use crate::byte_trait::ToBytes; use bytes::Bytes; use std::{fmt, fmt::Formatter}; diff --git a/rust-lib/flowy-sdk/src/flowy_server.rs b/rust-lib/flowy-sdk/src/flowy_server.rs index bcf6202d79..18df0ef6a6 100644 --- a/rust-lib/flowy-sdk/src/flowy_server.rs +++ b/rust-lib/flowy-sdk/src/flowy_server.rs @@ -1,9 +1,15 @@ +use flowy_dispatch::prelude::{DispatchFuture, EventDispatch, ModuleRequest, ToBytes}; use flowy_user::{ entities::{SignInParams, SignUpParams, UserDetail}, errors::{ErrorBuilder, UserError, UserErrorCode}, prelude::UserServer, sql_tables::UserTable, }; +use flowy_workspace::{ + entities::workspace::{CreateWorkspaceRequest, WorkspaceDetail}, + errors::WorkspaceError, + event::WorkspaceEvent::CreateWorkspace, +}; pub type ArcFlowyServer = std::sync::Arc; @@ -34,11 +40,40 @@ impl UserServer for FlowyServerMocker { )) } + fn sign_out(&self, _user_id: &str) -> Result<(), UserError> { + Err(ErrorBuilder::new(UserErrorCode::Unknown).build()) + } + fn get_user_info(&self, _user_id: &str) -> Result { Err(ErrorBuilder::new(UserErrorCode::Unknown).build()) } - fn sign_out(&self, _user_id: &str) -> Result<(), UserError> { - Err(ErrorBuilder::new(UserErrorCode::Unknown).build()) + fn create_workspace( + &self, + name: &str, + desc: &str, + _user_id: &str, + ) -> DispatchFuture> { + let payload: Vec = CreateWorkspaceRequest { + name: name.to_string(), + desc: desc.to_string(), + } + .into_bytes() + .unwrap(); + + let request = ModuleRequest::new(CreateWorkspace).payload(payload); + DispatchFuture { + fut: Box::pin(async move { + let _ = EventDispatch::async_send(request) + .await + .parse::() + .map_err(|e| { + ErrorBuilder::new(UserErrorCode::CreateDefaultWorkspaceFailed) + .error(e) + .build() + })?; + Ok(()) + }), + } } } diff --git a/rust-lib/flowy-sdk/src/lib.rs b/rust-lib/flowy-sdk/src/lib.rs index 0c73248108..581b20d05e 100644 --- a/rust-lib/flowy-sdk/src/lib.rs +++ b/rust-lib/flowy-sdk/src/lib.rs @@ -3,7 +3,6 @@ mod flowy_server; pub mod module; pub use crate::flowy_server::{ArcFlowyServer, FlowyServerMocker}; -use deps_resolve::*; use flowy_dispatch::prelude::*; use module::build_modules; pub use module::*; diff --git a/rust-lib/flowy-sdk/src/module.rs b/rust-lib/flowy-sdk/src/module.rs index 7fceeefb2e..bdc712005f 100644 --- a/rust-lib/flowy-sdk/src/module.rs +++ b/rust-lib/flowy-sdk/src/module.rs @@ -1,11 +1,9 @@ use crate::flowy_server::{ArcFlowyServer, FlowyServerMocker}; -use flowy_database::DBConnection; -use flowy_dispatch::prelude::{DispatchFuture, Module}; +use flowy_dispatch::prelude::Module; use flowy_user::prelude::*; use flowy_workspace::prelude::*; use crate::deps_resolve::WorkspaceUserImpl; -use flowy_workspace::entities::workspace::UserWorkspace; use std::sync::Arc; pub struct ModuleConfig { diff --git a/rust-lib/flowy-sqlite/src/pool.rs b/rust-lib/flowy-sqlite/src/pool.rs index f9f8646d58..62820a9362 100644 --- a/rust-lib/flowy-sqlite/src/pool.rs +++ b/rust-lib/flowy-sqlite/src/pool.rs @@ -1,4 +1,4 @@ -use crate::{conn_ext::*, errors::*, pragma::*}; +use crate::{errors::*, pragma::*}; use diesel::{connection::Connection, SqliteConnection}; use r2d2::{CustomizeConnection, ManageConnection, Pool}; use scheduled_thread_pool::ScheduledThreadPool; diff --git a/rust-lib/flowy-test/src/builder.rs b/rust-lib/flowy-test/src/builder.rs index 8c89780c07..e7a9c3b1b0 100644 --- a/rust-lib/flowy-test/src/builder.rs +++ b/rust-lib/flowy-test/src/builder.rs @@ -11,17 +11,19 @@ use crate::{ }; use flowy_user::errors::UserError; use flowy_workspace::errors::WorkspaceError; -use std::marker::PhantomData; +use std::{marker::PhantomData, sync::Once}; +static INIT: Once = Once::new(); pub type WorkspaceTestBuilder = TestBuilder>; impl WorkspaceTestBuilder { pub fn new() -> Self { - let builder = Self { + let mut builder = Self { tester: Box::new(FixedUserTester::::new()), user_detail: None, }; - builder.login_if_need() + INIT.call_once(|| builder.login_if_need()); + builder } } @@ -36,7 +38,7 @@ impl UserTestBuilder { builder } - pub fn reset(mut self) -> Self { self.logout().login() } + pub fn reset(mut self) -> Self { self.login() } } pub struct TestBuilder { @@ -54,14 +56,13 @@ where self } - pub fn login_if_need(mut self) -> Self { + pub fn login_if_need(&mut self) { let user_detail = self.tester.login_if_need(); self.user_detail = Some(user_detail); - self } pub fn logout(self) -> Self { - self.tester.logout(); + // self.tester.logout(); self } diff --git a/rust-lib/flowy-user/src/errors.rs b/rust-lib/flowy-user/src/errors.rs index b466090fc9..384793468f 100644 --- a/rust-lib/flowy-user/src/errors.rs +++ b/rust-lib/flowy-user/src/errors.rs @@ -53,6 +53,8 @@ pub enum UserErrorCode { UserWorkspaceInvalid = 23, #[display(fmt = "User id is invalid")] UserIdInvalid = 24, + #[display(fmt = "Create user default workspace failed")] + CreateDefaultWorkspaceFailed = 25, } impl std::default::Default for UserErrorCode { @@ -66,9 +68,38 @@ impl std::convert::From for UserError { .build() } } - +use diesel::result::DatabaseErrorKind; impl std::convert::From for UserError { fn from(error: flowy_sqlite::Error) -> Self { + // match error.kind() { + // ErrorKind::Msg(_) => {}, + // ErrorKind::R2D2(_) => {}, + // ErrorKind::Migrations(_) => {}, + // ErrorKind::Diesel(diesel_err) => match diesel_err { + // Error::InvalidCString(_) => {}, + // Error::DatabaseError(kind, _) => { + // match kind { + // DatabaseErrorKind::UniqueViolation => { + // + // } + // _ => {} + // } + // + // }, + // Error::NotFound => {}, + // Error::QueryBuilderError(_) => {}, + // Error::DeserializationError(_) => {}, + // Error::SerializationError(_) => {}, + // Error::RollbackTransaction => {}, + // Error::AlreadyInTransaction => {}, + // Error::__Nonexhaustive => {}, + // }, + // ErrorKind::Connection(_) => {}, + // ErrorKind::Io(_) => {}, + // ErrorKind::UnknownMigrationExists(_) => {}, + // ErrorKind::__Nonexhaustive { .. } => {}, + // } + ErrorBuilder::new(UserErrorCode::UserDatabaseInternalError) .error(error) .build() diff --git a/rust-lib/flowy-user/src/handlers/auth_handler.rs b/rust-lib/flowy-user/src/handlers/auth_handler.rs index 03d2be363b..601d8b6f09 100644 --- a/rust-lib/flowy-user/src/handlers/auth_handler.rs +++ b/rust-lib/flowy-user/src/handlers/auth_handler.rs @@ -15,7 +15,7 @@ pub async fn user_sign_in_handler( session: ModuleData>, ) -> ResponseResult { let params: SignInParams = data.into_inner().try_into()?; - let user = session.sign_in(params)?; + let user = session.sign_in(params).await?; let user_detail = UserDetail::from(user); response_ok(user_detail) } @@ -33,7 +33,7 @@ pub async fn user_sign_up_handler( session: ModuleData>, ) -> ResponseResult { let params: SignUpParams = data.into_inner().try_into()?; - let user = session.sign_up(params)?; + let user = session.sign_up(params).await?; let user_detail = UserDetail::from(user); response_ok(user_detail) } diff --git a/rust-lib/flowy-user/src/protobuf/model/errors.rs b/rust-lib/flowy-user/src/protobuf/model/errors.rs index ef1ed3e7b4..5c5e9468e0 100644 --- a/rust-lib/flowy-user/src/protobuf/model/errors.rs +++ b/rust-lib/flowy-user/src/protobuf/model/errors.rs @@ -229,6 +229,7 @@ pub enum UserErrorCode { UserNameInvalid = 22, UserWorkspaceInvalid = 23, UserIdInvalid = 24, + CreateDefaultWorkspaceFailed = 25, } impl ::protobuf::ProtobufEnum for UserErrorCode { @@ -252,6 +253,7 @@ impl ::protobuf::ProtobufEnum for UserErrorCode { 22 => ::std::option::Option::Some(UserErrorCode::UserNameInvalid), 23 => ::std::option::Option::Some(UserErrorCode::UserWorkspaceInvalid), 24 => ::std::option::Option::Some(UserErrorCode::UserIdInvalid), + 25 => ::std::option::Option::Some(UserErrorCode::CreateDefaultWorkspaceFailed), _ => ::std::option::Option::None } } @@ -272,6 +274,7 @@ impl ::protobuf::ProtobufEnum for UserErrorCode { UserErrorCode::UserNameInvalid, UserErrorCode::UserWorkspaceInvalid, UserErrorCode::UserIdInvalid, + UserErrorCode::CreateDefaultWorkspaceFailed, ]; values } @@ -302,7 +305,7 @@ impl ::protobuf::reflect::ProtobufValue for UserErrorCode { static file_descriptor_proto_data: &'static [u8] = b"\ \n\x0cerrors.proto\"A\n\tUserError\x12\"\n\x04code\x18\x01\x20\x01(\x0e2\ \x0e.UserErrorCodeR\x04code\x12\x10\n\x03msg\x18\x02\x20\x01(\tR\x03msg*\ - \xde\x02\n\rUserErrorCode\x12\x0b\n\x07Unknown\x10\0\x12\x1a\n\x16UserDa\ + \x80\x03\n\rUserErrorCode\x12\x0b\n\x07Unknown\x10\0\x12\x1a\n\x16UserDa\ tabaseInitFailed\x10\x01\x12\x1b\n\x17UserDatabaseWriteLocked\x10\x02\ \x12\x1a\n\x16UserDatabaseReadLocked\x10\x03\x12\x1b\n\x17UserDatabaseDi\ dNotMatch\x10\x04\x12\x1d\n\x19UserDatabaseInternalError\x10\x05\x12\x13\ @@ -310,43 +313,46 @@ static file_descriptor_proto_data: &'static [u8] = b"\ \x18\n\x14WriteCurrentIdFailed\x10\x0c\x12\x10\n\x0cEmailInvalid\x10\x14\ \x12\x13\n\x0fPasswordInvalid\x10\x15\x12\x13\n\x0fUserNameInvalid\x10\ \x16\x12\x18\n\x14UserWorkspaceInvalid\x10\x17\x12\x11\n\rUserIdInvalid\ - \x10\x18J\xee\x05\n\x06\x12\x04\0\0\x15\x01\n\x08\n\x01\x0c\x12\x03\0\0\ - \x12\n\n\n\x02\x04\0\x12\x04\x02\0\x05\x01\n\n\n\x03\x04\0\x01\x12\x03\ - \x02\x08\x11\n\x0b\n\x04\x04\0\x02\0\x12\x03\x03\x04\x1b\n\x0c\n\x05\x04\ - \0\x02\0\x06\x12\x03\x03\x04\x11\n\x0c\n\x05\x04\0\x02\0\x01\x12\x03\x03\ - \x12\x16\n\x0c\n\x05\x04\0\x02\0\x03\x12\x03\x03\x19\x1a\n\x0b\n\x04\x04\ - \0\x02\x01\x12\x03\x04\x04\x13\n\x0c\n\x05\x04\0\x02\x01\x05\x12\x03\x04\ - \x04\n\n\x0c\n\x05\x04\0\x02\x01\x01\x12\x03\x04\x0b\x0e\n\x0c\n\x05\x04\ - \0\x02\x01\x03\x12\x03\x04\x11\x12\n\n\n\x02\x05\0\x12\x04\x06\0\x15\x01\ - \n\n\n\x03\x05\0\x01\x12\x03\x06\x05\x12\n\x0b\n\x04\x05\0\x02\0\x12\x03\ - \x07\x04\x10\n\x0c\n\x05\x05\0\x02\0\x01\x12\x03\x07\x04\x0b\n\x0c\n\x05\ - \x05\0\x02\0\x02\x12\x03\x07\x0e\x0f\n\x0b\n\x04\x05\0\x02\x01\x12\x03\ - \x08\x04\x1f\n\x0c\n\x05\x05\0\x02\x01\x01\x12\x03\x08\x04\x1a\n\x0c\n\ - \x05\x05\0\x02\x01\x02\x12\x03\x08\x1d\x1e\n\x0b\n\x04\x05\0\x02\x02\x12\ - \x03\t\x04\x20\n\x0c\n\x05\x05\0\x02\x02\x01\x12\x03\t\x04\x1b\n\x0c\n\ - \x05\x05\0\x02\x02\x02\x12\x03\t\x1e\x1f\n\x0b\n\x04\x05\0\x02\x03\x12\ - \x03\n\x04\x1f\n\x0c\n\x05\x05\0\x02\x03\x01\x12\x03\n\x04\x1a\n\x0c\n\ - \x05\x05\0\x02\x03\x02\x12\x03\n\x1d\x1e\n\x0b\n\x04\x05\0\x02\x04\x12\ - \x03\x0b\x04\x20\n\x0c\n\x05\x05\0\x02\x04\x01\x12\x03\x0b\x04\x1b\n\x0c\ - \n\x05\x05\0\x02\x04\x02\x12\x03\x0b\x1e\x1f\n\x0b\n\x04\x05\0\x02\x05\ - \x12\x03\x0c\x04\"\n\x0c\n\x05\x05\0\x02\x05\x01\x12\x03\x0c\x04\x1d\n\ - \x0c\n\x05\x05\0\x02\x05\x02\x12\x03\x0c\x20!\n\x0b\n\x04\x05\0\x02\x06\ - \x12\x03\r\x04\x19\n\x0c\n\x05\x05\0\x02\x06\x01\x12\x03\r\x04\x13\n\x0c\ - \n\x05\x05\0\x02\x06\x02\x12\x03\r\x16\x18\n\x0b\n\x04\x05\0\x02\x07\x12\ - \x03\x0e\x04\x1d\n\x0c\n\x05\x05\0\x02\x07\x01\x12\x03\x0e\x04\x17\n\x0c\ - \n\x05\x05\0\x02\x07\x02\x12\x03\x0e\x1a\x1c\n\x0b\n\x04\x05\0\x02\x08\ - \x12\x03\x0f\x04\x1e\n\x0c\n\x05\x05\0\x02\x08\x01\x12\x03\x0f\x04\x18\n\ - \x0c\n\x05\x05\0\x02\x08\x02\x12\x03\x0f\x1b\x1d\n\x0b\n\x04\x05\0\x02\t\ - \x12\x03\x10\x04\x16\n\x0c\n\x05\x05\0\x02\t\x01\x12\x03\x10\x04\x10\n\ - \x0c\n\x05\x05\0\x02\t\x02\x12\x03\x10\x13\x15\n\x0b\n\x04\x05\0\x02\n\ - \x12\x03\x11\x04\x19\n\x0c\n\x05\x05\0\x02\n\x01\x12\x03\x11\x04\x13\n\ - \x0c\n\x05\x05\0\x02\n\x02\x12\x03\x11\x16\x18\n\x0b\n\x04\x05\0\x02\x0b\ - \x12\x03\x12\x04\x19\n\x0c\n\x05\x05\0\x02\x0b\x01\x12\x03\x12\x04\x13\n\ - \x0c\n\x05\x05\0\x02\x0b\x02\x12\x03\x12\x16\x18\n\x0b\n\x04\x05\0\x02\ - \x0c\x12\x03\x13\x04\x1e\n\x0c\n\x05\x05\0\x02\x0c\x01\x12\x03\x13\x04\ - \x18\n\x0c\n\x05\x05\0\x02\x0c\x02\x12\x03\x13\x1b\x1d\n\x0b\n\x04\x05\0\ - \x02\r\x12\x03\x14\x04\x17\n\x0c\n\x05\x05\0\x02\r\x01\x12\x03\x14\x04\ - \x11\n\x0c\n\x05\x05\0\x02\r\x02\x12\x03\x14\x14\x16b\x06proto3\ + \x10\x18\x12\x20\n\x1cCreateDefaultWorkspaceFailed\x10\x19J\x97\x06\n\ + \x06\x12\x04\0\0\x16\x01\n\x08\n\x01\x0c\x12\x03\0\0\x12\n\n\n\x02\x04\0\ + \x12\x04\x02\0\x05\x01\n\n\n\x03\x04\0\x01\x12\x03\x02\x08\x11\n\x0b\n\ + \x04\x04\0\x02\0\x12\x03\x03\x04\x1b\n\x0c\n\x05\x04\0\x02\0\x06\x12\x03\ + \x03\x04\x11\n\x0c\n\x05\x04\0\x02\0\x01\x12\x03\x03\x12\x16\n\x0c\n\x05\ + \x04\0\x02\0\x03\x12\x03\x03\x19\x1a\n\x0b\n\x04\x04\0\x02\x01\x12\x03\ + \x04\x04\x13\n\x0c\n\x05\x04\0\x02\x01\x05\x12\x03\x04\x04\n\n\x0c\n\x05\ + \x04\0\x02\x01\x01\x12\x03\x04\x0b\x0e\n\x0c\n\x05\x04\0\x02\x01\x03\x12\ + \x03\x04\x11\x12\n\n\n\x02\x05\0\x12\x04\x06\0\x16\x01\n\n\n\x03\x05\0\ + \x01\x12\x03\x06\x05\x12\n\x0b\n\x04\x05\0\x02\0\x12\x03\x07\x04\x10\n\ + \x0c\n\x05\x05\0\x02\0\x01\x12\x03\x07\x04\x0b\n\x0c\n\x05\x05\0\x02\0\ + \x02\x12\x03\x07\x0e\x0f\n\x0b\n\x04\x05\0\x02\x01\x12\x03\x08\x04\x1f\n\ + \x0c\n\x05\x05\0\x02\x01\x01\x12\x03\x08\x04\x1a\n\x0c\n\x05\x05\0\x02\ + \x01\x02\x12\x03\x08\x1d\x1e\n\x0b\n\x04\x05\0\x02\x02\x12\x03\t\x04\x20\ + \n\x0c\n\x05\x05\0\x02\x02\x01\x12\x03\t\x04\x1b\n\x0c\n\x05\x05\0\x02\ + \x02\x02\x12\x03\t\x1e\x1f\n\x0b\n\x04\x05\0\x02\x03\x12\x03\n\x04\x1f\n\ + \x0c\n\x05\x05\0\x02\x03\x01\x12\x03\n\x04\x1a\n\x0c\n\x05\x05\0\x02\x03\ + \x02\x12\x03\n\x1d\x1e\n\x0b\n\x04\x05\0\x02\x04\x12\x03\x0b\x04\x20\n\ + \x0c\n\x05\x05\0\x02\x04\x01\x12\x03\x0b\x04\x1b\n\x0c\n\x05\x05\0\x02\ + \x04\x02\x12\x03\x0b\x1e\x1f\n\x0b\n\x04\x05\0\x02\x05\x12\x03\x0c\x04\"\ + \n\x0c\n\x05\x05\0\x02\x05\x01\x12\x03\x0c\x04\x1d\n\x0c\n\x05\x05\0\x02\ + \x05\x02\x12\x03\x0c\x20!\n\x0b\n\x04\x05\0\x02\x06\x12\x03\r\x04\x19\n\ + \x0c\n\x05\x05\0\x02\x06\x01\x12\x03\r\x04\x13\n\x0c\n\x05\x05\0\x02\x06\ + \x02\x12\x03\r\x16\x18\n\x0b\n\x04\x05\0\x02\x07\x12\x03\x0e\x04\x1d\n\ + \x0c\n\x05\x05\0\x02\x07\x01\x12\x03\x0e\x04\x17\n\x0c\n\x05\x05\0\x02\ + \x07\x02\x12\x03\x0e\x1a\x1c\n\x0b\n\x04\x05\0\x02\x08\x12\x03\x0f\x04\ + \x1e\n\x0c\n\x05\x05\0\x02\x08\x01\x12\x03\x0f\x04\x18\n\x0c\n\x05\x05\0\ + \x02\x08\x02\x12\x03\x0f\x1b\x1d\n\x0b\n\x04\x05\0\x02\t\x12\x03\x10\x04\ + \x16\n\x0c\n\x05\x05\0\x02\t\x01\x12\x03\x10\x04\x10\n\x0c\n\x05\x05\0\ + \x02\t\x02\x12\x03\x10\x13\x15\n\x0b\n\x04\x05\0\x02\n\x12\x03\x11\x04\ + \x19\n\x0c\n\x05\x05\0\x02\n\x01\x12\x03\x11\x04\x13\n\x0c\n\x05\x05\0\ + \x02\n\x02\x12\x03\x11\x16\x18\n\x0b\n\x04\x05\0\x02\x0b\x12\x03\x12\x04\ + \x19\n\x0c\n\x05\x05\0\x02\x0b\x01\x12\x03\x12\x04\x13\n\x0c\n\x05\x05\0\ + \x02\x0b\x02\x12\x03\x12\x16\x18\n\x0b\n\x04\x05\0\x02\x0c\x12\x03\x13\ + \x04\x1e\n\x0c\n\x05\x05\0\x02\x0c\x01\x12\x03\x13\x04\x18\n\x0c\n\x05\ + \x05\0\x02\x0c\x02\x12\x03\x13\x1b\x1d\n\x0b\n\x04\x05\0\x02\r\x12\x03\ + \x14\x04\x17\n\x0c\n\x05\x05\0\x02\r\x01\x12\x03\x14\x04\x11\n\x0c\n\x05\ + \x05\0\x02\r\x02\x12\x03\x14\x14\x16\n\x0b\n\x04\x05\0\x02\x0e\x12\x03\ + \x15\x04&\n\x0c\n\x05\x05\0\x02\x0e\x01\x12\x03\x15\x04\x20\n\x0c\n\x05\ + \x05\0\x02\x0e\x02\x12\x03\x15#%b\x06proto3\ "; static file_descriptor_proto_lazy: ::protobuf::rt::LazyV2<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::rt::LazyV2::INIT; diff --git a/rust-lib/flowy-user/src/protobuf/proto/errors.proto b/rust-lib/flowy-user/src/protobuf/proto/errors.proto index 9a53106237..1e644873fa 100644 --- a/rust-lib/flowy-user/src/protobuf/proto/errors.proto +++ b/rust-lib/flowy-user/src/protobuf/proto/errors.proto @@ -19,4 +19,5 @@ enum UserErrorCode { UserNameInvalid = 22; UserWorkspaceInvalid = 23; UserIdInvalid = 24; + CreateDefaultWorkspaceFailed = 25; } diff --git a/rust-lib/flowy-user/src/services/user_session/user_server.rs b/rust-lib/flowy-user/src/services/user_session/user_server.rs index c5c7f3aac9..ab9085b535 100644 --- a/rust-lib/flowy-user/src/services/user_session/user_server.rs +++ b/rust-lib/flowy-user/src/services/user_session/user_server.rs @@ -3,10 +3,21 @@ use crate::{ errors::UserError, sql_tables::UserTable, }; +use flowy_dispatch::prelude::DispatchFuture; pub trait UserServer { fn sign_up(&self, params: SignUpParams) -> Result; + fn sign_in(&self, params: SignInParams) -> Result; - fn get_user_info(&self, user_id: &str) -> Result; + fn sign_out(&self, user_id: &str) -> Result<(), UserError>; + + fn get_user_info(&self, user_id: &str) -> Result; + + fn create_workspace( + &self, + name: &str, + desc: &str, + user_id: &str, + ) -> DispatchFuture>; } diff --git a/rust-lib/flowy-user/src/services/user_session/user_session.rs b/rust-lib/flowy-user/src/services/user_session/user_session.rs index e4a8dc663a..a226a3d279 100644 --- a/rust-lib/flowy-user/src/services/user_session/user_session.rs +++ b/rust-lib/flowy-user/src/services/user_session/user_session.rs @@ -18,6 +18,10 @@ use crate::{ }; use flowy_dispatch::prelude::{EventDispatch, ModuleRequest, ToBytes}; +const DEFAULT_WORKSPACE_NAME: &'static str = "My workspace"; +const DEFAULT_WORKSPACE_DESC: &'static str = "This is your first workspace"; +const DEFAULT_WORKSPACE: &'static str = "Default_Workspace"; + pub struct UserSessionConfig { root_dir: String, } @@ -56,17 +60,25 @@ impl UserSession { self.database.get_connection(&user_id) } - pub fn sign_in(&self, params: SignInParams) -> Result { + pub async fn sign_in(&self, params: SignInParams) -> Result { let user = self.server.sign_in(params)?; let _ = self.set_user_id(Some(user.id.clone()))?; - self.save_user(user) + let user_table = self.save_user(user)?; + let _ = self + .create_default_workspace_if_need(&user_table.id) + .await?; + Ok(user_table) } - pub fn sign_up(&self, params: SignUpParams) -> Result { + pub async fn sign_up(&self, params: SignUpParams) -> Result { let user = self.server.sign_up(params)?; let _ = self.set_user_id(Some(user.id.clone()))?; - self.save_user(user) + let user_table = self.save_user(user)?; + let _ = self + .create_default_workspace_if_need(&user_table.id) + .await?; + Ok(user_table) } pub fn sign_out(&self) -> Result<(), UserError> { @@ -147,7 +159,7 @@ impl UserSession { if user_id.is_none() { user_id = KVStore::get_str(USER_ID_CACHE_KEY); - self.set_user_id(user_id.clone()); + let _ = self.set_user_id(user_id.clone())?; } match user_id { @@ -170,6 +182,21 @@ impl UserSession { .unwrap()?; Ok(()) } + + async fn create_default_workspace_if_need(&self, user_id: &str) -> Result<(), UserError> { + let key = format!("{}{}", user_id, DEFAULT_WORKSPACE); + if KVStore::get_bool(&key).unwrap_or(false) { + return Ok(()); + } + + KVStore::set_bool(&key, true); + log::debug!("Create user:{} default workspace", user_id); + let _ = self + .server + .create_workspace(DEFAULT_WORKSPACE_NAME, DEFAULT_WORKSPACE_DESC, user_id) + .await?; + Ok(()) + } } pub fn current_user_id() -> Result { diff --git a/rust-lib/flowy-user/tests/event/sign_up_test.rs b/rust-lib/flowy-user/tests/event/sign_up_test.rs index 2122828e4d..037ed4a5b0 100644 --- a/rust-lib/flowy-user/tests/event/sign_up_test.rs +++ b/rust-lib/flowy-user/tests/event/sign_up_test.rs @@ -5,7 +5,6 @@ use serial_test::*; #[test] #[serial] fn sign_up_success() { - let _ = UserTestBuilder::new().event(SignOut).sync_send(); let request = SignUpRequest { email: random_valid_email(), name: valid_name(), @@ -17,8 +16,6 @@ fn sign_up_success() { .event(SignUp) .request(request) .sync_send(); - // .parse::(); - // dbg!(&response); } #[test] diff --git a/rust-lib/flowy-user/tests/event/user_status_test.rs b/rust-lib/flowy-user/tests/event/user_status_test.rs index ee5e56345d..391a325acd 100644 --- a/rust-lib/flowy-user/tests/event/user_status_test.rs +++ b/rust-lib/flowy-user/tests/event/user_status_test.rs @@ -3,14 +3,13 @@ use flowy_user::{event::UserEvent::*, prelude::*}; use serial_test::*; #[test] -#[should_panic] #[serial] fn user_status_get_failed_before_login() { - let _ = UserTestBuilder::new() + let a = UserTestBuilder::new() .logout() .event(GetStatus) - .sync_send() - .parse::(); + .assert_error() + .sync_send(); } #[test] diff --git a/rust-lib/flowy-workspace/src/event.rs b/rust-lib/flowy-workspace/src/event.rs index 8a45318ac2..6ad027feb4 100644 --- a/rust-lib/flowy-workspace/src/event.rs +++ b/rust-lib/flowy-workspace/src/event.rs @@ -11,4 +11,8 @@ pub enum WorkspaceEvent { #[display(fmt = "Get user's workspace detail")] #[event(output = "UserWorkspaceDetail")] GetWorkspaceDetail = 1, + + #[display(fmt = "Create app")] + #[event(input = "CreateAppRequest", output = "AppDetail")] + CreateApp = 101, } diff --git a/rust-lib/flowy-workspace/src/module.rs b/rust-lib/flowy-workspace/src/module.rs index 4033730c0f..473dd11b65 100644 --- a/rust-lib/flowy-workspace/src/module.rs +++ b/rust-lib/flowy-workspace/src/module.rs @@ -26,4 +26,5 @@ pub fn create(user: Arc) -> Module { .data(app_controller) .event(WorkspaceEvent::CreateWorkspace, create_workspace) .event(WorkspaceEvent::GetWorkspaceDetail, get_workspace_detail) + .event(WorkspaceEvent::CreateApp, create_app) } diff --git a/rust-lib/flowy-workspace/src/protobuf/model/event.rs b/rust-lib/flowy-workspace/src/protobuf/model/event.rs index 4e3e978ea5..b37c44d031 100644 --- a/rust-lib/flowy-workspace/src/protobuf/model/event.rs +++ b/rust-lib/flowy-workspace/src/protobuf/model/event.rs @@ -27,6 +27,7 @@ pub enum WorkspaceEvent { CreateWorkspace = 0, GetWorkspaceDetail = 1, + CreateApp = 101, } impl ::protobuf::ProtobufEnum for WorkspaceEvent { @@ -38,6 +39,7 @@ impl ::protobuf::ProtobufEnum for WorkspaceEvent { match value { 0 => ::std::option::Option::Some(WorkspaceEvent::CreateWorkspace), 1 => ::std::option::Option::Some(WorkspaceEvent::GetWorkspaceDetail), + 101 => ::std::option::Option::Some(WorkspaceEvent::CreateApp), _ => ::std::option::Option::None } } @@ -46,6 +48,7 @@ impl ::protobuf::ProtobufEnum for WorkspaceEvent { static values: &'static [WorkspaceEvent] = &[ WorkspaceEvent::CreateWorkspace, WorkspaceEvent::GetWorkspaceDetail, + WorkspaceEvent::CreateApp, ]; values } @@ -74,14 +77,17 @@ impl ::protobuf::reflect::ProtobufValue for WorkspaceEvent { } static file_descriptor_proto_data: &'static [u8] = b"\ - \n\x0bevent.proto*=\n\x0eWorkspaceEvent\x12\x13\n\x0fCreateWorkspace\x10\ - \0\x12\x16\n\x12GetWorkspaceDetail\x10\x01J|\n\x06\x12\x04\0\0\x05\x01\n\ - \x08\n\x01\x0c\x12\x03\0\0\x12\n\n\n\x02\x05\0\x12\x04\x02\0\x05\x01\n\n\ - \n\x03\x05\0\x01\x12\x03\x02\x05\x13\n\x0b\n\x04\x05\0\x02\0\x12\x03\x03\ - \x04\x18\n\x0c\n\x05\x05\0\x02\0\x01\x12\x03\x03\x04\x13\n\x0c\n\x05\x05\ - \0\x02\0\x02\x12\x03\x03\x16\x17\n\x0b\n\x04\x05\0\x02\x01\x12\x03\x04\ - \x04\x1b\n\x0c\n\x05\x05\0\x02\x01\x01\x12\x03\x04\x04\x16\n\x0c\n\x05\ - \x05\0\x02\x01\x02\x12\x03\x04\x19\x1ab\x06proto3\ + \n\x0bevent.proto*L\n\x0eWorkspaceEvent\x12\x13\n\x0fCreateWorkspace\x10\ + \0\x12\x16\n\x12GetWorkspaceDetail\x10\x01\x12\r\n\tCreateApp\x10eJ\xa5\ + \x01\n\x06\x12\x04\0\0\x06\x01\n\x08\n\x01\x0c\x12\x03\0\0\x12\n\n\n\x02\ + \x05\0\x12\x04\x02\0\x06\x01\n\n\n\x03\x05\0\x01\x12\x03\x02\x05\x13\n\ + \x0b\n\x04\x05\0\x02\0\x12\x03\x03\x04\x18\n\x0c\n\x05\x05\0\x02\0\x01\ + \x12\x03\x03\x04\x13\n\x0c\n\x05\x05\0\x02\0\x02\x12\x03\x03\x16\x17\n\ + \x0b\n\x04\x05\0\x02\x01\x12\x03\x04\x04\x1b\n\x0c\n\x05\x05\0\x02\x01\ + \x01\x12\x03\x04\x04\x16\n\x0c\n\x05\x05\0\x02\x01\x02\x12\x03\x04\x19\ + \x1a\n\x0b\n\x04\x05\0\x02\x02\x12\x03\x05\x04\x14\n\x0c\n\x05\x05\0\x02\ + \x02\x01\x12\x03\x05\x04\r\n\x0c\n\x05\x05\0\x02\x02\x02\x12\x03\x05\x10\ + \x13b\x06proto3\ "; static file_descriptor_proto_lazy: ::protobuf::rt::LazyV2<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::rt::LazyV2::INIT; diff --git a/rust-lib/flowy-workspace/src/protobuf/proto/event.proto b/rust-lib/flowy-workspace/src/protobuf/proto/event.proto index 0ccba3d647..bd0776b023 100644 --- a/rust-lib/flowy-workspace/src/protobuf/proto/event.proto +++ b/rust-lib/flowy-workspace/src/protobuf/proto/event.proto @@ -3,4 +3,5 @@ syntax = "proto3"; enum WorkspaceEvent { CreateWorkspace = 0; GetWorkspaceDetail = 1; + CreateApp = 101; } diff --git a/rust-lib/flowy-workspace/tests/event/app_test.rs b/rust-lib/flowy-workspace/tests/event/app_test.rs index 8a00950875..7b2ad2a691 100644 --- a/rust-lib/flowy-workspace/tests/event/app_test.rs +++ b/rust-lib/flowy-workspace/tests/event/app_test.rs @@ -1,15 +1,33 @@ -// #[test] -// fn app_create_success() { -// let request = CreateAppRequest { -// workspace_id: "".to_string(), -// name: "123".to_owned(), -// desc: "".to_owned(), -// color_style: Default::default(), -// }; -// -// let response = WorkspaceEventTester::new(CreateWorkspace) -// .request(request) -// .sync_send() -// .parse::(); -// dbg!(&response); -// } +use flowy_test::builder::WorkspaceTestBuilder; +use flowy_workspace::{ + entities::{ + app::{AppDetail, CreateAppRequest}, + workspace::UserWorkspaceDetail, + }, + event::WorkspaceEvent::{CreateApp, GetWorkspaceDetail}, +}; + +#[test] +fn app_create_success() { + let user_workspace = WorkspaceTestBuilder::new() + .event(GetWorkspaceDetail) + .sync_send() + .parse::(); + + let request = CreateAppRequest { + workspace_id: user_workspace.workspace.id, + name: "Github".to_owned(), + desc: "AppFlowy Github Project".to_owned(), + color_style: Default::default(), + }; + + let app_detail = WorkspaceTestBuilder::new() + .event(CreateApp) + .request(request) + .sync_send() + .parse::(); + + dbg!(&app_detail); +} + +// TODO 1) test update app 2) delete app diff --git a/rust-lib/flowy-workspace/tests/event/workspace_test.rs b/rust-lib/flowy-workspace/tests/event/workspace_test.rs index 2c0ffc6855..b6a636176d 100644 --- a/rust-lib/flowy-workspace/tests/event/workspace_test.rs +++ b/rust-lib/flowy-workspace/tests/event/workspace_test.rs @@ -22,6 +22,16 @@ fn workspace_create_success() { #[test] fn workspace_get_detail_success() { + let user_workspace = WorkspaceTestBuilder::new() + .event(GetWorkspaceDetail) + .sync_send() + .parse::(); + + dbg!(&user_workspace); +} + +#[test] +fn workspace_create_and_then_get_detail_success() { let request = CreateWorkspaceRequest { name: "Team A".to_owned(), desc: "Team A Description".to_owned(), @@ -61,21 +71,24 @@ fn workspace_create_with_invalid_name_test() { } } -// #[test] -// fn workspace_update_with_invalid_name_test() { -// for name in invalid_workspace_name_test_case() { -// let request = CreateWorkspaceRequest { -// name, -// desc: "".to_owned(), -// }; -// -// assert_eq!( -// WorkspaceEventTester::new(CreateWorkspace) -// .request(request) -// .sync_send() -// .error() -// .code, -// WorkspaceErrorCode::WorkspaceNameInvalid -// ) -// } -// } +#[test] +fn workspace_update_with_invalid_name_test() { + for name in invalid_workspace_name_test_case() { + let request = CreateWorkspaceRequest { + name, + desc: "".to_owned(), + }; + + assert_eq!( + WorkspaceTestBuilder::new() + .event(CreateWorkspace) + .request(request) + .sync_send() + .error() + .code, + WorkspaceErrorCode::WorkspaceNameInvalid + ) + } +} + +// TODO 1) delete workspace, but can't delete the last workspace From b547e9427340e008d6a50ed078dc96127dc0d84f Mon Sep 17 00:00:00 2001 From: appflowy Date: Mon, 19 Jul 2021 22:44:37 +0800 Subject: [PATCH 29/30] config view --- .../flowy-workspace/app_create.pb.dart | 26 +- .../flowy-workspace/app_create.pbjson.dart | 10 +- .../flowy-workspace/errors.pbenum.dart | 16 +- .../flowy-workspace/errors.pbjson.dart | 15 +- .../flowy-workspace/event.pbenum.dart | 2 + .../flowy-workspace/event.pbjson.dart | 3 +- .../protobuf/flowy-workspace/protobuf.dart | 1 + .../flowy-workspace/view_create.pb.dart | 234 +++++ .../flowy-workspace/view_create.pbenum.dart | 24 + .../flowy-workspace/view_create.pbjson.dart | 51 ++ .../flowy-workspace/view_create.pbserver.dart | 9 + .../flowy-workspace/workspace_create.pb.dart | 26 +- .../workspace_create.pbjson.dart | 10 +- .../workspace_user_detail.pb.dart | 10 +- .../workspace_user_detail.pbjson.dart | 4 +- .../2021-07-09-063045_flowy-user/down.sql | 5 +- .../2021-07-09-063045_flowy-user/up.sql | 34 + .../down.sql | 4 - .../2021-07-13-063102_flowy-workspace/up.sql | 34 - .../src/derive_cache/derive_cache.rs | 9 +- rust-lib/flowy-sdk/src/flowy_server.rs | 4 +- .../src/entities/app/app_create.rs | 4 +- .../flowy-workspace/src/entities/app/mod.rs | 2 +- rust-lib/flowy-workspace/src/entities/mod.rs | 1 + .../flowy-workspace/src/entities/view/mod.rs | 4 + .../src/entities/view/parser/mod.rs | 9 + .../src/entities/view/parser/view_desc.rs | 18 + .../src/entities/view/parser/view_name.rs | 22 + .../entities/view/parser/view_thumbnail.rs | 20 + .../src/entities/view/parser/view_type.rs | 13 + .../src/entities/view/view_create.rs | 104 +++ .../entities/workspace/workspace_create.rs | 2 +- .../workspace/workspace_user_detail.rs | 4 +- rust-lib/flowy-workspace/src/errors.rs | 19 +- rust-lib/flowy-workspace/src/event.rs | 6 +- .../src/handlers/app_handler.rs | 4 +- rust-lib/flowy-workspace/src/handlers/mod.rs | 2 + .../src/handlers/view_handler.rs | 16 + .../src/handlers/workspace_handler.rs | 4 +- rust-lib/flowy-workspace/src/macros.rs | 54 +- rust-lib/flowy-workspace/src/module.rs | 5 +- .../src/protobuf/model/app_create.rs | 116 +-- .../src/protobuf/model/errors.rs | 98 ++- .../src/protobuf/model/event.rs | 27 +- .../flowy-workspace/src/protobuf/model/mod.rs | 3 + .../src/protobuf/model/view_create.rs | 803 ++++++++++++++++++ .../src/protobuf/model/workspace_create.rs | 86 +- .../protobuf/model/workspace_user_detail.rs | 54 +- .../src/protobuf/proto/app_create.proto | 2 +- .../src/protobuf/proto/errors.proto | 13 +- .../src/protobuf/proto/event.proto | 1 + .../src/protobuf/proto/view_create.proto | 19 + .../src/protobuf/proto/workspace_create.proto | 2 +- .../proto/workspace_user_detail.proto | 2 +- .../src/services/app_controller.rs | 12 +- rust-lib/flowy-workspace/src/services/mod.rs | 2 + .../src/services/view_controller.rs | 28 + .../src/services/workspace_controller.rs | 8 +- .../flowy-workspace/src/sql_tables/app/app.rs | 21 +- .../src/sql_tables/view/view.rs | 106 +++ .../src/sql_tables/workspace/workspace.rs | 12 +- .../flowy-workspace/tests/event/app_test.rs | 4 +- .../tests/event/workspace_test.rs | 6 +- 63 files changed, 1908 insertions(+), 361 deletions(-) create mode 100644 app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/view_create.pb.dart create mode 100644 app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/view_create.pbenum.dart create mode 100644 app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/view_create.pbjson.dart create mode 100644 app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/view_create.pbserver.dart delete mode 100644 rust-lib/flowy-database/migrations/2021-07-13-063102_flowy-workspace/down.sql delete mode 100644 rust-lib/flowy-database/migrations/2021-07-13-063102_flowy-workspace/up.sql create mode 100644 rust-lib/flowy-workspace/src/entities/view/mod.rs create mode 100644 rust-lib/flowy-workspace/src/entities/view/parser/mod.rs create mode 100644 rust-lib/flowy-workspace/src/entities/view/parser/view_desc.rs create mode 100644 rust-lib/flowy-workspace/src/entities/view/parser/view_name.rs create mode 100644 rust-lib/flowy-workspace/src/entities/view/parser/view_thumbnail.rs create mode 100644 rust-lib/flowy-workspace/src/entities/view/parser/view_type.rs create mode 100644 rust-lib/flowy-workspace/src/entities/view/view_create.rs create mode 100644 rust-lib/flowy-workspace/src/handlers/view_handler.rs create mode 100644 rust-lib/flowy-workspace/src/protobuf/model/view_create.rs create mode 100644 rust-lib/flowy-workspace/src/protobuf/proto/view_create.proto create mode 100644 rust-lib/flowy-workspace/src/services/view_controller.rs diff --git a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/app_create.pb.dart b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/app_create.pb.dart index 7358eb7dca..fdb1ac1482 100644 --- a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/app_create.pb.dart +++ b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/app_create.pb.dart @@ -147,8 +147,8 @@ class ColorStyle extends $pb.GeneratedMessage { void clearThemeColor() => clearField(1); } -class AppDetail extends $pb.GeneratedMessage { - static final $pb.BuilderInfo _i = $pb.BuilderInfo(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'AppDetail', createEmptyInstance: create) +class App extends $pb.GeneratedMessage { + static final $pb.BuilderInfo _i = $pb.BuilderInfo(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'App', createEmptyInstance: create) ..aOS(1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'id') ..aOS(2, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'workspaceId') ..aOS(3, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'name') @@ -156,8 +156,8 @@ class AppDetail extends $pb.GeneratedMessage { ..hasRequiredFields = false ; - AppDetail._() : super(); - factory AppDetail({ + App._() : super(); + factory App({ $core.String? id, $core.String? workspaceId, $core.String? name, @@ -178,26 +178,26 @@ class AppDetail extends $pb.GeneratedMessage { } return _result; } - factory AppDetail.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); - factory AppDetail.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); + factory App.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); + factory App.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); @$core.Deprecated( 'Using this can add significant overhead to your binary. ' 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' 'Will be removed in next major version') - AppDetail clone() => AppDetail()..mergeFromMessage(this); + App clone() => App()..mergeFromMessage(this); @$core.Deprecated( 'Using this can add significant overhead to your binary. ' 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' 'Will be removed in next major version') - AppDetail copyWith(void Function(AppDetail) updates) => super.copyWith((message) => updates(message as AppDetail)) as AppDetail; // ignore: deprecated_member_use + App copyWith(void Function(App) updates) => super.copyWith((message) => updates(message as App)) as App; // ignore: deprecated_member_use $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') - static AppDetail create() => AppDetail._(); - AppDetail createEmptyInstance() => create(); - static $pb.PbList createRepeated() => $pb.PbList(); + static App create() => App._(); + App createEmptyInstance() => create(); + static $pb.PbList createRepeated() => $pb.PbList(); @$core.pragma('dart2js:noInline') - static AppDetail getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); - static AppDetail? _defaultInstance; + static App getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static App? _defaultInstance; @$pb.TagNumber(1) $core.String get id => $_getSZ(0); diff --git a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/app_create.pbjson.dart b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/app_create.pbjson.dart index 3e2548d302..46e4b0b849 100644 --- a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/app_create.pbjson.dart +++ b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/app_create.pbjson.dart @@ -31,9 +31,9 @@ const ColorStyle$json = const { /// Descriptor for `ColorStyle`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List colorStyleDescriptor = $convert.base64Decode('CgpDb2xvclN0eWxlEh8KC3RoZW1lX2NvbG9yGAEgASgJUgp0aGVtZUNvbG9y'); -@$core.Deprecated('Use appDetailDescriptor instead') -const AppDetail$json = const { - '1': 'AppDetail', +@$core.Deprecated('Use appDescriptor instead') +const App$json = const { + '1': 'App', '2': const [ const {'1': 'id', '3': 1, '4': 1, '5': 9, '10': 'id'}, const {'1': 'workspace_id', '3': 2, '4': 1, '5': 9, '10': 'workspaceId'}, @@ -42,5 +42,5 @@ const AppDetail$json = const { ], }; -/// Descriptor for `AppDetail`. Decode as a `google.protobuf.DescriptorProto`. -final $typed_data.Uint8List appDetailDescriptor = $convert.base64Decode('CglBcHBEZXRhaWwSDgoCaWQYASABKAlSAmlkEiEKDHdvcmtzcGFjZV9pZBgCIAEoCVILd29ya3NwYWNlSWQSEgoEbmFtZRgDIAEoCVIEbmFtZRISCgRkZXNjGAQgASgJUgRkZXNj'); +/// Descriptor for `App`. Decode as a `google.protobuf.DescriptorProto`. +final $typed_data.Uint8List appDescriptor = $convert.base64Decode('CgNBcHASDgoCaWQYASABKAlSAmlkEiEKDHdvcmtzcGFjZV9pZBgCIAEoCVILd29ya3NwYWNlSWQSEgoEbmFtZRgDIAEoCVIEbmFtZRISCgRkZXNjGAQgASgJUgRkZXNj'); diff --git a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/errors.pbenum.dart b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/errors.pbenum.dart index 40189fb948..ede6d2aa55 100644 --- a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/errors.pbenum.dart +++ b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/errors.pbenum.dart @@ -14,11 +14,14 @@ class WorkspaceErrorCode extends $pb.ProtobufEnum { static const WorkspaceErrorCode WorkspaceNameInvalid = WorkspaceErrorCode._(1, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'WorkspaceNameInvalid'); static const WorkspaceErrorCode WorkspaceIdInvalid = WorkspaceErrorCode._(2, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'WorkspaceIdInvalid'); static const WorkspaceErrorCode AppColorStyleInvalid = WorkspaceErrorCode._(3, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'AppColorStyleInvalid'); - static const WorkspaceErrorCode AppIdInvalid = WorkspaceErrorCode._(4, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'AppIdInvalid'); - static const WorkspaceErrorCode DatabaseConnectionFail = WorkspaceErrorCode._(5, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'DatabaseConnectionFail'); - static const WorkspaceErrorCode WorkspaceDatabaseError = WorkspaceErrorCode._(6, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'WorkspaceDatabaseError'); - static const WorkspaceErrorCode UserInternalError = WorkspaceErrorCode._(10, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'UserInternalError'); - static const WorkspaceErrorCode UserNotLoginYet = WorkspaceErrorCode._(11, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'UserNotLoginYet'); + static const WorkspaceErrorCode AppIdInvalid = WorkspaceErrorCode._(10, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'AppIdInvalid'); + static const WorkspaceErrorCode AppNameInvalid = WorkspaceErrorCode._(11, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'AppNameInvalid'); + static const WorkspaceErrorCode ViewNameInvalid = WorkspaceErrorCode._(20, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'ViewNameInvalid'); + static const WorkspaceErrorCode ViewThumbnailName = WorkspaceErrorCode._(21, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'ViewThumbnailName'); + static const WorkspaceErrorCode DatabaseConnectionFail = WorkspaceErrorCode._(100, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'DatabaseConnectionFail'); + static const WorkspaceErrorCode WorkspaceDatabaseError = WorkspaceErrorCode._(101, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'WorkspaceDatabaseError'); + static const WorkspaceErrorCode UserInternalError = WorkspaceErrorCode._(102, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'UserInternalError'); + static const WorkspaceErrorCode UserNotLoginYet = WorkspaceErrorCode._(103, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'UserNotLoginYet'); static const $core.List values = [ Unknown, @@ -26,6 +29,9 @@ class WorkspaceErrorCode extends $pb.ProtobufEnum { WorkspaceIdInvalid, AppColorStyleInvalid, AppIdInvalid, + AppNameInvalid, + ViewNameInvalid, + ViewThumbnailName, DatabaseConnectionFail, WorkspaceDatabaseError, UserInternalError, diff --git a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/errors.pbjson.dart b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/errors.pbjson.dart index b855710f36..1dd3186d24 100644 --- a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/errors.pbjson.dart +++ b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/errors.pbjson.dart @@ -16,16 +16,19 @@ const WorkspaceErrorCode$json = const { const {'1': 'WorkspaceNameInvalid', '2': 1}, const {'1': 'WorkspaceIdInvalid', '2': 2}, const {'1': 'AppColorStyleInvalid', '2': 3}, - const {'1': 'AppIdInvalid', '2': 4}, - const {'1': 'DatabaseConnectionFail', '2': 5}, - const {'1': 'WorkspaceDatabaseError', '2': 6}, - const {'1': 'UserInternalError', '2': 10}, - const {'1': 'UserNotLoginYet', '2': 11}, + const {'1': 'AppIdInvalid', '2': 10}, + const {'1': 'AppNameInvalid', '2': 11}, + const {'1': 'ViewNameInvalid', '2': 20}, + const {'1': 'ViewThumbnailName', '2': 21}, + const {'1': 'DatabaseConnectionFail', '2': 100}, + const {'1': 'WorkspaceDatabaseError', '2': 101}, + const {'1': 'UserInternalError', '2': 102}, + const {'1': 'UserNotLoginYet', '2': 103}, ], }; /// Descriptor for `WorkspaceErrorCode`. Decode as a `google.protobuf.EnumDescriptorProto`. -final $typed_data.Uint8List workspaceErrorCodeDescriptor = $convert.base64Decode('ChJXb3Jrc3BhY2VFcnJvckNvZGUSCwoHVW5rbm93bhAAEhgKFFdvcmtzcGFjZU5hbWVJbnZhbGlkEAESFgoSV29ya3NwYWNlSWRJbnZhbGlkEAISGAoUQXBwQ29sb3JTdHlsZUludmFsaWQQAxIQCgxBcHBJZEludmFsaWQQBBIaChZEYXRhYmFzZUNvbm5lY3Rpb25GYWlsEAUSGgoWV29ya3NwYWNlRGF0YWJhc2VFcnJvchAGEhUKEVVzZXJJbnRlcm5hbEVycm9yEAoSEwoPVXNlck5vdExvZ2luWWV0EAs='); +final $typed_data.Uint8List workspaceErrorCodeDescriptor = $convert.base64Decode('ChJXb3Jrc3BhY2VFcnJvckNvZGUSCwoHVW5rbm93bhAAEhgKFFdvcmtzcGFjZU5hbWVJbnZhbGlkEAESFgoSV29ya3NwYWNlSWRJbnZhbGlkEAISGAoUQXBwQ29sb3JTdHlsZUludmFsaWQQAxIQCgxBcHBJZEludmFsaWQQChISCg5BcHBOYW1lSW52YWxpZBALEhMKD1ZpZXdOYW1lSW52YWxpZBAUEhUKEVZpZXdUaHVtYm5haWxOYW1lEBUSGgoWRGF0YWJhc2VDb25uZWN0aW9uRmFpbBBkEhoKFldvcmtzcGFjZURhdGFiYXNlRXJyb3IQZRIVChFVc2VySW50ZXJuYWxFcnJvchBmEhMKD1VzZXJOb3RMb2dpbllldBBn'); @$core.Deprecated('Use workspaceErrorDescriptor instead') const WorkspaceError$json = const { '1': 'WorkspaceError', diff --git a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/event.pbenum.dart b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/event.pbenum.dart index e4f5d77688..08cec09e19 100644 --- a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/event.pbenum.dart +++ b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/event.pbenum.dart @@ -13,11 +13,13 @@ class WorkspaceEvent extends $pb.ProtobufEnum { static const WorkspaceEvent CreateWorkspace = WorkspaceEvent._(0, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'CreateWorkspace'); static const WorkspaceEvent GetWorkspaceDetail = WorkspaceEvent._(1, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'GetWorkspaceDetail'); static const WorkspaceEvent CreateApp = WorkspaceEvent._(101, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'CreateApp'); + static const WorkspaceEvent CreateView = WorkspaceEvent._(201, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'CreateView'); static const $core.List values = [ CreateWorkspace, GetWorkspaceDetail, CreateApp, + CreateView, ]; static final $core.Map<$core.int, WorkspaceEvent> _byValue = $pb.ProtobufEnum.initByValue(values); diff --git a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/event.pbjson.dart b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/event.pbjson.dart index 4cb911eaf0..b7cdc7c7d0 100644 --- a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/event.pbjson.dart +++ b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/event.pbjson.dart @@ -15,8 +15,9 @@ const WorkspaceEvent$json = const { const {'1': 'CreateWorkspace', '2': 0}, const {'1': 'GetWorkspaceDetail', '2': 1}, const {'1': 'CreateApp', '2': 101}, + const {'1': 'CreateView', '2': 201}, ], }; /// Descriptor for `WorkspaceEvent`. Decode as a `google.protobuf.EnumDescriptorProto`. -final $typed_data.Uint8List workspaceEventDescriptor = $convert.base64Decode('Cg5Xb3Jrc3BhY2VFdmVudBITCg9DcmVhdGVXb3Jrc3BhY2UQABIWChJHZXRXb3Jrc3BhY2VEZXRhaWwQARINCglDcmVhdGVBcHAQZQ=='); +final $typed_data.Uint8List workspaceEventDescriptor = $convert.base64Decode('Cg5Xb3Jrc3BhY2VFdmVudBITCg9DcmVhdGVXb3Jrc3BhY2UQABIWChJHZXRXb3Jrc3BhY2VEZXRhaWwQARINCglDcmVhdGVBcHAQZRIPCgpDcmVhdGVWaWV3EMkB'); diff --git a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/protobuf.dart b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/protobuf.dart index cee28e7715..cf45ec07ad 100644 --- a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/protobuf.dart +++ b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/protobuf.dart @@ -3,6 +3,7 @@ export './errors.pb.dart'; export './workspace_update.pb.dart'; export './app_create.pb.dart'; export './event.pb.dart'; +export './view_create.pb.dart'; export './workspace_user_detail.pb.dart'; export './workspace_create.pb.dart'; export './app_update.pb.dart'; diff --git a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/view_create.pb.dart b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/view_create.pb.dart new file mode 100644 index 0000000000..82f7d3a17d --- /dev/null +++ b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/view_create.pb.dart @@ -0,0 +1,234 @@ +/// +// Generated code. Do not modify. +// source: view_create.proto +// +// @dart = 2.12 +// ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields + +import 'dart:core' as $core; + +import 'package:protobuf/protobuf.dart' as $pb; + +import 'view_create.pbenum.dart'; + +export 'view_create.pbenum.dart'; + +enum CreateViewRequest_OneOfThumbnail { + thumbnail, + notSet +} + +class CreateViewRequest extends $pb.GeneratedMessage { + static const $core.Map<$core.int, CreateViewRequest_OneOfThumbnail> _CreateViewRequest_OneOfThumbnailByTag = { + 4 : CreateViewRequest_OneOfThumbnail.thumbnail, + 0 : CreateViewRequest_OneOfThumbnail.notSet + }; + static final $pb.BuilderInfo _i = $pb.BuilderInfo(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'CreateViewRequest', createEmptyInstance: create) + ..oo(0, [4]) + ..aOS(1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'appId') + ..aOS(2, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'name') + ..aOS(3, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'desc') + ..aOS(4, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'thumbnail') + ..e(5, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'viewType', $pb.PbFieldType.OE, defaultOrMaker: ViewTypeIdentifier.Docs, valueOf: ViewTypeIdentifier.valueOf, enumValues: ViewTypeIdentifier.values) + ..hasRequiredFields = false + ; + + CreateViewRequest._() : super(); + factory CreateViewRequest({ + $core.String? appId, + $core.String? name, + $core.String? desc, + $core.String? thumbnail, + ViewTypeIdentifier? viewType, + }) { + final _result = create(); + if (appId != null) { + _result.appId = appId; + } + if (name != null) { + _result.name = name; + } + if (desc != null) { + _result.desc = desc; + } + if (thumbnail != null) { + _result.thumbnail = thumbnail; + } + if (viewType != null) { + _result.viewType = viewType; + } + return _result; + } + factory CreateViewRequest.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); + factory CreateViewRequest.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); + @$core.Deprecated( + 'Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' + 'Will be removed in next major version') + CreateViewRequest clone() => CreateViewRequest()..mergeFromMessage(this); + @$core.Deprecated( + 'Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' + 'Will be removed in next major version') + CreateViewRequest copyWith(void Function(CreateViewRequest) updates) => super.copyWith((message) => updates(message as CreateViewRequest)) as CreateViewRequest; // ignore: deprecated_member_use + $pb.BuilderInfo get info_ => _i; + @$core.pragma('dart2js:noInline') + static CreateViewRequest create() => CreateViewRequest._(); + CreateViewRequest createEmptyInstance() => create(); + static $pb.PbList createRepeated() => $pb.PbList(); + @$core.pragma('dart2js:noInline') + static CreateViewRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static CreateViewRequest? _defaultInstance; + + CreateViewRequest_OneOfThumbnail whichOneOfThumbnail() => _CreateViewRequest_OneOfThumbnailByTag[$_whichOneof(0)]!; + void clearOneOfThumbnail() => clearField($_whichOneof(0)); + + @$pb.TagNumber(1) + $core.String get appId => $_getSZ(0); + @$pb.TagNumber(1) + set appId($core.String v) { $_setString(0, v); } + @$pb.TagNumber(1) + $core.bool hasAppId() => $_has(0); + @$pb.TagNumber(1) + void clearAppId() => clearField(1); + + @$pb.TagNumber(2) + $core.String get name => $_getSZ(1); + @$pb.TagNumber(2) + set name($core.String v) { $_setString(1, v); } + @$pb.TagNumber(2) + $core.bool hasName() => $_has(1); + @$pb.TagNumber(2) + void clearName() => clearField(2); + + @$pb.TagNumber(3) + $core.String get desc => $_getSZ(2); + @$pb.TagNumber(3) + set desc($core.String v) { $_setString(2, v); } + @$pb.TagNumber(3) + $core.bool hasDesc() => $_has(2); + @$pb.TagNumber(3) + void clearDesc() => clearField(3); + + @$pb.TagNumber(4) + $core.String get thumbnail => $_getSZ(3); + @$pb.TagNumber(4) + set thumbnail($core.String v) { $_setString(3, v); } + @$pb.TagNumber(4) + $core.bool hasThumbnail() => $_has(3); + @$pb.TagNumber(4) + void clearThumbnail() => clearField(4); + + @$pb.TagNumber(5) + ViewTypeIdentifier get viewType => $_getN(4); + @$pb.TagNumber(5) + set viewType(ViewTypeIdentifier v) { setField(5, v); } + @$pb.TagNumber(5) + $core.bool hasViewType() => $_has(4); + @$pb.TagNumber(5) + void clearViewType() => clearField(5); +} + +class View extends $pb.GeneratedMessage { + static final $pb.BuilderInfo _i = $pb.BuilderInfo(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'View', createEmptyInstance: create) + ..aOS(1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'id') + ..aOS(2, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'appId') + ..aOS(3, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'name') + ..aOS(4, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'desc') + ..e(5, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'viewType', $pb.PbFieldType.OE, defaultOrMaker: ViewTypeIdentifier.Docs, valueOf: ViewTypeIdentifier.valueOf, enumValues: ViewTypeIdentifier.values) + ..hasRequiredFields = false + ; + + View._() : super(); + factory View({ + $core.String? id, + $core.String? appId, + $core.String? name, + $core.String? desc, + ViewTypeIdentifier? viewType, + }) { + final _result = create(); + if (id != null) { + _result.id = id; + } + if (appId != null) { + _result.appId = appId; + } + if (name != null) { + _result.name = name; + } + if (desc != null) { + _result.desc = desc; + } + if (viewType != null) { + _result.viewType = viewType; + } + return _result; + } + factory View.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); + factory View.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); + @$core.Deprecated( + 'Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' + 'Will be removed in next major version') + View clone() => View()..mergeFromMessage(this); + @$core.Deprecated( + 'Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' + 'Will be removed in next major version') + View copyWith(void Function(View) updates) => super.copyWith((message) => updates(message as View)) as View; // ignore: deprecated_member_use + $pb.BuilderInfo get info_ => _i; + @$core.pragma('dart2js:noInline') + static View create() => View._(); + View createEmptyInstance() => create(); + static $pb.PbList createRepeated() => $pb.PbList(); + @$core.pragma('dart2js:noInline') + static View getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static View? _defaultInstance; + + @$pb.TagNumber(1) + $core.String get id => $_getSZ(0); + @$pb.TagNumber(1) + set id($core.String v) { $_setString(0, v); } + @$pb.TagNumber(1) + $core.bool hasId() => $_has(0); + @$pb.TagNumber(1) + void clearId() => clearField(1); + + @$pb.TagNumber(2) + $core.String get appId => $_getSZ(1); + @$pb.TagNumber(2) + set appId($core.String v) { $_setString(1, v); } + @$pb.TagNumber(2) + $core.bool hasAppId() => $_has(1); + @$pb.TagNumber(2) + void clearAppId() => clearField(2); + + @$pb.TagNumber(3) + $core.String get name => $_getSZ(2); + @$pb.TagNumber(3) + set name($core.String v) { $_setString(2, v); } + @$pb.TagNumber(3) + $core.bool hasName() => $_has(2); + @$pb.TagNumber(3) + void clearName() => clearField(3); + + @$pb.TagNumber(4) + $core.String get desc => $_getSZ(3); + @$pb.TagNumber(4) + set desc($core.String v) { $_setString(3, v); } + @$pb.TagNumber(4) + $core.bool hasDesc() => $_has(3); + @$pb.TagNumber(4) + void clearDesc() => clearField(4); + + @$pb.TagNumber(5) + ViewTypeIdentifier get viewType => $_getN(4); + @$pb.TagNumber(5) + set viewType(ViewTypeIdentifier v) { setField(5, v); } + @$pb.TagNumber(5) + $core.bool hasViewType() => $_has(4); + @$pb.TagNumber(5) + void clearViewType() => clearField(5); +} + diff --git a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/view_create.pbenum.dart b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/view_create.pbenum.dart new file mode 100644 index 0000000000..a685816a29 --- /dev/null +++ b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/view_create.pbenum.dart @@ -0,0 +1,24 @@ +/// +// Generated code. Do not modify. +// source: view_create.proto +// +// @dart = 2.12 +// ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields + +// ignore_for_file: UNDEFINED_SHOWN_NAME +import 'dart:core' as $core; +import 'package:protobuf/protobuf.dart' as $pb; + +class ViewTypeIdentifier extends $pb.ProtobufEnum { + static const ViewTypeIdentifier Docs = ViewTypeIdentifier._(0, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'Docs'); + + static const $core.List values = [ + Docs, + ]; + + static final $core.Map<$core.int, ViewTypeIdentifier> _byValue = $pb.ProtobufEnum.initByValue(values); + static ViewTypeIdentifier? valueOf($core.int value) => _byValue[value]; + + const ViewTypeIdentifier._($core.int v, $core.String n) : super(v, n); +} + diff --git a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/view_create.pbjson.dart b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/view_create.pbjson.dart new file mode 100644 index 0000000000..c17dd1699e --- /dev/null +++ b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/view_create.pbjson.dart @@ -0,0 +1,51 @@ +/// +// Generated code. Do not modify. +// source: view_create.proto +// +// @dart = 2.12 +// ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields,deprecated_member_use_from_same_package + +import 'dart:core' as $core; +import 'dart:convert' as $convert; +import 'dart:typed_data' as $typed_data; +@$core.Deprecated('Use viewTypeIdentifierDescriptor instead') +const ViewTypeIdentifier$json = const { + '1': 'ViewTypeIdentifier', + '2': const [ + const {'1': 'Docs', '2': 0}, + ], +}; + +/// Descriptor for `ViewTypeIdentifier`. Decode as a `google.protobuf.EnumDescriptorProto`. +final $typed_data.Uint8List viewTypeIdentifierDescriptor = $convert.base64Decode('ChJWaWV3VHlwZUlkZW50aWZpZXISCAoERG9jcxAA'); +@$core.Deprecated('Use createViewRequestDescriptor instead') +const CreateViewRequest$json = const { + '1': 'CreateViewRequest', + '2': const [ + const {'1': 'app_id', '3': 1, '4': 1, '5': 9, '10': 'appId'}, + const {'1': 'name', '3': 2, '4': 1, '5': 9, '10': 'name'}, + const {'1': 'desc', '3': 3, '4': 1, '5': 9, '10': 'desc'}, + const {'1': 'thumbnail', '3': 4, '4': 1, '5': 9, '9': 0, '10': 'thumbnail'}, + const {'1': 'view_type', '3': 5, '4': 1, '5': 14, '6': '.ViewTypeIdentifier', '10': 'viewType'}, + ], + '8': const [ + const {'1': 'one_of_thumbnail'}, + ], +}; + +/// Descriptor for `CreateViewRequest`. Decode as a `google.protobuf.DescriptorProto`. +final $typed_data.Uint8List createViewRequestDescriptor = $convert.base64Decode('ChFDcmVhdGVWaWV3UmVxdWVzdBIVCgZhcHBfaWQYASABKAlSBWFwcElkEhIKBG5hbWUYAiABKAlSBG5hbWUSEgoEZGVzYxgDIAEoCVIEZGVzYxIeCgl0aHVtYm5haWwYBCABKAlIAFIJdGh1bWJuYWlsEjAKCXZpZXdfdHlwZRgFIAEoDjITLlZpZXdUeXBlSWRlbnRpZmllclIIdmlld1R5cGVCEgoQb25lX29mX3RodW1ibmFpbA=='); +@$core.Deprecated('Use viewDescriptor instead') +const View$json = const { + '1': 'View', + '2': const [ + const {'1': 'id', '3': 1, '4': 1, '5': 9, '10': 'id'}, + const {'1': 'app_id', '3': 2, '4': 1, '5': 9, '10': 'appId'}, + const {'1': 'name', '3': 3, '4': 1, '5': 9, '10': 'name'}, + const {'1': 'desc', '3': 4, '4': 1, '5': 9, '10': 'desc'}, + const {'1': 'view_type', '3': 5, '4': 1, '5': 14, '6': '.ViewTypeIdentifier', '10': 'viewType'}, + ], +}; + +/// Descriptor for `View`. Decode as a `google.protobuf.DescriptorProto`. +final $typed_data.Uint8List viewDescriptor = $convert.base64Decode('CgRWaWV3Eg4KAmlkGAEgASgJUgJpZBIVCgZhcHBfaWQYAiABKAlSBWFwcElkEhIKBG5hbWUYAyABKAlSBG5hbWUSEgoEZGVzYxgEIAEoCVIEZGVzYxIwCgl2aWV3X3R5cGUYBSABKA4yEy5WaWV3VHlwZUlkZW50aWZpZXJSCHZpZXdUeXBl'); diff --git a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/view_create.pbserver.dart b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/view_create.pbserver.dart new file mode 100644 index 0000000000..8bfbe9d7d2 --- /dev/null +++ b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/view_create.pbserver.dart @@ -0,0 +1,9 @@ +/// +// Generated code. Do not modify. +// source: view_create.proto +// +// @dart = 2.12 +// ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields,deprecated_member_use_from_same_package + +export 'view_create.pb.dart'; + diff --git a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/workspace_create.pb.dart b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/workspace_create.pb.dart index 7b2f9bf8d7..e14b1f4382 100644 --- a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/workspace_create.pb.dart +++ b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/workspace_create.pb.dart @@ -70,16 +70,16 @@ class CreateWorkspaceRequest extends $pb.GeneratedMessage { void clearDesc() => clearField(2); } -class WorkspaceDetail extends $pb.GeneratedMessage { - static final $pb.BuilderInfo _i = $pb.BuilderInfo(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'WorkspaceDetail', createEmptyInstance: create) +class Workspace extends $pb.GeneratedMessage { + static final $pb.BuilderInfo _i = $pb.BuilderInfo(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'Workspace', createEmptyInstance: create) ..aOS(1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'id') ..aOS(2, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'name') ..aOS(3, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'desc') ..hasRequiredFields = false ; - WorkspaceDetail._() : super(); - factory WorkspaceDetail({ + Workspace._() : super(); + factory Workspace({ $core.String? id, $core.String? name, $core.String? desc, @@ -96,26 +96,26 @@ class WorkspaceDetail extends $pb.GeneratedMessage { } return _result; } - factory WorkspaceDetail.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); - factory WorkspaceDetail.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); + factory Workspace.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); + factory Workspace.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); @$core.Deprecated( 'Using this can add significant overhead to your binary. ' 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' 'Will be removed in next major version') - WorkspaceDetail clone() => WorkspaceDetail()..mergeFromMessage(this); + Workspace clone() => Workspace()..mergeFromMessage(this); @$core.Deprecated( 'Using this can add significant overhead to your binary. ' 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' 'Will be removed in next major version') - WorkspaceDetail copyWith(void Function(WorkspaceDetail) updates) => super.copyWith((message) => updates(message as WorkspaceDetail)) as WorkspaceDetail; // ignore: deprecated_member_use + Workspace copyWith(void Function(Workspace) updates) => super.copyWith((message) => updates(message as Workspace)) as Workspace; // ignore: deprecated_member_use $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') - static WorkspaceDetail create() => WorkspaceDetail._(); - WorkspaceDetail createEmptyInstance() => create(); - static $pb.PbList createRepeated() => $pb.PbList(); + static Workspace create() => Workspace._(); + Workspace createEmptyInstance() => create(); + static $pb.PbList createRepeated() => $pb.PbList(); @$core.pragma('dart2js:noInline') - static WorkspaceDetail getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); - static WorkspaceDetail? _defaultInstance; + static Workspace getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static Workspace? _defaultInstance; @$pb.TagNumber(1) $core.String get id => $_getSZ(0); diff --git a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/workspace_create.pbjson.dart b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/workspace_create.pbjson.dart index fcdf6d0c55..89729f1fc4 100644 --- a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/workspace_create.pbjson.dart +++ b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/workspace_create.pbjson.dart @@ -19,9 +19,9 @@ const CreateWorkspaceRequest$json = const { /// Descriptor for `CreateWorkspaceRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List createWorkspaceRequestDescriptor = $convert.base64Decode('ChZDcmVhdGVXb3Jrc3BhY2VSZXF1ZXN0EhIKBG5hbWUYASABKAlSBG5hbWUSEgoEZGVzYxgCIAEoCVIEZGVzYw=='); -@$core.Deprecated('Use workspaceDetailDescriptor instead') -const WorkspaceDetail$json = const { - '1': 'WorkspaceDetail', +@$core.Deprecated('Use workspaceDescriptor instead') +const Workspace$json = const { + '1': 'Workspace', '2': const [ const {'1': 'id', '3': 1, '4': 1, '5': 9, '10': 'id'}, const {'1': 'name', '3': 2, '4': 1, '5': 9, '10': 'name'}, @@ -29,5 +29,5 @@ const WorkspaceDetail$json = const { ], }; -/// Descriptor for `WorkspaceDetail`. Decode as a `google.protobuf.DescriptorProto`. -final $typed_data.Uint8List workspaceDetailDescriptor = $convert.base64Decode('Cg9Xb3Jrc3BhY2VEZXRhaWwSDgoCaWQYASABKAlSAmlkEhIKBG5hbWUYAiABKAlSBG5hbWUSEgoEZGVzYxgDIAEoCVIEZGVzYw=='); +/// Descriptor for `Workspace`. Decode as a `google.protobuf.DescriptorProto`. +final $typed_data.Uint8List workspaceDescriptor = $convert.base64Decode('CglXb3Jrc3BhY2USDgoCaWQYASABKAlSAmlkEhIKBG5hbWUYAiABKAlSBG5hbWUSEgoEZGVzYxgDIAEoCVIEZGVzYw=='); diff --git a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/workspace_user_detail.pb.dart b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/workspace_user_detail.pb.dart index 94f2b8bc49..553d431dd9 100644 --- a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/workspace_user_detail.pb.dart +++ b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/workspace_user_detail.pb.dart @@ -75,14 +75,14 @@ class UserWorkspace extends $pb.GeneratedMessage { class UserWorkspaceDetail extends $pb.GeneratedMessage { static final $pb.BuilderInfo _i = $pb.BuilderInfo(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'UserWorkspaceDetail', createEmptyInstance: create) ..aOS(1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'owner') - ..aOM<$0.WorkspaceDetail>(2, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'workspace', subBuilder: $0.WorkspaceDetail.create) + ..aOM<$0.Workspace>(2, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'workspace', subBuilder: $0.Workspace.create) ..hasRequiredFields = false ; UserWorkspaceDetail._() : super(); factory UserWorkspaceDetail({ $core.String? owner, - $0.WorkspaceDetail? workspace, + $0.Workspace? workspace, }) { final _result = create(); if (owner != null) { @@ -124,14 +124,14 @@ class UserWorkspaceDetail extends $pb.GeneratedMessage { void clearOwner() => clearField(1); @$pb.TagNumber(2) - $0.WorkspaceDetail get workspace => $_getN(1); + $0.Workspace get workspace => $_getN(1); @$pb.TagNumber(2) - set workspace($0.WorkspaceDetail v) { setField(2, v); } + set workspace($0.Workspace v) { setField(2, v); } @$pb.TagNumber(2) $core.bool hasWorkspace() => $_has(1); @$pb.TagNumber(2) void clearWorkspace() => clearField(2); @$pb.TagNumber(2) - $0.WorkspaceDetail ensureWorkspace() => $_ensure(1); + $0.Workspace ensureWorkspace() => $_ensure(1); } diff --git a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/workspace_user_detail.pbjson.dart b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/workspace_user_detail.pbjson.dart index 10d0b093c9..b267e42d5b 100644 --- a/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/workspace_user_detail.pbjson.dart +++ b/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-workspace/workspace_user_detail.pbjson.dart @@ -24,9 +24,9 @@ const UserWorkspaceDetail$json = const { '1': 'UserWorkspaceDetail', '2': const [ const {'1': 'owner', '3': 1, '4': 1, '5': 9, '10': 'owner'}, - const {'1': 'workspace', '3': 2, '4': 1, '5': 11, '6': '.WorkspaceDetail', '10': 'workspace'}, + const {'1': 'workspace', '3': 2, '4': 1, '5': 11, '6': '.Workspace', '10': 'workspace'}, ], }; /// Descriptor for `UserWorkspaceDetail`. Decode as a `google.protobuf.DescriptorProto`. -final $typed_data.Uint8List userWorkspaceDetailDescriptor = $convert.base64Decode('ChNVc2VyV29ya3NwYWNlRGV0YWlsEhQKBW93bmVyGAEgASgJUgVvd25lchIuCgl3b3Jrc3BhY2UYAiABKAsyEC5Xb3Jrc3BhY2VEZXRhaWxSCXdvcmtzcGFjZQ=='); +final $typed_data.Uint8List userWorkspaceDetailDescriptor = $convert.base64Decode('ChNVc2VyV29ya3NwYWNlRGV0YWlsEhQKBW93bmVyGAEgASgJUgVvd25lchIoCgl3b3Jrc3BhY2UYAiABKAsyCi5Xb3Jrc3BhY2VSCXdvcmtzcGFjZQ=='); diff --git a/rust-lib/flowy-database/migrations/2021-07-09-063045_flowy-user/down.sql b/rust-lib/flowy-database/migrations/2021-07-09-063045_flowy-user/down.sql index f1119aa25a..77ba5442e2 100644 --- a/rust-lib/flowy-database/migrations/2021-07-09-063045_flowy-user/down.sql +++ b/rust-lib/flowy-database/migrations/2021-07-09-063045_flowy-user/down.sql @@ -1,2 +1,5 @@ -- This file should undo anything in `up.sql` -DROP TABLE user_table; \ No newline at end of file +DROP TABLE user_table; +DROP TABLE workspace_table; +DROP TABLE app_table; +DROP TABLE view_table; \ No newline at end of file diff --git a/rust-lib/flowy-database/migrations/2021-07-09-063045_flowy-user/up.sql b/rust-lib/flowy-database/migrations/2021-07-09-063045_flowy-user/up.sql index 2ea0349782..570b6c4e4b 100644 --- a/rust-lib/flowy-database/migrations/2021-07-09-063045_flowy-user/up.sql +++ b/rust-lib/flowy-database/migrations/2021-07-09-063045_flowy-user/up.sql @@ -6,3 +6,37 @@ CREATE TABLE user_table ( password TEXT NOT NULL DEFAULT '', email TEXT NOT NULL DEFAULT '' ); + +CREATE TABLE workspace_table ( + id TEXT NOT NULL PRIMARY KEY, + name TEXT NOT NULL DEFAULT '', + desc TEXT NOT NULL DEFAULT '', + modified_time BIGINT NOT NULL DEFAULT 0, + create_time BIGINT NOT NULL DEFAULT 0, + user_id TEXT NOT NULL DEFAULT '', + version BIGINT NOT NULL DEFAULT 0 +); + +CREATE TABLE app_table ( + id TEXT NOT NULL PRIMARY KEY, + workspace_id TEXT NOT NULL DEFAULT '', + name TEXT NOT NULL DEFAULT '', + desc TEXT NOT NULL DEFAULT '', + color_style BLOB NOT NULL DEFAULT (x''), + last_view_id TEXT DEFAULT '', + modified_time BIGINT NOT NULL DEFAULT 0, + create_time BIGINT NOT NULL DEFAULT 0, + version BIGINT NOT NULL DEFAULT 0 +); + +CREATE TABLE view_table ( + id TEXT NOT NULL PRIMARY KEY, + app_id TEXT NOT NULL DEFAULT '', + name TEXT NOT NULL DEFAULT '', + desc TEXT NOT NULL DEFAULT '', + modified_time BIGINT NOT NULL DEFAULT 0, + create_time BIGINT NOT NULL DEFAULT 0, + thumbnail TEXT NOT NULL DEFAULT '', + view_type INTEGER NOT NULL DEFAULT 0, + version BIGINT NOT NULL DEFAULT 0 +); diff --git a/rust-lib/flowy-database/migrations/2021-07-13-063102_flowy-workspace/down.sql b/rust-lib/flowy-database/migrations/2021-07-13-063102_flowy-workspace/down.sql deleted file mode 100644 index bacfe9a64b..0000000000 --- a/rust-lib/flowy-database/migrations/2021-07-13-063102_flowy-workspace/down.sql +++ /dev/null @@ -1,4 +0,0 @@ --- This file should undo anything in `up.sql` -DROP TABLE workspace_table; -DROP TABLE app_table; -DROP TABLE view_table; \ No newline at end of file diff --git a/rust-lib/flowy-database/migrations/2021-07-13-063102_flowy-workspace/up.sql b/rust-lib/flowy-database/migrations/2021-07-13-063102_flowy-workspace/up.sql deleted file mode 100644 index 334b920141..0000000000 --- a/rust-lib/flowy-database/migrations/2021-07-13-063102_flowy-workspace/up.sql +++ /dev/null @@ -1,34 +0,0 @@ --- Your SQL goes here -CREATE TABLE workspace_table ( - id TEXT NOT NULL PRIMARY KEY, - name TEXT NOT NULL DEFAULT '', - desc TEXT NOT NULL DEFAULT '', - modified_time BIGINT NOT NULL DEFAULT 0, - create_time BIGINT NOT NULL DEFAULT 0, - user_id TEXT NOT NULL DEFAULT '', - version BIGINT NOT NULL DEFAULT 0 -); - -CREATE TABLE app_table ( - id TEXT NOT NULL PRIMARY KEY, - workspace_id TEXT NOT NULL DEFAULT '', - name TEXT NOT NULL DEFAULT '', - desc TEXT NOT NULL DEFAULT '', - color_style BLOB NOT NULL DEFAULT (x''), - last_view_id TEXT DEFAULT '', - modified_time BIGINT NOT NULL DEFAULT 0, - create_time BIGINT NOT NULL DEFAULT 0, - version BIGINT NOT NULL DEFAULT 0 -); - -CREATE TABLE view_table ( - id TEXT NOT NULL PRIMARY KEY, - app_id TEXT NOT NULL DEFAULT '', - name TEXT NOT NULL DEFAULT '', - desc TEXT NOT NULL DEFAULT '', - modified_time BIGINT NOT NULL DEFAULT 0, - create_time BIGINT NOT NULL DEFAULT 0, - thumbnail TEXT NOT NULL DEFAULT '', - view_type INTEGER NOT NULL DEFAULT 0, - version BIGINT NOT NULL DEFAULT 0 -); diff --git a/rust-lib/flowy-derive/src/derive_cache/derive_cache.rs b/rust-lib/flowy-derive/src/derive_cache/derive_cache.rs index 088c2ee0c3..f9ff418873 100644 --- a/rust-lib/flowy-derive/src/derive_cache/derive_cache.rs +++ b/rust-lib/flowy-derive/src/derive_cache/derive_cache.rs @@ -18,13 +18,15 @@ pub fn category_from_str(type_str: &str) -> TypeCategory { "KeyValue" | "CreateAppRequest" | "ColorStyle" - | "AppDetail" + | "App" | "UpdateAppRequest" | "UpdateWorkspaceRequest" | "CreateWorkspaceRequest" - | "WorkspaceDetail" + | "Workspace" | "UserWorkspace" | "UserWorkspaceDetail" + | "CreateViewRequest" + | "View" | "WorkspaceError" | "FFIRequest" | "FFIResponse" @@ -37,7 +39,8 @@ pub fn category_from_str(type_str: &str) -> TypeCategory { | "SignInParams" | "UserError" => TypeCategory::Protobuf, - "WorkspaceEvent" + "ViewTypeIdentifier" + | "WorkspaceEvent" | "WorkspaceErrorCode" | "FFIStatusCode" | "UserStatus" diff --git a/rust-lib/flowy-sdk/src/flowy_server.rs b/rust-lib/flowy-sdk/src/flowy_server.rs index 18df0ef6a6..08d5a8ea84 100644 --- a/rust-lib/flowy-sdk/src/flowy_server.rs +++ b/rust-lib/flowy-sdk/src/flowy_server.rs @@ -6,7 +6,7 @@ use flowy_user::{ sql_tables::UserTable, }; use flowy_workspace::{ - entities::workspace::{CreateWorkspaceRequest, WorkspaceDetail}, + entities::workspace::{CreateWorkspaceRequest, Workspace}, errors::WorkspaceError, event::WorkspaceEvent::CreateWorkspace, }; @@ -66,7 +66,7 @@ impl UserServer for FlowyServerMocker { fut: Box::pin(async move { let _ = EventDispatch::async_send(request) .await - .parse::() + .parse::() .map_err(|e| { ErrorBuilder::new(UserErrorCode::CreateDefaultWorkspaceFailed) .error(e) diff --git a/rust-lib/flowy-workspace/src/entities/app/app_create.rs b/rust-lib/flowy-workspace/src/entities/app/app_create.rs index 5d74537dcb..e4bbba81b2 100644 --- a/rust-lib/flowy-workspace/src/entities/app/app_create.rs +++ b/rust-lib/flowy-workspace/src/entities/app/app_create.rs @@ -41,7 +41,7 @@ impl TryInto for CreateAppRequest { fn try_into(self) -> Result { let name = AppName::parse(self.name).map_err(|e| { - ErrorBuilder::new(WorkspaceErrorCode::WorkspaceNameInvalid) + ErrorBuilder::new(WorkspaceErrorCode::AppNameInvalid) .msg(e) .build() })?; @@ -68,7 +68,7 @@ impl TryInto for CreateAppRequest { } #[derive(ProtoBuf, Default, Debug)] -pub struct AppDetail { +pub struct App { #[pb(index = 1)] pub id: String, diff --git a/rust-lib/flowy-workspace/src/entities/app/mod.rs b/rust-lib/flowy-workspace/src/entities/app/mod.rs index d370d42cd8..3f23b6b562 100644 --- a/rust-lib/flowy-workspace/src/entities/app/mod.rs +++ b/rust-lib/flowy-workspace/src/entities/app/mod.rs @@ -3,4 +3,4 @@ pub use app_update::*; mod app_create; mod app_update; -mod parser; +pub mod parser; diff --git a/rust-lib/flowy-workspace/src/entities/mod.rs b/rust-lib/flowy-workspace/src/entities/mod.rs index 8f9840256b..aae9164e81 100644 --- a/rust-lib/flowy-workspace/src/entities/mod.rs +++ b/rust-lib/flowy-workspace/src/entities/mod.rs @@ -1,2 +1,3 @@ pub mod app; +pub mod view; pub mod workspace; diff --git a/rust-lib/flowy-workspace/src/entities/view/mod.rs b/rust-lib/flowy-workspace/src/entities/view/mod.rs new file mode 100644 index 0000000000..f9768ab8f2 --- /dev/null +++ b/rust-lib/flowy-workspace/src/entities/view/mod.rs @@ -0,0 +1,4 @@ +mod parser; +mod view_create; + +pub use view_create::*; diff --git a/rust-lib/flowy-workspace/src/entities/view/parser/mod.rs b/rust-lib/flowy-workspace/src/entities/view/parser/mod.rs new file mode 100644 index 0000000000..088fdf8144 --- /dev/null +++ b/rust-lib/flowy-workspace/src/entities/view/parser/mod.rs @@ -0,0 +1,9 @@ +mod view_desc; +mod view_name; +mod view_thumbnail; +mod view_type; + +pub use view_desc::*; +pub use view_name::*; +pub use view_thumbnail::*; +pub use view_type::*; diff --git a/rust-lib/flowy-workspace/src/entities/view/parser/view_desc.rs b/rust-lib/flowy-workspace/src/entities/view/parser/view_desc.rs new file mode 100644 index 0000000000..b3635bc258 --- /dev/null +++ b/rust-lib/flowy-workspace/src/entities/view/parser/view_desc.rs @@ -0,0 +1,18 @@ +use unicode_segmentation::UnicodeSegmentation; + +#[derive(Debug)] +pub struct ViewDesc(pub String); + +impl ViewDesc { + pub fn parse(s: String) -> Result { + if s.graphemes(true).count() > 1000 { + return Err(format!("View desc too long")); + } + + Ok(Self(s)) + } +} + +impl AsRef for ViewDesc { + fn as_ref(&self) -> &str { &self.0 } +} diff --git a/rust-lib/flowy-workspace/src/entities/view/parser/view_name.rs b/rust-lib/flowy-workspace/src/entities/view/parser/view_name.rs new file mode 100644 index 0000000000..f283b092ca --- /dev/null +++ b/rust-lib/flowy-workspace/src/entities/view/parser/view_name.rs @@ -0,0 +1,22 @@ +use unicode_segmentation::UnicodeSegmentation; + +#[derive(Debug)] +pub struct ViewName(pub String); + +impl ViewName { + pub fn parse(s: String) -> Result { + if s.trim().is_empty() { + return Err(format!("View name can not be empty or whitespace")); + } + + if s.graphemes(true).count() > 256 { + return Err(format!("View name too long")); + } + + Ok(Self(s)) + } +} + +impl AsRef for ViewName { + fn as_ref(&self) -> &str { &self.0 } +} diff --git a/rust-lib/flowy-workspace/src/entities/view/parser/view_thumbnail.rs b/rust-lib/flowy-workspace/src/entities/view/parser/view_thumbnail.rs new file mode 100644 index 0000000000..6fe1aba136 --- /dev/null +++ b/rust-lib/flowy-workspace/src/entities/view/parser/view_thumbnail.rs @@ -0,0 +1,20 @@ +use unicode_segmentation::UnicodeSegmentation; + +#[derive(Debug)] +pub struct ViewThumbnail(pub String); + +impl ViewThumbnail { + pub fn parse(s: String) -> Result { + if s.trim().is_empty() { + return Err(format!("View thumbnail can not be empty or whitespace")); + } + + // TODO: verify the thumbnail url is valid or not + + Ok(Self(s)) + } +} + +impl AsRef for ViewThumbnail { + fn as_ref(&self) -> &str { &self.0 } +} diff --git a/rust-lib/flowy-workspace/src/entities/view/parser/view_type.rs b/rust-lib/flowy-workspace/src/entities/view/parser/view_type.rs new file mode 100644 index 0000000000..7486a6bdb5 --- /dev/null +++ b/rust-lib/flowy-workspace/src/entities/view/parser/view_type.rs @@ -0,0 +1,13 @@ +use crate::{entities::view::ViewTypeIdentifier, sql_tables::view::ViewType}; +use unicode_segmentation::UnicodeSegmentation; + +#[derive(Debug)] +pub struct ViewTypeCheck(pub ViewType); + +impl ViewTypeCheck { + pub fn parse(s: ViewTypeIdentifier) -> Result { + match s { + ViewTypeIdentifier::Docs => Ok(Self(ViewType::Docs)), + } + } +} diff --git a/rust-lib/flowy-workspace/src/entities/view/view_create.rs b/rust-lib/flowy-workspace/src/entities/view/view_create.rs new file mode 100644 index 0000000000..10b81491b8 --- /dev/null +++ b/rust-lib/flowy-workspace/src/entities/view/view_create.rs @@ -0,0 +1,104 @@ +use crate::{ + entities::{app::parser::AppId, view::parser::*}, + errors::{ErrorBuilder, WorkspaceError, WorkspaceErrorCode}, + sql_tables::view::ViewType, +}; +use flowy_derive::{ProtoBuf, ProtoBuf_Enum}; +use std::convert::TryInto; + +#[derive(Debug, ProtoBuf_Enum)] +pub enum ViewTypeIdentifier { + Docs = 0, +} + +impl std::default::Default for ViewTypeIdentifier { + fn default() -> Self { ViewTypeIdentifier::Docs } +} + +#[derive(Default, ProtoBuf)] +pub struct CreateViewRequest { + #[pb(index = 1)] + pub app_id: String, + + #[pb(index = 2)] + pub name: String, + + #[pb(index = 3)] + pub desc: String, + + #[pb(index = 4, one_of)] + pub thumbnail: Option, + + #[pb(index = 5)] + pub view_type: ViewTypeIdentifier, +} + +pub struct CreateViewParams { + pub app_id: String, + pub name: String, + pub desc: String, + pub thumbnail: String, + pub view_type: ViewType, +} + +impl TryInto for CreateViewRequest { + type Error = WorkspaceError; + + fn try_into(self) -> Result { + let name = ViewName::parse(self.name) + .map_err(|e| { + ErrorBuilder::new(WorkspaceErrorCode::ViewNameInvalid) + .msg(e) + .build() + })? + .0; + + let app_id = AppId::parse(self.app_id) + .map_err(|e| { + ErrorBuilder::new(WorkspaceErrorCode::AppIdInvalid) + .msg(e) + .build() + })? + .0; + + let thumbnail = match self.thumbnail { + None => "".to_string(), + Some(thumbnail) => { + ViewThumbnail::parse(thumbnail) + .map_err(|e| { + ErrorBuilder::new(WorkspaceErrorCode::ViewThumbnailName) + .msg(e) + .build() + })? + .0 + }, + }; + + let view_type = ViewTypeCheck::parse(self.view_type).unwrap().0; + Ok(CreateViewParams { + app_id, + name, + desc: self.desc, + thumbnail, + view_type, + }) + } +} + +#[derive(ProtoBuf, Default, Debug)] +pub struct View { + #[pb(index = 1)] + pub id: String, + + #[pb(index = 2)] + pub app_id: String, + + #[pb(index = 3)] + pub name: String, + + #[pb(index = 4)] + pub desc: String, + + #[pb(index = 5)] + pub view_type: ViewTypeIdentifier, +} diff --git a/rust-lib/flowy-workspace/src/entities/workspace/workspace_create.rs b/rust-lib/flowy-workspace/src/entities/workspace/workspace_create.rs index 8860009192..6a1b4656b7 100644 --- a/rust-lib/flowy-workspace/src/entities/workspace/workspace_create.rs +++ b/rust-lib/flowy-workspace/src/entities/workspace/workspace_create.rs @@ -34,7 +34,7 @@ impl TryInto for CreateWorkspaceRequest { } #[derive(ProtoBuf, Default, Debug)] -pub struct WorkspaceDetail { +pub struct Workspace { #[pb(index = 1)] pub id: String, diff --git a/rust-lib/flowy-workspace/src/entities/workspace/workspace_user_detail.rs b/rust-lib/flowy-workspace/src/entities/workspace/workspace_user_detail.rs index efe9a30b65..5db0639f39 100644 --- a/rust-lib/flowy-workspace/src/entities/workspace/workspace_user_detail.rs +++ b/rust-lib/flowy-workspace/src/entities/workspace/workspace_user_detail.rs @@ -1,4 +1,4 @@ -use crate::entities::workspace::WorkspaceDetail; +use crate::entities::workspace::Workspace; use flowy_derive::ProtoBuf; #[derive(ProtoBuf, Default, Debug)] @@ -16,5 +16,5 @@ pub struct UserWorkspaceDetail { pub owner: String, #[pb(index = 2)] - pub workspace: WorkspaceDetail, + pub workspace: Workspace, } diff --git a/rust-lib/flowy-workspace/src/errors.rs b/rust-lib/flowy-workspace/src/errors.rs index a0eb1e50c7..ec8380c2eb 100644 --- a/rust-lib/flowy-workspace/src/errors.rs +++ b/rust-lib/flowy-workspace/src/errors.rs @@ -36,19 +36,28 @@ pub enum WorkspaceErrorCode { AppColorStyleInvalid = 3, #[display(fmt = "App id is invalid")] - AppIdInvalid = 4, + AppIdInvalid = 10, + + #[display(fmt = "App name is invalid")] + AppNameInvalid = 11, + + #[display(fmt = "View name is invalid")] + ViewNameInvalid = 20, + + #[display(fmt = "Thumbnail of the view is invalid")] + ViewThumbnailName = 21, #[display(fmt = "Get database connection failed")] - DatabaseConnectionFail = 5, + DatabaseConnectionFail = 100, #[display(fmt = "Database internal error")] - WorkspaceDatabaseError = 6, + WorkspaceDatabaseError = 101, #[display(fmt = "User internal error")] - UserInternalError = 10, + UserInternalError = 102, #[display(fmt = "User not login yet")] - UserNotLoginYet = 11, + UserNotLoginYet = 103, } impl std::default::Default for WorkspaceErrorCode { diff --git a/rust-lib/flowy-workspace/src/event.rs b/rust-lib/flowy-workspace/src/event.rs index 6ad027feb4..fd707f9995 100644 --- a/rust-lib/flowy-workspace/src/event.rs +++ b/rust-lib/flowy-workspace/src/event.rs @@ -13,6 +13,10 @@ pub enum WorkspaceEvent { GetWorkspaceDetail = 1, #[display(fmt = "Create app")] - #[event(input = "CreateAppRequest", output = "AppDetail")] + #[event(input = "CreateAppRequest", output = "App")] CreateApp = 101, + + #[display(fmt = "Create view")] + #[event(input = "CreateViewRequest", output = "View")] + CreateView = 201, } diff --git a/rust-lib/flowy-workspace/src/handlers/app_handler.rs b/rust-lib/flowy-workspace/src/handlers/app_handler.rs index 72e41a5cbe..0100bffceb 100644 --- a/rust-lib/flowy-workspace/src/handlers/app_handler.rs +++ b/rust-lib/flowy-workspace/src/handlers/app_handler.rs @@ -1,5 +1,5 @@ use crate::{ - entities::app::{AppDetail, CreateAppParams, CreateAppRequest}, + entities::app::{App, CreateAppParams, CreateAppRequest}, errors::WorkspaceError, services::AppController, }; @@ -9,7 +9,7 @@ use std::{convert::TryInto, sync::Arc}; pub async fn create_app( data: Data, controller: ModuleData>, -) -> ResponseResult { +) -> ResponseResult { let params: CreateAppParams = data.into_inner().try_into()?; let detail = controller.save_app(params)?; response_ok(detail) diff --git a/rust-lib/flowy-workspace/src/handlers/mod.rs b/rust-lib/flowy-workspace/src/handlers/mod.rs index fdf08a9b51..95ed7acdcb 100644 --- a/rust-lib/flowy-workspace/src/handlers/mod.rs +++ b/rust-lib/flowy-workspace/src/handlers/mod.rs @@ -1,5 +1,7 @@ mod app_handler; +mod view_handler; mod workspace_handler; pub use app_handler::*; +pub use view_handler::*; pub use workspace_handler::*; diff --git a/rust-lib/flowy-workspace/src/handlers/view_handler.rs b/rust-lib/flowy-workspace/src/handlers/view_handler.rs new file mode 100644 index 0000000000..45510b708b --- /dev/null +++ b/rust-lib/flowy-workspace/src/handlers/view_handler.rs @@ -0,0 +1,16 @@ +use crate::{ + entities::view::{CreateViewParams, CreateViewRequest, View}, + errors::WorkspaceError, + services::ViewController, +}; +use flowy_dispatch::prelude::{response_ok, Data, ModuleData, ResponseResult}; +use std::{convert::TryInto, sync::Arc}; + +pub async fn create_view( + data: Data, + controller: ModuleData>, +) -> ResponseResult { + let params: CreateViewParams = data.into_inner().try_into()?; + let view = controller.save_view(params).await?; + response_ok(view) +} diff --git a/rust-lib/flowy-workspace/src/handlers/workspace_handler.rs b/rust-lib/flowy-workspace/src/handlers/workspace_handler.rs index b19d7258a0..ff73d58abf 100644 --- a/rust-lib/flowy-workspace/src/handlers/workspace_handler.rs +++ b/rust-lib/flowy-workspace/src/handlers/workspace_handler.rs @@ -4,7 +4,7 @@ use crate::{ CreateWorkspaceRequest, UserWorkspace, UserWorkspaceDetail, - WorkspaceDetail, + Workspace, }, errors::WorkspaceError, services::WorkspaceController, @@ -15,7 +15,7 @@ use std::{convert::TryInto, sync::Arc}; pub async fn create_workspace( data: Data, controller: ModuleData>, -) -> ResponseResult { +) -> ResponseResult { let controller = controller.get_ref().clone(); let params: CreateWorkspaceParams = data.into_inner().try_into()?; let detail = controller.save_workspace(params).await?; diff --git a/rust-lib/flowy-workspace/src/macros.rs b/rust-lib/flowy-workspace/src/macros.rs index 4690db7a9e..76431defce 100644 --- a/rust-lib/flowy-workspace/src/macros.rs +++ b/rust-lib/flowy-workspace/src/macros.rs @@ -9,25 +9,7 @@ macro_rules! impl_sql_binary_expression { out: &mut diesel::serialize::Output, ) -> diesel::serialize::Result { let bytes: Vec = self.try_into().map_err(|e| format!("{:?}", e))?; - diesel::serialize::ToSql::< - diesel::sql_types::Binary, - diesel::sqlite::Sqlite, - >::to_sql(&bytes, out) - - // match self.try_into() { - // Ok(bytes) => diesel::serialize::ToSql::< - // diesel::sql_types::Binary, - // diesel::sqlite::Sqlite, - // >::to_sql(&bytes, out), - // Err(e) => { - // log::error!( - // "{:?} serialize to bytes fail. {:?}", - // std::any::type_name::<$target>(), - // e - // ); - // panic!(); - // }, - // } + diesel::serialize::ToSql::::to_sql(&bytes, out) } } // https://docs.diesel.rs/src/diesel/sqlite/types/mod.rs.html#30-33 @@ -64,3 +46,37 @@ macro_rules! impl_sql_binary_expression { } }; } + +#[macro_export] +macro_rules! impl_sql_integer_expression { + ($target:ident) => { + use diesel::{ + deserialize, + deserialize::FromSql, + serialize, + serialize::{Output, ToSql}, + }; + use std::io::Write; + + impl ToSql for $target + where + DB: diesel::backend::Backend, + i32: ToSql, + { + fn to_sql(&self, out: &mut Output) -> serialize::Result { + (*self as i32).to_sql(out) + } + } + + impl FromSql for $target + where + DB: diesel::backend::Backend, + i32: FromSql, + { + fn from_sql(bytes: Option<&DB::RawValue>) -> deserialize::Result { + let smaill_int = i32::from_sql(bytes)?; + Ok($target::from(smaill_int)) + } + } + }; +} diff --git a/rust-lib/flowy-workspace/src/module.rs b/rust-lib/flowy-workspace/src/module.rs index 473dd11b65..7d5f7f540e 100644 --- a/rust-lib/flowy-workspace/src/module.rs +++ b/rust-lib/flowy-workspace/src/module.rs @@ -7,7 +7,7 @@ use crate::{ }; use flowy_database::DBConnection; -use crate::{entities::workspace::UserWorkspace, handlers::*}; +use crate::{entities::workspace::UserWorkspace, handlers::*, services::ViewController}; use std::sync::Arc; pub trait WorkspaceUser: Send + Sync { @@ -19,12 +19,15 @@ pub trait WorkspaceUser: Send + Sync { pub fn create(user: Arc) -> Module { let workspace_controller = Arc::new(WorkspaceController::new(user.clone())); let app_controller = Arc::new(AppController::new(user.clone())); + let view_controller = Arc::new(ViewController::new(user.clone())); Module::new() .name("Flowy-Workspace") .data(workspace_controller) .data(app_controller) + .data(view_controller) .event(WorkspaceEvent::CreateWorkspace, create_workspace) .event(WorkspaceEvent::GetWorkspaceDetail, get_workspace_detail) .event(WorkspaceEvent::CreateApp, create_app) + .event(WorkspaceEvent::CreateView, create_view) } diff --git a/rust-lib/flowy-workspace/src/protobuf/model/app_create.rs b/rust-lib/flowy-workspace/src/protobuf/model/app_create.rs index 7e9d0986fe..d2dd5814d0 100644 --- a/rust-lib/flowy-workspace/src/protobuf/model/app_create.rs +++ b/rust-lib/flowy-workspace/src/protobuf/model/app_create.rs @@ -483,7 +483,7 @@ impl ::protobuf::reflect::ProtobufValue for ColorStyle { } #[derive(PartialEq,Clone,Default)] -pub struct AppDetail { +pub struct App { // message fields pub id: ::std::string::String, pub workspace_id: ::std::string::String, @@ -494,14 +494,14 @@ pub struct AppDetail { pub cached_size: ::protobuf::CachedSize, } -impl<'a> ::std::default::Default for &'a AppDetail { - fn default() -> &'a AppDetail { - ::default_instance() +impl<'a> ::std::default::Default for &'a App { + fn default() -> &'a App { + ::default_instance() } } -impl AppDetail { - pub fn new() -> AppDetail { +impl App { + pub fn new() -> App { ::std::default::Default::default() } @@ -610,7 +610,7 @@ impl AppDetail { } } -impl ::protobuf::Message for AppDetail { +impl ::protobuf::Message for App { fn is_initialized(&self) -> bool { true } @@ -703,8 +703,8 @@ impl ::protobuf::Message for AppDetail { Self::descriptor_static() } - fn new() -> AppDetail { - AppDetail::new() + fn new() -> App { + App::new() } fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { @@ -713,39 +713,39 @@ impl ::protobuf::Message for AppDetail { let mut fields = ::std::vec::Vec::new(); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( "id", - |m: &AppDetail| { &m.id }, - |m: &mut AppDetail| { &mut m.id }, + |m: &App| { &m.id }, + |m: &mut App| { &mut m.id }, )); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( "workspace_id", - |m: &AppDetail| { &m.workspace_id }, - |m: &mut AppDetail| { &mut m.workspace_id }, + |m: &App| { &m.workspace_id }, + |m: &mut App| { &mut m.workspace_id }, )); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( "name", - |m: &AppDetail| { &m.name }, - |m: &mut AppDetail| { &mut m.name }, + |m: &App| { &m.name }, + |m: &mut App| { &mut m.name }, )); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( "desc", - |m: &AppDetail| { &m.desc }, - |m: &mut AppDetail| { &mut m.desc }, + |m: &App| { &m.desc }, + |m: &mut App| { &mut m.desc }, )); - ::protobuf::reflect::MessageDescriptor::new_pb_name::( - "AppDetail", + ::protobuf::reflect::MessageDescriptor::new_pb_name::( + "App", fields, file_descriptor_proto() ) }) } - fn default_instance() -> &'static AppDetail { - static instance: ::protobuf::rt::LazyV2 = ::protobuf::rt::LazyV2::INIT; - instance.get(AppDetail::new) + fn default_instance() -> &'static App { + static instance: ::protobuf::rt::LazyV2 = ::protobuf::rt::LazyV2::INIT; + instance.get(App::new) } } -impl ::protobuf::Clear for AppDetail { +impl ::protobuf::Clear for App { fn clear(&mut self) { self.id.clear(); self.workspace_id.clear(); @@ -755,13 +755,13 @@ impl ::protobuf::Clear for AppDetail { } } -impl ::std::fmt::Debug for AppDetail { +impl ::std::fmt::Debug for App { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { ::protobuf::text_format::fmt(self, f) } } -impl ::protobuf::reflect::ProtobufValue for AppDetail { +impl ::protobuf::reflect::ProtobufValue for App { fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef { ::protobuf::reflect::ReflectValueRef::Message(self) } @@ -772,39 +772,39 @@ static file_descriptor_proto_data: &'static [u8] = b"\ ce_id\x18\x01\x20\x01(\tR\x0bworkspaceId\x12\x12\n\x04name\x18\x02\x20\ \x01(\tR\x04name\x12\x12\n\x04desc\x18\x03\x20\x01(\tR\x04desc\x12,\n\ \x0bcolor_style\x18\x04\x20\x01(\x0b2\x0b.ColorStyleR\ncolorStyle\"-\n\n\ - ColorStyle\x12\x1f\n\x0btheme_color\x18\x01\x20\x01(\tR\nthemeColor\"f\n\ - \tAppDetail\x12\x0e\n\x02id\x18\x01\x20\x01(\tR\x02id\x12!\n\x0cworkspac\ - e_id\x18\x02\x20\x01(\tR\x0bworkspaceId\x12\x12\n\x04name\x18\x03\x20\ - \x01(\tR\x04name\x12\x12\n\x04desc\x18\x04\x20\x01(\tR\x04descJ\xc9\x04\ - \n\x06\x12\x04\0\0\x10\x01\n\x08\n\x01\x0c\x12\x03\0\0\x12\n\n\n\x02\x04\ - \0\x12\x04\x02\0\x07\x01\n\n\n\x03\x04\0\x01\x12\x03\x02\x08\x18\n\x0b\n\ - \x04\x04\0\x02\0\x12\x03\x03\x04\x1c\n\x0c\n\x05\x04\0\x02\0\x05\x12\x03\ - \x03\x04\n\n\x0c\n\x05\x04\0\x02\0\x01\x12\x03\x03\x0b\x17\n\x0c\n\x05\ - \x04\0\x02\0\x03\x12\x03\x03\x1a\x1b\n\x0b\n\x04\x04\0\x02\x01\x12\x03\ - \x04\x04\x14\n\x0c\n\x05\x04\0\x02\x01\x05\x12\x03\x04\x04\n\n\x0c\n\x05\ - \x04\0\x02\x01\x01\x12\x03\x04\x0b\x0f\n\x0c\n\x05\x04\0\x02\x01\x03\x12\ - \x03\x04\x12\x13\n\x0b\n\x04\x04\0\x02\x02\x12\x03\x05\x04\x14\n\x0c\n\ - \x05\x04\0\x02\x02\x05\x12\x03\x05\x04\n\n\x0c\n\x05\x04\0\x02\x02\x01\ - \x12\x03\x05\x0b\x0f\n\x0c\n\x05\x04\0\x02\x02\x03\x12\x03\x05\x12\x13\n\ - \x0b\n\x04\x04\0\x02\x03\x12\x03\x06\x04\x1f\n\x0c\n\x05\x04\0\x02\x03\ - \x06\x12\x03\x06\x04\x0e\n\x0c\n\x05\x04\0\x02\x03\x01\x12\x03\x06\x0f\ - \x1a\n\x0c\n\x05\x04\0\x02\x03\x03\x12\x03\x06\x1d\x1e\n\n\n\x02\x04\x01\ - \x12\x04\x08\0\n\x01\n\n\n\x03\x04\x01\x01\x12\x03\x08\x08\x12\n\x0b\n\ - \x04\x04\x01\x02\0\x12\x03\t\x04\x1b\n\x0c\n\x05\x04\x01\x02\0\x05\x12\ - \x03\t\x04\n\n\x0c\n\x05\x04\x01\x02\0\x01\x12\x03\t\x0b\x16\n\x0c\n\x05\ - \x04\x01\x02\0\x03\x12\x03\t\x19\x1a\n\n\n\x02\x04\x02\x12\x04\x0b\0\x10\ - \x01\n\n\n\x03\x04\x02\x01\x12\x03\x0b\x08\x11\n\x0b\n\x04\x04\x02\x02\0\ - \x12\x03\x0c\x04\x12\n\x0c\n\x05\x04\x02\x02\0\x05\x12\x03\x0c\x04\n\n\ - \x0c\n\x05\x04\x02\x02\0\x01\x12\x03\x0c\x0b\r\n\x0c\n\x05\x04\x02\x02\0\ - \x03\x12\x03\x0c\x10\x11\n\x0b\n\x04\x04\x02\x02\x01\x12\x03\r\x04\x1c\n\ - \x0c\n\x05\x04\x02\x02\x01\x05\x12\x03\r\x04\n\n\x0c\n\x05\x04\x02\x02\ - \x01\x01\x12\x03\r\x0b\x17\n\x0c\n\x05\x04\x02\x02\x01\x03\x12\x03\r\x1a\ - \x1b\n\x0b\n\x04\x04\x02\x02\x02\x12\x03\x0e\x04\x14\n\x0c\n\x05\x04\x02\ - \x02\x02\x05\x12\x03\x0e\x04\n\n\x0c\n\x05\x04\x02\x02\x02\x01\x12\x03\ - \x0e\x0b\x0f\n\x0c\n\x05\x04\x02\x02\x02\x03\x12\x03\x0e\x12\x13\n\x0b\n\ - \x04\x04\x02\x02\x03\x12\x03\x0f\x04\x14\n\x0c\n\x05\x04\x02\x02\x03\x05\ - \x12\x03\x0f\x04\n\n\x0c\n\x05\x04\x02\x02\x03\x01\x12\x03\x0f\x0b\x0f\n\ - \x0c\n\x05\x04\x02\x02\x03\x03\x12\x03\x0f\x12\x13b\x06proto3\ + ColorStyle\x12\x1f\n\x0btheme_color\x18\x01\x20\x01(\tR\nthemeColor\"`\n\ + \x03App\x12\x0e\n\x02id\x18\x01\x20\x01(\tR\x02id\x12!\n\x0cworkspace_id\ + \x18\x02\x20\x01(\tR\x0bworkspaceId\x12\x12\n\x04name\x18\x03\x20\x01(\t\ + R\x04name\x12\x12\n\x04desc\x18\x04\x20\x01(\tR\x04descJ\xc9\x04\n\x06\ + \x12\x04\0\0\x10\x01\n\x08\n\x01\x0c\x12\x03\0\0\x12\n\n\n\x02\x04\0\x12\ + \x04\x02\0\x07\x01\n\n\n\x03\x04\0\x01\x12\x03\x02\x08\x18\n\x0b\n\x04\ + \x04\0\x02\0\x12\x03\x03\x04\x1c\n\x0c\n\x05\x04\0\x02\0\x05\x12\x03\x03\ + \x04\n\n\x0c\n\x05\x04\0\x02\0\x01\x12\x03\x03\x0b\x17\n\x0c\n\x05\x04\0\ + \x02\0\x03\x12\x03\x03\x1a\x1b\n\x0b\n\x04\x04\0\x02\x01\x12\x03\x04\x04\ + \x14\n\x0c\n\x05\x04\0\x02\x01\x05\x12\x03\x04\x04\n\n\x0c\n\x05\x04\0\ + \x02\x01\x01\x12\x03\x04\x0b\x0f\n\x0c\n\x05\x04\0\x02\x01\x03\x12\x03\ + \x04\x12\x13\n\x0b\n\x04\x04\0\x02\x02\x12\x03\x05\x04\x14\n\x0c\n\x05\ + \x04\0\x02\x02\x05\x12\x03\x05\x04\n\n\x0c\n\x05\x04\0\x02\x02\x01\x12\ + \x03\x05\x0b\x0f\n\x0c\n\x05\x04\0\x02\x02\x03\x12\x03\x05\x12\x13\n\x0b\ + \n\x04\x04\0\x02\x03\x12\x03\x06\x04\x1f\n\x0c\n\x05\x04\0\x02\x03\x06\ + \x12\x03\x06\x04\x0e\n\x0c\n\x05\x04\0\x02\x03\x01\x12\x03\x06\x0f\x1a\n\ + \x0c\n\x05\x04\0\x02\x03\x03\x12\x03\x06\x1d\x1e\n\n\n\x02\x04\x01\x12\ + \x04\x08\0\n\x01\n\n\n\x03\x04\x01\x01\x12\x03\x08\x08\x12\n\x0b\n\x04\ + \x04\x01\x02\0\x12\x03\t\x04\x1b\n\x0c\n\x05\x04\x01\x02\0\x05\x12\x03\t\ + \x04\n\n\x0c\n\x05\x04\x01\x02\0\x01\x12\x03\t\x0b\x16\n\x0c\n\x05\x04\ + \x01\x02\0\x03\x12\x03\t\x19\x1a\n\n\n\x02\x04\x02\x12\x04\x0b\0\x10\x01\ + \n\n\n\x03\x04\x02\x01\x12\x03\x0b\x08\x0b\n\x0b\n\x04\x04\x02\x02\0\x12\ + \x03\x0c\x04\x12\n\x0c\n\x05\x04\x02\x02\0\x05\x12\x03\x0c\x04\n\n\x0c\n\ + \x05\x04\x02\x02\0\x01\x12\x03\x0c\x0b\r\n\x0c\n\x05\x04\x02\x02\0\x03\ + \x12\x03\x0c\x10\x11\n\x0b\n\x04\x04\x02\x02\x01\x12\x03\r\x04\x1c\n\x0c\ + \n\x05\x04\x02\x02\x01\x05\x12\x03\r\x04\n\n\x0c\n\x05\x04\x02\x02\x01\ + \x01\x12\x03\r\x0b\x17\n\x0c\n\x05\x04\x02\x02\x01\x03\x12\x03\r\x1a\x1b\ + \n\x0b\n\x04\x04\x02\x02\x02\x12\x03\x0e\x04\x14\n\x0c\n\x05\x04\x02\x02\ + \x02\x05\x12\x03\x0e\x04\n\n\x0c\n\x05\x04\x02\x02\x02\x01\x12\x03\x0e\ + \x0b\x0f\n\x0c\n\x05\x04\x02\x02\x02\x03\x12\x03\x0e\x12\x13\n\x0b\n\x04\ + \x04\x02\x02\x03\x12\x03\x0f\x04\x14\n\x0c\n\x05\x04\x02\x02\x03\x05\x12\ + \x03\x0f\x04\n\n\x0c\n\x05\x04\x02\x02\x03\x01\x12\x03\x0f\x0b\x0f\n\x0c\ + \n\x05\x04\x02\x02\x03\x03\x12\x03\x0f\x12\x13b\x06proto3\ "; static file_descriptor_proto_lazy: ::protobuf::rt::LazyV2<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::rt::LazyV2::INIT; diff --git a/rust-lib/flowy-workspace/src/protobuf/model/errors.rs b/rust-lib/flowy-workspace/src/protobuf/model/errors.rs index eda3e0c478..8e9695898d 100644 --- a/rust-lib/flowy-workspace/src/protobuf/model/errors.rs +++ b/rust-lib/flowy-workspace/src/protobuf/model/errors.rs @@ -219,11 +219,14 @@ pub enum WorkspaceErrorCode { WorkspaceNameInvalid = 1, WorkspaceIdInvalid = 2, AppColorStyleInvalid = 3, - AppIdInvalid = 4, - DatabaseConnectionFail = 5, - WorkspaceDatabaseError = 6, - UserInternalError = 10, - UserNotLoginYet = 11, + AppIdInvalid = 10, + AppNameInvalid = 11, + ViewNameInvalid = 20, + ViewThumbnailName = 21, + DatabaseConnectionFail = 100, + WorkspaceDatabaseError = 101, + UserInternalError = 102, + UserNotLoginYet = 103, } impl ::protobuf::ProtobufEnum for WorkspaceErrorCode { @@ -237,11 +240,14 @@ impl ::protobuf::ProtobufEnum for WorkspaceErrorCode { 1 => ::std::option::Option::Some(WorkspaceErrorCode::WorkspaceNameInvalid), 2 => ::std::option::Option::Some(WorkspaceErrorCode::WorkspaceIdInvalid), 3 => ::std::option::Option::Some(WorkspaceErrorCode::AppColorStyleInvalid), - 4 => ::std::option::Option::Some(WorkspaceErrorCode::AppIdInvalid), - 5 => ::std::option::Option::Some(WorkspaceErrorCode::DatabaseConnectionFail), - 6 => ::std::option::Option::Some(WorkspaceErrorCode::WorkspaceDatabaseError), - 10 => ::std::option::Option::Some(WorkspaceErrorCode::UserInternalError), - 11 => ::std::option::Option::Some(WorkspaceErrorCode::UserNotLoginYet), + 10 => ::std::option::Option::Some(WorkspaceErrorCode::AppIdInvalid), + 11 => ::std::option::Option::Some(WorkspaceErrorCode::AppNameInvalid), + 20 => ::std::option::Option::Some(WorkspaceErrorCode::ViewNameInvalid), + 21 => ::std::option::Option::Some(WorkspaceErrorCode::ViewThumbnailName), + 100 => ::std::option::Option::Some(WorkspaceErrorCode::DatabaseConnectionFail), + 101 => ::std::option::Option::Some(WorkspaceErrorCode::WorkspaceDatabaseError), + 102 => ::std::option::Option::Some(WorkspaceErrorCode::UserInternalError), + 103 => ::std::option::Option::Some(WorkspaceErrorCode::UserNotLoginYet), _ => ::std::option::Option::None } } @@ -253,6 +259,9 @@ impl ::protobuf::ProtobufEnum for WorkspaceErrorCode { WorkspaceErrorCode::WorkspaceIdInvalid, WorkspaceErrorCode::AppColorStyleInvalid, WorkspaceErrorCode::AppIdInvalid, + WorkspaceErrorCode::AppNameInvalid, + WorkspaceErrorCode::ViewNameInvalid, + WorkspaceErrorCode::ViewThumbnailName, WorkspaceErrorCode::DatabaseConnectionFail, WorkspaceErrorCode::WorkspaceDatabaseError, WorkspaceErrorCode::UserInternalError, @@ -287,39 +296,46 @@ impl ::protobuf::reflect::ProtobufValue for WorkspaceErrorCode { static file_descriptor_proto_data: &'static [u8] = b"\ \n\x0cerrors.proto\"K\n\x0eWorkspaceError\x12'\n\x04code\x18\x01\x20\x01\ (\x0e2\x13.WorkspaceErrorCodeR\x04code\x12\x10\n\x03msg\x18\x02\x20\x01(\ - \tR\x03msg*\xe3\x01\n\x12WorkspaceErrorCode\x12\x0b\n\x07Unknown\x10\0\ + \tR\x03msg*\xa3\x02\n\x12WorkspaceErrorCode\x12\x0b\n\x07Unknown\x10\0\ \x12\x18\n\x14WorkspaceNameInvalid\x10\x01\x12\x16\n\x12WorkspaceIdInval\ id\x10\x02\x12\x18\n\x14AppColorStyleInvalid\x10\x03\x12\x10\n\x0cAppIdI\ - nvalid\x10\x04\x12\x1a\n\x16DatabaseConnectionFail\x10\x05\x12\x1a\n\x16\ - WorkspaceDatabaseError\x10\x06\x12\x15\n\x11UserInternalError\x10\n\x12\ - \x13\n\x0fUserNotLoginYet\x10\x0bJ\xa1\x04\n\x06\x12\x04\0\0\x10\x01\n\ - \x08\n\x01\x0c\x12\x03\0\0\x12\n\n\n\x02\x04\0\x12\x04\x02\0\x05\x01\n\n\ - \n\x03\x04\0\x01\x12\x03\x02\x08\x16\n\x0b\n\x04\x04\0\x02\0\x12\x03\x03\ - \x04\x20\n\x0c\n\x05\x04\0\x02\0\x06\x12\x03\x03\x04\x16\n\x0c\n\x05\x04\ - \0\x02\0\x01\x12\x03\x03\x17\x1b\n\x0c\n\x05\x04\0\x02\0\x03\x12\x03\x03\ - \x1e\x1f\n\x0b\n\x04\x04\0\x02\x01\x12\x03\x04\x04\x13\n\x0c\n\x05\x04\0\ - \x02\x01\x05\x12\x03\x04\x04\n\n\x0c\n\x05\x04\0\x02\x01\x01\x12\x03\x04\ - \x0b\x0e\n\x0c\n\x05\x04\0\x02\x01\x03\x12\x03\x04\x11\x12\n\n\n\x02\x05\ - \0\x12\x04\x06\0\x10\x01\n\n\n\x03\x05\0\x01\x12\x03\x06\x05\x17\n\x0b\n\ - \x04\x05\0\x02\0\x12\x03\x07\x04\x10\n\x0c\n\x05\x05\0\x02\0\x01\x12\x03\ - \x07\x04\x0b\n\x0c\n\x05\x05\0\x02\0\x02\x12\x03\x07\x0e\x0f\n\x0b\n\x04\ - \x05\0\x02\x01\x12\x03\x08\x04\x1d\n\x0c\n\x05\x05\0\x02\x01\x01\x12\x03\ - \x08\x04\x18\n\x0c\n\x05\x05\0\x02\x01\x02\x12\x03\x08\x1b\x1c\n\x0b\n\ - \x04\x05\0\x02\x02\x12\x03\t\x04\x1b\n\x0c\n\x05\x05\0\x02\x02\x01\x12\ - \x03\t\x04\x16\n\x0c\n\x05\x05\0\x02\x02\x02\x12\x03\t\x19\x1a\n\x0b\n\ - \x04\x05\0\x02\x03\x12\x03\n\x04\x1d\n\x0c\n\x05\x05\0\x02\x03\x01\x12\ - \x03\n\x04\x18\n\x0c\n\x05\x05\0\x02\x03\x02\x12\x03\n\x1b\x1c\n\x0b\n\ - \x04\x05\0\x02\x04\x12\x03\x0b\x04\x15\n\x0c\n\x05\x05\0\x02\x04\x01\x12\ - \x03\x0b\x04\x10\n\x0c\n\x05\x05\0\x02\x04\x02\x12\x03\x0b\x13\x14\n\x0b\ - \n\x04\x05\0\x02\x05\x12\x03\x0c\x04\x1f\n\x0c\n\x05\x05\0\x02\x05\x01\ - \x12\x03\x0c\x04\x1a\n\x0c\n\x05\x05\0\x02\x05\x02\x12\x03\x0c\x1d\x1e\n\ - \x0b\n\x04\x05\0\x02\x06\x12\x03\r\x04\x1f\n\x0c\n\x05\x05\0\x02\x06\x01\ - \x12\x03\r\x04\x1a\n\x0c\n\x05\x05\0\x02\x06\x02\x12\x03\r\x1d\x1e\n\x0b\ - \n\x04\x05\0\x02\x07\x12\x03\x0e\x04\x1b\n\x0c\n\x05\x05\0\x02\x07\x01\ - \x12\x03\x0e\x04\x15\n\x0c\n\x05\x05\0\x02\x07\x02\x12\x03\x0e\x18\x1a\n\ - \x0b\n\x04\x05\0\x02\x08\x12\x03\x0f\x04\x19\n\x0c\n\x05\x05\0\x02\x08\ - \x01\x12\x03\x0f\x04\x13\n\x0c\n\x05\x05\0\x02\x08\x02\x12\x03\x0f\x16\ - \x18b\x06proto3\ + nvalid\x10\n\x12\x12\n\x0eAppNameInvalid\x10\x0b\x12\x13\n\x0fViewNameIn\ + valid\x10\x14\x12\x15\n\x11ViewThumbnailName\x10\x15\x12\x1a\n\x16Databa\ + seConnectionFail\x10d\x12\x1a\n\x16WorkspaceDatabaseError\x10e\x12\x15\n\ + \x11UserInternalError\x10f\x12\x13\n\x0fUserNotLoginYet\x10gJ\x9c\x05\n\ + \x06\x12\x04\0\0\x13\x01\n\x08\n\x01\x0c\x12\x03\0\0\x12\n\n\n\x02\x04\0\ + \x12\x04\x02\0\x05\x01\n\n\n\x03\x04\0\x01\x12\x03\x02\x08\x16\n\x0b\n\ + \x04\x04\0\x02\0\x12\x03\x03\x04\x20\n\x0c\n\x05\x04\0\x02\0\x06\x12\x03\ + \x03\x04\x16\n\x0c\n\x05\x04\0\x02\0\x01\x12\x03\x03\x17\x1b\n\x0c\n\x05\ + \x04\0\x02\0\x03\x12\x03\x03\x1e\x1f\n\x0b\n\x04\x04\0\x02\x01\x12\x03\ + \x04\x04\x13\n\x0c\n\x05\x04\0\x02\x01\x05\x12\x03\x04\x04\n\n\x0c\n\x05\ + \x04\0\x02\x01\x01\x12\x03\x04\x0b\x0e\n\x0c\n\x05\x04\0\x02\x01\x03\x12\ + \x03\x04\x11\x12\n\n\n\x02\x05\0\x12\x04\x06\0\x13\x01\n\n\n\x03\x05\0\ + \x01\x12\x03\x06\x05\x17\n\x0b\n\x04\x05\0\x02\0\x12\x03\x07\x04\x10\n\ + \x0c\n\x05\x05\0\x02\0\x01\x12\x03\x07\x04\x0b\n\x0c\n\x05\x05\0\x02\0\ + \x02\x12\x03\x07\x0e\x0f\n\x0b\n\x04\x05\0\x02\x01\x12\x03\x08\x04\x1d\n\ + \x0c\n\x05\x05\0\x02\x01\x01\x12\x03\x08\x04\x18\n\x0c\n\x05\x05\0\x02\ + \x01\x02\x12\x03\x08\x1b\x1c\n\x0b\n\x04\x05\0\x02\x02\x12\x03\t\x04\x1b\ + \n\x0c\n\x05\x05\0\x02\x02\x01\x12\x03\t\x04\x16\n\x0c\n\x05\x05\0\x02\ + \x02\x02\x12\x03\t\x19\x1a\n\x0b\n\x04\x05\0\x02\x03\x12\x03\n\x04\x1d\n\ + \x0c\n\x05\x05\0\x02\x03\x01\x12\x03\n\x04\x18\n\x0c\n\x05\x05\0\x02\x03\ + \x02\x12\x03\n\x1b\x1c\n\x0b\n\x04\x05\0\x02\x04\x12\x03\x0b\x04\x16\n\ + \x0c\n\x05\x05\0\x02\x04\x01\x12\x03\x0b\x04\x10\n\x0c\n\x05\x05\0\x02\ + \x04\x02\x12\x03\x0b\x13\x15\n\x0b\n\x04\x05\0\x02\x05\x12\x03\x0c\x04\ + \x18\n\x0c\n\x05\x05\0\x02\x05\x01\x12\x03\x0c\x04\x12\n\x0c\n\x05\x05\0\ + \x02\x05\x02\x12\x03\x0c\x15\x17\n\x0b\n\x04\x05\0\x02\x06\x12\x03\r\x04\ + \x19\n\x0c\n\x05\x05\0\x02\x06\x01\x12\x03\r\x04\x13\n\x0c\n\x05\x05\0\ + \x02\x06\x02\x12\x03\r\x16\x18\n\x0b\n\x04\x05\0\x02\x07\x12\x03\x0e\x04\ + \x1b\n\x0c\n\x05\x05\0\x02\x07\x01\x12\x03\x0e\x04\x15\n\x0c\n\x05\x05\0\ + \x02\x07\x02\x12\x03\x0e\x18\x1a\n\x0b\n\x04\x05\0\x02\x08\x12\x03\x0f\ + \x04!\n\x0c\n\x05\x05\0\x02\x08\x01\x12\x03\x0f\x04\x1a\n\x0c\n\x05\x05\ + \0\x02\x08\x02\x12\x03\x0f\x1d\x20\n\x0b\n\x04\x05\0\x02\t\x12\x03\x10\ + \x04!\n\x0c\n\x05\x05\0\x02\t\x01\x12\x03\x10\x04\x1a\n\x0c\n\x05\x05\0\ + \x02\t\x02\x12\x03\x10\x1d\x20\n\x0b\n\x04\x05\0\x02\n\x12\x03\x11\x04\ + \x1c\n\x0c\n\x05\x05\0\x02\n\x01\x12\x03\x11\x04\x15\n\x0c\n\x05\x05\0\ + \x02\n\x02\x12\x03\x11\x18\x1b\n\x0b\n\x04\x05\0\x02\x0b\x12\x03\x12\x04\ + \x1a\n\x0c\n\x05\x05\0\x02\x0b\x01\x12\x03\x12\x04\x13\n\x0c\n\x05\x05\0\ + \x02\x0b\x02\x12\x03\x12\x16\x19b\x06proto3\ "; static file_descriptor_proto_lazy: ::protobuf::rt::LazyV2<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::rt::LazyV2::INIT; diff --git a/rust-lib/flowy-workspace/src/protobuf/model/event.rs b/rust-lib/flowy-workspace/src/protobuf/model/event.rs index b37c44d031..efc2005564 100644 --- a/rust-lib/flowy-workspace/src/protobuf/model/event.rs +++ b/rust-lib/flowy-workspace/src/protobuf/model/event.rs @@ -28,6 +28,7 @@ pub enum WorkspaceEvent { CreateWorkspace = 0, GetWorkspaceDetail = 1, CreateApp = 101, + CreateView = 201, } impl ::protobuf::ProtobufEnum for WorkspaceEvent { @@ -40,6 +41,7 @@ impl ::protobuf::ProtobufEnum for WorkspaceEvent { 0 => ::std::option::Option::Some(WorkspaceEvent::CreateWorkspace), 1 => ::std::option::Option::Some(WorkspaceEvent::GetWorkspaceDetail), 101 => ::std::option::Option::Some(WorkspaceEvent::CreateApp), + 201 => ::std::option::Option::Some(WorkspaceEvent::CreateView), _ => ::std::option::Option::None } } @@ -49,6 +51,7 @@ impl ::protobuf::ProtobufEnum for WorkspaceEvent { WorkspaceEvent::CreateWorkspace, WorkspaceEvent::GetWorkspaceDetail, WorkspaceEvent::CreateApp, + WorkspaceEvent::CreateView, ]; values } @@ -77,17 +80,19 @@ impl ::protobuf::reflect::ProtobufValue for WorkspaceEvent { } static file_descriptor_proto_data: &'static [u8] = b"\ - \n\x0bevent.proto*L\n\x0eWorkspaceEvent\x12\x13\n\x0fCreateWorkspace\x10\ - \0\x12\x16\n\x12GetWorkspaceDetail\x10\x01\x12\r\n\tCreateApp\x10eJ\xa5\ - \x01\n\x06\x12\x04\0\0\x06\x01\n\x08\n\x01\x0c\x12\x03\0\0\x12\n\n\n\x02\ - \x05\0\x12\x04\x02\0\x06\x01\n\n\n\x03\x05\0\x01\x12\x03\x02\x05\x13\n\ - \x0b\n\x04\x05\0\x02\0\x12\x03\x03\x04\x18\n\x0c\n\x05\x05\0\x02\0\x01\ - \x12\x03\x03\x04\x13\n\x0c\n\x05\x05\0\x02\0\x02\x12\x03\x03\x16\x17\n\ - \x0b\n\x04\x05\0\x02\x01\x12\x03\x04\x04\x1b\n\x0c\n\x05\x05\0\x02\x01\ - \x01\x12\x03\x04\x04\x16\n\x0c\n\x05\x05\0\x02\x01\x02\x12\x03\x04\x19\ - \x1a\n\x0b\n\x04\x05\0\x02\x02\x12\x03\x05\x04\x14\n\x0c\n\x05\x05\0\x02\ - \x02\x01\x12\x03\x05\x04\r\n\x0c\n\x05\x05\0\x02\x02\x02\x12\x03\x05\x10\ - \x13b\x06proto3\ + \n\x0bevent.proto*]\n\x0eWorkspaceEvent\x12\x13\n\x0fCreateWorkspace\x10\ + \0\x12\x16\n\x12GetWorkspaceDetail\x10\x01\x12\r\n\tCreateApp\x10e\x12\ + \x0f\n\nCreateView\x10\xc9\x01J\xce\x01\n\x06\x12\x04\0\0\x07\x01\n\x08\ + \n\x01\x0c\x12\x03\0\0\x12\n\n\n\x02\x05\0\x12\x04\x02\0\x07\x01\n\n\n\ + \x03\x05\0\x01\x12\x03\x02\x05\x13\n\x0b\n\x04\x05\0\x02\0\x12\x03\x03\ + \x04\x18\n\x0c\n\x05\x05\0\x02\0\x01\x12\x03\x03\x04\x13\n\x0c\n\x05\x05\ + \0\x02\0\x02\x12\x03\x03\x16\x17\n\x0b\n\x04\x05\0\x02\x01\x12\x03\x04\ + \x04\x1b\n\x0c\n\x05\x05\0\x02\x01\x01\x12\x03\x04\x04\x16\n\x0c\n\x05\ + \x05\0\x02\x01\x02\x12\x03\x04\x19\x1a\n\x0b\n\x04\x05\0\x02\x02\x12\x03\ + \x05\x04\x14\n\x0c\n\x05\x05\0\x02\x02\x01\x12\x03\x05\x04\r\n\x0c\n\x05\ + \x05\0\x02\x02\x02\x12\x03\x05\x10\x13\n\x0b\n\x04\x05\0\x02\x03\x12\x03\ + \x06\x04\x15\n\x0c\n\x05\x05\0\x02\x03\x01\x12\x03\x06\x04\x0e\n\x0c\n\ + \x05\x05\0\x02\x03\x02\x12\x03\x06\x11\x14b\x06proto3\ "; static file_descriptor_proto_lazy: ::protobuf::rt::LazyV2<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::rt::LazyV2::INIT; diff --git a/rust-lib/flowy-workspace/src/protobuf/model/mod.rs b/rust-lib/flowy-workspace/src/protobuf/model/mod.rs index 1d98328c6d..27e3001c33 100644 --- a/rust-lib/flowy-workspace/src/protobuf/model/mod.rs +++ b/rust-lib/flowy-workspace/src/protobuf/model/mod.rs @@ -12,6 +12,9 @@ pub use app_create::*; mod event; pub use event::*; +mod view_create; +pub use view_create::*; + mod workspace_user_detail; pub use workspace_user_detail::*; diff --git a/rust-lib/flowy-workspace/src/protobuf/model/view_create.rs b/rust-lib/flowy-workspace/src/protobuf/model/view_create.rs new file mode 100644 index 0000000000..48a0c8f5e8 --- /dev/null +++ b/rust-lib/flowy-workspace/src/protobuf/model/view_create.rs @@ -0,0 +1,803 @@ +// This file is generated by rust-protobuf 2.22.1. Do not edit +// @generated + +// https://github.com/rust-lang/rust-clippy/issues/702 +#![allow(unknown_lints)] +#![allow(clippy::all)] + +#![allow(unused_attributes)] +#![cfg_attr(rustfmt, rustfmt::skip)] + +#![allow(box_pointers)] +#![allow(dead_code)] +#![allow(missing_docs)] +#![allow(non_camel_case_types)] +#![allow(non_snake_case)] +#![allow(non_upper_case_globals)] +#![allow(trivial_casts)] +#![allow(unused_imports)] +#![allow(unused_results)] +//! Generated file from `view_create.proto` + +/// Generated files are compatible only with the same version +/// of protobuf runtime. +// const _PROTOBUF_VERSION_CHECK: () = ::protobuf::VERSION_2_22_1; + +#[derive(PartialEq,Clone,Default)] +pub struct CreateViewRequest { + // message fields + pub app_id: ::std::string::String, + pub name: ::std::string::String, + pub desc: ::std::string::String, + pub view_type: ViewTypeIdentifier, + // message oneof groups + pub one_of_thumbnail: ::std::option::Option, + // special fields + pub unknown_fields: ::protobuf::UnknownFields, + pub cached_size: ::protobuf::CachedSize, +} + +impl<'a> ::std::default::Default for &'a CreateViewRequest { + fn default() -> &'a CreateViewRequest { + ::default_instance() + } +} + +#[derive(Clone,PartialEq,Debug)] +pub enum CreateViewRequest_oneof_one_of_thumbnail { + thumbnail(::std::string::String), +} + +impl CreateViewRequest { + pub fn new() -> CreateViewRequest { + ::std::default::Default::default() + } + + // string app_id = 1; + + + pub fn get_app_id(&self) -> &str { + &self.app_id + } + pub fn clear_app_id(&mut self) { + self.app_id.clear(); + } + + // Param is passed by value, moved + pub fn set_app_id(&mut self, v: ::std::string::String) { + self.app_id = v; + } + + // Mutable pointer to the field. + // If field is not initialized, it is initialized with default value first. + pub fn mut_app_id(&mut self) -> &mut ::std::string::String { + &mut self.app_id + } + + // Take field + pub fn take_app_id(&mut self) -> ::std::string::String { + ::std::mem::replace(&mut self.app_id, ::std::string::String::new()) + } + + // string name = 2; + + + pub fn get_name(&self) -> &str { + &self.name + } + pub fn clear_name(&mut self) { + self.name.clear(); + } + + // Param is passed by value, moved + pub fn set_name(&mut self, v: ::std::string::String) { + self.name = v; + } + + // Mutable pointer to the field. + // If field is not initialized, it is initialized with default value first. + pub fn mut_name(&mut self) -> &mut ::std::string::String { + &mut self.name + } + + // Take field + pub fn take_name(&mut self) -> ::std::string::String { + ::std::mem::replace(&mut self.name, ::std::string::String::new()) + } + + // string desc = 3; + + + pub fn get_desc(&self) -> &str { + &self.desc + } + pub fn clear_desc(&mut self) { + self.desc.clear(); + } + + // Param is passed by value, moved + pub fn set_desc(&mut self, v: ::std::string::String) { + self.desc = v; + } + + // Mutable pointer to the field. + // If field is not initialized, it is initialized with default value first. + pub fn mut_desc(&mut self) -> &mut ::std::string::String { + &mut self.desc + } + + // Take field + pub fn take_desc(&mut self) -> ::std::string::String { + ::std::mem::replace(&mut self.desc, ::std::string::String::new()) + } + + // string thumbnail = 4; + + + pub fn get_thumbnail(&self) -> &str { + match self.one_of_thumbnail { + ::std::option::Option::Some(CreateViewRequest_oneof_one_of_thumbnail::thumbnail(ref v)) => v, + _ => "", + } + } + pub fn clear_thumbnail(&mut self) { + self.one_of_thumbnail = ::std::option::Option::None; + } + + pub fn has_thumbnail(&self) -> bool { + match self.one_of_thumbnail { + ::std::option::Option::Some(CreateViewRequest_oneof_one_of_thumbnail::thumbnail(..)) => true, + _ => false, + } + } + + // Param is passed by value, moved + pub fn set_thumbnail(&mut self, v: ::std::string::String) { + self.one_of_thumbnail = ::std::option::Option::Some(CreateViewRequest_oneof_one_of_thumbnail::thumbnail(v)) + } + + // Mutable pointer to the field. + pub fn mut_thumbnail(&mut self) -> &mut ::std::string::String { + if let ::std::option::Option::Some(CreateViewRequest_oneof_one_of_thumbnail::thumbnail(_)) = self.one_of_thumbnail { + } else { + self.one_of_thumbnail = ::std::option::Option::Some(CreateViewRequest_oneof_one_of_thumbnail::thumbnail(::std::string::String::new())); + } + match self.one_of_thumbnail { + ::std::option::Option::Some(CreateViewRequest_oneof_one_of_thumbnail::thumbnail(ref mut v)) => v, + _ => panic!(), + } + } + + // Take field + pub fn take_thumbnail(&mut self) -> ::std::string::String { + if self.has_thumbnail() { + match self.one_of_thumbnail.take() { + ::std::option::Option::Some(CreateViewRequest_oneof_one_of_thumbnail::thumbnail(v)) => v, + _ => panic!(), + } + } else { + ::std::string::String::new() + } + } + + // .ViewTypeIdentifier view_type = 5; + + + pub fn get_view_type(&self) -> ViewTypeIdentifier { + self.view_type + } + pub fn clear_view_type(&mut self) { + self.view_type = ViewTypeIdentifier::Docs; + } + + // Param is passed by value, moved + pub fn set_view_type(&mut self, v: ViewTypeIdentifier) { + self.view_type = v; + } +} + +impl ::protobuf::Message for CreateViewRequest { + fn is_initialized(&self) -> bool { + true + } + + fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream<'_>) -> ::protobuf::ProtobufResult<()> { + while !is.eof()? { + let (field_number, wire_type) = is.read_tag_unpack()?; + match field_number { + 1 => { + ::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.app_id)?; + }, + 2 => { + ::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.name)?; + }, + 3 => { + ::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.desc)?; + }, + 4 => { + if wire_type != ::protobuf::wire_format::WireTypeLengthDelimited { + return ::std::result::Result::Err(::protobuf::rt::unexpected_wire_type(wire_type)); + } + self.one_of_thumbnail = ::std::option::Option::Some(CreateViewRequest_oneof_one_of_thumbnail::thumbnail(is.read_string()?)); + }, + 5 => { + ::protobuf::rt::read_proto3_enum_with_unknown_fields_into(wire_type, is, &mut self.view_type, 5, &mut self.unknown_fields)? + }, + _ => { + ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + }, + }; + } + ::std::result::Result::Ok(()) + } + + // Compute sizes of nested messages + #[allow(unused_variables)] + fn compute_size(&self) -> u32 { + let mut my_size = 0; + if !self.app_id.is_empty() { + my_size += ::protobuf::rt::string_size(1, &self.app_id); + } + if !self.name.is_empty() { + my_size += ::protobuf::rt::string_size(2, &self.name); + } + if !self.desc.is_empty() { + my_size += ::protobuf::rt::string_size(3, &self.desc); + } + if self.view_type != ViewTypeIdentifier::Docs { + my_size += ::protobuf::rt::enum_size(5, self.view_type); + } + if let ::std::option::Option::Some(ref v) = self.one_of_thumbnail { + match v { + &CreateViewRequest_oneof_one_of_thumbnail::thumbnail(ref v) => { + my_size += ::protobuf::rt::string_size(4, &v); + }, + }; + } + my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); + self.cached_size.set(my_size); + my_size + } + + fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::ProtobufResult<()> { + if !self.app_id.is_empty() { + os.write_string(1, &self.app_id)?; + } + if !self.name.is_empty() { + os.write_string(2, &self.name)?; + } + if !self.desc.is_empty() { + os.write_string(3, &self.desc)?; + } + if self.view_type != ViewTypeIdentifier::Docs { + os.write_enum(5, ::protobuf::ProtobufEnum::value(&self.view_type))?; + } + if let ::std::option::Option::Some(ref v) = self.one_of_thumbnail { + match v { + &CreateViewRequest_oneof_one_of_thumbnail::thumbnail(ref v) => { + os.write_string(4, v)?; + }, + }; + } + os.write_unknown_fields(self.get_unknown_fields())?; + ::std::result::Result::Ok(()) + } + + fn get_cached_size(&self) -> u32 { + self.cached_size.get() + } + + fn get_unknown_fields(&self) -> &::protobuf::UnknownFields { + &self.unknown_fields + } + + fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields { + &mut self.unknown_fields + } + + fn as_any(&self) -> &dyn (::std::any::Any) { + self as &dyn (::std::any::Any) + } + fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { + self as &mut dyn (::std::any::Any) + } + fn into_any(self: ::std::boxed::Box) -> ::std::boxed::Box { + self + } + + fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor { + Self::descriptor_static() + } + + fn new() -> CreateViewRequest { + CreateViewRequest::new() + } + + fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { + static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT; + descriptor.get(|| { + let mut fields = ::std::vec::Vec::new(); + fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( + "app_id", + |m: &CreateViewRequest| { &m.app_id }, + |m: &mut CreateViewRequest| { &mut m.app_id }, + )); + fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( + "name", + |m: &CreateViewRequest| { &m.name }, + |m: &mut CreateViewRequest| { &mut m.name }, + )); + fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( + "desc", + |m: &CreateViewRequest| { &m.desc }, + |m: &mut CreateViewRequest| { &mut m.desc }, + )); + fields.push(::protobuf::reflect::accessor::make_singular_string_accessor::<_>( + "thumbnail", + CreateViewRequest::has_thumbnail, + CreateViewRequest::get_thumbnail, + )); + fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeEnum>( + "view_type", + |m: &CreateViewRequest| { &m.view_type }, + |m: &mut CreateViewRequest| { &mut m.view_type }, + )); + ::protobuf::reflect::MessageDescriptor::new_pb_name::( + "CreateViewRequest", + fields, + file_descriptor_proto() + ) + }) + } + + fn default_instance() -> &'static CreateViewRequest { + static instance: ::protobuf::rt::LazyV2 = ::protobuf::rt::LazyV2::INIT; + instance.get(CreateViewRequest::new) + } +} + +impl ::protobuf::Clear for CreateViewRequest { + fn clear(&mut self) { + self.app_id.clear(); + self.name.clear(); + self.desc.clear(); + self.one_of_thumbnail = ::std::option::Option::None; + self.view_type = ViewTypeIdentifier::Docs; + self.unknown_fields.clear(); + } +} + +impl ::std::fmt::Debug for CreateViewRequest { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + ::protobuf::text_format::fmt(self, f) + } +} + +impl ::protobuf::reflect::ProtobufValue for CreateViewRequest { + fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef { + ::protobuf::reflect::ReflectValueRef::Message(self) + } +} + +#[derive(PartialEq,Clone,Default)] +pub struct View { + // message fields + pub id: ::std::string::String, + pub app_id: ::std::string::String, + pub name: ::std::string::String, + pub desc: ::std::string::String, + pub view_type: ViewTypeIdentifier, + // special fields + pub unknown_fields: ::protobuf::UnknownFields, + pub cached_size: ::protobuf::CachedSize, +} + +impl<'a> ::std::default::Default for &'a View { + fn default() -> &'a View { + ::default_instance() + } +} + +impl View { + pub fn new() -> View { + ::std::default::Default::default() + } + + // string id = 1; + + + pub fn get_id(&self) -> &str { + &self.id + } + pub fn clear_id(&mut self) { + self.id.clear(); + } + + // Param is passed by value, moved + pub fn set_id(&mut self, v: ::std::string::String) { + self.id = v; + } + + // Mutable pointer to the field. + // If field is not initialized, it is initialized with default value first. + pub fn mut_id(&mut self) -> &mut ::std::string::String { + &mut self.id + } + + // Take field + pub fn take_id(&mut self) -> ::std::string::String { + ::std::mem::replace(&mut self.id, ::std::string::String::new()) + } + + // string app_id = 2; + + + pub fn get_app_id(&self) -> &str { + &self.app_id + } + pub fn clear_app_id(&mut self) { + self.app_id.clear(); + } + + // Param is passed by value, moved + pub fn set_app_id(&mut self, v: ::std::string::String) { + self.app_id = v; + } + + // Mutable pointer to the field. + // If field is not initialized, it is initialized with default value first. + pub fn mut_app_id(&mut self) -> &mut ::std::string::String { + &mut self.app_id + } + + // Take field + pub fn take_app_id(&mut self) -> ::std::string::String { + ::std::mem::replace(&mut self.app_id, ::std::string::String::new()) + } + + // string name = 3; + + + pub fn get_name(&self) -> &str { + &self.name + } + pub fn clear_name(&mut self) { + self.name.clear(); + } + + // Param is passed by value, moved + pub fn set_name(&mut self, v: ::std::string::String) { + self.name = v; + } + + // Mutable pointer to the field. + // If field is not initialized, it is initialized with default value first. + pub fn mut_name(&mut self) -> &mut ::std::string::String { + &mut self.name + } + + // Take field + pub fn take_name(&mut self) -> ::std::string::String { + ::std::mem::replace(&mut self.name, ::std::string::String::new()) + } + + // string desc = 4; + + + pub fn get_desc(&self) -> &str { + &self.desc + } + pub fn clear_desc(&mut self) { + self.desc.clear(); + } + + // Param is passed by value, moved + pub fn set_desc(&mut self, v: ::std::string::String) { + self.desc = v; + } + + // Mutable pointer to the field. + // If field is not initialized, it is initialized with default value first. + pub fn mut_desc(&mut self) -> &mut ::std::string::String { + &mut self.desc + } + + // Take field + pub fn take_desc(&mut self) -> ::std::string::String { + ::std::mem::replace(&mut self.desc, ::std::string::String::new()) + } + + // .ViewTypeIdentifier view_type = 5; + + + pub fn get_view_type(&self) -> ViewTypeIdentifier { + self.view_type + } + pub fn clear_view_type(&mut self) { + self.view_type = ViewTypeIdentifier::Docs; + } + + // Param is passed by value, moved + pub fn set_view_type(&mut self, v: ViewTypeIdentifier) { + self.view_type = v; + } +} + +impl ::protobuf::Message for View { + fn is_initialized(&self) -> bool { + true + } + + fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream<'_>) -> ::protobuf::ProtobufResult<()> { + while !is.eof()? { + let (field_number, wire_type) = is.read_tag_unpack()?; + match field_number { + 1 => { + ::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.id)?; + }, + 2 => { + ::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.app_id)?; + }, + 3 => { + ::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.name)?; + }, + 4 => { + ::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.desc)?; + }, + 5 => { + ::protobuf::rt::read_proto3_enum_with_unknown_fields_into(wire_type, is, &mut self.view_type, 5, &mut self.unknown_fields)? + }, + _ => { + ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + }, + }; + } + ::std::result::Result::Ok(()) + } + + // Compute sizes of nested messages + #[allow(unused_variables)] + fn compute_size(&self) -> u32 { + let mut my_size = 0; + if !self.id.is_empty() { + my_size += ::protobuf::rt::string_size(1, &self.id); + } + if !self.app_id.is_empty() { + my_size += ::protobuf::rt::string_size(2, &self.app_id); + } + if !self.name.is_empty() { + my_size += ::protobuf::rt::string_size(3, &self.name); + } + if !self.desc.is_empty() { + my_size += ::protobuf::rt::string_size(4, &self.desc); + } + if self.view_type != ViewTypeIdentifier::Docs { + my_size += ::protobuf::rt::enum_size(5, self.view_type); + } + my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); + self.cached_size.set(my_size); + my_size + } + + fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::ProtobufResult<()> { + if !self.id.is_empty() { + os.write_string(1, &self.id)?; + } + if !self.app_id.is_empty() { + os.write_string(2, &self.app_id)?; + } + if !self.name.is_empty() { + os.write_string(3, &self.name)?; + } + if !self.desc.is_empty() { + os.write_string(4, &self.desc)?; + } + if self.view_type != ViewTypeIdentifier::Docs { + os.write_enum(5, ::protobuf::ProtobufEnum::value(&self.view_type))?; + } + os.write_unknown_fields(self.get_unknown_fields())?; + ::std::result::Result::Ok(()) + } + + fn get_cached_size(&self) -> u32 { + self.cached_size.get() + } + + fn get_unknown_fields(&self) -> &::protobuf::UnknownFields { + &self.unknown_fields + } + + fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields { + &mut self.unknown_fields + } + + fn as_any(&self) -> &dyn (::std::any::Any) { + self as &dyn (::std::any::Any) + } + fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { + self as &mut dyn (::std::any::Any) + } + fn into_any(self: ::std::boxed::Box) -> ::std::boxed::Box { + self + } + + fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor { + Self::descriptor_static() + } + + fn new() -> View { + View::new() + } + + fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { + static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT; + descriptor.get(|| { + let mut fields = ::std::vec::Vec::new(); + fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( + "id", + |m: &View| { &m.id }, + |m: &mut View| { &mut m.id }, + )); + fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( + "app_id", + |m: &View| { &m.app_id }, + |m: &mut View| { &mut m.app_id }, + )); + fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( + "name", + |m: &View| { &m.name }, + |m: &mut View| { &mut m.name }, + )); + fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( + "desc", + |m: &View| { &m.desc }, + |m: &mut View| { &mut m.desc }, + )); + fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeEnum>( + "view_type", + |m: &View| { &m.view_type }, + |m: &mut View| { &mut m.view_type }, + )); + ::protobuf::reflect::MessageDescriptor::new_pb_name::( + "View", + fields, + file_descriptor_proto() + ) + }) + } + + fn default_instance() -> &'static View { + static instance: ::protobuf::rt::LazyV2 = ::protobuf::rt::LazyV2::INIT; + instance.get(View::new) + } +} + +impl ::protobuf::Clear for View { + fn clear(&mut self) { + self.id.clear(); + self.app_id.clear(); + self.name.clear(); + self.desc.clear(); + self.view_type = ViewTypeIdentifier::Docs; + self.unknown_fields.clear(); + } +} + +impl ::std::fmt::Debug for View { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + ::protobuf::text_format::fmt(self, f) + } +} + +impl ::protobuf::reflect::ProtobufValue for View { + fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef { + ::protobuf::reflect::ReflectValueRef::Message(self) + } +} + +#[derive(Clone,PartialEq,Eq,Debug,Hash)] +pub enum ViewTypeIdentifier { + Docs = 0, +} + +impl ::protobuf::ProtobufEnum for ViewTypeIdentifier { + fn value(&self) -> i32 { + *self as i32 + } + + fn from_i32(value: i32) -> ::std::option::Option { + match value { + 0 => ::std::option::Option::Some(ViewTypeIdentifier::Docs), + _ => ::std::option::Option::None + } + } + + fn values() -> &'static [Self] { + static values: &'static [ViewTypeIdentifier] = &[ + ViewTypeIdentifier::Docs, + ]; + values + } + + fn enum_descriptor_static() -> &'static ::protobuf::reflect::EnumDescriptor { + static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::EnumDescriptor> = ::protobuf::rt::LazyV2::INIT; + descriptor.get(|| { + ::protobuf::reflect::EnumDescriptor::new_pb_name::("ViewTypeIdentifier", file_descriptor_proto()) + }) + } +} + +impl ::std::marker::Copy for ViewTypeIdentifier { +} + +impl ::std::default::Default for ViewTypeIdentifier { + fn default() -> Self { + ViewTypeIdentifier::Docs + } +} + +impl ::protobuf::reflect::ProtobufValue for ViewTypeIdentifier { + fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef { + ::protobuf::reflect::ReflectValueRef::Enum(::protobuf::ProtobufEnum::descriptor(self)) + } +} + +static file_descriptor_proto_data: &'static [u8] = b"\ + \n\x11view_create.proto\"\xb8\x01\n\x11CreateViewRequest\x12\x15\n\x06ap\ + p_id\x18\x01\x20\x01(\tR\x05appId\x12\x12\n\x04name\x18\x02\x20\x01(\tR\ + \x04name\x12\x12\n\x04desc\x18\x03\x20\x01(\tR\x04desc\x12\x1e\n\tthumbn\ + ail\x18\x04\x20\x01(\tH\0R\tthumbnail\x120\n\tview_type\x18\x05\x20\x01(\ + \x0e2\x13.ViewTypeIdentifierR\x08viewTypeB\x12\n\x10one_of_thumbnail\"\ + \x87\x01\n\x04View\x12\x0e\n\x02id\x18\x01\x20\x01(\tR\x02id\x12\x15\n\ + \x06app_id\x18\x02\x20\x01(\tR\x05appId\x12\x12\n\x04name\x18\x03\x20\ + \x01(\tR\x04name\x12\x12\n\x04desc\x18\x04\x20\x01(\tR\x04desc\x120\n\tv\ + iew_type\x18\x05\x20\x01(\x0e2\x13.ViewTypeIdentifierR\x08viewType*\x1e\ + \n\x12ViewTypeIdentifier\x12\x08\n\x04Docs\x10\0J\xc4\x05\n\x06\x12\x04\ + \0\0\x12\x01\n\x08\n\x01\x0c\x12\x03\0\0\x12\n\n\n\x02\x04\0\x12\x04\x02\ + \0\x08\x01\n\n\n\x03\x04\0\x01\x12\x03\x02\x08\x19\n\x0b\n\x04\x04\0\x02\ + \0\x12\x03\x03\x04\x16\n\x0c\n\x05\x04\0\x02\0\x05\x12\x03\x03\x04\n\n\ + \x0c\n\x05\x04\0\x02\0\x01\x12\x03\x03\x0b\x11\n\x0c\n\x05\x04\0\x02\0\ + \x03\x12\x03\x03\x14\x15\n\x0b\n\x04\x04\0\x02\x01\x12\x03\x04\x04\x14\n\ + \x0c\n\x05\x04\0\x02\x01\x05\x12\x03\x04\x04\n\n\x0c\n\x05\x04\0\x02\x01\ + \x01\x12\x03\x04\x0b\x0f\n\x0c\n\x05\x04\0\x02\x01\x03\x12\x03\x04\x12\ + \x13\n\x0b\n\x04\x04\0\x02\x02\x12\x03\x05\x04\x14\n\x0c\n\x05\x04\0\x02\ + \x02\x05\x12\x03\x05\x04\n\n\x0c\n\x05\x04\0\x02\x02\x01\x12\x03\x05\x0b\ + \x0f\n\x0c\n\x05\x04\0\x02\x02\x03\x12\x03\x05\x12\x13\n\x0b\n\x04\x04\0\ + \x08\0\x12\x03\x06\x044\n\x0c\n\x05\x04\0\x08\0\x01\x12\x03\x06\n\x1a\n\ + \x0b\n\x04\x04\0\x02\x03\x12\x03\x06\x1d2\n\x0c\n\x05\x04\0\x02\x03\x05\ + \x12\x03\x06\x1d#\n\x0c\n\x05\x04\0\x02\x03\x01\x12\x03\x06$-\n\x0c\n\ + \x05\x04\0\x02\x03\x03\x12\x03\x0601\n\x0b\n\x04\x04\0\x02\x04\x12\x03\ + \x07\x04%\n\x0c\n\x05\x04\0\x02\x04\x06\x12\x03\x07\x04\x16\n\x0c\n\x05\ + \x04\0\x02\x04\x01\x12\x03\x07\x17\x20\n\x0c\n\x05\x04\0\x02\x04\x03\x12\ + \x03\x07#$\n\n\n\x02\x04\x01\x12\x04\t\0\x0f\x01\n\n\n\x03\x04\x01\x01\ + \x12\x03\t\x08\x0c\n\x0b\n\x04\x04\x01\x02\0\x12\x03\n\x04\x12\n\x0c\n\ + \x05\x04\x01\x02\0\x05\x12\x03\n\x04\n\n\x0c\n\x05\x04\x01\x02\0\x01\x12\ + \x03\n\x0b\r\n\x0c\n\x05\x04\x01\x02\0\x03\x12\x03\n\x10\x11\n\x0b\n\x04\ + \x04\x01\x02\x01\x12\x03\x0b\x04\x16\n\x0c\n\x05\x04\x01\x02\x01\x05\x12\ + \x03\x0b\x04\n\n\x0c\n\x05\x04\x01\x02\x01\x01\x12\x03\x0b\x0b\x11\n\x0c\ + \n\x05\x04\x01\x02\x01\x03\x12\x03\x0b\x14\x15\n\x0b\n\x04\x04\x01\x02\ + \x02\x12\x03\x0c\x04\x14\n\x0c\n\x05\x04\x01\x02\x02\x05\x12\x03\x0c\x04\ + \n\n\x0c\n\x05\x04\x01\x02\x02\x01\x12\x03\x0c\x0b\x0f\n\x0c\n\x05\x04\ + \x01\x02\x02\x03\x12\x03\x0c\x12\x13\n\x0b\n\x04\x04\x01\x02\x03\x12\x03\ + \r\x04\x14\n\x0c\n\x05\x04\x01\x02\x03\x05\x12\x03\r\x04\n\n\x0c\n\x05\ + \x04\x01\x02\x03\x01\x12\x03\r\x0b\x0f\n\x0c\n\x05\x04\x01\x02\x03\x03\ + \x12\x03\r\x12\x13\n\x0b\n\x04\x04\x01\x02\x04\x12\x03\x0e\x04%\n\x0c\n\ + \x05\x04\x01\x02\x04\x06\x12\x03\x0e\x04\x16\n\x0c\n\x05\x04\x01\x02\x04\ + \x01\x12\x03\x0e\x17\x20\n\x0c\n\x05\x04\x01\x02\x04\x03\x12\x03\x0e#$\n\ + \n\n\x02\x05\0\x12\x04\x10\0\x12\x01\n\n\n\x03\x05\0\x01\x12\x03\x10\x05\ + \x17\n\x0b\n\x04\x05\0\x02\0\x12\x03\x11\x04\r\n\x0c\n\x05\x05\0\x02\0\ + \x01\x12\x03\x11\x04\x08\n\x0c\n\x05\x05\0\x02\0\x02\x12\x03\x11\x0b\x0c\ + b\x06proto3\ +"; + +static file_descriptor_proto_lazy: ::protobuf::rt::LazyV2<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::rt::LazyV2::INIT; + +fn parse_descriptor_proto() -> ::protobuf::descriptor::FileDescriptorProto { + ::protobuf::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() +} + +pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto { + file_descriptor_proto_lazy.get(|| { + parse_descriptor_proto() + }) +} diff --git a/rust-lib/flowy-workspace/src/protobuf/model/workspace_create.rs b/rust-lib/flowy-workspace/src/protobuf/model/workspace_create.rs index dd34c7851c..1022d2eabf 100644 --- a/rust-lib/flowy-workspace/src/protobuf/model/workspace_create.rs +++ b/rust-lib/flowy-workspace/src/protobuf/model/workspace_create.rs @@ -225,7 +225,7 @@ impl ::protobuf::reflect::ProtobufValue for CreateWorkspaceRequest { } #[derive(PartialEq,Clone,Default)] -pub struct WorkspaceDetail { +pub struct Workspace { // message fields pub id: ::std::string::String, pub name: ::std::string::String, @@ -235,14 +235,14 @@ pub struct WorkspaceDetail { pub cached_size: ::protobuf::CachedSize, } -impl<'a> ::std::default::Default for &'a WorkspaceDetail { - fn default() -> &'a WorkspaceDetail { - ::default_instance() +impl<'a> ::std::default::Default for &'a Workspace { + fn default() -> &'a Workspace { + ::default_instance() } } -impl WorkspaceDetail { - pub fn new() -> WorkspaceDetail { +impl Workspace { + pub fn new() -> Workspace { ::std::default::Default::default() } @@ -325,7 +325,7 @@ impl WorkspaceDetail { } } -impl ::protobuf::Message for WorkspaceDetail { +impl ::protobuf::Message for Workspace { fn is_initialized(&self) -> bool { true } @@ -409,8 +409,8 @@ impl ::protobuf::Message for WorkspaceDetail { Self::descriptor_static() } - fn new() -> WorkspaceDetail { - WorkspaceDetail::new() + fn new() -> Workspace { + Workspace::new() } fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { @@ -419,34 +419,34 @@ impl ::protobuf::Message for WorkspaceDetail { let mut fields = ::std::vec::Vec::new(); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( "id", - |m: &WorkspaceDetail| { &m.id }, - |m: &mut WorkspaceDetail| { &mut m.id }, + |m: &Workspace| { &m.id }, + |m: &mut Workspace| { &mut m.id }, )); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( "name", - |m: &WorkspaceDetail| { &m.name }, - |m: &mut WorkspaceDetail| { &mut m.name }, + |m: &Workspace| { &m.name }, + |m: &mut Workspace| { &mut m.name }, )); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( "desc", - |m: &WorkspaceDetail| { &m.desc }, - |m: &mut WorkspaceDetail| { &mut m.desc }, + |m: &Workspace| { &m.desc }, + |m: &mut Workspace| { &mut m.desc }, )); - ::protobuf::reflect::MessageDescriptor::new_pb_name::( - "WorkspaceDetail", + ::protobuf::reflect::MessageDescriptor::new_pb_name::( + "Workspace", fields, file_descriptor_proto() ) }) } - fn default_instance() -> &'static WorkspaceDetail { - static instance: ::protobuf::rt::LazyV2 = ::protobuf::rt::LazyV2::INIT; - instance.get(WorkspaceDetail::new) + fn default_instance() -> &'static Workspace { + static instance: ::protobuf::rt::LazyV2 = ::protobuf::rt::LazyV2::INIT; + instance.get(Workspace::new) } } -impl ::protobuf::Clear for WorkspaceDetail { +impl ::protobuf::Clear for Workspace { fn clear(&mut self) { self.id.clear(); self.name.clear(); @@ -455,13 +455,13 @@ impl ::protobuf::Clear for WorkspaceDetail { } } -impl ::std::fmt::Debug for WorkspaceDetail { +impl ::std::fmt::Debug for Workspace { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { ::protobuf::text_format::fmt(self, f) } } -impl ::protobuf::reflect::ProtobufValue for WorkspaceDetail { +impl ::protobuf::reflect::ProtobufValue for Workspace { fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef { ::protobuf::reflect::ReflectValueRef::Message(self) } @@ -470,26 +470,26 @@ impl ::protobuf::reflect::ProtobufValue for WorkspaceDetail { static file_descriptor_proto_data: &'static [u8] = b"\ \n\x16workspace_create.proto\"@\n\x16CreateWorkspaceRequest\x12\x12\n\ \x04name\x18\x01\x20\x01(\tR\x04name\x12\x12\n\x04desc\x18\x02\x20\x01(\ - \tR\x04desc\"I\n\x0fWorkspaceDetail\x12\x0e\n\x02id\x18\x01\x20\x01(\tR\ - \x02id\x12\x12\n\x04name\x18\x02\x20\x01(\tR\x04name\x12\x12\n\x04desc\ - \x18\x03\x20\x01(\tR\x04descJ\xd5\x02\n\x06\x12\x04\0\0\n\x01\n\x08\n\ - \x01\x0c\x12\x03\0\0\x12\n\n\n\x02\x04\0\x12\x04\x02\0\x05\x01\n\n\n\x03\ - \x04\0\x01\x12\x03\x02\x08\x1e\n\x0b\n\x04\x04\0\x02\0\x12\x03\x03\x04\ - \x14\n\x0c\n\x05\x04\0\x02\0\x05\x12\x03\x03\x04\n\n\x0c\n\x05\x04\0\x02\ - \0\x01\x12\x03\x03\x0b\x0f\n\x0c\n\x05\x04\0\x02\0\x03\x12\x03\x03\x12\ - \x13\n\x0b\n\x04\x04\0\x02\x01\x12\x03\x04\x04\x14\n\x0c\n\x05\x04\0\x02\ - \x01\x05\x12\x03\x04\x04\n\n\x0c\n\x05\x04\0\x02\x01\x01\x12\x03\x04\x0b\ - \x0f\n\x0c\n\x05\x04\0\x02\x01\x03\x12\x03\x04\x12\x13\n\n\n\x02\x04\x01\ - \x12\x04\x06\0\n\x01\n\n\n\x03\x04\x01\x01\x12\x03\x06\x08\x17\n\x0b\n\ - \x04\x04\x01\x02\0\x12\x03\x07\x04\x12\n\x0c\n\x05\x04\x01\x02\0\x05\x12\ - \x03\x07\x04\n\n\x0c\n\x05\x04\x01\x02\0\x01\x12\x03\x07\x0b\r\n\x0c\n\ - \x05\x04\x01\x02\0\x03\x12\x03\x07\x10\x11\n\x0b\n\x04\x04\x01\x02\x01\ - \x12\x03\x08\x04\x14\n\x0c\n\x05\x04\x01\x02\x01\x05\x12\x03\x08\x04\n\n\ - \x0c\n\x05\x04\x01\x02\x01\x01\x12\x03\x08\x0b\x0f\n\x0c\n\x05\x04\x01\ - \x02\x01\x03\x12\x03\x08\x12\x13\n\x0b\n\x04\x04\x01\x02\x02\x12\x03\t\ - \x04\x14\n\x0c\n\x05\x04\x01\x02\x02\x05\x12\x03\t\x04\n\n\x0c\n\x05\x04\ - \x01\x02\x02\x01\x12\x03\t\x0b\x0f\n\x0c\n\x05\x04\x01\x02\x02\x03\x12\ - \x03\t\x12\x13b\x06proto3\ + \tR\x04desc\"C\n\tWorkspace\x12\x0e\n\x02id\x18\x01\x20\x01(\tR\x02id\ + \x12\x12\n\x04name\x18\x02\x20\x01(\tR\x04name\x12\x12\n\x04desc\x18\x03\ + \x20\x01(\tR\x04descJ\xd5\x02\n\x06\x12\x04\0\0\n\x01\n\x08\n\x01\x0c\ + \x12\x03\0\0\x12\n\n\n\x02\x04\0\x12\x04\x02\0\x05\x01\n\n\n\x03\x04\0\ + \x01\x12\x03\x02\x08\x1e\n\x0b\n\x04\x04\0\x02\0\x12\x03\x03\x04\x14\n\ + \x0c\n\x05\x04\0\x02\0\x05\x12\x03\x03\x04\n\n\x0c\n\x05\x04\0\x02\0\x01\ + \x12\x03\x03\x0b\x0f\n\x0c\n\x05\x04\0\x02\0\x03\x12\x03\x03\x12\x13\n\ + \x0b\n\x04\x04\0\x02\x01\x12\x03\x04\x04\x14\n\x0c\n\x05\x04\0\x02\x01\ + \x05\x12\x03\x04\x04\n\n\x0c\n\x05\x04\0\x02\x01\x01\x12\x03\x04\x0b\x0f\ + \n\x0c\n\x05\x04\0\x02\x01\x03\x12\x03\x04\x12\x13\n\n\n\x02\x04\x01\x12\ + \x04\x06\0\n\x01\n\n\n\x03\x04\x01\x01\x12\x03\x06\x08\x11\n\x0b\n\x04\ + \x04\x01\x02\0\x12\x03\x07\x04\x12\n\x0c\n\x05\x04\x01\x02\0\x05\x12\x03\ + \x07\x04\n\n\x0c\n\x05\x04\x01\x02\0\x01\x12\x03\x07\x0b\r\n\x0c\n\x05\ + \x04\x01\x02\0\x03\x12\x03\x07\x10\x11\n\x0b\n\x04\x04\x01\x02\x01\x12\ + \x03\x08\x04\x14\n\x0c\n\x05\x04\x01\x02\x01\x05\x12\x03\x08\x04\n\n\x0c\ + \n\x05\x04\x01\x02\x01\x01\x12\x03\x08\x0b\x0f\n\x0c\n\x05\x04\x01\x02\ + \x01\x03\x12\x03\x08\x12\x13\n\x0b\n\x04\x04\x01\x02\x02\x12\x03\t\x04\ + \x14\n\x0c\n\x05\x04\x01\x02\x02\x05\x12\x03\t\x04\n\n\x0c\n\x05\x04\x01\ + \x02\x02\x01\x12\x03\t\x0b\x0f\n\x0c\n\x05\x04\x01\x02\x02\x03\x12\x03\t\ + \x12\x13b\x06proto3\ "; static file_descriptor_proto_lazy: ::protobuf::rt::LazyV2<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::rt::LazyV2::INIT; diff --git a/rust-lib/flowy-workspace/src/protobuf/model/workspace_user_detail.rs b/rust-lib/flowy-workspace/src/protobuf/model/workspace_user_detail.rs index 06507aa745..ca06200372 100644 --- a/rust-lib/flowy-workspace/src/protobuf/model/workspace_user_detail.rs +++ b/rust-lib/flowy-workspace/src/protobuf/model/workspace_user_detail.rs @@ -228,7 +228,7 @@ impl ::protobuf::reflect::ProtobufValue for UserWorkspace { pub struct UserWorkspaceDetail { // message fields pub owner: ::std::string::String, - pub workspace: ::protobuf::SingularPtrField, + pub workspace: ::protobuf::SingularPtrField, // special fields pub unknown_fields: ::protobuf::UnknownFields, pub cached_size: ::protobuf::CachedSize, @@ -271,11 +271,11 @@ impl UserWorkspaceDetail { ::std::mem::replace(&mut self.owner, ::std::string::String::new()) } - // .WorkspaceDetail workspace = 2; + // .Workspace workspace = 2; - pub fn get_workspace(&self) -> &super::workspace_create::WorkspaceDetail { - self.workspace.as_ref().unwrap_or_else(|| ::default_instance()) + pub fn get_workspace(&self) -> &super::workspace_create::Workspace { + self.workspace.as_ref().unwrap_or_else(|| ::default_instance()) } pub fn clear_workspace(&mut self) { self.workspace.clear(); @@ -286,13 +286,13 @@ impl UserWorkspaceDetail { } // Param is passed by value, moved - pub fn set_workspace(&mut self, v: super::workspace_create::WorkspaceDetail) { + pub fn set_workspace(&mut self, v: super::workspace_create::Workspace) { self.workspace = ::protobuf::SingularPtrField::some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. - pub fn mut_workspace(&mut self) -> &mut super::workspace_create::WorkspaceDetail { + pub fn mut_workspace(&mut self) -> &mut super::workspace_create::Workspace { if self.workspace.is_none() { self.workspace.set_default(); } @@ -300,8 +300,8 @@ impl UserWorkspaceDetail { } // Take field - pub fn take_workspace(&mut self) -> super::workspace_create::WorkspaceDetail { - self.workspace.take().unwrap_or_else(|| super::workspace_create::WorkspaceDetail::new()) + pub fn take_workspace(&mut self) -> super::workspace_create::Workspace { + self.workspace.take().unwrap_or_else(|| super::workspace_create::Workspace::new()) } } @@ -401,7 +401,7 @@ impl ::protobuf::Message for UserWorkspaceDetail { |m: &UserWorkspaceDetail| { &m.owner }, |m: &mut UserWorkspaceDetail| { &mut m.owner }, )); - fields.push(::protobuf::reflect::accessor::make_singular_ptr_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage>( + fields.push(::protobuf::reflect::accessor::make_singular_ptr_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage>( "workspace", |m: &UserWorkspaceDetail| { &m.workspace }, |m: &mut UserWorkspaceDetail| { &mut m.workspace }, @@ -443,24 +443,24 @@ impl ::protobuf::reflect::ProtobufValue for UserWorkspaceDetail { static file_descriptor_proto_data: &'static [u8] = b"\ \n\x1bworkspace_user_detail.proto\x1a\x16workspace_create.proto\"H\n\rUs\ erWorkspace\x12\x14\n\x05owner\x18\x01\x20\x01(\tR\x05owner\x12!\n\x0cwo\ - rkspace_id\x18\x02\x20\x01(\tR\x0bworkspaceId\"[\n\x13UserWorkspaceDetai\ - l\x12\x14\n\x05owner\x18\x01\x20\x01(\tR\x05owner\x12.\n\tworkspace\x18\ - \x02\x20\x01(\x0b2\x10.WorkspaceDetailR\tworkspaceJ\xa9\x02\n\x06\x12\ - \x04\0\0\n\x01\n\x08\n\x01\x0c\x12\x03\0\0\x12\n\t\n\x02\x03\0\x12\x03\ - \x01\0\x20\n\n\n\x02\x04\0\x12\x04\x03\0\x06\x01\n\n\n\x03\x04\0\x01\x12\ - \x03\x03\x08\x15\n\x0b\n\x04\x04\0\x02\0\x12\x03\x04\x04\x15\n\x0c\n\x05\ - \x04\0\x02\0\x05\x12\x03\x04\x04\n\n\x0c\n\x05\x04\0\x02\0\x01\x12\x03\ - \x04\x0b\x10\n\x0c\n\x05\x04\0\x02\0\x03\x12\x03\x04\x13\x14\n\x0b\n\x04\ - \x04\0\x02\x01\x12\x03\x05\x04\x1c\n\x0c\n\x05\x04\0\x02\x01\x05\x12\x03\ - \x05\x04\n\n\x0c\n\x05\x04\0\x02\x01\x01\x12\x03\x05\x0b\x17\n\x0c\n\x05\ - \x04\0\x02\x01\x03\x12\x03\x05\x1a\x1b\n\n\n\x02\x04\x01\x12\x04\x07\0\n\ - \x01\n\n\n\x03\x04\x01\x01\x12\x03\x07\x08\x1b\n\x0b\n\x04\x04\x01\x02\0\ - \x12\x03\x08\x04\x15\n\x0c\n\x05\x04\x01\x02\0\x05\x12\x03\x08\x04\n\n\ - \x0c\n\x05\x04\x01\x02\0\x01\x12\x03\x08\x0b\x10\n\x0c\n\x05\x04\x01\x02\ - \0\x03\x12\x03\x08\x13\x14\n\x0b\n\x04\x04\x01\x02\x01\x12\x03\t\x04\"\n\ - \x0c\n\x05\x04\x01\x02\x01\x06\x12\x03\t\x04\x13\n\x0c\n\x05\x04\x01\x02\ - \x01\x01\x12\x03\t\x14\x1d\n\x0c\n\x05\x04\x01\x02\x01\x03\x12\x03\t\x20\ - !b\x06proto3\ + rkspace_id\x18\x02\x20\x01(\tR\x0bworkspaceId\"U\n\x13UserWorkspaceDetai\ + l\x12\x14\n\x05owner\x18\x01\x20\x01(\tR\x05owner\x12(\n\tworkspace\x18\ + \x02\x20\x01(\x0b2\n.WorkspaceR\tworkspaceJ\xa9\x02\n\x06\x12\x04\0\0\n\ + \x01\n\x08\n\x01\x0c\x12\x03\0\0\x12\n\t\n\x02\x03\0\x12\x03\x01\0\x20\n\ + \n\n\x02\x04\0\x12\x04\x03\0\x06\x01\n\n\n\x03\x04\0\x01\x12\x03\x03\x08\ + \x15\n\x0b\n\x04\x04\0\x02\0\x12\x03\x04\x04\x15\n\x0c\n\x05\x04\0\x02\0\ + \x05\x12\x03\x04\x04\n\n\x0c\n\x05\x04\0\x02\0\x01\x12\x03\x04\x0b\x10\n\ + \x0c\n\x05\x04\0\x02\0\x03\x12\x03\x04\x13\x14\n\x0b\n\x04\x04\0\x02\x01\ + \x12\x03\x05\x04\x1c\n\x0c\n\x05\x04\0\x02\x01\x05\x12\x03\x05\x04\n\n\ + \x0c\n\x05\x04\0\x02\x01\x01\x12\x03\x05\x0b\x17\n\x0c\n\x05\x04\0\x02\ + \x01\x03\x12\x03\x05\x1a\x1b\n\n\n\x02\x04\x01\x12\x04\x07\0\n\x01\n\n\n\ + \x03\x04\x01\x01\x12\x03\x07\x08\x1b\n\x0b\n\x04\x04\x01\x02\0\x12\x03\ + \x08\x04\x15\n\x0c\n\x05\x04\x01\x02\0\x05\x12\x03\x08\x04\n\n\x0c\n\x05\ + \x04\x01\x02\0\x01\x12\x03\x08\x0b\x10\n\x0c\n\x05\x04\x01\x02\0\x03\x12\ + \x03\x08\x13\x14\n\x0b\n\x04\x04\x01\x02\x01\x12\x03\t\x04\x1c\n\x0c\n\ + \x05\x04\x01\x02\x01\x06\x12\x03\t\x04\r\n\x0c\n\x05\x04\x01\x02\x01\x01\ + \x12\x03\t\x0e\x17\n\x0c\n\x05\x04\x01\x02\x01\x03\x12\x03\t\x1a\x1bb\ + \x06proto3\ "; static file_descriptor_proto_lazy: ::protobuf::rt::LazyV2<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::rt::LazyV2::INIT; diff --git a/rust-lib/flowy-workspace/src/protobuf/proto/app_create.proto b/rust-lib/flowy-workspace/src/protobuf/proto/app_create.proto index fdb1591a26..10c585b344 100644 --- a/rust-lib/flowy-workspace/src/protobuf/proto/app_create.proto +++ b/rust-lib/flowy-workspace/src/protobuf/proto/app_create.proto @@ -9,7 +9,7 @@ message CreateAppRequest { message ColorStyle { string theme_color = 1; } -message AppDetail { +message App { string id = 1; string workspace_id = 2; string name = 3; diff --git a/rust-lib/flowy-workspace/src/protobuf/proto/errors.proto b/rust-lib/flowy-workspace/src/protobuf/proto/errors.proto index 478a1c052b..32ed650635 100644 --- a/rust-lib/flowy-workspace/src/protobuf/proto/errors.proto +++ b/rust-lib/flowy-workspace/src/protobuf/proto/errors.proto @@ -9,9 +9,12 @@ enum WorkspaceErrorCode { WorkspaceNameInvalid = 1; WorkspaceIdInvalid = 2; AppColorStyleInvalid = 3; - AppIdInvalid = 4; - DatabaseConnectionFail = 5; - WorkspaceDatabaseError = 6; - UserInternalError = 10; - UserNotLoginYet = 11; + AppIdInvalid = 10; + AppNameInvalid = 11; + ViewNameInvalid = 20; + ViewThumbnailName = 21; + DatabaseConnectionFail = 100; + WorkspaceDatabaseError = 101; + UserInternalError = 102; + UserNotLoginYet = 103; } diff --git a/rust-lib/flowy-workspace/src/protobuf/proto/event.proto b/rust-lib/flowy-workspace/src/protobuf/proto/event.proto index bd0776b023..42274c9a32 100644 --- a/rust-lib/flowy-workspace/src/protobuf/proto/event.proto +++ b/rust-lib/flowy-workspace/src/protobuf/proto/event.proto @@ -4,4 +4,5 @@ enum WorkspaceEvent { CreateWorkspace = 0; GetWorkspaceDetail = 1; CreateApp = 101; + CreateView = 201; } diff --git a/rust-lib/flowy-workspace/src/protobuf/proto/view_create.proto b/rust-lib/flowy-workspace/src/protobuf/proto/view_create.proto new file mode 100644 index 0000000000..00d2868e63 --- /dev/null +++ b/rust-lib/flowy-workspace/src/protobuf/proto/view_create.proto @@ -0,0 +1,19 @@ +syntax = "proto3"; + +message CreateViewRequest { + string app_id = 1; + string name = 2; + string desc = 3; + oneof one_of_thumbnail { string thumbnail = 4; }; + ViewTypeIdentifier view_type = 5; +} +message View { + string id = 1; + string app_id = 2; + string name = 3; + string desc = 4; + ViewTypeIdentifier view_type = 5; +} +enum ViewTypeIdentifier { + Docs = 0; +} diff --git a/rust-lib/flowy-workspace/src/protobuf/proto/workspace_create.proto b/rust-lib/flowy-workspace/src/protobuf/proto/workspace_create.proto index 24a35cc49f..0712daf539 100644 --- a/rust-lib/flowy-workspace/src/protobuf/proto/workspace_create.proto +++ b/rust-lib/flowy-workspace/src/protobuf/proto/workspace_create.proto @@ -4,7 +4,7 @@ message CreateWorkspaceRequest { string name = 1; string desc = 2; } -message WorkspaceDetail { +message Workspace { string id = 1; string name = 2; string desc = 3; diff --git a/rust-lib/flowy-workspace/src/protobuf/proto/workspace_user_detail.proto b/rust-lib/flowy-workspace/src/protobuf/proto/workspace_user_detail.proto index 14036d8d00..c43aed0503 100644 --- a/rust-lib/flowy-workspace/src/protobuf/proto/workspace_user_detail.proto +++ b/rust-lib/flowy-workspace/src/protobuf/proto/workspace_user_detail.proto @@ -7,5 +7,5 @@ message UserWorkspace { } message UserWorkspaceDetail { string owner = 1; - WorkspaceDetail workspace = 2; + Workspace workspace = 2; } diff --git a/rust-lib/flowy-workspace/src/services/app_controller.rs b/rust-lib/flowy-workspace/src/services/app_controller.rs index 0c7636abcf..16a2526e92 100644 --- a/rust-lib/flowy-workspace/src/services/app_controller.rs +++ b/rust-lib/flowy-workspace/src/services/app_controller.rs @@ -1,5 +1,5 @@ use crate::{ - entities::app::{AppDetail, CreateAppParams, *}, + entities::app::{App, CreateAppParams, *}, errors::*, module::WorkspaceUser, sql_tables::app::*, @@ -14,15 +14,15 @@ pub struct AppController { impl AppController { pub fn new(user: Arc) -> Self { Self { user } } - pub fn save_app(&self, params: CreateAppParams) -> Result { - let app = AppTable::new(params); + pub fn save_app(&self, params: CreateAppParams) -> Result { + let app_table = AppTable::new(params); let conn = self.user.db_connection()?; - let detail: AppDetail = app.clone().into(); + let app: App = app_table.clone().into(); let _ = diesel::insert_into(app_table::table) - .values(app) + .values(app_table) .execute(&*conn)?; - Ok(detail) + Ok(app) } pub fn update_app(&self, params: UpdateAppParams) -> Result<(), WorkspaceError> { diff --git a/rust-lib/flowy-workspace/src/services/mod.rs b/rust-lib/flowy-workspace/src/services/mod.rs index 0743fa6d23..35c19c299e 100644 --- a/rust-lib/flowy-workspace/src/services/mod.rs +++ b/rust-lib/flowy-workspace/src/services/mod.rs @@ -1,7 +1,9 @@ mod app_controller; mod database; mod helper; +mod view_controller; mod workspace_controller; pub use app_controller::*; +pub use view_controller::*; pub use workspace_controller::*; diff --git a/rust-lib/flowy-workspace/src/services/view_controller.rs b/rust-lib/flowy-workspace/src/services/view_controller.rs new file mode 100644 index 0000000000..2c0507a04e --- /dev/null +++ b/rust-lib/flowy-workspace/src/services/view_controller.rs @@ -0,0 +1,28 @@ +use crate::{ + entities::view::{CreateViewParams, View}, + errors::WorkspaceError, + module::WorkspaceUser, + sql_tables::view::ViewTable, +}; +use flowy_database::{prelude::*, schema::view_table}; +use std::sync::Arc; + +pub struct ViewController { + user: Arc, +} + +impl ViewController { + pub fn new(user: Arc) -> Self { Self { user } } + + pub async fn save_view(&self, params: CreateViewParams) -> Result { + let view_table = ViewTable::new(params); + let conn = self.user.db_connection()?; + let view: View = view_table.clone().into(); + + let _ = diesel::insert_into(view_table::table) + .values(view_table) + .execute(&*conn)?; + + Ok(view) + } +} diff --git a/rust-lib/flowy-workspace/src/services/workspace_controller.rs b/rust-lib/flowy-workspace/src/services/workspace_controller.rs index 8b5fadfdd4..0356cea43b 100644 --- a/rust-lib/flowy-workspace/src/services/workspace_controller.rs +++ b/rust-lib/flowy-workspace/src/services/workspace_controller.rs @@ -15,12 +15,12 @@ impl WorkspaceController { pub async fn save_workspace( &self, params: CreateWorkspaceParams, - ) -> Result { - let workspace = WorkspaceTable::new(params); - let detail: WorkspaceDetail = workspace.clone().into(); + ) -> Result { + let workspace_table = WorkspaceTable::new(params); + let detail: Workspace = workspace_table.clone().into(); let _ = diesel::insert_into(workspace_table::table) - .values(workspace) + .values(workspace_table) .execute(&*(self.user.db_connection()?))?; let _ = self.user.set_cur_workspace_id(&detail.id).await?; diff --git a/rust-lib/flowy-workspace/src/sql_tables/app/app.rs b/rust-lib/flowy-workspace/src/sql_tables/app/app.rs index 89b4b08f80..ea5f4080d7 100644 --- a/rust-lib/flowy-workspace/src/sql_tables/app/app.rs +++ b/rust-lib/flowy-workspace/src/sql_tables/app/app.rs @@ -1,5 +1,5 @@ use crate::{ - entities::app::{AppDetail, ColorStyle, CreateAppParams, UpdateAppParams}, + entities::app::{App, ColorStyle, CreateAppParams, UpdateAppParams}, impl_sql_binary_expression, sql_tables::workspace::WorkspaceTable, }; @@ -9,20 +9,9 @@ use flowy_infra::{timestamp, uuid}; use serde::{Deserialize, Serialize, __private::TryFrom}; use std::convert::TryInto; -#[derive( - PartialEq, - Serialize, - Deserialize, - Clone, - Debug, - Queryable, - Identifiable, - Insertable, - Associations, -)] +#[derive(PartialEq, Clone, Debug, Queryable, Identifiable, Insertable, Associations)] #[belongs_to(WorkspaceTable, foreign_key = "workspace_id")] #[table_name = "app_table"] -#[serde(tag = "type")] pub(crate) struct AppTable { pub id: String, pub workspace_id: String, // equal to #[belongs_to(Workspace, foreign_key = "workspace_id")]. @@ -105,9 +94,9 @@ impl AppTableChangeset { } } -impl std::convert::Into for AppTable { - fn into(self) -> AppDetail { - AppDetail { +impl std::convert::Into for AppTable { + fn into(self) -> App { + App { id: self.id, workspace_id: self.workspace_id, name: self.name, diff --git a/rust-lib/flowy-workspace/src/sql_tables/view/view.rs b/rust-lib/flowy-workspace/src/sql_tables/view/view.rs index e69de29bb2..0557fe884b 100644 --- a/rust-lib/flowy-workspace/src/sql_tables/view/view.rs +++ b/rust-lib/flowy-workspace/src/sql_tables/view/view.rs @@ -0,0 +1,106 @@ +use crate::{ + entities::view::{CreateViewParams, View, ViewTypeIdentifier}, + impl_sql_integer_expression, + sql_tables::app::AppTable, +}; +use diesel::sql_types::Integer; +use flowy_database::schema::{view_table, view_table::dsl}; +use flowy_infra::{timestamp, uuid}; + +#[derive(PartialEq, Clone, Debug, Queryable, Identifiable, Insertable, Associations)] +#[belongs_to(AppTable, foreign_key = "app_id")] +#[table_name = "view_table"] +pub(crate) struct ViewTable { + pub id: String, + pub app_id: String, + pub name: String, + pub desc: String, + pub modified_time: i64, + pub create_time: i64, + pub thumbnail: String, + pub view_type: ViewType, + pub version: i64, +} + +impl ViewTable { + pub fn new(params: CreateViewParams) -> Self { + let view_id = uuid(); + let time = timestamp(); + ViewTable { + id: view_id, + app_id: params.app_id, + name: params.name, + desc: params.desc, + modified_time: time, + create_time: time, + thumbnail: params.thumbnail, + view_type: params.view_type, + version: 0, + } + } +} + +impl std::convert::Into for ViewTable { + fn into(self) -> View { + let view_type = match self.view_type { + ViewType::Docs => ViewTypeIdentifier::Docs, + }; + + View { + id: self.id, + app_id: self.app_id, + name: self.name, + desc: self.desc, + view_type, + } + } +} + +#[derive(AsChangeset, Identifiable, Clone, Default, Debug)] +#[table_name = "view_table"] +pub struct ViewTableChangeset { + pub id: String, + pub name: Option, + pub desc: Option, + pub modified_time: i64, +} + +impl ViewTableChangeset { + pub fn new(id: &str) -> Self { + ViewTableChangeset { + id: id.to_string(), + name: None, + desc: None, + modified_time: timestamp(), + } + } +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash, FromSqlRow, AsExpression)] +#[repr(i32)] +#[sql_type = "Integer"] +pub enum ViewType { + Docs = 0, +} + +impl std::default::Default for ViewType { + fn default() -> Self { ViewType::Docs } +} + +impl std::convert::From for ViewType { + fn from(value: i32) -> Self { + match value { + 0 => ViewType::Docs, + o => { + log::error!("Unsupported view type {}, fallback to ViewType::Docs", o); + ViewType::Docs + }, + } + } +} + +impl ViewType { + pub fn value(&self) -> i32 { *self as i32 } +} + +impl_sql_integer_expression!(ViewType); diff --git a/rust-lib/flowy-workspace/src/sql_tables/workspace/workspace.rs b/rust-lib/flowy-workspace/src/sql_tables/workspace/workspace.rs index 2786b90938..5fb3e20ec8 100644 --- a/rust-lib/flowy-workspace/src/sql_tables/workspace/workspace.rs +++ b/rust-lib/flowy-workspace/src/sql_tables/workspace/workspace.rs @@ -1,11 +1,9 @@ -use crate::entities::workspace::{CreateWorkspaceParams, UpdateWorkspaceParams, WorkspaceDetail}; +use crate::entities::workspace::{CreateWorkspaceParams, UpdateWorkspaceParams, Workspace}; use flowy_database::schema::workspace_table; use flowy_infra::{timestamp, uuid}; -use serde::{Deserialize, Serialize}; -#[derive(PartialEq, Clone, Serialize, Deserialize, Debug, Queryable, Identifiable, Insertable)] +#[derive(PartialEq, Clone, Debug, Queryable, Identifiable, Insertable)] #[table_name = "workspace_table"] -#[serde(tag = "type")] pub struct WorkspaceTable { pub id: String, pub name: String, @@ -59,9 +57,9 @@ impl WorkspaceTableChangeset { } } -impl std::convert::Into for WorkspaceTable { - fn into(self) -> WorkspaceDetail { - WorkspaceDetail { +impl std::convert::Into for WorkspaceTable { + fn into(self) -> Workspace { + Workspace { id: self.id, name: self.name, desc: self.desc, diff --git a/rust-lib/flowy-workspace/tests/event/app_test.rs b/rust-lib/flowy-workspace/tests/event/app_test.rs index 7b2ad2a691..90b2574376 100644 --- a/rust-lib/flowy-workspace/tests/event/app_test.rs +++ b/rust-lib/flowy-workspace/tests/event/app_test.rs @@ -1,7 +1,7 @@ use flowy_test::builder::WorkspaceTestBuilder; use flowy_workspace::{ entities::{ - app::{AppDetail, CreateAppRequest}, + app::{App, CreateAppRequest}, workspace::UserWorkspaceDetail, }, event::WorkspaceEvent::{CreateApp, GetWorkspaceDetail}, @@ -25,7 +25,7 @@ fn app_create_success() { .event(CreateApp) .request(request) .sync_send() - .parse::(); + .parse::(); dbg!(&app_detail); } diff --git a/rust-lib/flowy-workspace/tests/event/workspace_test.rs b/rust-lib/flowy-workspace/tests/event/workspace_test.rs index b6a636176d..8158ee9913 100644 --- a/rust-lib/flowy-workspace/tests/event/workspace_test.rs +++ b/rust-lib/flowy-workspace/tests/event/workspace_test.rs @@ -1,6 +1,6 @@ use crate::helper::*; use flowy_workspace::{ - entities::workspace::{CreateWorkspaceRequest, UserWorkspaceDetail, WorkspaceDetail}, + entities::workspace::{CreateWorkspaceRequest, UserWorkspaceDetail, Workspace}, event::WorkspaceEvent::*, prelude::*, }; @@ -16,7 +16,7 @@ fn workspace_create_success() { .event(CreateWorkspace) .request(request) .sync_send() - .parse::(); + .parse::(); dbg!(&response); } @@ -41,7 +41,7 @@ fn workspace_create_and_then_get_detail_success() { .event(CreateWorkspace) .request(request) .sync_send() - .parse::(); + .parse::(); let user_workspace = WorkspaceTestBuilder::new() .event(GetWorkspaceDetail) From c4ae215746ae09f0799878ba40ad15ea6b547648 Mon Sep 17 00:00:00 2001 From: Jaylen Bian Date: Tue, 20 Jul 2021 11:21:43 +0800 Subject: [PATCH 30/30] [infra_ui] Remove deprecated files --- .../keyboard_web/lib/keyboard_web.dart | 16 ---------------- 1 file changed, 16 deletions(-) delete mode 100644 app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/lib/keyboard_web.dart diff --git a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/lib/keyboard_web.dart b/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/lib/keyboard_web.dart deleted file mode 100644 index 30e6eabb1d..0000000000 --- a/app_flowy/packages/flowy_infra_ui/platform_interface/keyboard_web/lib/keyboard_web.dart +++ /dev/null @@ -1,16 +0,0 @@ -library keyboard_web; - -import 'package:flutter_web_plugins/flutter_web_plugins.dart'; -import 'package:keyboard_platform_interface/keyboard_platform_interface.dart'; - -class KeyboardPlugin extends KeyboardPlatform { - static void registerWith(Registrar registrar) { - KeyboardPlatform.instance = KeyboardPlugin(); - } - - @override - Stream get onKeyboardChange async* { - // suppose that keyboard won't show in web side - yield false; - } -}