diff options
Diffstat (limited to 'lib/model')
121 files changed, 14673 insertions, 0 deletions
diff --git a/lib/model/app/contributors.dart b/lib/model/app/contributors.dart new file mode 100644 index 0000000..ae583e2 --- /dev/null +++ b/lib/model/app/contributors.dart @@ -0,0 +1,200 @@ +class Contributors { + static const translators = { + Contributor('D3ZOXY', 'its.ghost.message@gmail.com'), + Contributor('JanWaldhorn', 'weblate@jwh.anonaddy.com'), + Contributor('n-berenice', null), + Contributor('Jonatas de Almeida Barros', 'ajonatas56@gmail.com'), + Contributor('MeFinity', 'me.dot.finity@gmail.com'), + Contributor('Maki', null), + Contributor('HiSubway', 'shenyusoftware@gmail.com'), + Contributor('glemco', 'glemco@posteo.net'), + Contributor('Aerowolf', null), + Contributor('小默', 'duzhe163908@gmail.com'), + Contributor('metezd', 'itoldyouthat@protonmail.com'), + Contributor('Martijn Fabrie', null), + Contributor('Koen Koppens', 'koenkoppens@proton.me'), + Contributor('Emmanouil Papavergis', null), + Contributor('kha84', 'khalukhin@gmail.com'), + Contributor('gallegonovato', 'fran-carro@hotmail.es'), + Contributor('Havokdan', 'havokdan@yahoo.com.br'), + Contributor('Jean Mareilles', 'waged1266@tutanota.com'), + Contributor('이정희', 'daemul72@gmail.com'), + Contributor('Translator-3000', 'weblate.m1d0h@8shield.net'), + Contributor('Ralea Adrian Vicențiu', 'ralea.adrian@gmail.com'), + Contributor('Igor Sorocean', 'sorocean.igor@gmail.com'), + Contributor('JY3', 'GeeyunJY3@gmail.com'), + Contributor('Gediminas Murauskas', 'muziejusinfo@gmail.com'), + Contributor('Oğuz Ersen', 'oguz@ersen.moe'), + Contributor('Allan Nordhøy', 'epost@anotheragency.no'), + Contributor('pemibe', 'pemibe4634@dmonies.com'), + Contributor('Linerly', 'linerly@proton.me'), + Contributor('Skrripy', 'rozihrash.ya6w7@simplelogin.com'), + Contributor('vesp', 'vesp@post.cz'), + Contributor('Dan', 'denqwerta@gmail.com'), + Contributor('Tijolinho', 'pedrohenrique29.alfenas@gmail.com'), + Contributor('Piotr K', '1337.kelt@gmail.com'), + Contributor('rehork', 'cooky@e.email'), + Contributor('Eric', 'zxmegaxqug@hldrive.com'), // @hamburger2048 / 大王叫我来巡山 + Contributor('Aitor Salaberria', 'trslbrr@gmail.com'), + Contributor('Felipe Nogueira', 'contato.fnog@gmail.com'), + Contributor('kaajjo', 'claymanoff@gmail.com'), + Contributor('Eduardo Malaspina', 'vaio0@swismail.com'), + Contributor('Evgeniy Khramov', 'thejenjagamertjg@gmail.com'), + Contributor('syu_pf_ssy', 'syu.pf.ssy@outlook.com'), + Contributor('Dick Pluim', 'github@dickpluim.com'), + Contributor('György Viktor', 'wickdj@gmail.com'), + Contributor('byPety', 'peter@csordascsalad.hu'), + Contributor('tryvseu', 'tryvseu@tuta.io'), + Contributor('陳義昇', 'love80312@gmail.com'), + Contributor('Макар Разин', 'makarrazin14@gmail.com'), + Contributor('Leon', 'leonhoog@outlook.com'), + Contributor('stephen-cusi', 'magiskcurry@qq.com'), + Contributor('atilluF', '110931720+atilluF@users.noreply.github.com'), + Contributor('Davide Neri', 'davnerix@gmail.com'), + Contributor('ShiftCtrlAltDel', 'who--is@yandex.ru'), + Contributor('lol lol', 'besonderspositiverpanda@ji5.de'), + Contributor('Fabian Rennebeck', 'propago47@posteo.org'), + Contributor('Henry The Mole', 'htmole@gmail.com'), + Contributor('Kryštof Černý', 'cleverline1mc@gmail.com'), + Contributor('marciozomb13', 'marciozomb13@outlook.com'), + Contributor('yangyangdaji', '1504305527@qq.com'), + Contributor('ngocanhtve', 'ngocanh.tve@gmail.com'), + Contributor('Le Nhut Binh', 'bebinh2202@gmail.com'), + Contributor('Martin Frandel', 'martinko.fr@gmail.com'), + Contributor('Milan Šalka', 'salka.milan@googlemail.com'), + Contributor('Diviega Ayulsa', 'ayulsadiviega@gmail.com'), + Contributor('Fqwe1', 'Fqwe1@users.noreply.hosted.weblate.org'), + Contributor('Reza Almanda', 'rezaalmanda27@gmail.com'), + Contributor('Sveinn í Felli', 'sv1@fellsnet.is'), + Contributor('Henning Bunk', 'henningtbunk@gmail.com'), + Contributor('Samirah Ail', 'samiratalzahrani@gmail.com'), + Contributor('Salih Ail', 'rrrfff444@gmail.com'), + Contributor('Nasreddine Loukriz', 'nasreddineloukriz@gmail.com'), + Contributor('Mohamed Zeroug', 'mzeroug19@gmail.com'), + Contributor('ssantos', 'ssantos@web.de'), + Contributor('Сергій', 'sergiy.goncharuk.1@gmail.com'), + Contributor('v1s7', 'v1s7@users.noreply.hosted.weblate.org'), + Contributor('fuzfyy', 'egeozce35@gmail.com'), + Contributor('minh', 'teaminh@skiff.com'), + Contributor('luckris25', 'lk1thebestl@gmail.com'), + Contributor('Marc Amorós', 'marquitus99@gmail.com'), + Contributor('elea11', 'p.manuel.warnecke@gmail.com'), + Contributor('しいたけ', 'Shiitake@users.noreply.hosted.weblate.org'), + Contributor('wanzh', 'wanzh66666@gmail.com'), + Contributor('ID J', 'tabby4442@gmail.com'), + Contributor('randint', 'lancameb@hotmail.com'), + Contributor('امیر جهانگرد', 'ijahangard.a@gmail.com'), + Contributor('slasb37', 'p84haghi@gmail.com'), + Contributor('mimvahedi', 'vahedi0vahedi@gmail.com'), + Contributor('Alireza Rashidi', 'alirezarashidigoorabi@gmail.com'), + Contributor('何意挽秋風', '94283631+RejectVanity@users.noreply.github.com'), + Contributor('cheese', 'deanlemans5646@gmail.com'), + Contributor('Owen Elderbroek', 'o.elderbroek@gmail.com'), + Contributor('Maxi', 'maxitendo01@proton.me'), + Contributor('Jerguš Fonfer', 'caro.jf@protonmail.com'), + Contributor('elfriob', 'elfriob@ya.ru'), + Contributor('Stephan Paternotte', 'stephan@paternottes.net'), + Contributor('Tung Anh', 'buihuutunganh2007@gmail.com'), + Contributor('Adrien N', 'adriennathaniel1999@gmail.com'), + Contributor('Shift18', 'bribable.lawyer@posteo.net'), + Contributor('Andreas Håll', 'ante_skalman@hotmail.com'), + Contributor('Scorza9999', 'oliva.scorza@gmail.com'), + Contributor('Taufan', 'taufanxxx@gmail.com'), + Contributor('Leo Aaua Felix', 'g00g7el@gmail.com'), + Contributor('-J-', 'heyj0e@tuta.io'), + Contributor('bittin', 'bittin@reimu.nl'), + Contributor('splice11', 'trenchedgrandpa@protonmail.com'), + Contributor('Ihor Hordiichuk', 'igor_ck@outlook.com'), + Contributor('João Palmeiro', 'joaommpalmeiro@gmail.com'), + Contributor('Whoever4976', 'wolffjonas47@gmail.com'), + Contributor('Your Average Code', 'neumeiersi91358@th-nuernberg.de'), + Contributor('Paranoid Android', 'f.cherdzhiev@innopolis.university'), + Contributor('Noah Kenzie Rodriguez-Beus', 'noahbeus@protonmail.com'), + Contributor('5FeetUnder', '15950507+5FeetUnder@users.noreply.github.com'), + Contributor('Cleverson Cândido', 'optimuspraimu@gmail.com'), + Contributor('Hasan Kara', 'hasanbeytullahkara@gmail.com'), + Contributor('Thomas Di Cristofaro', 'hostedweblate.8347@tdc.akamail.it'), + Contributor('Petrov', 'i_v_c@mail.ru'), + Contributor('தமிழ்நேரம்', 'anishprabu.t@gmail.com'), + Contributor('bovirus', 'roberto.boriotti@canon.it'), + Contributor('Максим Горпиніч', 'maksimgorpinic2005a@gmail.com'), + Contributor('Priit Jõerüüt', 'hwlate@joeruut.com'), + Contributor('Dr Hieu', 'v7pvas7m@anonaddy.com'), + Contributor('Saúl Palacios', 'palacios22c@gmail.com'), + Contributor('Grooty12', 'Rasmus@rosendahl-kaa.name'), + Contributor('Victor M', 'victormorita@tuta.io'), + Contributor('cat', 'catsnote@proton.me'), + Contributor('Bruno Fragoso', 'darth_signa@hotmail.com'), + Contributor('hugoalh', 'hugoalh@users.noreply.hosted.weblate.org'), + Contributor('Josep M. Ferrer', 'txemaq@gmail.com'), + Contributor('pitroig', 'ona@riseup.net'), + Contributor('Rubén Castiñeiras Lorenzo', 'rcasl@outlook.com'), + Contributor('hanyang cheng', 'cinxiafortis@tutanota.de'), + Contributor('Chethan', 'chethan@users.noreply.hosted.weblate.org'), + Contributor('Prasannakumar T Bhat', 'pbhat99@gmail.com'), + Contributor('Bora Atıcı', 'boratici.acc@gmail.com'), + Contributor('Ettore Atalan', 'atalanttore@googlemail.com'), + Contributor('VertekPlus', 'vertekplus@users.noreply.hosted.weblate.org'), + Contributor('slabs37', 'p84haghi@gmail.com'), + Contributor('GiannosOB', 'giannos2105@gmail.com'), + Contributor('Miquel Martí', 'miquelmarti111@gmail.com'), + Contributor('Yurt Page', 'yurtpage@gmail.com'), + Contributor('Murcielago', 'weblate.j9bmx@slmail.me'), + Contributor('vm', 'varga.m007@gmail.com'), + Contributor('WMatheist', 'wmatheist@protonmail.com'), + Contributor('Daniel Nylander', 'daniel@danielnylander.se'), + Contributor('Alioc', 'hit.177411245@gmail.com'), + Contributor('Sasi Ba', 'sasiba8328@fuasha.com'), + Contributor('Sevect', 'sevect@users.noreply.hosted.weblate.org'), + Contributor('Star Athendwyl', 'weblate.tyke961@passmail.net'), + Contributor('Marija Grineviciute', 'marijagrine@protonmail.com'), + Contributor('Hasan Berat Kaylan', 'hasanberatkaylan@gmail.com'), + Contributor('Mahyar-Saberifard', 'mahyarsaberi20@gmail.com'), + Contributor('ggLuigi_Ching', 'chingy.cyl@gmail.com'), + Contributor('Åzze', 'laitinen.jere222@gmail.com'), + Contributor('Olli', 'ollinen@ollit.dev'), + Contributor('Ricky Tigg', 'ricky.tigg@gmail.com'), + Contributor('Oris5', 'otso.karttunen@gmail.com'), + Contributor('nullspace', 'jxhchina@gmail.com'), + Contributor('dcre', 'realdcre@users.noreply.hosted.weblate.org'), + Contributor('AUGANOS', 'giannoskai@proton.me'), + Contributor('H@di', 'hadi@hadisafari.ir'), + Contributor('Kachelkaiser', 'kachelkaiser@htpst.de'), + Contributor('Kiril Panayotov', 'eccyboo@protonmail.com'), + Contributor('Xusi Fons', 'xusi@keemail.me'), + Contributor('abc0922001', 'abc0922001@hotmail.com'), + // Contributor('Femini', 'nizamismidov4@gmail.com'), // Azerbaijani + // Contributor('Jamil Farajov', 'jamilfarajov@gmail.com'), // Azerbaijani + // Contributor('Alvi Khan', 'aveenalvi@gmail.com'), // Bengali + // Contributor('Htet Oo Hlaing', 'htetoh2006@outlook.com'), // Burmese + // Contributor('Khant', 'khant@users.noreply.hosted.weblate.org'), // Burmese + // Contributor('Thit Lwin', 'thitlwincoder@gmail.com'), // Burmese + // Contributor('Idj', 'joneltmp+goahn@gmail.com'), // Hebrew + // Contributor('elid', 'shopisrael12@gmail.com'), // Hebrew + // Contributor('Rohit Burman', 'rohitburman31p@rediffmail.com'), // Hindi + // Contributor('AJ07', 'ajaykumarmeena676@gmail.com'), // Hindi + // Contributor('Sartaj', 'ssaarrttaajj111@gmail.com'), // Hindi + // Contributor('Anurag Samota', 'anuragsamotasamota@gmail.com'), // Hindi + // Contributor('GoRaN', 'gorangharib.909@gmail.com'), // Kurdish (Central) + // Contributor('Rasti K5', 'rasti.khdhr@gmail.com'), // Kurdish (Central) + // Contributor('CYAXXX', 'ferhad.hasan9624@gmail.com'), // Kurdish (Northern) + // Contributor('Cx', 'cyax1@proton.me'), // Kurdish (Northern) + // Contributor('Raman', 'xysed@tutanota.com'), // Malayalam + // Contributor('Akhil Raj', 'akhilakae07@gmail.com'), // Malayalam + // Contributor('Over Barrow', 'rawixo6748@insfou.com'), // Nepali + // Contributor('Subham Jena', 'subhamjena8465@gmail.com'), // Odia + // Contributor('Prasanta-Hembram', 'Prasantahembram720@gmail.com'), // Santali + // Contributor('Enenra', 'nnra2210@gmail.com'), // Serbian + // Contributor('Nikola Perović', 'nikolaperovicccc@gmail.com'), // Serbian + // Contributor('mytja', 'mamnju21@gmail.com'), // Slovenian + // Contributor('Nattapong K', 'mixer5056@gmail.com'), // Thai + // Contributor('Feliks-WR', 'aq.1428@tuta.io'), // Urdu + }; +} + +class Contributor { + final String name; + final String? weblateEmail; + + const Contributor(this.name, this.weblateEmail); +} diff --git a/lib/model/app/dependencies.dart b/lib/model/app/dependencies.dart new file mode 100644 index 0000000..1f4c132 --- /dev/null +++ b/lib/model/app/dependencies.dart @@ -0,0 +1,410 @@ +import 'package:aves/app_flavor.dart'; + +class Dependencies { + static const String apache2 = 'Apache License 2.0'; + static const String bsd2 = 'BSD 2-Clause “Simplified” License'; + static const String bsd3 = 'BSD 3-Clause “Revised” License'; + static const String eclipse1 = 'Eclipse Public License 1.0'; + static const String lgpl3 = 'GNU Lesser General Public License v3.0'; + static const String mit = 'MIT License'; + static const String zlib = 'zlib License'; + + static const List<Dependency> androidDependencies = [ + Dependency( + name: 'AndroidSVG (Aves fork)', + license: apache2, + sourceUrl: 'https://github.com/deckerst/androidsvg', + ), + Dependency( + name: 'AndroidX (Core Kotlin, Exifinterface, Lifecycle Process, Multidex)', + license: apache2, + sourceUrl: 'https://android.googlesource.com/platform/frameworks/support/+/androidx-main/core/core-ktx', + ), + Dependency( + name: 'CWAC-Document', + license: apache2, + sourceUrl: 'https://github.com/commonsguy/cwac-document', + ), + Dependency( + name: 'Glide', + license: '$apache2, $bsd2', + sourceUrl: 'https://github.com/bumptech/glide', + ), + Dependency( + name: 'Metadata Extractor', + license: apache2, + sourceUrl: 'https://github.com/drewnoakes/metadata-extractor', + ), + Dependency( + name: 'MP4 Parser (Aves fork)', + license: apache2, + sourceUrl: 'https://github.com/deckerst/mp4parser', + ), + Dependency( + name: 'PixyMeta Android (Aves fork)', + license: eclipse1, + sourceUrl: 'https://github.com/deckerst/pixymeta-android', + ), + Dependency( + name: 'Tiff Bitmap Factory (Aves fork)', + license: mit, + sourceUrl: 'https://github.com/deckerst/Android-TiffBitmapFactory', + ), + ]; + + static const List<Dependency> _flutterPluginsCommon = [ + Dependency( + name: 'Connectivity Plus', + license: bsd3, + sourceUrl: 'https://github.com/fluttercommunity/plus_plugins/tree/main/packages/connectivity_plus', + ), + Dependency( + name: 'Device Info Plus', + license: bsd3, + sourceUrl: 'https://github.com/fluttercommunity/plus_plugins/tree/main/packages/device_info_plus', + ), + Dependency( + name: 'Dynamic Color', + license: apache2, + sourceUrl: 'https://github.com/material-foundation/flutter-packages/tree/main/packages/dynamic_color', + ), + Dependency( + name: 'Floating', + license: mit, + sourceUrl: 'https://github.com/wrbl606/floating', + ), + Dependency( + name: 'Flutter Display Mode', + license: mit, + sourceUrl: 'https://github.com/ajinasokan/flutter_displaymode', + ), + Dependency( + name: 'Local Auth', + license: bsd3, + sourceUrl: 'https://github.com/flutter/packages/tree/main/packages/local_auth/local_auth', + ), + Dependency( + name: 'Media Kit', + license: mit, + sourceUrl: 'https://github.com/media-kit/media-kit', + ), + Dependency( + name: 'Network Info Plus', + license: bsd3, + sourceUrl: 'https://github.com/fluttercommunity/plus_plugins/tree/main/packages/network_info_plus', + ), + Dependency( + name: 'Package Info Plus', + license: bsd3, + sourceUrl: 'https://github.com/fluttercommunity/plus_plugins/tree/main/packages/package_info_plus', + ), + Dependency( + name: 'Permission Handler', + license: mit, + sourceUrl: 'https://github.com/Baseflow/flutter-permission-handler', + ), + Dependency( + name: 'Printing', + license: apache2, + sourceUrl: 'https://github.com/DavBfr/dart_pdf', + ), + Dependency( + name: 'Screen Brightness', + license: mit, + sourceUrl: 'https://github.com/aaassseee/screen_brightness', + ), + Dependency( + name: 'Shared Preferences', + license: bsd3, + sourceUrl: 'https://github.com/flutter/packages/tree/main/packages/shared_preferences/shared_preferences', + ), + Dependency( + name: 'sqflite', + license: bsd2, + sourceUrl: 'https://github.com/tekartik/sqflite', + ), + Dependency( + name: 'Streams Channel (Aves fork)', + license: apache2, + sourceUrl: 'https://github.com/deckerst/aves_streams_channel', + ), + Dependency( + name: 'URL Launcher', + license: bsd3, + sourceUrl: 'https://github.com/flutter/packages/tree/main/packages/url_launcher/url_launcher', + ), + Dependency( + name: 'Volume Controller', + license: mit, + sourceUrl: 'https://github.com/kurenai7968/volume_controller', + ), + ]; + + static const List<Dependency> _googleMobileServices = [ + Dependency( + name: 'Google API Availability', + license: mit, + sourceUrl: 'https://github.com/Baseflow/flutter-google-api-availability', + ), + Dependency( + name: 'Google Maps for Flutter', + license: bsd3, + sourceUrl: 'https://github.com/flutter/packages/tree/main/packages/google_maps_flutter/google_maps_flutter', + ), + ]; + + static const List<Dependency> _flutterPluginsIzzyOnly = [ + ..._googleMobileServices, + ]; + + static const List<Dependency> _flutterPluginsLibreOnly = []; + + static const List<Dependency> _flutterPluginsPlayOnly = [ + ..._googleMobileServices, + Dependency( + name: 'FlutterFire (Core, Crashlytics)', + license: bsd3, + sourceUrl: 'https://github.com/FirebaseExtended/flutterfire', + ), + ]; + + static List<Dependency> flutterPlugins(AppFlavor flavor) => [ + ..._flutterPluginsCommon, + if (flavor == AppFlavor.izzy) ..._flutterPluginsIzzyOnly, + if (flavor == AppFlavor.libre) ..._flutterPluginsLibreOnly, + if (flavor == AppFlavor.play) ..._flutterPluginsPlayOnly, + ]; + + static const List<Dependency> flutterPackages = [ + Dependency( + name: 'Charts (Aves fork)', + license: apache2, + sourceUrl: 'https://github.com/deckerst/flutter_google_charts', + ), + Dependency( + name: 'Custom rounded rectangle border', + license: mit, + sourceUrl: 'https://github.com/lekanbar/custom_rounded_rectangle_border', + ), + Dependency( + name: 'Decorated Icon', + license: mit, + sourceUrl: 'https://github.com/benPesso/flutter_decorated_icon', + ), + Dependency( + name: 'Expansion Tile Card (Aves fork)', + license: bsd3, + sourceUrl: 'https://github.com/deckerst/expansion_tile_card', + ), + Dependency( + name: 'FlexColorPicker', + license: bsd3, + sourceUrl: 'https://github.com/rydmike/flex_color_picker', + ), + Dependency( + name: 'Flutter Highlight', + license: mit, + sourceUrl: 'https://github.com/git-touch/highlight', + ), + Dependency( + name: 'Flutter Map', + license: bsd3, + sourceUrl: 'https://github.com/fleaflet/flutter_map', + ), + Dependency( + name: 'Flutter Markdown Plus', + license: bsd3, + sourceUrl: 'https://github.com/foresightmobile/flutter_markdown_plus', + ), + Dependency( + name: 'Flutter Staggered Animations', + license: mit, + sourceUrl: 'https://github.com/mobiten/flutter_staggered_animations', + ), + Dependency( + name: 'Material Design Icons Flutter', + license: mit, + sourceUrl: 'https://github.com/ziofat/material_design_icons_flutter', + ), + Dependency( + name: 'Material Symbols Icons for Flutter', + license: apache2, + sourceUrl: 'https://github.com/timmaffett/material_symbols_icons', + ), + Dependency( + name: 'Overlay Support', + license: apache2, + sourceUrl: 'https://github.com/boyan01/overlay_support', + ), + Dependency( + name: 'Palette Generator', + license: bsd3, + sourceUrl: 'https://github.com/flutter/packages/tree/main/packages/palette_generator', + ), + Dependency( + name: 'Panorama (Aves fork)', + license: apache2, + sourceUrl: 'https://github.com/deckerst/aves_panorama', + ), + Dependency( + name: 'Pattern Lock', + license: apache2, + sourceUrl: 'https://github.com/qwert2603/pattern_lock', + ), + Dependency( + name: 'Percent Indicator', + license: bsd2, + sourceUrl: 'https://github.com/diegoveloper/flutter_percent_indicator', + ), + Dependency( + name: 'Pin Code Fields', + license: mit, + sourceUrl: 'https://github.com/adar2378/pin_code_fields', + ), + Dependency( + name: 'Provider', + license: mit, + sourceUrl: 'https://github.com/rrousselGit/provider', + ), + Dependency( + name: 'Smooth Page Indicator', + license: mit, + sourceUrl: 'https://github.com/Milad-Akarie/smooth_page_indicator', + ), + Dependency( + name: 'Vector Map Tiles', + license: bsd3, + sourceUrl: 'https://github.com/greensopinion/flutter-vector-map-tiles', + ), + Dependency( + name: 'Vector Tile Renderer', + license: bsd3, + sourceUrl: 'https://github.com/greensopinion/dart-vector-tile-renderer', + ), + ]; + + static const List<Dependency> dartPackages = [ + Dependency( + name: 'Collection', + license: bsd3, + sourceUrl: 'https://github.com/dart-lang/collection', + ), + Dependency( + name: 'Country Code', + license: mit, + sourceUrl: 'https://github.com/denixport/dart.country', + ), + Dependency( + name: 'CSV', + license: mit, + sourceUrl: 'https://github.com/close2/csv', + ), + Dependency( + name: 'DLNA Dart', + license: bsd3, + sourceUrl: 'https://github.com/suconghou/dlna-dart', + ), + Dependency( + name: 'Equatable', + license: mit, + sourceUrl: 'https://github.com/felangel/equatable', + ), + Dependency( + name: 'Event Bus', + license: mit, + sourceUrl: 'https://github.com/marcojakob/dart-event-bus', + ), + Dependency( + name: 'Fluster', + license: mit, + sourceUrl: 'https://github.com/alfonsocejudo/fluster', + ), + Dependency( + name: 'Flutter Lints', + license: bsd3, + sourceUrl: 'https://github.com/flutter/packages/tree/main/packages/flutter_lints', + ), + Dependency( + name: 'Get It', + license: mit, + sourceUrl: 'https://github.com/fluttercommunity/get_it', + ), + Dependency( + name: 'GPX', + license: apache2, + sourceUrl: 'https://github.com/kb0/dart-gpx', + ), + Dependency( + name: 'HTTP', + license: bsd3, + sourceUrl: 'https://github.com/dart-lang/http', + ), + Dependency( + name: 'Intl', + license: bsd3, + sourceUrl: 'https://github.com/dart-lang/intl', + ), + Dependency( + name: 'LatLong2', + license: apache2, + sourceUrl: 'https://github.com/jifalops/dart-latlong', + ), + Dependency( + name: 'Memory Leak Tracker', + license: bsd3, + sourceUrl: 'https://github.com/dart-lang/leak_tracker', + ), + Dependency( + name: 'Path', + license: bsd3, + sourceUrl: 'https://github.com/dart-lang/path', + ), + Dependency( + name: 'PDF for Dart and Flutter', + license: apache2, + sourceUrl: 'https://github.com/DavBfr/dart_pdf', + ), + Dependency( + name: 'Proj4dart', + license: mit, + sourceUrl: 'https://github.com/maRci002/proj4dart', + ), + Dependency( + name: 'Shelf', + license: bsd3, + sourceUrl: 'https://github.com/dart-lang/shelf', + ), + Dependency( + name: 'Stack Trace', + license: bsd3, + sourceUrl: 'https://github.com/dart-lang/stack_trace', + ), + Dependency( + name: 'Synchronized', + license: mit, + sourceUrl: 'https://github.com/tekartik/synchronized.dart/tree/master/synchronized', + ), + Dependency( + name: 'Vector Math', + license: '$zlib, $bsd3', + sourceUrl: 'https://github.com/google/vector_math.dart', + ), + Dependency( + name: 'XML', + license: mit, + sourceUrl: 'https://github.com/renggli/dart-xml', + ), + ]; +} + +class Dependency { + final String name; + final String license; + final String sourceUrl; + + const Dependency({ + required this.name, + required this.license, + required this.sourceUrl, + }); +} diff --git a/lib/model/app/intent.dart b/lib/model/app/intent.dart new file mode 100644 index 0000000..ee4985b --- /dev/null +++ b/lib/model/app/intent.dart @@ -0,0 +1,27 @@ +class IntentActions { + static const edit = 'edit'; + static const pickItems = 'pick_items'; + static const pickCollectionFilters = 'pick_collection_filters'; + static const screenSaver = 'screen_saver'; + static const screenSaverSettings = 'screen_saver_settings'; + static const search = 'search'; + static const setWallpaper = 'set_wallpaper'; + static const view = 'view'; + static const viewGeo = 'view_geo'; + static const widgetOpen = 'widget_open'; + static const widgetSettings = 'widget_settings'; +} + +class IntentDataKeys { + static const action = 'action'; + static const allowMultiple = 'allowMultiple'; + static const brightness = 'brightness'; + static const explorerPath = 'explorerPath'; + static const filters = 'filters'; + static const mimeType = 'mimeType'; + static const page = 'page'; + static const query = 'query'; + static const secureUris = 'secureUris'; + static const uri = 'uri'; + static const widgetId = 'widgetId'; +} diff --git a/lib/model/app/permissions.dart b/lib/model/app/permissions.dart new file mode 100644 index 0000000..3104272 --- /dev/null +++ b/lib/model/app/permissions.dart @@ -0,0 +1,16 @@ +import 'package:permission_handler/permission_handler.dart'; + +class Permissions { + static const storage = [ + Permission.storage, + // for media access on Android >=13 + Permission.photos, + Permission.videos, + ]; + + static const mediaAccess = [ + ...storage, + // to access media with unredacted metadata with scoped storage (Android >=10) + Permission.accessMediaLocation, + ]; +} diff --git a/lib/model/app/support.dart b/lib/model/app/support.dart new file mode 100644 index 0000000..c2e6da2 --- /dev/null +++ b/lib/model/app/support.dart @@ -0,0 +1,80 @@ +import 'package:aves/ref/mime_types.dart'; + +class AppSupport { + // TODO TLAD [codec] make it dynamic if it depends on OS/lib versions + static const Set<String> undecodableImages = { + MimeTypes.art, + MimeTypes.cdr, + MimeTypes.crw, + MimeTypes.djvu, + MimeTypes.dwg, + MimeTypes.dxf, + MimeTypes.flic, + MimeTypes.jpeg2000, + MimeTypes.jxl, + MimeTypes.pat, + MimeTypes.pcx, + MimeTypes.pnm, + MimeTypes.psdVnd, + MimeTypes.psdX, + MimeTypes.octetStream, + MimeTypes.rgbe, + MimeTypes.tap, + MimeTypes.wmf, + MimeTypes.zip, + }; + + static bool canDecode(String mimeType) => !undecodableImages.contains(mimeType); + + // `exifinterface` v1.3.3 declared support for DNG, but it strips non-standard Exif tags when saving attributes, + // and DNG requires DNG-specific tags saved along standard Exif. So it was actually breaking DNG files. + static bool canEditExif(String mimeType) { + switch (mimeType.toLowerCase()) { + // as of androidx.exifinterface:exifinterface:1.3.4 + case MimeTypes.jpeg: + case MimeTypes.png: + case MimeTypes.webp: + return true; + default: + return false; + } + } + + static bool canEditIptc(String mimeType) { + switch (mimeType.toLowerCase()) { + // as of latest PixyMeta + case MimeTypes.jpeg: + case MimeTypes.tiff: + return true; + default: + return false; + } + } + + static bool canEditXmp(String mimeType) { + switch (mimeType.toLowerCase()) { + // as of latest PixyMeta + case MimeTypes.gif: + case MimeTypes.jpeg: + case MimeTypes.png: + case MimeTypes.tiff: + return true; + // using `mp4parser` + case MimeTypes.mp4: + return true; + default: + return false; + } + } + + static bool canRemoveMetadata(String mimeType) { + switch (mimeType.toLowerCase()) { + // as of latest PixyMeta + case MimeTypes.jpeg: + case MimeTypes.tiff: + return true; + default: + return false; + } + } +} diff --git a/lib/model/app_inventory.dart b/lib/model/app_inventory.dart new file mode 100644 index 0000000..273216c --- /dev/null +++ b/lib/model/app_inventory.dart @@ -0,0 +1,82 @@ +import 'package:aves/services/common/services.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; + +final AppInventory appInventory = AppInventory._private(); + +class AppInventory { + Set<Package> _packages = {}; + List<String> _potentialAppDirs = []; + + ValueNotifier<bool> areAppNamesReadyNotifier = ValueNotifier(false); + + Iterable<Package> get _launcherPackages => _packages.where((v) => v.categoryLauncher); + + AppInventory._private(); + + Future<void> initAppNames() async { + if (_packages.isEmpty) { + debugPrint('Access installed app inventory'); + _packages = await appService.getPackages(); + _potentialAppDirs = _launcherPackages.expand((v) => v.potentialDirs).toList(); + areAppNamesReadyNotifier.value = true; + } + } + + Future<void> resetAppNames() async { + _packages.clear(); + _potentialAppDirs.clear(); + areAppNamesReadyNotifier.value = false; + } + + bool isPotentialAppDir(String dir) => _potentialAppDirs.contains(Package.normalizePotentialDir(dir)); + + String? getAlbumAppPackageName(String albumPath) { + final dir = Package.normalizePotentialDir(pContext.split(albumPath).last); + final package = _launcherPackages.firstWhereOrNull((v) => v.potentialDirs.contains(dir)); + return package?.packageName; + } + + String? getCurrentAppName(String packageName) { + final package = _packages.firstWhereOrNull((v) => v.packageName == packageName); + return package?.currentLabel; + } +} + +class Package { + final String packageName; + final String? currentLabel, englishLabel; + final bool categoryLauncher, isSystem; + final Set<String> ownedDirs = {}; + + Package({ + required this.packageName, + required this.currentLabel, + required this.englishLabel, + required this.categoryLauncher, + required this.isSystem, + }); + + factory Package.fromMap(Map map) { + return Package( + packageName: map['packageName'] ?? '', + currentLabel: map['currentLabel'], + englishLabel: map['englishLabel'], + categoryLauncher: map['categoryLauncher'] ?? false, + isSystem: map['isSystem'] ?? false, + ); + } + + Set<String> get potentialDirs => [ + currentLabel, + englishLabel, + ...ownedDirs, + ].nonNulls.map(normalizePotentialDir).toSet(); + + static String normalizePotentialDir(String dir) { + return dir.replaceAll('_', ' ').trim().toLowerCase(); + } + + @override + String toString() => '$runtimeType#${shortHash(this)}{packageName=$packageName, categoryLauncher=$categoryLauncher, isSystem=$isSystem, currentLabel=$currentLabel, englishLabel=$englishLabel, ownedDirs=$ownedDirs}'; +} diff --git a/lib/model/availability.dart b/lib/model/availability.dart new file mode 100644 index 0000000..5ce1d3c --- /dev/null +++ b/lib/model/availability.dart @@ -0,0 +1,64 @@ +import 'package:aves/model/device.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves_map/aves_map.dart'; +import 'package:connectivity_plus/connectivity_plus.dart'; +import 'package:flutter/foundation.dart'; + +abstract class AvesAvailability { + Future<void> onNewIntent(); + + void onResume(); + + bool get isLocked; + + Future<bool> get isConnected; + + Future<bool> get canLocatePlaces; + + List<EntryMapStyle> get mapStyles; +} + +class LiveAvesAvailability implements AvesAvailability { + bool? _isConnected, _isLocked; + + LiveAvesAvailability() { + Connectivity().onConnectivityChanged.listen(_updateConnectivityFromResult); + } + + @override + Future<void> onNewIntent() async { + _isLocked = await deviceService.isLocked(); + debugPrint('Device is locked=$_isLocked'); + } + + @override + void onResume() => _isConnected = null; + + @override + bool get isLocked => _isLocked ?? false; + + @override + Future<bool> get isConnected async { + if (_isConnected != null) return SynchronousFuture(_isConnected!); + final result = await (Connectivity().checkConnectivity()); + _updateConnectivityFromResult(result); + return _isConnected!; + } + + void _updateConnectivityFromResult(List<ConnectivityResult> result) { + final newValue = result.isNotEmpty && !result.contains(ConnectivityResult.none); + if (_isConnected != newValue) { + _isConnected = newValue; + debugPrint('Device is connected=$_isConnected'); + } + } + + @override + Future<bool> get canLocatePlaces async => device.hasGeocoder && await isConnected; + + @override + List<EntryMapStyle> get mapStyles => [ + ...mobileServices.mapStyles, + ...EntryMapStyles.baseStyles, + ]; +} diff --git a/lib/model/covers.dart b/lib/model/covers.dart new file mode 100644 index 0000000..69069cb --- /dev/null +++ b/lib/model/covers.dart @@ -0,0 +1,344 @@ +import 'dart:async'; + +import 'package:aves/model/app_inventory.dart'; +import 'package:aves/model/dynamic_albums.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/filters/container/album_group.dart'; +import 'package:aves/model/filters/container/dynamic_album.dart'; +import 'package:aves/model/filters/container/tag_group.dart'; +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/grouping/common.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/model/vaults/vaults.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/utils/android_file_utils.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:aves_utils/aves_utils.dart'; +import 'package:collection/collection.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/painting.dart'; +import 'package:synchronized/synchronized.dart'; + +final Covers covers = Covers._private(); + +typedef CoverProps = (int? entryId, String? packageName, Color? color); + +class Covers { + final Set<StreamSubscription> _subscriptions = {}; + final _lock = Lock(); + + final StreamController<Set<CollectionFilter>?> _entryChangeStreamController = StreamController.broadcast(); + final StreamController<Set<CollectionFilter>?> _packageChangeStreamController = StreamController.broadcast(); + final StreamController<Set<CollectionFilter>?> _colorChangeStreamController = StreamController.broadcast(); + + Stream<Set<CollectionFilter>?> get entryChangeStream => _entryChangeStreamController.stream; + + Stream<Set<CollectionFilter>?> get packageChangeStream => _packageChangeStreamController.stream; + + Stream<Set<CollectionFilter>?> get colorChangeStream => _colorChangeStreamController.stream; + + Set<CoverRow> _rows = {}; + + // do not subscribe to events from other modules in constructor + // so that modules can subscribe to each other + Covers._private(); + + Future<void> init() async { + _rows = await localMediaDb.loadAllCovers(); + _subscriptions.add(dynamicAlbums.eventBus.on<DynamicAlbumChangedEvent>().listen((e) => _updateCoveredDynamicAlbums(e.changes))); + _subscriptions.add(albumGrouping.eventBus.on<GroupUriChangedEvent>().listen((e) => _updateCoveredGroup(e.oldGroupUri, e.newGroupUri))); + _subscriptions.add(tagGrouping.eventBus.on<GroupUriChangedEvent>().listen((e) => _updateCoveredGroup(e.oldGroupUri, e.newGroupUri))); + } + + int get count => _rows.length; + + Set<CoverRow> get all => Set.unmodifiable(_rows); + + CoverProps? of(CollectionFilter filter) { + if (filter is StoredAlbumFilter && vaults.isLocked(filter.album)) return null; + + final row = _rows.firstWhereOrNull((row) => row.filter == filter); + return row != null ? (row.entryId, row.packageName, row.color) : null; + } + + Future<CoverProps?> remove(CollectionFilter filter, {bool notify = true}) async { + final props = of(filter); + if (props != null) { + await set(filter: filter, entryId: null, packageName: null, color: null); + + if (notify) { + final (entryId, packageName, color) = props; + if (entryId != null) _entryChangeStreamController.add({filter}); + if (packageName != null) _packageChangeStreamController.add({filter}); + if (color != null) _colorChangeStreamController.add({filter}); + } + } + return props; + } + + Future<void> removeAll(Set<CollectionFilter> filters, {bool notify = true}) async { + final entryIdChanged = <CollectionFilter>{}; + final packageNameChanged = <CollectionFilter>{}; + final colorChanged = <CollectionFilter>{}; + + for (final filter in filters) { + final props = await remove(filter, notify: false); + if (notify && props != null) { + final (entryId, packageName, color) = props; + if (entryId != null) entryIdChanged.add(filter); + if (packageName != null) packageNameChanged.add(filter); + if (color != null) colorChanged.add(filter); + } + } + + if (notify) { + if (entryIdChanged.isNotEmpty) _entryChangeStreamController.add(entryIdChanged); + if (packageNameChanged.isNotEmpty) _packageChangeStreamController.add(packageNameChanged); + if (colorChanged.isNotEmpty) _colorChangeStreamController.add(colorChanged); + } + } + + Future<void> set({ + required CollectionFilter filter, + required int? entryId, + required String? packageName, + required Color? color, + bool notify = true, + }) async { + // erase contextual properties from filters before saving them + switch (filter) { + case StoredAlbumFilter _: + filter = StoredAlbumFilter(filter.album, null); + case AlbumGroupFilter _: + filter = AlbumGroupFilter.empty(filter.uri); + case TagGroupFilter _: + filter = TagGroupFilter.empty(filter.uri); + } + + final oldRows = _rows.where((row) => row.filter == filter).toSet(); + _rows.removeAll(oldRows); + await localMediaDb.removeCovers({filter}); + + final oldRow = oldRows.firstOrNull; + final oldEntry = oldRow?.entryId; + final oldPackage = oldRow?.packageName; + final oldColor = oldRow?.color; + + if (entryId != null || packageName != null || color != null) { + final row = CoverRow( + filter: filter, + entryId: entryId, + packageName: packageName, + color: color, + ); + _rows.add(row); + await localMediaDb.addCovers({row}); + } + + if (notify) { + if (oldEntry != entryId) _entryChangeStreamController.add({filter}); + if (oldPackage != packageName) _packageChangeStreamController.add({filter}); + if (oldColor != color) _colorChangeStreamController.add({filter}); + } + } + + Future<void> _removeEntryFromRows(Set<CoverRow> rows) { + return Future.forEach<CoverRow>( + rows, + (row) => set( + filter: row.filter, + entryId: null, + packageName: row.packageName, + color: row.color, + )); + } + + Future<void> moveEntry(AvesEntry entry) async { + final entryId = entry.id; + await _removeEntryFromRows(_rows.where((row) => row.entryId == entryId && !row.filter.test(entry)).toSet()); + } + + Future<void> removeIds(Set<int> entryIds) async { + await _removeEntryFromRows(_rows.where((row) => entryIds.contains(row.entryId)).toSet()); + } + + Future<void> clear() async { + await localMediaDb.clearCovers(); + _rows.clear(); + + _entryChangeStreamController.add(null); + _packageChangeStreamController.add(null); + _colorChangeStreamController.add(null); + } + + AlbumType effectiveAlbumType(String albumPath) { + final filterPackage = of(StoredAlbumFilter(albumPath, null))?.$2; + if (filterPackage != null) { + return filterPackage.isEmpty ? AlbumType.regular : AlbumType.app; + } else { + return androidFileUtils.getAlbumType(albumPath); + } + } + + String? effectiveAlbumPackage(String albumPath) { + final filterPackage = of(StoredAlbumFilter(albumPath, null))?.$2; + return filterPackage ?? appInventory.getAlbumAppPackageName(albumPath); + } + + Future<void> _updateCoveredDynamicAlbums(Map<DynamicAlbumFilter, DynamicAlbumFilter?> changes) async { + await _lock.synchronized(() async { + await Future.forEach(changes.entries, (kv) async { + final oldFilter = kv.key; + final newFilter = kv.value; + + final cover = await covers.remove(oldFilter, notify: false); + if (cover != null && newFilter != null) { + await covers.set( + filter: newFilter, + entryId: cover.$1, + packageName: cover.$2, + color: cover.$3, + notify: true, + ); + } + }); + }); + } + + Future<void> _updateCoveredGroup(Uri oldGroupUri, Uri newGroupUri) async { + await _lock.synchronized(() async { + final grouping = FilterGrouping.forUri(oldGroupUri); + if (grouping != null) { + final oldFilter = grouping.uriToFilter(oldGroupUri); + final newFilter = grouping.uriToFilter(newGroupUri); + + if (oldFilter != null) { + final cover = await covers.remove(oldFilter, notify: false); + if (cover != null && newFilter != null) { + await covers.set( + filter: newFilter, + entryId: cover.$1, + packageName: cover.$2, + color: cover.$3, + notify: true, + ); + } + } + } + }); + } + + // import/export + + List<Map<String, dynamic>>? export(CollectionSource source) { + final visibleEntries = source.visibleEntries; + final jsonList = all + .map((row) { + final entryId = row.entryId; + final path = visibleEntries.firstWhereOrNull((entry) => entryId == entry.id)?.path; + final volume = androidFileUtils.getStorageVolume(path)?.path; + final relativePath = volume != null ? path?.substring(volume.length) : null; + final packageName = row.packageName; + final colorJson = row.color?.toJson(); + + return { + 'filter': row.filter.toJson(), + if (volume != null) 'volume': volume, + if (relativePath != null) 'relativePath': relativePath, + if (packageName != null) 'packageName': packageName, + if (colorJson != null) 'color': colorJson, + }; + }) + .nonNulls + .toList(); + return jsonList.isNotEmpty ? jsonList : null; + } + + void import(dynamic jsonList, CollectionSource source) { + if (jsonList is! List) { + debugPrint('failed to import covers for jsonMap=$jsonList'); + return; + } + + final visibleEntries = source.visibleEntries; + jsonList.forEach((row) { + try { + final filter = CollectionFilter.fromJson(row['filter']); + if (filter == null) { + debugPrint('failed to import cover for row=$row'); + return; + } + + final volume = row['volume'] as String?; + final relativePath = row['relativePath'] as String?; + final packageName = row['packageName'] as String?; + final color = row['color']; + // for backward compatibility, color used to be an `int`, now a `string` + final colorJson = color is String ? color : null; + + AvesEntry? entry; + if (volume != null && relativePath != null) { + final path = pContext.join(volume, relativePath); + entry = visibleEntries.firstWhereOrNull((entry) => entry.path == path && filter.test(entry)); + if (entry == null) { + debugPrint('failed to import cover entry for path=$path, filter=$filter'); + } + } + + if (entry != null || packageName != null || colorJson != null) { + set( + filter: filter, + entryId: entry?.id, + packageName: packageName, + color: ExtraColor.fromJson(colorJson), + ); + } + } catch (error, stack) { + debugPrint('failed to import cover for row=$row with error=$error\n$stack'); + } + }); + } +} + +@immutable +class CoverRow extends Equatable { + final CollectionFilter filter; + final int? entryId; + final String? packageName; + final Color? color; + + @override + List<Object?> get props => [filter, entryId, packageName, color]; + + const CoverRow({ + required this.filter, + required this.entryId, + required this.packageName, + required this.color, + }); + + static CoverRow? fromMap(Map map) { + final filter = CollectionFilter.fromJson(map['filter']); + if (filter == null) return null; + + final entryId = map['entryId'] as int?; + final packageName = map['packageName'] as String?; + final colorJson = map['color'] as String?; + + return CoverRow( + filter: filter, + entryId: entryId, + packageName: packageName, + color: ExtraColor.fromJson(colorJson), + ); + } + + Map<String, dynamic> toMap() => { + 'filter': filter.toJson(), + 'entryId': entryId, + 'packageName': packageName, + 'color': color?.toJson(), + }; +} diff --git a/lib/model/db/db.dart b/lib/model/db/db.dart new file mode 100644 index 0000000..c7e7820 --- /dev/null +++ b/lib/model/db/db.dart @@ -0,0 +1,136 @@ +import 'package:aves/model/covers.dart'; +import 'package:aves/model/dynamic_albums.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/favourites.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/metadata/address.dart'; +import 'package:aves/model/metadata/catalog.dart'; +import 'package:aves/model/metadata/trash.dart'; +import 'package:aves/model/vaults/details.dart'; +import 'package:aves/model/viewer/video_playback.dart'; + +abstract class LocalMediaDb { + int get nextId; + + Future<String> get path; + + Future<void> init(); + + Future<int> dbFileSize(); + + Future<void> reset(); + + Future<void> removeIds(Set<int> ids, {Set<EntryDataType>? dataTypes}); + + // entries + + Future<void> clearEntries(); + + Future<Set<AvesEntry>> loadEntries({int? origin, String? directory}); + + Future<Set<AvesEntry>> loadEntriesById(Set<int> ids); + + Future<void> insertEntries(Set<AvesEntry> entries); + + Future<void> updateEntry(int id, AvesEntry entry); + + Future<Set<AvesEntry>> searchLiveEntries(String query, {int? limit}); + + Future<Set<AvesEntry>> searchLiveDuplicates(int origin, Set<AvesEntry>? entries); + + // date taken + + Future<void> clearDates(); + + Future<Map<int?, int?>> loadDates(); + + // catalog metadata + + Future<void> clearCatalogMetadata(); + + Future<Set<CatalogMetadata>> loadCatalogMetadata(); + + Future<Set<CatalogMetadata>> loadCatalogMetadataById(Set<int> ids); + + Future<void> saveCatalogMetadata(Set<CatalogMetadata> metadataEntries); + + Future<void> updateCatalogMetadata(int id, CatalogMetadata? metadata); + + // address + + Future<void> clearAddresses(); + + Future<Set<AddressDetails>> loadAddresses(); + + Future<Set<AddressDetails>> loadAddressesById(Set<int> ids); + + Future<void> saveAddresses(Set<AddressDetails> addresses); + + Future<void> updateAddress(int id, AddressDetails? address); + + // vaults + + Future<void> clearVaults(); + + Future<Set<VaultDetails>> loadAllVaults(); + + Future<void> addVaults(Set<VaultDetails> rows); + + Future<void> updateVault(String oldName, VaultDetails row); + + Future<void> removeVaults(Set<VaultDetails> rows); + + // trash + + Future<void> clearTrashDetails(); + + Future<Set<TrashDetails>> loadAllTrashDetails(); + + Future<void> updateTrash(int id, TrashDetails? details); + + // favourites + + Future<void> clearFavourites(); + + Future<Set<FavouriteRow>> loadAllFavourites(); + + Future<void> addFavourites(Set<FavouriteRow> rows); + + Future<void> updateFavouriteId(int id, FavouriteRow row); + + Future<void> removeFavourites(Set<FavouriteRow> rows); + + // covers + + Future<void> clearCovers(); + + Future<Set<CoverRow>> loadAllCovers(); + + Future<void> addCovers(Set<CoverRow> rows); + + Future<void> updateCoverEntryId(int id, CoverRow row); + + Future<void> removeCovers(Set<CollectionFilter> filters); + + // dynamic albums + + Future<int> clearDynamicAlbums(); + + Future<Set<DynamicAlbumRow>> loadAllDynamicAlbums(); + + Future<void> addDynamicAlbums(Set<DynamicAlbumRow> rows); + + Future<void> removeDynamicAlbums(Set<String> names); + + // video playback + + Future<void> clearVideoPlayback(); + + Future<Set<VideoPlaybackRow>> loadAllVideoPlayback(); + + Future<VideoPlaybackRow?> loadVideoPlayback(int id); + + Future<void> addVideoPlayback(Set<VideoPlaybackRow> rows); + + Future<void> removeVideoPlayback(Set<int> ids); +} diff --git a/lib/model/db/db_extension.dart b/lib/model/db/db_extension.dart new file mode 100644 index 0000000..a0d2a66 --- /dev/null +++ b/lib/model/db/db_extension.dart @@ -0,0 +1,13 @@ +import 'package:sqflite/sqflite.dart'; + +extension ExtraDatabase on Database { + // check table existence via `sqlite_master` + // `sqlite_schema` is the alias used in SQLite documentation, + // but it was introduced in SQLite v3.33.0 and it is unavailable on Android API < 34, + // and the historical alias `sqlite_master` is still supported. + // cf https://www.sqlite.org/faq.html#q7 + Future<bool> tableExists(String table) async { + final results = await query('sqlite_master', where: 'type = ? AND name = ?', whereArgs: ['table', table]); + return results.isNotEmpty; + } +} diff --git a/lib/model/db/db_sqflite.dart b/lib/model/db/db_sqflite.dart new file mode 100644 index 0000000..6d44421 --- /dev/null +++ b/lib/model/db/db_sqflite.dart @@ -0,0 +1,704 @@ +import 'dart:io'; + +import 'package:aves/model/covers.dart'; +import 'package:aves/model/db/db.dart'; +import 'package:aves/model/db/db_sqflite_schema.dart'; +import 'package:aves/model/db/db_sqflite_upgrade.dart'; +import 'package:aves/model/dynamic_albums.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/favourites.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/metadata/address.dart'; +import 'package:aves/model/metadata/catalog.dart'; +import 'package:aves/model/metadata/trash.dart'; +import 'package:aves/model/vaults/details.dart'; +import 'package:aves/model/viewer/video_playback.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; +import 'package:sqflite/sqflite.dart'; + +class SqfliteLocalMediaDb implements LocalMediaDb { + late Database _db; + + @override + Future<String> get path async => pContext.join(await getDatabasesPath(), 'metadata.db'); + + static const entryTable = SqfliteLocalMediaDbSchema.entryTable; + static const dateTakenTable = SqfliteLocalMediaDbSchema.dateTakenTable; + static const metadataTable = SqfliteLocalMediaDbSchema.metadataTable; + static const addressTable = SqfliteLocalMediaDbSchema.addressTable; + static const favouriteTable = SqfliteLocalMediaDbSchema.favouriteTable; + static const coverTable = SqfliteLocalMediaDbSchema.coverTable; + static const dynamicAlbumTable = SqfliteLocalMediaDbSchema.dynamicAlbumTable; + static const vaultTable = SqfliteLocalMediaDbSchema.vaultTable; + static const trashTable = SqfliteLocalMediaDbSchema.trashTable; + static const videoPlaybackTable = SqfliteLocalMediaDbSchema.videoPlaybackTable; + + static const _entryInsertSliceMaxCount = 10000; // number of entries + static const _queryCursorBufferSize = 1000; // number of rows + static int _lastId = 0; + + @override + int get nextId => ++_lastId; + + @override + Future<void> init() async { + _db = await openDatabase( + await path, + onCreate: (db, version) => SqfliteLocalMediaDbSchema.createLatestVersion(db), + onUpgrade: LocalMediaDbUpgrader.upgradeDb, + version: 15, + ); + + final maxIdRows = await _db.rawQuery('SELECT MAX(id) AS maxId FROM $entryTable'); + _lastId = (maxIdRows.firstOrNull?['maxId'] as int?) ?? 0; + } + + @override + Future<int> dbFileSize() async { + final file = File(await path); + return await file.exists() ? await file.length() : 0; + } + + @override + Future<void> reset() async { + debugPrint('$runtimeType reset'); + await _db.close(); + await deleteDatabase(await path); + await init(); + } + + @override + Future<void> removeIds(Set<int> ids, {Set<EntryDataType>? dataTypes}) async { + if (ids.isEmpty) return; + + final _dataTypes = dataTypes ?? EntryDataType.values.toSet(); + + // using array in `whereArgs` and using it with `where arg IN ?` is a pain, so we prefer `batch` instead + final batch = _db.batch(); + const where = 'id = ?'; + const coverWhere = 'entryId = ?'; + ids.forEach((id) { + final whereArgs = [id]; + if (_dataTypes.contains(EntryDataType.basic)) { + batch.delete(entryTable, where: where, whereArgs: whereArgs); + } + if (_dataTypes.contains(EntryDataType.catalog)) { + batch.delete(dateTakenTable, where: where, whereArgs: whereArgs); + batch.delete(metadataTable, where: where, whereArgs: whereArgs); + } + if (_dataTypes.contains(EntryDataType.address)) { + batch.delete(addressTable, where: where, whereArgs: whereArgs); + } + if (_dataTypes.contains(EntryDataType.references)) { + batch.delete(favouriteTable, where: where, whereArgs: whereArgs); + batch.delete(coverTable, where: coverWhere, whereArgs: whereArgs); + batch.delete(trashTable, where: where, whereArgs: whereArgs); + batch.delete(videoPlaybackTable, where: where, whereArgs: whereArgs); + } + }); + await batch.commit(noResult: true); + } + + // entries + + @override + Future<void> clearEntries() async { + final count = await _db.delete(entryTable, where: '1'); + debugPrint('$runtimeType clearEntries deleted $count rows'); + } + + @override + Future<Set<AvesEntry>> loadEntries({int? origin, String? directory}) async { + String? where; + final whereArgs = <Object?>[]; + + if (origin != null) { + where = 'origin = ?'; + whereArgs.add(origin); + } + + final entries = <AvesEntry>{}; + if (directory != null) { + final separator = pContext.separator; + if (!directory.endsWith(separator)) { + directory = '$directory$separator'; + } + + where = '${where != null ? '$where AND ' : ''}path LIKE ?'; + whereArgs.add('$directory%'); + final cursor = await _db.queryCursor(entryTable, where: where, whereArgs: whereArgs, bufferSize: _queryCursorBufferSize); + + final dirLength = directory.length; + while (await cursor.moveNext()) { + final row = cursor.current; + // skip entries in subfolders + final path = row['path'] as String?; + if (path != null && !path.substring(dirLength).contains(separator)) { + entries.add(AvesEntry.fromMap(row)); + } + } + } else { + final cursor = await _db.queryCursor(entryTable, where: where, whereArgs: whereArgs, bufferSize: _queryCursorBufferSize); + while (await cursor.moveNext()) { + entries.add(AvesEntry.fromMap(cursor.current)); + } + } + + return entries; + } + + @override + Future<Set<AvesEntry>> loadEntriesById(Set<int> ids) => _getByIds(ids, entryTable, AvesEntry.fromMap); + + @override + Future<void> insertEntries(Set<AvesEntry> entries) async { + if (entries.isEmpty) return; + final stopwatch = Stopwatch()..start(); + // slice entries to avoid memory issues + int inserted = 0; + await Future.forEach(entries.slices(_entryInsertSliceMaxCount), (slice) async { + debugPrint('$runtimeType saveEntries inserting slice of [${inserted + 1}, ${inserted + slice.length}] entries'); + final batch = _db.batch(); + slice.forEach((entry) => _batchInsertEntry(batch, entry)); + await batch.commit(noResult: true); + inserted += slice.length; + }); + debugPrint('$runtimeType saveEntries complete in ${stopwatch.elapsed.inMilliseconds}ms for ${entries.length} entries'); + } + + @override + Future<void> updateEntry(int id, AvesEntry entry) async { + final batch = _db.batch(); + batch.delete(entryTable, where: 'id = ?', whereArgs: [id]); + _batchInsertEntry(batch, entry); + await batch.commit(noResult: true); + } + + void _batchInsertEntry(Batch batch, AvesEntry entry) { + batch.insert( + entryTable, + entry.toDatabaseMap(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); + } + + @override + Future<Set<AvesEntry>> searchLiveEntries(String query, {int? limit}) async { + final rows = await _db.query( + entryTable, + where: '(title LIKE ? OR path LIKE ?) AND trashed = ?', + whereArgs: ['%$query%', '%$query%', 0], + orderBy: 'sourceDateTakenMillis DESC', + limit: limit, + ); + return rows.map(AvesEntry.fromMap).toSet(); + } + + @override + Future<Set<AvesEntry>> searchLiveDuplicates(int origin, Set<AvesEntry>? entries) async { + String where = 'origin = ? AND trashed = ?'; + if (entries != null) { + where += ' AND contentId IN (${entries.map((v) => v.contentId).join(',')})'; + } + final rows = await _db.rawQuery( + 'SELECT *, MAX(id) AS id' + ' FROM $entryTable' + ' WHERE $where' + ' GROUP BY contentId' + ' HAVING COUNT(id) > 1', + [origin, 0], + ); + final duplicates = rows.map(AvesEntry.fromMap).toSet(); + if (duplicates.isNotEmpty) { + debugPrint('$runtimeType found duplicates=$duplicates'); + } + // returns most recent duplicate for each duplicated content ID + return duplicates; + } + + // date taken + + @override + Future<void> clearDates() async { + final count = await _db.delete(dateTakenTable, where: '1'); + debugPrint('$runtimeType clearDates deleted $count rows'); + } + + @override + Future<Map<int?, int?>> loadDates() async { + final result = <int?, int?>{}; + final cursor = await _db.queryCursor(dateTakenTable, bufferSize: _queryCursorBufferSize); + while (await cursor.moveNext()) { + final row = cursor.current; + result[row['id'] as int] = row['dateMillis'] as int? ?? 0; + } + return result; + } + + // catalog metadata + + @override + Future<void> clearCatalogMetadata() async { + final count = await _db.delete(metadataTable, where: '1'); + debugPrint('$runtimeType clearMetadataEntries deleted $count rows'); + } + + @override + Future<Set<CatalogMetadata>> loadCatalogMetadata() async { + final result = <CatalogMetadata>{}; + final cursor = await _db.queryCursor(metadataTable, bufferSize: _queryCursorBufferSize); + while (await cursor.moveNext()) { + result.add(CatalogMetadata.fromMap(cursor.current)); + } + return result; + } + + @override + Future<Set<CatalogMetadata>> loadCatalogMetadataById(Set<int> ids) => _getByIds(ids, metadataTable, CatalogMetadata.fromMap); + + @override + Future<void> saveCatalogMetadata(Set<CatalogMetadata> metadataEntries) async { + if (metadataEntries.isEmpty) return; + final stopwatch = Stopwatch()..start(); + try { + final batch = _db.batch(); + metadataEntries.forEach((metadata) => _batchInsertMetadata(batch, metadata)); + await batch.commit(noResult: true); + debugPrint('$runtimeType saveMetadata complete in ${stopwatch.elapsed.inMilliseconds}ms for ${metadataEntries.length} entries'); + } catch (error, stack) { + debugPrint('$runtimeType failed to save metadata with error=$error\n$stack'); + } + } + + @override + Future<void> updateCatalogMetadata(int id, CatalogMetadata? metadata) async { + final batch = _db.batch(); + batch.delete(dateTakenTable, where: 'id = ?', whereArgs: [id]); + batch.delete(metadataTable, where: 'id = ?', whereArgs: [id]); + _batchInsertMetadata(batch, metadata); + await batch.commit(noResult: true); + } + + void _batchInsertMetadata(Batch batch, CatalogMetadata? metadata) { + if (metadata == null) return; + if (metadata.dateMillis != 0) { + batch.insert( + dateTakenTable, + { + 'id': metadata.id, + 'dateMillis': metadata.dateMillis, + }, + conflictAlgorithm: ConflictAlgorithm.replace, + ); + } + batch.insert( + metadataTable, + metadata.toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); + } + + // address + + @override + Future<void> clearAddresses() async { + final count = await _db.delete(addressTable, where: '1'); + debugPrint('$runtimeType clearAddresses deleted $count rows'); + } + + @override + Future<Set<AddressDetails>> loadAddresses() async { + final result = <AddressDetails>{}; + final cursor = await _db.queryCursor(addressTable, bufferSize: _queryCursorBufferSize); + while (await cursor.moveNext()) { + result.add(AddressDetails.fromMap(cursor.current)); + } + return result; + } + + @override + Future<Set<AddressDetails>> loadAddressesById(Set<int> ids) => _getByIds(ids, addressTable, AddressDetails.fromMap); + + @override + Future<void> saveAddresses(Set<AddressDetails> addresses) async { + if (addresses.isEmpty) return; + final stopwatch = Stopwatch()..start(); + final batch = _db.batch(); + addresses.forEach((address) => _batchInsertAddress(batch, address)); + await batch.commit(noResult: true); + debugPrint('$runtimeType saveAddresses complete in ${stopwatch.elapsed.inMilliseconds}ms for ${addresses.length} entries'); + } + + @override + Future<void> updateAddress(int id, AddressDetails? address) async { + final batch = _db.batch(); + batch.delete(addressTable, where: 'id = ?', whereArgs: [id]); + _batchInsertAddress(batch, address); + await batch.commit(noResult: true); + } + + void _batchInsertAddress(Batch batch, AddressDetails? address) { + if (address == null) return; + batch.insert( + addressTable, + address.toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); + } + + // vaults + + @override + Future<void> clearVaults() async { + final count = await _db.delete(vaultTable, where: '1'); + debugPrint('$runtimeType clearVaults deleted $count rows'); + } + + @override + Future<Set<VaultDetails>> loadAllVaults() async { + final result = <VaultDetails>{}; + final cursor = await _db.queryCursor(vaultTable, bufferSize: _queryCursorBufferSize); + while (await cursor.moveNext()) { + result.add(VaultDetails.fromMap(cursor.current)); + } + return result; + } + + @override + Future<void> addVaults(Set<VaultDetails> rows) async { + if (rows.isEmpty) return; + final batch = _db.batch(); + rows.forEach((row) => _batchInsertVault(batch, row)); + await batch.commit(noResult: true); + } + + @override + Future<void> updateVault(String oldName, VaultDetails row) async { + final batch = _db.batch(); + batch.delete(vaultTable, where: 'name = ?', whereArgs: [oldName]); + _batchInsertVault(batch, row); + await batch.commit(noResult: true); + } + + void _batchInsertVault(Batch batch, VaultDetails row) { + batch.insert( + vaultTable, + row.toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); + } + + @override + Future<void> removeVaults(Set<VaultDetails> rows) async { + if (rows.isEmpty) return; + + // using array in `whereArgs` and using it with `where arg IN ?` is a pain, so we prefer `batch` instead + final batch = _db.batch(); + rows.map((v) => v.name).forEach((name) => batch.delete(vaultTable, where: 'name = ?', whereArgs: [name])); + await batch.commit(noResult: true); + } + + // trash + + @override + Future<void> clearTrashDetails() async { + final count = await _db.delete(trashTable, where: '1'); + debugPrint('$runtimeType clearTrashDetails deleted $count rows'); + } + + @override + Future<Set<TrashDetails>> loadAllTrashDetails() async { + final result = <TrashDetails>{}; + final cursor = await _db.queryCursor(trashTable, bufferSize: _queryCursorBufferSize); + while (await cursor.moveNext()) { + result.add(TrashDetails.fromMap(cursor.current)); + } + return result; + } + + @override + Future<void> updateTrash(int id, TrashDetails? details) async { + final batch = _db.batch(); + batch.delete(trashTable, where: 'id = ?', whereArgs: [id]); + _batchInsertTrashDetails(batch, details); + await batch.commit(noResult: true); + } + + void _batchInsertTrashDetails(Batch batch, TrashDetails? details) { + if (details == null) return; + batch.insert( + trashTable, + details.toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); + } + + // favourites + + @override + Future<void> clearFavourites() async { + final count = await _db.delete(favouriteTable, where: '1'); + debugPrint('$runtimeType clearFavourites deleted $count rows'); + } + + @override + Future<Set<FavouriteRow>> loadAllFavourites() async { + final result = <FavouriteRow>{}; + final cursor = await _db.queryCursor(favouriteTable, bufferSize: _queryCursorBufferSize); + while (await cursor.moveNext()) { + result.add(FavouriteRow.fromMap(cursor.current)); + } + return result; + } + + @override + Future<void> addFavourites(Set<FavouriteRow> rows) async { + if (rows.isEmpty) return; + final batch = _db.batch(); + rows.forEach((row) => _batchInsertFavourite(batch, row)); + await batch.commit(noResult: true); + } + + @override + Future<void> updateFavouriteId(int id, FavouriteRow row) async { + final batch = _db.batch(); + batch.delete(favouriteTable, where: 'id = ?', whereArgs: [id]); + _batchInsertFavourite(batch, row); + await batch.commit(noResult: true); + } + + void _batchInsertFavourite(Batch batch, FavouriteRow row) { + batch.insert( + favouriteTable, + row.toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); + } + + @override + Future<void> removeFavourites(Set<FavouriteRow> rows) async { + if (rows.isEmpty) return; + final ids = rows.map((row) => row.entryId); + if (ids.isEmpty) return; + + // using array in `whereArgs` and using it with `where arg IN ?` is a pain, so we prefer `batch` instead + final batch = _db.batch(); + ids.forEach((id) => batch.delete(favouriteTable, where: 'id = ?', whereArgs: [id])); + await batch.commit(noResult: true); + } + + // covers + + @override + Future<void> clearCovers() async { + final count = await _db.delete(coverTable, where: '1'); + debugPrint('$runtimeType clearCovers deleted $count rows'); + } + + @override + Future<Set<CoverRow>> loadAllCovers() async { + final result = <CoverRow>{}; + final cursor = await _db.queryCursor(coverTable, bufferSize: _queryCursorBufferSize); + while (await cursor.moveNext()) { + final rowMap = cursor.current; + final row = CoverRow.fromMap(rowMap); + if (row != null) { + result.add(row); + } else { + debugPrint('$runtimeType failed to deserialize cover from row=$rowMap'); + } + } + return result; + } + + @override + Future<void> addCovers(Set<CoverRow> rows) async { + if (rows.isEmpty) return; + + final batch = _db.batch(); + rows.forEach((row) => _batchInsertCover(batch, row)); + await batch.commit(noResult: true); + } + + @override + Future<void> updateCoverEntryId(int id, CoverRow row) async { + final batch = _db.batch(); + batch.delete(coverTable, where: 'entryId = ?', whereArgs: [id]); + _batchInsertCover(batch, row); + await batch.commit(noResult: true); + } + + void _batchInsertCover(Batch batch, CoverRow row) { + batch.insert( + coverTable, + row.toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); + } + + @override + Future<void> removeCovers(Set<CollectionFilter> filters) async { + if (filters.isEmpty) return; + + // for backward compatibility, remove stored JSON instead of removing de/reserialized filters + final obsoleteFilterJson = <String>{}; + + final rows = await _db.query(coverTable); + rows.forEach((row) { + final filterJson = row['filter'] as String?; + if (filterJson != null) { + final filter = CollectionFilter.fromJson(filterJson); + if (filters.any((v) => filter == v)) { + obsoleteFilterJson.add(filterJson); + } + } + }); + + // using array in `whereArgs` and using it with `where arg IN ?` is a pain, so we prefer `batch` instead + final batch = _db.batch(); + obsoleteFilterJson.forEach((filterJson) => batch.delete(coverTable, where: 'filter = ?', whereArgs: [filterJson])); + await batch.commit(noResult: true); + } + + // dynamic albums + + @override + Future<int> clearDynamicAlbums() async { + final count = await _db.delete(dynamicAlbumTable, where: '1'); + debugPrint('$runtimeType clearDynamicAlbums deleted $count rows'); + return count; + } + + @override + Future<Set<DynamicAlbumRow>> loadAllDynamicAlbums({int bufferSize = _queryCursorBufferSize}) async { + final result = <DynamicAlbumRow>{}; + try { + final cursor = await _db.queryCursor(dynamicAlbumTable, bufferSize: bufferSize); + while (await cursor.moveNext()) { + final rowMap = cursor.current; + final row = DynamicAlbumRow.fromMap(rowMap); + if (row != null) { + result.add(row); + } else { + debugPrint('$runtimeType failed to deserialize dynamic album from row=$rowMap'); + } + } + } catch (error, stack) { + debugPrint('$runtimeType failed to query table=$dynamicAlbumTable error=$error\n$stack'); + if (bufferSize > 1) { + // a large row may prevent reading from the table because of cursor window size limit, + // so we retry without buffer to read as many rows as we can, and removing the others + debugPrint('$runtimeType retry to query table=$dynamicAlbumTable with no cursor buffer'); + final safeRows = await loadAllDynamicAlbums(bufferSize: 1); + final clearedCount = await clearDynamicAlbums(); + await addDynamicAlbums(safeRows); + final addedCount = safeRows.length; + final lostCount = clearedCount - addedCount; + debugPrint('$runtimeType kept $addedCount rows, lost $lostCount rows from table=$dynamicAlbumTable'); + return safeRows; + } + } + return result; + } + + @override + Future<void> addDynamicAlbums(Set<DynamicAlbumRow> rows) async { + if (rows.isEmpty) return; + + final batch = _db.batch(); + rows.forEach((row) => _batchInsertDynamicAlbum(batch, row)); + await batch.commit(noResult: true); + } + + void _batchInsertDynamicAlbum(Batch batch, DynamicAlbumRow row) { + batch.insert( + dynamicAlbumTable, + row.toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); + } + + @override + Future<void> removeDynamicAlbums(Set<String> names) async { + if (names.isEmpty) return; + + // using array in `whereArgs` and using it with `where arg IN ?` is a pain, so we prefer `batch` instead + final batch = _db.batch(); + names.forEach((name) => batch.delete(dynamicAlbumTable, where: 'name = ?', whereArgs: [name])); + await batch.commit(noResult: true); + } + + // video playback + + @override + Future<void> clearVideoPlayback() async { + final count = await _db.delete(videoPlaybackTable, where: '1'); + debugPrint('$runtimeType clearVideoPlayback deleted $count rows'); + } + + @override + Future<Set<VideoPlaybackRow>> loadAllVideoPlayback() async { + final result = <VideoPlaybackRow>{}; + final cursor = await _db.queryCursor(videoPlaybackTable, bufferSize: _queryCursorBufferSize); + while (await cursor.moveNext()) { + final rowMap = cursor.current; + final row = VideoPlaybackRow.fromMap(rowMap); + if (row != null) { + result.add(row); + } else { + debugPrint('$runtimeType failed to deserialize video playback from row=$rowMap'); + } + } + return result; + } + + @override + Future<VideoPlaybackRow?> loadVideoPlayback(int id) async { + final rows = await _db.query(videoPlaybackTable, where: 'id = ?', whereArgs: [id]); + if (rows.isEmpty) return null; + + return VideoPlaybackRow.fromMap(rows.first); + } + + @override + Future<void> addVideoPlayback(Set<VideoPlaybackRow> rows) async { + if (rows.isEmpty) return; + + final batch = _db.batch(); + rows.forEach((row) => _batchInsertVideoPlayback(batch, row)); + await batch.commit(noResult: true); + } + + void _batchInsertVideoPlayback(Batch batch, VideoPlaybackRow row) { + batch.insert( + videoPlaybackTable, + row.toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); + } + + @override + Future<void> removeVideoPlayback(Set<int> ids) async { + if (ids.isEmpty) return; + + // using array in `whereArgs` and using it with `where arg IN ?` is a pain, so we prefer `batch` instead + final batch = _db.batch(); + ids.forEach((id) => batch.delete(videoPlaybackTable, where: 'id = ?', whereArgs: [id])); + await batch.commit(noResult: true); + } + + // convenience methods + + Future<Set<T>> _getByIds<T>(Set<int> ids, String table, T Function(Map<String, Object?> row) mapRow) async { + final result = <T>{}; + if (ids.isNotEmpty) { + final cursor = await _db.queryCursor(table, where: 'id IN (${ids.join(',')})', bufferSize: _queryCursorBufferSize); + while (await cursor.moveNext()) { + result.add(mapRow(cursor.current)); + } + } + return result; + } +} diff --git a/lib/model/db/db_sqflite_schema.dart b/lib/model/db/db_sqflite_schema.dart new file mode 100644 index 0000000..1d1d810 --- /dev/null +++ b/lib/model/db/db_sqflite_schema.dart @@ -0,0 +1,118 @@ +import 'package:sqflite/sqflite.dart'; + +class SqfliteLocalMediaDbSchema { + static const entryTable = 'entry'; + static const dateTakenTable = 'dateTaken'; + static const metadataTable = 'metadata'; + static const addressTable = 'address'; + static const favouriteTable = 'favourites'; + static const coverTable = 'covers'; + static const dynamicAlbumTable = 'dynamicAlbums'; + static const vaultTable = 'vaults'; + static const trashTable = 'trash'; + static const videoPlaybackTable = 'videoPlayback'; + + static const allTables = [ + entryTable, + dateTakenTable, + metadataTable, + addressTable, + favouriteTable, + coverTable, + dynamicAlbumTable, + vaultTable, + trashTable, + videoPlaybackTable, + ]; + + static Future<void> createLatestVersion(Database db) async { + await Future.forEach(allTables, (table) => createTable(db, table)); + } + + static Future<void> createTable(Database db, String table) { + switch (table) { + case entryTable: + return db.execute('CREATE TABLE $entryTable(' + 'id INTEGER PRIMARY KEY' + ', contentId INTEGER' + ', uri TEXT' + ', path TEXT' + ', sourceMimeType TEXT' + ', width INTEGER' + ', height INTEGER' + ', sourceRotationDegrees INTEGER' + ', sizeBytes INTEGER' + ', title TEXT' + ', dateAddedSecs INTEGER DEFAULT (strftime(\'%s\',\'now\'))' + ', dateModifiedMillis INTEGER' + ', sourceDateTakenMillis INTEGER' + ', durationMillis INTEGER' + ', trashed INTEGER DEFAULT 0' + ', origin INTEGER DEFAULT 0' + ')'); + case dateTakenTable: + return db.execute('CREATE TABLE $dateTakenTable(' + 'id INTEGER PRIMARY KEY' + ', dateMillis INTEGER' + ')'); + case metadataTable: + return db.execute('CREATE TABLE $metadataTable(' + 'id INTEGER PRIMARY KEY' + ', mimeType TEXT' + ', dateMillis INTEGER' + ', flags INTEGER' + ', rotationDegrees INTEGER' + ', xmpSubjects TEXT' + ', xmpTitle TEXT' + ', latitude REAL' + ', longitude REAL' + ', rating INTEGER' + ')'); + case addressTable: + return db.execute('CREATE TABLE $addressTable(' + 'id INTEGER PRIMARY KEY' + ', addressLine TEXT' + ', countryCode TEXT' + ', countryName TEXT' + ', adminArea TEXT' + ', locality TEXT' + ')'); + case favouriteTable: + return db.execute('CREATE TABLE $favouriteTable(' + 'id INTEGER PRIMARY KEY' + ')'); + case coverTable: + return db.execute('CREATE TABLE $coverTable(' + 'filter TEXT PRIMARY KEY' + ', entryId INTEGER' + ', packageName TEXT' + ', color TEXT' + ')'); + case dynamicAlbumTable: + return db.execute('CREATE TABLE $dynamicAlbumTable(' + 'name TEXT PRIMARY KEY' + ', filter TEXT' + ')'); + case vaultTable: + return db.execute('CREATE TABLE $vaultTable(' + 'name TEXT PRIMARY KEY' + ', autoLock INTEGER' + ', useBin INTEGER' + ', lockType TEXT' + ')'); + case trashTable: + return db.execute('CREATE TABLE $trashTable(' + 'id INTEGER PRIMARY KEY' + ', path TEXT' + ', dateMillis INTEGER' + ')'); + case videoPlaybackTable: + return db.execute('CREATE TABLE $videoPlaybackTable(' + 'id INTEGER PRIMARY KEY' + ', resumeTimeMillis INTEGER' + ')'); + default: + throw Exception('unknown table=$table'); + } + } +} diff --git a/lib/model/db/db_sqflite_upgrade.dart b/lib/model/db/db_sqflite_upgrade.dart new file mode 100644 index 0000000..4796ea1 --- /dev/null +++ b/lib/model/db/db_sqflite_upgrade.dart @@ -0,0 +1,503 @@ +import 'dart:ui'; + +import 'package:aves/model/covers.dart'; +import 'package:aves/model/db/db_extension.dart'; +import 'package:aves/model/db/db_sqflite_schema.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:flutter/foundation.dart'; +import 'package:sqflite/sqflite.dart'; + +class LocalMediaDbUpgrader { + static const entryTable = SqfliteLocalMediaDbSchema.entryTable; + static const dateTakenTable = SqfliteLocalMediaDbSchema.dateTakenTable; + static const metadataTable = SqfliteLocalMediaDbSchema.metadataTable; + static const addressTable = SqfliteLocalMediaDbSchema.addressTable; + static const favouriteTable = SqfliteLocalMediaDbSchema.favouriteTable; + static const coverTable = SqfliteLocalMediaDbSchema.coverTable; + static const dynamicAlbumTable = SqfliteLocalMediaDbSchema.dynamicAlbumTable; + static const vaultTable = SqfliteLocalMediaDbSchema.vaultTable; + static const trashTable = SqfliteLocalMediaDbSchema.trashTable; + static const videoPlaybackTable = SqfliteLocalMediaDbSchema.videoPlaybackTable; + + // warning: "ALTER TABLE ... RENAME COLUMN ..." is not supported + // on SQLite <3.25.0, bundled on older Android devices + static Future<void> upgradeDb(Database db, int oldVersion, int newVersion) async { + debugPrint('DB will be upgraded from v$oldVersion to v$newVersion'); + while (oldVersion < newVersion) { + switch (oldVersion) { + case 1: + await _upgradeFrom1(db); + case 2: + await _upgradeFrom2(db); + case 3: + await _upgradeFrom3(db); + case 4: + await _upgradeFrom4(db); + case 5: + await _upgradeFrom5(db); + case 6: + await _upgradeFrom6(db); + case 7: + await _upgradeFrom7(db); + case 8: + await _upgradeFrom8(db); + case 9: + await _upgradeFrom9(db); + case 10: + await _upgradeFrom10(db); + case 11: + await _upgradeFrom11(db); + case 12: + await _upgradeFrom12(db); + case 13: + await _upgradeFrom13(db); + case 14: + await _upgradeFrom14(db); + } + oldVersion++; + } + await _sanitize(db); + } + + static Future<void> _sanitize(Database db) async { + // ensure all tables exist + await Future.forEach(SqfliteLocalMediaDbSchema.allTables, (table) async { + if (!(await db.tableExists(table))) { + await SqfliteLocalMediaDbSchema.createTable(db, table); + } + }); + + // remove rows referencing future entry IDs + final maxIdRows = await db.rawQuery('SELECT MAX(id) AS maxId FROM $entryTable'); + final lastId = (maxIdRows.firstOrNull?['maxId'] as int?) ?? 0; + await db.delete(favouriteTable, where: 'id > ?', whereArgs: [lastId]); + await db.delete(coverTable, where: 'entryId > ?', whereArgs: [lastId]); + } + + static Future<void> _upgradeFrom1(Database db) async { + debugPrint('upgrading DB from v1'); + + // rename column 'orientationDegrees' to 'sourceRotationDegrees' + const newEntryTable = '${entryTable}TEMP'; + await db.execute('CREATE TABLE $newEntryTable (' + 'contentId INTEGER PRIMARY KEY' + ', uri TEXT' + ', path TEXT' + ', sourceMimeType TEXT' + ', width INTEGER' + ', height INTEGER' + ', sourceRotationDegrees INTEGER' + ', sizeBytes INTEGER' + ', title TEXT' + ', dateModifiedSecs INTEGER' + ', sourceDateTakenMillis INTEGER' + ', durationMillis INTEGER' + ')'); + await db.rawInsert('INSERT INTO $newEntryTable (contentId,uri,path,sourceMimeType,width,height,sourceRotationDegrees,sizeBytes,title,dateModifiedSecs,sourceDateTakenMillis,durationMillis)' + ' SELECT contentId,uri,path,sourceMimeType,width,height,orientationDegrees,sizeBytes,title,dateModifiedSecs,sourceDateTakenMillis,durationMillis' + ' FROM $entryTable;'); + await db.execute('DROP TABLE $entryTable;'); + await db.execute('ALTER TABLE $newEntryTable RENAME TO $entryTable;'); + + // rename column 'videoRotation' to 'rotationDegrees' + const newMetadataTable = '${metadataTable}TEMP'; + await db.execute('CREATE TABLE $newMetadataTable (' + 'contentId INTEGER PRIMARY KEY' + ', mimeType TEXT' + ', dateMillis INTEGER' + ', isAnimated INTEGER' + ', rotationDegrees INTEGER' + ', xmpSubjects TEXT' + ', xmpTitleDescription TEXT' + ', latitude REAL' + ', longitude REAL' + ')'); + await db.rawInsert('INSERT INTO $newMetadataTable (contentId,mimeType,dateMillis,isAnimated,rotationDegrees,xmpSubjects,xmpTitleDescription,latitude,longitude)' + ' SELECT contentId,mimeType,dateMillis,isAnimated,videoRotation,xmpSubjects,xmpTitleDescription,latitude,longitude' + ' FROM $metadataTable;'); + await db.rawInsert('UPDATE $newMetadataTable SET rotationDegrees = NULL WHERE rotationDegrees = 0;'); + await db.execute('DROP TABLE $metadataTable;'); + await db.execute('ALTER TABLE $newMetadataTable RENAME TO $metadataTable;'); + + // new column 'isFlipped' + await db.execute('ALTER TABLE $metadataTable ADD COLUMN isFlipped INTEGER;'); + } + + static Future<void> _upgradeFrom2(Database db) async { + debugPrint('upgrading DB from v2'); + + // merge columns 'isAnimated' and 'isFlipped' into 'flags' + const newMetadataTable = '${metadataTable}TEMP'; + await db.execute('CREATE TABLE $newMetadataTable (' + 'contentId INTEGER PRIMARY KEY' + ', mimeType TEXT' + ', dateMillis INTEGER' + ', flags INTEGER' + ', rotationDegrees INTEGER' + ', xmpSubjects TEXT' + ', xmpTitleDescription TEXT' + ', latitude REAL' + ', longitude REAL' + ')'); + await db.rawInsert('INSERT INTO $newMetadataTable (contentId,mimeType,dateMillis,flags,rotationDegrees,xmpSubjects,xmpTitleDescription,latitude,longitude)' + ' SELECT contentId,mimeType,dateMillis,ifnull(isAnimated,0)+ifnull(isFlipped,0)*2,rotationDegrees,xmpSubjects,xmpTitleDescription,latitude,longitude' + ' FROM $metadataTable;'); + await db.execute('DROP TABLE $metadataTable;'); + await db.execute('ALTER TABLE $newMetadataTable RENAME TO $metadataTable;'); + } + + static Future<void> _upgradeFrom3(Database db) async { + debugPrint('upgrading DB from v3'); + await db.execute('CREATE TABLE $coverTable (' + 'filter TEXT PRIMARY KEY' + ', contentId INTEGER' + ')'); + } + + static Future<void> _upgradeFrom4(Database db) async { + debugPrint('upgrading DB from v4'); + await db.execute('CREATE TABLE $videoPlaybackTable (' + 'contentId INTEGER PRIMARY KEY' + ', resumeTimeMillis INTEGER' + ')'); + } + + static Future<void> _upgradeFrom5(Database db) async { + debugPrint('upgrading DB from v5'); + await db.execute('ALTER TABLE $metadataTable ADD COLUMN rating INTEGER;'); + } + + static Future<void> _upgradeFrom6(Database db) async { + debugPrint('upgrading DB from v6'); + // new primary key column `id` instead of `contentId` + // new column `trashed` + await db.transaction((txn) async { + const newEntryTable = '${entryTable}TEMP'; + await db.execute('CREATE TABLE $newEntryTable (' + 'id INTEGER PRIMARY KEY' + ', contentId INTEGER' + ', uri TEXT' + ', path TEXT' + ', sourceMimeType TEXT' + ', width INTEGER' + ', height INTEGER' + ', sourceRotationDegrees INTEGER' + ', sizeBytes INTEGER' + ', title TEXT' + ', dateModifiedSecs INTEGER' + ', sourceDateTakenMillis INTEGER' + ', durationMillis INTEGER' + ', trashed INTEGER DEFAULT 0' + ')'); + await db.rawInsert('INSERT INTO $newEntryTable (id,contentId,uri,path,sourceMimeType,width,height,sourceRotationDegrees,sizeBytes,title,dateModifiedSecs,sourceDateTakenMillis,durationMillis)' + ' SELECT contentId,contentId,uri,path,sourceMimeType,width,height,sourceRotationDegrees,sizeBytes,title,dateModifiedSecs,sourceDateTakenMillis,durationMillis' + ' FROM $entryTable;'); + await db.execute('DROP TABLE $entryTable;'); + await db.execute('ALTER TABLE $newEntryTable RENAME TO $entryTable;'); + }); + + // rename column `contentId` to `id` + await db.transaction((txn) async { + const newDateTakenTable = '${dateTakenTable}TEMP'; + await db.execute('CREATE TABLE $newDateTakenTable (' + 'id INTEGER PRIMARY KEY' + ', dateMillis INTEGER' + ')'); + await db.rawInsert('INSERT INTO $newDateTakenTable (id,dateMillis)' + ' SELECT contentId,dateMillis' + ' FROM $dateTakenTable;'); + await db.execute('DROP TABLE $dateTakenTable;'); + await db.execute('ALTER TABLE $newDateTakenTable RENAME TO $dateTakenTable;'); + }); + + // rename column `contentId` to `id` + await db.transaction((txn) async { + const newMetadataTable = '${metadataTable}TEMP'; + await db.execute('CREATE TABLE $newMetadataTable (' + 'id INTEGER PRIMARY KEY' + ', mimeType TEXT' + ', dateMillis INTEGER' + ', flags INTEGER' + ', rotationDegrees INTEGER' + ', xmpSubjects TEXT' + ', xmpTitleDescription TEXT' + ', latitude REAL' + ', longitude REAL' + ', rating INTEGER' + ')'); + await db.rawInsert('INSERT INTO $newMetadataTable (id,mimeType,dateMillis,flags,rotationDegrees,xmpSubjects,xmpTitleDescription,latitude,longitude,rating)' + ' SELECT contentId,mimeType,dateMillis,flags,rotationDegrees,xmpSubjects,xmpTitleDescription,latitude,longitude,rating' + ' FROM $metadataTable;'); + await db.execute('DROP TABLE $metadataTable;'); + await db.execute('ALTER TABLE $newMetadataTable RENAME TO $metadataTable;'); + }); + + // rename column `contentId` to `id` + await db.transaction((txn) async { + const newAddressTable = '${addressTable}TEMP'; + await db.execute('CREATE TABLE $newAddressTable (' + 'id INTEGER PRIMARY KEY' + ', addressLine TEXT' + ', countryCode TEXT' + ', countryName TEXT' + ', adminArea TEXT' + ', locality TEXT' + ')'); + await db.rawInsert('INSERT INTO $newAddressTable (id,addressLine,countryCode,countryName,adminArea,locality)' + ' SELECT contentId,addressLine,countryCode,countryName,adminArea,locality' + ' FROM $addressTable;'); + await db.execute('DROP TABLE $addressTable;'); + await db.execute('ALTER TABLE $newAddressTable RENAME TO $addressTable;'); + }); + + // rename column `contentId` to `id` + await db.transaction((txn) async { + const newVideoPlaybackTable = '${videoPlaybackTable}TEMP'; + await db.execute('CREATE TABLE $newVideoPlaybackTable (' + 'id INTEGER PRIMARY KEY' + ', resumeTimeMillis INTEGER' + ')'); + await db.rawInsert('INSERT INTO $newVideoPlaybackTable (id,resumeTimeMillis)' + ' SELECT contentId,resumeTimeMillis' + ' FROM $videoPlaybackTable;'); + await db.execute('DROP TABLE $videoPlaybackTable;'); + await db.execute('ALTER TABLE $newVideoPlaybackTable RENAME TO $videoPlaybackTable;'); + }); + + // rename column `contentId` to `id` + // remove column `path` + await db.transaction((txn) async { + const newFavouriteTable = '${favouriteTable}TEMP'; + await db.execute('CREATE TABLE $newFavouriteTable (' + 'id INTEGER PRIMARY KEY' + ')'); + await db.rawInsert('INSERT INTO $newFavouriteTable (id)' + ' SELECT contentId' + ' FROM $favouriteTable;'); + await db.execute('DROP TABLE $favouriteTable;'); + await db.execute('ALTER TABLE $newFavouriteTable RENAME TO $favouriteTable;'); + }); + + // rename column `contentId` to `entryId` + await db.transaction((txn) async { + const newCoverTable = '${coverTable}TEMP'; + await db.execute('CREATE TABLE $newCoverTable (' + 'filter TEXT PRIMARY KEY' + ', entryId INTEGER' + ')'); + await db.rawInsert('INSERT INTO $newCoverTable (filter,entryId)' + ' SELECT filter,contentId' + ' FROM $coverTable;'); + await db.execute('DROP TABLE $coverTable;'); + await db.execute('ALTER TABLE $newCoverTable RENAME TO $coverTable;'); + }); + + // new table + await db.execute('CREATE TABLE $trashTable (' + 'id INTEGER PRIMARY KEY' + ', path TEXT' + ', dateMillis INTEGER' + ')'); + } + + static Future<void> _upgradeFrom7(Database db) async { + debugPrint('upgrading DB from v7'); + await db.execute('ALTER TABLE $coverTable ADD COLUMN packageName TEXT;'); + await db.execute('ALTER TABLE $coverTable ADD COLUMN color INTEGER;'); + } + + static Future<void> _upgradeFrom8(Database db) async { + debugPrint('upgrading DB from v8'); + + // new column `dateAddedSecs` + await db.transaction((txn) async { + const newEntryTable = '${entryTable}TEMP'; + await db.execute('CREATE TABLE $newEntryTable (' + 'id INTEGER PRIMARY KEY' + ', contentId INTEGER' + ', uri TEXT' + ', path TEXT' + ', sourceMimeType TEXT' + ', width INTEGER' + ', height INTEGER' + ', sourceRotationDegrees INTEGER' + ', sizeBytes INTEGER' + ', title TEXT' + ', dateAddedSecs INTEGER DEFAULT (strftime(\'%s\',\'now\'))' + ', dateModifiedSecs INTEGER' + ', sourceDateTakenMillis INTEGER' + ', durationMillis INTEGER' + ', trashed INTEGER DEFAULT 0' + ')'); + await db.rawInsert('INSERT INTO $newEntryTable (id,contentId,uri,path,sourceMimeType,width,height,sourceRotationDegrees,sizeBytes,title,dateModifiedSecs,sourceDateTakenMillis,durationMillis,trashed)' + ' SELECT id,contentId,uri,path,sourceMimeType,width,height,sourceRotationDegrees,sizeBytes,title,dateModifiedSecs,sourceDateTakenMillis,durationMillis,trashed' + ' FROM $entryTable;'); + await db.execute('DROP TABLE $entryTable;'); + await db.execute('ALTER TABLE $newEntryTable RENAME TO $entryTable;'); + }); + + // rename column `xmpTitleDescription` to `xmpTitle` + await db.transaction((txn) async { + const newMetadataTable = '${metadataTable}TEMP'; + await db.execute('CREATE TABLE $newMetadataTable (' + 'id INTEGER PRIMARY KEY' + ', mimeType TEXT' + ', dateMillis INTEGER' + ', flags INTEGER' + ', rotationDegrees INTEGER' + ', xmpSubjects TEXT' + ', xmpTitle TEXT' + ', latitude REAL' + ', longitude REAL' + ', rating INTEGER' + ')'); + await db.rawInsert('INSERT INTO $newMetadataTable (id,mimeType,dateMillis,flags,rotationDegrees,xmpSubjects,xmpTitle,latitude,longitude,rating)' + ' SELECT id,mimeType,dateMillis,flags,rotationDegrees,xmpSubjects,xmpTitleDescription,latitude,longitude,rating' + ' FROM $metadataTable;'); + await db.execute('DROP TABLE $metadataTable;'); + await db.execute('ALTER TABLE $newMetadataTable RENAME TO $metadataTable;'); + }); + } + + static Future<void> _upgradeFrom9(Database db) async { + debugPrint('upgrading DB from v9'); + + // clean duplicates introduced before Aves v1.7.1 + final duplicatedContentIdRows = await db.query(entryTable, columns: ['contentId'], groupBy: 'contentId', having: 'COUNT(id) > 1 AND contentId IS NOT NULL'); + final duplicatedContentIds = duplicatedContentIdRows.map((row) => row['contentId'] as int?).nonNulls.toSet(); + final duplicateIds = <int>{}; + await Future.forEach(duplicatedContentIds, (contentId) async { + final rows = await db.query(entryTable, columns: ['id'], where: 'contentId = ?', whereArgs: [contentId]); + final ids = rows.map((row) => row['id'] as int?).nonNulls.toList()..sort(); + if (ids.length > 1) { + ids.removeAt(0); + duplicateIds.addAll(ids); + } + }); + final batch = db.batch(); + const where = 'id = ?'; + const coverWhere = 'entryId = ?'; + duplicateIds.forEach((id) { + final whereArgs = [id]; + batch.delete(entryTable, where: where, whereArgs: whereArgs); + batch.delete(dateTakenTable, where: where, whereArgs: whereArgs); + batch.delete(metadataTable, where: where, whereArgs: whereArgs); + batch.delete(addressTable, where: where, whereArgs: whereArgs); + batch.delete(favouriteTable, where: where, whereArgs: whereArgs); + batch.delete(coverTable, where: coverWhere, whereArgs: whereArgs); + batch.delete(trashTable, where: where, whereArgs: whereArgs); + batch.delete(videoPlaybackTable, where: where, whereArgs: whereArgs); + }); + await batch.commit(noResult: true); + } + + static Future<void> _upgradeFrom10(Database db) async { + debugPrint('upgrading DB from v10'); + + await db.execute('ALTER TABLE $entryTable ADD COLUMN origin INTEGER DEFAULT 0;'); + + await db.execute('CREATE TABLE $vaultTable (' + 'name TEXT PRIMARY KEY' + ', autoLock INTEGER' + ', useBin INTEGER' + ', lockType TEXT' + ')'); + } + + static Future<void> _upgradeFrom11(Database db) async { + debugPrint('upgrading DB from v11'); + + await db.execute('CREATE TABLE $dynamicAlbumTable (' + 'name TEXT PRIMARY KEY' + ', filter TEXT' + ')'); + } + + static Future<void> _upgradeFrom12(Database db) async { + debugPrint('upgrading DB from v12'); + + // retrieve covers stored with `int` color value + final rows = <CoverRow>{}; + final cursor = await db.queryCursor(coverTable); + while (await cursor.moveNext()) { + final Map map = cursor.current; + final filter = CollectionFilter.fromJson(map['filter']); + if (filter != null) { + final colorValue = map['color'] as int?; + final color = colorValue != null ? Color(colorValue) : null; + final row = CoverRow( + filter: filter, + entryId: map['entryId'] as int?, + packageName: map['packageName'] as String?, + color: color, + ); + rows.add(row); + } + } + + // convert `color` column type from value number to JSON string + const newCoverTable = '${coverTable}TEMP'; + await db.execute('CREATE TABLE $newCoverTable (' + 'filter TEXT PRIMARY KEY' + ', entryId INTEGER' + ', packageName TEXT' + ', color TEXT' + ')'); + + // insert covers with `string` color value + if (rows.isNotEmpty) { + final batch = db.batch(); + rows.forEach((row) { + batch.insert( + newCoverTable, + row.toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); + }); + await batch.commit(noResult: true); + } + + await db.execute('DROP TABLE $coverTable;'); + await db.execute('ALTER TABLE $newCoverTable RENAME TO $coverTable;'); + } + + static Future<void> _upgradeFrom13(Database db) async { + debugPrint('upgrading DB from v13'); + + if (await db.tableExists(entryTable)) { + // rename column 'dateModifiedSecs' to 'dateModifiedMillis' + const newEntryTable = '${entryTable}TEMP'; + await db.execute('CREATE TABLE $newEntryTable (' + 'id INTEGER PRIMARY KEY' + ', contentId INTEGER' + ', uri TEXT' + ', path TEXT' + ', sourceMimeType TEXT' + ', width INTEGER' + ', height INTEGER' + ', sourceRotationDegrees INTEGER' + ', sizeBytes INTEGER' + ', title TEXT' + ', dateAddedSecs INTEGER DEFAULT (strftime(\'%s\',\'now\'))' + ', dateModifiedMillis INTEGER' + ', sourceDateTakenMillis INTEGER' + ', durationMillis INTEGER' + ', trashed INTEGER DEFAULT 0' + ', origin INTEGER DEFAULT 0' + ')'); + await db.rawInsert('INSERT INTO $newEntryTable (id,contentId,uri,path,sourceMimeType,width,height,sourceRotationDegrees,sizeBytes,title,dateAddedSecs,dateModifiedMillis,sourceDateTakenMillis,durationMillis,trashed,origin)' + ' SELECT id,contentId,uri,path,sourceMimeType,width,height,sourceRotationDegrees,sizeBytes,title,dateAddedSecs,dateModifiedSecs*1000,sourceDateTakenMillis,durationMillis,trashed,origin' + ' FROM $entryTable;'); + await db.execute('DROP TABLE $entryTable;'); + await db.execute('ALTER TABLE $newEntryTable RENAME TO $entryTable;'); + } + } + + static Future<void> _upgradeFrom14(Database db) async { + debugPrint('upgrading DB from v14'); + + // transitional upgrade previously used to sanitize rebuildable tables + // (dateTakenTable, metadataTable, addressTable, trashTable, videoPlaybackTable) + // for users with a potentially corrupted DB following upgrade to v1.12.4 + } +} diff --git a/lib/model/device.dart b/lib/model/device.dart new file mode 100644 index 0000000..85607bb --- /dev/null +++ b/lib/model/device.dart @@ -0,0 +1,70 @@ +import 'package:aves/services/common/services.dart'; +import 'package:device_info_plus/device_info_plus.dart'; +import 'package:local_auth/local_auth.dart'; +import 'package:package_info_plus/package_info_plus.dart'; + +final Device device = Device._private(); + +class Device { + late final String _packageName, _packageVersion, _userAgent; + late final bool _canAuthenticateUser, _canPinShortcut; + late final bool _canRenderFlagEmojis, _canRenderSubdivisionFlagEmojis, _canRequestManageMedia, _canSetLockScreenWallpaper; + late final bool _hasGeocoder, _isDynamicColorAvailable, _isTelevision, _showPinShortcutFeedback, _supportEdgeToEdgeUIMode, _supportPictureInPicture; + + String get packageName => _packageName; + + String get packageVersion => _packageVersion; + + String get userAgent => _userAgent; + + bool get canAuthenticateUser => _canAuthenticateUser; + + bool get canPinShortcut => _canPinShortcut; + + bool get canRenderFlagEmojis => _canRenderFlagEmojis; + + bool get canRenderSubdivisionFlagEmojis => _canRenderSubdivisionFlagEmojis; + + bool get canRequestManageMedia => _canRequestManageMedia; + + bool get canSetLockScreenWallpaper => _canSetLockScreenWallpaper; + + bool get hasGeocoder => _hasGeocoder; + + bool get isDynamicColorAvailable => _isDynamicColorAvailable; + + bool get isTelevision => _isTelevision; + + bool get showPinShortcutFeedback => _showPinShortcutFeedback; + + bool get supportEdgeToEdgeUIMode => _supportEdgeToEdgeUIMode; + + bool get supportPictureInPicture => _supportPictureInPicture; + + Device._private(); + + Future<void> init() async { + final packageInfo = await PackageInfo.fromPlatform(); + _packageName = packageInfo.packageName; + _packageVersion = packageInfo.version; + _userAgent = '$_packageName/$_packageVersion'; + + final androidInfo = await DeviceInfoPlugin().androidInfo; + _isTelevision = androidInfo.systemFeatures.contains('android.software.leanback'); + + final auth = LocalAuthentication(); + _canAuthenticateUser = await auth.canCheckBiometrics || await auth.isDeviceSupported(); + + final capabilities = await deviceService.getCapabilities(); + _canPinShortcut = capabilities['canPinShortcut'] ?? false; + _canRenderFlagEmojis = capabilities['canRenderFlagEmojis'] ?? false; + _canRenderSubdivisionFlagEmojis = capabilities['canRenderSubdivisionFlagEmojis'] ?? false; + _canRequestManageMedia = capabilities['canRequestManageMedia'] ?? false; + _canSetLockScreenWallpaper = capabilities['canSetLockScreenWallpaper'] ?? false; + _hasGeocoder = capabilities['hasGeocoder'] ?? false; + _isDynamicColorAvailable = capabilities['isDynamicColorAvailable'] ?? false; + _showPinShortcutFeedback = capabilities['showPinShortcutFeedback'] ?? false; + _supportEdgeToEdgeUIMode = capabilities['supportEdgeToEdgeUIMode'] ?? false; + _supportPictureInPicture = capabilities['supportPictureInPicture'] ?? false; + } +} diff --git a/lib/model/dynamic_albums.dart b/lib/model/dynamic_albums.dart new file mode 100644 index 0000000..f943803 --- /dev/null +++ b/lib/model/dynamic_albums.dart @@ -0,0 +1,173 @@ +import 'dart:async'; + +import 'package:aves/model/filters/container/container.dart'; +import 'package:aves/model/filters/container/dynamic_album.dart'; +import 'package:aves/model/filters/container/group_base.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/grouping/common.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:collection/collection.dart'; +import 'package:equatable/equatable.dart'; +import 'package:event_bus/event_bus.dart'; +import 'package:flutter/foundation.dart'; +import 'package:synchronized/synchronized.dart'; + +final DynamicAlbums dynamicAlbums = DynamicAlbums._private(); + +class DynamicAlbums with ChangeNotifier { + final Set<StreamSubscription> _subscriptions = {}; + final _lock = Lock(); + Set<DynamicAlbumFilter> _rows = {}; + + final EventBus eventBus = EventBus(); + + // do not subscribe to events from other modules in constructor + // so that modules can subscribe to each other + DynamicAlbums._private() { + if (kFlutterMemoryAllocationsEnabled) ChangeNotifier.maybeDispatchObjectCreation(this); + } + + Future<void> init() async { + _rows = (await localMediaDb.loadAllDynamicAlbums()).map((v) => DynamicAlbumFilter(v.name, v.filter)).toSet(); + _subscriptions.add(albumGrouping.eventBus.on<GroupUriChangedEvent>().listen((e) => _onGroupUriChanged(e.oldGroupUri, e.newGroupUri))); + } + + int get count => _rows.length; + + Set<DynamicAlbumFilter> get all => Set.unmodifiable(_rows); + + Future<void> _doAdd(Set<DynamicAlbumFilter>? filters) async { + if (filters == null || filters.isEmpty) return; + await localMediaDb.addDynamicAlbums(filters.map((v) => DynamicAlbumRow(name: v.name, filter: v.filter)).toSet()); + _rows.addAll(filters); + } + + Future<void> _doRemove(Set<String>? names) async { + if (names == null || names.isEmpty) return; + await localMediaDb.removeDynamicAlbums(names); + _rows.removeWhere((v) => names.contains(v.name)); + } + + Future<void> add(DynamicAlbumFilter filter) async { + await _lock.synchronized(() async { + await _doAdd({filter}); + notifyListeners(); + }); + } + + Future<void> remove(Set<DynamicAlbumFilter> filters) async { + await _lock.synchronized(() async { + await _doRemove(filters.map((filter) => filter.name).toSet()); + notifyListeners(); + eventBus.fire(DynamicAlbumChangedEvent(Map.fromEntries(filters.map((v) => MapEntry(v, null))))); + }); + } + + Future<void> rename(DynamicAlbumFilter oldFilter, String newName) async { + await _lock.synchronized(() async { + final newFilter = DynamicAlbumFilter(newName, oldFilter.filter); + await _doRemove({oldFilter.name}); + await _doAdd({newFilter}); + notifyListeners(); + eventBus.fire(DynamicAlbumChangedEvent({oldFilter: newFilter})); + }); + } + + Future<void> update(Map<DynamicAlbumFilter, DynamicAlbumFilter?> changes) async { + await _lock.synchronized(() async { + final oldFilterNames = changes.keys.map((v) => v.name).toSet(); + final newFilters = changes.values.nonNulls.toSet(); + await _doRemove(oldFilterNames); + await _doAdd(newFilters); + notifyListeners(); + eventBus.fire(DynamicAlbumChangedEvent(changes)); + }); + } + + Future<void> clear() => remove(all); + + DynamicAlbumFilter? get(String name) => _rows.firstWhereOrNull((row) => row.name == name); + + bool contains(String? name) => name != null && get(name) != null; + + Future<void> _onGroupUriChanged(Uri oldGroupUri, Uri newGroupUri) async { + bool isOldGroupFilter(CollectionFilter filter) => filter is GroupBaseFilter && filter.uri == oldGroupUri; + final oldDynamicAlbumFilters = _rows.where((v) => v.containsFilter(isOldGroupFilter)).toSet(); + if (oldDynamicAlbumFilters.isEmpty) return; + + final grouping = FilterGrouping.forUri(oldGroupUri); + final newGroupFilter = grouping?.uriToFilter(newGroupUri); + CollectionFilter? transformer(v) { + if (isOldGroupFilter(v)) return v.reversed ? newGroupFilter?.reverse() : newGroupFilter; + if (v is ContainerFilter) return v.replaceFilters(transformer); + return v; + } + + final newFilters = <DynamicAlbumFilter, DynamicAlbumFilter?>{}; + oldDynamicAlbumFilters.forEach((oldFilter) { + final newFilter = oldFilter.replaceFilters(transformer); + newFilters[oldFilter] = newFilter; + }); + await update(newFilters); + } + + // import/export + + List<String>? export() { + final jsonList = all.map((row) => row.toJson()).toList(); + return jsonList.isNotEmpty ? jsonList : null; + } + + void import(dynamic jsonList) { + if (jsonList is! List) { + debugPrint('failed to import dynamic albums for jsonMap=$jsonList'); + return; + } + + jsonList.forEach((row) { + final filter = CollectionFilter.fromJson(row); + if (filter == null || filter is! DynamicAlbumFilter) { + debugPrint('failed to import dynamic album for row=$row'); + return; + } + + add(filter); + }); + } +} + +@immutable +class DynamicAlbumRow extends Equatable { + final String name; + final CollectionFilter filter; + + @override + List<Object?> get props => [name, filter]; + + const DynamicAlbumRow({ + required this.name, + required this.filter, + }); + + static DynamicAlbumRow? fromMap(Map map) { + final filter = CollectionFilter.fromJson(map['filter']); + if (filter == null) return null; + + return DynamicAlbumRow( + name: map['name'] as String, + filter: filter, + ); + } + + Map<String, dynamic> toMap() => { + 'name': name, + 'filter': filter.toJson(), + }; +} + +@immutable +class DynamicAlbumChangedEvent { + final Map<DynamicAlbumFilter, DynamicAlbumFilter?> changes; + + const DynamicAlbumChangedEvent(this.changes); +} diff --git a/lib/model/entry/cache.dart b/lib/model/entry/cache.dart new file mode 100644 index 0000000..ecb32d7 --- /dev/null +++ b/lib/model/entry/cache.dart @@ -0,0 +1,64 @@ +import 'dart:async'; + +import 'package:aves/image_providers/full_image_provider.dart'; +import 'package:aves/image_providers/thumbnail_provider.dart'; +import 'package:flutter/foundation.dart'; + +class EntryCache { + // ordered descending + static final thumbnailRequestExtents = <double>[]; + + static void markThumbnailExtent(double extent) { + if (!thumbnailRequestExtents.contains(extent)) { + thumbnailRequestExtents + ..add(extent) + ..sort((a, b) => b.compareTo(a)); + } + } + + static Future<void> evict( + String uri, + String mimeType, + int? dateModifiedMillis, + int rotationDegrees, + bool isFlipped, + bool isAnimated, + ) async { + debugPrint('Evict cached images for uri=$uri, mimeType=$mimeType, dateModifiedMillis=$dateModifiedMillis, rotationDegrees=$rotationDegrees, isFlipped=$isFlipped, isAnimated=$isAnimated'); + + // TODO TLAD provide pageId parameter for multi page items, if someday image editing features are added for them + int? pageId; + + // evict fullscreen image + await FullImage( + uri: uri, + mimeType: mimeType, + pageId: pageId, + rotationDegrees: rotationDegrees, + isFlipped: isFlipped, + isAnimated: isAnimated, + ).evict(); + + // evict low quality thumbnail (without specified extents) + await ThumbnailProvider(ThumbnailProviderKey( + uri: uri, + mimeType: mimeType, + pageId: pageId, + dateModifiedMillis: dateModifiedMillis ?? 0, + rotationDegrees: rotationDegrees, + isFlipped: isFlipped, + )).evict(); + + await Future.forEach<double>( + thumbnailRequestExtents, + (extent) => ThumbnailProvider(ThumbnailProviderKey( + uri: uri, + mimeType: mimeType, + pageId: pageId, + dateModifiedMillis: dateModifiedMillis ?? 0, + rotationDegrees: rotationDegrees, + isFlipped: isFlipped, + extent: extent, + )).evict()); + } +} diff --git a/lib/model/entry/dirs.dart b/lib/model/entry/dirs.dart new file mode 100644 index 0000000..6db7918 --- /dev/null +++ b/lib/model/entry/dirs.dart @@ -0,0 +1,76 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:aves/services/common/services.dart'; +import 'package:aves/utils/android_file_utils.dart'; +import 'package:collection/collection.dart'; + +final entryDirRepo = EntryDirRepo._private(); + +class EntryDirRepo { + EntryDirRepo._private(); + + // mapping between the raw entry directory path to a resolvable directory + final Map<String?, EntryDir> _dirs = {}; + final StreamController<EntryDir> _ambiguousDirStreamController = StreamController.broadcast(); + + Stream<EntryDir> get ambiguousDirStream => _ambiguousDirStreamController.stream; + + // get a resolvable directory for a raw entry directory path + EntryDir getOrCreate(String? asIs) { + var entryDir = _dirs[asIs]; + if (entryDir != null) return entryDir; + + final asIsLower = asIs?.toLowerCase(); + entryDir = _dirs.values.firstWhereOrNull((dir) => dir.asIsLower == asIsLower); + if (entryDir != null && !entryDir.ambiguous) { + entryDir.ambiguous = true; + _ambiguousDirStreamController.add(entryDir); + } + + return _dirs.putIfAbsent(asIs, () => entryDir ?? EntryDir(asIs)); + } +} + +// Some directories are ambiguous because they use different cases, +// but the OS merge and present them as one directory. +// This class resolves ambiguous directories to get the directory path +// with the right case, as presented by the OS. +class EntryDir { + final String? asIs, asIsLower; + bool ambiguous = false; + String? _resolved; + + EntryDir(this.asIs) : asIsLower = asIs?.toLowerCase(); + + String? get resolved { + if (!ambiguous) return asIs; + if (asIs == null) return null; + + _resolved ??= _resolve(); + return _resolved; + } + + String? _resolve() { + final vrl = androidFileUtils.relativeDirectoryFromPath(asIs!); + if (vrl == null || vrl.relativeDir.isEmpty) return asIs; + + var resolved = vrl.volumePath; + final parts = pContext.split(vrl.relativeDir); + for (final part in parts) { + FileSystemEntity? found; + final dir = Directory(resolved); + if (dir.existsSync()) { + final partLower = part.toLowerCase(); + try { + final childrenDirs = dir.listSync().where((v) => v.absolute is Directory).toSet(); + found = childrenDirs.firstWhereOrNull((v) => pContext.basename(v.path).toLowerCase() == partLower); + } catch (error) { + // ignore, could be IO issue when listing directory + } + } + resolved = found?.path ?? '$resolved${pContext.separator}$part'; + } + return resolved; + } +} diff --git a/lib/model/entry/entry.dart b/lib/model/entry/entry.dart new file mode 100644 index 0000000..b6f7cbc --- /dev/null +++ b/lib/model/entry/entry.dart @@ -0,0 +1,502 @@ +import 'dart:async'; +import 'dart:ui'; + +import 'package:aves/model/entry/cache.dart'; +import 'package:aves/model/entry/dirs.dart'; +import 'package:aves/model/entry/extensions/keys.dart'; +import 'package:aves/model/metadata/address.dart'; +import 'package:aves/model/metadata/catalog.dart'; +import 'package:aves/model/metadata/trash.dart'; +import 'package:aves/ref/mime_types.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/format.dart'; +import 'package:aves/utils/time_utils.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:aves_utils/aves_utils.dart'; +import 'package:flutter/foundation.dart'; +import 'package:leak_tracker/leak_tracker.dart'; + +enum EntryDataType { basic, aspectRatio, catalog, address, references } + +class AvesEntry with AvesEntryBase { + @override + int id; + + @override + String uri; + + @override + int? pageId; + + @override + int? sizeBytes; + + String? _path, _filename, _extension, _sourceTitle; + EntryDir? _directory; + int? contentId; + final String sourceMimeType; + int width, height, sourceRotationDegrees; + int? dateAddedSecs, _dateModifiedMillis, sourceDateTakenMillis, _durationMillis; + bool trashed; + int origin; + + int? _catalogDateMillis; + CatalogMetadata? _catalogMetadata; + AddressDetails? _addressDetails; + TrashDetails? trashDetails; + + // synthetic stack of related entries, e.g. burst shots or raw/developed pairs + List<AvesEntry>? stackedEntries; + + @override + final AChangeNotifier visualChangeNotifier = AChangeNotifier(); + + final AChangeNotifier metadataChangeNotifier = AChangeNotifier(), addressChangeNotifier = AChangeNotifier(); + + AvesEntry({ + required int? id, + required this.uri, + required String? path, + required this.contentId, + required this.pageId, + required this.sourceMimeType, + required this.width, + required this.height, + required this.sourceRotationDegrees, + required this.sizeBytes, + required String? sourceTitle, + required this.dateAddedSecs, + required int? dateModifiedMillis, + required this.sourceDateTakenMillis, + required int? durationMillis, + required this.trashed, + required this.origin, + this.stackedEntries, + }) : id = id ?? 0 { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectCreated( + library: 'aves', + className: '$AvesEntry', + object: this, + ); + } + this.path = path; + this.sourceTitle = sourceTitle; + this.dateModifiedMillis = dateModifiedMillis; + this.durationMillis = durationMillis; + } + + AvesEntry copyWith({ + int? id, + String? uri, + String? path, + int? contentId, + String? title, + int? dateAddedSecs, + int? dateModifiedMillis, + int? origin, + List<AvesEntry>? stackedEntries, + }) { + final copyEntryId = id ?? this.id; + final copied = AvesEntry( + id: copyEntryId, + uri: uri ?? this.uri, + path: path ?? this.path, + contentId: contentId ?? this.contentId, + pageId: null, + sourceMimeType: sourceMimeType, + width: width, + height: height, + sourceRotationDegrees: sourceRotationDegrees, + sizeBytes: sizeBytes, + sourceTitle: title ?? sourceTitle, + dateAddedSecs: dateAddedSecs ?? this.dateAddedSecs, + dateModifiedMillis: dateModifiedMillis ?? this.dateModifiedMillis, + sourceDateTakenMillis: sourceDateTakenMillis, + durationMillis: durationMillis, + trashed: trashed, + origin: origin ?? this.origin, + stackedEntries: stackedEntries ?? this.stackedEntries, + ) + ..catalogMetadata = _catalogMetadata?.copyWith(id: copyEntryId) + ..addressDetails = _addressDetails?.copyWith(id: copyEntryId) + ..trashDetails = trashDetails?.copyWith(id: copyEntryId); + + return copied; + } + + // from DB or platform source entry + factory AvesEntry.fromMap(Map map) { + return AvesEntry( + id: map[EntryFields.id] as int?, + uri: map[EntryFields.uri] as String, + path: map[EntryFields.path] as String?, + pageId: null, + contentId: map[EntryFields.contentId] as int?, + sourceMimeType: map[EntryFields.sourceMimeType] as String, + width: map[EntryFields.width] as int? ?? 0, + height: map[EntryFields.height] as int? ?? 0, + sourceRotationDegrees: map[EntryFields.sourceRotationDegrees] as int? ?? 0, + sizeBytes: map[EntryFields.sizeBytes] as int?, + sourceTitle: map[EntryFields.title] as String?, + dateAddedSecs: map[EntryFields.dateAddedSecs] as int?, + dateModifiedMillis: map[EntryFields.dateModifiedMillis] as int?, + sourceDateTakenMillis: map[EntryFields.sourceDateTakenMillis] as int?, + durationMillis: map[EntryFields.durationMillis] as int?, + trashed: (map[EntryFields.trashed] as int? ?? 0) != 0, + origin: map[EntryFields.origin] as int, + ); + } + + // for DB only + Map<String, dynamic> toDatabaseMap() { + return { + EntryFields.id: id, + EntryFields.uri: uri, + EntryFields.path: path, + EntryFields.contentId: contentId, + EntryFields.sourceMimeType: sourceMimeType, + EntryFields.width: width, + EntryFields.height: height, + EntryFields.sourceRotationDegrees: sourceRotationDegrees, + EntryFields.sizeBytes: sizeBytes, + EntryFields.title: sourceTitle, + EntryFields.dateAddedSecs: dateAddedSecs, + EntryFields.dateModifiedMillis: dateModifiedMillis, + EntryFields.sourceDateTakenMillis: sourceDateTakenMillis, + EntryFields.durationMillis: durationMillis, + EntryFields.trashed: trashed ? 1 : 0, + EntryFields.origin: origin, + }; + } + + Map<String, dynamic> toPlatformEntryMap() { + return { + EntryFields.uri: uri, + EntryFields.path: path, + EntryFields.pageId: pageId, + EntryFields.mimeType: mimeType, + EntryFields.width: width, + EntryFields.height: height, + EntryFields.rotationDegrees: rotationDegrees, + EntryFields.isFlipped: isFlipped, + EntryFields.dateModifiedMillis: dateModifiedMillis, + EntryFields.sizeBytes: sizeBytes, + EntryFields.trashed: trashed, + EntryFields.trashPath: trashDetails?.path, + EntryFields.origin: origin, + }; + } + + void dispose() { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectDisposed(object: this); + } + visualChangeNotifier.dispose(); + metadataChangeNotifier.dispose(); + addressChangeNotifier.dispose(); + } + + // do not implement [Object.==] and [Object.hashCode] using mutable attributes (e.g. `uri`) + // so that we can reliably use instances in a `Set`, which requires consistent hash codes over time + + @override + String toString() => '$runtimeType#${shortHash(this)}{id=$id, uri=$uri, path=$path, pageId=$pageId}'; + + set path(String? path) { + _path = path; + _directory = null; + _filename = null; + _extension = null; + _bestTitle = null; + } + + @override + String? get path => _path; + + // directory path, without the trailing separator + String? get directory { + _directory ??= entryDirRepo.getOrCreate(path != null ? pContext.dirname(path!) : null); + return _directory!.resolved; + } + + String? get filenameWithoutExtension { + _filename ??= path != null ? pContext.basenameWithoutExtension(path!) : null; + return _filename; + } + + // file extension, including the `.` + String? get extension { + _extension ??= path != null ? pContext.extension(path!) : null; + return _extension; + } + + // the MIME type reported by the Media Store is unreliable + // so we use the one found during cataloguing if possible + @override + String get mimeType => _catalogMetadata?.mimeType ?? sourceMimeType; + + bool get isCatalogued => _catalogMetadata != null; + + DateTime? _bestDate; + + DateTime? get bestDate { + _bestDate ??= dateTimeFromMillis(_catalogDateMillis) ?? dateTimeFromMillis(sourceDateTakenMillis) ?? dateTimeFromMillis(dateModifiedMillis ?? 0); + return _bestDate; + } + + @override + bool get isAnimated => catalogMetadata?.isAnimated ?? false; + + bool get isHdr => _catalogMetadata?.isHdr ?? false; + + int get rating => _catalogMetadata?.rating ?? 0; + + @override + int get rotationDegrees => _catalogMetadata?.rotationDegrees ?? sourceRotationDegrees; + + set rotationDegrees(int rotationDegrees) { + sourceRotationDegrees = rotationDegrees; + _catalogMetadata?.rotationDegrees = rotationDegrees; + } + + bool get isFlipped => _catalogMetadata?.isFlipped ?? false; + + set isFlipped(bool isFlipped) => _catalogMetadata?.isFlipped = isFlipped; + + // Media Store size/rotation is inaccurate, e.g. a portrait FHD video is rotated according to its metadata, + // so it should be registered as width=1920, height=1080, orientation=90, + // but is incorrectly registered as width=1080, height=1920, orientation=0. + // Double-checking the width/height during loading or cataloguing is the proper solution, but it would take space and time. + // Comparing width and height can help with the portrait FHD video example, + // but it fails for a portrait screenshot rotated, which is landscape with width=1080, height=1920, orientation=90 + bool get isRotated => rotationDegrees % 180 == 90; + + @override + double get displayAspectRatio { + if (width == 0 || height == 0) return 1; + return isRotated ? height / width : width / height; + } + + @override + Size get displaySize { + final w = width.toDouble(); + final h = height.toDouble(); + return isRotated ? Size(h, w) : Size(w, h); + } + + String? get sourceTitle => _sourceTitle; + + set sourceTitle(String? sourceTitle) { + _sourceTitle = sourceTitle; + _bestTitle = null; + } + + int? get dateModifiedMillis => _dateModifiedMillis; + + set dateModifiedMillis(int? dateModifiedMillis) { + _dateModifiedMillis = dateModifiedMillis; + _bestDate = null; + } + + // TODO TLAD cache _monthTaken + DateTime? get monthTaken { + final d = bestDate; + return d == null ? null : DateTime(d.year, d.month); + } + + // TODO TLAD cache _dayTaken + DateTime? get dayTaken { + final d = bestDate; + return d == null ? null : DateTime(d.year, d.month, d.day); + } + + @override + int? get durationMillis => _durationMillis; + + set durationMillis(int? durationMillis) { + _durationMillis = durationMillis; + _durationText = null; + } + + String? _durationText; + + String get durationText { + _durationText ??= formatFriendlyDuration(Duration(milliseconds: durationMillis ?? 0)); + return _durationText!; + } + + // returns whether this entry has GPS coordinates + // (0, 0) coordinates are considered invalid, as it is likely a default value + bool get hasGps => (_catalogMetadata?.latitude ?? 0) != 0 || (_catalogMetadata?.longitude ?? 0) != 0; + + bool get hasAddress => _addressDetails != null; + + // has a place, or at least the full country name + // derived from Google reverse geocoding addresses + bool get hasFineAddress => _addressDetails?.place?.isNotEmpty == true || (_addressDetails?.countryName?.length ?? 0) > 3; + + Set<String>? _tags; + + Set<String> get tags { + _tags ??= _catalogMetadata?.xmpSubjects?.split(';').where((tag) => tag.isNotEmpty).toSet() ?? {}; + return _tags!; + } + + String? _bestTitle; + + @override + String? get bestTitle { + _bestTitle ??= _catalogMetadata?.xmpTitle?.isNotEmpty == true ? _catalogMetadata!.xmpTitle : (filenameWithoutExtension ?? sourceTitle); + return _bestTitle; + } + + int? get catalogDateMillis => _catalogDateMillis; + + set catalogDateMillis(int? dateMillis) { + _catalogDateMillis = dateMillis; + _bestDate = null; + } + + CatalogMetadata? get catalogMetadata => _catalogMetadata; + + set catalogMetadata(CatalogMetadata? newMetadata) { + final oldMimeType = mimeType; + final oldDateModifiedMillis = dateModifiedMillis; + final oldRotationDegrees = rotationDegrees; + final oldIsFlipped = isFlipped; + + catalogDateMillis = newMetadata?.dateMillis; + _catalogMetadata = newMetadata; + _bestTitle = null; + _tags = null; + metadataChangeNotifier.notify(); + + _onVisualFieldChanged(oldMimeType, oldDateModifiedMillis, oldRotationDegrees, oldIsFlipped); + } + + void clearMetadata() { + catalogMetadata = null; + addressDetails = null; + } + + AddressDetails? get addressDetails => _addressDetails; + + set addressDetails(AddressDetails? newAddress) { + _addressDetails = newAddress; + addressChangeNotifier.notify(); + } + + String get shortAddress { + // `admin area` examples: Seoul, Geneva, null + // `locality` examples: Mapo-gu, Geneva, Annecy + return { + _addressDetails?.countryName, + _addressDetails?.adminArea, + _addressDetails?.locality, + }.nonNulls.where((v) => v.isNotEmpty).join(', '); + } + + static void normalizeMimeTypeFields(Map fields) { + final mimeType = fields[EntryFields.mimeType] as String?; + if (mimeType != null) { + fields[EntryFields.mimeType] = MimeTypes.normalize(mimeType); + } + final sourceMimeType = fields[EntryFields.sourceMimeType] as String?; + if (sourceMimeType != null) { + fields[EntryFields.sourceMimeType] = MimeTypes.normalize(sourceMimeType); + } + } + + Future<void> applyNewFields(Map newFields, {required bool persist}) async { + final oldMimeType = mimeType; + final oldDateModifiedMillis = this.dateModifiedMillis; + final oldRotationDegrees = this.rotationDegrees; + final oldIsFlipped = this.isFlipped; + + final uri = newFields[EntryFields.uri]; + if (uri is String) this.uri = uri; + final path = newFields[EntryFields.path]; + if (path is String) this.path = path; + final contentId = newFields[EntryFields.contentId]; + if (contentId is int) this.contentId = contentId; + + final sourceTitle = newFields[EntryFields.title]; + if (sourceTitle is String) this.sourceTitle = sourceTitle; + final sourceRotationDegrees = newFields[EntryFields.sourceRotationDegrees]; + if (sourceRotationDegrees is int) this.sourceRotationDegrees = sourceRotationDegrees; + final sourceDateTakenMillis = newFields[EntryFields.sourceDateTakenMillis]; + if (sourceDateTakenMillis is int) this.sourceDateTakenMillis = sourceDateTakenMillis; + + final width = newFields[EntryFields.width]; + if (width is int) this.width = width; + final height = newFields[EntryFields.height]; + if (height is int) this.height = height; + final durationMillis = newFields[EntryFields.durationMillis]; + if (durationMillis is int) this.durationMillis = durationMillis; + + final sizeBytes = newFields[EntryFields.sizeBytes]; + if (sizeBytes is int) this.sizeBytes = sizeBytes; + final dateModifiedMillis = newFields[EntryFields.dateModifiedMillis]; + if (dateModifiedMillis is int) this.dateModifiedMillis = dateModifiedMillis; + final rotationDegrees = newFields[EntryFields.rotationDegrees]; + if (rotationDegrees is int) this.rotationDegrees = rotationDegrees; + final isFlipped = newFields[EntryFields.isFlipped]; + if (isFlipped is bool) this.isFlipped = isFlipped; + + if (persist) { + await localMediaDb.updateEntry(id, this); + if (catalogMetadata != null) await localMediaDb.saveCatalogMetadata({catalogMetadata!}); + } + + await _onVisualFieldChanged(oldMimeType, oldDateModifiedMillis, oldRotationDegrees, oldIsFlipped); + metadataChangeNotifier.notify(); + } + + Future<void> refresh({ + required bool background, + required bool persist, + required Set<EntryDataType> dataTypes, + }) async { + // clear derived fields + _bestDate = null; + _bestTitle = null; + _tags = null; + + if (persist) { + await localMediaDb.removeIds({id}, dataTypes: dataTypes); + } + + final updatedEntry = await mediaFetchService.getEntry(uri, mimeType); + if (updatedEntry != null) { + await applyNewFields(updatedEntry.toDatabaseMap(), persist: persist); + } + } + + Future<bool> delete() { + final opCompleter = Completer<bool>(); + mediaEditService.delete(entries: {this}).listen( + (event) => opCompleter.complete(event.success && !event.skipped), + onError: opCompleter.completeError, + onDone: () { + if (!opCompleter.isCompleted) { + opCompleter.complete(false); + } + }, + ); + return opCompleter.future; + } + + // when the MIME type or the image itself changed (e.g. after rotation) + Future<void> _onVisualFieldChanged( + String oldMimeType, + int? oldDateModifiedMillis, + int oldRotationDegrees, + bool oldIsFlipped, + ) async { + if ((!MimeTypes.refersToSameType(oldMimeType, mimeType) && !MimeTypes.isVideo(oldMimeType)) || oldDateModifiedMillis != dateModifiedMillis || oldRotationDegrees != rotationDegrees || oldIsFlipped != isFlipped) { + await EntryCache.evict(uri, oldMimeType, oldDateModifiedMillis, oldRotationDegrees, oldIsFlipped, isAnimated); + visualChangeNotifier.notify(); + } + } +} diff --git a/lib/model/entry/extensions/catalog.dart b/lib/model/entry/extensions/catalog.dart new file mode 100644 index 0000000..593fadd --- /dev/null +++ b/lib/model/entry/extensions/catalog.dart @@ -0,0 +1,82 @@ +import 'dart:async'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/keys.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/model/media/geotiff.dart'; +import 'package:aves/model/media/video/metadata.dart'; +import 'package:aves/model/metadata/catalog.dart'; +import 'package:aves/ref/mime_types.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/services/metadata/svg_metadata_service.dart'; +import 'package:flutter/foundation.dart'; + +extension ExtraAvesEntryCatalog on AvesEntry { + Future<void> catalog({required bool background, required bool force, required bool persist}) async { + if (isCatalogued && !force) return; + + final beforeAvailableHeapSize = await deviceService.getAvailableHeapSize(); + + if (isSvg) { + // vector image sizing is not essential, so we should not spend time for it during loading + // but it is useful anyway (for aspect ratios etc.) so we size them during cataloguing + final size = await SvgMetadataService.getSize(this); + if (size != null) { + final fields = { + EntryFields.width: size.width.ceil(), + EntryFields.height: size.height.ceil(), + }; + await applyNewFields(fields, persist: persist); + } + catalogMetadata = CatalogMetadata(id: id); + } else { + // pre-processing + if (isVideo || mimeType == MimeTypes.avif) { + // on initial loading, original source may report incorrect size, rotation or duration + final fields = await VideoMetadataFormatter.getLoadingMetadata(this); + // check size as the video interpreter may fail on some AVIF stills + final width = fields[EntryFields.width]; + final height = fields[EntryFields.height]; + final isValid = (width == null || width > 0) && (height == null || height > 0); + if (isValid) { + await applyNewFields(fields, persist: persist); + } + } + + // cataloguing on platform + catalogMetadata = await metadataFetchService.getCatalogMetadata(this, background: background); + + // post-processing + if ((isVideo && (catalogMetadata?.dateMillis ?? 0) == 0) || (mimeType == MimeTypes.avif && durationMillis != null)) { + final videoMetadata = await VideoMetadataFormatter.completeCatalogMetadata(this); + if (videoMetadata != null) { + catalogMetadata = videoMetadata; + } + } + if (isGeotiff && !hasGps) { + final info = await metadataFetchService.getGeoTiffInfo(this); + if (info != null) { + final center = GeoTiffCoordinateConverter( + info: info, + entry: this, + ).center; + if (center != null) { + catalogMetadata = catalogMetadata?.copyWith( + latitude: center.latitude, + longitude: center.longitude, + ); + } + } + } + } + + final afterAvailableHeapSize = await deviceService.getAvailableHeapSize(); + final diff = beforeAvailableHeapSize - afterAvailableHeapSize; + const largeHeapUsageThreshold = 15 * (1 << 20); // MB + + if (diff > largeHeapUsageThreshold) { + debugPrint('Large heap usage (${diff}B) from cataloguing entry=$this size=$sizeBytes'); + await deviceService.requestGarbageCollection(); + } + } +} diff --git a/lib/model/entry/extensions/favourites.dart b/lib/model/entry/extensions/favourites.dart new file mode 100644 index 0000000..22ca36f --- /dev/null +++ b/lib/model/entry/extensions/favourites.dart @@ -0,0 +1,26 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/favourites.dart'; + +extension ExtraAvesEntryFav on AvesEntry { + bool get isFavourite => favourites.isFavourite(this); + + Future<void> toggleFavourite() async { + if (isFavourite) { + await removeFromFavourites(); + } else { + await addToFavourites(); + } + } + + Future<void> addToFavourites() async { + if (!isFavourite) { + await favourites.add({this}); + } + } + + Future<void> removeFromFavourites() async { + if (isFavourite) { + await favourites.removeEntries({this}); + } + } +} diff --git a/lib/model/entry/extensions/images.dart b/lib/model/entry/extensions/images.dart new file mode 100644 index 0000000..8181bd5 --- /dev/null +++ b/lib/model/entry/extensions/images.dart @@ -0,0 +1,83 @@ +import 'dart:math'; + +import 'package:aves/image_providers/full_image_provider.dart'; +import 'package:aves/image_providers/region_provider.dart'; +import 'package:aves/image_providers/thumbnail_provider.dart'; +import 'package:aves/model/entry/cache.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/utils/math_utils.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/painting.dart'; + +extension ExtraAvesEntryImages on AvesEntry { + bool isThumbnailReady({double extent = 0}) => _isReady(_getThumbnailProviderKey(extent)); + + ThumbnailProvider getThumbnail({double extent = 0}) { + return ThumbnailProvider(_getThumbnailProviderKey(extent)); + } + + ThumbnailProviderKey _getThumbnailProviderKey(double extent) { + final requestExtent = extent.roundToDouble(); + EntryCache.markThumbnailExtent(requestExtent); + return ThumbnailProviderKey( + uri: uri, + mimeType: mimeType, + pageId: pageId, + rotationDegrees: rotationDegrees, + isFlipped: isFlipped, + dateModifiedMillis: dateModifiedMillis ?? -1, + extent: requestExtent, + ); + } + + RegionProvider getRegion({int sampleSize = 1, double scale = 1, required Rectangle<num> region}) { + return RegionProvider(RegionProviderKey( + uri: uri, + mimeType: mimeType, + pageId: pageId, + sizeBytes: sizeBytes, + rotationDegrees: rotationDegrees, + isFlipped: isFlipped, + sampleSize: sampleSize, + regionRect: Rectangle( + (region.left * scale).round(), + (region.top * scale).round(), + (region.width * scale).round(), + (region.height * scale).round(), + ), + imageSize: Size((width * scale).toDouble(), (height * scale).toDouble()), + )); + } + + Rectangle<double> get fullImageRegion => Rectangle<double>(.0, .0, width.toDouble(), height.toDouble()); + + FullImage get fullImage => FullImage( + uri: uri, + mimeType: mimeType, + pageId: pageId, + rotationDegrees: rotationDegrees, + isFlipped: isFlipped, + isAnimated: isAnimated, + sizeBytes: sizeBytes, + ); + + bool _isReady(Object providerKey) => imageCache.statusForKey(providerKey).keepAlive; + + List<ThumbnailProvider> get cachedThumbnails => EntryCache.thumbnailRequestExtents.map(_getThumbnailProviderKey).where(_isReady).map(ThumbnailProvider.new).toList(); + + ThumbnailProvider get bestCachedThumbnail { + final sizedThumbnailKey = EntryCache.thumbnailRequestExtents.map(_getThumbnailProviderKey).firstWhereOrNull(_isReady); + return sizedThumbnailKey != null ? ThumbnailProvider(sizedThumbnailKey) : getThumbnail(); + } + + static int sampleSizeForScale({ + required double magnifierScale, + required double devicePixelRatio, + }) { + var sample = 0; + if (0 < magnifierScale && magnifierScale < 1) { + sample = highestPowerOf2(1 / (magnifierScale * devicePixelRatio)); + } + return max<int>(1, sample); + } +} diff --git a/lib/model/entry/extensions/info.dart b/lib/model/entry/extensions/info.dart new file mode 100644 index 0000000..81fc0bf --- /dev/null +++ b/lib/model/entry/extensions/info.dart @@ -0,0 +1,179 @@ +import 'dart:async'; +import 'dart:collection'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/multipage.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/model/media/video/metadata.dart'; +import 'package:aves/ref/mime_types.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/services/metadata/svg_metadata_service.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/theme/format.dart'; +import 'package:aves/theme/text.dart'; +import 'package:aves/widgets/viewer/info/metadata/metadata_dir.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/widgets.dart'; +import 'package:provider/provider.dart'; + +extension ExtraAvesEntryInfo on AvesEntry { + // directory names may contain the name of their parent directory (as prefix + '/') + // directory names may contain an index (as suffix in '[]') + static final directoryNamePattern = RegExp(r'^((?<parent>.*?)/)?(?<name>.*?)(\[(?<index>\d+)\])?$'); + + Future<List<MapEntry<String, MetadataDirectory>>> getMetadataDirectories(BuildContext context) async { + final rawMetadata = await (isSvg ? SvgMetadataService.getAllMetadata(this) : metadataFetchService.getAllMetadata(this)); + final directories = rawMetadata.entries.map((dirKV) { + var directoryName = dirKV.key as String; + + String? parent; + int? index; + final match = directoryNamePattern.firstMatch(directoryName); + if (match != null) { + parent = match.namedGroup('parent'); + final nameMatch = match.namedGroup('name'); + if (nameMatch != null) { + directoryName = nameMatch; + } + final indexMatch = match.namedGroup('index'); + if (indexMatch != null) { + index = int.tryParse(indexMatch); + } + } + + final rawTags = dirKV.value as Map; + return MetadataDirectory( + directoryName, + _toSortedTags(rawTags), + parent: parent, + index: index, + ); + }).toList(); + + if (isVideo || (mimeType == MimeTypes.heif && isMultiPage) || mimeType == MimeTypes.avif) { + directories.addAll(await _getStreamDirectories(context)); + } + + final titledDirectories = directories.map((dir) { + var title = dir.name; + if (directories.where((dir) => dir.name == title).length > 1 && dir.parent?.isNotEmpty == true) { + title = '${dir.parent}/$title'; + } + if (dir.index != null) { + title += ' ${dir.index}'; + } + return MapEntry(title, dir); + }).toList() + ..sort((a, b) => compareAsciiUpperCase(a.key, b.key)); + + return titledDirectories; + } + + Future<List<MetadataDirectory>> _getStreamDirectories(BuildContext context) async { + final directories = <MetadataDirectory>[]; + final mediaInfo = await videoMetadataFetcher.getMetadata(this); + if (!context.mounted) { + return directories; + } + + final formattedMediaTags = VideoMetadataFormatter.formatInfo(mediaInfo); + if (formattedMediaTags.isNotEmpty) { + // overwrite generic directory found from the platform side + directories.add(MetadataDirectory(MetadataDirectory.mediaDirectory, _toSortedTags(formattedMediaTags))); + } + + if (mediaInfo.containsKey(Keys.chapters)) { + final allChapters = (mediaInfo.remove(Keys.chapters) as List).cast<Map>(); + if (allChapters.isNotEmpty) { + allChapters.sortBy((v) => v[Keys.time] as num? ?? 0); + + final chapterTags = SplayTreeMap.of(Map.fromEntries(allChapters.mapIndexed((i, chapter) { + final chapterNumber = i + 1; + final time = Duration(seconds: (chapter[Keys.time] as num? ?? 0).round()); + final title = chapter[Keys.title] as String? ?? 'Chapter $chapterNumber'; + return MapEntry('$chapterNumber${AText.separator}${formatFriendlyDuration(time)}', title); + })), compareNatural); + directories.add(MetadataDirectory('Chapters', chapterTags)); + } + } + + if (mediaInfo.containsKey(Keys.streams)) { + String getTypeText(Map stream) { + final type = stream[Keys.streamType] ?? MediaStreamTypes.unknown; + switch (type) { + case MediaStreamTypes.attachment: + return 'Attachment'; + case MediaStreamTypes.audio: + return 'Audio'; + case MediaStreamTypes.metadata: + return 'Metadata'; + case MediaStreamTypes.subtitle: + case MediaStreamTypes.timedText: + return 'Text'; + case MediaStreamTypes.video: + return stream.containsKey(Keys.fpsDen) || stream.containsKey(Keys.fps) ? 'Video' : 'Image'; + case MediaStreamTypes.unknown: + default: + return 'Unknown'; + } + } + + final allStreams = (mediaInfo[Keys.streams] as List).cast<Map>(); + final attachmentStreams = allStreams.where((stream) => stream[Keys.streamType] == MediaStreamTypes.attachment).toList(); + final knownStreams = allStreams.whereNot(attachmentStreams.contains); + + // display known streams as separate directories (e.g. video, audio, subs) + if (knownStreams.isNotEmpty) { + final indexDigits = knownStreams.length.toString().length; + + final colors = context.read<AvesColorsData>(); + for (final stream in knownStreams) { + final index = (stream[Keys.index] ?? 0) + 1; + final typeText = getTypeText(stream); + final dirName = [ + 'Stream ${index.toString().padLeft(indexDigits, '0')}', + typeText, + ].join(AText.separator); + final formattedStreamTags = VideoMetadataFormatter.formatInfo(stream); + if (formattedStreamTags.isNotEmpty) { + final color = colors.fromString(typeText); + directories.add(MetadataDirectory(dirName, _toSortedTags(formattedStreamTags), color: color)); + } + } + } + + // group attachments by format (e.g. TTF fonts) + if (attachmentStreams.isNotEmpty) { + final formatCount = <String, List<String?>>{}; + for (final stream in attachmentStreams) { + final codec = (stream[Keys.codecName] as String? ?? 'unknown').toUpperCase(); + if (!formatCount.containsKey(codec)) { + formatCount[codec] = []; + } + formatCount[codec]!.add(stream[Keys.filename]); + } + if (formatCount.isNotEmpty) { + final rawTags = formatCount.map((key, value) { + final count = value.length; + // remove duplicate names, so number of displayed names may not match displayed count + final names = value.nonNulls.toSet().toList()..sort(compareAsciiUpperCase); + return MapEntry(key, '$count items: ${names.join(', ')}'); + }); + directories.add(MetadataDirectory('Attachments', _toSortedTags(rawTags))); + } + } + } + return directories; + } + + SplayTreeMap<String, String> _toSortedTags(Map rawTags) { + final tags = SplayTreeMap.of(Map.fromEntries(rawTags.entries.map((tagKV) { + var value = (tagKV.value as String? ?? '').trim(); + if (value.isEmpty) return null; + final tagName = tagKV.key as String; + return MapEntry(tagName, value); + }).nonNulls)); + return tags; + } +} diff --git a/lib/model/entry/extensions/keys.dart b/lib/model/entry/extensions/keys.dart new file mode 100644 index 0000000..d6eeafb --- /dev/null +++ b/lib/model/entry/extensions/keys.dart @@ -0,0 +1,28 @@ +// entry fields exported and imported from/to the platform side +// should match `EntryFields` on platform side +class EntryFields { + static const id = 'id'; // int + static const origin = 'origin'; // int + static const uri = 'uri'; // string + static const contentId = 'contentId'; // long + static const path = 'path'; // string + static const pageId = 'pageId'; // int + static const sourceMimeType = 'sourceMimeType'; // string + static const mimeType = 'mimeType'; // string + + static const width = 'width'; // int + static const height = 'height'; // int + static const sourceRotationDegrees = 'sourceRotationDegrees'; // int + static const rotationDegrees = 'rotationDegrees'; // int + static const isFlipped = 'isFlipped'; // boolean + + static const dateAddedSecs = 'dateAddedSecs'; // long + static const dateModifiedMillis = 'dateModifiedMillis'; // long + static const sourceDateTakenMillis = 'sourceDateTakenMillis'; // long + static const durationMillis = 'durationMillis'; // long + + static const sizeBytes = 'sizeBytes'; // long + static const trashed = 'trashed'; // boolean + static const trashPath = 'trashPath'; // string + static const title = 'title'; // string +} diff --git a/lib/model/entry/extensions/location.dart b/lib/model/entry/extensions/location.dart new file mode 100644 index 0000000..e33c4ab --- /dev/null +++ b/lib/model/entry/extensions/location.dart @@ -0,0 +1,90 @@ +import 'dart:async'; +import 'dart:ui'; + +import 'package:aves/geo/countries.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/metadata/address.dart'; +import 'package:aves/services/common/service_policy.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/services/geocoding_service.dart'; +import 'package:country_code/country_code.dart'; +import 'package:flutter/foundation.dart'; +import 'package:latlong2/latlong.dart'; + +extension ExtraAvesEntryLocation on AvesEntry { + static final _invalidLocalityPattern = RegExp(r'^[-+\dA-Z]+$'); + + LatLng? get latLng => hasGps ? LatLng(catalogMetadata!.latitude!, catalogMetadata!.longitude!) : null; + + Future<void> locate({required bool background, required bool force, required Locale geocoderLocale}) async { + if (hasGps) { + await _locateCountry(force: force); + if (await availability.canLocatePlaces) { + await locatePlace(background: background, force: force, geocoderLocale: geocoderLocale); + } + } else { + addressDetails = null; + } + } + + // quick reverse geocoding to find the country, using an offline asset + Future<void> _locateCountry({required bool force}) async { + if (!hasGps || (hasAddress && !force)) return; + final countryCode = await countryTopology.countryCode(latLng!); + setCountry(countryCode); + } + + void setCountry(CountryCode? countryCode) { + if (hasFineAddress || countryCode == null) return; + addressDetails = AddressDetails( + id: id, + countryCode: countryCode.alpha2, + countryName: countryCode.alpha3, + ); + } + + // full reverse geocoding, requiring Play Services and some connectivity + Future<void> locatePlace({required bool background, required bool force, required Locale geocoderLocale}) async { + if (!hasGps || (hasFineAddress && !force)) return; + try { + Future<List<Address>> call() => GeocodingService.getAddress(latLng!, geocoderLocale); + final addresses = await (background + ? servicePolicy.call( + call, + priority: ServiceCallPriority.getLocation, + ) + : call()); + if (addresses.isNotEmpty) { + final v = addresses.first; + var locality = v.locality ?? v.subLocality ?? v.featureName; + if (locality == null || _invalidLocalityPattern.hasMatch(locality) || {v.subThoroughfare, v.countryName}.contains(locality)) { + locality = v.subAdminArea; + } + addressDetails = AddressDetails( + id: id, + countryCode: v.countryCode?.toUpperCase(), + countryName: v.countryName, + adminArea: v.adminArea, + locality: locality, + ); + } + } catch (error, stack) { + debugPrint('$runtimeType locate failed with path=$path coordinates=$latLng error=$error\n$stack'); + } + } + + Future<String?> findAddressLine({required Locale geocoderLocale}) async { + if (!hasGps) return null; + + try { + final addresses = await GeocodingService.getAddress(latLng!, geocoderLocale); + if (addresses.isNotEmpty) { + final address = addresses.first; + return address.addressLine; + } + } catch (error, stack) { + debugPrint('$runtimeType findAddressLine failed with path=$path coordinates=$latLng error=$error\n$stack'); + } + return null; + } +} diff --git a/lib/model/entry/extensions/metadata_edition.dart b/lib/model/entry/extensions/metadata_edition.dart new file mode 100644 index 0000000..3c196d4 --- /dev/null +++ b/lib/model/entry/extensions/metadata_edition.dart @@ -0,0 +1,590 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:aves/convert/convert.dart'; +import 'package:aves/model/device.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/catalog.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/model/metadata/date_modifier.dart'; +import 'package:aves/ref/locales.dart'; +import 'package:aves/ref/metadata/exif.dart'; +import 'package:aves/ref/metadata/iptc.dart'; +import 'package:aves/ref/metadata/xmp.dart'; +import 'package:aves/ref/mime_types.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/services/metadata/xmp.dart'; +import 'package:aves/utils/time_utils.dart'; +import 'package:aves/utils/xmp_utils.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/foundation.dart'; +import 'package:intl/intl.dart'; +import 'package:latlong2/latlong.dart'; +import 'package:xml/xml.dart'; + +extension ExtraAvesEntryMetadataEdition on AvesEntry { + static final _iso6709LatitudeFormatter = NumberFormat('00.0000', asciiLocale); + static final _iso6709LongitudeFormatter = NumberFormat('000.0000', asciiLocale); + + Future<Set<EntryDataType>> editDate(DateModifier userModifier) async { + final dataTypes = <EntryDataType>{}; + + final appliedModifier = await _applyDateModifierToEntry(userModifier); + if (appliedModifier == null) { + if (isValid && userModifier.action != DateEditAction.copyField) { + await reportService.recordError('failed to get date for modifier=$userModifier, entry=$this'); + } + return {}; + } + + if (isExifEditionSupported && appliedModifier.fields.any((v) => v.type == MetadataType.exif)) { + final newFields = await metadataEditService.editExifDate(this, appliedModifier); + if (newFields.isNotEmpty) { + dataTypes.addAll({ + EntryDataType.basic, + EntryDataType.catalog, + }); + } + } + + if (isXmpEditionSupported && appliedModifier.fields.any((v) => v.type == MetadataType.xmp)) { + final metadata = { + MetadataType.xmp: await _editXmp((descriptions) { + switch (appliedModifier.action) { + case DateEditAction.setCustom: + case DateEditAction.copyField: + case DateEditAction.copyItem: + case DateEditAction.extractFromTitle: + editCreateDateXmp(descriptions, appliedModifier.setDateTime); + case DateEditAction.shift: + final xmpDate = XMP.getString(descriptions, XmpAttributes.xmpCreateDate, namespace: XmpNamespaces.xmp); + if (xmpDate != null) { + final date = DateTime.tryParse(xmpDate); + if (date != null) { + // TODO TLAD [date] DateTime.tryParse converts to UTC time, losing the time zone offset + final shiftedDate = date.add(Duration(seconds: appliedModifier.shiftSeconds!)); + editCreateDateXmp(descriptions, shiftedDate); + } else { + reportService.recordError('failed to parse XMP date=$xmpDate'); + } + } + case DateEditAction.remove: + editCreateDateXmp(descriptions, null); + } + return true; + }), + }; + final newFields = await metadataEditService.editMetadata(this, metadata); + if (newFields.isNotEmpty) { + dataTypes.addAll({ + EntryDataType.basic, + EntryDataType.catalog, + }); + } + } + + return dataTypes; + } + + static const removalLocation = LatLng(0, 0); + + Future<Set<EntryDataType>> editLocation(LatLng? latLng) async { + final dataTypes = <EntryDataType>{}; + final metadata = <MetadataType, dynamic>{}; + + final missingDate = await _missingDateCheckAndExifEdit(dataTypes); + + if (isExifEditionSupported) { + // clear every GPS field + final exifFields = Map<MetadataField, dynamic>.fromEntries(MetadataFields.exifGpsFields.map((k) => MapEntry(k, null))); + // add latitude & longitude, if any + if (latLng != null && latLng != removalLocation) { + final latitude = latLng.latitude; + final longitude = latLng.longitude; + exifFields.addAll({ + MetadataField.exifGpsLatitude: latitude.abs(), + MetadataField.exifGpsLatitudeRef: latitude >= 0 ? Exif.latitudeNorth : Exif.latitudeSouth, + MetadataField.exifGpsLongitude: longitude.abs(), + MetadataField.exifGpsLongitudeRef: longitude >= 0 ? Exif.longitudeEast : Exif.longitudeWest, + }); + } + metadata[MetadataType.exif] = Map<String, dynamic>.fromEntries(exifFields.entries.map((kv) => MapEntry(kv.key.toPlatform!, kv.value))); + + if (isXmpEditionSupported && missingDate != null) { + metadata[MetadataType.xmp] = await _editXmp((descriptions) { + editCreateDateXmp(descriptions, missingDate); + return true; + }); + } + } + + if (mimeType == MimeTypes.mp4) { + final mp4Fields = <MetadataField, String?>{}; + + String? iso6709String; + if (latLng != null && latLng != removalLocation) { + final latitude = latLng.latitude; + final longitude = latLng.longitude; + final isoLat = '${latitude >= 0 ? '+' : '-'}${_iso6709LatitudeFormatter.format(latitude.abs())}'; + final isoLon = '${longitude >= 0 ? '+' : '-'}${_iso6709LongitudeFormatter.format(longitude.abs())}'; + iso6709String = '$isoLat$isoLon/'; + } + mp4Fields[MetadataField.mp4GpsCoordinates] = iso6709String; + + if (missingDate != null) { + final xmpParts = await _editXmp((descriptions) { + editCreateDateXmp(descriptions, missingDate); + return true; + }); + mp4Fields[MetadataField.mp4Xmp] = xmpParts[xmpCoreKey]; + } + + metadata[MetadataType.mp4] = Map<String, String?>.fromEntries(mp4Fields.entries.map((kv) => MapEntry(kv.key.toPlatform!, kv.value))); + } + + final newFields = await metadataEditService.editMetadata(this, metadata); + if (newFields.isNotEmpty) { + dataTypes.addAll({ + EntryDataType.catalog, + EntryDataType.address, + }); + } + return dataTypes; + } + + Future<Set<EntryDataType>> _changeExifOrientation(Future<Map<String, dynamic>> Function() apply) async { + final dataTypes = <EntryDataType>{}; + + await _missingDateCheckAndExifEdit(dataTypes); + + final newFields = await apply(); + // applying fields is only useful for a smoother visual change, + // as proper refreshing and persistence happens at the caller level + await applyNewFields(newFields, persist: false); + if (newFields.isNotEmpty) { + dataTypes.addAll({ + EntryDataType.basic, + EntryDataType.aspectRatio, + EntryDataType.catalog, + }); + } + return dataTypes; + } + + Future<Set<EntryDataType>> _rotateMp4(int rotationDegrees) async { + final dataTypes = <EntryDataType>{}; + + final missingDate = await _missingDateCheckAndExifEdit(dataTypes); + + final mp4Fields = <MetadataField, String?>{ + MetadataField.mp4RotationDegrees: rotationDegrees.toString(), + }; + + if (missingDate != null) { + final xmpParts = await _editXmp((descriptions) { + editCreateDateXmp(descriptions, missingDate); + return true; + }); + mp4Fields[MetadataField.mp4Xmp] = xmpParts[xmpCoreKey]; + } + + final metadata = <MetadataType, dynamic>{ + MetadataType.mp4: Map<String, String?>.fromEntries(mp4Fields.entries.map((kv) => MapEntry(kv.key.toPlatform!, kv.value))), + }; + + final newFields = await metadataEditService.editMetadata(this, metadata); + // applying fields is only useful for a smoother visual change, + // as proper refreshing and persistence happens at the caller level + await applyNewFields(newFields, persist: false); + if (newFields.isNotEmpty) { + dataTypes.addAll({ + EntryDataType.basic, + EntryDataType.aspectRatio, + EntryDataType.catalog, + }); + } + return dataTypes; + } + + Future<Set<EntryDataType>> rotate({required bool clockwise}) { + if (mimeType == MimeTypes.mp4) { + return _rotateMp4((rotationDegrees + (clockwise ? 90 : -90) + 360) % 360); + } else { + return _changeExifOrientation(() => metadataEditService.rotate(this, clockwise: clockwise)); + } + } + + Future<Set<EntryDataType>> flip() { + return _changeExifOrientation(() => metadataEditService.flip(this)); + } + + // write title: + // - IPTC / object-name, if IPTC exists + // - XMP / dc:title + // write description: + // - Exif / ImageDescription (clear field) + // - Exif / UserComment (clear field) + // - IPTC / caption-abstract, if IPTC exists + // - XMP / dc:description + Future<Set<EntryDataType>> editTitleDescription(Map<DescriptionField, String?> fields) async { + final dataTypes = <EntryDataType>{}; + final metadata = <MetadataType, dynamic>{}; + + final missingDate = await _missingDateCheckAndExifEdit(dataTypes); + + final editTitle = fields.keys.contains(DescriptionField.title); + final editDescription = fields.keys.contains(DescriptionField.description); + final title = fields[DescriptionField.title]; + final description = fields[DescriptionField.description]; + + if (isExifEditionSupported && editDescription) { + metadata[MetadataType.exif] = { + // clear field because it is subpar, with ASCII support only + MetadataField.exifImageDescription.toPlatform!: null, + // clear field because it is subpar, with ambiguous encoding + MetadataField.exifUserComment.toPlatform!: null, + }; + } + + if (isIptcEditionSupported) { + final iptc = await metadataFetchService.getIptc(this); + if (iptc != null) { + if (editTitle) { + editIptcValues(iptc, IPTC.applicationRecord, IPTC.objectName, {if (title != null) title}); + } + if (editDescription) { + editIptcValues(iptc, IPTC.applicationRecord, IPTC.captionAbstractTag, {if (description != null) description}); + } + metadata[MetadataType.iptc] = iptc; + } + } + + if (isXmpEditionSupported) { + metadata[MetadataType.xmp] = await _editXmp((descriptions) { + var modified = false; + if (editTitle) { + modified |= XMP.setAttribute( + descriptions, + XmpElements.dcTitle, + title, + namespace: XmpNamespaces.dc, + strat: XmpEditStrategy.always, + ); + } + if (editDescription) { + modified |= XMP.setAttribute( + descriptions, + XmpElements.dcDescription, + description, + namespace: XmpNamespaces.dc, + strat: XmpEditStrategy.always, + ); + } + if (modified && missingDate != null) { + editCreateDateXmp(descriptions, missingDate); + } + return modified; + }); + } + + final newFields = await metadataEditService.editMetadata(this, metadata); + if (newFields.isNotEmpty) { + dataTypes.addAll({ + EntryDataType.basic, + EntryDataType.catalog, + }); + } + + return dataTypes; + } + + // write: + // - IPTC / keywords, if IPTC exists + // - XMP / dc:subject + Future<Set<EntryDataType>> editTags(Set<String> tags) async { + final dataTypes = <EntryDataType>{}; + final metadata = <MetadataType, dynamic>{}; + + final missingDate = await _missingDateCheckAndExifEdit(dataTypes); + + if (isIptcEditionSupported) { + final iptc = await metadataFetchService.getIptc(this); + if (iptc != null) { + editIptcValues(iptc, IPTC.applicationRecord, IPTC.keywordsTag, tags); + metadata[MetadataType.iptc] = iptc; + } + } + + if (isXmpEditionSupported) { + metadata[MetadataType.xmp] = await _editXmp((descriptions) { + final modified = editTagsXmp(descriptions, tags); + if (modified && missingDate != null) { + editCreateDateXmp(descriptions, missingDate); + } + return modified; + }); + } + + final newFields = await metadataEditService.editMetadata(this, metadata); + if (newFields.isNotEmpty) { + dataTypes.add(EntryDataType.catalog); + } + return dataTypes; + } + + // write: + // - XMP / xmp:Rating + // update: + // - XMP / MicrosoftPhoto:Rating + // ignore (Windows tags, not part of Exif 2.32 spec): + // - Exif / Rating + // - Exif / RatingPercent + Future<Set<EntryDataType>> editRating(int? rating) async { + final dataTypes = <EntryDataType>{}; + final metadata = <MetadataType, dynamic>{}; + + final missingDate = await _missingDateCheckAndExifEdit(dataTypes); + + if (isXmpEditionSupported) { + metadata[MetadataType.xmp] = await _editXmp((descriptions) { + final modified = editRatingXmp(descriptions, rating); + if (modified && missingDate != null) { + editCreateDateXmp(descriptions, missingDate); + } + return modified; + }); + } + + final newFields = await metadataEditService.editMetadata(this, metadata); + if (newFields.isNotEmpty) { + dataTypes.add(EntryDataType.catalog); + } + return dataTypes; + } + + // remove: + // - trailer video + // - XMP / Container:Directory + // - XMP / GCamera:MicroVideo* + // - XMP / GCamera:MotionPhoto* + Future<Set<EntryDataType>> removeTrailerVideo() async { + final dataTypes = <EntryDataType>{}; + final metadata = <MetadataType, dynamic>{}; + + if (!isXmpEditionSupported) return dataTypes; + + final missingDate = await _missingDateCheckAndExifEdit(dataTypes); + + final newFields = await metadataEditService.removeTrailerVideo(this); + + metadata[MetadataType.xmp] = await _editXmp((descriptions) { + final modified = removeContainerXmp(descriptions); + if (modified && missingDate != null) { + editCreateDateXmp(descriptions, missingDate); + } + return modified; + }); + + newFields.addAll(await metadataEditService.editMetadata(this, metadata, autoCorrectTrailerOffset: false)); + if (newFields.isNotEmpty) { + dataTypes.add(EntryDataType.catalog); + } + return dataTypes; + } + + Future<Set<EntryDataType>> removeMetadata(Set<MetadataType> types) async { + final dataTypes = <EntryDataType>{}; + + final newFields = await metadataEditService.removeTypes(this, types); + if (newFields.isNotEmpty) { + dataTypes.addAll({ + EntryDataType.basic, + EntryDataType.aspectRatio, + EntryDataType.catalog, + EntryDataType.address, + }); + } + return dataTypes; + } + + static void editIptcValues(List<Map<String, dynamic>> iptc, int record, int tag, Set<String> values) { + iptc.removeWhere((v) => v['record'] == record && v['tag'] == tag); + iptc.add({ + 'record': record, + 'tag': tag, + 'values': values.map((v) => utf8.encode(v)).toList(), + }); + } + + @visibleForTesting + static bool editCreateDateXmp(List<XmlNode> descriptions, DateTime? date) { + return XMP.setAttribute( + descriptions, + XmpAttributes.xmpCreateDate, + date != null ? XMP.toXmpDate(date) : null, + namespace: XmpNamespaces.xmp, + strat: XmpEditStrategy.always, + ); + } + + @visibleForTesting + static bool editTagsXmp(List<XmlNode> descriptions, Set<String> tags) { + return XMP.setStringBag( + descriptions, + XmpElements.dcSubject, + tags, + namespace: XmpNamespaces.dc, + strat: XmpEditStrategy.always, + ); + } + + @visibleForTesting + static bool editRatingXmp(List<XmlNode> descriptions, int? rating) { + bool modified = false; + + modified |= XMP.setAttribute( + descriptions, + XmpElements.xmpRating, + (rating ?? 0) == 0 ? null : '$rating', + namespace: XmpNamespaces.xmp, + strat: XmpEditStrategy.always, + ); + + modified |= XMP.setAttribute( + descriptions, + XmpElements.msPhotoRating, + XMP.toMsPhotoRating(rating), + namespace: XmpNamespaces.microsoftPhoto, + strat: XmpEditStrategy.updateIfPresent, + ); + + return modified; + } + + @visibleForTesting + static bool removeContainerXmp(List<XmlNode> descriptions) { + bool modified = false; + + modified |= XMP.removeElements( + descriptions, + XmpElements.containerDirectory, + XmpNamespaces.gContainer, + ); + + modified |= [ + XmpAttributes.gCameraMicroVideo, + XmpAttributes.gCameraMicroVideoVersion, + XmpAttributes.gCameraMicroVideoOffset, + XmpAttributes.gCameraMicroVideoPresentationTimestampUs, + XmpAttributes.gCameraMotionPhoto, + XmpAttributes.gCameraMotionPhotoVersion, + XmpAttributes.gCameraMotionPhotoPresentationTimestampUs, + ].fold<bool>(modified, (prev, name) { + return prev |= XMP.removeElements( + descriptions, + name, + XmpNamespaces.gCamera, + ); + }); + + return modified; + } + + // convenience methods + + // This method checks whether the item already has a metadata date, + // and adds a date (the file modified date) via Exif if possible. + // It returns a date if the caller needs to add it via other metadata types (e.g. XMP). + Future<DateTime?> _missingDateCheckAndExifEdit(Set<EntryDataType> dataTypes) async { + if (path == null) return null; + + // make sure entry is catalogued before we check whether is has a metadata date + if (!isCatalogued) { + await catalog(background: false, force: false, persist: true); + } + final dateMillis = catalogMetadata?.dateMillis; + if (dateMillis != null && dateMillis > 0) return null; + + late DateTime date; + try { + date = await File(path!).lastModified(); + } on FileSystemException catch (_) { + return null; + } + + if (isExifEditionSupported) { + final newFields = await metadataEditService.editExifDate(this, DateModifier.setCustom(const {MetadataField.exifDateOriginal}, date)); + if (newFields.isNotEmpty) { + dataTypes.addAll({ + EntryDataType.basic, + EntryDataType.catalog, + }); + return null; + } + } + + return date; + } + + Future<DateModifier?> _applyDateModifierToEntry(DateModifier modifier) async { + Set<MetadataField> mainMetadataDate() => {isExifEditionSupported ? MetadataField.exifDateOriginal : MetadataField.xmpXmpCreateDate}; + + switch (modifier.action) { + case DateEditAction.copyField: + DateTime? date; + final source = modifier.copyFieldSource; + if (source != null) { + switch (source) { + case DateFieldSource.fileModifiedDate: + try { + if (path != null) { + final file = File(path!); + if (await file.exists()) { + date = await file.lastModified(); + } + } + } on FileSystemException catch (_) {} + default: + date = await metadataFetchService.getDate(this, source.toMetadataField()!); + } + } + return date != null ? DateModifier.setCustom(mainMetadataDate(), date) : null; + case DateEditAction.extractFromTitle: + final date = parseUnknownDateFormat(bestTitle); + return date != null ? DateModifier.setCustom(mainMetadataDate(), date) : null; + case DateEditAction.setCustom: + case DateEditAction.copyItem: + return DateModifier.setCustom(mainMetadataDate(), modifier.setDateTime!); + case DateEditAction.shift: + case DateEditAction.remove: + return modifier; + } + } + + static const xmpCoreKey = 'xmp'; + static const xmpExtendedKey = 'extendedXmp'; + + Future<Map<String, String?>> _editXmp(bool Function(List<XmlNode> descriptions) apply) async { + final xmp = await metadataFetchService.getXmp(this); + if (xmp == null) { + throw Exception('failed to get XMP'); + } + + final xmpString = xmp.xmpString; + final extendedXmpString = xmp.extendedXmpString; + + final editedXmpString = await XMP.edit( + xmpString, + 'Aves v${device.packageVersion}', + apply, + ); + + final editedXmp = AvesXmp(xmpString: editedXmpString, extendedXmpString: extendedXmpString); + return { + xmpCoreKey: editedXmp.xmpString, + xmpExtendedKey: editedXmp.extendedXmpString, + }; + } +} + +enum DescriptionField { title, description } diff --git a/lib/model/entry/extensions/multipage.dart b/lib/model/entry/extensions/multipage.dart new file mode 100644 index 0000000..6b32a8e --- /dev/null +++ b/lib/model/entry/extensions/multipage.dart @@ -0,0 +1,43 @@ +import 'dart:async'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/multipage.dart'; +import 'package:aves/ref/bursts.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:collection/collection.dart'; + +extension ExtraAvesEntryMultipage on AvesEntry { + bool get isMultiPage => isStack || ((catalogMetadata?.isMultiPage ?? false) && (isMotionPhoto || !isHdr)); + + bool get isStack => stackedEntries?.isNotEmpty == true; + + bool get isMotionPhoto => catalogMetadata?.isMotionPhoto ?? false; + + String? getBurstKey(List<String> patterns) { + final key = BurstPatterns.getKeyForName(filenameWithoutExtension, patterns); + return key != null ? '$directory/$key' : null; + } + + Future<MultiPageInfo?> getMultiPageInfo() async { + if (isStack) { + return MultiPageInfo( + mainEntry: this, + pages: stackedEntries! + .mapIndexed((index, entry) => SinglePageInfo( + index: index, + pageId: entry.id, + isDefault: index == 0, + uri: entry.uri, + mimeType: entry.mimeType, + width: entry.width, + height: entry.height, + rotationDegrees: entry.rotationDegrees, + durationMillis: entry.durationMillis, + )) + .toList(), + ); + } else { + return await metadataFetchService.getMultiPageInfo(this); + } + } +} diff --git a/lib/model/entry/extensions/props.dart b/lib/model/entry/extensions/props.dart new file mode 100644 index 0000000..ec21ab7 --- /dev/null +++ b/lib/model/entry/extensions/props.dart @@ -0,0 +1,140 @@ +import 'dart:io'; +import 'dart:ui'; + +import 'package:aves/model/app/support.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/trash.dart'; +import 'package:aves/ref/mime_types.dart'; +import 'package:aves/ref/unicode.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/text.dart'; +import 'package:aves/utils/android_file_utils.dart'; +import 'package:aves/utils/time_utils.dart'; +import 'package:intl/intl.dart'; + +extension ExtraAvesEntryProps on AvesEntry { + bool get isValid => !isMissingAtPath && sizeBytes != 0 && width > 0 && height > 0; + + // type + + String get mimeTypeAnySubtype => mimeType.replaceAll(RegExp('/.*'), '/*'); + + bool get canHaveAlpha => MimeTypes.canHaveAlpha(mimeType); + + bool get isSvg => mimeType == MimeTypes.svg; + + bool get isRaw => MimeTypes.isRaw(mimeType); + + bool get isImage => MimeTypes.isImage(mimeType); + + bool get isVideo => MimeTypes.isVideo(mimeType) || (mimeType == MimeTypes.avif && isAnimated); + + bool get isPureVideo => isVideo && !isAnimated; + + // size + + bool get useTiles => !isAnimated; + + bool get isSized => width > 0 && height > 0; + + Size videoDisplaySize(double? sar) { + final size = displaySize; + if (sar != null && sar != 1) { + final dar = displayAspectRatio * sar; + final w = size.width; + final h = size.height; + if (w >= h) return Size(w, w / dar); + if (h > w) return Size(h * dar, h); + } + return size; + } + + // text + + String getResolutionText(String locale) { + final dimensionFormatter = NumberFormat('0', locale); + final ws = dimensionFormatter.format(width); + final hs = dimensionFormatter.format(height); + return isRotated ? '$hs${AText.resolutionSeparator}$ws' : '$ws${AText.resolutionSeparator}$hs'; + } + + String get aspectRatioText { + const separator = UniChars.ratio; + if (width > 0 && height > 0) { + final gcd = width.gcd(height); + final w = width ~/ gcd; + final h = height ~/ gcd; + return isRotated ? '$h$separator$w' : '$w$separator$h'; + } else { + return '?$separator?'; + } + } + + // catalog + + bool get isGeotiff => catalogMetadata?.isGeotiff ?? false; + + bool get is360 => catalogMetadata?.is360 ?? false; + + // trash + + bool get isExpiredTrash { + final dateMillis = trashDetails?.dateMillis; + if (dateMillis == null) return false; + return DateTime.fromMillisecondsSinceEpoch(dateMillis).add(TrashMixin.binKeepDuration).isBefore(DateTime.now()); + } + + int? get trashDaysLeft { + final dateMillis = trashDetails?.dateMillis; + if (dateMillis == null) return null; + return DateTime.fromMillisecondsSinceEpoch(dateMillis).add(TrashMixin.binKeepDuration).difference(DateTime.now()).inHumanDays; + } + + // storage + + String? get storageDirectory => trashed ? pContext.dirname(trashDetails!.path) : directory; + + bool get isMissingAtPath { + final _storagePath = trashed ? trashDetails?.path : path; + return _storagePath != null && !File(_storagePath).existsSync(); + } + + // providers + + bool get _isVaultContent => path?.startsWith(androidFileUtils.vaultRoot) ?? false; + + bool get _isMediaStoreContent => uri.startsWith(AndroidFileUtils.mediaStoreUriRoot); + + bool get isMediaStoreMediaContent => _isMediaStoreContent && AndroidFileUtils.mediaUriPathRoots.any(uri.contains); + + // edition + + bool get canEdit => !settings.isReadOnly && path != null && !trashed && (_isMediaStoreContent || _isVaultContent); + + bool get canEditDate => canEdit && (isExifEditionSupported || isXmpEditionSupported); + + bool get canEditLocation => canEdit && (isExifEditionSupported || mimeType == MimeTypes.mp4); + + bool get canEditTitleDescription => canEdit && isXmpEditionSupported; + + bool get canEditRating => canEdit && isXmpEditionSupported; + + bool get canEditTags => canEdit && isXmpEditionSupported; + + bool get canRotate => canEdit && (isExifEditionSupported || mimeType == MimeTypes.mp4); + + bool get canFlip => canEdit && isExifEditionSupported; + + // app support + + bool get isDecodingSupported => AppSupport.canDecode(mimeType); + + bool get isExifEditionSupported => AppSupport.canEditExif(mimeType); + + bool get isIptcEditionSupported => AppSupport.canEditIptc(mimeType); + + bool get isXmpEditionSupported => AppSupport.canEditXmp(mimeType); + + bool get isMetadataRemovalSupported => AppSupport.canRemoveMetadata(mimeType); +} diff --git a/lib/model/entry/origins.dart b/lib/model/entry/origins.dart new file mode 100644 index 0000000..efc3549 --- /dev/null +++ b/lib/model/entry/origins.dart @@ -0,0 +1,6 @@ +class EntryOrigins { + static const int mediaStoreContent = 0; + static const int unknownContent = 1; + static const int file = 2; + static const int vault = 3; +} diff --git a/lib/model/entry/sort.dart b/lib/model/entry/sort.dart new file mode 100644 index 0000000..e0e5573 --- /dev/null +++ b/lib/model/entry/sort.dart @@ -0,0 +1,52 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/utils/time_utils.dart'; +import 'package:collection/collection.dart'; + +class AvesEntrySort { + // compare by: + // 1) title ascending + // 2) extension ascending + static int compareByName(AvesEntry a, AvesEntry b) { + final c = compareAsciiUpperCaseNatural(a.bestTitle ?? '', b.bestTitle ?? ''); + return c != 0 ? c : compareAsciiUpperCase(a.extension ?? '', b.extension ?? ''); + } + + // compare by: + // 1) date descending + // 2) name descending + static int compareByDate(AvesEntry a, AvesEntry b) { + var c = (b.bestDate ?? epoch).compareTo(a.bestDate ?? epoch); + if (c != 0) return c; + return compareByName(b, a); + } + + // compare by: + // 1) rating descending + // 2) date descending + static int compareByRating(AvesEntry a, AvesEntry b) { + final c = b.rating.compareTo(a.rating); + return c != 0 ? c : compareByDate(a, b); + } + + // compare by: + // 1) size descending + // 2) date descending + static int compareBySize(AvesEntry a, AvesEntry b) { + final c = (b.sizeBytes ?? 0).compareTo(a.sizeBytes ?? 0); + return c != 0 ? c : compareByDate(a, b); + } + + // compare by: + // 1) duration descending + // 2) date descending + static int compareByDuration(AvesEntry a, AvesEntry b) { + final c = (b.durationMillis ?? 0).compareTo(a.durationMillis ?? 0); + return c != 0 ? c : compareByDate(a, b); + } + + // compare by: + // 1) path ascending + static int compareByPath(AvesEntry a, AvesEntry b) { + return compareAsciiUpperCase(a.path ?? '', b.path ?? ''); + } +} diff --git a/lib/model/favourites.dart b/lib/model/favourites.dart new file mode 100644 index 0000000..7df6d02 --- /dev/null +++ b/lib/model/favourites.dart @@ -0,0 +1,129 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/utils/android_file_utils.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flutter/foundation.dart'; + +final Favourites favourites = Favourites._private(); + +class Favourites with ChangeNotifier { + Set<FavouriteRow> _rows = {}; + + Favourites._private() { + if (kFlutterMemoryAllocationsEnabled) ChangeNotifier.maybeDispatchObjectCreation(this); + } + + Future<void> init() async { + _rows = await localMediaDb.loadAllFavourites(); + } + + int get count => _rows.length; + + Set<int> get all => Set.unmodifiable(_rows.map((v) => v.entryId)); + + bool isFavourite(AvesEntry entry) => _rows.any((row) => row.entryId == entry.id); + + FavouriteRow _entryToRow(AvesEntry entry) => FavouriteRow(entryId: entry.id); + + Future<void> add(Set<AvesEntry> entries) async { + final newRows = entries.map(_entryToRow).toSet(); + + await localMediaDb.addFavourites(newRows); + _rows.addAll(newRows); + + notifyListeners(); + } + + Future<void> removeEntries(Set<AvesEntry> entries) => removeIds(entries.map((entry) => entry.id).toSet()); + + Future<void> removeIds(Set<int> entryIds) async { + final removedRows = _rows.where((row) => entryIds.contains(row.entryId)).toSet(); + + await localMediaDb.removeFavourites(removedRows); + removedRows.forEach(_rows.remove); + + notifyListeners(); + } + + Future<void> clear() async { + await localMediaDb.clearFavourites(); + _rows.clear(); + + notifyListeners(); + } + + // import/export + + Map<String, List<String>>? export(CollectionSource source) { + final visibleEntries = source.visibleEntries; + final ids = all; + final paths = visibleEntries.where((entry) => ids.contains(entry.id)).map((entry) => entry.path).nonNulls.toSet(); + final byVolume = groupBy<String, StorageVolume?>(paths, androidFileUtils.getStorageVolume); + final jsonMap = Map.fromEntries(byVolume.entries.map((kv) { + final volume = kv.key?.path; + if (volume == null) return null; + final rootLength = volume.length; + final relativePaths = kv.value.map((v) => v.substring(rootLength)).toList(); + return MapEntry(volume, relativePaths); + }).nonNulls); + return jsonMap.isNotEmpty ? jsonMap : null; + } + + void import(dynamic jsonMap, CollectionSource source) { + if (jsonMap is! Map) { + debugPrint('failed to import favourites for jsonMap=$jsonMap'); + return; + } + + final visibleEntries = source.visibleEntries; + final foundEntries = <AvesEntry>{}; + final missedPaths = <String>{}; + jsonMap.forEach((volume, relativePaths) { + if (volume is String && relativePaths is List) { + relativePaths.forEach((relativePath) { + final path = pContext.join(volume, relativePath); + final entry = visibleEntries.firstWhereOrNull((entry) => entry.path == path); + if (entry != null) { + foundEntries.add(entry); + } else { + missedPaths.add(path); + } + }); + } else { + debugPrint('failed to import favourites for volume=$volume, relativePaths=${relativePaths.runtimeType}'); + } + + if (foundEntries.isNotEmpty) { + add(foundEntries); + } + if (missedPaths.isNotEmpty) { + debugPrint('failed to import favourites with ${missedPaths.length} missed paths'); + } + }); + } +} + +@immutable +class FavouriteRow extends Equatable { + final int entryId; + + @override + List<Object?> get props => [entryId]; + + const FavouriteRow({ + required this.entryId, + }); + + factory FavouriteRow.fromMap(Map map) { + return FavouriteRow( + entryId: map['id'] as int, + ); + } + + Map<String, dynamic> toMap() => { + 'id': entryId, + }; +} diff --git a/lib/model/filters/aspect_ratio.dart b/lib/model/filters/aspect_ratio.dart new file mode 100644 index 0000000..c791464 --- /dev/null +++ b/lib/model/filters/aspect_ratio.dart @@ -0,0 +1,78 @@ +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/filters/query.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/widgets.dart'; + +class AspectRatioFilter extends CollectionFilter { + static const type = 'aspect_ratio'; + + final double threshold; + final String op; + late final EntryPredicate _test; + + static final landscape = AspectRatioFilter(1, QueryFilter.opGreater); + static final portrait = AspectRatioFilter(1, QueryFilter.opLower); + + @override + List<Object?> get props => [threshold, op, reversed]; + + AspectRatioFilter(this.threshold, this.op, {super.reversed = false}) { + switch (op) { + case QueryFilter.opEqual: + _test = (entry) => entry.displayAspectRatio == threshold; + case QueryFilter.opLower: + _test = (entry) => entry.displayAspectRatio < threshold; + case QueryFilter.opGreater: + _test = (entry) => entry.displayAspectRatio > threshold; + } + } + + factory AspectRatioFilter.fromMap(Map<String, dynamic> json) { + return AspectRatioFilter( + json['threshold'] as double, + json['op'] as String, + reversed: json['reversed'] ?? false, + ); + } + + @override + Map<String, dynamic> toMap() => { + 'type': type, + 'threshold': threshold, + 'op': op, + 'reversed': reversed, + }; + + @override + EntryPredicate get positiveTest => _test; + + @override + bool get exclusiveProp => true; + + @override + String get universalLabel => '$op $threshold'; + + @override + String getLabel(BuildContext context) { + final l10n = context.l10n; + if (threshold == 1) { + switch (op) { + case QueryFilter.opGreater: + return l10n.filterAspectRatioLandscapeLabel; + case QueryFilter.opLower: + return l10n.filterAspectRatioPortraitLabel; + } + } + return universalLabel; + } + + @override + Widget? iconBuilder(BuildContext context, double size, {bool allowGenericIcon = true}) => Icon(AIcons.aspectRatio, size: size); + + @override + String get category => type; + + @override + String get key => '$type-$reversed-$threshold-$op'; +} diff --git a/lib/model/filters/container/album_group.dart b/lib/model/filters/container/album_group.dart new file mode 100644 index 0000000..6f1e77d --- /dev/null +++ b/lib/model/filters/container/album_group.dart @@ -0,0 +1,42 @@ +import 'package:aves/model/filters/container/group_base.dart'; +import 'package:aves/model/filters/container/set_or.dart'; +import 'package:aves/model/filters/filters.dart'; + +mixin AlbumBaseFilter on CollectionFilter {} + +// placeholder to pick a group, distinguishing this root filter from cancelling +class _RootAlbumGroupFilter extends DummyCollectionFilter with AlbumBaseFilter { + _RootAlbumGroupFilter._private({required super.reversed}); +} + +class AlbumGroupFilter extends GroupBaseFilter with AlbumBaseFilter { + static const type = 'album_group'; + + static AlbumBaseFilter root = _RootAlbumGroupFilter._private(reversed: false); + + AlbumGroupFilter(super.uri, super.filter, {super.reversed = false}); + + factory AlbumGroupFilter.empty(Uri uri) => AlbumGroupFilter(uri, SetOrFilter(const {})); + + static AlbumGroupFilter? fromMap(Map<String, dynamic> json) { + final props = GroupBaseFilter.fromMap(json); + if (props == null) return null; + + final (uri, filter, reversed) = props; + return AlbumGroupFilter(uri, filter, reversed: reversed); + } + + @override + String get category => type; + + // container + + @override + AlbumGroupFilter? replaceFilters(CollectionFilter? Function(CollectionFilter oldFilter) toElement) { + return AlbumGroupFilter( + uri, + filter.replaceFilters(toElement), + reversed: reversed, + ); + } +} diff --git a/lib/model/filters/container/container.dart b/lib/model/filters/container/container.dart new file mode 100644 index 0000000..08f7901 --- /dev/null +++ b/lib/model/filters/container/container.dart @@ -0,0 +1,11 @@ +import 'package:aves/model/filters/filters.dart'; + +mixin ContainerFilter<T extends CollectionFilter> on CollectionFilter { + Set<CollectionFilter> get innerFilters; + + bool containsFilter(CollectionFilterPredicate test) { + return innerFilters.any(test) || innerFilters.whereType<ContainerFilter>().any((v) => v.containsFilter(test)); + } + + T? replaceFilters(CollectionFilter? Function(CollectionFilter oldFilter) toElement); +} diff --git a/lib/model/filters/container/dynamic_album.dart b/lib/model/filters/container/dynamic_album.dart new file mode 100644 index 0000000..b5fa5c3 --- /dev/null +++ b/lib/model/filters/container/dynamic_album.dart @@ -0,0 +1,77 @@ +import 'package:aves/model/filters/container/album_group.dart'; +import 'package:aves/model/filters/container/container.dart'; +import 'package:aves/model/filters/covered/covered.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:flutter/widgets.dart'; + +// a dynamic album can act as: +// - an alias, when inner filter is a simple filter, +// - a combination, when inner filter is a container. +class DynamicAlbumFilter extends CollectionFilter with ContainerFilter, CoveredFilter, AlbumBaseFilter { + static const type = 'dynamic_album'; + + final String name; + final CollectionFilter filter; + + @override + List<Object?> get props => [name, filter, reversed]; + + DynamicAlbumFilter(this.name, this.filter, {super.reversed = false}); + + static DynamicAlbumFilter? fromMap(Map<String, dynamic> json) { + final filter = CollectionFilter.fromJson(json['filter']); + if (filter == null) return null; + + return DynamicAlbumFilter( + json['name'], + filter, + reversed: json['reversed'] ?? false, + ); + } + + @override + Map<String, dynamic> toMap() => { + 'type': type, + 'name': name, + 'filter': filter.toJson(), + 'reversed': reversed, + }; + + @override + EntryPredicate get positiveTest => filter.test; + + @override + bool get exclusiveProp => false; + + @override + String get universalLabel => name; + + @override + Widget? iconBuilder(BuildContext context, double size, {bool allowGenericIcon = true}) { + return allowGenericIcon ? Icon(AIcons.dynamicAlbum, size: size) : null; + } + + @override + String get category => type; + + @override + String get key => '$type-$reversed-$name'; + + // container + + @override + Set<CollectionFilter> get innerFilters => {filter}; + + @override + DynamicAlbumFilter? replaceFilters(CollectionFilter? Function(CollectionFilter oldFilter) toElement) { + final newFilter = toElement(filter); + return newFilter != null + ? DynamicAlbumFilter( + name, + newFilter, + reversed: reversed, + ) + : null; + } +} diff --git a/lib/model/filters/container/group_base.dart b/lib/model/filters/container/group_base.dart new file mode 100644 index 0000000..18bf777 --- /dev/null +++ b/lib/model/filters/container/group_base.dart @@ -0,0 +1,66 @@ +import 'package:aves/model/filters/container/container.dart'; +import 'package:aves/model/filters/container/set_or.dart'; +import 'package:aves/model/filters/covered/covered.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/grouping/common.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:flutter/widgets.dart'; + +abstract class GroupBaseFilter extends CollectionFilter with ContainerFilter, CoveredFilter { + final Uri uri; + final SetOrFilter filter; + late final String _name; + + // do not include contextual `filter` to `props` + // stringify URI because its runtime type is undetermined and different types falsify equality checks + @override + List<Object?> get props => [uri.toString(), reversed]; + + GroupBaseFilter(this.uri, this.filter, {super.reversed = false}) { + _name = FilterGrouping.getGroupName(uri) ?? ''; + } + + @override + EntryPredicate get positiveTest => filter.test; + + @override + bool get exclusiveProp => false; + + @override + String get universalLabel => _name; + + @override + Widget? iconBuilder(BuildContext context, double size, {bool allowGenericIcon = true}) { + return allowGenericIcon ? Icon(AIcons.group, size: size) : null; + } + + @override + String get key => '$category-$reversed-$uri'; + + // container + + @override + Set<CollectionFilter> get innerFilters => {filter}; + + // serialization + + static (Uri, SetOrFilter, bool)? fromMap(Map<String, dynamic> json) { + final filter = CollectionFilter.fromJson(json['filter']); + if (filter == null || filter is! SetOrFilter) return null; + + final uriString = json['uri']; + final uri = uriString is String ? Uri.tryParse(uriString) : null; + if (uri == null) return null; + + final reversed = json['reversed'] ?? false; + return (uri, filter, reversed); + } + + @override + Map<String, dynamic> toMap() => { + 'type': category, + 'uri': uri.toString(), + 'filter': filter.toJson(), + 'reversed': reversed, + }; +} diff --git a/lib/model/filters/container/set_and.dart b/lib/model/filters/container/set_and.dart new file mode 100644 index 0000000..82b09fe --- /dev/null +++ b/lib/model/filters/container/set_and.dart @@ -0,0 +1,89 @@ +import 'package:aves/model/filters/container/container.dart'; +import 'package:aves/model/filters/covered/location.dart'; +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/widgets.dart'; + +// `AND` op for multiple filters +// can handle containing no filters +class SetAndFilter extends CollectionFilter with ContainerFilter { + static const type = 'and'; + + late final List<CollectionFilter> _filters; + + late final EntryPredicate _test; + late final IconData? _genericIcon; + + @override + List<Object?> get props => [_filters, reversed]; + + CollectionFilter? get _first => _filters.firstOrNull; + + SetAndFilter(Set<CollectionFilter> filters, {super.reversed = false}) { + _filters = filters.toList().sorted(); + _test = (entry) => _filters.every((v) => v.test(entry)); + switch (_first) { + case StoredAlbumFilter(): + _genericIcon = AIcons.album; + case LocationFilter(level: LocationLevel.country): + _genericIcon = AIcons.country; + case LocationFilter(level: LocationLevel.state): + _genericIcon = AIcons.state; + default: + _genericIcon = null; + } + } + + static SetAndFilter? fromMap(Map<String, dynamic> json) { + final filters = (json['filters'] as List).cast<String>().map(CollectionFilter.fromJson).nonNulls.toSet(); + return SetAndFilter( + filters, + reversed: json['reversed'] ?? false, + ); + } + + @override + Map<String, dynamic> toMap() => { + 'type': type, + 'filters': _filters.map((v) => v.toJson()).toList(), + 'reversed': reversed, + }; + + @override + EntryPredicate get positiveTest => _test; + + @override + bool get exclusiveProp => false; + + @override + String get universalLabel => _filters.map((v) => v.universalLabel).join(', '); + + @override + String getLabel(BuildContext context) => _filters.map((v) => v.getLabel(context)).join(', '); + + @override + Widget? iconBuilder(BuildContext context, double size, {bool allowGenericIcon = true}) { + return _genericIcon != null ? Icon(_genericIcon, size: size) : _first?.iconBuilder(context, size, allowGenericIcon: allowGenericIcon); + } + + @override + String get category => _first?.category ?? type; + + @override + String get key => '$type-$reversed-${_filters.map((v) => v.key)}'; + + // container + + @override + Set<CollectionFilter> get innerFilters => _filters.toSet(); + + @override + SetAndFilter replaceFilters(CollectionFilter? Function(CollectionFilter oldFilter) toElement) { + return SetAndFilter( + _filters.map((v) => toElement(v)).nonNulls.toSet(), + reversed: reversed, + ); + } +} diff --git a/lib/model/filters/container/set_or.dart b/lib/model/filters/container/set_or.dart new file mode 100644 index 0000000..27a271b --- /dev/null +++ b/lib/model/filters/container/set_or.dart @@ -0,0 +1,89 @@ +import 'package:aves/model/filters/container/container.dart'; +import 'package:aves/model/filters/covered/location.dart'; +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/widgets.dart'; + +// `OR` op for multiple filters +// can handle containing no filters +class SetOrFilter extends CollectionFilter with ContainerFilter { + static const type = 'or'; + + late final List<CollectionFilter> _filters; + + late final EntryPredicate _test; + late final IconData? _genericIcon; + + @override + List<Object?> get props => [_filters, reversed]; + + CollectionFilter? get _first => _filters.firstOrNull; + + SetOrFilter(Set<CollectionFilter> filters, {super.reversed = false}) { + _filters = filters.toList().sorted(); + _test = (entry) => _filters.any((v) => v.test(entry)); + switch (_first) { + case StoredAlbumFilter _: + _genericIcon = AIcons.album; + case LocationFilter(level: LocationLevel.country): + _genericIcon = AIcons.country; + case LocationFilter(level: LocationLevel.state): + _genericIcon = AIcons.state; + default: + _genericIcon = null; + } + } + + static SetOrFilter? fromMap(Map<String, dynamic> json) { + final filters = (json['filters'] as List).cast<String>().map(CollectionFilter.fromJson).nonNulls.toSet(); + return SetOrFilter( + filters, + reversed: json['reversed'] ?? false, + ); + } + + @override + Map<String, dynamic> toMap() => { + 'type': type, + 'filters': _filters.map((v) => v.toJson()).toList(), + 'reversed': reversed, + }; + + @override + EntryPredicate get positiveTest => _test; + + @override + bool get exclusiveProp => false; + + @override + String get universalLabel => _filters.map((v) => v.universalLabel).join(', '); + + @override + String getLabel(BuildContext context) => _filters.map((v) => v.getLabel(context)).join(', '); + + @override + Widget? iconBuilder(BuildContext context, double size, {bool allowGenericIcon = true}) { + return _genericIcon != null ? Icon(_genericIcon, size: size) : _first?.iconBuilder(context, size, allowGenericIcon: allowGenericIcon); + } + + @override + String get category => _first?.category ?? type; + + @override + String get key => '$type-$reversed-${_filters.map((v) => v.key)}'; + + // container + + @override + Set<CollectionFilter> get innerFilters => _filters.toSet(); + + @override + SetOrFilter replaceFilters(CollectionFilter? Function(CollectionFilter oldFilter) toElement) { + return SetOrFilter( + _filters.map((v) => toElement(v)).nonNulls.toSet(), + reversed: reversed, + ); + } +} diff --git a/lib/model/filters/container/tag_group.dart b/lib/model/filters/container/tag_group.dart new file mode 100644 index 0000000..76b1728 --- /dev/null +++ b/lib/model/filters/container/tag_group.dart @@ -0,0 +1,42 @@ +import 'package:aves/model/filters/container/group_base.dart'; +import 'package:aves/model/filters/container/set_or.dart'; +import 'package:aves/model/filters/filters.dart'; + +mixin TagBaseFilter on CollectionFilter {} + +// placeholder to pick a group, distinguishing this root filter from cancelling +class _RootTagGroupFilter extends DummyCollectionFilter with TagBaseFilter { + _RootTagGroupFilter._private({required super.reversed}); +} + +class TagGroupFilter extends GroupBaseFilter with TagBaseFilter { + static const type = 'tag_group'; + + static TagBaseFilter root = _RootTagGroupFilter._private(reversed: false); + + TagGroupFilter(super.uri, super.filter, {super.reversed = false}); + + factory TagGroupFilter.empty(Uri uri) => TagGroupFilter(uri, SetOrFilter(const {})); + + static TagGroupFilter? fromMap(Map<String, dynamic> json) { + final props = GroupBaseFilter.fromMap(json); + if (props == null) return null; + + final (uri, filter, reversed) = props; + return TagGroupFilter(uri, filter, reversed: reversed); + } + + @override + String get category => type; + + // container + + @override + TagGroupFilter? replaceFilters(CollectionFilter? Function(CollectionFilter oldFilter) toElement) { + return TagGroupFilter( + uri, + filter.replaceFilters(toElement), + reversed: reversed, + ); + } +} diff --git a/lib/model/filters/coordinate.dart b/lib/model/filters/coordinate.dart new file mode 100644 index 0000000..71edeec --- /dev/null +++ b/lib/model/filters/coordinate.dart @@ -0,0 +1,82 @@ +import 'package:aves/l10n/l10n.dart'; +import 'package:aves/model/entry/extensions/location.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/settings/enums/coordinate_format.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves_map/aves_map.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/widgets.dart'; +import 'package:latlong2/latlong.dart'; + +class CoordinateFilter extends CollectionFilter { + static const type = 'coordinate'; + + final LatLng sw; + final LatLng ne; + final bool minuteSecondPadding; + late final EntryPredicate _test; + + @override + List<Object?> get props => [sw, ne, reversed]; + + CoordinateFilter(this.sw, this.ne, {this.minuteSecondPadding = false, super.reversed = false}) { + _test = (entry) => GeoUtils.contains(sw, ne, entry.latLng); + } + + factory CoordinateFilter.fromMap(Map<String, dynamic> json) { + return CoordinateFilter( + LatLng.fromJson(json['sw']), + LatLng.fromJson(json['ne']), + reversed: json['reversed'] ?? false, + ); + } + + @override + Map<String, dynamic> toMap() => { + 'type': type, + 'sw': sw.toJson(), + 'ne': ne.toJson(), + 'reversed': reversed, + }; + + @override + EntryPredicate get positiveTest => _test; + + String _formatBounds(String Function(LatLng latLng) s) => '${s(ne)}\n${s(sw)}'; + + @override + bool get exclusiveProp => false; + + @override + String get universalLabel { + return _formatBounds((latLng) => CoordinateFormat.decimal.formatWithoutDirectionality( + lookupAppLocalizations(AppLocalizations.supportedLocales.first), + latLng, + minuteSecondPadding: minuteSecondPadding, + dmsSecondDecimals: 0, + )); + } + + @override + String getLabel(BuildContext context) { + return _formatBounds((latLng) { + final format = settings.coordinateFormat; + return format.format( + context, + latLng, + minuteSecondPadding: minuteSecondPadding, + dmsSecondDecimals: format == CoordinateFormat.ddm ? 2 : 0, + ); + }); + } + + @override + Widget? iconBuilder(BuildContext context, double size, {bool allowGenericIcon = true}) => Icon(AIcons.geoBounds, size: size); + + @override + String get category => type; + + @override + String get key => '$type-$reversed-$sw-$ne'; +} diff --git a/lib/model/filters/covered/covered.dart b/lib/model/filters/covered/covered.dart new file mode 100644 index 0000000..6e4b2c6 --- /dev/null +++ b/lib/model/filters/covered/covered.dart @@ -0,0 +1,16 @@ +import 'package:aves/model/covers.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; + +@immutable +mixin CoveredFilter on CollectionFilter { + @override + Future<Color> color(BuildContext context) { + final customColor = covers.of(this)?.$3; + if (customColor != null) { + return SynchronousFuture(customColor); + } + return super.color(context); + } +} diff --git a/lib/model/filters/covered/location.dart b/lib/model/filters/covered/location.dart new file mode 100644 index 0000000..4c5af65 --- /dev/null +++ b/lib/model/filters/covered/location.dart @@ -0,0 +1,134 @@ +import 'package:aves/model/device.dart'; +import 'package:aves/model/filters/covered/covered.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/utils/emoji_utils.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/widgets.dart'; + +class LocationFilter extends CollectionFilter with CoveredFilter { + static const type = 'location'; + static const locationSeparator = ';'; + + final LocationLevel level; + late final String _location; + late final String? _code; + late final EntryPredicate _test; + + static final unlocated = LocationFilter(LocationLevel.place, ''); + static final located = unlocated.reverse(); + + bool get _isUnlocated => _location.isEmpty; + + @override + List<Object?> get props => [level, _location, _code, reversed]; + + LocationFilter(this.level, String location, {super.reversed = false}) { + final split = location.split(locationSeparator); + _location = split.isNotEmpty ? split[0] : location; + _code = split.length > 1 ? split[1] : null; + + if (_isUnlocated) { + _test = (entry) => !entry.hasGps; + } else { + switch (level) { + case LocationLevel.country: + _test = (entry) => entry.addressDetails?.countryCode == _code; + case LocationLevel.state: + _test = (entry) => entry.addressDetails?.stateCode == _code; + case LocationLevel.place: + _test = (entry) => entry.addressDetails?.place == _location; + } + } + } + + factory LocationFilter.fromMap(Map<String, dynamic> json) { + return LocationFilter( + LocationLevel.values.firstWhereOrNull((v) => v.toString() == json['level']) ?? LocationLevel.place, + json['location'], + reversed: json['reversed'] ?? false, + ); + } + + @override + Map<String, dynamic> toMap() { + String location = _location; + switch (level) { + case LocationLevel.country: + case LocationLevel.state: + if (_code != null) { + location = _nameAndCode; + } + case LocationLevel.place: + break; + } + return { + 'type': type, + 'level': level.toString(), + 'location': location, + 'reversed': reversed, + }; + } + + String get _nameAndCode => '$_location$locationSeparator$_code'; + + String? get code => _code; + + String get place => _location; + + @override + EntryPredicate get positiveTest => _test; + + @override + bool get exclusiveProp => true; + + @override + String get universalLabel => _location; + + @override + String getLabel(BuildContext context) => _isUnlocated ? context.l10n.filterNoLocationLabel : _location; + + @override + Widget? iconBuilder(BuildContext context, double size, {bool allowGenericIcon = true}) { + if (_isUnlocated) { + return Icon(AIcons.locationUnlocated, size: size); + } + switch (level) { + case LocationLevel.country: + if (_code != null && device.canRenderFlagEmojis) { + final flag = EmojiUtils.countryCodeToFlag(_code); + if (flag != null) { + return Text( + flag, + style: TextStyle(fontSize: size), + textScaler: TextScaler.noScaling, + ); + } + } + return Icon(AIcons.country, size: size); + case LocationLevel.state: + if (_code != null && device.canRenderSubdivisionFlagEmojis) { + final flag = EmojiUtils.stateCodeToFlag(_code); + if (flag != null) { + return Text( + flag, + style: TextStyle(fontSize: size), + textScaler: TextScaler.noScaling, + ); + } + } + return Icon(AIcons.state, size: size); + case LocationLevel.place: + return Icon(AIcons.place, size: size); + } + } + + @override + String get category => type; + + @override + String get key => '$type-$reversed-$level-$code-$place'; +} + +enum LocationLevel { place, state, country } diff --git a/lib/model/filters/covered/stored_album.dart b/lib/model/filters/covered/stored_album.dart new file mode 100644 index 0000000..127bc4b --- /dev/null +++ b/lib/model/filters/covered/stored_album.dart @@ -0,0 +1,118 @@ +import 'package:aves/model/covers.dart'; +import 'package:aves/model/filters/container/album_group.dart'; +import 'package:aves/model/filters/covered/covered.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/vaults/vaults.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/utils/android_file_utils.dart'; +import 'package:aves/widgets/common/identity/aves_icons.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; +import 'package:provider/provider.dart'; + +class StoredAlbumFilter extends CollectionFilter with CoveredFilter, AlbumBaseFilter { + static const type = 'album'; + + final String album; + final String? displayName; + late final EntryPredicate _test; + + // do not include contextual `displayName` to `props` + @override + List<Object?> get props => [album, reversed]; + + StoredAlbumFilter(this.album, this.displayName, {super.reversed = false}) { + _test = (entry) => entry.directory == album; + } + + factory StoredAlbumFilter.fromMap(Map<String, dynamic> json) { + return StoredAlbumFilter( + json['album'], + json['uniqueName'], + reversed: json['reversed'] ?? false, + ); + } + + @override + Map<String, dynamic> toMap() => { + 'type': type, + 'album': album, + 'uniqueName': displayName, + 'reversed': reversed, + }; + + @override + EntryPredicate get positiveTest => _test; + + @override + bool get exclusiveProp => true; + + @override + String get universalLabel => displayName ?? pContext.split(album).last; + + @override + String getTooltip(BuildContext context) => isVault ? super.getTooltip(context) : album; + + @override + Widget? iconBuilder(BuildContext context, double size, {bool allowGenericIcon = true}) { + return IconUtils.getAlbumIcon( + context: context, + albumPath: album, + size: size, + ) ?? + (allowGenericIcon ? Icon(AIcons.album, size: size) : null); + } + + @override + Future<Color> color(BuildContext context) { + // custom color has precedence over others, even custom app color + final customColor = covers.of(this)?.$3; + if (customColor != null) return SynchronousFuture(customColor); + + final colors = context.read<AvesColorsData>(); + // do not use async/await and rely on `SynchronousFuture` + // to prevent rebuilding of the `FutureBuilder` listening on this future + final albumType = covers.effectiveAlbumType(album); + switch (albumType) { + case AlbumType.regular: + case AlbumType.vault: + break; + case AlbumType.app: + final appColor = colors.appColor(album); + if (appColor != null) return appColor; + case AlbumType.camera: + return SynchronousFuture(colors.albumCamera); + case AlbumType.download: + return SynchronousFuture(colors.albumDownload); + case AlbumType.screenRecordings: + return SynchronousFuture(colors.albumScreenRecordings); + case AlbumType.screenshots: + return SynchronousFuture(colors.albumScreenshots); + case AlbumType.videoCaptures: + return SynchronousFuture(colors.albumVideoCaptures); + } + return super.color(context); + } + + @override + String get category => type; + + // key is expected by test driver + @override + String get key => '$type-$reversed-$album'; + + StorageVolume? get storageVolume => androidFileUtils.getStorageVolume(album); + + bool get canRename { + if (isVault) return true; + + // do not allow renaming volume root + final dir = androidFileUtils.relativeDirectoryFromPath(album); + return dir != null && dir.relativeDir.isNotEmpty; + } + + bool get isVault => vaults.isVault(album); +} diff --git a/lib/model/filters/covered/tag.dart b/lib/model/filters/covered/tag.dart new file mode 100644 index 0000000..3ba9989 --- /dev/null +++ b/lib/model/filters/covered/tag.dart @@ -0,0 +1,61 @@ +import 'package:aves/model/filters/container/tag_group.dart'; +import 'package:aves/model/filters/covered/covered.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/widgets.dart'; + +class TagFilter extends CollectionFilter with CoveredFilter, TagBaseFilter { + static const type = 'tag'; + + final String tag; + late final EntryPredicate _test; + + @override + List<Object?> get props => [tag, reversed]; + + TagFilter(this.tag, {super.reversed = false}) { + if (tag.isEmpty) { + _test = (entry) => entry.tags.isEmpty; + } else { + _test = (entry) => entry.tags.contains(tag); + } + } + + factory TagFilter.fromMap(Map<String, dynamic> json) { + return TagFilter( + json['tag'], + reversed: json['reversed'] ?? false, + ); + } + + @override + Map<String, dynamic> toMap() => { + 'type': type, + 'tag': tag, + 'reversed': reversed, + }; + + @override + EntryPredicate get positiveTest => _test; + + @override + bool get exclusiveProp => false; + + @override + String get universalLabel => tag; + + @override + String getLabel(BuildContext context) => tag.isEmpty ? context.l10n.filterNoTagLabel : tag; + + @override + Widget? iconBuilder(BuildContext context, double size, {bool allowGenericIcon = true}) { + return allowGenericIcon ? Icon(tag.isEmpty ? AIcons.tagUntagged : AIcons.tag, size: size) : null; + } + + @override + String get category => type; + + @override + String get key => '$type-$reversed-$tag'; +} diff --git a/lib/model/filters/date.dart b/lib/model/filters/date.dart new file mode 100644 index 0000000..d01f184 --- /dev/null +++ b/lib/model/filters/date.dart @@ -0,0 +1,134 @@ +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/theme/format.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/utils/time_utils.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/widgets.dart'; +import 'package:intl/intl.dart'; + +class DateFilter extends CollectionFilter { + static const type = 'date'; + + final DateLevel level; + late final DateTime? date; + late final DateTime _effectiveDate; + late final EntryPredicate _test; + + static final onThisDay = DateFilter(DateLevel.md, null); + + @override + List<Object?> get props => [level, date, reversed]; + + DateFilter(this.level, this.date, {super.reversed = false}) { + _effectiveDate = date ?? DateTime.now(); + switch (level) { + case DateLevel.y: + _test = (entry) => entry.bestDate?.isAtSameYearAs(_effectiveDate) ?? false; + case DateLevel.ym: + _test = (entry) => entry.bestDate?.isAtSameMonthAs(_effectiveDate) ?? false; + case DateLevel.ymd: + _test = (entry) => entry.bestDate?.isAtSameDayAs(_effectiveDate) ?? false; + case DateLevel.md: + final month = _effectiveDate.month; + final day = _effectiveDate.day; + _test = (entry) { + final bestDate = entry.bestDate; + return bestDate != null && bestDate.month == month && bestDate.day == day; + }; + case DateLevel.m: + final month = _effectiveDate.month; + _test = (entry) => entry.bestDate?.month == month; + case DateLevel.d: + final day = _effectiveDate.day; + _test = (entry) => entry.bestDate?.day == day; + } + } + + factory DateFilter.fromMap(Map<String, dynamic> json) { + final dateString = json['date'] as String?; + return DateFilter( + DateLevel.values.firstWhereOrNull((v) => v.toString() == json['level']) ?? DateLevel.ymd, + dateString != null ? DateTime.tryParse(dateString) : null, + reversed: json['reversed'] ?? false, + ); + } + + @override + Map<String, dynamic> toMap() => { + 'type': type, + 'level': level.toString(), + 'date': date?.toIso8601String(), + 'reversed': reversed, + }; + + @override + EntryPredicate get positiveTest => _test; + + @override + bool get exclusiveProp => true; + + @override + bool isCompatible(CollectionFilter other) { + if (other is DateFilter) { + if (reversed != other.reversed && this == other.reverse()) return false; + return reversed || other.reversed || isCompatibleLevel(level, other.level); + } else { + return true; + } + } + + static bool isCompatibleLevel(DateLevel a, DateLevel b) { + switch (a) { + case DateLevel.y: + return {DateLevel.md, DateLevel.m, DateLevel.d}.contains(b); + case DateLevel.ym: + return DateLevel.d == b; + case DateLevel.ymd: + return false; + case DateLevel.md: + return DateLevel.y == b; + case DateLevel.m: + return {DateLevel.y, DateLevel.d}.contains(b); + case DateLevel.d: + return {DateLevel.y, DateLevel.ym, DateLevel.m}.contains(b); + } + } + + @override + String get universalLabel => _effectiveDate.toIso8601String(); + + @override + String getLabel(BuildContext context) { + final locale = context.locale; + switch (level) { + case DateLevel.y: + return DateFormat.y(locale).format(_effectiveDate); + case DateLevel.ym: + return DateFormat.yMMM(locale).format(_effectiveDate); + case DateLevel.ymd: + return formatDay(_effectiveDate, locale); + case DateLevel.md: + if (date != null) { + return DateFormat.MMMd(locale).format(_effectiveDate); + } else { + return context.l10n.filterOnThisDayLabel; + } + case DateLevel.m: + return DateFormat.MMMM(locale).format(_effectiveDate); + case DateLevel.d: + return DateFormat.d(locale).format(_effectiveDate); + } + } + + @override + Widget? iconBuilder(BuildContext context, double size, {bool allowGenericIcon = true}) => Icon(AIcons.date, size: size); + + @override + String get category => type; + + @override + String get key => '$type-$reversed-$level-$date'; +} + +enum DateLevel { y, ym, ymd, md, m, d } diff --git a/lib/model/filters/favourite.dart b/lib/model/filters/favourite.dart new file mode 100644 index 0000000..1538fdb --- /dev/null +++ b/lib/model/filters/favourite.dart @@ -0,0 +1,61 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/favourites.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; +import 'package:provider/provider.dart'; + +class FavouriteFilter extends CollectionFilter { + static const type = 'favourite'; + + static bool _test(AvesEntry entry) => entry.isFavourite; + + static const instance = FavouriteFilter._private(); + static const instanceReversed = FavouriteFilter._private(reversed: true); + + @override + List<Object?> get props => [reversed]; + + const FavouriteFilter._private({super.reversed = false}); + + factory FavouriteFilter.fromMap(Map<String, dynamic> json) { + final reversed = json['reversed'] ?? false; + return reversed ? instanceReversed : instance; + } + + @override + Map<String, dynamic> toMap() => { + 'type': type, + 'reversed': reversed, + }; + + @override + EntryPredicate get positiveTest => _test; + + @override + bool get exclusiveProp => false; + + @override + String get universalLabel => type; + + @override + String getLabel(BuildContext context) => context.l10n.filterFavouriteLabel; + + @override + Widget? iconBuilder(BuildContext context, double size, {bool allowGenericIcon = true}) => Icon(AIcons.favourite, size: size); + + @override + Future<Color> color(BuildContext context) { + final colors = context.read<AvesColorsData>(); + return SynchronousFuture(colors.favourite); + } + + @override + String get category => type; + + @override + String get key => '$type-$reversed'; +} diff --git a/lib/model/filters/filters.dart b/lib/model/filters/filters.dart new file mode 100644 index 0000000..0ebabaa --- /dev/null +++ b/lib/model/filters/filters.dart @@ -0,0 +1,218 @@ +import 'dart:convert'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/filters/aspect_ratio.dart'; +import 'package:aves/model/filters/container/album_group.dart'; +import 'package:aves/model/filters/container/dynamic_album.dart'; +import 'package:aves/model/filters/container/set_and.dart'; +import 'package:aves/model/filters/container/set_or.dart'; +import 'package:aves/model/filters/container/tag_group.dart'; +import 'package:aves/model/filters/coordinate.dart'; +import 'package:aves/model/filters/covered/location.dart'; +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/filters/covered/tag.dart'; +import 'package:aves/model/filters/date.dart'; +import 'package:aves/model/filters/favourite.dart'; +import 'package:aves/model/filters/mime.dart'; +import 'package:aves/model/filters/missing.dart'; +import 'package:aves/model/filters/path.dart'; +import 'package:aves/model/filters/placeholder.dart'; +import 'package:aves/model/filters/query.dart'; +import 'package:aves/model/filters/rating.dart'; +import 'package:aves/model/filters/recent.dart'; +import 'package:aves/model/filters/trash.dart'; +import 'package:aves/model/filters/type.dart'; +import 'package:aves/model/filters/weekday.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:collection/collection.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; +import 'package:provider/provider.dart'; + +@immutable +abstract class CollectionFilter extends Equatable implements Comparable<CollectionFilter> { + static const List<String> categoryOrder = [ + TrashFilter.type, + QueryFilter.type, + SetAndFilter.type, + SetOrFilter.type, + MimeFilter.type, + AlbumGroupFilter.type, + TagGroupFilter.type, + DynamicAlbumFilter.type, + StoredAlbumFilter.type, + TypeFilter.type, + RecentlyAddedFilter.type, + DateFilter.type, + WeekDayFilter.type, + LocationFilter.type, + CoordinateFilter.type, + FavouriteFilter.type, + RatingFilter.type, + TagFilter.type, + AspectRatioFilter.type, + MissingFilter.type, + PathFilter.type, + ]; + + final bool reversed; + + const CollectionFilter({required this.reversed}); + + static CollectionFilter? _fromMap(Map<String, dynamic> jsonMap) { + final type = jsonMap['type']; + switch (type) { + case AlbumGroupFilter.type: + return AlbumGroupFilter.fromMap(jsonMap); + case TagGroupFilter.type: + return TagGroupFilter.fromMap(jsonMap); + case AspectRatioFilter.type: + return AspectRatioFilter.fromMap(jsonMap); + case CoordinateFilter.type: + return CoordinateFilter.fromMap(jsonMap); + case DateFilter.type: + return DateFilter.fromMap(jsonMap); + case DynamicAlbumFilter.type: + return DynamicAlbumFilter.fromMap(jsonMap); + case FavouriteFilter.type: + return FavouriteFilter.fromMap(jsonMap); + case LocationFilter.type: + return LocationFilter.fromMap(jsonMap); + case MimeFilter.type: + return MimeFilter.fromMap(jsonMap); + case MissingFilter.type: + return MissingFilter.fromMap(jsonMap); + case SetAndFilter.type: + return SetAndFilter.fromMap(jsonMap); + case SetOrFilter.type: + return SetOrFilter.fromMap(jsonMap); + case PathFilter.type: + return PathFilter.fromMap(jsonMap); + case PlaceholderFilter.type: + return PlaceholderFilter.fromMap(jsonMap); + case QueryFilter.type: + return QueryFilter.fromMap(jsonMap); + case RatingFilter.type: + return RatingFilter.fromMap(jsonMap); + case RecentlyAddedFilter.type: + return RecentlyAddedFilter.fromMap(jsonMap); + case StoredAlbumFilter.type: + return StoredAlbumFilter.fromMap(jsonMap); + case TagFilter.type: + return TagFilter.fromMap(jsonMap); + case TypeFilter.type: + return TypeFilter.fromMap(jsonMap); + case TrashFilter.type: + return TrashFilter.fromMap(jsonMap); + case WeekDayFilter.type: + return WeekDayFilter.fromMap(jsonMap); + } + debugPrint('failed to deserialize filter from JSON map=$jsonMap'); + return null; + } + + static CollectionFilter? fromJson(String? jsonString) { + if (jsonString == null || jsonString.isEmpty) return null; + + try { + final jsonMap = jsonDecode(jsonString); + if (jsonMap is Map<String, dynamic>) { + return _fromMap(jsonMap); + } + debugPrint('failed to parse filter from json=$jsonString'); + } catch (error) { + // no need for stack + debugPrint('failed to parse filter from json=$jsonString error=$error'); + } + return null; + } + + Map<String, dynamic> toMap(); + + String toJson() => jsonEncode(toMap()); + + EntryPredicate get positiveTest; + + EntryPredicate get test => reversed ? (v) => !positiveTest(v) : positiveTest; + + CollectionFilter reverse() => _fromMap(toMap()..['reversed'] = !reversed)!; + + bool get exclusiveProp; + + bool isCompatible(CollectionFilter other) { + if (category != other.category) return true; + if (!reversed && !other.reversed) return !exclusiveProp; + if (reversed && other.reversed) return true; + if (this == other.reverse()) return false; + return true; + } + + String get universalLabel; + + String getLabel(BuildContext context) => universalLabel; + + String getTooltip(BuildContext context) => getLabel(context); + + bool matchLabel(BuildContext context, String query) => getLabel(context).toUpperCase().contains(query); + + Widget? iconBuilder(BuildContext context, double size, {bool allowGenericIcon = true}) => null; + + Future<Color> color(BuildContext context) { + final colors = context.read<AvesColorsData>(); + return SynchronousFuture(colors.fromString(getLabel(context))); + } + + String get category; + + // to be used as widget key + String get key; + + int get displayPriority => categoryOrder.indexOf(category); + + @override + int compareTo(CollectionFilter other) { + final c = displayPriority.compareTo(other.displayPriority); + // assume we compare context-independent labels + return c != 0 ? c : compareAsciiUpperCaseNatural(universalLabel, other.universalLabel); + } +} + +@immutable +class FilterGridItem<T extends CollectionFilter> with EquatableMixin { + final T filter; + final AvesEntry? entry; + + @override + List<Object?> get props => [filter, entry?.uri]; + + const FilterGridItem(this.filter, this.entry); +} + +typedef EntryPredicate = bool Function(AvesEntry entry); +typedef CollectionFilterPredicate = bool Function(CollectionFilter filter); + +abstract class DummyCollectionFilter extends CollectionFilter { + const DummyCollectionFilter({required super.reversed}); + + @override + String get category => throw UnimplementedError(); + + @override + bool get exclusiveProp => throw UnimplementedError(); + + @override + String get key => throw UnimplementedError(); + + @override + EntryPredicate get positiveTest => throw UnimplementedError(); + + @override + List<Object?> get props => throw UnimplementedError(); + + @override + Map<String, dynamic> toMap() => throw UnimplementedError(); + + @override + String get universalLabel => throw UnimplementedError(); +} diff --git a/lib/model/filters/mime.dart b/lib/model/filters/mime.dart new file mode 100644 index 0000000..e96e6ab --- /dev/null +++ b/lib/model/filters/mime.dart @@ -0,0 +1,105 @@ +import 'dart:async'; + +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/ref/mime_types.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/utils/mime_utils.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; +import 'package:provider/provider.dart'; + +class MimeFilter extends CollectionFilter { + static const type = 'mime'; + + final String mime; + late final String _label; + late final IconData _icon; + late final EntryPredicate _test; + + static final image = MimeFilter(MimeTypes.anyImage); + static final video = MimeFilter(MimeTypes.anyVideo); + + @override + List<Object?> get props => [mime, reversed]; + + MimeFilter(this.mime, {super.reversed = false}) { + IconData? icon; + var lowMime = mime.toLowerCase(); + if (lowMime.endsWith('/*')) { + lowMime = lowMime.substring(0, lowMime.length - 2); + _test = (entry) => entry.mimeType.startsWith(lowMime); + _label = lowMime.toUpperCase(); + if (mime == MimeTypes.anyImage) { + icon = AIcons.image; + } else if (mime == MimeTypes.anyVideo) { + icon = AIcons.video; + } + } else { + _test = (entry) => entry.mimeType == lowMime; + _label = MimeUtils.displayType(lowMime); + } + _icon = icon ?? AIcons.vector; + } + + factory MimeFilter.fromMap(Map<String, dynamic> json) { + return MimeFilter( + json['mime'], + reversed: json['reversed'] ?? false, + ); + } + + @override + Map<String, dynamic> toMap() => { + 'type': type, + 'mime': mime, + 'reversed': reversed, + }; + + @override + EntryPredicate get positiveTest => _test; + + @override + bool get exclusiveProp => true; + + @override + String get universalLabel => _label; + + @override + String getLabel(BuildContext context) { + final l10n = context.l10n; + return switch (mime) { + MimeTypes.anyImage => l10n.filterMimeImageLabel, + MimeTypes.anyVideo => l10n.filterMimeVideoLabel, + _ => _label, + }; + } + + @override + String getTooltip(BuildContext context) { + return '${getLabel(context)} ($mime)'; + } + + @override + Widget? iconBuilder(BuildContext context, double size, {bool allowGenericIcon = true}) => Icon(_icon, size: size); + + @override + Future<Color> color(BuildContext context) { + final colors = context.read<AvesColorsData>(); + switch (mime) { + case MimeTypes.anyImage: + return SynchronousFuture(colors.image); + case MimeTypes.anyVideo: + return SynchronousFuture(colors.video); + default: + return SynchronousFuture(colors.fromString(_label)); + } + } + + @override + String get category => type; + + @override + String get key => '$type-$reversed-$mime'; +} diff --git a/lib/model/filters/missing.dart b/lib/model/filters/missing.dart new file mode 100644 index 0000000..6866435 --- /dev/null +++ b/lib/model/filters/missing.dart @@ -0,0 +1,80 @@ +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/widgets.dart'; + +class MissingFilter extends CollectionFilter { + static const type = 'missing'; + + static const _date = 'date'; + static const _fineAddress = 'fine_address'; + static const _title = 'title'; + + final String metadataType; + late final IconData _icon; + late final EntryPredicate _test; + + static final date = MissingFilter._private(_date); + static final fineAddress = MissingFilter._private(_fineAddress); + static final title = MissingFilter._private(_title); + + @override + List<Object?> get props => [metadataType, reversed]; + + MissingFilter._private(this.metadataType, {super.reversed = false}) { + switch (metadataType) { + case _date: + _test = (entry) => (entry.catalogMetadata?.dateMillis ?? 0) == 0; + _icon = AIcons.dateUndated; + case _fineAddress: + _test = (entry) => entry.hasGps && !entry.hasFineAddress; + _icon = AIcons.locationUnlocated; + case _title: + _test = (entry) => (entry.catalogMetadata?.xmpTitle ?? '').isEmpty; + _icon = AIcons.descriptionUntitled; + } + } + + factory MissingFilter.fromMap(Map<String, dynamic> json) { + return MissingFilter._private( + json['metadataType'], + reversed: json['reversed'] ?? false, + ); + } + + @override + Map<String, dynamic> toMap() => { + 'type': type, + 'metadataType': metadataType, + 'reversed': reversed, + }; + + @override + EntryPredicate get positiveTest => _test; + + @override + bool get exclusiveProp => false; + + @override + String get universalLabel => metadataType; + + @override + String getLabel(BuildContext context) { + final l10n = context.l10n; + return switch (metadataType) { + _date => l10n.filterNoDateLabel, + _fineAddress => l10n.filterNoAddressLabel, + _title => l10n.filterNoTitleLabel, + _ => metadataType, + }; + } + + @override + Widget? iconBuilder(BuildContext context, double size, {bool allowGenericIcon = true}) => Icon(_icon, size: size); + + @override + String get category => type; + + @override + String get key => '$type-$reversed-$metadataType'; +} diff --git a/lib/model/filters/path.dart b/lib/model/filters/path.dart new file mode 100644 index 0000000..7cee212 --- /dev/null +++ b/lib/model/filters/path.dart @@ -0,0 +1,74 @@ +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/utils/android_file_utils.dart'; +import 'package:aves/view/view.dart'; +import 'package:flutter/widgets.dart'; + +class PathFilter extends CollectionFilter { + static const type = 'path'; + + // including trailing separator + late final String path; + + // without trailing separator + late final String _rootAlbum; + + late final EntryPredicate _test; + + @override + List<Object?> get props => [path, reversed]; + + PathFilter(String path, {super.reversed = false}) { + this.path = path.endsWith(pContext.separator) ? path : '$path${pContext.separator}'; + _rootAlbum = this.path.substring(0, this.path.length - 1); + _test = (entry) { + final dir = entry.directory; + if (dir == null) return false; + // avoid string building in most cases + return dir.startsWith(_rootAlbum) && '$dir${pContext.separator}'.startsWith(this.path); + }; + } + + factory PathFilter.fromMap(Map<String, dynamic> json) { + return PathFilter( + json['path'], + reversed: json['reversed'] ?? false, + ); + } + + @override + Map<String, dynamic> toMap() => { + 'type': type, + 'path': path, + 'reversed': reversed, + }; + + @override + EntryPredicate get positiveTest => _test; + + @override + bool get exclusiveProp => true; + + @override + String get universalLabel => path; + + @override + String getLabel(BuildContext context) { + final _directory = androidFileUtils.relativeDirectoryFromPath(path); + if (_directory == null) return universalLabel; + if (_directory.relativeDir.isEmpty) { + return _directory.getVolumeDescription(context); + } + return pContext.split(_directory.relativeDir).last; + } + + @override + Widget? iconBuilder(BuildContext context, double size, {bool allowGenericIcon = true}) => Icon(AIcons.path, size: size); + + @override + String get category => type; + + @override + String get key => '$type-$reversed-$path'; +} diff --git a/lib/model/filters/placeholder.dart b/lib/model/filters/placeholder.dart new file mode 100644 index 0000000..b217a59 --- /dev/null +++ b/lib/model/filters/placeholder.dart @@ -0,0 +1,106 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/catalog.dart'; +import 'package:aves/model/entry/extensions/location.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/widgets.dart'; + +class PlaceholderFilter extends CollectionFilter { + static const type = 'placeholder'; + + static const _country = 'country'; + static const _state = 'state'; + static const _place = 'place'; + + final String placeholder; + late final IconData _icon; + + static final country = PlaceholderFilter._private(_country); + static final state = PlaceholderFilter._private(_state); + static final place = PlaceholderFilter._private(_place); + + @override + List<Object?> get props => [placeholder]; + + PlaceholderFilter._private(this.placeholder) : super(reversed: false) { + switch (placeholder) { + case _country: + _icon = AIcons.country; + case _state: + _icon = AIcons.state; + case _place: + _icon = AIcons.place; + } + } + + factory PlaceholderFilter.fromMap(Map<String, dynamic> json) { + return PlaceholderFilter._private( + json['placeholder'], + ); + } + + @override + Map<String, dynamic> toMap() => { + 'type': type, + 'placeholder': placeholder, + }; + + Future<String?> toTag(AvesEntry entry) async { + switch (placeholder) { + case _country: + case _state: + case _place: + if (!entry.isCatalogued) { + await entry.catalog(background: false, force: false, persist: true); + } + if (!entry.hasGps) return null; + + if (!entry.hasFineAddress) { + await entry.locate(background: false, force: false, geocoderLocale: settings.appliedLocale); + } + final address = entry.addressDetails; + if (address == null) return null; + + switch (placeholder) { + case _country: + return address.countryName; + case _state: + return address.stateName; + case _place: + return address.place; + } + } + return null; + } + + @override + EntryPredicate get positiveTest => (entry) => throw Exception('this is not a test'); + + @override + bool get exclusiveProp => false; + + @override + String get universalLabel => placeholder; + + @override + String getLabel(BuildContext context) { + final l10n = context.l10n; + return switch (placeholder) { + _country => l10n.tagPlaceholderCountry, + _state => l10n.tagPlaceholderState, + _place => l10n.tagPlaceholderPlace, + _ => placeholder, + }; + } + + @override + Widget? iconBuilder(BuildContext context, double size, {bool allowGenericIcon = true}) => Icon(_icon, size: size); + + @override + String get category => type; + + @override + String get key => '$type-$reversed-$placeholder'; +} diff --git a/lib/model/filters/query.dart b/lib/model/filters/query.dart new file mode 100644 index 0000000..80e8d78 --- /dev/null +++ b/lib/model/filters/query.dart @@ -0,0 +1,208 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/utils/file_utils.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; +import 'package:provider/provider.dart'; + +class QueryFilter extends CollectionFilter { + static const type = 'query'; + + static final exactRegex = RegExp('^"(.*)"\$'); + + final String query; + final bool colorful, live; + late final EntryPredicate _test; + + @override + List<Object?> get props => [query, live, reversed]; + + static final _fieldPattern = RegExp(r'(.+)([=<>])(.+)'); + static final _fileSizePattern = RegExp(r'(\d+)([KMG])?'); + static const keyContentExtension = 'EXT'; + static const keyContentId = 'ID'; + static const keyContentYear = 'YEAR'; + static const keyContentMonth = 'MONTH'; + static const keyContentDay = 'DAY'; + static const keyContentWidth = 'WIDTH'; + static const keyContentHeight = 'HEIGHT'; + static const keyContentSize = 'SIZE'; + static const opEqual = '='; + static const opLower = '<'; + static const opGreater = '>'; + + QueryFilter(this.query, {this.colorful = true, this.live = false, super.reversed = false}) { + var upQuery = query.toUpperCase(); + + final test = fieldTest(upQuery); + if (test != null) { + _test = test; + return; + } + + // allow NOT queries starting with `-` + final not = upQuery.startsWith('-'); + if (not) { + upQuery = upQuery.substring(1); + } + + // allow untrimmed queries wrapped with `"..."` + final matches = exactRegex.allMatches(upQuery); + if (matches.length == 1) { + upQuery = matches.first.group(1)!; + } + + // default to title search + bool testTitle(AvesEntry entry) => entry.bestTitle?.toUpperCase().contains(upQuery) == true; + _test = not ? (entry) => !testTitle(entry) : testTitle; + } + + factory QueryFilter.fromMap(Map<String, dynamic> json) { + return QueryFilter( + json['query'], + reversed: json['reversed'] ?? false, + ); + } + + @override + Map<String, dynamic> toMap() => { + 'type': type, + 'query': query, + 'reversed': reversed, + }; + + @override + EntryPredicate get positiveTest => _test; + + @override + bool get exclusiveProp => false; + + @override + String get universalLabel => query; + + @override + Widget? iconBuilder(BuildContext context, double size, {bool allowGenericIcon = true}) => Icon(AIcons.text, fill: 1, size: size); + + @override + Future<Color> color(BuildContext context) { + if (colorful) { + return super.color(context); + } + + final colors = context.read<AvesColorsData>(); + return SynchronousFuture(colors.neutral); + } + + @override + String get category => type; + + @override + String get key => '$type-$reversed-$query'; + + EntryPredicate? fieldTest(String upQuery) { + var match = _fieldPattern.firstMatch(upQuery); + if (match == null) return null; + + final key = match.group(1)?.trim(); + final op = match.group(2)?.trim(); + var valueString = match.group(3)?.trim(); + if (key == null || op == null || valueString == null) return null; + + final valueInt = int.tryParse(valueString); + + switch (key) { + case keyContentExtension: + if (op == opEqual) { + final extension = '.$valueString'; + return (entry) => entry.extension?.toUpperCase() == extension; + } + case keyContentId: + if (valueInt == null) return null; + if (op == opEqual) { + return (entry) => entry.contentId == valueInt; + } + case keyContentYear: + if (valueInt == null) return null; + switch (op) { + case opEqual: + return (entry) => (entry.bestDate?.year ?? 0) == valueInt; + case opLower: + return (entry) => (entry.bestDate?.year ?? 0) < valueInt; + case opGreater: + return (entry) => (entry.bestDate?.year ?? 0) > valueInt; + } + case keyContentMonth: + if (valueInt == null) return null; + switch (op) { + case opEqual: + return (entry) => (entry.bestDate?.month ?? 0) == valueInt; + case opLower: + return (entry) => (entry.bestDate?.month ?? 0) < valueInt; + case opGreater: + return (entry) => (entry.bestDate?.month ?? 0) > valueInt; + } + case keyContentDay: + if (valueInt == null) return null; + switch (op) { + case opEqual: + return (entry) => (entry.bestDate?.day ?? 0) == valueInt; + case opLower: + return (entry) => (entry.bestDate?.day ?? 0) < valueInt; + case opGreater: + return (entry) => (entry.bestDate?.day ?? 0) > valueInt; + } + case keyContentWidth: + if (valueInt == null) return null; + switch (op) { + case opEqual: + return (entry) => entry.displaySize.width == valueInt; + case opLower: + return (entry) => entry.displaySize.width < valueInt; + case opGreater: + return (entry) => entry.displaySize.width > valueInt; + } + case keyContentHeight: + if (valueInt == null) return null; + switch (op) { + case opEqual: + return (entry) => entry.displaySize.height == valueInt; + case opLower: + return (entry) => entry.displaySize.height < valueInt; + case opGreater: + return (entry) => entry.displaySize.height > valueInt; + } + case keyContentSize: + match = _fileSizePattern.firstMatch(valueString); + if (match == null) return null; + + valueString = match.group(1)?.trim(); + if (valueString == null) return null; + final valueInt = int.tryParse(valueString); + if (valueInt == null) return null; + + var bytes = valueInt; + final multiplierString = match.group(2)?.trim(); + switch (multiplierString) { + case 'K': + bytes *= kilo; + case 'M': + bytes *= mega; + case 'G': + bytes *= giga; + } + + switch (op) { + case opEqual: + return (entry) => (entry.sizeBytes ?? 0) == bytes; + case opLower: + return (entry) => (entry.sizeBytes ?? 0) < bytes; + case opGreater: + return (entry) => (entry.sizeBytes ?? 0) > bytes; + } + } + + return null; + } +} diff --git a/lib/model/filters/rating.dart b/lib/model/filters/rating.dart new file mode 100644 index 0000000..b907442 --- /dev/null +++ b/lib/model/filters/rating.dart @@ -0,0 +1,96 @@ +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/ref/unicode.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/widgets.dart'; + +class RatingFilter extends CollectionFilter { + static const type = 'rating'; + + final int rating; + final String op; + late final EntryPredicate _test; + + static const opEqual = '='; + static const opOrLower = '<='; + static const opOrGreater = '>='; + + @override + List<Object?> get props => [rating, op, reversed]; + + RatingFilter(this.rating, {this.op = opEqual, super.reversed = false}) { + _test = switch (op) { + opOrLower => (entry) => entry.rating <= rating && entry.rating > 0, + opOrGreater => (entry) => entry.rating >= rating, + opEqual || _ => (entry) => entry.rating == rating, + }; + } + + RatingFilter copyWith(String op) => RatingFilter( + rating, + op: op, + reversed: reversed, + ); + + factory RatingFilter.fromMap(Map<String, dynamic> json) { + return RatingFilter( + json['rating'] ?? 0, + op: json['op'] ?? opEqual, + reversed: json['reversed'] ?? false, + ); + } + + @override + Map<String, dynamic> toMap() => { + 'type': type, + 'rating': rating, + 'op': op, + 'reversed': reversed, + }; + + @override + EntryPredicate get positiveTest => _test; + + @override + bool get exclusiveProp => true; + + @override + String get universalLabel => '$op $rating'; + + @override + String getLabel(BuildContext context) => switch (op) { + opOrLower || opOrGreater => '${UniChars.whiteMediumStar} ${formatRatingRange(context, rating, op)}', + opEqual || _ => formatRating(context, rating), + }; + + @override + Widget? iconBuilder(BuildContext context, double size, {bool allowGenericIcon = true}) { + return switch (rating) { + -1 => Icon(AIcons.ratingRejected, size: size), + 0 => Icon(AIcons.ratingUnrated, size: size), + _ => null, + }; + } + + @override + String get category => type; + + @override + String get key => '$type-$reversed-$rating-$op'; + + static String formatRating(BuildContext context, int rating) { + return switch (rating) { + -1 => context.l10n.filterRatingRejectedLabel, + 0 => context.l10n.filterNoRatingLabel, + _ => UniChars.whiteMediumStar * rating, + }; + } + + static String formatRatingRange(BuildContext context, int rating, String op) { + return switch (op) { + opOrLower => '1~$rating', + opOrGreater => '$rating~5', + opEqual || _ => '$rating', + }; + } +} diff --git a/lib/model/filters/recent.dart b/lib/model/filters/recent.dart new file mode 100644 index 0000000..d39a08b --- /dev/null +++ b/lib/model/filters/recent.dart @@ -0,0 +1,61 @@ +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/widgets.dart'; + +class RecentlyAddedFilter extends CollectionFilter { + static const type = 'recently_added'; + + static late EntryPredicate _test; + + static final instance = RecentlyAddedFilter._private(); + static final instanceReversed = RecentlyAddedFilter._private(reversed: true); + + static late int nowSecs; + + static void updateNow() { + nowSecs = DateTime.now().millisecondsSinceEpoch ~/ 1000; + _test = (entry) => (nowSecs - (entry.dateAddedSecs ?? 0)) < _dayInSecs; + } + + static const _dayInSecs = 24 * 60 * 60; + + @override + List<Object?> get props => [reversed]; + + RecentlyAddedFilter._private({super.reversed = false}) { + updateNow(); + } + + factory RecentlyAddedFilter.fromMap(Map<String, dynamic> json) { + final reversed = json['reversed'] ?? false; + return reversed ? instanceReversed : instance; + } + + @override + Map<String, dynamic> toMap() => { + 'type': type, + 'reversed': reversed, + }; + + @override + EntryPredicate get positiveTest => _test; + + @override + bool get exclusiveProp => false; + + @override + String get universalLabel => type; + + @override + String getLabel(BuildContext context) => context.l10n.filterRecentlyAddedLabel; + + @override + Widget? iconBuilder(BuildContext context, double size, {bool allowGenericIcon = true}) => Icon(AIcons.dateRecent, size: size); + + @override + String get category => type; + + @override + String get key => '$type-$reversed'; +} diff --git a/lib/model/filters/trash.dart b/lib/model/filters/trash.dart new file mode 100644 index 0000000..f250bfa --- /dev/null +++ b/lib/model/filters/trash.dart @@ -0,0 +1,51 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/widgets.dart'; + +class TrashFilter extends CollectionFilter { + static const type = 'trash'; + + static bool _test(AvesEntry entry) => entry.trashed; + + static const instance = TrashFilter._private(); + static const instanceReversed = TrashFilter._private(reversed: true); + + @override + List<Object?> get props => [reversed]; + + const TrashFilter._private({super.reversed = false}); + + factory TrashFilter.fromMap(Map<String, dynamic> json) { + final reversed = json['reversed'] ?? false; + return reversed ? instanceReversed : instance; + } + + @override + Map<String, dynamic> toMap() => { + 'type': type, + 'reversed': reversed, + }; + + @override + EntryPredicate get positiveTest => _test; + + @override + bool get exclusiveProp => false; + + @override + String get universalLabel => type; + + @override + String getLabel(BuildContext context) => context.l10n.filterBinLabel; + + @override + Widget? iconBuilder(BuildContext context, double size, {bool allowGenericIcon = true}) => Icon(AIcons.bin, size: size); + + @override + String get category => type; + + @override + String get key => '$type-$reversed'; +} diff --git a/lib/model/filters/type.dart b/lib/model/filters/type.dart new file mode 100644 index 0000000..9d1e747 --- /dev/null +++ b/lib/model/filters/type.dart @@ -0,0 +1,129 @@ +import 'package:aves/model/entry/extensions/multipage.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; +import 'package:provider/provider.dart'; + +class TypeFilter extends CollectionFilter { + static const type = 'type'; + + static const _animated = 'animated'; // subset of `image/gif` and `image/webp` + static const _geotiff = 'geotiff'; // subset of `image/tiff` + static const _hdr = 'hdr'; // subset of `image/jpeg` + static const _motionPhoto = 'motion_photo'; // subset of images (jpeg, heic) + static const _panorama = 'panorama'; // subset of images + static const _raw = 'raw'; // specific image formats + static const _sphericalVideo = 'spherical_video'; // subset of videos + + final String itemType; + late final IconData _icon; + late final EntryPredicate _test; + + static final animated = TypeFilter._private(_animated); + static final geotiff = TypeFilter._private(_geotiff); + static final hdr = TypeFilter._private(_hdr); + static final motionPhoto = TypeFilter._private(_motionPhoto); + static final panorama = TypeFilter._private(_panorama); + static final raw = TypeFilter._private(_raw); + static final sphericalVideo = TypeFilter._private(_sphericalVideo); + + @override + List<Object?> get props => [itemType, reversed]; + + TypeFilter._private(this.itemType, {super.reversed = false}) { + switch (itemType) { + case _animated: + _test = (entry) => entry.isAnimated; + _icon = AIcons.animated; + case _geotiff: + _test = (entry) => entry.isGeotiff; + _icon = AIcons.geo; + case _hdr: + _test = (entry) => entry.isHdr; + _icon = AIcons.hdr; + case _motionPhoto: + _test = (entry) => entry.isMotionPhoto; + _icon = AIcons.motionPhoto; + case _panorama: + _test = (entry) => entry.isImage && entry.is360; + _icon = AIcons.panorama; + case _raw: + _test = (entry) => entry.isRaw; + _icon = AIcons.raw; + case _sphericalVideo: + _test = (entry) => entry.isVideo && entry.is360; + _icon = AIcons.sphericalVideo; + } + } + + factory TypeFilter.fromMap(Map<String, dynamic> json) { + return TypeFilter._private( + json['itemType'], + reversed: json['reversed'] ?? false, + ); + } + + @override + Map<String, dynamic> toMap() => { + 'type': type, + 'itemType': itemType, + 'reversed': reversed, + }; + + @override + EntryPredicate get positiveTest => _test; + + @override + bool get exclusiveProp => false; + + @override + String get universalLabel => itemType; + + @override + String getLabel(BuildContext context) { + final l10n = context.l10n; + return switch (itemType) { + _animated => l10n.filterTypeAnimatedLabel, + _geotiff => l10n.filterTypeGeotiffLabel, + _hdr => 'HDR', + _motionPhoto => l10n.filterTypeMotionPhotoLabel, + _panorama => l10n.filterTypePanoramaLabel, + _raw => l10n.filterTypeRawLabel, + _sphericalVideo => l10n.filterTypeSphericalVideoLabel, + _ => itemType, + }; + } + + @override + Widget? iconBuilder(BuildContext context, double size, {bool allowGenericIcon = true}) => Icon(_icon, size: size); + + @override + Future<Color> color(BuildContext context) { + final colors = context.read<AvesColorsData>(); + switch (itemType) { + case _animated: + return SynchronousFuture(colors.animated); + case _geotiff: + return SynchronousFuture(colors.geotiff); + case _motionPhoto: + return SynchronousFuture(colors.motionPhoto); + case _panorama: + return SynchronousFuture(colors.panorama); + case _raw: + return SynchronousFuture(colors.raw); + case _sphericalVideo: + return SynchronousFuture(colors.sphericalVideo); + } + return super.color(context); + } + + @override + String get category => type; + + @override + String get key => '$type-$reversed-$itemType'; +} diff --git a/lib/model/filters/weekday.dart b/lib/model/filters/weekday.dart new file mode 100644 index 0000000..29d9d10 --- /dev/null +++ b/lib/model/filters/weekday.dart @@ -0,0 +1,58 @@ +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/widgets.dart'; +import 'package:intl/intl.dart'; + +class WeekDayFilter extends CollectionFilter { + static const type = 'weekday'; + + late final int weekday; + late final EntryPredicate _test; + + @override + List<Object?> get props => [weekday, reversed]; + + // `weekday` should be in [1, 7], with 1 as Monday + WeekDayFilter(this.weekday, {super.reversed = false}) { + _test = (entry) => entry.bestDate?.weekday == weekday; + } + + factory WeekDayFilter.fromMap(Map<String, dynamic> json) { + return WeekDayFilter( + json['weekday'] as int, + reversed: json['reversed'] ?? false, + ); + } + + @override + Map<String, dynamic> toMap() => { + 'type': type, + 'weekday': weekday, + 'reversed': reversed, + }; + + @override + EntryPredicate get positiveTest => _test; + + @override + bool get exclusiveProp => true; + + @override + String get universalLabel => weekday.toString(); + + @override + String getLabel(BuildContext context) { + final dateSymbols = DateFormat(null, context.locale).dateSymbols; + return dateSymbols.STANDALONEWEEKDAYS[weekday % 7]; + } + + @override + Widget? iconBuilder(BuildContext context, double size, {bool allowGenericIcon = true}) => Icon(AIcons.dateWeekday, size: size); + + @override + String get category => type; + + @override + String get key => '$type-$reversed-$weekday'; +} diff --git a/lib/model/grouping/common.dart b/lib/model/grouping/common.dart new file mode 100644 index 0000000..2cc8c9b --- /dev/null +++ b/lib/model/grouping/common.dart @@ -0,0 +1,374 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:aves/model/dynamic_albums.dart'; +import 'package:aves/model/filters/container/album_group.dart'; +import 'package:aves/model/filters/container/dynamic_album.dart'; +import 'package:aves/model/filters/container/group_base.dart'; +import 'package:aves/model/filters/container/set_or.dart'; +import 'package:aves/model/filters/container/tag_group.dart'; +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/filters/covered/tag.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/grouping/convert.dart'; +import 'package:aves/model/source/album.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/model/source/events.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/utils/collection_utils.dart'; +import 'package:collection/collection.dart'; +import 'package:event_bus/event_bus.dart'; +import 'package:flutter/foundation.dart'; + +final FilterGrouping albumGrouping = FilterGrouping._private(FilterGrouping.hostAlbums, AlbumGroupFilter.new); +final FilterGrouping tagGrouping = FilterGrouping._private(FilterGrouping.hostTags, TagGroupFilter.new); + +// album group URI: "aves://albums/group?path=/group12/subgroup34" +// stored album URI: "aves://albums/stored?path=/volume/dir/path12" +// dynamic album URI: "aves://albums/dynamic?name=dynalbum12" +class FilterGrouping<T extends GroupBaseFilter> with ChangeNotifier { + static const scheme = 'aves'; + static const hostAlbums = 'albums'; + static const hostTags = 'tags'; + + static const _groupPath = '/group'; + static const _groupPathParamKey = 'path'; + + final EventBus eventBus = EventBus(); + + final String _host; + final T Function(Uri uri, SetOrFilter filter) _createGroupFilter; + final Map<Uri, Set<Uri>> _groups = {}; + final Set<StreamSubscription> _subscriptions = {}; + final Map<CollectionSource, Set<StreamSubscription>> _sourceSubscriptions = {}; + CollectionSource? _source; + + Map<Uri, Set<Uri>> get allGroups => Map.unmodifiable(_groups); + + // do not subscribe to events from other modules in constructor + // so that modules can subscribe to each other + FilterGrouping._private(this._host, this._createGroupFilter) { + if (kFlutterMemoryAllocationsEnabled) ChangeNotifier.maybeDispatchObjectCreation(this); + } + + void init() { + _subscriptions.add(dynamicAlbums.eventBus.on<DynamicAlbumChangedEvent>().listen((e) => _clearObsoleteFilters())); + } + + void setGroups(Map<Uri, Set<Uri>> groups) { + _groups.clear(); + _groups.addAll(groups); + } + + @override + void dispose() { + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + _sourceSubscriptions.keys.toSet().forEach(unregisterSource); + super.dispose(); + } + + void registerSource(CollectionSource source) { + unregisterSource(_source); + final sourceEvents = source.eventBus; + _sourceSubscriptions[source] = { + sourceEvents.on<EntryMovedEvent>().listen((e) => _clearObsoleteFilters()), + sourceEvents.on<EntryRemovedEvent>().listen((e) => _clearObsoleteFilters()), + sourceEvents.on<AlbumsChangedEvent>().listen((e) => _clearObsoleteFilters()), + }; + _source = source; + } + + void unregisterSource(CollectionSource? source) { + _sourceSubscriptions.remove(source) + ?..forEach((sub) => sub.cancel()) + ..clear(); + } + + void addToGroup(Set<Uri> childrenUris, Uri? destinationGroup) { + _removeFromGroups(childrenUris); + if (destinationGroup != null) { + _ensureGroupFromRoot(destinationGroup); + final children = _groups[destinationGroup] ?? {}; + children.addAll(childrenUris); + _groups[destinationGroup] = children; + } + _reparentGroupPaths(childrenUris, destinationGroup); + _cleanEmptyGroups(); + notifyListeners(); + } + + void rename(Uri oldUri, Uri newUri) { + final childrenUris = _groups[oldUri]; + if (childrenUris == null) return; + + // local copy to prevent concurrent modification + addToGroup(Set.of(childrenUris), newUri); + eventBus.fire(GroupUriChangedEvent(oldUri, newUri)); + } + + bool get isNotEmpty => _groups.isNotEmpty; + + bool exists(Uri? groupUri) => _groups.containsKey(groupUri); + + Set<Uri> getGroups() => _groups.keys.toSet(); + + // returns number of filters within provided group, following subgroups without counting them + // providing the null root will yield 0, rather than the total number of filters in the collection (which is out of scope) + int countLeaves(Uri? groupUri) { + int count = 0; + if (groupUri != null) { + final childrenUris = _groups[groupUri]; + if (childrenUris != null) { + childrenUris.map(uriToFilter).nonNulls.forEach((filter) { + if (filter is GroupBaseFilter) { + count += countLeaves(filter.uri); + } else { + count++; + } + }); + } + } + return count; + } + + // returns filters directly within the provided group, including subgroups as filters + // providing the null root will yield its direct group filters + Set<CollectionFilter> getDirectChildren(Uri? currentGroupUri) { + if (currentGroupUri == null) { + return _groups.entries.where((kv) => getParentGroup(kv.key) == currentGroupUri).map((kv) { + final groupUri = kv.key; + final childrenUris = kv.value; + final childrenFilters = childrenUris.map(uriToFilter).nonNulls.toSet(); + return _createGroupFilter(groupUri, SetOrFilter(childrenFilters)); + }).toSet(); + } + + final childrenUris = _groups.entries.firstWhereOrNull((kv) => kv.key == currentGroupUri)?.value; + if (childrenUris != null) { + return childrenUris.map(uriToFilter).nonNulls.toSet(); + } + + return {}; + } + + Uri buildGroupUri(Uri? parentGroupUri, String name) { + return _buildGroupUri(_host, parentGroupUri, name); + } + + CollectionFilter? uriToFilter(Uri? uri) { + if (uri == null || uri.host != _host) return null; + + if (FilterGrouping.isGroupUri(uri)) { + return _createGroupFilter(uri, SetOrFilter(getDirectChildren(uri))); + } + + return GroupingConversion.uriToFilter(uri); + } + + void _removeFromGroups(Set<Uri> uris) { + _groups.forEach((_, childrenUris) { + childrenUris.removeAll(uris); + }); + } + + void _cleanEmptyGroups() { + final emptyGroupUris = _groups.entries.where((kv) => kv.value.isEmpty).map((v) => v.key).toSet(); + if (emptyGroupUris.isNotEmpty) { + _removeFromGroups(emptyGroupUris); + _groups.removeWhere((groupUri, _) => emptyGroupUris.contains(groupUri)); + _cleanEmptyGroups(); + } + } + + void _reparentGroupPaths(Set<Uri> childrenUris, Uri? parentGroupUri) { + final groupUris = childrenUris.where(FilterGrouping.isGroupUri).toSet(); + groupUris.forEach((oldGroupUri) { + final name = FilterGrouping.getGroupName(oldGroupUri); + if (name != null) { + final groupChildrenUris = _groups.remove(oldGroupUri); + if (groupChildrenUris != null) { + // create child group with updated URI + final newGroupUri = buildGroupUri(parentGroupUri, name); + _groups[newGroupUri] = groupChildrenUris; + + // update child group URI in parent group itself + if (parentGroupUri != null) { + final children = _groups[parentGroupUri]; + if (children != null && children.remove(oldGroupUri)) { + children.add(newGroupUri); + } + } + + eventBus.fire(GroupUriChangedEvent(oldGroupUri, newGroupUri)); + _reparentGroupPaths(groupChildrenUris, newGroupUri); + } + } + }); + } + + void _ensureGroupFromRoot(Uri groupUri) { + final parentGroupUri = FilterGrouping.getParentGroup(groupUri); + if (parentGroupUri != null) { + final children = _groups[parentGroupUri] ?? {}; + children.addAll({groupUri}); + _groups[parentGroupUri] = children; + _ensureGroupFromRoot(parentGroupUri); + } + } + + void _clearObsoleteFilters() { + final source = _source; + if (source == null || source.targetScope != CollectionSource.fullScope || !source.isReady) return; + + _groups.entries.forEach((kv) { + final groupUri = kv.key; + final childrenUris = kv.value; + + final allEntries = source.allEntries; + final rawAlbums = source.rawAlbums; + final sortedTags = source.sortedTags; + + childrenUris.toSet().forEach((childUri) { + final filter = uriToFilter(childUri); + var valid = false; + if (filter != null) { + switch (filter) { + case GroupBaseFilter _: + valid = true; + case DynamicAlbumFilter _: + valid = dynamicAlbums.contains(filter.name); + case StoredAlbumFilter _: + // check album itself + final isVisibleAlbum = rawAlbums.contains(filter.album); + if (isVisibleAlbum) { + valid = true; + } else { + // check non-visible content (hidden, trash, etc.) + valid = allEntries.any(filter.test); + } + case TagFilter _: + // check tag itself + final isVisibleTag = sortedTags.contains(filter.tag); + if (isVisibleTag) { + valid = true; + } else { + // check non-visible content (hidden, trash, etc.) + valid = allEntries.any(filter.test); + } + } + } + if (!valid) { + childrenUris.remove(childUri); + debugPrint('Removed obsolete childUri=$childUri from group=$groupUri'); + } + }); + }); + _cleanEmptyGroups(); + } + + // group uri / filter conversion + + static String? getGroupPath(Uri? uri) => uri?.queryParameters[_groupPathParamKey]; + + static String? getGroupName(Uri? uri) { + final path = getGroupPath(uri); + return path != null ? pContext.split(path).lastOrNull : null; + } + + static bool isGroupUri(Uri uri) => uri.path == FilterGrouping._groupPath; + + // parent group URI is `null` for root + static Uri _buildGroupUri(String host, Uri? parentGroupUri, String name) { + if (parentGroupUri != null) { + final path = getGroupPath(parentGroupUri); + if (path != null) { + return parentGroupUri.replace( + queryParameters: { + _groupPathParamKey: pContext.join(path, name), + }, + ); + } + } + return Uri( + scheme: scheme, + host: host, + path: _groupPath, + queryParameters: { + _groupPathParamKey: name, + }, + ); + } + + // returns `null` for root + Uri? getFilterParent(CollectionFilter filter) { + final uri = GroupingConversion.filterToUri(filter); + if (uri == null) return null; + + if (isGroupUri(uri)) { + return getParentGroup(uri); + } else { + return _groups.entries.firstWhereOrNull((kv) { + return kv.value.contains(uri); + })?.key; + } + } + + // returns `null` for root + static Uri? getParentGroup(Uri? groupUri) { + if (groupUri == null) return null; + + final path = getGroupPath(groupUri); + if (path != null) { + final segments = pContext.split(path); + final newLength = segments.length - 1; + if (newLength > 0) { + return groupUri.replace( + queryParameters: { + _groupPathParamKey: pContext.joinAll(segments.take(newLength)), + }, + ); + } + } + return null; + } + + static FilterGrouping? forUri(Uri uri) { + switch (uri.host) { + case hostAlbums: + return albumGrouping; + case hostTags: + return tagGrouping; + default: + return null; + } + } + + // serialization + + static String toJson(Map<Uri, Set<Uri>> groups) => jsonEncode(groups.map((parentUri, childrenUris) { + return MapEntry(parentUri.toString(), childrenUris.map((v) => v.toString()).toList()); + })); + + static Map<Uri, Set<Uri>>? fromJson(String? jsonString) { + if (jsonString == null || jsonString.isEmpty) return null; + + final jsonMap = jsonDecode(jsonString); + if (jsonMap is! Map) return null; + + return jsonMap.map((parent, children) { + final Uri? parentUri = parent is String ? Uri.tryParse(parent) : null; + final Set<Uri> childrenUris = children is Iterable ? children.whereType<String>().map(Uri.tryParse).nonNulls.toSet() : {}; + return MapEntry(parentUri, childrenUris); + }).whereNotNullKey(); + } +} + +@immutable +class GroupUriChangedEvent { + final Uri oldGroupUri; + final Uri newGroupUri; + + const GroupUriChangedEvent(this.oldGroupUri, this.newGroupUri); +} diff --git a/lib/model/grouping/convert.dart b/lib/model/grouping/convert.dart new file mode 100644 index 0000000..d27663a --- /dev/null +++ b/lib/model/grouping/convert.dart @@ -0,0 +1,87 @@ +import 'package:aves/model/dynamic_albums.dart'; +import 'package:aves/model/filters/container/dynamic_album.dart'; +import 'package:aves/model/filters/container/group_base.dart'; +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/filters/covered/tag.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/grouping/common.dart'; + +mixin GroupingConversion { + static const _storedAlbumPath = '/stored'; + static const _dynamicAlbumPath = '/dynamic'; + static const _tagPath = '/tag'; + static const _nameParamKey = 'name'; + static const _storagePathParamKey = 'path'; + + static CollectionFilter? uriToFilter(Uri uri) { + switch (uri.path) { + case _storedAlbumPath: + final album = uri.queryParameters[_storagePathParamKey]; + if (album != null) { + return StoredAlbumFilter(album, null); + } + case _dynamicAlbumPath: + final name = uri.queryParameters[_nameParamKey]; + if (name != null) { + return dynamicAlbums.get(name); + } + case _tagPath: + final tag = uri.queryParameters[_nameParamKey]; + if (tag != null) { + return TagFilter(tag); + } + default: + throw Exception('unhandled path=${uri.path} with uri=$uri'); + } + + throw Exception('failed to convert to filter with uri=$uri'); + } + + static Uri? filterToUri(CollectionFilter filter) { + switch (filter) { + case GroupBaseFilter _: + return filter.uri; + case StoredAlbumFilter _: + return _buildStoredAlbumUri(filter.album); + case DynamicAlbumFilter _: + return _buildDynamicAlbumUri(filter.name); + case TagFilter _: + return _buildTagUri(filter.tag); + default: + throw Exception('unknown type with filter=$filter'); + } + } + + static Uri _buildStoredAlbumUri(String album) { + return Uri( + scheme: FilterGrouping.scheme, + host: FilterGrouping.hostAlbums, + path: _storedAlbumPath, + queryParameters: { + _storagePathParamKey: album, + }, + ); + } + + static Uri _buildDynamicAlbumUri(String name) { + return Uri( + scheme: FilterGrouping.scheme, + host: FilterGrouping.hostAlbums, + path: _dynamicAlbumPath, + queryParameters: { + _nameParamKey: name, + }, + ); + } + + static Uri _buildTagUri(String tag) { + return Uri( + scheme: FilterGrouping.scheme, + host: FilterGrouping.hostTags, + path: _tagPath, + queryParameters: { + _nameParamKey: tag, + }, + ); + } +} diff --git a/lib/model/highlight.dart b/lib/model/highlight.dart new file mode 100644 index 0000000..43f0340 --- /dev/null +++ b/lib/model/highlight.dart @@ -0,0 +1,71 @@ +import 'package:event_bus/event_bus.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/painting.dart'; + +class HighlightInfo extends ChangeNotifier { + final EventBus eventBus = EventBus(); + + HighlightInfo() { + if (kFlutterMemoryAllocationsEnabled) ChangeNotifier.maybeDispatchObjectCreation(this); + } + + void trackItem<T>( + T? item, { + TrackPredicate? predicate, + Alignment? alignment, + bool? animate, + Object? highlightItem, + }) { + if (item != null) { + eventBus.fire(TrackEvent<T>( + item, + predicate ?? (_) => true, + alignment ?? Alignment.center, + animate ?? true, + highlightItem, + )); + } + } + + Object? _item; + + void set(Object item) { + if (_item == item) return; + _item = item; + notifyListeners(); + } + + Object? clear() { + if (_item == null) return null; + final item = _item; + _item = null; + notifyListeners(); + return item; + } + + bool contains(Object item) => _item == item; + + @override + String toString() => '$runtimeType#${shortHash(this)}{item=$_item}'; +} + +@immutable +class TrackEvent<T> { + final T item; + final TrackPredicate predicate; + final Alignment alignment; + final bool animate; + final Object? highlightItem; + + const TrackEvent( + this.item, + this.predicate, + this.alignment, + this.animate, + this.highlightItem, + ); +} + +// `itemVisibility`: percent of the item tracked already visible in viewport +// returns whether to proceed with tracking +typedef TrackPredicate = bool Function(double itemVisibility); diff --git a/lib/model/media/geotiff.dart b/lib/model/media/geotiff.dart new file mode 100644 index 0000000..ad036ae --- /dev/null +++ b/lib/model/media/geotiff.dart @@ -0,0 +1,266 @@ +import 'dart:async'; +import 'dart:math'; +import 'dart:ui' as ui; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/images.dart'; +import 'package:aves/ref/metadata/geotiff.dart'; +import 'package:aves/utils/math_utils.dart'; +import 'package:aves_map/aves_map.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flutter/widgets.dart'; +import 'package:latlong2/latlong.dart'; +import 'package:proj4dart/proj4dart.dart' as proj4; + +@immutable +class GeoTiffInfo extends Equatable { + final List<double>? modelPixelScale, modelTiePoints, modelTransformation; + final int? projCSType, projLinearUnits; + + @override + List<Object?> get props => [modelPixelScale, modelTiePoints, modelTransformation, projCSType, projLinearUnits]; + + const GeoTiffInfo({ + this.modelPixelScale, + this.modelTiePoints, + this.modelTransformation, + this.projCSType, + this.projLinearUnits, + }); + + factory GeoTiffInfo.fromMap(Map map) { + return GeoTiffInfo( + modelPixelScale: (map[GeoTiffExifTags.modelPixelScale] as List?)?.cast<double>(), + modelTiePoints: (map[GeoTiffExifTags.modelTiePoints] as List?)?.cast<double>(), + modelTransformation: (map[GeoTiffExifTags.modelTransformation] as List?)?.cast<double>(), + projCSType: map[GeoTiffKeys.projCSType] as int?, + projLinearUnits: map[GeoTiffKeys.projLinearUnits] as int?, + ); + } +} + +class MappedGeoTiff with MapOverlay { + final AvesEntry entry; + + late final GeoTiffCoordinateConverter _converter; + late final int _mapServiceTileSize; + late final MapServiceHelper _mapServiceHelper; + + static final _tileImagePaint = Paint(); + static final _tileMissingPaint = Paint() + ..style = PaintingStyle.fill + ..color = const Color(0xFF000000); + + MappedGeoTiff({ + required GeoTiffInfo info, + required this.entry, + required double devicePixelRatio, + }) { + _converter = GeoTiffCoordinateConverter(info: info, entry: entry); + _mapServiceTileSize = (256 * devicePixelRatio).round(); + _mapServiceHelper = MapServiceHelper(_mapServiceTileSize); + } + + @override + Future<MapTile?> getTile(int tx, int ty, int? zoomLevel) async { + zoomLevel ??= 0; + + // global projected coordinates in meters (EPSG:3857 Spherical Mercator) + final tileTopLeft3857 = _mapServiceHelper.tileTopLeft(tx, ty, zoomLevel); + final tileBottomRight3857 = _mapServiceHelper.tileTopLeft(tx + 1, ty + 1, zoomLevel); + + // image region coordinates in pixels + final tileTopLeftPx = _converter.epsg3857ToPoint(tileTopLeft3857); + final tileBottomRightPx = _converter.epsg3857ToPoint(tileBottomRight3857); + if (tileTopLeftPx == null || tileBottomRightPx == null) return null; + + final tileLeft = tileTopLeftPx.x; + final tileRight = tileBottomRightPx.x; + final tileTop = tileTopLeftPx.y; + final tileBottom = tileBottomRightPx.y; + + final width = entry.width; + final height = entry.height; + + final regionLeft = tileLeft.clamp(0, width); + final regionRight = tileRight.clamp(0, width); + final regionTop = tileTop.clamp(0, height); + final regionBottom = tileBottom.clamp(0, height); + + final regionWidth = regionRight - regionLeft; + final regionHeight = regionBottom - regionTop; + if (regionWidth == 0 || regionHeight == 0) return null; + + final tileXScale = (tileRight - tileLeft) / _mapServiceTileSize; + final sampleSize = max<int>(1, highestPowerOf2(tileXScale)); + final region = entry.getRegion( + sampleSize: sampleSize, + region: Rectangle(regionLeft, regionTop, regionWidth, regionHeight), + ); + + final imageInfoCompleter = Completer<ImageInfo?>(); + final imageStream = region.resolve(ImageConfiguration.empty); + final imageStreamListener = ImageStreamListener((image, synchronousCall) { + imageInfoCompleter.complete(image); + }, onError: imageInfoCompleter.completeError); + imageStream.addListener(imageStreamListener); + ImageInfo? regionImageInfo; + try { + regionImageInfo = await imageInfoCompleter.future; + } catch (error) { + debugPrint('failed to get image for region=$region with error=$error'); + } + imageStream.removeListener(imageStreamListener); + + final imageOffset = Offset( + regionLeft > tileLeft ? (regionLeft - tileLeft).toDouble() : 0, + regionTop > tileTop ? (regionTop - tileTop).toDouble() : 0, + ); + final tileImageScaleX = (tileRight - tileLeft) / _mapServiceTileSize; + final tileImageScaleY = (tileBottom - tileTop) / _mapServiceTileSize; + + final recorder = ui.PictureRecorder(); + final canvas = Canvas(recorder); + canvas.scale(1 / tileImageScaleX, 1 / tileImageScaleY); + if (regionImageInfo != null) { + final s = sampleSize.toDouble(); + canvas.scale(s, s); + canvas.drawImage(regionImageInfo.image, imageOffset / s, _tileImagePaint); + canvas.scale(1 / s, 1 / s); + } else { + // fallback to show area + canvas.drawRect( + Rect.fromLTWH( + imageOffset.dx, + imageOffset.dy, + regionWidth.toDouble(), + regionHeight.toDouble(), + ), + _tileMissingPaint, + ); + } + canvas.scale(tileImageScaleX, tileImageScaleY); + + final picture = recorder.endRecording(); + final tileImage = await picture.toImage(_mapServiceTileSize, _mapServiceTileSize); + final byteData = await tileImage.toByteData(format: ui.ImageByteFormat.png); + if (byteData == null) return null; + + return MapTile( + width: tileImage.width, + height: tileImage.height, + data: byteData.buffer.asUint8List(), + ); + } + + @override + String get id => entry.uri; + + @override + ImageProvider get imageProvider => entry.fullImage; + + @override + bool get canOverlay => center != null; + + LatLng? get center => _converter.center; + + @override + LatLng? get topLeft => _converter.topLeft; + + @override + LatLng? get bottomRight => _converter.bottomRight; +} + +class GeoTiffCoordinateConverter { + final AvesEntry entry; + + late LatLng? Function(Point<int> pixel) pointToLatLng; + late Point<int>? Function(Point<double> smPoint) epsg3857ToPoint; + + GeoTiffCoordinateConverter({ + required GeoTiffInfo info, + required this.entry, + }) { + pointToLatLng = (_) => null; + epsg3857ToPoint = (_) => null; + + // limitation: only support some UTM coordinate systems + final projCSType = info.projCSType; + final srcProj4 = GeoUtils.epsgToProj4(projCSType); + if (srcProj4 == null) { + debugPrint('unsupported projCSType=$projCSType'); + return; + } + + // limitation: only support model space values in units of meters + // TODO TLAD [geotiff] default from parsing proj4 instead of meter? + final projLinearUnits = info.projLinearUnits ?? GeoTiffUnits.linearMeter; + if (projLinearUnits != GeoTiffUnits.linearMeter) { + debugPrint('unsupported projLinearUnits=$projLinearUnits'); + return; + } + + // limitation: only support tie points, not transformation matrix + final modelTiePoints = info.modelTiePoints; + if (modelTiePoints == null) return; + + if (modelTiePoints.length < 6) return; + + // map image space (I,J,K) to model space (X,Y,Z) + final tpI = modelTiePoints[0]; + final tpJ = modelTiePoints[1]; + final tpK = modelTiePoints[2]; + final tpX = modelTiePoints[3]; + final tpY = modelTiePoints[4]; + final tpZ = modelTiePoints[5]; + + // limitation: expect 0,0,0,X,Y,0 + if (tpI != 0 || tpJ != 0 || tpK != 0 || tpZ != 0) return; + + final modelPixelScale = info.modelPixelScale; + if (modelPixelScale == null || modelPixelScale.length < 2) return; + + final xScale = modelPixelScale[0]; + final yScale = modelPixelScale[1]; + + final geoTiffProjection = proj4.Projection.parse(srcProj4); + final projToLatLng = proj4.ProjectionTuple( + fromProj: geoTiffProjection, + toProj: proj4.Projection.WGS84, + ); + pointToLatLng = (pixel) { + final srcPoint = proj4.Point( + x: tpX + pixel.x * xScale, + y: tpY - pixel.y * yScale, + ); + final destPoint = projToLatLng.forward(srcPoint); + + final latitude = destPoint.y; + final longitude = destPoint.x; + if (latitude >= -90.0 && latitude <= 90.0 && longitude >= -180.0 && longitude <= 180.0) { + return LatLng(latitude, longitude); + } + return null; + }; + + final projFromMapService = proj4.ProjectionTuple( + fromProj: proj4.Projection.GOOGLE, + toProj: geoTiffProjection, + ); + epsg3857ToPoint = (smPoint) { + final srcPoint = proj4.Point(x: smPoint.x, y: smPoint.y); + final destPoint = projFromMapService.forward(srcPoint); + return Point(((destPoint.x - tpX) / xScale).round(), -((destPoint.y - tpY) / yScale).round()); + }; + } + + int get width => entry.width; + + int get height => entry.height; + + LatLng? get center => pointToLatLng(Point((width / 2).round(), (height / 2).round())); + + LatLng? get topLeft => pointToLatLng(const Point(0, 0)); + + LatLng? get bottomRight => pointToLatLng(Point(width, height)); +} diff --git a/lib/model/media/panorama.dart b/lib/model/media/panorama.dart new file mode 100644 index 0000000..981908e --- /dev/null +++ b/lib/model/media/panorama.dart @@ -0,0 +1,86 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; + +class PanoramaInfo { + final Rect? croppedAreaRect; + final Size? fullPanoSize; + final String? projectionType; + + PanoramaInfo({ + this.croppedAreaRect, + this.fullPanoSize, + this.projectionType, + }); + + factory PanoramaInfo.fromMap(Map map) { + var cLeft = map['croppedAreaLeft'] as int?; + var cTop = map['croppedAreaTop'] as int?; + var cWidth = map['croppedAreaWidth'] as int?; + var cHeight = map['croppedAreaHeight'] as int?; + var fWidth = map['fullPanoWidth'] as int?; + var fHeight = map['fullPanoHeight'] as int?; + final projectionType = map['projectionType'] as String?; + + // handle missing `fullPanoHeight` (e.g. Samsung camera app panorama mode) + if (fHeight == null && fWidth != null && cHeight != null) { + fHeight = (fWidth / 2).round(); + cTop = ((fHeight - cHeight) / 2).round(); + } + + // handle inconsistent sizing (e.g. rotated image taken with OnePlus EB2103) + if (cWidth != null && cHeight != null && fWidth != null && fHeight != null) { + final croppedOrientation = cWidth > cHeight ? Orientation.landscape : Orientation.portrait; + final fullOrientation = fWidth > fHeight ? Orientation.landscape : Orientation.portrait; + var inconsistent = false; + if (croppedOrientation != fullOrientation) { + // inconsistent orientation + inconsistent = true; + final tmp = cHeight; + cHeight = cWidth; + cWidth = tmp; + } + + if (cWidth > fWidth) { + // inconsistent full/cropped width + inconsistent = true; + final tmp = fWidth; + fWidth = cWidth; + cWidth = tmp; + } + + if (cHeight > fHeight) { + // inconsistent full/cropped height + inconsistent = true; + final tmp = cHeight; + cHeight = fHeight; + fHeight = tmp; + } + + if (inconsistent) { + cLeft = (fWidth - cWidth) ~/ 2; + cTop = (fHeight - cHeight) ~/ 2; + } + } + + Rect? croppedAreaRect; + if (cLeft != null && cTop != null && cWidth != null && cHeight != null) { + croppedAreaRect = Rect.fromLTWH(cLeft.toDouble(), cTop.toDouble(), cWidth.toDouble(), cHeight.toDouble()); + } + + Size? fullPanoSize; + if (fWidth != null && fHeight != null) { + fullPanoSize = Size(fWidth.toDouble(), fHeight.toDouble()); + } + + return PanoramaInfo( + croppedAreaRect: croppedAreaRect, + fullPanoSize: fullPanoSize, + projectionType: projectionType, + ); + } + + bool get hasCroppedArea => croppedAreaRect != null && fullPanoSize != null; + + @override + String toString() => '$runtimeType#${shortHash(this)}{croppedAreaRect=$croppedAreaRect, fullPanoSize=$fullPanoSize, projectionType=$projectionType}'; +} diff --git a/lib/model/media/video/channel_layouts.dart b/lib/model/media/video/channel_layouts.dart new file mode 100644 index 0000000..c2ed853 --- /dev/null +++ b/lib/model/media/video/channel_layouts.dart @@ -0,0 +1,94 @@ +// channel layout constants from FFmpeg libavutil/channel_layout.h +class ChannelLayouts { + // ignore_for_file: constant_identifier_names + + static const FRONT_LEFT = 0x00000001; + static const FRONT_RIGHT = 0x00000002; + static const FRONT_CENTER = 0x00000004; + static const LOW_FREQUENCY = 0x00000008; + static const BACK_LEFT = 0x00000010; + static const BACK_RIGHT = 0x00000020; + static const FRONT_LEFT_OF_CENTER = 0x00000040; + static const FRONT_RIGHT_OF_CENTER = 0x00000080; + static const BACK_CENTER = 0x00000100; + static const SIDE_LEFT = 0x00000200; + static const SIDE_RIGHT = 0x00000400; + static const TOP_CENTER = 0x00000800; + static const TOP_FRONT_LEFT = 0x00001000; + static const TOP_FRONT_CENTER = 0x00002000; + static const TOP_FRONT_RIGHT = 0x00004000; + static const TOP_BACK_LEFT = 0x00008000; + static const TOP_BACK_CENTER = 0x00010000; + static const TOP_BACK_RIGHT = 0x00020000; + static const STEREO_LEFT = 0x20000000; + static const STEREO_RIGHT = 0x40000000; + + static const WIDE_LEFT = 0x0000000080000000; + static const WIDE_RIGHT = 0x0000000100000000; + static const SURROUND_DIRECT_LEFT = 0x0000000200000000; + static const SURROUND_DIRECT_RIGHT = 0x0000000400000000; + static const LOW_FREQUENCY_2 = 0x0000000800000000; + + static const LAYOUT_NATIVE = 0x8000000000000000; + + static const LAYOUT_MONO = (FRONT_CENTER); + static const LAYOUT_STEREO = (FRONT_LEFT | FRONT_RIGHT); + static const LAYOUT_2POINT1 = (LAYOUT_STEREO | LOW_FREQUENCY); + static const LAYOUT_2_1 = (LAYOUT_STEREO | BACK_CENTER); + static const LAYOUT_SURROUND = (LAYOUT_STEREO | FRONT_CENTER); + static const LAYOUT_3POINT1 = (LAYOUT_SURROUND | LOW_FREQUENCY); + static const LAYOUT_4POINT0 = (LAYOUT_SURROUND | BACK_CENTER); + static const LAYOUT_4POINT1 = (LAYOUT_4POINT0 | LOW_FREQUENCY); + static const LAYOUT_2_2 = (LAYOUT_STEREO | SIDE_LEFT | SIDE_RIGHT); + static const LAYOUT_QUAD = (LAYOUT_STEREO | BACK_LEFT | BACK_RIGHT); + static const LAYOUT_5POINT0 = (LAYOUT_SURROUND | SIDE_LEFT | SIDE_RIGHT); + static const LAYOUT_5POINT1 = (LAYOUT_5POINT0 | LOW_FREQUENCY); + static const LAYOUT_5POINT0_BACK = (LAYOUT_SURROUND | BACK_LEFT | BACK_RIGHT); + static const LAYOUT_5POINT1_BACK = (LAYOUT_5POINT0_BACK | LOW_FREQUENCY); + static const LAYOUT_6POINT0 = (LAYOUT_5POINT0 | BACK_CENTER); + static const LAYOUT_6POINT0_FRONT = (LAYOUT_2_2 | FRONT_LEFT_OF_CENTER | FRONT_RIGHT_OF_CENTER); + static const LAYOUT_HEXAGONAL = (LAYOUT_5POINT0_BACK | BACK_CENTER); + static const LAYOUT_6POINT1 = (LAYOUT_5POINT1 | BACK_CENTER); + static const LAYOUT_6POINT1_BACK = (LAYOUT_5POINT1_BACK | BACK_CENTER); + static const LAYOUT_6POINT1_FRONT = (LAYOUT_6POINT0_FRONT | LOW_FREQUENCY); + static const LAYOUT_7POINT0 = (LAYOUT_5POINT0 | BACK_LEFT | BACK_RIGHT); + static const LAYOUT_7POINT0_FRONT = (LAYOUT_5POINT0 | FRONT_LEFT_OF_CENTER | FRONT_RIGHT_OF_CENTER); + static const LAYOUT_7POINT1 = (LAYOUT_5POINT1 | BACK_LEFT | BACK_RIGHT); + static const LAYOUT_7POINT1_WIDE = (LAYOUT_5POINT1 | FRONT_LEFT_OF_CENTER | FRONT_RIGHT_OF_CENTER); + static const LAYOUT_7POINT1_WIDE_BACK = (LAYOUT_5POINT1_BACK | FRONT_LEFT_OF_CENTER | FRONT_RIGHT_OF_CENTER); + static const LAYOUT_OCTAGONAL = (LAYOUT_5POINT0 | BACK_LEFT | BACK_CENTER | BACK_RIGHT); + static const LAYOUT_HEXADECAGONAL = (LAYOUT_OCTAGONAL | WIDE_LEFT | WIDE_RIGHT | TOP_BACK_LEFT | TOP_BACK_RIGHT | TOP_BACK_CENTER | TOP_FRONT_CENTER | TOP_FRONT_LEFT | TOP_FRONT_RIGHT); + static const LAYOUT_STEREO_DOWNMIX = (STEREO_LEFT | STEREO_RIGHT); + + static const names = { + LAYOUT_NATIVE: 'native', + LAYOUT_MONO: 'mono', + LAYOUT_STEREO: 'stereo 2.0 • FL FR', + LAYOUT_2POINT1: 'stereo 2.1 • FL FR LFE', + LAYOUT_2_1: 'surround 3.0 • FL FR BC', + LAYOUT_SURROUND: 'stereo 3.0 • FL FR FC', + LAYOUT_3POINT1: 'stereo 3.1 • FL FR FC LFE', + LAYOUT_4POINT0: 'surround 4.0 • FL FR FC BC', + LAYOUT_4POINT1: 'surround 4.1 • FL FR FC BC LFE', + LAYOUT_2_2: 'quad (side) • FL FR SL SR', + LAYOUT_QUAD: 'quad (back) • FL FR BL BR', + LAYOUT_5POINT0: '5.0 (side) • FL FR FC SL SR', + LAYOUT_5POINT1: '5.1 (side) • FL FR FC SL SR LFE', + LAYOUT_5POINT0_BACK: '5.0 (back) • FL FR FC BL BR', + LAYOUT_5POINT1_BACK: '5.1 (back) • FL FR FC BL BR LFE', + LAYOUT_6POINT0: '6.0 (side) • FL FR FC SL SR BC', + LAYOUT_6POINT0_FRONT: '6.0 (front) • FL FR FLC FRC SL SR', + LAYOUT_HEXAGONAL: 'hexagonal • FL FR FC BL BR BC', + LAYOUT_6POINT1: '6.1 (side) • FL FR FC SL SR BC LFE', + LAYOUT_6POINT1_BACK: '6.1 (back) • FL FR FC BL BR BC LFE', + LAYOUT_6POINT1_FRONT: '6.1 (front) • FL FR FLC FRC SL SR LFE', + LAYOUT_7POINT0: 'surround 7.0 • FL FR FC SL SR BL BR', + LAYOUT_7POINT0_FRONT: 'wide 7.0 • FL FR FC FLC FRC SL SR', + LAYOUT_7POINT1: 'surround 7.1 • FL FR FC SL SR BL BR LFE', + LAYOUT_7POINT1_WIDE: 'wide 7.1 • FL FR FC FLC FRC SL SR LFE', + LAYOUT_7POINT1_WIDE_BACK: 'wide 7.1 (back) • FL FR FC FLC FRC BL BR LFE', + LAYOUT_OCTAGONAL: 'octagonal • FL FR FC SL SR BL BR BC', + LAYOUT_HEXADECAGONAL: 'hexadecagonal • FL FR FC WL WR TFL TFR TFC SL SR BL BR BC TBL TBR TBC', + LAYOUT_STEREO_DOWNMIX: 'stereo downmix', + }; +} diff --git a/lib/model/media/video/codecs.dart b/lib/model/media/video/codecs.dart new file mode 100644 index 0000000..aa29d56 --- /dev/null +++ b/lib/model/media/video/codecs.dart @@ -0,0 +1,16 @@ +class Codecs { + static const aac = 'aac'; + static const ac3 = 'ac3'; + static const eac3 = 'eac3'; + static const h264 = 'h264'; + static const hevc = 'hevc'; + static const matroska = 'matroska'; + static const mpeg4 = 'mpeg4'; + static const mpts = 'mpegts'; + static const opus = 'opus'; + static const pgs = 'hdmv_pgs_subtitle'; + static const subrip = 'subrip'; + static const theora = 'theora'; + static const vorbis = 'vorbis'; + static const webm = 'webm'; +} diff --git a/lib/model/media/video/metadata.dart b/lib/model/media/video/metadata.dart new file mode 100644 index 0000000..46a885c --- /dev/null +++ b/lib/model/media/video/metadata.dart @@ -0,0 +1,506 @@ +import 'dart:async'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/keys.dart'; +import 'package:aves/model/media/video/channel_layouts.dart'; +import 'package:aves/model/media/video/codecs.dart'; +import 'package:aves/model/media/video/profiles/aac.dart'; +import 'package:aves/model/media/video/profiles/h264.dart'; +import 'package:aves/model/media/video/profiles/hevc.dart'; +import 'package:aves/model/media/video/stereo_3d_modes.dart'; +import 'package:aves/model/metadata/catalog.dart'; +import 'package:aves/ref/languages.dart'; +import 'package:aves/ref/locales.dart'; +import 'package:aves/ref/mime_types.dart'; +import 'package:aves/ref/mp4.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/format.dart'; +import 'package:aves/utils/file_utils.dart'; +import 'package:aves/utils/math_utils.dart'; +import 'package:aves/utils/string_utils.dart'; +import 'package:aves/utils/time_utils.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; + +class VideoMetadataFormatter { + static final _dateY4M2D2H2m2s2Pattern = RegExp(r'(\d{4})[-./:](\d{1,2})[-./:](\d{1,2})([ T](\d{1,2}):(\d{1,2}):(\d{1,2})( ([ap]\.? ?m\.?))?)?'); + static final _ambiguousDatePatterns = { + RegExp(r'^\d{2}[-/]\d{2}[-/]\d{4}$'), + }; + static final _durationHmsmPattern = RegExp(r'(\d+):(\d+):(\d+)(.\d+)'); + static final _durationSmPattern = RegExp(r'(\d+)(.\d+)'); + static final _locationPattern = RegExp(r'([+-][.0-9]+)'); + static final Map<String, String> _codecNames = { + Codecs.ac3: 'AC-3', + Codecs.eac3: 'E-AC-3', + Codecs.h264: 'AVC (H.264)', + Codecs.hevc: 'HEVC (H.265)', + Codecs.matroska: 'Matroska', + Codecs.mpeg4: 'MPEG-4 Visual', + Codecs.mpts: 'MPEG-TS', + Codecs.opus: 'Opus', + Codecs.pgs: 'PGS', + Codecs.subrip: 'SubRip', + Codecs.theora: 'Theora', + Codecs.vorbis: 'Vorbis', + Codecs.webm: 'WebM', + }; + + // fetch size, rotation and duration + static Future<Map<String, int>> getLoadingMetadata(AvesEntry entry) async { + final mediaInfo = await videoMetadataFetcher.getMetadata(entry); + final fields = <String, int>{}; + + final streams = mediaInfo[Keys.streams]; + if (streams is List) { + final allStreamInfo = streams.cast<Map>(); + final sizedStream = allStreamInfo.firstWhereOrNull((stream) => stream.containsKey(Keys.videoWidth) && stream.containsKey(Keys.videoHeight)); + if (sizedStream != null) { + final width = sizedStream[Keys.videoWidth]; + final height = sizedStream[Keys.videoHeight]; + if (width is int && height is int) { + fields[EntryFields.width] = width; + fields[EntryFields.height] = height; + } + + final rotationDegrees = sizedStream[Keys.rotate]; + if (rotationDegrees is int) { + fields[EntryFields.rotationDegrees] = rotationDegrees; + } + } + } + + final durationMicros = mediaInfo[Keys.durationMicros]; + if (durationMicros is num) { + fields[EntryFields.durationMillis] = (durationMicros / 1000).round(); + } else { + final duration = _parseDuration(mediaInfo[Keys.duration]); + if (duration != null && duration > Duration.zero) { + fields[EntryFields.durationMillis] = duration.inMilliseconds; + } + } + return fields; + } + + // fetch date and animated status + static Future<CatalogMetadata?> completeCatalogMetadata(AvesEntry entry) async { + var catalogMetadata = entry.catalogMetadata ?? CatalogMetadata(id: entry.id); + + final mediaInfo = await videoMetadataFetcher.getMetadata(entry); + + if (entry.mimeType == MimeTypes.avif) { + final duration = _parseDuration(mediaInfo[Keys.duration]); + if (duration == null || duration == Duration.zero) return null; + + catalogMetadata = catalogMetadata.copyWith(isAnimated: true); + } + + // only consider values with at least 8 characters (yyyymmdd), + // ignoring unset values like `0`, as well as year values like `2021` + bool isDefined(dynamic value) => value is String && value.length >= 8; + + var dateString = mediaInfo[Keys.date]; + if (!isDefined(dateString)) { + dateString = mediaInfo[Keys.creationTime]; + } + int? dateMillis; + if (isDefined(dateString)) { + dateMillis = parseVideoDate(dateString); + if (dateMillis == null && !isAmbiguousDate(dateString)) { + await reportService.recordError('getCatalogMetadata failed to parse date=$dateString for mimeType=${entry.mimeType} entry=$entry'); + } + } + + // exclude date if it is suspiciously close to epoch + if (dateMillis != null && !DateTime.fromMillisecondsSinceEpoch(dateMillis).isAtSameDayAs(epoch)) { + catalogMetadata = catalogMetadata.copyWith(dateMillis: dateMillis); + } + + return catalogMetadata; + } + + static bool isAmbiguousDate(String dateString) { + return _ambiguousDatePatterns.any((pattern) => pattern.hasMatch(dateString)); + } + + static int? parseVideoDate(String dateString) { + final date = DateTime.tryParse(dateString); + if (date != null) { + return date.millisecondsSinceEpoch; + } + + // `DateTime` does not recognize these values found in the wild: + // - `UTC 2021-05-30 19:14:21` + // - `2021/10/31 21:23:17` + // - `2021-09-10T7:14:49 pmZ` + // - `2022-01-28T5:07:46 p. m.Z` + // - `2012-1-1T12:00:00Z` + // - `2020.10.14` + // - `2016:11:16 18:00:00` + // - `2021` (not enough to build a date) + + var match = _dateY4M2D2H2m2s2Pattern.firstMatch(dateString); + if (match != null) { + final year = int.tryParse(match.group(1)!); + final month = int.tryParse(match.group(2)!); + final day = int.tryParse(match.group(3)!); + + if (year != null && month != null && day != null) { + var hour = 0, minute = 0, second = 0, pm = false; + if (match.groupCount >= 7 && match.group(4) != null) { + hour = int.tryParse(match.group(5)!) ?? 0; + minute = int.tryParse(match.group(6)!) ?? 0; + second = int.tryParse(match.group(7)!) ?? 0; + pm = {'pm', 'p. m.'}.contains(match.group(9)); + } + + final date = DateTime(year, month, day, hour + (pm ? 12 : 0), minute, second, 0); + return date.millisecondsSinceEpoch; + } + } + + return null; + } + + // pattern to extract optional language code suffix, e.g. 'location-eng' + static final keyWithLanguagePattern = RegExp(r'^(.*)-([a-z]{3})$'); + + static Map<String, String> formatInfo(Map info) { + final dir = <String, String>{}; + final streamType = info[Keys.streamType]; + final codec = info[Keys.codecName]; + for (final kv in info.entries) { + final value = kv.value; + if (value != null) { + try { + String? key; + String? keyLanguage; + // some keys have a language suffix, but they may be duplicates + // we only keep the root key when they have the same value as the same key with no language + final languageMatch = keyWithLanguagePattern.firstMatch(kv.key); + if (languageMatch != null) { + final code = languageMatch.group(2)!; + final native = _formatLanguage(code); + if (native != code) { + final root = languageMatch.group(1)!; + final rootValue = info[root]; + // skip if it is a duplicate of the same entry with no language + if (rootValue == value) continue; + key = root; + if (info.keys.cast<String>().where((k) => k.startsWith('$root-')).length > 1) { + // only keep language when multiple languages are present + keyLanguage = native; + } + } + } + key = (key ?? (kv.key as String)).toLowerCase(); + + void save(String key, dynamic value) { + if (value != null) { + dir[keyLanguage != null ? '$key ($keyLanguage)' : key] = value.toString(); + } + } + + switch (key) { + case Keys.chapters: + case Keys.codecLevel: + case Keys.codecTag: + case Keys.codecTagString: + case Keys.durationTs: + case Keys.fpsNum: + case Keys.index: + case Keys.isAvc: + case Keys.probeScore: + case Keys.programCount: + case Keys.refs: + case Keys.sarNum: + case Keys.selectedAudioStream: + case Keys.selectedTextStream: + case Keys.selectedVideoStream: + case Keys.statisticsTags: + case Keys.streamCount: + case Keys.streams: + case Keys.streamType: + case Keys.tbrNum: + case Keys.tbrDen: + break; + case Keys.androidCaptureFramerate: + final captureFps = double.parse(value); + save('Capture Frame Rate', '${roundToPrecision(captureFps, decimals: 3)} FPS'); + case Keys.androidManufacturer: + save('Android Manufacturer', value); + case Keys.androidModel: + save('Android Model', value); + case Keys.androidVersion: + save('Android Version', value); + case Keys.audioChannels: + save('Audio Channels', value); + case Keys.bitrate: + case Keys.bps: + save('Bit Rate', _formatMetric(value, 'b/s')); + case Keys.byteCount: + save('Size', _formatFilesize(value)); + case Keys.channelLayout: + save('Channel Layout', _formatChannelLayout(value)); + case Keys.codecName: + if (value != 'none') { + save('Format', _formatCodecName(value)); + } + case Keys.codecPixelFormat: + if (streamType == MediaStreamTypes.video) { + // this is just a short name used by FFmpeg + // user-friendly descriptions for related enums are defined in libavutil/pixfmt.h + save('Pixel Format', value.toString().toUpperCase()); + } + case Keys.hwPixelFormat: + save('Hardware Pixel Format', value.toString().toUpperCase()); + case Keys.codedHeight: + save('Coded Height', '$value pixels'); + case Keys.codedWidth: + save('Coded Width', '$value pixels'); + case Keys.decoderHeight: + save('Decoder Height', '$value pixels'); + case Keys.decoderWidth: + save('Decoder Width', '$value pixels'); + case Keys.colorMatrix: + save('Color Matrix', value.toString().toUpperCase()); + case Keys.colorPrimaries: + save('Color Primaries', value.toString().toUpperCase()); + case Keys.colorRange: + save('Color Range', value.toString().toUpperCase()); + case Keys.colorSpace: + save('Color Space', value.toString().toUpperCase()); + case Keys.colorTransfer: + save('Color Transfer', value.toString().toUpperCase()); + case Keys.codecProfileId: + { + final profile = int.tryParse(value); + if (profile != null) { + String? profileString; + switch (codec) { + case Codecs.h264: + case Codecs.hevc: + { + final levelValue = info[Keys.codecLevel]; + if (levelValue != null) { + final level = levelValue is int ? levelValue : int.tryParse(levelValue) ?? 0; + if (codec == Codecs.h264) { + profileString = H264.formatProfile(profile, level); + } else { + profileString = Hevc.formatProfile(profile, level); + } + } + } + case Codecs.aac: + profileString = AAC.formatProfile(profile); + default: + profileString = profile.toString(); + } + save('Format Profile', profileString); + } + } + case Keys.compatibleBrands: + final formattedBrands = RegExp(r'.{4}').allMatches(value).map((m) { + final brand = m.group(0)!; + return _formatBrand(brand); + }).join(', '); + save('Compatible Brands', formattedBrands); + case Keys.creationTime: + save('Creation Time', _formatDate(value)); + case Keys.date: + if (value is String && value != '0') { + final charCount = value.length; + save(charCount == 4 ? 'Year' : 'Date', value); + } + case Keys.duration: + save('Duration', _formatDuration(value)); + case Keys.durationMicros: + if (value != 0) save('Duration', formatPreciseDuration(Duration(microseconds: value))); + case Keys.extraDataSize: + save('Extra Data Size', _formatFilesize(value)); + case Keys.fps: + save('Frame Rate', '${roundToPrecision(info[Keys.fps], decimals: 3)} FPS'); + case Keys.fpsDen: + save('Frame Rate', '${roundToPrecision(info[Keys.fpsNum] / info[Keys.fpsDen], decimals: 3)} FPS'); + case Keys.frameCount: + save('Frame Count', value); + case Keys.gamma: + save('Gamma', value.toString().toUpperCase()); + case Keys.hasBFrames: + save('Has B-Frames', value); + case Keys.hearingImpaired: + save('Hearing impaired', value); + case Keys.language: + if (value != 'und') save('Language', _formatLanguage(value)); + case Keys.location: + save('Location', _formatLocation(value)); + case Keys.majorBrand: + save('Major Brand', _formatBrand(value)); + case Keys.mediaFormat: + save('Format', value.toString().splitMapJoin(',', onMatch: (s) => ', ', onNonMatch: _formatCodecName)); + case Keys.minorVersion: + if (value != '0') save('Minor Version', value); + case Keys.nalLengthSize: + save('NAL Length Size', _formatFilesize(value)); + case Keys.quicktimeLocationAccuracyHorizontal: + save('QuickTime Location Horizontal Accuracy', value); + case Keys.quicktimeCreationDate: + case Keys.quicktimeLocationIso6709: + case Keys.quicktimeMake: + case Keys.quicktimeModel: + case Keys.quicktimeSoftware: + // redundant with `QuickTime Metadata` directory + break; + case Keys.rFrameRate: + save('R Frame Rate', value); + case Keys.rotate: + save('Rotation', '$value°'); + case Keys.sampleFormat: + save('Sample Format', value.toString().toUpperCase()); + case Keys.sampleRate: + save('Sample Rate', _formatMetric(value, 'Hz')); + case Keys.sar: + save('Sample Aspect Ratio', value); + case Keys.sarDen: + final sarNum = info[Keys.sarNum]; + final sarDen = info[Keys.sarDen]; + // skip common square pixels (1:1) + if (sarNum != sarDen) save('SAR', '$sarNum:$sarDen'); + case Keys.segmentCount: + save('Segment Count', value); + case Keys.sourceOshash: + save('Source OSHash', value); + case Keys.startMicros: + if (value != 0) save('Start', formatPreciseDuration(Duration(microseconds: value))); + case Keys.startPts: + save('Start PTS', value); + case Keys.startTime: + save('Start', _formatDuration(value)); + case Keys.statisticsWritingApp: + save('Stats Writing App', value); + case Keys.statisticsWritingDateUtc: + save('Stats Writing Date', _formatDate(value)); + case Keys.stereo3dMode: + save('Stereo 3D Mode', _formatStereo3dMode(value)); + case Keys.timeBase: + save('Time Base', value); + case Keys.track: + if (value != '0') save('Track', value); + case Keys.vendorId: + save('Vendor ID', value); + case Keys.videoHeight: + save('Video Height', '$value pixels'); + case Keys.videoWidth: + save('Video Width', '$value pixels'); + case Keys.visualImpaired: + save('Visual impaired', value); + case Keys.xiaomiSlowMoment: + save('Xiaomi Slow Moment', value); + default: + save(key.toSentenceCase(), value); + } + } catch (error) { + debugPrint('failed to process video info key=${kv.key} value=${kv.value}, error=$error'); + } + } + } + return dir; + } + + static String _formatBrand(String value) => Mp4.brands[value] ?? value; + + static String _formatChannelLayout(dynamic value) { + if (value is int) { + return ChannelLayouts.names[value] ?? 'unknown ($value)'; + } + return '$value'; + } + + static String _formatCodecName(String value) => _codecNames[value] ?? value.toUpperCase().replaceAll('_', ' '); + + // input example: '2021-04-12T09:14:37.000000Z' + static String? _formatDate(String value) { + final date = DateTime.tryParse(value); + if (date == null) return value; + if (date == epoch) return null; + return date.toIso8601String(); + } + + static String _formatStereo3dMode(String value) => Stereo3dModes.names[value] ?? value; + + // input example: '00:00:05.408000000' or '5.408000' + static Duration? _parseDuration(String? value) { + if (value == null) return null; + + var match = _durationHmsmPattern.firstMatch(value); + if (match != null) { + final h = int.tryParse(match.group(1)!); + final m = int.tryParse(match.group(2)!); + final s = int.tryParse(match.group(3)!); + final millis = double.tryParse(match.group(4)!); + if (h != null && m != null && s != null && millis != null) { + return Duration( + hours: h, + minutes: m, + seconds: s, + milliseconds: (millis * 1000).toInt(), + ); + } + } + + match = _durationSmPattern.firstMatch(value); + if (match != null) { + final s = int.tryParse(match.group(1)!); + final millis = double.tryParse(match.group(2)!); + if (s != null && millis != null) { + return Duration( + seconds: s, + milliseconds: (millis * 1000).toInt(), + ); + } + } + + return null; + } + + // input example: '00:00:05.408000000' or '5.408000' + static String _formatDuration(String value) { + final duration = _parseDuration(value); + return duration != null ? formatPreciseDuration(duration) : value; + } + + static String _formatFilesize(dynamic value) { + final size = value is int ? value : int.tryParse(value); + return size != null ? formatFileSize(asciiLocale, size) : value; + } + + static String _formatLanguage(String value) { + final language = Language.living639_2.firstWhereOrNull((language) => language.iso639_2 == value); + return language?.native ?? value; + } + + // format ISO 6709 input, e.g. '+37.5090+127.0243/' (Samsung), '+51.3328-000.7053+113.474/' (Apple) + static String? _formatLocation(String value) { + final matches = _locationPattern.allMatches(value); + if (matches.isNotEmpty) { + final coordinates = matches.map((m) => double.tryParse(m.group(0)!)).toList(); + if (coordinates.every((c) => c == 0)) return null; + return coordinates.join(', '); + } + return value; + } + + static String _formatMetric(dynamic size, String unit, {int round = 2}) { + if (size is String) { + final parsed = int.tryParse(size); + if (parsed == null) return size; + size = parsed; + } + + const divider = 1000; + if (size < divider) return '$size $unit'; + if (size < divider * divider) return '${(size / divider).toStringAsFixed(round)} K$unit'; + return '${(size / divider / divider).toStringAsFixed(round)} M$unit'; + } +} diff --git a/lib/model/media/video/profiles/aac.dart b/lib/model/media/video/profiles/aac.dart new file mode 100644 index 0000000..ffeb1e8 --- /dev/null +++ b/lib/model/media/video/profiles/aac.dart @@ -0,0 +1,33 @@ +class AAC { + static const profileMain = 0; + static const profileLowComplexity = 1; + static const profileScalableSampleRate = 2; + static const profileLongTermPrediction = 3; + static const profileHighEfficiency = 4; + static const profileHighEfficiencyV2 = 28; + static const profileLowDelay = 22; + static const profileLowDelayV2 = 38; + + static String formatProfile(int profileIndex) { + switch (profileIndex) { + case profileMain: + return 'Main'; + case profileLowComplexity: + return 'LC'; + case profileLongTermPrediction: + return 'LTP'; + case profileScalableSampleRate: + return 'SSR'; + case profileHighEfficiency: + return 'HE-AAC'; + case profileHighEfficiencyV2: + return 'HE-AAC v2'; + case profileLowDelay: + return 'LD'; + case profileLowDelayV2: + return 'ELD'; + default: + return '$profileIndex'; + } + } +} diff --git a/lib/model/media/video/profiles/h264.dart b/lib/model/media/video/profiles/h264.dart new file mode 100644 index 0000000..5fb99ac --- /dev/null +++ b/lib/model/media/video/profiles/h264.dart @@ -0,0 +1,62 @@ +class H264 { + static const profileConstrained = 1 << 9; + static const profileIntra = 1 << 11; + + static const profileBaseline = 66; + static const profileConstrainedBaseline = 66 | profileConstrained; + static const profileMain = 77; + static const profileExtended = 88; + static const profileHigh = 100; + static const profileHigh10 = 110; + static const profileHigh422 = 122; + static const profileHigh444 = 144; + static const profileHigh444Predictive = 244; + + // intra + static const profileHigh10Intra = 110 | profileIntra; + static const profileHigh422Intra = 122 | profileIntra; + static const profileHigh444Intra = 244 | profileIntra; + static const profileCAVLC444 = 44; + + // multiview + static const profileMultiviewHigh = 118; + static const profileStereoHigh = 128; + static const profileMultiviewDepthHigh = 138; + + static String formatProfile(int profileIndex, int levelIndex) { + String profile; + switch (profileIndex) { + case profileBaseline: + profile = 'Baseline'; + case profileConstrainedBaseline: + profile = 'Constrained Baseline'; + case profileMain: + profile = 'Main'; + case profileExtended: + profile = 'Extended'; + case profileHigh: + profile = 'High'; + case profileHigh10: + profile = 'High 10'; + case profileHigh10Intra: + profile = 'High 10 Intra'; + case profileHigh422: + profile = 'High 4:2:2'; + case profileHigh422Intra: + profile = 'High 4:2:2 Intra'; + case profileHigh444: + profile = 'High 4:4:4'; + case profileHigh444Predictive: + profile = 'High 4:4:4 Predictive'; + case profileHigh444Intra: + profile = 'High 4:4:4 Intra'; + case profileCAVLC444: + profile = 'CAVLC 4:4:4'; + default: + return '$profileIndex'; + } + if (levelIndex <= 0) return profile; + final level = (levelIndex / 10.0).toStringAsFixed(levelIndex % 10 != 0 ? 1 : 0); + return '$profile Profile, Level $level'; + } +} diff --git a/lib/model/media/video/profiles/hevc.dart b/lib/model/media/video/profiles/hevc.dart new file mode 100644 index 0000000..880982e --- /dev/null +++ b/lib/model/media/video/profiles/hevc.dart @@ -0,0 +1,25 @@ +class Hevc { + static const profileMain = 1; + static const profileMain10 = 2; + static const profileMainStillPicture = 3; + static const profileRExt = 4; + + static String formatProfile(int profileIndex, int levelIndex) { + String profile; + switch (profileIndex) { + case profileMain: + profile = 'Main'; + case profileMain10: + profile = 'Main 10'; + case profileMainStillPicture: + profile = 'Main Still Picture'; + case profileRExt: + profile = 'Format Range'; + default: + return '$profileIndex'; + } + if (levelIndex <= 0) return profile; + final level = (levelIndex / 30.0).toStringAsFixed(levelIndex % 10 != 0 ? 1 : 0); + return '$profile Profile, Level $level'; + } +} diff --git a/lib/model/media/video/stereo_3d_modes.dart b/lib/model/media/video/stereo_3d_modes.dart new file mode 100644 index 0000000..d0ff76b --- /dev/null +++ b/lib/model/media/video/stereo_3d_modes.dart @@ -0,0 +1,22 @@ +class Stereo3dModes { + static const names = { + 'ab2l': 'above below half height left first', + 'tb2l': 'above below half height left first', + 'ab2r': 'above below half height right first', + 'tb2r': 'above below half height right first', + 'abl': 'above below left first', + 'tbl': 'above below left first', + 'abr': 'above below right first', + 'tbr': 'above below right first', + 'al': 'alternating frames left first', + 'ar': 'alternating frames right first', + 'sbs2l': 'side by side half width left first', + 'sbs2r': 'side by side half width right first', + 'sbsl': 'side by side left first', + 'sbsr': 'side by side right first', + 'irl': 'interleave rows left first', + 'irr': 'interleave rows right first', + 'icl': 'interleave columns left first', + 'icr': 'interleave columns right first', + }; +} diff --git a/lib/model/metadata/address.dart b/lib/model/metadata/address.dart new file mode 100644 index 0000000..2680799 --- /dev/null +++ b/lib/model/metadata/address.dart @@ -0,0 +1,56 @@ +import 'package:aves/geo/states.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flutter/foundation.dart'; + +@immutable +class AddressDetails extends Equatable { + final int id; + final String? countryCode, countryName, adminArea, locality; + + @override + List<Object?> get props => [id, countryCode, countryName, adminArea, locality]; + + String? get place => locality != null && locality!.isNotEmpty ? locality : adminArea; + + String? get stateCode => GeoStates.stateCodeByName[stateName]; + + String? get stateName => GeoStates.stateCountryCodes.contains(countryCode) ? adminArea : null; + + const AddressDetails({ + required this.id, + this.countryCode, + this.countryName, + this.adminArea, + this.locality, + }); + + AddressDetails copyWith({ + int? id, + }) { + return AddressDetails( + id: id ?? this.id, + countryCode: countryCode, + countryName: countryName, + adminArea: adminArea, + locality: locality, + ); + } + + factory AddressDetails.fromMap(Map map) { + return AddressDetails( + id: map['id'] as int, + countryCode: map['countryCode'] as String?, + countryName: map['countryName'] as String?, + adminArea: map['adminArea'] as String?, + locality: map['locality'] as String?, + ); + } + + Map<String, dynamic> toMap() => { + 'id': id, + 'countryCode': countryCode, + 'countryName': countryName, + 'adminArea': adminArea, + 'locality': locality, + }; +} diff --git a/lib/model/metadata/catalog.dart b/lib/model/metadata/catalog.dart new file mode 100644 index 0000000..2c668d3 --- /dev/null +++ b/lib/model/metadata/catalog.dart @@ -0,0 +1,126 @@ +import 'package:aves/services/geocoding_service.dart'; +import 'package:flutter/foundation.dart'; + +class CatalogMetadata { + final int id; + final int? dateMillis; + final bool isAnimated, isGeotiff, is360, isMultiPage, isMotionPhoto, isHdr; + bool isFlipped; + int? rotationDegrees; + final String? mimeType, xmpSubjects, xmpTitle; + double? latitude, longitude; + Address? address; + int rating; + + // less lenient than Flutter's `precisionErrorTolerance` (1e-10) + static const double _precisionErrorTolerance = 1e-9; + + static const _isAnimatedMask = 1 << 0; + static const _isFlippedMask = 1 << 1; + static const _isGeotiffMask = 1 << 2; + static const _is360Mask = 1 << 3; + static const _isMultiPageMask = 1 << 4; + static const _isMotionPhotoMask = 1 << 5; + static const _isHdr = 1 << 6; // for images: embedded HDR gainmap, for videos: HDR color transfer + + CatalogMetadata({ + required this.id, + this.mimeType, + this.dateMillis, + this.isAnimated = false, + this.isFlipped = false, + this.isGeotiff = false, + this.is360 = false, + this.isMultiPage = false, + this.isMotionPhoto = false, + this.isHdr = false, + this.rotationDegrees, + this.xmpSubjects, + this.xmpTitle, + double? latitude, + double? longitude, + this.rating = 0, + }) { + // Geocoder throws an `IllegalArgumentException` when a coordinate has a funky value like `1.7056881853375E7` + // We also exclude zero coordinates, taking into account precision errors (e.g. {5.952380952380953e-11,-2.7777777777777777e-10}), + // but Flutter's `precisionErrorTolerance` (1e-10) is slightly too lenient for this case. + if (latitude != null && longitude != null && (latitude.abs() > _precisionErrorTolerance || longitude.abs() > _precisionErrorTolerance)) { + // funny case: some files have latitude and longitude reverse + // (e.g. a Japanese location at lat~=133 and long~=34, which is a valid longitude but an invalid latitude) + // so we should check and assign both coordinates at once + if (latitude >= -90.0 && latitude <= 90.0 && longitude >= -180.0 && longitude <= 180.0) { + this.latitude = latitude; + this.longitude = longitude; + } + } + } + + CatalogMetadata copyWith({ + int? id, + String? mimeType, + int? dateMillis, + bool? isAnimated, + bool? isMultiPage, + int? rotationDegrees, + double? latitude, + double? longitude, + }) { + return CatalogMetadata( + id: id ?? this.id, + mimeType: mimeType ?? this.mimeType, + dateMillis: dateMillis ?? this.dateMillis, + isAnimated: isAnimated ?? this.isAnimated, + isFlipped: isFlipped, + isGeotiff: isGeotiff, + is360: is360, + isMultiPage: isMultiPage ?? this.isMultiPage, + isMotionPhoto: isMotionPhoto, + isHdr: isHdr, + rotationDegrees: rotationDegrees ?? this.rotationDegrees, + xmpSubjects: xmpSubjects, + xmpTitle: xmpTitle, + latitude: latitude ?? this.latitude, + longitude: longitude ?? this.longitude, + rating: rating, + ); + } + + factory CatalogMetadata.fromMap(Map map) { + final flags = map['flags'] ?? 0; + return CatalogMetadata( + id: map['id'], + mimeType: map['mimeType'], + dateMillis: map['dateMillis'] ?? 0, + isAnimated: flags & _isAnimatedMask != 0, + isFlipped: flags & _isFlippedMask != 0, + isGeotiff: flags & _isGeotiffMask != 0, + is360: flags & _is360Mask != 0, + isMultiPage: flags & _isMultiPageMask != 0, + isMotionPhoto: flags & _isMotionPhotoMask != 0, + isHdr: flags & _isHdr != 0, + // `rotationDegrees` should default to `sourceRotationDegrees`, not 0 + rotationDegrees: map['rotationDegrees'], + xmpSubjects: map['xmpSubjects'] ?? '', + xmpTitle: map['xmpTitle'] ?? '', + latitude: map['latitude'], + longitude: map['longitude'], + rating: map['rating'] ?? 0, + ); + } + + Map<String, dynamic> toMap() => { + 'id': id, + 'mimeType': mimeType, + 'dateMillis': dateMillis, + 'flags': (isAnimated ? _isAnimatedMask : 0) | (isFlipped ? _isFlippedMask : 0) | (isGeotiff ? _isGeotiffMask : 0) | (is360 ? _is360Mask : 0) | (isMultiPage ? _isMultiPageMask : 0) | (isMotionPhoto ? _isMotionPhotoMask : 0) | (isHdr ? _isHdr : 0), + 'rotationDegrees': rotationDegrees, + 'xmpSubjects': xmpSubjects, + 'xmpTitle': xmpTitle, + 'latitude': latitude, + 'longitude': longitude, + 'rating': rating, + }; + + @override + String toString() => '$runtimeType#${shortHash(this)}{id=$id, mimeType=$mimeType, dateMillis=$dateMillis, isAnimated=$isAnimated, isFlipped=$isFlipped, isGeotiff=$isGeotiff, is360=$is360, isMultiPage=$isMultiPage, isMotionPhoto=$isMotionPhoto, rotationDegrees=$rotationDegrees, xmpSubjects=$xmpSubjects, xmpTitle=$xmpTitle, latitude=$latitude, longitude=$longitude, rating=$rating}'; +} diff --git a/lib/model/metadata/date_modifier.dart b/lib/model/metadata/date_modifier.dart new file mode 100644 index 0000000..b34a86e --- /dev/null +++ b/lib/model/metadata/date_modifier.dart @@ -0,0 +1,51 @@ +import 'package:aves_model/aves_model.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flutter/foundation.dart'; + +@immutable +class DateModifier extends Equatable { + static const writableFields = [ + MetadataField.exifDate, + MetadataField.exifDateOriginal, + MetadataField.exifDateDigitized, + MetadataField.exifGpsDatestamp, + MetadataField.xmpXmpCreateDate, + ]; + + final DateEditAction action; + final Set<MetadataField> fields; + final DateTime? setDateTime; + final DateFieldSource? copyFieldSource; + final int? shiftSeconds; + + @override + List<Object?> get props => [action, fields, setDateTime, copyFieldSource, shiftSeconds]; + + const DateModifier._private( + this.action, { + this.fields = const {}, + this.setDateTime, + this.copyFieldSource, + this.shiftSeconds, + }); + + factory DateModifier.setCustom(Set<MetadataField> fields, DateTime dateTime) { + return DateModifier._private(DateEditAction.setCustom, fields: fields, setDateTime: dateTime); + } + + factory DateModifier.copyField(DateFieldSource copyFieldSource) { + return DateModifier._private(DateEditAction.copyField, copyFieldSource: copyFieldSource); + } + + factory DateModifier.extractFromTitle() { + return const DateModifier._private(DateEditAction.extractFromTitle); + } + + factory DateModifier.shift(Set<MetadataField> fields, int shiftSeconds) { + return DateModifier._private(DateEditAction.shift, fields: fields, shiftSeconds: shiftSeconds); + } + + factory DateModifier.remove(Set<MetadataField> fields) { + return DateModifier._private(DateEditAction.remove, fields: fields); + } +} diff --git a/lib/model/metadata/overlay.dart b/lib/model/metadata/overlay.dart new file mode 100644 index 0000000..55e145f --- /dev/null +++ b/lib/model/metadata/overlay.dart @@ -0,0 +1,32 @@ +import 'package:equatable/equatable.dart'; +import 'package:flutter/foundation.dart'; + +@immutable +class OverlayMetadata extends Equatable { + final double? aperture, focalLength; + final String? description, exposureTime; + final int? iso; + + @override + List<Object?> get props => [aperture, description, exposureTime, focalLength, iso]; + + bool get hasShootingDetails => aperture != null || exposureTime != null || focalLength != null || iso != null; + + const OverlayMetadata({ + this.aperture, + this.description, + this.exposureTime, + this.focalLength, + this.iso, + }); + + factory OverlayMetadata.fromMap(Map map) { + return OverlayMetadata( + aperture: map['aperture'] as double?, + description: map['description'] as String?, + exposureTime: map['exposureTime'] as String?, + focalLength: map['focalLength'] as double?, + iso: map['iso'] as int?, + ); + } +} diff --git a/lib/model/metadata/trash.dart b/lib/model/metadata/trash.dart new file mode 100644 index 0000000..260661d --- /dev/null +++ b/lib/model/metadata/trash.dart @@ -0,0 +1,42 @@ +import 'package:equatable/equatable.dart'; +import 'package:flutter/foundation.dart'; + +@immutable +class TrashDetails extends Equatable { + final int id; + final String path; + final int dateMillis; + + @override + List<Object?> get props => [id, path, dateMillis]; + + const TrashDetails({ + required this.id, + required this.path, + required this.dateMillis, + }); + + TrashDetails copyWith({ + int? id, + }) { + return TrashDetails( + id: id ?? this.id, + path: path, + dateMillis: dateMillis, + ); + } + + factory TrashDetails.fromMap(Map map) { + return TrashDetails( + id: map['id'] as int, + path: map['path'] as String, + dateMillis: map['dateMillis'] as int, + ); + } + + Map<String, dynamic> toMap() => { + 'id': id, + 'path': path, + 'dateMillis': dateMillis, + }; +} diff --git a/lib/model/multipage.dart b/lib/model/multipage.dart new file mode 100644 index 0000000..9755955 --- /dev/null +++ b/lib/model/multipage.dart @@ -0,0 +1,205 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/keys.dart'; +import 'package:aves/model/entry/extensions/multipage.dart'; +import 'package:aves/ref/mime_types.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; +import 'package:leak_tracker/leak_tracker.dart'; + +class MultiPageInfo { + final AvesEntry mainEntry; + final List<SinglePageInfo> _pages; + final Map<SinglePageInfo, AvesEntry> _pageEntries = {}; + final Set<AvesEntry> _transientEntries = <AvesEntry>{}; + + int get pageCount => _pages.length; + + MultiPageInfo({ + required this.mainEntry, + required List<SinglePageInfo> pages, + }) : _pages = pages { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectCreated( + library: 'aves', + className: '$MultiPageInfo', + object: this, + ); + } + if (_pages.isNotEmpty) { + _pages.sort(); + // make sure there is a page marked as default + if (defaultPage == null) { + final firstPage = _pages.removeAt(0); + _pages.insert(0, firstPage.copyWith(isDefault: true)); + } + + final stackedEntries = mainEntry.stackedEntries; + if (stackedEntries != null) { + _pageEntries.addEntries(pages.map((pageInfo) { + final pageEntry = stackedEntries.firstWhere((entry) => entry.uri == pageInfo.uri); + return MapEntry(pageInfo, pageEntry); + })); + } + } + } + + void dispose() { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectDisposed(object: this); + } + _transientEntries.forEach((entry) => entry.dispose()); + } + + factory MultiPageInfo.fromPageMaps(AvesEntry mainEntry, List<Map> pageMaps) { + return MultiPageInfo( + mainEntry: mainEntry, + pages: pageMaps.map(SinglePageInfo.fromMap).toList(), + ); + } + + SinglePageInfo? get defaultPage => _pages.firstWhereOrNull((page) => page.isDefault); + + SinglePageInfo? getById(int? pageId) => _pages.firstWhereOrNull((page) => page.pageId == pageId); + + SinglePageInfo? getByIndex(int? pageIndex) => _pages.firstWhereOrNull((page) => page.index == pageIndex); + + AvesEntry getPageEntryByIndex(int? pageIndex) => _getPageEntry(getByIndex(pageIndex)); + + AvesEntry _getPageEntry(SinglePageInfo? pageInfo) { + if (pageInfo != null) { + return _pageEntries.putIfAbsent(pageInfo, () => _createPageEntry(pageInfo)); + } else { + return mainEntry; + } + } + + Set<AvesEntry> get videoPageEntries => _pages.where((page) => page.isVideo).map(_getPageEntry).toSet(); + + List<AvesEntry> get exportEntries => _pages.map((pageInfo) => _createPageEntry(pageInfo, eraseDefaultPageId: false)).toList(); + + Future<void> extractMotionPhotoVideo() async { + final videoPage = _pages.firstWhereOrNull((page) => page.isVideo); + if (videoPage != null && videoPage.uri == null) { + final fields = await embeddedDataService.extractMotionPhotoVideo(mainEntry); + if (fields.containsKey(EntryFields.uri)) { + final pageIndex = _pages.indexOf(videoPage); + _pages.removeAt(pageIndex); + _pages.insert( + pageIndex, + videoPage.copyWith( + uri: fields[EntryFields.uri] as String?, + // the initial fake page may contain inaccurate values for the following fields + // so we override them with values from the extracted standalone video + rotationDegrees: fields[EntryFields.sourceRotationDegrees] as int?, + durationMillis: fields[EntryFields.durationMillis] as int?, + )); + _pageEntries.remove(videoPage); + } + } + } + + AvesEntry _createPageEntry(SinglePageInfo pageInfo, {bool eraseDefaultPageId = true}) { + // do not provide the page ID for the default page, + // so that we can treat this page like the main entry + // and retrieve cached images for it + final pageId = eraseDefaultPageId && pageInfo.isDefault ? null : pageInfo.pageId; + + // dynamically extracted video is not in the trash like the original motion photo + final trashed = (mainEntry.isMotionPhoto && pageInfo.isVideo) ? false : mainEntry.trashed; + + final pageEntry = AvesEntry( + id: mainEntry.id, + uri: pageInfo.uri ?? mainEntry.uri, + path: mainEntry.path, + contentId: mainEntry.contentId, + pageId: pageId, + sourceMimeType: pageInfo.mimeType, + width: pageInfo.width, + height: pageInfo.height, + sourceRotationDegrees: pageInfo.rotationDegrees ?? mainEntry.sourceRotationDegrees, + sizeBytes: mainEntry.sizeBytes, + sourceTitle: mainEntry.sourceTitle, + dateAddedSecs: mainEntry.dateAddedSecs, + dateModifiedMillis: mainEntry.dateModifiedMillis, + sourceDateTakenMillis: mainEntry.sourceDateTakenMillis, + durationMillis: pageInfo.durationMillis ?? mainEntry.durationMillis, + trashed: trashed, + origin: mainEntry.origin, + ) + ..catalogMetadata = mainEntry.catalogMetadata?.copyWith( + mimeType: pageInfo.mimeType, + isMultiPage: false, + rotationDegrees: pageInfo.rotationDegrees, + ) + ..addressDetails = mainEntry.addressDetails?.copyWith() + ..trashDetails = trashed ? mainEntry.trashDetails : null; + _transientEntries.add(pageEntry); + return pageEntry; + } + + @override + String toString() => '$runtimeType#${shortHash(this)}{mainEntry=$mainEntry, pages=$_pages}'; +} + +class SinglePageInfo implements Comparable<SinglePageInfo> { + final int index, pageId; + final bool isDefault; + final String? uri; + final String mimeType; + final int width, height; + final int? rotationDegrees, durationMillis; + + const SinglePageInfo({ + required this.index, + required this.pageId, + required this.isDefault, + this.uri, + required this.mimeType, + required this.width, + required this.height, + this.rotationDegrees, + this.durationMillis, + }); + + SinglePageInfo copyWith({ + bool? isDefault, + String? uri, + int? rotationDegrees, + int? durationMillis, + }) { + return SinglePageInfo( + index: index, + pageId: pageId, + isDefault: isDefault ?? this.isDefault, + uri: uri ?? this.uri, + mimeType: mimeType, + width: width, + height: height, + rotationDegrees: rotationDegrees ?? this.rotationDegrees, + durationMillis: durationMillis ?? this.durationMillis, + ); + } + + factory SinglePageInfo.fromMap(Map map) { + final index = map['page'] as int; + return SinglePageInfo( + index: index, + pageId: index, + isDefault: map['isDefault'] as bool? ?? false, + mimeType: map['mimeType'] as String, + width: map['width'] as int? ?? 0, + height: map['height'] as int? ?? 0, + rotationDegrees: map['rotationDegrees'] as int?, + durationMillis: map['durationMillis'] as int?, + ); + } + + bool get isVideo => MimeTypes.isVideo(mimeType); + + @override + String toString() => '$runtimeType#${shortHash(this)}{index=$index, pageId=$pageId, isDefault=$isDefault, uri=$uri, mimeType=$mimeType, width=$width, height=$height, rotationDegrees=$rotationDegrees, durationMillis=$durationMillis}'; + + @override + int compareTo(SinglePageInfo other) => index.compareTo(other.index); +} diff --git a/lib/model/naming_pattern.dart b/lib/model/naming_pattern.dart new file mode 100644 index 0000000..24882ee --- /dev/null +++ b/lib/model/naming_pattern.dart @@ -0,0 +1,277 @@ +import 'package:aves/convert/convert.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flutter/foundation.dart'; +import 'package:intl/intl.dart'; + +@immutable +class NamingPattern { + final List<NamingProcessor> processors; + + static final processorPattern = RegExp(r'<(.+?)(,(.+?))?>'); + static const processorOptionSeparator = ','; + static const optionKeyValueSeparator = '='; + + const NamingPattern(this.processors); + + factory NamingPattern.from({ + required String userPattern, + required int entryCount, + required String locale, + }) { + final processors = <NamingProcessor>[]; + + const defaultCounterStart = 1; + final defaultCounterPadding = '$entryCount'.length; + + var index = 0; + final matches = processorPattern.allMatches(userPattern); + matches.forEach((match) { + final start = match.start; + final end = match.end; + if (index < start) { + processors.add(LiteralNamingProcessor(userPattern.substring(index, start))); + index = start; + } + final processorKey = match.group(1); + final processorOptions = match.group(3); + switch (processorKey) { + case CounterNamingProcessor.key: + int? start, padding; + _applyProcessorOptions(processorOptions, (key, value) { + final valueInt = int.tryParse(value); + if (valueInt != null) { + switch (key) { + case CounterNamingProcessor.optionStart: + start = valueInt; + case CounterNamingProcessor.optionPadding: + padding = valueInt; + } + } + }); + processors.add(CounterNamingProcessor(start: start ?? defaultCounterStart, padding: padding ?? defaultCounterPadding)); + case DateNamingProcessor.key: + if (processorOptions != null) { + processors.add(DateNamingProcessor(processorOptions.trim(), locale)); + } + case HashNamingProcessor.key: + if (processorOptions != null) { + processors.add(HashNamingProcessor(processorOptions.trim())); + } + case MetadataFieldNamingProcessor.key: + if (processorOptions != null) { + processors.add(MetadataFieldNamingProcessor(processorOptions.trim())); + } + case NameNamingProcessor.key: + processors.add(const NameNamingProcessor()); + case TagsNamingProcessor.key: + processors.add(TagsNamingProcessor(processorOptions?.trim() ?? '')); + default: + debugPrint('unsupported naming processor: ${match.group(0)}'); + } + index = end; + }); + if (index < userPattern.length) { + processors.add(LiteralNamingProcessor(userPattern.substring(index, userPattern.length))); + } + + return NamingPattern(processors); + } + + static void _applyProcessorOptions(String? processorOptions, void Function(String key, String value) applyOption) { + if (processorOptions != null) { + processorOptions.split(processorOptionSeparator).map((v) => v.trim()).forEach((kv) { + final parts = kv.split(optionKeyValueSeparator); + if (parts.length >= 2) { + final key = parts[0]; + final value = parts.skip(1).join(optionKeyValueSeparator); + applyOption(key, value); + } + }); + } + } + + static int getInsertionOffset(String userPattern, int offset) { + offset = offset.clamp(0, userPattern.length); + final matches = processorPattern.allMatches(userPattern); + for (final match in matches) { + final start = match.start; + final end = match.end; + if (offset <= start) return offset; + if (offset <= end) return end; + } + return offset; + } + + static String defaultPatternFor(String processorKey) { + switch (processorKey) { + case DateNamingProcessor.key: + return '<$processorKey, yyyyMMdd-HHmmss>'; + case HashNamingProcessor.key: + return '<$processorKey, md5>'; + case TagsNamingProcessor.key: + return '<$processorKey, ->'; + case CounterNamingProcessor.key: + case NameNamingProcessor.key: + default: + if (processorKey.startsWith(MetadataFieldNamingProcessor.key)) { + final field = MetadataFieldNamingProcessor.fieldFromKey(processorKey); + return '<${MetadataFieldNamingProcessor.key}, $field>'; + } + return '<$processorKey>'; + } + } + + Future<String> apply(AvesEntry entry, int index) async { + final fields = processors.expand((v) => v.getRequiredFields()).toSet(); + final fieldValues = await metadataFetchService.getFields(entry, fields); + return processors.map((v) => v.process(entry, index, fieldValues) ?? '').join().trim(); + } +} + +@immutable +abstract class NamingProcessor extends Equatable { + const NamingProcessor(); + + String? process(AvesEntry entry, int index, Map<String, dynamic> fieldValues); + + Set<MetadataField> getRequiredFields() => {}; +} + +@immutable +class LiteralNamingProcessor extends NamingProcessor { + final String text; + + @override + List<Object?> get props => [text]; + + const LiteralNamingProcessor(this.text); + + @override + String? process(AvesEntry entry, int index, Map<String, dynamic> fieldValues) => text; +} + +@immutable +class DateNamingProcessor extends NamingProcessor { + static const key = 'date'; + + final DateFormat format; + + @override + List<Object?> get props => [format.pattern]; + + DateNamingProcessor(String pattern, String locale) : format = DateFormat(pattern, locale); + + @override + String? process(AvesEntry entry, int index, Map<String, dynamic> fieldValues) { + final date = entry.bestDate; + return date != null ? format.format(date) : null; + } +} + +@immutable +class TagsNamingProcessor extends NamingProcessor { + static const key = 'tags'; + static const defaultSeparator = ' '; + + final String separator; + + @override + List<Object?> get props => [separator]; + + TagsNamingProcessor(String separator) : separator = separator.isEmpty ? defaultSeparator : separator; + + @override + String? process(AvesEntry entry, int index, Map<String, dynamic> fieldValues) { + return entry.tags.join(separator); + } +} + +@immutable +class MetadataFieldNamingProcessor extends NamingProcessor { + static const key = 'field'; + + static String keyWithField(MetadataField field) => '$key-${field.name}'; + + // loose, for user to see and later parse + static String fieldFromKey(String keyWithField) => keyWithField.substring(key.length + 1); + + late final MetadataField? field; + + @override + List<Object?> get props => [field]; + + MetadataFieldNamingProcessor(String field) { + final lowerField = field.toLowerCase(); + this.field = MetadataField.values.firstWhereOrNull((v) => v.name.toLowerCase() == lowerField); + } + + @override + Set<MetadataField> getRequiredFields() => {field}.nonNulls.toSet(); + + @override + String? process(AvesEntry entry, int index, Map<String, dynamic> fieldValues) { + return fieldValues[field?.toPlatform]?.toString(); + } +} + +@immutable +class NameNamingProcessor extends NamingProcessor { + static const key = 'name'; + + @override + List<Object?> get props => []; + + const NameNamingProcessor(); + + @override + String? process(AvesEntry entry, int index, Map<String, dynamic> fieldValues) => entry.filenameWithoutExtension; +} + +@immutable +class CounterNamingProcessor extends NamingProcessor { + final int start; + final int padding; + + static const key = 'counter'; + static const optionStart = 'start'; + static const optionPadding = 'padding'; + + @override + List<Object?> get props => [start, padding]; + + const CounterNamingProcessor({ + required this.start, + required this.padding, + }); + + @override + String? process(AvesEntry entry, int index, Map<String, dynamic> fieldValues) => '${index + start}'.padLeft(padding, '0'); +} + +@immutable +class HashNamingProcessor extends NamingProcessor { + static const key = 'hash'; + static const optionFunction = 'function'; + + late final MetadataField? function; + + @override + List<Object?> get props => [function]; + + HashNamingProcessor(String function) { + final lowerField = 'hash${function.toLowerCase()}'; + this.function = MetadataField.values.firstWhereOrNull((v) => v.name.toLowerCase() == lowerField); + } + + @override + Set<MetadataField> getRequiredFields() => {function}.nonNulls.toSet(); + + @override + String? process(AvesEntry entry, int index, Map<String, dynamic> fieldValues) { + return fieldValues[function?.toPlatform]?.toString(); + } +} diff --git a/lib/model/query.dart b/lib/model/query.dart new file mode 100644 index 0000000..fa468f1 --- /dev/null +++ b/lib/model/query.dart @@ -0,0 +1,49 @@ +import 'dart:async'; + +import 'package:aves_utils/aves_utils.dart'; +import 'package:flutter/foundation.dart'; + +class Query extends ChangeNotifier { + final AChangeNotifier _focusRequestNotifier = AChangeNotifier(); + final ValueNotifier<String> _queryNotifier = ValueNotifier(''); + final StreamController<bool> _enabledStreamController = StreamController.broadcast(); + + Query({required bool enabled, required String? initialValue}) { + if (kFlutterMemoryAllocationsEnabled) ChangeNotifier.maybeDispatchObjectCreation(this); + _enabled = enabled; + if (initialValue != null && initialValue.isNotEmpty) { + _enabled = true; + queryNotifier.value = initialValue; + } + } + + @override + void dispose() { + _focusRequestNotifier.dispose(); + _queryNotifier.dispose(); + super.dispose(); + } + + bool _enabled = false; + + bool get enabled => _enabled; + + set enabled(bool value) { + _enabled = value; + _enabledStreamController.add(_enabled); + queryNotifier.value = ''; + notifyListeners(); + + if (_enabled) { + focusRequestNotifier.notifyListeners(); + } + } + + void toggle() => enabled = !enabled; + + Stream<bool> get enabledStream => _enabledStreamController.stream; + + AChangeNotifier get focusRequestNotifier => _focusRequestNotifier; + + ValueNotifier<String> get queryNotifier => _queryNotifier; +} diff --git a/lib/model/selection.dart b/lib/model/selection.dart new file mode 100644 index 0000000..fbb6014 --- /dev/null +++ b/lib/model/selection.dart @@ -0,0 +1,58 @@ +import 'package:flutter/foundation.dart'; + +class Selection<T> extends ChangeNotifier { + bool _isSelecting = false; + + bool get isSelecting => _isSelecting; + + final Set<T> _selectedItems = {}; + + Set<T> get selectedItems => _selectedItems; + + Selection() { + if (kFlutterMemoryAllocationsEnabled) ChangeNotifier.maybeDispatchObjectCreation(this); + } + + void browse() { + if (!_isSelecting) return; + _isSelecting = false; + notifyListeners(); + } + + void select() { + if (_isSelecting) return; + // clear selection on `select`, not on `browse`, so that + // the selection count is stable when transitioning to browse + clearSelection(); + _isSelecting = true; + notifyListeners(); + } + + bool isSelected(Iterable<T> items) => items.every(selectedItems.contains); + + void addToSelection(Iterable<T> items) { + if (items.isEmpty) return; + + select(); + _selectedItems.addAll(items); + notifyListeners(); + } + + void removeFromSelection(Iterable<T> items) { + if (items.isEmpty) return; + + _selectedItems.removeAll(items); + notifyListeners(); + } + + void clearSelection() { + _selectedItems.clear(); + notifyListeners(); + } + + void toggleSelection(T item) { + if (!_isSelecting) select(); + if (!_selectedItems.remove(item)) _selectedItems.add(item); + notifyListeners(); + } +} diff --git a/lib/model/settings/defaults.dart b/lib/model/settings/defaults.dart new file mode 100644 index 0000000..b758b99 --- /dev/null +++ b/lib/model/settings/defaults.dart @@ -0,0 +1,145 @@ +import 'package:aves/model/filters/favourite.dart'; +import 'package:aves/model/filters/mime.dart'; +import 'package:aves/model/filters/recent.dart'; +import 'package:aves/model/naming_pattern.dart'; +import 'package:aves/ref/mime_types.dart'; +import 'package:aves/widgets/collection/collection_page.dart'; +import 'package:aves/widgets/explorer/explorer_page.dart'; +import 'package:aves/widgets/filter_grids/albums_page.dart'; +import 'package:aves/widgets/filter_grids/countries_page.dart'; +import 'package:aves/widgets/filter_grids/tags_page.dart'; +import 'package:aves/widgets/navigation/nav_item.dart'; +import 'package:aves_model/aves_model.dart'; + +class SettingsDefaults { + // app + static const hasAcceptedTerms = false; + static const canUseAnalysisService = true; + static const isInstalledAppAccessAllowed = false; + static const isErrorReportingAllowed = false; + static const tileLayout = TileLayout.grid; + static const entryRenamingPattern = '<${DateNamingProcessor.key}, yyyyMMdd-HHmmss> <${NameNamingProcessor.key}>'; + + // display + static const displayRefreshRateMode = DisplayRefreshRateMode.auto; + static const themeBrightness = AvesThemeBrightness.system; + static const themeColorMode = AvesThemeColorMode.polychrome; + static const enableDynamicColor = false; + static const enableBlurEffect = true; // `enableBlurEffect` has a contextual default value + static const maxBrightness = MaxBrightness.never; + static const forceTvLayout = false; + + // navigation + static const mustBackTwiceToExit = true; + static const keepScreenOn = KeepScreenOn.viewerOnly; + static const homePage = HomePageSetting.collection; + static const confirm = true; + static const setMetadataDateBeforeFileOp = false; + static final drawerTypeBookmarks = [ + null, + RecentlyAddedFilter.instance, + ]; + static const drawerPageBookmarks = [ + AlbumListPage.routeName, + CountryListPage.routeName, + TagListPage.routeName, + ExplorerPage.routeName, + ]; + static final bottomNavigationActions = [ + const AvesNavItem(route: CollectionPage.routeName), + AvesNavItem(route: CollectionPage.routeName, filters: {MimeFilter.video}), + AvesNavItem(route: CollectionPage.routeName, filters: {FavouriteFilter.instance}), + const AvesNavItem(route: AlbumListPage.routeName), + ]; + + // collection + static const collectionSectionFactor = EntrySectionFactor.month; + static const collectionSortFactor = EntrySortFactor.date; + static const collectionBrowsingQuickActions = [ + EntrySetAction.searchCollection, + ]; + static const collectionSelectionQuickActions = [ + EntrySetAction.share, + EntrySetAction.delete, + ]; + static const showThumbnailFavourite = true; + static const showThumbnailHdr = true; + static const thumbnailLocationIcon = ThumbnailOverlayLocationIcon.none; + static const thumbnailTagIcon = ThumbnailOverlayTagIcon.none; + static const showThumbnailMotionPhoto = true; + static const showThumbnailRating = true; + static const showThumbnailRaw = true; + static const showThumbnailVideoDuration = true; + + // filter grids + static const albumGroupFactor = AlbumChipSectionFactor.importance; + static const chipListSortFactor = ChipSortFactor.name; + + // viewer + static const viewerQuickActions = [ + EntryAction.rotateScreen, + EntryAction.toggleFavourite, + EntryAction.share, + EntryAction.delete, + ]; + static const showOverlayOnOpening = true; + static const showOverlayMinimap = false; + static const showOverlayZoomLevel = false; + static const overlayHistogramStyle = OverlayHistogramStyle.none; + static const showOverlayInfo = true; + static const showOverlayDescription = false; + static const showOverlayRatingTags = false; + static const showOverlayShootingDetails = false; + static const showOverlayThumbnailPreview = false; + static const viewerGestureSideTapNext = false; + static const viewerUseCutout = true; + static const enableMotionPhotoAutoPlay = false; + + // info + static const infoMapZoom = 12.0; + static const coordinateFormat = CoordinateFormat.dms; + static const unitSystem = UnitSystem.metric; + + // tag editor + + static const tagEditorCurrentFilterSectionExpanded = true; + + // converter + + static const convertMimeType = MimeTypes.jpeg; + static const convertQuality = 95; + static const convertWriteMetadata = true; + + // rendering + static const imageBackground = EntryBackground.white; + + // search + static const saveSearchHistory = true; + + // bin + static const enableBin = true; + + // accessibility + static const showPinchGestureAlternatives = false; + static const accessibilityAnimations = AccessibilityAnimations.system; + static const timeToTakeAction = AccessibilityTimeout.s3; + + // slideshow + static const slideshowRepeat = false; + static const slideshowShuffle = false; + static const slideshowFillScreen = false; + static const slideshowAnimatedZoomEffect = true; + static const slideshowTransition = ViewerTransition.fade; + static const slideshowVideoPlayback = SlideshowVideoPlayback.playMuted; + static const slideshowInterval = 5; + + // widget + static const widgetOutline = false; + static const widgetShape = WidgetShape.rrect; + static const widgetOpenPage = WidgetOpenPage.viewer; + static const widgetDisplayedItem = WidgetDisplayedItem.random; + + // platform settings + static const isRotationLocked = false; + static const areAnimationsRemoved = false; +} diff --git a/lib/model/settings/enums/accessibility_animations.dart b/lib/model/settings/enums/accessibility_animations.dart new file mode 100644 index 0000000..25f9e0f --- /dev/null +++ b/lib/model/settings/enums/accessibility_animations.dart @@ -0,0 +1,32 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/widgets.dart'; + +extension ExtraAccessibilityAnimations on AccessibilityAnimations { + bool get animate { + switch (this) { + case AccessibilityAnimations.system: + // as of Flutter v2.5.1, the check for `disableAnimations` is unreliable + // so we cannot use `window.accessibilityFeatures.disableAnimations` nor `MediaQuery.of(context).disableAnimations` + return !settings.areAnimationsRemoved; + case AccessibilityAnimations.disabled: + return false; + case AccessibilityAnimations.enabled: + return true; + } + } + + Duration get popUpAnimationDuration => animate ? ADurations.popupMenuAnimation : Duration.zero; + + Duration get popUpAnimationDelay => popUpAnimationDuration + const Duration(milliseconds: ADurations.transitionMarginMillis); + + AnimationStyle get popUpAnimationStyle { + return animate + ? AnimationStyle( + curve: Curves.easeInOutCubic, + duration: popUpAnimationDuration, + ) + : AnimationStyle.noAnimation; + } +} diff --git a/lib/model/settings/enums/accessibility_timeout.dart b/lib/model/settings/enums/accessibility_timeout.dart new file mode 100644 index 0000000..dddd22b --- /dev/null +++ b/lib/model/settings/enums/accessibility_timeout.dart @@ -0,0 +1,26 @@ +import 'package:aves/services/accessibility_service.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves_model/aves_model.dart'; + +extension ExtraAccessibilityTimeout on AccessibilityTimeout { + Future<Duration> getSnackBarDuration(bool hasAction) async { + switch (this) { + case AccessibilityTimeout.system: + if (hasAction) { + return Duration(milliseconds: await (AccessibilityService.getRecommendedTimeToTakeAction(ADurations.opToastActionDisplay))); + } else { + return Duration(milliseconds: await (AccessibilityService.getRecommendedTimeToRead(ADurations.opToastTextDisplay))); + } + case AccessibilityTimeout.s1: + return const Duration(seconds: 1); + case AccessibilityTimeout.s3: + return const Duration(seconds: 3); + case AccessibilityTimeout.s5: + return const Duration(seconds: 5); + case AccessibilityTimeout.s10: + return const Duration(seconds: 10); + case AccessibilityTimeout.s30: + return const Duration(seconds: 30); + } + } +} diff --git a/lib/model/settings/enums/coordinate_format.dart b/lib/model/settings/enums/coordinate_format.dart new file mode 100644 index 0000000..2572bac --- /dev/null +++ b/lib/model/settings/enums/coordinate_format.dart @@ -0,0 +1,95 @@ +import 'package:aves/l10n/l10n.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/widgets.dart'; +import 'package:intl/intl.dart'; +import 'package:latlong2/latlong.dart'; + +extension ExtraCoordinateFormat on CoordinateFormat { + static const _separator = ', '; + + String format(BuildContext context, LatLng latLng, {bool minuteSecondPadding = false, int? dmsSecondDecimals}) { + final text = formatWithoutDirectionality(context.l10n, latLng, minuteSecondPadding: minuteSecondPadding, dmsSecondDecimals: dmsSecondDecimals); + return context.applyDirectionality(text); + } + + String formatWithoutDirectionality(AppLocalizations l10n, LatLng latLng, {bool minuteSecondPadding = false, int? dmsSecondDecimals}) { + switch (this) { + case CoordinateFormat.dms: + return toDMS(l10n, latLng, minuteSecondPadding: minuteSecondPadding, secondDecimals: dmsSecondDecimals ?? 2).join(_separator); + case CoordinateFormat.ddm: + return toDDM(l10n, latLng, minutePadding: minuteSecondPadding, minuteDecimals: dmsSecondDecimals ?? 4).join(_separator); + case CoordinateFormat.decimal: + return _toDecimal(l10n, latLng).join(_separator); + } + } + + // returns coordinates formatted as DMS, e.g. ['41° 24′ 12.2″ N', '2° 10′ 26.5″ E'] + static List<String> toDMS(AppLocalizations l10n, LatLng latLng, {bool minuteSecondPadding = false, int secondDecimals = 2}) { + final locale = l10n.localeName; + final lat = latLng.latitude; + final lng = latLng.longitude; + final latSexa = _decimal2sexagesimal(lat, minuteSecondPadding, secondDecimals, locale); + final lngSexa = _decimal2sexagesimal(lng, minuteSecondPadding, secondDecimals, locale); + return [ + l10n.coordinateDms(latSexa, lat < 0 ? l10n.coordinateDmsSouth : l10n.coordinateDmsNorth), + l10n.coordinateDms(lngSexa, lng < 0 ? l10n.coordinateDmsWest : l10n.coordinateDmsEast), + ]; + } + + // returns coordinates formatted as DDM, e.g. ['41° 24.2028′ N', '2° 10.4418′ E'] + static List<String> toDDM(AppLocalizations l10n, LatLng latLng, {bool minutePadding = false, int minuteDecimals = 4}) { + final locale = l10n.localeName; + final lat = latLng.latitude; + final lng = latLng.longitude; + final latSexa = _decimal2ddm(lat, minutePadding, minuteDecimals, locale); + final lngSexa = _decimal2ddm(lng, minutePadding, minuteDecimals, locale); + return [ + l10n.coordinateDms(latSexa, lat < 0 ? l10n.coordinateDmsSouth : l10n.coordinateDmsNorth), + l10n.coordinateDms(lngSexa, lng < 0 ? l10n.coordinateDmsWest : l10n.coordinateDmsEast), + ]; + } + + static String _decimal2sexagesimal( + double degDecimal, + bool minuteSecondPadding, + int secondDecimals, + String locale, + ) { + final degAbs = degDecimal.abs(); + final deg = degAbs.toInt(); + final minDecimal = (degAbs - deg) * 60; + final min = minDecimal.toInt(); + final sec = (minDecimal - min) * 60; + + final degText = NumberFormat('0', locale).format(deg); + final minText = NumberFormat('0' * (minuteSecondPadding ? 2 : 1), locale).format(min); + final secText = NumberFormat('${'0' * (minuteSecondPadding ? 2 : 1)}${secondDecimals > 0 ? '.${'0' * secondDecimals}' : ''}', locale).format(sec); + + return '$degText° $minText′ $secText″'; + } + + static String _decimal2ddm( + double degDecimal, + bool minutePadding, + int minuteDecimals, + String locale, + ) { + final degAbs = degDecimal.abs(); + final deg = degAbs.toInt(); + final min = (degAbs - deg) * 60; + + final degText = NumberFormat('0', locale).format(deg); + final minText = NumberFormat('${'0' * (minutePadding ? 2 : 1)}${minuteDecimals > 0 ? '.${'0' * minuteDecimals}' : ''}', locale).format(min); + + return '$degText° $minText′'; + } + + static List<String> _toDecimal(AppLocalizations l10n, LatLng latLng) { + final coordinateFormatter = NumberFormat('0.000000°', l10n.localeName); + return [ + coordinateFormatter.format(latLng.latitude), + coordinateFormatter.format(latLng.longitude), + ]; + } +} diff --git a/lib/model/settings/enums/display_refresh_rate_mode.dart b/lib/model/settings/enums/display_refresh_rate_mode.dart new file mode 100644 index 0000000..32d1cd2 --- /dev/null +++ b/lib/model/settings/enums/display_refresh_rate_mode.dart @@ -0,0 +1,24 @@ +import 'package:aves/services/common/services.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:device_info_plus/device_info_plus.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter_displaymode/flutter_displaymode.dart'; + +extension ExtraDisplayRefreshRateMode on DisplayRefreshRateMode { + Future<void> apply() async { + if (!await windowService.isActivity()) return; + + final androidInfo = await DeviceInfoPlugin().androidInfo; + if (androidInfo.version.sdkInt < 23) return; + + debugPrint('Apply display refresh rate: $name'); + switch (this) { + case DisplayRefreshRateMode.auto: + await FlutterDisplayMode.setPreferredMode(DisplayMode.auto); + case DisplayRefreshRateMode.highest: + await FlutterDisplayMode.setHighRefreshRate(); + case DisplayRefreshRateMode.lowest: + await FlutterDisplayMode.setLowRefreshRate(); + } + } +} diff --git a/lib/model/settings/enums/entry_background.dart b/lib/model/settings/enums/entry_background.dart new file mode 100644 index 0000000..9661c4d --- /dev/null +++ b/lib/model/settings/enums/entry_background.dart @@ -0,0 +1,25 @@ +import 'dart:ui'; + +import 'package:aves_model/aves_model.dart'; + +extension ExtraEntryBackground on EntryBackground { + bool get isColor { + switch (this) { + case EntryBackground.black: + case EntryBackground.white: + return true; + default: + return false; + } + } + + Color get color { + switch (this) { + case EntryBackground.white: + return const Color(0xFFFFFFFF); + case EntryBackground.black: + default: + return const Color(0xFF000000); + } + } +} diff --git a/lib/model/settings/enums/screen_on.dart b/lib/model/settings/enums/screen_on.dart new file mode 100644 index 0000000..2d6e63b --- /dev/null +++ b/lib/model/settings/enums/screen_on.dart @@ -0,0 +1,8 @@ +import 'package:aves/services/common/services.dart'; +import 'package:aves_model/aves_model.dart'; + +extension ExtraKeepScreenOn on KeepScreenOn { + void apply() { + windowService.keepScreenOn(this == KeepScreenOn.always); + } +} diff --git a/lib/model/settings/enums/subtitle_position.dart b/lib/model/settings/enums/subtitle_position.dart new file mode 100644 index 0000000..a37ad72 --- /dev/null +++ b/lib/model/settings/enums/subtitle_position.dart @@ -0,0 +1,13 @@ +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/painting.dart'; + +extension ExtraSubtitlePosition on SubtitlePosition { + TextAlignVertical toTextAlignVertical() { + switch (this) { + case SubtitlePosition.top: + return TextAlignVertical.top; + case SubtitlePosition.bottom: + return TextAlignVertical.bottom; + } + } +} diff --git a/lib/model/settings/enums/theme_brightness.dart b/lib/model/settings/enums/theme_brightness.dart new file mode 100644 index 0000000..5bcbd75 --- /dev/null +++ b/lib/model/settings/enums/theme_brightness.dart @@ -0,0 +1,16 @@ +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; + +extension ExtraAvesThemeBrightness on AvesThemeBrightness { + ThemeMode get appThemeMode { + switch (this) { + case AvesThemeBrightness.system: + return ThemeMode.system; + case AvesThemeBrightness.light: + return ThemeMode.light; + case AvesThemeBrightness.dark: + case AvesThemeBrightness.black: + return ThemeMode.dark; + } + } +} diff --git a/lib/model/settings/enums/viewer_transition.dart b/lib/model/settings/enums/viewer_transition.dart new file mode 100644 index 0000000..b9c0cc0 --- /dev/null +++ b/lib/model/settings/enums/viewer_transition.dart @@ -0,0 +1,63 @@ +import 'dart:math'; + +import 'package:aves/widgets/viewer/controls/transitions.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/widgets.dart'; + +extension ExtraViewerTransition on ViewerTransition { + TransitionBuilder builder(PageController pageController, int index) { + switch (this) { + case ViewerTransition.slide: + return PageTransitionEffects.slide(pageController, index, parallax: false); + case ViewerTransition.parallax: + return PageTransitionEffects.slide(pageController, index, parallax: true); + case ViewerTransition.fade: + return PageTransitionEffects.fade(pageController, index, zoomIn: false); + case ViewerTransition.zoomIn: + return PageTransitionEffects.fade(pageController, index, zoomIn: true); + case ViewerTransition.none: + return PageTransitionEffects.none(pageController, index); + case ViewerTransition.random: + return _ViewerTransitionRandomizer.getBuilder(pageController, index); + } + } +} + +class _ViewerTransitionRandomizer { + static const options = [ + ViewerTransition.slide, + ViewerTransition.parallax, + ViewerTransition.fade, + ViewerTransition.zoomIn, + ]; + + static final List<(int, ViewerTransition)> _indexedTransitions = []; + + static TransitionBuilder getBuilder( + PageController pageController, + int index, + ) => + (context, child) { + final negative = pageController.hasClients && pageController.position.haveDimensions && (pageController.page! - index).isNegative; + final transition = _getTransition(negative ? index - 1 : index); + final builder = transition.builder(pageController, index); + return builder(context, child); + }; + + static ViewerTransition _getTransition(int transitionIndex) { + var indexedTransition = _indexedTransitions.firstWhereOrNull((v) => v.$1 == transitionIndex); + if (indexedTransition != null) { + _indexedTransitions.remove(indexedTransition); + } else { + indexedTransition = (transitionIndex, options[Random().nextInt(options.length)]); + } + _indexedTransitions.insert(0, indexedTransition); + while (_indexedTransitions.length > 3) { + _indexedTransitions.removeLast(); + } + + final (_, transition) = indexedTransition; + return transition; + } +} diff --git a/lib/model/settings/enums/widget_outline.dart b/lib/model/settings/enums/widget_outline.dart new file mode 100644 index 0000000..660d66d --- /dev/null +++ b/lib/model/settings/enums/widget_outline.dart @@ -0,0 +1,33 @@ +import 'package:aves_model/aves_model.dart'; +import 'package:dynamic_color/dynamic_color.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; + +extension ExtraWidgetOutline on WidgetOutline { + Future<Color?> color(Brightness brightness) async { + switch (this) { + case WidgetOutline.none: + return SynchronousFuture(null); + case WidgetOutline.black: + return SynchronousFuture(Colors.black); + case WidgetOutline.white: + return SynchronousFuture(Colors.white); + case WidgetOutline.systemBlackAndWhite: + return SynchronousFuture(brightness == Brightness.dark ? Colors.black : Colors.white); + case WidgetOutline.systemBlackAndWhiteHighContrast: + return SynchronousFuture(brightness == Brightness.dark ? Colors.white : Colors.black); + case WidgetOutline.systemDynamicLowContrast: + final color = await _getDynamicColor(brightness == Brightness.dark ? Brightness.light : Brightness.dark); + return color ?? await WidgetOutline.systemBlackAndWhite.color(brightness); + case WidgetOutline.systemDynamic: + final color = await _getDynamicColor(brightness); + return color ?? await WidgetOutline.systemBlackAndWhiteHighContrast.color(brightness); + } + } + + Future<Color?> _getDynamicColor(Brightness brightness) async { + final corePalette = await DynamicColorPlugin.getCorePalette(); + final scheme = corePalette?.toColorScheme(brightness: brightness); + return scheme?.primary; + } +} diff --git a/lib/model/settings/enums/widget_shape.dart b/lib/model/settings/enums/widget_shape.dart new file mode 100644 index 0000000..5a7b88f --- /dev/null +++ b/lib/model/settings/enums/widget_shape.dart @@ -0,0 +1,199 @@ +import 'dart:math'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/painting.dart'; + +extension ExtraWidgetShape on WidgetShape { + static const double _defaultCornerRadius = 24; + + Path path(Size widgetSize, double devicePixelRatio, {double? cornerRadiusPx}) { + final rect = Offset.zero & widgetSize; + switch (this) { + case WidgetShape.bumpyColumns: + return _buildBumpyColumnsPath(rect); + case WidgetShape.bumpyRows: + return _buildBumpyRowsPath(rect); + case WidgetShape.circle: + return Path() + ..addOval(Rect.fromCircle( + center: rect.center, + radius: rect.shortestSide / 2, + )); + case WidgetShape.concaveSquare: + return _buildConcaveSquarePath(rect); + case WidgetShape.heart: + return _buildHeartPath(rect); + case WidgetShape.rrect: + return Path()..addRRect(BorderRadius.circular(cornerRadiusPx ?? (_defaultCornerRadius * devicePixelRatio)).toRRect(rect)); + case WidgetShape.tearRectLeft: + final radius = cornerRadiusPx ?? (_defaultCornerRadius * devicePixelRatio); + return _buildTearRectPath(rect, topLeftRadiusPx: radius, topRightRadiusPx: radius * 2); + case WidgetShape.tearRectRight: + final radius = cornerRadiusPx ?? (_defaultCornerRadius * devicePixelRatio); + return _buildTearRectPath(rect, topLeftRadiusPx: radius * 2, topRightRadiusPx: radius); + case WidgetShape.wavyCircle16: + return _buildWavyCirclePath(rect, 16, .5); + } + } + + Path _buildBumpyColumnsPath(Rect rect) { + final radius = rect.width / 4; + final topY = radius; + final bottomY = rect.height - radius; + const angleUnit = pi / 6; + return Path() + ..moveTo(0, topY) + ..arcTo(Rect.fromCircle(center: Offset(radius, topY), radius: radius), -6 * angleUnit, 4 * angleUnit, false) + ..arcTo(Rect.fromCircle(center: Offset(radius * 2, topY), radius: radius), -4 * angleUnit, 2 * angleUnit, false) + ..arcTo(Rect.fromCircle(center: Offset(radius * 3, topY), radius: radius), -4 * angleUnit, 4 * angleUnit, false) + ..lineTo(rect.width, bottomY) + ..arcTo(Rect.fromCircle(center: Offset(radius * 3, bottomY), radius: radius), 0, 4 * angleUnit, false) + ..arcTo(Rect.fromCircle(center: Offset(radius * 2, bottomY), radius: radius), 2 * angleUnit, 2 * angleUnit, false) + ..arcTo(Rect.fromCircle(center: Offset(radius, bottomY), radius: radius), 2 * angleUnit, 4 * angleUnit, false) + ..lineTo(0, topY); + } + + Path _buildBumpyRowsPath(Rect rect) { + final radius = rect.height / 4; + final leftX = radius; + final rightX = rect.width - radius; + const angleUnit = pi / 6; + return Path() + ..moveTo(leftX, 0) + ..lineTo(rightX, 0) + ..arcTo(Rect.fromCircle(center: Offset(rightX, radius), radius: radius), -3 * angleUnit, 4 * angleUnit, false) + ..arcTo(Rect.fromCircle(center: Offset(rightX, radius * 2), radius: radius), -angleUnit, 2 * angleUnit, false) + ..arcTo(Rect.fromCircle(center: Offset(rightX, radius * 3), radius: radius), -angleUnit, 4 * angleUnit, false) + ..lineTo(leftX, rect.height) + ..arcTo(Rect.fromCircle(center: Offset(leftX, radius * 3), radius: radius), 3 * angleUnit, 4 * angleUnit, false) + ..arcTo(Rect.fromCircle(center: Offset(leftX, radius * 2), radius: radius), 5 * angleUnit, 2 * angleUnit, false) + ..arcTo(Rect.fromCircle(center: Offset(leftX, radius), radius: radius), 5 * angleUnit, 4 * angleUnit, false); + } + + Path _buildConcaveSquarePath(Rect rect) { + final center = rect.center; + final dim = rect.shortestSide; + final radius = dim / 4; + + final tl = center + Offset(-radius, -radius); + final tr = center + Offset(radius, -radius); + final br = center + Offset(radius, radius); + final bl = center + Offset(-radius, radius); + + final outsideDim = radius * (1 + sqrt(3)); + final left = center + Offset(-outsideDim, 0); + final top = center + Offset(0, -outsideDim); + final right = center + Offset(outsideDim, 0); + final bottom = center + Offset(0, outsideDim); + + final tlTop = (tl + top) / 2; + final topTr = (top + tr) / 2; + final trRight = (tr + right) / 2; + final rightBr = (right + br) / 2; + final brBottom = (br + bottom) / 2; + final bottomBl = (bottom + bl) / 2; + final blLeft = (bl + left) / 2; + final leftTl = (left + tl) / 2; + + final r = Radius.circular(radius); + return Path() + ..moveTo(tlTop.dx, tlTop.dy) + ..arcToPoint(topTr, radius: r, clockwise: false) + ..arcToPoint(trRight, radius: r) + ..arcToPoint(rightBr, radius: r, clockwise: false) + ..arcToPoint(brBottom, radius: r) + ..arcToPoint(bottomBl, radius: r, clockwise: false) + ..arcToPoint(blLeft, radius: r) + ..arcToPoint(leftTl, radius: r, clockwise: false) + ..arcToPoint(tlTop, radius: r); + } + + Path _buildHeartPath(Rect rect) { + final center = rect.center; + final dim = rect.shortestSide; + const p0dy = -.4; + const p1dx = .5; + const p1dy = -.4; + const p2dx = .8; + const p2dy = .5; + const p3dy = .5 - p0dy; + return Path() + ..moveTo(center.dx, center.dy) + ..relativeMoveTo(0, dim * p0dy) + ..relativeCubicTo(dim * -p1dx, dim * p1dy, dim * -p2dx, dim * p2dy, 0, dim * p3dy) + ..moveTo(center.dx, center.dy) + ..relativeMoveTo(0, dim * p0dy) + ..relativeCubicTo(dim * p1dx, dim * p1dy, dim * p2dx, dim * p2dy, 0, dim * p3dy); + } + + Path _buildTearRectPath(Rect rect, {required double topLeftRadiusPx, required double topRightRadiusPx}) { + final topLeftRadius = Radius.circular(topLeftRadiusPx); + final topRightRadius = Radius.circular(topRightRadiusPx); + return Path() + ..addRRect(BorderRadius.only( + topLeft: topLeftRadius, + topRight: topRightRadius, + bottomLeft: topRightRadius, + bottomRight: topLeftRadius, + ).toRRect(rect)); + } + + Path _buildWavyCirclePath(Rect rect, int bumpCount, double amplitudeFactor, {double angleOffset = 0}) { + final center = rect.center; + final dim = rect.shortestSide; + + final waveAmplitude = amplitudeFactor / bumpCount; + final circleRadius = (dim / 2) * (1 - waveAmplitude); + + final pointCount = (dim * dim).round(); + final angleIncrement = 2 * pi / pointCount; + final points = List.generate(pointCount, (i) { + final t = angleIncrement * i; + final r = cos((t + angleOffset) * bumpCount) * waveAmplitude + 1; + final dx = r * cos(t) * circleRadius; + final dy = r * sin(t) * circleRadius; + return Offset(center.dx + dx, center.dy + dy); + }); + final origin = points.first; + + final path = Path()..moveTo(origin.dx, origin.dy); + for (var i = 0; i <= pointCount; i++) { + final p = points[i % pointCount]; + path.lineTo(p.dx, p.dy); + } + return path; + } + + double extentPx(Size widgetSizePx, AvesEntry entry) { + switch (this) { + case WidgetShape.bumpyColumns: + case WidgetShape.bumpyRows: + case WidgetShape.rrect: + case WidgetShape.tearRectLeft: + case WidgetShape.tearRectRight: + final entryRatio = entry.displayAspectRatio; + final widgetRatio = widgetSizePx.width / widgetSizePx.height; + if (entryRatio > 1) { + // landscape entry, must return thumbnail height as extent + if (widgetRatio > entryRatio) { + return widgetSizePx.width / entryRatio; + } else { + return widgetSizePx.height; + } + } else { + // portrait entry, must return thumbnail width as extent + if (widgetRatio > entryRatio) { + return widgetSizePx.width; + } else { + return widgetSizePx.height * entryRatio; + } + } + case WidgetShape.circle: + case WidgetShape.heart: + case WidgetShape.wavyCircle16: + case WidgetShape.concaveSquare: + return widgetSizePx.shortestSide; + } + } +} diff --git a/lib/model/settings/modules/app.dart b/lib/model/settings/modules/app.dart new file mode 100644 index 0000000..53ea9c1 --- /dev/null +++ b/lib/model/settings/modules/app.dart @@ -0,0 +1,142 @@ +import 'package:aves/model/filters/covered/tag.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/settings/defaults.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/model/vaults/vaults.dart'; +import 'package:aves/widgets/aves_app.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/widgets.dart'; + +mixin AppSettings on SettingsAccess { + static const int recentFilterHistoryMax = 20; + + void initAppSettings() { + vaults.addListener(_onVaultsChanged); + } + + bool get hasAcceptedTerms => getBool(SettingKeys.hasAcceptedTermsKey) ?? SettingsDefaults.hasAcceptedTerms; + + set hasAcceptedTerms(bool newValue) => set(SettingKeys.hasAcceptedTermsKey, newValue); + + bool get canUseAnalysisService => getBool(SettingKeys.canUseAnalysisServiceKey) ?? SettingsDefaults.canUseAnalysisService; + + set canUseAnalysisService(bool newValue) => set(SettingKeys.canUseAnalysisServiceKey, newValue); + + bool get isInstalledAppAccessAllowed => getBool(SettingKeys.isInstalledAppAccessAllowedKey) ?? SettingsDefaults.isInstalledAppAccessAllowed; + + set isInstalledAppAccessAllowed(bool newValue) => set(SettingKeys.isInstalledAppAccessAllowedKey, newValue); + + bool get isErrorReportingAllowed => getBool(SettingKeys.isErrorReportingAllowedKey) ?? SettingsDefaults.isErrorReportingAllowed; + + set isErrorReportingAllowed(bool newValue) => set(SettingKeys.isErrorReportingAllowedKey, newValue); + + static const localeSeparator = '-'; + + Locale? get locale { + // exceptionally allow getting locale before settings are initialized + final tag = initialized ? getString(SettingKeys.localeKey) : null; + if (tag != null) { + final codes = tag.split(localeSeparator); + return Locale.fromSubtags( + languageCode: codes[0], + scriptCode: codes[1] == '' ? null : codes[1], + countryCode: codes[2] == '' ? null : codes[2], + ); + } + return null; + } + + set locale(Locale? newValue) { + String? tag; + if (newValue != null) { + tag = [ + newValue.languageCode, + newValue.scriptCode ?? '', + newValue.countryCode ?? '', + ].join(localeSeparator); + } + set(SettingKeys.localeKey, tag); + resetAppliedLocale(); + } + + List<Locale> _systemLocalesFallback = []; + + set systemLocalesFallback(List<Locale> locales) => _systemLocalesFallback = locales; + + Locale? _appliedLocale; + + void resetAppliedLocale() => _appliedLocale = null; + + Locale get appliedLocale { + if (_appliedLocale == null) { + final _locale = locale; + final preferredLocales = <Locale>[]; + if (_locale != null) { + preferredLocales.add(_locale); + } else { + preferredLocales.addAll(WidgetsBinding.instance.platformDispatcher.locales); + if (preferredLocales.isEmpty) { + // the `window` locales may be empty in a window-less service context + preferredLocales.addAll(_systemLocalesFallback); + } + } + _appliedLocale = basicLocaleListResolution(preferredLocales, AvesApp.supportedLocales); + } + return _appliedLocale!; + } + + bool get forceWesternArabicNumerals => getBool(SettingKeys.forceWesternArabicNumeralsKey) ?? false; + + set forceWesternArabicNumerals(bool newValue) => set(SettingKeys.forceWesternArabicNumeralsKey, newValue); + + int get catalogTimeZoneOffsetMillis => getInt(SettingKeys.catalogTimeZoneOffsetMillisKey) ?? 0; + + set catalogTimeZoneOffsetMillis(int newValue) => set(SettingKeys.catalogTimeZoneOffsetMillisKey, newValue); + + double getTileExtent(String routeName) => getDouble(SettingKeys.tileExtentPrefixKey + routeName) ?? 0; + + void setTileExtent(String routeName, double newValue) => set(SettingKeys.tileExtentPrefixKey + routeName, newValue); + + TileLayout getTileLayout(String routeName) => getEnumOrDefault(SettingKeys.tileLayoutPrefixKey + routeName, SettingsDefaults.tileLayout, TileLayout.values); + + void setTileLayout(String routeName, TileLayout newValue) => set(SettingKeys.tileLayoutPrefixKey + routeName, newValue.toString()); + + String get entryRenamingPattern => getString(SettingKeys.entryRenamingPatternKey) ?? SettingsDefaults.entryRenamingPattern; + + set entryRenamingPattern(String newValue) => set(SettingKeys.entryRenamingPatternKey, newValue); + + List<int>? get topEntryIds => getStringList(SettingKeys.topEntryIdsKey)?.map(int.tryParse).nonNulls.toList(); + + set topEntryIds(List<int>? newValue) => set(SettingKeys.topEntryIdsKey, newValue?.map((id) => id.toString()).nonNulls.toList()); + + List<String> get recentDestinationAlbums => getStringList(SettingKeys.recentDestinationAlbumsKey) ?? []; + + set recentDestinationAlbums(List<String> newValue) => set(SettingKeys.recentDestinationAlbumsKey, newValue.take(recentFilterHistoryMax).toList()); + + // recent tags + + List<CollectionFilter> get _recentTags => (getStringList(SettingKeys.recentTagsKey) ?? []).map(CollectionFilter.fromJson).nonNulls.toList(); + + set _recentTags(List<CollectionFilter> newValue) => set(SettingKeys.recentTagsKey, newValue.take(recentFilterHistoryMax).map((filter) => filter.toJson()).toList()); + + // when vaults are unlocked, recent tags are transient and not persisted + List<CollectionFilter>? _protectedRecentTags; + + List<CollectionFilter> get recentTags => vaults.needProtection ? _protectedRecentTags ?? List.of(_recentTags) : _recentTags; + + set recentTags(List<CollectionFilter> newValue) { + if (vaults.needProtection) { + _protectedRecentTags = newValue; + } else { + _recentTags = newValue; + } + } + + void _onVaultsChanged() => _protectedRecentTags = null; + + void removeObsoleteRecentTags(CollectionSource? source) { + if (source != null) { + recentTags = recentTags.where((v) => v is! TagFilter || source.sortedTags.contains(v.tag)).toList(); + } + } +} diff --git a/lib/model/settings/modules/collection.dart b/lib/model/settings/modules/collection.dart new file mode 100644 index 0000000..5ccd095 --- /dev/null +++ b/lib/model/settings/modules/collection.dart @@ -0,0 +1,60 @@ +import 'package:aves/model/settings/defaults.dart'; +import 'package:aves_model/aves_model.dart'; + +mixin CollectionSettings on SettingsAccess { + List<String> get collectionBurstPatterns => getStringList(SettingKeys.collectionBurstPatternsKey) ?? []; + + set collectionBurstPatterns(List<String> newValue) => set(SettingKeys.collectionBurstPatternsKey, newValue); + + EntrySectionFactor get collectionSectionFactor => getEnumOrDefault(SettingKeys.collectionGroupFactorKey, SettingsDefaults.collectionSectionFactor, EntrySectionFactor.values); + + set collectionSectionFactor(EntrySectionFactor newValue) => set(SettingKeys.collectionGroupFactorKey, newValue.toString()); + + EntrySortFactor get collectionSortFactor => getEnumOrDefault(SettingKeys.collectionSortFactorKey, SettingsDefaults.collectionSortFactor, EntrySortFactor.values); + + set collectionSortFactor(EntrySortFactor newValue) => set(SettingKeys.collectionSortFactorKey, newValue.toString()); + + bool get collectionSortReverse => getBool(SettingKeys.collectionSortReverseKey) ?? false; + + set collectionSortReverse(bool newValue) => set(SettingKeys.collectionSortReverseKey, newValue); + + List<EntrySetAction> get collectionBrowsingQuickActions => getEnumListOrDefault(SettingKeys.collectionBrowsingQuickActionsKey, SettingsDefaults.collectionBrowsingQuickActions, EntrySetAction.values); + + set collectionBrowsingQuickActions(List<EntrySetAction> newValue) => set(SettingKeys.collectionBrowsingQuickActionsKey, newValue.map((v) => v.toString()).toList()); + + List<EntrySetAction> get collectionSelectionQuickActions => getEnumListOrDefault(SettingKeys.collectionSelectionQuickActionsKey, SettingsDefaults.collectionSelectionQuickActions, EntrySetAction.values); + + set collectionSelectionQuickActions(List<EntrySetAction> newValue) => set(SettingKeys.collectionSelectionQuickActionsKey, newValue.map((v) => v.toString()).toList()); + + bool get showThumbnailFavourite => getBool(SettingKeys.showThumbnailFavouriteKey) ?? SettingsDefaults.showThumbnailFavourite; + + set showThumbnailFavourite(bool newValue) => set(SettingKeys.showThumbnailFavouriteKey, newValue); + + bool get showThumbnailHdr => getBool(SettingKeys.showThumbnailHdrKey) ?? SettingsDefaults.showThumbnailHdr; + + set showThumbnailHdr(bool newValue) => set(SettingKeys.showThumbnailHdrKey, newValue); + + ThumbnailOverlayLocationIcon get thumbnailLocationIcon => getEnumOrDefault(SettingKeys.thumbnailLocationIconKey, SettingsDefaults.thumbnailLocationIcon, ThumbnailOverlayLocationIcon.values); + + set thumbnailLocationIcon(ThumbnailOverlayLocationIcon newValue) => set(SettingKeys.thumbnailLocationIconKey, newValue.toString()); + + ThumbnailOverlayTagIcon get thumbnailTagIcon => getEnumOrDefault(SettingKeys.thumbnailTagIconKey, SettingsDefaults.thumbnailTagIcon, ThumbnailOverlayTagIcon.values); + + set thumbnailTagIcon(ThumbnailOverlayTagIcon newValue) => set(SettingKeys.thumbnailTagIconKey, newValue.toString()); + + bool get showThumbnailMotionPhoto => getBool(SettingKeys.showThumbnailMotionPhotoKey) ?? SettingsDefaults.showThumbnailMotionPhoto; + + set showThumbnailMotionPhoto(bool newValue) => set(SettingKeys.showThumbnailMotionPhotoKey, newValue); + + bool get showThumbnailRating => getBool(SettingKeys.showThumbnailRatingKey) ?? SettingsDefaults.showThumbnailRating; + + set showThumbnailRating(bool newValue) => set(SettingKeys.showThumbnailRatingKey, newValue); + + bool get showThumbnailRaw => getBool(SettingKeys.showThumbnailRawKey) ?? SettingsDefaults.showThumbnailRaw; + + set showThumbnailRaw(bool newValue) => set(SettingKeys.showThumbnailRawKey, newValue); + + bool get showThumbnailVideoDuration => getBool(SettingKeys.showThumbnailVideoDurationKey) ?? SettingsDefaults.showThumbnailVideoDuration; + + set showThumbnailVideoDuration(bool newValue) => set(SettingKeys.showThumbnailVideoDurationKey, newValue); +} diff --git a/lib/model/settings/modules/debug.dart b/lib/model/settings/modules/debug.dart new file mode 100644 index 0000000..f740206 --- /dev/null +++ b/lib/model/settings/modules/debug.dart @@ -0,0 +1,7 @@ +import 'package:aves_model/aves_model.dart'; + +mixin DebugSettings on SettingsAccess { + bool get debugShowViewerTiles => getBool(SettingKeys.debugShowViewerTilesKey) ?? false; + + set debugShowViewerTiles(bool newValue) => set(SettingKeys.debugShowViewerTilesKey, newValue); +} diff --git a/lib/model/settings/modules/display.dart b/lib/model/settings/modules/display.dart new file mode 100644 index 0000000..390dd87 --- /dev/null +++ b/lib/model/settings/modules/display.dart @@ -0,0 +1,37 @@ +import 'package:aves/model/device.dart'; +import 'package:aves/model/settings/defaults.dart'; +import 'package:aves_model/aves_model.dart'; + +mixin DisplaySettings on SettingsAccess { + DisplayRefreshRateMode get displayRefreshRateMode => getEnumOrDefault(SettingKeys.displayRefreshRateModeKey, SettingsDefaults.displayRefreshRateMode, DisplayRefreshRateMode.values); + + set displayRefreshRateMode(DisplayRefreshRateMode newValue) => set(SettingKeys.displayRefreshRateModeKey, newValue.toString()); + + AvesThemeBrightness get themeBrightness => getEnumOrDefault(SettingKeys.themeBrightnessKey, SettingsDefaults.themeBrightness, AvesThemeBrightness.values); + + set themeBrightness(AvesThemeBrightness newValue) => set(SettingKeys.themeBrightnessKey, newValue.toString()); + + AvesThemeColorMode get themeColorMode => getEnumOrDefault(SettingKeys.themeColorModeKey, SettingsDefaults.themeColorMode, AvesThemeColorMode.values); + + set themeColorMode(AvesThemeColorMode newValue) => set(SettingKeys.themeColorModeKey, newValue.toString()); + + bool get enableDynamicColor => getBool(SettingKeys.enableDynamicColorKey) ?? SettingsDefaults.enableDynamicColor; + + set enableDynamicColor(bool newValue) => set(SettingKeys.enableDynamicColorKey, newValue); + + bool get enableBlurEffect => getBool(SettingKeys.enableBlurEffectKey) ?? SettingsDefaults.enableBlurEffect; + + set enableBlurEffect(bool newValue) => set(SettingKeys.enableBlurEffectKey, newValue); + + MaxBrightness get maxBrightness => getEnumOrDefault(SettingKeys.maxBrightnessKey, SettingsDefaults.maxBrightness, MaxBrightness.values); + + set maxBrightness(MaxBrightness newValue) => set(SettingKeys.maxBrightnessKey, newValue.toString()); + + bool get forceTvLayout => getBool(SettingKeys.forceTvLayoutKey) ?? SettingsDefaults.forceTvLayout; + + set forceTvLayout(bool newValue) => set(SettingKeys.forceTvLayoutKey, newValue); + + bool get useTvLayout => device.isTelevision || forceTvLayout; + + bool get isReadOnly => useTvLayout; +} diff --git a/lib/model/settings/modules/filter_grids.dart b/lib/model/settings/modules/filter_grids.dart new file mode 100644 index 0000000..1dcc772 --- /dev/null +++ b/lib/model/settings/modules/filter_grids.dart @@ -0,0 +1,117 @@ +import 'package:aves/model/filters/container/dynamic_album.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/grouping/common.dart'; +import 'package:aves/model/settings/defaults.dart'; +import 'package:aves/utils/collection_utils.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:synchronized/synchronized.dart'; + +mixin FilterGridsSettings on SettingsAccess { + AlbumChipSectionFactor get albumSectionFactor => getEnumOrDefault(SettingKeys.albumSectionFactorKey, SettingsDefaults.albumGroupFactor, AlbumChipSectionFactor.values); + + set albumSectionFactor(AlbumChipSectionFactor newValue) => set(SettingKeys.albumSectionFactorKey, newValue.toString()); + + ChipSortFactor get albumSortFactor => getEnumOrDefault(SettingKeys.albumSortFactorKey, SettingsDefaults.chipListSortFactor, ChipSortFactor.values); + + set albumSortFactor(ChipSortFactor newValue) => set(SettingKeys.albumSortFactorKey, newValue.toString()); + + ChipSortFactor get countrySortFactor => getEnumOrDefault(SettingKeys.countrySortFactorKey, SettingsDefaults.chipListSortFactor, ChipSortFactor.values); + + set countrySortFactor(ChipSortFactor newValue) => set(SettingKeys.countrySortFactorKey, newValue.toString()); + + ChipSortFactor get stateSortFactor => getEnumOrDefault(SettingKeys.stateSortFactorKey, SettingsDefaults.chipListSortFactor, ChipSortFactor.values); + + set stateSortFactor(ChipSortFactor newValue) => set(SettingKeys.stateSortFactorKey, newValue.toString()); + + ChipSortFactor get placeSortFactor => getEnumOrDefault(SettingKeys.placeSortFactorKey, SettingsDefaults.chipListSortFactor, ChipSortFactor.values); + + set placeSortFactor(ChipSortFactor newValue) => set(SettingKeys.placeSortFactorKey, newValue.toString()); + + ChipSortFactor get tagSortFactor => getEnumOrDefault(SettingKeys.tagSortFactorKey, SettingsDefaults.chipListSortFactor, ChipSortFactor.values); + + set tagSortFactor(ChipSortFactor newValue) => set(SettingKeys.tagSortFactorKey, newValue.toString()); + + bool get albumSortReverse => getBool(SettingKeys.albumSortReverseKey) ?? false; + + set albumSortReverse(bool newValue) => set(SettingKeys.albumSortReverseKey, newValue); + + bool get countrySortReverse => getBool(SettingKeys.countrySortReverseKey) ?? false; + + set countrySortReverse(bool newValue) => set(SettingKeys.countrySortReverseKey, newValue); + + bool get stateSortReverse => getBool(SettingKeys.stateSortReverseKey) ?? false; + + set stateSortReverse(bool newValue) => set(SettingKeys.stateSortReverseKey, newValue); + + bool get placeSortReverse => getBool(SettingKeys.placeSortReverseKey) ?? false; + + set placeSortReverse(bool newValue) => set(SettingKeys.placeSortReverseKey, newValue); + + bool get tagSortReverse => getBool(SettingKeys.tagSortReverseKey) ?? false; + + set tagSortReverse(bool newValue) => set(SettingKeys.tagSortReverseKey, newValue); + + Set<CollectionFilter> get pinnedFilters => (getStringList(SettingKeys.pinnedFiltersKey) ?? []).map(CollectionFilter.fromJson).nonNulls.toSet(); + + set pinnedFilters(Set<CollectionFilter> newValue) => set(SettingKeys.pinnedFiltersKey, newValue.map((filter) => filter.toJson()).toList()); + + bool getShowTitleQuery(String routeName) => getBool(SettingKeys.showTitleQueryPrefixKey + routeName) ?? false; + + void setShowTitleQuery(String routeName, bool newValue) => set(SettingKeys.showTitleQueryPrefixKey + routeName, newValue); + + void resetShowTitleQuery() { + final configuredKeys = store.getKeys().where((v) => v.startsWith(SettingKeys.showTitleQueryPrefixKey)).toSet(); + configuredKeys.forEach((key) => set(key, false)); + } + + Map<Uri, Set<Uri>> get albumGroups => FilterGrouping.fromJson(getString(SettingKeys.albumGroupsKey)) ?? {}; + + set albumGroups(Map<Uri, Set<Uri>> groups) => set(SettingKeys.albumGroupsKey, FilterGrouping.toJson(groups)); + + Map<Uri, Set<Uri>> get tagGroups => FilterGrouping.fromJson(getString(SettingKeys.tagGroupsKey)) ?? {}; + + set tagGroups(Map<Uri, Set<Uri>> groups) => set(SettingKeys.tagGroupsKey, FilterGrouping.toJson(groups)); + + // listening + + final _lockForPins = Lock(); + + Future<void> updatePinnedDynamicAlbums(Map<DynamicAlbumFilter, DynamicAlbumFilter?> changes) async { + await _lockForPins.synchronized(() async { + final _pinnedFilters = pinnedFilters; + bool changed = false; + changes.forEach((oldFilter, newFilter) { + if (newFilter != null) { + changed |= _pinnedFilters.replace(oldFilter, newFilter); + } else { + changed |= _pinnedFilters.remove(oldFilter); + } + }); + if (changed) { + pinnedFilters = _pinnedFilters; + } + }); + } + + Future<void> updatePinnedGroup(Uri oldGroupUri, Uri newGroupUri) async { + await _lockForPins.synchronized(() async { + final _pinnedFilters = pinnedFilters; + bool changed = false; + final grouping = FilterGrouping.forUri(oldGroupUri); + if (grouping != null) { + final oldFilter = grouping.uriToFilter(oldGroupUri); + final newFilter = grouping.uriToFilter(newGroupUri); + if (oldFilter != null && newFilter != null) { + changed |= _pinnedFilters.replace(oldFilter, newFilter); + } + } + if (changed) { + pinnedFilters = _pinnedFilters; + } + }); + } + + void saveAlbumGroups() => albumGroups = albumGrouping.allGroups; + + void saveTagGroups() => tagGroups = tagGrouping.allGroups; +} diff --git a/lib/model/settings/modules/info.dart b/lib/model/settings/modules/info.dart new file mode 100644 index 0000000..18e8094 --- /dev/null +++ b/lib/model/settings/modules/info.dart @@ -0,0 +1,16 @@ +import 'package:aves/model/settings/defaults.dart'; +import 'package:aves_model/aves_model.dart'; + +mixin InfoSettings on SettingsAccess { + double get infoMapZoom => getDouble(SettingKeys.infoMapZoomKey) ?? SettingsDefaults.infoMapZoom; + + set infoMapZoom(double newValue) => set(SettingKeys.infoMapZoomKey, newValue); + + CoordinateFormat get coordinateFormat => getEnumOrDefault(SettingKeys.coordinateFormatKey, SettingsDefaults.coordinateFormat, CoordinateFormat.values); + + set coordinateFormat(CoordinateFormat newValue) => set(SettingKeys.coordinateFormatKey, newValue.toString()); + + UnitSystem get unitSystem => getEnumOrDefault(SettingKeys.unitSystemKey, SettingsDefaults.unitSystem, UnitSystem.values); + + set unitSystem(UnitSystem newValue) => set(SettingKeys.unitSystemKey, newValue.toString()); +} diff --git a/lib/model/settings/modules/navigation.dart b/lib/model/settings/modules/navigation.dart new file mode 100644 index 0000000..94d7634 --- /dev/null +++ b/lib/model/settings/modules/navigation.dart @@ -0,0 +1,142 @@ +import 'package:aves/model/filters/container/album_group.dart'; +import 'package:aves/model/filters/container/dynamic_album.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/grouping/common.dart'; +import 'package:aves/model/settings/defaults.dart'; +import 'package:aves/utils/collection_utils.dart'; +import 'package:aves/widgets/collection/collection_page.dart'; +import 'package:aves/widgets/explorer/explorer_page.dart'; +import 'package:aves/widgets/filter_grids/albums_page.dart'; +import 'package:aves/widgets/filter_grids/tags_page.dart'; +import 'package:aves/widgets/navigation/nav_item.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:synchronized/synchronized.dart'; + +mixin NavigationSettings on SettingsAccess { + bool get mustBackTwiceToExit => getBool(SettingKeys.mustBackTwiceToExitKey) ?? SettingsDefaults.mustBackTwiceToExit; + + set mustBackTwiceToExit(bool newValue) => set(SettingKeys.mustBackTwiceToExitKey, newValue); + + KeepScreenOn get keepScreenOn => getEnumOrDefault(SettingKeys.keepScreenOnKey, SettingsDefaults.keepScreenOn, KeepScreenOn.values); + + set keepScreenOn(KeepScreenOn newValue) => set(SettingKeys.keepScreenOnKey, newValue.toString()); + + HomePageSetting get homePage => getEnumOrDefault(SettingKeys.homePageKey, SettingsDefaults.homePage, HomePageSetting.values); + + Set<CollectionFilter> get homeCustomCollection => (getStringList(SettingKeys.homeCustomCollectionKey) ?? []).map(CollectionFilter.fromJson).nonNulls.toSet(); + + String? get homeCustomExplorerPath => getString(SettingKeys.homeCustomExplorerPathKey); + + AvesNavItem get homeNavItem { + switch (homePage) { + case HomePageSetting.collection: + return AvesNavItem(route: CollectionPage.routeName, filters: homeCustomCollection); + case HomePageSetting.albums: + return const AvesNavItem(route: AlbumListPage.routeName); + case HomePageSetting.tags: + return const AvesNavItem(route: TagListPage.routeName); + case HomePageSetting.explorer: + return AvesNavItem(route: ExplorerPage.routeName, path: homeCustomExplorerPath); + } + } + + void setHome( + HomePageSetting homePage, { + Set<CollectionFilter> customCollection = const {}, + String? customExplorerPath, + }) { + set(SettingKeys.homePageKey, homePage.toString()); + set(SettingKeys.homeCustomCollectionKey, customCollection.map((filter) => filter.toJson()).toList()); + set(SettingKeys.homeCustomExplorerPathKey, customExplorerPath); + } + + bool get confirmCreateVault => getBool(SettingKeys.confirmCreateVaultKey) ?? SettingsDefaults.confirm; + + set confirmCreateVault(bool newValue) => set(SettingKeys.confirmCreateVaultKey, newValue); + + bool get confirmDeleteForever => getBool(SettingKeys.confirmDeleteForeverKey) ?? SettingsDefaults.confirm; + + set confirmDeleteForever(bool newValue) => set(SettingKeys.confirmDeleteForeverKey, newValue); + + bool get confirmMoveToBin => getBool(SettingKeys.confirmMoveToBinKey) ?? SettingsDefaults.confirm; + + set confirmMoveToBin(bool newValue) => set(SettingKeys.confirmMoveToBinKey, newValue); + + bool get confirmMoveUndatedItems => getBool(SettingKeys.confirmMoveUndatedItemsKey) ?? SettingsDefaults.confirm; + + set confirmMoveUndatedItems(bool newValue) => set(SettingKeys.confirmMoveUndatedItemsKey, newValue); + + bool get confirmAfterMoveToBin => getBool(SettingKeys.confirmAfterMoveToBinKey) ?? SettingsDefaults.confirm; + + set confirmAfterMoveToBin(bool newValue) => set(SettingKeys.confirmAfterMoveToBinKey, newValue); + + bool get setMetadataDateBeforeFileOp => getBool(SettingKeys.setMetadataDateBeforeFileOpKey) ?? SettingsDefaults.setMetadataDateBeforeFileOp; + + set setMetadataDateBeforeFileOp(bool newValue) => set(SettingKeys.setMetadataDateBeforeFileOpKey, newValue); + + List<CollectionFilter?> get drawerTypeBookmarks => + getStringList(SettingKeys.drawerTypeBookmarksKey)?.map((v) { + if (v.isEmpty) return null; + return CollectionFilter.fromJson(v); + }).toList() ?? + SettingsDefaults.drawerTypeBookmarks; + + set drawerTypeBookmarks(List<CollectionFilter?> newValue) => set(SettingKeys.drawerTypeBookmarksKey, newValue.map((filter) => filter?.toJson() ?? '').toList()); + + List<AlbumBaseFilter>? get drawerAlbumBookmarks => getStringList(SettingKeys.drawerAlbumBookmarksKey)?.map(CollectionFilter.fromJson).whereType<AlbumBaseFilter>().toList(); + + set drawerAlbumBookmarks(List<AlbumBaseFilter>? newValue) => set(SettingKeys.drawerAlbumBookmarksKey, newValue?.map((filter) => filter.toJson()).toList()); + + List<String> get drawerPageBookmarks => getStringList(SettingKeys.drawerPageBookmarksKey) ?? SettingsDefaults.drawerPageBookmarks; + + set drawerPageBookmarks(List<String> newValue) => set(SettingKeys.drawerPageBookmarksKey, newValue); + + List<AvesNavItem> get bottomNavigationActions => getStringList(SettingKeys.bottomNavigationActionsKey)?.map(AvesNavItem.fromJson).nonNulls.toList() ?? SettingsDefaults.bottomNavigationActions; + + set bottomNavigationActions(List<AvesNavItem>? newValue) => set(SettingKeys.bottomNavigationActionsKey, newValue?.map((v) => v.toJson()).toList()); + + bool get enableBottomNavigationBar => bottomNavigationActions.length >= 2; + + // listening + + final _lockForBookmarks = Lock(); + + Future<void> updateBookmarkedDynamicAlbums(Map<DynamicAlbumFilter, DynamicAlbumFilter?> changes) async { + await _lockForBookmarks.synchronized(() async { + final _bookmarks = drawerAlbumBookmarks; + bool changed = false; + if (_bookmarks != null) { + changes.forEach((oldFilter, newFilter) { + if (newFilter != null) { + changed |= _bookmarks.replace(oldFilter, newFilter); + } else { + changed |= _bookmarks.remove(oldFilter); + } + }); + } + if (changed) { + drawerAlbumBookmarks = _bookmarks; + } + }); + } + + Future<void> updateBookmarkedGroup(Uri oldGroupUri, Uri newGroupUri) async { + await _lockForBookmarks.synchronized(() async { + final _bookmarks = drawerAlbumBookmarks; + bool changed = false; + if (_bookmarks != null) { + final grouping = FilterGrouping.forUri(oldGroupUri); + if (grouping != null) { + final oldFilter = grouping.uriToFilter(oldGroupUri); + final newFilter = grouping.uriToFilter(newGroupUri); + if (oldFilter is AlbumBaseFilter && newFilter is AlbumBaseFilter) { + changed |= _bookmarks.replace(oldFilter, newFilter); + } + } + } + if (changed) { + drawerAlbumBookmarks = _bookmarks; + } + }); + } +} diff --git a/lib/model/settings/modules/privacy.dart b/lib/model/settings/modules/privacy.dart new file mode 100644 index 0000000..a6408b8 --- /dev/null +++ b/lib/model/settings/modules/privacy.dart @@ -0,0 +1,46 @@ +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/settings/modules/search.dart'; +import 'package:aves_model/aves_model.dart'; + +mixin PrivacySettings on SettingsAccess, SearchSettings { + Set<CollectionFilter> get hiddenFilters => (getStringList(SettingKeys.hiddenFiltersKey) ?? []).map(CollectionFilter.fromJson).nonNulls.toSet(); + + set hiddenFilters(Set<CollectionFilter> newValue) => set(SettingKeys.hiddenFiltersKey, newValue.map((filter) => filter.toJson()).toList()); + + void changeFilterVisibility(Set<CollectionFilter> filters, bool visible) { + final _deactivatedHiddenFilters = deactivatedHiddenFilters; + final _hiddenFilters = hiddenFilters; + + _deactivatedHiddenFilters.removeAll(filters); + if (visible) { + _hiddenFilters.removeAll(filters); + } else { + _hiddenFilters.addAll(filters); + searchHistory = searchHistory..removeWhere(filters.contains); + } + + deactivatedHiddenFilters = _deactivatedHiddenFilters; + hiddenFilters = _hiddenFilters; + } + + Set<CollectionFilter> get deactivatedHiddenFilters => (getStringList(SettingKeys.deactivatedHiddenFiltersKey) ?? []).map(CollectionFilter.fromJson).nonNulls.toSet(); + + set deactivatedHiddenFilters(Set<CollectionFilter> newValue) => set(SettingKeys.deactivatedHiddenFiltersKey, newValue.map((filter) => filter.toJson()).toList()); + + void activateHiddenFilter(CollectionFilter filter, bool active) { + final _deactivatedHiddenFilters = deactivatedHiddenFilters; + final _hiddenFilters = hiddenFilters; + + if (active) { + _deactivatedHiddenFilters.remove(filter); + _hiddenFilters.add(filter); + searchHistory = searchHistory..remove(filter); + } else { + _deactivatedHiddenFilters.add(filter); + _hiddenFilters.remove(filter); + } + + deactivatedHiddenFilters = _deactivatedHiddenFilters; + hiddenFilters = _hiddenFilters; + } +} diff --git a/lib/model/settings/modules/screen_saver.dart b/lib/model/settings/modules/screen_saver.dart new file mode 100644 index 0000000..176bac4 --- /dev/null +++ b/lib/model/settings/modules/screen_saver.dart @@ -0,0 +1,29 @@ +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/settings/defaults.dart'; +import 'package:aves_model/aves_model.dart'; + +mixin ScreenSaverSettings on SettingsAccess { + bool get screenSaverFillScreen => getBool(SettingKeys.screenSaverFillScreenKey) ?? SettingsDefaults.slideshowFillScreen; + + set screenSaverFillScreen(bool newValue) => set(SettingKeys.screenSaverFillScreenKey, newValue); + + bool get screenSaverAnimatedZoomEffect => getBool(SettingKeys.screenSaverAnimatedZoomEffectKey) ?? SettingsDefaults.slideshowAnimatedZoomEffect; + + set screenSaverAnimatedZoomEffect(bool newValue) => set(SettingKeys.screenSaverAnimatedZoomEffectKey, newValue); + + ViewerTransition get screenSaverTransition => getEnumOrDefault(SettingKeys.screenSaverTransitionKey, SettingsDefaults.slideshowTransition, ViewerTransition.values); + + set screenSaverTransition(ViewerTransition newValue) => set(SettingKeys.screenSaverTransitionKey, newValue.toString()); + + SlideshowVideoPlayback get screenSaverVideoPlayback => getEnumOrDefault(SettingKeys.screenSaverVideoPlaybackKey, SettingsDefaults.slideshowVideoPlayback, SlideshowVideoPlayback.values); + + set screenSaverVideoPlayback(SlideshowVideoPlayback newValue) => set(SettingKeys.screenSaverVideoPlaybackKey, newValue.toString()); + + int get screenSaverInterval => getInt(SettingKeys.screenSaverIntervalKey) ?? SettingsDefaults.slideshowInterval; + + set screenSaverInterval(int newValue) => set(SettingKeys.screenSaverIntervalKey, newValue); + + Set<CollectionFilter> get screenSaverCollectionFilters => (getStringList(SettingKeys.screenSaverCollectionFiltersKey) ?? []).map(CollectionFilter.fromJson).nonNulls.toSet(); + + set screenSaverCollectionFilters(Set<CollectionFilter> newValue) => set(SettingKeys.screenSaverCollectionFiltersKey, newValue.map((filter) => filter.toJson()).toList()); +} diff --git a/lib/model/settings/modules/search.dart b/lib/model/settings/modules/search.dart new file mode 100644 index 0000000..3a5ff94 --- /dev/null +++ b/lib/model/settings/modules/search.dart @@ -0,0 +1,13 @@ +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/settings/defaults.dart'; +import 'package:aves_model/aves_model.dart'; + +mixin SearchSettings on SettingsAccess { + bool get saveSearchHistory => getBool(SettingKeys.saveSearchHistoryKey) ?? SettingsDefaults.saveSearchHistory; + + set saveSearchHistory(bool newValue) => set(SettingKeys.saveSearchHistoryKey, newValue); + + List<CollectionFilter> get searchHistory => (getStringList(SettingKeys.searchHistoryKey) ?? []).map(CollectionFilter.fromJson).nonNulls.toList(); + + set searchHistory(List<CollectionFilter> newValue) => set(SettingKeys.searchHistoryKey, newValue.map((filter) => filter.toJson()).toList()); +} diff --git a/lib/model/settings/modules/slideshow.dart b/lib/model/settings/modules/slideshow.dart new file mode 100644 index 0000000..50740e9 --- /dev/null +++ b/lib/model/settings/modules/slideshow.dart @@ -0,0 +1,32 @@ +import 'package:aves/model/settings/defaults.dart'; +import 'package:aves_model/aves_model.dart'; + +mixin SlideshowSettings on SettingsAccess { + bool get slideshowRepeat => getBool(SettingKeys.slideshowRepeatKey) ?? SettingsDefaults.slideshowRepeat; + + set slideshowRepeat(bool newValue) => set(SettingKeys.slideshowRepeatKey, newValue); + + bool get slideshowShuffle => getBool(SettingKeys.slideshowShuffleKey) ?? SettingsDefaults.slideshowShuffle; + + set slideshowShuffle(bool newValue) => set(SettingKeys.slideshowShuffleKey, newValue); + + bool get slideshowFillScreen => getBool(SettingKeys.slideshowFillScreenKey) ?? SettingsDefaults.slideshowFillScreen; + + set slideshowFillScreen(bool newValue) => set(SettingKeys.slideshowFillScreenKey, newValue); + + bool get slideshowAnimatedZoomEffect => getBool(SettingKeys.slideshowAnimatedZoomEffectKey) ?? SettingsDefaults.slideshowAnimatedZoomEffect; + + set slideshowAnimatedZoomEffect(bool newValue) => set(SettingKeys.slideshowAnimatedZoomEffectKey, newValue); + + ViewerTransition get slideshowTransition => getEnumOrDefault(SettingKeys.slideshowTransitionKey, SettingsDefaults.slideshowTransition, ViewerTransition.values); + + set slideshowTransition(ViewerTransition newValue) => set(SettingKeys.slideshowTransitionKey, newValue.toString()); + + SlideshowVideoPlayback get slideshowVideoPlayback => getEnumOrDefault(SettingKeys.slideshowVideoPlaybackKey, SettingsDefaults.slideshowVideoPlayback, SlideshowVideoPlayback.values); + + set slideshowVideoPlayback(SlideshowVideoPlayback newValue) => set(SettingKeys.slideshowVideoPlaybackKey, newValue.toString()); + + int get slideshowInterval => getInt(SettingKeys.slideshowIntervalKey) ?? SettingsDefaults.slideshowInterval; + + set slideshowInterval(int newValue) => set(SettingKeys.slideshowIntervalKey, newValue); +} diff --git a/lib/model/settings/modules/viewer.dart b/lib/model/settings/modules/viewer.dart new file mode 100644 index 0000000..7d4f86f --- /dev/null +++ b/lib/model/settings/modules/viewer.dart @@ -0,0 +1,60 @@ +import 'package:aves/model/settings/defaults.dart'; +import 'package:aves_model/aves_model.dart'; + +mixin ViewerSettings on SettingsAccess { + List<EntryAction> get viewerQuickActions => getEnumListOrDefault(SettingKeys.viewerQuickActionsKey, SettingsDefaults.viewerQuickActions, EntryAction.values); + + set viewerQuickActions(List<EntryAction> newValue) => set(SettingKeys.viewerQuickActionsKey, newValue.map((v) => v.toString()).toList()); + + bool get showOverlayOnOpening => getBool(SettingKeys.showOverlayOnOpeningKey) ?? SettingsDefaults.showOverlayOnOpening; + + set showOverlayOnOpening(bool newValue) => set(SettingKeys.showOverlayOnOpeningKey, newValue); + + bool get showOverlayMinimap => getBool(SettingKeys.showOverlayMinimapKey) ?? SettingsDefaults.showOverlayMinimap; + + set showOverlayMinimap(bool newValue) => set(SettingKeys.showOverlayMinimapKey, newValue); + + bool get showOverlayZoomLevel => getBool(SettingKeys.showOverlayZoomLevelKey) ?? SettingsDefaults.showOverlayZoomLevel; + + set showOverlayZoomLevel(bool newValue) => set(SettingKeys.showOverlayZoomLevelKey, newValue); + + OverlayHistogramStyle get overlayHistogramStyle => getEnumOrDefault(SettingKeys.overlayHistogramStyleKey, SettingsDefaults.overlayHistogramStyle, OverlayHistogramStyle.values); + + set overlayHistogramStyle(OverlayHistogramStyle newValue) => set(SettingKeys.overlayHistogramStyleKey, newValue.toString()); + + bool get showOverlayInfo => getBool(SettingKeys.showOverlayInfoKey) ?? SettingsDefaults.showOverlayInfo; + + set showOverlayInfo(bool newValue) => set(SettingKeys.showOverlayInfoKey, newValue); + + bool get showOverlayDescription => getBool(SettingKeys.showOverlayDescriptionKey) ?? SettingsDefaults.showOverlayDescription; + + set showOverlayDescription(bool newValue) => set(SettingKeys.showOverlayDescriptionKey, newValue); + + bool get showOverlayRatingTags => getBool(SettingKeys.showOverlayRatingTagsKey) ?? SettingsDefaults.showOverlayRatingTags; + + set showOverlayRatingTags(bool newValue) => set(SettingKeys.showOverlayRatingTagsKey, newValue); + + bool get showOverlayShootingDetails => getBool(SettingKeys.showOverlayShootingDetailsKey) ?? SettingsDefaults.showOverlayShootingDetails; + + set showOverlayShootingDetails(bool newValue) => set(SettingKeys.showOverlayShootingDetailsKey, newValue); + + bool get showOverlayThumbnailPreview => getBool(SettingKeys.showOverlayThumbnailPreviewKey) ?? SettingsDefaults.showOverlayThumbnailPreview; + + set showOverlayThumbnailPreview(bool newValue) => set(SettingKeys.showOverlayThumbnailPreviewKey, newValue); + + bool get viewerGestureSideTapNext => getBool(SettingKeys.viewerGestureSideTapNextKey) ?? SettingsDefaults.viewerGestureSideTapNext; + + set viewerGestureSideTapNext(bool newValue) => set(SettingKeys.viewerGestureSideTapNextKey, newValue); + + bool get viewerUseCutout => getBool(SettingKeys.viewerUseCutoutKey) ?? SettingsDefaults.viewerUseCutout; + + set viewerUseCutout(bool newValue) => set(SettingKeys.viewerUseCutoutKey, newValue); + + bool get enableMotionPhotoAutoPlay => getBool(SettingKeys.enableMotionPhotoAutoPlayKey) ?? SettingsDefaults.enableMotionPhotoAutoPlay; + + set enableMotionPhotoAutoPlay(bool newValue) => set(SettingKeys.enableMotionPhotoAutoPlayKey, newValue); + + EntryBackground get imageBackground => getEnumOrDefault(SettingKeys.imageBackgroundKey, SettingsDefaults.imageBackground, EntryBackground.values); + + set imageBackground(EntryBackground newValue) => set(SettingKeys.imageBackgroundKey, newValue.toString()); +} diff --git a/lib/model/settings/modules/widget.dart b/lib/model/settings/modules/widget.dart new file mode 100644 index 0000000..f1b3c91 --- /dev/null +++ b/lib/model/settings/modules/widget.dart @@ -0,0 +1,29 @@ +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/settings/defaults.dart'; +import 'package:aves_model/aves_model.dart'; + +mixin WidgetSettings on SettingsAccess { + WidgetOutline getWidgetOutline(int widgetId) => getEnumOrDefault('${SettingKeys.widgetOutlinePrefixKey}$widgetId', WidgetOutline.none, WidgetOutline.values); + + void setWidgetOutline(int widgetId, WidgetOutline newValue) => set('${SettingKeys.widgetOutlinePrefixKey}$widgetId', newValue.toString()); + + WidgetShape getWidgetShape(int widgetId) => getEnumOrDefault('${SettingKeys.widgetShapePrefixKey}$widgetId', SettingsDefaults.widgetShape, WidgetShape.values); + + void setWidgetShape(int widgetId, WidgetShape newValue) => set('${SettingKeys.widgetShapePrefixKey}$widgetId', newValue.toString()); + + Set<CollectionFilter> getWidgetCollectionFilters(int widgetId) => (getStringList('${SettingKeys.widgetCollectionFiltersPrefixKey}$widgetId') ?? []).map(CollectionFilter.fromJson).nonNulls.toSet(); + + void setWidgetCollectionFilters(int widgetId, Set<CollectionFilter> newValue) => set('${SettingKeys.widgetCollectionFiltersPrefixKey}$widgetId', newValue.map((filter) => filter.toJson()).toList()); + + WidgetOpenPage getWidgetOpenPage(int widgetId) => getEnumOrDefault('${SettingKeys.widgetOpenPagePrefixKey}$widgetId', SettingsDefaults.widgetOpenPage, WidgetOpenPage.values); + + void setWidgetOpenPage(int widgetId, WidgetOpenPage newValue) => set('${SettingKeys.widgetOpenPagePrefixKey}$widgetId', newValue.toString()); + + WidgetDisplayedItem getWidgetDisplayedItem(int widgetId) => getEnumOrDefault('${SettingKeys.widgetDisplayedItemPrefixKey}$widgetId', SettingsDefaults.widgetDisplayedItem, WidgetDisplayedItem.values); + + void setWidgetDisplayedItem(int widgetId, WidgetDisplayedItem newValue) => set('${SettingKeys.widgetDisplayedItemPrefixKey}$widgetId', newValue.toString()); + + String? getWidgetUri(int widgetId) => getString('${SettingKeys.widgetUriPrefixKey}$widgetId'); + + void setWidgetUri(int widgetId, String? newValue) => set('${SettingKeys.widgetUriPrefixKey}$widgetId', newValue); +} diff --git a/lib/model/settings/settings.dart b/lib/model/settings/settings.dart new file mode 100644 index 0000000..4e0bd1b --- /dev/null +++ b/lib/model/settings/settings.dart @@ -0,0 +1,490 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:math'; + +import 'package:aves/app_flavor.dart'; +import 'package:aves/model/device.dart'; +import 'package:aves/model/dynamic_albums.dart'; +import 'package:aves/model/filters/favourite.dart'; +import 'package:aves/model/filters/mime.dart'; +import 'package:aves/model/grouping/common.dart'; +import 'package:aves/model/settings/defaults.dart'; +import 'package:aves/model/settings/enums/accessibility_animations.dart'; +import 'package:aves/model/settings/modules/app.dart'; +import 'package:aves/model/settings/modules/collection.dart'; +import 'package:aves/model/settings/modules/debug.dart'; +import 'package:aves/model/settings/modules/display.dart'; +import 'package:aves/model/settings/modules/filter_grids.dart'; +import 'package:aves/model/settings/modules/info.dart'; +import 'package:aves/model/settings/modules/navigation.dart'; +import 'package:aves/model/settings/modules/privacy.dart'; +import 'package:aves/model/settings/modules/screen_saver.dart'; +import 'package:aves/model/settings/modules/search.dart'; +import 'package:aves/model/settings/modules/slideshow.dart'; +import 'package:aves/model/settings/modules/viewer.dart'; +import 'package:aves/model/settings/modules/widget.dart'; +import 'package:aves/ref/bursts.dart'; +import 'package:aves/services/accessibility_service.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/widgets/common/search/page.dart'; +import 'package:aves/widgets/filter_grids/albums_page.dart'; +import 'package:aves/widgets/filter_grids/countries_page.dart'; +import 'package:aves/widgets/filter_grids/places_page.dart'; +import 'package:aves/widgets/filter_grids/tags_page.dart'; +import 'package:aves_map/aves_map.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:aves_utils/aves_utils.dart'; +import 'package:aves_video/aves_video.dart'; +import 'package:collection/collection.dart'; +import 'package:device_info_plus/device_info_plus.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/services.dart'; +import 'package:latlong2/latlong.dart'; + +final Settings settings = Settings._private(); + +class Settings with ChangeNotifier, SettingsAccess, SearchSettings, AppSettings, CollectionSettings, DebugSettings, DisplaySettings, FilterGridsSettings, InfoSettings, NavigationSettings, PrivacySettings, ScreenSaverSettings, SlideshowSettings, SubtitlesSettings, VideoSettings, ViewerSettings, WidgetSettings { + final Set<StreamSubscription> _subscriptions = {}; + final EventChannel _platformSettingsChangeChannel = const OptionalEventChannel('deckers.thibault/aves/settings_change'); + final StreamController<SettingsChangedEvent> _updateStreamController = StreamController.broadcast(); + final StreamController<SettingsChangedEvent> _updateTileExtentStreamController = StreamController.broadcast(); + + @override + Stream<SettingsChangedEvent> get updateStream => _updateStreamController.stream; + + Stream<SettingsChangedEvent> get updateTileExtentStream => _updateTileExtentStreamController.stream; + + @override + bool get initialized => store.initialized; + + @override + SettingsStore get store => settingsStore; + + Settings._private() { + if (kFlutterMemoryAllocationsEnabled) ChangeNotifier.maybeDispatchObjectCreation(this); + } + + Future<void> init({required bool monitorPlatformSettings}) async { + await store.init(); + resetAppliedLocale(); + _unregister(); + _register(monitorPlatformSettings); + initAppSettings(); + } + + void _unregister() { + albumGrouping.removeListener(saveAlbumGroups); + tagGrouping.removeListener(saveTagGroups); + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + } + + void _register(bool monitorPlatformSettings) { + albumGrouping.addListener(saveAlbumGroups); + tagGrouping.addListener(saveTagGroups); + _subscriptions.add(dynamicAlbums.eventBus.on<DynamicAlbumChangedEvent>().listen((e) { + final changes = e.changes; + updateBookmarkedDynamicAlbums(changes); + updatePinnedDynamicAlbums(changes); + })); + _subscriptions.add(albumGrouping.eventBus.on<GroupUriChangedEvent>().listen(_onGroupingChange)); + _subscriptions.add(tagGrouping.eventBus.on<GroupUriChangedEvent>().listen(_onGroupingChange)); + if (monitorPlatformSettings) { + _subscriptions.add(_platformSettingsChangeChannel.receiveBroadcastStream().listen((event) => _onPlatformSettingsChanged(event as Map?))); + } + } + + void _onGroupingChange(GroupUriChangedEvent event) { + final oldGroupUri = event.oldGroupUri; + final newGroupUri = event.newGroupUri; + updateBookmarkedGroup(oldGroupUri, newGroupUri); + updatePinnedGroup(oldGroupUri, newGroupUri); + } + + Future<void> reload() => store.reload(); + + Future<void> reset({required bool includeInternalKeys}) async { + if (includeInternalKeys) { + await store.clear(); + } else { + await Future.forEach<String>(store.getKeys().whereNot(SettingKeys.isInternalKey), store.remove); + } + } + + Future<void> setContextualDefaults(AppFlavor flavor) async { + // performance + final performanceClass = await deviceService.getPerformanceClass(); + enableBlurEffect = performanceClass >= 29; + + final androidInfo = await DeviceInfoPlugin().androidInfo; + final manufacturer = androidInfo.manufacturer.toLowerCase(); + final pattern = BurstPatterns.byManufacturer[manufacturer]; + collectionBurstPatterns = pattern != null ? [pattern] : []; + + // availability + if (flavor.hasMapStyleDefault) { + final defaultMapStyle = mobileServices.defaultMapStyle; + if (defaultMapStyle != null && mobileServices.mapStyles.contains(defaultMapStyle)) { + mapStyle = defaultMapStyle; + } else { + final styles = EntryMapStyles.baseStyles; + mapStyle = styles[Random().nextInt(styles.length)]; + } + } + + if (settings.useTvLayout) { + applyTvSettings(); + } + } + + void applyTvSettings() { + themeBrightness = AvesThemeBrightness.dark; + maxBrightness = MaxBrightness.never; + mustBackTwiceToExit = false; + // address `TV-BU` / `TV-BY` requirements from https://developer.android.com/docs/quality-guidelines/tv-app-quality + keepScreenOn = KeepScreenOn.videoPlayback; + drawerTypeBookmarks = [ + null, + MimeFilter.video, + FavouriteFilter.instance, + ]; + drawerPageBookmarks = [ + AlbumListPage.routeName, + CountryListPage.routeName, + PlaceListPage.routeName, + TagListPage.routeName, + SearchPage.routeName, + ]; + bottomNavigationActions = []; + showOverlayOnOpening = false; + showOverlayMinimap = false; + showOverlayZoomLevel = false; + showOverlayThumbnailPreview = false; + viewerGestureSideTapNext = false; + viewerUseCutout = true; + videoBackgroundMode = VideoBackgroundMode.disabled; + videoControlActions = []; + videoGestureDoubleTapTogglePlay = false; + videoGestureSideDoubleTapSeek = false; + enableBin = false; + showPinchGestureAlternatives = true; + resetShowTitleQuery(); + } + + Future<void> sanitize() async { + if (timeToTakeAction == AccessibilityTimeout.system && !await AccessibilityService.hasRecommendedTimeouts()) { + set(SettingKeys.timeToTakeActionKey, null); + } + if (viewerUseCutout != SettingsDefaults.viewerUseCutout && !await windowService.isCutoutAware()) { + set(SettingKeys.viewerUseCutoutKey, null); + } + if (videoBackgroundMode == VideoBackgroundMode.pip && !device.supportPictureInPicture) { + set(SettingKeys.videoBackgroundModeKey, null); + } + collectionBurstPatterns = collectionBurstPatterns.where(BurstPatterns.options.contains).toList(); + } + + // tag editor + + bool get tagEditorCurrentFilterSectionExpanded => getBool(SettingKeys.tagEditorCurrentFilterSectionExpandedKey) ?? SettingsDefaults.tagEditorCurrentFilterSectionExpanded; + + set tagEditorCurrentFilterSectionExpanded(bool newValue) => set(SettingKeys.tagEditorCurrentFilterSectionExpandedKey, newValue); + + String? get tagEditorExpandedSection => getString(SettingKeys.tagEditorExpandedSectionKey); + + set tagEditorExpandedSection(String? newValue) => set(SettingKeys.tagEditorExpandedSectionKey, newValue); + + // converter + + String get convertMimeType => getString(SettingKeys.convertMimeTypeKey) ?? SettingsDefaults.convertMimeType; + + set convertMimeType(String newValue) => set(SettingKeys.convertMimeTypeKey, newValue); + + int get convertQuality => getInt(SettingKeys.convertQualityKey) ?? SettingsDefaults.convertQuality; + + set convertQuality(int newValue) => set(SettingKeys.convertQualityKey, newValue); + + bool get convertWriteMetadata => getBool(SettingKeys.convertWriteMetadataKey) ?? SettingsDefaults.convertWriteMetadata; + + set convertWriteMetadata(bool newValue) => set(SettingKeys.convertWriteMetadataKey, newValue); + + // map + + EntryMapStyle? get mapStyle { + var preferred = getString(SettingKeys.mapStyleKey); + + // backward compatibility with definition as enum + const oldEnumPrefix = 'EntryMapStyle.'; + if (preferred != null && preferred.startsWith(oldEnumPrefix)) { + preferred = preferred.substring(oldEnumPrefix.length); + if (preferred.isEmpty) preferred = null; + } + + if (preferred == null) return null; + + final styles = [...availability.mapStyles, ...customMapStyles]; + return styles.firstWhereOrNull((v) => v.key == preferred) ?? styles.first; + } + + set mapStyle(EntryMapStyle? newValue) => set(SettingKeys.mapStyleKey, newValue?.key); + + LatLng? get mapDefaultCenter { + final json = getString(SettingKeys.mapDefaultCenterKey); + return json != null ? LatLng.fromJson(jsonDecode(json)) : null; + } + + set mapDefaultCenter(LatLng? newValue) => set(SettingKeys.mapDefaultCenterKey, newValue != null ? jsonEncode(newValue.toJson()) : null); + + Set<EntryMapStyle> get customMapStyles => (getStringList(SettingKeys.customMapStylesKey) ?? []).map(EntryMapStyle.fromJson).nonNulls.toSet(); + + set customMapStyles(Set<EntryMapStyle> newValue) => set(SettingKeys.customMapStylesKey, newValue.map((filter) => filter.toJson()).toList()); + + // bin + + bool get enableBin => getBool(SettingKeys.enableBinKey) ?? SettingsDefaults.enableBin; + + set enableBin(bool newValue) => set(SettingKeys.enableBinKey, newValue); + + // accessibility + + bool get showPinchGestureAlternatives => getBool(SettingKeys.showPinchGestureAlternativesKey) ?? SettingsDefaults.showPinchGestureAlternatives; + + set showPinchGestureAlternatives(bool newValue) => set(SettingKeys.showPinchGestureAlternativesKey, newValue); + + AccessibilityAnimations get accessibilityAnimations => getEnumOrDefault(SettingKeys.accessibilityAnimationsKey, SettingsDefaults.accessibilityAnimations, AccessibilityAnimations.values); + + bool get animate => accessibilityAnimations.animate; + + set accessibilityAnimations(AccessibilityAnimations newValue) => set(SettingKeys.accessibilityAnimationsKey, newValue.toString()); + + AccessibilityTimeout get timeToTakeAction => getEnumOrDefault(SettingKeys.timeToTakeActionKey, SettingsDefaults.timeToTakeAction, AccessibilityTimeout.values); + + set timeToTakeAction(AccessibilityTimeout newValue) => set(SettingKeys.timeToTakeActionKey, newValue.toString()); + + // platform settings + + void _onPlatformSettingsChanged(Map? fields) { + fields?.forEach((key, value) { + switch (key) { + case SettingKeys.platformAccelerometerRotationKey: + if (value is num) { + isRotationLocked = value == 0; + } + case SettingKeys.platformTransitionAnimationScaleKey: + if (value is num) { + areAnimationsRemoved = value == 0; + } + case SettingKeys.platformLongPressTimeoutMillisKey: + if (value is num) { + longPressTimeoutMillis = value.toInt(); + } + } + }); + } + + bool get isRotationLocked => getBool(SettingKeys.platformAccelerometerRotationKey) ?? SettingsDefaults.isRotationLocked; + + set isRotationLocked(bool newValue) => set(SettingKeys.platformAccelerometerRotationKey, newValue); + + bool get areAnimationsRemoved => getBool(SettingKeys.platformTransitionAnimationScaleKey) ?? SettingsDefaults.areAnimationsRemoved; + + set areAnimationsRemoved(bool newValue) => set(SettingKeys.platformTransitionAnimationScaleKey, newValue); + + Duration get longPressTimeout => Duration(milliseconds: getInt(SettingKeys.platformLongPressTimeoutMillisKey) ?? kLongPressTimeout.inMilliseconds); + + set longPressTimeoutMillis(int newValue) => set(SettingKeys.platformLongPressTimeoutMillisKey, newValue); + + // import/export + + Map<String, dynamic> export() => Map.fromEntries( + store.getKeys().whereNot(SettingKeys.isInternalKey).map((k) => MapEntry(k, store.get(k))), + ); + + Future<void> import(dynamic jsonMap) async { + if (jsonMap is Map<String, dynamic>) { + // clear to restore defaults + await reset(includeInternalKeys: false); + + // apply user modifications + jsonMap.forEach((key, newValue) { + final oldValue = store.get(key); + + if (newValue == null) { + store.remove(key); + } else if (key.startsWith(SettingKeys.tileExtentPrefixKey)) { + if (newValue is double) { + store.setDouble(key, newValue); + } else { + debugPrint('failed to import key=$key, value=$newValue is not a double'); + } + } else if (key.startsWith(SettingKeys.tileLayoutPrefixKey)) { + if (newValue is String) { + store.setString(key, newValue); + } else { + debugPrint('failed to import key=$key, value=$newValue is not a string'); + } + } else if (key.startsWith(SettingKeys.showTitleQueryPrefixKey)) { + if (newValue is bool) { + store.setBool(key, newValue); + } else { + debugPrint('failed to import key=$key, value=$newValue is not a bool'); + } + } else { + switch (key) { + case SettingKeys.convertQualityKey: + case SettingKeys.screenSaverIntervalKey: + case SettingKeys.slideshowIntervalKey: + if (newValue is int) { + store.setInt(key, newValue); + } else { + debugPrint('failed to import key=$key, value=$newValue is not an int'); + } + case SettingKeys.subtitleFontSizeKey: + case SettingKeys.infoMapZoomKey: + if (newValue is double) { + store.setDouble(key, newValue); + } else { + debugPrint('failed to import key=$key, value=$newValue is not a double'); + } + case SettingKeys.isInstalledAppAccessAllowedKey: + case SettingKeys.isErrorReportingAllowedKey: + case SettingKeys.forceWesternArabicNumeralsKey: + case SettingKeys.enableDynamicColorKey: + case SettingKeys.enableBlurEffectKey: + case SettingKeys.mustBackTwiceToExitKey: + case SettingKeys.confirmCreateVaultKey: + case SettingKeys.confirmDeleteForeverKey: + case SettingKeys.confirmMoveToBinKey: + case SettingKeys.confirmMoveUndatedItemsKey: + case SettingKeys.confirmAfterMoveToBinKey: + case SettingKeys.setMetadataDateBeforeFileOpKey: + case SettingKeys.collectionSortReverseKey: + case SettingKeys.showThumbnailFavouriteKey: + case SettingKeys.showThumbnailHdrKey: + case SettingKeys.showThumbnailMotionPhotoKey: + case SettingKeys.showThumbnailRatingKey: + case SettingKeys.showThumbnailRawKey: + case SettingKeys.showThumbnailVideoDurationKey: + case SettingKeys.albumSortReverseKey: + case SettingKeys.countrySortReverseKey: + case SettingKeys.stateSortReverseKey: + case SettingKeys.placeSortReverseKey: + case SettingKeys.tagSortReverseKey: + case SettingKeys.showOverlayOnOpeningKey: + case SettingKeys.showOverlayMinimapKey: + case SettingKeys.showOverlayZoomLevelKey: + case SettingKeys.showOverlayInfoKey: + case SettingKeys.showOverlayDescriptionKey: + case SettingKeys.showOverlayRatingTagsKey: + case SettingKeys.showOverlayShootingDetailsKey: + case SettingKeys.showOverlayThumbnailPreviewKey: + case SettingKeys.viewerGestureSideTapNextKey: + case SettingKeys.viewerUseCutoutKey: + case SettingKeys.enableMotionPhotoAutoPlayKey: + case SettingKeys.enableVideoHardwareAccelerationKey: + case SettingKeys.videoGestureDoubleTapTogglePlayKey: + case SettingKeys.videoGestureSideDoubleTapSeekKey: + case SettingKeys.videoGestureVerticalDragBrightnessVolumeKey: + case SettingKeys.subtitleShowOutlineKey: + case SettingKeys.tagEditorCurrentFilterSectionExpandedKey: + case SettingKeys.convertWriteMetadataKey: + case SettingKeys.saveSearchHistoryKey: + case SettingKeys.showPinchGestureAlternativesKey: + case SettingKeys.screenSaverFillScreenKey: + case SettingKeys.screenSaverAnimatedZoomEffectKey: + case SettingKeys.slideshowRepeatKey: + case SettingKeys.slideshowShuffleKey: + case SettingKeys.slideshowFillScreenKey: + case SettingKeys.slideshowAnimatedZoomEffectKey: + if (newValue is bool) { + store.setBool(key, newValue); + } else { + debugPrint('failed to import key=$key, value=$newValue is not a bool'); + } + case SettingKeys.localeKey: + case SettingKeys.displayRefreshRateModeKey: + case SettingKeys.themeBrightnessKey: + case SettingKeys.themeColorModeKey: + case SettingKeys.maxBrightnessKey: + case SettingKeys.keepScreenOnKey: + case SettingKeys.homePageKey: + case SettingKeys.homeCustomExplorerPathKey: + case SettingKeys.collectionGroupFactorKey: + case SettingKeys.collectionSortFactorKey: + case SettingKeys.thumbnailLocationIconKey: + case SettingKeys.thumbnailTagIconKey: + case SettingKeys.albumSectionFactorKey: + case SettingKeys.albumSortFactorKey: + case SettingKeys.countrySortFactorKey: + case SettingKeys.stateSortFactorKey: + case SettingKeys.placeSortFactorKey: + case SettingKeys.tagSortFactorKey: + case SettingKeys.albumGroupsKey: + case SettingKeys.tagGroupsKey: + case SettingKeys.imageBackgroundKey: + case SettingKeys.videoAutoPlayModeKey: + case SettingKeys.videoBackgroundModeKey: + case SettingKeys.videoLoopModeKey: + case SettingKeys.videoResumptionModeKey: + case SettingKeys.subtitleTextAlignmentKey: + case SettingKeys.subtitleTextPositionKey: + case SettingKeys.subtitleTextColorKey: + case SettingKeys.subtitleBackgroundColorKey: + case SettingKeys.tagEditorExpandedSectionKey: + case SettingKeys.convertMimeTypeKey: + case SettingKeys.mapStyleKey: + case SettingKeys.mapDefaultCenterKey: + case SettingKeys.coordinateFormatKey: + case SettingKeys.unitSystemKey: + case SettingKeys.accessibilityAnimationsKey: + case SettingKeys.timeToTakeActionKey: + case SettingKeys.screenSaverTransitionKey: + case SettingKeys.screenSaverVideoPlaybackKey: + case SettingKeys.slideshowTransitionKey: + case SettingKeys.slideshowVideoPlaybackKey: + if (newValue is String) { + store.setString(key, newValue); + } else { + debugPrint('failed to import key=$key, value=$newValue is not a string'); + } + case SettingKeys.customMapStylesKey: + case SettingKeys.homeCustomCollectionKey: + case SettingKeys.drawerTypeBookmarksKey: + case SettingKeys.drawerAlbumBookmarksKey: + case SettingKeys.drawerPageBookmarksKey: + case SettingKeys.bottomNavigationActionsKey: + case SettingKeys.collectionBurstPatternsKey: + case SettingKeys.pinnedFiltersKey: + case SettingKeys.hiddenFiltersKey: + case SettingKeys.deactivatedHiddenFiltersKey: + case SettingKeys.collectionBrowsingQuickActionsKey: + case SettingKeys.collectionSelectionQuickActionsKey: + case SettingKeys.viewerQuickActionsKey: + case SettingKeys.videoControlActionsKey: + case SettingKeys.screenSaverCollectionFiltersKey: + if (newValue is List) { + store.setStringList(key, newValue.cast<String>()); + } else { + debugPrint('failed to import key=$key, value=$newValue is not a list'); + } + } + } + if (oldValue != newValue) { + notifyKeyChange(key, oldValue, newValue); + } + }); + await sanitize(); + notifyListeners(); + } + } + + @override + void notifyKeyChange(String key, dynamic oldValue, dynamic newValue) { + _updateStreamController.add(SettingsChangedEvent(key, oldValue, newValue)); + if (key.startsWith(SettingKeys.tileExtentPrefixKey)) { + _updateTileExtentStreamController.add(SettingsChangedEvent(key, oldValue, newValue)); + } + } +} diff --git a/lib/model/settings/store_shared_pref.dart b/lib/model/settings/store_shared_pref.dart new file mode 100644 index 0000000..6547d8c --- /dev/null +++ b/lib/model/settings/store_shared_pref.dart @@ -0,0 +1,68 @@ +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/foundation.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +class SharedPrefSettingsStore implements SettingsStore { + static SharedPreferences? _prefs; + + @override + bool get initialized => _prefs != null; + + @override + Future<void> init() async { + try { + _prefs = await SharedPreferences.getInstance(); + } catch (error, stack) { + debugPrint('$runtimeType init error=$error\n$stack'); + } + } + + @override + Future<void> reload() => _prefs!.reload(); + + @override + Future<bool> clear() => _prefs!.clear(); + + @override + Future<bool> remove(String key) => _prefs!.remove(key); + + // get + + @override + Set<String> getKeys() => _prefs!.getKeys(); + + @override + Object? get(String key) => _prefs!.get(key); + + @override + bool? getBool(String key) => _prefs!.getBool(key); + + @override + int? getInt(String key) => _prefs!.getInt(key); + + @override + double? getDouble(String key) => _prefs!.getDouble(key); + + @override + String? getString(String key) => _prefs!.getString(key); + + @override + List<String>? getStringList(String key) => _prefs!.getStringList(key); + + // set + + @override + Future<bool> setBool(String key, bool value) => _prefs!.setBool(key, value); + + @override + Future<bool> setInt(String key, int value) => _prefs!.setInt(key, value); + + @override + Future<bool> setDouble(String key, double value) => _prefs!.setDouble(key, value); + + @override + Future<bool> setString(String key, String value) => _prefs!.setString(key, value); + + @override + Future<bool> setStringList(String key, List<String> value) => _prefs!.setStringList(key, value); +} diff --git a/lib/model/source/album.dart b/lib/model/source/album.dart new file mode 100644 index 0000000..a3fea5a --- /dev/null +++ b/lib/model/source/album.dart @@ -0,0 +1,274 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/filters/container/album_group.dart'; +import 'package:aves/model/filters/container/dynamic_album.dart'; +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/model/vaults/vaults.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/utils/android_file_utils.dart'; +import 'package:aves/utils/collection_utils.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/widgets.dart'; + +mixin AlbumMixin on SourceBase { + final Set<String> _directories = {}; + final Set<String> _newAlbums = {}; + + List<String> get rawAlbums => List.unmodifiable(_directories); + + Set<StoredAlbumFilter> getNewAlbumFilters(BuildContext context) => Set.unmodifiable(_newAlbums.map((v) => StoredAlbumFilter(v, getStoredAlbumDisplayName(context, v)))); + + int compareAlbumsByPath(String? a, String? b) => compareAsciiUpperCase(a ??= '', b ??= ''); + + int compareAlbumsByName(String? a, String? b) { + a ??= ''; + b ??= ''; + final ua = getStoredAlbumDisplayName(null, a); + final ub = getStoredAlbumDisplayName(null, b); + final c = compareAsciiUpperCaseNatural(ua, ub); + if (c != 0) return c; + final va = androidFileUtils.getStorageVolume(a)?.path ?? ''; + final vb = androidFileUtils.getStorageVolume(b)?.path ?? ''; + return compareAsciiUpperCaseNatural(va, vb); + } + + void notifyAlbumsChanged() { + eventBus.fire(AlbumsChangedEvent()); + } + + void _onAlbumChanged({bool notify = true}) { + invalidateStoredAlbumDisplayNames(); + if (notify) { + notifyAlbumsChanged(); + } + } + + Map<String, AvesEntry?> getAlbumEntries() { + final entries = sortedEntriesByDate; + final regularAlbums = <String>[], appAlbums = <String>[], specialAlbums = <String>[]; + for (final album in rawAlbums) { + switch (androidFileUtils.getAlbumType(album)) { + case AlbumType.regular: + regularAlbums.add(album); + case AlbumType.app: + appAlbums.add(album); + default: + specialAlbums.add(album); + } + } + return Map.fromEntries([...specialAlbums, ...appAlbums, ...regularAlbums].map((album) => MapEntry( + album, + entries.firstWhereOrNull((entry) => entry.directory == album), + ))); + } + + void updateDirectories() { + addDirectories(albums: { + ...visibleEntries.map((entry) => entry.directory), + ...vaults.all.map((v) => v.path), + }); + cleanEmptyAlbums(); + } + + void addDirectories({required Set<String?> albums, bool notify = true}) { + if (!_directories.containsAll(albums)) { + _directories.addAll(albums.nonNulls); + _onAlbumChanged(notify: notify); + } + } + + void cleanEmptyAlbums([Set<String>? albums]) { + final removableAlbums = (albums ?? _directories).where(_isRemovable).toSet(); + if (removableAlbums.isNotEmpty) { + _directories.removeAll(removableAlbums); + _onAlbumChanged(); + invalidateAlbumFilterSummary(directories: removableAlbums); + } + } + + bool _isRemovable(String album) { + if (visibleEntries.any((entry) => entry.directory == album)) return false; + if (_newAlbums.contains(album)) return false; + if (vaults.isVault(album)) return false; + if (settings.pinnedFilters.whereType<StoredAlbumFilter>().map((v) => v.album).contains(album)) return false; + return true; + } + + // filter summary + + // by filter key + final Map<String, int> _filterEntryCountMap = {}, _filterSizeMap = {}; + final Map<String, AvesEntry?> _filterRecentEntryMap = {}; + + void invalidateAlbumFilterSummary({ + Set<AvesEntry>? entries, + Set<String?>? directories, + bool notify = true, + }) { + if (_filterEntryCountMap.isEmpty && _filterSizeMap.isEmpty && _filterRecentEntryMap.isEmpty) return; + + if (entries == null && directories == null) { + _filterEntryCountMap.clear(); + _filterSizeMap.clear(); + _filterRecentEntryMap.clear(); + } else { + // clear entries only for modified album directories + directories ??= {}; + if (entries != null) { + directories.addAll(entries.map((entry) => entry.directory).nonNulls); + } + directories.nonNulls.map((v) => StoredAlbumFilter(v, null).key).forEach((key) { + _filterEntryCountMap.remove(key); + _filterSizeMap.remove(key); + _filterRecentEntryMap.remove(key); + }); + + // clear entries for all dynamic albums and groups + invalidateDynamicAlbumFilterSummary(notify: false); + invalidateAlbumGroupFilterSummary(notify: false); + } + if (notify) { + eventBus.fire(StoredAlbumSummaryInvalidatedEvent(directories)); + eventBus.fire(const DynamicAlbumSummaryInvalidatedEvent()); + eventBus.fire(const AlbumGroupSummaryInvalidatedEvent()); + } + } + + void invalidateDynamicAlbumFilterSummary({bool notify = true}) { + _filterEntryCountMap.removeWhere(_isDynamicAlbumKey); + _filterSizeMap.removeWhere(_isDynamicAlbumKey); + _filterRecentEntryMap.removeWhere(_isDynamicAlbumKey); + + if (notify) { + eventBus.fire(const DynamicAlbumSummaryInvalidatedEvent()); + } + } + + void invalidateAlbumGroupFilterSummary({bool notify = true}) { + _filterEntryCountMap.removeWhere(_isAlbumGroupKey); + _filterSizeMap.removeWhere(_isAlbumGroupKey); + _filterRecentEntryMap.removeWhere(_isAlbumGroupKey); + + if (notify) { + eventBus.fire(const AlbumGroupSummaryInvalidatedEvent()); + } + } + + bool _isDynamicAlbumKey(String key, _) => key.startsWith('${DynamicAlbumFilter.type}-'); + + bool _isAlbumGroupKey(String key, _) => key.startsWith('${AlbumGroupFilter.type}-'); + + int albumEntryCount(AlbumBaseFilter filter) { + return _filterEntryCountMap.putIfAbsent(filter.key, () => visibleEntries.where(filter.test).length); + } + + int albumSize(AlbumBaseFilter filter) { + return _filterSizeMap.putIfAbsent(filter.key, () => visibleEntries.where(filter.test).map((v) => v.sizeBytes).sum); + } + + AvesEntry? albumRecentEntry(AlbumBaseFilter filter) { + return _filterRecentEntryMap.putIfAbsent(filter.key, () => sortedEntriesByDate.firstWhereOrNull(filter.test)); + } + + // new albums + + void createStoredAlbum(String directory) { + if (!_directories.contains(directory)) { + _newAlbums.add(directory); + addDirectories(albums: {directory}); + } + } + + void renameNewAlbum(String source, String destination) { + if (_newAlbums.remove(source)) { + cleanEmptyAlbums({source}); + createStoredAlbum(destination); + } + } + + void forgetNewAlbums(Set<String> directories) { + _newAlbums.removeAll(directories); + } + + // display names + + final Map<String, String> _albumDisplayNamesWithContext = {}, _albumDisplayNamesWithoutContext = {}; + + void invalidateStoredAlbumDisplayNames() { + _albumDisplayNamesWithContext.clear(); + _albumDisplayNamesWithoutContext.clear(); + } + + String _computeStoredAlbumDisplayName(BuildContext? context, String dirPath) { + final separator = pContext.separator; + assert(!dirPath.endsWith(separator)); + + final type = androidFileUtils.getAlbumType(dirPath); + if (context != null) { + final name = type.getName(context); + if (name != null) return name; + } + + if (type == AlbumType.vault) return pContext.basename(dirPath); + + final dir = androidFileUtils.relativeDirectoryFromPath(dirPath); + if (dir == null) return dirPath; + + final relativeDir = dir.relativeDir; + if (relativeDir.isEmpty) { + final volume = androidFileUtils.getStorageVolume(dirPath)!; + return volume.getDescription(context); + } + + String unique(String dirPath, Set<String> others) { + final parts = pContext.split(dirPath); + for (var i = parts.length - 1; i > 0; i--) { + final name = pContext.joinAll(['', ...parts.skip(i)]); + final testName = '$separator${name.toLowerCase()}'; + if (others.every((item) => !item.endsWith(testName))) return name; + } + return dirPath; + } + + final otherAlbumsOnDevice = _directories.nonNulls.where((item) => item != dirPath).map((v) => v.toLowerCase()).toSet(); + final uniqueNameInDevice = unique(dirPath, otherAlbumsOnDevice); + if (uniqueNameInDevice.length <= relativeDir.length) { + return uniqueNameInDevice; + } + + final volumePath = dir.volumePath.toLowerCase(); + String trimVolumePath(String? path) => path!.substring(dir.volumePath.length); + final otherAlbumsOnVolume = otherAlbumsOnDevice.where((path) => path.startsWith(volumePath)).map(trimVolumePath).toSet(); + final uniqueNameInVolume = unique(trimVolumePath(dirPath), otherAlbumsOnVolume); + final volume = androidFileUtils.getStorageVolume(dirPath)!; + if (volume.isPrimary) { + return uniqueNameInVolume; + } else { + return '$uniqueNameInVolume (${volume.getDescription(context)})'; + } + } + + String getStoredAlbumDisplayName(BuildContext? context, String dirPath) { + final names = (context != null ? _albumDisplayNamesWithContext : _albumDisplayNamesWithoutContext); + return names.putIfAbsent(dirPath, () => _computeStoredAlbumDisplayName(context, dirPath)); + } +} + +class AlbumsChangedEvent {} + +class DynamicAlbumSummaryInvalidatedEvent { + const DynamicAlbumSummaryInvalidatedEvent(); +} + +class AlbumGroupSummaryInvalidatedEvent { + const AlbumGroupSummaryInvalidatedEvent(); +} + +class StoredAlbumSummaryInvalidatedEvent { + final Set<String?>? directories; + + const StoredAlbumSummaryInvalidatedEvent(this.directories); +} diff --git a/lib/model/source/analysis_controller.dart b/lib/model/source/analysis_controller.dart new file mode 100644 index 0000000..1efde19 --- /dev/null +++ b/lib/model/source/analysis_controller.dart @@ -0,0 +1,37 @@ +import 'package:flutter/foundation.dart'; +import 'package:leak_tracker/leak_tracker.dart'; + +class AnalysisController { + final bool canStartService, force; + final int progressTotal, progressOffset; + final List<int>? entryIds; + + final ValueNotifier<bool> _stopSignal = ValueNotifier(false); + + AnalysisController({ + this.canStartService = true, + this.entryIds, + this.force = false, + this.progressTotal = 0, + this.progressOffset = 0, + }) { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectCreated( + library: 'aves', + className: '$AnalysisController', + object: this, + ); + } + } + + void dispose() { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectDisposed(object: this); + } + _stopSignal.dispose(); + } + + bool get isStopping => _stopSignal.value; + + void enableStopSignal() => _stopSignal.value = true; +} diff --git a/lib/model/source/collection_lens.dart b/lib/model/source/collection_lens.dart new file mode 100644 index 0000000..7df7e8d --- /dev/null +++ b/lib/model/source/collection_lens.dart @@ -0,0 +1,435 @@ +import 'dart:async'; +import 'dart:collection'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/multipage.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/model/entry/sort.dart'; +import 'package:aves/model/favourites.dart'; +import 'package:aves/model/filters/covered/location.dart'; +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/filters/favourite.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/filters/query.dart'; +import 'package:aves/model/filters/rating.dart'; +import 'package:aves/model/filters/trash.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/model/source/events.dart'; +import 'package:aves/model/source/location/location.dart'; +import 'package:aves/model/source/section_keys.dart'; +import 'package:aves/model/source/tag.dart'; +import 'package:aves/ref/mime_types.dart'; +import 'package:aves/utils/collection_utils.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:aves_utils/aves_utils.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; + +class CollectionLens with ChangeNotifier { + final CollectionSource source; + final Set<CollectionFilter> filters; + List<String> burstPatterns; + EntrySectionFactor sectionFactor; + EntrySortFactor sortFactor; + bool sortReverse; + final AChangeNotifier filterChangeNotifier = AChangeNotifier(), sortSectionChangeNotifier = AChangeNotifier(); + final Set<StreamSubscription> _subscriptions = {}; + int? id; + bool listenToSource, stackBursts, stackDevelopedRaws, fixedSort; + List<AvesEntry>? fixedSelection; + + final Set<AvesEntry> _syntheticEntries = {}; + List<AvesEntry> _filteredSortedEntries = []; + + Map<SectionKey, List<AvesEntry>> sections = Map.unmodifiable({}); + + CollectionLens({ + required this.source, + Set<CollectionFilter?>? filters, + this.id, + this.listenToSource = true, + this.stackBursts = true, + this.stackDevelopedRaws = true, + this.fixedSort = false, + this.fixedSelection, + }) : filters = (filters ?? {}).nonNulls.toSet(), + burstPatterns = settings.collectionBurstPatterns, + sectionFactor = settings.collectionSectionFactor, + sortFactor = settings.collectionSortFactor, + sortReverse = settings.collectionSortReverse { + if (kFlutterMemoryAllocationsEnabled) ChangeNotifier.maybeDispatchObjectCreation(this); + id ??= hashCode; + if (listenToSource) { + final sourceEvents = source.eventBus; + _subscriptions.add(sourceEvents.on<EntryAddedEvent>().listen((e) => _onEntryAdded(e.entries))); + _subscriptions.add(sourceEvents.on<EntryRemovedEvent>().listen((e) => _onEntryRemoved(e.entries))); + _subscriptions.add(sourceEvents.on<EntryMovedEvent>().listen((e) { + switch (e.type) { + case MoveType.copy: + case MoveType.export: + // refreshing new items is already handled via `EntryAddedEvent`s + break; + case MoveType.move: + case MoveType.fromBin: + refresh(); + case MoveType.toBin: + _onEntryRemoved(e.entries); + } + })); + _subscriptions.add(sourceEvents.on<EntryRefreshedEvent>().listen((e) => refresh())); + _subscriptions.add(sourceEvents.on<FilterVisibilityChangedEvent>().listen((e) => refresh())); + _subscriptions.add(sourceEvents.on<CatalogMetadataChangedEvent>().listen((e) => refresh())); + _subscriptions.add(sourceEvents.on<AddressMetadataChangedEvent>().listen((e) { + if (this.filters.any((filter) => filter is LocationFilter)) { + refresh(); + } + })); + favourites.addListener(_onFavouritesChanged); + } + _subscriptions.add(settings.updateStream + .where((event) => [ + SettingKeys.collectionBurstPatternsKey, + SettingKeys.collectionSortFactorKey, + SettingKeys.collectionGroupFactorKey, + SettingKeys.collectionSortReverseKey, + ].contains(event.key)) + .listen((_) => _onSettingsChanged())); + refresh(); + } + + @override + void dispose() { + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + favourites.removeListener(_onFavouritesChanged); + filterChangeNotifier.dispose(); + sortSectionChangeNotifier.dispose(); + _disposeSyntheticEntries(); + super.dispose(); + } + + CollectionLens copyWith({ + CollectionSource? source, + Set<CollectionFilter>? filters, + bool? listenToSource, + List<AvesEntry>? fixedSelection, + }) => + CollectionLens( + source: source ?? this.source, + filters: filters ?? this.filters, + id: id, + listenToSource: listenToSource ?? this.listenToSource, + fixedSelection: fixedSelection ?? this.fixedSelection, + ); + + void _disposeSyntheticEntries() { + _syntheticEntries.forEach((v) => v.dispose()); + _syntheticEntries.clear(); + } + + bool get isEmpty => _filteredSortedEntries.isEmpty; + + int get entryCount => _filteredSortedEntries.length; + + // sorted as displayed to the user, i.e. sorted then sectioned, not an absolute order on all entries + List<AvesEntry>? _sortedEntries; + + List<AvesEntry> get sortedEntries { + _sortedEntries ??= List.of(sections.entries.expand((kv) => kv.value)); + return _sortedEntries!; + } + + bool get showHeaders { + bool showAlbumHeaders() => !filters.any((v) => v is StoredAlbumFilter && !v.reversed); + + switch (sortFactor) { + case EntrySortFactor.date: + switch (sectionFactor) { + case EntrySectionFactor.none: + return false; + case EntrySectionFactor.album: + return showAlbumHeaders(); + case EntrySectionFactor.month: + return true; + case EntrySectionFactor.day: + return true; + } + case EntrySortFactor.name: + case EntrySortFactor.path: + return showAlbumHeaders(); + case EntrySortFactor.rating: + return !filters.any((f) => f is RatingFilter); + case EntrySortFactor.size: + case EntrySortFactor.duration: + return false; + } + } + + void addFilters(Set<CollectionFilter> newFilters) { + if (filters.containsAll(newFilters)) return; + for (final filter in newFilters) { + filters.removeWhere((other) => !filter.isCompatible(other)); + } + filters.addAll(newFilters); + _onFilterChanged(); + } + + void removeFilter(CollectionFilter filter) { + if (!filters.contains(filter)) return; + filters.remove(filter); + _onFilterChanged(); + } + + void setLiveQuery(String query) { + filters.removeWhere((v) => v is QueryFilter && v.live); + if (query.isNotEmpty) { + filters.add(QueryFilter(query, live: true)); + } + _onFilterChanged(); + } + + void _onFilterChanged() { + refresh(); + filterChangeNotifier.notifyListeners(); + } + + void _applyFilters() { + final entries = fixedSelection ?? (filters.contains(TrashFilter.instance) ? source.trashedEntries : source.visibleEntries); + _disposeSyntheticEntries(); + _filteredSortedEntries = List.of(filters.isEmpty ? entries : entries.where((entry) => filters.every((filter) => filter.test(entry)))); + + if (stackBursts) { + _stackBursts(); + } + if (stackDevelopedRaws) { + _stackDevelopedRaws(); + } + } + + void _stackBursts() { + final byBurstKey = groupBy<AvesEntry, String?>(_filteredSortedEntries, (entry) => entry.getBurstKey(burstPatterns)).whereNotNullKey(); + byBurstKey.forEach((burstKey, entries) { + if (entries.length > 1) { + entries.sort(AvesEntrySort.compareByName); + final mainEntry = entries.first; + final stackEntry = mainEntry.copyWith(stackedEntries: entries); + _syntheticEntries.add(stackEntry); + + entries.skip(1).forEach((subEntry) { + _filteredSortedEntries.remove(subEntry); + }); + final index = _filteredSortedEntries.indexOf(mainEntry); + _filteredSortedEntries.removeAt(index); + _filteredSortedEntries.insert(index, stackEntry); + } + }); + } + + void _stackDevelopedRaws() { + final allRawEntries = _filteredSortedEntries.where((entry) => entry.isRaw).toSet(); + if (allRawEntries.isNotEmpty) { + final allDevelopedEntries = _filteredSortedEntries.where((entry) => MimeTypes.developedRawImages.contains(entry.mimeType)).toSet(); + final rawEntriesByDir = groupBy<AvesEntry, String?>(allRawEntries, (entry) => entry.directory); + rawEntriesByDir.forEach((dir, dirRawEntries) { + if (dir != null) { + final dirDevelopedEntries = allDevelopedEntries.where((entry) => entry.directory == dir).toSet(); + for (final rawEntry in dirRawEntries) { + final rawFilename = rawEntry.filenameWithoutExtension; + final developedEntry = dirDevelopedEntries.firstWhereOrNull((entry) => entry.filenameWithoutExtension == rawFilename); + if (developedEntry != null) { + final mainEntry = developedEntry; + final subEntry = rawEntry; + + final stackEntry = mainEntry.copyWith(stackedEntries: [mainEntry, subEntry]); + _syntheticEntries.add(stackEntry); + + _filteredSortedEntries.remove(subEntry); + final index = _filteredSortedEntries.indexOf(mainEntry); + _filteredSortedEntries.removeAt(index); + _filteredSortedEntries.insert(0, stackEntry); + } + } + } + }); + } + } + + void _applySort() { + if (fixedSort) return; + + switch (sortFactor) { + case EntrySortFactor.date: + _filteredSortedEntries.sort(AvesEntrySort.compareByDate); + case EntrySortFactor.name: + _filteredSortedEntries.sort(AvesEntrySort.compareByName); + case EntrySortFactor.rating: + _filteredSortedEntries.sort(AvesEntrySort.compareByRating); + case EntrySortFactor.size: + _filteredSortedEntries.sort(AvesEntrySort.compareBySize); + case EntrySortFactor.duration: + _filteredSortedEntries.sort(AvesEntrySort.compareByDuration); + case EntrySortFactor.path: + _filteredSortedEntries.sort(AvesEntrySort.compareByPath); + } + if (sortReverse) { + _filteredSortedEntries = _filteredSortedEntries.reversed.toList(); + } + } + + void _applySection() { + if (fixedSort) { + sections = Map.fromEntries([ + MapEntry(const SectionKey(), _filteredSortedEntries), + ]); + } else { + switch (sortFactor) { + case EntrySortFactor.date: + switch (sectionFactor) { + case EntrySectionFactor.album: + sections = groupBy<AvesEntry, EntryAlbumSectionKey>(_filteredSortedEntries, (entry) => EntryAlbumSectionKey(entry.directory)); + case EntrySectionFactor.month: + sections = groupBy<AvesEntry, EntryDateSectionKey>(_filteredSortedEntries, (entry) => EntryDateSectionKey(entry.monthTaken)); + case EntrySectionFactor.day: + sections = groupBy<AvesEntry, EntryDateSectionKey>(_filteredSortedEntries, (entry) => EntryDateSectionKey(entry.dayTaken)); + case EntrySectionFactor.none: + sections = Map.fromEntries([ + MapEntry(const SectionKey(), _filteredSortedEntries), + ]); + } + case EntrySortFactor.name: + final byAlbum = groupBy<AvesEntry, EntryAlbumSectionKey>(_filteredSortedEntries, (entry) => EntryAlbumSectionKey(entry.directory)); + final int Function(EntryAlbumSectionKey, EntryAlbumSectionKey) compare = sortReverse ? (a, b) => source.compareAlbumsByName(b.directory, a.directory) : (a, b) => source.compareAlbumsByName(a.directory, b.directory); + sections = SplayTreeMap<EntryAlbumSectionKey, List<AvesEntry>>.of(byAlbum, compare); + case EntrySortFactor.rating: + sections = groupBy<AvesEntry, EntryRatingSectionKey>(_filteredSortedEntries, (entry) => EntryRatingSectionKey(entry.rating)); + case EntrySortFactor.size: + case EntrySortFactor.duration: + sections = Map.fromEntries([ + MapEntry(const SectionKey(), _filteredSortedEntries), + ]); + case EntrySortFactor.path: + final byAlbum = groupBy<AvesEntry, EntryAlbumSectionKey>(_filteredSortedEntries, (entry) => EntryAlbumSectionKey(entry.directory)); + final int Function(EntryAlbumSectionKey, EntryAlbumSectionKey) compare = sortReverse ? (a, b) => source.compareAlbumsByPath(b.directory, a.directory) : (a, b) => source.compareAlbumsByPath(a.directory, b.directory); + sections = SplayTreeMap<EntryAlbumSectionKey, List<AvesEntry>>.of(byAlbum, compare); + } + } + sections = Map.unmodifiable(sections); + _sortedEntries = null; + notifyListeners(); + } + + // metadata change should also trigger a full refresh + // as dates impact sorting and sectioning + void refresh() { + _applyFilters(); + _applySort(); + _applySection(); + } + + void _onFavouritesChanged() { + if (filters.any((filter) => filter is FavouriteFilter)) { + refresh(); + } + } + + void _onSettingsChanged() { + final newBurstPatterns = settings.collectionBurstPatterns; + final newSortFactor = settings.collectionSortFactor; + final newSectionFactor = settings.collectionSectionFactor; + final newSortReverse = settings.collectionSortReverse; + + final needFilter = burstPatterns != newBurstPatterns; + final needSort = needFilter || sortFactor != newSortFactor || sortReverse != newSortReverse; + final needSection = needSort || sectionFactor != newSectionFactor; + + if (needFilter) { + burstPatterns = newBurstPatterns; + _applyFilters(); + } + if (needSort) { + sortFactor = newSortFactor; + sortReverse = newSortReverse; + _applySort(); + } + if (needSection) { + sectionFactor = newSectionFactor; + _applySection(); + } + + if (needFilter) { + filterChangeNotifier.notifyListeners(); + } + if (needSort || needSection) { + sortSectionChangeNotifier.notifyListeners(); + } + } + + void _onEntryAdded(Set<AvesEntry>? entries) { + refresh(); + } + + void _onEntryRemoved(Set<AvesEntry> entries) { + if (_syntheticEntries.isNotEmpty) { + // find impacted stacks + final obsoleteStacks = <AvesEntry>{}; + + void _replaceStack(AvesEntry stackEntry, AvesEntry entry) { + obsoleteStacks.add(stackEntry); + fixedSelection?.replace(stackEntry, entry); + _filteredSortedEntries.replace(stackEntry, entry); + _sortedEntries?.replace(stackEntry, entry); + sections.forEach((key, sectionEntries) => sectionEntries.replace(stackEntry, entry)); + } + + final stacks = _filteredSortedEntries.where((entry) => entry.isStack).toSet(); + stacks.forEach((stackEntry) { + final subEntries = stackEntry.stackedEntries!; + if (subEntries.any(entries.contains)) { + final mainEntry = subEntries.first; + + // remove the deleted sub-entries + subEntries.removeWhere(entries.contains); + + switch (subEntries.length) { + case 0: + // remove the stack itself + obsoleteStacks.add(stackEntry); + break; + case 1: + // replace the stack by the last remaining sub-entry + _replaceStack(stackEntry, subEntries.first); + break; + default: + // keep the stack with the remaining sub-entries + if (!subEntries.contains(mainEntry)) { + // recreate the stack with the correct main entry + _replaceStack(stackEntry, subEntries.first.copyWith(stackedEntries: subEntries)); + } + break; + } + } + }); + + obsoleteStacks.forEach((stackEntry) { + _syntheticEntries.remove(stackEntry); + stackEntry.dispose(); + }); + entries.addAll(obsoleteStacks); + } + + // we should remove obsolete entries and sections + // but do not apply sort/section + // as section order change would surprise the user while browsing + fixedSelection?.removeWhere(entries.contains); + _filteredSortedEntries.removeWhere(entries.contains); + _sortedEntries?.removeWhere(entries.contains); + sections.forEach((key, sectionEntries) => sectionEntries.removeWhere(entries.contains)); + sections = Map.unmodifiable(Map.fromEntries(sections.entries.where((kv) => kv.value.isNotEmpty))); + notifyListeners(); + } + + @override + String toString() => '$runtimeType#${shortHash(this)}{id=$id, source=$source, filters=$filters, entryCount=$entryCount}'; +} diff --git a/lib/model/source/collection_source.dart b/lib/model/source/collection_source.dart new file mode 100644 index 0000000..e591691 --- /dev/null +++ b/lib/model/source/collection_source.dart @@ -0,0 +1,636 @@ +import 'dart:async'; +import 'dart:ui'; + +import 'package:aves/model/covers.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/catalog.dart'; +import 'package:aves/model/entry/extensions/keys.dart'; +import 'package:aves/model/entry/extensions/location.dart'; +import 'package:aves/model/entry/sort.dart'; +import 'package:aves/model/favourites.dart'; +import 'package:aves/model/filters/container/album_group.dart'; +import 'package:aves/model/filters/container/tag_group.dart'; +import 'package:aves/model/filters/covered/location.dart'; +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/filters/trash.dart'; +import 'package:aves/model/grouping/common.dart'; +import 'package:aves/model/grouping/convert.dart'; +import 'package:aves/model/metadata/trash.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/album.dart'; +import 'package:aves/model/source/analysis_controller.dart'; +import 'package:aves/model/source/events.dart'; +import 'package:aves/model/source/location/country.dart'; +import 'package:aves/model/source/location/location.dart'; +import 'package:aves/model/source/location/place.dart'; +import 'package:aves/model/source/location/state.dart'; +import 'package:aves/model/source/tag.dart'; +import 'package:aves/model/source/trash.dart'; +import 'package:aves/model/vaults/vaults.dart'; +import 'package:aves/services/analysis_service.dart'; +import 'package:aves/services/common/image_op_events.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/widgets/aves_app.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:event_bus/event_bus.dart'; +import 'package:flutter/foundation.dart'; +import 'package:leak_tracker/leak_tracker.dart'; + +typedef SourceScope = Set<CollectionFilter>?; + +mixin SourceBase { + EventBus get eventBus; + + Map<int, AvesEntry> get entryById; + + Set<AvesEntry> get allEntries; + + Set<AvesEntry> get visibleEntries; + + Set<AvesEntry> get trashedEntries; + + List<AvesEntry> get sortedEntriesByDate; + + ValueNotifier<SourceState> stateNotifier = ValueNotifier(SourceState.ready); + + set state(SourceState value) => stateNotifier.value = value; + + SourceState get state => stateNotifier.value; + + bool get isReady => state == SourceState.ready; + + ValueNotifier<ProgressEvent> progressNotifier = ValueNotifier(const ProgressEvent(done: 0, total: 0)); + + void setProgress({required int done, required int total}) => progressNotifier.value = ProgressEvent(done: done, total: total); + + void invalidateEntries(); +} + +abstract class CollectionSource with SourceBase, AlbumMixin, CountryMixin, PlaceMixin, StateMixin, LocationMixin, TagMixin, TrashMixin { + static const fullScope = <CollectionFilter>{}; + + CollectionSource() { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectCreated( + library: 'aves', + className: '$CollectionSource', + object: this, + ); + } + settings.updateStream.where((event) => event.key == SettingKeys.localeKey).listen((_) => invalidateStoredAlbumDisplayNames()); + settings.updateStream.where((event) => event.key == SettingKeys.hiddenFiltersKey).listen((event) { + final oldValue = event.oldValue; + if (oldValue is List<String>?) { + final oldHiddenFilters = (oldValue ?? []).map(CollectionFilter.fromJson).nonNulls.toSet(); + final newlyVisibleFilters = oldHiddenFilters.whereNot(settings.hiddenFilters.contains).toSet(); + _onFilterVisibilityChanged(newlyVisibleFilters); + } + }); + vaults.addListener(_onVaultsChanged); + } + + @mustCallSuper + void dispose() { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectDisposed(object: this); + } + vaults.removeListener(_onVaultsChanged); + _rawEntries.forEach((v) => v.dispose()); + } + + set canAnalyze(bool enabled); + + final EventBus _eventBus = EventBus(); + + @override + EventBus get eventBus => _eventBus; + + final Map<int, AvesEntry> _entryById = {}; + + @override + Map<int, AvesEntry> get entryById => Map.unmodifiable(_entryById); + + final Set<AvesEntry> _rawEntries = {}; + + @override + Set<AvesEntry> get allEntries => Set.unmodifiable(_rawEntries); + + Set<AvesEntry>? _visibleEntries, _trashedEntries; + + @override + Set<AvesEntry> get visibleEntries { + _visibleEntries ??= Set.unmodifiable(_applyHiddenFilters(_rawEntries)); + return _visibleEntries!; + } + + @override + Set<AvesEntry> get trashedEntries { + _trashedEntries ??= Set.unmodifiable(_applyTrashFilter(_rawEntries)); + return _trashedEntries!; + } + + List<AvesEntry>? _sortedEntriesByDate; + + @override + List<AvesEntry> get sortedEntriesByDate { + _sortedEntriesByDate ??= List.unmodifiable(visibleEntries.toList()..sort(AvesEntrySort.compareByDate)); + return _sortedEntriesByDate!; + } + + // known date by entry ID + late Map<int?, int?> _savedDates; + + Future<void> loadDates() async { + _savedDates = Map.unmodifiable(await localMediaDb.loadDates()); + } + + Set<CollectionFilter> _getAppHiddenFilters() => { + ...settings.hiddenFilters, + ...vaults.vaultDirectories.where(vaults.isLocked).map((v) => StoredAlbumFilter(v, null)), + }; + + Iterable<AvesEntry> _applyHiddenFilters(Iterable<AvesEntry> entries) { + final hiddenFilters = { + TrashFilter.instance, + ..._getAppHiddenFilters(), + }; + return entries.where((entry) => !hiddenFilters.any((filter) => filter.test(entry))); + } + + Iterable<AvesEntry> _applyTrashFilter(Iterable<AvesEntry> entries) { + final hiddenFilters = _getAppHiddenFilters(); + return entries.where(TrashFilter.instance.test).where((entry) => !hiddenFilters.any((filter) => filter.test(entry))); + } + + void _invalidate({Set<AvesEntry>? entries, bool notify = true}) { + invalidateEntries(); + invalidateAlbumFilterSummary(entries: entries, notify: notify); + invalidateCountryFilterSummary(entries: entries, notify: notify); + invalidatePlaceFilterSummary(entries: entries, notify: notify); + invalidateStateFilterSummary(entries: entries, notify: notify); + invalidateTagFilterSummary(entries: entries, notify: notify); + } + + @override + void invalidateEntries() { + _visibleEntries = null; + _trashedEntries = null; + _sortedEntriesByDate = null; + } + + void updateDerivedFilters([Set<AvesEntry>? entries]) { + _invalidate(entries: entries); + // it is possible for entries hidden by a filter type, to have an impact on other types + // e.g. given a sole entry for country C and tag T, hiding T should make C disappear too + updateDirectories(); + updateLocations(); + updateTags(); + } + + void addEntries(Set<AvesEntry> entries, {bool notify = true}) { + if (entries.isEmpty) return; + + final newIdMapEntries = Map.fromEntries(entries.map((entry) => MapEntry(entry.id, entry))); + if (_rawEntries.isNotEmpty) { + final newIds = newIdMapEntries.keys.toSet(); + _rawEntries.removeWhere((entry) => newIds.contains(entry.id)); + } + + entries.where((entry) => entry.catalogDateMillis == null).forEach((entry) { + entry.catalogDateMillis = _savedDates[entry.id]; + }); + + _entryById.addAll(newIdMapEntries); + _rawEntries.addAll(entries); + _invalidate(entries: entries, notify: notify); + + addDirectories(albums: _applyHiddenFilters(entries).map((entry) => entry.directory).toSet(), notify: notify); + if (notify) { + eventBus.fire(EntryAddedEvent(entries)); + } + } + + Future<void> removeEntries(Set<String> uris, {required bool includeTrash}) async { + if (uris.isEmpty) return; + + final entries = _rawEntries.where((entry) => uris.contains(entry.uri)).toSet(); + if (!includeTrash) { + entries.removeWhere(TrashFilter.instance.test); + } + if (entries.isEmpty) return; + + final ids = entries.map((entry) => entry.id).toSet(); + await favourites.removeIds(ids); + await covers.removeIds(ids); + await localMediaDb.removeIds(ids); + + ids.forEach((id) => _entryById.remove); + _rawEntries.removeAll(entries); + updateDerivedFilters(entries); + eventBus.fire(EntryRemovedEvent(entries)); + } + + void clearEntries() { + _entryById.clear(); + _rawEntries.clear(); + _invalidate(); + + // do not update directories/locations/tags here + // as it could reset filter dependent settings (pins, bookmarks, etc.) + // caller should take care of updating these at the right time + } + + Future<void> _moveEntry(AvesEntry entry, Map newFields, {required bool persist}) async { + newFields.keys.forEach((key) { + final newValue = newFields[key]; + switch (key) { + case EntryFields.contentId: + entry.contentId = newValue as int?; + case EntryFields.dateModifiedMillis: + // `dateModifiedMillis` changes when moving entries to another directory, + // but it does not change when renaming the containing directory + entry.dateModifiedMillis = newValue as int?; + case EntryFields.path: + entry.path = newValue as String?; + case EntryFields.title: + entry.sourceTitle = newValue as String?; + case EntryFields.trashed: + final trashed = newValue as bool; + entry.trashed = trashed; + entry.trashDetails = trashed + ? TrashDetails( + id: entry.id, + path: newFields[EntryFields.trashPath] as String, + dateMillis: DateTime.now().millisecondsSinceEpoch, + ) + : null; + case EntryFields.uri: + entry.uri = newValue as String; + case EntryFields.origin: + entry.origin = newValue as int; + } + }); + if (entry.trashed) { + final trashPath = entry.trashDetails?.path; + if (trashPath != null) { + entry.contentId = null; + entry.uri = Uri.file(trashPath).toString(); + } else { + debugPrint('failed to update uri from unknown trash path for uri=${entry.uri}'); + } + } + + if (persist) { + await covers.moveEntry(entry); + final id = entry.id; + await localMediaDb.updateEntry(id, entry); + await localMediaDb.updateCatalogMetadata(id, entry.catalogMetadata); + await localMediaDb.updateAddress(id, entry.addressDetails); + await localMediaDb.updateTrash(id, entry.trashDetails); + } + } + + Future<void> renameStoredAlbum(String sourceAlbum, String destinationAlbum, Set<AvesEntry> entries, Set<MoveOpEvent> movedOps) async { + final oldFilter = StoredAlbumFilter(sourceAlbum, null); + final newFilter = StoredAlbumFilter(destinationAlbum, null); + + final group = albumGrouping.getFilterParent(oldFilter); + final pinned = settings.pinnedFilters.contains(oldFilter); + + if (vaults.isVault(sourceAlbum)) { + await vaults.rename(sourceAlbum, destinationAlbum); + } + + final existingCover = covers.of(oldFilter); + await covers.set( + filter: newFilter, + entryId: existingCover?.$1, + packageName: existingCover?.$2, + color: existingCover?.$3, + ); + + renameNewAlbum(sourceAlbum, destinationAlbum); + await updateAfterMove( + todoEntries: entries, + moveType: MoveType.move, + destinationAlbums: {destinationAlbum}, + movedOps: movedOps, + ); + + // update bookmark + final albumBookmarks = settings.drawerAlbumBookmarks; + if (albumBookmarks != null) { + final index = albumBookmarks.indexWhere((v) => v is StoredAlbumFilter && v.album == sourceAlbum); + if (index >= 0) { + albumBookmarks.removeAt(index); + albumBookmarks.insert(index, newFilter); + settings.drawerAlbumBookmarks = albumBookmarks; + } + } + // update group + if (group != null) { + final newFilterUri = GroupingConversion.filterToUri(newFilter); + if (newFilterUri != null) { + albumGrouping.addToGroup({newFilterUri}, group); + } + final oldFilterUri = GroupingConversion.filterToUri(oldFilter); + if (oldFilterUri != null) { + albumGrouping.addToGroup({oldFilterUri}, null); + } + } + // restore pin, as the obsolete album got removed and its associated state cleaned + if (pinned) { + settings.pinnedFilters = settings.pinnedFilters + ..remove(oldFilter) + ..add(newFilter); + } + } + + Future<void> updateAfterMove({ + required Set<AvesEntry> todoEntries, + required MoveType moveType, + required Set<String> destinationAlbums, + required Set<MoveOpEvent> movedOps, + }) async { + if (movedOps.isEmpty) return; + + final replacedUris = movedOps + .map((movedOp) => movedOp.newFields[EntryFields.path] as String?) + .map((targetPath) { + final existingEntry = _rawEntries.firstWhereOrNull((entry) => entry.path == targetPath && !entry.trashed); + return existingEntry?.uri; + }) + .nonNulls + .toSet(); + await removeEntries(replacedUris, includeTrash: false); + + final fromAlbums = <String?>{}; + final movedEntries = <AvesEntry>{}; + final copy = moveType == MoveType.copy; + if (copy) { + movedOps.forEach((movedOp) { + final sourceUri = movedOp.uri; + final newFields = movedOp.newFields; + final sourceEntry = todoEntries.firstWhereOrNull((entry) => entry.uri == sourceUri); + if (sourceEntry != null) { + fromAlbums.add(sourceEntry.directory); + movedEntries.add(sourceEntry.copyWith( + id: localMediaDb.nextId, + uri: newFields[EntryFields.uri] as String?, + path: newFields[EntryFields.path] as String?, + contentId: newFields[EntryFields.contentId] as int?, + // title can change when moved files are automatically renamed to avoid conflict + title: newFields[EntryFields.title] as String?, + dateAddedSecs: newFields[EntryFields.dateAddedSecs] as int?, + dateModifiedMillis: newFields[EntryFields.dateModifiedMillis] as int?, + origin: newFields[EntryFields.origin] as int?, + )); + } else { + debugPrint('failed to find source entry with uri=$sourceUri'); + } + }); + await localMediaDb.insertEntries(movedEntries); + await localMediaDb.saveCatalogMetadata(movedEntries.map((entry) => entry.catalogMetadata).nonNulls.toSet()); + await localMediaDb.saveAddresses(movedEntries.map((entry) => entry.addressDetails).nonNulls.toSet()); + } else { + await Future.forEach<MoveOpEvent>(movedOps, (movedOp) async { + final newFields = movedOp.newFields; + if (newFields.isNotEmpty) { + final sourceUri = movedOp.uri; + final entry = todoEntries.firstWhereOrNull((entry) => entry.uri == sourceUri); + if (entry != null) { + if (moveType == MoveType.fromBin) { + newFields[EntryFields.trashed] = false; + } else { + fromAlbums.add(entry.directory); + } + movedEntries.add(entry); + await _moveEntry(entry, newFields, persist: true); + } + } + }); + } + + switch (moveType) { + case MoveType.copy: + addEntries(movedEntries); + case MoveType.move: + case MoveType.export: + cleanEmptyAlbums(fromAlbums.nonNulls.toSet()); + addDirectories(albums: destinationAlbums); + case MoveType.toBin: + case MoveType.fromBin: + updateDerivedFilters(movedEntries); + } + invalidateAlbumFilterSummary(directories: fromAlbums); + _invalidate(entries: movedEntries); + eventBus.fire(EntryMovedEvent(moveType, movedEntries)); + } + + Future<void> updateAfterRename({ + required Set<AvesEntry> todoEntries, + required Set<MoveOpEvent> movedOps, + required bool persist, + }) async { + if (movedOps.isEmpty) return; + + final movedEntries = <AvesEntry>{}; + await Future.forEach<MoveOpEvent>(movedOps, (movedOp) async { + final newFields = movedOp.newFields; + if (newFields.isNotEmpty) { + final sourceUri = movedOp.uri; + final entry = todoEntries.firstWhereOrNull((entry) => entry.uri == sourceUri); + if (entry != null) { + movedEntries.add(entry); + await _moveEntry(entry, newFields, persist: persist); + } + } + }); + + eventBus.fire(EntryMovedEvent(MoveType.move, movedEntries)); + } + + SourceScope get loadedScope; + + SourceScope get targetScope; + + Future<void> init({ + required SourceScope scope, + AnalysisController? analysisController, + bool loadTopEntriesFirst = false, + }); + + Future<Set<String>> refreshUris(Set<String> changedUris, {AnalysisController? analysisController}); + + Future<void> refreshEntries(Set<AvesEntry> entries, Set<EntryDataType> dataTypes) async { + const background = false; + const persist = true; + + await Future.forEach(entries, (entry) async { + await entry.refresh(background: background, persist: persist, dataTypes: dataTypes); + }); + + if (dataTypes.contains(EntryDataType.aspectRatio)) { + onAspectRatioChanged(); + } + + if (dataTypes.contains(EntryDataType.catalog)) { + // explicit GC before cataloguing multiple items + await deviceService.requestGarbageCollection(); + await Future.forEach(entries, (entry) async { + await entry.catalog(background: background, force: dataTypes.contains(EntryDataType.catalog), persist: persist); + await localMediaDb.updateCatalogMetadata(entry.id, entry.catalogMetadata); + }); + onCatalogMetadataChanged(); + } + + if (dataTypes.contains(EntryDataType.address)) { + await Future.forEach(entries, (entry) async { + await entry.locate(background: background, force: dataTypes.contains(EntryDataType.address), geocoderLocale: settings.appliedLocale); + await localMediaDb.updateAddress(entry.id, entry.addressDetails); + }); + onAddressMetadataChanged(); + } + + updateDerivedFilters(entries); + eventBus.fire(EntryRefreshedEvent(entries)); + } + + Future<void> analyze(AnalysisController? analysisController, {Set<AvesEntry>? entries}) async { + // not only visible entries, as hidden and vault items may be analyzed + final todoEntries = entries ?? allEntries; + final defaultAnalysisController = AnalysisController(); + final _analysisController = analysisController ?? defaultAnalysisController; + final force = _analysisController.force; + if (!_analysisController.isStopping) { + var startAnalysisService = false; + if (_analysisController.canStartService && settings.canUseAnalysisService) { + // cataloguing + if (!startAnalysisService) { + final opCount = (force ? todoEntries : todoEntries.where(TagMixin.catalogEntriesTest)).length; + startAnalysisService = opCount > TagMixin.commitCountThreshold; + } + // ignore locating countries + // locating places + if (!startAnalysisService && await availability.canLocatePlaces) { + final opCount = (force ? todoEntries.where((entry) => entry.hasGps) : todoEntries.where(LocationMixin.locatePlacesTest)).length; + startAnalysisService = opCount > LocationMixin.commitCountThreshold; + } + } + + debugPrint('analyze ${todoEntries.length} entries, force=$force, starting service=$startAnalysisService'); + if (startAnalysisService) { + final lifecycleState = AvesApp.lifecycleStateNotifier.value; + switch (lifecycleState) { + case AppLifecycleState.resumed: + case AppLifecycleState.inactive: + await AnalysisService.startService( + force: force, + entryIds: entries?.map((entry) => entry.id).toList(), + ); + default: + unawaited(reportService.log('analysis service not started because app is in state=$lifecycleState')); + } + } else { + // explicit GC before cataloguing multiple items + await deviceService.requestGarbageCollection(); + await catalogEntries(_analysisController, todoEntries); + updateDerivedFilters(todoEntries); + await locateEntries(_analysisController, todoEntries); + updateDerivedFilters(todoEntries); + } + } + defaultAnalysisController.dispose(); + state = SourceState.ready; + } + + void onAspectRatioChanged() => eventBus.fire(AspectRatioChangedEvent()); + + // monitoring + + bool _canRefresh = true; + + void pauseMonitoring() => _canRefresh = false; + + void resumeMonitoring() => _canRefresh = true; + + bool get canRefresh => _canRefresh; + + // filter summary + + int count(CollectionFilter filter) { + switch (filter) { + case AlbumBaseFilter _: + return albumEntryCount(filter); + case LocationFilter(level: LocationLevel.country): + return countryEntryCount(filter); + case LocationFilter(level: LocationLevel.state): + return stateEntryCount(filter); + case LocationFilter(level: LocationLevel.place): + return placeEntryCount(filter); + case TagBaseFilter _: + return tagEntryCount(filter); + } + return 0; + } + + int size(CollectionFilter filter) { + switch (filter) { + case AlbumBaseFilter _: + return albumSize(filter); + case LocationFilter(level: LocationLevel.country): + return countrySize(filter); + case LocationFilter(level: LocationLevel.state): + return stateSize(filter); + case LocationFilter(level: LocationLevel.place): + return placeSize(filter); + case TagBaseFilter _: + return tagSize(filter); + } + return 0; + } + + AvesEntry? recentEntry(CollectionFilter filter) { + switch (filter) { + case AlbumBaseFilter _: + return albumRecentEntry(filter); + case LocationFilter(level: LocationLevel.country): + return countryRecentEntry(filter); + case LocationFilter(level: LocationLevel.state): + return stateRecentEntry(filter); + case LocationFilter(level: LocationLevel.place): + return placeRecentEntry(filter); + case TagBaseFilter _: + return tagRecentEntry(filter); + } + return null; + } + + AvesEntry? coverEntry(CollectionFilter filter) { + final id = covers.of(filter)?.$1; + if (id != null) { + final entry = visibleEntries.firstWhereOrNull((entry) => entry.id == id); + if (entry != null) return entry; + } + return recentEntry(filter); + } + + void _onFilterVisibilityChanged(Set<CollectionFilter> newlyVisibleFilters) { + updateDerivedFilters(); + eventBus.fire(const FilterVisibilityChangedEvent()); + + if (newlyVisibleFilters.isNotEmpty) { + final candidateEntries = visibleEntries.where((entry) => newlyVisibleFilters.any((f) => f.test(entry))).toSet(); + analyze(null, entries: candidateEntries); + } + } + + void _onVaultsChanged() { + final newlyVisibleFilters = vaults.vaultDirectories.whereNot(vaults.isLocked).map((v) => StoredAlbumFilter(v, null)).toSet(); + _onFilterVisibilityChanged(newlyVisibleFilters); + } +} + +class AspectRatioChangedEvent {} diff --git a/lib/model/source/events.dart b/lib/model/source/events.dart new file mode 100644 index 0000000..ec8dc28 --- /dev/null +++ b/lib/model/source/events.dart @@ -0,0 +1,44 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/foundation.dart'; + +@immutable +class EntryAddedEvent { + final Set<AvesEntry>? entries; + + const EntryAddedEvent([this.entries]); +} + +@immutable +class EntryRemovedEvent { + final Set<AvesEntry> entries; + + const EntryRemovedEvent(this.entries); +} + +@immutable +class EntryMovedEvent { + final MoveType type; + final Set<AvesEntry> entries; + + const EntryMovedEvent(this.type, this.entries); +} + +@immutable +class EntryRefreshedEvent { + final Set<AvesEntry> entries; + + const EntryRefreshedEvent(this.entries); +} + +@immutable +class FilterVisibilityChangedEvent { + const FilterVisibilityChangedEvent(); +} + +@immutable +class ProgressEvent { + final int done, total; + + const ProgressEvent({required this.done, required this.total}); +} diff --git a/lib/model/source/location/country.dart b/lib/model/source/location/country.dart new file mode 100644 index 0000000..f799407 --- /dev/null +++ b/lib/model/source/location/country.dart @@ -0,0 +1,64 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/filters/covered/location.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/utils/collection_utils.dart'; +import 'package:collection/collection.dart'; + +mixin CountryMixin on SourceBase { + // by country code + final Map<String, int> _filterEntryCountMap = {}, _filterSizeMap = {}; + final Map<String, AvesEntry?> _filterRecentEntryMap = {}; + + void invalidateCountryFilterSummary({ + Set<AvesEntry>? entries, + Set<String>? countryCodes, + bool notify = true, + }) { + if (_filterEntryCountMap.isEmpty && _filterSizeMap.isEmpty && _filterRecentEntryMap.isEmpty) return; + + if (entries == null && countryCodes == null) { + _filterEntryCountMap.clear(); + _filterSizeMap.clear(); + _filterRecentEntryMap.clear(); + } else { + countryCodes ??= {}; + if (entries != null) { + countryCodes.addAll(entries.where((entry) => entry.hasAddress).map((entry) => entry.addressDetails?.countryCode).nonNulls); + } + countryCodes.forEach((countryCode) { + _filterEntryCountMap.remove(countryCode); + _filterSizeMap.remove(countryCode); + _filterRecentEntryMap.remove(countryCode); + }); + } + if (notify) { + eventBus.fire(CountrySummaryInvalidatedEvent(countryCodes)); + } + } + + int countryEntryCount(LocationFilter filter) { + final countryCode = filter.code; + if (countryCode == null) return 0; + return _filterEntryCountMap.putIfAbsent(countryCode, () => visibleEntries.where(filter.test).length); + } + + int countrySize(LocationFilter filter) { + final countryCode = filter.code; + if (countryCode == null) return 0; + return _filterSizeMap.putIfAbsent(countryCode, () => visibleEntries.where(filter.test).map((v) => v.sizeBytes).sum); + } + + AvesEntry? countryRecentEntry(LocationFilter filter) { + final countryCode = filter.code; + if (countryCode == null) return null; + return _filterRecentEntryMap.putIfAbsent(countryCode, () => sortedEntriesByDate.firstWhereOrNull(filter.test)); + } +} + +class CountriesChangedEvent {} + +class CountrySummaryInvalidatedEvent { + final Set<String>? countryCodes; + + const CountrySummaryInvalidatedEvent(this.countryCodes); +} diff --git a/lib/model/source/location/location.dart b/lib/model/source/location/location.dart new file mode 100644 index 0000000..30ca150 --- /dev/null +++ b/lib/model/source/location/location.dart @@ -0,0 +1,208 @@ +import 'dart:math'; + +import 'package:aves/geo/countries.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/location.dart'; +import 'package:aves/model/filters/covered/location.dart'; +import 'package:aves/model/metadata/address.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/analysis_controller.dart'; +import 'package:aves/model/source/location/country.dart'; +import 'package:aves/model/source/location/place.dart'; +import 'package:aves/model/source/location/state.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; + +mixin LocationMixin on CountryMixin, StateMixin { + static const commitCountThreshold = 200; + static const _stopCheckCountThreshold = 50; + + List<String> sortedCountries = List.unmodifiable([]); + List<String> sortedStates = List.unmodifiable([]); + List<String> sortedPlaces = List.unmodifiable([]); + + Future<void> loadAddresses({Set<int>? ids}) async { + final saved = await (ids != null ? localMediaDb.loadAddressesById(ids) : localMediaDb.loadAddresses()); + final idMap = entryById; + saved.forEach((metadata) => idMap[metadata.id]?.addressDetails = metadata); + invalidateEntries(); + onAddressMetadataChanged(); + } + + Future<void> locateEntries(AnalysisController controller, Set<AvesEntry> candidateEntries) async { + await _locateCountries(controller, candidateEntries); + await _locatePlaces(controller, candidateEntries); + + final unlocatedIds = candidateEntries.where((entry) => !entry.hasGps).map((entry) => entry.id).toSet(); + if (unlocatedIds.isNotEmpty) { + await localMediaDb.removeIds(unlocatedIds, dataTypes: {EntryDataType.address}); + onAddressMetadataChanged(); + } + } + + static bool locateCountriesTest(AvesEntry entry) => entry.hasGps && !entry.hasAddress; + + static bool locatePlacesTest(AvesEntry entry) => entry.hasGps && !entry.hasFineAddress; + + // quick reverse geocoding to find the countries, using an offline asset + Future<void> _locateCountries(AnalysisController controller, Set<AvesEntry> candidateEntries) async { + if (controller.isStopping) return; + + final force = controller.force; + final todo = (force ? candidateEntries.where((entry) => entry.hasGps) : candidateEntries.where(locateCountriesTest)).toSet(); + if (todo.isEmpty) return; + + state = SourceState.locatingCountries; + var progressDone = 0; + final progressTotal = todo.length; + setProgress(done: progressDone, total: progressTotal); + + final countryCodeMap = await countryTopology.countryCodeMap(todo.map((entry) => entry.latLng!).toSet()); + final newAddresses = <AddressDetails>{}; + todo.forEach((entry) { + final position = entry.latLng; + final countryCode = countryCodeMap.entries.firstWhereOrNull((kv) => kv.value.contains(position))?.key; + entry.setCountry(countryCode); + if (entry.hasAddress) { + newAddresses.add(entry.addressDetails!); + } + setProgress(done: ++progressDone, total: progressTotal); + }); + if (newAddresses.isNotEmpty) { + await localMediaDb.saveAddresses(Set.unmodifiable(newAddresses)); + onAddressMetadataChanged(); + } + } + + // full reverse geocoding, requiring geocoder and some connectivity + Future<void> _locatePlaces(AnalysisController controller, Set<AvesEntry> candidateEntries) async { + if (controller.isStopping) return; + if (!await availability.canLocatePlaces) return; + + final force = controller.force; + final todo = (force ? candidateEntries.where((entry) => entry.hasGps) : candidateEntries.where(locatePlacesTest)).toSet(); + if (todo.isEmpty) return; + + // geocoder calls take between 150ms and 250ms + // approximation and caching can reduce geocoder usage + // for example, for a set of 2932 entries: + // - 2476 calls (84%) when approximating to 6 decimal places (~10cm - individual humans) + // - 2433 calls (83%) when approximating to 5 decimal places (~1m - individual trees, houses) + // - 2277 calls (78%) when approximating to 4 decimal places (~10m - individual street, large buildings) + // - 1521 calls (52%) when approximating to 3 decimal places (~100m - neighborhood, street) + // - 652 calls (22%) when approximating to 2 decimal places (~1km - town or village) + // cf https://en.wikipedia.org/wiki/Decimal_degrees#Precision + final latLngFactor = pow(10, 2); + (int latitude, int longitude) approximateLatLng(AvesEntry entry) { + // entry has coordinates + final catalogMetadata = entry.catalogMetadata!; + final lat = catalogMetadata.latitude!; + final lng = catalogMetadata.longitude!; + return ((lat * latLngFactor).round(), (lng * latLngFactor).round()); + } + + final located = visibleEntries.where((entry) => entry.hasGps).toSet().difference(todo); + final knownLocations = <(int, int), AddressDetails?>{}; + located.forEach((entry) { + knownLocations.putIfAbsent(approximateLatLng(entry), () => entry.addressDetails); + }); + + state = SourceState.locatingPlaces; + var progressDone = 0; + final progressTotal = todo.length; + setProgress(done: progressDone, total: progressTotal); + + var stopCheckCount = 0; + final newAddresses = <AddressDetails>{}; + for (final entry in todo) { + final latLng = approximateLatLng(entry); + if (knownLocations.containsKey(latLng)) { + entry.addressDetails = knownLocations[latLng]?.copyWith(id: entry.id); + } else { + await entry.locatePlace(background: true, force: force, geocoderLocale: settings.appliedLocale); + // it is intended to insert `null` if the geocoder failed, + // so that we skip geocoding of following entries with the same coordinates + knownLocations[latLng] = entry.addressDetails; + } + if (entry.hasFineAddress) { + newAddresses.add(entry.addressDetails!); + if (newAddresses.length >= commitCountThreshold) { + await localMediaDb.saveAddresses(Set.unmodifiable(newAddresses)); + onAddressMetadataChanged(); + newAddresses.clear(); + } + if (++stopCheckCount >= _stopCheckCountThreshold) { + stopCheckCount = 0; + if (controller.isStopping) return; + } + } + setProgress(done: ++progressDone, total: progressTotal); + } + if (newAddresses.isNotEmpty) { + await localMediaDb.saveAddresses(Set.unmodifiable(newAddresses)); + onAddressMetadataChanged(); + } + } + + void onAddressMetadataChanged() { + updateLocations(); + eventBus.fire(AddressMetadataChangedEvent()); + } + + void updateLocations() { + final locations = visibleEntries.map((entry) => entry.addressDetails).nonNulls.toList(); + + final updatedPlaces = locations.map((address) => address.place).nonNulls.where((v) => v.isNotEmpty).toSet().toList()..sort(compareAsciiUpperCase); + if (!listEquals(updatedPlaces, sortedPlaces)) { + sortedPlaces = List.unmodifiable(updatedPlaces); + eventBus.fire(PlacesChangedEvent()); + } + + final updatedStates = _getAreaByCode( + locations: locations, + getCode: (v) => v.stateCode, + getName: (v) => v.stateName, + ); + if (!listEquals(updatedStates, sortedStates)) { + sortedStates = List.unmodifiable(updatedStates); + invalidateStateFilterSummary(); + eventBus.fire(StatesChangedEvent()); + } + + final updatedCountries = _getAreaByCode( + locations: locations, + getCode: (v) => v.countryCode, + getName: (v) => v.countryName, + ); + if (!listEquals(updatedCountries, sortedCountries)) { + sortedCountries = List.unmodifiable(updatedCountries); + invalidateCountryFilterSummary(); + eventBus.fire(CountriesChangedEvent()); + } + } + + // the same country/state code could be found with different country/state names + // e.g. if the locale changed between geocoding calls + // so we merge countries/states by code, keeping only one name for each code + List<String> _getAreaByCode({ + required List<AddressDetails> locations, + required String? Function(AddressDetails address) getCode, + required String? Function(AddressDetails address) getName, + }) { + final namesByCode = Map.fromEntries(locations.map((address) { + final code = getCode(address); + if (code == null || code.isEmpty) return null; + return MapEntry(code, getName(address)); + }).nonNulls); + return namesByCode.entries.map((kv) { + final code = kv.key; + final name = kv.value; + return '${name != null && name.isNotEmpty ? name : code}${LocationFilter.locationSeparator}$code'; + }).toList() + ..sort(compareAsciiUpperCase); + } +} + +class AddressMetadataChangedEvent {} diff --git a/lib/model/source/location/place.dart b/lib/model/source/location/place.dart new file mode 100644 index 0000000..42d7cd3 --- /dev/null +++ b/lib/model/source/location/place.dart @@ -0,0 +1,58 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/filters/covered/location.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/utils/collection_utils.dart'; +import 'package:collection/collection.dart'; + +mixin PlaceMixin on SourceBase { + // by place + final Map<String, int> _filterEntryCountMap = {}, _filterSizeMap = {}; + final Map<String, AvesEntry?> _filterRecentEntryMap = {}; + + void invalidatePlaceFilterSummary({ + Set<AvesEntry>? entries, + Set<String>? places, + bool notify = true, + }) { + if (_filterEntryCountMap.isEmpty && _filterSizeMap.isEmpty && _filterRecentEntryMap.isEmpty) return; + + if (entries == null && places == null) { + _filterEntryCountMap.clear(); + _filterSizeMap.clear(); + _filterRecentEntryMap.clear(); + } else { + places ??= {}; + if (entries != null) { + places.addAll(entries.map((entry) => entry.addressDetails?.place).nonNulls); + } + places.forEach((place) { + _filterEntryCountMap.remove(place); + _filterSizeMap.remove(place); + _filterRecentEntryMap.remove(place); + }); + } + if (notify) { + eventBus.fire(PlaceSummaryInvalidatedEvent(places)); + } + } + + int placeEntryCount(LocationFilter filter) { + return _filterEntryCountMap.putIfAbsent(filter.place, () => visibleEntries.where(filter.test).length); + } + + int placeSize(LocationFilter filter) { + return _filterSizeMap.putIfAbsent(filter.place, () => visibleEntries.where(filter.test).map((v) => v.sizeBytes).sum); + } + + AvesEntry? placeRecentEntry(LocationFilter filter) { + return _filterRecentEntryMap.putIfAbsent(filter.place, () => sortedEntriesByDate.firstWhereOrNull(filter.test)); + } +} + +class PlacesChangedEvent {} + +class PlaceSummaryInvalidatedEvent { + final Set<String>? places; + + const PlaceSummaryInvalidatedEvent(this.places); +} diff --git a/lib/model/source/location/state.dart b/lib/model/source/location/state.dart new file mode 100644 index 0000000..8eb4abd --- /dev/null +++ b/lib/model/source/location/state.dart @@ -0,0 +1,64 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/filters/covered/location.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/utils/collection_utils.dart'; +import 'package:collection/collection.dart'; + +mixin StateMixin on SourceBase { + // by state code + final Map<String, int> _filterEntryCountMap = {}, _filterSizeMap = {}; + final Map<String, AvesEntry?> _filterRecentEntryMap = {}; + + void invalidateStateFilterSummary({ + Set<AvesEntry>? entries, + Set<String>? stateCodes, + bool notify = true, + }) { + if (_filterEntryCountMap.isEmpty && _filterSizeMap.isEmpty && _filterRecentEntryMap.isEmpty) return; + + if (entries == null && stateCodes == null) { + _filterEntryCountMap.clear(); + _filterSizeMap.clear(); + _filterRecentEntryMap.clear(); + } else { + stateCodes ??= {}; + if (entries != null) { + stateCodes.addAll(entries.where((entry) => entry.hasAddress).map((entry) => entry.addressDetails?.stateCode).nonNulls); + } + stateCodes.forEach((stateCode) { + _filterEntryCountMap.remove(stateCode); + _filterSizeMap.remove(stateCode); + _filterRecentEntryMap.remove(stateCode); + }); + } + if (notify) { + eventBus.fire(StateSummaryInvalidatedEvent(stateCodes)); + } + } + + int stateEntryCount(LocationFilter filter) { + final stateCode = filter.code; + if (stateCode == null) return 0; + return _filterEntryCountMap.putIfAbsent(stateCode, () => visibleEntries.where(filter.test).length); + } + + int stateSize(LocationFilter filter) { + final stateCode = filter.code; + if (stateCode == null) return 0; + return _filterSizeMap.putIfAbsent(stateCode, () => visibleEntries.where(filter.test).map((v) => v.sizeBytes).sum); + } + + AvesEntry? stateRecentEntry(LocationFilter filter) { + final stateCode = filter.code; + if (stateCode == null) return null; + return _filterRecentEntryMap.putIfAbsent(stateCode, () => sortedEntriesByDate.firstWhereOrNull(filter.test)); + } +} + +class StatesChangedEvent {} + +class StateSummaryInvalidatedEvent { + final Set<String>? stateCodes; + + const StateSummaryInvalidatedEvent(this.stateCodes); +} diff --git a/lib/model/source/media_store_source.dart b/lib/model/source/media_store_source.dart new file mode 100644 index 0000000..7ea6769 --- /dev/null +++ b/lib/model/source/media_store_source.dart @@ -0,0 +1,426 @@ +import 'dart:async'; + +import 'package:aves/model/covers.dart'; +import 'package:aves/model/dynamic_albums.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/origins.dart'; +import 'package:aves/model/favourites.dart'; +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/grouping/common.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/analysis_controller.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/model/vaults/vaults.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/utils/android_file_utils.dart'; +import 'package:aves/utils/debouncer.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; + +class MediaStoreSource extends CollectionSource { + final Debouncer _changeDebouncer = Debouncer(delay: ADurations.mediaContentChangeDebounceDelay); + final Set<String> _changedUris = {}; + int? _lastGeneration; + SourceScope _loadedScope, _targetScope; + bool _canAnalyze = true; + Future<void>? _essentialLoader; + + @override + set canAnalyze(bool enabled) => _canAnalyze = enabled; + + @override + SourceScope get loadedScope => _loadedScope; + + @override + SourceScope get targetScope => _targetScope; + + @override + Future<void> init({ + required SourceScope scope, + AnalysisController? analysisController, + bool loadTopEntriesFirst = false, + }) async { + _targetScope = scope; + await reportService.log('$runtimeType init target scope=$scope'); + _essentialLoader ??= _loadEssentials(); + await _essentialLoader; + addDirectories(albums: settings.pinnedFilters.whereType<StoredAlbumFilter>().map((v) => v.album).toSet()); + await updateGeneration(); + unawaited(_loadEntries( + analysisController: analysisController, + loadTopEntriesFirst: loadTopEntriesFirst, + )); + } + + Future<void> _loadEssentials() async { + final stopwatch = Stopwatch()..start(); + state = SourceState.loading; + await localMediaDb.init(); + await vaults.init(); + await favourites.init(); + albumGrouping.init(); + albumGrouping.setGroups(settings.albumGroups); + albumGrouping.registerSource(this); + tagGrouping.init(); + tagGrouping.setGroups(settings.tagGroups); + tagGrouping.registerSource(this); + await covers.init(); + await dynamicAlbums.init(); + + final deviceOffset = DateTime.now().timeZoneOffset.inMilliseconds; + final catalogOffset = settings.catalogTimeZoneOffsetMillis; + if (deviceOffset != catalogOffset) { + unawaited(reportService.log('Time zone offset change: $catalogOffset -> $deviceOffset. Clear catalog metadata to get correct date/times.')); + await localMediaDb.clearDates(); + await localMediaDb.clearCatalogMetadata(); + settings.catalogTimeZoneOffsetMillis = deviceOffset; + } + await loadDates(); + debugPrint('$runtimeType load essentials complete in ${stopwatch.elapsed.inMilliseconds}ms'); + } + + Future<void> _loadEntries({ + AnalysisController? analysisController, + required bool loadTopEntriesFirst, + }) async { + unawaited(reportService.log('$runtimeType load (known) start')); + final stopwatch = Stopwatch()..start(); + state = SourceState.loading; + clearEntries(); + + final scopeAlbumFilters = _targetScope?.whereType<StoredAlbumFilter>(); + final scopeDirectory = scopeAlbumFilters != null && scopeAlbumFilters.length == 1 ? scopeAlbumFilters.first.album : null; + + final Set<AvesEntry> topEntries = {}; + if (loadTopEntriesFirst) { + final topIds = settings.topEntryIds?.toSet(); + if (topIds != null) { + debugPrint('$runtimeType load ${stopwatch.elapsed} load ${topIds.length} top entries'); + topEntries.addAll(await localMediaDb.loadEntriesById(topIds)); + addEntries(topEntries); + } + } + + debugPrint('$runtimeType load ${stopwatch.elapsed} fetch known entries'); + final knownEntries = await localMediaDb.loadEntries(origin: EntryOrigins.mediaStoreContent, directory: scopeDirectory); + final knownLiveEntries = knownEntries.where((entry) => !entry.trashed).toSet(); + unawaited(reportService.setCustomKey('is_large_collection', knownEntries.length > 100000)); + unawaited(reportService.log('$runtimeType found ${knownEntries.length} known entries')); + + debugPrint('$runtimeType load ${stopwatch.elapsed} check obsolete entries'); + final knownDateByContentId = Map.fromEntries(knownLiveEntries.map((entry) => MapEntry(entry.contentId, entry.dateModifiedMillis))); + final knownContentIds = knownDateByContentId.keys.toList(); + final removedContentIds = (await mediaStoreService.checkObsoleteContentIds(knownContentIds)).toSet(); + if (topEntries.isNotEmpty) { + final removedTopEntries = topEntries.where((entry) => removedContentIds.contains(entry.contentId)); + await removeEntries(removedTopEntries.map((entry) => entry.uri).toSet(), includeTrash: false); + } + final removedEntries = knownEntries.where((entry) => removedContentIds.contains(entry.contentId)).toSet(); + knownEntries.removeAll(removedEntries); + + // show known entries + debugPrint('$runtimeType load ${stopwatch.elapsed} add known entries'); + // add entries without notifying, so that the collection is not refreshed + // with items that may be hidden right away because of their metadata + addEntries(knownEntries, notify: false); + // but use album notification without waiting for cataloguing + // so that it is more reactive when picking an album in view mode + notifyAlbumsChanged(); + + await _loadVaultEntries(scopeDirectory); + + debugPrint('$runtimeType load ${stopwatch.elapsed} load metadata'); + if (scopeDirectory != null) { + final ids = knownLiveEntries.map((entry) => entry.id).toSet(); + await loadCatalogMetadata(ids: ids); + await loadAddresses(ids: ids); + } else { + await loadCatalogMetadata(); + await loadAddresses(); + + // trash + await loadTrashDetails(); + unawaited(deleteExpiredTrash().then( + (deletedUris) { + if (deletedUris.isNotEmpty) { + debugPrint('evicted ${deletedUris.length} expired items from the trash'); + removeEntries(deletedUris, includeTrash: true); + } + }, + onError: (error) => debugPrint('failed to evict expired trash error=$error'), + )); + } + updateDerivedFilters(); + + // clean up obsolete entries + if (removedEntries.isNotEmpty) { + debugPrint('$runtimeType load ${stopwatch.elapsed} remove obsolete entries'); + await localMediaDb.removeIds(removedEntries.map((entry) => entry.id).toSet()); + } + + _loadedScope = _targetScope; + unawaited(reportService.log('$runtimeType load (known) done in ${stopwatch.elapsed.inSeconds}s for ${knownEntries.length} known, ${removedEntries.length} removed')); + + if (_canAnalyze) { + // it can discover new entries only if it can analyze them + await _loadNewEntries( + analysisController: analysisController, + directory: scopeDirectory, + knownLiveEntries: knownLiveEntries, + knownDateByContentId: knownDateByContentId, + ); + } else { + state = SourceState.ready; + } + } + + Future<void> _loadNewEntries({ + required AnalysisController? analysisController, + required String? directory, + required Set<AvesEntry> knownLiveEntries, + required Map<int?, int?> knownDateByContentId, + }) async { + unawaited(reportService.log('$runtimeType load (new) start')); + final stopwatch = Stopwatch()..start(); + + // items to add to the collection + final newEntries = <AvesEntry>{}; + + // recover untracked trash items + debugPrint('$runtimeType load ${stopwatch.elapsed} recover untracked entries'); + if (directory == null) { + newEntries.addAll(await recoverUntrackedTrashItems()); + } + + // verify paths because some apps move files without updating their `last modified date` + debugPrint('$runtimeType load ${stopwatch.elapsed} check obsolete paths'); + final knownPathByContentId = Map.fromEntries(knownLiveEntries.map((entry) => MapEntry(entry.contentId, entry.path))); + final movedContentIds = (await mediaStoreService.checkObsoletePaths(knownPathByContentId)).toSet(); + movedContentIds.forEach((contentId) { + // make obsolete by resetting its modified date + knownDateByContentId[contentId] = 0; + }); + + // fetch new & modified entries + debugPrint('$runtimeType load ${stopwatch.elapsed} fetch new entries'); + final knownContentIds = knownDateByContentId.keys.toSet(); + mediaStoreService.getEntries(knownDateByContentId, directory: directory).listen( + (entry) { + // when discovering modified entry with known content ID, + // reuse known entry ID to overwrite it while preserving favourites, etc. + final contentId = entry.contentId; + final existingEntry = knownContentIds.contains(contentId) ? knownLiveEntries.firstWhereOrNull((entry) => entry.contentId == contentId) : null; + entry.id = existingEntry?.id ?? localMediaDb.nextId; + + newEntries.add(entry); + setProgress(done: newEntries.length, total: 0); + }, + onDone: () async { + if (newEntries.isNotEmpty) { + debugPrint('$runtimeType load ${stopwatch.elapsed} save ${newEntries.length} new entries'); + await localMediaDb.insertEntries(newEntries); + + // TODO TLAD find duplication cause + final duplicates = await localMediaDb.searchLiveDuplicates(EntryOrigins.mediaStoreContent, newEntries); + if (duplicates.isNotEmpty) { + unawaited(reportService.recordError(Exception('Loading entries yielded duplicates=${duplicates.join(', ')}'))); + // post-error cleanup + await localMediaDb.removeIds(duplicates.map((v) => v.id).toSet()); + for (final duplicate in duplicates) { + final duplicateId = duplicate.id; + newEntries.removeWhere((v) => duplicateId == v.id); + } + } + + addEntries(newEntries); + + // new entries include existing entries with obsolete paths + // so directories may be added, but also removed or simply have their content summary changed + invalidateAlbumFilterSummary(); + updateDirectories(); + } + + debugPrint('$runtimeType load ${stopwatch.elapsed} analyze'); + Set<AvesEntry>? analysisEntries; + final analysisIds = analysisController?.entryIds; + if (analysisIds != null) { + // not only visible entries, as hidden and vault items may be analyzed + analysisEntries = allEntries.where((entry) => analysisIds.contains(entry.id)).toSet(); + } + await analyze(analysisController, entries: analysisEntries); + + // the home page may not reflect the current derived filters + // as the initial addition of entries is silent, + // so we manually notify change for potential home screen filters + notifyAlbumsChanged(); + + unawaited(reportService.log('$runtimeType load (new) done in ${stopwatch.elapsed.inSeconds}s for ${newEntries.length} new entries')); + }, + onError: (error) => debugPrint('$runtimeType stream error=$error'), + ); + } + + // returns URIs to retry later. They could be URIs that are: + // 1) currently being processed during bulk move/deletion + // 2) registered in the Media Store but still being processed by their owner in a temporary location + // For example, when taking a picture with a Galaxy S10e default camera app, querying the Media Store + // sometimes yields an entry with its temporary path: `/data/sec/camera/!@#$%^..._temp.jpg` + @override + Future<Set<String>> refreshUris(Set<String> changedUris, {AnalysisController? analysisController}) async { + if (!canRefresh || _essentialLoader == null || !isReady) return changedUris; + + state = SourceState.loading; + + unawaited(reportService.log('$runtimeType refresh start for ${changedUris.length} uris')); + final changedUriByContentId = Map.fromEntries(changedUris.map((uri) { + final pathSegments = Uri.parse(uri).pathSegments; + // e.g. URI `content://media/` has no path segment + if (pathSegments.isEmpty) return null; + final idString = pathSegments.last; + final contentId = int.tryParse(idString); + if (contentId == null) return null; + return MapEntry(contentId, uri); + }).nonNulls); + + // clean up obsolete entries + final obsoleteContentIds = (await mediaStoreService.checkObsoleteContentIds(changedUriByContentId.keys.toList())).toSet(); + final obsoleteUris = obsoleteContentIds.map((contentId) => changedUriByContentId[contentId]).nonNulls.toSet(); + await removeEntries(obsoleteUris, includeTrash: false); + obsoleteContentIds.forEach(changedUriByContentId.remove); + + // fetch new entries + final tempUris = <String>{}; + final newEntries = <AvesEntry>{}, entriesToRefresh = <AvesEntry>{}; + final existingDirectories = <String>{}; + for (final kv in changedUriByContentId.entries) { + final contentId = kv.key; + final uri = kv.value; + final sourceEntry = await mediaFetchService.getEntry(uri, null); + if (sourceEntry != null) { + final existingEntry = allEntries.firstWhereOrNull((entry) => entry.contentId == contentId); + // compare paths because some apps move files without updating their `last modified date` + if (existingEntry == null || (sourceEntry.dateModifiedMillis ?? 0) > (existingEntry.dateModifiedMillis ?? 0) || sourceEntry.path != existingEntry.path) { + final newPath = sourceEntry.path; + final volume = newPath != null ? androidFileUtils.getStorageVolume(newPath) : null; + if (volume != null) { + if (existingEntry != null) { + entriesToRefresh.add(existingEntry); + } else if (_canAnalyze) { + // it can discover new entries only if it can analyze them + sourceEntry.id = localMediaDb.nextId; + newEntries.add(sourceEntry); + } + final existingDirectory = existingEntry?.directory; + if (existingDirectory != null) { + existingDirectories.add(existingDirectory); + } + } else { + debugPrint('$runtimeType refreshUris entry=$sourceEntry is not located on a known storage volume. Will retry soon...'); + tempUris.add(uri); + } + } + } + } + + await _refreshVaultEntries( + changedUris: changedUris.where(vaults.isVaultEntryUri).toSet(), + newEntries: newEntries, + entriesToRefresh: entriesToRefresh, + existingDirectories: existingDirectories, + ); + + invalidateAlbumFilterSummary(directories: existingDirectories); + + if (newEntries.isNotEmpty) { + await localMediaDb.insertEntries(newEntries); + + // TODO TLAD find duplication cause + final duplicates = await localMediaDb.searchLiveDuplicates(EntryOrigins.mediaStoreContent, newEntries); + if (duplicates.isNotEmpty) { + unawaited(reportService.recordError(Exception('Refreshing entries yielded duplicates=${duplicates.join(', ')}'))); + // post-error cleanup + await localMediaDb.removeIds(duplicates.map((v) => v.id).toSet()); + for (final duplicate in duplicates) { + final duplicateId = duplicate.id; + newEntries.removeWhere((v) => duplicateId == v.id); + tempUris.add(duplicate.uri); + } + } + + addEntries(newEntries); + await analyze(analysisController, entries: newEntries); + } + + if (entriesToRefresh.isNotEmpty) { + await refreshEntries(entriesToRefresh, EntryDataType.values.toSet()); + } + + unawaited(reportService.log('$runtimeType refresh end for ${changedUris.length} uris')); + + state = SourceState.ready; + + return tempUris; + } + + void onStoreChanged(String? uri) { + if (uri != null) _changedUris.add(uri); + if (_changedUris.isNotEmpty) { + _changeDebouncer(() async { + final todo = _changedUris.toSet(); + _changedUris.clear(); + final tempUris = await refreshUris(todo); + if (tempUris.isNotEmpty) { + _changedUris.addAll(tempUris); + onStoreChanged(null); + } + }); + } + } + + Future<void> checkForChanges() async { + final sinceGeneration = _lastGeneration; + if (sinceGeneration != null) { + _changedUris.addAll(await mediaStoreService.getChangedUris(sinceGeneration)); + onStoreChanged(null); + } + await updateGeneration(); + } + + Future<void> updateGeneration() async { + _lastGeneration = await mediaStoreService.getGeneration(); + } + + // vault + + Future<void> _loadVaultEntries(String? directory) async { + addEntries(await localMediaDb.loadEntries(origin: EntryOrigins.vault, directory: directory)); + } + + Future<void> _refreshVaultEntries({ + required Set<String> changedUris, + required Set<AvesEntry> newEntries, + required Set<AvesEntry> entriesToRefresh, + required Set<String> existingDirectories, + }) async { + for (final uri in changedUris) { + final existingEntry = allEntries.firstWhereOrNull((entry) => entry.uri == uri); + if (existingEntry != null) { + entriesToRefresh.add(existingEntry); + final existingDirectory = existingEntry.directory; + if (existingDirectory != null) { + existingDirectories.add(existingDirectory); + } + } else { + final sourceEntry = await mediaFetchService.getEntry(uri, null, allowUnsized: true); + if (sourceEntry != null) { + newEntries.add(sourceEntry.copyWith( + id: localMediaDb.nextId, + origin: EntryOrigins.vault, + )); + } + } + } + } +} diff --git a/lib/model/source/section_keys.dart b/lib/model/source/section_keys.dart new file mode 100644 index 0000000..52cfb48 --- /dev/null +++ b/lib/model/source/section_keys.dart @@ -0,0 +1,34 @@ +import 'package:equatable/equatable.dart'; +import 'package:flutter/foundation.dart'; + +@immutable +class SectionKey { + const SectionKey(); +} + +class EntryAlbumSectionKey extends SectionKey with EquatableMixin { + final String? directory; + + @override + List<Object?> get props => [directory]; + + const EntryAlbumSectionKey(this.directory); +} + +class EntryDateSectionKey extends SectionKey with EquatableMixin { + final DateTime? date; + + @override + List<Object?> get props => [date]; + + const EntryDateSectionKey(this.date); +} + +class EntryRatingSectionKey extends SectionKey with EquatableMixin { + final int rating; + + @override + List<Object?> get props => [rating]; + + const EntryRatingSectionKey(this.rating); +} diff --git a/lib/model/source/tag.dart b/lib/model/source/tag.dart new file mode 100644 index 0000000..7f8bf28 --- /dev/null +++ b/lib/model/source/tag.dart @@ -0,0 +1,155 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/catalog.dart'; +import 'package:aves/model/filters/container/tag_group.dart'; +import 'package:aves/model/filters/covered/tag.dart'; +import 'package:aves/model/metadata/catalog.dart'; +import 'package:aves/model/source/analysis_controller.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/utils/collection_utils.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; + +mixin TagMixin on SourceBase { + static const commitCountThreshold = 400; + static const _stopCheckCountThreshold = 100; + + List<String> sortedTags = List.unmodifiable([]); + + Future<void> loadCatalogMetadata({Set<int>? ids}) async { + final saved = await (ids != null ? localMediaDb.loadCatalogMetadataById(ids) : localMediaDb.loadCatalogMetadata()); + final idMap = entryById; + saved.forEach((metadata) => idMap[metadata.id]?.catalogMetadata = metadata); + invalidateEntries(); + onCatalogMetadataChanged(); + } + + static bool catalogEntriesTest(AvesEntry entry) => !entry.isCatalogued; + + Future<void> catalogEntries(AnalysisController controller, Set<AvesEntry> candidateEntries) async { + if (controller.isStopping) return; + + final force = controller.force; + final todo = force ? candidateEntries : candidateEntries.where(catalogEntriesTest).toSet(); + if (todo.isEmpty) return; + + state = SourceState.cataloguing; + var progressDone = controller.progressOffset; + var progressTotal = controller.progressTotal; + if (progressTotal == 0) { + progressTotal = todo.length; + } + setProgress(done: progressDone, total: progressTotal); + + var stopCheckCount = 0; + final newMetadata = <CatalogMetadata>{}; + for (final entry in todo) { + await entry.catalog(background: true, force: force, persist: true); + if (entry.isCatalogued) { + newMetadata.add(entry.catalogMetadata!); + if (newMetadata.length >= commitCountThreshold) { + await localMediaDb.saveCatalogMetadata(Set.unmodifiable(newMetadata)); + onCatalogMetadataChanged(); + newMetadata.clear(); + } + if (++stopCheckCount >= _stopCheckCountThreshold) { + stopCheckCount = 0; + if (controller.isStopping) return; + } + } + setProgress(done: ++progressDone, total: progressTotal); + } + await localMediaDb.saveCatalogMetadata(Set.unmodifiable(newMetadata)); + onCatalogMetadataChanged(); + } + + void onCatalogMetadataChanged() { + updateTags(); + eventBus.fire(CatalogMetadataChangedEvent()); + } + + void updateTags() { + final updatedTags = visibleEntries.expand((entry) => entry.tags).toSet().toList()..sort(compareAsciiUpperCaseNatural); + if (!listEquals(updatedTags, sortedTags)) { + sortedTags = List.unmodifiable(updatedTags); + invalidateTagFilterSummary(); + eventBus.fire(TagsChangedEvent()); + } + } + + // filter summary + + // by tag + final Map<String, int> _filterEntryCountMap = {}, _filterSizeMap = {}; + final Map<String, AvesEntry?> _filterRecentEntryMap = {}; + + void invalidateTagFilterSummary({ + Set<AvesEntry>? entries, + Set<String>? tags, + bool notify = true, + }) { + if (_filterEntryCountMap.isEmpty && _filterSizeMap.isEmpty && _filterRecentEntryMap.isEmpty) return; + + if (entries == null && tags == null) { + _filterEntryCountMap.clear(); + _filterSizeMap.clear(); + _filterRecentEntryMap.clear(); + } else { + tags ??= {}; + if (entries != null) { + tags.addAll(entries.where((entry) => entry.isCatalogued).expand((entry) => entry.tags)); + } + tags.map((v) => TagFilter(v).key).forEach((key) { + _filterEntryCountMap.remove(key); + _filterSizeMap.remove(key); + _filterRecentEntryMap.remove(key); + }); + + // clear entries for all groups + invalidateTagGroupFilterSummary(notify: false); + } + if (notify) { + eventBus.fire(TagSummaryInvalidatedEvent(tags)); + eventBus.fire(const TagGroupSummaryInvalidatedEvent()); + } + } + + void invalidateTagGroupFilterSummary({bool notify = true}) { + _filterEntryCountMap.removeWhere(_isTagGroupKey); + _filterSizeMap.removeWhere(_isTagGroupKey); + _filterRecentEntryMap.removeWhere(_isTagGroupKey); + + if (notify) { + eventBus.fire(const TagGroupSummaryInvalidatedEvent()); + } + } + + bool _isTagGroupKey(String key, _) => key.startsWith('${TagGroupFilter.type}-'); + + int tagEntryCount(TagBaseFilter filter) { + return _filterEntryCountMap.putIfAbsent(filter.key, () => visibleEntries.where(filter.test).length); + } + + int tagSize(TagBaseFilter filter) { + return _filterSizeMap.putIfAbsent(filter.key, () => visibleEntries.where(filter.test).map((v) => v.sizeBytes).sum); + } + + AvesEntry? tagRecentEntry(TagBaseFilter filter) { + return _filterRecentEntryMap.putIfAbsent(filter.key, () => sortedEntriesByDate.firstWhereOrNull(filter.test)); + } +} + +class CatalogMetadataChangedEvent {} + +class TagsChangedEvent {} + +class TagGroupSummaryInvalidatedEvent { + const TagGroupSummaryInvalidatedEvent(); +} + +class TagSummaryInvalidatedEvent { + final Set<String>? tags; + + const TagSummaryInvalidatedEvent(this.tags); +} diff --git a/lib/model/source/trash.dart b/lib/model/source/trash.dart new file mode 100644 index 0000000..6afbce6 --- /dev/null +++ b/lib/model/source/trash.dart @@ -0,0 +1,86 @@ +import 'dart:async'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/model/metadata/trash.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/services/common/image_op_events.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/utils/android_file_utils.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; + +mixin TrashMixin on SourceBase { + static const Duration binKeepDuration = Duration(days: 30); + + Future<void> loadTrashDetails() async { + final saved = await localMediaDb.loadAllTrashDetails(); + final idMap = entryById; + saved.forEach((details) => idMap[details.id]?.trashDetails = details); + } + + Future<Set<String>> deleteExpiredTrash() async { + final expiredEntries = trashedEntries.where((entry) => entry.isExpiredTrash).toSet(); + if (expiredEntries.isEmpty) return {}; + + final processed = <ImageOpEvent>{}; + final opCompleter = Completer<Set<String>>(); + mediaEditService.delete(entries: expiredEntries).listen( + processed.add, + onError: opCompleter.completeError, + onDone: () async { + final successOps = processed.where((e) => e.success).toSet(); + final deletedOps = successOps.where((e) => !e.skipped).toSet(); + final deletedUris = deletedOps.map((event) => event.uri).toSet(); + opCompleter.complete(deletedUris); + }, + ); + return await opCompleter.future; + } + + Future<Set<AvesEntry>> recoverUntrackedTrashItems() async { + final newEntries = <AvesEntry>{}; + + final knownPaths = allEntries.map((v) => v.trashDetails?.path).nonNulls.toSet(); + final untrackedPaths = await storageService.getUntrackedTrashPaths(knownPaths); + if (untrackedPaths.isNotEmpty) { + debugPrint('Recovering ${untrackedPaths.length} untracked bin items'); + final recoveryPath = pContext.join(androidFileUtils.picturesPath, AndroidFileUtils.recoveryDir); + await Future.forEach(untrackedPaths, (untrackedPath) async { + TrashDetails _buildTrashDetails(int id) => TrashDetails( + id: id, + path: untrackedPath, + dateMillis: DateTime.now().millisecondsSinceEpoch, + ); + + final uri = Uri.file(untrackedPath).toString(); + final entry = allEntries.firstWhereOrNull((v) => v.uri == uri); + if (entry != null) { + // there is already a matching entry + // but missing trash details, and possibly not marked as trash + final id = entry.id; + entry.contentId = null; + entry.trashed = true; + entry.trashDetails = _buildTrashDetails(id); + // persist + await localMediaDb.updateEntry(id, entry); + await localMediaDb.updateTrash(id, entry.trashDetails); + } else { + // there is no matching entry + final sourceEntry = await mediaFetchService.getEntry(uri, null, allowUnsized: true); + if (sourceEntry != null) { + final id = localMediaDb.nextId; + sourceEntry.id = id; + sourceEntry.path = pContext.join(recoveryPath, pContext.basename(untrackedPath)); + sourceEntry.trashed = true; + sourceEntry.trashDetails = _buildTrashDetails(id); + newEntries.add(sourceEntry); + } else { + await reportService.recordError('Failed to recover untracked bin item at uri=$uri'); + } + } + }); + } + return newEntries; + } +} diff --git a/lib/model/vaults/details.dart b/lib/model/vaults/details.dart new file mode 100644 index 0000000..4d1a165 --- /dev/null +++ b/lib/model/vaults/details.dart @@ -0,0 +1,57 @@ +import 'package:aves/utils/android_file_utils.dart'; +import 'package:aves/utils/collection_utils.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flutter/foundation.dart'; + +@immutable +class VaultDetails extends Equatable { + final String name; + final bool autoLockScreenOff, useBin; + final VaultLockType lockType; + + @override + List<Object?> get props => [name, autoLockScreenOff, useBin, lockType]; + + const VaultDetails({ + required this.name, + required this.autoLockScreenOff, + required this.useBin, + required this.lockType, + }); + + VaultDetails copyWith({ + String? name, + }) { + return VaultDetails( + name: name ?? this.name, + autoLockScreenOff: autoLockScreenOff, + useBin: useBin, + lockType: lockType, + ); + } + + factory VaultDetails.fromMap(Map map) { + return VaultDetails( + name: map['name'] as String, + autoLockScreenOff: (map['autoLock'] as int? ?? 0) != 0, + useBin: (map['useBin'] as int? ?? 0) != 0, + lockType: VaultLockType.values.safeByName(map['lockType'] as String, VaultLockType.system), + ); + } + + Map<String, dynamic> toMap() => { + 'name': name, + 'autoLock': autoLockScreenOff ? 1 : 0, + 'useBin': useBin ? 1 : 0, + 'lockType': lockType.name, + }; + + String get passKey => 'vault_pass_$name'; + + String get path => '${androidFileUtils.vaultRoot}$name'; + + static String? nameFromPath(String path) { + return path.startsWith(androidFileUtils.vaultRoot) ? path.substring(androidFileUtils.vaultRoot.length) : null; + } +} diff --git a/lib/model/vaults/vaults.dart b/lib/model/vaults/vaults.dart new file mode 100644 index 0000000..c2bfd65 --- /dev/null +++ b/lib/model/vaults/vaults.dart @@ -0,0 +1,193 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/origins.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/model/vaults/details.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves_screen_state/aves_screen_state.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; +import 'package:provider/provider.dart'; + +final Vaults vaults = Vaults._private(); + +class Vaults extends ChangeNotifier { + final Set<StreamSubscription> _subscriptions = {}; + Set<VaultDetails> _rows = {}; + final Set<String> _unlockedDirPaths = {}; + + static const _fileScheme = 'file'; + + Vaults._private() { + if (kFlutterMemoryAllocationsEnabled) ChangeNotifier.maybeDispatchObjectCreation(this); + } + + Future<void> init() async { + _rows = await localMediaDb.loadAllVaults(); + _vaultDirPaths = null; + final screenStateStream = Platform.isAndroid ? AvesScreenState().screenStateStream : null; + if (screenStateStream != null) { + _subscriptions.add(screenStateStream.where((event) => event == ScreenStateEvent.off).listen((event) => _onScreenOff())); + } + } + + @override + void dispose() { + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + super.dispose(); + } + + Set<VaultDetails> get all => Set.unmodifiable(_rows); + + VaultDetails? detailsForPath(String dirPath) => _rows.firstWhereOrNull((v) => v.path == dirPath); + + Future<void> create(VaultDetails details) async { + await localMediaDb.addVaults({details}); + + _rows.add(details); + _vaultDirPaths = null; + _unlockedDirPaths.add(details.path); + _onLockStateChanged(); + } + + Future<void> remove(Set<String> dirPaths) async { + final details = dirPaths.map(detailsForPath).nonNulls.toSet(); + if (details.isEmpty) return; + + await localMediaDb.removeVaults(details); + + await Future.forEach(details, (v) => securityService.writeValue(v.passKey, null)); + + _rows.removeAll(details); + _vaultDirPaths = null; + _unlockedDirPaths.removeAll(dirPaths); + _onLockStateChanged(); + } + + Future<void> rename(String oldDirPath, String newDirPath) async { + final oldDetails = detailsForPath(oldDirPath); + if (oldDetails == null) return; + + final newName = VaultDetails.nameFromPath(newDirPath); + if (newName == null) return; + + final newDetails = oldDetails.copyWith(name: newName); + await localMediaDb.updateVault(oldDetails.name, newDetails); + + final pass = await securityService.readValue(oldDetails.passKey); + if (pass != null) { + await securityService.writeValue(newDetails.passKey, pass); + } + + _rows + ..remove(oldDetails) + ..add(newDetails); + _vaultDirPaths = null; + _unlockedDirPaths + ..remove(oldDirPath) + ..add(newDirPath); + _onLockStateChanged(); + } + + // update details, except name + Future<void> update(VaultDetails newDetails) async { + final oldDetails = detailsForPath(newDetails.path); + if (oldDetails == null) return; + + await localMediaDb.updateVault(newDetails.name, newDetails); + + _rows + ..remove(oldDetails) + ..add(newDetails); + } + + Future<void> clear() async { + await localMediaDb.clearVaults(); + _rows.clear(); + _vaultDirPaths = null; + } + + Set<String>? _vaultDirPaths; + + Set<String> get vaultDirectories { + _vaultDirPaths ??= _rows.map((v) => v.path).toSet(); + return _vaultDirPaths!; + } + + VaultDetails? getVault(String? dirPath) => all.firstWhereOrNull((v) => v.path == dirPath); + + bool isVault(String dirPath) => vaultDirectories.contains(dirPath); + + bool isLocked(String dirPath) => isVault(dirPath) && !_unlockedDirPaths.contains(dirPath); + + bool isVaultEntryUri(String uriString) { + final uri = Uri.parse(uriString); + if (uri.scheme != _fileScheme) return false; + + final path = uri.pathSegments.fold('', (prev, v) => '$prev${pContext.separator}$v'); + return vaultDirectories.any(path.startsWith); + } + + void lock(Set<String> dirPaths) { + final unlocked = dirPaths.where((v) => isVault(v) && !isLocked(v)).toSet(); + if (unlocked.isEmpty) return; + + _unlockedDirPaths.removeAll(unlocked); + _onLockStateChanged(); + } + + Future<void> unlock(BuildContext context, String dirPath) async { + if (!vaults.isVault(dirPath) || !vaults.isLocked(dirPath)) return; + + // recover untracked vault items + final source = context.read<CollectionSource>(); + final newEntries = await recoverUntrackedItems(source, dirPath); + if (newEntries.isNotEmpty) { + source.addEntries(newEntries); + await localMediaDb.insertEntries(newEntries); + unawaited(source.analyze(null, entries: newEntries)); + } + + _unlockedDirPaths.add(dirPath); + _onLockStateChanged(); + } + + Future<Set<AvesEntry>> recoverUntrackedItems(CollectionSource source, String dirPath) async { + final newEntries = <AvesEntry>{}; + + final vaultName = detailsForPath(dirPath)?.name; + if (vaultName == null) return newEntries; + + final knownPaths = source.allEntries.where((v) => v.origin == EntryOrigins.vault && v.directory == dirPath).map((v) => v.path).nonNulls.toSet(); + final untrackedPaths = await storageService.getUntrackedVaultPaths(vaultName, knownPaths); + if (untrackedPaths.isNotEmpty) { + debugPrint('Recovering ${untrackedPaths.length} untracked vault items'); + await Future.forEach(untrackedPaths, (untrackedPath) async { + final uri = Uri.file(untrackedPath).toString(); + final sourceEntry = await mediaFetchService.getEntry(uri, null, allowUnsized: true); + if (sourceEntry != null) { + sourceEntry.id = localMediaDb.nextId; + sourceEntry.origin = EntryOrigins.vault; + newEntries.add(sourceEntry); + } else { + await reportService.recordError('Failed to recover untracked vault item at uri=$uri'); + } + }); + } + return newEntries; + } + + void _onScreenOff() => lock(all.where((v) => v.autoLockScreenOff).map((v) => v.path).toSet()); + + bool get needProtection => _unlockedDirPaths.isNotEmpty; + + void _onLockStateChanged() { + windowService.secureScreen(needProtection); + notifyListeners(); + } +} diff --git a/lib/model/viewer/video_playback.dart b/lib/model/viewer/video_playback.dart new file mode 100644 index 0000000..43bfce3 --- /dev/null +++ b/lib/model/viewer/video_playback.dart @@ -0,0 +1,27 @@ +import 'package:equatable/equatable.dart'; +import 'package:flutter/foundation.dart'; + +@immutable +class VideoPlaybackRow extends Equatable { + final int entryId, resumeTimeMillis; + + @override + List<Object?> get props => [entryId, resumeTimeMillis]; + + const VideoPlaybackRow({ + required this.entryId, + required this.resumeTimeMillis, + }); + + static VideoPlaybackRow? fromMap(Map map) { + return VideoPlaybackRow( + entryId: map['id'], + resumeTimeMillis: map['resumeTimeMillis'], + ); + } + + Map<String, dynamic> toMap() => { + 'id': entryId, + 'resumeTimeMillis': resumeTimeMillis, + }; +} diff --git a/lib/model/viewer/view_state.dart b/lib/model/viewer/view_state.dart new file mode 100644 index 0000000..6e8c573 --- /dev/null +++ b/lib/model/viewer/view_state.dart @@ -0,0 +1,54 @@ +import 'package:equatable/equatable.dart'; +import 'package:flutter/widgets.dart'; + +@immutable +class ViewState extends Equatable { + final Offset position; + final double? scale; + final Size? viewportSize, contentSize; + + static const ViewState zero = ViewState( + position: Offset.zero, + scale: 0, + viewportSize: null, + contentSize: null, + ); + + @override + List<Object?> get props => [position, scale, viewportSize, contentSize]; + + const ViewState({ + required this.position, + required this.scale, + required this.viewportSize, + required this.contentSize, + }); + + ViewState copyWith({ + Offset? position, + double? scale, + Size? viewportSize, + Size? contentSize, + }) { + return ViewState( + position: position ?? this.position, + scale: scale ?? this.scale, + viewportSize: viewportSize ?? this.viewportSize, + contentSize: contentSize ?? this.contentSize, + ); + } + + Matrix4 get matrix { + final _viewportSize = viewportSize ?? Size.zero; + final _contentSize = contentSize ?? Size.zero; + final _scale = scale ?? 1.0; + + final scaledContentSize = _contentSize * _scale; + final viewOffset = _viewportSize.center(Offset.zero) - scaledContentSize.center(Offset.zero); + + return Matrix4.identity() + ..translate(position.dx, position.dy) + ..translate(viewOffset.dx, viewOffset.dy) + ..scale(_scale, _scale, 1); + } +} |
