Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve_wallpaper_performance #290

Merged
merged 4 commits into from
Feb 22, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions lib/l10n/app_de.arb
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,19 @@
"bluetoothStartDiscovery": "Starte Suche",
"bluetoothStopDiscovery": "Stoppe Suche",
"wallpaperPageTitle": "Hintergrund",
"wallpaperPageBackgroundModeLabel": "Hintergrundmodus",
"wallpaperPageBackgroundModeWallpaper": "Hintergrundbild",
"wallpaperPageBackgroundModeColoredBackground": "Farbiger Hintergrund",
"wallpaperPageBackgroundModeImageOfTheDay": "Hintergrund des Tages",
"wallpaperPageYourWallpapersHeadline": "Ihre Hintergründe",
"wallpaperPageDefaultWallpapersHeadline": "Standardhintergründe",
"wallpaperPageColorModeLabel": "Farbmodus",
"wallpaperPageHorizontalGradient": "horizontaler Verlauf",
"wallpaperPageVerticalGradient": "vertikaler Verlauf",
"wallpaperPageSolid": "einfarbig",
"wallpaperPagePickerTitlePrimary": "Wählen Sie die Hauptfarbe",
"wallpaperPagePickerTitleSecondary": "Wählen Sie eine zweite Farbe",
"wallpaperPagePickerWheelHeading": "Farbschattierungen",
"appearancePageTitle": "Erscheinungsbild",
"multiTaskingPageTitle": "Multi-tasking",
"notificationsPageTitle": "Benachrichtigungen",
Expand Down
13 changes: 13 additions & 0 deletions lib/l10n/app_en.arb
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,19 @@
"bluetoothStartDiscovery": "Start discovery",
"bluetoothStopDiscovery": "Stop discovery",
"wallpaperPageTitle": "Wallpaper",
"wallpaperPageBackgroundModeLabel": "Background mode",
"wallpaperPageBackgroundModeWallpaper": "Wallpaper",
"wallpaperPageBackgroundModeColoredBackground": "Colored background",
"wallpaperPageBackgroundModeImageOfTheDay": "Image of the day",
"wallpaperPageYourWallpapersHeadline": "Your wallpapers",
"wallpaperPageDefaultWallpapersHeadline": "Default wallpapers",
"wallpaperPageColorModeLabel": "Color mode",
"wallpaperPageHorizontalGradient": "horizontal gradient",
"wallpaperPageVerticalGradient": "vertical gradient",
"wallpaperPageSolid": "solid",
"wallpaperPagePickerTitlePrimary": "Select a primary color",
"wallpaperPagePickerTitleSecondary": "Select a secondary color",
"wallpaperPagePickerWheelHeading": "Color and shades",
"appearancePageTitle": "Appearance",
"multiTaskingPageTitle": "Multi-tasking",
"notificationsPageTitle": "Notifications",
Expand Down
31 changes: 15 additions & 16 deletions lib/view/pages/wallpaper/color_shading_option_row.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import 'package:flex_color_picker/flex_color_picker.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:settings/l10n/l10n.dart';
import 'package:settings/utils.dart';
import 'package:settings/view/pages/wallpaper/wallpaper_model.dart';
import 'package:yaru_widgets/yaru_widgets.dart';
Expand Down Expand Up @@ -34,17 +35,17 @@ class ColorShadingOptionRow extends StatelessWidget {
DropdownButton<ColorShadingType>(
onChanged: (value) => model.colorShadingType = value,
value: value,
items: const [
items: [
DropdownMenuItem(
child: Text('solid color'),
child: Text(context.l10n.wallpaperPageSolid),
value: ColorShadingType.solid,
),
DropdownMenuItem(
child: Text('horizontal gradient'),
child: Text(context.l10n.wallpaperPageHorizontalGradient),
value: ColorShadingType.horizontal,
),
DropdownMenuItem(
child: Text('vertical gradient'),
child: Text(context.l10n.wallpaperPageVerticalGradient),
value: ColorShadingType.vertical,
),
],
Expand Down Expand Up @@ -87,20 +88,18 @@ class ColorShadingOptionRow extends StatelessWidget {
},
width: 40,
height: 40,
borderRadius: 4,
spacing: 5,
borderRadius: 8,
spacing: 10,
runSpacing: 5,
wheelDiameter: 155,
heading: Text(
primary ? 'Select a primary color' : 'Select a secondary color',
style: Theme.of(context).textTheme.subtitle1,
),
subheading: Text(
'Select color shade',
style: Theme.of(context).textTheme.subtitle1,
primary
? context.l10n.wallpaperPagePickerTitlePrimary
: context.l10n.wallpaperPagePickerTitleSecondary,
style: Theme.of(context).textTheme.titleLarge,
),
wheelSubheading: Text(
'Selected color and its shades',
context.l10n.wallpaperPagePickerWheelHeading,
style: Theme.of(context).textTheme.subtitle1,
),
showMaterialName: true,
Expand All @@ -116,16 +115,16 @@ class ColorShadingOptionRow extends StatelessWidget {
selectedPickerTypeColor: Theme.of(context).colorScheme.primary,
pickersEnabled: const <ColorPickerType, bool>{
ColorPickerType.both: false,
ColorPickerType.primary: true,
ColorPickerType.accent: true,
ColorPickerType.primary: false,
ColorPickerType.accent: false,
ColorPickerType.bw: false,
ColorPickerType.custom: true,
ColorPickerType.wheel: true,
},
).showPickerDialog(
context,
constraints:
const BoxConstraints(minHeight: 480, minWidth: 300, maxWidth: 320),
const BoxConstraints(minHeight: 300, minWidth: 300, maxWidth: 320),
);
}
}
90 changes: 50 additions & 40 deletions lib/view/pages/wallpaper/wallpaper_model.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,27 @@ import 'package:path_provider/path_provider.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

const gnomeWallpaperSuffix = 'file://';
const _gnomeUserWallpaperLocation = '/.local/share/backgrounds/';
const _bingApiUrl =
'https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US';
const _bingUrl = 'http://www.bing.com';
const _nasaUrl =
'https://api.nasa.gov/planetary/apod?api_key=PdQXYMNV2kT9atjMjNI9gbzLqe7qF6TcEHXhexXg';

class WallpaperModel extends SafeChangeNotifier {
final Settings? _wallpaperSettings;
static const _pictureUriKey = 'picture-uri';
static const _preinstalledWallpapersDir = '/usr/share/backgrounds';
static const _colorShadingTypeKey = 'color-shading-type';
static const _primaryColorKey = 'primary-color';
static const _secondaryColorKey = 'secondary-color';

String errorMessage = '';
WallpaperMode wallpaperMode = WallpaperMode.custom;
ImageOfTheDayProvider imageOfTheDayProvider = ImageOfTheDayProvider.bing;


final String? _userWallpapersDir =
Platform.environment['HOME']! + '/.local/share/backgrounds/';
Platform.environment['HOME']! + _gnomeUserWallpaperLocation;

WallpaperModel(SettingsService service)
: _wallpaperSettings = service.lookup(schemaBackground) {
Expand All @@ -36,62 +43,63 @@ class WallpaperModel extends SafeChangeNotifier {
}

String get pictureUri =>
_wallpaperSettings!.stringValue(_pictureUriKey) ?? '';
_wallpaperSettings?.stringValue(_pictureUriKey) ?? '';

set pictureUri(String picPathString) {
_wallpaperSettings!.setValue(
_pictureUriKey, picPathString.isEmpty ? '' : 'file://' + picPathString);
_wallpaperSettings?.setValue(_pictureUriKey,
picPathString.isEmpty ? '' : gnomeWallpaperSuffix + picPathString);
notifyListeners();
}

Future<void> copyToCollection(String picPathString) async {
File image = File(picPathString);
if (_userWallpapersDir != null) return;
await image
.copy(_userWallpapersDir! + File(picPathString).uri.pathSegments.last);
notifyListeners();
}

Future<void> removeFromCollection(String picPathString) async {
final purePath = picPathString.replaceAll('file://', '');
final purePath = picPathString.replaceAll(gnomeWallpaperSuffix, '');
File image = File(purePath);
await image.delete();
notifyListeners();
}

Future<List<String>> get preInstalledBackgrounds async {
Future<List<String>?> get preInstalledBackgrounds async {
return (await getImages(_preinstalledWallpapersDir))
.map((e) => e.path)
?.map((e) => e.path)
.toList();
}

Future<List<String>> get customBackgrounds async {
return (await getImages(_userWallpapersDir!)).map((e) => e.path).toList();
Future<List<String>?> get customBackgrounds async {
return (await getImages(_userWallpapersDir!))?.map((e) => e.path).toList();
}

Future<Iterable<File>> getImages(String dir) async {
Future<Iterable<File>?> getImages(String dir) async {
return (await Directory(dir).list().toList())
.whereType<File>()
.where((element) => lookupMimeType(element.path)!.startsWith('image/'));
}

String get primaryColor =>
_wallpaperSettings!.stringValue(_primaryColorKey) ?? '';
_wallpaperSettings?.stringValue(_primaryColorKey) ?? '';

set primaryColor(String colorHexValueString) {
_wallpaperSettings!.setValue(_primaryColorKey, colorHexValueString);
_wallpaperSettings?.setValue(_primaryColorKey, colorHexValueString);
notifyListeners();
}

String get secondaryColor =>
_wallpaperSettings!.stringValue(_secondaryColorKey) ?? '';
_wallpaperSettings?.stringValue(_secondaryColorKey) ?? '';

set secondaryColor(String colorHexValueString) {
_wallpaperSettings!.setValue(_secondaryColorKey, colorHexValueString);
_wallpaperSettings?.setValue(_secondaryColorKey, colorHexValueString);
notifyListeners();
}

ColorShadingType get colorShadingType {
final type = _wallpaperSettings!.stringValue(_colorShadingTypeKey);
final type = _wallpaperSettings?.stringValue(_colorShadingTypeKey);
return type == 'solid'
? ColorShadingType.solid
: type == 'vertical'
Expand All @@ -102,13 +110,13 @@ class WallpaperModel extends SafeChangeNotifier {
set colorShadingType(ColorShadingType? colorShadingType) {
switch (colorShadingType) {
case ColorShadingType.horizontal:
_wallpaperSettings!.setValue(_colorShadingTypeKey, 'horizontal');
_wallpaperSettings?.setValue(_colorShadingTypeKey, 'horizontal');
break;
case ColorShadingType.vertical:
_wallpaperSettings!.setValue(_colorShadingTypeKey, 'vertical');
_wallpaperSettings?.setValue(_colorShadingTypeKey, 'vertical');
break;
case ColorShadingType.solid:
_wallpaperSettings!.setValue(_colorShadingTypeKey, 'solid');
_wallpaperSettings?.setValue(_colorShadingTypeKey, 'solid');
break;
case null:
return;
Expand Down Expand Up @@ -138,34 +146,32 @@ class WallpaperModel extends SafeChangeNotifier {

void _setFirstWallpaper() async {
final list = await preInstalledBackgrounds;
pictureUri = list.first;
pictureUri = list?.first ?? '';
}

void refreshUrlWallpaper(){
setUrlWallpaperProvider(imageOfTheDayProvider);
}
Future<void> refreshUrlWallpaper() async {
await setUrlWallpaperProvider(imageOfTheDayProvider);
}

Future<void> setUrlWallpaperProvider(
Future<void> setUrlWallpaperProvider(
ImageOfTheDayProvider newImageOfTheDayProvider) async {
errorMessage = '';
//Set the new provider
imageOfTheDayProvider = newImageOfTheDayProvider;

//Load the user's Documents Directory to store the downloaded wallpapers
final Directory directory = await getApplicationDocumentsDirectory();
// Load the user's Documents Directory to store the downloaded wallpapers
final directory = await getApplicationDocumentsDirectory();
final file = File('${directory.path}/${imageOfTheDayProvider.name}.jpeg');

final Map providers = {
'bing': {
'apiUrl':
'https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US',
'apiUrl': _bingApiUrl,
'getImageUrl': (jsonData) {
return 'http://www.bing.com' +
json.decode(jsonData.body)['images'][0]['url'];
return _bingUrl + json.decode(jsonData.body)['images'][0]['url'];
}
},
'nasa': {
'apiUrl':
'https://api.nasa.gov/planetary/apod?api_key=PdQXYMNV2kT9atjMjNI9gbzLqe7qF6TcEHXhexXg', //The api uses my own api_key
'apiUrl': _nasaUrl, //The api uses my own api_key
'getImageUrl': (jsonData) {
return json.decode(jsonData.body)['url'];
}
Expand All @@ -180,18 +186,19 @@ Future<void> setUrlWallpaperProvider(
return currentProvider['getImageUrl'](imageMetadataResponse);
}

String imageUrl = await getImageUrl();
String imageUrl = '';
imageUrl = await getImageUrl().onError((error, stackTrace) {
return errorMessage = error.toString();
});

// Refetch if the image doesn't exist or the current image is older than a day
bool shouldRefetch =
!file.existsSync() || file.lastModifiedSync().day != DateTime.now().day;

if (shouldRefetch) {
if (!file.existsSync() ||
file.lastModifiedSync().day != DateTime.now().day) {
var imageResponse = await http.get(Uri.parse(imageUrl));
await file.writeAsBytes(imageResponse.bodyBytes);
}

//Set the wallpaper to the downloaded image path
// Set the wallpaper to the downloaded image path
pictureUri = file.path;
}
}
Expand All @@ -200,4 +207,7 @@ enum ColorShadingType { solid, vertical, horizontal }

enum WallpaperMode { solid, custom, imageOfTheDay }

enum ImageOfTheDayProvider { bing, nasa,}
enum ImageOfTheDayProvider {
bing,
nasa,
}
Loading