-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
apps_list_cubit.dart
341 lines (286 loc) · 10.5 KB
/
apps_list_cubit.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
import 'dart:async';
import 'dart:io' as io;
import 'package:collection/collection.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import '../../../settings/cubit/settings_cubit.dart';
import '../../active_window/active_window.dart';
import '../../app_version/app_version.dart';
import '../../hotkey/global/hotkey_service.dart';
import '../../logs/logs.dart';
import '../../native_platform/native_platform.dart';
import '../../storage/storage_repository.dart';
import '../../system_tray/system_tray.dart';
import '../apps_list.dart';
part 'apps_list_state.dart';
part 'apps_list_cubit.freezed.dart';
class AppsListCubit extends Cubit<AppsListState> {
final HotkeyService _hotkeyService;
final NativePlatform _nativePlatform;
final ProcessRepository _processRepository;
final SettingsCubit _settingsCubit;
final StorageRepository _storage;
final SystemTrayManager _systemTrayManager;
final AppVersion _appVersion;
AppsListCubit({
required HotkeyService hotkeyService,
required NativePlatform nativePlatform,
required ProcessRepository processRepository,
required SettingsCubit settingsCubit,
required StorageRepository storage,
required SystemTrayManager systemTrayManager,
required AppVersion appVersion,
bool testing = false,
}) : _hotkeyService = hotkeyService,
_nativePlatform = nativePlatform,
_settingsCubit = settingsCubit,
_processRepository = processRepository,
_storage = storage,
_systemTrayManager = systemTrayManager,
_appVersion = appVersion,
super(AppsListState.initial()) {
_initialize();
}
Future<void> _initialize() async {
await _fetchWindows();
emit(state.copyWith(loading: false));
setAutoRefresh(
autoRefresh: _settingsCubit.state.autoRefresh,
refreshInterval: _settingsCubit.state.refreshInterval,
);
_listenForHotkey();
_listenForSystemTrayShowEvent();
await fetchVersionData();
}
/// Populate the list of visible windows.
Future<void> _fetchWindows() async {
final windows = await _nativePlatform.windows(
showHidden: _settingsCubit.state.showHiddenWindows,
);
// Filter out windows that are likely not desired or workable,
// for example the root window, unknown (0) pid, etc.
windows.removeWhere((element) => element.process.pid < 10);
for (var i = 0; i < windows.length; i++) {
windows[i] = await _refreshWindowProcess(windows[i]);
}
windows.sortWindows(_settingsCubit.state.pinSuspendedWindows);
emit(state.copyWith(windows: windows));
}
Timer? _timer;
/// The timer which auto-refreshes the list of open windows.
///
/// [refreshInterval] is how often to refresh data, in seconds.
void setAutoRefresh({
required bool autoRefresh,
required int refreshInterval,
}) {
if (_timer != null) _timer?.cancel();
if (autoRefresh) {
_timer = Timer.periodic(
Duration(seconds: refreshInterval),
(timer) => _fetchWindows(),
);
}
}
/// Fetch version data so we can notify user of updates.
@visibleForTesting
Future<void> fetchVersionData() async {
final runningVersion = _appVersion.running();
final latestVersion = await _appVersion.latest();
final String? ignoredUpdate = await _storage.getValue('ignoredUpdate');
final updateHasBeenIgnored = (latestVersion == ignoredUpdate);
final updateAvailable =
(updateHasBeenIgnored) ? false : await _appVersion.updateAvailable();
emit(state.copyWith(
runningVersion: runningVersion,
updateVersion: latestVersion,
updateAvailable: updateAvailable,
));
}
Future<void> manualRefresh() async {
emit(state.copyWith(loading: true));
await _fetchWindows();
emit(state.copyWith(loading: false));
}
/// Set a filter for the windows shown in the list.
Future<void> setWindowFilter(String pattern) async {
emit(state.copyWith(windowFilter: pattern.toLowerCase()));
}
/// Toggle suspend / resume for the process associated with the given window.
Future<bool> toggle(Window window) async {
window = await _refreshWindowProcess(window);
bool successful;
final interaction = (window.process.status == ProcessStatus.suspended)
? InteractionType.resume
: InteractionType.suspend;
log.i('Beginning ${interaction.name} for window: $window');
if (interaction == InteractionType.resume) {
successful = await _resume(window);
} else {
successful = await _suspend(window);
}
log.i('${interaction.name} was successful: $successful');
window = await _refreshWindowProcess(window);
log.i('Window after interaction: $window');
if (!successful) await _addInteractionError(window, interaction);
// Create a copy of the state of windows, with this window's info refreshed.
final windows = [...state.windows];
final index = windows.indexWhere((element) => element.id == window.id);
windows.replaceRange(
index,
index + 1,
[window],
);
windows.sortWindows(_settingsCubit.state.pinSuspendedWindows);
emit(state.copyWith(
windows: windows,
));
return successful;
}
/// Toggle suspend/resume for all instances of [executable].
///
/// For example, if called on mpv and there are multiple windows / instances
/// of the app running, they will all be suspended.
Future<void> toggleExecutable(String executable) async {
final matchingWindows = state //
.windows
.where((e) => e.process.executable == executable);
for (var match in matchingWindows) {
await toggle(match);
}
}
Future<bool> toggleActiveWindow() async {
final activeWindow = ActiveWindow(
_nativePlatform,
_processRepository,
_storage,
);
return await activeWindow.toggle();
}
/// Toggle suspend/resume for all instances of [window.process.executable].
///
/// For example, if called on mpv and there are multiple windows / instances
/// of the app running, they will all be suspended.
Future<void> toggleAll(Window window) async {
final matchingWindows = state //
.windows
.where((e) =>
(e.process.executable == window.process.executable) &&
// Ensure we only perform the intended action. Eg, if we are
// suspending all but some are already suspended we don't want the
// already suspended instances to resume.
(e.process.status == window.process.status));
for (var match in matchingWindows) {
await toggle(match);
}
}
/// React when a configured hotkey is pressed.
void _listenForHotkey() {
_hotkeyService.hotkeyTriggeredStream.listen((hotkey) async {
await manualRefresh();
if (hotkey == _settingsCubit.state.hotKey) {
log.i('Triggering toggle from hotkey press.');
await toggleActiveWindow();
} else {
final appSpecificHotkey = _settingsCubit.state.appSpecificHotKeys
.firstWhereOrNull((e) => e.hotkey == hotkey);
if (appSpecificHotkey == null) return;
log.i('Triggering toggle from app-specific hotkey press.\n'
'Hotkey: $hotkey\n'
'Executable: ${appSpecificHotkey.executable}');
await toggleExecutable(appSpecificHotkey.executable);
}
});
}
/// After the window is shown via the system tray, refresh the list of windows.
void _listenForSystemTrayShowEvent() {
_systemTrayManager.eventStream.listen((event) async {
if (event == SystemTrayEvent.windowShow) {
await manualRefresh();
}
});
}
Future<bool> _resume(Window window) async {
final successful = await _processRepository.resume(window.process.pid);
// Restore the window _after_ resuming or it might not restore.
if (successful) await _restore(window);
return successful;
}
Future<bool> _suspend(Window window) async {
await _minimize(window);
final successful = await _processRepository.suspend(window.process.pid);
// If suspend failed, restore the window so the user won't mistakenly
// think that the suspend was successful.
if (!successful) await _restore(window);
return successful;
}
Future<void> _minimize(Window window) async {
if (!_settingsCubit.state.minimizeWindows) return;
// Minimize the window before suspending or it might not minimize.
await _nativePlatform.minimizeWindow(window.id);
// Small delay on Win32 to ensure the window actually minimizes.
// Doesn't seem to be necessary on Linux.
if (io.Platform.isWindows) {
await Future.delayed(const Duration(milliseconds: 500));
}
}
Future<void> _restore(Window window) async {
if (!_settingsCubit.state.minimizeWindows) return;
await _nativePlatform.restoreWindow(window.id);
}
/// Refresh the process status associated with [window].
Future<Window> _refreshWindowProcess(Window window) async {
final process = window.process;
return window.copyWith(
process: process.copyWith(
status: await _processRepository.getProcessStatus(process.pid),
),
);
}
/// Refresh the process status and add an [InteractionError].
Future<void> _addInteractionError(
Window window,
InteractionType interaction,
) async {
final interactionError = InteractionError(
interactionType: interaction,
statusAfterInteraction: window.process.status,
windowId: window.id,
);
final errors = [...state.interactionErrors] //
..addError(interactionError);
emit(state.copyWith(
interactionErrors: errors,
));
}
@override
Future<void> close() async {
_timer?.cancel();
await super.close();
}
}
extension on List<InteractionError> {
void addError(InteractionError interactionError) {
removeWhere((e) => e.windowId == interactionError.windowId);
add(interactionError);
}
}
extension on List<Window> {
/// Sort the windows by executable name.
///
/// If the user has enabled pinning suspended windows to the top of the list,
/// those windows will be sorted to the top.
void sortWindows(bool pinSuspendedWindows) {
sort((a, b) {
final aIsSuspended = a.process.status == ProcessStatus.suspended;
final bIsSuspended = b.process.status == ProcessStatus.suspended;
if (pinSuspendedWindows) {
if (aIsSuspended && !bIsSuspended) return -1;
if (!aIsSuspended && bIsSuspended) return 1;
}
return a.process.executable.toLowerCase().compareTo(
b.process.executable.toLowerCase(),
);
});
}
}