feat: support windows supabase deeplink callback (#3133)

This commit is contained in:
Lucas.Xu
2023-08-07 16:54:50 +07:00
committed by GitHub
parent fbb1753350
commit 95a938657b
8 changed files with 231 additions and 122 deletions

View File

@ -1,15 +1,29 @@
import 'dart:async';
import 'dart:io';
import 'package:appflowy/env/env.dart'; import 'package:appflowy/env/env.dart';
import 'package:appflowy/workspace/application/settings/application_data_storage.dart'; import 'package:appflowy/workspace/application/settings/application_data_storage.dart';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:supabase_flutter/supabase_flutter.dart'; import 'package:supabase_flutter/supabase_flutter.dart';
import 'package:url_protocol/url_protocol.dart';
import 'package:hive_flutter/hive_flutter.dart'; import 'package:hive_flutter/hive_flutter.dart';
import 'package:path/path.dart' as p; import 'package:path/path.dart' as p;
import '../startup.dart'; import '../startup.dart';
// ONLY supports in macOS and Windows now.
//
// If you need to update the schema, please update the following files:
// - appflowy_flutter/macos/Runner/Info.plist (macOS)
// - the callback url in Supabase dashboard
const appflowyDeepLinkSchema = 'appflowy-flutter';
const supabaseLoginCallback = '$appflowyDeepLinkSchema://login-callback';
bool isSupabaseInitialized = false; bool isSupabaseInitialized = false;
const hiveBoxName = 'appflowy_supabase_authentication'; const hiveBoxName = 'appflowy_supabase_authentication';
// Used to store the session of the supabase in case of the user switch the different folder.
Supabase? supabase;
class InitSupabaseTask extends LaunchTask { class InitSupabaseTask extends LaunchTask {
@override @override
Future<void> initialize(LaunchContext context) async { Future<void> initialize(LaunchContext context) async {
@ -20,7 +34,15 @@ class InitSupabaseTask extends LaunchTask {
if (isSupabaseInitialized) { if (isSupabaseInitialized) {
return; return;
} }
await Supabase.initialize(
// register deep link for Windows
if (Platform.isWindows) {
registerProtocolHandler(appflowyDeepLinkSchema);
}
supabase?.dispose();
supabase = null;
supabase = await Supabase.initialize(
url: Env.supabaseUrl, url: Env.supabaseUrl,
anonKey: Env.supabaseAnonKey, anonKey: Env.supabaseAnonKey,
debug: kDebugMode, debug: kDebugMode,

View File

@ -1,6 +1,7 @@
import 'dart:async'; import 'dart:async';
import 'package:appflowy/env/env.dart'; import 'package:appflowy/env/env.dart';
import 'package:appflowy/startup/tasks/prelude.dart';
import 'package:appflowy/user/application/auth/appflowy_auth_service.dart'; import 'package:appflowy/user/application/auth/appflowy_auth_service.dart';
import 'package:appflowy/user/application/auth/auth_service.dart'; import 'package:appflowy/user/application/auth/auth_service.dart';
import 'package:appflowy/user/application/user_service.dart'; import 'package:appflowy/user/application/user_service.dart';
@ -13,9 +14,6 @@ import 'package:flutter/foundation.dart';
import 'package:supabase_flutter/supabase_flutter.dart'; import 'package:supabase_flutter/supabase_flutter.dart';
import 'auth_error.dart'; import 'auth_error.dart';
// can't use underscore here.
const loginCallback = 'io.appflowy.appflowy-flutter://login-callback';
class SupabaseAuthService implements AuthService { class SupabaseAuthService implements AuthService {
SupabaseAuthService(); SupabaseAuthService();
@ -123,7 +121,7 @@ class SupabaseAuthService implements AuthService {
final response = await _auth.signInWithOAuth( final response = await _auth.signInWithOAuth(
provider, provider,
queryParams: queryParamsForProvider(provider), queryParams: queryParamsForProvider(provider),
redirectTo: loginCallback, redirectTo: supabaseLoginCallback,
); );
if (!response) { if (!response) {
completer.complete(left(AuthError.supabaseSignInWithOauthError)); completer.complete(left(AuthError.supabaseSignInWithOauthError));
@ -171,7 +169,7 @@ class SupabaseAuthService implements AuthService {
await _auth.signInWithOtp( await _auth.signInWithOtp(
email: email, email: email,
emailRedirectTo: kIsWeb ? null : loginCallback, emailRedirectTo: kIsWeb ? null : supabaseLoginCallback,
); );
return completer.future; return completer.future;
} }

View File

@ -34,7 +34,7 @@
<string></string> <string></string>
<key>CFBundleURLSchemes</key> <key>CFBundleURLSchemes</key>
<array> <array>
<string>io.appflowy.appflowy-flutter</string> <string>appflowy-flutter</string>
</array> </array>
</dict> </dict>
</array> </array>

View File

@ -1589,6 +1589,15 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "3.0.6" version: "3.0.6"
url_protocol:
dependency: "direct main"
description:
path: "."
ref: HEAD
resolved-ref: "77a84201ed8ca50082f4248f3a373d053b1c0462"
url: "https://github.com/LucasXu0/flutter_url_protocol.git"
source: git
version: "1.0.0"
uuid: uuid:
dependency: transitive dependency: transitive
description: description:

View File

@ -98,6 +98,10 @@ dependencies:
supabase_flutter: ^1.10.4 supabase_flutter: ^1.10.4
envied: ^0.3.0+3 envied: ^0.3.0+3
dotted_border: ^2.0.0+3 dotted_border: ^2.0.0+3
url_protocol:
git:
url: https://github.com/LucasXu0/flutter_url_protocol.git
commit: 77a8420
hive: ^2.2.3 hive: ^2.2.3
hive_flutter: ^1.1.0 hive_flutter: ^1.1.0

View File

@ -8,16 +8,6 @@
int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
_In_ wchar_t *command_line, _In_ int show_command) _In_ wchar_t *command_line, _In_ int show_command)
{ {
HANDLE hMutexInstance = CreateMutex(NULL, TRUE, L"AppFlowyMutex");
HWND handle = FindWindowA(NULL, "AppFlowy");
if (GetLastError() == ERROR_ALREADY_EXISTS) {
WINDOWPLACEMENT place = { sizeof(WINDOWPLACEMENT) };
GetWindowPlacement(handle, &place);
ShowWindow(handle, SW_NORMAL);
return 0;
}
// Attach to console when present (e.g., 'flutter run') or create a // Attach to console when present (e.g., 'flutter run') or create a
// new console when running with a debugger. // new console when running with a debugger.
if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent())
@ -53,6 +43,5 @@ int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
} }
::CoUninitialize(); ::CoUninitialize();
ReleaseMutex(hMutexInstance);
return EXIT_SUCCESS; return EXIT_SUCCESS;
} }

View File

@ -4,7 +4,10 @@
#include "resource.h" #include "resource.h"
namespace { #include "app_links/app_links_plugin_c_api.h"
namespace
{
constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW";
@ -15,21 +18,25 @@ using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd);
// Scale helper to convert logical scaler values to physical using passed in // Scale helper to convert logical scaler values to physical using passed in
// scale factor // scale factor
int Scale(int source, double scale_factor) { int Scale(int source, double scale_factor)
{
return static_cast<int>(source * scale_factor); return static_cast<int>(source * scale_factor);
} }
// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. // Dynamically loads the |EnableNonClientDpiScaling| from the User32 module.
// This API is only needed for PerMonitor V1 awareness mode. // This API is only needed for PerMonitor V1 awareness mode.
void EnableFullDpiSupportIfAvailable(HWND hwnd) { void EnableFullDpiSupportIfAvailable(HWND hwnd)
{
HMODULE user32_module = LoadLibraryA("User32.dll"); HMODULE user32_module = LoadLibraryA("User32.dll");
if (!user32_module) { if (!user32_module)
{
return; return;
} }
auto enable_non_client_dpi_scaling = auto enable_non_client_dpi_scaling =
reinterpret_cast<EnableNonClientDpiScaling *>( reinterpret_cast<EnableNonClientDpiScaling *>(
GetProcAddress(user32_module, "EnableNonClientDpiScaling")); GetProcAddress(user32_module, "EnableNonClientDpiScaling"));
if (enable_non_client_dpi_scaling != nullptr) { if (enable_non_client_dpi_scaling != nullptr)
{
enable_non_client_dpi_scaling(hwnd); enable_non_client_dpi_scaling(hwnd);
FreeLibrary(user32_module); FreeLibrary(user32_module);
} }
@ -38,13 +45,16 @@ void EnableFullDpiSupportIfAvailable(HWND hwnd) {
} // namespace } // namespace
// Manages the Win32Window's window class registration. // Manages the Win32Window's window class registration.
class WindowClassRegistrar { class WindowClassRegistrar
{
public: public:
~WindowClassRegistrar() = default; ~WindowClassRegistrar() = default;
// Returns the singleton registar instance. // Returns the singleton registar instance.
static WindowClassRegistrar* GetInstance() { static WindowClassRegistrar *GetInstance()
if (!instance_) { {
if (!instance_)
{
instance_ = new WindowClassRegistrar(); instance_ = new WindowClassRegistrar();
} }
return instance_; return instance_;
@ -68,8 +78,10 @@ class WindowClassRegistrar {
WindowClassRegistrar *WindowClassRegistrar::instance_ = nullptr; WindowClassRegistrar *WindowClassRegistrar::instance_ = nullptr;
const wchar_t* WindowClassRegistrar::GetWindowClass() { const wchar_t *WindowClassRegistrar::GetWindowClass()
if (!class_registered_) { {
if (!class_registered_)
{
WNDCLASS window_class{}; WNDCLASS window_class{};
window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); window_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
window_class.lpszClassName = kWindowClassName; window_class.lpszClassName = kWindowClassName;
@ -88,23 +100,32 @@ const wchar_t* WindowClassRegistrar::GetWindowClass() {
return kWindowClassName; return kWindowClassName;
} }
void WindowClassRegistrar::UnregisterWindowClass() { void WindowClassRegistrar::UnregisterWindowClass()
{
UnregisterClass(kWindowClassName, nullptr); UnregisterClass(kWindowClassName, nullptr);
class_registered_ = false; class_registered_ = false;
} }
Win32Window::Win32Window() { Win32Window::Win32Window()
{
++g_active_window_count; ++g_active_window_count;
} }
Win32Window::~Win32Window() { Win32Window::~Win32Window()
{
--g_active_window_count; --g_active_window_count;
Destroy(); Destroy();
} }
bool Win32Window::CreateAndShow(const std::wstring &title, bool Win32Window::CreateAndShow(const std::wstring &title,
const Point &origin, const Point &origin,
const Size& size) { const Size &size)
{
if (SendAppLinkToInstance(title))
{
return false;
}
Destroy(); Destroy();
const wchar_t *window_class = const wchar_t *window_class =
@ -122,19 +143,59 @@ bool Win32Window::CreateAndShow(const std::wstring& title,
Scale(size.width, scale_factor), Scale(size.height, scale_factor), Scale(size.width, scale_factor), Scale(size.height, scale_factor),
nullptr, nullptr, GetModuleHandle(nullptr), this); nullptr, nullptr, GetModuleHandle(nullptr), this);
if (!window) { if (!window)
{
return false; return false;
} }
return OnCreate(); return OnCreate();
} }
bool Win32Window::SendAppLinkToInstance(const std::wstring &title)
{
// Find our exact window
HWND hwnd = ::FindWindow(kWindowClassName, title.c_str());
if (hwnd)
{
// Dispatch new link to current window
SendAppLink(hwnd);
// (Optional) Restore our window to front in same state
WINDOWPLACEMENT place = {sizeof(WINDOWPLACEMENT)};
GetWindowPlacement(hwnd, &place);
switch (place.showCmd)
{
case SW_SHOWMAXIMIZED:
ShowWindow(hwnd, SW_SHOWMAXIMIZED);
break;
case SW_SHOWMINIMIZED:
ShowWindow(hwnd, SW_RESTORE);
break;
default:
ShowWindow(hwnd, SW_NORMAL);
break;
}
SetWindowPos(0, HWND_TOP, 0, 0, 0, 0, SWP_SHOWWINDOW | SWP_NOSIZE | SWP_NOMOVE);
SetForegroundWindow(hwnd);
// Window has been found, don't create another one.
return true;
}
return false;
}
// static // static
LRESULT CALLBACK Win32Window::WndProc(HWND const window, LRESULT CALLBACK Win32Window::WndProc(HWND const window,
UINT const message, UINT const message,
WPARAM const wparam, WPARAM const wparam,
LPARAM const lparam) noexcept { LPARAM const lparam) noexcept
if (message == WM_NCCREATE) { {
if (message == WM_NCCREATE)
{
auto window_struct = reinterpret_cast<CREATESTRUCT *>(lparam); auto window_struct = reinterpret_cast<CREATESTRUCT *>(lparam);
SetWindowLongPtr(window, GWLP_USERDATA, SetWindowLongPtr(window, GWLP_USERDATA,
reinterpret_cast<LONG_PTR>(window_struct->lpCreateParams)); reinterpret_cast<LONG_PTR>(window_struct->lpCreateParams));
@ -142,7 +203,9 @@ LRESULT CALLBACK Win32Window::WndProc(HWND const window,
auto that = static_cast<Win32Window *>(window_struct->lpCreateParams); auto that = static_cast<Win32Window *>(window_struct->lpCreateParams);
EnableFullDpiSupportIfAvailable(window); EnableFullDpiSupportIfAvailable(window);
that->window_handle_ = window; that->window_handle_ = window;
} else if (Win32Window* that = GetThisFromHandle(window)) { }
else if (Win32Window *that = GetThisFromHandle(window))
{
return that->MessageHandler(window, message, wparam, lparam); return that->MessageHandler(window, message, wparam, lparam);
} }
@ -153,17 +216,21 @@ LRESULT
Win32Window::MessageHandler(HWND hwnd, Win32Window::MessageHandler(HWND hwnd,
UINT const message, UINT const message,
WPARAM const wparam, WPARAM const wparam,
LPARAM const lparam) noexcept { LPARAM const lparam) noexcept
switch (message) { {
switch (message)
{
case WM_DESTROY: case WM_DESTROY:
window_handle_ = nullptr; window_handle_ = nullptr;
Destroy(); Destroy();
if (quit_on_close_) { if (quit_on_close_)
{
PostQuitMessage(0); PostQuitMessage(0);
} }
return 0; return 0;
case WM_DPICHANGED: { case WM_DPICHANGED:
{
auto newRectSize = reinterpret_cast<RECT *>(lparam); auto newRectSize = reinterpret_cast<RECT *>(lparam);
LONG newWidth = newRectSize->right - newRectSize->left; LONG newWidth = newRectSize->right - newRectSize->left;
LONG newHeight = newRectSize->bottom - newRectSize->top; LONG newHeight = newRectSize->bottom - newRectSize->top;
@ -173,9 +240,11 @@ Win32Window::MessageHandler(HWND hwnd,
return 0; return 0;
} }
case WM_SIZE: { case WM_SIZE:
{
RECT rect = GetClientArea(); RECT rect = GetClientArea();
if (child_content_ != nullptr) { if (child_content_ != nullptr)
{
// Size and position the child window. // Size and position the child window.
MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left,
rect.bottom - rect.top, TRUE); rect.bottom - rect.top, TRUE);
@ -184,7 +253,8 @@ Win32Window::MessageHandler(HWND hwnd,
} }
case WM_ACTIVATE: case WM_ACTIVATE:
if (child_content_ != nullptr) { if (child_content_ != nullptr)
{
SetFocus(child_content_); SetFocus(child_content_);
} }
return 0; return 0;
@ -193,24 +263,29 @@ Win32Window::MessageHandler(HWND hwnd,
return DefWindowProc(window_handle_, message, wparam, lparam); return DefWindowProc(window_handle_, message, wparam, lparam);
} }
void Win32Window::Destroy() { void Win32Window::Destroy()
{
OnDestroy(); OnDestroy();
if (window_handle_) { if (window_handle_)
{
DestroyWindow(window_handle_); DestroyWindow(window_handle_);
window_handle_ = nullptr; window_handle_ = nullptr;
} }
if (g_active_window_count == 0) { if (g_active_window_count == 0)
{
WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); WindowClassRegistrar::GetInstance()->UnregisterWindowClass();
} }
} }
Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { Win32Window *Win32Window::GetThisFromHandle(HWND const window) noexcept
{
return reinterpret_cast<Win32Window *>( return reinterpret_cast<Win32Window *>(
GetWindowLongPtr(window, GWLP_USERDATA)); GetWindowLongPtr(window, GWLP_USERDATA));
} }
void Win32Window::SetChildContent(HWND content) { void Win32Window::SetChildContent(HWND content)
{
child_content_ = content; child_content_ = content;
SetParent(content, window_handle_); SetParent(content, window_handle_);
RECT frame = GetClientArea(); RECT frame = GetClientArea();
@ -221,25 +296,30 @@ void Win32Window::SetChildContent(HWND content) {
SetFocus(child_content_); SetFocus(child_content_);
} }
RECT Win32Window::GetClientArea() { RECT Win32Window::GetClientArea()
{
RECT frame; RECT frame;
GetClientRect(window_handle_, &frame); GetClientRect(window_handle_, &frame);
return frame; return frame;
} }
HWND Win32Window::GetHandle() { HWND Win32Window::GetHandle()
{
return window_handle_; return window_handle_;
} }
void Win32Window::SetQuitOnClose(bool quit_on_close) { void Win32Window::SetQuitOnClose(bool quit_on_close)
{
quit_on_close_ = quit_on_close; quit_on_close_ = quit_on_close;
} }
bool Win32Window::OnCreate() { bool Win32Window::OnCreate()
{
// No-op; provided for subclasses. // No-op; provided for subclasses.
return true; return true;
} }
void Win32Window::OnDestroy() { void Win32Window::OnDestroy()
{
// No-op; provided for subclasses. // No-op; provided for subclasses.
} }

View File

@ -10,15 +10,18 @@
// A class abstraction for a high DPI-aware Win32 Window. Intended to be // A class abstraction for a high DPI-aware Win32 Window. Intended to be
// inherited from by classes that wish to specialize with custom // inherited from by classes that wish to specialize with custom
// rendering and input handling // rendering and input handling
class Win32Window { class Win32Window
{
public: public:
struct Point { struct Point
{
unsigned int x; unsigned int x;
unsigned int y; unsigned int y;
Point(unsigned int x, unsigned int y) : x(x), y(y) {} Point(unsigned int x, unsigned int y) : x(x), y(y) {}
}; };
struct Size { struct Size
{
unsigned int width; unsigned int width;
unsigned int height; unsigned int height;
Size(unsigned int width, unsigned int height) Size(unsigned int width, unsigned int height)
@ -86,6 +89,10 @@ class Win32Window {
// Retrieves a class instance pointer for |window| // Retrieves a class instance pointer for |window|
static Win32Window *GetThisFromHandle(HWND const window) noexcept; static Win32Window *GetThisFromHandle(HWND const window) noexcept;
// Dispatches link if any.
// This method enables our app to be with a single instance too.
bool SendAppLinkToInstance(const std::wstring &title);
bool quit_on_close_ = false; bool quit_on_close_ = false;
// window handle for top level window. // window handle for top level window.