diff --git a/.metadata b/.metadata new file mode 100644 index 00000000..08c24780 --- /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: "3b62efc2a3da49882f43c372e0bc53daef7295a6" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 3b62efc2a3da49882f43c372e0bc53daef7295a6 + base_revision: 3b62efc2a3da49882f43c372e0bc53daef7295a6 + - platform: android + create_revision: 3b62efc2a3da49882f43c372e0bc53daef7295a6 + base_revision: 3b62efc2a3da49882f43c372e0bc53daef7295a6 + - platform: ios + create_revision: 3b62efc2a3da49882f43c372e0bc53daef7295a6 + base_revision: 3b62efc2a3da49882f43c372e0bc53daef7295a6 + - platform: linux + create_revision: 3b62efc2a3da49882f43c372e0bc53daef7295a6 + base_revision: 3b62efc2a3da49882f43c372e0bc53daef7295a6 + - platform: macos + create_revision: 3b62efc2a3da49882f43c372e0bc53daef7295a6 + base_revision: 3b62efc2a3da49882f43c372e0bc53daef7295a6 + - platform: web + create_revision: 3b62efc2a3da49882f43c372e0bc53daef7295a6 + base_revision: 3b62efc2a3da49882f43c372e0bc53daef7295a6 + - platform: windows + create_revision: 3b62efc2a3da49882f43c372e0bc53daef7295a6 + base_revision: 3b62efc2a3da49882f43c372e0bc53daef7295a6 + + # 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/.vscode/mcp.json b/.vscode/mcp.json new file mode 100644 index 00000000..0a531ebd --- /dev/null +++ b/.vscode/mcp.json @@ -0,0 +1,9 @@ +{ + "servers": { + "supabase": { + "type": "http", + "url": "https://mcp.supabase.com/mcp?project_ref=wqjebgpbwrfzshaabprh" + } + }, + "inputs": [] +} \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 00000000..2c049e5a --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# tasq + +A new Flutter project. diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 00000000..f9b30346 --- /dev/null +++ b/analysis_options.yaml @@ -0,0 +1 @@ +include: package:flutter_lints/flutter.yaml diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 00000000..be3943c9 --- /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 00000000..d2f5ba6b --- /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 = "com.example.tasq" + compileSdk = flutter.compileSdkVersion + ndkVersion = flutter.ndkVersion + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + kotlinOptions { + jvmTarget = JavaVersion.VERSION_17.toString() + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId = "com.example.tasq" + // 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 00000000..399f6981 --- /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 00000000..c0b90a2e --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/kotlin/com/example/tasq/MainActivity.kt b/android/app/src/main/kotlin/com/example/tasq/MainActivity.kt new file mode 100644 index 00000000..cc94f81f --- /dev/null +++ b/android/app/src/main/kotlin/com/example/tasq/MainActivity.kt @@ -0,0 +1,5 @@ +package com.example.tasq + +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 00000000..f74085f3 --- /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 00000000..304732f8 --- /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 00000000..0813bfab 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 00000000..2501b925 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 00000000..31ab5851 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 00000000..92c47791 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 00000000..904167f5 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 00000000..06952be7 --- /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 00000000..cb1ef880 --- /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 00000000..399f6981 --- /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 00000000..dbee657b --- /dev/null +++ b/android/build.gradle.kts @@ -0,0 +1,24 @@ +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 00000000..fbee1d8c --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,2 @@ +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..e4ef43fb --- /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.14-all.zip diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts new file mode 100644 index 00000000..ca7fe065 --- /dev/null +++ b/android/settings.gradle.kts @@ -0,0 +1,26 @@ +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.11.1" apply false + id("org.jetbrains.kotlin.android") version "2.2.20" apply false +} + +include(":app") diff --git a/assets/tasq_ico.png b/assets/tasq_ico.png new file mode 100644 index 00000000..5efbbdeb Binary files /dev/null and b/assets/tasq_ico.png differ diff --git a/assets/tasq_notification.wav b/assets/tasq_notification.wav new file mode 100644 index 00000000..bd047ac1 Binary files /dev/null and b/assets/tasq_notification.wav differ diff --git a/ios/.gitignore b/ios/.gitignore new file mode 100644 index 00000000..7a7f9873 --- /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 00000000..1dc6cf76 --- /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 + 13.0 + + diff --git a/ios/Flutter/Debug.xcconfig b/ios/Flutter/Debug.xcconfig new file mode 100644 index 00000000..592ceee8 --- /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 00000000..592ceee8 --- /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 00000000..bcacaf8a --- /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 = 13.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 = com.example.tasq; + 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 = com.example.tasq.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 = com.example.tasq.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 = com.example.tasq.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 = AppIcon; + 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 = 13.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 = AppIcon; + 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 = 13.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 = com.example.tasq; + 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 = com.example.tasq; + 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 00000000..919434a6 --- /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 00000000..18d98100 --- /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 00000000..f9b0d7c5 --- /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 00000000..e3773d42 --- /dev/null +++ b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,101 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 00000000..1d526a16 --- /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 00000000..18d98100 --- /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 00000000..f9b0d7c5 --- /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 00000000..62666446 --- /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 00000000..d36b1fab --- /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 00000000..0557e1ab 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 00000000..a3ca0407 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 00000000..5e963b79 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 00000000..df655f7d 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 00000000..5017990b 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 00000000..c7601299 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 00000000..bcabdbcc 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 00000000..5e963b79 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 00000000..73938a0f 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 00000000..46d4ea72 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-50x50@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@1x.png new file mode 100644 index 00000000..1e803b69 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@2x.png new file mode 100644 index 00000000..79f896d8 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png new file mode 100644 index 00000000..ed012636 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.png new file mode 100644 index 00000000..7505e35a Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.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 00000000..46d4ea72 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 00000000..f855f13a 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-72x72@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@1x.png new file mode 100644 index 00000000..0813bfab Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.png new file mode 100644 index 00000000..92c47791 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.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 00000000..8e022e97 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 00000000..79419e76 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 00000000..19a26dbc 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 00000000..0bedcf2f --- /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 00000000..9da19eac 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 00000000..9da19eac 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 00000000..9da19eac 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 00000000..89c2725b --- /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 00000000..f2e259c7 --- /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 00000000..f3c28516 --- /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 00000000..c03a8c3e --- /dev/null +++ b/ios/Runner/Info.plist @@ -0,0 +1,49 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Tasq + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + tasq + 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 00000000..308a2a56 --- /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 00000000..86a7c3b1 --- /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 00000000..b17f1a4a --- /dev/null +++ b/lib/app.dart @@ -0,0 +1,22 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import 'routing/app_router.dart'; +import 'theme/app_theme.dart'; + +class TasqApp extends ConsumerWidget { + const TasqApp({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final router = ref.watch(appRouterProvider); + + return MaterialApp.router( + title: 'TasQ', + routerConfig: router, + theme: AppTheme.light(), + darkTheme: AppTheme.dark(), + themeMode: ThemeMode.system, + ); + } +} diff --git a/lib/main.dart b/lib/main.dart new file mode 100644 index 00000000..47b79ec2 --- /dev/null +++ b/lib/main.dart @@ -0,0 +1,73 @@ +import 'package:flutter/material.dart'; +import 'package:audioplayers/audioplayers.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:supabase_flutter/supabase_flutter.dart'; +import 'package:flutter_dotenv/flutter_dotenv.dart'; + +import 'app.dart'; +import 'providers/notifications_provider.dart'; + +Future main() async { + WidgetsFlutterBinding.ensureInitialized(); + + await dotenv.load(fileName: '.env'); + + final supabaseUrl = dotenv.env['SUPABASE_URL'] ?? ''; + final supabaseAnonKey = dotenv.env['SUPABASE_ANON_KEY'] ?? ''; + + if (supabaseUrl.isEmpty || supabaseAnonKey.isEmpty) { + runApp(const _MissingConfigApp()); + return; + } + + await Supabase.initialize(url: supabaseUrl, anonKey: supabaseAnonKey); + + runApp( + ProviderScope( + observers: [NotificationSoundObserver()], + child: const TasqApp(), + ), + ); +} + +class NotificationSoundObserver extends ProviderObserver { + static final AudioPlayer _player = AudioPlayer(); + + @override + void didUpdateProvider( + ProviderBase provider, + Object? previousValue, + Object? newValue, + ProviderContainer container, + ) { + if (provider == unreadNotificationsCountProvider) { + final prev = previousValue as int?; + final next = newValue as int?; + if (prev != null && next != null && next > prev) { + _player.play(AssetSource('tasq_notification.wav')); + } + } + } +} + +class _MissingConfigApp extends StatelessWidget { + const _MissingConfigApp(); + + @override + Widget build(BuildContext context) { + return const MaterialApp( + home: Scaffold( + body: Center( + child: Padding( + padding: EdgeInsets.all(24), + child: Text( + 'Missing SUPABASE_URL or SUPABASE_ANON_KEY. ' + 'Provide them in the .env file.', + textAlign: TextAlign.center, + ), + ), + ), + ), + ); + } +} diff --git a/lib/models/notification_item.dart b/lib/models/notification_item.dart new file mode 100644 index 00000000..e041c864 --- /dev/null +++ b/lib/models/notification_item.dart @@ -0,0 +1,41 @@ +class NotificationItem { + NotificationItem({ + required this.id, + required this.userId, + required this.actorId, + required this.ticketId, + required this.taskId, + required this.messageId, + required this.type, + required this.createdAt, + required this.readAt, + }); + + final String id; + final String userId; + final String? actorId; + final String? ticketId; + final String? taskId; + final int? messageId; + final String type; + final DateTime createdAt; + final DateTime? readAt; + + bool get isUnread => readAt == null; + + factory NotificationItem.fromMap(Map map) { + return NotificationItem( + id: map['id'] as String, + userId: map['user_id'] as String, + actorId: map['actor_id'] as String?, + ticketId: map['ticket_id'] as String?, + taskId: map['task_id'] as String?, + messageId: map['message_id'] as int?, + type: map['type'] as String? ?? 'mention', + createdAt: DateTime.parse(map['created_at'] as String), + readAt: map['read_at'] == null + ? null + : DateTime.parse(map['read_at'] as String), + ); + } +} diff --git a/lib/models/office.dart b/lib/models/office.dart new file mode 100644 index 00000000..fc7575fa --- /dev/null +++ b/lib/models/office.dart @@ -0,0 +1,10 @@ +class Office { + Office({required this.id, required this.name}); + + final String id; + final String name; + + factory Office.fromMap(Map map) { + return Office(id: map['id'] as String, name: map['name'] as String? ?? ''); + } +} diff --git a/lib/models/profile.dart b/lib/models/profile.dart new file mode 100644 index 00000000..7af0418a --- /dev/null +++ b/lib/models/profile.dart @@ -0,0 +1,15 @@ +class Profile { + Profile({required this.id, required this.role, required this.fullName}); + + final String id; + final String role; + final String fullName; + + factory Profile.fromMap(Map map) { + return Profile( + id: map['id'] as String, + role: map['role'] as String? ?? 'standard', + fullName: map['full_name'] as String? ?? '', + ); + } +} diff --git a/lib/models/task.dart b/lib/models/task.dart new file mode 100644 index 00000000..4b6eb621 --- /dev/null +++ b/lib/models/task.dart @@ -0,0 +1,50 @@ +class Task { + Task({ + required this.id, + required this.ticketId, + required this.title, + required this.description, + required this.officeId, + required this.status, + required this.priority, + required this.queueOrder, + required this.createdAt, + required this.creatorId, + required this.startedAt, + required this.completedAt, + }); + + final String id; + final String? ticketId; + final String title; + final String description; + final String? officeId; + final String status; + final int priority; + final int? queueOrder; + final DateTime createdAt; + final String? creatorId; + final DateTime? startedAt; + final DateTime? completedAt; + + factory Task.fromMap(Map map) { + return Task( + id: map['id'] as String, + ticketId: map['ticket_id'] as String?, + title: map['title'] as String? ?? 'Task', + description: map['description'] as String? ?? '', + officeId: map['office_id'] as String?, + status: map['status'] as String? ?? 'queued', + priority: map['priority'] as int? ?? 1, + queueOrder: map['queue_order'] as int?, + createdAt: DateTime.parse(map['created_at'] as String), + creatorId: map['creator_id'] as String?, + startedAt: map['started_at'] == null + ? null + : DateTime.parse(map['started_at'] as String), + completedAt: map['completed_at'] == null + ? null + : DateTime.parse(map['completed_at'] as String), + ); + } +} diff --git a/lib/models/task_assignment.dart b/lib/models/task_assignment.dart new file mode 100644 index 00000000..b04c621f --- /dev/null +++ b/lib/models/task_assignment.dart @@ -0,0 +1,19 @@ +class TaskAssignment { + TaskAssignment({ + required this.taskId, + required this.userId, + required this.createdAt, + }); + + final String taskId; + final String userId; + final DateTime createdAt; + + factory TaskAssignment.fromMap(Map map) { + return TaskAssignment( + taskId: map['task_id'] as String, + userId: map['user_id'] as String, + createdAt: DateTime.parse(map['created_at'] as String), + ); + } +} diff --git a/lib/models/ticket.dart b/lib/models/ticket.dart new file mode 100644 index 00000000..251792ce --- /dev/null +++ b/lib/models/ticket.dart @@ -0,0 +1,46 @@ +class Ticket { + Ticket({ + required this.id, + required this.subject, + required this.description, + required this.officeId, + required this.status, + required this.createdAt, + required this.creatorId, + required this.respondedAt, + required this.promotedAt, + required this.closedAt, + }); + + final String id; + final String subject; + final String description; + final String officeId; + final String status; + final DateTime createdAt; + final String? creatorId; + final DateTime? respondedAt; + final DateTime? promotedAt; + final DateTime? closedAt; + + factory Ticket.fromMap(Map map) { + return Ticket( + id: map['id'] as String, + subject: map['subject'] as String? ?? '', + description: map['description'] as String? ?? '', + officeId: map['office_id'] as String? ?? '', + status: map['status'] as String? ?? 'pending', + createdAt: DateTime.parse(map['created_at'] as String), + creatorId: map['creator_id'] as String?, + respondedAt: map['responded_at'] == null + ? null + : DateTime.parse(map['responded_at'] as String), + promotedAt: map['promoted_at'] == null + ? null + : DateTime.parse(map['promoted_at'] as String), + closedAt: map['closed_at'] == null + ? null + : DateTime.parse(map['closed_at'] as String), + ); + } +} diff --git a/lib/models/ticket_message.dart b/lib/models/ticket_message.dart new file mode 100644 index 00000000..3e9aadb8 --- /dev/null +++ b/lib/models/ticket_message.dart @@ -0,0 +1,28 @@ +class TicketMessage { + TicketMessage({ + required this.id, + required this.ticketId, + required this.taskId, + required this.senderId, + required this.content, + required this.createdAt, + }); + + final int id; + final String? ticketId; + final String? taskId; + final String? senderId; + final String content; + final DateTime createdAt; + + factory TicketMessage.fromMap(Map map) { + return TicketMessage( + id: map['id'] as int, + ticketId: map['ticket_id'] as String?, + taskId: map['task_id'] as String?, + senderId: map['sender_id'] as String?, + content: map['content'] as String? ?? '', + createdAt: DateTime.parse(map['created_at'] as String), + ); + } +} diff --git a/lib/models/user_office.dart b/lib/models/user_office.dart new file mode 100644 index 00000000..1e8a35fb --- /dev/null +++ b/lib/models/user_office.dart @@ -0,0 +1,13 @@ +class UserOffice { + UserOffice({required this.userId, required this.officeId}); + + final String userId; + final String officeId; + + factory UserOffice.fromMap(Map map) { + return UserOffice( + userId: map['user_id'] as String, + officeId: map['office_id'] as String, + ); + } +} diff --git a/lib/providers/admin_user_provider.dart b/lib/providers/admin_user_provider.dart new file mode 100644 index 00000000..ab43dc18 --- /dev/null +++ b/lib/providers/admin_user_provider.dart @@ -0,0 +1,105 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:supabase_flutter/supabase_flutter.dart'; + +import 'supabase_provider.dart'; + +final adminUserControllerProvider = Provider((ref) { + final client = ref.watch(supabaseClientProvider); + return AdminUserController(client); +}); + +class AdminUserStatus { + AdminUserStatus({required this.email, required this.bannedUntil}); + + final String? email; + final DateTime? bannedUntil; + + bool get isLocked { + if (bannedUntil == null) return false; + return bannedUntil!.isAfter(DateTime.now().toUtc()); + } +} + +class AdminUserController { + AdminUserController(this._client); + + final SupabaseClient _client; + + Future updateProfile({ + required String userId, + required String fullName, + required String role, + }) async { + await _client + .from('profiles') + .update({'full_name': fullName, 'role': role}) + .eq('id', userId); + } + + Future updateRole({ + required String userId, + required String role, + }) async { + await _client.from('profiles').update({'role': role}).eq('id', userId); + } + + Future setPassword({ + required String userId, + required String password, + }) async { + await _invokeAdminFunction( + action: 'set_password', + payload: {'userId': userId, 'password': password}, + ); + } + + Future setLock({required String userId, required bool locked}) async { + await _invokeAdminFunction( + action: 'set_lock', + payload: {'userId': userId, 'locked': locked}, + ); + } + + Future fetchStatus(String userId) async { + final data = await _invokeAdminFunction( + action: 'get_user', + payload: {'userId': userId}, + ); + final user = (data as Map)['user'] as Map; + final bannedUntilRaw = user['banned_until'] as String?; + return AdminUserStatus( + email: user['email'] as String?, + bannedUntil: bannedUntilRaw == null + ? null + : DateTime.tryParse(bannedUntilRaw), + ); + } + + Future _invokeAdminFunction({ + required String action, + required Map payload, + }) async { + final response = await _client.functions.invoke( + 'admin_user_management', + body: {'action': action, ...payload}, + ); + if (response.status != 200) { + throw Exception(_extractErrorMessage(response.data)); + } + return response.data; + } + + String _extractErrorMessage(dynamic data) { + if (data is Map) { + final error = data['error']; + if (error is String && error.trim().isNotEmpty) { + return error; + } + final message = data['message']; + if (message is String && message.trim().isNotEmpty) { + return message; + } + } + return 'Admin request failed.'; + } +} diff --git a/lib/providers/auth_provider.dart b/lib/providers/auth_provider.dart new file mode 100644 index 00000000..be0016f0 --- /dev/null +++ b/lib/providers/auth_provider.dart @@ -0,0 +1,69 @@ +import 'dart:async'; + +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:supabase_flutter/supabase_flutter.dart'; + +import 'supabase_provider.dart'; + +final authStateChangesProvider = StreamProvider((ref) { + final client = ref.watch(supabaseClientProvider); + return client.auth.onAuthStateChange; +}); + +final sessionProvider = Provider((ref) { + final client = ref.watch(supabaseClientProvider); + return client.auth.currentSession; +}); + +final authControllerProvider = Provider((ref) { + final client = ref.watch(supabaseClientProvider); + return AuthController(client); +}); + +class AuthController { + AuthController(this._client); + + final SupabaseClient _client; + + Future signInWithPassword({ + required String email, + required String password, + }) { + return _client.auth.signInWithPassword(email: email, password: password); + } + + Future signUp({ + required String email, + required String password, + String? fullName, + List? officeIds, + }) { + return _client.auth.signUp( + email: email, + password: password, + data: { + if (fullName != null && fullName.trim().isNotEmpty) + 'full_name': fullName.trim(), + if (officeIds != null && officeIds.isNotEmpty) 'office_ids': officeIds, + }, + ); + } + + Future signInWithGoogle({String? redirectTo}) { + return _client.auth.signInWithOAuth( + OAuthProvider.google, + redirectTo: redirectTo, + ); + } + + Future signInWithMeta({String? redirectTo}) { + return _client.auth.signInWithOAuth( + OAuthProvider.facebook, + redirectTo: redirectTo, + ); + } + + Future signOut() { + return _client.auth.signOut(); + } +} diff --git a/lib/providers/notifications_provider.dart b/lib/providers/notifications_provider.dart new file mode 100644 index 00000000..42014348 --- /dev/null +++ b/lib/providers/notifications_provider.dart @@ -0,0 +1,97 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:supabase_flutter/supabase_flutter.dart'; + +import '../models/notification_item.dart'; +import 'profile_provider.dart'; +import 'supabase_provider.dart'; + +final notificationsProvider = StreamProvider>((ref) { + final userId = ref.watch(currentUserIdProvider); + if (userId == null) { + return const Stream.empty(); + } + final client = ref.watch(supabaseClientProvider); + return client + .from('notifications') + .stream(primaryKey: ['id']) + .eq('user_id', userId) + .order('created_at', ascending: false) + .map((rows) => rows.map(NotificationItem.fromMap).toList()); +}); + +final unreadNotificationsCountProvider = Provider((ref) { + final notificationsAsync = ref.watch(notificationsProvider); + return notificationsAsync.maybeWhen( + data: (items) => items.where((item) => item.isUnread).length, + orElse: () => 0, + ); +}); + +final notificationsControllerProvider = Provider(( + ref, +) { + final client = ref.watch(supabaseClientProvider); + return NotificationsController(client); +}); + +class NotificationsController { + NotificationsController(this._client); + + final SupabaseClient _client; + + Future createMentionNotifications({ + required List userIds, + required String actorId, + required int messageId, + String? ticketId, + String? taskId, + }) async { + if (userIds.isEmpty) return; + if ((ticketId == null || ticketId.isEmpty) && + (taskId == null || taskId.isEmpty)) { + return; + } + final rows = userIds + .map( + (userId) => { + 'user_id': userId, + 'actor_id': actorId, + 'ticket_id': ticketId, + 'task_id': taskId, + 'message_id': messageId, + 'type': 'mention', + }, + ) + .toList(); + await _client.from('notifications').insert(rows); + } + + Future markRead(String id) async { + await _client + .from('notifications') + .update({'read_at': DateTime.now().toUtc().toIso8601String()}) + .eq('id', id); + } + + Future markReadForTicket(String ticketId) async { + final userId = _client.auth.currentUser?.id; + if (userId == null) return; + await _client + .from('notifications') + .update({'read_at': DateTime.now().toUtc().toIso8601String()}) + .eq('ticket_id', ticketId) + .eq('user_id', userId) + .filter('read_at', 'is', null); + } + + Future markReadForTask(String taskId) async { + final userId = _client.auth.currentUser?.id; + if (userId == null) return; + await _client + .from('notifications') + .update({'read_at': DateTime.now().toUtc().toIso8601String()}) + .eq('task_id', taskId) + .eq('user_id', userId) + .filter('read_at', 'is', null); + } +} diff --git a/lib/providers/profile_provider.dart b/lib/providers/profile_provider.dart new file mode 100644 index 00000000..a110e175 --- /dev/null +++ b/lib/providers/profile_provider.dart @@ -0,0 +1,45 @@ +import 'dart:async'; + +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../models/profile.dart'; +import 'auth_provider.dart'; +import 'supabase_provider.dart'; + +final currentUserIdProvider = Provider((ref) { + final authState = ref.watch(authStateChangesProvider); + return authState.maybeWhen( + data: (state) => state.session?.user.id, + orElse: () => ref.watch(sessionProvider)?.user.id, + ); +}); + +final currentProfileProvider = StreamProvider((ref) { + final userId = ref.watch(currentUserIdProvider); + if (userId == null) { + return const Stream.empty(); + } + final client = ref.watch(supabaseClientProvider); + return client + .from('profiles') + .stream(primaryKey: ['id']) + .eq('id', userId) + .map((rows) => rows.isEmpty ? null : Profile.fromMap(rows.first)); +}); + +final profilesProvider = StreamProvider>((ref) { + final client = ref.watch(supabaseClientProvider); + return client + .from('profiles') + .stream(primaryKey: ['id']) + .order('full_name') + .map((rows) => rows.map(Profile.fromMap).toList()); +}); + +final isAdminProvider = Provider((ref) { + final profileAsync = ref.watch(currentProfileProvider); + return profileAsync.maybeWhen( + data: (profile) => profile?.role == 'admin', + orElse: () => false, + ); +}); diff --git a/lib/providers/supabase_provider.dart b/lib/providers/supabase_provider.dart new file mode 100644 index 00000000..5729a60c --- /dev/null +++ b/lib/providers/supabase_provider.dart @@ -0,0 +1,6 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:supabase_flutter/supabase_flutter.dart'; + +final supabaseClientProvider = Provider((ref) { + return Supabase.instance.client; +}); diff --git a/lib/providers/tasks_provider.dart b/lib/providers/tasks_provider.dart new file mode 100644 index 00000000..17e29c2d --- /dev/null +++ b/lib/providers/tasks_provider.dart @@ -0,0 +1,235 @@ +import 'dart:async'; + +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:supabase_flutter/supabase_flutter.dart'; +import '../models/task.dart'; +import '../models/task_assignment.dart'; +import 'profile_provider.dart'; +import 'supabase_provider.dart'; +import 'tickets_provider.dart'; +import 'user_offices_provider.dart'; + +final tasksProvider = StreamProvider>((ref) { + final client = ref.watch(supabaseClientProvider); + final profileAsync = ref.watch(currentProfileProvider); + final ticketsAsync = ref.watch(ticketsProvider); + final assignmentsAsync = ref.watch(userOfficesProvider); + + final profile = profileAsync.valueOrNull; + if (profile == null) { + return Stream.value(const []); + } + + final isGlobal = + profile.role == 'admin' || + profile.role == 'dispatcher' || + profile.role == 'it_staff'; + + if (isGlobal) { + return client + .from('tasks') + .stream(primaryKey: ['id']) + .order('queue_order', ascending: true) + .order('created_at') + .map((rows) => rows.map(Task.fromMap).toList()); + } + + final allowedTicketIds = + ticketsAsync.valueOrNull?.map((ticket) => ticket.id).toList() ?? + []; + final officeIds = + assignmentsAsync.valueOrNull + ?.where((assignment) => assignment.userId == profile.id) + .map((assignment) => assignment.officeId) + .toSet() + .toList() ?? + []; + + if (allowedTicketIds.isEmpty && officeIds.isEmpty) { + return Stream.value(const []); + } + + return client + .from('tasks') + .stream(primaryKey: ['id']) + .order('queue_order', ascending: true) + .order('created_at') + .map( + (rows) => rows.map(Task.fromMap).where((task) { + final matchesTicket = + task.ticketId != null && allowedTicketIds.contains(task.ticketId); + final matchesOffice = + task.officeId != null && officeIds.contains(task.officeId); + return matchesTicket || matchesOffice; + }).toList(), + ); +}); + +final taskAssignmentsProvider = StreamProvider>((ref) { + final client = ref.watch(supabaseClientProvider); + return client + .from('task_assignments') + .stream(primaryKey: ['task_id', 'user_id']) + .map((rows) => rows.map(TaskAssignment.fromMap).toList()); +}); + +final taskAssignmentsControllerProvider = Provider(( + ref, +) { + final client = ref.watch(supabaseClientProvider); + return TaskAssignmentsController(client); +}); + +final tasksControllerProvider = Provider((ref) { + final client = ref.watch(supabaseClientProvider); + return TasksController(client); +}); + +class TasksController { + TasksController(this._client); + + final SupabaseClient _client; + + Future updateTaskStatus({ + required String taskId, + required String status, + }) async { + await _client.from('tasks').update({'status': status}).eq('id', taskId); + } + + Future createTask({ + required String title, + required String description, + required String officeId, + }) async { + final actorId = _client.auth.currentUser?.id; + final data = await _client + .from('tasks') + .insert({ + 'title': title, + 'description': description, + 'office_id': officeId, + }) + .select('id') + .single(); + final taskId = data['id'] as String?; + if (taskId == null) return; + unawaited(_notifyCreated(taskId: taskId, actorId: actorId)); + } + + Future _notifyCreated({ + required String taskId, + required String? actorId, + }) async { + try { + final recipients = await _fetchRoleUserIds( + roles: const ['dispatcher', 'it_staff'], + excludeUserId: actorId, + ); + if (recipients.isEmpty) return; + final rows = recipients + .map( + (userId) => { + 'user_id': userId, + 'actor_id': actorId, + 'task_id': taskId, + 'type': 'created', + }, + ) + .toList(); + await _client.from('notifications').insert(rows); + } catch (_) { + return; + } + } + + Future> _fetchRoleUserIds({ + required List roles, + required String? excludeUserId, + }) async { + try { + final data = await _client + .from('profiles') + .select('id, role') + .inFilter('role', roles); + final rows = data as List; + final ids = rows + .map((row) => row['id'] as String?) + .whereType() + .where((id) => id.isNotEmpty && id != excludeUserId) + .toList(); + return ids; + } catch (_) { + return []; + } + } +} + +class TaskAssignmentsController { + TaskAssignmentsController(this._client); + + final SupabaseClient _client; + + Future replaceAssignments({ + required String taskId, + required String? ticketId, + required List newUserIds, + required List currentUserIds, + }) async { + final nextIds = newUserIds.toSet(); + final currentIds = currentUserIds.toSet(); + final toAdd = nextIds.difference(currentIds).toList(); + final toRemove = currentIds.difference(nextIds).toList(); + + if (toAdd.isNotEmpty) { + final rows = toAdd + .map((userId) => {'task_id': taskId, 'user_id': userId}) + .toList(); + await _client.from('task_assignments').insert(rows); + await _notifyAssigned(taskId: taskId, ticketId: ticketId, userIds: toAdd); + } + if (toRemove.isNotEmpty) { + await _client + .from('task_assignments') + .delete() + .eq('task_id', taskId) + .inFilter('user_id', toRemove); + } + } + + Future _notifyAssigned({ + required String taskId, + required String? ticketId, + required List userIds, + }) async { + if (userIds.isEmpty) return; + try { + final actorId = _client.auth.currentUser?.id; + final rows = userIds + .map( + (userId) => { + 'user_id': userId, + 'actor_id': actorId, + 'task_id': taskId, + 'ticket_id': ticketId, + 'type': 'assignment', + }, + ) + .toList(); + await _client.from('notifications').insert(rows); + } catch (_) { + return; + } + } + + Future removeAssignment({ + required String taskId, + required String userId, + }) async { + await _client + .from('task_assignments') + .delete() + .eq('task_id', taskId) + .eq('user_id', userId); + } +} diff --git a/lib/providers/tickets_provider.dart b/lib/providers/tickets_provider.dart new file mode 100644 index 00000000..111067e2 --- /dev/null +++ b/lib/providers/tickets_provider.dart @@ -0,0 +1,248 @@ +import 'dart:async'; + +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:supabase_flutter/supabase_flutter.dart'; + +import '../models/office.dart'; +import '../models/ticket.dart'; +import '../models/ticket_message.dart'; +import 'profile_provider.dart'; +import 'supabase_provider.dart'; +import 'user_offices_provider.dart'; + +final officesProvider = StreamProvider>((ref) { + final client = ref.watch(supabaseClientProvider); + return client + .from('offices') + .stream(primaryKey: ['id']) + .order('name') + .map((rows) => rows.map(Office.fromMap).toList()); +}); + +final officesOnceProvider = FutureProvider>((ref) async { + final client = ref.watch(supabaseClientProvider); + final rows = await client.from('offices').select().order('name'); + return (rows as List) + .map((row) => Office.fromMap(row as Map)) + .toList(); +}); + +final officesControllerProvider = Provider((ref) { + final client = ref.watch(supabaseClientProvider); + return OfficesController(client); +}); + +final ticketsProvider = StreamProvider>((ref) { + final client = ref.watch(supabaseClientProvider); + final profileAsync = ref.watch(currentProfileProvider); + final assignmentsAsync = ref.watch(userOfficesProvider); + + final profile = profileAsync.valueOrNull; + if (profile == null) { + return Stream.value(const []); + } + + final isGlobal = + profile.role == 'admin' || + profile.role == 'dispatcher' || + profile.role == 'it_staff'; + + if (isGlobal) { + return client + .from('tickets') + .stream(primaryKey: ['id']) + .order('created_at', ascending: false) + .map((rows) => rows.map(Ticket.fromMap).toList()); + } + + final officeIds = + assignmentsAsync.valueOrNull + ?.where((assignment) => assignment.userId == profile.id) + .map((assignment) => assignment.officeId) + .toSet() + .toList() ?? + []; + if (officeIds.isEmpty) { + return Stream.value(const []); + } + + return client + .from('tickets') + .stream(primaryKey: ['id']) + .inFilter('office_id', officeIds) + .order('created_at', ascending: false) + .map((rows) => rows.map(Ticket.fromMap).toList()); +}); + +final ticketMessagesProvider = + StreamProvider.family, String>((ref, ticketId) { + final client = ref.watch(supabaseClientProvider); + return client + .from('ticket_messages') + .stream(primaryKey: ['id']) + .eq('ticket_id', ticketId) + .order('created_at', ascending: false) + .map((rows) => rows.map(TicketMessage.fromMap).toList()); + }); + +final ticketMessagesAllProvider = StreamProvider>((ref) { + final client = ref.watch(supabaseClientProvider); + return client + .from('ticket_messages') + .stream(primaryKey: ['id']) + .order('created_at', ascending: false) + .map((rows) => rows.map(TicketMessage.fromMap).toList()); +}); + +final taskMessagesProvider = StreamProvider.family, String>( + (ref, taskId) { + final client = ref.watch(supabaseClientProvider); + return client + .from('ticket_messages') + .stream(primaryKey: ['id']) + .eq('task_id', taskId) + .order('created_at', ascending: false) + .map((rows) => rows.map(TicketMessage.fromMap).toList()); + }, +); + +final ticketsControllerProvider = Provider((ref) { + final client = ref.watch(supabaseClientProvider); + return TicketsController(client); +}); + +class TicketsController { + TicketsController(this._client); + + final SupabaseClient _client; + + Future createTicket({ + required String subject, + required String description, + required String officeId, + }) async { + final actorId = _client.auth.currentUser?.id; + final data = await _client + .from('tickets') + .insert({ + 'subject': subject, + 'description': description, + 'office_id': officeId, + 'creator_id': _client.auth.currentUser?.id, + }) + .select('id') + .single(); + final ticketId = data['id'] as String?; + if (ticketId == null) return; + unawaited(_notifyCreated(ticketId: ticketId, actorId: actorId)); + } + + Future _notifyCreated({ + required String ticketId, + required String? actorId, + }) async { + try { + final recipients = await _fetchRoleUserIds( + roles: const ['dispatcher', 'it_staff'], + excludeUserId: actorId, + ); + if (recipients.isEmpty) return; + final rows = recipients + .map( + (userId) => { + 'user_id': userId, + 'actor_id': actorId, + 'ticket_id': ticketId, + 'type': 'created', + }, + ) + .toList(); + await _client.from('notifications').insert(rows); + } catch (_) { + return; + } + } + + Future> _fetchRoleUserIds({ + required List roles, + required String? excludeUserId, + }) async { + try { + final data = await _client + .from('profiles') + .select('id, role') + .inFilter('role', roles); + final rows = data as List; + final ids = rows + .map((row) => row['id'] as String?) + .whereType() + .where((id) => id.isNotEmpty && id != excludeUserId) + .toList(); + return ids; + } catch (_) { + return []; + } + } + + Future sendTicketMessage({ + required String ticketId, + required String content, + }) async { + final data = await _client + .from('ticket_messages') + .insert({ + 'ticket_id': ticketId, + 'content': content, + 'sender_id': _client.auth.currentUser?.id, + }) + .select() + .single(); + return TicketMessage.fromMap(data); + } + + Future sendTaskMessage({ + required String taskId, + required String? ticketId, + required String content, + }) async { + final payload = { + 'task_id': taskId, + 'content': content, + 'sender_id': _client.auth.currentUser?.id, + }; + if (ticketId != null) { + payload['ticket_id'] = ticketId; + } + final data = await _client + .from('ticket_messages') + .insert(payload) + .select() + .single(); + return TicketMessage.fromMap(data); + } + + Future updateTicketStatus({ + required String ticketId, + required String status, + }) async { + await _client.from('tickets').update({'status': status}).eq('id', ticketId); + } +} + +class OfficesController { + OfficesController(this._client); + + final SupabaseClient _client; + + Future createOffice({required String name}) async { + await _client.from('offices').insert({'name': name}); + } + + Future updateOffice({required String id, required String name}) async { + await _client.from('offices').update({'name': name}).eq('id', id); + } + + Future deleteOffice({required String id}) async { + await _client.from('offices').delete().eq('id', id); + } +} diff --git a/lib/providers/typing_provider.dart b/lib/providers/typing_provider.dart new file mode 100644 index 00000000..0d7993fa --- /dev/null +++ b/lib/providers/typing_provider.dart @@ -0,0 +1,152 @@ +import 'dart:async'; + +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:supabase_flutter/supabase_flutter.dart'; + +import 'supabase_provider.dart'; + +class TypingIndicatorState { + const TypingIndicatorState({ + required this.userIds, + required this.channelStatus, + required this.lastPayload, + }); + + final Set userIds; + final String channelStatus; + final Map lastPayload; + + TypingIndicatorState copyWith({ + Set? userIds, + String? channelStatus, + Map? lastPayload, + }) { + return TypingIndicatorState( + userIds: userIds ?? this.userIds, + channelStatus: channelStatus ?? this.channelStatus, + lastPayload: lastPayload ?? this.lastPayload, + ); + } +} + +final typingIndicatorProvider = StateNotifierProvider.autoDispose + .family(( + ref, + ticketId, + ) { + final client = ref.watch(supabaseClientProvider); + final controller = TypingIndicatorController(client, ticketId); + ref.onDispose(controller.dispose); + return controller; + }); + +class TypingIndicatorController extends StateNotifier { + TypingIndicatorController(this._client, this._ticketId) + : super( + const TypingIndicatorState( + userIds: {}, + channelStatus: 'init', + lastPayload: {}, + ), + ) { + _initChannel(); + } + + final SupabaseClient _client; + final String _ticketId; + RealtimeChannel? _channel; + Timer? _typingTimer; + final Map _remoteTimeouts = {}; + + void _initChannel() { + final channel = _client.channel('typing:$_ticketId'); + channel.onBroadcast( + event: 'typing', + callback: (payload) { + final Map data = _extractPayload(payload); + final userId = data['user_id'] as String?; + final rawType = data['type']?.toString(); + final currentUserId = _client.auth.currentUser?.id; + state = state.copyWith(lastPayload: data); + if (userId == null || userId == currentUserId) { + return; + } + if (rawType == 'stop') { + _clearRemoteTyping(userId); + return; + } + _markRemoteTyping(userId); + }, + ); + channel.subscribe((status, error) { + state = state.copyWith(channelStatus: status.name); + }); + _channel = channel; + } + + Map _extractPayload(dynamic payload) { + if (payload is Map) { + final inner = payload['payload']; + if (inner is Map) { + return inner; + } + return payload; + } + final dynamic inner = payload.payload; + if (inner is Map) { + return inner; + } + return {}; + } + + void userTyping() { + if (_client.auth.currentUser?.id == null) return; + _sendTypingEvent('start'); + _typingTimer?.cancel(); + _typingTimer = Timer(const Duration(milliseconds: 150), () { + _sendTypingEvent('stop'); + }); + } + + void stopTyping() { + _typingTimer?.cancel(); + _sendTypingEvent('stop'); + } + + void _markRemoteTyping(String userId) { + final updated = {...state.userIds, userId}; + state = state.copyWith(userIds: updated); + _remoteTimeouts[userId]?.cancel(); + _remoteTimeouts[userId] = Timer(const Duration(milliseconds: 400), () { + _clearRemoteTyping(userId); + }); + } + + void _clearRemoteTyping(String userId) { + final updated = {...state.userIds}..remove(userId); + state = state.copyWith(userIds: updated); + _remoteTimeouts[userId]?.cancel(); + _remoteTimeouts.remove(userId); + } + + void _sendTypingEvent(String type) { + final userId = _client.auth.currentUser?.id; + if (userId == null || _channel == null) return; + _channel!.sendBroadcastMessage( + event: 'typing', + payload: {'user_id': userId, 'type': type}, + ); + } + + @override + void dispose() { + stopTyping(); + _typingTimer?.cancel(); + for (final timer in _remoteTimeouts.values) { + timer.cancel(); + } + _remoteTimeouts.clear(); + _channel?.unsubscribe(); + super.dispose(); + } +} diff --git a/lib/providers/user_offices_provider.dart b/lib/providers/user_offices_provider.dart new file mode 100644 index 00000000..6742bb66 --- /dev/null +++ b/lib/providers/user_offices_provider.dart @@ -0,0 +1,46 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:supabase_flutter/supabase_flutter.dart'; + +import '../models/user_office.dart'; +import 'supabase_provider.dart'; + +final userOfficesProvider = StreamProvider>((ref) { + final client = ref.watch(supabaseClientProvider); + return client + .from('user_offices') + .stream(primaryKey: ['user_id', 'office_id']) + .order('created_at') + .map((rows) => rows.map(UserOffice.fromMap).toList()); +}); + +final userOfficesControllerProvider = Provider((ref) { + final client = ref.watch(supabaseClientProvider); + return UserOfficesController(client); +}); + +class UserOfficesController { + UserOfficesController(this._client); + + final SupabaseClient _client; + + Future assignUserOffice({ + required String userId, + required String officeId, + }) async { + await _client.from('user_offices').insert({ + 'user_id': userId, + 'office_id': officeId, + }); + } + + Future removeUserOffice({ + required String userId, + required String officeId, + }) async { + await _client + .from('user_offices') + .delete() + .eq('user_id', userId) + .eq('office_id', officeId); + } +} diff --git a/lib/routing/app_router.dart b/lib/routing/app_router.dart new file mode 100644 index 00000000..ea346904 --- /dev/null +++ b/lib/routing/app_router.dart @@ -0,0 +1,160 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../providers/auth_provider.dart'; +import '../providers/profile_provider.dart'; +import '../screens/auth/login_screen.dart'; +import '../screens/auth/signup_screen.dart'; +import '../screens/admin/offices_screen.dart'; +import '../screens/admin/user_management_screen.dart'; +import '../screens/dashboard/dashboard_screen.dart'; +import '../screens/notifications/notifications_screen.dart'; +import '../screens/shared/under_development_screen.dart'; +import '../screens/tasks/task_detail_screen.dart'; +import '../screens/tasks/tasks_list_screen.dart'; +import '../screens/tickets/ticket_detail_screen.dart'; +import '../screens/tickets/tickets_list_screen.dart'; +import '../widgets/app_shell.dart'; + +final appRouterProvider = Provider((ref) { + final notifier = RouterNotifier(ref); + ref.onDispose(notifier.dispose); + + return GoRouter( + initialLocation: '/dashboard', + refreshListenable: notifier, + redirect: (context, state) { + final authState = ref.read(authStateChangesProvider); + final session = authState.maybeWhen( + data: (state) => state.session, + orElse: () => ref.read(sessionProvider), + ); + final isAuthRoute = + state.fullPath == '/login' || state.fullPath == '/signup'; + final isSignedIn = session != null; + final profileAsync = ref.read(currentProfileProvider); + final isAdminRoute = state.matchedLocation.startsWith('/settings'); + final isAdmin = profileAsync.maybeWhen( + data: (profile) => profile?.role == 'admin', + orElse: () => false, + ); + + if (!isSignedIn && !isAuthRoute) { + return '/login'; + } + if (isSignedIn && isAuthRoute) { + return '/dashboard'; + } + if (isAdminRoute && !isAdmin) { + return '/tickets'; + } + return null; + }, + routes: [ + GoRoute(path: '/login', builder: (context, state) => const LoginScreen()), + GoRoute( + path: '/signup', + builder: (context, state) => const SignUpScreen(), + ), + ShellRoute( + builder: (context, state, child) => AppScaffold(child: child), + routes: [ + GoRoute( + path: '/dashboard', + builder: (context, state) => const DashboardScreen(), + ), + GoRoute( + path: '/tickets', + builder: (context, state) => const TicketsListScreen(), + routes: [ + GoRoute( + path: ':id', + builder: (context, state) => TicketDetailScreen( + ticketId: state.pathParameters['id'] ?? '', + ), + ), + ], + ), + GoRoute( + path: '/tasks', + builder: (context, state) => const TasksListScreen(), + routes: [ + GoRoute( + path: ':id', + builder: (context, state) => + TaskDetailScreen(taskId: state.pathParameters['id'] ?? ''), + ), + ], + ), + GoRoute( + path: '/events', + builder: (context, state) => const UnderDevelopmentScreen( + title: 'Events', + subtitle: 'Event monitoring is under development.', + icon: Icons.event, + ), + ), + GoRoute( + path: '/announcements', + builder: (context, state) => const UnderDevelopmentScreen( + title: 'Announcement', + subtitle: 'Operational broadcasts are coming soon.', + icon: Icons.campaign, + ), + ), + GoRoute( + path: '/workforce', + builder: (context, state) => const UnderDevelopmentScreen( + title: 'Workforce', + subtitle: 'Workforce management is in progress.', + icon: Icons.groups, + ), + ), + GoRoute( + path: '/reports', + builder: (context, state) => const UnderDevelopmentScreen( + title: 'Reports', + subtitle: 'Reporting automation is under development.', + icon: Icons.analytics, + ), + ), + GoRoute( + path: '/settings/users', + builder: (context, state) => const UserManagementScreen(), + ), + GoRoute( + path: '/settings/offices', + builder: (context, state) => const OfficesScreen(), + ), + GoRoute( + path: '/notifications', + builder: (context, state) => const NotificationsScreen(), + ), + ], + ), + ], + ); +}); + +class RouterNotifier extends ChangeNotifier { + RouterNotifier(this.ref) { + _authSub = ref.listen(authStateChangesProvider, (previous, next) { + notifyListeners(); + }); + _profileSub = ref.listen(currentProfileProvider, (previous, next) { + notifyListeners(); + }); + } + + final Ref ref; + late final ProviderSubscription _authSub; + late final ProviderSubscription _profileSub; + + @override + void dispose() { + _authSub.close(); + _profileSub.close(); + super.dispose(); + } +} diff --git a/lib/screens/admin/offices_screen.dart b/lib/screens/admin/offices_screen.dart new file mode 100644 index 00000000..2c7f48a3 --- /dev/null +++ b/lib/screens/admin/offices_screen.dart @@ -0,0 +1,185 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../models/office.dart'; +import '../../providers/profile_provider.dart'; +import '../../providers/tickets_provider.dart'; +import '../../widgets/responsive_body.dart'; + +class OfficesScreen extends ConsumerWidget { + const OfficesScreen({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final isAdmin = ref.watch(isAdminProvider); + final officesAsync = ref.watch(officesProvider); + + return Scaffold( + body: ResponsiveBody( + maxWidth: 800, + child: !isAdmin + ? const Center(child: Text('Admin access required.')) + : officesAsync.when( + data: (offices) { + if (offices.isEmpty) { + return const Center(child: Text('No offices found.')); + } + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsets.only(top: 16, bottom: 8), + child: Row( + children: [ + Expanded( + child: Text( + 'Office Management', + style: Theme.of(context).textTheme.titleLarge + ?.copyWith(fontWeight: FontWeight.w700), + ), + ), + TextButton.icon( + onPressed: () => context.go('/settings/users'), + icon: const Icon(Icons.group), + label: const Text('User access'), + ), + ], + ), + ), + Expanded( + child: ListView.separated( + padding: const EdgeInsets.only(bottom: 24), + itemCount: offices.length, + separatorBuilder: (_, index) => + const SizedBox(height: 12), + itemBuilder: (context, index) { + final office = offices[index]; + return ListTile( + leading: const Icon(Icons.apartment_outlined), + title: Text(office.name), + trailing: Wrap( + spacing: 8, + children: [ + IconButton( + tooltip: 'Edit', + icon: const Icon(Icons.edit), + onPressed: () => _showOfficeDialog( + context, + ref, + office: office, + ), + ), + IconButton( + tooltip: 'Delete', + icon: const Icon(Icons.delete), + onPressed: () => + _confirmDelete(context, ref, office), + ), + ], + ), + ); + }, + ), + ), + ], + ); + }, + loading: () => const Center(child: CircularProgressIndicator()), + error: (error, _) => + Center(child: Text('Failed to load offices: $error')), + ), + ), + floatingActionButton: isAdmin + ? FloatingActionButton.extended( + onPressed: () => _showOfficeDialog(context, ref), + icon: const Icon(Icons.add), + label: const Text('New Office'), + ) + : null, + ); + } + + Future _showOfficeDialog( + BuildContext context, + WidgetRef ref, { + Office? office, + }) async { + final nameController = TextEditingController(text: office?.name ?? ''); + + await showDialog( + context: context, + builder: (dialogContext) { + return AlertDialog( + title: Text(office == null ? 'Create Office' : 'Edit Office'), + content: TextField( + controller: nameController, + decoration: const InputDecoration(labelText: 'Office name'), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(), + child: const Text('Cancel'), + ), + FilledButton( + onPressed: () async { + final name = nameController.text.trim(); + if (name.isEmpty) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Name is required.')), + ); + return; + } + final controller = ref.read(officesControllerProvider); + if (office == null) { + await controller.createOffice(name: name); + } else { + await controller.updateOffice(id: office.id, name: name); + } + ref.invalidate(officesProvider); + if (context.mounted) { + Navigator.of(dialogContext).pop(); + } + }, + child: Text(office == null ? 'Create' : 'Save'), + ), + ], + ); + }, + ); + } + + Future _confirmDelete( + BuildContext context, + WidgetRef ref, + Office office, + ) async { + await showDialog( + context: context, + builder: (dialogContext) { + return AlertDialog( + title: const Text('Delete Office'), + content: Text('Delete ${office.name}? This cannot be undone.'), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(), + child: const Text('Cancel'), + ), + FilledButton( + onPressed: () async { + await ref + .read(officesControllerProvider) + .deleteOffice(id: office.id); + ref.invalidate(officesProvider); + if (context.mounted) { + Navigator.of(dialogContext).pop(); + } + }, + child: const Text('Delete'), + ), + ], + ); + }, + ); + } +} diff --git a/lib/screens/admin/user_management_screen.dart b/lib/screens/admin/user_management_screen.dart new file mode 100644 index 00000000..39b0f45e --- /dev/null +++ b/lib/screens/admin/user_management_screen.dart @@ -0,0 +1,672 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../models/office.dart'; +import '../../models/profile.dart'; +import '../../models/ticket_message.dart'; +import '../../models/user_office.dart'; +import '../../providers/admin_user_provider.dart'; +import '../../providers/profile_provider.dart'; +import '../../providers/tickets_provider.dart'; +import '../../providers/user_offices_provider.dart'; +import '../../widgets/responsive_body.dart'; + +class UserManagementScreen extends ConsumerStatefulWidget { + const UserManagementScreen({super.key}); + + @override + ConsumerState createState() => + _UserManagementScreenState(); +} + +class _UserManagementScreenState extends ConsumerState { + static const List _roles = [ + 'standard', + 'dispatcher', + 'it_staff', + 'admin', + ]; + + final _fullNameController = TextEditingController(); + + String? _selectedUserId; + String? _selectedRole; + Set _selectedOfficeIds = {}; + AdminUserStatus? _selectedStatus; + bool _isSaving = false; + bool _isStatusLoading = false; + final Map _statusCache = {}; + final Set _statusLoading = {}; + final Set _statusErrors = {}; + Set _prefetchedUserIds = {}; + + @override + void dispose() { + _fullNameController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final isAdmin = ref.watch(isAdminProvider); + final profilesAsync = ref.watch(profilesProvider); + final officesAsync = ref.watch(officesProvider); + final assignmentsAsync = ref.watch(userOfficesProvider); + final messagesAsync = ref.watch(ticketMessagesAllProvider); + + return Scaffold( + body: ResponsiveBody( + maxWidth: 1080, + child: !isAdmin + ? const Center(child: Text('Admin access required.')) + : _buildContent( + context, + profilesAsync, + officesAsync, + assignmentsAsync, + messagesAsync, + ), + ), + ); + } + + Widget _buildContent( + BuildContext context, + AsyncValue> profilesAsync, + AsyncValue> officesAsync, + AsyncValue> assignmentsAsync, + AsyncValue> messagesAsync, + ) { + if (profilesAsync.isLoading || + officesAsync.isLoading || + assignmentsAsync.isLoading || + messagesAsync.isLoading) { + return const Center(child: CircularProgressIndicator()); + } + + if (profilesAsync.hasError || + officesAsync.hasError || + assignmentsAsync.hasError || + messagesAsync.hasError) { + final error = + profilesAsync.error ?? + officesAsync.error ?? + assignmentsAsync.error ?? + messagesAsync.error ?? + 'Unknown error'; + return Center(child: Text('Failed to load data: $error')); + } + + final profiles = profilesAsync.valueOrNull ?? []; + final offices = officesAsync.valueOrNull ?? []; + final assignments = assignmentsAsync.valueOrNull ?? []; + final messages = messagesAsync.valueOrNull ?? []; + + _prefetchStatuses(profiles); + + final lastActiveByUser = {}; + for (final message in messages) { + final senderId = message.senderId; + if (senderId == null) continue; + final current = lastActiveByUser[senderId]; + if (current == null || message.createdAt.isAfter(current)) { + lastActiveByUser[senderId] = message.createdAt; + } + } + + return Padding( + padding: const EdgeInsets.symmetric(vertical: 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text( + 'User Management', + style: Theme.of( + context, + ).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.w700), + ), + const SizedBox(height: 16), + Expanded( + child: _buildUserTable( + context, + profiles, + offices, + assignments, + lastActiveByUser, + ), + ), + ], + ), + ); + } + + Widget _buildUserTable( + BuildContext context, + List profiles, + List offices, + List assignments, + Map lastActiveByUser, + ) { + if (profiles.isEmpty) { + return const Center(child: Text('No users found.')); + } + final officeNameById = { + for (final office in offices) office.id: office.name, + }; + + final officeCountByUser = {}; + for (final assignment in assignments) { + officeCountByUser.update( + assignment.userId, + (value) => value + 1, + ifAbsent: () => 1, + ); + } + + return Material( + color: Theme.of(context).colorScheme.surface, + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: ConstrainedBox( + constraints: const BoxConstraints(minWidth: 720), + child: SingleChildScrollView( + child: DataTable( + headingRowHeight: 46, + dataRowMinHeight: 48, + dataRowMaxHeight: 64, + columnSpacing: 24, + horizontalMargin: 16, + dividerThickness: 1, + headingRowColor: MaterialStateProperty.resolveWith( + (states) => Theme.of(context).colorScheme.surfaceVariant, + ), + columns: const [ + DataColumn(label: Text('User')), + DataColumn(label: Text('Email')), + DataColumn(label: Text('Role')), + DataColumn(label: Text('Offices')), + DataColumn(label: Text('Status')), + DataColumn(label: Text('Last active')), + ], + rows: profiles.asMap().entries.map((entry) { + final index = entry.key; + final profile = entry.value; + final label = profile.fullName.isEmpty + ? profile.id + : profile.fullName; + final status = _statusCache[profile.id]; + final hasError = _statusErrors.contains(profile.id); + final isLoading = _statusLoading.contains(profile.id); + final email = hasError + ? 'Unavailable' + : (status?.email ?? (isLoading ? 'Loading...' : 'N/A')); + final statusLabel = hasError + ? 'Unavailable' + : (status == null + ? (isLoading ? 'Loading...' : 'Unknown') + : (status.isLocked ? 'Locked' : 'Active')); + final officeCount = officeCountByUser[profile.id] ?? 0; + final officeLabel = officeCount == 0 ? 'None' : '$officeCount'; + final officeNames = assignments + .where((assignment) => assignment.userId == profile.id) + .map( + (assignment) => + officeNameById[assignment.officeId] ?? + assignment.officeId, + ) + .toList(); + final officesText = officeNames.isEmpty + ? 'No offices' + : officeNames.join(', '); + final lastActive = _formatLastActive( + lastActiveByUser[profile.id]?.toLocal(), + ); + + return DataRow.byIndex( + index: index, + onSelectChanged: (selected) { + if (selected != true) return; + _showUserDialog(context, profile, offices, assignments); + }, + color: MaterialStateProperty.resolveWith((states) { + if (states.contains(MaterialState.selected)) { + return Theme.of( + context, + ).colorScheme.surfaceTint.withOpacity(0.12); + } + if (index.isEven) { + return Theme.of( + context, + ).colorScheme.surface.withOpacity(0.6); + } + return Theme.of(context).colorScheme.surface; + }), + cells: [ + DataCell(Text(label)), + DataCell(Text(email)), + DataCell(Text(profile.role)), + DataCell( + Tooltip(message: officesText, child: Text(officeLabel)), + ), + DataCell(Text(statusLabel)), + DataCell(Text(lastActive)), + ], + ); + }).toList(), + ), + ), + ), + ), + ); + } + + void _ensureStatusLoaded(String userId) { + if (_statusCache.containsKey(userId) || _statusLoading.contains(userId)) { + return; + } + _statusLoading.add(userId); + _statusErrors.remove(userId); + ref + .read(adminUserControllerProvider) + .fetchStatus(userId) + .then((status) { + if (!mounted) return; + setState(() { + _statusCache[userId] = status; + _statusLoading.remove(userId); + }); + }) + .catchError((_) { + if (!mounted) return; + setState(() { + _statusLoading.remove(userId); + _statusErrors.add(userId); + }); + }); + } + + void _prefetchStatuses(List profiles) { + final ids = profiles.map((profile) => profile.id).toSet(); + final missing = ids.difference(_prefetchedUserIds); + if (missing.isEmpty) return; + _prefetchedUserIds = ids; + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + for (final userId in missing) { + _ensureStatusLoaded(userId); + } + }); + } + + Future _showUserDialog( + BuildContext context, + Profile profile, + List offices, + List assignments, + ) async { + await _selectUser(profile); + final currentOfficeIds = assignments + .where((assignment) => assignment.userId == profile.id) + .map((assignment) => assignment.officeId) + .toSet(); + + if (!context.mounted) return; + await showDialog( + context: context, + builder: (dialogContext) { + return StatefulBuilder( + builder: (context, setDialogState) { + return AlertDialog( + title: const Text('Update user'), + content: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 520), + child: SingleChildScrollView( + child: _buildUserForm( + context, + profile, + offices, + currentOfficeIds, + setDialogState, + ), + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(), + child: const Text('Close'), + ), + ], + ); + }, + ); + }, + ); + } + + Widget _buildUserForm( + BuildContext context, + Profile profile, + List offices, + Set currentOfficeIds, + StateSetter setDialogState, + ) { + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + TextFormField( + controller: _fullNameController, + decoration: const InputDecoration(labelText: 'Full name'), + ), + const SizedBox(height: 12), + DropdownButtonFormField( + key: ValueKey('role_${_selectedUserId ?? 'none'}'), + initialValue: _selectedRole, + items: _roles + .map((role) => DropdownMenuItem(value: role, child: Text(role))) + .toList(), + onChanged: (value) => setDialogState(() => _selectedRole = value), + decoration: const InputDecoration(labelText: 'Role'), + ), + const SizedBox(height: 12), + _buildStatusRow(profile), + const SizedBox(height: 16), + Text('Offices', style: Theme.of(context).textTheme.titleSmall), + const SizedBox(height: 8), + if (offices.isEmpty) const Text('No offices available.'), + if (offices.isNotEmpty) + Column( + children: offices + .map( + (office) => CheckboxListTile( + value: _selectedOfficeIds.contains(office.id), + onChanged: _isSaving + ? null + : (selected) { + setDialogState(() { + if (selected == true) { + _selectedOfficeIds.add(office.id); + } else { + _selectedOfficeIds.remove(office.id); + } + }); + }, + title: Text(office.name), + controlAffinity: ListTileControlAffinity.leading, + contentPadding: EdgeInsets.zero, + ), + ) + .toList(), + ), + const SizedBox(height: 16), + Row( + children: [ + Expanded( + child: FilledButton( + onPressed: _isSaving + ? null + : () async { + final saved = await _saveChanges( + context, + profile, + currentOfficeIds, + setDialogState, + ); + if (saved && context.mounted) { + Navigator.of(context).pop(); + } + }, + child: _isSaving + ? const SizedBox( + height: 18, + width: 18, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Text('Save changes'), + ), + ), + ], + ), + ], + ); + } + + Widget _buildStatusRow(Profile profile) { + final email = _selectedStatus?.email; + final isLocked = _selectedStatus?.isLocked ?? false; + final lockLabel = isLocked ? 'Unlock' : 'Lock'; + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Email: ${email ?? 'Loading...'}', + style: Theme.of(context).textTheme.bodySmall, + ), + const SizedBox(height: 8), + Row( + children: [ + OutlinedButton.icon( + onPressed: _isStatusLoading + ? null + : () => _showPasswordResetDialog(profile.id), + icon: const Icon(Icons.password), + label: const Text('Reset password'), + ), + const SizedBox(width: 12), + OutlinedButton.icon( + onPressed: _isStatusLoading + ? null + : () => _toggleLock(profile.id, !isLocked), + icon: Icon(isLocked ? Icons.lock_open : Icons.lock), + label: Text(lockLabel), + ), + ], + ), + ], + ); + } + + Future _selectUser(Profile profile) async { + setState(() { + _selectedUserId = profile.id; + _selectedRole = profile.role; + _fullNameController.text = profile.fullName; + _selectedStatus = null; + _isStatusLoading = true; + }); + + final assignments = ref.read(userOfficesProvider).valueOrNull ?? []; + final officeIds = assignments + .where((assignment) => assignment.userId == profile.id) + .map((assignment) => assignment.officeId) + .toSet(); + setState(() => _selectedOfficeIds = officeIds); + + try { + final status = await ref + .read(adminUserControllerProvider) + .fetchStatus(profile.id); + if (mounted) { + setState(() { + _selectedStatus = status; + _statusCache[profile.id] = status; + }); + } + } catch (_) { + if (mounted) { + setState( + () => + _selectedStatus = AdminUserStatus(email: null, bannedUntil: null), + ); + } + } finally { + if (mounted) { + setState(() => _isStatusLoading = false); + } + } + } + + Future _saveChanges( + BuildContext context, + Profile profile, + Set currentOfficeIds, + StateSetter setDialogState, + ) async { + final role = _selectedRole ?? profile.role; + final fullName = _fullNameController.text.trim(); + if (fullName.isEmpty) { + ScaffoldMessenger.of( + context, + ).showSnackBar(const SnackBar(content: Text('Full name is required.'))); + return false; + } + + if (_selectedOfficeIds.isEmpty) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Select at least one office.')), + ); + return false; + } + + setDialogState(() => _isSaving = true); + try { + await ref + .read(adminUserControllerProvider) + .updateProfile(userId: profile.id, fullName: fullName, role: role); + + final toAdd = _selectedOfficeIds.difference(currentOfficeIds); + final toRemove = currentOfficeIds.difference(_selectedOfficeIds); + final controller = ref.read(userOfficesControllerProvider); + + for (final officeId in toAdd) { + await controller.assignUserOffice( + userId: profile.id, + officeId: officeId, + ); + } + + for (final officeId in toRemove) { + await controller.removeUserOffice( + userId: profile.id, + officeId: officeId, + ); + } + + ref.invalidate(profilesProvider); + ref.invalidate(userOfficesProvider); + + if (!context.mounted) return true; + ScaffoldMessenger.of( + context, + ).showSnackBar(const SnackBar(content: Text('User updated.'))); + return true; + } catch (error) { + if (!context.mounted) return false; + ScaffoldMessenger.of( + context, + ).showSnackBar(SnackBar(content: Text('Update failed: $error'))); + return false; + } finally { + setDialogState(() => _isSaving = false); + } + } + + Future _showPasswordResetDialog(String userId) async { + final controller = TextEditingController(); + final formKey = GlobalKey(); + + await showDialog( + context: context, + builder: (dialogContext) { + return AlertDialog( + title: const Text('Set temporary password'), + content: Form( + key: formKey, + child: TextFormField( + controller: controller, + decoration: const InputDecoration(labelText: 'New password'), + obscureText: true, + validator: (value) { + if (value == null || value.trim().length < 8) { + return 'Use at least 8 characters.'; + } + return null; + }, + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(), + child: const Text('Cancel'), + ), + FilledButton( + onPressed: () async { + if (!formKey.currentState!.validate()) return; + try { + await ref + .read(adminUserControllerProvider) + .setPassword( + userId: userId, + password: controller.text.trim(), + ); + if (!dialogContext.mounted) return; + Navigator.of(dialogContext).pop(); + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Password updated.')), + ); + } catch (error) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Reset failed: $error')), + ); + } + }, + child: const Text('Update password'), + ), + ], + ); + }, + ); + } + + Future _toggleLock(String userId, bool locked) async { + setState(() => _isStatusLoading = true); + try { + await ref + .read(adminUserControllerProvider) + .setLock(userId: userId, locked: locked); + final status = await ref + .read(adminUserControllerProvider) + .fetchStatus(userId); + if (!mounted) return; + setState(() => _selectedStatus = status); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(locked ? 'User locked.' : 'User unlocked.')), + ); + } catch (error) { + if (!mounted) return; + ScaffoldMessenger.of( + context, + ).showSnackBar(SnackBar(content: Text('Lock update failed: $error'))); + } finally { + if (mounted) { + setState(() => _isStatusLoading = false); + } + } + } + + String _formatLastActive(DateTime? value) { + if (value == null) return 'N/A'; + final now = DateTime.now(); + final diff = now.difference(value); + if (diff.inMinutes < 1) return 'Just now'; + if (diff.inHours < 1) return '${diff.inMinutes}m ago'; + if (diff.inDays < 1) return '${diff.inHours}h ago'; + if (diff.inDays < 7) return '${diff.inDays}d ago'; + final month = value.month.toString().padLeft(2, '0'); + final day = value.day.toString().padLeft(2, '0'); + return '${value.year}-$month-$day'; + } +} diff --git a/lib/screens/auth/login_screen.dart b/lib/screens/auth/login_screen.dart new file mode 100644 index 00000000..462e1ab3 --- /dev/null +++ b/lib/screens/auth/login_screen.dart @@ -0,0 +1,179 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:font_awesome_flutter/font_awesome_flutter.dart'; +import 'package:go_router/go_router.dart'; + +import '../../providers/auth_provider.dart'; +import '../../widgets/responsive_body.dart'; + +class LoginScreen extends ConsumerStatefulWidget { + const LoginScreen({super.key}); + + @override + ConsumerState createState() => _LoginScreenState(); +} + +class _LoginScreenState extends ConsumerState { + final _formKey = GlobalKey(); + final _emailController = TextEditingController(); + final _passwordController = TextEditingController(); + + bool _isLoading = false; + + @override + void dispose() { + _emailController.dispose(); + _passwordController.dispose(); + super.dispose(); + } + + Future _handleEmailSignIn() async { + if (!_formKey.currentState!.validate()) return; + setState(() => _isLoading = true); + + final auth = ref.read(authControllerProvider); + try { + final response = await auth.signInWithPassword( + email: _emailController.text.trim(), + password: _passwordController.text, + ); + if (response.session != null && mounted) { + context.go('/tickets'); + } else if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Check your email to confirm sign-in.')), + ); + } + } on Exception catch (error) { + if (mounted) { + ScaffoldMessenger.of( + context, + ).showSnackBar(SnackBar(content: Text('Sign in failed: $error'))); + } + } finally { + if (mounted) { + setState(() => _isLoading = false); + } + } + } + + Future _handleOAuthSignIn({required bool google}) async { + setState(() => _isLoading = true); + final auth = ref.read(authControllerProvider); + final redirectTo = kIsWeb ? Uri.base.origin : null; + + try { + if (google) { + await auth.signInWithGoogle(redirectTo: redirectTo); + } else { + await auth.signInWithMeta(redirectTo: redirectTo); + } + } on Exception catch (error) { + if (mounted) { + ScaffoldMessenger.of( + context, + ).showSnackBar(SnackBar(content: Text('OAuth failed: $error'))); + } + } finally { + if (mounted) { + setState(() => _isLoading = false); + } + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar(title: const Text('Sign In')), + body: ResponsiveBody( + maxWidth: 480, + padding: const EdgeInsets.symmetric(vertical: 24), + child: Form( + key: _formKey, + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Center( + child: Column( + children: [ + Image.asset('assets/tasq_ico.png', height: 72, width: 72), + const SizedBox(height: 12), + Text( + 'TasQ', + style: Theme.of(context).textTheme.headlineSmall, + ), + ], + ), + ), + const SizedBox(height: 24), + TextFormField( + controller: _emailController, + decoration: const InputDecoration(labelText: 'Email'), + keyboardType: TextInputType.emailAddress, + textInputAction: TextInputAction.next, + validator: (value) { + if (value == null || value.trim().isEmpty) { + return 'Email is required.'; + } + return null; + }, + ), + const SizedBox(height: 12), + TextFormField( + controller: _passwordController, + decoration: const InputDecoration(labelText: 'Password'), + obscureText: true, + textInputAction: TextInputAction.done, + onFieldSubmitted: (_) { + if (!_isLoading) { + _handleEmailSignIn(); + } + }, + validator: (value) { + if (value == null || value.isEmpty) { + return 'Password is required.'; + } + return null; + }, + ), + const SizedBox(height: 24), + FilledButton( + onPressed: _isLoading ? null : _handleEmailSignIn, + child: _isLoading + ? const SizedBox( + height: 18, + width: 18, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Text('Sign In'), + ), + const SizedBox(height: 12), + OutlinedButton.icon( + onPressed: _isLoading + ? null + : () => _handleOAuthSignIn(google: true), + icon: const FaIcon(FontAwesomeIcons.google, size: 18), + label: const Text('Continue with Google'), + ), + const SizedBox(height: 8), + OutlinedButton.icon( + onPressed: _isLoading + ? null + : () => _handleOAuthSignIn(google: false), + icon: const FaIcon(FontAwesomeIcons.facebook, size: 18), + label: const Text('Continue with Meta'), + ), + const SizedBox(height: 16), + TextButton( + onPressed: _isLoading ? null : () => context.go('/signup'), + child: const Text('Create account'), + ), + ], + ), + ), + ), + ); + } +} diff --git a/lib/screens/auth/signup_screen.dart b/lib/screens/auth/signup_screen.dart new file mode 100644 index 00000000..b1469362 --- /dev/null +++ b/lib/screens/auth/signup_screen.dart @@ -0,0 +1,275 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../providers/auth_provider.dart'; +import '../../providers/tickets_provider.dart'; +import '../../widgets/responsive_body.dart'; + +class SignUpScreen extends ConsumerStatefulWidget { + const SignUpScreen({super.key}); + + @override + ConsumerState createState() => _SignUpScreenState(); +} + +class _SignUpScreenState extends ConsumerState { + final _formKey = GlobalKey(); + final _fullNameController = TextEditingController(); + final _emailController = TextEditingController(); + final _passwordController = TextEditingController(); + final _confirmPasswordController = TextEditingController(); + + final Set _selectedOfficeIds = {}; + double _passwordStrength = 0.0; + String _passwordStrengthLabel = 'Very weak'; + Color _passwordStrengthColor = Colors.red; + + bool _isLoading = false; + + @override + void initState() { + super.initState(); + _passwordController.addListener(_updatePasswordStrength); + } + + @override + void dispose() { + _passwordController.removeListener(_updatePasswordStrength); + _fullNameController.dispose(); + _emailController.dispose(); + _passwordController.dispose(); + _confirmPasswordController.dispose(); + super.dispose(); + } + + Future _handleSignUp() async { + if (!_formKey.currentState!.validate()) return; + if (_selectedOfficeIds.isEmpty) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Select at least one office.')), + ); + return; + } + setState(() => _isLoading = true); + + final auth = ref.read(authControllerProvider); + try { + await auth.signUp( + email: _emailController.text.trim(), + password: _passwordController.text, + fullName: _fullNameController.text.trim(), + officeIds: _selectedOfficeIds.toList(), + ); + if (mounted) { + context.go('/login'); + } + } on Exception catch (error) { + if (mounted) { + ScaffoldMessenger.of( + context, + ).showSnackBar(SnackBar(content: Text('Sign up failed: $error'))); + } + } finally { + if (mounted) { + setState(() => _isLoading = false); + } + } + } + + @override + Widget build(BuildContext context) { + final officesAsync = ref.watch(officesOnceProvider); + return Scaffold( + appBar: AppBar(title: const Text('Create Account')), + body: ResponsiveBody( + maxWidth: 480, + padding: const EdgeInsets.symmetric(vertical: 24), + child: Form( + key: _formKey, + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Center( + child: Column( + children: [ + Image.asset('assets/tasq_ico.png', height: 72, width: 72), + const SizedBox(height: 12), + Text( + 'TasQ', + style: Theme.of(context).textTheme.headlineSmall, + ), + ], + ), + ), + const SizedBox(height: 24), + TextFormField( + controller: _fullNameController, + decoration: const InputDecoration(labelText: 'Full name'), + textInputAction: TextInputAction.next, + validator: (value) { + if (value == null || value.trim().isEmpty) { + return 'Full name is required.'; + } + return null; + }, + ), + const SizedBox(height: 12), + TextFormField( + controller: _emailController, + decoration: const InputDecoration(labelText: 'Email'), + keyboardType: TextInputType.emailAddress, + textInputAction: TextInputAction.next, + validator: (value) { + if (value == null || value.trim().isEmpty) { + return 'Email is required.'; + } + return null; + }, + ), + const SizedBox(height: 12), + TextFormField( + controller: _passwordController, + decoration: const InputDecoration(labelText: 'Password'), + obscureText: true, + textInputAction: TextInputAction.next, + validator: (value) { + if (value == null || value.isEmpty) { + return 'Password is required.'; + } + if (value.length < 6) { + return 'Use at least 6 characters.'; + } + return null; + }, + ), + const SizedBox(height: 8), + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Password strength: $_passwordStrengthLabel', + style: Theme.of(context).textTheme.labelMedium, + ), + const SizedBox(height: 6), + LinearProgressIndicator( + value: _passwordStrength, + minHeight: 8, + borderRadius: BorderRadius.circular(8), + color: _passwordStrengthColor, + backgroundColor: Theme.of( + context, + ).colorScheme.surfaceContainerHighest, + ), + ], + ), + const SizedBox(height: 12), + TextFormField( + controller: _confirmPasswordController, + decoration: const InputDecoration( + labelText: 'Confirm password', + ), + obscureText: true, + textInputAction: TextInputAction.done, + onFieldSubmitted: (_) { + if (!_isLoading) { + _handleSignUp(); + } + }, + validator: (value) { + if (value == null || value.isEmpty) { + return 'Confirm your password.'; + } + if (value != _passwordController.text) { + return 'Passwords do not match.'; + } + return null; + }, + ), + const SizedBox(height: 16), + Text('Offices', style: Theme.of(context).textTheme.titleSmall), + const SizedBox(height: 8), + officesAsync.when( + data: (offices) { + if (offices.isEmpty) { + return const Text('No offices available.'); + } + return Column( + children: offices + .map( + (office) => CheckboxListTile( + value: _selectedOfficeIds.contains(office.id), + onChanged: _isLoading + ? null + : (selected) { + setState(() { + if (selected == true) { + _selectedOfficeIds.add(office.id); + } else { + _selectedOfficeIds.remove(office.id); + } + }); + }, + title: Text(office.name), + controlAffinity: ListTileControlAffinity.leading, + contentPadding: EdgeInsets.zero, + ), + ) + .toList(), + ); + }, + loading: () => const LinearProgressIndicator(), + error: (error, _) => Text('Failed to load offices: $error'), + ), + const SizedBox(height: 24), + FilledButton( + onPressed: _isLoading ? null : _handleSignUp, + child: _isLoading + ? const SizedBox( + height: 18, + width: 18, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Text('Create Account'), + ), + const SizedBox(height: 12), + TextButton( + onPressed: _isLoading ? null : () => context.go('/login'), + child: const Text('Back to sign in'), + ), + ], + ), + ), + ), + ); + } + + void _updatePasswordStrength() { + final text = _passwordController.text; + var score = 0; + if (text.length >= 8) score++; + if (text.length >= 12) score++; + if (RegExp(r'[A-Z]').hasMatch(text)) score++; + if (RegExp(r'[a-z]').hasMatch(text)) score++; + if (RegExp(r'\d').hasMatch(text)) score++; + if (RegExp(r'[!@#$%^&*(),.?":{}|<>\[\]\\/+=;_-]').hasMatch(text)) { + score++; + } + + final normalized = (score / 6).clamp(0.0, 1.0); + final (label, color) = switch (normalized) { + <= 0.2 => ('Very weak', Colors.red), + <= 0.4 => ('Weak', Colors.deepOrange), + <= 0.6 => ('Fair', Colors.orange), + <= 0.8 => ('Strong', Colors.green), + _ => ('Excellent', Colors.teal), + }; + + setState(() { + _passwordStrength = normalized; + _passwordStrengthLabel = label; + _passwordStrengthColor = color; + }); + } +} diff --git a/lib/screens/dashboard/dashboard_screen.dart b/lib/screens/dashboard/dashboard_screen.dart new file mode 100644 index 00000000..ad7cc021 --- /dev/null +++ b/lib/screens/dashboard/dashboard_screen.dart @@ -0,0 +1,637 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../models/profile.dart'; +import '../../models/task.dart'; +import '../../models/task_assignment.dart'; +import '../../models/ticket.dart'; +import '../../models/ticket_message.dart'; +import '../../providers/profile_provider.dart'; +import '../../providers/tasks_provider.dart'; +import '../../providers/tickets_provider.dart'; +import '../../widgets/responsive_body.dart'; + +class DashboardMetrics { + DashboardMetrics({ + required this.newTicketsToday, + required this.closedToday, + required this.openTickets, + required this.avgResponse, + required this.avgTriage, + required this.longestResponse, + required this.tasksCreatedToday, + required this.tasksCompletedToday, + required this.openTasks, + required this.staffRows, + }); + + final int newTicketsToday; + final int closedToday; + final int openTickets; + + final Duration? avgResponse; + final Duration? avgTriage; + final Duration? longestResponse; + + final int tasksCreatedToday; + final int tasksCompletedToday; + final int openTasks; + + final List staffRows; +} + +class StaffRowMetrics { + StaffRowMetrics({ + required this.userId, + required this.name, + required this.status, + required this.ticketsRespondedToday, + required this.tasksClosedToday, + }); + + final String userId; + final String name; + final String status; + final int ticketsRespondedToday; + final int tasksClosedToday; +} + +final dashboardMetricsProvider = Provider>((ref) { + final ticketsAsync = ref.watch(ticketsProvider); + final tasksAsync = ref.watch(tasksProvider); + final profilesAsync = ref.watch(profilesProvider); + final assignmentsAsync = ref.watch(taskAssignmentsProvider); + final messagesAsync = ref.watch(ticketMessagesAllProvider); + + final asyncValues = [ + ticketsAsync, + tasksAsync, + profilesAsync, + assignmentsAsync, + messagesAsync, + ]; + + if (asyncValues.any((value) => value.hasError)) { + final errorValue = asyncValues.firstWhere((value) => value.hasError); + final error = errorValue.error ?? 'Failed to load dashboard'; + final stack = errorValue.stackTrace ?? StackTrace.current; + return AsyncError(error, stack); + } + + if (asyncValues.any((value) => value.isLoading)) { + return const AsyncLoading(); + } + + final tickets = ticketsAsync.valueOrNull ?? const []; + final tasks = tasksAsync.valueOrNull ?? const []; + final profiles = profilesAsync.valueOrNull ?? const []; + final assignments = assignmentsAsync.valueOrNull ?? const []; + final messages = messagesAsync.valueOrNull ?? const []; + + final now = DateTime.now(); + final startOfDay = DateTime(now.year, now.month, now.day); + + final staffProfiles = profiles + .where((profile) => profile.role == 'it_staff') + .toList(); + final staffIds = profiles + .where( + (profile) => + profile.role == 'admin' || + profile.role == 'dispatcher' || + profile.role == 'it_staff', + ) + .map((profile) => profile.id) + .toSet(); + + bool isToday(DateTime value) => !value.isBefore(startOfDay); + + final firstStaffMessageByTicket = {}; + final lastStaffMessageByUser = {}; + final respondedTicketsByUser = >{}; + for (final message in messages) { + final ticketId = message.ticketId; + final senderId = message.senderId; + if (ticketId != null && senderId != null && staffIds.contains(senderId)) { + final current = firstStaffMessageByTicket[ticketId]; + if (current == null || message.createdAt.isBefore(current)) { + firstStaffMessageByTicket[ticketId] = message.createdAt; + } + final last = lastStaffMessageByUser[senderId]; + if (last == null || message.createdAt.isAfter(last)) { + lastStaffMessageByUser[senderId] = message.createdAt; + } + if (isToday(message.createdAt)) { + respondedTicketsByUser + .putIfAbsent(senderId, () => {}) + .add(ticketId); + } + } + } + + DateTime? respondedAtForTicket(Ticket ticket) { + final staffMessageAt = firstStaffMessageByTicket[ticket.id]; + if (staffMessageAt != null) { + return staffMessageAt; + } + if (ticket.promotedAt != null) { + return ticket.promotedAt; + } + return null; + } + + Duration? responseDuration(Ticket ticket) { + final respondedAt = respondedAtForTicket(ticket); + if (respondedAt == null) { + return null; + } + final duration = respondedAt.difference(ticket.createdAt); + return duration.isNegative ? Duration.zero : duration; + } + + Duration? triageDuration(Ticket ticket) { + final respondedAt = respondedAtForTicket(ticket); + if (respondedAt == null) { + return null; + } + final triageEnd = _earliestDate(ticket.promotedAt, ticket.closedAt); + if (triageEnd == null) { + return null; + } + final duration = triageEnd.difference(respondedAt); + return duration.isNegative ? Duration.zero : duration; + } + + final ticketsToday = tickets.where((ticket) => isToday(ticket.createdAt)); + final closedToday = tickets.where( + (ticket) => ticket.closedAt != null && isToday(ticket.closedAt!), + ); + final openTickets = tickets.where((ticket) => ticket.status != 'closed'); + + final responseDurationsToday = ticketsToday + .map(responseDuration) + .whereType() + .toList(); + final triageDurationsToday = ticketsToday + .map(triageDuration) + .whereType() + .toList(); + + final avgResponse = _averageDuration(responseDurationsToday); + final avgTriage = _averageDuration(triageDurationsToday); + final longestResponse = responseDurationsToday.isEmpty + ? null + : responseDurationsToday.reduce( + (a, b) => a.inSeconds >= b.inSeconds ? a : b, + ); + + final tasksCreatedToday = tasks.where((task) => isToday(task.createdAt)); + final tasksCompletedToday = tasks.where( + (task) => task.completedAt != null && isToday(task.completedAt!), + ); + final openTasks = tasks.where((task) => task.status != 'completed'); + + final taskById = {for (final task in tasks) task.id: task}; + final staffOnTask = {}; + for (final assignment in assignments) { + final task = taskById[assignment.taskId]; + if (task == null) { + continue; + } + if (task.status == 'in_progress') { + staffOnTask.add(assignment.userId); + } + } + + final tasksClosedByUser = >{}; + for (final assignment in assignments) { + final task = taskById[assignment.taskId]; + if (task == null || task.completedAt == null) { + continue; + } + if (!isToday(task.completedAt!)) { + continue; + } + tasksClosedByUser + .putIfAbsent(assignment.userId, () => {}) + .add(task.id); + } + + const triageWindow = Duration(minutes: 1); + final triageCutoff = now.subtract(triageWindow); + + final staffRows = staffProfiles.map((staff) { + final lastMessage = lastStaffMessageByUser[staff.id]; + final ticketsResponded = respondedTicketsByUser[staff.id]?.length ?? 0; + final tasksClosed = tasksClosedByUser[staff.id]?.length ?? 0; + final onTask = staffOnTask.contains(staff.id); + final inTriage = lastMessage != null && lastMessage.isAfter(triageCutoff); + final status = onTask + ? 'On task' + : inTriage + ? 'In triage' + : 'Vacant'; + + return StaffRowMetrics( + userId: staff.id, + name: staff.fullName.isNotEmpty ? staff.fullName : staff.id, + status: status, + ticketsRespondedToday: ticketsResponded, + tasksClosedToday: tasksClosed, + ); + }).toList(); + + return AsyncData( + DashboardMetrics( + newTicketsToday: ticketsToday.length, + closedToday: closedToday.length, + openTickets: openTickets.length, + avgResponse: avgResponse, + avgTriage: avgTriage, + longestResponse: longestResponse, + tasksCreatedToday: tasksCreatedToday.length, + tasksCompletedToday: tasksCompletedToday.length, + openTasks: openTasks.length, + staffRows: staffRows, + ), + ); +}); + +class DashboardScreen extends StatelessWidget { + const DashboardScreen({super.key}); + + @override + Widget build(BuildContext context) { + return ResponsiveBody( + child: LayoutBuilder( + builder: (context, constraints) { + final isWide = constraints.maxWidth >= 980; + final metricsColumn = Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.only(top: 16, bottom: 8), + child: Align( + alignment: Alignment.center, + child: Text( + 'Dashboard', + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.titleLarge?.copyWith( + fontWeight: FontWeight.w700, + ), + ), + ), + ), + const _DashboardStatusBanner(), + _sectionTitle(context, 'Core Daily KPIs'), + _cardGrid(context, [ + _MetricCard( + title: 'New tickets today', + valueBuilder: (metrics) => metrics.newTicketsToday.toString(), + ), + _MetricCard( + title: 'Closed today', + valueBuilder: (metrics) => metrics.closedToday.toString(), + ), + _MetricCard( + title: 'Open tickets', + valueBuilder: (metrics) => metrics.openTickets.toString(), + ), + ]), + const SizedBox(height: 20), + _sectionTitle(context, 'TAT / Response'), + _cardGrid(context, [ + _MetricCard( + title: 'Avg response', + valueBuilder: (metrics) => + _formatDuration(metrics.avgResponse), + ), + _MetricCard( + title: 'Avg triage', + valueBuilder: (metrics) => _formatDuration(metrics.avgTriage), + ), + _MetricCard( + title: 'Longest response', + valueBuilder: (metrics) => + _formatDuration(metrics.longestResponse), + ), + ]), + const SizedBox(height: 20), + _sectionTitle(context, 'Task Flow'), + _cardGrid(context, [ + _MetricCard( + title: 'Tasks created', + valueBuilder: (metrics) => + metrics.tasksCreatedToday.toString(), + ), + _MetricCard( + title: 'Tasks completed', + valueBuilder: (metrics) => + metrics.tasksCompletedToday.toString(), + ), + _MetricCard( + title: 'Open tasks', + valueBuilder: (metrics) => metrics.openTasks.toString(), + ), + ]), + ], + ); + + final staffColumn = Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const SizedBox(height: 16), + _sectionTitle(context, 'IT Staff Pulse'), + const _StaffTable(), + ], + ); + + if (isWide) { + return Center( + child: ConstrainedBox( + constraints: BoxConstraints(minHeight: constraints.maxHeight), + child: Row( + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + ConstrainedBox( + constraints: BoxConstraints( + maxWidth: constraints.maxWidth * 0.6, + ), + child: metricsColumn, + ), + const SizedBox(width: 20), + ConstrainedBox( + constraints: BoxConstraints( + maxWidth: constraints.maxWidth * 0.35, + ), + child: staffColumn, + ), + ], + ), + ), + ); + } + + return SingleChildScrollView( + padding: const EdgeInsets.only(bottom: 24), + child: Center( + child: ConstrainedBox( + constraints: BoxConstraints(minHeight: constraints.maxHeight), + child: Column( + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + metricsColumn, + const SizedBox(height: 12), + staffColumn, + ], + ), + ), + ), + ); + }, + ), + ); + } + + Widget _sectionTitle(BuildContext context, String title) { + return Padding( + padding: const EdgeInsets.only(bottom: 12), + child: Text( + title, + style: Theme.of( + context, + ).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.w700), + ), + ); + } + + Widget _cardGrid(BuildContext context, List cards) { + return LayoutBuilder( + builder: (context, constraints) { + final width = constraints.maxWidth; + final columns = width >= 900 + ? 3 + : width >= 620 + ? 2 + : 1; + final spacing = 12.0; + final cardWidth = (width - (columns - 1) * spacing) / columns; + return Wrap( + alignment: WrapAlignment.center, + runAlignment: WrapAlignment.center, + spacing: spacing, + runSpacing: spacing, + children: cards + .map((card) => SizedBox(width: cardWidth, child: card)) + .toList(), + ); + }, + ); + } +} + +class _DashboardStatusBanner extends ConsumerWidget { + const _DashboardStatusBanner(); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final metricsAsync = ref.watch(dashboardMetricsProvider); + return metricsAsync.when( + data: (_) => const SizedBox.shrink(), + loading: () => const Padding( + padding: EdgeInsets.only(bottom: 12), + child: LinearProgressIndicator(minHeight: 2), + ), + error: (error, _) => Padding( + padding: const EdgeInsets.only(bottom: 12), + child: Text( + 'Dashboard data error: $error', + style: Theme.of(context).textTheme.bodySmall?.copyWith( + color: Theme.of(context).colorScheme.error, + ), + ), + ), + ); + } +} + +class _MetricCard extends ConsumerWidget { + const _MetricCard({required this.title, required this.valueBuilder}); + + final String title; + final String Function(DashboardMetrics metrics) valueBuilder; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final metricsAsync = ref.watch(dashboardMetricsProvider); + final value = metricsAsync.when( + data: (metrics) => valueBuilder(metrics), + loading: () => '—', + error: (error, _) => 'Error', + ); + + return Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.surface, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: Theme.of(context).colorScheme.outlineVariant), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: Theme.of( + context, + ).textTheme.labelLarge?.copyWith(fontWeight: FontWeight.w600), + ), + const SizedBox(height: 10), + Text( + value, + style: Theme.of( + context, + ).textTheme.headlineSmall?.copyWith(fontWeight: FontWeight.w700), + ), + ], + ), + ); + } +} + +class _StaffTable extends StatelessWidget { + const _StaffTable(); + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.surface, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: Theme.of(context).colorScheme.outlineVariant), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: const [ + _StaffTableHeader(), + SizedBox(height: 8), + _StaffTableBody(), + ], + ), + ); + } +} + +class _StaffTableHeader extends StatelessWidget { + const _StaffTableHeader(); + + @override + Widget build(BuildContext context) { + final style = Theme.of( + context, + ).textTheme.labelMedium?.copyWith(fontWeight: FontWeight.w700); + return Row( + children: [ + Expanded(flex: 3, child: Text('IT Staff', style: style)), + Expanded(flex: 2, child: Text('Status', style: style)), + Expanded(flex: 2, child: Text('Tickets', style: style)), + Expanded(flex: 2, child: Text('Tasks', style: style)), + ], + ); + } +} + +class _StaffTableBody extends ConsumerWidget { + const _StaffTableBody(); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final metricsAsync = ref.watch(dashboardMetricsProvider); + return metricsAsync.when( + data: (metrics) { + if (metrics.staffRows.isEmpty) { + return Text( + 'No IT staff available.', + style: Theme.of(context).textTheme.bodySmall, + ); + } + return Column( + children: metrics.staffRows + .map((row) => _StaffRow(row: row)) + .toList(), + ); + }, + loading: () => const Text('Loading staff...'), + error: (error, _) => Text('Failed to load staff: $error'), + ); + } +} + +class _StaffRow extends StatelessWidget { + const _StaffRow({required this.row}); + + final StaffRowMetrics row; + + @override + Widget build(BuildContext context) { + final valueStyle = Theme.of(context).textTheme.bodySmall; + return Padding( + padding: const EdgeInsets.symmetric(vertical: 6), + child: Row( + children: [ + Expanded(flex: 3, child: Text(row.name, style: valueStyle)), + Expanded(flex: 2, child: Text(row.status, style: valueStyle)), + Expanded( + flex: 2, + child: Text( + row.ticketsRespondedToday.toString(), + style: valueStyle, + ), + ), + Expanded( + flex: 2, + child: Text(row.tasksClosedToday.toString(), style: valueStyle), + ), + ], + ), + ); + } +} + +Duration? _averageDuration(List durations) { + if (durations.isEmpty) { + return null; + } + final totalSeconds = durations + .map((duration) => duration.inSeconds) + .reduce((a, b) => a + b); + return Duration(seconds: (totalSeconds / durations.length).round()); +} + +DateTime? _earliestDate(DateTime? first, DateTime? second) { + if (first == null) return second; + if (second == null) return first; + return first.isBefore(second) ? first : second; +} + +String _formatDuration(Duration? duration) { + if (duration == null) { + return 'Pending'; + } + if (duration.inSeconds < 60) { + return 'Less than a minute'; + } + final hours = duration.inHours; + final minutes = duration.inMinutes.remainder(60); + if (hours > 0) { + return '${hours}h ${minutes}m'; + } + return '${minutes}m'; +} diff --git a/lib/screens/notifications/notifications_screen.dart b/lib/screens/notifications/notifications_screen.dart new file mode 100644 index 00000000..31568890 --- /dev/null +++ b/lib/screens/notifications/notifications_screen.dart @@ -0,0 +1,147 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../providers/notifications_provider.dart'; +import '../../providers/profile_provider.dart'; +import '../../providers/tasks_provider.dart'; +import '../../providers/tickets_provider.dart'; +import '../../widgets/responsive_body.dart'; + +class NotificationsScreen extends ConsumerWidget { + const NotificationsScreen({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final notificationsAsync = ref.watch(notificationsProvider); + final profilesAsync = ref.watch(profilesProvider); + final ticketsAsync = ref.watch(ticketsProvider); + final tasksAsync = ref.watch(tasksProvider); + + final profileById = { + for (final profile in profilesAsync.valueOrNull ?? []) + profile.id: profile, + }; + final ticketById = { + for (final ticket in ticketsAsync.valueOrNull ?? []) ticket.id: ticket, + }; + final taskById = { + for (final task in tasksAsync.valueOrNull ?? []) task.id: task, + }; + + return ResponsiveBody( + child: notificationsAsync.when( + data: (items) { + if (items.isEmpty) { + return const Center(child: Text('No notifications yet.')); + } + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsets.only(top: 16, bottom: 8), + child: Text( + 'Notifications', + style: Theme.of( + context, + ).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.w700), + ), + ), + Expanded( + child: ListView.separated( + padding: const EdgeInsets.only(bottom: 24), + itemCount: items.length, + separatorBuilder: (context, index) => + const SizedBox(height: 12), + itemBuilder: (context, index) { + final item = items[index]; + final actorName = item.actorId == null + ? 'System' + : (profileById[item.actorId]?.fullName ?? + item.actorId!); + final ticketSubject = item.ticketId == null + ? 'Ticket' + : (ticketById[item.ticketId]?.subject ?? + item.ticketId!); + final taskTitle = item.taskId == null + ? 'Task' + : (taskById[item.taskId]?.title ?? item.taskId!); + final subtitle = item.taskId != null + ? taskTitle + : ticketSubject; + + final title = _notificationTitle(item.type, actorName); + final icon = _notificationIcon(item.type); + + return ListTile( + leading: Icon(icon), + title: Text(title), + subtitle: Text(subtitle), + trailing: item.isUnread + ? const Icon( + Icons.circle, + size: 10, + color: Colors.red, + ) + : null, + onTap: () async { + final ticketId = item.ticketId; + final taskId = item.taskId; + if (ticketId != null) { + await ref + .read(notificationsControllerProvider) + .markReadForTicket(ticketId); + } else if (taskId != null) { + await ref + .read(notificationsControllerProvider) + .markReadForTask(taskId); + } else if (item.isUnread) { + await ref + .read(notificationsControllerProvider) + .markRead(item.id); + } + if (!context.mounted) return; + if (taskId != null) { + context.go('/tasks/$taskId'); + } else if (ticketId != null) { + context.go('/tickets/$ticketId'); + } + }, + ); + }, + ), + ), + ], + ); + }, + loading: () => const Center(child: CircularProgressIndicator()), + error: (error, _) => + Center(child: Text('Failed to load notifications: $error')), + ), + ); + } + + String _notificationTitle(String type, String actorName) { + switch (type) { + case 'assignment': + return '$actorName assigned you'; + case 'created': + return '$actorName created a new item'; + case 'mention': + default: + return '$actorName mentioned you'; + } + } + + IconData _notificationIcon(String type) { + switch (type) { + case 'assignment': + return Icons.assignment_ind_outlined; + case 'created': + return Icons.campaign_outlined; + case 'mention': + default: + return Icons.alternate_email; + } + } +} diff --git a/lib/screens/shared/under_development_screen.dart b/lib/screens/shared/under_development_screen.dart new file mode 100644 index 00000000..c897cbc9 --- /dev/null +++ b/lib/screens/shared/under_development_screen.dart @@ -0,0 +1,84 @@ +import 'package:flutter/material.dart'; + +import '../../widgets/responsive_body.dart'; + +class UnderDevelopmentScreen extends StatelessWidget { + const UnderDevelopmentScreen({ + super.key, + required this.title, + required this.subtitle, + required this.icon, + }); + + final String title; + final String subtitle; + final IconData icon; + + @override + Widget build(BuildContext context) { + return ResponsiveBody( + maxWidth: 720, + padding: const EdgeInsets.symmetric(vertical: 32), + child: Center( + child: Card( + child: Padding( + padding: const EdgeInsets.all(32), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: 72, + height: 72, + decoration: BoxDecoration( + color: Theme.of( + context, + ).colorScheme.primaryContainer.withValues(alpha: 0.7), + borderRadius: BorderRadius.circular(20), + ), + child: Icon( + icon, + size: 36, + color: Theme.of(context).colorScheme.primary, + ), + ), + const SizedBox(height: 20), + Text( + title, + style: Theme.of(context).textTheme.headlineSmall?.copyWith( + fontWeight: FontWeight.w700, + ), + textAlign: TextAlign.center, + ), + const SizedBox(height: 8), + Text( + subtitle, + style: Theme.of(context).textTheme.bodyMedium?.copyWith( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + textAlign: TextAlign.center, + ), + const SizedBox(height: 20), + Container( + padding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 8, + ), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(999), + color: Theme.of( + context, + ).colorScheme.surfaceContainerHighest, + ), + child: Text( + 'Under development', + style: Theme.of(context).textTheme.labelLarge, + ), + ), + ], + ), + ), + ), + ), + ); + } +} diff --git a/lib/screens/tasks/task_detail_screen.dart b/lib/screens/tasks/task_detail_screen.dart new file mode 100644 index 00000000..bac414ee --- /dev/null +++ b/lib/screens/tasks/task_detail_screen.dart @@ -0,0 +1,822 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../models/profile.dart'; +import '../../models/task.dart'; +import '../../models/task_assignment.dart'; +import '../../models/ticket.dart'; +import '../../models/ticket_message.dart'; +import '../../providers/notifications_provider.dart'; +import '../../providers/profile_provider.dart'; +import '../../providers/tasks_provider.dart'; +import '../../providers/tickets_provider.dart'; +import '../../providers/typing_provider.dart'; +import '../../widgets/responsive_body.dart'; +import '../../widgets/task_assignment_section.dart'; +import '../../widgets/typing_dots.dart'; + +class TaskDetailScreen extends ConsumerStatefulWidget { + const TaskDetailScreen({super.key, required this.taskId}); + + final String taskId; + + @override + ConsumerState createState() => _TaskDetailScreenState(); +} + +class _TaskDetailScreenState extends ConsumerState { + final _messageController = TextEditingController(); + static const List _statusOptions = [ + 'queued', + 'in_progress', + 'completed', + ]; + String? _mentionQuery; + int? _mentionStart; + List _mentionResults = []; + + @override + void initState() { + super.initState(); + Future.microtask( + () => ref + .read(notificationsControllerProvider) + .markReadForTask(widget.taskId), + ); + } + + @override + void dispose() { + _messageController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final tasksAsync = ref.watch(tasksProvider); + final ticketsAsync = ref.watch(ticketsProvider); + final officesAsync = ref.watch(officesProvider); + final profileAsync = ref.watch(currentProfileProvider); + final assignmentsAsync = ref.watch(taskAssignmentsProvider); + final taskMessagesAsync = ref.watch(taskMessagesProvider(widget.taskId)); + final profilesAsync = ref.watch(profilesProvider); + + final task = _findTask(tasksAsync, widget.taskId); + if (task == null) { + return const ResponsiveBody( + child: Center(child: Text('Task not found.')), + ); + } + + final ticketId = task.ticketId; + final typingChannelId = task.id; + final ticket = ticketId == null + ? null + : _findTicket(ticketsAsync, ticketId); + final officeById = { + for (final office in officesAsync.valueOrNull ?? []) office.id: office, + }; + final officeId = ticket?.officeId ?? task.officeId; + final officeName = officeId == null + ? 'Unassigned office' + : (officeById[officeId]?.name ?? officeId); + final description = ticket?.description ?? task.description; + + final canAssign = profileAsync.maybeWhen( + data: (profile) => profile != null && _canAssignStaff(profile.role), + orElse: () => false, + ); + final showAssign = canAssign && task.status != 'completed'; + final assignments = assignmentsAsync.valueOrNull ?? []; + final canUpdateStatus = _canUpdateStatus( + profileAsync.valueOrNull, + assignments, + task.id, + ); + final typingState = ref.watch(typingIndicatorProvider(typingChannelId)); + final canSendMessages = task.status != 'completed'; + + final messagesAsync = _mergeMessages( + taskMessagesAsync, + ticketId == null ? null : ref.watch(ticketMessagesProvider(ticketId)), + ); + + return ResponsiveBody( + child: Column( + children: [ + Padding( + padding: const EdgeInsets.only(top: 16, bottom: 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Align( + alignment: Alignment.center, + child: Text( + task.title.isNotEmpty ? task.title : 'Task ${task.id}', + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.titleLarge?.copyWith( + fontWeight: FontWeight.w700, + ), + ), + ), + const SizedBox(height: 6), + Align( + alignment: Alignment.center, + child: Text( + _createdByLabel(profilesAsync, task, ticket), + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.bodySmall, + ), + ), + const SizedBox(height: 8), + Wrap( + spacing: 12, + runSpacing: 8, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + _buildStatusChip(context, task, canUpdateStatus), + Text('Office: $officeName'), + ], + ), + if (description.isNotEmpty) ...[ + const SizedBox(height: 12), + Text(description), + ], + const SizedBox(height: 12), + _buildTatSection(task), + const SizedBox(height: 16), + TaskAssignmentSection(taskId: task.id, canAssign: showAssign), + ], + ), + ), + const Divider(height: 1), + Expanded( + child: messagesAsync.when( + data: (messages) => _buildMessages( + context, + messages, + profilesAsync.valueOrNull ?? [], + ), + loading: () => const Center(child: CircularProgressIndicator()), + error: (error, _) => + Center(child: Text('Failed to load messages: $error')), + ), + ), + SafeArea( + top: false, + child: Padding( + padding: const EdgeInsets.fromLTRB(0, 8, 0, 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (typingState.userIds.isNotEmpty) + Padding( + padding: const EdgeInsets.only(bottom: 6), + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 10, + vertical: 6, + ), + decoration: BoxDecoration( + color: Theme.of( + context, + ).colorScheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(16), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + _typingLabel(typingState.userIds, profilesAsync), + style: Theme.of(context).textTheme.labelSmall, + ), + const SizedBox(width: 8), + TypingDots( + size: 8, + color: Theme.of(context).colorScheme.primary, + ), + ], + ), + ), + ), + if (_mentionQuery != null) + Padding( + padding: const EdgeInsets.only(bottom: 8), + child: _buildMentionList(profilesAsync), + ), + if (!canSendMessages) + Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Text( + 'Messaging is disabled for completed tasks.', + style: Theme.of(context).textTheme.labelMedium, + ), + ), + Row( + children: [ + Expanded( + child: TextField( + controller: _messageController, + decoration: const InputDecoration( + hintText: 'Message...', + ), + textInputAction: TextInputAction.send, + enabled: canSendMessages, + onChanged: (_) => _handleComposerChanged( + profilesAsync.valueOrNull ?? [], + ref.read(currentUserIdProvider), + canSendMessages, + typingChannelId, + ), + onSubmitted: (_) => _handleSendMessage( + task, + profilesAsync.valueOrNull ?? [], + ref.read(currentUserIdProvider), + canSendMessages, + typingChannelId, + ), + ), + ), + const SizedBox(width: 12), + IconButton( + tooltip: 'Send', + onPressed: canSendMessages + ? () => _handleSendMessage( + task, + profilesAsync.valueOrNull ?? [], + ref.read(currentUserIdProvider), + canSendMessages, + typingChannelId, + ) + : null, + icon: const Icon(Icons.send), + ), + ], + ), + ], + ), + ), + ), + ], + ), + ); + } + + String _createdByLabel( + AsyncValue> profilesAsync, + Task task, + Ticket? ticket, + ) { + final creatorId = task.creatorId ?? ticket?.creatorId; + if (creatorId == null || creatorId.isEmpty) { + return 'Created by: Unknown'; + } + final profile = profilesAsync.valueOrNull + ?.where((item) => item.id == creatorId) + .firstOrNull; + final name = profile?.fullName.isNotEmpty == true + ? profile!.fullName + : creatorId; + return 'Created by: $name'; + } + + Widget _buildMessages( + BuildContext context, + List messages, + List profiles, + ) { + if (messages.isEmpty) { + return const Center(child: Text('No messages yet.')); + } + final profileById = {for (final profile in profiles) profile.id: profile}; + final currentUserId = ref.read(currentUserIdProvider); + + return ListView.builder( + reverse: true, + padding: const EdgeInsets.fromLTRB(0, 16, 0, 72), + itemCount: messages.length, + itemBuilder: (context, index) { + final message = messages[index]; + final isMe = currentUserId != null && message.senderId == currentUserId; + final senderName = message.senderId == null + ? 'System' + : profileById[message.senderId]?.fullName ?? message.senderId!; + final bubbleColor = isMe + ? Theme.of(context).colorScheme.primaryContainer + : Theme.of(context).colorScheme.surfaceContainerHighest; + final textColor = isMe + ? Theme.of(context).colorScheme.onPrimaryContainer + : Theme.of(context).colorScheme.onSurface; + + return Align( + alignment: isMe ? Alignment.centerRight : Alignment.centerLeft, + child: Column( + crossAxisAlignment: isMe + ? CrossAxisAlignment.end + : CrossAxisAlignment.start, + children: [ + if (!isMe) + Padding( + padding: const EdgeInsets.only(bottom: 4), + child: Text( + senderName, + style: Theme.of(context).textTheme.labelSmall, + ), + ), + Container( + margin: const EdgeInsets.only(bottom: 12), + padding: const EdgeInsets.all(12), + constraints: const BoxConstraints(maxWidth: 520), + decoration: BoxDecoration( + color: bubbleColor, + borderRadius: BorderRadius.only( + topLeft: const Radius.circular(16), + topRight: const Radius.circular(16), + bottomLeft: Radius.circular(isMe ? 16 : 4), + bottomRight: Radius.circular(isMe ? 4 : 16), + ), + ), + child: _buildMentionText(message.content, textColor, profiles), + ), + ], + ), + ); + }, + ); + } + + Widget _buildTatSection(Task task) { + final animateQueue = task.status == 'queued'; + final animateExecution = task.startedAt != null && task.completedAt == null; + + if (!animateQueue && !animateExecution) { + return _buildTatContent(task, DateTime.now()); + } + + return StreamBuilder( + stream: Stream.periodic(const Duration(seconds: 1), (tick) => tick), + builder: (context, snapshot) { + return _buildTatContent(task, DateTime.now()); + }, + ); + } + + Widget _buildTatContent(Task task, DateTime now) { + final queueDuration = task.status == 'queued' + ? now.difference(task.createdAt) + : _safeDuration(task.startedAt?.difference(task.createdAt)); + final executionDuration = task.status == 'queued' + ? null + : task.startedAt == null + ? null + : task.completedAt == null + ? now.difference(task.startedAt!) + : task.completedAt!.difference(task.startedAt!); + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('Queue duration: ${_formatDuration(queueDuration)}'), + const SizedBox(height: 8), + Text('Task execution time: ${_formatDuration(executionDuration)}'), + ], + ); + } + + Duration? _safeDuration(Duration? duration) { + if (duration == null) { + return null; + } + return duration.isNegative ? Duration.zero : duration; + } + + String _formatDuration(Duration? duration) { + if (duration == null) { + return 'Pending'; + } + if (duration.inSeconds < 60) { + return 'Less than a minute'; + } + final hours = duration.inHours; + final minutes = duration.inMinutes.remainder(60); + if (hours > 0) { + return '${hours}h ${minutes}m'; + } + return '${minutes}m'; + } + + Widget _buildMentionText( + String text, + Color baseColor, + List profiles, + ) { + final mentionColor = Theme.of(context).colorScheme.primary; + final spans = _mentionSpans(text, baseColor, mentionColor, profiles); + return RichText( + text: TextSpan( + children: spans, + style: TextStyle(color: baseColor), + ), + ); + } + + List _mentionSpans( + String text, + Color baseColor, + Color mentionColor, + List profiles, + ) { + final mentionLabels = profiles + .map( + (profile) => profile.fullName.isEmpty ? profile.id : profile.fullName, + ) + .where((label) => label.isNotEmpty) + .map(_escapeRegExp) + .toList(); + final pattern = mentionLabels.isEmpty + ? r'@\S+' + : '@(?:${mentionLabels.join('|')})'; + final matches = RegExp(pattern, caseSensitive: false).allMatches(text); + if (matches.isEmpty) { + return [ + TextSpan( + text: text, + style: TextStyle(color: baseColor), + ), + ]; + } + + final spans = []; + var lastIndex = 0; + for (final match in matches) { + if (match.start > lastIndex) { + spans.add( + TextSpan( + text: text.substring(lastIndex, match.start), + style: TextStyle(color: baseColor), + ), + ); + } + spans.add( + TextSpan( + text: text.substring(match.start, match.end), + style: TextStyle(color: mentionColor, fontWeight: FontWeight.w700), + ), + ); + lastIndex = match.end; + } + if (lastIndex < text.length) { + spans.add( + TextSpan( + text: text.substring(lastIndex), + style: TextStyle(color: baseColor), + ), + ); + } + return spans; + } + + String _escapeRegExp(String value) { + return value.replaceAllMapped( + RegExp(r'[\\^$.*+?()[\]{}|]'), + (match) => '\\${match[0]}', + ); + } + + AsyncValue> _mergeMessages( + AsyncValue> taskMessages, + AsyncValue>? ticketMessages, + ) { + if (ticketMessages == null) { + return taskMessages; + } + return taskMessages.when( + data: (taskData) => ticketMessages.when( + data: (ticketData) { + final byId = { + for (final message in taskData) message.id: message, + for (final message in ticketData) message.id: message, + }; + final merged = byId.values.toList() + ..sort((a, b) => b.createdAt.compareTo(a.createdAt)); + return AsyncValue.data(merged); + }, + loading: () => const AsyncLoading>(), + error: (error, stackTrace) => + AsyncError>(error, stackTrace), + ), + loading: () => const AsyncLoading>(), + error: (error, stackTrace) => + AsyncError>(error, stackTrace), + ); + } + + Future _handleSendMessage( + Task task, + List profiles, + String? currentUserId, + bool canSendMessages, + String typingChannelId, + ) async { + if (!canSendMessages) return; + final content = _messageController.text.trim(); + if (content.isEmpty) { + return; + } + ref.read(typingIndicatorProvider(typingChannelId).notifier).stopTyping(); + final message = await ref + .read(ticketsControllerProvider) + .sendTaskMessage( + taskId: task.id, + ticketId: task.ticketId, + content: content, + ); + final mentionUserIds = _extractMentionedUserIds( + content, + profiles, + currentUserId, + ); + if (mentionUserIds.isNotEmpty && currentUserId != null) { + await ref + .read(notificationsControllerProvider) + .createMentionNotifications( + userIds: mentionUserIds, + actorId: currentUserId, + ticketId: task.ticketId, + taskId: task.id, + messageId: message.id, + ); + } + ref.invalidate(taskMessagesProvider(task.id)); + if (task.ticketId != null) { + ref.invalidate(ticketMessagesProvider(task.ticketId!)); + } + if (mounted) { + _messageController.clear(); + _clearMentions(); + } + } + + void _handleComposerChanged( + List profiles, + String? currentUserId, + bool canSendMessages, + String typingChannelId, + ) { + if (!canSendMessages) { + ref.read(typingIndicatorProvider(typingChannelId).notifier).stopTyping(); + _clearMentions(); + return; + } + ref.read(typingIndicatorProvider(typingChannelId).notifier).userTyping(); + final text = _messageController.text; + final cursor = _messageController.selection.baseOffset; + if (cursor < 0) { + _clearMentions(); + return; + } + final textBeforeCursor = text.substring(0, cursor); + final atIndex = textBeforeCursor.lastIndexOf('@'); + if (atIndex == -1) { + _clearMentions(); + return; + } + if (atIndex > 0 && !_isWhitespace(textBeforeCursor[atIndex - 1])) { + _clearMentions(); + return; + } + final query = textBeforeCursor.substring(atIndex + 1); + if (query.contains(RegExp(r'\s'))) { + _clearMentions(); + return; + } + final normalizedQuery = query.toLowerCase(); + final candidates = profiles.where((profile) { + if (profile.id == currentUserId) { + return false; + } + final label = profile.fullName.isEmpty ? profile.id : profile.fullName; + return label.toLowerCase().contains(normalizedQuery); + }).toList(); + setState(() { + _mentionQuery = query; + _mentionStart = atIndex; + _mentionResults = candidates.take(6).toList(); + }); + } + + void _clearMentions() { + if (_mentionQuery == null && _mentionResults.isEmpty) { + return; + } + setState(() { + _mentionQuery = null; + _mentionStart = null; + _mentionResults = []; + }); + } + + bool _isWhitespace(String char) { + return char.trim().isEmpty; + } + + List _extractMentionedUserIds( + String content, + List profiles, + String? currentUserId, + ) { + final lower = content.toLowerCase(); + final mentioned = {}; + for (final profile in profiles) { + if (profile.id == currentUserId) continue; + final label = profile.fullName.isEmpty ? profile.id : profile.fullName; + if (label.isEmpty) continue; + final token = '@${label.toLowerCase()}'; + if (lower.contains(token)) { + mentioned.add(profile.id); + } + } + return mentioned.toList(); + } + + Widget _buildMentionList(AsyncValue> profilesAsync) { + if (_mentionResults.isEmpty) { + return const SizedBox.shrink(); + } + + return Container( + constraints: const BoxConstraints(maxHeight: 200), + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(12), + ), + child: ListView.separated( + shrinkWrap: true, + padding: const EdgeInsets.symmetric(vertical: 8), + itemCount: _mentionResults.length, + separatorBuilder: (context, index) => const SizedBox(height: 4), + itemBuilder: (context, index) { + final profile = _mentionResults[index]; + final label = profile.fullName.isEmpty + ? profile.id + : profile.fullName; + return ListTile( + dense: true, + title: Text(label), + onTap: () => _insertMention(profile), + ); + }, + ), + ); + } + + void _insertMention(Profile profile) { + final start = _mentionStart; + if (start == null) { + _clearMentions(); + return; + } + final text = _messageController.text; + final cursor = _messageController.selection.baseOffset; + final end = cursor < 0 ? text.length : cursor; + final label = profile.fullName.isEmpty ? profile.id : profile.fullName; + final mentionText = '@$label '; + final updated = text.replaceRange(start, end, mentionText); + final newCursor = start + mentionText.length; + _messageController.text = updated; + _messageController.selection = TextSelection.collapsed(offset: newCursor); + _clearMentions(); + } + + String _typingLabel( + Set userIds, + AsyncValue> profilesAsync, + ) { + final profileById = { + for (final profile in profilesAsync.valueOrNull ?? []) + profile.id: profile, + }; + final names = userIds + .map((id) => profileById[id]?.fullName ?? id) + .where((name) => name.isNotEmpty) + .toList(); + if (names.isEmpty) { + return 'Someone is typing...'; + } + if (names.length == 1) { + return '${names.first} is typing...'; + } + if (names.length == 2) { + return '${names[0]} and ${names[1]} are typing...'; + } + return '${names[0]}, ${names[1]} and others are typing...'; + } + + Task? _findTask(AsyncValue> tasksAsync, String taskId) { + return tasksAsync.maybeWhen( + data: (tasks) => tasks.where((task) => task.id == taskId).firstOrNull, + orElse: () => null, + ); + } + + Ticket? _findTicket(AsyncValue> ticketsAsync, String ticketId) { + return ticketsAsync.maybeWhen( + data: (tickets) => + tickets.where((ticket) => ticket.id == ticketId).firstOrNull, + orElse: () => null, + ); + } + + bool _canAssignStaff(String role) { + return role == 'admin' || role == 'dispatcher' || role == 'it_staff'; + } + + Widget _buildStatusChip( + BuildContext context, + Task task, + bool canUpdateStatus, + ) { + final chip = Chip( + label: Text(task.status.toUpperCase()), + backgroundColor: _statusColor(context, task.status), + labelStyle: TextStyle( + color: _statusTextColor(context, task.status), + fontWeight: FontWeight.w600, + ), + ); + + if (!canUpdateStatus) { + return chip; + } + + return PopupMenuButton( + onSelected: (value) async { + await ref + .read(tasksControllerProvider) + .updateTaskStatus(taskId: task.id, status: value); + ref.invalidate(tasksProvider); + }, + itemBuilder: (context) => _statusOptions + .map( + (status) => PopupMenuItem( + value: status, + child: Text(_statusMenuLabel(status)), + ), + ) + .toList(), + child: chip, + ); + } + + String _statusMenuLabel(String status) { + return switch (status) { + 'queued' => 'Queued', + 'in_progress' => 'In progress', + 'completed' => 'Completed', + _ => status, + }; + } + + Color _statusColor(BuildContext context, String status) { + return switch (status) { + 'queued' => Colors.blueGrey.shade200, + 'in_progress' => Colors.blue.shade300, + 'completed' => Colors.green.shade300, + _ => Theme.of(context).colorScheme.surfaceContainerHighest, + }; + } + + Color _statusTextColor(BuildContext context, String status) { + return switch (status) { + 'queued' => Colors.blueGrey.shade900, + 'in_progress' => Colors.blue.shade900, + 'completed' => Colors.green.shade900, + _ => Theme.of(context).colorScheme.onSurfaceVariant, + }; + } + + bool _canUpdateStatus( + Profile? profile, + List assignments, + String taskId, + ) { + if (profile == null) { + return false; + } + final isGlobal = + profile.role == 'admin' || + profile.role == 'dispatcher' || + profile.role == 'it_staff'; + if (isGlobal) { + return true; + } + return assignments.any( + (assignment) => + assignment.taskId == taskId && assignment.userId == profile.id, + ); + } +} + +extension _FirstOrNull on Iterable { + T? get firstOrNull => isEmpty ? null : first; +} diff --git a/lib/screens/tasks/tasks_list_screen.dart b/lib/screens/tasks/tasks_list_screen.dart new file mode 100644 index 00000000..45b360e7 --- /dev/null +++ b/lib/screens/tasks/tasks_list_screen.dart @@ -0,0 +1,319 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../models/notification_item.dart'; +import '../../models/task.dart'; +import '../../providers/notifications_provider.dart'; +import '../../providers/profile_provider.dart'; +import '../../providers/tasks_provider.dart'; +import '../../providers/tickets_provider.dart'; +import '../../providers/typing_provider.dart'; +import '../../widgets/responsive_body.dart'; +import '../../widgets/typing_dots.dart'; + +class TasksListScreen extends ConsumerWidget { + const TasksListScreen({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final tasksAsync = ref.watch(tasksProvider); + final ticketsAsync = ref.watch(ticketsProvider); + final officesAsync = ref.watch(officesProvider); + final profileAsync = ref.watch(currentProfileProvider); + final notificationsAsync = ref.watch(notificationsProvider); + + final canCreate = profileAsync.maybeWhen( + data: (profile) => + profile != null && + (profile.role == 'admin' || + profile.role == 'dispatcher' || + profile.role == 'it_staff'), + orElse: () => false, + ); + + final ticketById = { + for (final ticket in ticketsAsync.valueOrNull ?? []) ticket.id: ticket, + }; + final officeById = { + for (final office in officesAsync.valueOrNull ?? []) office.id: office, + }; + + return Scaffold( + body: ResponsiveBody( + child: tasksAsync.when( + data: (tasks) { + if (tasks.isEmpty) { + return const Center(child: Text('No tasks yet.')); + } + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsets.only(top: 16, bottom: 8), + child: Align( + alignment: Alignment.center, + child: Text( + 'Tasks', + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.titleLarge?.copyWith( + fontWeight: FontWeight.w700, + ), + ), + ), + ), + Expanded( + child: ListView.separated( + padding: const EdgeInsets.only(bottom: 24), + itemCount: tasks.length, + separatorBuilder: (context, index) => + const SizedBox(height: 12), + itemBuilder: (context, index) { + final task = tasks[index]; + final ticketId = task.ticketId; + final ticket = ticketId == null + ? null + : ticketById[ticketId]; + final officeId = ticket?.officeId ?? task.officeId; + final officeName = officeId == null + ? 'Unassigned office' + : (officeById[officeId]?.name ?? officeId); + final subtitle = _buildSubtitle(officeName, task.status); + final hasMention = _hasTaskMention( + notificationsAsync, + task, + ); + final typingChannelId = task.id; + final typingState = ref.watch( + typingIndicatorProvider(typingChannelId), + ); + final showTyping = typingState.userIds.isNotEmpty; + + return ListTile( + leading: _buildQueueBadge(context, task), + title: Text( + task.title.isNotEmpty + ? task.title + : (ticket?.subject ?? 'Task ${task.id}'), + ), + subtitle: Text(subtitle), + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + _buildStatusChip(context, task.status), + if (showTyping) ...[ + const SizedBox(width: 6), + TypingDots( + size: 6, + color: Theme.of(context).colorScheme.primary, + ), + ], + if (hasMention) + const Padding( + padding: EdgeInsets.only(left: 8), + child: Icon( + Icons.circle, + size: 10, + color: Colors.red, + ), + ), + ], + ), + onTap: () => context.go('/tasks/${task.id}'), + ); + }, + ), + ), + ], + ); + }, + loading: () => const Center(child: CircularProgressIndicator()), + error: (error, _) => + Center(child: Text('Failed to load tasks: $error')), + ), + ), + floatingActionButton: canCreate + ? FloatingActionButton.extended( + onPressed: () => _showCreateTaskDialog(context, ref), + icon: const Icon(Icons.add), + label: const Text('New Task'), + ) + : null, + ); + } + + Future _showCreateTaskDialog( + BuildContext context, + WidgetRef ref, + ) async { + final titleController = TextEditingController(); + final descriptionController = TextEditingController(); + String? selectedOfficeId; + + await showDialog( + context: context, + builder: (dialogContext) { + return StatefulBuilder( + builder: (context, setState) { + final officesAsync = ref.watch(officesProvider); + return AlertDialog( + title: const Text('Create Task'), + content: SizedBox( + width: 360, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + TextField( + controller: titleController, + decoration: const InputDecoration( + labelText: 'Task title', + ), + ), + const SizedBox(height: 12), + TextField( + controller: descriptionController, + decoration: const InputDecoration( + labelText: 'Description', + ), + maxLines: 3, + ), + const SizedBox(height: 12), + officesAsync.when( + data: (offices) { + if (offices.isEmpty) { + return const Text('No offices available.'); + } + selectedOfficeId ??= offices.first.id; + return DropdownButtonFormField( + initialValue: selectedOfficeId, + decoration: const InputDecoration( + labelText: 'Office', + ), + items: offices + .map( + (office) => DropdownMenuItem( + value: office.id, + child: Text(office.name), + ), + ) + .toList(), + onChanged: (value) => + setState(() => selectedOfficeId = value), + ); + }, + loading: () => const Align( + alignment: Alignment.centerLeft, + child: CircularProgressIndicator(), + ), + error: (error, _) => + Text('Failed to load offices: $error'), + ), + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(), + child: const Text('Cancel'), + ), + FilledButton( + onPressed: () async { + final title = titleController.text.trim(); + final description = descriptionController.text.trim(); + final officeId = selectedOfficeId; + if (title.isEmpty || officeId == null) { + return; + } + await ref + .read(tasksControllerProvider) + .createTask( + title: title, + description: description, + officeId: officeId, + ); + if (context.mounted) { + Navigator.of(dialogContext).pop(); + } + }, + child: const Text('Create'), + ), + ], + ); + }, + ); + }, + ); + } + + bool _hasTaskMention( + AsyncValue> notificationsAsync, + Task task, + ) { + return notificationsAsync.maybeWhen( + data: (items) => items.any( + (item) => + item.isUnread && + (item.taskId == task.id || item.ticketId == task.ticketId), + ), + orElse: () => false, + ); + } + + Widget _buildQueueBadge(BuildContext context, Task task) { + final queueOrder = task.queueOrder; + final isQueued = task.status == 'queued'; + if (!isQueued || queueOrder == null) { + return const Icon(Icons.fact_check_outlined); + } + return Container( + width: 40, + height: 40, + alignment: Alignment.center, + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.primaryContainer, + borderRadius: BorderRadius.circular(12), + ), + child: Text( + '#$queueOrder', + style: Theme.of(context).textTheme.labelMedium?.copyWith( + fontWeight: FontWeight.w700, + color: Theme.of(context).colorScheme.onPrimaryContainer, + ), + ), + ); + } + + String _buildSubtitle(String officeName, String status) { + final statusLabel = status.toUpperCase(); + return '$officeName · $statusLabel'; + } + + Widget _buildStatusChip(BuildContext context, String status) { + return Chip( + label: Text(status.toUpperCase()), + backgroundColor: _statusColor(context, status), + labelStyle: TextStyle( + color: _statusTextColor(context, status), + fontWeight: FontWeight.w600, + ), + ); + } + + Color _statusColor(BuildContext context, String status) { + return switch (status) { + 'queued' => Colors.blueGrey.shade200, + 'in_progress' => Colors.blue.shade300, + 'completed' => Colors.green.shade300, + _ => Theme.of(context).colorScheme.surfaceContainerHighest, + }; + } + + Color _statusTextColor(BuildContext context, String status) { + return switch (status) { + 'queued' => Colors.blueGrey.shade900, + 'in_progress' => Colors.blue.shade900, + 'completed' => Colors.green.shade900, + _ => Theme.of(context).colorScheme.onSurfaceVariant, + }; + } +} diff --git a/lib/screens/tickets/ticket_detail_screen.dart b/lib/screens/tickets/ticket_detail_screen.dart new file mode 100644 index 00000000..8356d628 --- /dev/null +++ b/lib/screens/tickets/ticket_detail_screen.dart @@ -0,0 +1,859 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; +import 'package:supabase_flutter/supabase_flutter.dart'; + +import '../../models/office.dart'; +import '../../models/profile.dart'; +import '../../models/task.dart'; +import '../../models/ticket.dart'; +import '../../models/ticket_message.dart'; +import '../../providers/notifications_provider.dart'; +import '../../providers/profile_provider.dart'; +import '../../providers/tasks_provider.dart'; +import '../../providers/tickets_provider.dart'; +import '../../providers/typing_provider.dart'; +import '../../widgets/responsive_body.dart'; +import '../../widgets/task_assignment_section.dart'; +import '../../widgets/typing_dots.dart'; + +class TicketDetailScreen extends ConsumerStatefulWidget { + const TicketDetailScreen({super.key, required this.ticketId}); + + final String ticketId; + + @override + ConsumerState createState() => _TicketDetailScreenState(); +} + +class _TicketDetailScreenState extends ConsumerState { + final _messageController = TextEditingController(); + static const List _statusOptions = ['pending', 'promoted', 'closed']; + String? _mentionQuery; + int? _mentionStart; + List _mentionResults = []; + + @override + void initState() { + super.initState(); + Future.microtask( + () => ref + .read(notificationsControllerProvider) + .markReadForTicket(widget.ticketId), + ); + } + + @override + void dispose() { + _messageController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final ticket = _findTicket(ref, widget.ticketId); + final messagesAsync = ref.watch(ticketMessagesProvider(widget.ticketId)); + final profilesAsync = ref.watch(profilesProvider); + final officesAsync = ref.watch(officesProvider); + final currentProfileAsync = ref.watch(currentProfileProvider); + final tasksAsync = ref.watch(tasksProvider); + final typingState = ref.watch(typingIndicatorProvider(widget.ticketId)); + final canPromote = currentProfileAsync.maybeWhen( + data: (profile) => profile != null && _canPromote(profile.role), + orElse: () => false, + ); + final canSendMessages = ticket != null && ticket.status != 'closed'; + final canAssign = currentProfileAsync.maybeWhen( + data: (profile) => profile != null && _canAssignStaff(profile.role), + orElse: () => false, + ); + final showAssign = canAssign && ticket?.status != 'closed'; + final taskForTicket = ticket == null + ? null + : _findTaskForTicket(tasksAsync, ticket.id); + final hasStaffMessage = _hasStaffMessage( + messagesAsync.valueOrNull ?? const [], + profilesAsync.valueOrNull ?? const [], + ); + final effectiveRespondedAt = ticket?.promotedAt != null && !hasStaffMessage + ? ticket!.promotedAt + : ticket?.respondedAt; + + return ResponsiveBody( + child: Column( + children: [ + if (ticket != null) + Padding( + padding: const EdgeInsets.symmetric(vertical: 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Align( + alignment: Alignment.center, + child: Text( + ticket.subject, + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.titleLarge?.copyWith( + fontWeight: FontWeight.w700, + ), + ), + ), + const SizedBox(height: 6), + Align( + alignment: Alignment.center, + child: Text( + _filedByLabel(profilesAsync, ticket), + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.bodySmall, + ), + ), + const SizedBox(height: 8), + Wrap( + spacing: 12, + runSpacing: 8, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + _buildStatusChip(context, ref, ticket, canPromote), + Text('Office: ${_officeLabel(officesAsync, ticket)}'), + ], + ), + const SizedBox(height: 12), + Text(ticket.description), + const SizedBox(height: 12), + _buildTatRow(context, ticket, effectiveRespondedAt), + if (taskForTicket != null) ...[ + const SizedBox(height: 16), + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: TaskAssignmentSection( + taskId: taskForTicket.id, + canAssign: showAssign, + ), + ), + const SizedBox(width: 8), + IconButton( + tooltip: 'Open task', + onPressed: () => + context.go('/tasks/${taskForTicket.id}'), + icon: const Icon(Icons.open_in_new), + ), + ], + ), + ], + ], + ), + ), + const Divider(height: 1), + Expanded( + child: messagesAsync.when( + data: (messages) { + if (messages.isEmpty) { + return const Center(child: Text('No messages yet.')); + } + final profileById = { + for (final profile in profilesAsync.valueOrNull ?? []) + profile.id: profile, + }; + return ListView.builder( + reverse: true, + padding: const EdgeInsets.fromLTRB(0, 16, 0, 72), + itemCount: messages.length, + itemBuilder: (context, index) { + final message = messages[index]; + final currentUserId = + Supabase.instance.client.auth.currentUser?.id; + final isMe = + currentUserId != null && + message.senderId == currentUserId; + final senderName = message.senderId == null + ? 'System' + : profileById[message.senderId]?.fullName ?? + message.senderId!; + final bubbleColor = isMe + ? Theme.of(context).colorScheme.primaryContainer + : Theme.of(context).colorScheme.surfaceContainerHighest; + final textColor = isMe + ? Theme.of(context).colorScheme.onPrimaryContainer + : Theme.of(context).colorScheme.onSurface; + + return Align( + alignment: isMe + ? Alignment.centerRight + : Alignment.centerLeft, + child: Column( + crossAxisAlignment: isMe + ? CrossAxisAlignment.end + : CrossAxisAlignment.start, + children: [ + if (!isMe) + Padding( + padding: const EdgeInsets.only(bottom: 4), + child: Text( + senderName, + style: Theme.of(context).textTheme.labelSmall, + ), + ), + Container( + margin: const EdgeInsets.only(bottom: 12), + padding: const EdgeInsets.all(12), + constraints: const BoxConstraints(maxWidth: 520), + decoration: BoxDecoration( + color: bubbleColor, + borderRadius: BorderRadius.only( + topLeft: const Radius.circular(16), + topRight: const Radius.circular(16), + bottomLeft: Radius.circular(isMe ? 16 : 4), + bottomRight: Radius.circular(isMe ? 4 : 16), + ), + ), + child: _buildMentionText( + message.content, + textColor, + profilesAsync.valueOrNull ?? [], + ), + ), + ], + ), + ); + }, + ); + }, + loading: () => const Center(child: CircularProgressIndicator()), + error: (error, _) => + Center(child: Text('Failed to load messages: $error')), + ), + ), + SafeArea( + top: false, + child: Padding( + padding: const EdgeInsets.fromLTRB(0, 8, 0, 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (typingState.userIds.isNotEmpty) + Padding( + padding: const EdgeInsets.only(bottom: 6), + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 10, + vertical: 6, + ), + decoration: BoxDecoration( + color: Theme.of( + context, + ).colorScheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(16), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + _typingLabel(typingState.userIds, profilesAsync), + style: Theme.of(context).textTheme.labelSmall, + ), + const SizedBox(width: 8), + TypingDots( + size: 8, + color: Theme.of(context).colorScheme.primary, + ), + ], + ), + ), + ), + if (_mentionQuery != null) + Padding( + padding: const EdgeInsets.only(bottom: 8), + child: _buildMentionList(profilesAsync), + ), + if (!canSendMessages) + Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Text( + 'Messaging is disabled for closed tickets.', + style: Theme.of(context).textTheme.labelMedium, + ), + ), + Row( + children: [ + Expanded( + child: TextField( + controller: _messageController, + decoration: const InputDecoration( + hintText: 'Message...', + ), + enabled: canSendMessages, + textInputAction: TextInputAction.send, + onChanged: canSendMessages + ? (_) => _handleComposerChanged( + profilesAsync.valueOrNull ?? [], + Supabase.instance.client.auth.currentUser?.id, + canSendMessages, + ) + : null, + onSubmitted: canSendMessages + ? (_) => _handleSendMessage( + ref, + profilesAsync.valueOrNull ?? [], + Supabase.instance.client.auth.currentUser?.id, + canSendMessages, + ) + : null, + ), + ), + const SizedBox(width: 12), + IconButton( + tooltip: 'Send', + onPressed: canSendMessages + ? () => _handleSendMessage( + ref, + profilesAsync.valueOrNull ?? [], + Supabase.instance.client.auth.currentUser?.id, + canSendMessages, + ) + : null, + icon: const Icon(Icons.send), + ), + ], + ), + ], + ), + ), + ), + ], + ), + ); + } + + String _filedByLabel(AsyncValue> profilesAsync, Ticket ticket) { + final creatorId = ticket.creatorId; + if (creatorId == null || creatorId.isEmpty) { + return 'Filed by: Unknown'; + } + final profile = profilesAsync.valueOrNull + ?.where((item) => item.id == creatorId) + .firstOrNull; + final name = profile?.fullName.isNotEmpty == true + ? profile!.fullName + : creatorId; + return 'Filed by: $name'; + } + + Ticket? _findTicket(WidgetRef ref, String ticketId) { + final ticketsAsync = ref.watch(ticketsProvider); + return ticketsAsync.maybeWhen( + data: (tickets) => + tickets.where((ticket) => ticket.id == ticketId).firstOrNull, + orElse: () => null, + ); + } + + bool _hasStaffMessage(List messages, List profiles) { + if (messages.isEmpty || profiles.isEmpty) { + return false; + } + final staffIds = profiles + .where( + (profile) => + profile.role == 'admin' || + profile.role == 'dispatcher' || + profile.role == 'it_staff', + ) + .map((profile) => profile.id) + .toSet(); + if (staffIds.isEmpty) { + return false; + } + return messages.any( + (message) => + message.senderId != null && staffIds.contains(message.senderId!), + ); + } + + Task? _findTaskForTicket(AsyncValue> tasksAsync, String ticketId) { + return tasksAsync.maybeWhen( + data: (tasks) => + tasks.where((task) => task.ticketId == ticketId).firstOrNull, + orElse: () => null, + ); + } + + Future _handleSendMessage( + WidgetRef ref, + List profiles, + String? currentUserId, + bool canSendMessages, + ) async { + if (!canSendMessages) return; + final content = _messageController.text.trim(); + if (content.isEmpty) return; + ref.read(typingIndicatorProvider(widget.ticketId).notifier).stopTyping(); + final message = await ref + .read(ticketsControllerProvider) + .sendTicketMessage(ticketId: widget.ticketId, content: content); + final mentionUserIds = _extractMentionedUserIds( + content, + profiles, + currentUserId, + ); + if (mentionUserIds.isNotEmpty && currentUserId != null) { + await ref + .read(notificationsControllerProvider) + .createMentionNotifications( + userIds: mentionUserIds, + actorId: currentUserId, + ticketId: widget.ticketId, + messageId: message.id, + ); + } + ref.invalidate(ticketMessagesProvider(widget.ticketId)); + if (mounted) { + _messageController.clear(); + _clearMentions(); + } + } + + List _extractMentionedUserIds( + String content, + List profiles, + String? currentUserId, + ) { + final lower = content.toLowerCase(); + final mentioned = {}; + for (final profile in profiles) { + if (profile.id == currentUserId) continue; + final label = profile.fullName.isEmpty ? profile.id : profile.fullName; + if (label.isEmpty) continue; + final token = '@${label.toLowerCase()}'; + if (lower.contains(token)) { + mentioned.add(profile.id); + } + } + return mentioned.toList(); + } + + void _handleComposerChanged( + List profiles, + String? currentUserId, + bool canSendMessages, + ) { + if (!canSendMessages) { + ref.read(typingIndicatorProvider(widget.ticketId).notifier).stopTyping(); + _clearMentions(); + return; + } + ref.read(typingIndicatorProvider(widget.ticketId).notifier).userTyping(); + final text = _messageController.text; + final cursor = _messageController.selection.baseOffset; + if (cursor < 0) { + _clearMentions(); + return; + } + final textBeforeCursor = text.substring(0, cursor); + final atIndex = textBeforeCursor.lastIndexOf('@'); + if (atIndex == -1) { + _clearMentions(); + return; + } + if (atIndex > 0 && !_isWhitespace(textBeforeCursor[atIndex - 1])) { + _clearMentions(); + return; + } + final query = textBeforeCursor.substring(atIndex + 1); + if (query.contains(RegExp(r'\s'))) { + _clearMentions(); + return; + } + final normalizedQuery = query.toLowerCase(); + final candidates = profiles.where((profile) { + if (profile.id == currentUserId) { + return false; + } + final label = profile.fullName.isEmpty ? profile.id : profile.fullName; + return label.toLowerCase().contains(normalizedQuery); + }).toList(); + setState(() { + _mentionQuery = query; + _mentionStart = atIndex; + _mentionResults = candidates.take(6).toList(); + }); + } + + void _clearMentions() { + if (_mentionQuery == null && _mentionResults.isEmpty) { + return; + } + setState(() { + _mentionQuery = null; + _mentionStart = null; + _mentionResults = []; + }); + } + + bool _isWhitespace(String char) { + return char.trim().isEmpty; + } + + String _typingLabel( + Set userIds, + AsyncValue> profilesAsync, + ) { + final profileById = { + for (final profile in profilesAsync.valueOrNull ?? []) + profile.id: profile, + }; + final names = userIds + .map((id) => profileById[id]?.fullName ?? id) + .where((name) => name.isNotEmpty) + .toList(); + if (names.isEmpty) { + return 'Someone is typing...'; + } + if (names.length == 1) { + return '${names.first} is typing...'; + } + if (names.length == 2) { + return '${names[0]} and ${names[1]} are typing...'; + } + return '${names[0]}, ${names[1]} and others are typing...'; + } + + Widget _buildMentionList(AsyncValue> profilesAsync) { + if (_mentionResults.isEmpty) { + return const SizedBox.shrink(); + } + + return Container( + constraints: const BoxConstraints(maxHeight: 200), + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(12), + ), + child: ListView.separated( + shrinkWrap: true, + padding: const EdgeInsets.symmetric(vertical: 8), + itemCount: _mentionResults.length, + separatorBuilder: (context, index) => const SizedBox(height: 4), + itemBuilder: (context, index) { + final profile = _mentionResults[index]; + final label = profile.fullName.isEmpty + ? profile.id + : profile.fullName; + return ListTile( + dense: true, + title: Text(label), + onTap: () => _insertMention(profile), + ); + }, + ), + ); + } + + void _insertMention(Profile profile) { + final start = _mentionStart; + if (start == null) { + _clearMentions(); + return; + } + final text = _messageController.text; + final cursor = _messageController.selection.baseOffset; + final end = cursor < 0 ? text.length : cursor; + final label = profile.fullName.isEmpty ? profile.id : profile.fullName; + final mentionText = '@$label '; + final updated = text.replaceRange(start, end, mentionText); + final newCursor = start + mentionText.length; + _messageController.text = updated; + _messageController.selection = TextSelection.collapsed(offset: newCursor); + _clearMentions(); + } + + Widget _buildTatRow( + BuildContext context, + Ticket ticket, + DateTime? respondedAtOverride, + ) { + final respondedAt = respondedAtOverride ?? ticket.respondedAt; + final responseDuration = respondedAt?.difference(ticket.createdAt); + final triageEnd = _earliestDate(ticket.promotedAt, ticket.closedAt); + final triageStart = respondedAt; + final triageDuration = triageStart == null || triageEnd == null + ? null + : triageEnd.difference(triageStart); + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Response time: ${responseDuration == null ? 'Pending' : _formatDuration(responseDuration)}', + ), + const SizedBox(height: 8), + Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Expanded( + child: Text( + 'Triage duration: ${triageDuration == null ? 'Pending' : _formatDuration(triageDuration)}', + ), + ), + IconButton( + tooltip: 'View timeline', + onPressed: () => _showTimelineDialog(context, ticket), + icon: const Icon(Icons.access_time), + ), + ], + ), + ], + ); + } + + Widget _buildMentionText( + String text, + Color baseColor, + List profiles, + ) { + final mentionColor = Theme.of(context).colorScheme.primary; + final spans = _mentionSpans(text, baseColor, mentionColor, profiles); + return RichText( + text: TextSpan( + children: spans, + style: TextStyle(color: baseColor), + ), + ); + } + + List _mentionSpans( + String text, + Color baseColor, + Color mentionColor, + List profiles, + ) { + final mentionLabels = profiles + .map( + (profile) => profile.fullName.isEmpty ? profile.id : profile.fullName, + ) + .where((label) => label.isNotEmpty) + .map(_escapeRegExp) + .toList(); + final pattern = mentionLabels.isEmpty + ? r'@\S+' + : '@(?:${mentionLabels.join('|')})'; + final matches = RegExp(pattern, caseSensitive: false).allMatches(text); + if (matches.isEmpty) { + return [ + TextSpan( + text: text, + style: TextStyle(color: baseColor), + ), + ]; + } + + final spans = []; + var lastIndex = 0; + for (final match in matches) { + if (match.start > lastIndex) { + spans.add( + TextSpan( + text: text.substring(lastIndex, match.start), + style: TextStyle(color: baseColor), + ), + ); + } + spans.add( + TextSpan( + text: text.substring(match.start, match.end), + style: TextStyle(color: mentionColor, fontWeight: FontWeight.w700), + ), + ); + lastIndex = match.end; + } + if (lastIndex < text.length) { + spans.add( + TextSpan( + text: text.substring(lastIndex), + style: TextStyle(color: baseColor), + ), + ); + } + return spans; + } + + String _escapeRegExp(String value) { + return value.replaceAllMapped( + RegExp(r'[\\^$.*+?()[\]{}|]'), + (match) => '\\${match[0]}', + ); + } + + DateTime? _earliestDate(DateTime? first, DateTime? second) { + if (first == null) return second; + if (second == null) return first; + return first.isBefore(second) ? first : second; + } + + String _officeLabel(AsyncValue> officesAsync, Ticket ticket) { + final offices = officesAsync.valueOrNull ?? []; + final office = offices + .where((item) => item.id == ticket.officeId) + .firstOrNull; + return office?.name ?? ticket.officeId; + } + + String _formatDate(DateTime value) { + final local = value.toLocal(); + final monthNames = [ + 'Jan', + 'Feb', + 'Mar', + 'Apr', + 'May', + 'Jun', + 'Jul', + 'Aug', + 'Sep', + 'Oct', + 'Nov', + 'Dec', + ]; + final month = monthNames[local.month - 1]; + final day = local.day.toString().padLeft(2, '0'); + final year = local.year.toString(); + final hour24 = local.hour; + final hour12 = hour24 % 12 == 0 ? 12 : hour24 % 12; + final minute = local.minute.toString().padLeft(2, '0'); + final ampm = hour24 >= 12 ? 'PM' : 'AM'; + return '$month $day, $year $hour12:$minute $ampm'; + } + + Future _showTimelineDialog(BuildContext context, Ticket ticket) async { + await showDialog( + context: context, + builder: (dialogContext) { + return AlertDialog( + title: const Text('Ticket Timeline'), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _timelineRow('Created', ticket.createdAt), + _timelineRow('Responded', ticket.respondedAt), + _timelineRow('Promoted', ticket.promotedAt), + _timelineRow('Closed', ticket.closedAt), + ], + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(), + child: const Text('Close'), + ), + ], + ); + }, + ); + } + + Widget _timelineRow(String label, DateTime? value) { + return Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Text('$label: ${value == null ? '—' : _formatDate(value)}'), + ); + } + + String _formatDuration(Duration duration) { + if (duration.inSeconds < 60) { + return 'Less than a minute'; + } + final hours = duration.inHours; + final minutes = duration.inMinutes.remainder(60); + if (hours > 0) { + return '${hours}h ${minutes}m'; + } + return '${minutes}m'; + } + + Widget _buildStatusChip( + BuildContext context, + WidgetRef ref, + Ticket ticket, + bool canPromote, + ) { + final isLocked = ticket.status == 'promoted' || ticket.status == 'closed'; + final chip = Chip( + label: Text(_statusLabel(ticket.status)), + backgroundColor: _statusColor(context, ticket.status), + labelStyle: TextStyle( + color: _statusTextColor(context, ticket.status), + fontWeight: FontWeight.w600, + ), + ); + + if (isLocked) { + return chip; + } + + final availableStatuses = canPromote + ? _statusOptions + : _statusOptions.where((status) => status != 'promoted').toList(); + + return PopupMenuButton( + onSelected: (value) async { + await ref + .read(ticketsControllerProvider) + .updateTicketStatus(ticketId: ticket.id, status: value); + ref.invalidate(ticketsProvider); + }, + itemBuilder: (context) => availableStatuses + .map( + (status) => PopupMenuItem( + value: status, + child: Text(_statusMenuLabel(status)), + ), + ) + .toList(), + child: chip, + ); + } + + String _statusLabel(String status) { + return status.toUpperCase(); + } + + String _statusMenuLabel(String status) { + return switch (status) { + 'pending' => 'Pending', + 'promoted' => 'Promote to Task', + 'closed' => 'Close', + _ => status, + }; + } + + bool _canPromote(String role) { + return role == 'admin' || role == 'dispatcher' || role == 'it_staff'; + } + + bool _canAssignStaff(String role) { + return role == 'admin' || role == 'dispatcher' || role == 'it_staff'; + } + + Color _statusColor(BuildContext context, String status) { + return switch (status) { + 'pending' => Colors.amber.shade300, + 'promoted' => Colors.blue.shade300, + 'closed' => Colors.green.shade300, + _ => Theme.of(context).colorScheme.surfaceContainerHighest, + }; + } + + Color _statusTextColor(BuildContext context, String status) { + return switch (status) { + 'pending' => Colors.brown.shade900, + 'promoted' => Colors.blue.shade900, + 'closed' => Colors.green.shade900, + _ => Theme.of(context).colorScheme.onSurfaceVariant, + }; + } +} + +extension _FirstOrNull on Iterable { + T? get firstOrNull => isEmpty ? null : first; +} diff --git a/lib/screens/tickets/tickets_list_screen.dart b/lib/screens/tickets/tickets_list_screen.dart new file mode 100644 index 00000000..e07dd7b1 --- /dev/null +++ b/lib/screens/tickets/tickets_list_screen.dart @@ -0,0 +1,268 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../models/office.dart'; +import '../../models/notification_item.dart'; +import '../../providers/notifications_provider.dart'; +import '../../providers/tickets_provider.dart'; +import '../../providers/typing_provider.dart'; +import '../../widgets/responsive_body.dart'; +import '../../widgets/typing_dots.dart'; + +class TicketsListScreen extends ConsumerWidget { + const TicketsListScreen({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final ticketsAsync = ref.watch(ticketsProvider); + final officesAsync = ref.watch(officesProvider); + final notificationsAsync = ref.watch(notificationsProvider); + + return Scaffold( + body: ResponsiveBody( + child: ticketsAsync.when( + data: (tickets) { + if (tickets.isEmpty) { + return const Center(child: Text('No tickets yet.')); + } + final officeById = { + for (final office in officesAsync.valueOrNull ?? []) + office.id: office, + }; + final unreadByTicketId = _unreadByTicketId(notificationsAsync); + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsets.only(top: 16, bottom: 8), + child: Align( + alignment: Alignment.center, + child: Text( + 'Tickets', + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.titleLarge?.copyWith( + fontWeight: FontWeight.w700, + ), + ), + ), + ), + Expanded( + child: ListView.separated( + padding: const EdgeInsets.only(bottom: 24), + itemCount: tickets.length, + separatorBuilder: (context, index) => + const SizedBox(height: 12), + itemBuilder: (context, index) { + final ticket = tickets[index]; + final officeName = + officeById[ticket.officeId]?.name ?? ticket.officeId; + final hasMention = unreadByTicketId[ticket.id] == true; + final typingState = ref.watch( + typingIndicatorProvider(ticket.id), + ); + final showTyping = typingState.userIds.isNotEmpty; + return ListTile( + leading: const Icon(Icons.confirmation_number_outlined), + title: Text(ticket.subject), + subtitle: Text(officeName), + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + _buildStatusChip(context, ticket.status), + if (showTyping) ...[ + const SizedBox(width: 6), + TypingDots( + size: 6, + color: Theme.of(context).colorScheme.primary, + ), + ], + if (hasMention) + const Padding( + padding: EdgeInsets.only(left: 8), + child: Icon( + Icons.circle, + size: 10, + color: Colors.red, + ), + ), + ], + ), + onTap: () => context.go('/tickets/${ticket.id}'), + ); + }, + ), + ), + ], + ); + }, + loading: () => const Center(child: CircularProgressIndicator()), + error: (error, _) => + Center(child: Text('Failed to load tickets: $error')), + ), + ), + floatingActionButton: FloatingActionButton.extended( + onPressed: () => _showCreateTicketDialog(context, ref), + icon: const Icon(Icons.add), + label: const Text('New Ticket'), + ), + ); + } + + Future _showCreateTicketDialog( + BuildContext context, + WidgetRef ref, + ) async { + final subjectController = TextEditingController(); + final descriptionController = TextEditingController(); + Office? selectedOffice; + + await showDialog( + context: context, + builder: (dialogContext) { + return StatefulBuilder( + builder: (context, setState) { + return AlertDialog( + title: const Text('Create Ticket'), + content: Consumer( + builder: (context, ref, child) { + final officesAsync = ref.watch(officesProvider); + return SizedBox( + width: 360, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + TextField( + controller: subjectController, + decoration: const InputDecoration( + labelText: 'Subject', + ), + ), + const SizedBox(height: 12), + TextField( + controller: descriptionController, + decoration: const InputDecoration( + labelText: 'Description', + ), + maxLines: 3, + ), + const SizedBox(height: 12), + officesAsync.when( + data: (offices) { + if (offices.isEmpty) { + return const Text('No offices assigned.'); + } + selectedOffice ??= offices.first; + return DropdownButtonFormField( + key: ValueKey(selectedOffice?.id), + initialValue: selectedOffice, + items: offices + .map( + (office) => DropdownMenuItem( + value: office, + child: Text(office.name), + ), + ) + .toList(), + onChanged: (value) => + setState(() => selectedOffice = value), + decoration: const InputDecoration( + labelText: 'Office', + ), + ); + }, + loading: () => const LinearProgressIndicator(), + error: (error, _) => + Text('Failed to load offices: $error'), + ), + ], + ), + ); + }, + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(), + child: const Text('Cancel'), + ), + FilledButton( + onPressed: () async { + final subject = subjectController.text.trim(); + final description = descriptionController.text.trim(); + if (subject.isEmpty || + description.isEmpty || + selectedOffice == null) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Fill out all fields.')), + ); + return; + } + await ref + .read(ticketsControllerProvider) + .createTicket( + subject: subject, + description: description, + officeId: selectedOffice!.id, + ); + ref.invalidate(ticketsProvider); + if (context.mounted) { + Navigator.of(dialogContext).pop(); + } + }, + child: const Text('Create'), + ), + ], + ); + }, + ); + }, + ); + } + + Map _unreadByTicketId( + AsyncValue> notificationsAsync, + ) { + return notificationsAsync.maybeWhen( + data: (items) { + final map = {}; + for (final item in items) { + if (item.ticketId == null) continue; + if (item.isUnread) { + map[item.ticketId!] = true; + } + } + return map; + }, + orElse: () => {}, + ); + } + + Widget _buildStatusChip(BuildContext context, String status) { + return Chip( + label: Text(status.toUpperCase()), + backgroundColor: _statusColor(context, status), + labelStyle: TextStyle( + color: _statusTextColor(context, status), + fontWeight: FontWeight.w600, + ), + ); + } + + Color _statusColor(BuildContext context, String status) { + return switch (status) { + 'pending' => Colors.amber.shade300, + 'promoted' => Colors.blue.shade300, + 'closed' => Colors.green.shade300, + _ => Theme.of(context).colorScheme.surfaceContainerHighest, + }; + } + + Color _statusTextColor(BuildContext context, String status) { + return switch (status) { + 'pending' => Colors.brown.shade900, + 'promoted' => Colors.blue.shade900, + 'closed' => Colors.green.shade900, + _ => Theme.of(context).colorScheme.onSurfaceVariant, + }; + } +} diff --git a/lib/theme/app_theme.dart b/lib/theme/app_theme.dart new file mode 100644 index 00000000..33fc206a --- /dev/null +++ b/lib/theme/app_theme.dart @@ -0,0 +1,188 @@ +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; + +class AppTheme { + static ThemeData light() { + final base = ThemeData( + colorScheme: ColorScheme.fromSeed( + seedColor: const Color(0xFF0C4A6E), + brightness: Brightness.light, + ), + useMaterial3: true, + ); + + final textTheme = GoogleFonts.spaceGroteskTextTheme(base.textTheme); + + return base.copyWith( + textTheme: textTheme, + scaffoldBackgroundColor: const Color(0xFFF6F8FA), + appBarTheme: AppBarTheme( + backgroundColor: base.colorScheme.surface, + foregroundColor: base.colorScheme.onSurface, + elevation: 0, + centerTitle: false, + titleTextStyle: textTheme.titleLarge?.copyWith( + fontWeight: FontWeight.w700, + letterSpacing: 0.2, + ), + ), + cardTheme: CardThemeData( + color: base.colorScheme.surface, + elevation: 0.6, + margin: EdgeInsets.zero, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + side: BorderSide(color: base.colorScheme.outlineVariant), + ), + ), + dividerTheme: DividerThemeData( + color: base.colorScheme.outlineVariant, + thickness: 1, + ), + inputDecorationTheme: InputDecorationTheme( + filled: true, + fillColor: base.colorScheme.surface, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: BorderSide(color: base.colorScheme.outlineVariant), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: BorderSide(color: base.colorScheme.outlineVariant), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: BorderSide(color: base.colorScheme.primary, width: 1.5), + ), + ), + filledButtonTheme: FilledButtonThemeData( + style: FilledButton.styleFrom( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + ), + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 14), + ), + ), + outlinedButtonTheme: OutlinedButtonThemeData( + style: OutlinedButton.styleFrom( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + ), + side: BorderSide(color: base.colorScheme.outline), + padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 12), + ), + ), + navigationRailTheme: NavigationRailThemeData( + backgroundColor: base.colorScheme.surface, + selectedIconTheme: IconThemeData(color: base.colorScheme.primary), + selectedLabelTextStyle: textTheme.labelLarge?.copyWith( + fontWeight: FontWeight.w600, + ), + unselectedIconTheme: IconThemeData(color: base.colorScheme.onSurface), + ), + navigationBarTheme: NavigationBarThemeData( + backgroundColor: base.colorScheme.surface, + indicatorColor: base.colorScheme.primaryContainer, + labelTextStyle: WidgetStateProperty.all( + textTheme.labelMedium?.copyWith(fontWeight: FontWeight.w600), + ), + ), + listTileTheme: ListTileThemeData( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + tileColor: base.colorScheme.surface, + ), + ); + } + + static ThemeData dark() { + final base = ThemeData( + colorScheme: ColorScheme.fromSeed( + seedColor: const Color(0xFF38BDF8), + brightness: Brightness.dark, + ), + useMaterial3: true, + ); + + final textTheme = GoogleFonts.spaceGroteskTextTheme(base.textTheme); + + return base.copyWith( + textTheme: textTheme, + scaffoldBackgroundColor: const Color(0xFF0B111A), + appBarTheme: AppBarTheme( + backgroundColor: base.colorScheme.surface, + foregroundColor: base.colorScheme.onSurface, + elevation: 0, + centerTitle: false, + titleTextStyle: textTheme.titleLarge?.copyWith( + fontWeight: FontWeight.w700, + letterSpacing: 0.2, + ), + ), + cardTheme: CardThemeData( + color: const Color(0xFF121A24), + elevation: 0, + margin: EdgeInsets.zero, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + side: BorderSide(color: base.colorScheme.outlineVariant), + ), + ), + dividerTheme: DividerThemeData( + color: base.colorScheme.outlineVariant, + thickness: 1, + ), + inputDecorationTheme: InputDecorationTheme( + filled: true, + fillColor: const Color(0xFF121A24), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: BorderSide(color: base.colorScheme.outlineVariant), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: BorderSide(color: base.colorScheme.outlineVariant), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: BorderSide(color: base.colorScheme.primary, width: 1.5), + ), + ), + filledButtonTheme: FilledButtonThemeData( + style: FilledButton.styleFrom( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + ), + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 14), + ), + ), + outlinedButtonTheme: OutlinedButtonThemeData( + style: OutlinedButton.styleFrom( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + ), + side: BorderSide(color: base.colorScheme.outline), + padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 12), + ), + ), + navigationRailTheme: NavigationRailThemeData( + backgroundColor: base.colorScheme.surface, + selectedIconTheme: IconThemeData(color: base.colorScheme.primary), + selectedLabelTextStyle: textTheme.labelLarge?.copyWith( + fontWeight: FontWeight.w600, + ), + unselectedIconTheme: IconThemeData(color: base.colorScheme.onSurface), + ), + navigationBarTheme: NavigationBarThemeData( + backgroundColor: base.colorScheme.surface, + indicatorColor: base.colorScheme.primaryContainer, + labelTextStyle: WidgetStateProperty.all( + textTheme.labelMedium?.copyWith(fontWeight: FontWeight.w600), + ), + ), + listTileTheme: ListTileThemeData( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + tileColor: const Color(0xFF121A24), + ), + ); + } +} diff --git a/lib/widgets/app_shell.dart b/lib/widgets/app_shell.dart new file mode 100644 index 00000000..8bd440f4 --- /dev/null +++ b/lib/widgets/app_shell.dart @@ -0,0 +1,470 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../providers/auth_provider.dart'; +import '../providers/notifications_provider.dart'; +import '../providers/profile_provider.dart'; + +class AppScaffold extends ConsumerWidget { + const AppScaffold({super.key, required this.child}); + + final Widget child; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final profileAsync = ref.watch(currentProfileProvider); + final role = profileAsync.maybeWhen( + data: (profile) => profile?.role ?? 'standard', + orElse: () => 'standard', + ); + final displayName = profileAsync.maybeWhen( + data: (profile) { + final name = profile?.fullName.trim() ?? ''; + return name.isNotEmpty ? name : 'User'; + }, + orElse: () => 'User', + ); + + final isStandard = role == 'standard'; + final location = GoRouterState.of(context).uri.toString(); + final sections = _buildSections(role); + + final width = MediaQuery.of(context).size.width; + final showRail = !isStandard && width >= 860; + final isExtended = !isStandard && width >= 1120; + final showDrawer = !isStandard && !showRail; + + return Scaffold( + appBar: AppBar( + title: Row( + children: [ + const Icon(Icons.memory), + const SizedBox(width: 8), + Text('TasQ'), + ], + ), + actions: [ + if (isStandard) + PopupMenuButton( + tooltip: 'Account', + onSelected: (value) { + if (value == 0) { + ref.read(authControllerProvider).signOut(); + } + }, + itemBuilder: (context) => const [ + PopupMenuItem(value: 0, child: Text('Sign out')), + ], + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 12), + child: Row( + children: [ + const Icon(Icons.account_circle), + const SizedBox(width: 8), + Text(displayName), + const SizedBox(width: 4), + const Icon(Icons.expand_more), + ], + ), + ), + ) + else + IconButton( + tooltip: 'Sign out', + onPressed: () => ref.read(authControllerProvider).signOut(), + icon: const Icon(Icons.logout), + ), + const _NotificationBell(), + ], + ), + drawer: showDrawer + ? Drawer( + child: AppSideNav( + sections: sections, + location: location, + extended: true, + displayName: displayName, + onLogout: () => ref.read(authControllerProvider).signOut(), + ), + ) + : null, + bottomNavigationBar: isStandard + ? AppBottomNav(location: location, items: _standardNavItems()) + : null, + body: Row( + children: [ + if (showRail) + AppSideNav( + sections: sections, + location: location, + extended: isExtended, + displayName: displayName, + onLogout: () => ref.read(authControllerProvider).signOut(), + ), + Expanded(child: _ShellBackground(child: child)), + ], + ), + ); + } +} + +class AppSideNav extends StatelessWidget { + const AppSideNav({ + super.key, + required this.sections, + required this.location, + required this.extended, + required this.displayName, + required this.onLogout, + }); + + final List sections; + final String location; + final bool extended; + final String displayName; + final VoidCallback onLogout; + + @override + Widget build(BuildContext context) { + final width = extended ? 240.0 : 72.0; + return Container( + width: width, + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.surface, + border: Border( + right: BorderSide( + color: Theme.of(context).colorScheme.outlineVariant, + ), + ), + ), + child: ListView( + padding: const EdgeInsets.symmetric(vertical: 12), + children: [ + Padding( + padding: EdgeInsets.symmetric( + horizontal: extended ? 16 : 12, + vertical: 8, + ), + child: Row( + children: [ + Image.asset( + 'assets/tasq_ico.png', + width: 28, + height: 28, + fit: BoxFit.contain, + ), + if (extended) ...[ + const SizedBox(width: 12), + Expanded( + child: Text( + displayName, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: Theme.of(context).textTheme.titleSmall?.copyWith( + fontWeight: FontWeight.w600, + ), + ), + ), + ], + ], + ), + ), + const SizedBox(height: 4), + for (final section in sections) ...[ + if (section.label != null && extended) + Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 8), + child: Text( + section.label!, + style: Theme.of(context).textTheme.labelMedium?.copyWith( + color: Theme.of(context).colorScheme.onSurfaceVariant, + letterSpacing: 0.4, + ), + ), + ), + for (final item in section.items) + _NavTile( + item: item, + selected: _isSelected(location, item.route), + extended: extended, + onLogout: onLogout, + ), + ], + ], + ), + ); + } +} + +class AppBottomNav extends StatelessWidget { + const AppBottomNav({super.key, required this.location, required this.items}); + + final String location; + final List items; + + @override + Widget build(BuildContext context) { + final index = _currentIndex(location, items); + return NavigationBar( + selectedIndex: index, + onDestinationSelected: (value) { + final target = items[value].route; + if (target.isNotEmpty) { + context.go(target); + } + }, + destinations: [ + for (final item in items) + NavigationDestination( + icon: Icon(item.icon), + selectedIcon: Icon(item.selectedIcon ?? item.icon), + label: item.label, + ), + ], + ); + } +} + +class _NavTile extends StatelessWidget { + const _NavTile({ + required this.item, + required this.selected, + required this.extended, + required this.onLogout, + }); + + final NavItem item; + final bool selected; + final bool extended; + final VoidCallback onLogout; + + @override + Widget build(BuildContext context) { + final colorScheme = Theme.of(context).colorScheme; + final iconColor = selected ? colorScheme.primary : colorScheme.onSurface; + final background = selected + ? colorScheme.primaryContainer.withValues(alpha: 0.6) + : Colors.transparent; + + final content = Container( + margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration( + color: background, + borderRadius: BorderRadius.circular(12), + ), + child: ListTile( + leading: Icon(item.icon, color: iconColor), + title: extended ? Text(item.label) : null, + onTap: () => item.onTap(context, onLogout: onLogout), + dense: true, + visualDensity: VisualDensity.compact, + ), + ); + + if (extended) { + return content; + } + + return Tooltip(message: item.label, child: content); + } +} + +class _NotificationBell extends ConsumerWidget { + const _NotificationBell(); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final unreadCount = ref.watch(unreadNotificationsCountProvider); + return IconButton( + tooltip: 'Notifications', + onPressed: () => context.go('/notifications'), + icon: Stack( + clipBehavior: Clip.none, + children: [ + const Icon(Icons.notifications), + if (unreadCount > 0) + const Positioned( + right: -2, + top: -2, + child: Icon(Icons.circle, size: 10, color: Colors.red), + ), + ], + ), + ); + } +} + +class _ShellBackground extends StatelessWidget { + const _ShellBackground({required this.child}); + + final Widget child; + + @override + Widget build(BuildContext context) { + return Container( + decoration: BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topLeft, + end: Alignment.bottomRight, + colors: [ + Theme.of(context).colorScheme.surface, + Theme.of(context).colorScheme.surfaceContainerLowest, + ], + ), + ), + child: child, + ); + } +} + +class NavItem { + NavItem({ + required this.label, + required this.route, + required this.icon, + this.selectedIcon, + this.isLogout = false, + }); + + final String label; + final String route; + final IconData icon; + final IconData? selectedIcon; + final bool isLogout; + + void onTap(BuildContext context, {VoidCallback? onLogout}) { + if (isLogout) { + onLogout?.call(); + return; + } + if (route.isNotEmpty) { + context.go(route); + } + } +} + +class NavSection { + NavSection({this.label, required this.items}); + + final String? label; + final List items; +} + +List _buildSections(String role) { + final mainItems = [ + NavItem( + label: 'Dashboard', + route: '/dashboard', + icon: Icons.grid_view, + selectedIcon: Icons.grid_view_rounded, + ), + NavItem( + label: 'Tickets', + route: '/tickets', + icon: Icons.support_agent_outlined, + selectedIcon: Icons.support_agent, + ), + NavItem( + label: 'Tasks', + route: '/tasks', + icon: Icons.task_outlined, + selectedIcon: Icons.task, + ), + NavItem( + label: 'Events', + route: '/events', + icon: Icons.event_outlined, + selectedIcon: Icons.event, + ), + NavItem( + label: 'Announcement', + route: '/announcements', + icon: Icons.campaign_outlined, + selectedIcon: Icons.campaign, + ), + NavItem( + label: 'Workforce', + route: '/workforce', + icon: Icons.groups_outlined, + selectedIcon: Icons.groups, + ), + NavItem( + label: 'Reports', + route: '/reports', + icon: Icons.analytics_outlined, + selectedIcon: Icons.analytics, + ), + ]; + + if (role == 'admin') { + return [ + NavSection(label: 'Operations', items: mainItems), + NavSection( + label: 'Settings', + items: [ + NavItem( + label: 'User Management', + route: '/settings/users', + icon: Icons.admin_panel_settings_outlined, + selectedIcon: Icons.admin_panel_settings, + ), + NavItem( + label: 'Office Management', + route: '/settings/offices', + icon: Icons.apartment_outlined, + selectedIcon: Icons.apartment, + ), + NavItem( + label: 'Logout', + route: '', + icon: Icons.logout, + isLogout: true, + ), + ], + ), + ]; + } + + return [NavSection(label: 'Operations', items: mainItems)]; +} + +List _standardNavItems() { + return [ + NavItem( + label: 'Dashboard', + route: '/dashboard', + icon: Icons.grid_view, + selectedIcon: Icons.grid_view_rounded, + ), + NavItem( + label: 'Tickets', + route: '/tickets', + icon: Icons.support_agent_outlined, + selectedIcon: Icons.support_agent, + ), + NavItem( + label: 'Tasks', + route: '/tasks', + icon: Icons.task_outlined, + selectedIcon: Icons.task, + ), + NavItem( + label: 'Events', + route: '/events', + icon: Icons.event_outlined, + selectedIcon: Icons.event, + ), + ]; +} + +bool _isSelected(String location, String route) { + if (route.isEmpty) return false; + if (location == route) return true; + return location.startsWith('$route/'); +} + +int _currentIndex(String location, List items) { + final index = items.indexWhere((item) => _isSelected(location, item.route)); + return index == -1 ? 0 : index; +} diff --git a/lib/widgets/responsive_body.dart b/lib/widgets/responsive_body.dart new file mode 100644 index 00000000..247894db --- /dev/null +++ b/lib/widgets/responsive_body.dart @@ -0,0 +1,46 @@ +import 'package:flutter/widgets.dart'; + +class ResponsiveBody extends StatelessWidget { + const ResponsiveBody({ + super.key, + required this.child, + this.maxWidth = 960, + this.padding = EdgeInsets.zero, + }); + + final Widget child; + final double maxWidth; + final EdgeInsetsGeometry padding; + + @override + Widget build(BuildContext context) { + return LayoutBuilder( + builder: (context, constraints) { + final width = constraints.maxWidth; + final horizontalPadding = switch (width) { + >= 1200 => 96.0, + >= 900 => 64.0, + >= 600 => 32.0, + _ => 16.0, + }; + + return Padding( + padding: padding.add( + EdgeInsets.symmetric(horizontal: horizontalPadding), + ), + child: Align( + alignment: Alignment.topCenter, + child: ConstrainedBox( + constraints: BoxConstraints(maxWidth: maxWidth), + child: SizedBox( + width: double.infinity, + height: constraints.maxHeight, + child: child, + ), + ), + ), + ); + }, + ); + } +} diff --git a/lib/widgets/task_assignment_section.dart b/lib/widgets/task_assignment_section.dart new file mode 100644 index 00000000..cfe4c604 --- /dev/null +++ b/lib/widgets/task_assignment_section.dart @@ -0,0 +1,233 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../models/profile.dart'; +import '../providers/profile_provider.dart'; +import '../providers/tasks_provider.dart'; + +class TaskAssignmentSection extends ConsumerWidget { + const TaskAssignmentSection({ + super.key, + required this.taskId, + required this.canAssign, + }); + + final String taskId; + final bool canAssign; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final profilesAsync = ref.watch(profilesProvider); + final tasksAsync = ref.watch(tasksProvider); + final assignmentsAsync = ref.watch(taskAssignmentsProvider); + + final profiles = profilesAsync.valueOrNull ?? []; + final tasks = tasksAsync.valueOrNull ?? []; + final taskTicketId = tasks + .where((task) => task.id == taskId) + .map((task) => task.ticketId) + .firstOrNull; + final assignments = assignmentsAsync.valueOrNull ?? []; + + final itStaff = + profiles.where((profile) => profile.role == 'it_staff').toList() + ..sort((a, b) => a.fullName.compareTo(b.fullName)); + + final assignedForTask = assignments + .where((assignment) => assignment.taskId == taskId) + .toList(); + final assignedIds = assignedForTask.map((a) => a.userId).toSet(); + + final activeTaskIds = tasks + .where( + (task) => task.status == 'queued' || task.status == 'in_progress', + ) + .map((task) => task.id) + .toSet(); + + final activeAssignmentsByUser = >{}; + for (final assignment in assignments) { + if (!activeTaskIds.contains(assignment.taskId)) { + continue; + } + activeAssignmentsByUser + .putIfAbsent(assignment.userId, () => {}) + .add(assignment.taskId); + } + + bool isVacant(String userId) { + final active = activeAssignmentsByUser[userId]; + if (active == null || active.isEmpty) { + return true; + } + return active.length == 1 && active.contains(taskId); + } + + final eligibleStaff = itStaff + .where( + (profile) => isVacant(profile.id) || assignedIds.contains(profile.id), + ) + .toList(); + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Text( + 'Assigned IT Staff', + style: Theme.of( + context, + ).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.w700), + ), + const Spacer(), + if (canAssign) + TextButton.icon( + onPressed: () => _showAssignmentDialog( + context, + ref, + eligibleStaff, + assignedIds, + taskTicketId, + ), + icon: const Icon(Icons.group_add), + label: const Text('Assign'), + ), + ], + ), + const SizedBox(height: 8), + if (assignedForTask.isEmpty) + Text( + 'No IT staff assigned.', + style: Theme.of(context).textTheme.bodyMedium, + ) + else + Wrap( + spacing: 8, + runSpacing: 6, + children: assignedForTask.map((assignment) { + final profile = profiles + .where((item) => item.id == assignment.userId) + .firstOrNull; + final label = profile?.fullName.isNotEmpty == true + ? profile!.fullName + : assignment.userId; + return InputChip( + label: Text(label), + onDeleted: canAssign + ? () => ref + .read(taskAssignmentsControllerProvider) + .removeAssignment( + taskId: taskId, + userId: assignment.userId, + ) + : null, + ); + }).toList(), + ), + ], + ); + } + + Future _showAssignmentDialog( + BuildContext context, + WidgetRef ref, + List eligibleStaff, + Set assignedIds, + String? taskTicketId, + ) async { + if (eligibleStaff.isEmpty && assignedIds.isEmpty) { + await showDialog( + context: context, + builder: (dialogContext) { + return AlertDialog( + title: const Text('Assign IT Staff'), + content: const Text('No vacant IT staff available.'), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(), + child: const Text('Close'), + ), + ], + ); + }, + ); + return; + } + + final selection = assignedIds.toSet(); + await showDialog( + context: context, + builder: (dialogContext) { + return StatefulBuilder( + builder: (context, setState) { + return AlertDialog( + title: const Text('Assign IT Staff'), + contentPadding: const EdgeInsets.fromLTRB(24, 20, 24, 12), + content: SizedBox( + width: 360, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 12), + child: ListView.builder( + shrinkWrap: true, + itemCount: eligibleStaff.length, + itemBuilder: (context, index) { + final staff = eligibleStaff[index]; + final name = staff.fullName.isNotEmpty + ? staff.fullName + : staff.id; + final selected = selection.contains(staff.id); + return CheckboxListTile( + value: selected, + title: Text(name), + contentPadding: const EdgeInsets.symmetric( + horizontal: 12, + vertical: 2, + ), + onChanged: (value) { + setState(() { + if (value == true) { + selection.add(staff.id); + } else { + selection.remove(staff.id); + } + }); + }, + ); + }, + ), + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(), + child: const Text('Cancel'), + ), + FilledButton( + onPressed: () async { + await ref + .read(taskAssignmentsControllerProvider) + .replaceAssignments( + taskId: taskId, + ticketId: taskTicketId, + newUserIds: selection.toList(), + currentUserIds: assignedIds.toList(), + ); + if (context.mounted) { + Navigator.of(dialogContext).pop(); + } + }, + child: const Text('Save'), + ), + ], + ); + }, + ); + }, + ); + } +} + +extension _FirstOrNull on Iterable { + T? get firstOrNull => isEmpty ? null : first; +} diff --git a/lib/widgets/typing_dots.dart b/lib/widgets/typing_dots.dart new file mode 100644 index 00000000..2b222054 --- /dev/null +++ b/lib/widgets/typing_dots.dart @@ -0,0 +1,72 @@ +import 'package:flutter/material.dart'; + +class TypingDots extends StatefulWidget { + const TypingDots({super.key, this.size = 6, this.color, this.spacing = 4}); + + final double size; + final double spacing; + final Color? color; + + @override + State createState() => _TypingDotsState(); +} + +class _TypingDotsState extends State + with SingleTickerProviderStateMixin { + late final AnimationController _controller; + + @override + void initState() { + super.initState(); + _controller = AnimationController( + vsync: this, + duration: const Duration(milliseconds: 1200), + )..repeat(); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + double _opacity(double t, double offset) { + final phase = (t + offset) % 1.0; + final distance = (phase - 0.5).abs(); + final ramp = 1.0 - (distance / 0.5); + return 0.3 + 0.7 * ramp.clamp(0.0, 1.0); + } + + @override + Widget build(BuildContext context) { + final color = + widget.color ?? Theme.of(context).colorScheme.onSurfaceVariant; + return AnimatedBuilder( + animation: _controller, + builder: (context, child) { + final t = _controller.value; + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + _dot(color, _opacity(t, 0.0)), + SizedBox(width: widget.spacing), + _dot(color, _opacity(t, 0.2)), + SizedBox(width: widget.spacing), + _dot(color, _opacity(t, 0.4)), + ], + ); + }, + ); + } + + Widget _dot(Color color, double opacity) { + return Opacity( + opacity: opacity, + child: Container( + width: widget.size, + height: widget.size, + decoration: BoxDecoration(color: color, shape: BoxShape.circle), + ), + ); + } +} diff --git a/linux/.gitignore b/linux/.gitignore new file mode 100644 index 00000000..d3896c98 --- /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 00000000..0917f5d3 --- /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 "tasq") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "com.example.tasq") + +# 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 00000000..d5bd0164 --- /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 00000000..fb283e0d --- /dev/null +++ b/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,23 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include +#include +#include + +void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) audioplayers_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "AudioplayersLinuxPlugin"); + audioplayers_linux_plugin_register_with_registrar(audioplayers_linux_registrar); + g_autoptr(FlPluginRegistrar) gtk_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "GtkPlugin"); + gtk_plugin_register_with_registrar(gtk_registrar); + g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin"); + url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar); +} diff --git a/linux/flutter/generated_plugin_registrant.h b/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 00000000..e0f0a47b --- /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 00000000..e88480f7 --- /dev/null +++ b/linux/flutter/generated_plugins.cmake @@ -0,0 +1,26 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + audioplayers_linux + gtk + url_launcher_linux +) + +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 00000000..e97dabc7 --- /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 00000000..e7c5c543 --- /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 00000000..cf73461c --- /dev/null +++ b/linux/runner/my_application.cc @@ -0,0 +1,148 @@ +#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) + +// Called when first Flutter frame received. +static void first_frame_cb(MyApplication* self, FlView* view) { + gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view))); +} + +// 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, "tasq"); + 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, "tasq"); + } + + gtk_window_set_default_size(window, 1280, 720); + + 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); + GdkRGBA background_color; + // Background defaults to black, override it here if necessary, e.g. #00000000 + // for transparent. + gdk_rgba_parse(&background_color, "#000000"); + fl_view_set_background_color(view, &background_color); + gtk_widget_show(GTK_WIDGET(view)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + // Show the window when Flutter renders. + // Requires the view to be realized so we can start rendering. + g_signal_connect_swapped(view, "first-frame", G_CALLBACK(first_frame_cb), + self); + gtk_widget_realize(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 00000000..db16367a --- /dev/null +++ b/linux/runner/my_application.h @@ -0,0 +1,21 @@ +#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 00000000..746adbb6 --- /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 00000000..c2efd0b6 --- /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 00000000..c2efd0b6 --- /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 00000000..d282e3e5 --- /dev/null +++ b/macos/Flutter/GeneratedPluginRegistrant.swift @@ -0,0 +1,18 @@ +// +// Generated file. Do not edit. +// + +import FlutterMacOS +import Foundation + +import app_links +import audioplayers_darwin +import shared_preferences_foundation +import url_launcher_macos + +func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + AppLinksMacosPlugin.register(with: registry.registrar(forPlugin: "AppLinksMacosPlugin")) + AudioplayersDarwinPlugin.register(with: registry.registrar(forPlugin: "AudioplayersDarwinPlugin")) + SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) + UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin")) +} diff --git a/macos/Runner.xcodeproj/project.pbxproj b/macos/Runner.xcodeproj/project.pbxproj new file mode 100644 index 00000000..10fa8bca --- /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 /* tasq.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "tasq.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 /* tasq.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 /* tasq.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 = com.example.tasq.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/tasq.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/tasq"; + }; + 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 = com.example.tasq.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/tasq.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/tasq"; + }; + 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 = com.example.tasq.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/tasq.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/tasq"; + }; + 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.15; + 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.15; + 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.15; + 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 00000000..18d98100 --- /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 00000000..63e35358 --- /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 00000000..1d526a16 --- /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 00000000..18d98100 --- /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 00000000..b3c17614 --- /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 00000000..a2ec33f1 --- /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 00000000..82b6f9d9 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 00000000..13b35eba 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 00000000..0a3f5fa4 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 00000000..bdb57226 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 00000000..f083318e 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 00000000..326c0e72 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 00000000..2f1632cf 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 00000000..80e867a4 --- /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 00000000..b0b394e4 --- /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 = tasq + +// The application's bundle identifier +PRODUCT_BUNDLE_IDENTIFIER = com.example.tasq + +// The copyright displayed in application information +PRODUCT_COPYRIGHT = Copyright © 2026 com.example. All rights reserved. diff --git a/macos/Runner/Configs/Debug.xcconfig b/macos/Runner/Configs/Debug.xcconfig new file mode 100644 index 00000000..36b0fd94 --- /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 00000000..dff4f495 --- /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 00000000..42bcbf47 --- /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 00000000..dddb8a30 --- /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 00000000..4789daa6 --- /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 00000000..3cc05eb2 --- /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 00000000..852fa1a4 --- /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 00000000..61f3bd1f --- /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 00000000..aa4fa3e7 --- /dev/null +++ b/pubspec.lock @@ -0,0 +1,930 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + adaptive_number: + dependency: transitive + description: + name: adaptive_number + sha256: "3a567544e9b5c9c803006f51140ad544aedc79604fd4f3f2c1380003f97c1d77" + url: "https://pub.dev" + source: hosted + version: "1.0.0" + app_links: + dependency: transitive + description: + name: app_links + sha256: "5f88447519add627fe1cbcab4fd1da3d4fed15b9baf29f28b22535c95ecee3e8" + url: "https://pub.dev" + source: hosted + version: "6.4.1" + app_links_linux: + dependency: transitive + description: + name: app_links_linux + sha256: f5f7173a78609f3dfd4c2ff2c95bd559ab43c80a87dc6a095921d96c05688c81 + url: "https://pub.dev" + source: hosted + version: "1.0.3" + app_links_platform_interface: + dependency: transitive + description: + name: app_links_platform_interface + sha256: "05f5379577c513b534a29ddea68176a4d4802c46180ee8e2e966257158772a3f" + url: "https://pub.dev" + source: hosted + version: "2.0.2" + app_links_web: + dependency: transitive + description: + name: app_links_web + sha256: af060ed76183f9e2b87510a9480e56a5352b6c249778d07bd2c95fc35632a555 + url: "https://pub.dev" + source: hosted + version: "1.0.4" + archive: + dependency: transitive + description: + name: archive + sha256: "2fde1607386ab523f7a36bb3e7edb43bd58e6edaf2ffb29d8a6d578b297fdbbd" + url: "https://pub.dev" + source: hosted + version: "4.0.7" + 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: "758e6d74e971c3e5aceb4110bfd6698efc7f501675bcfe0c775459a8140750eb" + url: "https://pub.dev" + source: hosted + version: "2.13.0" + audioplayers: + dependency: "direct main" + description: + name: audioplayers + sha256: "5441fa0ceb8807a5ad701199806510e56afde2b4913d9d17c2f19f2902cf0ae4" + url: "https://pub.dev" + source: hosted + version: "6.5.1" + audioplayers_android: + dependency: transitive + description: + name: audioplayers_android + sha256: "60a6728277228413a85755bd3ffd6fab98f6555608923813ce383b190a360605" + url: "https://pub.dev" + source: hosted + version: "5.2.1" + audioplayers_darwin: + dependency: transitive + description: + name: audioplayers_darwin + sha256: "0811d6924904ca13f9ef90d19081e4a87f7297ddc19fc3d31f60af1aaafee333" + url: "https://pub.dev" + source: hosted + version: "6.3.0" + audioplayers_linux: + dependency: transitive + description: + name: audioplayers_linux + sha256: f75bce1ce864170ef5e6a2c6a61cd3339e1a17ce11e99a25bae4474ea491d001 + url: "https://pub.dev" + source: hosted + version: "4.2.1" + audioplayers_platform_interface: + dependency: transitive + description: + name: audioplayers_platform_interface + sha256: "0e2f6a919ab56d0fec272e801abc07b26ae7f31980f912f24af4748763e5a656" + url: "https://pub.dev" + source: hosted + version: "7.1.1" + audioplayers_web: + dependency: transitive + description: + name: audioplayers_web + sha256: "1c0f17cec68455556775f1e50ca85c40c05c714a99c5eb1d2d57cc17ba5522d7" + url: "https://pub.dev" + source: hosted + version: "5.1.1" + audioplayers_windows: + dependency: transitive + description: + name: audioplayers_windows + sha256: "4048797865105b26d47628e6abb49231ea5de84884160229251f37dfcbe52fd7" + url: "https://pub.dev" + source: hosted + version: "4.2.1" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + characters: + dependency: transitive + description: + name: characters + sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + checked_yaml: + dependency: transitive + description: + name: checked_yaml + sha256: "959525d3162f249993882720d52b7e0c833978df229be20702b33d48d91de70f" + url: "https://pub.dev" + source: hosted + version: "2.0.4" + 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_assets: + dependency: transitive + description: + name: code_assets + sha256: "83ccdaa064c980b5596c35dd64a8d3ecc68620174ab9b90b6343b753aa721687" + url: "https://pub.dev" + source: hosted + version: "1.0.0" + 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: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf + url: "https://pub.dev" + source: hosted + version: "3.0.7" + dart_jsonwebtoken: + dependency: transitive + description: + name: dart_jsonwebtoken + sha256: "0de65691c1d736e9459f22f654ddd6fd8368a271d4e41aa07e53e6301eff5075" + url: "https://pub.dev" + source: hosted + version: "3.3.1" + ed25519_edwards: + dependency: transitive + description: + name: ed25519_edwards + sha256: "6ce0112d131327ec6d42beede1e5dfd526069b18ad45dcf654f15074ad9276cd" + url: "https://pub.dev" + source: hosted + version: "0.3.1" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44" + url: "https://pub.dev" + source: hosted + version: "1.3.3" + ffi: + dependency: transitive + description: + name: ffi + sha256: d07d37192dbf97461359c1518788f203b0c9102cfd2c35a716b823741219542c + url: "https://pub.dev" + source: hosted + version: "2.1.5" + 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" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_dotenv: + dependency: "direct main" + description: + name: flutter_dotenv + sha256: b7c7be5cd9f6ef7a78429cabd2774d3c4af50e79cb2b7593e3d5d763ef95c61b + url: "https://pub.dev" + source: hosted + version: "5.2.1" + flutter_launcher_icons: + dependency: "direct dev" + description: + name: flutter_launcher_icons + sha256: "526faf84284b86a4cb36d20a5e45147747b7563d921373d4ee0559c54fcdbcea" + url: "https://pub.dev" + source: hosted + version: "0.13.1" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: "3105dc8492f6183fb076ccf1f351ac3d60564bff92e20bfc4af9cc1651f4e7e1" + url: "https://pub.dev" + source: hosted + version: "6.0.0" + flutter_riverpod: + dependency: "direct main" + description: + name: flutter_riverpod + sha256: "9532ee6db4a943a1ed8383072a2e3eeda041db5657cdf6d2acecf3c21ecbe7e1" + url: "https://pub.dev" + source: hosted + version: "2.6.1" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + font_awesome_flutter: + dependency: "direct main" + description: + name: font_awesome_flutter + sha256: b9011df3a1fa02993630b8fb83526368cf2206a711259830325bab2f1d2a4eb0 + url: "https://pub.dev" + source: hosted + version: "10.12.0" + functions_client: + dependency: transitive + description: + name: functions_client + sha256: "94074d62167ae634127ef6095f536835063a7dc80f2b1aa306d2346ff9023996" + url: "https://pub.dev" + source: hosted + version: "2.5.0" + glob: + dependency: transitive + description: + name: glob + sha256: c3f1ee72c96f8f78935e18aa8cecced9ab132419e8625dc187e1c2408efc20de + url: "https://pub.dev" + source: hosted + version: "2.1.3" + go_router: + dependency: "direct main" + description: + name: go_router + sha256: f02fd7d2a4dc512fec615529824fdd217fecb3a3d3de68360293a551f21634b3 + url: "https://pub.dev" + source: hosted + version: "14.8.1" + google_fonts: + dependency: "direct main" + description: + name: google_fonts + sha256: ba03d03bcaa2f6cb7bd920e3b5027181db75ab524f8891c8bc3aa603885b8055 + url: "https://pub.dev" + source: hosted + version: "6.3.3" + gotrue: + dependency: transitive + description: + name: gotrue + sha256: f7b52008311941a7c3e99f9590c4ee32dfc102a5442e43abf1b287d9f8cc39b2 + url: "https://pub.dev" + source: hosted + version: "2.18.0" + gtk: + dependency: transitive + description: + name: gtk + sha256: e8ce9ca4b1df106e4d72dad201d345ea1a036cc12c360f1a7d5a758f78ffa42c + url: "https://pub.dev" + source: hosted + version: "2.1.0" + hooks: + dependency: transitive + description: + name: hooks + sha256: "7a08a0d684cb3b8fb604b78455d5d352f502b68079f7b80b831c62220ab0a4f6" + url: "https://pub.dev" + source: hosted + version: "1.0.1" + http: + dependency: transitive + description: + name: http + sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412" + url: "https://pub.dev" + source: hosted + version: "1.6.0" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571" + url: "https://pub.dev" + source: hosted + version: "4.1.2" + image: + dependency: transitive + description: + name: image + sha256: "492bd52f6c4fbb6ee41f781ff27765ce5f627910e1e0cbecfa3d9add5562604c" + url: "https://pub.dev" + source: hosted + version: "4.7.2" + json_annotation: + dependency: transitive + description: + name: json_annotation + sha256: "805fa86df56383000f640384b282ce0cb8431f1a7a2396de92fb66186d8c57df" + url: "https://pub.dev" + source: hosted + version: "4.10.0" + jwt_decode: + dependency: transitive + description: + name: jwt_decode + sha256: d2e9f68c052b2225130977429d30f187aa1981d789c76ad104a32243cfdebfbb + url: "https://pub.dev" + source: hosted + version: "0.3.1" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de" + url: "https://pub.dev" + source: hosted + version: "11.0.2" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1" + url: "https://pub.dev" + source: hosted + version: "3.0.10" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + lints: + dependency: transitive + description: + name: lints + sha256: "12f842a479589fea194fe5c5a3095abc7be0c1f2ddfa9a0e76aed1dbd26a87df" + url: "https://pub.dev" + source: hosted + version: "6.1.0" + 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: "23f08335362185a5ea2ad3a4e597f1375e78bce8a040df5c600c8d3552ef2394" + url: "https://pub.dev" + source: hosted + version: "1.17.0" + mime: + dependency: transitive + description: + name: mime + sha256: "41a20518f0cb1256669420fdba0cd90d21561e560ac240f26ef8322e45bb7ed6" + url: "https://pub.dev" + source: hosted + version: "2.0.0" + native_toolchain_c: + dependency: transitive + description: + name: native_toolchain_c + sha256: "89e83885ba09da5fdf2cdacc8002a712ca238c28b7f717910b34bcd27b0d03ac" + url: "https://pub.dev" + source: hosted + version: "0.17.4" + objective_c: + dependency: transitive + description: + name: objective_c + sha256: "100a1c87616ab6ed41ec263b083c0ef3261ee6cd1dc3b0f35f8ddfa4f996fe52" + url: "https://pub.dev" + source: hosted + version: "9.3.0" + path: + dependency: transitive + description: + name: path + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.dev" + source: hosted + version: "1.9.1" + path_provider: + dependency: transitive + 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: f2c65e21139ce2c3dad46922be8272bb5963516045659e71bb16e151c93b580e + url: "https://pub.dev" + source: hosted + version: "2.2.22" + path_provider_foundation: + dependency: transitive + description: + name: path_provider_foundation + sha256: "2a376b7d6392d80cd3705782d2caa734ca4727776db0b6ec36ef3f1855197699" + url: "https://pub.dev" + source: hosted + version: "2.6.0" + 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" + petitparser: + dependency: transitive + description: + name: petitparser + sha256: "1a97266a94f7350d30ae522c0af07890c70b8e62c71e8e3920d1db4d23c057d1" + url: "https://pub.dev" + source: hosted + version: "7.0.1" + 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" + pointycastle: + dependency: transitive + description: + name: pointycastle + sha256: "92aa3841d083cc4b0f4709b5c74fd6409a3e6ba833ffc7dc6a8fee096366acf5" + url: "https://pub.dev" + source: hosted + version: "4.0.0" + posix: + dependency: transitive + description: + name: posix + sha256: "6323a5b0fa688b6a010df4905a56b00181479e6d10534cecfecede2aa55add61" + url: "https://pub.dev" + source: hosted + version: "6.0.3" + postgrest: + dependency: transitive + description: + name: postgrest + sha256: f4b6bb24b465c47649243ef0140475de8a0ec311dc9c75ebe573b2dcabb10460 + url: "https://pub.dev" + source: hosted + version: "2.6.0" + pub_semver: + dependency: transitive + description: + name: pub_semver + sha256: "5bfcf68ca79ef689f8990d1160781b4bad40a3bd5e5218ad4076ddb7f4081585" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + realtime_client: + dependency: transitive + description: + name: realtime_client + sha256: "5268afc208d02fb9109854d262c1ebf6ece224cd285199ae1d2f92d2ff49dbf1" + url: "https://pub.dev" + source: hosted + version: "2.7.0" + retry: + dependency: transitive + description: + name: retry + sha256: "822e118d5b3aafed083109c72d5f484c6dc66707885e07c0fbcb8b986bba7efc" + url: "https://pub.dev" + source: hosted + version: "3.1.2" + riverpod: + dependency: transitive + description: + name: riverpod + sha256: "59062512288d3056b2321804332a13ffdd1bf16df70dcc8e506e411280a72959" + url: "https://pub.dev" + source: hosted + version: "2.6.1" + rxdart: + dependency: transitive + description: + name: rxdart + sha256: "5c3004a4a8dbb94bd4bf5412a4def4acdaa12e12f269737a5751369e12d1a962" + url: "https://pub.dev" + source: hosted + version: "0.28.0" + shared_preferences: + dependency: transitive + description: + name: shared_preferences + sha256: "2939ae520c9024cb197fc20dee269cd8cdbf564c8b5746374ec6cacdc5169e64" + url: "https://pub.dev" + source: hosted + version: "2.5.4" + shared_preferences_android: + dependency: transitive + description: + name: shared_preferences_android + sha256: cbc40be9be1c5af4dab4d6e0de4d5d3729e6f3d65b89d21e1815d57705644a6f + url: "https://pub.dev" + source: hosted + version: "2.4.20" + shared_preferences_foundation: + dependency: transitive + description: + name: shared_preferences_foundation + sha256: "4e7eaffc2b17ba398759f1151415869a34771ba11ebbccd1b0145472a619a64f" + url: "https://pub.dev" + source: hosted + version: "2.5.6" + 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" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_span: + dependency: transitive + description: + name: source_span + sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab" + url: "https://pub.dev" + source: hosted + version: "1.10.2" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" + url: "https://pub.dev" + source: hosted + version: "1.12.1" + state_notifier: + dependency: transitive + description: + name: state_notifier + sha256: b8677376aa54f2d7c58280d5a007f9e8774f1968d1fb1c096adcb4792fba29bb + url: "https://pub.dev" + source: hosted + version: "1.0.0" + storage_client: + dependency: transitive + description: + name: storage_client + sha256: "1c61b19ed9e78f37fdd1ca8b729ab8484e6c8fe82e15c87e070b861951183657" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" + url: "https://pub.dev" + source: hosted + version: "1.4.1" + supabase: + dependency: transitive + description: + name: supabase + sha256: cc039f63a3168386b3a4f338f3bff342c860d415a3578f3fbe854024aee6f911 + url: "https://pub.dev" + source: hosted + version: "2.10.2" + supabase_flutter: + dependency: "direct main" + description: + name: supabase_flutter + sha256: "92b2416ecb6a5c3ed34cf6e382b35ce6cc8921b64f2a9299d5d28968d42b09bb" + url: "https://pub.dev" + source: hosted + version: "2.12.0" + synchronized: + dependency: transitive + description: + name: synchronized + sha256: c254ade258ec8282947a0acbbc90b9575b4f19673533ee46f2f6e9b3aeefd7c0 + url: "https://pub.dev" + source: hosted + version: "3.4.0" + 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: ab2726c1a94d3176a45960b6234466ec367179b87dd74f1611adb1f3b5fb9d55 + url: "https://pub.dev" + source: hosted + version: "0.7.7" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + url_launcher: + dependency: transitive + description: + name: url_launcher + sha256: f6a7e5c4835bb4e3026a04793a4199ca2d14c739ec378fdfe23fc8075d0439f8 + url: "https://pub.dev" + source: hosted + version: "6.3.2" + url_launcher_android: + dependency: transitive + description: + name: url_launcher_android + sha256: "767344bf3063897b5cf0db830e94f904528e6dd50a6dfaf839f0abf509009611" + url: "https://pub.dev" + source: hosted + version: "6.3.28" + url_launcher_ios: + dependency: transitive + description: + name: url_launcher_ios + sha256: cfde38aa257dae62ffe79c87fab20165dfdf6988c1d31b58ebf59b9106062aad + url: "https://pub.dev" + source: hosted + version: "6.3.6" + url_launcher_linux: + dependency: transitive + description: + name: url_launcher_linux + sha256: d5e14138b3bc193a0f63c10a53c94b91d399df0512b1f29b94a043db7482384a + url: "https://pub.dev" + source: hosted + version: "3.2.2" + url_launcher_macos: + dependency: transitive + description: + name: url_launcher_macos + sha256: "368adf46f71ad3c21b8f06614adb38346f193f3a59ba8fe9a2fd74133070ba18" + url: "https://pub.dev" + source: hosted + version: "3.2.5" + url_launcher_platform_interface: + dependency: transitive + description: + name: url_launcher_platform_interface + sha256: "552f8a1e663569be95a8190206a38187b531910283c3e982193e4f2733f01029" + url: "https://pub.dev" + source: hosted + version: "2.3.2" + url_launcher_web: + dependency: transitive + description: + name: url_launcher_web + sha256: d0412fcf4c6b31ecfdb7762359b7206ffba3bbffd396c6d9f9c4616ece476c1f + url: "https://pub.dev" + source: hosted + version: "2.4.2" + url_launcher_windows: + dependency: transitive + description: + name: url_launcher_windows + sha256: "712c70ab1b99744ff066053cbe3e80c73332b38d46e5e945c98689b2e66fc15f" + url: "https://pub.dev" + source: hosted + version: "3.1.5" + uuid: + dependency: transitive + description: + name: uuid + sha256: a11b666489b1954e01d992f3d601b1804a33937b5a8fe677bd26b8a9f96f96e8 + url: "https://pub.dev" + source: hosted + version: "4.5.2" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b + url: "https://pub.dev" + source: hosted + version: "2.2.0" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: "45caa6c5917fa127b5dbcfbd1fa60b14e583afdc08bfc96dda38886ca252eb60" + url: "https://pub.dev" + source: hosted + version: "15.0.2" + 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" + xml: + dependency: transitive + description: + name: xml + sha256: "971043b3a0d3da28727e40ed3e0b5d18b742fa5a68665cca88e74b7876d5e025" + url: "https://pub.dev" + source: hosted + version: "6.6.1" + yaml: + dependency: transitive + description: + name: yaml + sha256: b9da305ac7c39faa3f030eccd175340f968459dae4af175130b3fc47e40d76ce + url: "https://pub.dev" + source: hosted + version: "3.1.3" + yet_another_json_isolate: + dependency: transitive + description: + name: yet_another_json_isolate + sha256: fe45897501fa156ccefbfb9359c9462ce5dec092f05e8a56109db30be864f01e + url: "https://pub.dev" + source: hosted + version: "2.1.0" +sdks: + dart: ">=3.10.7 <4.0.0" + flutter: ">=3.38.4" diff --git a/pubspec.yaml b/pubspec.yaml new file mode 100644 index 00000000..f96df653 --- /dev/null +++ b/pubspec.yaml @@ -0,0 +1,40 @@ +name: tasq +description: "A new Flutter project." +publish_to: 'none' +version: 0.1.0 + +environment: + sdk: ^3.10.7 + +dependencies: + flutter: + sdk: flutter + supabase_flutter: ^2.6.0 + flutter_riverpod: ^2.6.1 + go_router: ^14.6.2 + flutter_dotenv: ^5.2.1 + font_awesome_flutter: ^10.7.0 + google_fonts: ^6.2.1 + audioplayers: ^6.1.0 + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^6.0.0 + flutter_launcher_icons: ^0.13.1 + +flutter: + uses-material-design: true + assets: + - .env + - assets/ + +flutter_launcher_icons: + android: true + ios: true + image_path: assets/tasq_ico.png + web: + generate: true + image_path: assets/tasq_ico.png + background_color: "#FFFFFF" + theme_color: "#FFFFFF" diff --git a/supabase/functions/admin_user_management/index.ts b/supabase/functions/admin_user_management/index.ts new file mode 100644 index 00000000..4e39cfab --- /dev/null +++ b/supabase/functions/admin_user_management/index.ts @@ -0,0 +1,95 @@ +import { serve } from "https://deno.land/std@0.203.0/http/server.ts"; +import { createClient } from "https://esm.sh/@supabase/supabase-js@2"; + +const jsonResponse = (body: unknown, status = 200) => + new Response(JSON.stringify(body), { + status, + headers: { "Content-Type": "application/json" }, + }); + +serve(async (req) => { + if (req.method != "POST") { + return jsonResponse({ error: "Method not allowed" }, 405); + } + + const supabaseUrl = Deno.env.get("SUPABASE_URL") ?? ""; + const anonKey = Deno.env.get("SUPABASE_ANON_KEY") ?? ""; + const serviceKey = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY") ?? ""; + if (!supabaseUrl || !anonKey || !serviceKey) { + return jsonResponse({ error: "Missing env configuration" }, 500); + } + + const authHeader = req.headers.get("Authorization") ?? ""; + const token = authHeader.replace("Bearer ", "").trim(); + if (!token) { + return jsonResponse({ error: "Missing access token" }, 401); + } + + const authClient = createClient(supabaseUrl, anonKey, { + global: { headers: { Authorization: `Bearer ${token}` } }, + }); + const { data: authData, error: authError } = + await authClient.auth.getUser(); + if (authError || !authData?.user) { + return jsonResponse({ error: "Unauthorized" }, 401); + } + + const adminClient = createClient(supabaseUrl, serviceKey); + const { data: profile, error: profileError } = await adminClient + .from("profiles") + .select("role") + .eq("id", authData.user.id) + .maybeSingle(); + const role = (profile?.role ?? "").toString().toLowerCase(); + if (profileError || role != "admin") { + return jsonResponse({ error: "Forbidden" }, 403); + } + + let payload: Record = {}; + try { + payload = await req.json(); + } catch (_) { + return jsonResponse({ error: "Invalid JSON" }, 400); + } + + const action = payload.action as string | undefined; + const userId = payload.userId as string | undefined; + if (!action || !userId) { + return jsonResponse({ error: "Missing action or userId" }, 400); + } + + if (action == "get_user") { + const { data, error } = await adminClient.auth.admin.getUserById(userId); + if (error) { + return jsonResponse({ error: error.message }, 400); + } + return jsonResponse({ user: data.user }); + } + + if (action == "set_password") { + const password = payload.password as string | undefined; + if (!password || password.length < 8) { + return jsonResponse({ error: "Password must be at least 8 characters" }, 400); + } + const { error } = await adminClient.auth.admin.updateUserById(userId, { + password, + }); + if (error) { + return jsonResponse({ error: error.message }, 400); + } + return jsonResponse({ ok: true }); + } + + if (action == "set_lock") { + const locked = Boolean(payload.locked); + const { error } = await adminClient.auth.admin.updateUserById(userId, { + ban_duration: locked ? "100y" : "0s", + }); + if (error) { + return jsonResponse({ error: error.message }, 400); + } + return jsonResponse({ ok: true }); + } + + return jsonResponse({ error: "Unknown action" }, 400); +}); diff --git a/web/favicon.png b/web/favicon.png new file mode 100644 index 00000000..33a60b87 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 00000000..904167f5 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 00000000..82c1afed 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 00000000..904167f5 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 00000000..82c1afed 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 00000000..d21efd81 --- /dev/null +++ b/web/index.html @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + tasq + + + + + + diff --git a/web/manifest.json b/web/manifest.json new file mode 100644 index 00000000..85c4b394 --- /dev/null +++ b/web/manifest.json @@ -0,0 +1,35 @@ +{ + "name": "tasq", + "short_name": "tasq", + "start_url": ".", + "display": "standalone", + "background_color": "#FFFFFF", + "theme_color": "#FFFFFF", + "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" + } + ] +} \ No newline at end of file diff --git a/windows/.gitignore b/windows/.gitignore new file mode 100644 index 00000000..d492d0d9 --- /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 00000000..b124c6cc --- /dev/null +++ b/windows/CMakeLists.txt @@ -0,0 +1,108 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(tasq 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 "tasq") + +# 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 00000000..903f4899 --- /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 00000000..0e1b3832 --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,20 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include +#include +#include + +void RegisterPlugins(flutter::PluginRegistry* registry) { + AppLinksPluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("AppLinksPluginCApi")); + AudioplayersWindowsPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("AudioplayersWindowsPlugin")); + UrlLauncherWindowsRegisterWithRegistrar( + registry->GetRegistrarForPlugin("UrlLauncherWindows")); +} diff --git a/windows/flutter/generated_plugin_registrant.h b/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 00000000..dc139d85 --- /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 00000000..99c6ac61 --- /dev/null +++ b/windows/flutter/generated_plugins.cmake @@ -0,0 +1,26 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + app_links + audioplayers_windows + url_launcher_windows +) + +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 00000000..394917c0 --- /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 00000000..80711a02 --- /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", "com.example" "\0" + VALUE "FileDescription", "tasq" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "tasq" "\0" + VALUE "LegalCopyright", "Copyright (C) 2026 com.example. All rights reserved." "\0" + VALUE "OriginalFilename", "tasq.exe" "\0" + VALUE "ProductName", "tasq" "\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 00000000..955ee303 --- /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 00000000..6da0652f --- /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 00000000..acefb195 --- /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"tasq", 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 00000000..66a65d1e --- /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 00000000..c04e20ca 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 00000000..153653e8 --- /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 00000000..3a0b4651 --- /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 00000000..3879d547 --- /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 00000000..60608d0f --- /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 00000000..e901dde6 --- /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_