commit 295625c70f2b69b53eb70fa3d959b0ab4f695b01 Author: Sanders Date: Mon May 12 19:08:22 2025 +0300 Init diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..79c113f --- /dev/null +++ b/.gitignore @@ -0,0 +1,45 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/.metadata b/.metadata new file mode 100644 index 0000000..e8f7bf9 --- /dev/null +++ b/.metadata @@ -0,0 +1,45 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "ea121f8859e4b13e47a8f845e4586164519588bc" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: ea121f8859e4b13e47a8f845e4586164519588bc + base_revision: ea121f8859e4b13e47a8f845e4586164519588bc + - platform: android + create_revision: ea121f8859e4b13e47a8f845e4586164519588bc + base_revision: ea121f8859e4b13e47a8f845e4586164519588bc + - platform: ios + create_revision: ea121f8859e4b13e47a8f845e4586164519588bc + base_revision: ea121f8859e4b13e47a8f845e4586164519588bc + - platform: linux + create_revision: ea121f8859e4b13e47a8f845e4586164519588bc + base_revision: ea121f8859e4b13e47a8f845e4586164519588bc + - platform: macos + create_revision: ea121f8859e4b13e47a8f845e4586164519588bc + base_revision: ea121f8859e4b13e47a8f845e4586164519588bc + - platform: web + create_revision: ea121f8859e4b13e47a8f845e4586164519588bc + base_revision: ea121f8859e4b13e47a8f845e4586164519588bc + - platform: windows + create_revision: ea121f8859e4b13e47a8f845e4586164519588bc + base_revision: ea121f8859e4b13e47a8f845e4586164519588bc + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/README.md b/README.md new file mode 100644 index 0000000..251487d --- /dev/null +++ b/README.md @@ -0,0 +1,16 @@ +# finance_app_2 + +A new Flutter project. + +## Getting Started + +This project is a starting point for a Flutter application. + +A few resources to get you started if this is your first Flutter project: + +- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) +- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook) + +For help getting started with Flutter development, view the +[online documentation](https://docs.flutter.dev/), which offers tutorials, +samples, guidance on mobile development, and a full API reference. diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 0000000..0d29021 --- /dev/null +++ b/analysis_options.yaml @@ -0,0 +1,28 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at https://dart.dev/lints. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000..be3943c --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,14 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java +.cxx/ + +# Remember to never publicly share your keystore. +# See https://flutter.dev/to/reference-keystore +key.properties +**/*.keystore +**/*.jks diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts new file mode 100644 index 0000000..1d83390 --- /dev/null +++ b/android/app/build.gradle.kts @@ -0,0 +1,44 @@ +plugins { + id("com.android.application") + id("kotlin-android") + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id("dev.flutter.flutter-gradle-plugin") +} + +android { + namespace = "ru.sanders.finance_app_2" + compileSdk = flutter.compileSdkVersion + ndkVersion = "28.1.13356709" + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 + } + + kotlinOptions { + jvmTarget = JavaVersion.VERSION_11.toString() + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId = "ru.sanders.finance_app_2" + // You can update the following values to match your application needs. + // For more information, see: https://flutter.dev/to/review-gradle-config. + minSdk = flutter.minSdkVersion + targetSdk = flutter.targetSdkVersion + versionCode = flutter.versionCode + versionName = flutter.versionName + } + + buildTypes { + release { + // TODO: Add your own signing config for the release build. + // Signing with the debug keys for now, so `flutter run --release` works. + signingConfig = signingConfigs.getByName("debug") + } + } +} + +flutter { + source = "../.." +} diff --git a/android/app/src/debug/AndroidManifest.xml b/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..b0dc2b4 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/kotlin/ru/sanders/finance_app_2/MainActivity.kt b/android/app/src/main/kotlin/ru/sanders/finance_app_2/MainActivity.kt new file mode 100644 index 0000000..4f13320 --- /dev/null +++ b/android/app/src/main/kotlin/ru/sanders/finance_app_2/MainActivity.kt @@ -0,0 +1,5 @@ +package ru.sanders.finance_app_2 + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity : FlutterActivity() diff --git a/android/app/src/main/res/drawable-v21/launch_background.xml b/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 0000000..f74085f --- /dev/null +++ b/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/drawable/launch_background.xml b/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 0000000..304732f --- /dev/null +++ b/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..db77bb4 Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..17987b7 Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..09d4391 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..d5f1c8d Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..4d6372e Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/values-night/styles.xml b/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000..06952be --- /dev/null +++ b/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/main/res/values/styles.xml b/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..cb1ef88 --- /dev/null +++ b/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/profile/AndroidManifest.xml b/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/build.gradle.kts b/android/build.gradle.kts new file mode 100644 index 0000000..89176ef --- /dev/null +++ b/android/build.gradle.kts @@ -0,0 +1,21 @@ +allprojects { + repositories { + google() + mavenCentral() + } +} + +val newBuildDir: Directory = rootProject.layout.buildDirectory.dir("../../build").get() +rootProject.layout.buildDirectory.value(newBuildDir) + +subprojects { + val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name) + project.layout.buildDirectory.value(newSubprojectBuildDir) +} +subprojects { + project.evaluationDependsOn(":app") +} + +tasks.register("clean") { + delete(rootProject.layout.buildDirectory) +} diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000..f018a61 --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true +android.enableJetifier=true diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..afa1e8e --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-all.zip diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts new file mode 100644 index 0000000..a439442 --- /dev/null +++ b/android/settings.gradle.kts @@ -0,0 +1,25 @@ +pluginManagement { + val flutterSdkPath = run { + val properties = java.util.Properties() + file("local.properties").inputStream().use { properties.load(it) } + val flutterSdkPath = properties.getProperty("flutter.sdk") + require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" } + flutterSdkPath + } + + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +plugins { + id("dev.flutter.flutter-plugin-loader") version "1.0.0" + id("com.android.application") version "8.7.0" apply false + id("org.jetbrains.kotlin.android") version "1.8.22" apply false +} + +include(":app") diff --git a/ios/.gitignore b/ios/.gitignore new file mode 100644 index 0000000..7a7f987 --- /dev/null +++ b/ios/.gitignore @@ -0,0 +1,34 @@ +**/dgph +*.mode1v3 +*.mode2v3 +*.moved-aside +*.pbxuser +*.perspectivev3 +**/*sync/ +.sconsign.dblite +.tags* +**/.vagrant/ +**/DerivedData/ +Icon? +**/Pods/ +**/.symlinks/ +profile +xcuserdata +**/.generated/ +Flutter/App.framework +Flutter/Flutter.framework +Flutter/Flutter.podspec +Flutter/Generated.xcconfig +Flutter/ephemeral/ +Flutter/app.flx +Flutter/app.zip +Flutter/flutter_assets/ +Flutter/flutter_export_environment.sh +ServiceDefinitions.json +Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!default.mode1v3 +!default.mode2v3 +!default.pbxuser +!default.perspectivev3 diff --git a/ios/Flutter/AppFrameworkInfo.plist b/ios/Flutter/AppFrameworkInfo.plist new file mode 100644 index 0000000..7c56964 --- /dev/null +++ b/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + MinimumOSVersion + 12.0 + + diff --git a/ios/Flutter/Debug.xcconfig b/ios/Flutter/Debug.xcconfig new file mode 100644 index 0000000..592ceee --- /dev/null +++ b/ios/Flutter/Debug.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/ios/Flutter/Release.xcconfig b/ios/Flutter/Release.xcconfig new file mode 100644 index 0000000..592ceee --- /dev/null +++ b/ios/Flutter/Release.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..5c9e9a2 --- /dev/null +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,616 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXBuildFile section */ + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; }; + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C8085294A63A400263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 97C146E61CF9000F007C117D /* Project object */; + proxyType = 1; + remoteGlobalIDString = 97C146ED1CF9000F007C117D; + remoteInfo = Runner; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 9705A1C41CF9048500538489 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; + 331C807B294A618700263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; + 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; + 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 97C146EB1CF9000F007C117D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C8082294A63A400263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C807B294A618700263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 9740EEB31CF90195004384FC /* Generated.xcconfig */, + ); + name = Flutter; + sourceTree = ""; + }; + 97C146E51CF9000F007C117D = { + isa = PBXGroup; + children = ( + 9740EEB11CF90186004384FC /* Flutter */, + 97C146F01CF9000F007C117D /* Runner */, + 97C146EF1CF9000F007C117D /* Products */, + 331C8082294A63A400263BE5 /* RunnerTests */, + ); + sourceTree = ""; + }; + 97C146EF1CF9000F007C117D /* Products */ = { + isa = PBXGroup; + children = ( + 97C146EE1CF9000F007C117D /* Runner.app */, + 331C8081294A63A400263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 97C146F01CF9000F007C117D /* Runner */ = { + isa = PBXGroup; + children = ( + 97C146FA1CF9000F007C117D /* Main.storyboard */, + 97C146FD1CF9000F007C117D /* Assets.xcassets */, + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, + 97C147021CF9000F007C117D /* Info.plist */, + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, + ); + path = Runner; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C8080294A63A400263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C807D294A63A400263BE5 /* Sources */, + 331C807F294A63A400263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C8086294A63A400263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 97C146ED1CF9000F007C117D /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 9740EEB61CF901F6004384FC /* Run Script */, + 97C146EA1CF9000F007C117D /* Sources */, + 97C146EB1CF9000F007C117D /* Frameworks */, + 97C146EC1CF9000F007C117D /* Resources */, + 9705A1C41CF9048500538489 /* Embed Frameworks */, + 3B06AD1E1E4923F5004D2608 /* Thin Binary */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Runner; + productName = Runner; + productReference = 97C146EE1CF9000F007C117D /* Runner.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 97C146E61CF9000F007C117D /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C8080294A63A400263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 97C146ED1CF9000F007C117D; + }; + 97C146ED1CF9000F007C117D = { + CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 1100; + }; + }; + }; + buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 97C146E51CF9000F007C117D; + productRefGroup = 97C146EF1CF9000F007C117D /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 97C146ED1CF9000F007C117D /* Runner */, + 331C8080294A63A400263BE5 /* RunnerTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C807F294A63A400263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EC1CF9000F007C117D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}", + ); + name = "Thin Binary"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; + }; + 9740EEB61CF901F6004384FC /* Run Script */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Run Script"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C807D294A63A400263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EA1CF9000F007C117D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C8086294A63A400263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 97C146ED1CF9000F007C117D /* Runner */; + targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 97C146FA1CF9000F007C117D /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C146FB1CF9000F007C117D /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C147001CF9000F007C117D /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 249021D3217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Profile; + }; + 249021D4217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = ru.sanders.financeApp2; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Profile; + }; + 331C8088294A63A400263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = ru.sanders.financeApp2.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Debug; + }; + 331C8089294A63A400263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = ru.sanders.financeApp2.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Release; + }; + 331C808A294A63A400263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = ru.sanders.financeApp2.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Profile; + }; + 97C147031CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 97C147041CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 97C147061CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = ru.sanders.financeApp2; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Debug; + }; + 97C147071CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = ru.sanders.financeApp2; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C8088294A63A400263BE5 /* Debug */, + 331C8089294A63A400263BE5 /* Release */, + 331C808A294A63A400263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147031CF9000F007C117D /* Debug */, + 97C147041CF9000F007C117D /* Release */, + 249021D3217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147061CF9000F007C117D /* Debug */, + 97C147071CF9000F007C117D /* Release */, + 249021D4217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 97C146E61CF9000F007C117D /* Project object */; +} diff --git a/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..15cada4 --- /dev/null +++ b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,99 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift new file mode 100644 index 0000000..6266644 --- /dev/null +++ b/ios/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import Flutter +import UIKit + +@main +@objc class AppDelegate: FlutterAppDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + GeneratedPluginRegistrant.register(with: self) + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } +} diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..d36b1fa --- /dev/null +++ b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,122 @@ +{ + "images" : [ + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@3x.png", + "scale" : "3x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@3x.png", + "scale" : "3x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@3x.png", + "scale" : "3x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@2x.png", + "scale" : "2x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@3x.png", + "scale" : "3x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@1x.png", + "scale" : "1x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@1x.png", + "scale" : "1x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@1x.png", + "scale" : "1x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@2x.png", + "scale" : "2x" + }, + { + "size" : "83.5x83.5", + "idiom" : "ipad", + "filename" : "Icon-App-83.5x83.5@2x.png", + "scale" : "2x" + }, + { + "size" : "1024x1024", + "idiom" : "ios-marketing", + "filename" : "Icon-App-1024x1024@1x.png", + "scale" : "1x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 0000000..dc9ada4 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png new file mode 100644 index 0000000..7353c41 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png new file mode 100644 index 0000000..797d452 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png new file mode 100644 index 0000000..6ed2d93 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png new file mode 100644 index 0000000..4cd7b00 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png new file mode 100644 index 0000000..fe73094 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png new file mode 100644 index 0000000..321773c Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png new file mode 100644 index 0000000..797d452 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png new file mode 100644 index 0000000..502f463 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png new file mode 100644 index 0000000..0ec3034 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png new file mode 100644 index 0000000..0ec3034 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png new file mode 100644 index 0000000..e9f5fea Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png new file mode 100644 index 0000000..84ac32a Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png new file mode 100644 index 0000000..8953cba Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png new file mode 100644 index 0000000..0467bf1 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 0000000..0bedcf2 --- /dev/null +++ b/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "LaunchImage.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md new file mode 100644 index 0000000..89c2725 --- /dev/null +++ b/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md @@ -0,0 +1,5 @@ +# Launch Screen Assets + +You can customize the launch screen with your own desired assets by replacing the image files in this directory. + +You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. \ No newline at end of file diff --git a/ios/Runner/Base.lproj/LaunchScreen.storyboard b/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..f2e259c --- /dev/null +++ b/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/Base.lproj/Main.storyboard b/ios/Runner/Base.lproj/Main.storyboard new file mode 100644 index 0000000..f3c2851 --- /dev/null +++ b/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist new file mode 100644 index 0000000..c6dde4e --- /dev/null +++ b/ios/Runner/Info.plist @@ -0,0 +1,49 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Finance App 2 + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + finance_app_2 + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSRequiresIPhoneOS + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + CADisableMinimumFrameDurationOnPhone + + UIApplicationSupportsIndirectInputEvents + + + diff --git a/ios/Runner/Runner-Bridging-Header.h b/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 0000000..308a2a5 --- /dev/null +++ b/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" diff --git a/ios/RunnerTests/RunnerTests.swift b/ios/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..86a7c3b --- /dev/null +++ b/ios/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Flutter +import UIKit +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/lib/app.dart b/lib/app.dart new file mode 100644 index 0000000..370f98b --- /dev/null +++ b/lib/app.dart @@ -0,0 +1,41 @@ +import 'package:flutter/material.dart'; +import 'screens/expenses_screen.dart'; +import 'theme/app_theme.dart'; +import 'database/database.dart'; // Import the database + +class MyApp extends StatefulWidget { + final AppDatabase database; // Принимаем экземпляр базы данных + + const MyApp({Key? key, required this.database}) : super(key: key); + + @override + State createState() => _MyAppState(); +} + +class _MyAppState extends State { + // Состояние для управления темой (светлая/темная) + bool _isDarkMode = false; + + // Метод для переключения темы + void toggleTheme() { + setState(() { + _isDarkMode = !_isDarkMode; + }); + } + + @override + Widget build(BuildContext context) { + return MaterialApp( + title: 'Finance App', // Обновленный заголовок + debugShowCheckedModeBanner: false, // Скрыть баннер Debug + themeMode: _isDarkMode ? ThemeMode.dark : ThemeMode.light, // Управление темой + theme: AppTheme.lightTheme, // Светлая тема + darkTheme: AppTheme.darkTheme, // Темная тема + home: ExpensesScreen( + database: widget.database, // Передаем базу данных в главный экран + toggleTheme: toggleTheme, // Передаем функцию переключения темы + isDarkMode: _isDarkMode, // Передаем текущее состояние темы + ), + ); + } +} diff --git a/lib/database/database.dart b/lib/database/database.dart new file mode 100644 index 0000000..8cf4702 --- /dev/null +++ b/lib/database/database.dart @@ -0,0 +1,432 @@ +// ignore_for_file: unused_import // Часто генерируется при условном импорте + +import 'package:drift/drift.dart'; +import 'package:async/async.dart'; +import 'package:flutter/material.dart' as c; // Use alias 'c' for flutter material +// Условный импорт бэкенда базы данных +// Выбирает реализацию connect() в зависимости от платформы +import 'database_connection/connection.dart' // Базовый импорт + if (dart.library.html) 'database_connection/connection_web.dart' // Для Веб + if (dart.library.io) 'database_connection/connection_native.dart'; // Для Нативных платформ (Android, iOS, Desktop) + +// Импортируем модель категории для возвращаемого типа и утилиты +import '../models/category.dart'; +import '../utils/category_utils.dart'; // Helper for category details + +// Эта строка указывает Drift сгенерировать файл database.g.dart +part 'database.g.dart'; + +// Enum for transaction type (used internally and potentially externally) +enum TransactionType { income, expense } + +// Определение таблицы Categories +// ИСПРАВЛЕНО: Имя класса таблицы изменено на Categories для ясности +@DataClassName('CategoryDb') +class Categories extends Table { // Changed class name to plural 'Categories' + IntColumn get id => integer().autoIncrement()(); + TextColumn get name => text().unique()(); + TextColumn get icon => text()(); // Store icon name (e.g., 'shopping_cart_outlined') + IntColumn get color => integer()(); // Store color value (e.g., Colors.green.value) +} + +// Определение таблицы Transactions +// Имя таблицы в SQL будет 'transactions' (snake_case от имени класса) +@DataClassName('Transaction') // Keep the generated class name as Transaction +class Transactions extends Table { + IntColumn get id => integer().autoIncrement()(); // Primary key + TextColumn get categoryName => text().named('category_name')(); // Имя категории (или 'Income') + RealColumn get amount => real()(); // Сумма транзакции + DateTimeColumn get date => dateTime()(); // Дата транзакции + TextColumn get merchant => text().named('merchant')(); // Название продавца/источника + // ИСПРАВЛЕНО: Добавлено .withDefault() для значения по умолчанию + TextColumn get type => text().named('type').withDefault(const Constant('expense'))(); // Тип транзакции ('income' или 'expense') +} + +// Класс базы данных +// Аннотация @DriftDatabase указывает Drift сгенерировать код для этой базы данных +@DriftDatabase(tables: [Categories, Transactions]) // Updated table name here +class AppDatabase extends _$AppDatabase { + // Используем функцию connect() из условного импорта для создания соединения + // Во время компиляции будет выбрана правильная реализация connect() + // из connection_web.dart или connection_native.dart. + AppDatabase() : super(connect()); + + // Версия схемы. Увеличивайте при изменении структуры таблиц. + @override + int get schemaVersion => 4; // Increased version due to adding Categories table + + @override + MigrationStrategy get migration => MigrationStrategy( + onCreate: (m) async { + await m.createAll(); + // Вставляем начальные данные ТОЛЬКО при создании базы данных + print("Database created. Inserting initial data..."); + // ИЗМЕНЕНО: Вызов insertInitialDataIfNeeded теперь только здесь + await insertInitialDataIfNeeded(); + }, + onUpgrade: (m, from, to) async { + // Drift автоматически обработает добавление новых таблиц (Categories) + // при обновлении до версии 4. + // Нам нужно только обработать специфичные изменения, как добавление колонки type. + if (from < 4) { // Check if upgrading from a version before 4 + // Check if the 'type' column exists before trying to add it + // This requires a more complex check, usually involving inspecting the schema. + // For simplicity, we assume if version is < 4, the column might be missing. + // A safer approach involves querying PRAGMA table_info(transactions); + // However, Drift's default migration handles adding columns well. + // Let's ensure the Categories table is created if upgrading from very old versions. + await m.createTable(categories); // Ensure categories table exists + // Add the 'type' column if it doesn't exist (Drift might handle this, but explicit is safer) + // We'll rely on Drift's default behavior for adding the column here. + // If specific default values or constraints were needed during upgrade, + // more complex logic would be required. + } + if (from == 1) { + // Example: If migrating specifically from 1, maybe add the type column + // await m.addColumn(transactions, transactions.type); + // But the check `from < 4` above is more general if relying on Drift's auto-migration. + } + // Add more migration steps for future versions here + // if (from < 5) { ... } + + // ИЗМЕНЕНО: Удален вызов insertInitialDataIfNeeded отсюда + // Не нужно вставлять начальные данные при обновлении существующей БД. + }, + beforeOpen: (details) async { + // ИЗМЕНЕНО: Удален вызов insertInitialDataIfNeeded отсюда + // Логика вставки начальных данных теперь полностью в onCreate. + if (details.wasCreated) { + print("Database was created. Initial data should have been inserted via onCreate."); + } else { + print("Opening existing database version ${details.versionNow}."); + } + // Можно добавить здесь другие проверки или настройки при открытии, если нужно. + return Future.value(); // beforeOpen должен возвращать Future + }, + ); + + + // --- Методы для работы с транзакциями --- + + // Получить все транзакции в виде потока, упорядоченные по дате (сначала новые) + // Возвращает non-nullable Stream> (Transaction - сгенерированный Drift класс) + Stream> watchAllTransactions() { + return (select(transactions) + ..orderBy([(t) => OrderingTerm(expression: t.date, mode: OrderingMode.desc)])) + .watch(); + } + + // Получить транзакции, отфильтрованные по категории РАСХОДОВ, в виде потока + // Если categoryName == 'All', возвращает ВСЕ транзакции (и доходы, и расходы) + // Возвращает non-nullable Stream> (Transaction - сгенерированный Drift класс) + Stream> watchFilteredTransactions(String categoryName) { + if (categoryName == 'All') { + // watchAllTransactions теперь возвращает non-nullable Stream + return watchAllTransactions(); // Return all types if filter is 'All' + } + // Otherwise, filter by the provided category name AND ensure it's an expense + return (select(transactions) + ..where((t) => t.categoryName.equals(categoryName) & t.type.equals('expense')) + ..orderBy([(t) => OrderingTerm(expression: t.date, mode: OrderingMode.desc)])) + .watch(); + } + + // Добавить новую транзакцию + // Принимает TransactionsCompanion - сгенерированный Drift класс (должен включать type) + Future addTransaction(TransactionsCompanion entry) { + // Убедимся, что тип указан + assert(entry.type.present && (entry.type.value == 'income' || entry.type.value == 'expense')); + // Убедимся, что для дохода используется специальная категория + if (entry.type.value == 'income') { + assert(entry.categoryName.present && entry.categoryName.value == 'Income'); + } + return into(transactions).insert(entry); + } + + // Обновить существующую транзакцию + // Принимает TransactionsCompanion, который должен содержать ID + // Возвращает true, если обновление прошло успешно + Future updateTransaction(TransactionsCompanion entry) { + // Проверяем, что ID предоставлен для обновления + assert(entry.id.present); + // Убедимся, что тип указан + assert(entry.type.present && (entry.type.value == 'income' || entry.type.value == 'expense')); + // Убедимся, что для дохода используется специальная категория + if (entry.type.value == 'income') { + assert(entry.categoryName.present && entry.categoryName.value == 'Income'); + } + + // Используем .replace() для обновления записи по ID + // replace возвращает true, если запись была обновлена (найдена по ID) + return update(transactions).replace(entry); + } + + // Удалить транзакцию по ID + // Возвращает количество удаленных строк (0 или 1) + Future deleteTransaction(int id) { + // Используем .delete() с условием where + return (delete(transactions)..where((t) => t.id.equals(id))).go(); + } + + + // --- Методы для работы с категориями --- + + // Получить все категории в виде потока, упорядоченные по имени + // Возвращает Stream> (CategoryDb - сгенерированный Drift класс) + Stream> watchAllCategoriesDb() { + return (select(categories)..orderBy([(c) => OrderingTerm(expression: c.name)])).watch(); + } + + // Добавить новую категорию + // Принимает CategoriesCompanion (сгенерированный Drift) + // Возвращает ID вставленной категории + Future addCategory(CategoriesCompanion entry) { + // Проверяем, что имя, иконка и цвет предоставлены + assert(entry.name.present && entry.name.value.isNotEmpty); + assert(entry.icon.present); // Icon can be empty string if needed + assert(entry.color.present); + // Не позволяем добавить категорию с именем 'Income' (case-insensitive) + assert(entry.name.value.toLowerCase() != 'income'); + return into(categories).insert(entry); + } + + // Обновить существующую категорию + // Принимает CategoriesCompanion, который должен содержать ID + // Возвращает true, если обновление прошло успешно + Future updateCategory(CategoriesCompanion entry) { + // Проверяем, что ID предоставлен для обновления + assert(entry.id.present); + // Проверяем, что имя не 'Income' (case-insensitive) + if (entry.name.present && entry.name.value.toLowerCase() == 'income') { + print("Error: Cannot rename category to 'Income'."); + return Future.value(false); // Запрещаем переименование в 'Income' + } + + // Используем транзакцию для проверки и обновления + return transaction(() async { + // Находим категорию по ID перед обновлением + final existingCategory = await (select(categories)..where((c) => c.id.equals(entry.id.value))).getSingleOrNull(); + + // Проверяем, существует ли категория и не является ли она 'Income' + if (existingCategory == null) { + print("Error: Category with ID ${entry.id.value} not found for update."); + return false; // Категория не найдена + } + if (existingCategory.name == 'Income') { + print("Error: Cannot update the 'Income' category."); + return false; // Запрещаем обновление категории 'Income' + } + + // Выполняем обновление + // Метод replace возвращает true, если запись была обновлена + final updated = await update(categories).replace(entry); + + // Если имя категории было изменено, нужно обновить categoryName во всех связанных транзакциях + if (updated && entry.name.present && entry.name.value != existingCategory.name) { + print("Category name changed from '${existingCategory.name}' to '${entry.name.value}'. Updating transactions..."); + final updatedTransactions = await (update(transactions) + ..where((t) => t.categoryName.equals(existingCategory.name))) + .write(TransactionsCompanion( + categoryName: Value(entry.name.value), + )); + print("Updated $updatedTransactions transactions with the new category name."); + } + + return updated; // Возвращаем результат replace + }); + } + + // Удалить категорию по ID + // Возвращает количество удаленных строк (0 или 1) + Future deleteCategory(int id) { + // Используем транзакцию для проверок и удаления + return transaction(() async { + // Находим категорию по ID перед удалением + final categoryToDelete = await (select(categories)..where((c) => c.id.equals(id))).getSingleOrNull(); + + // Проверяем, существует ли категория + if (categoryToDelete == null) { + print("Error: Category with ID $id not found for deletion."); + return 0; // Категория не найдена + } + + // Запрещаем удаление категории 'Income' + if (categoryToDelete.name == 'Income') { + print("Error: Cannot delete the 'Income' category."); + return 0; // Возвращаем 0, т.к. ничего не удалено + } + + // Проверяем, есть ли транзакции с этой категорией + // Используем имя категории для связи (т.к. нет внешнего ключа) + final query = selectOnly(transactions) + ..addColumns([transactions.id.count()]) + ..where(transactions.categoryName.equals(categoryToDelete.name)); // Используем имя для связи + + final result = await query.getSingleOrNull(); + final transactionCount = result?.read(transactions.id.count()) ?? 0; + + if (transactionCount > 0) { + print("Error: Cannot delete category '${categoryToDelete.name}' because it has $transactionCount associated transaction(s)."); + // Можно выбросить исключение или вернуть 0, чтобы показать неудачу + // throw Exception("Cannot delete category with transactions."); + return 0; // Не удаляем, возвращаем 0 + } + + // Если транзакций нет, удаляем категорию + print("Deleting category '${categoryToDelete.name}' (ID: $id)..."); + final deletedRows = await (delete(categories)..where((c) => c.id.equals(id))).go(); + print("Deleted $deletedRows category row(s)."); + return deletedRows; // Возвращаем количество удаленных строк + }); + } + + + // Получить категорию по ID (если нужно) + Future getCategoryById(int id) { + return (select(categories)..where((c) => c.id.equals(id))).getSingleOrNull(); + } + + // --- Методы для агрегации и отчетов --- + + // Вычислить и наблюдать за общими суммами по категориям РАСХОДОВ + // Возвращает Stream> где Category - это класс модели из '../models/category.dart' + Stream> calculateCategoryTotals() { + // 1. Создаем поток, который объединяет транзакции и категории + final transactionsStream = watchAllTransactions(); + final categoriesStream = watchAllCategoriesDb(); + + // Используем StreamZip для объединения последних данных из обоих потоков + return StreamZip([transactionsStream, categoriesStream]).map((data) { + final transactionList = data[0] as List; + final categoryList = data[1] as List; + + // Создаем Map для быстрого доступа к деталям категории по имени + final categoryDetailsMap = { + for (var cat in categoryList) cat.name: cat + }; + + // 2. Фильтруем только расходы и группируем по categoryName, суммируя amount + final categoryTotals = {}; + for (var transaction in transactionList) { + // Суммируем только расходы (исключая 'Income') + if (transaction.type == 'expense') { + categoryTotals.update( + transaction.categoryName, + (value) => value + transaction.amount, + ifAbsent: () => transaction.amount, + ); + } + } + + // 3. Преобразуем сгруппированные данные в список объектов Category (модель UI) + return categoryTotals.entries.map((entry) { + final categoryName = entry.key; + final totalAmount = entry.value; + // Получаем детали категории из Map (или используем дефолтные, если категория была удалена) + final categoryDb = categoryDetailsMap[categoryName]; + final iconData = CategoryUtils.getIconFromString(categoryDb?.icon); // Используем утилиту + final colorData = categoryDb != null ? c.Color(categoryDb.color) : c.Colors.grey.shade500; // Цвет из БД или дефолтный + + return Category( // Это Category из models/category.dart + categoryName, + totalAmount, + colorData, + iconData, + ); + }).toList() + // Сортируем категории по сумме (от большей к меньшей) + ..sort((a, b) => b.amount.compareTo(a.amount)); + }); + } + + + // Вычислить и наблюдать за общей суммой ДОХОДОВ + Stream watchTotalIncome() { + // Создаем выражение для суммы amount + final amountSum = transactions.amount.sum(); + // Строим запрос: выбрать сумму amount из transactions, где type = 'income' + final query = selectOnly(transactions) + ..addColumns([amountSum]) + ..where(transactions.type.equals('income')); + + // Выполняем запрос и наблюдаем за изменениями + // map преобразует результат (единственную строку с суммой) в double + // ?? 0.0 обрабатывает случай, когда доходов нет (сумма будет null) + return query.watchSingleOrNull().map((result) => result?.read(amountSum) ?? 0.0); + } + + // Вычислить и наблюдать за общей суммой РАСХОДОВ (альтернатива суммированию категорий) + Stream watchTotalExpenses() { + final amountSum = transactions.amount.sum(); + final query = selectOnly(transactions) + ..addColumns([amountSum]) + ..where(transactions.type.equals('expense')); + return query.watchSingleOrNull().map((result) => result?.read(amountSum) ?? 0.0); + } + + + // Добавление начальных данных (вызывается только из onCreate) + // ИЗМЕНЕНО: Убран необязательный параметр isCreating, т.к. вызывается только при создании + Future insertInitialDataIfNeeded() async { + // Проверяем, есть ли уже категории (на всякий случай, хотя в onCreate их быть не должно) + final categoriesCountResult = await (selectOnly(categories)..addColumns([categories.id.count()])).getSingleOrNull(); + final categoriesCount = categoriesCountResult?.read(categories.id.count()) ?? 0; + + if (categoriesCount == 0) { + print("Inserting initial categories..."); + // Получаем доступные цвета из CategoryUtils + final availableColors = CategoryUtils.availableColors; + + await batch((batch) { + batch.insertAll(categories, [ + // Используем CategoriesCompanion (сгенерированный для таблицы Categories) + // Используем реальные имена иконок Material Icons и конкретные значения цветов из списка + CategoriesCompanion.insert(name: 'Groceries', icon: 'shopping_cart_outlined', color: availableColors[0].value), // Red + CategoriesCompanion.insert(name: 'Subscriptions', icon: 'subscriptions_outlined', color: availableColors[4].value), // Indigo + CategoriesCompanion.insert(name: 'Restaurant', icon: 'restaurant_menu_outlined', color: availableColors[14].value), // Orange + CategoriesCompanion.insert(name: 'Shopping', icon: 'shopping_bag_outlined', color: availableColors[5].value), // Blue + CategoriesCompanion.insert(name: 'Transport', icon: 'directions_bus_filled_outlined', color: availableColors[2].value), // Purple + CategoriesCompanion.insert(name: 'Travel', icon: 'flight_takeoff_outlined', color: availableColors[7].value), // Cyan + CategoriesCompanion.insert(name: 'Utilities', icon: 'home_outlined', color: availableColors[8].value), // Teal + // 'Income' category - use a specific icon and color (можно тоже взять из списка или оставить уникальный) + // Оставим уникальный цвет для Income для выделения + CategoriesCompanion.insert(name: 'Income', icon: 'attach_money', color: c.Colors.lightGreenAccent.shade700.value), + ]); + }); + print("Initial categories inserted."); + } else { + // Эта ветка не должна выполняться при вызове из onCreate, но оставим для отладки + print("Categories table already contains data ($categoriesCount categories). Skipping initial category insertion."); + } + + // Проверяем, есть ли уже транзакции (аналогично, не должно быть в onCreate) + final countResult = await (selectOnly(transactions)..addColumns([transactions.id.count()])).getSingleOrNull(); + final transactionCount = countResult?.read(transactions.id.count()) ?? 0; + + // Вставляем данные только если таблица транзакций пуста + if (transactionCount == 0) { + print("Inserting initial transactions..."); + // Используем batch для эффективной вставки нескольких записей + await batch((batch) { + batch.insertAll(transactions, [ + // Используем TransactionsCompanion для создания записей для вставки + // Поле type будет 'expense' по умолчанию из-за .withDefault() в определении колонки + TransactionsCompanion.insert(categoryName: 'Groceries', amount: 45.99, date: DateTime.now().subtract(const Duration(days: 1, hours: 2)), merchant: 'Whole Foods Market'), + TransactionsCompanion.insert(categoryName: 'Subscriptions', amount: 39.99, date: DateTime.now().subtract(const Duration(days: 2, hours: 5)), merchant: 'Netflix Premium'), + TransactionsCompanion.insert(categoryName: 'Restaurant', amount: 78.50, date: DateTime.now().subtract(const Duration(days: 2, hours: 19)), merchant: 'Italian Corner'), + TransactionsCompanion.insert(categoryName: 'Shopping', amount: 132.75, date: DateTime.now().subtract(const Duration(days: 3, hours: 11)), merchant: 'Apple Store'), + TransactionsCompanion.insert(categoryName: 'Groceries', amount: 23.45, date: DateTime.now().subtract(const Duration(days: 4, hours: 9)), merchant: 'Local Market'), + TransactionsCompanion.insert(categoryName: 'Transport', amount: 15.00, date: DateTime.now().subtract(const Duration(days: 5, hours: 8)), merchant: 'City Bus'), + TransactionsCompanion.insert(categoryName: 'Restaurant', amount: 56.80, date: DateTime.now().subtract(const Duration(days: 5, hours: 20)), merchant: 'Sushi Express'), + TransactionsCompanion.insert(categoryName: 'Utilities', amount: 85.20, date: DateTime.now().subtract(const Duration(days: 6, hours: 10)), merchant: 'Electricity Bill'), // Example: Added Utilities transaction + // Пример дохода - здесь нужно явно указать type: 'income' + TransactionsCompanion.insert(categoryName: 'Income', amount: 1200.00, date: DateTime.now().subtract(const Duration(days: 7, hours: 9)), merchant: 'Salary', type: Value('income')), + ]); + }); + print("Initial transactions inserted successfully."); + } else { + // Эта ветка не должна выполняться при вызове из onCreate + print("Transactions table already contains data ($transactionCount transactions). Skipping initial transaction insertion."); + } + } +} diff --git a/lib/database/database.g.dart b/lib/database/database.g.dart new file mode 100644 index 0000000..223db59 --- /dev/null +++ b/lib/database/database.g.dart @@ -0,0 +1,1130 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'database.dart'; + +// ignore_for_file: type=lint +class $CategoriesTable extends Categories + with TableInfo<$CategoriesTable, CategoryDb> { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + $CategoriesTable(this.attachedDatabase, [this._alias]); + static const VerificationMeta _idMeta = const VerificationMeta('id'); + @override + late final GeneratedColumn id = GeneratedColumn( + 'id', + aliasedName, + false, + hasAutoIncrement: true, + type: DriftSqlType.int, + requiredDuringInsert: false, + defaultConstraints: GeneratedColumn.constraintIsAlways( + 'PRIMARY KEY AUTOINCREMENT', + ), + ); + static const VerificationMeta _nameMeta = const VerificationMeta('name'); + @override + late final GeneratedColumn name = GeneratedColumn( + 'name', + aliasedName, + false, + type: DriftSqlType.string, + requiredDuringInsert: true, + defaultConstraints: GeneratedColumn.constraintIsAlways('UNIQUE'), + ); + static const VerificationMeta _iconMeta = const VerificationMeta('icon'); + @override + late final GeneratedColumn icon = GeneratedColumn( + 'icon', + aliasedName, + false, + type: DriftSqlType.string, + requiredDuringInsert: true, + ); + static const VerificationMeta _colorMeta = const VerificationMeta('color'); + @override + late final GeneratedColumn color = GeneratedColumn( + 'color', + aliasedName, + false, + type: DriftSqlType.int, + requiredDuringInsert: true, + ); + @override + List get $columns => [id, name, icon, color]; + @override + String get aliasedName => _alias ?? actualTableName; + @override + String get actualTableName => $name; + static const String $name = 'categories'; + @override + VerificationContext validateIntegrity( + Insertable instance, { + bool isInserting = false, + }) { + final context = VerificationContext(); + final data = instance.toColumns(true); + if (data.containsKey('id')) { + context.handle(_idMeta, id.isAcceptableOrUnknown(data['id']!, _idMeta)); + } + if (data.containsKey('name')) { + context.handle( + _nameMeta, + name.isAcceptableOrUnknown(data['name']!, _nameMeta), + ); + } else if (isInserting) { + context.missing(_nameMeta); + } + if (data.containsKey('icon')) { + context.handle( + _iconMeta, + icon.isAcceptableOrUnknown(data['icon']!, _iconMeta), + ); + } else if (isInserting) { + context.missing(_iconMeta); + } + if (data.containsKey('color')) { + context.handle( + _colorMeta, + color.isAcceptableOrUnknown(data['color']!, _colorMeta), + ); + } else if (isInserting) { + context.missing(_colorMeta); + } + return context; + } + + @override + Set get $primaryKey => {id}; + @override + CategoryDb map(Map data, {String? tablePrefix}) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return CategoryDb( + id: + attachedDatabase.typeMapping.read( + DriftSqlType.int, + data['${effectivePrefix}id'], + )!, + name: + attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}name'], + )!, + icon: + attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}icon'], + )!, + color: + attachedDatabase.typeMapping.read( + DriftSqlType.int, + data['${effectivePrefix}color'], + )!, + ); + } + + @override + $CategoriesTable createAlias(String alias) { + return $CategoriesTable(attachedDatabase, alias); + } +} + +class CategoryDb extends DataClass implements Insertable { + final int id; + final String name; + final String icon; + final int color; + const CategoryDb({ + required this.id, + required this.name, + required this.icon, + required this.color, + }); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['id'] = Variable(id); + map['name'] = Variable(name); + map['icon'] = Variable(icon); + map['color'] = Variable(color); + return map; + } + + CategoriesCompanion toCompanion(bool nullToAbsent) { + return CategoriesCompanion( + id: Value(id), + name: Value(name), + icon: Value(icon), + color: Value(color), + ); + } + + factory CategoryDb.fromJson( + Map json, { + ValueSerializer? serializer, + }) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return CategoryDb( + id: serializer.fromJson(json['id']), + name: serializer.fromJson(json['name']), + icon: serializer.fromJson(json['icon']), + color: serializer.fromJson(json['color']), + ); + } + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'id': serializer.toJson(id), + 'name': serializer.toJson(name), + 'icon': serializer.toJson(icon), + 'color': serializer.toJson(color), + }; + } + + CategoryDb copyWith({int? id, String? name, String? icon, int? color}) => + CategoryDb( + id: id ?? this.id, + name: name ?? this.name, + icon: icon ?? this.icon, + color: color ?? this.color, + ); + CategoryDb copyWithCompanion(CategoriesCompanion data) { + return CategoryDb( + id: data.id.present ? data.id.value : this.id, + name: data.name.present ? data.name.value : this.name, + icon: data.icon.present ? data.icon.value : this.icon, + color: data.color.present ? data.color.value : this.color, + ); + } + + @override + String toString() { + return (StringBuffer('CategoryDb(') + ..write('id: $id, ') + ..write('name: $name, ') + ..write('icon: $icon, ') + ..write('color: $color') + ..write(')')) + .toString(); + } + + @override + int get hashCode => Object.hash(id, name, icon, color); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is CategoryDb && + other.id == this.id && + other.name == this.name && + other.icon == this.icon && + other.color == this.color); +} + +class CategoriesCompanion extends UpdateCompanion { + final Value id; + final Value name; + final Value icon; + final Value color; + const CategoriesCompanion({ + this.id = const Value.absent(), + this.name = const Value.absent(), + this.icon = const Value.absent(), + this.color = const Value.absent(), + }); + CategoriesCompanion.insert({ + this.id = const Value.absent(), + required String name, + required String icon, + required int color, + }) : name = Value(name), + icon = Value(icon), + color = Value(color); + static Insertable custom({ + Expression? id, + Expression? name, + Expression? icon, + Expression? color, + }) { + return RawValuesInsertable({ + if (id != null) 'id': id, + if (name != null) 'name': name, + if (icon != null) 'icon': icon, + if (color != null) 'color': color, + }); + } + + CategoriesCompanion copyWith({ + Value? id, + Value? name, + Value? icon, + Value? color, + }) { + return CategoriesCompanion( + id: id ?? this.id, + name: name ?? this.name, + icon: icon ?? this.icon, + color: color ?? this.color, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (id.present) { + map['id'] = Variable(id.value); + } + if (name.present) { + map['name'] = Variable(name.value); + } + if (icon.present) { + map['icon'] = Variable(icon.value); + } + if (color.present) { + map['color'] = Variable(color.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('CategoriesCompanion(') + ..write('id: $id, ') + ..write('name: $name, ') + ..write('icon: $icon, ') + ..write('color: $color') + ..write(')')) + .toString(); + } +} + +class $TransactionsTable extends Transactions + with TableInfo<$TransactionsTable, Transaction> { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + $TransactionsTable(this.attachedDatabase, [this._alias]); + static const VerificationMeta _idMeta = const VerificationMeta('id'); + @override + late final GeneratedColumn id = GeneratedColumn( + 'id', + aliasedName, + false, + hasAutoIncrement: true, + type: DriftSqlType.int, + requiredDuringInsert: false, + defaultConstraints: GeneratedColumn.constraintIsAlways( + 'PRIMARY KEY AUTOINCREMENT', + ), + ); + static const VerificationMeta _categoryNameMeta = const VerificationMeta( + 'categoryName', + ); + @override + late final GeneratedColumn categoryName = GeneratedColumn( + 'category_name', + aliasedName, + false, + type: DriftSqlType.string, + requiredDuringInsert: true, + ); + static const VerificationMeta _amountMeta = const VerificationMeta('amount'); + @override + late final GeneratedColumn amount = GeneratedColumn( + 'amount', + aliasedName, + false, + type: DriftSqlType.double, + requiredDuringInsert: true, + ); + static const VerificationMeta _dateMeta = const VerificationMeta('date'); + @override + late final GeneratedColumn date = GeneratedColumn( + 'date', + aliasedName, + false, + type: DriftSqlType.dateTime, + requiredDuringInsert: true, + ); + static const VerificationMeta _merchantMeta = const VerificationMeta( + 'merchant', + ); + @override + late final GeneratedColumn merchant = GeneratedColumn( + 'merchant', + aliasedName, + false, + type: DriftSqlType.string, + requiredDuringInsert: true, + ); + static const VerificationMeta _typeMeta = const VerificationMeta('type'); + @override + late final GeneratedColumn type = GeneratedColumn( + 'type', + aliasedName, + false, + type: DriftSqlType.string, + requiredDuringInsert: false, + defaultValue: const Constant('expense'), + ); + @override + List get $columns => [ + id, + categoryName, + amount, + date, + merchant, + type, + ]; + @override + String get aliasedName => _alias ?? actualTableName; + @override + String get actualTableName => $name; + static const String $name = 'transactions'; + @override + VerificationContext validateIntegrity( + Insertable instance, { + bool isInserting = false, + }) { + final context = VerificationContext(); + final data = instance.toColumns(true); + if (data.containsKey('id')) { + context.handle(_idMeta, id.isAcceptableOrUnknown(data['id']!, _idMeta)); + } + if (data.containsKey('category_name')) { + context.handle( + _categoryNameMeta, + categoryName.isAcceptableOrUnknown( + data['category_name']!, + _categoryNameMeta, + ), + ); + } else if (isInserting) { + context.missing(_categoryNameMeta); + } + if (data.containsKey('amount')) { + context.handle( + _amountMeta, + amount.isAcceptableOrUnknown(data['amount']!, _amountMeta), + ); + } else if (isInserting) { + context.missing(_amountMeta); + } + if (data.containsKey('date')) { + context.handle( + _dateMeta, + date.isAcceptableOrUnknown(data['date']!, _dateMeta), + ); + } else if (isInserting) { + context.missing(_dateMeta); + } + if (data.containsKey('merchant')) { + context.handle( + _merchantMeta, + merchant.isAcceptableOrUnknown(data['merchant']!, _merchantMeta), + ); + } else if (isInserting) { + context.missing(_merchantMeta); + } + if (data.containsKey('type')) { + context.handle( + _typeMeta, + type.isAcceptableOrUnknown(data['type']!, _typeMeta), + ); + } + return context; + } + + @override + Set get $primaryKey => {id}; + @override + Transaction map(Map data, {String? tablePrefix}) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return Transaction( + id: + attachedDatabase.typeMapping.read( + DriftSqlType.int, + data['${effectivePrefix}id'], + )!, + categoryName: + attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}category_name'], + )!, + amount: + attachedDatabase.typeMapping.read( + DriftSqlType.double, + data['${effectivePrefix}amount'], + )!, + date: + attachedDatabase.typeMapping.read( + DriftSqlType.dateTime, + data['${effectivePrefix}date'], + )!, + merchant: + attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}merchant'], + )!, + type: + attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}type'], + )!, + ); + } + + @override + $TransactionsTable createAlias(String alias) { + return $TransactionsTable(attachedDatabase, alias); + } +} + +class Transaction extends DataClass implements Insertable { + final int id; + final String categoryName; + final double amount; + final DateTime date; + final String merchant; + final String type; + const Transaction({ + required this.id, + required this.categoryName, + required this.amount, + required this.date, + required this.merchant, + required this.type, + }); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['id'] = Variable(id); + map['category_name'] = Variable(categoryName); + map['amount'] = Variable(amount); + map['date'] = Variable(date); + map['merchant'] = Variable(merchant); + map['type'] = Variable(type); + return map; + } + + TransactionsCompanion toCompanion(bool nullToAbsent) { + return TransactionsCompanion( + id: Value(id), + categoryName: Value(categoryName), + amount: Value(amount), + date: Value(date), + merchant: Value(merchant), + type: Value(type), + ); + } + + factory Transaction.fromJson( + Map json, { + ValueSerializer? serializer, + }) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return Transaction( + id: serializer.fromJson(json['id']), + categoryName: serializer.fromJson(json['categoryName']), + amount: serializer.fromJson(json['amount']), + date: serializer.fromJson(json['date']), + merchant: serializer.fromJson(json['merchant']), + type: serializer.fromJson(json['type']), + ); + } + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'id': serializer.toJson(id), + 'categoryName': serializer.toJson(categoryName), + 'amount': serializer.toJson(amount), + 'date': serializer.toJson(date), + 'merchant': serializer.toJson(merchant), + 'type': serializer.toJson(type), + }; + } + + Transaction copyWith({ + int? id, + String? categoryName, + double? amount, + DateTime? date, + String? merchant, + String? type, + }) => Transaction( + id: id ?? this.id, + categoryName: categoryName ?? this.categoryName, + amount: amount ?? this.amount, + date: date ?? this.date, + merchant: merchant ?? this.merchant, + type: type ?? this.type, + ); + Transaction copyWithCompanion(TransactionsCompanion data) { + return Transaction( + id: data.id.present ? data.id.value : this.id, + categoryName: + data.categoryName.present + ? data.categoryName.value + : this.categoryName, + amount: data.amount.present ? data.amount.value : this.amount, + date: data.date.present ? data.date.value : this.date, + merchant: data.merchant.present ? data.merchant.value : this.merchant, + type: data.type.present ? data.type.value : this.type, + ); + } + + @override + String toString() { + return (StringBuffer('Transaction(') + ..write('id: $id, ') + ..write('categoryName: $categoryName, ') + ..write('amount: $amount, ') + ..write('date: $date, ') + ..write('merchant: $merchant, ') + ..write('type: $type') + ..write(')')) + .toString(); + } + + @override + int get hashCode => + Object.hash(id, categoryName, amount, date, merchant, type); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is Transaction && + other.id == this.id && + other.categoryName == this.categoryName && + other.amount == this.amount && + other.date == this.date && + other.merchant == this.merchant && + other.type == this.type); +} + +class TransactionsCompanion extends UpdateCompanion { + final Value id; + final Value categoryName; + final Value amount; + final Value date; + final Value merchant; + final Value type; + const TransactionsCompanion({ + this.id = const Value.absent(), + this.categoryName = const Value.absent(), + this.amount = const Value.absent(), + this.date = const Value.absent(), + this.merchant = const Value.absent(), + this.type = const Value.absent(), + }); + TransactionsCompanion.insert({ + this.id = const Value.absent(), + required String categoryName, + required double amount, + required DateTime date, + required String merchant, + this.type = const Value.absent(), + }) : categoryName = Value(categoryName), + amount = Value(amount), + date = Value(date), + merchant = Value(merchant); + static Insertable custom({ + Expression? id, + Expression? categoryName, + Expression? amount, + Expression? date, + Expression? merchant, + Expression? type, + }) { + return RawValuesInsertable({ + if (id != null) 'id': id, + if (categoryName != null) 'category_name': categoryName, + if (amount != null) 'amount': amount, + if (date != null) 'date': date, + if (merchant != null) 'merchant': merchant, + if (type != null) 'type': type, + }); + } + + TransactionsCompanion copyWith({ + Value? id, + Value? categoryName, + Value? amount, + Value? date, + Value? merchant, + Value? type, + }) { + return TransactionsCompanion( + id: id ?? this.id, + categoryName: categoryName ?? this.categoryName, + amount: amount ?? this.amount, + date: date ?? this.date, + merchant: merchant ?? this.merchant, + type: type ?? this.type, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (id.present) { + map['id'] = Variable(id.value); + } + if (categoryName.present) { + map['category_name'] = Variable(categoryName.value); + } + if (amount.present) { + map['amount'] = Variable(amount.value); + } + if (date.present) { + map['date'] = Variable(date.value); + } + if (merchant.present) { + map['merchant'] = Variable(merchant.value); + } + if (type.present) { + map['type'] = Variable(type.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('TransactionsCompanion(') + ..write('id: $id, ') + ..write('categoryName: $categoryName, ') + ..write('amount: $amount, ') + ..write('date: $date, ') + ..write('merchant: $merchant, ') + ..write('type: $type') + ..write(')')) + .toString(); + } +} + +abstract class _$AppDatabase extends GeneratedDatabase { + _$AppDatabase(QueryExecutor e) : super(e); + $AppDatabaseManager get managers => $AppDatabaseManager(this); + late final $CategoriesTable categories = $CategoriesTable(this); + late final $TransactionsTable transactions = $TransactionsTable(this); + @override + Iterable> get allTables => + allSchemaEntities.whereType>(); + @override + List get allSchemaEntities => [ + categories, + transactions, + ]; +} + +typedef $$CategoriesTableCreateCompanionBuilder = + CategoriesCompanion Function({ + Value id, + required String name, + required String icon, + required int color, + }); +typedef $$CategoriesTableUpdateCompanionBuilder = + CategoriesCompanion Function({ + Value id, + Value name, + Value icon, + Value color, + }); + +class $$CategoriesTableFilterComposer + extends Composer<_$AppDatabase, $CategoriesTable> { + $$CategoriesTableFilterComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + ColumnFilters get id => $composableBuilder( + column: $table.id, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get name => $composableBuilder( + column: $table.name, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get icon => $composableBuilder( + column: $table.icon, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get color => $composableBuilder( + column: $table.color, + builder: (column) => ColumnFilters(column), + ); +} + +class $$CategoriesTableOrderingComposer + extends Composer<_$AppDatabase, $CategoriesTable> { + $$CategoriesTableOrderingComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + ColumnOrderings get id => $composableBuilder( + column: $table.id, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get name => $composableBuilder( + column: $table.name, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get icon => $composableBuilder( + column: $table.icon, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get color => $composableBuilder( + column: $table.color, + builder: (column) => ColumnOrderings(column), + ); +} + +class $$CategoriesTableAnnotationComposer + extends Composer<_$AppDatabase, $CategoriesTable> { + $$CategoriesTableAnnotationComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + GeneratedColumn get id => + $composableBuilder(column: $table.id, builder: (column) => column); + + GeneratedColumn get name => + $composableBuilder(column: $table.name, builder: (column) => column); + + GeneratedColumn get icon => + $composableBuilder(column: $table.icon, builder: (column) => column); + + GeneratedColumn get color => + $composableBuilder(column: $table.color, builder: (column) => column); +} + +class $$CategoriesTableTableManager + extends + RootTableManager< + _$AppDatabase, + $CategoriesTable, + CategoryDb, + $$CategoriesTableFilterComposer, + $$CategoriesTableOrderingComposer, + $$CategoriesTableAnnotationComposer, + $$CategoriesTableCreateCompanionBuilder, + $$CategoriesTableUpdateCompanionBuilder, + ( + CategoryDb, + BaseReferences<_$AppDatabase, $CategoriesTable, CategoryDb>, + ), + CategoryDb, + PrefetchHooks Function() + > { + $$CategoriesTableTableManager(_$AppDatabase db, $CategoriesTable table) + : super( + TableManagerState( + db: db, + table: table, + createFilteringComposer: + () => $$CategoriesTableFilterComposer($db: db, $table: table), + createOrderingComposer: + () => $$CategoriesTableOrderingComposer($db: db, $table: table), + createComputedFieldComposer: + () => $$CategoriesTableAnnotationComposer($db: db, $table: table), + updateCompanionCallback: + ({ + Value id = const Value.absent(), + Value name = const Value.absent(), + Value icon = const Value.absent(), + Value color = const Value.absent(), + }) => CategoriesCompanion( + id: id, + name: name, + icon: icon, + color: color, + ), + createCompanionCallback: + ({ + Value id = const Value.absent(), + required String name, + required String icon, + required int color, + }) => CategoriesCompanion.insert( + id: id, + name: name, + icon: icon, + color: color, + ), + withReferenceMapper: + (p0) => + p0 + .map( + (e) => ( + e.readTable(table), + BaseReferences(db, table, e), + ), + ) + .toList(), + prefetchHooksCallback: null, + ), + ); +} + +typedef $$CategoriesTableProcessedTableManager = + ProcessedTableManager< + _$AppDatabase, + $CategoriesTable, + CategoryDb, + $$CategoriesTableFilterComposer, + $$CategoriesTableOrderingComposer, + $$CategoriesTableAnnotationComposer, + $$CategoriesTableCreateCompanionBuilder, + $$CategoriesTableUpdateCompanionBuilder, + (CategoryDb, BaseReferences<_$AppDatabase, $CategoriesTable, CategoryDb>), + CategoryDb, + PrefetchHooks Function() + >; +typedef $$TransactionsTableCreateCompanionBuilder = + TransactionsCompanion Function({ + Value id, + required String categoryName, + required double amount, + required DateTime date, + required String merchant, + Value type, + }); +typedef $$TransactionsTableUpdateCompanionBuilder = + TransactionsCompanion Function({ + Value id, + Value categoryName, + Value amount, + Value date, + Value merchant, + Value type, + }); + +class $$TransactionsTableFilterComposer + extends Composer<_$AppDatabase, $TransactionsTable> { + $$TransactionsTableFilterComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + ColumnFilters get id => $composableBuilder( + column: $table.id, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get categoryName => $composableBuilder( + column: $table.categoryName, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get amount => $composableBuilder( + column: $table.amount, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get date => $composableBuilder( + column: $table.date, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get merchant => $composableBuilder( + column: $table.merchant, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get type => $composableBuilder( + column: $table.type, + builder: (column) => ColumnFilters(column), + ); +} + +class $$TransactionsTableOrderingComposer + extends Composer<_$AppDatabase, $TransactionsTable> { + $$TransactionsTableOrderingComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + ColumnOrderings get id => $composableBuilder( + column: $table.id, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get categoryName => $composableBuilder( + column: $table.categoryName, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get amount => $composableBuilder( + column: $table.amount, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get date => $composableBuilder( + column: $table.date, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get merchant => $composableBuilder( + column: $table.merchant, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get type => $composableBuilder( + column: $table.type, + builder: (column) => ColumnOrderings(column), + ); +} + +class $$TransactionsTableAnnotationComposer + extends Composer<_$AppDatabase, $TransactionsTable> { + $$TransactionsTableAnnotationComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + GeneratedColumn get id => + $composableBuilder(column: $table.id, builder: (column) => column); + + GeneratedColumn get categoryName => $composableBuilder( + column: $table.categoryName, + builder: (column) => column, + ); + + GeneratedColumn get amount => + $composableBuilder(column: $table.amount, builder: (column) => column); + + GeneratedColumn get date => + $composableBuilder(column: $table.date, builder: (column) => column); + + GeneratedColumn get merchant => + $composableBuilder(column: $table.merchant, builder: (column) => column); + + GeneratedColumn get type => + $composableBuilder(column: $table.type, builder: (column) => column); +} + +class $$TransactionsTableTableManager + extends + RootTableManager< + _$AppDatabase, + $TransactionsTable, + Transaction, + $$TransactionsTableFilterComposer, + $$TransactionsTableOrderingComposer, + $$TransactionsTableAnnotationComposer, + $$TransactionsTableCreateCompanionBuilder, + $$TransactionsTableUpdateCompanionBuilder, + ( + Transaction, + BaseReferences<_$AppDatabase, $TransactionsTable, Transaction>, + ), + Transaction, + PrefetchHooks Function() + > { + $$TransactionsTableTableManager(_$AppDatabase db, $TransactionsTable table) + : super( + TableManagerState( + db: db, + table: table, + createFilteringComposer: + () => $$TransactionsTableFilterComposer($db: db, $table: table), + createOrderingComposer: + () => $$TransactionsTableOrderingComposer($db: db, $table: table), + createComputedFieldComposer: + () => + $$TransactionsTableAnnotationComposer($db: db, $table: table), + updateCompanionCallback: + ({ + Value id = const Value.absent(), + Value categoryName = const Value.absent(), + Value amount = const Value.absent(), + Value date = const Value.absent(), + Value merchant = const Value.absent(), + Value type = const Value.absent(), + }) => TransactionsCompanion( + id: id, + categoryName: categoryName, + amount: amount, + date: date, + merchant: merchant, + type: type, + ), + createCompanionCallback: + ({ + Value id = const Value.absent(), + required String categoryName, + required double amount, + required DateTime date, + required String merchant, + Value type = const Value.absent(), + }) => TransactionsCompanion.insert( + id: id, + categoryName: categoryName, + amount: amount, + date: date, + merchant: merchant, + type: type, + ), + withReferenceMapper: + (p0) => + p0 + .map( + (e) => ( + e.readTable(table), + BaseReferences(db, table, e), + ), + ) + .toList(), + prefetchHooksCallback: null, + ), + ); +} + +typedef $$TransactionsTableProcessedTableManager = + ProcessedTableManager< + _$AppDatabase, + $TransactionsTable, + Transaction, + $$TransactionsTableFilterComposer, + $$TransactionsTableOrderingComposer, + $$TransactionsTableAnnotationComposer, + $$TransactionsTableCreateCompanionBuilder, + $$TransactionsTableUpdateCompanionBuilder, + ( + Transaction, + BaseReferences<_$AppDatabase, $TransactionsTable, Transaction>, + ), + Transaction, + PrefetchHooks Function() + >; + +class $AppDatabaseManager { + final _$AppDatabase _db; + $AppDatabaseManager(this._db); + $$CategoriesTableTableManager get categories => + $$CategoriesTableTableManager(_db, _db.categories); + $$TransactionsTableTableManager get transactions => + $$TransactionsTableTableManager(_db, _db.transactions); +} diff --git a/lib/database/database_connection/connection.dart b/lib/database/database_connection/connection.dart new file mode 100644 index 0000000..ace0070 --- /dev/null +++ b/lib/database/database_connection/connection.dart @@ -0,0 +1,12 @@ +// lib/database/database_connection/connection.dart +import 'package:drift/drift.dart'; + +// Этот файл служит базой для условного импорта. +// Реализации находятся в connection_web.dart и connection_native.dart. + +// Определим функцию-заглушку, чтобы основной файл database.dart +// мог ее импортировать без ошибок анализатора. +// Во время выполнения будет вызвана реализация из соответствующего +// файла (web или native) благодаря условному импорту. +QueryExecutor connect() => throw UnsupportedError( + 'Stub connect function should not be called. Ensure conditional imports are set up correctly.'); diff --git a/lib/database/database_connection/connection_native.dart b/lib/database/database_connection/connection_native.dart new file mode 100644 index 0000000..ebab0da --- /dev/null +++ b/lib/database/database_connection/connection_native.dart @@ -0,0 +1,33 @@ +// lib/database/database_connection/connection_native.dart +import 'dart:io'; + +import 'package:drift/drift.dart'; +import 'package:drift/native.dart'; +import 'package:path_provider/path_provider.dart'; +import 'package:path/path.dart' as p; +// sqlite3_flutter_libs и sqlite3 импортируются для возможной тонкой настройки, +// но часто NativeDatabase справляется автоматически. +// import 'package:sqlite3_flutter_libs/sqlite3_flutter_libs.dart'; +// import 'package:sqlite3/sqlite3.dart'; + +QueryExecutor connect() { + print("Connecting to database using NativeDatabase (Lazy)"); + // Используем LazyDatabase для отложенной инициализации на нативных платформах + return LazyDatabase(() async { + // Получаем папку для хранения документов приложения + final dbFolder = await getApplicationDocumentsDirectory(); + // Создаем путь к файлу 'db.sqlite' в этой папке + final file = File(p.join(dbFolder.path, 'db.sqlite')); + print("Database file path (Native): ${file.path}"); // Логируем путь для отладки + + // Настройка библиотеки sqlite3 (обычно не требуется для Android/iOS/macOS с sqlite3_flutter_libs) + // if (Platform.isWindows || Platform.isLinux) { + // // Может потребоваться дополнительная настройка для Desktop + // // await applyWorkaroundToOpenSqlite3Library(); + // } + + // Используем NativeDatabase для открытия соединения + // logStatements: true полезен для отладки SQL-запросов + return NativeDatabase(file, logStatements: false); + }); +} diff --git a/lib/database/database_connection/connection_web.dart b/lib/database/database_connection/connection_web.dart new file mode 100644 index 0000000..bbd2954 --- /dev/null +++ b/lib/database/database_connection/connection_web.dart @@ -0,0 +1,15 @@ +// lib/database/database_connection/connection_web.dart +import 'package:drift/drift.dart'; +import 'package:drift/web.dart'; +// import 'package:drift/wasm.dart'; // <-- Удалить этот импорт, он больше не нужен здесь + +QueryExecutor connect() { + print("Connecting to database using WebDatabase (default configuration)"); + + // Используем стандартный конструктор WebDatabase. + // Drift попытается автоматически найти и загрузить sqlite3.wasm по пути /sqlite3.wasm + return WebDatabase( + 'db', // Имя базы данных в IndexedDB + logStatements: false, + ); +} diff --git a/lib/main.dart b/lib/main.dart new file mode 100644 index 0000000..ac38456 --- /dev/null +++ b/lib/main.dart @@ -0,0 +1,46 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/foundation.dart'; // Для kIsWeb +// import 'package:drift/wasm.dart'; // <-- Удалить этот импорт +import 'app.dart'; // Import the new app root widget +import 'database/database.dart'; // Import the database + +Future main() async { + // Необходимо для асинхронных операций перед runApp, например, инициализации БД + WidgetsFlutterBinding.ensureInitialized(); + + // --- Удалить весь этот блок --- + // // Инициализация WASM-модуля SQLite для веб-платформы + // if (kIsWeb) { + // print("Running on Web, attempting to initialize sqlite3.wasm..."); + // // Указываем Drift, где найти файл sqlite3.wasm. + // // WasmDatabase.resolveFile попытается найти его автоматически (обычно в корне /sqlite3.wasm). + // final result = await WasmDatabase.resolveFile('sqlite3.wasm'); // <-- Ошибка здесь + // + // if (result.isSuccessful) { + // print("sqlite3.wasm loaded successfully."); + // } else { + // // Если файл не найден или произошла ошибка загрузки + // print("Error loading sqlite3.wasm: ${result.errorMessage}"); + // // Здесь можно предпринять действия, если загрузка не удалась, + // // например, показать сообщение об ошибке пользователю или использовать + // // альтернативное хранилище. Пока просто выводим ошибку в консоль. + // // Приложение может не работать корректно без базы данных. + // } + // } else { + // print("Running on Native platform, skipping WASM initialization."); + // } + // --- Конец удаляемого блока --- + + + // Создаем единственный экземпляр базы данных для всего приложения + // WebDatabase (вызываемый через connect() на вебе) должен сам справиться с WASM + final database = AppDatabase(); + + // Опционально: Вставляем начальные данные, если база данных пуста + // Это полезно для первого запуска или демонстрации + // Делаем это после создания экземпляра БД + await database.insertInitialDataIfNeeded(); + + // Запускаем приложение, передавая экземпляр базы данных + runApp(MyApp(database: database)); +} diff --git a/lib/models/category.dart b/lib/models/category.dart new file mode 100644 index 0000000..ffd9465 --- /dev/null +++ b/lib/models/category.dart @@ -0,0 +1,10 @@ +import 'package:flutter/material.dart'; + +class Category { + final String name; + final double amount; + final Color colorCode; + final IconData iconCode; + + Category(this.name, this.amount, this.colorCode, this.iconCode); +} diff --git a/lib/models/transaction_record.dart b/lib/models/transaction_record.dart new file mode 100644 index 0000000..dd6b15f --- /dev/null +++ b/lib/models/transaction_record.dart @@ -0,0 +1,23 @@ +import 'package:flutter/material.dart'; +import 'category.dart'; + +class TransactionRecord { + final int id; + final String type; // 'income' or 'expense' + final double amount; + final Category? category; // Reference to category (null for income) + final DateTime date; + final String merchant; + + TransactionRecord({ + required this.id, + required this.type, + required this.amount, + this.category, + required this.date, + required this.merchant, + }); + + // Removed the hardcoded id getter + // get id => 1; +} diff --git a/lib/screens/expenses_screen.dart b/lib/screens/expenses_screen.dart new file mode 100644 index 0000000..c787ab2 --- /dev/null +++ b/lib/screens/expenses_screen.dart @@ -0,0 +1,1237 @@ +import 'package:drift/drift.dart' show Value; // Only import Value for optional fields +import 'package:flutter/material.dart'; +import 'package:fl_chart/fl_chart.dart'; // Used indirectly by SpendingPieChart +import 'package:intl/intl.dart'; // For date formatting +import 'dart:async'; +import 'package:async/async.dart'; // Import StreamZip + +// Removed import 'dart:math'; // No longer needed for random data + +import '../database/database.dart' as db; // Import database with prefix 'db' +import '../models/category.dart'; // Keep Category model for UI structure (SpendingPieChart) +// Import TransactionRecord with a different alias to avoid conflict with db.Transaction +import '../models/transaction_record.dart' as model; // Assuming this model will have a 'type' field +import '../widgets/summary_item.dart'; +import '../widgets/expandable_section.dart'; +import '../widgets/spending_pie_chart.dart'; +import '../widgets/transaction_list_item.dart'; +import '../widgets/filter_chip_widget.dart'; +import '../utils/category_utils.dart'; // Import category utils +import 'profile_screen.dart'; // Import profile screen +import 'settings_menu_screen.dart'; // Import the new settings menu screen +import '../widgets/add_category_dialog.dart'; // Import the new dialog +import '../widgets/edit_transaction_dialog.dart'; // Import the new edit dialog + +// Enum for transaction type selection in the form +enum TransactionType { expense, income } + +class ExpensesScreen extends StatefulWidget { + final Function toggleTheme; + final bool isDarkMode; + final db.AppDatabase database; // Accept database instance + + const ExpensesScreen({ + Key? key, + required this.toggleTheme, + required this.isDarkMode, + required this.database, // Require database instance + }) : super(key: key); + + @override + State createState() => _ExpensesScreenState(); +} + +class _ExpensesScreenState extends State with TickerProviderStateMixin { + // Animation controllers for UI elements + late AnimationController _pieChartAnimationController; + late Animation _pieChartAnimation; + late AnimationController _pieChartExpandController; + late Animation _pieChartHeightFactor; + + // State variables + int _selectedNavIndex = 0; // Index for bottom navigation bar + bool _isPieChartExpanded = true; // Controls visibility of the pie chart section + bool _isFilterVisible = false; // Controls visibility of the filter chips + String _selectedFilter = 'All'; // Currently selected transaction filter + late Stream> _transactionsStream; // Stream for transactions + late Stream _totalIncomeStream; // Stream for total income + late Stream _totalExpensesStream; // Stream for total expenses + late Stream> _categoriesStream; // Stream for categories from DB + + @override + void initState() { + super.initState(); + + // Initialize animation controller for pie chart fade/scale effect + _pieChartAnimationController = AnimationController( + vsync: this, + duration: const Duration(milliseconds: 800), + ); + _pieChartAnimation = CurvedAnimation( + parent: _pieChartAnimationController, + curve: Curves.easeInOut, + ); + + // Initialize animation controller for pie chart expand/collapse effect + _pieChartExpandController = AnimationController( + vsync: this, + duration: const Duration(milliseconds: 300), + value: 1.0, // Start expanded + ); + _pieChartHeightFactor = CurvedAnimation( + parent: _pieChartExpandController, + curve: Curves.easeInOut, + ); + + // Initialize the streams + _transactionsStream = widget.database.watchFilteredTransactions(_selectedFilter); + _totalIncomeStream = widget.database.watchTotalIncome(); + _totalExpensesStream = widget.database.watchTotalExpenses(); // Use direct expense stream + _categoriesStream = widget.database.watchAllCategoriesDb(); // Watch categories from DB + + // Start the pie chart appearance animation + _pieChartAnimationController.forward(); + } + + @override + void dispose() { + // Dispose controllers to free up resources + _pieChartAnimationController.dispose(); + _pieChartExpandController.dispose(); + super.dispose(); + } + + // Stream that provides category totals calculated from transactions (EXPENSES ONLY) + Stream> _watchCategoryTotals() { + // This stream is provided by Drift and updates automatically. + // It's already configured in database.dart to only calculate expenses. + return widget.database.calculateCategoryTotals(); + } + + // Toggles the visibility of the pie chart section with animation + void _togglePieChartVisibility() { + setState(() { + _isPieChartExpanded = !_isPieChartExpanded; + if (_isPieChartExpanded) { + _pieChartExpandController.forward(); // Expand animation + } else { + _pieChartExpandController.reverse(); // Collapse animation + } + }); + } + + // Toggles the visibility of the filter chip row + void _toggleFilterVisibility() { + setState(() { + _isFilterVisible = !_isFilterVisible; + }); + } + + // Applies the selected filter to the transaction list + void _applyFilter(String filter) { + // Only call setState if the filter actually changes + if (_selectedFilter != filter) { + setState(() { + _selectedFilter = filter; + // Update the stream instance when the filter changes + // watchFilteredTransactions handles 'All' vs specific expense category + _transactionsStream = widget.database.watchFilteredTransactions(_selectedFilter); + }); + } + } + + // --- Function to show the modal bottom sheet for adding a transaction --- + void _showAddTransactionSheet() { + showModalBottomSheet( + context: context, + isScrollControlled: true, // Allows the sheet to take up more height + shape: const RoundedRectangleBorder( // Rounded corners + borderRadius: BorderRadius.vertical(top: Radius.circular(20)), + ), + builder: (context) { + // Pass the database instance and the categories stream to the form widget + return Padding( + // Add padding to account for the keyboard + padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom), + child: _AddTransactionForm( + database: widget.database, + categoriesStream: _categoriesStream, // Pass the stream here + ), + ); + }, + ); + } + // --- End of show add transaction sheet function --- + + // --- Function to handle Bottom Navigation Bar taps --- + void _onItemTapped(int index) { + setState(() { + _selectedNavIndex = index; + }); + // Handle navigation based on index + switch (index) { + case 0: + // Stay on Expenses Screen (Home) + break; + case 1: + // TODO: Navigate to Reports Screen + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Reports Screen not implemented yet.'), + duration: Duration(seconds: 1), + behavior: SnackBarBehavior.floating, + ), + ); + break; + case 2: + // Navigate to Settings Menu Screen + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => SettingsMenuScreen(database: widget.database), // Navigate to the new menu screen + ), + ); + break; + } + } + // --- End of Bottom Navigation Bar taps function --- + + // --- Function to show the edit transaction dialog --- + void _showEditTransactionDialog(db.Transaction transaction) async { + final updatedTransaction = await showDialog( + context: context, + builder: (context) => EditTransactionDialog( + database: widget.database, + transaction: transaction, + categoriesStream: _categoriesStream, // Pass categories stream + ), + ); + + if (updatedTransaction != null) { + // Transaction was updated, database stream will automatically refresh the list + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Транзакция обновлена.'), + duration: Duration(seconds: 2), + behavior: SnackBarBehavior.floating, + ), + ); + } + } + } + // --- End of show edit transaction dialog function --- + + // --- Function to handle transaction deletion --- + void _deleteTransaction(int transactionId) async { + // Show a confirmation dialog before deleting + final bool confirmDelete = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Подтверждение удаления'), + content: const Text('Вы уверены, что хотите удалить эту транзакцию?'), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(false), // Cancel + child: const Text('Отмена'), + ), + TextButton( + onPressed: () => Navigator.of(context).pop(true), // Confirm + child: const Text('Удалить'), + style: TextButton.styleFrom(foregroundColor: Colors.red), + ), + ], + ), + ) ?? false; // Default to false if dialog is dismissed + + if (confirmDelete) { + try { + final deletedCount = await widget.database.deleteTransaction(transactionId); + if (deletedCount > 0) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Транзакция удалена.'), + duration: Duration(seconds: 2), + behavior: SnackBarBehavior.floating, + ), + ); + } + } else { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Не удалось удалить транзакцию.'), + backgroundColor: Colors.red, + duration: Duration(seconds: 2), + behavior: SnackBarBehavior.floating, + ), + ); + } + } + } catch (e) { + print('Error deleting transaction: $e'); + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Ошибка при удалении транзакции: $e'), + backgroundColor: Colors.red, + duration: Duration(seconds: 3), + behavior: SnackBarBehavior.floating, + ), + ); + } + } + } + } + // --- End of handle transaction deletion function --- + + + @override + Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + final theme = Theme.of(context); // Get theme for easier access to styles + + return Scaffold( + appBar: AppBar( + // Title with icon + title: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.account_balance_wallet_outlined, // Updated icon + color: isDark ? Colors.greenAccent.shade100 : Colors.green.shade800, + size: 24, + ), + const SizedBox(width: 8), + const Text('My Finances'), // Updated title + ], + ), + centerTitle: true, + // Theme toggle button + leading: IconButton( + tooltip: isDark ? 'Switch to Light Mode' : 'Switch to Dark Mode', + icon: Icon( + widget.isDarkMode ? Icons.wb_sunny_outlined : Icons.nightlight_round, + color: widget.isDarkMode ? Colors.yellow.shade300 : Colors.blue.shade700, + ), + onPressed: () => widget.toggleTheme(), + ), + // Profile avatar button + actions: [ + Padding( + padding: const EdgeInsets.only(right: 12.0), // Adjusted padding + child: Hero( + tag: 'profileAvatar', // Tag for Hero animation + child: Material( + type: MaterialType.transparency, // Needed for Hero animation across routes + child: IconButton( + tooltip: 'View Profile', + icon: CircleAvatar( + radius: 18, // Slightly smaller avatar + backgroundColor: isDark ? Colors.green.shade800 : Colors.green.shade100, + child: const Icon(Icons.person_outline, color: Colors.green, size: 20), + ), + onPressed: () { + // Navigate to ProfileScreen with a fade transition + Navigator.push( + context, + PageRouteBuilder( + pageBuilder: (_, __, ___) => const ProfileScreen(), + transitionsBuilder: (_, animation, __, child) { + return FadeTransition(opacity: animation, child: child); + }, + transitionDuration: const Duration(milliseconds: 350), // Adjusted duration + ), + ); + }, + ), + ), + ), + ), + ], + ), + // Use multiple StreamBuilders for different data points (income, expenses, categories) + body: MultiStreamBuilder( + streams: [ + _watchCategoryTotals(), // Stream> for pie chart (expenses only) + _totalIncomeStream, // Stream for total income + _totalExpensesStream, // Stream for total expenses + _categoriesStream, // Stream> for filter chips + ], + builder: (context, snapshots) { + // Check if all streams have data (or handle loading/error states individually) + if (snapshots.any((s) => s.connectionState == ConnectionState.waiting && !s.hasData)) { + return const Center(child: CircularProgressIndicator()); + } + if (snapshots.any((s) => s.hasError)) { + // Find the first error and display it + final errorSnapshot = snapshots.firstWhere((s) => s.hasError); + return Center(child: Text('Error loading data: ${errorSnapshot.error}')); + } + + // Safely extract data with defaults + final expenseCategoriesForPie = snapshots[0].data as List? ?? []; + final totalIncome = snapshots[1].data as double? ?? 0.0; + final totalExpenses = snapshots[2].data as double? ?? 0.0; + final allDbCategories = snapshots[3].data as List? ?? []; + + // Filter out the 'Income' category for display in expense filters/pie chart + final expenseDbCategories = allDbCategories.where((c) => c.name != 'Income').toList(); + + + // Main column layout + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, // Stretch children horizontally + children: [ + Expanded( + // Use SingleChildScrollView for content that might overflow + child: SingleChildScrollView( + physics: const BouncingScrollPhysics(), // iOS-like scroll physics + child: Column( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + // --- Summary Card --- + Padding( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 8), + child: Card( + elevation: 2, // Subtle shadow + child: Padding( + padding: const EdgeInsets.all(16.0), // Adjusted padding + child: Column( + children: [ + Text( + 'Financial Summary', // More general title + style: theme.textTheme.titleMedium, // Use theme style + ), + const SizedBox(height: 8), + // Display Net Balance (Income - Expenses) + Row( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, // Align baseline + children: [ + Text( + 'Net Balance: ', + style: TextStyle( + fontSize: 18, // Smaller label + fontWeight: FontWeight.w500, + color: theme.textTheme.bodySmall?.color, + ), + ), + Text( + '${totalIncome >= totalExpenses ? '+' : '-'} \$', // Sign based on balance + style: TextStyle( + fontSize: 20, // Smaller dollar sign + fontWeight: FontWeight.w500, // Medium weight + color: (totalIncome - totalExpenses) >= 0 ? Colors.green : Colors.red, + ), + ), + Text( + NumberFormat.currency(symbol: '', decimalDigits: 2).format((totalIncome - totalExpenses).abs()), // Format number + style: TextStyle( + fontSize: 36, // Slightly smaller amount + fontWeight: FontWeight.bold, + color: (totalIncome - totalExpenses) >= 0 ? Colors.green : Colors.red, + letterSpacing: -1, // Tighten spacing + ), + ), + ], + ), + const SizedBox(height: 16), + // Divider line + Divider(height: 1, thickness: 1, indent: 20, endIndent: 20, color: theme.dividerColor.withOpacity(0.5)), + const SizedBox(height: 16), + // Income / Expenses summary items + Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, // Distribute space + children: [ + SummaryItem( // Display total income from stream + icon: Icons.arrow_downward_rounded, + title: 'Income', + amount: '\$${NumberFormat.currency(symbol: '', decimalDigits: 2).format(totalIncome)}', + color: Colors.green, + ), + // Vertical divider + Container( + height: 35, + width: 1, + color: theme.dividerColor.withOpacity(0.5), + ), + SummaryItem( // Display total expenses from stream + icon: Icons.arrow_upward_rounded, + title: 'Expenses', + amount: '\$${NumberFormat.currency(symbol: '', decimalDigits: 2).format(totalExpenses)}', + color: Colors.red, + ), + ], + ), + ], + ), + ), + ), + ), + + // --- Pie Chart Section (Shows EXPENSE Breakdown) --- + ExpandableSection( + title: 'Expense Breakdown', // Clarified title + icon: Icons.pie_chart_outline_rounded, // Updated icon + isExpanded: _isPieChartExpanded, + onTap: _togglePieChartVisibility, + heightFactor: _pieChartHeightFactor, // Animation controller + child: SpendingPieChart( + // Use the categories calculated specifically for the pie chart + categories: expenseCategoriesForPie, + totalExpenses: totalExpenses, // Pass calculated total expenses + animation: _pieChartAnimation, // Appearance animation + ), + ), + + // --- Transaction List Section --- + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Header with Title and Filter/See All buttons + Padding( + padding: const EdgeInsets.fromLTRB(16, 20, 16, 4), // Adjusted padding + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + 'Recent Transactions', + style: theme.textTheme.titleLarge?.copyWith( // Use theme style + fontWeight: FontWeight.w600, // Bold weight + ), + ), + // Filter button + Row( + children: [ + InkWell( // Use InkWell for ripple effect + onTap: _toggleFilterVisibility, + borderRadius: BorderRadius.circular(16), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6), + decoration: BoxDecoration( + color: isDark ? Colors.grey.shade800 : Colors.grey.shade200, + borderRadius: BorderRadius.circular(16), + ), + child: Row( + children: [ + Text( + _selectedFilter == 'All' ? 'All Types' : _selectedFilter, // Display current filter + style: TextStyle( + fontSize: 13, // Smaller font + color: isDark ? Colors.white70 : Colors.black87, + ), + ), + const SizedBox(width: 4), + Icon( + Icons.filter_list_alt, // Updated icon + size: 18, // Slightly larger icon + color: isDark ? Colors.white70 : Colors.black87, + ), + ], + ), + ), + ), + ], + ), + ], + ), + ), + + // --- Filter Chips Row (Animated Visibility) --- + // Shows 'All' and EXPENSE categories from the database stream + AnimatedContainer( + duration: const Duration(milliseconds: 300), // Animation duration + curve: Curves.easeInOut, // Animation curve + height: _isFilterVisible ? 50 : 0, // Animate height + clipBehavior: Clip.hardEdge, // Prevent overflow during animation + decoration: const BoxDecoration(), // Needed for clipBehavior + padding: EdgeInsets.symmetric( + vertical: _isFilterVisible ? 8 : 0, // Animate padding + ), + child: ListView( // Use ListView for horizontal scrolling + scrollDirection: Axis.horizontal, + padding: const EdgeInsets.symmetric(horizontal: 16), + children: [ + // "All" filter chip (shows income and expenses) + FilterChipWidget( + label: 'All Types', + isSelected: _selectedFilter == 'All', + onTap: () => _applyFilter('All') + ), + // Dynamically generate filter chips from EXPENSE categories (from DB) + ...expenseDbCategories.map((category) => + FilterChipWidget( + label: category.name, // Use name from CategoryDb + isSelected: _selectedFilter == category.name, + onTap: () => _applyFilter(category.name) // Applies expense category filter + ) + ).toList(), + ], + ), + ), + + // --- Transactions List (using StreamBuilder) --- + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0), + child: Card( // Wrap list in a Card for background/border + margin: EdgeInsets.zero, + elevation: 0, // No shadow for inner card + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + side: BorderSide(color: theme.dividerColor.withOpacity(0.5), width: 1) // Subtle border + ), + clipBehavior: Clip.antiAlias, // Clip list items to card shape + child: StreamBuilder>( + // Use the stream instance from the state (_transactionsStream is updated by _applyFilter) + stream: _transactionsStream, + builder: (context, transactionSnapshot) { + // Handle loading state for transactions + if (transactionSnapshot.connectionState == ConnectionState.waiting) { + if (!transactionSnapshot.hasData) { + return const SizedBox( + height: 150, // Placeholder height + child: Center(child: CircularProgressIndicator(strokeWidth: 2)), + ); + } + } + // Handle error state for transactions + if (transactionSnapshot.hasError) { + return SizedBox( + height: 150, + child: Center(child: Text('Error: ${transactionSnapshot.error}')), + ); + } + // Get transaction data (or empty list) + final transactions = transactionSnapshot.data ?? []; + + // Display message if no transactions match the filter + if (transactions.isEmpty && transactionSnapshot.connectionState != ConnectionState.waiting) { + return SizedBox( + height: 150, + child: Center( + child: Text( + _selectedFilter == 'All' + ? 'No transactions yet.' + : 'No expenses found for $_selectedFilter.', // Updated message + style: theme.textTheme.bodyMedium?.copyWith(color: Colors.grey), + ), + ), + ); + } + + // Use ListView.builder to display transactions efficiently + return ListView.separated( + itemCount: transactions.length, + physics: const NeverScrollableScrollPhysics(), // Disable inner scrolling + shrinkWrap: true, // Fit content height + padding: const EdgeInsets.symmetric(vertical: 8.0), // Padding inside the card + separatorBuilder: (context, index) => Divider( + height: 1, thickness: 1, indent: 16, endIndent: 16, + color: theme.dividerColor.withOpacity(0.3), + ), + itemBuilder: (context, index) { + // Get the db.Transaction object from the stream + final dbTransaction = transactions[index]; + + // Find the corresponding CategoryDb object for details (icon, color) + // This assumes category names are unique. Handle potential null if category deleted. + final categoryDb = allDbCategories.firstWhere( + (c) => c.name == dbTransaction.categoryName, + orElse: () => db.CategoryDb( // Provide a default if not found + id: -1, + name: dbTransaction.categoryName, + icon: 'help_outline', // Default icon name (string) + color: Colors.grey.value // Default color + ), + ); + + // Get icon data from string name using the new utility function + final iconData = CategoryUtils.getIconFromString(categoryDb.icon); + final colorData = Color(categoryDb.color); + + + // Create the model.TransactionRecord needed by TransactionListItem + final transactionRecord = model.TransactionRecord( + id: dbTransaction.id, + type: dbTransaction.type, + amount: dbTransaction.amount, + // Create the UI Category model only for expenses + category: dbTransaction.type == 'expense' + ? Category( + dbTransaction.categoryName, + dbTransaction.amount, // Amount here might be redundant? + colorData, + iconData, + ) + : null, // No UI Category for income type + date: dbTransaction.date, + merchant: dbTransaction.merchant, + ); + + // Use the TransactionListItem widget + return TransactionListItem( + key: ValueKey(dbTransaction.id), // Use the real ID for the key + transaction: transactionRecord, // Pass the model.TransactionRecord + // Pass the original db.Transaction object for editing/deleting + onEdit: () => _showEditTransactionDialog(dbTransaction), + onDelete: () => _deleteTransaction(dbTransaction.id), + ); + }, + ); + }, + ), + ), + ), + const SizedBox(height: 16), // Bottom padding inside scroll view + ], + ), + const SizedBox(height: 80), // Extra bottom padding below list to avoid FAB overlap + ], + ), + ), + ), + ], + ); + }, + ), + // Bottom Navigation Bar + bottomNavigationBar: BottomNavigationBar( + currentIndex: _selectedNavIndex, + onTap: _onItemTapped, // Use the new handler function + items: const [ // Use const for static items + BottomNavigationBarItem( + icon: Icon(Icons.home_filled), // Use filled icon for selected state + label: 'Home', + ), + BottomNavigationBarItem( + icon: Icon(Icons.bar_chart_rounded), + label: 'Reports', + ), + BottomNavigationBarItem( + icon: Icon(Icons.settings_outlined), + activeIcon: Icon(Icons.settings), // Filled icon when active + label: 'Settings', + ), + ], + ), + // Floating Action Button to add new transaction + floatingActionButton: FloatingActionButton.extended( // Use extended FAB + onPressed: _showAddTransactionSheet, // Show the modal sheet on press + tooltip: 'Add Transaction', + icon: const Icon(Icons.add), + label: const Text('Add'), + ), + floatingActionButtonLocation: FloatingActionButtonLocation.endFloat, // Standard location + ); + } +} + + +// Helper widget to manage multiple streams for the main body +class MultiStreamBuilder extends StatelessWidget { + final List> streams; + final Widget Function(BuildContext, List>) builder; + + const MultiStreamBuilder({ + Key? key, + required this.streams, + required this.builder, + }) : super(key: key); // Use super constructor + + @override + Widget build(BuildContext context) { + // Combine streams ensuring all emit at least one value (or handle initial nulls) + // Using StreamZip might wait until all streams emit. Behavior depends on stream types. + // Consider using combineLatest or similar if waiting isn't desired. + return StreamBuilder>( // Use List and check types later + stream: StreamZip(streams), // StreamZip waits for all streams to emit at least once + builder: (context, combinedSnapshot) { + if (combinedSnapshot.connectionState == ConnectionState.waiting && !combinedSnapshot.hasData) { + // Show loading only if waiting AND no data has arrived yet + return const Center(child: CircularProgressIndicator()); + } + + if (combinedSnapshot.hasError) { + return Center(child: Text('Error combining streams: ${combinedSnapshot.error}')); + } + + // Create AsyncSnapshot objects manually for the builder + // This allows handling individual stream states if needed, though StreamZip simplifies it + final snapshots = List>.generate( + streams.length, + (index) { + if (combinedSnapshot.hasData) { + // If combined stream has data, assume individual streams are done (or active with data) + return AsyncSnapshot.withData(ConnectionState.active, combinedSnapshot.data![index]); + } else if (combinedSnapshot.hasError) { + // Propagate error to individual snapshots (might need refinement) + return AsyncSnapshot.withError(ConnectionState.active, combinedSnapshot.error!); + } else { + // Default to waiting state if combined stream is waiting + return const AsyncSnapshot.waiting(); + } + }, + ); + + // Call the original builder function with the list of snapshots + return builder(context, snapshots); + }, + ); + } + + // This helper function is no longer needed as StreamZip handles the combination + // Stream>> _combineStreams() { ... } +} + + +// --- Widget for the Add Transaction Form --- +class _AddTransactionForm extends StatefulWidget { + final db.AppDatabase database; + final Stream> categoriesStream; // Receive stream + + const _AddTransactionForm({ + Key? key, + required this.database, + required this.categoriesStream, // Require stream + }) : super(key: key); + + @override + State<_AddTransactionForm> createState() => _AddTransactionFormState(); +} + +class _AddTransactionFormState extends State<_AddTransactionForm> { + final _formKey = GlobalKey(); // Key for form validation + final _amountController = TextEditingController(); + final _merchantController = TextEditingController(); // Label changes based on type + String? _selectedCategoryName; // Store the NAME of the selected category + DateTime _selectedDate = DateTime.now(); // Default to today, includes time + TransactionType _selectedType = TransactionType.expense; // Default to expense + + // No longer need static list: final List _categories = CategoryUtils.getAllCategoryNames(); + + @override + void initState() { + super.initState(); + // Set the initial category if the list is not empty and type is expense + // We need to listen to the stream for the initial value + // Setting initial value here is tricky with streams, better handle in StreamBuilder + // if (_selectedType == TransactionType.expense && _categories.isNotEmpty) { + // _selectedCategoryName = _categories[0]; + // } + } + + @override + void dispose() { + _amountController.dispose(); + _merchantController.dispose(); + super.dispose(); + } + + // Function to show the date and time pickers + Future _selectDateTime(BuildContext context) async { + // 1. Pick Date + final DateTime? pickedDate = await showDatePicker( + context: context, + initialDate: _selectedDate, + firstDate: DateTime(2000), // Allow dates from year 2000 + lastDate: DateTime.now().add(const Duration(days: 365)), // Allow up to one year in future + ); + + if (pickedDate != null) { + // If date was picked, proceed to pick time + // 2. Pick Time + final TimeOfDay? pickedTime = await showTimePicker( + context: context, + initialTime: TimeOfDay.fromDateTime(_selectedDate), // Use current time from state + ); + + if (pickedTime != null) { + // If time was also picked, combine date and time and update state + setState(() { + _selectedDate = DateTime( + pickedDate.year, + pickedDate.month, + pickedDate.day, + pickedTime.hour, + pickedTime.minute, + ); + }); + } else { + // If only date was picked, update state with the picked date and existing time + setState(() { + _selectedDate = DateTime( + pickedDate.year, + pickedDate.month, + pickedDate.day, + _selectedDate.hour, // Keep existing hour + _selectedDate.minute, // Keep existing minute + ); + }); + } + } + // If date picker was cancelled (pickedDate == null), do nothing. + } + + + // Function to handle form submission + void _submitTransaction() async { + // Validate the form + if (_formKey.currentState!.validate()) { + // Parse amount + final amount = double.tryParse(_amountController.text); + if (amount == null || amount <= 0) { + // Show error if amount is invalid + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Please enter a valid positive amount.'), + backgroundColor: Colors.red, + behavior: SnackBarBehavior.floating, + ), + ); + return; + } + + // Determine category and type string + String categoryToSave; + String typeString = _selectedType == TransactionType.income ? 'income' : 'expense'; + + if (_selectedType == TransactionType.income) { + categoryToSave = 'Income'; // Use a fixed category for income + } else { + // Ensure a category is selected for expenses + if (_selectedCategoryName == null) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Please select a category for the expense.'), + backgroundColor: Colors.red, + behavior: SnackBarBehavior.floating, + ), + ); + return; + } + categoryToSave = _selectedCategoryName!; + } + + // Create the transaction companion including the type + final merchantValue = _merchantController.text.isNotEmpty + ? _merchantController.text + : (_selectedType == TransactionType.income ? 'Unknown Source' : 'Unknown Merchant'); + + final newTransaction = db.TransactionsCompanion( + categoryName: Value(categoryToSave), + amount: Value(amount), + date: Value(_selectedDate), + merchant: Value(merchantValue), + type: Value(typeString), + ); + + try { + // Add transaction to the database + await widget.database.addTransaction(newTransaction); + + // Close the bottom sheet + if (mounted) Navigator.pop(context); + + // Show success message + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('${_selectedType == TransactionType.income ? "Income" : "Expense"} added: ${typeString == 'income' ? '' : '$categoryToSave - '}\$${amount.toStringAsFixed(2)}'), + duration: const Duration(seconds: 2), + behavior: SnackBarBehavior.floating, + ), + ); + } + } catch (e) { + print('Error adding transaction: $e'); + // Show error message + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Error adding transaction: $e'), + backgroundColor: Colors.red, + behavior: SnackBarBehavior.floating, + ), + ); + } + } + } + } + + // --- Function to handle Add Category button press --- + void _showAddCategoryDialog() async { + // Show the dialog and wait for the result + final newCategory = await showDialog( // Expecting CategoryDb or null + context: context, + builder: (context) => AddCategoryDialog(database: widget.database), + ); + + // If a new category was created and returned + if (newCategory != null) { + // Set the newly created category as selected in the dropdown + setState(() { + _selectedCategoryName = newCategory.name; + }); + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Категория "${newCategory.name}" создана и выбрана.'), + duration: const Duration(seconds: 2), + ), + ); + } + } + } + // --- End of Add Category Function --- + + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final isDark = theme.brightness == Brightness.dark; + final bool isIncome = _selectedType == TransactionType.income; + + return Padding( + padding: const EdgeInsets.all(20.0), + child: Form( + key: _formKey, + child: Column( + mainAxisSize: MainAxisSize.min, // Take minimum space needed + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // --- Header --- + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + 'Add New Transaction', + style: theme.textTheme.titleLarge?.copyWith(fontWeight: FontWeight.w600), + ), + IconButton( + icon: const Icon(Icons.close), + onPressed: () => Navigator.pop(context), // Close button + tooltip: 'Close', + ) + ], + ), + const SizedBox(height: 16), + + // --- Transaction Type Selector --- + Center( + child: ToggleButtons( + isSelected: [!isIncome, isIncome], // [Expense selected, Income selected] + onPressed: (int index) { + setState(() { + _selectedType = index == 0 ? TransactionType.expense : TransactionType.income; + // Reset category selection if switching to income + if (_selectedType == TransactionType.income) { + _selectedCategoryName = null; + } else { + // Don't reset to default here, let StreamBuilder handle initial state + // _selectedCategoryName = _categories[0]; // Remove this + } + }); + }, + borderRadius: BorderRadius.circular(12), + constraints: BoxConstraints(minWidth: (MediaQuery.of(context).size.width - 60) / 2, minHeight: 40), // Adjust width based on screen + selectedColor: Colors.white, + fillColor: isIncome ? Colors.green.shade400 : Colors.red.shade400, + color: isDark ? Colors.white70 : Colors.black54, + selectedBorderColor: isIncome ? Colors.green.shade600 : Colors.red.shade600, + borderColor: isDark ? Colors.grey.shade600 : Colors.grey.shade400, + children: const [ + Padding( + padding: EdgeInsets.symmetric(horizontal: 16.0), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ Icon(Icons.arrow_upward_rounded, size: 18), SizedBox(width: 8), Text('Expense'), ], + ), + ), + Padding( + padding: EdgeInsets.symmetric(horizontal: 16.0), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ Icon(Icons.arrow_downward_rounded, size: 18), SizedBox(width: 8), Text('Income'), ], + ), + ), + ], + ), + ), + const SizedBox(height: 20), + + + // --- Amount Field --- + TextFormField( + controller: _amountController, + decoration: InputDecoration( + labelText: 'Amount', + prefixIcon: Icon(Icons.attach_money, color: isIncome ? Colors.green : theme.colorScheme.primary), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)), + filled: true, + fillColor: isDark ? Colors.grey.shade800.withOpacity(0.5) : Colors.grey.shade100, + ), + keyboardType: const TextInputType.numberWithOptions(decimal: true), + validator: (value) { + if (value == null || value.isEmpty) { + return 'Please enter an amount'; + } + if (double.tryParse(value) == null || double.parse(value) <= 0) { + return 'Please enter a valid positive number'; + } + return null; + }, + ), + const SizedBox(height: 16), + + // --- Category Dropdown and Add Button (Only for Expenses, uses StreamBuilder) --- + if (!isIncome) + StreamBuilder>( + stream: widget.categoriesStream, + builder: (context, snapshot) { + if (snapshot.connectionState == ConnectionState.waiting && !snapshot.hasData) { + return const Center(child: CircularProgressIndicator(strokeWidth: 2)); + } + if (snapshot.hasError) { + return Text('Error loading categories: ${snapshot.error}'); + } + + final categoriesFromDb = snapshot.data ?? []; + // Filter out 'Income' category for the dropdown + final expenseCategories = categoriesFromDb.where((c) => c.name != 'Income').toList(); + + // Ensure _selectedCategoryName is valid or reset it + if (_selectedCategoryName != null && !expenseCategories.any((c) => c.name == _selectedCategoryName)) { + _selectedCategoryName = null; // Reset if selected category is no longer valid + } + // Set default selection if nothing is selected and list is not empty + if (_selectedCategoryName == null && expenseCategories.isNotEmpty) { + // Use WidgetsBinding to schedule state update after build + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) { // Check if widget is still mounted + setState(() { + _selectedCategoryName = expenseCategories[0].name; + }); + } + }); + } + + + return Row( + crossAxisAlignment: CrossAxisAlignment.start, // Align items to the top + children: [ + // Dropdown takes most space + Expanded( + child: DropdownButtonFormField( + value: _selectedCategoryName, // Use the name state variable + decoration: InputDecoration( + labelText: 'Category', + border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)), + filled: true, + fillColor: isDark ? Colors.grey.shade800.withOpacity(0.5) : Colors.grey.shade100, + contentPadding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 16.0), // Adjust padding if needed + ), + // Map CategoryDb objects to DropdownMenuItem + items: expenseCategories.map((db.CategoryDb category) { + // Get icon data using the new utility function + final iconData = CategoryUtils.getIconFromString(category.icon); + final colorData = Color(category.color); + return DropdownMenuItem( + value: category.name, // Value is the category name (String) + child: Row( + children: [ + Icon(iconData, color: colorData, size: 20), + const SizedBox(width: 10), + Text(category.name), + ], + ), + ); + }).toList(), + onChanged: (String? newValue) { + setState(() { + _selectedCategoryName = newValue; // Update the selected name + }); + }, + validator: (value) { + // Only validate if it's an expense + if (_selectedType == TransactionType.expense && value == null) { + return 'Please select a category'; + } + return null; // No validation needed for income + }, + ), + ), + // Add Category Button + Padding( + padding: const EdgeInsets.only(left: 8.0, top: 8.0), // Add padding to space it out and align vertically + child: IconButton( + icon: Icon(Icons.add_circle_outline, color: theme.colorScheme.primary), + tooltip: 'Создать категорию', // Tooltip in Russian as requested + onPressed: _showAddCategoryDialog, // Call the function to show the dialog + ), + ), + ], + ); + }, + ), + if (!isIncome) const SizedBox(height: 16), // Spacer only if category row is shown + + // --- Date and Time Picker --- + InkWell( + onTap: () => _selectDateTime(context), // Use the combined picker function + child: InputDecorator( + decoration: InputDecoration( + labelText: 'Date & Time', // Updated label + prefixIcon: const Icon(Icons.calendar_today_outlined), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)), + filled: true, + fillColor: isDark ? Colors.grey.shade800.withOpacity(0.5) : Colors.grey.shade100, + ), + child: Text( + // Format date and time nicely + DateFormat.yMMMd().add_jm().format(_selectedDate), + style: theme.textTheme.bodyLarge, + ), + ), + ), + const SizedBox(height: 16), + + // --- Merchant / Source Field --- + TextFormField( + controller: _merchantController, + decoration: InputDecoration( + labelText: isIncome ? 'Source' : 'Merchant / Store', // Dynamic label + prefixIcon: Icon(isIncome ? Icons.source_outlined : Icons.storefront_outlined), // Dynamic icon + border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)), + filled: true, + fillColor: isDark ? Colors.grey.shade800.withOpacity(0.5) : Colors.grey.shade100, + ), + textCapitalization: TextCapitalization.words, + // No validator needed, can be empty + ), + const SizedBox(height: 24), + + // --- Save Button --- + SizedBox( + width: double.infinity, // Make button full width + child: ElevatedButton.icon( + onPressed: _submitTransaction, + icon: const Icon(Icons.save_alt_rounded), + label: Text(isIncome ? 'Save Income' : 'Save Expense'), // Dynamic label + style: ElevatedButton.styleFrom( + padding: const EdgeInsets.symmetric(vertical: 14), + textStyle: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + backgroundColor: isIncome ? Colors.green : theme.colorScheme.primary, // Dynamic color + foregroundColor: theme.colorScheme.onPrimary, // Text color on primary + ), + ), + ), + const SizedBox(height: 10), // Padding at the bottom + ], + ), + ), + ); + } +} diff --git a/lib/screens/profile_screen.dart b/lib/screens/profile_screen.dart new file mode 100644 index 0000000..90cb3c4 --- /dev/null +++ b/lib/screens/profile_screen.dart @@ -0,0 +1,73 @@ +import 'package:flutter/material.dart'; + +class ProfileScreen extends StatelessWidget { + const ProfileScreen({Key? key}) : super(key: key); + + @override + Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + + return Scaffold( + appBar: AppBar( + title: const Text('Profile'), + centerTitle: true, + leading: IconButton( + icon: const Icon(Icons.arrow_back), + onPressed: () => Navigator.pop(context), + ), + ), + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Hero( + tag: 'profileAvatar', // Tag must match the one in ExpensesScreen + child: Material( // Wrap with Material for Hero animation + type: MaterialType.transparency, + child: CircleAvatar( + radius: 50, + backgroundColor: isDark ? Colors.green.shade800 : Colors.green.shade100, + child: const Icon( + Icons.person, + size: 50, + color: Colors.green, + ), + ), + ), + ), + const SizedBox(height: 24), + Text( + 'John Doe', + style: TextStyle( + fontSize: 24, + fontWeight: FontWeight.bold, + color: isDark ? Colors.white : Colors.black, + ), + ), + const SizedBox(height: 8), + Text( + 'john.doe@example.com', + style: TextStyle( + fontSize: 16, + color: isDark ? Colors.grey.shade400 : Colors.grey.shade700, + ), + ), + const SizedBox(height: 32), + ElevatedButton( + onPressed: () {}, + style: ElevatedButton.styleFrom( + backgroundColor: isDark ? Colors.green.shade700 : Colors.green, + foregroundColor: Colors.white, + padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 12), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + ), + ), + child: const Text('Edit Profile'), + ), + ], + ), + ), + ); + } +} diff --git a/lib/screens/settings_menu_screen.dart b/lib/screens/settings_menu_screen.dart new file mode 100644 index 0000000..0c9d6ea --- /dev/null +++ b/lib/screens/settings_menu_screen.dart @@ -0,0 +1,49 @@ +import 'package:flutter/material.dart'; +import '../database/database.dart' as db; +import 'settings_screen.dart'; // Импортируем переименованный экран + +class SettingsMenuScreen extends StatelessWidget { + final db.AppDatabase database; + + const SettingsMenuScreen({Key? key, required this.database}) : super(key: key); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + + return Scaffold( + appBar: AppBar( + title: const Text('Настройки'), + centerTitle: true, + backgroundColor: theme.appBarTheme.backgroundColor, + elevation: theme.appBarTheme.elevation, + ), + body: ListView( + padding: const EdgeInsets.symmetric(vertical: 8.0), + children: [ + // Опция "Редактирование категорий" + ListTile( + leading: CircleAvatar( + radius: 22, + backgroundColor: theme.colorScheme.primary.withOpacity(0.15), + child: Icon(Icons.category_outlined, color: theme.colorScheme.primary, size: 24), + ), + title: Text('Редактирование категорий', style: theme.textTheme.titleMedium), + trailing: Icon(Icons.arrow_forward_ios, size: 18, color: theme.colorScheme.onSurface.withOpacity(0.6)), + onTap: () { + // Переход на экран редактирования категорий + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => CategorySettingsScreen(database: database), + ), + ); + }, + ), + // Добавьте другие опции настроек здесь в будущем + // ListTile(...), + ], + ), + ); + } +} diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart new file mode 100644 index 0000000..560177e --- /dev/null +++ b/lib/screens/settings_screen.dart @@ -0,0 +1,211 @@ +import 'package:flutter/material.dart'; +import 'package:drift/drift.dart' show Value; +import '../database/database.dart' as db; +import '../utils/category_utils.dart'; +import '../widgets/edit_category_dialog.dart'; // Импортируем диалог + +// Переименован класс SettingsScreen в CategorySettingsScreen +class CategorySettingsScreen extends StatefulWidget { + final db.AppDatabase database; + + const CategorySettingsScreen({Key? key, required this.database}) : super(key: key); + + @override + State createState() => _CategorySettingsScreenState(); +} + +// Переименован класс _SettingsScreenState в _CategorySettingsScreenState +class _CategorySettingsScreenState extends State { + late Stream> _categoriesStream; + + @override + void initState() { + super.initState(); + _categoriesStream = widget.database.watchAllCategoriesDb(); + } + + // Функция для показа диалога добавления/редактирования + void _showEditCategoryDialog({db.CategoryDb? categoryToEdit}) async { + final result = await showDialog( // Ожидаем bool (true если сохранено) + context: context, + builder: (context) => EditCategoryDialog( + database: widget.database, + categoryToEdit: categoryToEdit, // Передаем категорию для редактирования или null для добавления + ), + ); + + if (result == true && mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(categoryToEdit == null ? 'Категория добавлена' : 'Категория обновлена'), + duration: const Duration(seconds: 2), + behavior: SnackBarBehavior.floating, + ), + ); + } + } + + // Функция для удаления категории (с подтверждением) + void _deleteCategory(db.CategoryDb category) async { + // Не позволяем удалять 'Income' + if (category.name == 'Income') { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Категорию "Income" нельзя удалить.'), + backgroundColor: Colors.orange, + behavior: SnackBarBehavior.floating, + ), + ); + return; + } + + final confirm = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Удалить категорию?'), + content: Text('Вы уверены, что хотите удалить категорию "${category.name}"? Это действие нельзя отменить.\n\nТранзакции с этой категорией могут отображаться некорректно или вызвать ошибки при попытке их отображения, если они не будут переназначены.'), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(false), // Отмена + child: const Text('Отмена'), + ), + TextButton( + onPressed: () => Navigator.of(context).pop(true), // Подтвердить + style: TextButton.styleFrom(foregroundColor: Colors.red), + child: const Text('Удалить'), + ), + ], + ), + ); + + if (confirm == true) { + try { + // Попытка удаления категории из базы данных + final deletedRows = await widget.database.deleteCategory(category.id); + + if (deletedRows > 0 && mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Категория "${category.name}" удалена.'), + duration: const Duration(seconds: 2), + behavior: SnackBarBehavior.floating, + ), + ); + } else if (deletedRows == 0 && mounted) { + // Это может произойти, если deleteCategory вернул 0 (например, из-за наличия транзакций) + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Не удалось удалить категорию "${category.name}". Возможно, она используется в транзакциях.'), + backgroundColor: Colors.red, + duration: const Duration(seconds: 3), + behavior: SnackBarBehavior.floating, + ), + ); + } + } catch (e) { + if (mounted) { + print("Error deleting category: $e"); // Логируем ошибку + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Ошибка при удалении категории: ${e.toString()}'), + backgroundColor: Colors.red, + behavior: SnackBarBehavior.floating, + ), + ); + } + } + } + } + + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final isDark = theme.brightness == Brightness.dark; + + return Scaffold( + appBar: AppBar( + title: const Text('Редактирование категорий'), // Обновленный заголовок + centerTitle: true, + backgroundColor: theme.appBarTheme.backgroundColor, // Ensure AppBar color matches theme + elevation: theme.appBarTheme.elevation, // Ensure elevation matches theme + ), + body: StreamBuilder>( + stream: _categoriesStream, + builder: (context, snapshot) { + if (snapshot.connectionState == ConnectionState.waiting && !snapshot.hasData) { + return const Center(child: CircularProgressIndicator()); + } + if (snapshot.hasError) { + return Center(child: Text('Ошибка загрузки категорий: ${snapshot.error}')); + } + final categories = snapshot.data ?? []; + // Фильтруем категорию 'Income', чтобы ее нельзя было редактировать/удалять отсюда + final editableCategories = categories.where((c) => c.name != 'Income').toList(); + + if (editableCategories.isEmpty && snapshot.connectionState != ConnectionState.waiting) { + return Center( + child: Padding( + padding: const EdgeInsets.all(20.0), + child: Text( + 'Нет категорий для редактирования.\nНажмите "+", чтобы добавить новую категорию расходов.', + textAlign: TextAlign.center, + style: theme.textTheme.bodyLarge?.copyWith(color: Colors.grey), + ), + ), + ); + } + + return ListView.separated( + padding: const EdgeInsets.symmetric(vertical: 8.0), // Add padding around the list + itemCount: editableCategories.length, + separatorBuilder: (context, index) => Divider( + height: 1, + thickness: 1, + indent: 72, // Indent to align with text after avatar + endIndent: 16, + color: theme.dividerColor.withOpacity(0.3), + ), + itemBuilder: (context, index) { + final category = editableCategories[index]; + final iconData = CategoryUtils.getIconFromString(category.icon); + final colorData = Color(category.color); + + return ListTile( + leading: CircleAvatar( + radius: 22, // Slightly larger avatar + backgroundColor: colorData.withOpacity(isDark ? 0.3 : 0.15), + child: Icon(iconData, color: colorData, size: 24), + ), + title: Text(category.name, style: theme.textTheme.titleMedium), + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + IconButton( + icon: Icon(Icons.edit_outlined, color: theme.colorScheme.primary.withOpacity(0.8)), + tooltip: 'Редактировать', + splashRadius: 24, + onPressed: () => _showEditCategoryDialog(categoryToEdit: category), + ), + IconButton( + icon: Icon(Icons.delete_outline, color: Colors.red.shade400.withOpacity(0.8)), + tooltip: 'Удалить', + splashRadius: 24, + onPressed: () => _deleteCategory(category), + ), + ], + ), + onTap: () => _showEditCategoryDialog(categoryToEdit: category), // Тоже открывает редактирование + ); + }, + ); + }, + ), + floatingActionButton: FloatingActionButton( + onPressed: () => _showEditCategoryDialog(), // Вызов без аргумента для добавления + tooltip: 'Добавить категорию', + child: const Icon(Icons.add), + ), + ); + } +} diff --git a/lib/theme/app_theme.dart b/lib/theme/app_theme.dart new file mode 100644 index 0000000..887d8a4 --- /dev/null +++ b/lib/theme/app_theme.dart @@ -0,0 +1,99 @@ +import 'package:flutter/material.dart'; + +class AppTheme { + static ThemeData get lightTheme { + return ThemeData( + brightness: Brightness.light, + primaryColor: Colors.green, + scaffoldBackgroundColor: Colors.grey.shade50, + colorScheme: ColorScheme.fromSeed( + brightness: Brightness.light, + seedColor: Colors.green, + primary: Colors.green, + secondary: Colors.green.shade300, + surface: Colors.white, + background: Colors.grey.shade50, + ), + cardTheme: CardTheme( + elevation: 1, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16.0), + ), + color: Colors.white, + ), + appBarTheme: AppBarTheme( + backgroundColor: Colors.white, + elevation: 0, + iconTheme: IconThemeData(color: Colors.green.shade700), + titleTextStyle: const TextStyle( + color: Colors.black87, + fontSize: 22, + fontWeight: FontWeight.bold, + fontFamily: 'Montserrat', // Ensure font family is applied here too + ), + ), + floatingActionButtonTheme: const FloatingActionButtonThemeData( + backgroundColor: Colors.green, + foregroundColor: Colors.white, + ), + bottomNavigationBarTheme: BottomNavigationBarThemeData( + backgroundColor: Colors.white, + selectedItemColor: Colors.green, + unselectedItemColor: Colors.grey.shade600, + ), + fontFamily: 'Montserrat', + ); + } + + static ThemeData get darkTheme { + return ThemeData( + brightness: Brightness.dark, + primaryColor: Colors.green.shade400, + scaffoldBackgroundColor: const Color(0xFF121212), + colorScheme: ColorScheme.fromSeed( + brightness: Brightness.dark, + seedColor: Colors.green, + primary: Colors.green.shade400, + secondary: Colors.green.shade200, + surface: const Color(0xFF222222), // Used for Card background in dark theme + background: const Color(0xFF121212), + onSurface: Colors.white, // Default text color on surface + ), + cardTheme: CardTheme( + elevation: 4, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16.0), + ), + color: const Color(0xFF1E1E1E), // Darker card color + ), + appBarTheme: const AppBarTheme( + backgroundColor: Color(0xFF1A1A1A), // Slightly different dark background + elevation: 0, + iconTheme: IconThemeData(color: Colors.greenAccent), + titleTextStyle: TextStyle( + color: Colors.white, + fontSize: 22, + fontWeight: FontWeight.bold, + fontFamily: 'Montserrat', // Ensure font family is applied here too + ), + ), + floatingActionButtonTheme: FloatingActionButtonThemeData( + backgroundColor: Colors.green.shade400, + foregroundColor: Colors.black87, // Better contrast on light green + ), + bottomNavigationBarTheme: BottomNavigationBarThemeData( + backgroundColor: const Color(0xFF1A1A1A), + selectedItemColor: Colors.green.shade300, + unselectedItemColor: Colors.grey.shade500, + ), + textTheme: const TextTheme( + bodyLarge: TextStyle(color: Colors.white), // Default text style + bodyMedium: TextStyle(color: Colors.white70), // Secondary text style + // Define other text styles if needed + ).apply( // Ensure font family is applied globally for text + fontFamily: 'Montserrat', + ), + fontFamily: 'Montserrat', + ); + } +} diff --git a/lib/utils/category_utils.dart b/lib/utils/category_utils.dart new file mode 100644 index 0000000..1474ac2 --- /dev/null +++ b/lib/utils/category_utils.dart @@ -0,0 +1,247 @@ +import 'package:flutter/material.dart'; +import '../models/category.dart'; // Import the Category model for return types + +// Helper class to manage category details (icon, color) based on name +class CategoryUtils { + // Private map storing details for each predefined category name. + // Using a record `({IconData icon, Color color})` for concise structure. + // This map is mainly for initial data and potentially fallback display logic. + // The actual icon/color for user-created categories will come from the database. + // DEPRECATED: Rely on _stringToIconData and database color instead. + // static final Map _categoryDetails = { ... }; + + // Default details to return if a category name is not found (e.g., deleted category). + // DEPRECATED: Use getIconFromString and default color instead. + // static final _defaultDetails = (iconCode: Icons.category_outlined, colorCode: Colors.grey.shade500); + + /// DEPRECATED: Returns the IconData and Color associated with a given category name (primarily for fallback). + /// It's better to rely on data fetched directly from the database (CategoryDb). + static ({Color colorCode, IconData iconCode}) getCategoryDetails(String categoryName) { + // Fallback logic using the string-to-icon map and a default color + final icon = getIconFromString(categoryName); // Use the reliable method + // Find color from initial data if possible, otherwise default grey + // This part is still weak, ideally color comes from DB. + Color color = Colors.grey.shade500; // Default color + // Quick check against some known initial names for color fallback + if (categoryName == 'Groceries') color = Colors.green.shade400; + if (categoryName == 'Subscriptions') color = Colors.orange.shade400; + if (categoryName == 'Restaurant') color = Colors.red.shade400; + if (categoryName == 'Shopping') color = Colors.blue.shade400; + if (categoryName == 'Transport') color = Colors.purple.shade400; + if (categoryName == 'Travel') color = Colors.cyan.shade400; + if (categoryName == 'Utilities') color = Colors.teal.shade400; // Updated from home_outlined + if (categoryName == 'Income') color = Colors.lightGreenAccent.shade700; + + return (colorCode: color, iconCode: icon); + } + + /// DEPRECATED: Returns a `Category` object based on its name and amount (primarily for UI models like Pie Chart). + /// Fetches icon/color details using `getCategoryDetails` as a fallback mechanism. + /// Should be replaced by logic that uses CategoryDb data directly. + static Category getCategoryByName(String name, double amount) { + final details = getCategoryDetails(name); + return Category(name, amount, details.colorCode, details.iconCode); + } + + /// DEPRECATED: Returns a list of all predefined category names (excluding placeholders). + /// Might be less useful now that categories are fully dynamic. + static List getAllCategoryNames() { + // Return keys from _stringToIconData, excluding special ones + return _stringToIconData.keys.where((key) => + key != 'help_outline' && + key != 'label_outline' && + key != 'attach_money' && // Exclude Income + key != 'category_outlined' // Exclude Other/Default + ).toList(); + } + + /// Converts a string icon name (like 'shopping_cart_outlined') to IconData. + /// This map is crucial for displaying icons based on the string stored in the DB. + static final Map _stringToIconData = { + // Existing Icons + 'shopping_cart_outlined': Icons.shopping_cart_outlined, // Groceries + 'subscriptions_outlined': Icons.subscriptions_outlined, // Subscriptions + 'restaurant_menu_outlined': Icons.restaurant_menu_outlined, // Restaurant + 'shopping_bag_outlined': Icons.shopping_bag_outlined, // Shopping + 'directions_bus_filled_outlined': Icons.directions_bus_filled_outlined, // Transport + 'flight_takeoff_outlined': Icons.flight_takeoff_outlined, // Travel + 'lightbulb_outline': Icons.lightbulb_outline, // Utilities (alternative) + 'local_hospital_outlined': Icons.local_hospital_outlined, // Health + 'movie_filter_outlined': Icons.movie_filter_outlined, // Entertainment + 'attach_money': Icons.attach_money, // Income (Special) + 'category_outlined': Icons.category_outlined, // Other/Default (Fallback) + 'label_outline': Icons.label_outline, // Placeholder (Internal) + 'help_outline': Icons.help_outline, // Placeholder/Error (Internal) + 'home_outlined': Icons.home_outlined, // Home/Rent/Mortgage/Utilities + 'pets_outlined': Icons.pets_outlined, // Pets + 'school_outlined': Icons.school_outlined, // Education/School + 'fitness_center_outlined': Icons.fitness_center_outlined, // Gym/Fitness + 'checkroom_outlined': Icons.checkroom_outlined, // Clothing + 'devices_other_outlined': Icons.devices_other_outlined, // Electronics + 'card_giftcard_outlined': Icons.card_giftcard_outlined, // Gifts + 'volunteer_activism_outlined': Icons.volunteer_activism_outlined, // Charity/Donations + 'receipt_long_outlined': Icons.receipt_long_outlined, // Bills/Receipts + 'savings_outlined': Icons.savings_outlined, // Savings/Investments + 'credit_card_outlined': Icons.credit_card_outlined, // Credit Card Payment + 'build_outlined': Icons.build_outlined, // Repairs/Maintenance + 'child_friendly_outlined': Icons.child_friendly_outlined, // Child Care + 'work_outline': Icons.work_outline, // Work related + 'book_outlined': Icons.book_outlined, // Books/Magazines + 'music_note_outlined': Icons.music_note_outlined, // Music + 'sports_esports_outlined': Icons.sports_esports_outlined, // Games/Hobbies + 'local_bar_outlined': Icons.local_bar_outlined, // Drinks/Bar + 'cake_outlined': Icons.cake_outlined, // Celebrations/Party + 'park_outlined': Icons.park_outlined, // Parks/Outdoors + 'science_outlined': Icons.science_outlined, // Science/Tech + 'palette_outlined': Icons.palette_outlined, // Art/Design + 'account_balance_outlined': Icons.account_balance_outlined, // Bank/Finance Fees + 'analytics_outlined': Icons.analytics_outlined, // Analysis/Reports (Maybe internal?) + 'apartment_outlined': Icons.apartment_outlined, // Rent/Mortgage (Alternative) + 'beach_access_outlined': Icons.beach_access_outlined, // Vacation/Beach + 'brush_outlined': Icons.brush_outlined, // Personal Care/Cosmetics + 'business_center_outlined': Icons.business_center_outlined, // Business Expenses + 'call_outlined': Icons.call_outlined, // Phone Bill + 'camera_alt_outlined': Icons.camera_alt_outlined, // Photography/Equipment + 'car_rental_outlined': Icons.car_rental_outlined, // Car Rental + 'car_repair_outlined': Icons.car_repair_outlined, // Car Repair + 'celebration_outlined': Icons.celebration_outlined, // Party/Events (Alternative) + 'computer_outlined': Icons.computer_outlined, // Computer/Software + 'construction_outlined': Icons.construction_outlined, // Home Improvement + 'cottage_outlined': Icons.cottage_outlined, // Vacation Home/Cottage + 'delivery_dining_outlined': Icons.delivery_dining_outlined, // Food Delivery + 'diamond_outlined': Icons.diamond_outlined, // Jewelry/Luxury + 'dry_cleaning_outlined': Icons.dry_cleaning_outlined, // Laundry/Dry Cleaning + 'electrical_services_outlined': Icons.electrical_services_outlined, // Electrician + 'emoji_events_outlined': Icons.emoji_events_outlined, // Awards/Competitions + 'fastfood_outlined': Icons.fastfood_outlined, // Fast Food + 'fax_outlined': Icons.fax_outlined, // Office Supplies (Maybe outdated?) + 'festival_outlined': Icons.festival_outlined, // Festivals/Events + 'fireplace_outlined': Icons.fireplace_outlined, // Heating/Fuel + 'flatware_outlined': Icons.flatware_outlined, // Kitchenware + 'gas_meter_outlined': Icons.gas_meter_outlined, // Gas Bill + 'gavel_outlined': Icons.gavel_outlined, // Legal Fees + 'grass_outlined': Icons.grass_outlined, // Gardening/Lawn Care + 'hardware_outlined': Icons.hardware_outlined, // Hardware Store + 'hearing_outlined': Icons.hearing_outlined, // Audio/Headphones + 'hiking_outlined': Icons.hiking_outlined, // Hiking/Outdoor Gear + 'icecream_outlined': Icons.icecream_outlined, // Ice Cream/Desserts + 'interests_outlined': Icons.interests_outlined, // Hobbies General + 'key_outlined': Icons.key_outlined, // Keys/Locks + 'liquor_outlined': Icons.liquor_outlined, // Alcohol + 'local_activity_outlined': Icons.local_activity_outlined, // Tickets/Events + 'local_atm_outlined': Icons.local_atm_outlined, // ATM Withdrawal (Maybe internal?) + 'local_convenience_store_outlined': Icons.local_convenience_store_outlined, // Convenience Store + 'local_florist_outlined': Icons.local_florist_outlined, // Flowers + 'local_gas_station_outlined': Icons.local_gas_station_outlined, // Gas/Fuel + 'local_laundry_service_outlined': Icons.local_laundry_service_outlined, // Laundry Service + 'local_mall_outlined': Icons.local_mall_outlined, // Mall Shopping + 'local_offer_outlined': Icons.local_offer_outlined, // Discounts/Sales/Coupons + 'local_parking_outlined': Icons.local_parking_outlined, // Parking Fees + 'local_pharmacy_outlined': Icons.local_pharmacy_outlined, // Pharmacy + 'local_pizza_outlined': Icons.local_pizza_outlined, // Pizza + 'local_shipping_outlined': Icons.local_shipping_outlined, // Shipping Costs + 'local_taxi_outlined': Icons.local_taxi_outlined, // Taxi/Rideshare + 'lunch_dining_outlined': Icons.lunch_dining_outlined, // Lunch + 'medication_outlined': Icons.medication_outlined, // Medication + 'museum_outlined': Icons.museum_outlined, // Museum/Exhibits + 'newspaper_outlined': Icons.newspaper_outlined, // Newspapers/Magazines + 'paid_outlined': Icons.paid_outlined, // Payments/Transfers (Maybe internal?) + 'pedal_bike_outlined': Icons.pedal_bike_outlined, // Cycling + 'plumbing_outlined': Icons.plumbing_outlined, // Plumber + 'ramen_dining_outlined': Icons.ramen_dining_outlined, // Noodles/Asian Food + 'recycling_outlined': Icons.recycling_outlined, // Recycling Fees + 'redeem_outlined': Icons.redeem_outlined, // Gifts Received/Redeemed (Maybe internal?) + 'request_quote_outlined': Icons.request_quote_outlined, // Invoices/Quotes (Maybe internal?) + 'roller_skating_outlined': Icons.roller_skating_outlined, // Skating + 'roofing_outlined': Icons.roofing_outlined, // Roofing Repair + 'room_service_outlined': Icons.room_service_outlined, // Hotel Service + 'shield_outlined': Icons.shield_outlined, // Insurance + 'skateboarding_outlined': Icons.skateboarding_outlined, // Skateboarding + 'smoking_rooms_outlined': Icons.smoking_rooms_outlined, // Tobacco + 'spa_outlined': Icons.spa_outlined, // Spa/Wellness + 'sports_bar_outlined': Icons.sports_bar_outlined, // Sports Bar + 'sports_basketball_outlined': Icons.sports_basketball_outlined, // Basketball + 'sports_football_outlined': Icons.sports_football_outlined, // Football + 'sports_golf_outlined': Icons.sports_golf_outlined, // Golf + 'sports_gymnastics_outlined': Icons.sports_gymnastics_outlined, // Gymnastics + 'sports_handball_outlined': Icons.sports_handball_outlined, // Handball + 'sports_hockey_outlined': Icons.sports_hockey_outlined, // Hockey + 'sports_kabaddi_outlined': Icons.sports_kabaddi_outlined, // Kabaddi + 'sports_mma_outlined': Icons.sports_mma_outlined, // MMA + 'sports_motorsports_outlined': Icons.sports_motorsports_outlined, // Motorsports + 'sports_soccer_outlined': Icons.sports_soccer_outlined, // Soccer + 'sports_tennis_outlined': Icons.sports_tennis_outlined, // Tennis + 'sports_volleyball_outlined': Icons.sports_volleyball_outlined, // Volleyball + 'stadium_outlined': Icons.stadium_outlined, // Stadium/Events + 'store_mall_directory_outlined': Icons.store_mall_directory_outlined, // Department Store + 'stroller_outlined': Icons.stroller_outlined, // Baby Supplies + 'subway_outlined': Icons.subway_outlined, // Subway/Metro + 'surfing_outlined': Icons.surfing_outlined, // Surfing + 'sync_alt_outlined': Icons.sync_alt_outlined, // Transfers (Maybe internal?) + 'theater_comedy_outlined': Icons.theater_comedy_outlined, // Comedy Club + 'theaters_outlined': Icons.theaters_outlined, // Cinema/Theater + 'toys_outlined': Icons.toys_outlined, // Toys + 'train_outlined': Icons.train_outlined, // Train Travel + 'tram_outlined': Icons.tram_outlined, // Tram + 'two_wheeler_outlined': Icons.two_wheeler_outlined, // Motorcycle/Scooter + 'vape_free_outlined': Icons.vape_free_outlined, // Vaping (quit) + 'vaping_rooms_outlined': Icons.vaping_rooms_outlined, // Vaping + 'videogame_asset_outlined': Icons.videogame_asset_outlined, // Video Games + 'water_drop_outlined': Icons.water_drop_outlined, // Water Bill + 'wifi_outlined': Icons.wifi_outlined, // Internet Bill + 'wine_bar_outlined': Icons.wine_bar_outlined, // Wine Bar + }; + + /// Returns the IconData corresponding to the given icon name string. + /// If the `iconName` is not found or is null/empty, returns a default fallback icon (`Icons.help_outline`). + static IconData getIconFromString(String? iconName) { + if (iconName == null || iconName.isEmpty) { + return Icons.help_outline; // Default for null or empty + } + return _stringToIconData[iconName] ?? Icons.help_outline; // Return default if not found in map + } + + /// Returns a map of available icons for selection in UI (e.g., dropdowns, dialogs). + /// Excludes placeholder/internal icons like 'help_outline', 'label_outline', + /// 'category_outlined', and the special 'attach_money' (Income). + static Map getAvailableIcons() { + final availableIcons = Map.from(_stringToIconData); + // Remove icons not intended for user selection as expense categories + availableIcons.remove('help_outline'); // Internal fallback/error + availableIcons.remove('label_outline'); // Internal placeholder + availableIcons.remove('category_outlined'); // Internal generic fallback + availableIcons.remove('attach_money'); // Reserved for Income type + // Consider removing others if they represent internal states: + // availableIcons.remove('sync_alt_outlined'); // Transfers? + // availableIcons.remove('paid_outlined'); // Payments? + // availableIcons.remove('local_atm_outlined'); // ATM? + // availableIcons.remove('redeem_outlined'); // Gifts Received? + // availableIcons.remove('request_quote_outlined'); // Invoices? + // availableIcons.remove('analytics_outlined'); // Reports? + return availableIcons; + } + + /// List of available colors for category selection in UI. + static const List availableColors = [ + // Primary Colors (Good starting points) + Colors.red, Colors.pink, Colors.purple, Colors.deepPurple, + Colors.indigo, Colors.blue, Colors.lightBlue, Colors.cyan, + Colors.teal, Colors.green, Colors.lightGreen, Colors.lime, + Colors.yellow, Colors.amber, Colors.orange, Colors.deepOrange, + Colors.brown, Colors.grey, Colors.blueGrey, + + // Accent Colors (Brighter, use with care) + Colors.redAccent, Colors.pinkAccent, Colors.purpleAccent, Colors.deepPurpleAccent, + Colors.indigoAccent, Colors.blueAccent, Colors.lightBlueAccent, Colors.cyanAccent, + Colors.tealAccent, Colors.greenAccent, Colors.limeAccent, + Colors.yellowAccent, Colors.amberAccent, Colors.orangeAccent, Colors.deepOrangeAccent, + + // Shade variations (More subtle options) + /*Colors.red.shade300, Colors.pink.shade200, Colors.purple.shade300, + Colors.indigo.shade300, Colors.blue.shade300, Colors.lightBlue.shade300, + Colors.cyan.shade300, Colors.teal.shade300, Colors.green.shade300, + Colors.lightGreen.shade300, Colors.lime.shade300, Colors.yellow.shade600, // Darker yellow + Colors.amber.shade300, Colors.orange.shade300, Colors.deepOrange.shade300, + Colors.brown.shade300, Colors.grey.shade400, Colors.blueGrey.shade300,*/ + ]; +} diff --git a/lib/widgets/add_category_dialog.dart b/lib/widgets/add_category_dialog.dart new file mode 100644 index 0000000..6823213 --- /dev/null +++ b/lib/widgets/add_category_dialog.dart @@ -0,0 +1,268 @@ +import 'package:drift/drift.dart' show Value; +import 'package:flutter/material.dart'; +import '../database/database.dart' as db; // Import database with prefix 'db' +import '../utils/category_utils.dart'; // Import CategoryUtils + +class AddCategoryDialog extends StatefulWidget { + final db.AppDatabase database; + + const AddCategoryDialog({Key? key, required this.database}) : super(key: key); + + @override + State createState() => _AddCategoryDialogState(); +} + +class _AddCategoryDialogState extends State { + final _formKey = GlobalKey(); + final _nameController = TextEditingController(); + // State for selected icon + String _selectedIconName = 'label_outline'; // Default icon name (string) + IconData _selectedIconData = Icons.label_outline; // Default icon data + // State for selected color + Color _selectedColor = CategoryUtils.availableColors[9]; // Default to green + + @override + void initState() { + super.initState(); + // Initialize icon data based on the default name + _selectedIconData = CategoryUtils.getIconFromString(_selectedIconName); + } + + @override + void dispose() { + _nameController.dispose(); + super.dispose(); + } + + // --- Function to show the icon picker dialog --- + Future _showIconPicker() async { + final Map availableIcons = CategoryUtils.getAvailableIcons(); + final List iconNames = availableIcons.keys.toList(); + final List iconDatas = availableIcons.values.toList(); + print("Number of available icons: ${availableIcons.length}"); // Debug print + + final String? chosenIconName = await showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: const Text('Выберите иконку'), + contentPadding: const EdgeInsets.all(10.0), // Adjust padding + content: SizedBox( // Constrain the size of the dialog content + width: double.maxFinite, // Use maximum width available + height: 300, // <--- ЗАДАЕМ ВЫСОТУ ДЛЯ ОБЛАСТИ ПРОКРУТКИ + child: GridView.builder( + // shrinkWrap: true, // <--- УБИРАЕМ SHRINKWRAP + itemCount: iconNames.length, + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 5, // Adjust number of columns + crossAxisSpacing: 10.0, + mainAxisSpacing: 10.0, + ), + itemBuilder: (context, index) { + final bool isSelected = _selectedIconName == iconNames[index]; + return InkWell( + onTap: () { + Navigator.pop(context, iconNames[index]); // Return the selected icon name (String) + }, + borderRadius: BorderRadius.circular(8.0), // Ripple effect matches border + child: Container( + decoration: BoxDecoration( + border: Border.all( + color: isSelected + ? Theme.of(context).colorScheme.primary // Highlight selected + : Colors.grey.withOpacity(0.3), // Subtle border for all + width: isSelected ? 2.0 : 1.0, // Thicker border if selected + ), + borderRadius: BorderRadius.circular(8.0), + color: isSelected ? Theme.of(context).colorScheme.primary.withOpacity(0.1) : null, + ), + child: Icon( + iconDatas[index], + size: 30.0, // Adjust icon size + color: Theme.of(context).brightness == Brightness.dark + ? Colors.white70 + : Colors.black87, + ), + ), + ); + }, + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, null), // Close without selection + child: const Text('Отмена'), + ), + ], + ); + }, + ); + + // Update state if an icon was chosen + if (chosenIconName != null) { + setState(() { + _selectedIconName = chosenIconName; + _selectedIconData = CategoryUtils.getIconFromString(chosenIconName); + }); + } + } + // --- End of Icon Picker Function --- + + + Future _saveCategory() async { + if (_formKey.currentState!.validate()) { + final name = _nameController.text; + // Use the selected icon name + final icon = _selectedIconName; + // Use the selected color value + final color = _selectedColor.value; + + final newCategoryCompanion = db.CategoriesCompanion( + name: Value(name), + icon: Value(icon), // Use selected icon name + color: Value(color), // Use selected color value + ); + + try { + // TODO: Add check for duplicate category name before inserting (more robustly) + final newCategoryId = await widget.database.addCategory(newCategoryCompanion); + final newCategory = await widget.database.getCategoryById(newCategoryId); + if (mounted) { + Navigator.pop(context, newCategory); // Return the newly created CategoryDb object + } + } catch (e) { + print('Error adding category: $e'); + // Handle potential duplicate name error from database (depends on DB constraints) + String errorMessage = 'Произошла ошибка при добавлении категории.'; + if (e.toString().toLowerCase().contains('unique constraint failed')) { + errorMessage = 'Категория с таким именем уже существует.'; + } + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(errorMessage), + backgroundColor: Colors.red, + ), + ); + } + } + } + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + // Determine icon color based on the selected background color's brightness + final iconColor = ThemeData.estimateBrightnessForColor(_selectedColor) == Brightness.dark + ? Colors.white70 + : Colors.black87; + + return AlertDialog( + title: const Text('Создать категорию'), + content: Form( + key: _formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, // Align children to the start + children: [ + // --- Icon and Name Row --- + Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + // --- Icon Picker --- + Padding( + padding: const EdgeInsets.only(right: 16.0, bottom: 10.0), // Add padding + child: InkWell( + onTap: _showIconPicker, // Show picker on tap + customBorder: const CircleBorder(), // Make ripple circular + child: CircleAvatar( + radius: 24, + backgroundColor: _selectedColor, // Use selected color for background + child: Icon( + _selectedIconData, // Display selected icon + color: iconColor, // Adjust icon color based on background + size: 26, + ), + ), + ), + ), + // --- Name Field --- + Expanded( + child: TextFormField( + controller: _nameController, + decoration: const InputDecoration( + labelText: 'Название категории', + ), + validator: (value) { + if (value == null || value.isEmpty) { + return 'Пожалуйста, введите название'; + } + // Basic length check + if (value.length > 50) { + return 'Название слишком длинное'; + } + return null; + }, + textCapitalization: TextCapitalization.sentences, + ), + ), + ], + ), + const SizedBox(height: 20), // Space before color picker + + // --- Color Picker --- + const Text('Выберите цвет:', style: TextStyle(fontSize: 16)), + const SizedBox(height: 8), + Wrap( // Use Wrap for horizontal layout with wrapping + spacing: 8.0, // Horizontal space between circles + runSpacing: 8.0, // Vertical space between rows + children: CategoryUtils.availableColors.map((color) { + final bool isSelected = _selectedColor == color; + return InkWell( + onTap: () { + setState(() { + _selectedColor = color; // Update selected color on tap + }); + }, + customBorder: const CircleBorder(), + child: Container( + width: 32, // Size of the color circle + height: 32, + decoration: BoxDecoration( + color: color, + shape: BoxShape.circle, + border: Border.all( + color: isSelected + ? theme.colorScheme.onSurface // Highlight selected + : theme.dividerColor, // Border for others + width: isSelected ? 3.0 : 1.0, + ), + boxShadow: isSelected ? [ + BoxShadow( + color: Colors.black.withOpacity(0.3), + blurRadius: 3, + offset: const Offset(0, 1), + ) + ] : null, + ), + ), + ); + }).toList(), + ), + const SizedBox(height: 16), // Add some space at the bottom + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, null), // Return null if cancelled + child: const Text('Отмена'), + ), + ElevatedButton( + onPressed: _saveCategory, + child: const Text('Сохранить'), + ), + ], + ); + } +} diff --git a/lib/widgets/edit_category_dialog.dart b/lib/widgets/edit_category_dialog.dart new file mode 100644 index 0000000..be6b2f2 --- /dev/null +++ b/lib/widgets/edit_category_dialog.dart @@ -0,0 +1,299 @@ +import 'package:flutter/material.dart'; +import 'package:drift/drift.dart' show Value; +import '../database/database.dart' as db; +import '../utils/category_utils.dart'; + +class EditCategoryDialog extends StatefulWidget { + final db.AppDatabase database; + final db.CategoryDb? categoryToEdit; // null если добавляем новую + + const EditCategoryDialog({ + Key? key, + required this.database, + this.categoryToEdit, + }) : super(key: key); + + @override + State createState() => _EditCategoryDialogState(); +} + +class _EditCategoryDialogState extends State { + final _formKey = GlobalKey(); + late TextEditingController _nameController; + String? _selectedIconName; + Color? _selectedColor; + + bool get _isEditing => widget.categoryToEdit != null; + + @override + void initState() { + super.initState(); + _nameController = TextEditingController(text: widget.categoryToEdit?.name ?? ''); + // Ensure the initial icon exists in the available list, otherwise pick the first + _selectedIconName = widget.categoryToEdit?.icon; + if (_selectedIconName == null || !CategoryUtils.getAvailableIcons().containsKey(_selectedIconName)) { + _selectedIconName = CategoryUtils.getAvailableIcons().keys.first; + } + + // Инициализируем цвет. + // Если редактируем существующую категорию, используем ее цвет из БД. + // Если добавляем новую, используем первый цвет из доступных. + if (_isEditing) { + _selectedColor = Color(widget.categoryToEdit!.color); + } else { + _selectedColor = CategoryUtils.availableColors.first; + } + + // Убедимся, что _selectedColor не null после инициализации + // (это должно быть гарантировано логикой выше, но для безопасности) + _selectedColor ??= CategoryUtils.availableColors.first; + } + + @override + void dispose() { + _nameController.dispose(); + super.dispose(); + } + + Future _saveCategory() async { + if (_formKey.currentState!.validate()) { + final name = _nameController.text.trim(); + final icon = _selectedIconName; + final color = _selectedColor; + + if (icon == null || color == null) { + // This should not happen due to initialization logic, but check anyway + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Пожалуйста, выберите иконку и цвет'), + backgroundColor: Colors.orange, + behavior: SnackBarBehavior.floating, + ), + ); + } + return; + } + + // Проверка на уникальность имени (кроме случая редактирования той же категории) + // Используем case-insensitive сравнение + final existingCategories = await widget.database.watchAllCategoriesDb().first; + final isNameTaken = existingCategories.any((c) => + c.name.toLowerCase() == name.toLowerCase() && + (!_isEditing || c.id != widget.categoryToEdit!.id)); // Проверяем ID только при редактировании + + if (isNameTaken) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Категория с именем "$name" уже существует.'), + backgroundColor: Colors.orange, + behavior: SnackBarBehavior.floating, + ), + ); + } + return; + } + // Запрещаем имя 'Income' (case-insensitive) + if (name.toLowerCase() == 'income') { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Имя "Income" зарезервировано.'), + backgroundColor: Colors.orange, + behavior: SnackBarBehavior.floating, + ), + ); + } + return; + } + + + final companion = db.CategoriesCompanion( + id: _isEditing ? Value(widget.categoryToEdit!.id) : const Value.absent(), + name: Value(name), + icon: Value(icon), + color: Value(color.value), + ); + + try { + if (_isEditing) { + await widget.database.updateCategory(companion); + } else { + await widget.database.addCategory(companion); + } + if (mounted) Navigator.of(context).pop(true); // Возвращаем true при успехе + } catch (e) { + print('Error saving category: $e'); + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Ошибка сохранения категории: ${e.toString()}'), + backgroundColor: Colors.red, + behavior: SnackBarBehavior.floating, + ), + ); + } + } + } + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final isDark = theme.brightness == Brightness.dark; + final availableIcons = CategoryUtils.getAvailableIcons(); // Get filtered icons + + // Объединяем цвет текущей категории (если редактируем) с доступными цветами + // для отображения в палитре. Это нужно, чтобы текущий цвет был виден, + // даже если его нет в стандартном списке. + final List displayedColors = List.from(CategoryUtils.availableColors); + if (_isEditing && _selectedColor != null && !CategoryUtils.availableColors.contains(_selectedColor)) { + // Добавляем цвет текущей категории в начало списка для отображения + displayedColors.insert(0, _selectedColor!); + } + + + return AlertDialog( + title: Text(_isEditing ? 'Редактировать категорию' : 'Добавить категорию'), + contentPadding: const EdgeInsets.fromLTRB(24.0, 20.0, 24.0, 0.0), // Adjust padding + content: SizedBox( // Constrain width for better appearance on large screens + width: MediaQuery.of(context).size.width * 0.8, // Example width constraint + child: SingleChildScrollView( // Позволяет прокручивать, если не помещается + child: Form( + key: _formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, // Align labels to start + children: [ + // --- Поле Имя --- + TextFormField( + controller: _nameController, + decoration: InputDecoration( + labelText: 'Название категории', + border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)), + filled: true, + fillColor: isDark ? Colors.grey.shade800.withOpacity(0.5) : Colors.grey.shade100, + ), + validator: (value) { + if (value == null || value.trim().isEmpty) { + return 'Введите название'; + } + if (value.trim().toLowerCase() == 'income') { + return 'Имя "Income" зарезервировано'; + } + return null; + }, + textCapitalization: TextCapitalization.words, + ), + const SizedBox(height: 20), + + // --- Выбор Иконки --- + DropdownButtonFormField( + value: _selectedIconName, + isExpanded: true, // Allow dropdown to expand + decoration: InputDecoration( + labelText: 'Иконка', + border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)), + filled: true, + fillColor: isDark ? Colors.grey.shade800.withOpacity(0.5) : Colors.grey.shade100, + contentPadding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 16.0), + ), + items: availableIcons.entries.map((entry) { + return DropdownMenuItem( + value: entry.key, + child: Row( + children: [ + Icon(entry.value, color: _selectedColor ?? theme.colorScheme.primary, size: 20), + const SizedBox(width: 12), + // Отображаем имя иконки, убирая '_outlined' и делая первую букву заглавной + Text(entry.key.replaceAll('_outlined', '').replaceAll('_', ' ').capitalizeFirst()), + ], + ), + ); + }).toList(), + onChanged: (value) { + if (value != null) { + setState(() { + _selectedIconName = value; + }); + } + }, + validator: (value) => value == null ? 'Выберите иконку' : null, + ), + const SizedBox(height: 20), + + // --- Выбор Цвета --- + Text('Цвет категории:', style: theme.textTheme.titleSmall), + const SizedBox(height: 10), + Wrap( // Используем Wrap для отображения цветов в несколько рядов + spacing: 10.0, // Горизонтальный отступ + runSpacing: 10.0, // Вертикальный отступ + children: displayedColors.map((color) { // Используем объединенный список цветов + final isSelected = _selectedColor == color; + return GestureDetector( + onTap: () { + setState(() { + _selectedColor = color; + }); + }, + child: Container( + width: 38, + height: 38, + decoration: BoxDecoration( + color: color, + shape: BoxShape.circle, + border: Border.all( + color: isSelected + ? (isDark ? Colors.white70 : Colors.black87) + : theme.dividerColor.withOpacity(0.5), // Subtle border for unselected + width: isSelected ? 2.5 : 1.0, + ), + boxShadow: isSelected ? [ + BoxShadow( + color: color.withOpacity(0.5), + blurRadius: 4, + offset: const Offset(0, 2), + ) + ] : [], + ), + child: isSelected + ? Icon(Icons.check, color: ThemeData.estimateBrightnessForColor(color) == Brightness.dark ? Colors.white : Colors.black, size: 20) + : null, + ), + ); + }).toList(), + ), + const SizedBox(height: 24), // Add space before actions + ], + ), + ), + ), + ), + actionsPadding: const EdgeInsets.fromLTRB(24.0, 0.0, 24.0, 16.0), // Adjust actions padding + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(false), // Возвращаем false при отмене + child: const Text('Отмена'), + ), + ElevatedButton.icon( + icon: const Icon(Icons.save_alt_rounded), + onPressed: _saveCategory, + label: const Text('Сохранить'), + style: ElevatedButton.styleFrom( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + ), + ), + ], + ); + } +} + +// Helper extension for capitalizing first letter +extension StringExtension on String { + String capitalizeFirst() { + if (isEmpty) return this; + return "${this[0].toUpperCase()}${substring(1)}"; + } +} diff --git a/lib/widgets/edit_transaction_dialog.dart b/lib/widgets/edit_transaction_dialog.dart new file mode 100644 index 0000000..653bfa7 --- /dev/null +++ b/lib/widgets/edit_transaction_dialog.dart @@ -0,0 +1,382 @@ +import 'package:flutter/material.dart'; +import 'package:drift/drift.dart' show Value; +import 'package:intl/intl.dart'; + +import '../database/database.dart' as db; +import '../utils/category_utils.dart'; // For icon and color utilities + +class EditTransactionDialog extends StatefulWidget { + final db.AppDatabase database; + final db.Transaction transaction; // The transaction to edit + final Stream> categoriesStream; // Stream of available categories + + const EditTransactionDialog({ + Key? key, + required this.database, + required this.transaction, + required this.categoriesStream, + }) : super(key: key); + + @override + State createState() => _EditTransactionDialogState(); +} + +class _EditTransactionDialogState extends State { + final _formKey = GlobalKey(); + late TextEditingController _amountController; + late TextEditingController _merchantController; + late String? _selectedCategoryName; // Can be null for Income + late DateTime _selectedDate; + late db.TransactionType _selectedType; + + @override + void initState() { + super.initState(); + // Initialize controllers and state with existing transaction data + _amountController = TextEditingController(text: widget.transaction.amount.toString()); + _merchantController = TextEditingController(text: widget.transaction.merchant); + _selectedDate = widget.transaction.date; + _selectedType = widget.transaction.type == 'income' ? db.TransactionType.income : db.TransactionType.expense; + + // Set initial category name based on transaction type + if (_selectedType == db.TransactionType.expense) { + _selectedCategoryName = widget.transaction.categoryName; + } else { + _selectedCategoryName = null; // Income doesn't have a selectable category + } + } + + @override + void dispose() { + _amountController.dispose(); + _merchantController.dispose(); + super.dispose(); + } + + // Function to show the date and time pickers + Future _selectDateTime(BuildContext context) async { + // 1. Pick Date + final DateTime? pickedDate = await showDatePicker( + context: context, + initialDate: _selectedDate, + firstDate: DateTime(2000), + lastDate: DateTime.now().add(const Duration(days: 365)), + ); + + if (pickedDate != null) { + // If date was picked, proceed to pick time + // 2. Pick Time + final TimeOfDay? pickedTime = await showTimePicker( + context: context, + initialTime: TimeOfDay.fromDateTime(_selectedDate), + ); + + if (pickedTime != null) { + // If time was also picked, combine date and time and update state + setState(() { + _selectedDate = DateTime( + pickedDate.year, + pickedDate.month, + pickedDate.day, + pickedTime.hour, + pickedTime.minute, + ); + }); + } else { + // If only date was picked, update state with the picked date and existing time + setState(() { + _selectedDate = DateTime( + pickedDate.year, + pickedDate.month, + pickedDate.day, + _selectedDate.hour, // Keep existing hour + _selectedDate.minute, // Keep existing minute + ); + }); + } + } + } + + // Function to handle form submission (Update) + void _updateTransaction() async { + if (_formKey.currentState!.validate()) { + final amount = double.tryParse(_amountController.text); + if (amount == null || amount <= 0) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Пожалуйста, введите корректную положительную сумму.'), + backgroundColor: Colors.red, + ), + ); + return; + } + + String categoryToSave; + String typeString = _selectedType == db.TransactionType.income ? 'income' : 'expense'; + + if (_selectedType == db.TransactionType.income) { + categoryToSave = 'Income'; // Fixed category for income + } else { + if (_selectedCategoryName == null) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Пожалуйста, выберите категорию для расхода.'), + backgroundColor: Colors.red, + ), + ); + return; + } + categoryToSave = _selectedCategoryName!; + } + + // Create the updated transaction companion + final updatedTransaction = db.TransactionsCompanion( + id: Value(widget.transaction.id), // Include the ID for update + categoryName: Value(categoryToSave), + amount: Value(amount), + date: Value(_selectedDate), + merchant: Value(_merchantController.text), + type: Value(typeString), + ); + + try { + // Update transaction in the database + final success = await widget.database.updateTransaction(updatedTransaction); + + if (success) { + // Close the dialog and return the updated transaction + if (mounted) Navigator.of(context).pop(widget.transaction.copyWith( // Return a copy with updated values + categoryName: categoryToSave, + amount: amount, + date: _selectedDate, + merchant: _merchantController.text, + type: typeString, + )); + } else { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Не удалось обновить транзакцию.'), + backgroundColor: Colors.red, + ), + ); + } + } + } catch (e) { + print('Error updating transaction: $e'); + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Ошибка при обновлении транзакции: $e'), + backgroundColor: Colors.red, + ), + ); + } + } + } + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final isDark = theme.brightness == Brightness.dark; + final bool isIncome = _selectedType == db.TransactionType.income; + + return AlertDialog( + title: const Text('Редактировать транзакцию'), + content: SingleChildScrollView( // Use SingleChildScrollView for content + child: Form( + key: _formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // --- Transaction Type Selector --- + Center( + child: ToggleButtons( + isSelected: [!isIncome, isIncome], + onPressed: (int index) { + setState(() { + _selectedType = index == 0 ? db.TransactionType.expense : db.TransactionType.income; + // Reset category selection if switching to income + if (_selectedType == db.TransactionType.income) { + _selectedCategoryName = null; + } else { + // If switching to expense, try to select the first expense category + // This relies on the StreamBuilder below to update the dropdown + // and potentially set a default if _selectedCategoryName is null. + } + }); + }, + borderRadius: BorderRadius.circular(12), + // ИЗМЕНЕНО: Уменьшена минимальная ширина кнопок + constraints: BoxConstraints(minWidth: (MediaQuery.of(context).size.width - 160) / 2, minHeight: 40), // Adjusted width for dialog + selectedColor: Colors.white, + fillColor: isIncome ? Colors.green.shade400 : Colors.red.shade400, + color: isDark ? Colors.white70 : Colors.black54, + selectedBorderColor: isIncome ? Colors.green.shade600 : Colors.red.shade600, + borderColor: isDark ? Colors.grey.shade600 : Colors.grey.shade400, + children: const [ + Padding( + padding: EdgeInsets.symmetric(horizontal: 16.0), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ Icon(Icons.arrow_upward_rounded, size: 18), SizedBox(width: 8), Text('Расход'), ], + ), + ), + Padding( + padding: EdgeInsets.symmetric(horizontal: 16.0), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ Icon(Icons.arrow_downward_rounded, size: 18), SizedBox(width: 8), Text('Доход'), ], + ), + ), + ], + ), + ), + const SizedBox(height: 20), + + // --- Amount Field --- + TextFormField( + controller: _amountController, + decoration: InputDecoration( + labelText: 'Сумма', + prefixIcon: Icon(Icons.attach_money, color: isIncome ? Colors.green : theme.colorScheme.primary), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)), + filled: true, + fillColor: isDark ? Colors.grey.shade800.withOpacity(0.5) : Colors.grey.shade100, + ), + keyboardType: const TextInputType.numberWithOptions(decimal: true), + validator: (value) { + if (value == null || value.isEmpty) { + return 'Пожалуйста, введите сумму'; + } + if (double.tryParse(value) == null || double.parse(value) <= 0) { + return 'Пожалуйста, введите корректное положительное число'; + } + return null; + }, + ), + const SizedBox(height: 16), + + // --- Category Dropdown (Only for Expenses, uses StreamBuilder) --- + if (!isIncome) + StreamBuilder>( + stream: widget.categoriesStream, + builder: (context, snapshot) { + if (snapshot.connectionState == ConnectionState.waiting && !snapshot.hasData) { + return const Center(child: CircularProgressIndicator(strokeWidth: 2)); + } + if (snapshot.hasError) { + return Text('Ошибка загрузки категорий: ${snapshot.error}'); + } + + final categoriesFromDb = snapshot.data ?? []; + // Filter out 'Income' category for the dropdown + final expenseCategories = categoriesFromDb.where((c) => c.name != 'Income').toList(); + + // Ensure _selectedCategoryName is valid or reset it + if (_selectedCategoryName != null && !expenseCategories.any((c) => c.name == _selectedCategoryName)) { + _selectedCategoryName = null; // Reset if selected category is no longer valid + } + // Set default selection if nothing is selected and list is not empty + // This handles the case when switching from Income to Expense + if (_selectedCategoryName == null && expenseCategories.isNotEmpty) { + // Use WidgetsBinding to schedule state update after build + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) { // Check if widget is still mounted + setState(() { + _selectedCategoryName = expenseCategories[0].name; + }); + } + }); + } + + + return DropdownButtonFormField( + value: _selectedCategoryName, + decoration: InputDecoration( + labelText: 'Категория', + border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)), + filled: true, + fillColor: isDark ? Colors.grey.shade800.withOpacity(0.5) : Colors.grey.shade100, + contentPadding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 16.0), + ), + items: expenseCategories.map((db.CategoryDb category) { + final iconData = CategoryUtils.getIconFromString(category.icon); + final colorData = Color(category.color); + return DropdownMenuItem( + value: category.name, + child: Row( + children: [ + Icon(iconData, color: colorData, size: 20), + const SizedBox(width: 10), + Text(category.name), + ], + ), + ); + }).toList(), + onChanged: (String? newValue) { + setState(() { + _selectedCategoryName = newValue; + }); + }, + validator: (value) { + if (_selectedType == db.TransactionType.expense && value == null) { + return 'Пожалуйста, выберите категорию'; + } + return null; + }, + ); + }, + ), + if (!isIncome) const SizedBox(height: 16), + + // --- Date and Time Picker --- + InkWell( + onTap: () => _selectDateTime(context), + child: InputDecorator( + decoration: InputDecoration( + labelText: 'Дата и время', + prefixIcon: const Icon(Icons.calendar_today_outlined), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)), + filled: true, + fillColor: isDark ? Colors.grey.shade800.withOpacity(0.5) : Colors.grey.shade100, + ), + child: Text( + DateFormat.yMMMd().add_jm().format(_selectedDate), + style: theme.textTheme.bodyLarge, + ), + ), + ), + const SizedBox(height: 16), + + // --- Merchant / Source Field --- + TextFormField( + controller: _merchantController, + decoration: InputDecoration( + labelText: isIncome ? 'Источник' : 'Продавец / Магазин', + prefixIcon: Icon(isIncome ? Icons.source_outlined : Icons.storefront_outlined), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)), + filled: true, + fillColor: isDark ? Colors.grey.shade800.withOpacity(0.5) : Colors.grey.shade100, + ), + textCapitalization: TextCapitalization.words, + ), + ], + ), + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), // Close dialog + child: const Text('Отмена'), + ), + ElevatedButton( + onPressed: _updateTransaction, // Call update function + child: const Text('Сохранить'), + ), + ], + ); + } +} diff --git a/lib/widgets/expandable_section.dart b/lib/widgets/expandable_section.dart new file mode 100644 index 0000000..5a85b80 --- /dev/null +++ b/lib/widgets/expandable_section.dart @@ -0,0 +1,101 @@ +import 'package:flutter/material.dart'; + +class ExpandableSection extends StatelessWidget { + final String title; + final IconData icon; + final bool isExpanded; + final VoidCallback onTap; + final Widget child; + final Animation heightFactor; + + const ExpandableSection({ + Key? key, + required this.title, + required this.icon, + required this.isExpanded, + required this.onTap, + required this.heightFactor, + required this.child, + }) : super(key: key); + + @override + Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + + return Column( + children: [ + GestureDetector( + onTap: onTap, + child: Container( + width: double.infinity, + margin: const EdgeInsets.fromLTRB(16, 8, 16, 0), + padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 12.0), + decoration: BoxDecoration( + color: isDark ? Colors.grey.shade800 : Colors.green.shade100, + borderRadius: BorderRadius.vertical( + top: const Radius.circular(16), + bottom: Radius.circular(isExpanded ? 0 : 16), + ), + ), + child: Row( + children: [ + Icon( + icon, + color: isDark ? Colors.green.shade300 : Colors.green.shade800, + size: 20, + ), + const SizedBox(width: 8), + Text( + title, + style: TextStyle( + fontWeight: FontWeight.bold, + color: isDark ? Colors.green.shade300 : Colors.green.shade800, + ), + ), + const Spacer(), + AnimatedRotation( + turns: isExpanded ? 0.5 : 0, + duration: const Duration(milliseconds: 300), + child: Icon( + Icons.keyboard_arrow_down, + color: isDark ? Colors.green.shade300 : Colors.green.shade800, + ), + ), + ], + ), + ), + ), + AnimatedBuilder( + animation: heightFactor, + builder: (context, innerChild) { + return ClipRect( + child: Align( + heightFactor: heightFactor.value, + child: Container( + margin: const EdgeInsets.fromLTRB(16, 0, 16, 0), + decoration: BoxDecoration( + color: isDark ? const Color(0xFF1E1E1E) : Colors.white, + borderRadius: const BorderRadius.vertical( + bottom: Radius.circular(16), + ), + boxShadow: [ + BoxShadow( + color: isDark + ? Colors.black.withOpacity(0.3) + : Colors.green.withOpacity(0.1), + blurRadius: 8, + offset: const Offset(0, 4), + ), + ], + ), + child: innerChild, + ), + ), + ); + }, + child: child, + ), + ], + ); + } +} diff --git a/lib/widgets/filter_chip_widget.dart b/lib/widgets/filter_chip_widget.dart new file mode 100644 index 0000000..b70b752 --- /dev/null +++ b/lib/widgets/filter_chip_widget.dart @@ -0,0 +1,49 @@ +import 'package:flutter/material.dart'; + +class FilterChipWidget extends StatelessWidget { + final String label; + final bool isSelected; + final VoidCallback onTap; + + const FilterChipWidget({ + Key? key, + required this.label, + required this.isSelected, + required this.onTap, + }) : super(key: key); + + @override + Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + + return GestureDetector( + onTap: onTap, + child: Container( + margin: const EdgeInsets.only(right: 8), + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), // Smaller padding + decoration: BoxDecoration( + color: isSelected + ? (isDark ? Colors.green.shade700 : Colors.green.shade100) + : (isDark ? Colors.grey.shade800 : Colors.grey.shade200), + borderRadius: BorderRadius.circular(14), // Smaller radius + border: isSelected + ? Border.all( + color: isDark ? Colors.green.shade300 : Colors.green, + width: 1, + ) + : null, + ), + child: Text( + label, + style: TextStyle( + fontSize: 12, // Smaller text + fontWeight: isSelected ? FontWeight.bold : FontWeight.normal, + color: isSelected + ? (isDark ? Colors.white : Colors.green.shade700) + : (isDark ? Colors.white70 : Colors.grey.shade700), + ), + ), + ), + ); + } +} diff --git a/lib/widgets/spending_pie_chart.dart b/lib/widgets/spending_pie_chart.dart new file mode 100644 index 0000000..6643500 --- /dev/null +++ b/lib/widgets/spending_pie_chart.dart @@ -0,0 +1,318 @@ +import 'package:flutter/material.dart'; +import 'package:fl_chart/fl_chart.dart'; +import 'package:intl/intl.dart'; // For number formatting + +import '../models/category.dart'; // Keep using the Category model for UI structure + +// Changed to StatefulWidget to manage its own selection state +class SpendingPieChart extends StatefulWidget { + final List categories; // Expect List from database calculation + final double totalExpenses; + final Animation animation; // For fade/scale animation + + const SpendingPieChart({ + Key? key, + required this.categories, + required this.totalExpenses, + required this.animation, + // Removed selectedPieIndex and onSelectPieCategory + }) : super(key: key); + + @override + State createState() => _SpendingPieChartState(); +} + +class _SpendingPieChartState extends State { + // State for the selected index is now managed internally + int _selectedPieIndex = -1; + + // Handles selection logic internally + void _handlePieTap(int index) { + setState(() { + // If the same index is selected, deselect (-1), otherwise select the new index + _selectedPieIndex = (_selectedPieIndex == index) ? -1 : index; + }); + } + + @override + Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + final theme = Theme.of(context); + final currencyFormatter = NumberFormat.currency(locale: 'en_US', symbol: '\$'); // Or your preferred locale/symbol + + // Handle the case where there are no categories to display + if (widget.categories.isEmpty) { + return AnimatedBuilder( // Still use animation for consistency + animation: widget.animation, + builder: (context, child) => Opacity( + opacity: widget.animation.value, + child: Container( + height: 230, // Maintain similar height to the chart version + alignment: Alignment.center, + padding: const EdgeInsets.all(16), + child: Text( + 'No spending data for this period.', + textAlign: TextAlign.center, + style: theme.textTheme.bodyMedium?.copyWith(color: Colors.grey), + ), + ), + ), + ); + } + + // Use AnimatedBuilder to apply the fade/scale animation + return AnimatedBuilder( + animation: widget.animation, + builder: (context, child) { + return Transform.scale( + scale: widget.animation.value, // Apply scale animation + child: Opacity( + opacity: widget.animation.value, // Apply fade animation + child: Container( + padding: const EdgeInsets.symmetric(vertical: 8.0), // Reduced vertical padding + height: 230, // Fixed height for the chart and legend area + child: Row( + children: [ + // --- Pie Chart --- + Expanded( + flex: 5, // Give more space to the chart itself + child: Stack( // Use Stack to overlay text on the chart center + alignment: Alignment.center, + children: [ + PieChart( + PieChartData( + // Handle touch events on the pie chart + pieTouchData: PieTouchData( + touchCallback: (FlTouchEvent event, PieTouchResponse? pieTouchResponse) { + // We are only interested in TapUp events to trigger selection changes + if (event is FlTapUpEvent) { + final section = pieTouchResponse?.touchedSection; + if (section != null) { + // Tap occurred ON a section + final touchedIndex = section.touchedSectionIndex; + // Use internal handler to update state + _handlePieTap(touchedIndex); + } else { + // Tap occurred OUTSIDE any section + // Deselect if something was selected + if (_selectedPieIndex != -1) { + _handlePieTap(-1); // Pass -1 to deselect + } + } + } + }, + ), + borderData: FlBorderData(show: false), // No border around the chart + sectionsSpace: 2, // Space between slices + centerSpaceRadius: 50, // Radius of the center hole + sections: _generatePieSections(context), // Generate slices data + startDegreeOffset: -90, // Start chart from the top (12 o'clock) + ), + // Optional animation when data changes + swapAnimationDuration: const Duration(milliseconds: 250), + swapAnimationCurve: Curves.easeInOut, + ), + // --- Center Text (Displayed when a slice is selected) --- + if (_selectedPieIndex != -1) + _buildCenterText(context, currencyFormatter) + else // Optional: Display total or default text when nothing is selected + _buildDefaultCenterText(context, currencyFormatter), + ], + ), + ), + const SizedBox(width: 8), // Spacing between chart and legend + + // --- Legend --- + Expanded( + flex: 4, // Allocate space for the legend + // Use ListView for scrollable legend if many categories + child: ListView.builder( + itemCount: widget.categories.length, + padding: const EdgeInsets.only(right: 8), // Padding for legend items + itemBuilder: (context, index) => _buildPieLegendItem(context, index), + ), + ), + ], + ), + ), + ), + ); + }, + ); + } + + // Builds the text displayed in the center when a slice is selected + Widget _buildCenterText(BuildContext context, NumberFormat formatter) { + final theme = Theme.of(context); + // Check if selectedPieIndex is valid before accessing categories + if (_selectedPieIndex < 0 || _selectedPieIndex >= widget.categories.length) { + // Return an empty container or default text if index is invalid + return _buildDefaultCenterText(context, formatter); + } + final selectedCategory = widget.categories[_selectedPieIndex]; + return Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text( + selectedCategory.name, + style: theme.textTheme.bodyMedium?.copyWith( + fontWeight: FontWeight.bold, + color: theme.textTheme.bodyLarge?.color?.withOpacity(0.8), + ), + textAlign: TextAlign.center, + overflow: TextOverflow.ellipsis, + ), + const SizedBox(height: 4), + Text( + formatter.format(selectedCategory.amount), // Format the amount as currency + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.bold, + color: selectedCategory.colorCode, // Use category color for amount + ), + textAlign: TextAlign.center, + ), + ], + ); + } + + // Builds the default text displayed in the center when no slice is selected + Widget _buildDefaultCenterText(BuildContext context, NumberFormat formatter) { + final theme = Theme.of(context); + return Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text( + 'Total', // Label for the total amount + style: theme.textTheme.bodyMedium?.copyWith( + fontWeight: FontWeight.bold, + color: theme.textTheme.bodyLarge?.color?.withOpacity(0.7), + ), + textAlign: TextAlign.center, + ), + const SizedBox(height: 4), + Text( + formatter.format(widget.totalExpenses), // Display total expenses + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.bold, + color: theme.textTheme.bodyLarge?.color // Use default text color + ), + textAlign: TextAlign.center, + ), + ], + ); + } + + + // Builds a single item for the legend + Widget _buildPieLegendItem(BuildContext context, int index) { + final isDark = Theme.of(context).brightness == Brightness.dark; + final theme = Theme.of(context); + final isSelected = index == _selectedPieIndex; // Check if this item is selected using internal state + // Check if index is valid before accessing categories + if (index < 0 || index >= widget.categories.length) { + return const SizedBox.shrink(); // Return empty if index is invalid + } + final category = widget.categories[index]; + // Calculate percentage, handle totalExpenses being zero + final percentage = widget.totalExpenses > 0 ? (category.amount / widget.totalExpenses * 100) : 0.0; + + // Use InkWell for tap feedback and GestureDetector for tap logic + return InkWell( + onTap: () => _handlePieTap(index), // Use internal handler on tap + borderRadius: BorderRadius.circular(8), // Match border radius + child: AnimatedContainer( + duration: const Duration(milliseconds: 200), // Animation for selection change + margin: const EdgeInsets.symmetric(vertical: 3.0), // Spacing between legend items + padding: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0), // Padding inside item + decoration: BoxDecoration( + // Highlight background if selected + color: isSelected + ? category.colorCode.withOpacity(isDark ? 0.3 : 0.15) + : Colors.transparent, + borderRadius: BorderRadius.circular(8), + // Add border if selected + border: Border.all( + color: isSelected ? category.colorCode.withOpacity(0.8) : Colors.transparent, + width: 1.5, + ), + ), + child: Row( + children: [ + // Color indicator dot + Container( + width: 10, + height: 10, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: category.colorCode.withOpacity(isDark ? 0.9 : 1.0), // Use category color + ), + ), + const SizedBox(width: 8), // Spacing + // Category name + Expanded( + child: Text( + category.name, + style: theme.textTheme.bodyMedium?.copyWith( + fontWeight: isSelected ? FontWeight.bold : FontWeight.normal, // Bold if selected + color: theme.textTheme.bodyLarge?.color, // Use default body text color + ), + overflow: TextOverflow.ellipsis, // Prevent long names from wrapping + ), + ), + const SizedBox(width: 8), // Spacing + // Percentage text + Text( + '${percentage.toStringAsFixed(1)}%', // Format percentage + style: theme.textTheme.bodySmall?.copyWith( + fontWeight: isSelected ? FontWeight.bold : FontWeight.normal, // Bold if selected + color: theme.textTheme.bodyMedium?.color?.withOpacity(0.7), // Slightly faded color + ), + ), + ], + ), + ), + ); + } + + // Generates the data for each slice (PieChartSectionData) of the pie chart + List _generatePieSections(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + + return List.generate(widget.categories.length, (i) { + // Check if index is valid before accessing categories + if (i < 0 || i >= widget.categories.length) { + // This should ideally not happen if List.generate is used correctly, + // but adding a safeguard. + return PieChartSectionData(); // Return an empty section + } + final isTouched = i == _selectedPieIndex; // Check if this slice is selected using internal state + // Make selected slice slightly larger + final double radius = isTouched ? 65 : 55; + // Make title font slightly larger when selected + final double titleFontSize = isTouched ? 14 : 12; + final category = widget.categories[i]; + // Calculate percentage for the title + final percentage = widget.totalExpenses > 0 ? (category.amount / widget.totalExpenses * 100) : 0; + + return PieChartSectionData( + color: category.colorCode.withOpacity(isDark ? 0.85 : 1.0), // Use category color + value: category.amount, // Value determines the slice size + title: '${percentage.toStringAsFixed(0)}%', // Display percentage as title + radius: radius, // Apply radius (larger if touched) + titleStyle: TextStyle( + fontSize: titleFontSize, // Apply font size (larger if touched) + fontWeight: FontWeight.bold, + color: Colors.white.withOpacity(0.9), // White text for contrast on colored slices + shadows: const [Shadow(color: Colors.black38, blurRadius: 2)], // Subtle shadow for readability + ), + // Add border to selected slice for emphasis + borderSide: isTouched + ? BorderSide(color: isDark ? Colors.white60 : Colors.black54, width: 2) + : BorderSide(color: category.colorCode.withOpacity(0.5), width: 1), + // Optional: Add badge (icon) to the selected slice + // badgeWidget: isTouched ? Icon(category.icon, color: Colors.white, size: 16) : null, + // badgePositionPercentageOffset: .98, + ); + }); + } +} diff --git a/lib/widgets/summary_item.dart b/lib/widgets/summary_item.dart new file mode 100644 index 0000000..1e7a9ad --- /dev/null +++ b/lib/widgets/summary_item.dart @@ -0,0 +1,51 @@ +import 'package:flutter/material.dart'; + +class SummaryItem extends StatelessWidget { + final IconData icon; + final String title; + final String amount; + final Color color; + + const SummaryItem({ + Key? key, + required this.icon, + required this.title, + required this.amount, + required this.color, + }) : super(key: key); + + @override + Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + return Column( + children: [ + Row( + children: [ + Icon( + icon, + size: 16, + color: isDark ? color.withOpacity(0.8) : color, + ), + const SizedBox(width: 4), + Text( + title, + style: TextStyle( + fontSize: 13, + color: isDark ? Colors.grey.shade400 : Colors.grey.shade700, + ), + ), + ], + ), + const SizedBox(height: 4), + Text( + amount, + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.bold, + color: isDark ? Colors.white : Colors.black87, + ), + ), + ], + ); + } +} diff --git a/lib/widgets/transaction_list_item.dart b/lib/widgets/transaction_list_item.dart new file mode 100644 index 0000000..78fb100 --- /dev/null +++ b/lib/widgets/transaction_list_item.dart @@ -0,0 +1,148 @@ +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; // For date formatting + +import '../models/transaction_record.dart'; // Use the model class + +class TransactionListItem extends StatelessWidget { + final TransactionRecord transaction; // Use the model class + final VoidCallback? onEdit; // Callback for edit action + final VoidCallback? onDelete; // Callback for delete action + + const TransactionListItem({ + Key? key, + required this.transaction, + this.onEdit, // Make callbacks optional + this.onDelete, + }) : super(key: key); + + // Function to show the options menu + void _showOptionsMenu(BuildContext context) { + showModalBottomSheet( + context: context, + builder: (context) { + return SafeArea( // Use SafeArea to avoid system UI + child: Column( + mainAxisSize: MainAxisSize.min, // Take minimum space + children: [ + ListTile( + leading: const Icon(Icons.edit_outlined), + title: const Text('Редактировать'), + onTap: () { + Navigator.pop(context); // Close the bottom sheet + onEdit?.call(); // Call the edit callback if it exists + }, + ), + ListTile( + leading: const Icon(Icons.delete_outline, color: Colors.red), + title: const Text('Удалить', style: TextStyle(color: Colors.red)), + onTap: () { + Navigator.pop(context); // Close the bottom sheet + onDelete?.call(); // Call the delete callback if it exists + }, + ), + // Optional: Add a Cancel button + ListTile( + leading: const Icon(Icons.cancel_outlined), + title: const Text('Отмена'), + onTap: () => Navigator.pop(context), + ), + ], + ), + ); + }, + ); + } + + + @override + Widget build(BuildContext context) { + final isExpense = transaction.type == 'expense'; + final theme = Theme.of(context); + + // Wrap the ListTile in an InkWell to handle long press + return InkWell( + onLongPress: () => _showOptionsMenu(context), // Show menu on long press + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 12.0), // Adjusted padding + child: Row( + children: [ + // Category Icon (only for expenses) + if (isExpense && transaction.category != null) + Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: transaction.category!.colorCode.withOpacity(0.1), // Use category color + shape: BoxShape.circle, + ), + child: Icon( + transaction.category!.iconCode, // Use category icon + color: transaction.category!.colorCode, + size: 20, + ), + ) + else if (!isExpense) // Icon for Income + Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: Colors.green.shade100, // Specific color for income icon background + shape: BoxShape.circle, + ), + child: Icon( + Icons.attach_money_outlined, // Specific icon for income + color: Colors.green.shade700, + size: 20, + ), + ), + const SizedBox(width: 16), // Space between icon and text + + // Transaction Details (Category/Merchant, Date) + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + isExpense ? transaction.merchant : transaction.merchant, // Display merchant for both for now + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.w500, // Medium weight + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, // Prevent overflow + ), + const SizedBox(height: 4), + Text( + // Display category name for expense, or 'Income' for income + isExpense ? transaction.category?.name ?? 'Unknown Category' : 'Income', + style: theme.textTheme.bodySmall?.copyWith( + color: theme.textTheme.bodySmall?.color?.withOpacity(0.7), // Subtle color + ), + ), + ], + ), + ), + + // Amount and Date + Column( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Text( + '${isExpense ? '-' : '+'} \$${NumberFormat.currency(symbol: '', decimalDigits: 2).format(transaction.amount)}', // Format amount with sign + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.bold, + color: isExpense ? Colors.red.shade600 : Colors.green.shade600, // Color based on type + ), + ), + const SizedBox(height: 4), + Text( + DateFormat('MMM d, yyyy').format(transaction.date), // Format date + style: theme.textTheme.bodySmall?.copyWith( + color: theme.textTheme.bodySmall?.color?.withOpacity(0.7), // Subtle color + ), + ), + ], + ), + ], + ), + ), + ); + } +} diff --git a/linux/.gitignore b/linux/.gitignore new file mode 100644 index 0000000..d3896c9 --- /dev/null +++ b/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/linux/CMakeLists.txt b/linux/CMakeLists.txt new file mode 100644 index 0000000..4425a8f --- /dev/null +++ b/linux/CMakeLists.txt @@ -0,0 +1,128 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "finance_app_2") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "ru.sanders.finance_app_2") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Load bundled libraries from the lib/ directory relative to the binary. +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Root filesystem for cross-building. +if(FLUTTER_TARGET_PLATFORM_SYSROOT) + set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +endif() + +# Define build configuration options. +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") +endif() + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_14) + target_compile_options(${TARGET} PRIVATE -Wall -Werror) + target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) + +# Only the install-generated bundle's copy of the executable will launch +# correctly, since the resources must in the right relative locations. To avoid +# people trying to run the unbundled copy, put it in a subdirectory instead of +# the default top-level location. +set_target_properties(${BINARY_NAME} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" +) + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +# Start with a clean build bundle directory every time. +install(CODE " + file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") + " COMPONENT Runtime) + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) + install(FILES "${bundled_library}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endforeach(bundled_library) + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/linux/flutter/CMakeLists.txt b/linux/flutter/CMakeLists.txt new file mode 100644 index 0000000..d5bd016 --- /dev/null +++ b/linux/flutter/CMakeLists.txt @@ -0,0 +1,88 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.10) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) +pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) +pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) + +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "fl_basic_message_channel.h" + "fl_binary_codec.h" + "fl_binary_messenger.h" + "fl_dart_project.h" + "fl_engine.h" + "fl_json_message_codec.h" + "fl_json_method_codec.h" + "fl_message_codec.h" + "fl_method_call.h" + "fl_method_channel.h" + "fl_method_codec.h" + "fl_method_response.h" + "fl_plugin_registrar.h" + "fl_plugin_registry.h" + "fl_standard_message_codec.h" + "fl_standard_method_codec.h" + "fl_string_codec.h" + "fl_value.h" + "fl_view.h" + "flutter_linux.h" +) +list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +target_link_libraries(flutter INTERFACE + PkgConfig::GTK + PkgConfig::GLIB + PkgConfig::GIO +) +add_dependencies(flutter flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/linux/flutter/generated_plugin_registrant.cc b/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..2c1ec4f --- /dev/null +++ b/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include + +void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) sqlite3_flutter_libs_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "Sqlite3FlutterLibsPlugin"); + sqlite3_flutter_libs_plugin_register_with_registrar(sqlite3_flutter_libs_registrar); +} diff --git a/linux/flutter/generated_plugin_registrant.h b/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..e0f0a47 --- /dev/null +++ b/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/linux/flutter/generated_plugins.cmake b/linux/flutter/generated_plugins.cmake new file mode 100644 index 0000000..7ea2a80 --- /dev/null +++ b/linux/flutter/generated_plugins.cmake @@ -0,0 +1,24 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + sqlite3_flutter_libs +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/linux/runner/CMakeLists.txt b/linux/runner/CMakeLists.txt new file mode 100644 index 0000000..e97dabc --- /dev/null +++ b/linux/runner/CMakeLists.txt @@ -0,0 +1,26 @@ +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} + "main.cc" + "my_application.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the application ID. +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Add dependency libraries. Add any application-specific dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) + +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") diff --git a/linux/runner/main.cc b/linux/runner/main.cc new file mode 100644 index 0000000..e7c5c54 --- /dev/null +++ b/linux/runner/main.cc @@ -0,0 +1,6 @@ +#include "my_application.h" + +int main(int argc, char** argv) { + g_autoptr(MyApplication) app = my_application_new(); + return g_application_run(G_APPLICATION(app), argc, argv); +} diff --git a/linux/runner/my_application.cc b/linux/runner/my_application.cc new file mode 100644 index 0000000..a60f51d --- /dev/null +++ b/linux/runner/my_application.cc @@ -0,0 +1,130 @@ +#include "my_application.h" + +#include +#ifdef GDK_WINDOWING_X11 +#include +#endif + +#include "flutter/generated_plugin_registrant.h" + +struct _MyApplication { + GtkApplication parent_instance; + char** dart_entrypoint_arguments; +}; + +G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) + +// Implements GApplication::activate. +static void my_application_activate(GApplication* application) { + MyApplication* self = MY_APPLICATION(application); + GtkWindow* window = + GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); + + // Use a header bar when running in GNOME as this is the common style used + // by applications and is the setup most users will be using (e.g. Ubuntu + // desktop). + // If running on X and not using GNOME then just use a traditional title bar + // in case the window manager does more exotic layout, e.g. tiling. + // If running on Wayland assume the header bar will work (may need changing + // if future cases occur). + gboolean use_header_bar = TRUE; +#ifdef GDK_WINDOWING_X11 + GdkScreen* screen = gtk_window_get_screen(window); + if (GDK_IS_X11_SCREEN(screen)) { + const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); + if (g_strcmp0(wm_name, "GNOME Shell") != 0) { + use_header_bar = FALSE; + } + } +#endif + if (use_header_bar) { + GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); + gtk_widget_show(GTK_WIDGET(header_bar)); + gtk_header_bar_set_title(header_bar, "finance_app_2"); + gtk_header_bar_set_show_close_button(header_bar, TRUE); + gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); + } else { + gtk_window_set_title(window, "finance_app_2"); + } + + gtk_window_set_default_size(window, 1280, 720); + gtk_widget_show(GTK_WIDGET(window)); + + g_autoptr(FlDartProject) project = fl_dart_project_new(); + fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments); + + FlView* view = fl_view_new(project); + gtk_widget_show(GTK_WIDGET(view)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + + gtk_widget_grab_focus(GTK_WIDGET(view)); +} + +// Implements GApplication::local_command_line. +static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) { + MyApplication* self = MY_APPLICATION(application); + // Strip out the first argument as it is the binary name. + self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); + + g_autoptr(GError) error = nullptr; + if (!g_application_register(application, nullptr, &error)) { + g_warning("Failed to register: %s", error->message); + *exit_status = 1; + return TRUE; + } + + g_application_activate(application); + *exit_status = 0; + + return TRUE; +} + +// Implements GApplication::startup. +static void my_application_startup(GApplication* application) { + //MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application startup. + + G_APPLICATION_CLASS(my_application_parent_class)->startup(application); +} + +// Implements GApplication::shutdown. +static void my_application_shutdown(GApplication* application) { + //MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application shutdown. + + G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application); +} + +// Implements GObject::dispose. +static void my_application_dispose(GObject* object) { + MyApplication* self = MY_APPLICATION(object); + g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); + G_OBJECT_CLASS(my_application_parent_class)->dispose(object); +} + +static void my_application_class_init(MyApplicationClass* klass) { + G_APPLICATION_CLASS(klass)->activate = my_application_activate; + G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line; + G_APPLICATION_CLASS(klass)->startup = my_application_startup; + G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown; + G_OBJECT_CLASS(klass)->dispose = my_application_dispose; +} + +static void my_application_init(MyApplication* self) {} + +MyApplication* my_application_new() { + // Set the program name to the application ID, which helps various systems + // like GTK and desktop environments map this running application to its + // corresponding .desktop file. This ensures better integration by allowing + // the application to be recognized beyond its binary name. + g_set_prgname(APPLICATION_ID); + + return MY_APPLICATION(g_object_new(my_application_get_type(), + "application-id", APPLICATION_ID, + "flags", G_APPLICATION_NON_UNIQUE, + nullptr)); +} diff --git a/linux/runner/my_application.h b/linux/runner/my_application.h new file mode 100644 index 0000000..72271d5 --- /dev/null +++ b/linux/runner/my_application.h @@ -0,0 +1,18 @@ +#ifndef FLUTTER_MY_APPLICATION_H_ +#define FLUTTER_MY_APPLICATION_H_ + +#include + +G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION, + GtkApplication) + +/** + * my_application_new: + * + * Creates a new Flutter-based application. + * + * Returns: a new #MyApplication. + */ +MyApplication* my_application_new(); + +#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/macos/.gitignore b/macos/.gitignore new file mode 100644 index 0000000..746adbb --- /dev/null +++ b/macos/.gitignore @@ -0,0 +1,7 @@ +# Flutter-related +**/Flutter/ephemeral/ +**/Pods/ + +# Xcode-related +**/dgph +**/xcuserdata/ diff --git a/macos/Flutter/Flutter-Debug.xcconfig b/macos/Flutter/Flutter-Debug.xcconfig new file mode 100644 index 0000000..c2efd0b --- /dev/null +++ b/macos/Flutter/Flutter-Debug.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/macos/Flutter/Flutter-Release.xcconfig b/macos/Flutter/Flutter-Release.xcconfig new file mode 100644 index 0000000..c2efd0b --- /dev/null +++ b/macos/Flutter/Flutter-Release.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift new file mode 100644 index 0000000..d24cdf2 --- /dev/null +++ b/macos/Flutter/GeneratedPluginRegistrant.swift @@ -0,0 +1,18 @@ +// +// Generated file. Do not edit. +// + +import FlutterMacOS +import Foundation + +import flutter_web_auth +import path_provider_foundation +import shared_preferences_foundation +import sqlite3_flutter_libs + +func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + FlutterWebAuthPlugin.register(with: registry.registrar(forPlugin: "FlutterWebAuthPlugin")) + PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin")) + SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) + Sqlite3FlutterLibsPlugin.register(with: registry.registrar(forPlugin: "Sqlite3FlutterLibsPlugin")) +} diff --git a/macos/Runner.xcodeproj/project.pbxproj b/macos/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..773a430 --- /dev/null +++ b/macos/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,705 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXAggregateTarget section */ + 33CC111A2044C6BA0003C045 /* Flutter Assemble */ = { + isa = PBXAggregateTarget; + buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */; + buildPhases = ( + 33CC111E2044C6BF0003C045 /* ShellScript */, + ); + dependencies = ( + ); + name = "Flutter Assemble"; + productName = FLX; + }; +/* End PBXAggregateTarget section */ + +/* Begin PBXBuildFile section */ + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; }; + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC10EC2044A3C60003C045; + remoteInfo = Runner; + }; + 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC111A2044C6BA0003C045; + remoteInfo = FLX; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 33CC110E2044A8840003C045 /* Bundle Framework */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Bundle Framework"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; + 33CC10ED2044A3C60003C045 /* finance_app_2.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "finance_app_2.app"; sourceTree = BUILT_PRODUCTS_DIR; }; + 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = ""; }; + 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; + 33CC10F72044A3C60003C045 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = Runner/Info.plist; sourceTree = ""; }; + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainFlutterWindow.swift; sourceTree = ""; }; + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Debug.xcconfig"; sourceTree = ""; }; + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Release.xcconfig"; sourceTree = ""; }; + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Flutter-Generated.xcconfig"; path = "ephemeral/Flutter-Generated.xcconfig"; sourceTree = ""; }; + 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; + 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; + 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 331C80D2294CF70F00263BE5 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EA2044A3C60003C045 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C80D6294CF71000263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C80D7294CF71000263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 33BA886A226E78AF003329D5 /* Configs */ = { + isa = PBXGroup; + children = ( + 33E5194F232828860026EE4D /* AppInfo.xcconfig */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */, + ); + path = Configs; + sourceTree = ""; + }; + 33CC10E42044A3C60003C045 = { + isa = PBXGroup; + children = ( + 33FAB671232836740065AC1E /* Runner */, + 33CEB47122A05771004F2AC0 /* Flutter */, + 331C80D6294CF71000263BE5 /* RunnerTests */, + 33CC10EE2044A3C60003C045 /* Products */, + D73912EC22F37F3D000D13A0 /* Frameworks */, + ); + sourceTree = ""; + }; + 33CC10EE2044A3C60003C045 /* Products */ = { + isa = PBXGroup; + children = ( + 33CC10ED2044A3C60003C045 /* finance_app_2.app */, + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 33CC11242044D66E0003C045 /* Resources */ = { + isa = PBXGroup; + children = ( + 33CC10F22044A3C60003C045 /* Assets.xcassets */, + 33CC10F42044A3C60003C045 /* MainMenu.xib */, + 33CC10F72044A3C60003C045 /* Info.plist */, + ); + name = Resources; + path = ..; + sourceTree = ""; + }; + 33CEB47122A05771004F2AC0 /* Flutter */ = { + isa = PBXGroup; + children = ( + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */, + ); + path = Flutter; + sourceTree = ""; + }; + 33FAB671232836740065AC1E /* Runner */ = { + isa = PBXGroup; + children = ( + 33CC10F02044A3C60003C045 /* AppDelegate.swift */, + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */, + 33E51913231747F40026EE4D /* DebugProfile.entitlements */, + 33E51914231749380026EE4D /* Release.entitlements */, + 33CC11242044D66E0003C045 /* Resources */, + 33BA886A226E78AF003329D5 /* Configs */, + ); + path = Runner; + sourceTree = ""; + }; + D73912EC22F37F3D000D13A0 /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C80D4294CF70F00263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C80D1294CF70F00263BE5 /* Sources */, + 331C80D2294CF70F00263BE5 /* Frameworks */, + 331C80D3294CF70F00263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C80DA294CF71000263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C80D5294CF71000263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 33CC10EC2044A3C60003C045 /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 33CC10E92044A3C60003C045 /* Sources */, + 33CC10EA2044A3C60003C045 /* Frameworks */, + 33CC10EB2044A3C60003C045 /* Resources */, + 33CC110E2044A8840003C045 /* Bundle Framework */, + 3399D490228B24CF009A79C7 /* ShellScript */, + ); + buildRules = ( + ); + dependencies = ( + 33CC11202044C79F0003C045 /* PBXTargetDependency */, + ); + name = Runner; + productName = Runner; + productReference = 33CC10ED2044A3C60003C045 /* finance_app_2.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 33CC10E52044A3C60003C045 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastSwiftUpdateCheck = 0920; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C80D4294CF70F00263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 33CC10EC2044A3C60003C045; + }; + 33CC10EC2044A3C60003C045 = { + CreatedOnToolsVersion = 9.2; + LastSwiftMigration = 1100; + ProvisioningStyle = Automatic; + SystemCapabilities = { + com.apple.Sandbox = { + enabled = 1; + }; + }; + }; + 33CC111A2044C6BA0003C045 = { + CreatedOnToolsVersion = 9.2; + ProvisioningStyle = Manual; + }; + }; + }; + buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 33CC10E42044A3C60003C045; + productRefGroup = 33CC10EE2044A3C60003C045 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 33CC10EC2044A3C60003C045 /* Runner */, + 331C80D4294CF70F00263BE5 /* RunnerTests */, + 33CC111A2044C6BA0003C045 /* Flutter Assemble */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C80D3294CF70F00263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EB2044A3C60003C045 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */, + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3399D490228B24CF009A79C7 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n"; + }; + 33CC111E2044C6BF0003C045 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + Flutter/ephemeral/FlutterInputs.xcfilelist, + ); + inputPaths = ( + Flutter/ephemeral/tripwire, + ); + outputFileListPaths = ( + Flutter/ephemeral/FlutterOutputs.xcfilelist, + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C80D1294CF70F00263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10E92044A3C60003C045 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */, + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */, + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C80DA294CF71000263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC10EC2044A3C60003C045 /* Runner */; + targetProxy = 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */; + }; + 33CC11202044C79F0003C045 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */; + targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 33CC10F42044A3C60003C045 /* MainMenu.xib */ = { + isa = PBXVariantGroup; + children = ( + 33CC10F52044A3C60003C045 /* Base */, + ); + name = MainMenu.xib; + path = Runner; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 331C80DB294CF71000263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = ru.sanders.financeApp2.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/finance_app_2.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/finance_app_2"; + }; + name = Debug; + }; + 331C80DC294CF71000263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = ru.sanders.financeApp2.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/finance_app_2.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/finance_app_2"; + }; + name = Release; + }; + 331C80DD294CF71000263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = ru.sanders.financeApp2.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/finance_app_2.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/finance_app_2"; + }; + name = Profile; + }; + 338D0CE9231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.14; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Profile; + }; + 338D0CEA231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Profile; + }; + 338D0CEB231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Profile; + }; + 33CC10F92044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.14; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 33CC10FA2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.14; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; + 33CC10FC2044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + 33CC10FD2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + 33CC111C2044C6BA0003C045 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + 33CC111D2044C6BA0003C045 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C80DB294CF71000263BE5 /* Debug */, + 331C80DC294CF71000263BE5 /* Release */, + 331C80DD294CF71000263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10F92044A3C60003C045 /* Debug */, + 33CC10FA2044A3C60003C045 /* Release */, + 338D0CE9231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10FC2044A3C60003C045 /* Debug */, + 33CC10FD2044A3C60003C045 /* Release */, + 338D0CEA231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC111C2044C6BA0003C045 /* Debug */, + 33CC111D2044C6BA0003C045 /* Release */, + 338D0CEB231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 33CC10E52044A3C60003C045 /* Project object */; +} diff --git a/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..21b83e4 --- /dev/null +++ b/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,99 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macos/Runner.xcworkspace/contents.xcworkspacedata b/macos/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/macos/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/macos/Runner/AppDelegate.swift b/macos/Runner/AppDelegate.swift new file mode 100644 index 0000000..b3c1761 --- /dev/null +++ b/macos/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import Cocoa +import FlutterMacOS + +@main +class AppDelegate: FlutterAppDelegate { + override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { + return true + } + + override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { + return true + } +} diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..a2ec33f --- /dev/null +++ b/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,68 @@ +{ + "images" : [ + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_16.png", + "scale" : "1x" + }, + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "2x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "1x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_64.png", + "scale" : "2x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_128.png", + "scale" : "1x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "2x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "1x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "2x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "1x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_1024.png", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png new file mode 100644 index 0000000..82b6f9d Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png new file mode 100644 index 0000000..13b35eb Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png new file mode 100644 index 0000000..0a3f5fa Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png new file mode 100644 index 0000000..bdb5722 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png new file mode 100644 index 0000000..f083318 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png new file mode 100644 index 0000000..326c0e7 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png new file mode 100644 index 0000000..2f1632c Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png differ diff --git a/macos/Runner/Base.lproj/MainMenu.xib b/macos/Runner/Base.lproj/MainMenu.xib new file mode 100644 index 0000000..80e867a --- /dev/null +++ b/macos/Runner/Base.lproj/MainMenu.xib @@ -0,0 +1,343 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macos/Runner/Configs/AppInfo.xcconfig b/macos/Runner/Configs/AppInfo.xcconfig new file mode 100644 index 0000000..1fbe404 --- /dev/null +++ b/macos/Runner/Configs/AppInfo.xcconfig @@ -0,0 +1,14 @@ +// Application-level settings for the Runner target. +// +// This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the +// future. If not, the values below would default to using the project name when this becomes a +// 'flutter create' template. + +// The application's name. By default this is also the title of the Flutter window. +PRODUCT_NAME = finance_app_2 + +// The application's bundle identifier +PRODUCT_BUNDLE_IDENTIFIER = ru.sanders.financeApp2 + +// The copyright displayed in application information +PRODUCT_COPYRIGHT = Copyright © 2025 ru.sanders. All rights reserved. diff --git a/macos/Runner/Configs/Debug.xcconfig b/macos/Runner/Configs/Debug.xcconfig new file mode 100644 index 0000000..36b0fd9 --- /dev/null +++ b/macos/Runner/Configs/Debug.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Debug.xcconfig" +#include "Warnings.xcconfig" diff --git a/macos/Runner/Configs/Release.xcconfig b/macos/Runner/Configs/Release.xcconfig new file mode 100644 index 0000000..dff4f49 --- /dev/null +++ b/macos/Runner/Configs/Release.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Release.xcconfig" +#include "Warnings.xcconfig" diff --git a/macos/Runner/Configs/Warnings.xcconfig b/macos/Runner/Configs/Warnings.xcconfig new file mode 100644 index 0000000..42bcbf4 --- /dev/null +++ b/macos/Runner/Configs/Warnings.xcconfig @@ -0,0 +1,13 @@ +WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings +GCC_WARN_UNDECLARED_SELECTOR = YES +CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES +CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE +CLANG_WARN__DUPLICATE_METHOD_MATCH = YES +CLANG_WARN_PRAGMA_PACK = YES +CLANG_WARN_STRICT_PROTOTYPES = YES +CLANG_WARN_COMMA = YES +GCC_WARN_STRICT_SELECTOR_MATCH = YES +CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES +CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES +GCC_WARN_SHADOW = YES +CLANG_WARN_UNREACHABLE_CODE = YES diff --git a/macos/Runner/DebugProfile.entitlements b/macos/Runner/DebugProfile.entitlements new file mode 100644 index 0000000..dddb8a3 --- /dev/null +++ b/macos/Runner/DebugProfile.entitlements @@ -0,0 +1,12 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.cs.allow-jit + + com.apple.security.network.server + + + diff --git a/macos/Runner/Info.plist b/macos/Runner/Info.plist new file mode 100644 index 0000000..4789daa --- /dev/null +++ b/macos/Runner/Info.plist @@ -0,0 +1,32 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIconFile + + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSMinimumSystemVersion + $(MACOSX_DEPLOYMENT_TARGET) + NSHumanReadableCopyright + $(PRODUCT_COPYRIGHT) + NSMainNibFile + MainMenu + NSPrincipalClass + NSApplication + + diff --git a/macos/Runner/MainFlutterWindow.swift b/macos/Runner/MainFlutterWindow.swift new file mode 100644 index 0000000..3cc05eb --- /dev/null +++ b/macos/Runner/MainFlutterWindow.swift @@ -0,0 +1,15 @@ +import Cocoa +import FlutterMacOS + +class MainFlutterWindow: NSWindow { + override func awakeFromNib() { + let flutterViewController = FlutterViewController() + let windowFrame = self.frame + self.contentViewController = flutterViewController + self.setFrame(windowFrame, display: true) + + RegisterGeneratedPlugins(registry: flutterViewController) + + super.awakeFromNib() + } +} diff --git a/macos/Runner/Release.entitlements b/macos/Runner/Release.entitlements new file mode 100644 index 0000000..852fa1a --- /dev/null +++ b/macos/Runner/Release.entitlements @@ -0,0 +1,8 @@ + + + + + com.apple.security.app-sandbox + + + diff --git a/macos/RunnerTests/RunnerTests.swift b/macos/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..61f3bd1 --- /dev/null +++ b/macos/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Cocoa +import FlutterMacOS +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/pubspec.lock b/pubspec.lock new file mode 100644 index 0000000..2032265 --- /dev/null +++ b/pubspec.lock @@ -0,0 +1,802 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + _fe_analyzer_shared: + dependency: transitive + description: + name: _fe_analyzer_shared + sha256: e55636ed79578b9abca5fecf9437947798f5ef7456308b5cb85720b793eac92f + url: "https://pub.dev" + source: hosted + version: "82.0.0" + analyzer: + dependency: transitive + description: + name: analyzer + sha256: "904ae5bb474d32c38fb9482e2d925d5454cda04ddd0e55d2e6826bc72f6ba8c0" + url: "https://pub.dev" + source: hosted + version: "7.4.5" + args: + dependency: transitive + description: + name: args + sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04 + url: "https://pub.dev" + source: hosted + version: "2.7.0" + async: + dependency: transitive + description: + name: async + sha256: d2872f9c19731c2e5f10444b14686eb7cc85c76274bd6c16e1816bff9a3bab63 + url: "https://pub.dev" + source: hosted + version: "2.12.0" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + build: + dependency: transitive + description: + name: build + sha256: cef23f1eda9b57566c81e2133d196f8e3df48f244b317368d65c5943d91148f0 + url: "https://pub.dev" + source: hosted + version: "2.4.2" + build_config: + dependency: transitive + description: + name: build_config + sha256: "4ae2de3e1e67ea270081eaee972e1bd8f027d459f249e0f1186730784c2e7e33" + url: "https://pub.dev" + source: hosted + version: "1.1.2" + build_daemon: + dependency: transitive + description: + name: build_daemon + sha256: "8e928697a82be082206edb0b9c99c5a4ad6bc31c9e9b8b2f291ae65cd4a25daa" + url: "https://pub.dev" + source: hosted + version: "4.0.4" + build_resolvers: + dependency: transitive + description: + name: build_resolvers + sha256: b9e4fda21d846e192628e7a4f6deda6888c36b5b69ba02ff291a01fd529140f0 + url: "https://pub.dev" + source: hosted + version: "2.4.4" + build_runner: + dependency: "direct dev" + description: + name: build_runner + sha256: "058fe9dce1de7d69c4b84fada934df3e0153dd000758c4d65964d0166779aa99" + url: "https://pub.dev" + source: hosted + version: "2.4.15" + build_runner_core: + dependency: transitive + description: + name: build_runner_core + sha256: "22e3aa1c80e0ada3722fe5b63fd43d9c8990759d0a2cf489c8c5d7b2bdebc021" + url: "https://pub.dev" + source: hosted + version: "8.0.0" + built_collection: + dependency: transitive + description: + name: built_collection + sha256: "376e3dd27b51ea877c28d525560790aee2e6fbb5f20e2f85d5081027d94e2100" + url: "https://pub.dev" + source: hosted + version: "5.1.1" + built_value: + dependency: transitive + description: + name: built_value + sha256: ea90e81dc4a25a043d9bee692d20ed6d1c4a1662a28c03a96417446c093ed6b4 + url: "https://pub.dev" + source: hosted + version: "8.9.5" + characters: + dependency: transitive + description: + name: characters + sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + charcode: + dependency: transitive + description: + name: charcode + sha256: fb0f1107cac15a5ea6ef0a6ef71a807b9e4267c713bb93e00e92d737cc8dbd8a + url: "https://pub.dev" + source: hosted + version: "1.4.0" + checked_yaml: + dependency: transitive + description: + name: checked_yaml + sha256: feb6bed21949061731a7a75fc5d2aa727cf160b91af9a3e464c5e3a32e28b5ff + url: "https://pub.dev" + source: hosted + version: "2.0.3" + cli_util: + dependency: transitive + description: + name: cli_util + sha256: ff6785f7e9e3c38ac98b2fb035701789de90154024a75b6cb926445e83197d1c + url: "https://pub.dev" + source: hosted + version: "0.4.2" + clock: + dependency: transitive + description: + name: clock + sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b + url: "https://pub.dev" + source: hosted + version: "1.1.2" + code_builder: + dependency: transitive + description: + name: code_builder + sha256: "0ec10bf4a89e4c613960bf1e8b42c64127021740fb21640c29c909826a5eea3e" + url: "https://pub.dev" + source: hosted + version: "4.10.1" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.dev" + source: hosted + version: "1.19.1" + convert: + dependency: transitive + description: + name: convert + sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68 + url: "https://pub.dev" + source: hosted + version: "3.1.2" + crypto: + dependency: transitive + description: + name: crypto + sha256: "1e445881f28f22d6140f181e07737b22f1e099a5e1ff94b0af2f9e4a463f4855" + url: "https://pub.dev" + source: hosted + version: "3.0.6" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + sha256: ba631d1c7f7bef6b729a622b7b752645a2d076dba9976925b8f25725a30e1ee6 + url: "https://pub.dev" + source: hosted + version: "1.0.8" + dart_style: + dependency: transitive + description: + name: dart_style + sha256: "27eb0ae77836989a3bc541ce55595e8ceee0992807f14511552a898ddd0d88ac" + url: "https://pub.dev" + source: hosted + version: "3.0.1" + drift: + dependency: "direct main" + description: + name: drift + sha256: b584ddeb2b74436735dd2cf746d2d021e19a9a6770f409212fd5cbc2814ada85 + url: "https://pub.dev" + source: hosted + version: "2.26.1" + drift_dev: + dependency: "direct dev" + description: + name: drift_dev + sha256: "54dc207c6e4662741f60e5752678df183957ab907754ffab0372a7082f6d2816" + url: "https://pub.dev" + source: hosted + version: "2.26.1" + equatable: + dependency: transitive + description: + name: equatable + sha256: "567c64b3cb4cf82397aac55f4f0cbd3ca20d77c6c03bedbc4ceaddc08904aef7" + url: "https://pub.dev" + source: hosted + version: "2.0.7" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "6a95e56b2449df2273fd8c45a662d6947ce1ebb7aafe80e550a3f68297f3cacc" + url: "https://pub.dev" + source: hosted + version: "1.3.2" + ffi: + dependency: transitive + description: + name: ffi + sha256: "289279317b4b16eb2bb7e271abccd4bf84ec9bdcbe999e278a94b804f5630418" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + file: + dependency: transitive + description: + name: file + sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4 + url: "https://pub.dev" + source: hosted + version: "7.0.1" + fixnum: + dependency: transitive + description: + name: fixnum + sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be + url: "https://pub.dev" + source: hosted + version: "1.1.1" + fl_chart: + dependency: "direct main" + description: + name: fl_chart + sha256: f2e9137f261d0f53a820f6b829c80ba570ac915284c8e32789d973834796eca0 + url: "https://pub.dev" + source: hosted + version: "0.71.0" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: "5398f14efa795ffb7a33e9b6a08798b26a180edac4ad7db3f231e40f82ce11e1" + url: "https://pub.dev" + source: hosted + version: "5.0.0" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + flutter_web_auth: + dependency: "direct main" + description: + name: flutter_web_auth + sha256: "95e4856e24fb6ac1678f5ff334743b63f782d839ab324543d29ccbd295176209" + url: "https://pub.dev" + source: hosted + version: "0.6.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + frontend_server_client: + dependency: transitive + description: + name: frontend_server_client + sha256: f64a0333a82f30b0cca061bc3d143813a486dc086b574bfb233b7c1372427694 + url: "https://pub.dev" + source: hosted + version: "4.0.0" + glob: + dependency: transitive + description: + name: glob + sha256: c3f1ee72c96f8f78935e18aa8cecced9ab132419e8625dc187e1c2408efc20de + url: "https://pub.dev" + source: hosted + version: "2.1.3" + graphs: + dependency: transitive + description: + name: graphs + sha256: "741bbf84165310a68ff28fe9e727332eef1407342fca52759cb21ad8177bb8d0" + url: "https://pub.dev" + source: hosted + version: "2.3.2" + http: + dependency: transitive + description: + name: http + sha256: "2c11f3f94c687ee9bad77c171151672986360b2b001d109814ee7140b2cf261b" + url: "https://pub.dev" + source: hosted + version: "1.4.0" + http_multi_server: + dependency: transitive + description: + name: http_multi_server + sha256: aa6199f908078bb1c5efb8d8638d4ae191aac11b311132c3ef48ce352fb52ef8 + url: "https://pub.dev" + source: hosted + version: "3.2.2" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571" + url: "https://pub.dev" + source: hosted + version: "4.1.2" + intl: + dependency: "direct main" + description: + name: intl + sha256: d6f56758b7d3014a48af9701c085700aac781a92a87a62b1333b46d8879661cf + url: "https://pub.dev" + source: hosted + version: "0.19.0" + io: + dependency: transitive + description: + name: io + sha256: dfd5a80599cf0165756e3181807ed3e77daf6dd4137caaad72d0b7931597650b + url: "https://pub.dev" + source: hosted + version: "1.0.5" + js: + dependency: transitive + description: + name: js + sha256: "53385261521cc4a0c4658fd0ad07a7d14591cf8fc33abbceae306ddb974888dc" + url: "https://pub.dev" + source: hosted + version: "0.7.2" + json_annotation: + dependency: transitive + description: + name: json_annotation + sha256: "1ce844379ca14835a50d2f019a3099f419082cfdd231cd86a142af94dd5c6bb1" + url: "https://pub.dev" + source: hosted + version: "4.9.0" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: c35baad643ba394b40aac41080300150a4f08fd0fd6a10378f8f7c6bc161acec + url: "https://pub.dev" + source: hosted + version: "10.0.8" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: f8b613e7e6a13ec79cfdc0e97638fddb3ab848452eff057653abd3edba760573 + url: "https://pub.dev" + source: hosted + version: "3.0.9" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "6ba465d5d76e67ddf503e1161d1f4a6bc42306f9d66ca1e8f079a47290fb06d3" + url: "https://pub.dev" + source: hosted + version: "3.0.1" + lints: + dependency: transitive + description: + name: lints + sha256: c35bb79562d980e9a453fc715854e1ed39e24e7d0297a880ef54e17f9874a9d7 + url: "https://pub.dev" + source: hosted + version: "5.1.1" + logging: + dependency: transitive + description: + name: logging + sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61 + url: "https://pub.dev" + source: hosted + version: "1.3.0" + matcher: + dependency: transitive + description: + name: matcher + sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2 + url: "https://pub.dev" + source: hosted + version: "0.12.17" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec + url: "https://pub.dev" + source: hosted + version: "0.11.1" + meta: + dependency: transitive + description: + name: meta + sha256: e3641ec5d63ebf0d9b41bd43201a66e3fc79a65db5f61fc181f04cd27aab950c + url: "https://pub.dev" + source: hosted + version: "1.16.0" + mime: + dependency: transitive + description: + name: mime + sha256: "41a20518f0cb1256669420fdba0cd90d21561e560ac240f26ef8322e45bb7ed6" + url: "https://pub.dev" + source: hosted + version: "2.0.0" + package_config: + dependency: transitive + description: + name: package_config + sha256: f096c55ebb7deb7e384101542bfba8c52696c1b56fca2eb62827989ef2353bbc + url: "https://pub.dev" + source: hosted + version: "2.2.0" + path: + dependency: "direct main" + description: + name: path + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.dev" + source: hosted + version: "1.9.1" + path_provider: + dependency: "direct main" + description: + name: path_provider + sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd" + url: "https://pub.dev" + source: hosted + version: "2.1.5" + path_provider_android: + dependency: transitive + description: + name: path_provider_android + sha256: d0d310befe2c8ab9e7f393288ccbb11b60c019c6b5afc21973eeee4dda2b35e9 + url: "https://pub.dev" + source: hosted + version: "2.2.17" + path_provider_foundation: + dependency: transitive + description: + name: path_provider_foundation + sha256: "4843174df4d288f5e29185bd6e72a6fbdf5a4a4602717eed565497429f179942" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279 + url: "https://pub.dev" + source: hosted + version: "2.2.1" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 + url: "https://pub.dev" + source: hosted + version: "2.3.0" + platform: + dependency: transitive + description: + name: platform + sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984" + url: "https://pub.dev" + source: hosted + version: "3.1.6" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.dev" + source: hosted + version: "2.1.8" + pool: + dependency: transitive + description: + name: pool + sha256: "20fe868b6314b322ea036ba325e6fc0711a22948856475e2c2b6306e8ab39c2a" + url: "https://pub.dev" + source: hosted + version: "1.5.1" + pub_semver: + dependency: transitive + description: + name: pub_semver + sha256: "5bfcf68ca79ef689f8990d1160781b4bad40a3bd5e5218ad4076ddb7f4081585" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + pubspec_parse: + dependency: transitive + description: + name: pubspec_parse + sha256: "0560ba233314abbed0a48a2956f7f022cce7c3e1e73df540277da7544cad4082" + url: "https://pub.dev" + source: hosted + version: "1.5.0" + recase: + dependency: transitive + description: + name: recase + sha256: e4eb4ec2dcdee52dcf99cb4ceabaffc631d7424ee55e56f280bc039737f89213 + url: "https://pub.dev" + source: hosted + version: "4.1.0" + shared_preferences: + dependency: "direct main" + description: + name: shared_preferences + sha256: "6e8bf70b7fef813df4e9a36f658ac46d107db4b4cfe1048b477d4e453a8159f5" + url: "https://pub.dev" + source: hosted + version: "2.5.3" + shared_preferences_android: + dependency: transitive + description: + name: shared_preferences_android + sha256: "20cbd561f743a342c76c151d6ddb93a9ce6005751e7aa458baad3858bfbfb6ac" + url: "https://pub.dev" + source: hosted + version: "2.4.10" + shared_preferences_foundation: + dependency: transitive + description: + name: shared_preferences_foundation + sha256: "6a52cfcdaeac77cad8c97b539ff688ccfc458c007b4db12be584fbe5c0e49e03" + url: "https://pub.dev" + source: hosted + version: "2.5.4" + shared_preferences_linux: + dependency: transitive + description: + name: shared_preferences_linux + sha256: "580abfd40f415611503cae30adf626e6656dfb2f0cee8f465ece7b6defb40f2f" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shared_preferences_platform_interface: + dependency: transitive + description: + name: shared_preferences_platform_interface + sha256: "57cbf196c486bc2cf1f02b85784932c6094376284b3ad5779d1b1c6c6a816b80" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shared_preferences_web: + dependency: transitive + description: + name: shared_preferences_web + sha256: c49bd060261c9a3f0ff445892695d6212ff603ef3115edbb448509d407600019 + url: "https://pub.dev" + source: hosted + version: "2.4.3" + shared_preferences_windows: + dependency: transitive + description: + name: shared_preferences_windows + sha256: "94ef0f72b2d71bc3e700e025db3710911bd51a71cefb65cc609dd0d9a982e3c1" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shelf: + dependency: transitive + description: + name: shelf + sha256: e7dd780a7ffb623c57850b33f43309312fc863fb6aa3d276a754bb299839ef12 + url: "https://pub.dev" + source: hosted + version: "1.4.2" + shelf_web_socket: + dependency: transitive + description: + name: shelf_web_socket + sha256: "3632775c8e90d6c9712f883e633716432a27758216dfb61bd86a8321c0580925" + url: "https://pub.dev" + source: hosted + version: "3.0.0" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_gen: + dependency: transitive + description: + name: source_gen + sha256: "35c8150ece9e8c8d263337a265153c3329667640850b9304861faea59fc98f6b" + url: "https://pub.dev" + source: hosted + version: "2.0.0" + source_span: + dependency: transitive + description: + name: source_span + sha256: "254ee5351d6cb365c859e20ee823c3bb479bf4a293c22d17a9f1bf144ce86f7c" + url: "https://pub.dev" + source: hosted + version: "1.10.1" + sqlite3: + dependency: transitive + description: + name: sqlite3 + sha256: "310af39c40dd0bb2058538333c9d9840a2725ae0b9f77e4fd09ad6696aa8f66e" + url: "https://pub.dev" + source: hosted + version: "2.7.5" + sqlite3_flutter_libs: + dependency: "direct main" + description: + name: sqlite3_flutter_libs + sha256: "1a96b59227828d9eb1463191d684b37a27d66ee5ed7597fcf42eee6452c88a14" + url: "https://pub.dev" + source: hosted + version: "0.5.32" + sqlparser: + dependency: transitive + description: + name: sqlparser + sha256: "27dd0a9f0c02e22ac0eb42a23df9ea079ce69b52bb4a3b478d64e0ef34a263ee" + url: "https://pub.dev" + source: hosted + version: "0.41.0" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" + url: "https://pub.dev" + source: hosted + version: "1.12.1" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + stream_transform: + dependency: transitive + description: + name: stream_transform + sha256: ad47125e588cfd37a9a7f86c7d6356dde8dfe89d071d293f80ca9e9273a33871 + url: "https://pub.dev" + source: hosted + version: "2.1.1" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" + url: "https://pub.dev" + source: hosted + version: "1.4.1" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" + url: "https://pub.dev" + source: hosted + version: "1.2.2" + test_api: + dependency: transitive + description: + name: test_api + sha256: fb31f383e2ee25fbbfe06b40fe21e1e458d14080e3c67e7ba0acfde4df4e0bbd + url: "https://pub.dev" + source: hosted + version: "0.7.4" + timing: + dependency: transitive + description: + name: timing + sha256: "62ee18aca144e4a9f29d212f5a4c6a053be252b895ab14b5821996cff4ed90fe" + url: "https://pub.dev" + source: hosted + version: "1.0.2" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: "0968250880a6c5fe7edc067ed0a13d4bae1577fe2771dcf3010d52c4a9d3ca14" + url: "https://pub.dev" + source: hosted + version: "14.3.1" + watcher: + dependency: transitive + description: + name: watcher + sha256: "69da27e49efa56a15f8afe8f4438c4ec02eff0a117df1b22ea4aad194fe1c104" + url: "https://pub.dev" + source: hosted + version: "1.1.1" + web: + dependency: transitive + description: + name: web + sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a" + url: "https://pub.dev" + source: hosted + version: "1.1.1" + web_socket: + dependency: transitive + description: + name: web_socket + sha256: "34d64019aa8e36bf9842ac014bb5d2f5586ca73df5e4d9bf5c936975cae6982c" + url: "https://pub.dev" + source: hosted + version: "1.0.1" + web_socket_channel: + dependency: transitive + description: + name: web_socket_channel + sha256: d645757fb0f4773d602444000a8131ff5d48c9e47adfe9772652dd1a4f2d45c8 + url: "https://pub.dev" + source: hosted + version: "3.0.3" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + yaml: + dependency: transitive + description: + name: yaml + sha256: b9da305ac7c39faa3f030eccd175340f968459dae4af175130b3fc47e40d76ce + url: "https://pub.dev" + source: hosted + version: "3.1.3" +sdks: + dart: ">=3.7.0 <4.0.0" + flutter: ">=3.27.0" diff --git a/pubspec.yaml b/pubspec.yaml new file mode 100644 index 0000000..f360f3f --- /dev/null +++ b/pubspec.yaml @@ -0,0 +1,99 @@ +name: finance_app +description: "A new Flutter project." +# The following line prevents the package from being accidentally published to +# pub.dev using `flutter pub publish`. This is preferred for private packages. +publish_to: 'none' # Remove this line if you wish to publish to pub.dev + +# The following defines the version and build number for your application. +# A version number is three numbers separated by dots, like 1.2.43 +# followed by an optional build number separated by a +. +# Both the version and the builder number may be overridden in flutter +# build by specifying --build-name and --build-number, respectively. +# In Android, build-name is used as versionName while build-number used as versionCode. +# Read more about Android versioning at https://developer.android.com/studio/publish/versioning +# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion. +# Read more about iOS versioning at +# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html +# In Windows, build-name is used as the major, minor, and patch parts +# of the product and file versions while build-number is used as the build suffix. +version: 1.0.0+1 + +environment: + sdk: ^3.7.0 # Drift 2.18 requires Dart 3.4+, Drift 2.16 requires Dart 3.3+ + +# Dependencies specify other packages that your package needs in order to work. +# To automatically upgrade your package dependencies to the latest versions +# consider running `flutter pub upgrade --major-versions`. Alternatively, +# dependencies can be manually updated by changing the version numbers below to +# the latest version available on pub.dev. To see which dependencies have newer +# versions available, run `flutter pub outdated`. +dependencies: + flutter: + sdk: flutter + fl_chart: ^0.71.0 + intl: ^0.19.0 # For date formatting + flutter_web_auth: ^0.6.0 # Обновляем до последней стабильной версии + shared_preferences: ^2.0.6 # Для работы с локальным хранилищем + drift: ^2.18.0 # Updated Drift - основной пакет + sqlite3_flutter_libs: ^0.5.24 # Needed for native platforms + path_provider: ^2.1.3 # To find database file location on native + path: ^1.9.0 # To construct database file path on native + # rxdart: ^0.28.0 # Removed as it wasn't used in database.dart + # The following adds the Cupertino Icons font to your application. + # Use with the CupertinoIcons class for iOS style icons. + cupertino_icons: ^1.0.8 + +dev_dependencies: + flutter_test: + sdk: flutter + drift_dev: ^2.18.0 # Updated Drift code generator + build_runner: ^2.4.11 # Updated build_runner + + # The "flutter_lints" package below contains a set of recommended lints to + # encourage good coding practices. The lint set provided by the package is + # activated in the `analysis_options.yaml` file located at the root of your + # package. See that file for information about deactivating specific lint + # rules and activating additional ones. + flutter_lints: ^5.0.0 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter packages. +flutter: + + # The following line ensures that the Material Icons font is + # included with your application, so that you can use the icons in + # the material Icons class. + uses-material-design: true + + # To add assets to your application, add an assets section, like this: + # assets: + # - images/a_dot_burr.jpeg + # - images/a_dot_ham.jpeg + + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.dev/to/resolution-aware-images + + # For details regarding adding assets from package dependencies, see + # https://flutter.dev/to/asset-from-package + + # To add custom fonts to your application, add a fonts section here, + # in this "flutter" section. Each entry in this list should have a + # "family" key with the font family name, and a "fonts" key with a + # list giving the asset and other descriptors for the font. For + # example: + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic + # - family: Trajan Pro + # fonts: + # - asset: fonts/TrajanPro.ttf + # - asset: fonts/TrajanPro_Bold.ttf + # weight: 700 + # + # For details regarding fonts from package dependencies, + # see https://flutter.dev/to/font-from-package diff --git a/test/widget_test.dart b/test/widget_test.dart new file mode 100644 index 0000000..5f6291d --- /dev/null +++ b/test/widget_test.dart @@ -0,0 +1,10 @@ +// This is a basic Flutter widget test. +// +// To perform an interaction with a widget in your test, use the WidgetTester +// utility in the flutter_test package. For example, you can send tap and scroll +// gestures. You can also use WidgetTester to find child widgets in the widget +// tree, read text, and verify that the values of widget properties are correct. + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + diff --git a/web/favicon.png b/web/favicon.png new file mode 100644 index 0000000..8aaa46a Binary files /dev/null and b/web/favicon.png differ diff --git a/web/icons/Icon-192.png b/web/icons/Icon-192.png new file mode 100644 index 0000000..b749bfe Binary files /dev/null and b/web/icons/Icon-192.png differ diff --git a/web/icons/Icon-512.png b/web/icons/Icon-512.png new file mode 100644 index 0000000..88cfd48 Binary files /dev/null and b/web/icons/Icon-512.png differ diff --git a/web/icons/Icon-maskable-192.png b/web/icons/Icon-maskable-192.png new file mode 100644 index 0000000..eb9b4d7 Binary files /dev/null and b/web/icons/Icon-maskable-192.png differ diff --git a/web/icons/Icon-maskable-512.png b/web/icons/Icon-maskable-512.png new file mode 100644 index 0000000..d69c566 Binary files /dev/null and b/web/icons/Icon-maskable-512.png differ diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..727cb06 --- /dev/null +++ b/web/index.html @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + finance_app_2 + + + + + + diff --git a/web/manifest.json b/web/manifest.json new file mode 100644 index 0000000..cc3aa4d --- /dev/null +++ b/web/manifest.json @@ -0,0 +1,35 @@ +{ + "name": "finance_app_2", + "short_name": "finance_app_2", + "start_url": ".", + "display": "standalone", + "background_color": "#0175C2", + "theme_color": "#0175C2", + "description": "A new Flutter project.", + "orientation": "portrait-primary", + "prefer_related_applications": false, + "icons": [ + { + "src": "icons/Icon-192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "icons/Icon-512.png", + "sizes": "512x512", + "type": "image/png" + }, + { + "src": "icons/Icon-maskable-192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "maskable" + }, + { + "src": "icons/Icon-maskable-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "maskable" + } + ] +} diff --git a/windows/.gitignore b/windows/.gitignore new file mode 100644 index 0000000..d492d0d --- /dev/null +++ b/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/windows/CMakeLists.txt b/windows/CMakeLists.txt new file mode 100644 index 0000000..affa737 --- /dev/null +++ b/windows/CMakeLists.txt @@ -0,0 +1,108 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(finance_app_2 LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "finance_app_2") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(VERSION 3.14...3.25) + +# Define build configuration option. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() +# Define settings for the Profile build mode. +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/windows/flutter/CMakeLists.txt b/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000..903f489 --- /dev/null +++ b/windows/flutter/CMakeLists.txt @@ -0,0 +1,109 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# Set fallback configurations for older versions of the flutter tool. +if (NOT DEFINED FLUTTER_TARGET_PLATFORM) + set(FLUTTER_TARGET_PLATFORM "windows-x64") +endif() + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + ${FLUTTER_TARGET_PLATFORM} $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..988f3c8 --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,14 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include + +void RegisterPlugins(flutter::PluginRegistry* registry) { + Sqlite3FlutterLibsPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("Sqlite3FlutterLibsPlugin")); +} diff --git a/windows/flutter/generated_plugin_registrant.h b/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..dc139d8 --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake new file mode 100644 index 0000000..8abff95 --- /dev/null +++ b/windows/flutter/generated_plugins.cmake @@ -0,0 +1,24 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + sqlite3_flutter_libs +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/windows/runner/CMakeLists.txt b/windows/runner/CMakeLists.txt new file mode 100644 index 0000000..394917c --- /dev/null +++ b/windows/runner/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/windows/runner/Runner.rc b/windows/runner/Runner.rc new file mode 100644 index 0000000..dbbbe74 --- /dev/null +++ b/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) +#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD +#else +#define VERSION_AS_NUMBER 1,0,0,0 +#endif + +#if defined(FLUTTER_VERSION) +#define VERSION_AS_STRING FLUTTER_VERSION +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "ru.sanders" "\0" + VALUE "FileDescription", "finance_app_2" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "finance_app_2" "\0" + VALUE "LegalCopyright", "Copyright (C) 2025 ru.sanders. All rights reserved." "\0" + VALUE "OriginalFilename", "finance_app_2.exe" "\0" + VALUE "ProductName", "finance_app_2" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/windows/runner/flutter_window.cpp b/windows/runner/flutter_window.cpp new file mode 100644 index 0000000..955ee30 --- /dev/null +++ b/windows/runner/flutter_window.cpp @@ -0,0 +1,71 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + // Flutter can complete the first frame before the "show window" callback is + // registered. The following call ensures a frame is pending to ensure the + // window is shown. It is a no-op if the first frame hasn't completed yet. + flutter_controller_->ForceRedraw(); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/windows/runner/flutter_window.h b/windows/runner/flutter_window.h new file mode 100644 index 0000000..6da0652 --- /dev/null +++ b/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/windows/runner/main.cpp b/windows/runner/main.cpp new file mode 100644 index 0000000..703de10 --- /dev/null +++ b/windows/runner/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.Create(L"finance_app_2", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/windows/runner/resource.h b/windows/runner/resource.h new file mode 100644 index 0000000..66a65d1 --- /dev/null +++ b/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/windows/runner/resources/app_icon.ico b/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000..c04e20c Binary files /dev/null and b/windows/runner/resources/app_icon.ico differ diff --git a/windows/runner/runner.exe.manifest b/windows/runner/runner.exe.manifest new file mode 100644 index 0000000..153653e --- /dev/null +++ b/windows/runner/runner.exe.manifest @@ -0,0 +1,14 @@ + + + + + PerMonitorV2 + + + + + + + + + diff --git a/windows/runner/utils.cpp b/windows/runner/utils.cpp new file mode 100644 index 0000000..3a0b465 --- /dev/null +++ b/windows/runner/utils.cpp @@ -0,0 +1,65 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + unsigned int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, nullptr, 0, nullptr, nullptr) + -1; // remove the trailing null character + int input_length = (int)wcslen(utf16_string); + std::string utf8_string; + if (target_length == 0 || target_length > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, utf8_string.data(), target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/windows/runner/utils.h b/windows/runner/utils.h new file mode 100644 index 0000000..3879d54 --- /dev/null +++ b/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/windows/runner/win32_window.cpp b/windows/runner/win32_window.cpp new file mode 100644 index 0000000..60608d0 --- /dev/null +++ b/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#include "resource.h" + +namespace { + +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + } + FreeLibrary(user32_module); +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registrar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::Create(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + UpdateTheme(window); + + return OnCreate(); +} + +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/windows/runner/win32_window.h b/windows/runner/win32_window.h new file mode 100644 index 0000000..e901dde --- /dev/null +++ b/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates a win32 window with |title| that is positioned and sized using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_