forked from GitJournal/GitJournal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.dart
352 lines (300 loc) · 10.4 KB
/
app.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
/*
* SPDX-FileCopyrightText: 2019-2021 Vishesh Handa <[email protected]>
*
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:gitjournal/analytics/analytics.dart';
import 'package:gitjournal/analytics/route_observer.dart';
import 'package:gitjournal/app_router.dart';
import 'package:gitjournal/change_notifiers.dart';
import 'package:gitjournal/core/folder/notes_folder_config.dart';
import 'package:gitjournal/core/link.dart';
import 'package:gitjournal/core/views/note_links_view.dart';
import 'package:gitjournal/error_reporting.dart';
import 'package:gitjournal/iap/iap.dart';
import 'package:gitjournal/l10n.dart';
import 'package:gitjournal/logger/logger.dart';
import 'package:gitjournal/repository_manager.dart';
import 'package:gitjournal/screens/error_screen.dart';
import 'package:gitjournal/settings/app_config.dart';
import 'package:gitjournal/settings/settings.dart';
import 'package:gitjournal/settings/storage_config.dart';
import 'package:gitjournal/themes.dart';
import 'package:hive/hive.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'package:provider/provider.dart';
import 'package:quick_actions/quick_actions.dart';
import 'package:receive_sharing_intent/receive_sharing_intent.dart';
import 'package:sentry_flutter/sentry_flutter.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:universal_io/io.dart' show Directory, Platform;
class JournalApp extends StatefulWidget {
static Future<void> main(SharedPreferences pref) async {
await Log.init();
Log.i("--------------------------------");
Log.i("--------------------------------");
Log.i("--------------------------------");
Log.i("--------- App Launched ---------");
Log.i("--------------------------------");
Log.i("--------------------------------");
Log.i("--------------------------------");
var appConfig = AppConfig.instance;
Log.i("AppConfig", props: appConfig.toMap());
_enableAnalyticsIfPossible(appConfig, pref);
final gitBaseDirectory = (await getApplicationDocumentsDirectory()).path;
final cacheDir = (await getApplicationSupportDirectory()).path;
Hive.init(cacheDir);
Hive.registerAdapter(LinkAdapter());
Hive.registerAdapter(LinksListAdapter());
var repoManager = RepositoryManager(
gitBaseDir: gitBaseDirectory,
cacheDir: cacheDir,
pref: pref,
);
// Ignore the error, the router will show an error screen
await repoManager.buildActiveRepository();
GitJournalInAppPurchases.confirmProPurchaseBoot();
runApp(
GitJournalChangeNotifiers(
repoManager: repoManager,
appConfig: appConfig,
pref: pref,
child: JournalApp(repoManager: repoManager),
),
);
}
// TODO: All this logic should go inside the analytics package
static Future<void> _enableAnalyticsIfPossible(
AppConfig appConfig,
SharedPreferences pref,
) async {
var supportDir = await getApplicationSupportDirectory();
var analyticsStorage = p.join(supportDir.path, 'analytics');
await Directory(analyticsStorage).create(recursive: true);
var analytics = await Analytics.init(
pref: pref,
analyticsCallback: captureErrorBreadcrumb,
storagePath: analyticsStorage,
);
analytics.setUserProperty(
name: 'proMode',
value: appConfig.proMode.toString(),
);
}
final RepositoryManager repoManager;
const JournalApp({super.key, required this.repoManager});
@override
JournalAppState createState() => JournalAppState();
}
class JournalAppState extends State<JournalApp> {
final _navigatorKey = GlobalKey<NavigatorState>();
String? _pendingShortcut;
StreamSubscription? _intentDataStreamSubscription;
var _sharedText = "";
var _sharedImages = <String>[];
@override
void initState() {
super.initState();
if (!Platform.isAndroid && !Platform.isIOS) {
return;
}
const quickActions = QuickActions();
quickActions.initialize((String shortcutType) {
Log.i("Quick Action Open: $shortcutType");
if (_navigatorKey.currentState == null) {
Log.i("Quick Action delegating for after build");
WidgetsBinding.instance
.addPostFrameCallback((_) => _afterBuild(context));
setState(() {
_pendingShortcut = shortcutType;
});
return;
}
_navigatorKey.currentState!
.pushNamed(AppRoute.NewNotePrefix + shortcutType);
quickActions.setShortcutItems(<ShortcutItem>[
ShortcutItem(
type: 'Markdown',
localizedTitle: context.loc.actionsNewNote,
icon: "ic_markdown",
),
ShortcutItem(
type: 'Checklist',
localizedTitle: context.loc.actionsNewChecklist,
icon: "ic_tasks",
),
ShortcutItem(
type: 'Journal',
localizedTitle: context.loc.actionsNewJournal,
icon: "ic_book",
),
]);
});
_initShareSubscriptions();
}
void _afterBuild(BuildContext context) {
if (_pendingShortcut != null) {
var routeName = AppRoute.NewNotePrefix + _pendingShortcut!;
_navigatorKey.currentState!.pushNamed(routeName);
_pendingShortcut = null;
}
}
void _handleShare(Duration _) {
var noText = _sharedText.isEmpty;
var noImages = _sharedImages.isEmpty;
if (noText && noImages) {
return;
}
var folderConfig = context.read<NotesFolderConfig>();
var editor = folderConfig.defaultEditor.toInternalString();
_navigatorKey.currentState!.pushNamed(AppRoute.NewNotePrefix + editor);
}
@visibleForTesting
void handleSharedMedia(Iterable<SharedMediaFile> media) {
_sharedImages = [];
_sharedText = "";
// if (value.startsWith('gitjournal-identity://')) return;
for (var m in media) {
switch (m.type) {
case SharedMediaType.image:
Log.d("Received Image Share $m");
_sharedImages.add(m.path);
break;
case SharedMediaType.video:
Log.d("Received Video Share $m");
Log.d("Video sharing is not supported");
break;
case SharedMediaType.url:
Log.d("Received URL Share $m");
_sharedText =
_sharedText.isEmpty ? m.path : "$_sharedText\n${m.path}";
break;
case SharedMediaType.text:
Log.d("Received Text Share $m");
_sharedText =
_sharedText.isEmpty ? m.path : "$_sharedText\n${m.path}";
break;
case SharedMediaType.file:
Log.d("Received File Share $m");
Log.d("File sharing is not supported");
break;
}
Log.d("Received Media Share $m");
}
WidgetsBinding.instance.addPostFrameCallback(_handleShare);
}
void _initShareSubscriptions() {
if (!Platform.isAndroid && !Platform.isIOS) {
return;
}
// For sharing text and images coming from outside the app while the app is in the memory
_intentDataStreamSubscription = ReceiveSharingIntent.instance
.getMediaStream()
.listen((List<SharedMediaFile> value) {
Log.d("Received Media Share $value");
handleSharedMedia(value);
}, onError: (err) {
Log.e("getIntentDataStream error: $err");
});
// For sharing text and images coming from outside the app while the app is closed
ReceiveSharingIntent.instance
.getInitialMedia()
.then((List<SharedMediaFile> value) {
Log.d("Received MediaFile Share with App (media): $value");
handleSharedMedia(value);
});
}
@override
void dispose() {
_intentDataStreamSubscription?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
var repo = widget.repoManager.currentRepo;
// Repository.load can be quite slow, especially because of the 'git commit'
// on booting
// FIXME: Make Settings not depend on Repository
late Settings settings;
try {
settings = context.watch<Settings>();
} catch (_) {
return const SizedBox();
}
// FIXME: Settings can be null in this case!
AppRouter? router;
var themeMode = ThemeMode.system;
if (repo != null) {
var appConfig = context.watch<AppConfig>();
var storageConfig = context.watch<StorageConfig>();
router = AppRouter(
settings: settings,
appConfig: appConfig,
storageConfig: storageConfig,
);
themeMode = settings.theme.toThemeMode();
}
var initialRoute =
router != null ? router.initialRoute() : ErrorScreen.routePath;
/*
Also use -
* https://github.com/bernaferrari/RandomColorScheme
* https://pub.dev/packages/color_blindness
const FlexSchemeData customFlexScheme = FlexSchemeData(
name: 'Toledo purple',
description: 'Purple theme created from custom defined colors.',
light: FlexSchemeColor(
primary: Color(0xFF66bb6a),
primaryVariant: Color(0xFF338a3e),
secondary: Color(0xff6d4c41),
secondaryVariant: Color(0xFF338a3e),
),
dark: FlexSchemeColor(
primary: Color(0xff212121),
primaryVariant: Color(0xffc8635f),
secondary: Color(0xff689f38),
secondaryVariant: Color(0xff00be00),
),
);
*/
var locale = Locale(settings.locale);
var lSplit = settings.locale.split("_");
if (lSplit.length > 1) {
locale = Locale(lSplit[0], lSplit[1]);
}
return MaterialApp(
key: const ValueKey("App"),
navigatorKey: _navigatorKey,
title: 'GitJournal',
localizationsDelegates: gitJournalLocalizationDelegates,
supportedLocales: gitJournalSupportedLocales,
locale: locale,
theme: Themes.fromName(settings.lightTheme),
darkTheme: Themes.fromName(settings.darkTheme),
themeMode: themeMode,
navigatorObservers: <NavigatorObserver>[
AnalyticsRouteObserver(),
SentryNavigatorObserver(),
],
initialRoute: initialRoute,
debugShowCheckedModeBanner: false,
//debugShowMaterialGrid: true,
onGenerateRoute: (rs) {
if (router == null || repo == null) {
return MaterialPageRoute(
settings: rs,
builder: (context) => const ErrorScreen(),
);
}
var r = router.generateRoute(rs, repo, _sharedText, _sharedImages, () {
_sharedText = "";
_sharedImages = [];
});
return r;
},
);
}
}