From fde39d9f1273ed820e3dec9eac1d223809975a4b Mon Sep 17 00:00:00 2001 From: JaffaKetchup Date: Mon, 28 Aug 2023 16:15:11 +0100 Subject: [PATCH] Added `CancellableNetworkTileProvider` Added repository metafiles --- .gitignore | 49 ++--- .metadata | 10 + CHANGELOG.md | 5 + CODEOWNERS | 1 + LICENSE | 2 +- README.md | 13 +- analysis_options.yaml | 1 + jaffa_lints.yaml | 185 ++++++++++++++++++ ...flutter_map_cancellable_tile_provider.dart | 157 +++++++++++++++ pubspec.yaml | 30 +++ 10 files changed, 428 insertions(+), 25 deletions(-) create mode 100644 .metadata create mode 100644 CHANGELOG.md create mode 100644 CODEOWNERS create mode 100644 analysis_options.yaml create mode 100644 jaffa_lints.yaml create mode 100644 lib/flutter_map_cancellable_tile_provider.dart create mode 100644 pubspec.yaml diff --git a/.gitignore b/.gitignore index 3a83c2f..96486fd 100644 --- a/.gitignore +++ b/.gitignore @@ -1,27 +1,30 @@ -# See https://www.dartlang.org/guides/libraries/private-files +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ -# Files and directories created by pub +# 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 +# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. +/pubspec.lock +**/doc/api/ .dart_tool/ .packages build/ -# If you're building an application, you may want to check-in your pubspec.lock -pubspec.lock - -# Directory created by dartdoc -# If you don't generate documentation locally you can remove this line. -doc/api/ - -# dotenv environment variables file -.env* - -# Avoid committing generated Javascript files: -*.dart.js -*.info.json # Produced by the --dump-info flag. -*.js # When generated by dart2js. Don't specify *.js if your - # project includes source files written in JavaScript. -*.js_ -*.js.deps -*.js.map - -.flutter-plugins -.flutter-plugins-dependencies diff --git a/.metadata b/.metadata new file mode 100644 index 0000000..672ecbf --- /dev/null +++ b/.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: "e1e47221e86272429674bec4f1bd36acc4fc7b77" + channel: "stable" + +project_type: package diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..01ce391 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,5 @@ +# CHANGELOG + +## 1.0.0-preview + +* Initial version, awaiting flutter_map v6 release before v1 diff --git a/CODEOWNERS b/CODEOWNERS new file mode 100644 index 0000000..23b8c4d --- /dev/null +++ b/CODEOWNERS @@ -0,0 +1 @@ +/lib/ @jaffaketchup \ No newline at end of file diff --git a/LICENSE b/LICENSE index 8c15ca1..502cc77 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ BSD 3-Clause License -Copyright (c) 2023, fleaflet +Copyright (c) 2023, the 'flutter_map' authors and maintainers Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: diff --git a/README.md b/README.md index aaa69c6..d3a6e83 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,13 @@ # flutter_map_cancellable_tile_provider -Plugin for flutter_map that provides a `TileProvider` with the capability to cancel unnecessary HTTP requests + +Plugin for [flutter_map](https://github.com/fleaflet/flutter_map) that provides a `TileProvider` with the capability to cancel unnecessary HTTP requests (on the web) + +- Reduce tile loading durations +- Reduce costly tile requests to tile servers* +- Reduce (cellular) data consumption + +--- + +Unlike `NetworkTileProvider`, this uses '[dio](https://pub.dev/packages/dio)' to support cancelling/aborting unnecessary HTTP requests in-flight. Tiles that are removed/pruned before they are fully loaded do not need to complete loading, and therefore do not need to complete the request/download. This results in the tiles currently in the map's camera/viewport being loaded faster, as the tiles loaded whilst panning, zooming, or rotating are pruned, freeing up HTTP connections. It may also result in a reduction of costs, as there are less full tile requests to your tile server, but this will depend on their backend configuration and how quickly the tile is pruned. + +Note that these advantages only occur on the web, as only the web supports the abortion of HTTP requests. On other platforms, this acts equivalent to `NetworkTileProvider`, except using 'dio' instead of 'http'. diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 0000000..e10581c --- /dev/null +++ b/analysis_options.yaml @@ -0,0 +1 @@ +include: jaffa_lints.yaml \ No newline at end of file diff --git a/jaffa_lints.yaml b/jaffa_lints.yaml new file mode 100644 index 0000000..c7dab10 --- /dev/null +++ b/jaffa_lints.yaml @@ -0,0 +1,185 @@ +linter: + rules: + - always_declare_return_types + - always_require_non_null_named_parameters + - annotate_overrides + - avoid_annotating_with_dynamic + - avoid_catching_errors + - avoid_double_and_int_checks + - avoid_dynamic_calls + - avoid_empty_else + - avoid_escaping_inner_quotes + - avoid_field_initializers_in_const_classes + - avoid_final_parameters + - avoid_function_literals_in_foreach_calls + - avoid_implementing_value_types + - avoid_init_to_null + - avoid_js_rounded_ints + - avoid_multiple_declarations_per_line + - avoid_null_checks_in_equality_operators + - avoid_positional_boolean_parameters + - avoid_print + - avoid_private_typedef_functions + - avoid_redundant_argument_values + - avoid_relative_lib_imports + - avoid_renaming_method_parameters + - avoid_return_types_on_setters + - avoid_returning_null + - avoid_returning_null_for_future + - avoid_returning_null_for_void + - avoid_returning_this + - avoid_setters_without_getters + - avoid_shadowing_type_parameters + - avoid_single_cascade_in_expression_statements + - avoid_slow_async_io + - avoid_type_to_string + - avoid_types_as_parameter_names + - avoid_unnecessary_containers + - avoid_unused_constructor_parameters + - avoid_void_async + - avoid_web_libraries_in_flutter + - await_only_futures + - camel_case_extensions + - camel_case_types + - cancel_subscriptions + - cascade_invocations + - cast_nullable_to_non_nullable + - close_sinks + - comment_references + - conditional_uri_does_not_exist + - constant_identifier_names + - control_flow_in_finally + - curly_braces_in_flow_control_structures + - depend_on_referenced_packages + - deprecated_consistency + - directives_ordering + - do_not_use_environment + - empty_catches + - empty_constructor_bodies + - empty_statements + - eol_at_end_of_file + - exhaustive_cases + - file_names + - hash_and_equals + - implementation_imports + - iterable_contains_unrelated_type + - join_return_with_assignment + - leading_newlines_in_multiline_strings + - library_names + - library_prefixes + - library_private_types_in_public_api + - list_remove_unrelated_type + - literal_only_boolean_expressions + - missing_whitespace_between_adjacent_strings + - no_adjacent_strings_in_list + - no_default_cases + - no_duplicate_case_values + - no_leading_underscores_for_library_prefixes + - no_leading_underscores_for_local_identifiers + - no_logic_in_create_state + - no_runtimeType_toString + - non_constant_identifier_names + - noop_primitive_operations + - null_check_on_nullable_type_parameter + - null_closures + - one_member_abstracts + - only_throw_errors + - overridden_fields + - package_api_docs + - package_names + - package_prefixed_library_names + - parameter_assignments + - prefer_adjacent_string_concatenation + - prefer_asserts_in_initializer_lists + - prefer_asserts_with_message + - prefer_collection_literals + - prefer_conditional_assignment + - prefer_const_constructors + - prefer_const_constructors_in_immutables + - prefer_const_declarations + - prefer_const_literals_to_create_immutables + - prefer_constructors_over_static_methods + - prefer_contains + - prefer_equal_for_default_values + - prefer_expression_function_bodies + - prefer_final_fields + - prefer_final_in_for_each + - prefer_final_locals + - prefer_for_elements_to_map_fromIterable + - prefer_foreach + - prefer_function_declarations_over_variables + - prefer_generic_function_type_aliases + - prefer_if_null_operators + - prefer_initializing_formals + - prefer_inlined_adds + - prefer_int_literals + - prefer_interpolation_to_compose_strings + - prefer_is_empty + - prefer_is_not_empty + - prefer_is_not_operator + - prefer_iterable_whereType + - prefer_mixin + - prefer_null_aware_method_calls + - prefer_null_aware_operators + - prefer_relative_imports + - prefer_single_quotes + - prefer_spread_collections + - prefer_typing_uninitialized_variables + - prefer_void_to_null + - provide_deprecation_message + - recursive_getters + - require_trailing_commas + - secure_pubspec_urls + - sized_box_for_whitespace + - sized_box_shrink_expand + - slash_for_doc_comments + - sort_child_properties_last + - sort_pub_dependencies + - sort_unnamed_constructors_first + - test_types_in_equals + - throw_in_finally + - tighten_type_of_initializing_formals + - type_annotate_public_apis + - type_init_formals + - unawaited_futures + - unnecessary_await_in_return + - unnecessary_brace_in_string_interps + - unnecessary_const + - unnecessary_constructor_name + - unnecessary_getters_setters + - unnecessary_lambdas + - unnecessary_late + - unnecessary_new + - unnecessary_null_aware_assignments + - unnecessary_null_checks + - unnecessary_null_in_if_null_operators + - unnecessary_nullable_for_final_variable_declarations + - unnecessary_overrides + - unnecessary_parenthesis + - unnecessary_raw_strings + - unnecessary_statements + - unnecessary_string_escapes + - unnecessary_string_interpolations + - unnecessary_this + - unrelated_type_equality_checks + - unsafe_html + - use_build_context_synchronously + - use_colored_box + - use_decorated_box + - use_enums + - use_full_hex_values_for_flutter_colors + - use_function_type_syntax_for_parameters + - use_if_null_to_convert_nulls_to_bools + - use_is_even_rather_than_modulo + - use_key_in_widget_constructors + - use_late_for_private_fields_and_variables + - use_named_constants + - use_raw_strings + - use_rethrow_when_possible + - use_setters_to_change_properties + - use_string_buffers + - use_super_parameters + - use_test_throws_matchers + - use_to_and_as_if_applicable + - valid_regexps + - void_checks diff --git a/lib/flutter_map_cancellable_tile_provider.dart b/lib/flutter_map_cancellable_tile_provider.dart new file mode 100644 index 0000000..bb4ecdf --- /dev/null +++ b/lib/flutter_map_cancellable_tile_provider.dart @@ -0,0 +1,157 @@ +import 'dart:async'; +import 'dart:ui'; + +import 'package:dio/dio.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_map/flutter_map.dart'; + +/// [TileProvider] to fetch tiles from the network, with cancellation support +/// +/// Unlike [NetworkTileProvider], this uses [Dio] and supports +/// cancelling/aborting unnecessary HTTP requests in-flight. Tiles that are +/// removed/pruned before they are fully loaded do not need to complete loading, +/// and therefore do not need to complete the request/download. This results in +/// the tiles currently in the map's camera/viewport being loaded faster, as the +/// tiles loaded whilst panning, zooming, or rotating are pruned, freeing up HTTP +/// connections. It may also result in a reduction of costs, as there are less +/// full tile requests to your tile server, but this will depend on their backend +/// configuration and how quickly the tile is pruned. +/// +/// Note that these advantages only occur on the web, as only the web supports +/// the abortion of HTTP requests. On other platforms, this acts equivalent to +/// [NetworkTileProvider], except using 'package:dio' instead of 'package:http'. +/// +/// On the web, the 'User-Agent' header cannot be changed as specified in +/// [TileLayer.tileProvider]'s documentation, due to a Dart/browser limitation. +class CancellableNetworkTileProvider extends TileProvider { + /// Create a [TileProvider] to fetch tiles from the network, with cancellation + /// support + /// + /// Unlike [NetworkTileProvider], this uses [Dio] and supports + /// cancelling/aborting unnecessary HTTP requests in-flight. Tiles that are + /// removed/pruned before they are fully loaded do not need to complete + /// loading, and therefore do not need to complete the request/download. This + /// results in the tiles currently in the map's camera/viewport being loaded + /// faster, as the tiles loaded whilst panning, zooming, or rotating are + /// pruned, freeing up HTTP connections. It may also result in a reduction of + /// costs, as there are less full tile requests to your tile server, but this + /// will depend on their backend configuration and how quickly the tile is + /// pruned. + /// + /// Note that these advantages only occur on the web, as only the web supports + /// the abortion of HTTP requests. On other platforms, this acts equivalent to + /// [NetworkTileProvider], except using 'package:dio' instead of + /// 'package:http'. + /// + /// On the web, the 'User-Agent' header cannot be changed as specified in + /// [TileLayer.tileProvider]'s documentation, due to a Dart/browser limitation. + CancellableNetworkTileProvider({ + super.headers, + }) : _dio = Dio(); + + final Dio _dio; + // ignore: use_late_for_private_fields_and_variables + ImmutableBuffer? _cancelledImage; + + @override + bool get supportsCancelLoading => true; + + @override + ImageProvider getImageWithCancelLoadingSupport( + TileCoordinates coordinates, + TileLayer options, + Future cancelLoading, + ) => + _CNTPImageProvider( + url: getTileUrl(coordinates, options), + fallbackUrl: getTileFallbackUrl(coordinates, options), + tileProvider: this, + cancelLoading: cancelLoading, + ); + + @override + void dispose() { + _dio.close(); + super.dispose(); + } +} + +class _CNTPImageProvider extends ImageProvider<_CNTPImageProvider> { + final String url; + final String? fallbackUrl; + final CancellableNetworkTileProvider tileProvider; + final Future cancelLoading; + + const _CNTPImageProvider({ + required this.url, + required this.fallbackUrl, + required this.tileProvider, + required this.cancelLoading, + }); + + @override + ImageStreamCompleter loadImage( + _CNTPImageProvider key, + ImageDecoderCallback decode, + ) { + final chunkEvents = StreamController(); + + return MultiFrameImageStreamCompleter( + codec: _loadAsync(key, chunkEvents, decode), + chunkEvents: chunkEvents.stream, + scale: 1, + debugLabel: url, + informationCollector: () => [ + DiagnosticsProperty('URL', url), + DiagnosticsProperty('Fallback URL', fallbackUrl), + DiagnosticsProperty('Current provider', key), + ], + ); + } + + @override + Future<_CNTPImageProvider> obtainKey( + ImageConfiguration configuration, + ) => + SynchronousFuture<_CNTPImageProvider>(this); + + Future _loadAsync( + _CNTPImageProvider key, + StreamController chunkEvents, + ImageDecoderCallback decode, { + bool useFallback = false, + }) async { + final cancelToken = CancelToken(); + unawaited(cancelLoading.then((_) => cancelToken.cancel())); + + final Uint8List bytes; + try { + final response = await tileProvider._dio.get( + useFallback ? fallbackUrl! : url, + cancelToken: cancelToken, + options: Options( + headers: tileProvider.headers, + responseType: ResponseType.bytes, + ), + ); + bytes = response.data!; + } on DioException catch (err) { + if (CancelToken.isCancel(err)) { + return decode( + tileProvider._cancelledImage ??= await ImmutableBuffer.fromUint8List( + TileProvider.transparentImage, + ), + ); + } + if (useFallback || fallbackUrl == null) rethrow; + return _loadAsync(key, chunkEvents, decode, useFallback: true); + } catch (_) { + if (useFallback || fallbackUrl == null) rethrow; + return _loadAsync(key, chunkEvents, decode, useFallback: true); + } + + cancelLoading.ignore(); + return decode(await ImmutableBuffer.fromUint8List(bytes)); + } +} diff --git a/pubspec.yaml b/pubspec.yaml new file mode 100644 index 0000000..12d727e --- /dev/null +++ b/pubspec.yaml @@ -0,0 +1,30 @@ +name: flutter_map_cancellable_tile_provider +description: Plugin for flutter_map that provides a `TileProvider` with the capability to cancel unnecessary HTTP requests +version: 1.0.0-preview + +homepage: https://github.com/fleaflet/flutter_map +repository: https://github.com/fleaflet/flutter_map_cancellable_tile_provider +issue_tracker: https://github.com/fleaflet/flutter_map/issues +documentation: https://docs.fleaflet.dev + +topics: + - flutter-map + - map + +platforms: + android: + ios: + linux: + macos: + web: + windows: + +environment: + sdk: '>=3.0.0 <4.0.0' + flutter: ">=3.10.0" + +dependencies: + dio: ^5.3.2 + flutter: + sdk: flutter + flutter_map: ^6.0.0-dev.3