commit 250c4d1e50897ed754f842aec602cbeba3fb2180 Author: aryaziz22 Date: Tue Jul 7 09:58:33 2026 +0700 upload project skripsi diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..a2d8dbe --- /dev/null +++ b/.env.example @@ -0,0 +1,22 @@ +# Firebase Web Configuration +FIREBASE_API_KEY_WEB=your_web_api_key_here +FIREBASE_APP_ID_WEB=your_web_app_id_here +FIREBASE_MESSAGING_SENDER_ID=your_messaging_sender_id_here +FIREBASE_PROJECT_ID=your_project_id_here +FIREBASE_AUTH_DOMAIN=your_auth_domain_here +FIREBASE_STORAGE_BUCKET=your_storage_bucket_here +FIREBASE_MEASUREMENT_ID_WEB=your_web_measurement_id_here + +# Firebase Android Configuration +FIREBASE_API_KEY_ANDROID=your_android_api_key_here +FIREBASE_APP_ID_ANDROID=your_android_app_id_here + +# Firebase iOS Configuration +FIREBASE_API_KEY_IOS=your_ios_api_key_here +FIREBASE_APP_ID_IOS=your_ios_app_id_here +FIREBASE_IOS_BUNDLE_ID=your_ios_bundle_id_here + +# Firebase Windows Configuration +FIREBASE_API_KEY_WINDOWS=your_windows_api_key_here +FIREBASE_APP_ID_WINDOWS=your_windows_app_id_here +FIREBASE_MEASUREMENT_ID_WINDOWS=your_windows_measurement_id_here diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..edb2e1c --- /dev/null +++ b/.gitignore @@ -0,0 +1,56 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ +/coverage/ + +# Documentation and debug files +*_REPORT.txt +*_INDEX.dart +debug_*.dart +*.log + +# Environment variables +.env +.env.local +.env.*.local + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/.metadata b/.metadata new file mode 100644 index 0000000..3268d00 --- /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: "a402d9a4376add5bc2d6b1e33e53edaae58c07f8" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: a402d9a4376add5bc2d6b1e33e53edaae58c07f8 + base_revision: a402d9a4376add5bc2d6b1e33e53edaae58c07f8 + - platform: android + create_revision: a402d9a4376add5bc2d6b1e33e53edaae58c07f8 + base_revision: a402d9a4376add5bc2d6b1e33e53edaae58c07f8 + - platform: ios + create_revision: a402d9a4376add5bc2d6b1e33e53edaae58c07f8 + base_revision: a402d9a4376add5bc2d6b1e33e53edaae58c07f8 + - platform: linux + create_revision: a402d9a4376add5bc2d6b1e33e53edaae58c07f8 + base_revision: a402d9a4376add5bc2d6b1e33e53edaae58c07f8 + - platform: macos + create_revision: a402d9a4376add5bc2d6b1e33e53edaae58c07f8 + base_revision: a402d9a4376add5bc2d6b1e33e53edaae58c07f8 + - platform: web + create_revision: a402d9a4376add5bc2d6b1e33e53edaae58c07f8 + base_revision: a402d9a4376add5bc2d6b1e33e53edaae58c07f8 + - platform: windows + create_revision: a402d9a4376add5bc2d6b1e33e53edaae58c07f8 + base_revision: a402d9a4376add5bc2d6b1e33e53edaae58c07f8 + + # 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/Full code esp32.py b/Full code esp32.py new file mode 100644 index 0000000..e7fbf9c --- /dev/null +++ b/Full code esp32.py @@ -0,0 +1,416 @@ +import network # Library untuk koneksi Wi-Fi +import urequests # Library untuk HTTP request (API Firebase/Firestore) +import time # Library untuk jeda (delay) dan pengambilan waktu +import machine # Library untuk kontrol pin hardware ESP32 +import ntptime # Library untuk sinkronisasi waktu dari server internet + +# ================================================== +# 1. KONFIGURASI UTAMA +# ================================================== +# Kredensial Jaringan Wi-Fi +WIFI_SSID = "WARKOP" +WIFI_PASSWORD = "redi1234" + +# Kredensial Firebase & Firestore +API_KEY = "AIzaSyCvv9MrSLOQPlarND0iq8vjH3nUANHcKMI" +PROJECT_ID = "hydronutrify" +DOC_ID_FASE = "kqAxWYNRWqZtfqihpo31b5C0vNv1" # ID Dokumen untuk siklus tanam +DOC_ID_DATA = "latest_monitoring" # ID Dokumen untuk data real-time + +# Autentikasi Pengguna Firebase +USER_EMAIL = "oktagendeveloper@gmail.com" +USER_PASSWORD = "Mahasiswa22" + +# Variabel Global untuk menyimpan token sesi (diisi otomatis saat login) +auth_token = "" +my_user_id = "" + +# Pengaturan Waktu & Aktuator (Pompa) +PUMP_DURATION = 10 # Lama pompa menyala (10 detik) +DELAY_AFTER_PUMP = 30 # Jeda tunggu agar larutan nutrisi tercampur rata di bak +LOOP_INTERVAL = 3600 # Jeda sistem membaca sensor kembali (3600 detik = 1 Jam) +MAX_RETRY_NTP = 5 # Maksimal percobaan sinkronisasi waktu jika gagal + +# Logika Modul Relay (Active High) +RELAY_ON = 1 # Angka 1 mengirim sinyal HIGH (Pompa Menyala) +RELAY_OFF = 0 # Angka 0 mengirim sinyal LOW (Pompa Mati) + +# ================================================== +# 2. PARAMETER KALIBRASI SENSOR +# ================================================== +# Didapat dari rumus regresi linear (y = mx + c) saat kalibrasi +PH_SLOPE = -17.33919 +PH_INTERCEPT = 9.59919 + +TDS_SLOPE = 1424.404800 +TDS_INTERCEPT = -736.856200 + +# ================================================== +# 3. INISIALISASI HARDWARE +# ================================================== +print("=== INISIALISASI HARDWARE ===") + +# Inisialisasi Sensor Analog (ADC) +ph_pin = machine.ADC(machine.Pin(35)) +ph_pin.atten(machine.ADC.ATTN_11DB) # Setting range pembacaan tegangan 0 - 3.3V + +tds_pin = machine.ADC(machine.Pin(34)) +tds_pin.atten(machine.ADC.ATTN_11DB) + +# Inisialisasi Pin Relay untuk Pompa +pin_nutrisi_a = machine.Pin(13, machine.Pin.OUT) +pin_nutrisi_b = machine.Pin(12, machine.Pin.OUT) +pin_air_baku = machine.Pin(14, machine.Pin.OUT) +pin_ph_up = machine.Pin(27, machine.Pin.OUT) +pin_ph_down = machine.Pin(26, machine.Pin.OUT) + +# Dikelompokkan dalam dictionary agar mudah dipanggil +pumps = { + "nutrisi": [pin_nutrisi_a, pin_nutrisi_b], + "air_baku": pin_air_baku, + "ph_up": pin_ph_up, + "ph_down": pin_ph_down +} + +# Keamanan: Matikan semua relay saat alat baru dinyalakan +# Diberi jeda 0.1 detik antar pin untuk mencegah lonjakan listrik (Brownout) +for pin in [pin_nutrisi_a, pin_nutrisi_b, pin_air_baku, pin_ph_up, pin_ph_down]: + pin.value(RELAY_OFF) + time.sleep(0.1) + +print("Semua relay berhasil di-OFF-kan.\n") + +# Variabel untuk filter rata-rata pembacaan pH +ph_buffer = [] +BUFFER_SIZE = 10 + +# ================================================== +# 4. HELPER WIFI, LOGIN & NTP +# ================================================== + +def connect_wifi(): + """Fungsi untuk menyambungkan ESP32 ke jaringan Wi-Fi.""" + wlan = network.WLAN(network.STA_IF) + wlan.active(False) # Mematikan radio Wi-Fi sesaat untuk membersihkan memori (mencegah error internal state) + time.sleep(0.5) + wlan.active(True) # Menyalakan ulang radio Wi-Fi + + if not wlan.isconnected(): + wlan.connect(WIFI_SSID, WIFI_PASSWORD) + print("Connecting WiFi", end="") + timeout = 15 + while not wlan.isconnected() and timeout > 0: + print(".", end="") + time.sleep(1) + timeout -= 1 + + if wlan.isconnected(): + print("\nWiFi Connected!") + return True + return False + +def login_firebase(): + """Fungsi untuk otentikasi (login) ke Firebase menggunakan Email & Password.""" + global auth_token, my_user_id + url = f"https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key={API_KEY}" + payload = {"email": USER_EMAIL, "password": USER_PASSWORD, "returnSecureToken": True} + try: + res = urequests.post(url, json=payload) + data = res.json() + if res.status_code == 200: + auth_token, my_user_id = data["idToken"], data["localId"] # Menyimpan Token dan ID User + print("Login Firebase Berhasil!") + res.close() + return True + res.close() + except Exception as e: + print("Login error:", e) + return False + +def sync_time(): + """Fungsi untuk mengambil waktu global (NTP) dan mengubahnya ke WIB (UTC+7).""" + print("Mencoba sinkronisasi NTP...") + for i in range(MAX_RETRY_NTP): + try: + ntptime.settime() # Ambil waktu UTC + # Konversi waktu dari detik UTC ditambah 7 jam (7 * 3600 detik) + t = time.localtime(time.time() + 7*3600) + print(f"Waktu NTP tersinkron: {t[0]:04d}-{t[1]:02d}-{t[2]:02d} {t[3]:02d}:{t[4]:02d}") + return True + except: + print(f"Gagal NTP ({i+1})... mencoba lagi.") + time.sleep(2) + return False + +# ================================================== +# 5. PEMBACAAN SENSOR PENGKONDISI SINYAL +# ================================================== + +def baca_tegangan(pin, samples=15): + """Filter Median (Nilai Tengah) khusus untuk sensor pH.""" + data = [] + for _ in range(samples): + data.append(pin.read()) + time.sleep_ms(10) + data.sort() + return data[len(data)//2] * (3.3 / 4095) # Mengubah nilai mentah ADC ke Voltase + +def baca_tegangan_stabil(pin, samples=50): + """Filter Trimmed Mean khusus untuk sensor TDS yang fluktuatif.""" + data = [] + for _ in range(samples): + data.append(pin.read()) + time.sleep_ms(5) + data.sort() + # Membuang 10% data nilai ekstrem atas dan bawah (Noise Reduction) + potong = samples // 10 + data_bersih = data[potong : samples - potong] + rata_rata = sum(data_bersih) / len(data_bersih) + return rata_rata * (3.3 / 4095) + +def get_sensor_data(): + """Fungsi utama untuk membaca pH dan TDS, lalu memasukkannya ke rumus regresi.""" + global ph_buffer + + # === Membaca sensor pH === + v_ph = baca_tegangan(ph_pin) + ph_raw = (PH_SLOPE * v_ph) + PH_INTERCEPT # Rumus kalibrasi + + # Memasukkan nilai pH ke dalam antrean (buffer) rata-rata keliling (Moving Average) + ph_buffer.append(ph_raw) + if len(ph_buffer) > BUFFER_SIZE: + ph_buffer.pop(0) + ph_val = sum(ph_buffer) / len(ph_buffer) + if ph_val < 0 or ph_val > 14: ph_val = ph_raw # Proteksi nilai tidak masuk akal + + # === Membaca sensor TDS === + v_tds = baca_tegangan_stabil(tds_pin) + tds_val = (TDS_SLOPE * v_tds) + TDS_INTERCEPT # Rumus kalibrasi + if tds_val < 0: tds_val = 0 # TDS tidak boleh minus + + return round(ph_val, 2), int(tds_val) + +# ================================================== +# 6. KOMUNIKASI FIRESTORE +# ================================================== + +def fetch_growth_phase(): + """Mengambil status fase pertumbuhan (Semai/Vegetatif/Generatif) dari Firestore.""" + url = f"https://firestore.googleapis.com/v1/projects/{PROJECT_ID}/databases/(default)/documents/planting_cycles/{DOC_ID_FASE}" + headers = {"Authorization": f"Bearer {auth_token}"} + try: + res = urequests.get(url, headers=headers) + if res.status_code == 200: + data = res.json() + phase_str = data["fields"]["growth_phase"]["stringValue"] + res.close() + + # Menerjemahkan string Firestore ke kode Logika (F1/F2/F3) + if phase_str == "Semai": return "F1" + elif phase_str == "Vegetatif": return "F2" + elif phase_str == "Generatif": return "F3" + else: + print(f"-> Gagal ambil fase dari DB (Code: {res.status_code})") + print("-> Alasan Firebase:", res.text) + res.close() + except Exception as e: + print("-> Error koneksi fetch fase:", e) + + return "F1" # Jika internet putus, anggap berada di fase teraman (F1) + +def upload_to_firestore(ph, tds, st): + """Mengirim hasil bacaan sensor dan status pompa ke Firestore.""" + + # Validasi Tahun: Jika jam internal ESP32 menunjukkan tahun 2000 (belum sync), paksa sync + if time.localtime()[0] < 2024: + sync_time() + + # Membentuk string timestamp (Format RFC 3339) dengan zona WIB (+07:00) + waktu_wib_sec = time.time() + (7 * 3600) + t = time.localtime(waktu_wib_sec) + timestamp_str = f"{t[0]:04d}-{t[1]:02d}-{t[2]:02d}T{t[3]:02d}:{t[4]:02d}:{t[5]:02d}+07:00" + + # URL update API Firestore beserta updateMask agar divalidasi oleh Security Rules + url = f"https://firestore.googleapis.com/v1/projects/{PROJECT_ID}/databases/(default)/documents/hidroponik_data/{DOC_ID_DATA}?updateMask.fieldPaths=pH_value&updateMask.fieldPaths=nutrient_level&updateMask.fieldPaths=pump_nutrient_status&updateMask.fieldPaths=pump_water_status&updateMask.fieldPaths=pump_ph_up_status&updateMask.fieldPaths=pump_ph_down_status&updateMask.fieldPaths=timestamp&updateMask.fieldPaths=user_id" + + headers = {"Authorization": f"Bearer {auth_token}"} + + # Payload format JSON (Tipe data harus persis dengan Firestore Rules) + payload = { + "fields": { + "pH_value": {"doubleValue": float(ph)}, + "nutrient_level": {"integerValue": int(tds)}, + "pump_nutrient_status": {"booleanValue": st["nut"] == RELAY_ON}, + "pump_water_status": {"booleanValue": st["air"] == RELAY_ON}, + "pump_ph_up_status": {"booleanValue": st["pup"] == RELAY_ON}, + "pump_ph_down_status": {"booleanValue": st["pdown"] == RELAY_ON}, + "timestamp": {"timestampValue": timestamp_str}, + "user_id": {"stringValue": my_user_id} + } + } + + try: + print("Mengunggah ke Firestore...") + res = urequests.patch(url, json=payload, headers=headers) + if res.status_code == 200: + print("-> Upload Berhasil!") + else: + print(f"-> Upload Gagal (Code: {res.status_code})") + print("-> Detail Error:", res.text) + res.close() + except Exception as e: + print("-> Upload Error:", e) + +# ================================================== +# 7. LOGIKA KONTROL SISTEM PAKAR (FORWARD CHAINING) +# ================================================== + +def trigger_pump(pin, nama): + """Menyalakan relay spesifik sesuai PUMP_DURATION lalu mematikannya kembali.""" + print(f" ---> Mengaktifkan Pompa: {nama} ({PUMP_DURATION} Detik)") + pin.value(RELAY_ON) + time.sleep(PUMP_DURATION) + pin.value(RELAY_OFF) + print(f" ---> {nama} Selesai") + +def eksekusi_pompa(st): + """Fungsi jembatan untuk mengecek perintah logika mana yang bernilai ON.""" + if st["pup"] == RELAY_ON: trigger_pump(pumps["ph_up"], "PH UP") + if st["pdown"] == RELAY_ON: trigger_pump(pumps["ph_down"], "PH DOWN") + if st["air"] == RELAY_ON: trigger_pump(pumps["air_baku"], "AIR BAKU") + if st["nut"] == RELAY_ON: + trigger_pump(pumps["nutrisi"][0], "NUTRISI A") + trigger_pump(pumps["nutrisi"][1], "NUTRISI B") + +def run_forward_chaining(f_code, ph, tds): + """ + Mesin Inferensi (Forward Chaining). + Mengubah fakta pembacaan sensor menjadi aturan (Rule) keputusan status pompa. + Terdiri dari 24 Rule berdasarkan kombinasi (Fase, Status pH, Status TDS). + """ + + # Fakta 1: Klasifikasi tingkat pH (P) + p_code = "P1" if ph < 4.0 else "P2" if ph > 6.0 else "P3" + + # Fakta 2: Klasifikasi kebutuhan nutrisi TDS (T) bergantung pada Fase Tanam (F) + t_code = "T2" + if f_code == "F1": + if tds < 300: t_code = "T1" + elif tds > 500: t_code = "T3" + elif f_code == "F2": + if tds < 600: t_code = "T1" + elif tds > 800: t_code = "T3" + elif f_code == "F3": + if tds < 800: t_code = "T1" + elif tds > 1200: t_code = "T3" + + # Default semua target keputusan adalah MATI + st = {"nut": RELAY_OFF, "air": RELAY_OFF, "pup": RELAY_OFF, "pdown": RELAY_OFF} + + # Pemetaan 24 Rule + if f_code == "F1": + if p_code == "P1": + if t_code == "T1": st["pup"] = RELAY_ON; st["nut"] = RELAY_ON + elif t_code == "T2": st["pup"] = RELAY_ON + elif t_code == "T3": st["pup"] = RELAY_ON; st["air"] = RELAY_ON + elif p_code == "P2": + if t_code == "T1": st["pdown"] = RELAY_ON; st["nut"] = RELAY_ON + elif t_code == "T2": st["pdown"] = RELAY_ON + elif t_code == "T3": st["pdown"] = RELAY_ON; st["air"] = RELAY_ON + elif p_code == "P3": + if t_code == "T1": st["nut"] = RELAY_ON + elif t_code == "T3": st["air"] = RELAY_ON + + elif f_code == "F2": + if p_code == "P1": + if t_code == "T1": st["pup"] = RELAY_ON; st["nut"] = RELAY_ON + elif t_code == "T2": st["pup"] = RELAY_ON + elif t_code == "T3": st["pup"] = RELAY_ON; st["air"] = RELAY_ON + elif p_code == "P2": + if t_code == "T1": st["pdown"] = RELAY_ON; st["nut"] = RELAY_ON + elif t_code == "T2": st["pdown"] = RELAY_ON + elif t_code == "T3": st["pdown"] = RELAY_ON; st["air"] = RELAY_ON + elif p_code == "P3": + if t_code == "T1": st["nut"] = RELAY_ON + elif t_code == "T3": st["air"] = RELAY_ON + + elif f_code == "F3": + if p_code == "P1": + if t_code == "T1": st["pup"] = RELAY_ON; st["nut"] = RELAY_ON + elif t_code == "T2": st["pup"] = RELAY_ON + elif t_code == "T3": st["pup"] = RELAY_ON; st["air"] = RELAY_ON + elif p_code == "P2": + if t_code == "T1": st["pdown"] = RELAY_ON; st["nut"] = RELAY_ON + elif t_code == "T2": st["pdown"] = RELAY_ON + elif t_code == "T3": st["pdown"] = RELAY_ON; st["air"] = RELAY_ON + elif p_code == "P3": + if t_code == "T1": st["nut"] = RELAY_ON + elif t_code == "T3": st["air"] = RELAY_ON + + # Mengembalikan nilai status pompa yang dihasilkan mesin inferensi (belum dijalankan fisiknya) + return st + +# ================================================== +# 8. SIKLUS UTAMA (MAIN LOOP) +# ================================================== +print("=== MULAI KONEKSI ===") +if connect_wifi(): + sync_time() + if login_firebase(): + print("\nSistem Otonom HydroNutrify Aktif & Memasuki Main Loop.") + + try: + while True: + print("\n" + "="*40) + + # Langkah 1: Kumpulkan Data Lingkungan + f_code = fetch_growth_phase() + ph_val, tds_val = get_sensor_data() + print(f"Fase : {f_code} | pH : {ph_val} | TDS : {tds_val} PPM") + + # Langkah 2: Proses Data menggunakan Algoritma Forward Chaining + status_pompa = run_forward_chaining(f_code, ph_val, tds_val) + + # Langkah 3: Identifikasi apakah perlu tindakan aktuator + pompa_aktif = (status_pompa["nut"] == RELAY_ON or + status_pompa["air"] == RELAY_ON or + status_pompa["pup"] == RELAY_ON or + status_pompa["pdown"] == RELAY_ON) + + # Langkah 4: Metode Double Update untuk User Interface (UI) Real-Time + if pompa_aktif: + # Update ke-1: Beri tahu Firebase (dan Dashboard User) bahwa pompa menyala + print("-> Pompa AKTIF! Mengirim status ON ke Firebase...") + upload_to_firestore(ph_val, tds_val, status_pompa) + + # Tindakan Nyata: Nyalakan relay secara bergiliran + eksekusi_pompa(status_pompa) + + # Update ke-2: Setelah 10 detik, lapor kembali bahwa semua pompa sudah mati + print("-> Pompa Selesai. Memperbarui status Firebase menjadi OFF...") + status_mati_semua = {"nut": RELAY_OFF, "air": RELAY_OFF, "pup": RELAY_OFF, "pdown": RELAY_OFF} + upload_to_firestore(ph_val, tds_val, status_mati_semua) + else: + # Jika sensor ideal, cukup laporkan nilai sensornya saja + print("-> Kondisi Ideal (Semua Pompa OFF). Mengirim ke Firebase...") + upload_to_firestore(ph_val, tds_val, status_pompa) + + # Langkah 5: Masuk ke mode tunggu (1 Jam) + print(f"Menunggu {LOOP_INTERVAL} detik untuk siklus berikutnya...") + time.sleep(LOOP_INTERVAL) + + # Penanganan jika program dihentikan secara manual di Thonny (Ctrl+C) + except KeyboardInterrupt: + print("\nPROGRAM DIHENTIKAN MANUAL") + for pin in [pin_nutrisi_a, pin_nutrisi_b, pin_air_baku, pin_ph_up, pin_ph_down]: + pin.value(RELAY_OFF) + print("Semua pompa dimatikan demi keamanan.") + + # Penanganan jika terjadi error crash pada koneksi / memory ESP32 + except Exception as e: + print("\nLoop Error Kritis:", e) + time.sleep(5) + else: + print("Sistem berhenti: Gagal Login Firebase.") +else: + print("Sistem berhenti: Tidak ada koneksi WiFi.") \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..062c879 --- /dev/null +++ b/README.md @@ -0,0 +1,16 @@ +# mobile_monitoring + +A new Flutter project. + +## Getting Started + +This project is a starting point for a Flutter application. + +A few resources to get you started if this is your first Flutter project: + +- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) +- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook) + +For help getting started with Flutter development, view the +[online documentation](https://docs.flutter.dev/), which offers tutorials, +samples, guidance on mobile development, and a full API reference. diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 0000000..0d29021 --- /dev/null +++ b/analysis_options.yaml @@ -0,0 +1,28 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at https://dart.dev/lints. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000..be3943c --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,14 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java +.cxx/ + +# Remember to never publicly share your keystore. +# See https://flutter.dev/to/reference-keystore +key.properties +**/*.keystore +**/*.jks diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts new file mode 100644 index 0000000..f62b0ea --- /dev/null +++ b/android/app/build.gradle.kts @@ -0,0 +1,56 @@ +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") + // Google services Gradle plugin + id("com.google.gms.google-services") +} + +android { + namespace = "com.example.mobile_monitoring" + compileSdk = flutter.compileSdkVersion + ndkVersion = flutter.ndkVersion + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 + } + + kotlinOptions { + jvmTarget = JavaVersion.VERSION_11.toString() + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId = "com.example.mobile_monitoring" + 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") + } + } +} + +dependencies { + // Import the Firebase BoM + implementation(platform("com.google.firebase:firebase-bom:34.15.0")) + + // Add the dependencies for Firebase products you want to use + // When using the BoM, don't specify versions in Firebase dependencies + implementation("com.google.firebase:firebase-analytics") + + // Add the dependencies for any other desired Firebase products + // https://firebase.google.com/docs/android/setup#available-libraries +} + +flutter { + source = "../.." +} diff --git a/android/app/google-services.json b/android/app/google-services.json new file mode 100644 index 0000000..f0bd1a6 --- /dev/null +++ b/android/app/google-services.json @@ -0,0 +1,29 @@ +{ + "project_info": { + "project_number": "712867239915", + "project_id": "hydronutrify", + "storage_bucket": "hydronutrify.firebasestorage.app" + }, + "client": [ + { + "client_info": { + "mobilesdk_app_id": "1:712867239915:android:7a7db4cfb9d15a364e6bae", + "android_client_info": { + "package_name": "com.example.mobile_monitoring" + } + }, + "oauth_client": [], + "api_key": [ + { + "current_key": "AIzaSyAI0VsDbdr7pAxVpofSh3IP6sgYRmEkrx0" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [] + } + } + } + ], + "configuration_version": "1" +} \ No newline at end of file diff --git a/android/app/src/debug/AndroidManifest.xml b/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..1d476c0 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,52 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/kotlin/com/example/mobile_monitoring/MainActivity.kt b/android/app/src/main/kotlin/com/example/mobile_monitoring/MainActivity.kt new file mode 100644 index 0000000..2461b6f --- /dev/null +++ b/android/app/src/main/kotlin/com/example/mobile_monitoring/MainActivity.kt @@ -0,0 +1,5 @@ +package com.example.mobile_monitoring + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity : FlutterActivity() diff --git a/android/app/src/main/res/drawable-v21/launch_background.xml b/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 0000000..f74085f --- /dev/null +++ b/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/drawable/launch_background.xml b/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 0000000..304732f --- /dev/null +++ b/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..c878927 Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..9153370 Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..d877ab4 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..58de92c Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..557335f Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/values-night/styles.xml b/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000..06952be --- /dev/null +++ b/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/main/res/values/styles.xml b/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..cb1ef88 --- /dev/null +++ b/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/profile/AndroidManifest.xml b/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/build.gradle.kts b/android/build.gradle.kts new file mode 100644 index 0000000..351875f --- /dev/null +++ b/android/build.gradle.kts @@ -0,0 +1,28 @@ +plugins { + // Google services Gradle plugin (required for Firebase) + id("com.google.gms.google-services") apply false +} +allprojects { + repositories { + google() + mavenCentral() + } +} + +val newBuildDir: Directory = + rootProject.layout.buildDirectory + .dir("../../build") + .get() +rootProject.layout.buildDirectory.value(newBuildDir) + +subprojects { + val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name) + project.layout.buildDirectory.value(newSubprojectBuildDir) +} +subprojects { + project.evaluationDependsOn(":app") +} + +tasks.register("clean") { + delete(rootProject.layout.buildDirectory) +} diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000..f018a61 --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true +android.enableJetifier=true diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..ac3b479 --- /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.12-all.zip diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts new file mode 100644 index 0000000..506fad2 --- /dev/null +++ b/android/settings.gradle.kts @@ -0,0 +1,29 @@ +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.9.1" apply false + // START: FlutterFire Configuration + id("com.google.gms.google-services") version "4.5.0" apply false + // END: FlutterFire Configuration + id("org.jetbrains.kotlin.android") version "2.1.0" apply false +} + +include(":app") diff --git a/assets/images/app_icon.png b/assets/images/app_icon.png new file mode 100644 index 0000000..9de4c3a Binary files /dev/null and b/assets/images/app_icon.png differ diff --git a/assets/images/bg-splashscreen.png b/assets/images/bg-splashscreen.png new file mode 100644 index 0000000..67b8098 Binary files /dev/null and b/assets/images/bg-splashscreen.png differ diff --git a/assets/images/image-removebg-preview.png b/assets/images/image-removebg-preview.png new file mode 100644 index 0000000..02cb0d2 Binary files /dev/null and b/assets/images/image-removebg-preview.png differ diff --git a/firebase.json b/firebase.json new file mode 100644 index 0000000..1ae10f1 --- /dev/null +++ b/firebase.json @@ -0,0 +1,29 @@ +{ + "flutter": { + "platforms": { + "android": { + "default": { + "projectId": "iot-hidroponik-1f15d", + "appId": "1:818899803821:android:3170c751b511c51cd53024", + "fileOutput": "android/app/google-services.json" + } + }, + "dart": { + "lib/firebase_options.dart": { + "projectId": "iot-hidroponik-1f15d", + "configurations": { + "android": "1:818899803821:android:3170c751b511c51cd53024", + "ios": "1:818899803821:ios:f62f4dc11073557fd53024", + "macos": "1:818899803821:ios:f62f4dc11073557fd53024", + "web": "1:818899803821:web:12f08afaecaefcb9d53024", + "windows": "1:818899803821:web:b980c246619717ccd53024" + } + } + } + } + }, + "firestore": { + "rules": "firestore.rules", + "indexes": "firestore.indexes.json" + } +} \ No newline at end of file diff --git a/firestore.indexes.json b/firestore.indexes.json new file mode 100644 index 0000000..b8cf38f --- /dev/null +++ b/firestore.indexes.json @@ -0,0 +1,21 @@ +{ + "indexes": [ + { + "collectionGroup": "hidroponik_data", + "queryScope": "COLLECTION", + "fields": [ + { "fieldPath": "user_id", "order": "ASCENDING" }, + { "fieldPath": "timestamp", "order": "DESCENDING" } + ] + }, + { + "collectionGroup": "hidroponik_data", + "queryScope": "COLLECTION", + "fields": [ + { "fieldPath": "user_id", "order": "ASCENDING" }, + { "fieldPath": "timestamp", "order": "ASCENDING" } + ] + } + ], + "fieldOverrides": [] +} diff --git a/firestore.rules b/firestore.rules new file mode 100644 index 0000000..fb45ff0 --- /dev/null +++ b/firestore.rules @@ -0,0 +1,25 @@ +rules_version = '2'; +service cloud.firestore { + match /databases/{database}/documents { + + // 1. Collection 'users' - Akses untuk data profil pengguna + match /users/{userId} { + allow read, write: if request.auth != null; + } + + // 2. Collection 'planting_cycles' - Akses untuk fase & siklus tanam + match /planting_cycles/{cycleId} { + allow read, write: if request.auth != null; + } + + // 3. Collection 'hidroponik_data' - Akses untuk data sensor pH & TDS (ESP32 / Monitoring) + match /hidroponik_data/{document=**} { + allow read, write: if request.auth != null; + } + + // 4. Collection 'sensor_calibration' - Akses untuk data kalibrasi sensor + match /sensor_calibration/{document=**} { + allow read, write: if request.auth != null; + } + } +} diff --git a/ios/.gitignore b/ios/.gitignore new file mode 100644 index 0000000..7a7f987 --- /dev/null +++ b/ios/.gitignore @@ -0,0 +1,34 @@ +**/dgph +*.mode1v3 +*.mode2v3 +*.moved-aside +*.pbxuser +*.perspectivev3 +**/*sync/ +.sconsign.dblite +.tags* +**/.vagrant/ +**/DerivedData/ +Icon? +**/Pods/ +**/.symlinks/ +profile +xcuserdata +**/.generated/ +Flutter/App.framework +Flutter/Flutter.framework +Flutter/Flutter.podspec +Flutter/Generated.xcconfig +Flutter/ephemeral/ +Flutter/app.flx +Flutter/app.zip +Flutter/flutter_assets/ +Flutter/flutter_export_environment.sh +ServiceDefinitions.json +Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!default.mode1v3 +!default.mode2v3 +!default.pbxuser +!default.perspectivev3 diff --git a/ios/Flutter/AppFrameworkInfo.plist b/ios/Flutter/AppFrameworkInfo.plist new file mode 100644 index 0000000..1dc6cf7 --- /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 0000000..592ceee --- /dev/null +++ b/ios/Flutter/Debug.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/ios/Flutter/Release.xcconfig b/ios/Flutter/Release.xcconfig new file mode 100644 index 0000000..592ceee --- /dev/null +++ b/ios/Flutter/Release.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..f8bfdcb --- /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.mobileMonitoring; + 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.mobileMonitoring.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.mobileMonitoring.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.mobileMonitoring.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.mobileMonitoring; + 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.mobileMonitoring; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C8088294A63A400263BE5 /* Debug */, + 331C8089294A63A400263BE5 /* Release */, + 331C808A294A63A400263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147031CF9000F007C117D /* Debug */, + 97C147041CF9000F007C117D /* Release */, + 249021D3217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147061CF9000F007C117D /* Debug */, + 97C147071CF9000F007C117D /* Release */, + 249021D4217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 97C146E61CF9000F007C117D /* Project object */; +} diff --git a/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..e3773d4 --- /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 0000000..1d526a1 --- /dev/null +++ b/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift new file mode 100644 index 0000000..6266644 --- /dev/null +++ b/ios/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import Flutter +import UIKit + +@main +@objc class AppDelegate: FlutterAppDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + GeneratedPluginRegistrant.register(with: self) + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } +} diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..d0d98aa --- /dev/null +++ b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1 @@ +{"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":"57x57","idiom":"iphone","filename":"Icon-App-57x57@1x.png","scale":"1x"},{"size":"57x57","idiom":"iphone","filename":"Icon-App-57x57@2x.png","scale":"2x"},{"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":"50x50","idiom":"ipad","filename":"Icon-App-50x50@1x.png","scale":"1x"},{"size":"50x50","idiom":"ipad","filename":"Icon-App-50x50@2x.png","scale":"2x"},{"size":"72x72","idiom":"ipad","filename":"Icon-App-72x72@1x.png","scale":"1x"},{"size":"72x72","idiom":"ipad","filename":"Icon-App-72x72@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"}} \ No newline at end of file diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 0000000..6c7e867 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png new file mode 100644 index 0000000..e3f0cf9 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png new file mode 100644 index 0000000..50e2e21 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png new file mode 100644 index 0000000..37c77cf Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png new file mode 100644 index 0000000..bcbc0b4 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png new file mode 100644 index 0000000..e6c6017 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png new file mode 100644 index 0000000..019a796 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png new file mode 100644 index 0000000..50e2e21 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png new file mode 100644 index 0000000..1e65917 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png new file mode 100644 index 0000000..ff1436f 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 0000000..e1c20a3 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 0000000..29b246e 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 0000000..ea8b2cb 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 0000000..34eb8dc 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 0000000..ff1436f Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png new file mode 100644 index 0000000..7e97098 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 0000000..c878927 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 0000000..58de92c 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 0000000..7324af4 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png new file mode 100644 index 0000000..383a972 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png new file mode 100644 index 0000000..1cdbc52 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 0000000..0bedcf2 --- /dev/null +++ b/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "LaunchImage.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md new file mode 100644 index 0000000..89c2725 --- /dev/null +++ b/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md @@ -0,0 +1,5 @@ +# Launch Screen Assets + +You can customize the launch screen with your own desired assets by replacing the image files in this directory. + +You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. \ No newline at end of file diff --git a/ios/Runner/Base.lproj/LaunchScreen.storyboard b/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..f2e259c --- /dev/null +++ b/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/Base.lproj/Main.storyboard b/ios/Runner/Base.lproj/Main.storyboard new file mode 100644 index 0000000..f3c2851 --- /dev/null +++ b/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist new file mode 100644 index 0000000..16c968b --- /dev/null +++ b/ios/Runner/Info.plist @@ -0,0 +1,49 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Mobile Monitoring + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + mobile_monitoring + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSRequiresIPhoneOS + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + CADisableMinimumFrameDurationOnPhone + + UIApplicationSupportsIndirectInputEvents + + + diff --git a/ios/Runner/Runner-Bridging-Header.h b/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 0000000..308a2a5 --- /dev/null +++ b/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" diff --git a/ios/RunnerTests/RunnerTests.swift b/ios/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..86a7c3b --- /dev/null +++ b/ios/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Flutter +import UIKit +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/lib/core/constants/app_settings.dart b/lib/core/constants/app_settings.dart new file mode 100644 index 0000000..fe32a67 --- /dev/null +++ b/lib/core/constants/app_settings.dart @@ -0,0 +1,51 @@ +/// Konfigurasi umum aplikasi HydroNutrify +class AppSettings { + AppSettings._(); // Private constructor untuk mencegah instansiasi + + // App Configuration + static const String fontFamily = 'Poppins'; + static const bool debugMode = false; + static const bool enableAnalytics = true; + static const bool enableCrashReporting = true; + + // API Configuration + static const String apiBaseUrl = 'https://api.hydronutrify.com'; + static const Duration apiTimeout = Duration(seconds: 30); + static const int maxRetries = 3; + + // Firebase Configuration + static const bool enableFirebaseLogging = true; + + // UI Configuration + static const double defaultPadding = 16.0; + static const double defaultBorderRadius = 8.0; + static const double smallBorderRadius = 4.0; + static const double largeBorderRadius = 16.0; + + // Splash Screen + static const Duration splashDuration = Duration(seconds: 3); + + // Cache Duration + static const Duration cacheDuration = Duration(hours: 1); + static const Duration longCacheDuration = Duration(days: 7); + + // Page Size + static const int defaultPageSize = 20; + static const int maxPageSize = 100; + + // Refresh Intervals + static const Duration dataRefreshInterval = Duration(seconds: 30); + static const Duration uiRefreshInterval = Duration(milliseconds: 500); + + // Validation + static const int minPasswordLength = 6; + static const int maxPasswordLength = 128; + static const int minNameLength = 3; + static const int maxNameLength = 50; + static const int maxPhoneLength = 15; + + // Feature Flags + static const bool enableOfflineMode = true; + static const bool enableLocalNotifications = true; + static const bool enablePushNotifications = false; +} diff --git a/lib/core/constants/colors.dart b/lib/core/constants/colors.dart new file mode 100644 index 0000000..4e143a4 --- /dev/null +++ b/lib/core/constants/colors.dart @@ -0,0 +1,49 @@ +import 'package:flutter/material.dart'; + +/// Konfigurasi warna aplikasi HydroNutrify +class AppColors { + AppColors._(); // Private constructor untuk mencegah instansiasi + + // Primary Colors + static const Color primary = Colors.green; + static const Color primaryLight = Color(0xFF66BB6A); + static const Color primaryDark = Color(0xFF2E7D32); + + // Secondary Colors + static const Color secondary = Color(0xFF4CAF50); + static const Color secondaryLight = Color(0xFF81C784); + static const Color secondaryDark = Color(0xFF388E3C); + + // Neutral Colors + static const Color white = Color(0xFFFFFFFF); + static const Color black = Color(0xFF000000); + static const Color scaffoldBackground = Color(0xFFF9F9F9); + static const Color pageBackground = Color(0xFFFAFAFA); + static const Color lightGray = Color(0xFFF5F5F5); + static const Color mediumGray = Color(0xFFBDBDBD); + static const Color darkGray = Color(0xFF757575); + + // Status Colors + static const Color success = Color(0xFF4CAF50); + static const Color warning = Color(0xFFFFC107); + static const Color error = Color(0xFFF44336); + static const Color info = Color(0xFF2196F3); + static const Color navbarActive = Color(0xFF52C41A); + + // Text Colors + static const Color textPrimary = Color(0xFF212121); + static const Color textSecondary = Color(0xFF757575); + static const Color textHint = Color(0xFFBDBDBD); + static const Color textInverse = Color(0xFFFFFFFF); + + // Border Colors + static const Color borderLight = Color(0xFFE0E0E0); + static const Color borderDark = Color(0xFF9E9E9E); + + // Shadow Color + static const Color shadow = Color(0x1A000000); + + // Transparency + static Color blackWithOpacity(double opacity) => black.withValues(alpha: opacity); + static Color whiteWithOpacity(double opacity) => white.withValues(alpha: opacity); +} diff --git a/lib/core/constants/constants.dart b/lib/core/constants/constants.dart new file mode 100644 index 0000000..60629f6 --- /dev/null +++ b/lib/core/constants/constants.dart @@ -0,0 +1,4 @@ +// Export semua file constants di sini untuk kemudahan import +export 'colors.dart'; +export 'strings.dart'; +export 'app_settings.dart'; diff --git a/lib/core/constants/strings.dart b/lib/core/constants/strings.dart new file mode 100644 index 0000000..f62f480 --- /dev/null +++ b/lib/core/constants/strings.dart @@ -0,0 +1,94 @@ +/// Konfigurasi string statis aplikasi HydroNutrify +class AppStrings { + AppStrings._(); // Private constructor untuk mencegah instansiasi + + // App Metadata + static const String appName = 'HydroNutrify'; + static const String appTagline = 'Hidroponik Jadi Mudah.'; + static const String appVersion = '1.0.0'; + + // Navigation & Menu + static const String home = 'Beranda'; + static const String settings = 'Pengaturan'; + static const String profile = 'Profil'; + static const String flowManagement = 'Manajemen Aliran'; + static const String monitoring = 'Monitoring'; + static const String graph = 'Grafik'; + static const String monitoringGrafik = 'Monitoring Grafik & Statistik'; + static const String seeAll = 'Lihat Semua'; + + // Authentication + static const String login = 'Masuk'; + static const String register = 'Daftar'; + static const String logout = 'Keluar'; + static const String forgotPassword = 'Lupa Kata Sandi'; + static const String email = 'Email'; + static const String password = 'Kata Sandi'; + static const String confirmPassword = 'Konfirmasi Kata Sandi'; + static const String signIn = 'Masuk'; + static const String signUp = 'Daftar'; + static const String noAccount = 'Belum punya akun?'; + static const String alreadyHaveAccount = 'Sudah punya akun?'; + static const String changePassword = 'Ubah Kata Sandi'; + static const String currentPassword = 'Kata Sandi Saat Ini'; + static const String newPassword = 'Kata Sandi Baru'; + + // Profile + static const String myProfile = 'Profil Saya'; + static const String fullName = 'Nama Lengkap'; + static const String phone = 'Nomor Telepon'; + static const String address = 'Alamat'; + static const String editProfile = 'Edit Profil'; + + // Monitoring Data + static const String ph = 'pH'; + static const String tds = 'TDS'; + static const String temperature = 'Suhu'; + static const String humidity = 'Kelembaban'; + static const String ec = 'EC'; + static const String waterLevel = 'Tingkat Air'; + static const String growthPhase = 'Fase Pertumbuhan'; + + // Actions + static const String save = 'Simpan'; + static const String cancel = 'Batal'; + static const String edit = 'Edit'; + static const String delete = 'Hapus'; + static const String add = 'Tambah'; + static const String next = 'Selanjutnya'; + static const String retry = 'Coba Lagi'; + static const String previous = 'Sebelumnya'; + static const String confirm = 'Konfirmasi'; + static const String close = 'Tutup'; + + // Messages + static const String loadingData = 'Memuat data...'; + static const String noDataAvailable = 'Data tidak tersedia'; + static const String noMonitoringData = 'Belum ada data monitoring'; + static const String pleaseLogin = 'Silakan Login'; + static const String failedToLoadData = 'Gagal memuat data'; + static const String startPlantingFirst = 'Belum Memulai Tanam'; + static const String successfullyUpdated = 'Berhasil diperbarui'; + static const String failedToLoad = 'Gagal memuat data'; + static const String pleaseWait = 'Mohon tunggu...'; + static const String error = 'Error'; + static const String success = 'Berhasil'; + static const String warning = 'Peringatan'; + + // Errors + static const String invalidEmail = 'Email tidak valid'; + static const String passwordTooShort = 'Kata sandi minimal 6 karakter'; + static const String passwordMismatch = 'Kata sandi tidak cocok'; + static const String fillAllFields = 'Harap isi semua kolom'; + static const String networkError = 'Kesalahan jaringan. Periksa koneksi Anda'; + static const String serverError = 'Kesalahan server. Coba lagi nanti'; + static const String unknownError = 'Terjadi kesalahan tidak diketahui'; + + // Statistics + static const String weeklyStats = 'Statistik Mingguan'; + static const String monthlyStats = 'Statistik Bulanan'; + static const String average = 'Rata-rata'; + static const String minimum = 'Minimum'; + static const String maximum = 'Maksimum'; + static const String trend = 'Tren'; +} diff --git a/lib/core/core.dart b/lib/core/core.dart new file mode 100644 index 0000000..68a2cff --- /dev/null +++ b/lib/core/core.dart @@ -0,0 +1,6 @@ +// Export semua file core di sini untuk kemudahan import +export 'constants/constants.dart'; +export 'theme/theme.dart'; +export 'utils/cycle_phase_utils.dart'; +export 'utils/phase_display_utils.dart'; +export 'firebase_options.dart'; diff --git a/lib/core/firebase_options.dart b/lib/core/firebase_options.dart new file mode 100644 index 0000000..5e89ca7 --- /dev/null +++ b/lib/core/firebase_options.dart @@ -0,0 +1,89 @@ +// File generated by FlutterFire CLI. +// ignore_for_file: type=lint +import 'package:firebase_core/firebase_core.dart' show FirebaseOptions; +import 'package:flutter/foundation.dart' + show defaultTargetPlatform, kIsWeb, TargetPlatform; +import 'package:flutter_dotenv/flutter_dotenv.dart'; + +/// Default [FirebaseOptions] for use with your Firebase apps. +/// +/// Example: +/// ```dart +/// import 'firebase_options.dart'; +/// // ... +/// await Firebase.initializeApp( +/// options: DefaultFirebaseOptions.currentPlatform, +/// ); +/// ``` +class DefaultFirebaseOptions { + static FirebaseOptions get currentPlatform { + if (kIsWeb) { + return web; + } + switch (defaultTargetPlatform) { + case TargetPlatform.android: + return android; + case TargetPlatform.iOS: + return ios; + case TargetPlatform.macOS: + return macos; + case TargetPlatform.windows: + return windows; + case TargetPlatform.linux: + throw UnsupportedError( + 'DefaultFirebaseOptions have not been configured for linux - ' + 'you can reconfigure this by running the FlutterFire CLI again.', + ); + default: + throw UnsupportedError( + 'DefaultFirebaseOptions are not supported for this platform.', + ); + } + } + + static FirebaseOptions get web => FirebaseOptions( + apiKey: dotenv.env['FIREBASE_API_KEY_WEB'] ?? '', + appId: dotenv.env['FIREBASE_APP_ID_WEB'] ?? '', + messagingSenderId: dotenv.env['FIREBASE_MESSAGING_SENDER_ID'] ?? '', + projectId: dotenv.env['FIREBASE_PROJECT_ID'] ?? '', + authDomain: dotenv.env['FIREBASE_AUTH_DOMAIN'] ?? '', + storageBucket: dotenv.env['FIREBASE_STORAGE_BUCKET'] ?? '', + measurementId: dotenv.env['FIREBASE_MEASUREMENT_ID_WEB'] ?? '', + ); + + static FirebaseOptions get android => FirebaseOptions( + apiKey: dotenv.env['FIREBASE_API_KEY_ANDROID'] ?? '', + appId: dotenv.env['FIREBASE_APP_ID_ANDROID'] ?? '', + messagingSenderId: dotenv.env['FIREBASE_MESSAGING_SENDER_ID'] ?? '', + projectId: dotenv.env['FIREBASE_PROJECT_ID'] ?? '', + storageBucket: dotenv.env['FIREBASE_STORAGE_BUCKET'] ?? '', + ); + + static FirebaseOptions get ios => FirebaseOptions( + apiKey: dotenv.env['FIREBASE_API_KEY_IOS'] ?? '', + appId: dotenv.env['FIREBASE_APP_ID_IOS'] ?? '', + messagingSenderId: dotenv.env['FIREBASE_MESSAGING_SENDER_ID'] ?? '', + projectId: dotenv.env['FIREBASE_PROJECT_ID'] ?? '', + storageBucket: dotenv.env['FIREBASE_STORAGE_BUCKET'] ?? '', + iosBundleId: dotenv.env['FIREBASE_IOS_BUNDLE_ID'] ?? '', + ); + + static FirebaseOptions get macos => FirebaseOptions( + apiKey: dotenv.env['FIREBASE_API_KEY_IOS'] ?? '', + appId: dotenv.env['FIREBASE_APP_ID_IOS'] ?? '', + messagingSenderId: dotenv.env['FIREBASE_MESSAGING_SENDER_ID'] ?? '', + projectId: dotenv.env['FIREBASE_PROJECT_ID'] ?? '', + storageBucket: dotenv.env['FIREBASE_STORAGE_BUCKET'] ?? '', + iosBundleId: dotenv.env['FIREBASE_IOS_BUNDLE_ID'] ?? '', + ); + + static FirebaseOptions get windows => FirebaseOptions( + apiKey: dotenv.env['FIREBASE_API_KEY_WINDOWS'] ?? '', + appId: dotenv.env['FIREBASE_APP_ID_WINDOWS'] ?? '', + messagingSenderId: dotenv.env['FIREBASE_MESSAGING_SENDER_ID'] ?? '', + projectId: dotenv.env['FIREBASE_PROJECT_ID'] ?? '', + authDomain: dotenv.env['FIREBASE_AUTH_DOMAIN'] ?? '', + storageBucket: dotenv.env['FIREBASE_STORAGE_BUCKET'] ?? '', + measurementId: dotenv.env['FIREBASE_MEASUREMENT_ID_WINDOWS'] ?? '', + ); +} diff --git a/lib/core/theme/app_theme.dart b/lib/core/theme/app_theme.dart new file mode 100644 index 0000000..e84f8cd --- /dev/null +++ b/lib/core/theme/app_theme.dart @@ -0,0 +1,295 @@ +import 'package:flutter/material.dart'; +import 'package:mobile_monitoring/core/constants/colors.dart'; +import 'package:mobile_monitoring/core/constants/app_settings.dart'; + +/// Konfigurasi Theme untuk aplikasi HydroNutrify +class AppTheme { + AppTheme._(); // Private constructor untuk mencegah instansiasi + + /// Light Theme + static ThemeData get lightTheme { + return ThemeData( + useMaterial3: true, + brightness: Brightness.light, + fontFamily: AppSettings.fontFamily, + + // Color Scheme + colorScheme: ColorScheme.fromSeed( + seedColor: AppColors.primary, + brightness: Brightness.light, + ), + + // Scaffold Background + scaffoldBackgroundColor: AppColors.scaffoldBackground, + + // AppBar Theme + appBarTheme: AppBarTheme( + backgroundColor: AppColors.primary, + foregroundColor: AppColors.white, + elevation: 0, + centerTitle: true, + titleTextStyle: TextStyle( + color: AppColors.white, + fontSize: 20, + fontWeight: FontWeight.w600, + fontFamily: AppSettings.fontFamily, + ), + ), + + // Text Theme + textTheme: TextTheme( + // Large text styles + displayLarge: TextStyle( + fontSize: 32, + fontWeight: FontWeight.bold, + color: AppColors.textPrimary, + fontFamily: AppSettings.fontFamily, + ), + displayMedium: TextStyle( + fontSize: 28, + fontWeight: FontWeight.bold, + color: AppColors.textPrimary, + fontFamily: AppSettings.fontFamily, + ), + displaySmall: TextStyle( + fontSize: 24, + fontWeight: FontWeight.w600, + color: AppColors.textPrimary, + fontFamily: AppSettings.fontFamily, + ), + // Heading styles + headlineLarge: TextStyle( + fontSize: 22, + fontWeight: FontWeight.w600, + color: AppColors.textPrimary, + fontFamily: AppSettings.fontFamily, + ), + headlineMedium: TextStyle( + fontSize: 20, + fontWeight: FontWeight.w600, + color: AppColors.textPrimary, + fontFamily: AppSettings.fontFamily, + ), + headlineSmall: TextStyle( + fontSize: 18, + fontWeight: FontWeight.w600, + color: AppColors.textPrimary, + fontFamily: AppSettings.fontFamily, + ), + // Title styles + titleLarge: TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600, + color: AppColors.textPrimary, + fontFamily: AppSettings.fontFamily, + ), + titleMedium: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w500, + color: AppColors.textPrimary, + fontFamily: AppSettings.fontFamily, + ), + titleSmall: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w500, + color: AppColors.textPrimary, + fontFamily: AppSettings.fontFamily, + ), + // Body styles + bodyLarge: TextStyle( + fontSize: 16, + fontWeight: FontWeight.normal, + color: AppColors.textPrimary, + fontFamily: AppSettings.fontFamily, + ), + bodyMedium: TextStyle( + fontSize: 14, + fontWeight: FontWeight.normal, + color: AppColors.textPrimary, + fontFamily: AppSettings.fontFamily, + ), + bodySmall: TextStyle( + fontSize: 12, + fontWeight: FontWeight.normal, + color: AppColors.textSecondary, + fontFamily: AppSettings.fontFamily, + ), + // Label styles + labelLarge: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w500, + color: AppColors.textPrimary, + fontFamily: AppSettings.fontFamily, + ), + labelMedium: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w500, + color: AppColors.textPrimary, + fontFamily: AppSettings.fontFamily, + ), + labelSmall: TextStyle( + fontSize: 10, + fontWeight: FontWeight.w500, + color: AppColors.textSecondary, + fontFamily: AppSettings.fontFamily, + ), + ), + + // Button Styles + elevatedButtonTheme: ElevatedButtonThemeData( + style: ElevatedButton.styleFrom( + backgroundColor: AppColors.primary, + foregroundColor: AppColors.white, + padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(AppSettings.defaultBorderRadius), + ), + textStyle: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600, + ), + ), + ), + + outlinedButtonTheme: OutlinedButtonThemeData( + style: OutlinedButton.styleFrom( + foregroundColor: AppColors.primary, + side: const BorderSide(color: AppColors.primary, width: 1), + padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(AppSettings.defaultBorderRadius), + ), + textStyle: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600, + ), + ), + ), + + textButtonTheme: TextButtonThemeData( + style: TextButton.styleFrom( + foregroundColor: AppColors.primary, + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + textStyle: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + ), + ), + ), + + // Input Decoration Theme + inputDecorationTheme: InputDecorationTheme( + filled: true, + fillColor: AppColors.white, + contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(AppSettings.defaultBorderRadius), + borderSide: const BorderSide(color: AppColors.borderLight), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(AppSettings.defaultBorderRadius), + borderSide: const BorderSide(color: AppColors.borderLight), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(AppSettings.defaultBorderRadius), + borderSide: const BorderSide(color: AppColors.primary, width: 2), + ), + errorBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(AppSettings.defaultBorderRadius), + borderSide: const BorderSide(color: AppColors.error), + ), + focusedErrorBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(AppSettings.defaultBorderRadius), + borderSide: const BorderSide(color: AppColors.error, width: 2), + ), + labelStyle: const TextStyle(color: AppColors.textSecondary), + hintStyle: const TextStyle(color: AppColors.textHint), + errorStyle: const TextStyle(color: AppColors.error), + ), + + // Card Theme + cardTheme: CardThemeData( + color: AppColors.white, + elevation: 2, + margin: const EdgeInsets.all(8), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(AppSettings.defaultBorderRadius), + ), + ), + + // Dialog Theme + dialogTheme: DialogThemeData( + backgroundColor: AppColors.white, + elevation: 8, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(AppSettings.defaultBorderRadius), + ), + ), + + // Floating Action Button Theme + floatingActionButtonTheme: FloatingActionButtonThemeData( + backgroundColor: AppColors.primary, + foregroundColor: AppColors.white, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + ), + ), + + // Progress Indicator + progressIndicatorTheme: const ProgressIndicatorThemeData( + color: AppColors.primary, + ), + + // Divider Theme + dividerTheme: const DividerThemeData( + color: AppColors.borderLight, + thickness: 1, + space: 16, + ), + + // Chip Theme + chipTheme: ChipThemeData( + backgroundColor: AppColors.lightGray, + disabledColor: AppColors.mediumGray, + selectedColor: AppColors.primary, + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + labelStyle: const TextStyle( + color: AppColors.textPrimary, + fontSize: 14, + fontWeight: FontWeight.w500, + ), + secondaryLabelStyle: const TextStyle( + color: AppColors.white, + fontSize: 14, + fontWeight: FontWeight.w500, + ), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + ), + ), + + // Bottom Navigation Bar Theme + bottomNavigationBarTheme: BottomNavigationBarThemeData( + backgroundColor: AppColors.white, + selectedItemColor: AppColors.primary, + unselectedItemColor: AppColors.mediumGray, + elevation: 8, + type: BottomNavigationBarType.fixed, + ), + ); + } + + /// Dark Theme (Optional untuk masa depan) + static ThemeData get darkTheme { + return ThemeData( + useMaterial3: true, + brightness: Brightness.dark, + fontFamily: AppSettings.fontFamily, + colorScheme: ColorScheme.fromSeed( + seedColor: AppColors.primaryLight, + brightness: Brightness.dark, + ), + scaffoldBackgroundColor: Colors.grey[900], + ); + } +} diff --git a/lib/core/theme/theme.dart b/lib/core/theme/theme.dart new file mode 100644 index 0000000..8d14e21 --- /dev/null +++ b/lib/core/theme/theme.dart @@ -0,0 +1,2 @@ +// Export theme configuration +export 'app_theme.dart'; diff --git a/lib/core/utils/cycle_phase_utils.dart b/lib/core/utils/cycle_phase_utils.dart new file mode 100644 index 0000000..a35583e --- /dev/null +++ b/lib/core/utils/cycle_phase_utils.dart @@ -0,0 +1,58 @@ +import 'package:cloud_firestore/cloud_firestore.dart'; +import 'package:mobile_monitoring/core/utils/phase_display_utils.dart'; + +class CyclePhaseUtils { + static const List monthNames = [ + 'Jan', + 'Feb', + 'Mar', + 'Apr', + 'Mei', + 'Jun', + 'Jul', + 'Agu', + 'Sep', + 'Okt', + 'Nov', + 'Des', + ]; + + static DateTime? extractStartDate(Map? cycleData) { + final startValue = cycleData?['start_date']; + if (startValue is Timestamp) { + return startValue.toDate(); + } + if (startValue is DateTime) { + return startValue; + } + return null; + } + + static String calculateCyclePhase(int daysSincePlanting) { + if (daysSincePlanting <= 14) return PhaseDisplayUtils.semai.name; + if (daysSincePlanting <= 30) return PhaseDisplayUtils.vegetatif.name; + if (daysSincePlanting <= 60) return PhaseDisplayUtils.generatif.name; + return 'Panen'; + } + + static String calculateDisplayPhase(int daysSincePlanting) { + return PhaseDisplayUtils.fromDays(daysSincePlanting).name; + } + + static int inferDaysFromPhase(String? phase) { + switch ((phase ?? '').toLowerCase()) { + case 'panen': + return 61; + default: + final phaseConfig = PhaseDisplayUtils.fromName(phase); + if (phaseConfig == PhaseDisplayUtils.semai) return 7; + if (phaseConfig == PhaseDisplayUtils.vegetatif) return 20; + if (phaseConfig == PhaseDisplayUtils.generatif) return 40; + return 0; + } + } + + static String formatIndonesianDate(DateTime date) { + return '${date.day} ${monthNames[date.month - 1]} ${date.year}'; + } +} diff --git a/lib/core/utils/phase_display_utils.dart b/lib/core/utils/phase_display_utils.dart new file mode 100644 index 0000000..a59f7c2 --- /dev/null +++ b/lib/core/utils/phase_display_utils.dart @@ -0,0 +1,116 @@ +import 'package:flutter/material.dart'; + +class PhaseDisplayConfig { + final String name; + final Color color; + final int nutrientMin; + final int nutrientMax; + final int startDay; + final int? endDay; + + const PhaseDisplayConfig({ + required this.name, + required this.color, + required this.nutrientMin, + required this.nutrientMax, + required this.startDay, + required this.endDay, + }); + + String get dayRangeLabel => + endDay == null ? '$startDay+' : '$startDay-$endDay'; +} + +class PhaseProgressData { + final String phaseName; + final int dayInPhase; + final int phaseDuration; + final double progress; + + const PhaseProgressData({ + required this.phaseName, + required this.dayInPhase, + required this.phaseDuration, + required this.progress, + }); +} + +class PhaseDisplayUtils { + static const semai = PhaseDisplayConfig( + name: 'Semai', + color: Color(0xFF2196F3), + nutrientMin: 300, + nutrientMax: 500, + startDay: 1, + endDay: 14, + ); + + static const vegetatif = PhaseDisplayConfig( + name: 'Vegetatif', + color: Color(0xFF4CAF50), + nutrientMin: 400, + nutrientMax: 800, + startDay: 15, + endDay: 30, + ); + + static const generatif = PhaseDisplayConfig( + name: 'Generatif', + color: Color(0xFFFF9800), + nutrientMin: 800, + nutrientMax: 1300, + startDay: 31, + endDay: null, + ); + + static const List ordered = [semai, vegetatif, generatif]; + + static PhaseDisplayConfig fromDays(int daysSincePlanting) { + if (daysSincePlanting <= 14) return semai; + if (daysSincePlanting <= 30) return vegetatif; + return generatif; + } + + static PhaseDisplayConfig fromName(String? name) { + final lower = (name ?? '').toLowerCase(); + switch (lower) { + case 'semai': + return semai; + case 'generatif': + return generatif; + default: + return vegetatif; + } + } + + static PhaseProgressData progressData(int daysSincePlanting) { + final phase = fromDays(daysSincePlanting); + + if (phase == semai) { + return PhaseProgressData( + phaseName: phase.name, + dayInPhase: daysSincePlanting, + phaseDuration: 14, + progress: daysSincePlanting / 14, + ); + } + + if (phase == vegetatif) { + final dayInPhase = daysSincePlanting - 14; + return PhaseProgressData( + phaseName: phase.name, + dayInPhase: dayInPhase, + phaseDuration: 16, + progress: dayInPhase / 16, + ); + } + + final dayInPhase = daysSincePlanting - 30; + return PhaseProgressData( + phaseName: phase.name, + dayInPhase: dayInPhase, + phaseDuration: 30, + progress: (dayInPhase / 30).clamp(0.0, 1.0), + ); + } +} diff --git a/lib/data/data.dart b/lib/data/data.dart new file mode 100644 index 0000000..0aef604 --- /dev/null +++ b/lib/data/data.dart @@ -0,0 +1,4 @@ +// Export semua file dari data layer +export 'models/models.dart'; +export 'repositories/repositories.dart'; +export 'services/services.dart'; diff --git a/lib/data/models/models.dart b/lib/data/models/models.dart new file mode 100644 index 0000000..c8bc2fa --- /dev/null +++ b/lib/data/models/models.dart @@ -0,0 +1,2 @@ +// Export semua file dari models layer +export 'service_result.dart'; diff --git a/lib/data/models/service_result.dart b/lib/data/models/service_result.dart new file mode 100644 index 0000000..f3d9209 --- /dev/null +++ b/lib/data/models/service_result.dart @@ -0,0 +1,35 @@ +class ServiceResult { + final bool success; + final String message; + final T? data; + final String? errorCode; + + const ServiceResult({ + required this.success, + required this.message, + this.data, + this.errorCode, + }); + + factory ServiceResult.success({ + required String message, + T? data, + }) { + return ServiceResult( + success: true, + message: message, + data: data, + ); + } + + factory ServiceResult.failure({ + required String message, + String? errorCode, + }) { + return ServiceResult( + success: false, + message: message, + errorCode: errorCode, + ); + } +} diff --git a/lib/data/repositories/base_repository.dart b/lib/data/repositories/base_repository.dart new file mode 100644 index 0000000..e669fe3 --- /dev/null +++ b/lib/data/repositories/base_repository.dart @@ -0,0 +1,25 @@ +// Base Repository Interface +// +// Gunakan interface ini sebagai template untuk membuat repository-nya. +// Repository pattern memisahkan logika pengambilan data dari service. +// +// Contoh: +// ```dart +// abstract class UserRepository { +// Future getUserById(String userId); +// Future> getAllUsers(); +// Future updateUser(User user); +// Future deleteUser(String userId); +// } +// ``` + +abstract class BaseRepository { + // Template method untuk operasi yang dapat diulang + Future execute(Future Function() operation) async { + try { + return await operation(); + } catch (e) { + rethrow; + } + } +} diff --git a/lib/data/repositories/repositories.dart b/lib/data/repositories/repositories.dart new file mode 100644 index 0000000..1daf28d --- /dev/null +++ b/lib/data/repositories/repositories.dart @@ -0,0 +1,2 @@ +// Export semua repositories dari data layer +export 'base_repository.dart'; diff --git a/lib/data/services/auth_service.dart b/lib/data/services/auth_service.dart new file mode 100644 index 0000000..3d061b4 --- /dev/null +++ b/lib/data/services/auth_service.dart @@ -0,0 +1,217 @@ +import 'dart:async'; +import 'package:firebase_auth/firebase_auth.dart'; +import 'package:flutter/foundation.dart'; +import 'package:mobile_monitoring/data/models/service_result.dart'; + +/// Service untuk autentikasi (login, register, logout, reset password) +/// Backend logic - tidak ada dependency ke UI +class AuthService { + final FirebaseAuth _auth = FirebaseAuth.instance; + + User? get currentUser => _auth.currentUser; + Stream get authStateChanges => _auth.authStateChanges(); + + /// Login dengan email dan password + /// Returns ServiceResult dengan status success/failure dan pesan + Future> signInWithEmailAndPassword({ + required String email, + required String password, + }) async { + try { + debugPrint('[AuthService] Login attempt for: $email'); + + // Set language untuk error messages + _auth.setLanguageCode('id'); + + // Timeout untuk mencegah hang + final userCredential = await _auth + .signInWithEmailAndPassword(email: email, password: password) + .timeout( + const Duration(seconds: 20), + onTimeout: () { + throw TimeoutException('Login timeout'); + }, + ); + + debugPrint('[AuthService] ✓ Login success - User: ${userCredential.user?.email}'); + + return ServiceResult.success( + message: 'Login berhasil', + data: userCredential.user, + ); + + } on TimeoutException { + debugPrint('[AuthService] ✗ Login timeout'); + return ServiceResult.failure( + message: 'Login timeout. Periksa koneksi atau Google Play Services.', + errorCode: 'timeout', + ); + } on FirebaseAuthException catch (e) { + debugPrint('[AuthService] ✗ FirebaseAuthException: ${e.code} - ${e.message}'); + + final message = _mapFirebaseAuthError(e.code); + return ServiceResult.failure( + message: message, + errorCode: e.code, + ); + } catch (e) { + debugPrint('[AuthService] ✗ Unexpected error: $e'); + return ServiceResult.failure( + message: 'Terjadi kesalahan saat login', + errorCode: 'unknown', + ); + } + } + + /// Register akun baru dengan email, password, dan nama + Future> registerWithEmailAndPassword({ + required String email, + required String password, + required String name, + }) async { + try { + debugPrint('[AuthService] Register attempt for: $email'); + + final userCredential = await _auth.createUserWithEmailAndPassword( + email: email, + password: password, + ); + + // Update display name + await userCredential.user?.updateDisplayName(name); + await userCredential.user?.reload(); + + debugPrint('[AuthService] ✓ Register success - User: ${userCredential.user?.email}'); + + return ServiceResult.success( + message: 'Registrasi berhasil', + data: userCredential.user, + ); + + } on FirebaseAuthException catch (e) { + debugPrint('[AuthService] ✗ Register FirebaseAuthException: ${e.code} - ${e.message}'); + + String message; + switch (e.code) { + case 'weak-password': + message = 'Password terlalu lemah'; + break; + case 'email-already-in-use': + message = 'Email sudah terdaftar'; + break; + case 'invalid-email': + message = 'Email tidak valid'; + break; + default: + message = 'Terjadi kesalahan: ${e.message}'; + } + + return ServiceResult.failure( + message: message, + errorCode: e.code, + ); + } catch (e) { + debugPrint('[AuthService] ✗ Register unexpected error: $e'); + return ServiceResult.failure( + message: 'Terjadi kesalahan saat registrasi', + errorCode: 'unknown', + ); + } + } + + /// Logout user dari aplikasi + Future> signOut() async { + try { + debugPrint('[AuthService] Logout attempt'); + await _auth.signOut(); + debugPrint('[AuthService] ✓ Logout success'); + + return ServiceResult.success(message: 'Logout berhasil'); + } catch (e) { + debugPrint('[AuthService] ✗ Logout error: $e'); + return ServiceResult.failure( + message: 'Gagal logout', + errorCode: 'unknown', + ); + } + } + + /// Kirim email reset password + Future> resetPassword(String email) async { + try { + debugPrint('[AuthService] Reset password for: $email'); + + await _auth.sendPasswordResetEmail(email: email); + + debugPrint('[AuthService] ✓ Reset password email sent'); + + return ServiceResult.success( + message: 'Link reset password telah dikirim ke email Anda', + ); + + } on FirebaseAuthException catch (e) { + debugPrint('[AuthService] ✗ Reset password FirebaseAuthException: ${e.code}'); + + String message; + switch (e.code) { + case 'user-not-found': + message = 'Email tidak terdaftar'; + break; + case 'invalid-email': + message = 'Email tidak valid'; + break; + default: + message = 'Terjadi kesalahan: ${e.message}'; + } + + return ServiceResult.failure( + message: message, + errorCode: e.code, + ); + } catch (e) { + debugPrint('[AuthService] ✗ Reset password unexpected error: $e'); + return ServiceResult.failure( + message: 'Terjadi kesalahan', + errorCode: 'unknown', + ); + } + } + + /// Validasi email format + bool isValidEmail(String email) { + return email.isNotEmpty && email.contains('@'); + } + + /// Validasi password + bool isValidPassword(String password) { + return password.length >= 6; + } + + /// Map Firebase Auth error codes ke pesan yang user-friendly + String _mapFirebaseAuthError(String code) { + switch (code) { + case 'invalid-credential': + case 'wrong-password': + return 'Email atau password salah'; + case 'user-not-found': + return 'Akun belum terdaftar'; + case 'user-disabled': + return 'Akun dinonaktifkan'; + case 'too-many-requests': + return 'Terlalu banyak percobaan, coba lagi nanti'; + case 'network-request-failed': + return 'Koneksi internet bermasalah'; + case 'operation-not-allowed': + return 'Email/Password belum diaktifkan di Firebase'; + case 'app-not-authorized': + return 'App belum terdaftar di Firebase (package name/sha-1)'; + case 'invalid-api-key': + return 'API key Firebase tidak valid'; + case 'invalid-email': + return 'Format email tidak valid'; + default: + return 'Login gagal: $code'; + } + } +} + diff --git a/lib/data/services/flow_service.dart b/lib/data/services/flow_service.dart new file mode 100644 index 0000000..f512ba3 --- /dev/null +++ b/lib/data/services/flow_service.dart @@ -0,0 +1,343 @@ +import 'package:cloud_firestore/cloud_firestore.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart' show Color; +import 'package:mobile_monitoring/data/models/service_result.dart'; +import 'package:mobile_monitoring/core/utils/cycle_phase_utils.dart'; + +/// Model untuk monitoring data di Flow page +class FlowMonitoringData { + final double ph; + final double tds; + final String phStatus; + final String tdsStatus; + final Color phColor; + final Color tdsColor; + final bool pumpPhUp; + final bool pumpPhDown; + final bool pumpNutrient; + final bool pumpWater; + + FlowMonitoringData({ + required this.ph, + required this.tds, + required this.phStatus, + required this.tdsStatus, + required this.phColor, + required this.tdsColor, + required this.pumpPhUp, + required this.pumpPhDown, + required this.pumpNutrient, + required this.pumpWater, + }); +} + +/// Model untuk recap row +class RecapRow { + final String day; + final String morning; + final String afternoon; + final String night; + final DateTime date; + + RecapRow({ + required this.day, + required this.morning, + required this.afternoon, + required this.night, + required this.date, + }); + + Map toMap() { + return { + 'day': day, + 'morning': morning, + 'afternoon': afternoon, + 'night': night, + 'date': date, + }; + } +} + +/// Model untuk aggregate data per slot waktu +class _SlotAggregate { + double? _phSum; + double? _tdsSum; + int _count = 0; + + void add({required double ph, required double tds}) { + _phSum = (_phSum ?? 0) + ph; + _tdsSum = (_tdsSum ?? 0) + tds; + _count++; + } + + bool get hasData => _count > 0; + double? get phAverage => _count > 0 ? _phSum! / _count : null; + double? get tdsAverage => _count > 0 ? _tdsSum! / _count : null; +} + +/// Error info untuk Flow page +class FlowDataError { + final String displayMessage; + final String detailMessage; + final bool isAuthError; + + FlowDataError({ + required this.displayMessage, + required this.detailMessage, + required this.isAuthError, + }); + + factory FlowDataError.fromException(Object error) { + final errorMsg = error.toString(); + debugPrint('[FlowService] Error: $errorMsg'); + + bool isNotAuthError = errorMsg.contains('terautentikasi'); + + if (isNotAuthError) { + return FlowDataError( + displayMessage: 'Silakan Login', + detailMessage: 'Sesi Anda telah berakhir, login kembali', + isAuthError: true, + ); + } else { + return FlowDataError( + displayMessage: 'Gagal memuat data', + detailMessage: 'Pastikan koneksi internet stabil', + isAuthError: false, + ); + } + } +} + +/// Service untuk Flow Page - Backend Logic +/// Tidak ada dependency ke UI (no BuildContext, no Color from material) +class FlowService { + static const List dayNames = [ + 'Sen', + 'Sel', + 'Rab', + 'Kam', + 'Jum', + 'Sab', + 'Min', + ]; + + FlowMonitoringData _parseMonitoringData(Map data) { + debugPrint('[FlowService] parseMonitoringData()'); + + // Extract values + final double ph = (data['pH_value'] as num?)?.toDouble() ?? 0.0; + final double tds = (data['nutrient_level'] as num?)?.toDouble() ?? 0.0; + + // Extract pump status + final bool pumpPhUp = data['pump_ph_up_status'] ?? false; + final bool pumpPhDown = data['pump_ph_down_status'] ?? false; + final bool pumpNutrient = data['pump_nutrient_status'] ?? false; + final bool pumpWater = data['pump_water_status'] ?? false; + + // Determine abnormality + final bool phPumpOn = pumpPhUp || pumpPhDown; + final bool nutrientPumpOn = pumpNutrient || pumpWater; + + // Determine status and colors + final String phStatus = phPumpOn ? 'Abnormal' : 'Normal'; + final String tdsStatus = nutrientPumpOn ? 'Abnormal' : 'Normal'; + + // Use color codes instead of Color objects for backend + // Frontend will convert these to Color objects + final Color phColor = phPumpOn + ? const Color(0xFFFF9800) + : const Color(0xFF4CAF50); + final Color tdsColor = nutrientPumpOn + ? const Color(0xFFFF9800) + : const Color(0xFF4CAF50); + + debugPrint('[FlowService] pH: $ph, status: $phStatus'); + debugPrint('[FlowService] TDS: $tds, status: $tdsStatus'); + + return FlowMonitoringData( + ph: ph, + tds: tds, + phStatus: phStatus, + tdsStatus: tdsStatus, + phColor: phColor, + tdsColor: tdsColor, + pumpPhUp: pumpPhUp, + pumpPhDown: pumpPhDown, + pumpNutrient: pumpNutrient, + pumpWater: pumpWater, + ); + } + + ServiceResult parseMonitoringDataResult( + Map data, + ) { + try { + final parsed = _parseMonitoringData(data); + return ServiceResult.success( + message: 'Data flow monitoring berhasil diproses', + data: parsed, + ); + } catch (e) { + return ServiceResult.failure( + message: 'Gagal memproses data flow monitoring', + errorCode: 'parse_error', + ); + } + } + + List _generateRecapRows( + List> docs, + DateTime? startDate, + ) { + debugPrint('[FlowService] generateRecapRows()'); + debugPrint('[FlowService] Total docs: ${docs.length}'); + debugPrint('[FlowService] Start date: $startDate'); + + final now = DateTime.now(); + final filterEndDate = DateTime(now.year, now.month, now.day, 23, 59, 59); + + // Determine filter start date + DateTime filterStartDate; + if (startDate != null) { + final plantingStart = DateTime( + startDate.year, + startDate.month, + startDate.day, + ); + final sevenDaysAgo = now.subtract(const Duration(days: 6)); + filterStartDate = plantingStart.isBefore(sevenDaysAgo) + ? sevenDaysAgo + : plantingStart; + } else { + filterStartDate = now.subtract(const Duration(days: 6)); + } + + final dayCount = filterEndDate.difference(filterStartDate).inDays + 1; + debugPrint( + '[FlowService] Filter start: $filterStartDate, end: $filterEndDate', + ); + debugPrint('[FlowService] Day count: $dayCount'); + + // Create buckets for each day and time slot + final buckets = List.generate( + dayCount, + (_) => List.generate(3, (_) => _SlotAggregate()), + ); + + // Aggregate data into buckets + int processedCount = 0; + for (final data in docs) { + final timestamp = data['timestamp']; + DateTime? dt; + if (timestamp is Timestamp) { + dt = timestamp.toDate(); + } else if (timestamp is DateTime) { + dt = timestamp; + } + + if (dt == null || + dt.isBefore(filterStartDate) || + dt.isAfter(filterEndDate)) { + continue; + } + + final ph = (data['pH_value'] as num?)?.toDouble() ?? 0.0; + final tds = (data['nutrient_level'] as num?)?.toDouble() ?? 0.0; + + final dayIdx = dt.difference(filterStartDate).inDays; + if (dayIdx >= 0 && dayIdx < dayCount) { + final slotIdx = _getSlotIndexForHour(dt.hour); + buckets[dayIdx][slotIdx].add(ph: ph, tds: tds); + processedCount++; + } + } + + debugPrint('[FlowService] Processed $processedCount data points'); + + // Generate rows + final rows = []; + for (var i = 0; i < dayCount; i++) { + final date = filterStartDate.add(Duration(days: i)); + final dayName = + '${dayNames[(date.weekday - 1) % 7]} ${date.day}/${date.month}'; + rows.add( + RecapRow( + day: dayName, + morning: _formatSlotText(buckets[i][0]), + afternoon: _formatSlotText(buckets[i][1]), + night: _formatSlotText(buckets[i][2]), + date: date, + ), + ); + } + + debugPrint('[FlowService] Generated ${rows.length} recap rows'); + return rows; + } + + ServiceResult> generateRecapRowsResult( + List> docs, + DateTime? startDate, + ) { + try { + final rows = _generateRecapRows(docs, startDate); + return ServiceResult.success( + message: 'Rekap monitoring berhasil dibuat', + data: rows, + ); + } catch (e) { + return ServiceResult.failure( + message: 'Gagal membuat rekap monitoring', + errorCode: 'recap_error', + ); + } + } + + /// Get slot index based on hour (0=morning, 1=afternoon, 2=night) + int _getSlotIndexForHour(int hour) { + if (hour >= 5 && hour < 12) { + return 0; // Morning (5-12) + } else if (hour >= 12 && hour < 17) { + return 1; // Afternoon (12-17) + } else { + return 2; // Night (17-5) + } + } + + /// Format slot aggregate data to display text + String _formatSlotText(_SlotAggregate agg) { + if (!agg.hasData) return '-'; + final phAvg = agg.phAverage?.toStringAsFixed(1); + final tdsAvg = agg.tdsAverage?.toStringAsFixed(0); + final phPart = phAvg != null ? 'pH $phAvg' : ''; + final tdsPart = tdsAvg != null + ? '${phPart.isNotEmpty ? ' / ' : ''}${tdsAvg}ppm' + : ''; + return (phPart + tdsPart).isEmpty ? '-' : phPart + tdsPart; + } + + ServiceResult getErrorInfoResult(Object error) { + return ServiceResult.success( + message: 'Error flow berhasil dipetakan', + data: FlowDataError.fromException(error), + ); + } + + ServiceResult hasActiveCycleResult(Map? cycleData) { + return ServiceResult.success( + message: 'Status siklus aktif berhasil diperiksa', + data: cycleData != null && cycleData.isNotEmpty, + ); + } + + ServiceResult extractStartDateResult( + Map? cycleData, + ) { + final startDate = CyclePhaseUtils.extractStartDate(cycleData); + return ServiceResult.success( + message: 'Tanggal mulai siklus berhasil diambil', + data: startDate, + ); + } +} diff --git a/lib/data/services/graph_service.dart b/lib/data/services/graph_service.dart new file mode 100644 index 0000000..9f0e61a --- /dev/null +++ b/lib/data/services/graph_service.dart @@ -0,0 +1,45 @@ +import 'package:firebase_auth/firebase_auth.dart'; +import 'package:flutter/foundation.dart'; +import 'package:mobile_monitoring/data/models/service_result.dart'; + +/// Service untuk Grafik Page - Backend Logic +class GraphService { + final FirebaseAuth _auth = FirebaseAuth.instance; + + ServiceResult getCurrentUserIdResult() { + final uid = _auth.currentUser?.uid; + debugPrint('[GraphService] getCurrentUserIdResult()'); + debugPrint(' Current user email: ${_auth.currentUser?.email}'); + debugPrint(' Retrieved UID: "$uid"'); + if (uid == null || uid.isEmpty) { + return ServiceResult.failure( + message: 'User tidak terautentikasi', + errorCode: 'unauthenticated', + ); + } + return ServiceResult.success( + message: 'User ID berhasil diambil', + data: uid, + ); + } + + /// Get current user + User? getCurrentUser() { + return _auth.currentUser; + } + + /// Validate user authentication + bool isUserAuthenticated() { + final user = _auth.currentUser; + final isAuth = user != null && user.uid.isNotEmpty; + debugPrint('[GraphService] isUserAuthenticated: $isAuth'); + return isAuth; + } + + /// Check if user ID is valid + bool isValidUserId(String? userId) { + final isValid = userId != null && userId.isNotEmpty; + debugPrint('[GraphService] isValidUserId("$userId"): $isValid'); + return isValid; + } +} diff --git a/lib/data/services/hidroponik_data_service.dart b/lib/data/services/hidroponik_data_service.dart new file mode 100644 index 0000000..58a536b --- /dev/null +++ b/lib/data/services/hidroponik_data_service.dart @@ -0,0 +1,83 @@ +import 'package:flutter/foundation.dart'; +import 'package:cloud_firestore/cloud_firestore.dart'; + +/// Service untuk data monitoring hidroponik (pH, nutrisi, suhu, dll) +class HidroponikDataService { + static const String collectionName = 'hidroponik_data'; + + CollectionReference> get _collection => + FirebaseFirestore.instance.collection(collectionName); + + /// Stream data terbaru untuk kartu monitoring + Stream?> latestDataStream({String? userId}) { + return _collection.snapshots().map((snapshot) { + if (snapshot.docs.isEmpty) return null; + + final allDocs = snapshot.docs + .map((doc) => {...doc.data(), 'doc_id': doc.id}) + .toList(); + + // Cari dokumen yang memiliki user_id cocok + final userDocs = (userId != null && userId.isNotEmpty) + ? allDocs.where((d) => d['user_id'] == userId).toList() + : >[]; + + // Jika ada dokumen sesuai user_id pakai userDocs, jika belum ada pakai allDocs (fallback) + final targetDocs = userDocs.isNotEmpty ? userDocs : allDocs; + + targetDocs.sort((a, b) { + final aTime = a['timestamp']; + final bTime = b['timestamp']; + if (aTime is Timestamp && bTime is Timestamp) { + return bTime.compareTo(aTime); + } else if (aTime is DateTime && bTime is DateTime) { + return bTime.compareTo(aTime); + } + return 0; + }); + + return targetDocs.first; + }).handleError((error) { + debugPrint('[HidroponikDataService] latestDataStream error: $error'); + return null; + }); + } + + /// Stream histori data untuk grafik + Stream>> historyStream({ + int limit = 7, + String? userId, + }) { + return _collection.snapshots().map((snapshot) { + if (snapshot.docs.isEmpty) return >[]; + + final allDocs = snapshot.docs + .map((doc) => {...doc.data(), 'doc_id': doc.id}) + .toList(); + + // Cari dokumen yang memiliki user_id cocok + final userDocs = (userId != null && userId.isNotEmpty) + ? allDocs.where((d) => d['user_id'] == userId).toList() + : >[]; + + // Jika ada dokumen sesuai user_id pakai userDocs, jika belum ada pakai allDocs (fallback) + final targetDocs = userDocs.isNotEmpty ? userDocs : allDocs; + + targetDocs.sort((a, b) { + final aTime = a['timestamp']; + final bTime = b['timestamp']; + if (aTime is Timestamp && bTime is Timestamp) { + return bTime.compareTo(aTime); + } else if (aTime is DateTime && bTime is DateTime) { + return bTime.compareTo(aTime); + } + return 0; + }); + + return targetDocs.take(limit <= 0 ? 1 : limit).toList(); + }).handleError((error) { + debugPrint('[HidroponikDataService] historyStream error: $error'); + return >[]; + }); + } +} diff --git a/lib/data/services/home_service.dart b/lib/data/services/home_service.dart new file mode 100644 index 0000000..c526baa --- /dev/null +++ b/lib/data/services/home_service.dart @@ -0,0 +1,200 @@ +import 'package:firebase_auth/firebase_auth.dart'; +import 'package:flutter/foundation.dart'; +import 'package:mobile_monitoring/data/models/service_result.dart'; + +/// Model untuk data monitoring +class MonitoringData { + final String ph; + final String nutrisi; + final String phStatus; + final String nutrientStatus; + final bool pumpPhUp; + final bool pumpPhDown; + final bool pumpNutrient; + final bool pumpWater; + final bool isPhAbnormal; + final bool isNutrientAbnormal; + + MonitoringData({ + required this.ph, + required this.nutrisi, + required this.phStatus, + required this.nutrientStatus, + required this.pumpPhUp, + required this.pumpPhDown, + required this.pumpNutrient, + required this.pumpWater, + required this.isPhAbnormal, + required this.isNutrientAbnormal, + }); +} + +/// Model untuk status error +class HomeDataError { + final String displayMessage; + final String detailMessage; + final ErrorType errorType; + + HomeDataError({ + required this.displayMessage, + required this.detailMessage, + required this.errorType, + }); + + factory HomeDataError.fromException(Object error) { + final errorMsg = error.toString(); + debugPrint('[HomeService] Error: $errorMsg'); + + bool isPermissionError = errorMsg.contains('permission') || errorMsg.contains('Permission'); + bool isNotAuthError = errorMsg.contains('terautentikasi'); + + if (isPermissionError) { + return HomeDataError( + displayMessage: 'Akses Ditolak', + detailMessage: 'Anda tidak memiliki izin untuk melihat data ini', + errorType: ErrorType.permission, + ); + } else if (isNotAuthError) { + return HomeDataError( + displayMessage: 'Silakan Login', + detailMessage: 'Sesi Anda telah berakhir, login kembali', + errorType: ErrorType.authentication, + ); + } else { + return HomeDataError( + displayMessage: 'Gagal memuat data', + detailMessage: 'Pastikan koneksi internet stabil', + errorType: ErrorType.network, + ); + } + } +} + +enum ErrorType { + permission, + authentication, + network, + unknown, +} + +/// Service untuk Home Page - Backend Logic +class HomeService { + final FirebaseAuth _auth = FirebaseAuth.instance; + + ServiceResult getCurrentUserIdResult() { + final uid = _auth.currentUser?.uid; + debugPrint('[HomeService] getCurrentUserIdResult()'); + debugPrint(' Current user email: ${_auth.currentUser?.email}'); + debugPrint(' Retrieved UID: "$uid"'); + debugPrint(' UID length: ${uid?.length ?? 0}'); + debugPrint(' UID is empty: ${uid?.isEmpty ?? true}'); + if (uid == null || uid.isEmpty) { + return ServiceResult.failure( + message: 'User tidak terautentikasi', + errorCode: 'unauthenticated', + ); + } + return ServiceResult.success( + message: 'User ID berhasil diambil', + data: uid, + ); + } + + /// Get current user + User? getCurrentUser() { + return _auth.currentUser; + } + + /// Get user display name + String getUserDisplayName() { + final name = _auth.currentUser?.displayName; + return name?.isNotEmpty == true ? name! : 'Petani'; + } + + /// Get user initials untuk avatar + String getUserInitials(String? name) { + if (name == null || name.isEmpty) return 'U'; + final parts = name.trim().split(' '); + if (parts.length >= 2) { + return '${parts[0][0]}${parts[1][0]}'.toUpperCase(); + } + return name[0].toUpperCase(); + } + + MonitoringData _parseMonitoringData(Map data) { + debugPrint('[HomeService] parseMonitoringData()'); + debugPrint(' Raw data: ${data.toString()}'); + + // Extract pump status + final pumpPhUp = data['pump_ph_up_status'] ?? false; + final pumpPhDown = data['pump_ph_down_status'] ?? false; + final pumpNutrient = data['pump_nutrient_status'] ?? false; + final pumpWater = data['pump_water_status'] ?? false; + + // Determine abnormality status + final bool isPhAbnormal = pumpPhUp || pumpPhDown; + final bool isNutrientAbnormal = pumpNutrient || pumpWater; + + // Determine user-friendly status + final String phStatus = isPhAbnormal ? 'Abnormal' : 'Normal'; + final String nutrientStatus = isNutrientAbnormal ? 'Abnormal' : 'Normal'; + + // Extract and format values + final ph = data['pH_value']?.toString() ?? '-'; + final nutrisi = data['nutrient_level']?.toString() ?? '-'; + + debugPrint(' Parsed pH: $ph, status: $phStatus'); + debugPrint(' Parsed nutrient: $nutrisi, status: $nutrientStatus'); + debugPrint(' Pump status - PhUp: $pumpPhUp, PhDown: $pumpPhDown, Nutrient: $pumpNutrient, Water: $pumpWater'); + + return MonitoringData( + ph: ph, + nutrisi: nutrisi, + phStatus: phStatus, + nutrientStatus: nutrientStatus, + pumpPhUp: pumpPhUp, + pumpPhDown: pumpPhDown, + pumpNutrient: pumpNutrient, + pumpWater: pumpWater, + isPhAbnormal: isPhAbnormal, + isNutrientAbnormal: isNutrientAbnormal, + ); + } + + ServiceResult parseMonitoringDataResult(Map data) { + try { + final parsed = _parseMonitoringData(data); + return ServiceResult.success( + message: 'Data monitoring berhasil diproses', + data: parsed, + ); + } catch (e) { + return ServiceResult.failure( + message: 'Gagal memproses data monitoring', + errorCode: 'parse_error', + ); + } + } + + /// Validate user authentication + bool isUserAuthenticated() { + final user = _auth.currentUser; + final isAuth = user != null && user.uid.isNotEmpty; + debugPrint('[HomeService] isUserAuthenticated: $isAuth'); + return isAuth; + } + + /// Check if user ID is valid + bool isValidUserId(String? userId) { + final isValid = userId != null && userId.isNotEmpty; + debugPrint('[HomeService] isValidUserId("$userId"): $isValid'); + return isValid; + } + + ServiceResult getErrorInfoResult(Object error) { + return ServiceResult.success( + message: 'Error info berhasil dipetakan', + data: HomeDataError.fromException(error), + ); + } +} diff --git a/lib/data/services/planting_cycles_service.dart b/lib/data/services/planting_cycles_service.dart new file mode 100644 index 0000000..4cef4cd --- /dev/null +++ b/lib/data/services/planting_cycles_service.dart @@ -0,0 +1,140 @@ +import 'package:flutter/foundation.dart'; +import 'package:cloud_firestore/cloud_firestore.dart'; +import 'package:mobile_monitoring/core/utils/cycle_phase_utils.dart'; + +/// Service untuk mengelola siklus tanam dengan fase pertumbuhan otomatis +class PlantingCyclesService { + static const String collectionName = 'planting_cycles'; + + CollectionReference> get _collection => + FirebaseFirestore.instance.collection(collectionName); + + /// Stream siklus tanam yang sedang aktif (per user dengan fallback) + Stream?> getActiveCycleStream({required String userId}) { + return _collection.snapshots().map((snapshot) { + if (snapshot.docs.isEmpty) return null; + + if (userId.isNotEmpty) { + final matches = snapshot.docs.where((d) => d.id == userId).toList(); + if (matches.isNotEmpty && matches.first.data().isNotEmpty) { + return {...matches.first.data(), 'doc_id': matches.first.id}; + } + } + + // Fallback ke dokumen siklus tanam pertama di database + final firstDoc = snapshot.docs.first; + return {...firstDoc.data(), 'doc_id': firstDoc.id}; + }).handleError((error) { + debugPrint('[PlantingCyclesService] Stream error: $error'); + return null; + }); + } + + /// Tambah siklus tanam baru (gunakan userId sebagai doc ID) + Future addCycle({ + required String userId, + required DateTime startDate, + }) async { + if (userId.isEmpty) throw Exception('User tidak terautentikasi'); + + await _collection.doc(userId).set({ + 'user_id': userId, + 'start_date': Timestamp.fromDate(startDate), + 'days_since_planting': 0, + 'growth_phase': 'Semai', + 'created_at': FieldValue.serverTimestamp(), + 'updated_at': FieldValue.serverTimestamp(), + }); + + return userId; + } + + /// Update hari dan fase tanam berdasarkan start_date + Future updateCycleProgress({ + required String userId, + required DateTime startDate, + }) async { + final now = DateTime.now(); + final daysSincePlanting = now.difference(startDate).inDays; + final growthPhase = CyclePhaseUtils.calculateCyclePhase(daysSincePlanting); + + await _collection.doc(userId).set({ + 'days_since_planting': daysSincePlanting, + 'growth_phase': growthPhase, + 'updated_at': FieldValue.serverTimestamp(), + }, SetOptions(merge: true)); + } + + /// Hitung hari total siklus untuk panen + Future calculateCycleDaysBeforeDelete({required String userId}) async { + if (userId.isEmpty) throw Exception('User tidak terautentikasi'); + + final doc = await _collection.doc(userId).get(); + if (!doc.exists || doc.data() == null) { + throw Exception('Siklus tanam aktif tidak ditemukan'); + } + + final data = doc.data()!; + final startValue = data['start_date']; + DateTime? startDate; + + if (startValue is Timestamp) { + startDate = startValue.toDate(); + } else if (startValue is DateTime) { + startDate = startValue; + } + + final daysSincePlanting = startDate == null + ? (data['days_since_planting'] as num?)?.toInt() ?? 0 + : DateTime.now().difference(startDate).inDays; + + return daysSincePlanting; + } + + /// Hapus siklus tanam (gunakan userId) + Future deleteCycle({required String userId}) async { + await _collection.doc(userId).delete(); + } + + /// Get detail siklus berdasarkan userId dengan update otomatis + Future?> getCycleByUserId({ + required String userId, + }) async { + final doc = await _collection.doc(userId).get(); + if (!doc.exists || doc.data() == null) return null; + + final data = doc.data()!; + final startDate = (data['start_date'] as Timestamp).toDate(); + + // Update progress sebelum return + await updateCycleProgress(userId: userId, startDate: startDate); + + // Get data terbaru + final updatedDoc = await _collection.doc(userId).get(); + if (!updatedDoc.exists) return null; + return {...updatedDoc.data()!, 'doc_id': updatedDoc.id}; + } + + /// Get siklus aktif dengan info fase terkini + Future?> getActiveCycle({required String userId}) async { + if (userId.isEmpty) throw Exception('User tidak terautentikasi'); + + final doc = await _collection.doc(userId).get(); + if (!doc.exists || doc.data() == null) return null; + + final data = doc.data()!; + final startDate = (data['start_date'] as Timestamp).toDate(); + + // Hitung days_since_planting dan growth_phase terkini + final now = DateTime.now(); + final daysSincePlanting = now.difference(startDate).inDays; + final growthPhase = CyclePhaseUtils.calculateCyclePhase(daysSincePlanting); + + return { + ...data, + 'doc_id': doc.id, + 'days_since_planting': daysSincePlanting, + 'growth_phase': growthPhase, + }; + } +} diff --git a/lib/data/services/profile_service.dart b/lib/data/services/profile_service.dart new file mode 100644 index 0000000..b6e75e1 --- /dev/null +++ b/lib/data/services/profile_service.dart @@ -0,0 +1,192 @@ +import 'package:firebase_auth/firebase_auth.dart'; +import 'package:flutter/foundation.dart'; +import 'package:mobile_monitoring/data/models/service_result.dart'; + +/// Model untuk user profile info +class UserProfileInfo { + final String? displayName; + final String? email; + final String initials; + + UserProfileInfo({ + required this.displayName, + required this.email, + required this.initials, + }); +} + +/// Service untuk Profile Page - Backend Logic +/// Tidak ada dependency ke UI (no BuildContext, no widgets) +class ProfileService { + final FirebaseAuth _auth = FirebaseAuth.instance; + + /// Get current user profile info + UserProfileInfo? getCurrentUserProfile() { + final user = _auth.currentUser; + if (user == null) { + debugPrint('[ProfileService] No current user'); + return null; + } + + debugPrint('[ProfileService] getCurrentUserProfile()'); + debugPrint(' Name: ${user.displayName}'); + debugPrint(' Email: ${user.email}'); + + return UserProfileInfo( + displayName: user.displayName, + email: user.email, + initials: _generateInitials(user.displayName), + ); + } + + /// Get current user + User? getCurrentUser() { + return _auth.currentUser; + } + + /// Generate initials dari nama + /// Business logic untuk format display initials + String _generateInitials(String? name) { + if (name == null || name.isEmpty) return 'U'; + final parts = name.trim().split(' '); + if (parts.length >= 2) { + return '${parts[0][0]}${parts[1][0]}'.toUpperCase(); + } + return name[0].toUpperCase(); + } + + /// Generate initials - exposed untuk public use + String generateInitials(String? name) { + return _generateInitials(name); + } + + /// Update user profile name + /// Backend logic untuk update nama user + Future> updateUserName(String newName) async { + try { + final user = _auth.currentUser; + if (user == null) { + debugPrint('[ProfileService] No current user'); + return ServiceResult.failure( + message: 'Silakan login terlebih dahulu', + errorCode: 'no_user', + ); + } + + debugPrint('[ProfileService] updateUserName() - new name: "$newName"'); + + // Validasi input + if (newName.trim().isEmpty) { + return ServiceResult.failure( + message: 'Nama tidak boleh kosong', + errorCode: 'empty_name', + ); + } + + // Update display name + await user.updateDisplayName(newName.trim()); + await user.reload(); + + debugPrint('[ProfileService] ✓ Name updated successfully'); + + return ServiceResult.success( + message: 'Nama berhasil diperbarui', + ); + } catch (e) { + debugPrint('[ProfileService] ✗ Failed to update name: $e'); + return ServiceResult.failure( + message: 'Gagal memperbarui nama: $e', + errorCode: 'update_failed', + ); + } + } + + /// Validate password change + /// Business logic untuk validate password lama dan ganti dengan yang baru + Future> validateAndUpdatePassword( + String oldPassword, + String newPassword, + ) async { + try { + final user = _auth.currentUser; + if (user == null || user.email == null) { + debugPrint('[ProfileService] No current user or email'); + return ServiceResult.failure( + message: 'Silakan login terlebih dahulu', + errorCode: 'no_user', + ); + } + + debugPrint('[ProfileService] validateAndUpdatePassword()'); + debugPrint(' Email: ${user.email}'); + + // Validasi input + if (oldPassword.isEmpty || newPassword.isEmpty) { + return ServiceResult.failure( + message: 'Password tidak boleh kosong', + errorCode: 'empty_password', + ); + } + + if (newPassword.length < 6) { + return ServiceResult.failure( + message: 'Password baru minimal 6 karakter', + errorCode: 'weak_password', + ); + } + + // Reauthenticate dengan password lama + debugPrint('[ProfileService] Reauthenticating...'); + final credential = EmailAuthProvider.credential( + email: user.email!, + password: oldPassword, + ); + + try { + await user.reauthenticateWithCredential(credential); + debugPrint('[ProfileService] ✓ Reauthentication successful'); + } on FirebaseAuthException catch (e) { + debugPrint('[ProfileService] ✗ Reauthentication failed: ${e.code}'); + if (e.code == 'wrong-password') { + return ServiceResult.failure( + message: 'Password lama Anda salah', + errorCode: 'wrong_password', + ); + } + return ServiceResult.failure( + message: 'Gagal memverifikasi password lama', + errorCode: e.code, + ); + } + + // Update password + debugPrint('[ProfileService] Updating password...'); + await user.updatePassword(newPassword); + + debugPrint('[ProfileService] ✓ Password updated successfully'); + + return ServiceResult.success( + message: 'Password berhasil diubah', + ); + } catch (e) { + debugPrint('[ProfileService] ✗ Failed to update password: $e'); + return ServiceResult.failure( + message: 'Gagal mengubah password: $e', + errorCode: 'update_failed', + ); + } + } + + /// Validate email + bool isValidEmail(String email) { + return email.isNotEmpty && email.contains('@'); + } + + /// Check if user is authenticated + bool isUserAuthenticated() { + final user = _auth.currentUser; + final isAuth = user != null && user.uid.isNotEmpty; + debugPrint('[ProfileService] isUserAuthenticated: $isAuth'); + return isAuth; + } +} diff --git a/lib/data/services/register_service.dart b/lib/data/services/register_service.dart new file mode 100644 index 0000000..4435c3a --- /dev/null +++ b/lib/data/services/register_service.dart @@ -0,0 +1,80 @@ +import 'package:flutter/foundation.dart'; +import 'package:mobile_monitoring/data/services/auth_service.dart'; +import 'package:mobile_monitoring/data/services/users_service.dart'; +import 'package:mobile_monitoring/data/services/planting_cycles_service.dart'; +import 'package:mobile_monitoring/data/models/service_result.dart'; + +class RegisterRequest { + final String name; + final String email; + final String password; + final String confirmPassword; + + RegisterRequest({ + required this.name, + required this.email, + required this.password, + required this.confirmPassword, + }); +} + +class RegisterService { + final AuthService _authService; + final UsersService _usersService; + final PlantingCyclesService _cyclesService; + + RegisterService({ + AuthService? authService, + UsersService? usersService, + PlantingCyclesService? cyclesService, + }) : _authService = authService ?? AuthService(), + _usersService = usersService ?? UsersService(), + _cyclesService = cyclesService ?? PlantingCyclesService(); + + Future> register(RegisterRequest request) async { + final name = request.name.trim(); + final email = request.email.trim(); + final password = request.password; + final confirmPassword = request.confirmPassword; + + if (name.isEmpty) return ServiceResult.failure(message: 'Nama tidak boleh kosong'); + if (!_authService.isValidEmail(email)) return ServiceResult.failure(message: 'Email tidak valid'); + if (!_authService.isValidPassword(password)) return ServiceResult.failure(message: 'Password minimal 6 karakter'); + if (password != confirmPassword) return ServiceResult.failure(message: 'Password tidak cocok'); + + debugPrint('[RegisterService] Register attempt for: $email'); + + final result = await _authService.registerWithEmailAndPassword( + email: email, + password: password, + name: name, + ); + + if (result.success) { + final user = result.data; + if (user != null) { + try { + // 1. OTOMATIS BUILD COLLECTION 'users' + await _usersService.createUserDocument(user.uid, name, email); + + // 2. OTOMATIS BUILD COLLECTION 'planting_cycles' + // Fungsi addCycle di PlantingCyclesService akan membuat fase 'Semai' + await _cyclesService.addCycle( + userId: user.uid, + startDate: DateTime.now(), + ); + + debugPrint('[RegisterService] Berhasil men-generate semua collection awal'); + } catch (e) { + debugPrint('[RegisterService] Error saat membuat collection: $e'); + } + } + + return ServiceResult.success( + message: 'Registrasi berhasil! Selamat datang', + ); + } + + return ServiceResult.failure(message: result.message); + } +} diff --git a/lib/data/services/services.dart b/lib/data/services/services.dart new file mode 100644 index 0000000..d1352bc --- /dev/null +++ b/lib/data/services/services.dart @@ -0,0 +1,26 @@ +// Service Index - Barrel File +// Import semua services dari satu file ini untuk kemudahan +// +// Contoh penggunaan: +// import 'package:mobile_monitoring/data/services/services.dart'; +// +// Kemudian bisa langsung gunakan semua service: +// - AuthService +// - FlowService +// - GraphService +// - HidroponikDataService +// - HomeService +// - PlantingCyclesService +// - ProfileService +// - RegisterService +// - UsersService + +export 'auth_service.dart'; +export 'flow_service.dart'; +export 'graph_service.dart'; +export 'hidroponik_data_service.dart'; +export 'home_service.dart'; +export 'planting_cycles_service.dart'; +export 'profile_service.dart'; +export 'register_service.dart'; +export 'users_service.dart'; diff --git a/lib/data/services/users_service.dart b/lib/data/services/users_service.dart new file mode 100644 index 0000000..1e61f60 --- /dev/null +++ b/lib/data/services/users_service.dart @@ -0,0 +1,156 @@ +import 'dart:io'; +import 'package:flutter/foundation.dart'; +import 'package:firebase_auth/firebase_auth.dart'; +import 'package:cloud_firestore/cloud_firestore.dart'; +import 'package:image/image.dart' as img; +import 'package:path_provider/path_provider.dart'; + +/// Service untuk mengelola data user (profile, foto, password) +class UsersService { + final FirebaseAuth _auth = FirebaseAuth.instance; + final FirebaseFirestore _firestore = FirebaseFirestore.instance; + static const String collectionName = 'users'; + + User? get currentUser => _auth.currentUser; + String get userId => currentUser?.uid ?? ''; + + /// Inisiasi profil saat pertama kali register + Future createUserDocument(String uid, String name, String email) async { + try { + await _firestore.collection(collectionName).doc(uid).set({ + 'user_id': uid, + 'display_name': name.trim(), + 'email': email.trim(), + 'created_at': FieldValue.serverTimestamp(), + 'updated_at': FieldValue.serverTimestamp(), + }); + } catch (e) { + throw Exception('Gagal inisiasi dokumen user: $e'); + } + } + + /// Update nama user di Firebase Auth dan Firestore + Future updateName(String name) async { + try { + await currentUser?.updateDisplayName(name.trim()); + await _firestore.collection(collectionName).doc(userId).set( + { + 'user_id': userId, + 'display_name': name.trim(), + 'updated_at': FieldValue.serverTimestamp(), + }, + SetOptions(merge: true), + ); + await currentUser?.reload(); + } catch (e) { + throw Exception('Gagal update nama: $e'); + } + } + + /// Kompresi gambar ke 800x800px dengan quality 75% + Future _compressImage(File imageFile) async { + try { + final bytes = await imageFile.readAsBytes(); + final image = img.decodeImage(bytes); + if (image == null) throw Exception('Gagal decode gambar'); + + final resized = img.copyResize(image, width: 800, height: 800, maintainAspect: true); + final compressed = img.encodeJpg(resized, quality: 75); + + final dir = await getApplicationDocumentsDirectory(); + final compressedFile = File('${dir.path}/profile_compressed.jpg'); + await compressedFile.writeAsBytes(compressed); + return compressedFile; + } catch (e) { + throw Exception('Gagal kompresi foto: $e'); + } + } + + /// Simpan foto profil ke lokal storage dengan kompresi + Future saveProfilePhotoLocal(File imageFile) async { + try { + if (userId.isEmpty) throw Exception('User tidak terautentikasi'); + if (!await imageFile.exists()) throw Exception('File gambar tidak ditemukan'); + + final compressedFile = await _compressImage(imageFile); + final appDocDir = await getApplicationDocumentsDirectory(); + final photosDir = Directory('${appDocDir.path}/HydroNutrify/photos'); + + if (!await photosDir.exists()) { + await photosDir.create(recursive: true); + } + + final fileName = 'profile_${DateTime.now().millisecondsSinceEpoch}.jpg'; + final localPath = '${photosDir.path}/$fileName'; + await compressedFile.copy(localPath); + + await _firestore.collection(collectionName).doc(userId).set({ + 'user_id': userId, + 'profile_photo_filename': fileName, + 'profile_photo_path': localPath, + 'updated_at': FieldValue.serverTimestamp(), + }, SetOptions(merge: true)); + + return localPath; + } catch (e) { + throw Exception('Gagal simpan foto lokal: $e'); + } + } + + /// Get path foto profil dari lokal storage + Future getProfilePhotoPath() async { + try { + final profile = await getUserProfile(); + if (profile != null) { + final filePath = profile['profile_photo_path'] as String?; + if (filePath != null && await File(filePath).exists()) { + return filePath; + } + } + return null; + } catch (e) { + return null; + } + } + + /// Update password dengan re-authentication + Future reauthenticateAndUpdatePassword(String oldPassword, String newPassword) async { + try { + if (currentUser == null) throw Exception('User tidak ditemukan'); + final email = currentUser!.email; + if (email == null) throw Exception('Email tidak ditemukan'); + + final credential = EmailAuthProvider.credential(email: email, password: oldPassword); + await currentUser!.reauthenticateWithCredential(credential); + await currentUser!.updatePassword(newPassword); + } on FirebaseAuthException catch (e) { + if (e.code == 'wrong-password') { + throw Exception('Password lama salah'); + } else if (e.code == 'weak-password') { + throw Exception('Password baru terlalu lemah'); + } + throw Exception('Gagal update password: ${e.message}'); + } + } + + /// Get data profile user dari Firestore + Future?> getUserProfile() async { + try { + if (userId.isEmpty) return null; + final doc = await _firestore.collection(collectionName).doc(userId).get(); + return doc.data(); + } catch (e) { + return null; + } + } + + /// Stream perubahan profile user real-time + Stream getUserProfileStream() { + if (userId.isEmpty) return Stream.value(null); + return _firestore.collection(collectionName).doc(userId).snapshots().handleError((e) { + debugPrint('[UsersService] Stream error: $e'); + return null; + }); + } +} + diff --git a/lib/logic/controllers/auth_controller.dart b/lib/logic/controllers/auth_controller.dart new file mode 100644 index 0000000..4e4361c --- /dev/null +++ b/lib/logic/controllers/auth_controller.dart @@ -0,0 +1,91 @@ +import 'package:mobile_monitoring/data/models/service_result.dart'; +import 'package:mobile_monitoring/data/services/auth_service.dart'; +import 'package:mobile_monitoring/data/services/register_service.dart'; +import 'package:mobile_monitoring/logic/controllers/base_controller.dart'; + +class AuthController extends BaseController { + AuthController({AuthService? authService, RegisterService? registerService}) + : _authService = authService ?? AuthService(), + _registerService = registerService ?? RegisterService(); + + final AuthService _authService; + final RegisterService _registerService; + + bool _isLoading = false; + String? _lastMessage; + + bool get isLoading => _isLoading; + String? get lastMessage => _lastMessage; + String? get currentUserId => _authService.currentUser?.uid; + + Future> login({ + required String email, + required String password, + }) async { + _setLoading(true); + final result = await _authService.signInWithEmailAndPassword( + email: email.trim(), + password: password, + ); + _setLoading(false); + + _lastMessage = result.message; + notifyListeners(); + + if (!result.success) { + return ServiceResult.failure( + message: result.message, + errorCode: result.errorCode, + ); + } + + return ServiceResult.success(message: result.message); + } + + Future> register({ + required String name, + required String email, + required String password, + required String confirmPassword, + }) async { + _setLoading(true); + final result = await _registerService.register( + RegisterRequest( + name: name, + email: email, + password: password, + confirmPassword: confirmPassword, + ), + ); + _setLoading(false); + + _lastMessage = result.message; + notifyListeners(); + return result; + } + + Future> forgotPassword(String email) async { + _setLoading(true); + final result = await _authService.resetPassword(email.trim()); + _setLoading(false); + + _lastMessage = result.message; + notifyListeners(); + return result; + } + + Future> logout() async { + _setLoading(true); + final result = await _authService.signOut(); + _setLoading(false); + + _lastMessage = result.message; + notifyListeners(); + return result; + } + + void _setLoading(bool value) { + _isLoading = value; + notifyListeners(); + } +} diff --git a/lib/logic/controllers/base_controller.dart b/lib/logic/controllers/base_controller.dart new file mode 100644 index 0000000..c33bc15 --- /dev/null +++ b/lib/logic/controllers/base_controller.dart @@ -0,0 +1,7 @@ +import 'package:flutter/foundation.dart'; + +abstract class BaseController extends ChangeNotifier { + void onInit() {} + + void onReady() {} +} diff --git a/lib/logic/controllers/controllers.dart b/lib/logic/controllers/controllers.dart new file mode 100644 index 0000000..4802e58 --- /dev/null +++ b/lib/logic/controllers/controllers.dart @@ -0,0 +1,7 @@ +// Export semua controllers dari logic layer +export 'base_controller.dart'; +export 'auth_controller.dart'; +export 'profile_controller.dart'; +export 'home_controller.dart'; +export 'flow_controller.dart'; +export 'graph_controller.dart'; diff --git a/lib/logic/controllers/flow_controller.dart b/lib/logic/controllers/flow_controller.dart new file mode 100644 index 0000000..d0cbbf0 --- /dev/null +++ b/lib/logic/controllers/flow_controller.dart @@ -0,0 +1,65 @@ +import 'package:mobile_monitoring/data/models/service_result.dart'; +import 'package:mobile_monitoring/data/services/auth_service.dart'; +import 'package:mobile_monitoring/data/services/flow_service.dart'; +import 'package:mobile_monitoring/data/services/hidroponik_data_service.dart'; +import 'package:mobile_monitoring/data/services/planting_cycles_service.dart'; +import 'package:mobile_monitoring/logic/controllers/base_controller.dart'; + +class FlowController extends BaseController { + FlowController({ + FlowService? flowService, + AuthService? authService, + HidroponikDataService? hidroponikDataService, + PlantingCyclesService? plantingCyclesService, + }) : _flowService = flowService ?? FlowService(), + _authService = authService ?? AuthService(), + _hidroponikDataService = hidroponikDataService ?? HidroponikDataService(), + _plantingCyclesService = plantingCyclesService ?? PlantingCyclesService(); + + final FlowService _flowService; + final AuthService _authService; + final HidroponikDataService _hidroponikDataService; + final PlantingCyclesService _plantingCyclesService; + + String? resolveUserId(String? pageUserId) { + return pageUserId ?? _authService.currentUser?.uid; + } + + ServiceResult parseMonitoringData(Map data) { + return _flowService.parseMonitoringDataResult(data); + } + + ServiceResult mapError(Object error) { + return _flowService.getErrorInfoResult(error); + } + + ServiceResult hasActiveCycle(Map? cycleData) { + return _flowService.hasActiveCycleResult(cycleData); + } + + ServiceResult extractStartDate(Map? cycleData) { + return _flowService.extractStartDateResult(cycleData); + } + + ServiceResult> generateRecapRows( + List> docs, + DateTime? startDate, + ) { + return _flowService.generateRecapRowsResult(docs, startDate); + } + + Stream?> latestDataStream(String? userId) { + return _hidroponikDataService.latestDataStream(userId: userId); + } + + Stream?> activeCycleStream(String userId) { + return _plantingCyclesService.getActiveCycleStream(userId: userId); + } + + Stream>> historyStream({ + required int limit, + required String? userId, + }) { + return _hidroponikDataService.historyStream(limit: limit, userId: userId); + } +} diff --git a/lib/logic/controllers/graph_controller.dart b/lib/logic/controllers/graph_controller.dart new file mode 100644 index 0000000..155a76b --- /dev/null +++ b/lib/logic/controllers/graph_controller.dart @@ -0,0 +1,12 @@ +import 'package:mobile_monitoring/data/services/graph_service.dart'; +import 'package:mobile_monitoring/logic/controllers/base_controller.dart'; + +class GraphController extends BaseController { + GraphController({GraphService? graphService}) + : _graphService = graphService ?? GraphService(); + + final GraphService _graphService; + + String? get currentUserId => _graphService.getCurrentUserIdResult().data; + bool get isAuthenticated => _graphService.isUserAuthenticated(); +} diff --git a/lib/logic/controllers/home_controller.dart b/lib/logic/controllers/home_controller.dart new file mode 100644 index 0000000..d8d6264 --- /dev/null +++ b/lib/logic/controllers/home_controller.dart @@ -0,0 +1,39 @@ +import 'package:mobile_monitoring/data/models/service_result.dart'; +import 'package:mobile_monitoring/data/services/hidroponik_data_service.dart'; +import 'package:mobile_monitoring/data/services/home_service.dart'; +import 'package:mobile_monitoring/logic/controllers/base_controller.dart'; + +class HomeController extends BaseController { + HomeController({ + HomeService? homeService, + HidroponikDataService? hidroponikDataService, + }) : _homeService = homeService ?? HomeService(), + _hidroponikDataService = hidroponikDataService ?? HidroponikDataService(); + + final HomeService _homeService; + final HidroponikDataService _hidroponikDataService; + + int _selectedIndex = 1; + + int get selectedIndex => _selectedIndex; + String get userDisplayName => _homeService.getUserDisplayName(); + String get userInitials => _homeService.getUserInitials(userDisplayName); + String? get currentUserId => _homeService.getCurrentUserIdResult().data; + + void setSelectedIndex(int index) { + _selectedIndex = index; + notifyListeners(); + } + + ServiceResult parseMonitoringData(Map data) { + return _homeService.parseMonitoringDataResult(data); + } + + ServiceResult mapError(Object error) { + return _homeService.getErrorInfoResult(error); + } + + Stream?> latestDataStream(String? userId) { + return _hidroponikDataService.latestDataStream(userId: userId); + } +} diff --git a/lib/logic/controllers/profile_controller.dart b/lib/logic/controllers/profile_controller.dart new file mode 100644 index 0000000..05d2be4 --- /dev/null +++ b/lib/logic/controllers/profile_controller.dart @@ -0,0 +1,72 @@ +import 'package:flutter/material.dart'; +import 'package:mobile_monitoring/data/models/service_result.dart'; +import 'package:mobile_monitoring/data/services/auth_service.dart'; +import 'package:mobile_monitoring/data/services/profile_service.dart'; +import 'package:mobile_monitoring/logic/controllers/base_controller.dart'; + +class ProfileController extends BaseController { + ProfileController({ + ProfileService? profileService, + AuthService? authService, + }) : _profileService = profileService ?? ProfileService(), + _authService = authService ?? AuthService(); + + final ProfileService _profileService; + final AuthService _authService; + + final TextEditingController nameController = TextEditingController(); + + bool _isLoading = false; + UserProfileInfo? _profile; + + bool get isLoading => _isLoading; + UserProfileInfo? get profile => _profile; + + void loadProfile() { + _profile = _profileService.getCurrentUserProfile(); + nameController.text = _profile?.displayName ?? ''; + notifyListeners(); + } + + Future> updateProfile() async { + _setLoading(true); + final result = await _profileService.updateUserName(nameController.text.trim()); + if (result.success) { + _profile = _profileService.getCurrentUserProfile(); + nameController.text = _profile?.displayName ?? ''; + } + _setLoading(false); + return result; + } + + Future> changePassword({ + required String oldPassword, + required String newPassword, + }) async { + _setLoading(true); + final result = await _profileService.validateAndUpdatePassword( + oldPassword, + newPassword, + ); + _setLoading(false); + return result; + } + + Future> logout() async { + _setLoading(true); + final result = await _authService.signOut(); + _setLoading(false); + return result; + } + + void _setLoading(bool value) { + _isLoading = value; + notifyListeners(); + } + + @override + void dispose() { + nameController.dispose(); + super.dispose(); + } +} diff --git a/lib/logic/logic.dart b/lib/logic/logic.dart new file mode 100644 index 0000000..ed8af5f --- /dev/null +++ b/lib/logic/logic.dart @@ -0,0 +1,2 @@ +// Export semua file dari logic layer +export 'controllers/controllers.dart'; diff --git a/lib/main.dart b/lib/main.dart new file mode 100644 index 0000000..350979a --- /dev/null +++ b/lib/main.dart @@ -0,0 +1,123 @@ +import 'dart:async'; +import 'package:flutter/material.dart'; +import 'package:firebase_core/firebase_core.dart'; +import 'package:firebase_auth/firebase_auth.dart'; +import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:mobile_monitoring/core/firebase_options.dart'; +import 'package:mobile_monitoring/core/constants/strings.dart'; +import 'package:mobile_monitoring/core/theme/app_theme.dart'; +import 'package:mobile_monitoring/ui/pages/splash_screen.dart'; +import 'package:mobile_monitoring/ui/pages/login.dart'; +import 'package:mobile_monitoring/ui/pages/home.dart'; + +void main() async { + WidgetsFlutterBinding.ensureInitialized(); + await dotenv.load(fileName: '.env'); + FlutterError.onError = (details) { + FlutterError.presentError(details); + debugPrint('FlutterError: ${details.exceptionAsString()}'); + debugPrint(details.stack?.toString()); + }; + + await runZonedGuarded( + () async { + await Firebase.initializeApp( + options: DefaultFirebaseOptions.currentPlatform, + ); + // Disable reCAPTCHA for development + FirebaseAuth.instance.setSettings( + appVerificationDisabledForTesting: true, + ); + runApp(const MyApp()); + }, + (error, stack) { + debugPrint('Zoned error: $error'); + debugPrint(stack.toString()); + }, + ); +} + +class MyApp extends StatelessWidget { + const MyApp({super.key}); + + @override + Widget build(BuildContext context) { + return MaterialApp( + title: AppStrings.appName, + debugShowCheckedModeBanner: false, + theme: AppTheme.lightTheme, + navigatorObservers: [LoggingNavigatorObserver()], + home: const SplashScreen( + duration: Duration(seconds: 3), + nextPage: AuthWrapper(), + ), + onGenerateRoute: (settings) { + switch (settings.name) { + case '/home': + return MaterialPageRoute( + builder: (context) => const HomePage(), + settings: settings, + ); + default: + return null; + } + }, + ); + } +} + +class LoggingNavigatorObserver extends NavigatorObserver { + LoggingNavigatorObserver(); + + @override + void didPush(Route route, Route? previousRoute) { + debugPrint('NAV push: ${route.settings.name ?? route.runtimeType}'); + super.didPush(route, previousRoute); + } + + @override + void didPop(Route route, Route? previousRoute) { + debugPrint('NAV pop: ${route.settings.name ?? route.runtimeType}'); + super.didPop(route, previousRoute); + } + + @override + void didReplace({Route? newRoute, Route? oldRoute}) { + debugPrint( + 'NAV replace: ${oldRoute?.settings.name ?? oldRoute?.runtimeType} -> ${newRoute?.settings.name ?? newRoute?.runtimeType}', + ); + super.didReplace(newRoute: newRoute, oldRoute: oldRoute); + } +} + +class AuthWrapper extends StatefulWidget { + const AuthWrapper({super.key}); + + @override + State createState() => _AuthWrapperState(); +} + +class _AuthWrapperState extends State { + @override + Widget build(BuildContext context) { + return StreamBuilder( + stream: FirebaseAuth.instance.authStateChanges(), + builder: (context, snapshot) { + // Show loading while checking auth state + if (snapshot.connectionState == ConnectionState.waiting) { + return const Scaffold( + body: Center(child: CircularProgressIndicator()), + ); + } + + // If user is logged in, show home page + if (snapshot.hasData) { + return const HomePage(); + } + + // If user is not logged in, show login page + return const LoginPage(); + }, + ); + } +} diff --git a/lib/ui/pages/flow.dart b/lib/ui/pages/flow.dart new file mode 100644 index 0000000..cfbb449 --- /dev/null +++ b/lib/ui/pages/flow.dart @@ -0,0 +1,158 @@ +import 'package:flutter/material.dart'; +import 'package:mobile_monitoring/core/constants/constants.dart'; +import 'package:mobile_monitoring/data/services/flow_service.dart'; +import 'package:mobile_monitoring/logic/controllers/controllers.dart'; +import 'package:mobile_monitoring/ui/shared/monitoring_card.dart'; +import 'package:mobile_monitoring/ui/shared/monitoring_recap_table.dart'; +import 'package:mobile_monitoring/ui/shared/tips_card.dart'; + +class FlowPage extends StatefulWidget { + final String? userId; + + const FlowPage({super.key, this.userId}); + + @override + State createState() => _FlowPageState(); +} + +class _FlowPageState extends State { + final _controller = FlowController(); + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final userId = _controller.resolveUserId(widget.userId); + + return Scaffold( + backgroundColor: AppColors.pageBackground, + appBar: AppBar( + title: const Text(AppStrings.monitoring), + backgroundColor: AppColors.primary, + elevation: 0, + centerTitle: true, + foregroundColor: AppColors.white, + ), + body: SingleChildScrollView( + child: Padding( + padding: const EdgeInsets.all(AppSettings.defaultPadding), + child: Column( + children: [ + StreamBuilder?>( + stream: _controller.latestDataStream(userId), + builder: (context, snapshot) { + if (snapshot.connectionState == ConnectionState.waiting) { + return const SizedBox( + height: 250, + child: Center(child: CircularProgressIndicator()), + ); + } + + final data = snapshot.data; + final monitoringData = data != null + ? (_controller.parseMonitoringData(data).data ?? + FlowMonitoringData( + ph: 0.0, + tds: 0.0, + phStatus: 'Menunggu Data', + tdsStatus: 'Menunggu Data', + phColor: AppColors.primary, + tdsColor: AppColors.primary, + pumpPhUp: false, + pumpPhDown: false, + pumpNutrient: false, + pumpWater: false, + )) + : FlowMonitoringData( + ph: 0.0, + tds: 0.0, + phStatus: 'Menunggu Data', + tdsStatus: 'Menunggu Data', + phColor: AppColors.primary, + tdsColor: AppColors.primary, + pumpPhUp: false, + pumpPhDown: false, + pumpNutrient: false, + pumpWater: false, + ); + return Column( + children: [ + MonitoringCard( + title: 'PH Level', + value: monitoringData.ph.toStringAsFixed(2), + unit: '', + status: monitoringData.phStatus, + statusColor: monitoringData.phColor, + description: 'Jaga pH larutan antara 4.0 - 6.0', + userId: userId, + switch1Value: monitoringData.pumpPhUp, + switch2Value: monitoringData.pumpPhDown, + switch1Label: 'PH Up', + switch2Label: 'PH Down', + onSwitch1Changed: (_) => setState(() {}), + onSwitch2Changed: (_) => setState(() {}), + ), + const SizedBox(height: 4), + MonitoringCard( + title: 'Nutrient Level', + value: monitoringData.tds.toStringAsFixed(0), + unit: 'ppm', + status: monitoringData.tdsStatus, + statusColor: monitoringData.tdsColor, + description: 'Pastikan TDS/PPM sesuai fase', + userId: userId, + switch1Value: monitoringData.pumpNutrient, + switch2Value: monitoringData.pumpWater, + switch1Label: 'Nutrisi', + switch2Label: 'Air Baku', + onSwitch1Changed: (_) => setState(() {}), + onSwitch2Changed: (_) => setState(() {}), + ), + ], + ); + }, + ), + const SizedBox(height: 16), + StreamBuilder?>( + stream: _controller.activeCycleStream(userId ?? ''), + builder: (context, cycleSnapshot) { + final startDate = _controller.extractStartDate(cycleSnapshot.data).data; + return StreamBuilder>>( + stream: _controller.historyStream(limit: 500, userId: userId), + builder: (context, snapshot) { + if (snapshot.connectionState == ConnectionState.waiting) { + return const SizedBox( + height: 200, + child: Center(child: CircularProgressIndicator()), + ); + } + + final docs = snapshot.data ?? []; + if (docs.isEmpty) { + return const MonitoringRecapTable(data: []); + } + + final recapResult = _controller.generateRecapRows(docs, startDate); + if (!recapResult.success || recapResult.data == null) { + return const MonitoringRecapTable(data: []); + } + + final rowsAsMap = recapResult.data!.map((row) => row.toMap()).toList(); + return MonitoringRecapTable(data: rowsAsMap, startDate: startDate); + }, + ); + }, + ), + const SizedBox(height: 16), + const TipsCard(), + ], + ), + ), + ), + ); + } +} diff --git a/lib/ui/pages/home.dart b/lib/ui/pages/home.dart new file mode 100644 index 0000000..3e35514 --- /dev/null +++ b/lib/ui/pages/home.dart @@ -0,0 +1,221 @@ +import 'package:flutter/material.dart'; +import 'package:mobile_monitoring/core/constants/constants.dart'; +import 'package:mobile_monitoring/data/services/home_service.dart'; +import 'package:mobile_monitoring/logic/controllers/controllers.dart'; +import 'package:mobile_monitoring/ui/pages/flow.dart'; +import 'package:mobile_monitoring/ui/pages/settings.dart'; +import 'package:mobile_monitoring/ui/shared/shared.dart'; + +class HomePage extends StatefulWidget { + const HomePage({super.key}); + + @override + State createState() => _HomePageState(); +} + +class _HomePageState extends State { + final _controller = HomeController(); + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return ListenableBuilder( + listenable: _controller, + builder: (context, _) { + final userId = _controller.currentUserId; + final pages = [ + FlowPage(userId: userId), + _HomeScreenContent(controller: _controller), + const GraphMenuPage(), + ]; + + return Scaffold( + body: pages[_controller.selectedIndex], + bottomNavigationBar: BottomNavbar( + currentIndex: _controller.selectedIndex, + onTap: _controller.setSelectedIndex, + ), + ); + }, + ); + } +} + +class _HomeScreenContent extends StatelessWidget { + final HomeController controller; + + const _HomeScreenContent({required this.controller}); + + @override + Widget build(BuildContext context) { + final userId = controller.currentUserId; + + return SingleChildScrollView( + child: Container( + color: AppColors.pageBackground, + child: Column( + children: [ + HomeHeader(controller: controller), + SizedBox(height: MediaQuery.of(context).size.width >= 600 ? 40 : 30), + _buildSectionTitle(context, AppStrings.growthPhase), + const GrowthPhaseCard(), + const SizedBox(height: 24), + _buildSectionTitle( + context, + '${AppStrings.monitoring} & Kontrol', + onTap: () => Navigator.push( + context, + MaterialPageRoute(builder: (_) => FlowPage(userId: userId)), + ), + ), + Container( + width: double.infinity, + color: AppColors.lightGray, + child: _buildMonitoringCards(userId), + ), + const SizedBox(height: 24), + _buildSectionTitle( + context, + '${AppStrings.graph} ${AppStrings.monitoring}', + onTap: () => Navigator.push( + context, + MaterialPageRoute(builder: (_) => const GraphMenuPage()), + ), + ), + Padding( + padding: EdgeInsets.symmetric( + horizontal: MediaQuery.of(context).size.width >= 600 ? 32.0 : 16.0, + ), + child: GraphWidget(userId: userId), + ), + SizedBox(height: MediaQuery.of(context).size.width >= 600 ? 140 : 120), + ], + ), + ), + ); + } + + Widget _buildSectionTitle( + BuildContext context, + String title, { + VoidCallback? onTap, + }) { + final screenWidth = MediaQuery.of(context).size.width; + final isTablet = screenWidth >= 600; + final isSmallScreen = screenWidth < 360; + + return Padding( + padding: EdgeInsets.symmetric( + horizontal: isTablet ? 32.0 : (isSmallScreen ? 16.0 : 24.0), + vertical: 8.0, + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + title, + style: TextStyle( + fontSize: isTablet ? 24 : (isSmallScreen ? 18 : 20), + fontWeight: FontWeight.bold, + ), + ), + if (onTap != null) + GestureDetector( + onTap: onTap, + child: Text( + AppStrings.seeAll, + style: TextStyle( + color: AppColors.primaryDark, + fontWeight: FontWeight.w600, + fontSize: isTablet ? 16 : (isSmallScreen ? 12 : 14), + ), + ), + ), + ], + ), + ); + } + + Widget _buildMonitoringCards(String? userId) { + return SizedBox( + height: 330, + child: StreamBuilder?>( + stream: controller.latestDataStream(userId), + builder: (context, snapshot) { + if (snapshot.connectionState == ConnectionState.waiting) { + return const Center(child: CircularProgressIndicator()); + } + + final data = snapshot.data; + final monitoringData = data != null + ? (controller.parseMonitoringData(data).data ?? + MonitoringData( + ph: '-', + nutrisi: '-', + phStatus: 'Menunggu Data', + nutrientStatus: 'Menunggu Data', + pumpPhUp: false, + pumpPhDown: false, + pumpNutrient: false, + pumpWater: false, + isPhAbnormal: false, + isNutrientAbnormal: false, + )) + : MonitoringData( + ph: '-', + nutrisi: '-', + phStatus: 'Menunggu Data', + nutrientStatus: 'Menunggu Data', + pumpPhUp: false, + pumpPhDown: false, + pumpNutrient: false, + pumpWater: false, + isPhAbnormal: false, + isNutrientAbnormal: false, + ); + return ListView( + scrollDirection: Axis.horizontal, + padding: const EdgeInsets.symmetric(horizontal: 16), + children: [ + MonitoringCard( + title: 'PH Level', + value: monitoringData.ph, + unit: '', + status: monitoringData.phStatus, + statusColor: monitoringData.isPhAbnormal ? AppColors.warning : AppColors.primary, + description: 'Jaga pH larutan antara 4.0 - 6.0', + userId: userId, + switch1Value: monitoringData.pumpPhUp, + switch2Value: monitoringData.pumpPhDown, + switch1Label: 'PH Up', + switch2Label: 'PH Down', + onSwitch1Changed: (_) {}, + onSwitch2Changed: (_) {}, + ), + MonitoringCard( + title: 'Nutrient Level', + value: monitoringData.nutrisi, + unit: 'ppm', + status: monitoringData.nutrientStatus, + statusColor: monitoringData.isNutrientAbnormal ? AppColors.warning : AppColors.primary, + description: 'Pastikan TDS/PPM sesuai fase', + userId: userId, + switch1Value: monitoringData.pumpNutrient, + switch2Value: monitoringData.pumpWater, + switch1Label: 'Nutrisi', + switch2Label: 'Air Baku', + onSwitch1Changed: (_) {}, + onSwitch2Changed: (_) {}, + ), + ], + ); + }, + ), + ); + } +} diff --git a/lib/ui/pages/login.dart b/lib/ui/pages/login.dart new file mode 100644 index 0000000..25e221f --- /dev/null +++ b/lib/ui/pages/login.dart @@ -0,0 +1,141 @@ +import 'package:flutter/material.dart'; +import 'package:mobile_monitoring/core/constants/strings.dart'; +import 'package:mobile_monitoring/logic/controllers/controllers.dart'; +import 'package:mobile_monitoring/ui/pages/register.dart'; +import 'package:mobile_monitoring/ui/pages/home.dart'; +import 'package:mobile_monitoring/ui/shared/shared.dart'; + +/// Login Page - Frontend/UI Layer +/// Hanya menangani UI logic dan state management +class LoginPage extends StatefulWidget { + const LoginPage({super.key}); + + @override + State createState() => _LoginPageState(); +} + +class _LoginPageState extends State { + // UI Controllers dan State + final _formKey = GlobalKey(); + final _emailController = TextEditingController(); + final _passwordController = TextEditingController(); + + final _controller = AuthController(); + + @override + void dispose() { + _emailController.dispose(); + _passwordController.dispose(); + _controller.dispose(); + super.dispose(); + } + + /// Handle login - Frontend logic + /// Memanggil backend service dan bereaksi terhadap hasilnya + Future _login() async { + // Validasi form + if (!_formKey.currentState!.validate()) { + ErrorSnackbar.show( + context, + 'Periksa email dan password terlebih dahulu', + type: ErrorType.general, + ); + return; + } + + final result = await _controller.login( + email: _emailController.text, + password: _passwordController.text, + ); + + if (!mounted) return; + + // React terhadap hasil dari backend + if (result.success) { + _navigateToHome(); + } else { + ErrorSnackbar.show(context, result.message, type: ErrorType.general); + } + } + + /// Handle forgot password - Frontend logic + Future _forgotPassword() async { + final email = _emailController.text.trim(); + + // Validasi input + if (email.isEmpty) { + ErrorSnackbar.show( + context, + 'Masukkan email terlebih dahulu', + type: ErrorType.general, + ); + return; + } + + final result = await _controller.forgotPassword(email); + + if (!mounted) return; + + // Tampilkan hasil + if (result.success) { + SuccessSnackbar.show(context, result.message); + return; + } + ErrorSnackbar.show(context, result.message, type: ErrorType.general); + } + + /// Navigate ke home page (UI logic) + void _navigateToHome() { + Navigator.of(context).pushAndRemoveUntil( + MaterialPageRoute(builder: (_) => const HomePage()), + (_) => false, + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + body: AuthBackground( + child: SafeArea( + child: Center( + child: SingleChildScrollView( + padding: const EdgeInsets.all(24.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const BrandingHeader(), + const SizedBox(height: 50), + ListenableBuilder( + listenable: _controller, + builder: (context, _) { + return LoginForm( + formKey: _formKey, + emailController: _emailController, + passwordController: _passwordController, + isLoading: _controller.isLoading, + onLogin: _login, + onForgotPassword: _forgotPassword, + onRegisterTap: () { + Navigator.of(context).push( + MaterialPageRoute( + builder: (context) => const RegisterPage(), + ), + ); + }, + ); + }, + ), + const SizedBox(height: 12), + Text( + AppStrings.appName, + style: Theme.of(context).textTheme.labelMedium, + ), + ], + ), + ), + ), + ), + ), + ); + } +} diff --git a/lib/ui/pages/pages.dart b/lib/ui/pages/pages.dart new file mode 100644 index 0000000..977a948 --- /dev/null +++ b/lib/ui/pages/pages.dart @@ -0,0 +1,8 @@ +// Export semua pages dari UI layer +export 'flow.dart'; +export 'home.dart'; +export 'login.dart'; +export 'profile.dart'; +export 'register.dart'; +export 'settings.dart'; +export 'splash_screen.dart'; diff --git a/lib/ui/pages/profile.dart b/lib/ui/pages/profile.dart new file mode 100644 index 0000000..0f29cf9 --- /dev/null +++ b/lib/ui/pages/profile.dart @@ -0,0 +1,217 @@ +import 'package:flutter/material.dart'; +import 'package:mobile_monitoring/core/constants/constants.dart'; +import 'package:mobile_monitoring/logic/controllers/controllers.dart'; +import 'package:mobile_monitoring/ui/pages/login.dart'; +import 'package:mobile_monitoring/ui/shared/shared.dart'; + +class ProfilePage extends StatefulWidget { + const ProfilePage({super.key}); + + @override + State createState() => _ProfilePageState(); +} + +class _ProfilePageState extends State { + final _controller = ProfileController(); + + @override + void initState() { + super.initState(); + _controller.loadProfile(); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + Future _updateProfile() async { + final result = await _controller.updateProfile(); + + if (!mounted) return; + + if (result.success) { + SuccessSnackbar.show(context, result.message); + } else { + ErrorSnackbar.show(context, result.message, type: ErrorType.general); + } + + _controller.loadProfile(); + } + + Future _showChangePasswordDialog() async { + await showDialog( + context: context, + barrierDismissible: false, + builder: (context) => ChangePasswordDialog( + onChangePassword: (oldPassword, newPassword) async { + final result = await _controller.changePassword( + oldPassword: oldPassword, + newPassword: newPassword, + ); + + if (!result.success) { + throw Exception(result.message); + } + }, + ), + ); + } + + Future _handleLogout() async { + final confirm = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Konfirmasi Logout'), + content: const Text('Apakah Anda yakin ingin keluar?'), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, false), + child: const Text(AppStrings.cancel), + ), + ElevatedButton( + onPressed: () => Navigator.pop(context, true), + style: ElevatedButton.styleFrom( + backgroundColor: AppColors.error, + foregroundColor: AppColors.white, + ), + child: const Text('Keluar'), + ), + ], + ), + ); + + if (confirm == true && mounted) { + final result = await _controller.logout(); + + if (!mounted) return; + + if (result.success) { + Navigator.of(context).pushAndRemoveUntil( + MaterialPageRoute(builder: (context) => const LoginPage()), + (route) => false, + ); + } else { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(result.message), backgroundColor: AppColors.error), + ); + } + } + } + + @override + Widget build(BuildContext context) { + return ListenableBuilder( + listenable: _controller, + builder: (context, _) { + final profile = _controller.profile; + + return Scaffold( + appBar: AppBar( + title: const Text(AppStrings.profile), + backgroundColor: AppColors.primary, + foregroundColor: AppColors.white, + elevation: 0, + ), + body: SingleChildScrollView( + child: Column( + children: [ + // Profile Header dengan Avatar Inisial + Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(vertical: 40), + decoration: const BoxDecoration(color: AppColors.secondary), + child: Column( + children: [ + // Avatar dengan Inisial + Container( + width: 100, + height: 100, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: Colors.white, + border: Border.all(color: Colors.white, width: 4), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.2), + blurRadius: 8, + spreadRadius: 2, + ), + ], + ), + child: Center( + child: Text( + profile?.initials ?? 'U', + style: const TextStyle( + fontSize: 36, + fontWeight: FontWeight.bold, + color: AppColors.secondary, + ), + ), + ), + ), + const SizedBox(height: 16), + Text( + profile?.displayName ?? 'Pengguna', + style: const TextStyle( + fontSize: 24, + fontWeight: FontWeight.bold, + color: Colors.white, + ), + ), + const SizedBox(height: 4), + Text( + profile?.email ?? '', + style: TextStyle( + fontSize: 14, + color: Colors.white.withValues(alpha: 0.9), + ), + ), + ], + ), + ), + + // Form Section + Padding( + padding: const EdgeInsets.all(24.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + // Profile Form Component + ProfileForm( + nameController: _controller.nameController, + isLoading: _controller.isLoading, + userEmail: profile?.email, + onUpdate: _updateProfile, + ), + const SizedBox(height: 24), + + // Account Actions Component + AccountActionsCard( + onChangePassword: _showChangePasswordDialog, + onLogout: _handleLogout, + ), + const SizedBox(height: 16), + + // App Version + Center( + child: Text( + '${AppStrings.appName} v${AppStrings.appVersion}', + style: TextStyle( + color: Colors.grey.shade600, + fontSize: 12, + ), + ), + ), + ], + ), + ), + ], + ), + ), + ); + }, + ); + } +} diff --git a/lib/ui/pages/register.dart b/lib/ui/pages/register.dart new file mode 100644 index 0000000..6aa9552 --- /dev/null +++ b/lib/ui/pages/register.dart @@ -0,0 +1,102 @@ +import 'package:flutter/material.dart'; +import 'package:mobile_monitoring/logic/controllers/controllers.dart'; +import 'package:mobile_monitoring/ui/pages/home.dart'; +import 'package:mobile_monitoring/ui/shared/shared.dart'; + +class RegisterPage extends StatefulWidget { + const RegisterPage({super.key}); + + @override + State createState() => _RegisterPageState(); +} + +class _RegisterPageState extends State { + final _formKey = GlobalKey(); + final _nameController = TextEditingController(); + final _emailController = TextEditingController(); + final _passwordController = TextEditingController(); + final _confirmPasswordController = TextEditingController(); + final _controller = AuthController(); + + @override + void dispose() { + _nameController.dispose(); + _emailController.dispose(); + _passwordController.dispose(); + _confirmPasswordController.dispose(); + _controller.dispose(); + super.dispose(); + } + + /// Handle register - Frontend logic + /// Memanggil backend service dan bereaksi terhadap hasilnya + Future _register() async { + // Validasi form + if (!_formKey.currentState!.validate()) { + return; + } + + final result = await _controller.register( + name: _nameController.text, + email: _emailController.text, + password: _passwordController.text, + confirmPassword: _confirmPasswordController.text, + ); + + if (!mounted) return; + + if (result.success) { + _navigateToHome(); + SuccessSnackbar.show(context, result.message); + } else { + ErrorSnackbar.show(context, result.message, type: ErrorType.general); + } + } + + /// Navigate ke home page (UI logic) + void _navigateToHome() { + Navigator.of(context).pushAndRemoveUntil( + MaterialPageRoute(builder: (_) => const HomePage()), + (_) => false, + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + body: AuthBackground( + child: SafeArea( + child: Center( + child: SingleChildScrollView( + padding: const EdgeInsets.all(24.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const BrandingHeader(), + const SizedBox(height: 40), + ListenableBuilder( + listenable: _controller, + builder: (context, _) { + return RegisterForm( + formKey: _formKey, + nameController: _nameController, + emailController: _emailController, + passwordController: _passwordController, + confirmPasswordController: _confirmPasswordController, + isLoading: _controller.isLoading, + onRegister: _register, + onLoginTap: () { + Navigator.of(context).pop(); + }, + ); + }, + ), + ], + ), + ), + ), + ), + ), + ); + } +} diff --git a/lib/ui/pages/settings.dart b/lib/ui/pages/settings.dart new file mode 100644 index 0000000..c900bdb --- /dev/null +++ b/lib/ui/pages/settings.dart @@ -0,0 +1,66 @@ +import 'package:flutter/material.dart'; +import 'package:mobile_monitoring/core/constants/constants.dart'; +import 'package:mobile_monitoring/logic/controllers/controllers.dart'; +import 'package:mobile_monitoring/ui/shared/shared.dart'; + +/// Graph Menu Page (Settings) - Frontend/UI Layer +/// Hanya menangani UI logic dan rendering +class GraphMenuPage extends StatefulWidget { + const GraphMenuPage({super.key}); + + @override + State createState() => _GraphMenuPageState(); +} + +class _GraphMenuPageState extends State { + final _controller = GraphController(); + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final userId = _controller.currentUserId; + final screenWidth = MediaQuery.of(context).size.width; + final isTablet = screenWidth >= 600; + final isSmallScreen = screenWidth < 360; + + return Scaffold( + appBar: AppBar( + title: Text( + AppStrings.monitoringGrafik, + style: TextStyle( + fontSize: isTablet ? 22 : (isSmallScreen ? 16 : 18), + ), + ), + backgroundColor: AppColors.primary, + elevation: 0, + centerTitle: true, + foregroundColor: AppColors.white, + ), + backgroundColor: AppColors.white, + body: Center( + child: SingleChildScrollView( + child: Padding( + padding: EdgeInsets.symmetric( + horizontal: isTablet ? 24.0 : (isSmallScreen ? 12.0 : 16.0), + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + SizedBox(height: isTablet ? 32 : 24), + GraphWidget(userId: userId), + SizedBox(height: isTablet ? 40 : 32), + WeeklyStatsCard(userId: userId), + SizedBox(height: isTablet ? 40 : 32), + ], + ), + ), + ), + ), + ); + } +} diff --git a/lib/ui/pages/splash_screen.dart b/lib/ui/pages/splash_screen.dart new file mode 100644 index 0000000..734c2b8 --- /dev/null +++ b/lib/ui/pages/splash_screen.dart @@ -0,0 +1,143 @@ +import 'package:flutter/material.dart'; +import 'package:mobile_monitoring/core/constants/constants.dart'; + +class SplashScreen extends StatefulWidget { + const SplashScreen({ + super.key, + this.duration = const Duration(seconds: 5), + this.nextRouteName, + this.nextPage, + this.brandTitle = AppStrings.appName, + this.brandSubtitle = AppStrings.appTagline, + this.backgroundGradient, + this.showProgress = false, + }); + + final Duration duration; + final String? nextRouteName; + final Widget? nextPage; + final String brandTitle; + final String brandSubtitle; + final Gradient? backgroundGradient; + final bool showProgress; + + @override + State createState() => _SplashScreenState(); +} + +class _SplashScreenState extends State { + @override + void initState() { + super.initState(); + _goNext(); + } + + Future _goNext() async { + await Future.delayed(widget.duration); + if (!mounted) return; + + if (widget.nextPage != null) { + Navigator.of( + context, + ).pushReplacement(MaterialPageRoute(builder: (_) => widget.nextPage!)); + } else if (widget.nextRouteName != null) { + Navigator.of(context).pushReplacementNamed(widget.nextRouteName!); + } + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final background = Stack( + fit: StackFit.expand, + children: [ + Image.asset('assets/images/bg-splashscreen.png', fit: BoxFit.cover), + Container(color: Colors.black.withValues(alpha: 0.35)), + ], + ); + + return Scaffold( + body: Stack( + fit: StackFit.expand, + children: [ + background, + SafeArea( + child: Column( + children: [ + const Spacer(), + Column( + mainAxisSize: MainAxisSize.min, + children: [ + Stack( + children: [ + Text( + AppStrings.appName, + textAlign: TextAlign.center, + style: theme.textTheme.displayMedium?.copyWith( + foreground: Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 2.5 + ..color = Colors.black, + fontWeight: FontWeight.bold, + letterSpacing: 0.5, + ), + ), + Text( + AppStrings.appName, + textAlign: TextAlign.center, + style: theme.textTheme.displayMedium?.copyWith( + color: Colors.white, + fontWeight: FontWeight.bold, + letterSpacing: 0.5, + ), + ), + ], + ), + const SizedBox(height: 16), + Stack( + children: [ + Text( + AppStrings.appTagline, + textAlign: TextAlign.center, + style: theme.textTheme.titleLarge?.copyWith( + foreground: Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 0.5 + ..color = Colors.black, + fontWeight: FontWeight.w400, + letterSpacing: 1.2, + ), + ), + Text( + AppStrings.appTagline, + textAlign: TextAlign.center, + style: theme.textTheme.titleLarge?.copyWith( + color: Colors.white.withValues(alpha: 0.95), + fontWeight: FontWeight.w400, + letterSpacing: 1.2, + ), + ), + ], + ), + ], + ), + const Spacer(), + Padding( + padding: const EdgeInsets.only(bottom: 24.0), + child: Text( + 'Inovasi Mahasiswa Polije.', + textAlign: TextAlign.center, + style: theme.textTheme.bodyMedium?.copyWith( + color: Colors.white.withValues(alpha: 0.7), + fontSize: 16, + ), + ), + ), + ], + ), + ), + ], + ), + ); + } +} diff --git a/lib/ui/shared/account_actions_card.dart b/lib/ui/shared/account_actions_card.dart new file mode 100644 index 0000000..3ec8263 --- /dev/null +++ b/lib/ui/shared/account_actions_card.dart @@ -0,0 +1,47 @@ +import 'package:flutter/material.dart'; +import 'package:mobile_monitoring/core/constants/constants.dart'; +import 'package:mobile_monitoring/ui/shared/components/components.dart'; + +class AccountActionsCard extends StatelessWidget { + final VoidCallback onChangePassword; + final VoidCallback onLogout; + + const AccountActionsCard({ + super.key, + required this.onChangePassword, + required this.onLogout, + }); + + @override + Widget build(BuildContext context) { + return CustomCard( + elevation: 2, + borderRadius: 12, + padding: EdgeInsets.zero, + child: Column( + children: [ + const SectionHeader( + title: 'Aksi Akun', + showDivider: true, + ), + ListTile( + leading: const Icon(Icons.lock_outline, color: AppColors.primaryDark), + title: const Text('Ubah Password'), + trailing: const Icon(Icons.chevron_right), + onTap: onChangePassword, + ), + const Divider(height: 1), + ListTile( + leading: const Icon(Icons.logout, color: AppColors.error), + title: const Text( + 'Keluar', + style: TextStyle(color: AppColors.error), + ), + trailing: const Icon(Icons.chevron_right), + onTap: onLogout, + ), + ], + ), + ); + } +} diff --git a/lib/ui/shared/auth_background.dart b/lib/ui/shared/auth_background.dart new file mode 100644 index 0000000..9fce969 --- /dev/null +++ b/lib/ui/shared/auth_background.dart @@ -0,0 +1,27 @@ +import 'package:flutter/material.dart'; + +class AuthBackground extends StatelessWidget { + final Widget child; + final double overlayOpacity; + + const AuthBackground({ + super.key, + required this.child, + this.overlayOpacity = 0.35, + }); + + @override + Widget build(BuildContext context) { + return Stack( + fit: StackFit.expand, + children: [ + // Background image + Image.asset('assets/images/bg-splashscreen.png', fit: BoxFit.cover), + // Dark overlay + Container(color: Colors.black.withValues(alpha: overlayOpacity)), + // Content + child, + ], + ); + } +} diff --git a/lib/ui/shared/bottom_navbar.dart b/lib/ui/shared/bottom_navbar.dart new file mode 100644 index 0000000..d2fc99c --- /dev/null +++ b/lib/ui/shared/bottom_navbar.dart @@ -0,0 +1,147 @@ +import 'package:flutter/material.dart'; +import 'package:mobile_monitoring/core/constants/constants.dart'; + +class BottomNavbar extends StatelessWidget { + final int currentIndex; + final ValueChanged onTap; + + const BottomNavbar({ + super.key, + required this.currentIndex, + required this.onTap, + }); + + // Warna hijau yang dicocokkan dengan desain + final Color activeGreen = AppColors.navbarActive; + + Widget _buildNavItem(IconData icon, String label, int index) { + final isSelected = currentIndex == index; + return GestureDetector( + onTap: () => onTap(index), + behavior: HitTestBehavior.translucent, + child: SizedBox( + width: 70, // Memberikan area tap yang cukup + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + icon, + color: isSelected ? activeGreen : Colors.grey.shade400, + size: 28, + ), + const SizedBox(height: 4), + Text( + label, + style: TextStyle( + color: isSelected ? activeGreen : Colors.grey.shade500, + fontSize: 12, + fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal, + ), + ), + ], + ), + ), + ); + } + + Widget _buildHomeNavItem(int index) { + return GestureDetector( + onTap: () => onTap(index), + child: Container( + width: 60, + height: 60, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: activeGreen, // Warna hijau solid sesuai gambar + // Shadow dihapus/diminimalisir karena di desain aslinya terlihat flat + ), + child: const Icon( + Icons.home_rounded, + color: Colors.white, + size: 34, + ), + ), + ); + } + + @override + Widget build(BuildContext context) { + // Tinggi total navbar diperbesar sedikit untuk mengakomodasi notch & tombol melayang + return SizedBox( + height: 100, + child: Stack( + clipBehavior: Clip.none, + children: [ + // Background dengan notch melengkung yang di-generate otomatis + Positioned.fill( + child: CustomPaint( + painter: _NavbarNotchPainter(), + ), + ), + + // Menu Kiri dan Kanan + Positioned( + bottom: 0, + left: 0, + right: 0, + height: 65, // Tinggi area bar putihnya saja + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + // Menggunakan icon bar_chart agar mirip dengan desain 3 tiang grafik + _buildNavItem(Icons.bar_chart_rounded, AppStrings.monitoring, 0), + const SizedBox(width: 80), // Ruang kosong untuk notch di tengah + _buildNavItem(Icons.show_chart_rounded, AppStrings.graph, 2), + ], + ), + ), + + // Home Button di tengah + Positioned( + top: 5, // Mengatur posisi tombol melayang pas di atas lengkungan + left: 0, + right: 0, + child: Center( + child: _buildHomeNavItem(1), + ), + ), + ], + ), + ); + } +} + +class _NavbarNotchPainter extends CustomPainter { + @override + void paint(Canvas canvas, Size size) { + // Menggunakan bawaan Flutter agar lekukan otomatis presisi dan tidak ada glitch visual/abu-abu + const notchShape = CircularNotchedRectangle(); + + // Titik awal y untuk background putih (y = 35) + // Area dari y=0 hingga y=35 akan murni transparan menembus background aplikasi + final backgroundRect = Rect.fromLTWH(0, 35, size.width, size.height - 35); + + // Ukuran dan posisi lubang (notch) + final notchRect = Rect.fromCenter( + center: Offset(size.width / 2, 35), + width: 80, // Dibuat sedikit lebih besar dari tombol (60) agar ada spasi putihnya + height: 80, + ); + + // Dapatkan jalur (path) yang sudah dihitung otomatis + final path = notchShape.getOuterPath(backgroundRect, notchRect); + + // Gambar bayangan (shadow) yang halus, tidak menghasilkan blok abu-abu gelap + canvas.drawShadow(path, Colors.black.withValues(alpha: 0.1), 8.0, false); + + // Gambar background navbar putih + final paint = Paint() + ..color = Colors.white + ..style = PaintingStyle.fill; + + canvas.drawPath(path, paint); + } + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +} \ No newline at end of file diff --git a/lib/ui/shared/branding_header.dart b/lib/ui/shared/branding_header.dart new file mode 100644 index 0000000..40dba69 --- /dev/null +++ b/lib/ui/shared/branding_header.dart @@ -0,0 +1,40 @@ +import 'package:flutter/material.dart'; + +class BrandingHeader extends StatelessWidget { + final String title; + final String subtitle; + + const BrandingHeader({ + super.key, + this.title = 'HidroNutrify', + this.subtitle = 'Hydro Made Easy.', + }); + + @override + Widget build(BuildContext context) { + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + title, + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.displayMedium?.copyWith( + color: Colors.white, + fontWeight: FontWeight.bold, + shadows: [Shadow(color: Colors.black, blurRadius: 3)], + ), + ), + const SizedBox(height: 16), + Text( + subtitle, + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.titleLarge?.copyWith( + color: Colors.white, + letterSpacing: 1.2, + shadows: [Shadow(color: Colors.black26, blurRadius: 2)], + ), + ), + ], + ); + } +} diff --git a/lib/ui/shared/change_password_dialog.dart b/lib/ui/shared/change_password_dialog.dart new file mode 100644 index 0000000..020d7f0 --- /dev/null +++ b/lib/ui/shared/change_password_dialog.dart @@ -0,0 +1,176 @@ +import 'package:flutter/material.dart'; +import 'package:mobile_monitoring/core/constants/constants.dart'; + +class ChangePasswordDialog extends StatefulWidget { + final Function(String oldPassword, String newPassword) onChangePassword; + + const ChangePasswordDialog({super.key, required this.onChangePassword}); + + @override + State createState() => _ChangePasswordDialogState(); +} + +class _ChangePasswordDialogState extends State { + final _formKey = GlobalKey(); + final _oldPasswordController = TextEditingController(); + final _newPasswordController = TextEditingController(); + final _confirmPasswordController = TextEditingController(); + + bool _obscureOld = true; + bool _obscureNew = true; + bool _obscureConfirm = true; + bool _isLoading = false; + + @override + void dispose() { + _oldPasswordController.dispose(); + _newPasswordController.dispose(); + _confirmPasswordController.dispose(); + super.dispose(); + } + + Future _handleSubmit() async { + if (!_formKey.currentState!.validate()) return; + + setState(() => _isLoading = true); + + try { + await widget.onChangePassword(_oldPasswordController.text, _newPasswordController.text); + + if (mounted) { + Navigator.pop(context, true); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Password berhasil diubah'), backgroundColor: AppColors.success), + ); + } + } catch (e) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Gagal: $e'), backgroundColor: AppColors.error), + ); + } + } finally { + if (mounted) setState(() => _isLoading = false); + } + } + + Widget _buildPasswordField({ + required TextEditingController controller, + required bool obscure, + required VoidCallback onToggle, + required String label, + required String hint, + String? Function(String?)? validator, + }) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(label, style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500)), + const SizedBox(height: 8), + TextFormField( + controller: controller, + obscureText: obscure, + decoration: InputDecoration( + prefixIcon: const Icon(Icons.lock, color: AppColors.textSecondary), + suffixIcon: IconButton( + icon: Icon(obscure ? Icons.visibility_off : Icons.visibility, color: AppColors.textSecondary), + onPressed: onToggle, + ), + hintText: hint, + border: OutlineInputBorder(borderRadius: BorderRadius.circular(30)), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(30), + borderSide: const BorderSide(color: AppColors.black), + ), + contentPadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16), + ), + validator: validator, + ), + const SizedBox(height: 16), + ], + ); + } + + @override + Widget build(BuildContext context) { + return Dialog( + backgroundColor: AppColors.white, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), + child: Container( + constraints: const BoxConstraints(maxWidth: 400), + padding: const EdgeInsets.all(24), + child: SingleChildScrollView( + padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom), + child: Stack( + children: [ + Form( + key: _formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const Text('Ubah Password', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)), + const SizedBox(height: 24), + _buildPasswordField( + controller: _oldPasswordController, + obscure: _obscureOld, + onToggle: () => setState(() => _obscureOld = !_obscureOld), + label: 'Password lama', + hint: '************', + validator: (v) => v?.isEmpty ?? true ? 'Masukkan password lama' : null, + ), + _buildPasswordField( + controller: _newPasswordController, + obscure: _obscureNew, + onToggle: () => setState(() => _obscureNew = !_obscureNew), + label: 'Password baru', + hint: '************', + validator: (v) { + if (v?.isEmpty ?? true) return 'Masukkan password baru'; + if (v!.length < 6) return 'Password minimal 6 karakter'; + return null; + }, + ), + _buildPasswordField( + controller: _confirmPasswordController, + obscure: _obscureConfirm, + onToggle: () => setState(() => _obscureConfirm = !_obscureConfirm), + label: 'Konfirmasi password baru', + hint: '************', + validator: (v) { + if (v?.isEmpty ?? true) return 'Konfirmasi password tidak boleh kosong'; + if (v != _newPasswordController.text) return 'Password tidak cocok'; + return null; + }, + ), + const SizedBox(height: 8), + ElevatedButton( + onPressed: _isLoading ? null : _handleSubmit, + style: ElevatedButton.styleFrom( + backgroundColor: AppColors.secondary, + foregroundColor: AppColors.white, + padding: const EdgeInsets.symmetric(vertical: 16), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(30)), + minimumSize: const Size.fromHeight(48), + ), + child: _isLoading + ? const SizedBox(height: 20, width: 20, child: CircularProgressIndicator(strokeWidth: 2, color: AppColors.white)) + : const Text('Ubah Password', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), + ), + ], + ), + ), + Positioned( + top: 0, + right: 0, + child: IconButton( + onPressed: _isLoading ? null : () => Navigator.pop(context, false), + icon: const Icon(Icons.close, color: AppColors.textSecondary), + ), + ), + ], + ), + ), + ), + ); + } +} diff --git a/lib/ui/shared/components/README.md b/lib/ui/shared/components/README.md new file mode 100644 index 0000000..b7bbe46 --- /dev/null +++ b/lib/ui/shared/components/README.md @@ -0,0 +1,404 @@ +# UI Components Library + +Koleksi komponen UI yang reusable untuk aplikasi HydroNutrify. + +## 📁 Struktur + +``` +ui/shared/components/ +├── custom_button.dart # Button components +├── custom_textfield.dart # Text input components +├── custom_card.dart # Card & container components +├── custom_dialog.dart # Dialog & bottom sheet +├── custom_switch.dart # Switch, checkbox, radio +├── custom_appbar.dart # AppBar components +├── loading_indicator.dart # Loading states +├── empty_state.dart # Empty states +├── error_widget.dart # Error handling +├── status_badge.dart # Status & notification badges +├── section_header.dart # Section headers & dividers +└── components.dart # Barrel export file +``` + +## 🎨 Komponen + +### 1. **CustomButton** +Button dengan berbagai jenis dan ukuran. + +```dart +// Primary Button +CustomButton( + text: 'Login', + onPressed: () {}, + isLoading: false, + type: ButtonType.primary, + size: ButtonSize.medium, +) + +// Secondary Button with Icon +CustomButton( + text: 'Save', + icon: Icons.save, + type: ButtonType.secondary, + onPressed: () {}, +) + +// Danger Button +CustomButton( + text: 'Delete', + type: ButtonType.danger, + onPressed: () {}, +) +``` + +**ButtonType**: `primary`, `secondary`, `text`, `danger` +**ButtonSize**: `small`, `medium`, `large` + +--- + +### 2. **CustomTextField** +Text input field dengan fitur lengkap. + +```dart +CustomTextField( + controller: emailController, + labelText: 'Email', + hintText: 'Enter your email', + prefixIcon: Icons.email, + keyboardType: TextInputType.emailAddress, + validator: (value) => value?.isEmpty == true ? 'Required' : null, +) + +// Password Field dengan toggle +CustomTextField( + controller: passwordController, + labelText: 'Password', + obscureText: true, + showPasswordToggle: true, + prefixIcon: Icons.lock, +) +``` + +--- + +### 3. **CustomCard** +Card container yang fleksibel. + +```dart +// Basic Card +CustomCard( + child: Text('Content'), + padding: EdgeInsets.all(16), + elevation: 2, +) + +// Stat Card +StatCard( + title: 'Total Users', + value: '1,234', + subtitle: '+12% from last month', + icon: Icons.people, + iconColor: AppColors.primary, +) + +// Info Card +InfoCard( + title: 'Update Available', + description: 'Version 2.0 is ready to install', + icon: Icons.system_update, +) +``` + +--- + +### 4. **LoadingIndicator** +Loading states dengan berbagai variasi. + +```dart +// Simple Loading +LoadingIndicator( + size: 40, + message: 'Loading...', +) + +// Overlay Loading +OverlayLoading( + message: 'Processing...', +) + +// Shimmer Loading +ShimmerLoading( + width: 200, + height: 20, + borderRadius: BorderRadius.circular(8), +) + +// Linear Progress +CustomLinearProgress( + value: 0.6, + height: 4, +) +``` + +--- + +### 5. **EmptyState** +Widget untuk menampilkan empty state. + +```dart +// Custom Empty State +EmptyState( + title: 'No Data Found', + message: 'Try adding some items first', + icon: Icons.inbox_outlined, + actionText: 'Add Item', + onAction: () {}, +) + +// No Data Widget +NoDataWidget( + message: 'No records available', +) + +// No Connection Widget +NoConnectionWidget( + onRetry: () {}, +) +``` + +--- + +### 6. **CustomErrorWidget** +Error handling dan display. + +```dart +// Error Widget +CustomErrorWidget( + title: 'Something went wrong', + message: 'Please try again later', + type: ErrorType.general, + actionText: 'Retry', + onAction: () {}, +) + +// Error Snackbar +ErrorSnackbar.show( + context, + 'Failed to load data', + type: ErrorType.network, +) + +// Success Snackbar +SuccessSnackbar.show( + context, + 'Data saved successfully', +) +``` + +**ErrorType**: `general`, `network`, `notFound`, `permission`, `timeout` + +--- + +### 7. **CustomDialog** +Dialog dan bottom sheet. + +```dart +// Confirmation Dialog +final result = await CustomDialog.showConfirmation( + context: context, + title: 'Delete Item', + message: 'Are you sure?', + confirmText: 'Delete', + isDangerous: true, +); + +// Info Dialog +await CustomDialog.showInfo( + context: context, + title: 'Information', + message: 'Operation completed successfully', +); + +// Loading Dialog +CustomDialog.showLoading(context, message: 'Saving...'); +Navigator.pop(context); // Close when done + +// Bottom Sheet +await CustomBottomSheet.show( + context: context, + title: 'Select Option', + child: YourWidget(), + height: 300, +); +``` + +--- + +### 8. **Form Controls** +Switch, checkbox, dan radio buttons. + +```dart +// Custom Switch +CustomSwitch( + value: isEnabled, + onChanged: (value) {}, +) + +// Labeled Switch +LabeledSwitch( + label: 'Enable Notifications', + description: 'Receive updates and alerts', + value: isEnabled, + icon: Icons.notifications, + onChanged: (value) {}, +) + +// Labeled Checkbox +LabeledCheckbox( + label: 'I agree to terms', + value: isAgreed, + onChanged: (value) {}, +) + +// Labeled Radio +LabeledRadio( + label: 'Option 1', + value: 'option1', + initialGroupValue: selectedOption, + onChanged: (value) {}, +) +``` + +--- + +### 9. **StatusBadge** +Status dan notification badges. + +```dart +// Success Badge +StatusBadge.success('Active') + +// Warning Badge +StatusBadge.warning('Pending') + +// Error Badge +StatusBadge.error('Failed') + +// Info Badge +StatusBadge.info('New') + +// Notification Badge +NotificationBadge(count: 5) + +// Dot Badge +DotBadge(color: AppColors.error) +``` + +**BadgeSize**: `small`, `medium`, `large` + +--- + +### 10. **SectionHeader** +Headers untuk section. + +```dart +// Section Header +SectionHeader( + title: 'Recent Activity', + subtitle: 'Last 7 days', + trailingText: 'See All', + onTrailingTap: () {}, + showDivider: true, +) + +// Simple Section Header +SimpleSectionHeader( + title: 'Personal Information', +) + +// Icon Section Header +IconSectionHeader( + title: 'Settings', + icon: Icons.settings, + onTap: () {}, +) + +// Divider with Text +DividerWithText(text: 'OR') +``` + +--- + +### 11. **CustomAppBar** +AppBar components. + +```dart +// Custom AppBar +CustomAppBar( + title: 'Home', + actions: [ + IconButton( + icon: Icon(Icons.search), + onPressed: () {}, + ), + ], +) + +// Custom Tab Bar +CustomTabBar( + tabs: [ + Tab(text: 'Tab 1'), + Tab(text: 'Tab 2'), + ], +) + +// Sliver AppBar +CustomSliverAppBar( + title: 'Profile', + expandedHeight: 200, + flexibleSpace: YourWidget(), +) +``` + +--- + +## 📦 Cara Penggunaan + +Import dari barrel file untuk menggunakan semua komponen: + +```dart +import 'package:mobile_monitoring/ui/shared/components/components.dart'; +``` + +Atau import spesifik: + +```dart +import 'package:mobile_monitoring/ui/shared/components/custom_button.dart'; +import 'package:mobile_monitoring/ui/shared/components/custom_textfield.dart'; +``` + +--- + +## 🎯 Keuntungan + +✅ **Konsisten** - Semua komponen menggunakan theme dan colors yang sama +✅ **Reusable** - Mudah digunakan di seluruh aplikasi +✅ **Maintainable** - Update sekali, berpengaruh di semua tempat +✅ **Customizable** - Banyak parameter untuk customisasi +✅ **Type-safe** - Menggunakan enums untuk parameter + +--- + +## 🔧 Refactoring yang Sudah Dilakukan + +1. ✅ **login_form.dart** - Menggunakan CustomTextField, CustomButton, CustomCard +2. ✅ **register_form.dart** - Menggunakan CustomTextField, CustomButton, CustomCard + +--- + +## 📝 Todo + +- [ ] Refactor file-file lain untuk menggunakan komponen baru +- [ ] Tambah animasi pada komponen +- [ ] Tambah dark mode support +- [ ] Tambah accessibility features diff --git a/lib/ui/shared/components/components.dart b/lib/ui/shared/components/components.dart new file mode 100644 index 0000000..6aec354 --- /dev/null +++ b/lib/ui/shared/components/components.dart @@ -0,0 +1,33 @@ +// Export all basic UI components +// Import dari satu file ini untuk kemudahan penggunaan + +// Buttons +export 'custom_button.dart'; + +// Text Fields +export 'custom_textfield.dart'; + +// Cards +export 'custom_card.dart'; + +// Loading +export 'loading_indicator.dart'; + +// Empty & Error States +export 'empty_state.dart'; +export 'error_widget.dart'; + +// Dialogs & Bottom Sheets +export 'custom_dialog.dart'; + +// Form Controls +export 'custom_switch.dart'; + +// Badges +export 'status_badge.dart'; + +// Headers & Dividers +export 'section_header.dart'; + +// AppBars +export 'custom_appbar.dart'; diff --git a/lib/ui/shared/components/custom_appbar.dart b/lib/ui/shared/components/custom_appbar.dart new file mode 100644 index 0000000..133e76f --- /dev/null +++ b/lib/ui/shared/components/custom_appbar.dart @@ -0,0 +1,111 @@ +import 'package:flutter/material.dart'; +import 'package:mobile_monitoring/core/constants/colors.dart'; + +/// Custom AppBar - AppBar yang reusable +class CustomAppBar extends StatelessWidget implements PreferredSizeWidget { + final String title; + final List? actions; + final Widget? leading; + final bool centerTitle; + final Color? backgroundColor; + final Color? foregroundColor; + final double? elevation; + final PreferredSizeWidget? bottom; + + const CustomAppBar({ + super.key, + required this.title, + this.actions, + this.leading, + this.centerTitle = true, + this.backgroundColor, + this.foregroundColor, + this.elevation, + this.bottom, + }); + + @override + Widget build(BuildContext context) { + return AppBar( + title: Text(title), + actions: actions, + leading: leading, + centerTitle: centerTitle, + backgroundColor: backgroundColor ?? AppColors.primary, + foregroundColor: foregroundColor ?? AppColors.white, + elevation: elevation ?? 0, + bottom: bottom, + ); + } + + @override + Size get preferredSize => Size.fromHeight( + kToolbarHeight + (bottom?.preferredSize.height ?? 0), + ); +} + +/// Custom Tab Bar - Tab bar yang reusable +class CustomTabBar extends StatelessWidget implements PreferredSizeWidget { + final List tabs; + final Color? indicatorColor; + final Color? labelColor; + final Color? unselectedLabelColor; + + const CustomTabBar({ + super.key, + required this.tabs, + this.indicatorColor, + this.labelColor, + this.unselectedLabelColor, + }); + + @override + Widget build(BuildContext context) { + return TabBar( + tabs: tabs, + indicatorColor: indicatorColor ?? AppColors.white, + labelColor: labelColor ?? AppColors.white, + unselectedLabelColor: unselectedLabelColor ?? AppColors.white.withValues(alpha: 0.7), + ); + } + + @override + Size get preferredSize => const Size.fromHeight(kToolbarHeight); +} + +/// Sliver AppBar Custom - Sliver AppBar yang reusable +class CustomSliverAppBar extends StatelessWidget { + final String title; + final List? actions; + final Widget? flexibleSpace; + final double expandedHeight; + final bool floating; + final bool pinned; + final bool snap; + + const CustomSliverAppBar({ + super.key, + required this.title, + this.actions, + this.flexibleSpace, + this.expandedHeight = 200, + this.floating = false, + this.pinned = true, + this.snap = false, + }); + + @override + Widget build(BuildContext context) { + return SliverAppBar( + title: Text(title), + actions: actions, + flexibleSpace: flexibleSpace, + expandedHeight: expandedHeight, + floating: floating, + pinned: pinned, + snap: snap, + backgroundColor: AppColors.primary, + foregroundColor: AppColors.white, + ); + } +} diff --git a/lib/ui/shared/components/custom_button.dart b/lib/ui/shared/components/custom_button.dart new file mode 100644 index 0000000..f1e12bb --- /dev/null +++ b/lib/ui/shared/components/custom_button.dart @@ -0,0 +1,189 @@ +import 'package:flutter/material.dart'; +import 'package:mobile_monitoring/core/constants/colors.dart'; +import 'package:mobile_monitoring/core/constants/app_settings.dart'; + +/// Custom Button - Berbagai jenis button yang reusable +class CustomButton extends StatelessWidget { + final String text; + final VoidCallback? onPressed; + final bool isLoading; + final ButtonType type; + final ButtonSize size; + final IconData? icon; + final Color? backgroundColor; + final Color? textColor; + final double? width; + final double? height; + + const CustomButton({ + super.key, + required this.text, + this.onPressed, + this.isLoading = false, + this.type = ButtonType.primary, + this.size = ButtonSize.medium, + this.icon, + this.backgroundColor, + this.textColor, + this.width, + this.height, + }); + + @override + Widget build(BuildContext context) { + final isDisabled = onPressed == null || isLoading; + + return SizedBox( + width: width, + height: height ?? _getHeight(), + child: _buildButton(context, isDisabled), + ); + } + + Widget _buildButton(BuildContext context, bool isDisabled) { + switch (type) { + case ButtonType.primary: + return ElevatedButton( + onPressed: isDisabled ? null : onPressed, + style: ElevatedButton.styleFrom( + backgroundColor: backgroundColor ?? AppColors.primary, + foregroundColor: textColor ?? AppColors.white, + padding: _getPadding(), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(AppSettings.defaultBorderRadius), + ), + elevation: 2, + ), + child: _buildContent(), + ); + case ButtonType.secondary: + return OutlinedButton( + onPressed: isDisabled ? null : onPressed, + style: OutlinedButton.styleFrom( + foregroundColor: backgroundColor ?? AppColors.primary, + side: BorderSide( + color: backgroundColor ?? AppColors.primary, + width: 1.5, + ), + padding: _getPadding(), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(AppSettings.defaultBorderRadius), + ), + ), + child: _buildContent(), + ); + case ButtonType.text: + return TextButton( + onPressed: isDisabled ? null : onPressed, + style: TextButton.styleFrom( + foregroundColor: backgroundColor ?? AppColors.primary, + padding: _getPadding(), + ), + child: _buildContent(), + ); + case ButtonType.danger: + return ElevatedButton( + onPressed: isDisabled ? null : onPressed, + style: ElevatedButton.styleFrom( + backgroundColor: AppColors.error, + foregroundColor: AppColors.white, + padding: _getPadding(), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(AppSettings.defaultBorderRadius), + ), + elevation: 2, + ), + child: _buildContent(), + ); + } + } + + Widget _buildContent() { + if (isLoading) { + return SizedBox( + height: _getIndicatorSize(), + width: _getIndicatorSize(), + child: CircularProgressIndicator( + strokeWidth: 2, + valueColor: AlwaysStoppedAnimation( + type == ButtonType.primary || type == ButtonType.danger + ? AppColors.white + : AppColors.primary, + ), + ), + ); + } + + if (icon != null) { + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, size: _getIconSize()), + const SizedBox(width: 8), + Text(text, style: TextStyle(fontSize: _getFontSize())), + ], + ); + } + + return Text(text, style: TextStyle(fontSize: _getFontSize())); + } + + double _getHeight() { + switch (size) { + case ButtonSize.small: + return 36; + case ButtonSize.medium: + return 48; + case ButtonSize.large: + return 56; + } + } + + EdgeInsets _getPadding() { + switch (size) { + case ButtonSize.small: + return const EdgeInsets.symmetric(horizontal: 16, vertical: 8); + case ButtonSize.medium: + return const EdgeInsets.symmetric(horizontal: 24, vertical: 12); + case ButtonSize.large: + return const EdgeInsets.symmetric(horizontal: 32, vertical: 16); + } + } + + double _getFontSize() { + switch (size) { + case ButtonSize.small: + return 14; + case ButtonSize.medium: + return 16; + case ButtonSize.large: + return 18; + } + } + + double _getIconSize() { + switch (size) { + case ButtonSize.small: + return 18; + case ButtonSize.medium: + return 20; + case ButtonSize.large: + return 24; + } + } + + double _getIndicatorSize() { + switch (size) { + case ButtonSize.small: + return 16; + case ButtonSize.medium: + return 20; + case ButtonSize.large: + return 24; + } + } +} + +enum ButtonType { primary, secondary, text, danger } + +enum ButtonSize { small, medium, large } diff --git a/lib/ui/shared/components/custom_card.dart b/lib/ui/shared/components/custom_card.dart new file mode 100644 index 0000000..9fb11ac --- /dev/null +++ b/lib/ui/shared/components/custom_card.dart @@ -0,0 +1,210 @@ +import 'package:flutter/material.dart'; +import 'package:mobile_monitoring/core/constants/colors.dart'; +import 'package:mobile_monitoring/core/constants/app_settings.dart'; + +/// Custom Card - Card container yang reusable +class CustomCard extends StatelessWidget { + final Widget child; + final EdgeInsetsGeometry? padding; + final EdgeInsetsGeometry? margin; + final Color? backgroundColor; + final double? elevation; + final double? borderRadius; + final Border? border; + final VoidCallback? onTap; + final List? boxShadow; + + const CustomCard({ + super.key, + required this.child, + this.padding, + this.margin, + this.backgroundColor, + this.elevation, + this.borderRadius, + this.border, + this.onTap, + this.boxShadow, + }); + + @override + Widget build(BuildContext context) { + final cardContent = Container( + padding: padding ?? const EdgeInsets.all(16), + decoration: BoxDecoration( + color: backgroundColor ?? AppColors.white, + borderRadius: BorderRadius.circular( + borderRadius ?? AppSettings.defaultBorderRadius, + ), + border: border, + boxShadow: boxShadow ?? [ + if (elevation != null && elevation! > 0) + BoxShadow( + color: AppColors.shadow, + blurRadius: elevation! * 2, + spreadRadius: elevation! / 2, + offset: Offset(0, elevation! / 2), + ), + ], + ), + child: child, + ); + + if (onTap != null) { + return Padding( + padding: margin ?? const EdgeInsets.all(8), + child: Material( + color: Colors.transparent, + child: InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular( + borderRadius ?? AppSettings.defaultBorderRadius, + ), + child: cardContent, + ), + ), + ); + } + + return Padding( + padding: margin ?? const EdgeInsets.all(8), + child: cardContent, + ); + } +} + +/// Stat Card - Card untuk menampilkan statistik +class StatCard extends StatelessWidget { + final String title; + final String value; + final String? subtitle; + final IconData? icon; + final Color? iconColor; + final Color? backgroundColor; + final VoidCallback? onTap; + + const StatCard({ + super.key, + required this.title, + required this.value, + this.subtitle, + this.icon, + this.iconColor, + this.backgroundColor, + this.onTap, + }); + + @override + Widget build(BuildContext context) { + return CustomCard( + onTap: onTap, + backgroundColor: backgroundColor, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (icon != null) + Icon( + icon, + color: iconColor ?? AppColors.primary, + size: 32, + ), + const SizedBox(height: 8), + Text( + title, + style: const TextStyle( + fontSize: 14, + color: AppColors.textSecondary, + ), + ), + const SizedBox(height: 4), + Text( + value, + style: const TextStyle( + fontSize: 24, + fontWeight: FontWeight.bold, + color: AppColors.textPrimary, + ), + ), + if (subtitle != null) ...[ + const SizedBox(height: 4), + Text( + subtitle!, + style: const TextStyle( + fontSize: 12, + color: AppColors.textSecondary, + ), + ), + ], + ], + ), + ); + } +} + +/// Info Card - Card untuk menampilkan informasi dengan icon +class InfoCard extends StatelessWidget { + final String title; + final String description; + final IconData icon; + final Color? iconColor; + final Color? backgroundColor; + final VoidCallback? onTap; + + const InfoCard({ + super.key, + required this.title, + required this.description, + required this.icon, + this.iconColor, + this.backgroundColor, + this.onTap, + }); + + @override + Widget build(BuildContext context) { + return CustomCard( + onTap: onTap, + backgroundColor: backgroundColor, + child: Row( + children: [ + Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: (iconColor ?? AppColors.primary).withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(12), + ), + child: Icon( + icon, + color: iconColor ?? AppColors.primary, + size: 24, + ), + ), + const SizedBox(width: 16), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600, + color: AppColors.textPrimary, + ), + ), + const SizedBox(height: 4), + Text( + description, + style: const TextStyle( + fontSize: 14, + color: AppColors.textSecondary, + ), + ), + ], + ), + ), + ], + ), + ); + } +} diff --git a/lib/ui/shared/components/custom_dialog.dart b/lib/ui/shared/components/custom_dialog.dart new file mode 100644 index 0000000..b56a3e7 --- /dev/null +++ b/lib/ui/shared/components/custom_dialog.dart @@ -0,0 +1,252 @@ +import 'package:flutter/material.dart'; +import 'package:mobile_monitoring/core/constants/colors.dart'; +import 'package:mobile_monitoring/ui/shared/components/custom_button.dart'; + +/// Custom Dialog - Dialog yang reusable +class CustomDialog { + /// Confirmation Dialog - Dialog untuk konfirmasi aksi + static Future showConfirmation({ + required BuildContext context, + required String title, + required String message, + String confirmText = 'Ya', + String cancelText = 'Tidak', + bool isDangerous = false, + }) { + return showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text(title), + content: Text(message), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(false), + child: Text(cancelText), + ), + CustomButton( + text: confirmText, + type: isDangerous ? ButtonType.danger : ButtonType.primary, + size: ButtonSize.small, + onPressed: () => Navigator.of(context).pop(true), + ), + ], + ), + ); + } + + /// Info Dialog - Dialog untuk menampilkan informasi + static Future showInfo({ + required BuildContext context, + required String title, + required String message, + String buttonText = 'OK', + IconData? icon, + Color? iconColor, + }) { + return showDialog( + context: context, + builder: (context) => AlertDialog( + title: Row( + children: [ + if (icon != null) ...[ + Icon(icon, color: iconColor ?? AppColors.info), + const SizedBox(width: 12), + ], + Expanded(child: Text(title)), + ], + ), + content: Text(message), + actions: [ + CustomButton( + text: buttonText, + type: ButtonType.primary, + size: ButtonSize.small, + onPressed: () => Navigator.of(context).pop(), + ), + ], + ), + ); + } + + /// Error Dialog - Dialog untuk menampilkan error + static Future showError({ + required BuildContext context, + required String title, + required String message, + String buttonText = 'OK', + }) { + return showInfo( + context: context, + title: title, + message: message, + buttonText: buttonText, + icon: Icons.error_outline, + iconColor: AppColors.error, + ); + } + + /// Success Dialog - Dialog untuk menampilkan success + static Future showSuccess({ + required BuildContext context, + required String title, + required String message, + String buttonText = 'OK', + }) { + return showInfo( + context: context, + title: title, + message: message, + buttonText: buttonText, + icon: Icons.check_circle_outline, + iconColor: AppColors.success, + ); + } + + /// Loading Dialog - Dialog untuk menampilkan loading + static void showLoading(BuildContext context, {String? message}) { + showDialog( + context: context, + barrierDismissible: false, + builder: (context) => PopScope( + canPop: false, + child: AlertDialog( + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const CircularProgressIndicator(), + if (message != null) ...[ + const SizedBox(height: 16), + Text(message), + ], + ], + ), + ), + ), + ); + } + + /// Custom Content Dialog - Dialog dengan custom content + static Future showCustom({ + required BuildContext context, + required String title, + required Widget content, + List? actions, + bool barrierDismissible = true, + }) { + return showDialog( + context: context, + barrierDismissible: barrierDismissible, + builder: (context) => AlertDialog( + title: Text(title), + content: content, + actions: actions, + ), + ); + } +} + +/// Bottom Sheet Dialog - Bottom sheet yang reusable +class CustomBottomSheet { + /// Show custom bottom sheet + static Future show({ + required BuildContext context, + required Widget child, + String? title, + bool isDismissible = true, + bool enableDrag = true, + double? height, + }) { + return showModalBottomSheet( + context: context, + isDismissible: isDismissible, + enableDrag: enableDrag, + isScrollControlled: true, + backgroundColor: Colors.transparent, + builder: (context) => Container( + height: height, + decoration: const BoxDecoration( + color: AppColors.white, + borderRadius: BorderRadius.only( + topLeft: Radius.circular(20), + topRight: Radius.circular(20), + ), + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + if (enableDrag) ...[ + const SizedBox(height: 8), + Container( + width: 40, + height: 4, + decoration: BoxDecoration( + color: AppColors.mediumGray, + borderRadius: BorderRadius.circular(2), + ), + ), + const SizedBox(height: 8), + ], + if (title != null) ...[ + Padding( + padding: const EdgeInsets.all(16), + child: Text( + title, + style: const TextStyle( + fontSize: 18, + fontWeight: FontWeight.w600, + color: AppColors.textPrimary, + ), + ), + ), + const Divider(height: 1), + ], + Flexible(child: child), + ], + ), + ), + ); + } + + /// Show list bottom sheet + static Future showList({ + required BuildContext context, + required String title, + required List> items, + }) { + return show( + context: context, + title: title, + child: ListView.builder( + shrinkWrap: true, + itemCount: items.length, + itemBuilder: (context, index) { + final item = items[index]; + return ListTile( + leading: item.icon != null + ? Icon(item.icon, color: item.iconColor) + : null, + title: Text(item.title), + subtitle: item.subtitle != null ? Text(item.subtitle!) : null, + onTap: () => Navigator.of(context).pop(item.value), + ); + }, + ), + ); + } +} + +class BottomSheetItem { + final String title; + final String? subtitle; + final IconData? icon; + final Color? iconColor; + final T value; + + BottomSheetItem({ + required this.title, + this.subtitle, + this.icon, + this.iconColor, + required this.value, + }); +} diff --git a/lib/ui/shared/components/custom_switch.dart b/lib/ui/shared/components/custom_switch.dart new file mode 100644 index 0000000..82fe7c4 --- /dev/null +++ b/lib/ui/shared/components/custom_switch.dart @@ -0,0 +1,273 @@ +import 'package:flutter/material.dart'; +import 'package:mobile_monitoring/core/constants/colors.dart'; + +/// Custom Switch - Switch widget yang reusable +class CustomSwitch extends StatelessWidget { + final bool value; + final ValueChanged? onChanged; + final Color? activeColor; + final Color? inactiveColor; + + const CustomSwitch({ + super.key, + required this.value, + this.onChanged, + this.activeColor, + this.inactiveColor, + }); + + @override + Widget build(BuildContext context) { + return Switch( + value: value, + onChanged: onChanged, + activeTrackColor: activeColor ?? AppColors.primary, + inactiveThumbColor: inactiveColor ?? AppColors.mediumGray, + ); + } +} + +/// Labeled Switch - Switch dengan label +class LabeledSwitch extends StatelessWidget { + final String label; + final bool value; + final ValueChanged? onChanged; + final String? description; + final IconData? icon; + + const LabeledSwitch({ + super.key, + required this.label, + required this.value, + this.onChanged, + this.description, + this.icon, + }); + + @override + Widget build(BuildContext context) { + return InkWell( + onTap: onChanged != null ? () => onChanged!(!value) : null, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16), + child: Row( + children: [ + if (icon != null) ...[ + Icon( + icon, + color: AppColors.textSecondary, + size: 24, + ), + const SizedBox(width: 12), + ], + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + label, + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w500, + color: AppColors.textPrimary, + ), + ), + if (description != null) ...[ + const SizedBox(height: 4), + Text( + description!, + style: const TextStyle( + fontSize: 12, + color: AppColors.textSecondary, + ), + ), + ], + ], + ), + ), + CustomSwitch( + value: value, + onChanged: onChanged, + ), + ], + ), + ), + ); + } +} + +/// Custom Checkbox - Checkbox yang reusable +class CustomCheckbox extends StatelessWidget { + final bool value; + final ValueChanged? onChanged; + final Color? activeColor; + + const CustomCheckbox({ + super.key, + required this.value, + this.onChanged, + this.activeColor, + }); + + @override + Widget build(BuildContext context) { + return Checkbox( + value: value, + onChanged: onChanged, + activeColor: activeColor ?? AppColors.primary, + ); + } +} + +/// Labeled Checkbox - Checkbox dengan label +class LabeledCheckbox extends StatelessWidget { + final String label; + final bool value; + final ValueChanged? onChanged; + + const LabeledCheckbox({ + super.key, + required this.label, + required this.value, + this.onChanged, + }); + + @override + Widget build(BuildContext context) { + return InkWell( + onTap: onChanged != null ? () => onChanged!(!value) : null, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 8), + child: Row( + children: [ + CustomCheckbox( + value: value, + onChanged: onChanged, + ), + const SizedBox(width: 8), + Expanded( + child: Text( + label, + style: const TextStyle( + fontSize: 14, + color: AppColors.textPrimary, + ), + ), + ), + ], + ), + ), + ); + } +} + +/// Custom Radio - Radio button yang reusable +class CustomRadio extends StatefulWidget { + final T value; + final T initialGroupValue; + final ValueChanged? onChanged; + final Color? activeColor; + + const CustomRadio({ + super.key, + required this.value, + required this.initialGroupValue, + this.onChanged, + this.activeColor, + }); + + @override + State> createState() => _CustomRadioState(); +} + +class _CustomRadioState extends State> { + late T _groupValue; + + @override + void initState() { + super.initState(); + _groupValue = widget.initialGroupValue; + } + + @override + Widget build(BuildContext context) { + return GestureDetector( + onTap: widget.onChanged != null ? () { + setState(() { + _groupValue = widget.value; + }); + widget.onChanged!(widget.value); + } : null, + child: Container( + width: 20, + height: 20, + decoration: BoxDecoration( + shape: BoxShape.circle, + border: Border.all( + color: _groupValue == widget.value + ? (widget.activeColor ?? AppColors.primary) + : AppColors.borderDark, + width: 2, + ), + ), + child: _groupValue == widget.value + ? Center( + child: Container( + width: 10, + height: 10, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: widget.activeColor ?? AppColors.primary, + ), + ), + ) + : null, + ), + ); + } +} + +/// Labeled Radio - Radio button dengan label +class LabeledRadio extends StatelessWidget { + final String label; + final T value; + final T initialGroupValue; + final ValueChanged? onChanged; + + const LabeledRadio({ + super.key, + required this.label, + required this.value, + required this.initialGroupValue, + this.onChanged, + }); + + @override + Widget build(BuildContext context) { + return InkWell( + onTap: onChanged != null ? () => onChanged!(value) : null, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 8), + child: Row( + children: [ + CustomRadio( + value: value, + initialGroupValue: initialGroupValue, + onChanged: onChanged, + ), + const SizedBox(width: 8), + Expanded( + child: Text( + label, + style: const TextStyle( + fontSize: 14, + color: AppColors.textPrimary, + ), + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/ui/shared/components/custom_textfield.dart b/lib/ui/shared/components/custom_textfield.dart new file mode 100644 index 0000000..d6c0b6d --- /dev/null +++ b/lib/ui/shared/components/custom_textfield.dart @@ -0,0 +1,178 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:mobile_monitoring/core/constants/colors.dart'; +import 'package:mobile_monitoring/core/constants/app_settings.dart'; + +/// Custom TextField - Text input field yang reusable +class CustomTextField extends StatefulWidget { + final TextEditingController? controller; + final String? labelText; + final String? hintText; + final String? helperText; + final String? errorText; + final IconData? prefixIcon; + final IconData? suffixIcon; + final VoidCallback? onSuffixIconTap; + final bool obscureText; + final bool enabled; + final bool readOnly; + final TextInputType? keyboardType; + final TextInputAction? textInputAction; + final int? maxLines; + final int? minLines; + final int? maxLength; + final List? inputFormatters; + final String? Function(String?)? validator; + final void Function(String)? onChanged; + final void Function(String)? onSubmitted; + final void Function()? onTap; + final FocusNode? focusNode; + final TextCapitalization textCapitalization; + final bool autofocus; + final bool showPasswordToggle; + + const CustomTextField({ + super.key, + this.controller, + this.labelText, + this.hintText, + this.helperText, + this.errorText, + this.prefixIcon, + this.suffixIcon, + this.onSuffixIconTap, + this.obscureText = false, + this.enabled = true, + this.readOnly = false, + this.keyboardType, + this.textInputAction, + this.maxLines = 1, + this.minLines, + this.maxLength, + this.inputFormatters, + this.validator, + this.onChanged, + this.onSubmitted, + this.onTap, + this.focusNode, + this.textCapitalization = TextCapitalization.none, + this.autofocus = false, + this.showPasswordToggle = false, + }); + + @override + State createState() => _CustomTextFieldState(); +} + +class _CustomTextFieldState extends State { + late bool _obscureText; + + @override + void initState() { + super.initState(); + _obscureText = widget.obscureText; + } + + @override + void didUpdateWidget(CustomTextField oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.obscureText != widget.obscureText) { + _obscureText = widget.obscureText; + } + } + + @override + Widget build(BuildContext context) { + return TextFormField( + controller: widget.controller, + obscureText: _obscureText, + enabled: widget.enabled, + readOnly: widget.readOnly, + keyboardType: widget.keyboardType, + textInputAction: widget.textInputAction, + maxLines: _obscureText ? 1 : widget.maxLines, + minLines: widget.minLines, + maxLength: widget.maxLength, + inputFormatters: widget.inputFormatters, + validator: widget.validator, + onChanged: widget.onChanged, + onFieldSubmitted: widget.onSubmitted, + onTap: widget.onTap, + focusNode: widget.focusNode, + textCapitalization: widget.textCapitalization, + autofocus: widget.autofocus, + style: TextStyle( + color: widget.enabled ? AppColors.textPrimary : AppColors.textSecondary, + fontSize: 16, + ), + decoration: InputDecoration( + labelText: widget.labelText, + hintText: widget.hintText, + helperText: widget.helperText, + errorText: widget.errorText, + prefixIcon: widget.prefixIcon != null + ? Icon( + widget.prefixIcon, + color: AppColors.textSecondary, + ) + : null, + suffixIcon: _buildSuffixIcon(), + filled: true, + fillColor: widget.enabled ? AppColors.white : AppColors.lightGray, + contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(AppSettings.defaultBorderRadius), + borderSide: const BorderSide(color: AppColors.borderLight), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(AppSettings.defaultBorderRadius), + borderSide: const BorderSide(color: AppColors.borderLight), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(AppSettings.defaultBorderRadius), + borderSide: const BorderSide(color: AppColors.primary, width: 2), + ), + errorBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(AppSettings.defaultBorderRadius), + borderSide: const BorderSide(color: AppColors.error), + ), + focusedErrorBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(AppSettings.defaultBorderRadius), + borderSide: const BorderSide(color: AppColors.error, width: 2), + ), + disabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(AppSettings.defaultBorderRadius), + borderSide: const BorderSide(color: AppColors.borderLight), + ), + ), + ); + } + + Widget? _buildSuffixIcon() { + if (widget.showPasswordToggle && widget.obscureText) { + return IconButton( + icon: Icon( + _obscureText ? Icons.visibility_off : Icons.visibility, + color: AppColors.textSecondary, + ), + onPressed: () { + setState(() { + _obscureText = !_obscureText; + }); + }, + ); + } + + if (widget.suffixIcon != null) { + return IconButton( + icon: Icon( + widget.suffixIcon, + color: AppColors.textSecondary, + ), + onPressed: widget.onSuffixIconTap, + ); + } + + return null; + } +} diff --git a/lib/ui/shared/components/empty_state.dart b/lib/ui/shared/components/empty_state.dart new file mode 100644 index 0000000..76a5401 --- /dev/null +++ b/lib/ui/shared/components/empty_state.dart @@ -0,0 +1,120 @@ +import 'package:flutter/material.dart'; +import 'package:mobile_monitoring/core/constants/colors.dart'; + +/// Empty State - Widget untuk menampilkan empty state +class EmptyState extends StatelessWidget { + final String title; + final String? message; + final IconData? icon; + final Widget? illustration; + final String? actionText; + final VoidCallback? onAction; + + const EmptyState({ + super.key, + required this.title, + this.message, + this.icon, + this.illustration, + this.actionText, + this.onAction, + }); + + @override + Widget build(BuildContext context) { + return Center( + child: Padding( + padding: const EdgeInsets.all(32), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + if (illustration != null) + illustration! + else if (icon != null) + Icon( + icon, + size: 80, + color: AppColors.mediumGray, + ), + const SizedBox(height: 24), + Text( + title, + style: const TextStyle( + fontSize: 18, + fontWeight: FontWeight.w600, + color: AppColors.textPrimary, + ), + textAlign: TextAlign.center, + ), + if (message != null) ...[ + const SizedBox(height: 8), + Text( + message!, + style: const TextStyle( + fontSize: 14, + color: AppColors.textSecondary, + ), + textAlign: TextAlign.center, + ), + ], + if (actionText != null && onAction != null) ...[ + const SizedBox(height: 24), + ElevatedButton( + onPressed: onAction, + style: ElevatedButton.styleFrom( + backgroundColor: AppColors.primary, + foregroundColor: AppColors.white, + padding: const EdgeInsets.symmetric( + horizontal: 32, + vertical: 12, + ), + ), + child: Text(actionText!), + ), + ], + ], + ), + ), + ); + } +} + +/// No Data Widget - Widget untuk menampilkan tidak ada data +class NoDataWidget extends StatelessWidget { + final String? message; + + const NoDataWidget({ + super.key, + this.message, + }); + + @override + Widget build(BuildContext context) { + return EmptyState( + icon: Icons.inbox_outlined, + title: 'Tidak Ada Data', + message: message ?? 'Belum ada data yang tersedia', + ); + } +} + +/// No Connection Widget - Widget untuk menampilkan tidak ada koneksi +class NoConnectionWidget extends StatelessWidget { + final VoidCallback? onRetry; + + const NoConnectionWidget({ + super.key, + this.onRetry, + }); + + @override + Widget build(BuildContext context) { + return EmptyState( + icon: Icons.wifi_off_outlined, + title: 'Tidak Ada Koneksi', + message: 'Periksa koneksi internet Anda dan coba lagi', + actionText: 'Coba Lagi', + onAction: onRetry, + ); + } +} diff --git a/lib/ui/shared/components/error_widget.dart b/lib/ui/shared/components/error_widget.dart new file mode 100644 index 0000000..b027f67 --- /dev/null +++ b/lib/ui/shared/components/error_widget.dart @@ -0,0 +1,205 @@ +import 'package:flutter/material.dart'; +import 'package:mobile_monitoring/core/constants/colors.dart'; + +/// Error Widget - Widget untuk menampilkan error state +class CustomErrorWidget extends StatelessWidget { + final String title; + final String? message; + final IconData? icon; + final String? actionText; + final VoidCallback? onAction; + final ErrorType type; + + const CustomErrorWidget({ + super.key, + required this.title, + this.message, + this.icon, + this.actionText, + this.onAction, + this.type = ErrorType.general, + }); + + @override + Widget build(BuildContext context) { + return Center( + child: Padding( + padding: const EdgeInsets.all(32), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + icon ?? _getIconForType(), + size: 80, + color: _getColorForType(), + ), + const SizedBox(height: 24), + Text( + title, + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.w600, + color: _getColorForType(), + ), + textAlign: TextAlign.center, + ), + if (message != null) ...[ + const SizedBox(height: 8), + Text( + message!, + style: const TextStyle( + fontSize: 14, + color: AppColors.textSecondary, + ), + textAlign: TextAlign.center, + ), + ], + if (actionText != null && onAction != null) ...[ + const SizedBox(height: 24), + ElevatedButton( + onPressed: onAction, + style: ElevatedButton.styleFrom( + backgroundColor: _getColorForType(), + foregroundColor: AppColors.white, + padding: const EdgeInsets.symmetric( + horizontal: 32, + vertical: 12, + ), + ), + child: Text(actionText!), + ), + ], + ], + ), + ), + ); + } + + IconData _getIconForType() { + switch (type) { + case ErrorType.general: + return Icons.error_outline; + case ErrorType.network: + return Icons.wifi_off_outlined; + case ErrorType.notFound: + return Icons.search_off_outlined; + case ErrorType.permission: + return Icons.lock_outline; + case ErrorType.timeout: + return Icons.access_time_outlined; + } + } + + Color _getColorForType() { + switch (type) { + case ErrorType.general: + case ErrorType.timeout: + return AppColors.error; + case ErrorType.network: + return AppColors.warning; + case ErrorType.notFound: + return AppColors.info; + case ErrorType.permission: + return AppColors.darkGray; + } + } +} + +enum ErrorType { + general, + network, + notFound, + permission, + timeout, +} + +/// Error Snackbar - Helper untuk menampilkan error di snackbar +class ErrorSnackbar { + static void show(BuildContext context, String message, {ErrorType? type}) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Row( + children: [ + Icon( + _getIconForType(type ?? ErrorType.general), + color: AppColors.white, + ), + const SizedBox(width: 12), + Expanded( + child: Text( + message, + style: const TextStyle(color: AppColors.white), + ), + ), + ], + ), + backgroundColor: _getColorForType(type ?? ErrorType.general), + behavior: SnackBarBehavior.floating, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(8), + ), + duration: const Duration(seconds: 4), + ), + ); + } + + static IconData _getIconForType(ErrorType type) { + switch (type) { + case ErrorType.general: + return Icons.error_outline; + case ErrorType.network: + return Icons.wifi_off_outlined; + case ErrorType.notFound: + return Icons.search_off_outlined; + case ErrorType.permission: + return Icons.lock_outline; + case ErrorType.timeout: + return Icons.access_time_outlined; + } + } + + static Color _getColorForType(ErrorType type) { + switch (type) { + case ErrorType.general: + case ErrorType.timeout: + return AppColors.error; + case ErrorType.network: + return AppColors.warning; + case ErrorType.notFound: + return AppColors.info; + case ErrorType.permission: + return AppColors.darkGray; + } + } +} + +/// Success Snackbar - Helper untuk menampilkan success message +class SuccessSnackbar { + static void show(BuildContext context, String message) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Row( + children: [ + const Icon( + Icons.check_circle_outline, + color: AppColors.white, + ), + const SizedBox(width: 12), + Expanded( + child: Text( + message, + style: const TextStyle(color: AppColors.white), + ), + ), + ], + ), + backgroundColor: AppColors.success, + behavior: SnackBarBehavior.floating, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(8), + ), + duration: const Duration(seconds: 3), + ), + ); + } +} diff --git a/lib/ui/shared/components/loading_indicator.dart b/lib/ui/shared/components/loading_indicator.dart new file mode 100644 index 0000000..aaad9cd --- /dev/null +++ b/lib/ui/shared/components/loading_indicator.dart @@ -0,0 +1,181 @@ +import 'package:flutter/material.dart'; +import 'package:mobile_monitoring/core/constants/colors.dart'; + +/// Loading Indicator - Widget untuk menampilkan loading state +class LoadingIndicator extends StatelessWidget { + final double size; + final Color? color; + final String? message; + + const LoadingIndicator({ + super.key, + this.size = 40, + this.color, + this.message, + }); + + @override + Widget build(BuildContext context) { + return Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + SizedBox( + width: size, + height: size, + child: CircularProgressIndicator( + valueColor: AlwaysStoppedAnimation( + color ?? AppColors.primary, + ), + strokeWidth: 3, + ), + ), + if (message != null) ...[ + const SizedBox(height: 16), + Text( + message!, + style: const TextStyle( + fontSize: 14, + color: AppColors.textSecondary, + ), + textAlign: TextAlign.center, + ), + ], + ], + ), + ); + } +} + +/// Overlay Loading - Full screen loading dengan overlay +class OverlayLoading extends StatelessWidget { + final String? message; + + const OverlayLoading({ + super.key, + this.message, + }); + + @override + Widget build(BuildContext context) { + return Container( + color: Colors.black.withValues(alpha: 0.5), + child: Center( + child: Container( + padding: const EdgeInsets.all(24), + decoration: BoxDecoration( + color: AppColors.white, + borderRadius: BorderRadius.circular(16), + ), + child: LoadingIndicator(message: message), + ), + ), + ); + } +} + +/// Shimmer Loading - Shimmer effect untuk skeleton loading +class ShimmerLoading extends StatefulWidget { + final double width; + final double height; + final BorderRadius? borderRadius; + + const ShimmerLoading({ + super.key, + required this.width, + required this.height, + this.borderRadius, + }); + + @override + State createState() => _ShimmerLoadingState(); +} + +class _ShimmerLoadingState extends State + with SingleTickerProviderStateMixin { + late AnimationController _controller; + late Animation _animation; + + @override + void initState() { + super.initState(); + _controller = AnimationController( + duration: const Duration(milliseconds: 1500), + vsync: this, + )..repeat(); + _animation = Tween(begin: -1.0, end: 2.0).animate( + CurvedAnimation(parent: _controller, curve: Curves.easeInOut), + ); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return AnimatedBuilder( + animation: _animation, + builder: (context, child) { + return Container( + width: widget.width, + height: widget.height, + decoration: BoxDecoration( + borderRadius: widget.borderRadius ?? BorderRadius.circular(8), + gradient: LinearGradient( + begin: Alignment.centerLeft, + end: Alignment.centerRight, + colors: const [ + AppColors.lightGray, + AppColors.white, + AppColors.lightGray, + ], + stops: [ + _animation.value - 0.3, + _animation.value, + _animation.value + 0.3, + ], + ), + ), + ); + }, + ); + } +} + +/// Linear Progress Indicator - Progress bar +class CustomLinearProgress extends StatelessWidget { + final double? value; + final Color? backgroundColor; + final Color? valueColor; + final double height; + final BorderRadius? borderRadius; + + const CustomLinearProgress({ + super.key, + this.value, + this.backgroundColor, + this.valueColor, + this.height = 4, + this.borderRadius, + }); + + @override + Widget build(BuildContext context) { + return ClipRRect( + borderRadius: borderRadius ?? BorderRadius.circular(height / 2), + child: SizedBox( + height: height, + child: LinearProgressIndicator( + value: value, + backgroundColor: backgroundColor ?? AppColors.lightGray, + valueColor: AlwaysStoppedAnimation( + valueColor ?? AppColors.primary, + ), + ), + ), + ); + } +} diff --git a/lib/ui/shared/components/section_header.dart b/lib/ui/shared/components/section_header.dart new file mode 100644 index 0000000..48263b4 --- /dev/null +++ b/lib/ui/shared/components/section_header.dart @@ -0,0 +1,197 @@ +import 'package:flutter/material.dart'; +import 'package:mobile_monitoring/core/constants/colors.dart'; + +/// Section Header - Header untuk section di halaman +class SectionHeader extends StatelessWidget { + final String title; + final String? subtitle; + final Widget? trailing; + final VoidCallback? onTrailingTap; + final String? trailingText; + final EdgeInsetsGeometry? padding; + final bool showDivider; + + const SectionHeader({ + super.key, + required this.title, + this.subtitle, + this.trailing, + this.onTrailingTap, + this.trailingText, + this.padding, + this.showDivider = false, + }); + + @override + Widget build(BuildContext context) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: padding ?? const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + child: Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: const TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: AppColors.textPrimary, + ), + ), + if (subtitle != null) ...[ + const SizedBox(height: 4), + Text( + subtitle!, + style: const TextStyle( + fontSize: 14, + color: AppColors.textSecondary, + ), + ), + ], + ], + ), + ), + if (trailing != null) + trailing! + else if (trailingText != null) + TextButton( + onPressed: onTrailingTap, + child: Text(trailingText!), + ), + ], + ), + ), + if (showDivider) const Divider(height: 1), + ], + ); + } +} + +/// Simple Section Header - Header sederhana untuk section +class SimpleSectionHeader extends StatelessWidget { + final String title; + final EdgeInsetsGeometry? padding; + + const SimpleSectionHeader({ + super.key, + required this.title, + this.padding, + }); + + @override + Widget build(BuildContext context) { + return Padding( + padding: padding ?? const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + child: Text( + title, + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600, + color: AppColors.textPrimary, + ), + ), + ); + } +} + +/// Icon Section Header - Section header dengan icon +class IconSectionHeader extends StatelessWidget { + final String title; + final IconData icon; + final Color? iconColor; + final VoidCallback? onTap; + final EdgeInsetsGeometry? padding; + + const IconSectionHeader({ + super.key, + required this.title, + required this.icon, + this.iconColor, + this.onTap, + this.padding, + }); + + @override + Widget build(BuildContext context) { + return InkWell( + onTap: onTap, + child: Padding( + padding: padding ?? const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + child: Row( + children: [ + Icon( + icon, + color: iconColor ?? AppColors.primary, + size: 24, + ), + const SizedBox(width: 12), + Expanded( + child: Text( + title, + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600, + color: AppColors.textPrimary, + ), + ), + ), + if (onTap != null) + const Icon( + Icons.chevron_right, + color: AppColors.textSecondary, + ), + ], + ), + ), + ); + } +} + +/// Divider with Text - Divider dengan teks di tengah +class DividerWithText extends StatelessWidget { + final String text; + final Color? color; + final double? thickness; + + const DividerWithText({ + super.key, + required this.text, + this.color, + this.thickness, + }); + + @override + Widget build(BuildContext context) { + return Row( + children: [ + Expanded( + child: Divider( + color: color ?? AppColors.borderLight, + thickness: thickness ?? 1, + ), + ), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Text( + text, + style: const TextStyle( + fontSize: 12, + color: AppColors.textSecondary, + ), + ), + ), + Expanded( + child: Divider( + color: color ?? AppColors.borderLight, + thickness: thickness ?? 1, + ), + ), + ], + ); + } +} diff --git a/lib/ui/shared/components/status_badge.dart b/lib/ui/shared/components/status_badge.dart new file mode 100644 index 0000000..a58abfd --- /dev/null +++ b/lib/ui/shared/components/status_badge.dart @@ -0,0 +1,213 @@ +import 'package:flutter/material.dart'; +import 'package:mobile_monitoring/core/constants/colors.dart'; + +/// Status Badge - Badge untuk menampilkan status +class StatusBadge extends StatelessWidget { + final String label; + final Color? backgroundColor; + final Color? textColor; + final IconData? icon; + final BadgeSize size; + + const StatusBadge({ + super.key, + required this.label, + this.backgroundColor, + this.textColor, + this.icon, + this.size = BadgeSize.medium, + }); + + // Factory constructors untuk status umum + factory StatusBadge.success(String label, {BadgeSize size = BadgeSize.medium}) { + return StatusBadge( + label: label, + backgroundColor: AppColors.success, + textColor: AppColors.white, + icon: Icons.check_circle, + size: size, + ); + } + + factory StatusBadge.warning(String label, {BadgeSize size = BadgeSize.medium}) { + return StatusBadge( + label: label, + backgroundColor: AppColors.warning, + textColor: AppColors.white, + icon: Icons.warning, + size: size, + ); + } + + factory StatusBadge.error(String label, {BadgeSize size = BadgeSize.medium}) { + return StatusBadge( + label: label, + backgroundColor: AppColors.error, + textColor: AppColors.white, + icon: Icons.error, + size: size, + ); + } + + factory StatusBadge.info(String label, {BadgeSize size = BadgeSize.medium}) { + return StatusBadge( + label: label, + backgroundColor: AppColors.info, + textColor: AppColors.white, + icon: Icons.info, + size: size, + ); + } + + factory StatusBadge.neutral(String label, {BadgeSize size = BadgeSize.medium}) { + return StatusBadge( + label: label, + backgroundColor: AppColors.lightGray, + textColor: AppColors.textPrimary, + size: size, + ); + } + + @override + Widget build(BuildContext context) { + return Container( + padding: _getPadding(), + decoration: BoxDecoration( + color: backgroundColor ?? AppColors.primary, + borderRadius: BorderRadius.circular(12), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (icon != null) ...[ + Icon( + icon, + size: _getIconSize(), + color: textColor ?? AppColors.white, + ), + SizedBox(width: _getSpacing()), + ], + Text( + label, + style: TextStyle( + fontSize: _getFontSize(), + fontWeight: FontWeight.w600, + color: textColor ?? AppColors.white, + ), + ), + ], + ), + ); + } + + EdgeInsets _getPadding() { + switch (size) { + case BadgeSize.small: + return const EdgeInsets.symmetric(horizontal: 8, vertical: 4); + case BadgeSize.medium: + return const EdgeInsets.symmetric(horizontal: 12, vertical: 6); + case BadgeSize.large: + return const EdgeInsets.symmetric(horizontal: 16, vertical: 8); + } + } + + double _getFontSize() { + switch (size) { + case BadgeSize.small: + return 10; + case BadgeSize.medium: + return 12; + case BadgeSize.large: + return 14; + } + } + + double _getIconSize() { + switch (size) { + case BadgeSize.small: + return 12; + case BadgeSize.medium: + return 14; + case BadgeSize.large: + return 16; + } + } + + double _getSpacing() { + switch (size) { + case BadgeSize.small: + return 4; + case BadgeSize.medium: + return 6; + case BadgeSize.large: + return 8; + } + } +} + +enum BadgeSize { small, medium, large } + +/// Notification Badge - Badge untuk menampilkan notifikasi count +class NotificationBadge extends StatelessWidget { + final int count; + final Color? backgroundColor; + final Color? textColor; + + const NotificationBadge({ + super.key, + required this.count, + this.backgroundColor, + this.textColor, + }); + + @override + Widget build(BuildContext context) { + if (count <= 0) return const SizedBox.shrink(); + + return Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: backgroundColor ?? AppColors.error, + borderRadius: BorderRadius.circular(10), + ), + constraints: const BoxConstraints( + minWidth: 20, + minHeight: 20, + ), + child: Center( + child: Text( + count > 99 ? '99+' : count.toString(), + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.bold, + color: textColor ?? AppColors.white, + ), + ), + ), + ); + } +} + +/// Dot Badge - Badge berbentuk dot +class DotBadge extends StatelessWidget { + final Color? color; + final double size; + + const DotBadge({ + super.key, + this.color, + this.size = 8, + }); + + @override + Widget build(BuildContext context) { + return Container( + width: size, + height: size, + decoration: BoxDecoration( + color: color ?? AppColors.error, + shape: BoxShape.circle, + ), + ); + } +} diff --git a/lib/ui/shared/graph_widget.dart b/lib/ui/shared/graph_widget.dart new file mode 100644 index 0000000..4f67d5b --- /dev/null +++ b/lib/ui/shared/graph_widget.dart @@ -0,0 +1,320 @@ +import 'package:flutter/material.dart'; +import 'package:fl_chart/fl_chart.dart'; +import 'package:mobile_monitoring/core/constants/constants.dart'; +import 'package:mobile_monitoring/ui/widgets/graph_component_service.dart'; + +class GraphWidget extends StatefulWidget { + final String? userId; + const GraphWidget({super.key, this.userId}); + + @override + State createState() => _GraphWidgetState(); +} + +class _GraphWidgetState extends State { + final _graphService = GraphComponentService(); + + Widget _buildEmptyState({ + required IconData icon, + required String title, + required String subtitle, + Color? iconColor, + VoidCallback? onRetry, + }) { + return SizedBox( + height: 400, + child: Center( + child: Padding( + padding: const EdgeInsets.all(16.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(icon, color: iconColor ?? AppColors.textSecondary, size: 50), + const SizedBox(height: 16), + Text( + title, + textAlign: TextAlign.center, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 8), + Text( + subtitle, + textAlign: TextAlign.center, + style: const TextStyle(fontSize: 12, color: AppColors.textSecondary), + maxLines: 3, + overflow: TextOverflow.ellipsis, + ), + if (onRetry != null) ...[ + const SizedBox(height: 16), + ElevatedButton.icon( + onPressed: onRetry, + icon: const Icon(Icons.refresh, size: 18), + label: const Text(AppStrings.retry), + style: ElevatedButton.styleFrom( + padding: const EdgeInsets.symmetric( + horizontal: 20, + vertical: 10, + ), + ), + ), + ], + ], + ), + ), + ), + ); + } + + @override + Widget build(BuildContext context) { + if (widget.userId == null || widget.userId!.isEmpty) { + return _buildEmptyState( + icon: Icons.error_outline, + title: AppStrings.pleaseLogin, + subtitle: 'Sesi Anda telah berakhir, login kembali', + iconColor: AppColors.error, + ); + } + + return Center( + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: SizedBox( + width: 320, + child: StreamBuilder?>( + stream: _graphService.cycleStream(widget.userId ?? ''), + builder: (context, cycleSnapshot) { + final startDate = _graphService.extractStartDate( + cycleSnapshot.data, + ); + + return StreamBuilder>>( + stream: _graphService.historyStream( + limit: 500, + userId: widget.userId, + ), + builder: (context, snapshot) { + if (snapshot.hasError) { + final isAuthError = _graphService.isAuthError( + snapshot.error!, + ); + return _buildEmptyState( + icon: Icons.error_outline, + title: isAuthError + ? AppStrings.pleaseLogin + : AppStrings.failedToLoadData, + subtitle: isAuthError + ? 'Sesi Anda telah berakhir, login kembali' + : 'Terjadi kesalahan saat mengambil data grafik', + iconColor: isAuthError ? AppColors.error : AppColors.warning, + onRetry: () => setState(() {}), + ); + } + + if (snapshot.connectionState == ConnectionState.waiting) { + return const SizedBox( + height: 400, + child: Center(child: CircularProgressIndicator()), + ); + } + + final docs = snapshot.data ?? []; + if (docs.isEmpty) { + return _buildEmptyState( + icon: Icons.agriculture, + title: AppStrings.startPlantingFirst, + subtitle: 'Mulai monitoring untuk melihat grafik data', + iconColor: AppColors.primary, + ); + } + + final prepared = _graphService.prepareGraphData( + docs, + startDate, + ); + if (!prepared.success || prepared.data == null) { + return _buildEmptyState( + icon: Icons.calendar_today, + title: AppStrings.noDataAvailable, + subtitle: + 'Data akan tampil setelah Anda memulai monitoring', + ); + } + + final graphData = prepared.data!; + final phSpots = List.generate( + graphData.phValues.length, + (i) => FlSpot(i.toDouble(), graphData.phValues[i]), + ); + final nutrientSpots = List.generate( + graphData.nutrientValues.length, + (i) => FlSpot(i.toDouble(), graphData.nutrientValues[i]), + ); + + return Column( + children: [ + _GraphCard( + title: 'Grafik pH 7 Hari Terakhir', + color: AppColors.secondaryDark, + spots: phSpots, + minY: 0.0, + maxY: 8.0, + yLabel: 'pH', + xLabels: graphData.dayLabels, + yDecimal: true, + ), + const SizedBox(height: 24), + _GraphCard( + title: 'Grafik Nutrisi (TDS) 7 Hari Terakhir', + color: AppColors.info, + spots: nutrientSpots, + minY: 0, + maxY: 1400, + yLabel: 'ppm', + xLabels: graphData.dayLabels, + ), + ], + ); + }, + ); + }, + ), + ), + ), + ); + } +} + +class _GraphCard extends StatelessWidget { + final String title; + final Color color; + final List spots; + final double minY, maxY; + final String yLabel; + final List xLabels; + final bool yDecimal; + + const _GraphCard({ + required this.title, + required this.color, + required this.spots, + required this.minY, + required this.maxY, + required this.yLabel, + required this.xLabels, + this.yDecimal = false, + }); + + @override + Widget build(BuildContext context) { + return Container( + margin: const EdgeInsets.symmetric(vertical: 4), + padding: const EdgeInsets.fromLTRB(16, 16, 16, 8), + decoration: BoxDecoration( + color: AppColors.white, + borderRadius: BorderRadius.circular(30), + boxShadow: [ + BoxShadow( + color: AppColors.darkGray.withValues(alpha: 0.1), + spreadRadius: 2, + blurRadius: 10, + ), + ], + ), + height: 280, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(title, style: const TextStyle(fontWeight: FontWeight.bold)), + const SizedBox(height: 20), + Expanded( + child: LineChart( + LineChartData( + gridData: FlGridData( + show: true, + drawVerticalLine: false, + horizontalInterval: yDecimal ? 0.5 : (maxY - minY) / 5, + getDrawingHorizontalLine: (_) => + const FlLine(color: Color(0xffe7e8ec), strokeWidth: 1), + ), + titlesData: FlTitlesData( + show: true, + rightTitles: const AxisTitles( + sideTitles: SideTitles(showTitles: false), + ), + topTitles: const AxisTitles( + sideTitles: SideTitles(showTitles: false), + ), + bottomTitles: AxisTitles( + sideTitles: SideTitles( + showTitles: true, + reservedSize: 45, + interval: 1, + getTitlesWidget: (value, meta) { + final idx = value.toInt(); + return SideTitleWidget( + axisSide: meta.axisSide, + child: idx >= 0 && idx < xLabels.length + ? Text( + xLabels[idx], + style: const TextStyle( + fontSize: 9, + fontWeight: FontWeight.bold, + color: Color(0xff68737d), + ), + textAlign: TextAlign.center, + ) + : const SizedBox.shrink(), + ); + }, + ), + ), + leftTitles: AxisTitles( + sideTitles: SideTitles( + showTitles: true, + interval: yDecimal ? 0.5 : (maxY - minY) / 5, + reservedSize: 36, + getTitlesWidget: (value, meta) { + return value >= minY && value <= maxY + ? Text( + yDecimal + ? value.toStringAsFixed(1) + : value.toStringAsFixed(0), + style: const TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + color: Color(0xff67727d), + ), + ) + : const SizedBox.shrink(); + }, + ), + ), + ), + borderData: FlBorderData(show: false), + minX: 0, + maxX: (xLabels.length - 1).toDouble(), + minY: minY, + maxY: maxY, + lineBarsData: [ + LineChartBarData( + spots: spots, + isCurved: true, + color: color, + barWidth: 3, + isStrokeCapRound: true, + dotData: const FlDotData(show: false), + belowBarData: BarAreaData(show: false), + ), + ], + ), + ), + ), + ], + ), + ); + } +} diff --git a/lib/ui/shared/growth_phase_card.dart b/lib/ui/shared/growth_phase_card.dart new file mode 100644 index 0000000..8cd1081 --- /dev/null +++ b/lib/ui/shared/growth_phase_card.dart @@ -0,0 +1,472 @@ +import 'package:flutter/material.dart'; +import 'package:mobile_monitoring/core/constants/constants.dart'; +import 'package:mobile_monitoring/ui/widgets/growth_phase_service.dart'; +import 'package:mobile_monitoring/core/utils/phase_display_utils.dart'; + +class GrowthPhaseCard extends StatefulWidget { + const GrowthPhaseCard({super.key}); + + @override + State createState() => _GrowthPhaseCardState(); +} + +class _GrowthPhaseCardState extends State { + final _growthPhaseService = GrowthPhaseService(); + + void _showSnackBar(String msg, {bool isError = false}) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(msg), + backgroundColor: isError + ? AppColors.error + : (msg.contains('✓') ? AppColors.success : AppColors.info), + duration: const Duration(seconds: 2), + ), + ); + } + + Future _setPlantingDate() async { + final userId = _growthPhaseService.getCurrentUserId(); + if (userId.isEmpty) return; + final picked = await showDatePicker( + context: context, + initialDate: DateTime.now(), + firstDate: DateTime(2020), + lastDate: DateTime.now(), + builder: (context, child) => Theme( + data: Theme.of(context).copyWith( + colorScheme: const ColorScheme.light(primary: AppColors.primary), + ), + child: child!, + ), + ); + + if (picked != null) { + final result = await _growthPhaseService.savePlantingDate( + userId: userId, + plantingDate: picked, + ); + + _showSnackBar( + result.success ? '✓ ${result.message}!' : result.message, + isError: !result.success, + ); + } + } + + Future _resetCycle() async { + final userId = _growthPhaseService.getCurrentUserId(); + if (userId.isEmpty) return; + + final confirmed = await showDialog( + context: context, + builder: (ctx) => AlertDialog( + title: const Text('Reset Siklus?'), + content: const Text('Data tanggal tanam sebelumnya akan dihapus.'), + actions: [ + TextButton( + onPressed: () => Navigator.pop(ctx, false), + child: const Text('Batal'), + ), + ElevatedButton( + onPressed: () => Navigator.pop(ctx, true), + style: ElevatedButton.styleFrom(backgroundColor: AppColors.error), + child: const Text('Reset'), + ), + ], + ), + ); + + if (confirmed == true) { + final result = await _growthPhaseService.resetCycle(userId); + _showSnackBar( + result.success ? '✓ ${result.message}!' : result.message, + isError: !result.success, + ); + } + } + + Future _markHarvest() async { + final userId = _growthPhaseService.getCurrentUserId(); + if (userId.isEmpty) return; + + final result = await _growthPhaseService.markHarvest(userId); + _showSnackBar( + result.success ? '✓ ${result.message}' : result.message, + isError: !result.success, + ); + } + + Future _updatePhaseIfChanged( + String currentPhaseInDb, + String calculatedPhase, + int days, + DateTime startDate, + ) async { + final userId = _growthPhaseService.getCurrentUserId(); + if (userId.isEmpty) return; + + try { + await _growthPhaseService.updatePhaseIfChanged( + userId: userId, + currentPhaseInDb: currentPhaseInDb, + calculatedPhase: calculatedPhase, + days: days, + startDate: startDate, + ); + _showSnackBar('✓ Fase otomatis diperbarui ke $calculatedPhase'); + } catch (e) { + debugPrint('✗ Error updating phase: $e'); + } + } + + @override + Widget build(BuildContext context) { + final user = _growthPhaseService.getCurrentUser(); + if (user == null) { + return _buildCard( + child: const Text('Silakan login untuk melihat fase pertumbuhan.'), + ); + } + + return StreamBuilder?>( + stream: _growthPhaseService.activeCycleStream(user.uid), + builder: (context, snapshot) { + if (snapshot.hasError) { + return _buildCard(child: Text('Error: ${snapshot.error}')); + } + if (snapshot.connectionState == ConnectionState.waiting) { + return _buildCard( + child: const Center(child: CircularProgressIndicator()), + ); + } + + final data = snapshot.data; + if (data == null) { + return _buildEmptyState(); + } + + final startDate = _growthPhaseService.extractStartDate(data); + final currentPhaseInDb = data['growth_phase'] as String?; + + if (startDate != null) { + final days = DateTime.now().difference(startDate).inDays; + final calculatedPhase = _growthPhaseService.calculateCurrentPhase( + days, + ); + final currentPhase = + (currentPhaseInDb != null && currentPhaseInDb.isNotEmpty) + ? currentPhaseInDb + : calculatedPhase; + + if (currentPhaseInDb != null && currentPhaseInDb != calculatedPhase) { + Future.microtask( + () => _updatePhaseIfChanged( + currentPhaseInDb, + calculatedPhase, + days, + startDate, + ), + ); + } + + return _buildActiveState( + daysSincePlanting: days, + startDate: startDate, + currentPhase: currentPhase, + ); + } + + return _buildEmptyState(); + }, + ); + } + + Widget _buildCard({required Widget child}) { + return Container( + margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + padding: const EdgeInsets.all(20), + decoration: BoxDecoration( + color: AppColors.white, + borderRadius: BorderRadius.circular(20), + boxShadow: [ + BoxShadow( + color: _growthPhaseService.applyAlpha(AppColors.darkGray, 0.1), + spreadRadius: 2, + blurRadius: 10, + ), + ], + ), + child: child, + ); + } + + Widget _buildEmptyState() { + return _buildCard( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: _growthPhaseService.applyAlpha(AppColors.primary, 0.1), + borderRadius: BorderRadius.circular(12), + ), + child: const Icon( + Icons.eco, + color: AppColors.primary, + size: 24, + ), + ), + const SizedBox(width: 12), + const Expanded( + child: Text( + 'Fase Pertumbuhan', + style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), + ), + ), + ], + ), + const SizedBox(height: 16), + const Text( + 'Belum ada siklus tanam aktif', + style: TextStyle(fontSize: 14, color: Colors.grey), + ), + const SizedBox(height: 12), + SizedBox( + width: double.infinity, + child: ElevatedButton.icon( + onPressed: _setPlantingDate, + icon: const Icon(Icons.event, size: 20), + label: const Text('Mulai Tanam'), + style: ElevatedButton.styleFrom( + backgroundColor: AppColors.primary, + foregroundColor: AppColors.white, + padding: const EdgeInsets.symmetric(vertical: 14), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + ), + ), + ), + ), + ], + ), + ); + } + + Widget _buildActiveState({ + required int daysSincePlanting, + DateTime? startDate, + required String currentPhase, + }) { + final phaseColor = _growthPhaseService.getPhaseColor(currentPhase); + final phaseData = _growthPhaseService.getPhaseData(daysSincePlanting); + + final phaseDay = phaseData['day'] as int; + final phaseDuration = phaseData['duration'] as int; + final progress = phaseData['progress'] as double; + + return _buildCard( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: _growthPhaseService.applyAlpha(phaseColor, 0.1), + borderRadius: BorderRadius.circular(12), + ), + child: Icon(Icons.eco, color: phaseColor, size: 24), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Fase Pertumbuhan', + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.bold, + ), + ), + Text( + 'Hari ke-$daysSincePlanting', + style: TextStyle(fontSize: 12, color: Colors.grey[600]), + ), + ], + ), + ), + IconButton( + icon: const Icon(Icons.refresh, size: 20), + onPressed: _resetCycle, + padding: EdgeInsets.zero, + constraints: const BoxConstraints(), + ), + ], + ), + const SizedBox(height: 16), + Container( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + decoration: BoxDecoration( + color: _growthPhaseService.applyAlpha(phaseColor, 0.15), + borderRadius: BorderRadius.circular(20), + border: Border.all(color: phaseColor, width: 1.5), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.circle, color: phaseColor, size: 12), + const SizedBox(width: 8), + Text( + 'Fase $currentPhase', + style: TextStyle( + color: phaseColor, + fontWeight: FontWeight.bold, + ), + ), + Text( + ' (Hari $phaseDay/$phaseDuration)', + style: TextStyle(color: phaseColor, fontSize: 12), + ), + ], + ), + ), + const SizedBox(height: 16), + ClipRRect( + borderRadius: BorderRadius.circular(10), + child: LinearProgressIndicator( + value: progress.clamp(0.0, 1.0), + backgroundColor: Colors.grey[200], + color: phaseColor, + minHeight: 8, + ), + ), + const SizedBox(height: 20), + const Divider(), + const SizedBox(height: 12), + Row( + children: List.generate(PhaseDisplayUtils.ordered.length, (index) { + final phase = PhaseDisplayUtils.ordered[index]; + final isActive = + phase.name.toLowerCase() == currentPhase.toLowerCase(); + final isPassed = daysSincePlanting >= phase.startDay; + + return Expanded( + child: Padding( + padding: EdgeInsets.only( + right: index < PhaseDisplayUtils.ordered.length - 1 ? 8 : 0, + ), + child: _buildPhaseItem( + phase.name, + phase.dayRangeLabel, + phase.color, + isActive, + isPassed, + ), + ), + ); + }), + ), + if (startDate != null) ...[ + const SizedBox(height: 16), + Row( + children: [ + Icon(Icons.event, size: 16, color: Colors.grey[600]), + const SizedBox(width: 6), + Text( + 'Mulai: ${_growthPhaseService.formatDate(startDate)}', + style: TextStyle(fontSize: 12, color: Colors.grey[600]), + ), + ], + ), + ], + const SizedBox(height: 16), + Row( + children: [ + Expanded( + child: OutlinedButton.icon( + onPressed: _resetCycle, + icon: const Icon(Icons.refresh, size: 16), + label: const Text('Reset'), + style: OutlinedButton.styleFrom( + foregroundColor: AppColors.error, + side: const BorderSide(color: AppColors.error), + ), + ), + ), + const SizedBox(width: 12), + Expanded( + child: ElevatedButton.icon( + onPressed: _markHarvest, + icon: const Icon(Icons.agriculture, size: 16), + label: const Text('Panen'), + style: ElevatedButton.styleFrom( + backgroundColor: AppColors.primary, + ), + ), + ), + ], + ), + ], + ), + ); + } + + Widget _buildPhaseItem( + String name, + String range, + Color color, + bool isActive, + bool isPassed, + ) { + return Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: isActive + ? _growthPhaseService.applyAlpha(color, 0.15) + : (isPassed ? Colors.grey[100] : Colors.grey[50]), + borderRadius: BorderRadius.circular(8), + border: Border.all( + color: isActive + ? color + : (isPassed ? Colors.grey : Colors.grey[300]!), + width: isActive ? 2 : 1, + ), + ), + child: Column( + children: [ + Icon( + isPassed ? Icons.check_circle : Icons.circle_outlined, + size: 18, + color: isActive + ? color + : (isPassed ? Colors.grey : Colors.grey[400]), + ), + const SizedBox(height: 4), + Text( + name, + style: TextStyle( + fontSize: 10, + fontWeight: isActive ? FontWeight.bold : FontWeight.normal, + color: isActive + ? color + : (isPassed ? Colors.grey : Colors.grey[600]), + ), + textAlign: TextAlign.center, + ), + Text( + range, + style: TextStyle(fontSize: 8, color: Colors.grey[500]), + textAlign: TextAlign.center, + ), + ], + ), + ); + } +} diff --git a/lib/ui/shared/home_header.dart b/lib/ui/shared/home_header.dart new file mode 100644 index 0000000..de4e3de --- /dev/null +++ b/lib/ui/shared/home_header.dart @@ -0,0 +1,141 @@ +import 'package:flutter/material.dart'; +import 'package:mobile_monitoring/core/constants/constants.dart'; +import 'package:mobile_monitoring/logic/controllers/controllers.dart'; +import 'package:mobile_monitoring/ui/pages/profile.dart'; + +class HomeHeader extends StatelessWidget { + final HomeController controller; + + const HomeHeader({super.key, required this.controller}); + + @override + Widget build(BuildContext context) { + final userName = controller.userDisplayName; + final userInitials = controller.userInitials; + final screenWidth = MediaQuery.of(context).size.width; + final isSmallScreen = screenWidth < 360; + final isTablet = screenWidth >= 600; + + final imageWidth = isTablet ? screenWidth * 0.40 : screenWidth * 0.58; + final imageHeight = isTablet ? 240.0 : 200.0; + final imageTop = isTablet ? 50.0 : (isSmallScreen ? 70.0 : 65.0); + final imageRight = isTablet ? -40.0 : -30.0; + final rightPadding = isTablet ? screenWidth * 0.38 : screenWidth * 0.46; + + return SizedBox( + height: 250, + child: Stack( + clipBehavior: Clip.none, + children: [ + ClipPath( + clipper: _HeaderCurveClipper(), + child: Container( + height: 250, + color: AppColors.secondary, + child: Padding( + padding: EdgeInsets.only(top: 40, left: 20, right: rightPadding, bottom: 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Halo, $userName!', + style: TextStyle( + color: Colors.white, + fontSize: isTablet ? 24 : (isSmallScreen ? 18 : 20), + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 4), + Text( + 'Selamat datang di ${AppStrings.appName}.', + style: TextStyle( + color: Colors.white, + fontSize: isTablet ? 20 : (isSmallScreen ? 16 : 18), + fontWeight: FontWeight.w600, + ), + ), + const SizedBox(height: 12), + Flexible( + child: Text( + 'Monitor dan kelola nutrisi hidroponik Anda dengan mudah dan efisien.', + style: TextStyle( + color: Colors.white.withValues(alpha: 0.95), + fontSize: isTablet ? 14 : (isSmallScreen ? 11 : 12), + height: 1.5, + ), + maxLines: 5, + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), + ), + ), + ), + Positioned( + top: imageTop, + right: imageRight, + child: Image.asset( + 'assets/images/image-removebg-preview.png', + width: imageWidth, + height: imageHeight, + fit: BoxFit.contain, + ), + ), + Positioned( + top: 40, + right: 20, + child: GestureDetector( + onTap: () { + Navigator.of(context).push( + MaterialPageRoute(builder: (context) => const ProfilePage()), + ); + }, + child: Container( + decoration: BoxDecoration( + shape: BoxShape.circle, + border: Border.all(color: Colors.white, width: 2), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.2), + blurRadius: 4, + spreadRadius: 1, + ), + ], + ), + child: CircleAvatar( + radius: 20, + backgroundColor: AppColors.secondaryLight, + child: Text( + userInitials, + style: const TextStyle( + color: Colors.white, + fontWeight: FontWeight.bold, + fontSize: 16, + ), + ), + ), + ), + ), + ), + ], + ), + ); + } +} + +class _HeaderCurveClipper extends CustomClipper { + @override + Path getClip(Size size) { + final path = Path(); + path.lineTo(0, size.height - 60); + path.quadraticBezierTo(size.width * 0.25, size.height, size.width * 0.5, size.height - 40); + path.quadraticBezierTo(size.width * 0.75, size.height - 80, size.width, size.height - 40); + path.lineTo(size.width, 0); + path.close(); + return path; + } + + @override + bool shouldReclip(CustomClipper oldClipper) => false; +} diff --git a/lib/ui/shared/login_form.dart b/lib/ui/shared/login_form.dart new file mode 100644 index 0000000..798db77 --- /dev/null +++ b/lib/ui/shared/login_form.dart @@ -0,0 +1,117 @@ +import 'package:flutter/material.dart'; +import 'package:mobile_monitoring/ui/shared/components/components.dart'; +import 'package:mobile_monitoring/core/constants/strings.dart'; + +class LoginForm extends StatefulWidget { + final TextEditingController emailController; + final TextEditingController passwordController; + final GlobalKey formKey; + final VoidCallback onLogin; + final VoidCallback onForgotPassword; + final VoidCallback onRegisterTap; + final bool isLoading; + + const LoginForm({ + super.key, + required this.emailController, + required this.passwordController, + required this.formKey, + required this.onLogin, + required this.onForgotPassword, + required this.onRegisterTap, + this.isLoading = false, + }); + + @override + State createState() => _LoginFormState(); +} + +class _LoginFormState extends State { + @override + Widget build(BuildContext context) { + return CustomCard( + padding: const EdgeInsets.all(24), + elevation: 5, + borderRadius: 20, + child: Form( + key: widget.formKey, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const Text( + AppStrings.login, + style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold), + textAlign: TextAlign.center, + ), + const SizedBox(height: 24), + + // Email Field + CustomTextField( + controller: widget.emailController, + keyboardType: TextInputType.emailAddress, + labelText: AppStrings.email, + prefixIcon: Icons.email, + validator: (value) { + if (value == null || value.isEmpty) { + return 'Email tidak boleh kosong'; + } + if (!value.contains('@')) { + return AppStrings.invalidEmail; + } + return null; + }, + ), + const SizedBox(height: 16), + + // Password Field + CustomTextField( + controller: widget.passwordController, + obscureText: true, + showPasswordToggle: true, + labelText: AppStrings.password, + prefixIcon: Icons.lock, + validator: (value) { + if (value == null || value.isEmpty) { + return 'Password tidak boleh kosong'; + } + if (value.length < 6) { + return AppStrings.passwordTooShort; + } + return null; + }, + ), + const SizedBox(height: 24), + + // Login Button + CustomButton( + text: AppStrings.signIn, + onPressed: widget.isLoading + ? null + : () { + debugPrint('Login button pressed'); + widget.onLogin(); + }, + isLoading: widget.isLoading, + width: double.infinity, + ), + const SizedBox(height: 16), + + // Register Link + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text(AppStrings.noAccount), + CustomButton( + text: AppStrings.signUp, + type: ButtonType.text, + size: ButtonSize.small, + onPressed: widget.onRegisterTap, + ), + ], + ), + ], + ), + ), + ); + } +} diff --git a/lib/ui/shared/monitoring_card.dart b/lib/ui/shared/monitoring_card.dart new file mode 100644 index 0000000..fa9d635 --- /dev/null +++ b/lib/ui/shared/monitoring_card.dart @@ -0,0 +1,290 @@ +import 'package:flutter/material.dart'; +import 'package:mobile_monitoring/core/constants/constants.dart'; +import 'package:mobile_monitoring/ui/widgets/monitoring_card_service.dart'; +import 'package:mobile_monitoring/core/utils/phase_display_utils.dart'; + +class MonitoringCard extends StatefulWidget { + final String title; + final String value; + final String unit; + final String status; + final Color statusColor; + final String description; + final String? userId; + + final bool? switch1Value; + final bool? switch2Value; + final String? switch1Label; + final String? switch2Label; + final Function(bool)? onSwitch1Changed; + final Function(bool)? onSwitch2Changed; + + const MonitoringCard({ + super.key, + required this.title, + required this.value, + required this.unit, + required this.status, + required this.statusColor, + required this.description, + this.userId, + this.switch1Value, + this.switch2Value, + this.switch1Label, + this.switch2Label, + this.onSwitch1Changed, + this.onSwitch2Changed, + }); + + @override + State createState() => _MonitoringCardState(); +} + +class _MonitoringCardState extends State { + final _monitoringService = MonitoringCardService(); + + @override + Widget build(BuildContext context) { + if (widget.userId == null || widget.userId!.isEmpty) { + return _buildCard(PhaseDisplayUtils.vegetatif); + } + + return StreamBuilder( + stream: _monitoringService.growthPhaseStream(widget.userId), + builder: (context, snapshot) { + final phase = snapshot.data ?? PhaseDisplayUtils.vegetatif; + return _buildCard(phase); + }, + ); + } + + Widget _buildCard(PhaseDisplayConfig phase) { + final phaseName = phase.name; + final phaseColor = phase.color; + final statusData = _monitoringService.determineStatus( + title: widget.title, + value: widget.value, + phase: phase, + fallbackStatus: widget.status, + fallbackColor: widget.statusColor, + fallbackDescription: widget.description, + ); + final status = statusData.status; + final statusColor = statusData.color; + final description = statusData.description; + + final isPh = widget.title.toLowerCase().contains('ph'); + final isNutrient = widget.title.toLowerCase().contains('nutrient'); + final hasControls = + widget.switch1Label != null && widget.switch2Label != null; + + return Container( + width: 320, + height: hasControls ? 310 : 280, + margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 12), + padding: const EdgeInsets.fromLTRB(18, 14, 18, 16), + decoration: BoxDecoration( + color: AppColors.white, + borderRadius: const BorderRadius.only( + topLeft: Radius.circular(36), + bottomRight: Radius.circular(36), + ), + boxShadow: const [ + BoxShadow( + color: Colors.black12, + blurRadius: 16, + offset: Offset(0, 8), + ), + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Container( + padding: const EdgeInsets.symmetric( + horizontal: 12, + vertical: 4, + ), + decoration: BoxDecoration( + color: phaseColor.withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: phaseColor, width: 1), + ), + child: Text( + phaseName, + style: TextStyle( + color: phaseColor, + fontWeight: FontWeight.bold, + fontSize: 12, + ), + ), + ), + if (isNutrient || isPh) + Text( + isPh + ? 'Target: 4.0-6.0' + : 'Target: ${phase.nutrientMin}-${phase.nutrientMax} ppm', + style: const TextStyle( + fontSize: 11, + color: AppColors.textSecondary, + fontWeight: FontWeight.w500, + ), + ), + ], + ), + const SizedBox(height: 8), + Row( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + isPh + ? 'Level PH' + : isNutrient + ? 'Kadar Nutrisi' + : widget.title, + style: const TextStyle( + fontWeight: FontWeight.bold, + fontSize: 18, + letterSpacing: 0.5, + ), + ), + Row( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Text( + isPh + ? 'PH ${widget.value.replaceAll(RegExp(r'[^0-9\.]'), '')}' + : widget.value, + style: const TextStyle( + fontSize: 28, + fontWeight: FontWeight.bold, + letterSpacing: 0.5, + ), + ), + if (widget.unit.isNotEmpty && !isPh) + Padding( + padding: const EdgeInsets.only(left: 4.0, bottom: 2.0), + child: Text( + widget.unit, + style: const TextStyle( + fontSize: 16, + color: AppColors.textSecondary, + fontWeight: FontWeight.w500, + ), + ), + ), + ], + ), + ], + ), + const SizedBox(height: 6), + Text( + isPh + ? 'Jaga pH larutan antara 4.0 - 6.0 untuk pertumbuhan optimal.' + : isNutrient + ? 'Pastikan TDS/PPM nutrisi sesuai kebutuhan tanaman.' + : description, + style: const TextStyle(fontSize: 12, color: AppColors.textSecondary), + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + const SizedBox(height: 12), + Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + CustomPaint( + painter: _CircleStatusPainter(color: statusColor), + child: SizedBox( + width: 85, + height: 85, + child: Center( + child: Text( + status, + style: TextStyle( + color: statusColor, + fontWeight: FontWeight.bold, + fontSize: 15, + ), + textAlign: TextAlign.center, + ), + ), + ), + ), + const SizedBox(width: 12), + if (hasControls) + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _buildSwitchRow( + widget.switch1Label!, + widget.switch1Value ?? false, + widget.onSwitch1Changed, + ), + const SizedBox(height: 2), + _buildSwitchRow( + widget.switch2Label!, + widget.switch2Value ?? false, + widget.onSwitch2Changed, + ), + ], + ), + ), + ], + ), + ], + ), + ); + } + + Widget _buildSwitchRow(String label, bool value, Function(bool)? onChanged) { + return Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + label, + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w500, + color: value ? AppColors.secondary : AppColors.black, + ), + ), + Transform.scale( + scale: 0.85, + child: Switch( + value: value, + onChanged: onChanged, + activeThumbColor: AppColors.secondary, + inactiveThumbColor: AppColors.darkGray, + inactiveTrackColor: AppColors.mediumGray, + ), + ), + ], + ); + } +} + +class _CircleStatusPainter extends CustomPainter { + final Color color; + _CircleStatusPainter({required this.color}); + + @override + void paint(Canvas canvas, Size size) { + final paint = Paint() + ..color = color + ..strokeWidth = 5 + ..style = PaintingStyle.stroke; + canvas.drawCircle( + Offset(size.width / 2, size.height / 2), + size.width / 2 - 4, + paint, + ); + } + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +} diff --git a/lib/ui/shared/monitoring_recap_table.dart b/lib/ui/shared/monitoring_recap_table.dart new file mode 100644 index 0000000..867c33b --- /dev/null +++ b/lib/ui/shared/monitoring_recap_table.dart @@ -0,0 +1,141 @@ +import 'package:flutter/material.dart'; +import 'package:mobile_monitoring/core/constants/constants.dart'; + +class MonitoringRecapTable extends StatelessWidget { + final List> data; + final DateTime? startDate; + + const MonitoringRecapTable({ + super.key, + required this.data, + this.startDate, + }); + + @override + Widget build(BuildContext context) { + // Cek apakah ada data + if (data.isEmpty) { + return Center( + child: SizedBox( + width: 320, + child: Card( + elevation: 2, + color: AppColors.white, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + child: Padding( + padding: const EdgeInsets.all(24.0), + child: Column( + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.agriculture, color: AppColors.primary, size: 50), + const SizedBox(height: 16), + const Text( + AppStrings.startPlantingFirst, + textAlign: TextAlign.center, + style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold), + ), + const SizedBox(height: 8), + const Text( + 'Rekap monitoring akan muncul setelah Anda memulai monitoring', + textAlign: TextAlign.center, + style: TextStyle(fontSize: 12, color: Colors.grey), + ), + ], + ), + ), + ), + ), + ); + } + + return Center( + child: SizedBox( + width: 320, + child: Card( + elevation: 2, + color: AppColors.white, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + child: Padding( + padding: const EdgeInsets.all(12.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Rekap Monitoring 7 Hari Terakhir', + style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16, color: AppColors.black), + ), + const SizedBox(height: 8), + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Container( + constraints: const BoxConstraints(minWidth: 500), + child: Table( + columnWidths: const { + 0: FlexColumnWidth(1.2), + 1: FlexColumnWidth(1.1), + 2: FlexColumnWidth(1.1), + 3: FlexColumnWidth(1.1), + }, + border: TableBorder(horizontalInside: BorderSide(color: AppColors.borderLight, width: 1)), + children: [ + TableRow( + decoration: const BoxDecoration(color: AppColors.lightGray), + children: [ + _headerCell('Hari'), + _headerCell('Pagi'), + _headerCell('Sore'), + _headerCell('Malam'), + ], + ), + ...data.map((row) => TableRow( + children: [ + _bodyCell(row['day'], isBold: true), + _bodyCell(row['morning']), + _bodyCell(row['afternoon']), + _bodyCell(row['night']), + ], + )) + ], + ), + ), + ), + ], + ), + ), + ), + ), + ); + } + // Widget untuk header cell + static Widget _headerCell(String text) { + return Container( + padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 8), + alignment: Alignment.center, + child: Text( + text, + style: const TextStyle( + fontWeight: FontWeight.bold, + color: AppColors.textPrimary, + fontSize: 14, + ), + ), + ); + } + + // Widget untuk body cell + static Widget _bodyCell(dynamic text, {bool isBold = false}) { + return Container( + padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 8), + alignment: Alignment.center, + child: Text( + text != null ? text.toString() : '-', + style: TextStyle( + fontWeight: isBold ? FontWeight.w600 : FontWeight.normal, + color: AppColors.textPrimary, + fontSize: 13, + ), + ), + ); + } +} diff --git a/lib/ui/shared/profile_form.dart b/lib/ui/shared/profile_form.dart new file mode 100644 index 0000000..fd13de1 --- /dev/null +++ b/lib/ui/shared/profile_form.dart @@ -0,0 +1,85 @@ +import 'package:flutter/material.dart'; +import 'package:mobile_monitoring/core/constants/strings.dart'; +import 'package:mobile_monitoring/ui/shared/components/components.dart'; + +class ProfileForm extends StatefulWidget { + final TextEditingController nameController; + final bool isLoading; + final String? userEmail; + final VoidCallback onUpdate; + + const ProfileForm({ + super.key, + required this.nameController, + required this.isLoading, + required this.userEmail, + required this.onUpdate, + }); + + @override + State createState() => _ProfileFormState(); +} + +class _ProfileFormState extends State { + final _formKey = GlobalKey(); + + @override + void dispose() { + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return CustomCard( + elevation: 2, + borderRadius: 12, + padding: const EdgeInsets.all(16), + child: Form( + key: _formKey, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Informasi Akun', + style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), + ), + const SizedBox(height: 16), + CustomTextField( + controller: widget.nameController, + labelText: AppStrings.fullName, + prefixIcon: Icons.person, + validator: (value) { + if (value == null || value.isEmpty) { + return 'Nama tidak boleh kosong'; + } + return null; + }, + ), + const SizedBox(height: 16), + TextFormField( + initialValue: widget.userEmail ?? '', + decoration: const InputDecoration( + labelText: AppStrings.email, + prefixIcon: Icon(Icons.email), + ), + enabled: false, + ), + const SizedBox(height: 24), + CustomButton( + text: 'Perbarui Profile', + onPressed: widget.isLoading + ? null + : () { + if (_formKey.currentState!.validate()) { + widget.onUpdate(); + } + }, + isLoading: widget.isLoading, + width: double.infinity, + ), + ], + ), + ), + ); + } +} diff --git a/lib/ui/shared/profile_header.dart b/lib/ui/shared/profile_header.dart new file mode 100644 index 0000000..b9f194d --- /dev/null +++ b/lib/ui/shared/profile_header.dart @@ -0,0 +1,120 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:mobile_monitoring/core/constants/constants.dart'; + +class ProfileHeader extends StatelessWidget { + final String? displayName; + final String? email; + final File? selectedImage; + final String? photoUrl; + final VoidCallback onCameraPressed; + + const ProfileHeader({ + super.key, + required this.displayName, + required this.email, + required this.onCameraPressed, + this.selectedImage, + this.photoUrl, + }); + + String _getInitials(String? name) { + if (name == null || name.isEmpty) return 'U'; + final parts = name.trim().split(' '); + if (parts.length >= 2) { + return '${parts[0][0]}${parts[1][0]}'.toUpperCase(); + } + return name[0].toUpperCase(); + } + + ImageProvider? _buildImageProvider() { + if (selectedImage != null) { + return FileImage(selectedImage!); + } + if (photoUrl == null || photoUrl!.isEmpty) { + return null; + } + if (photoUrl!.startsWith('http://') || photoUrl!.startsWith('https://')) { + return NetworkImage(photoUrl!); + } + return FileImage(File(photoUrl!)); + } + + @override + Widget build(BuildContext context) { + final avatarProvider = _buildImageProvider(); + + return Container( + width: double.infinity, + decoration: const BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [AppColors.secondaryLight, AppColors.secondaryDark], + ), + ), + padding: const EdgeInsets.symmetric(vertical: 40), + child: Column( + children: [ + // Profile Avatar + Stack( + children: [ + CircleAvatar( + radius: 60, + backgroundColor: AppColors.white, + child: CircleAvatar( + radius: 55, + backgroundColor: AppColors.secondaryLight, + backgroundImage: avatarProvider, + child: avatarProvider == null + ? Text( + _getInitials(displayName), + style: const TextStyle( + fontWeight: FontWeight.bold, + color: AppColors.white, + ), + ) + : null, + ), + ), + Positioned( + bottom: 0, + right: 0, + child: Container( + decoration: BoxDecoration( + color: AppColors.primaryDark, + shape: BoxShape.circle, + border: Border.all(color: AppColors.white, width: 3), + ), + child: IconButton( + icon: const Icon(Icons.camera_alt, size: 20), + color: AppColors.white, + onPressed: onCameraPressed, + ), + ), + ), + ], + ), + const SizedBox(height: 16), + Text( + displayName ?? 'Nama Pengguna', + style: const TextStyle( + fontSize: 24, + fontWeight: FontWeight.bold, + color: Colors.white, + ), + ), + const SizedBox(height: 4), + Text( + email ?? '', + style: TextStyle( + fontSize: 16, + color: Colors.white.withValues(alpha: 0.9), + ), + ), + ], + ), + ); + } +} diff --git a/lib/ui/shared/register_form.dart b/lib/ui/shared/register_form.dart new file mode 100644 index 0000000..1b4079f --- /dev/null +++ b/lib/ui/shared/register_form.dart @@ -0,0 +1,144 @@ +import 'package:flutter/material.dart'; +import 'package:mobile_monitoring/ui/shared/components/components.dart'; +import 'package:mobile_monitoring/core/constants/strings.dart'; + +class RegisterForm extends StatefulWidget { + final TextEditingController nameController; + final TextEditingController emailController; + final TextEditingController passwordController; + final TextEditingController confirmPasswordController; + final GlobalKey formKey; + final VoidCallback onRegister; + final VoidCallback onLoginTap; + final bool isLoading; + + const RegisterForm({ + super.key, + required this.nameController, + required this.emailController, + required this.passwordController, + required this.confirmPasswordController, + required this.formKey, + required this.onRegister, + required this.onLoginTap, + this.isLoading = false, + }); + + @override + State createState() => _RegisterFormState(); +} + +class _RegisterFormState extends State { + @override + Widget build(BuildContext context) { + return CustomCard( + padding: const EdgeInsets.all(24), + elevation: 5, + borderRadius: 20, + child: Form( + key: widget.formKey, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const Text( + AppStrings.register, + style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold), + textAlign: TextAlign.center, + ), + const SizedBox(height: 24), + + // Name Field + CustomTextField( + controller: widget.nameController, + labelText: AppStrings.fullName, + prefixIcon: Icons.person, + validator: (value) { + if (value == null || value.isEmpty) { + return 'Nama tidak boleh kosong'; + } + return null; + }, + ), + const SizedBox(height: 16), + + // Email Field + CustomTextField( + controller: widget.emailController, + keyboardType: TextInputType.emailAddress, + labelText: AppStrings.email, + prefixIcon: Icons.email, + validator: (value) { + if (value == null || value.isEmpty) { + return 'Email tidak boleh kosong'; + } + if (!value.contains('@')) { + return AppStrings.invalidEmail; + } + return null; + }, + ), + const SizedBox(height: 16), + + // Password Field + CustomTextField( + controller: widget.passwordController, + obscureText: true, + showPasswordToggle: true, + labelText: AppStrings.password, + prefixIcon: Icons.lock, + validator: (value) { + if (value == null || value.isEmpty) { + return 'Password tidak boleh kosong'; + } + if (value.length < 6) { + return AppStrings.passwordTooShort; + } + return null; + }, + ), + const SizedBox(height: 16), + + // Confirm Password Field + CustomTextField( + controller: widget.confirmPasswordController, + obscureText: true, + showPasswordToggle: true, + labelText: AppStrings.confirmPassword, + prefixIcon: Icons.lock_outline, + validator: (value) { + if (value == null || value.isEmpty) { + return 'Konfirmasi password tidak boleh kosong'; + } + return null; + }, + ), + const SizedBox(height: 24), + + // Register Button + CustomButton( + text: AppStrings.signUp, + onPressed: widget.isLoading ? null : widget.onRegister, + isLoading: widget.isLoading, + width: double.infinity, + ), + const SizedBox(height: 16), + + // Login Link + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text(AppStrings.alreadyHaveAccount), + CustomButton( + text: AppStrings.signIn, + type: ButtonType.text, + size: ButtonSize.small, + onPressed: widget.onLoginTap, + ), + ], + ), + ], + ), + ), + ); + } +} diff --git a/lib/ui/shared/shared.dart b/lib/ui/shared/shared.dart new file mode 100644 index 0000000..778ed98 --- /dev/null +++ b/lib/ui/shared/shared.dart @@ -0,0 +1,20 @@ +// Export all basic UI components first +export 'components/components.dart'; + +// Export semua shared widgets dari UI layer +export 'account_actions_card.dart'; +export 'auth_background.dart'; +export 'bottom_navbar.dart'; +export 'branding_header.dart'; +export 'change_password_dialog.dart'; +export 'graph_widget.dart'; +export 'growth_phase_card.dart'; +export 'home_header.dart'; +export 'login_form.dart'; +export 'monitoring_card.dart'; +export 'monitoring_recap_table.dart'; +export 'profile_form.dart'; +export 'profile_header.dart'; +export 'register_form.dart'; +export 'tips_card.dart'; +export 'weekly_stats_card.dart'; diff --git a/lib/ui/shared/tips_card.dart b/lib/ui/shared/tips_card.dart new file mode 100644 index 0000000..3595fb3 --- /dev/null +++ b/lib/ui/shared/tips_card.dart @@ -0,0 +1,22 @@ +import 'package:flutter/material.dart'; + +class TipsCard extends StatelessWidget { + const TipsCard({super.key}); + + @override + Widget build(BuildContext context) { + return Card( + color: Colors.blue[50], + margin: const EdgeInsets.symmetric(horizontal: 16), + child: const Padding( + padding: EdgeInsets.all(16.0), + child: Text( + '• Jaga pH larutan antara 4.0 - 6.0\n' + '• Pastikan TDS/PPM sesuai kebutuhan tanaman\n' + '• Cek sensor secara berkala', + style: TextStyle(fontSize: 14, color: Colors.black87), + ), + ), + ); + } +} diff --git a/lib/ui/shared/weekly_stats_card.dart b/lib/ui/shared/weekly_stats_card.dart new file mode 100644 index 0000000..5eb0664 --- /dev/null +++ b/lib/ui/shared/weekly_stats_card.dart @@ -0,0 +1,231 @@ +import 'package:flutter/material.dart'; +import 'package:mobile_monitoring/core/constants/constants.dart'; +import 'package:mobile_monitoring/ui/widgets/graph_component_service.dart'; + +class WeeklyStatsCard extends StatelessWidget { + final String? userId; + + const WeeklyStatsCard({super.key, this.userId}); + + @override + Widget build(BuildContext context) { + final graphService = GraphComponentService(); + + return Container( + width: 320, + padding: const EdgeInsets.all(18), + decoration: BoxDecoration( + color: AppColors.white, + borderRadius: BorderRadius.circular(30), + boxShadow: [ + BoxShadow( + color: AppColors.darkGray.withValues(alpha: 0.08), + spreadRadius: 2, + blurRadius: 10, + ), + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Statistik Mingguan pH', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 16, + color: Color.fromARGB(255, 0, 0, 0), + ), + ), + const SizedBox(height: 12), + StreamBuilder>>( + stream: graphService.historyStream(limit: 7, userId: userId), + builder: (context, snapshot) { + if (snapshot.hasError) { + final isAuthError = graphService.isAuthError(snapshot.error!); + + if (isAuthError) { + return SizedBox( + height: 150, + child: Center( + child: Padding( + padding: const EdgeInsets.all(8.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + Icons.error_outline, + color: AppColors.error, + size: 32, + ), + const SizedBox(height: 8), + const Text( + AppStrings.pleaseLogin, + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + ), + ), + ], + ), + ), + ), + ); + } + } + + if (snapshot.connectionState == ConnectionState.waiting) { + return const SizedBox( + height: 150, + child: Center( + child: CircularProgressIndicator(strokeWidth: 2), + ), + ); + } + + final docs = snapshot.data ?? []; + if (docs.isEmpty) { + return SizedBox( + height: 150, + child: Center( + child: Padding( + padding: const EdgeInsets.all(8.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + Icons.agriculture, + color: AppColors.primary, + size: 32, + ), + const SizedBox(height: 8), + const Text( + AppStrings.startPlantingFirst, + textAlign: TextAlign.center, + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + ), + ), + ], + ), + ), + ), + ); + } + + final statsResult = graphService.calculateWeeklyStats(docs); + if (!statsResult.success || statsResult.data == null) { + return const SizedBox( + height: 150, + child: Center( + child: Text( + AppStrings.noDataAvailable, + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + ), + ), + ), + ); + } + + final stats = statsResult.data!; + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: [ + _StatBox( + label: 'Minimum', + value: stats.minPh.toStringAsFixed(1), + color: AppColors.primary, + ), + _StatBox( + label: 'Maksimum', + value: stats.maxPh.toStringAsFixed(1), + color: AppColors.primary, + ), + _StatBox( + label: 'Rata-rata', + value: stats.avgPh.toStringAsFixed(1), + color: AppColors.primary, + ), + ], + ), + const SizedBox(height: 24), + const Text( + 'Statistik Mingguan Nutrisi (TDS)', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 16, + color: Color.fromARGB(255, 0, 0, 0), + ), + ), + const SizedBox(height: 12), + Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: [ + _StatBox( + label: 'Minimum', + value: stats.minTds.toStringAsFixed(0), + color: AppColors.primary, + ), + _StatBox( + label: 'Maksimum', + value: stats.maxTds.toStringAsFixed(0), + color: AppColors.primary, + ), + _StatBox( + label: 'Rata-rata', + value: stats.avgTds.toStringAsFixed(0), + color: AppColors.primary, + ), + ], + ), + ], + ); + }, + ), + ], + ), + ); + } +} + +class _StatBox extends StatelessWidget { + final String label; + final String value; + final Color color; + const _StatBox({ + required this.label, + required this.value, + required this.color, + }); + + @override + Widget build(BuildContext context) { + return Column( + children: [ + Container( + padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 18), + decoration: BoxDecoration( + color: color.withValues(alpha: 0.15), + borderRadius: BorderRadius.circular(12), + ), + child: Text( + value, + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 18, + color: color, + ), + ), + ), + const SizedBox(height: 6), + Text(label, style: TextStyle(fontSize: 13, color: color)), + ], + ); + } +} diff --git a/lib/ui/ui.dart b/lib/ui/ui.dart new file mode 100644 index 0000000..89da97b --- /dev/null +++ b/lib/ui/ui.dart @@ -0,0 +1,4 @@ +// Export semua file dari UI layer +export 'pages/pages.dart'; +export 'shared/shared.dart'; +export 'widgets/widgets.dart'; diff --git a/lib/ui/widgets/graph_component_service.dart b/lib/ui/widgets/graph_component_service.dart new file mode 100644 index 0000000..c69b6ba --- /dev/null +++ b/lib/ui/widgets/graph_component_service.dart @@ -0,0 +1,287 @@ +import 'package:cloud_firestore/cloud_firestore.dart'; +import 'package:mobile_monitoring/data/services/hidroponik_data_service.dart'; +import 'package:mobile_monitoring/data/models/service_result.dart'; +import 'package:mobile_monitoring/data/services/planting_cycles_service.dart'; +import 'package:mobile_monitoring/core/utils/cycle_phase_utils.dart'; + +class GraphPreparedData { + final List dayLabels; + final List phValues; + final List nutrientValues; + + GraphPreparedData({ + required this.dayLabels, + required this.phValues, + required this.nutrientValues, + }); +} + +class WeeklyStatsData { + final double minPh; + final double maxPh; + final double avgPh; + final double minTds; + final double maxTds; + final double avgTds; + + WeeklyStatsData({ + required this.minPh, + required this.maxPh, + required this.avgPh, + required this.minTds, + required this.maxTds, + required this.avgTds, + }); +} + +class GraphComponentService { + final HidroponikDataService _dataService; + final PlantingCyclesService _cyclesService; + + GraphComponentService({ + HidroponikDataService? dataService, + PlantingCyclesService? cyclesService, + }) : _dataService = dataService ?? HidroponikDataService(), + _cyclesService = cyclesService ?? PlantingCyclesService(); + + Stream?> cycleStream(String userId) { + if (userId.isEmpty) { + return Stream.value(null); + } + return _cyclesService.getActiveCycleStream(userId: userId); + } + + Stream>> historyStream({ + required String? userId, + int limit = 500, + }) { + return _dataService.historyStream(limit: limit, userId: userId); + } + + DateTime? extractStartDate(Map? cycleData) { + return CyclePhaseUtils.extractStartDate(cycleData); + } + + bool isAuthError(Object error) { + return error.toString().contains('terautentikasi'); + } + + ServiceResult prepareGraphData( + List> docs, + DateTime? startDate, + ) { + if (docs.isEmpty) { + return ServiceResult.failure( + message: 'Belum ada data monitoring', + errorCode: 'no_data', + ); + } + + final validDocs = >[]; + for (final doc in docs) { + final timestamp = doc['timestamp']; + DateTime? dt; + if (timestamp is Timestamp) { + dt = timestamp.toDate(); + } else if (timestamp is DateTime) { + dt = timestamp; + } + if (dt != null) validDocs.add({...doc, 'datetime': dt}); + } + + if (validDocs.isEmpty) { + return ServiceResult.failure( + message: 'Belum ada data valid untuk ditampilkan', + errorCode: 'invalid_data', + ); + } + + validDocs.sort( + (a, b) => + (a['datetime'] as DateTime).compareTo(b['datetime'] as DateTime), + ); + + final now = DateTime.now(); + final filterEndDate = DateTime(now.year, now.month, now.day, 23, 59, 59); + + DateTime filterStartDate; + if (startDate != null) { + final plantingStart = DateTime( + startDate.year, + startDate.month, + startDate.day, + ); + final sevenDaysAgo = now.subtract(const Duration(days: 6)); + filterStartDate = plantingStart.isBefore(sevenDaysAgo) + ? sevenDaysAgo + : plantingStart; + } else { + filterStartDate = now.subtract(const Duration(days: 6)); + } + + final filteredDocs = validDocs.where((doc) { + final dt = doc['datetime'] as DateTime; + return dt.compareTo(filterStartDate) >= 0 && + dt.compareTo(filterEndDate) <= 0; + }).toList(); + + if (filteredDocs.isEmpty) { + return ServiceResult.failure( + message: 'Belum ada data dalam rentang waktu grafik', + errorCode: 'no_data_in_range', + ); + } + + final dayCount = filterEndDate.difference(filterStartDate).inDays + 1; + final buckets = List.generate(dayCount, (_) => _DailyBucket()); + + for (final doc in filteredDocs) { + final dt = doc['datetime'] as DateTime; + final phVal = (doc['pH_value'] as num?)?.toDouble() ?? 0.0; + final nutVal = (doc['nutrient_level'] as num?)?.toDouble() ?? 0.0; + + final dayIndex = dt.difference(filterStartDate).inDays; + if (dayIndex >= 0 && dayIndex < dayCount) { + final slotIndex = _slotIndexForHour(dt.hour); + buckets[dayIndex].add( + slotIndex: slotIndex, + ph: phVal, + nutrient: nutVal, + ); + } + } + + if (!buckets.any((b) => b.hasData)) { + return ServiceResult.failure( + message: 'Belum ada data agregat yang bisa ditampilkan', + errorCode: 'no_aggregate_data', + ); + } + + const dayNames = ['Sen', 'Sel', 'Rab', 'Kam', 'Jum', 'Sab', 'Min']; + final dayLabels = []; + for (var i = 0; i < dayCount; i++) { + final dayDate = filterStartDate.add(Duration(days: i)); + dayLabels.add( + '${dayNames[dayDate.weekday - 1]}\n${dayDate.day}/${dayDate.month}', + ); + } + + final phValues = List.generate(dayCount, (i) => buckets[i].phAverage); + final nutrientValues = List.generate( + dayCount, + (i) => buckets[i].nutrientAverage, + ); + + return ServiceResult.success( + message: 'Data grafik berhasil diproses', + data: GraphPreparedData( + dayLabels: dayLabels, + phValues: phValues, + nutrientValues: nutrientValues, + ), + ); + } + + ServiceResult calculateWeeklyStats( + List> docs, + ) { + if (docs.isEmpty) { + return ServiceResult.failure( + message: 'Belum ada data statistik', + errorCode: 'no_data', + ); + } + + final phValues = []; + final tdsValues = []; + + for (final data in docs) { + phValues.add((data['pH_value'] as num?)?.toDouble() ?? 0.0); + tdsValues.add((data['nutrient_level'] as num?)?.toDouble() ?? 0.0); + } + + if (phValues.isEmpty || tdsValues.isEmpty) { + return ServiceResult.failure( + message: 'Data statistik tidak valid', + errorCode: 'invalid_data', + ); + } + + final minPh = phValues.reduce((a, b) => a < b ? a : b); + final maxPh = phValues.reduce((a, b) => a > b ? a : b); + final avgPh = phValues.reduce((a, b) => a + b) / phValues.length; + + final minTds = tdsValues.reduce((a, b) => a < b ? a : b); + final maxTds = tdsValues.reduce((a, b) => a > b ? a : b); + final avgTds = tdsValues.reduce((a, b) => a + b) / tdsValues.length; + + return ServiceResult.success( + message: 'Statistik mingguan berhasil dihitung', + data: WeeklyStatsData( + minPh: minPh, + maxPh: maxPh, + avgPh: avgPh, + minTds: minTds, + maxTds: maxTds, + avgTds: avgTds, + ), + ); + } + + int _slotIndexForHour(int hour) { + if (hour >= 5 && hour < 12) return 0; + if (hour >= 12 && hour < 18) return 1; + return 2; + } +} + +class _DailyBucket { + final _slots = List.generate(3, (_) => _DailySlot()); + + void add({required int slotIndex, double? ph, double? nutrient}) { + _slots[slotIndex].add(ph: ph, nutrient: nutrient); + } + + bool get hasData => _slots.any((slot) => slot.hasData); + + double get phAverage { + final slotAverages = _slots + .where((s) => s.phCount > 0) + .map((s) => s.phSum / s.phCount) + .toList(); + return slotAverages.isEmpty + ? 0 + : slotAverages.reduce((a, b) => a + b) / slotAverages.length; + } + + double get nutrientAverage { + final slotAverages = _slots + .where((s) => s.nutrientCount > 0) + .map((s) => s.nutrientSum / s.nutrientCount) + .toList(); + return slotAverages.isEmpty + ? 0 + : slotAverages.reduce((a, b) => a + b) / slotAverages.length; + } +} + +class _DailySlot { + double phSum = 0; + double nutrientSum = 0; + int phCount = 0; + int nutrientCount = 0; + + void add({double? ph, double? nutrient}) { + if (ph != null) { + phSum += ph; + phCount++; + } + if (nutrient != null) { + nutrientSum += nutrient; + nutrientCount++; + } + } + + bool get hasData => phCount > 0 || nutrientCount > 0; +} diff --git a/lib/ui/widgets/growth_phase_service.dart b/lib/ui/widgets/growth_phase_service.dart new file mode 100644 index 0000000..990b5b2 --- /dev/null +++ b/lib/ui/widgets/growth_phase_service.dart @@ -0,0 +1,188 @@ +import 'package:cloud_firestore/cloud_firestore.dart'; +import 'package:firebase_auth/firebase_auth.dart'; +import 'package:flutter/material.dart'; +import 'package:mobile_monitoring/data/services/planting_cycles_service.dart'; +import 'package:mobile_monitoring/data/models/service_result.dart'; +import 'package:mobile_monitoring/core/utils/cycle_phase_utils.dart'; +import 'package:mobile_monitoring/core/utils/phase_display_utils.dart'; + +class GrowthPhaseService { + final PlantingCyclesService _cyclesService; + final FirebaseFirestore _firestore; + final FirebaseAuth _auth; + + GrowthPhaseService({ + PlantingCyclesService? cyclesService, + FirebaseFirestore? firestore, + FirebaseAuth? auth, + }) : _cyclesService = cyclesService ?? PlantingCyclesService(), + _firestore = firestore ?? FirebaseFirestore.instance, + _auth = auth ?? FirebaseAuth.instance; + + String getCurrentUserId() => _auth.currentUser?.uid ?? ''; + + User? getCurrentUser() => _auth.currentUser; + + Stream?> activeCycleStream(String userId) { + if (userId.isEmpty) { + return Stream.value(null); + } + + return _cyclesService.getActiveCycleStream(userId: userId); + } + + DateTime? extractStartDate(Map? cycleData) { + return CyclePhaseUtils.extractStartDate(cycleData); + } + + // Calculate phase name based on days since planting + String calculateCurrentPhase(int days) { + return CyclePhaseUtils.calculateDisplayPhase(days); + } + + // Get phase color + Color getPhaseColor(String phase) { + return PhaseDisplayUtils.fromName(phase).color; + } + + // Apply alpha to a color + Color applyAlpha(Color color, double opacity) { + return color.withValues(alpha: (color.a * opacity).clamp(0.0, 1.0)); + } + + // Format date for display (e.g., "5 Mei 2024") + String formatDate(DateTime date) { + return CyclePhaseUtils.formatIndonesianDate(date); + } + + // Get phase data (duration, progress) for a given days count + Map getPhaseData(int daysSincePlanting) { + final progressData = PhaseDisplayUtils.progressData(daysSincePlanting); + return { + 'day': progressData.dayInPhase, + 'duration': progressData.phaseDuration, + 'progress': progressData.progress, + }; + } + + Future> savePlantingDate({ + required String userId, + required DateTime plantingDate, + }) async { + if (userId.isEmpty) { + return ServiceResult.failure( + message: 'User tidak terautentikasi', + errorCode: 'unauthenticated', + ); + } + + try { + final days = DateTime.now().difference(plantingDate).inDays; + final phase = calculateCurrentPhase(days); + + await _cyclesService.addCycle(userId: userId, startDate: plantingDate); + await _createPhaseSnapshot( + userId: userId, + phase: phase, + daysSincePlanting: days, + ); + + return ServiceResult.success(message: 'Tanggal tanam disimpan'); + } catch (e) { + return ServiceResult.failure( + message: 'Gagal menyimpan tanggal tanam: $e', + errorCode: 'save_cycle_failed', + ); + } + } + + Future> resetCycle(String userId) async { + if (userId.isEmpty) { + return ServiceResult.failure( + message: 'User tidak terautentikasi', + errorCode: 'unauthenticated', + ); + } + + try { + await _cyclesService.deleteCycle(userId: userId); + return ServiceResult.success(message: 'Siklus direset'); + } catch (e) { + return ServiceResult.failure( + message: 'Gagal reset siklus: $e', + errorCode: 'reset_failed', + ); + } + } + + Future> markHarvest(String userId) async { + if (userId.isEmpty) { + return ServiceResult.failure( + message: 'User tidak terautentikasi', + errorCode: 'unauthenticated', + ); + } + + try { + // Hitung total hari siklus sebelum menghapus + final daysSincePlanting = await _cyclesService + .calculateCycleDaysBeforeDelete(userId: userId); + + // Catat snapshot panen untuk historikal + await _createPhaseSnapshot( + userId: userId, + phase: 'Panen', + daysSincePlanting: daysSincePlanting, + ); + + // Hapus siklus aktif setelah panen dicatat + await _cyclesService.deleteCycle(userId: userId); + + return ServiceResult.success(message: 'Panen dicatat, siklus selesai'); + } catch (e) { + return ServiceResult.failure( + message: 'Gagal mencatat panen: $e', + errorCode: 'harvest_failed', + ); + } + } + + Future updatePhaseIfChanged({ + required String userId, + required String currentPhaseInDb, + required String calculatedPhase, + required int days, + required DateTime startDate, + }) async { + if (currentPhaseInDb == calculatedPhase) return; + + await _cyclesService.updateCycleProgress( + userId: userId, + startDate: startDate, + ); + await _createPhaseSnapshot( + userId: userId, + phase: calculatedPhase, + daysSincePlanting: days, + ); + } + + Future _createPhaseSnapshot({ + required String userId, + required String phase, + int? daysSincePlanting, + }) async { + await _firestore.collection('hidroponik_data').add({ + 'user_id': userId, + 'growth_phase': phase, + if (daysSincePlanting != null) 'days_since_planting': daysSincePlanting, + 'pH_value': 0.0, + 'nutrient_level': 0.0, + 'pump_ph_up_status': false, + 'pump_ph_down_status': false, + 'pump_nutrient_status': false, + 'pump_water_status': false, + 'timestamp': FieldValue.serverTimestamp(), + }); + } +} diff --git a/lib/ui/widgets/monitoring_card_service.dart b/lib/ui/widgets/monitoring_card_service.dart new file mode 100644 index 0000000..6f50dee --- /dev/null +++ b/lib/ui/widgets/monitoring_card_service.dart @@ -0,0 +1,111 @@ +import 'package:flutter/material.dart'; +import 'package:mobile_monitoring/data/services/planting_cycles_service.dart'; +import 'package:mobile_monitoring/core/utils/phase_display_utils.dart'; + +class MonitoringStatusData { + final String status; + final Color color; + final String description; + + const MonitoringStatusData({ + required this.status, + required this.color, + required this.description, + }); +} + +class MonitoringCardService { + final PlantingCyclesService _cyclesService; + + static const double _phMin = 4.0; + static const double _phMax = 6.0; + + MonitoringCardService({PlantingCyclesService? cyclesService}) + : _cyclesService = cyclesService ?? PlantingCyclesService(); + + Stream growthPhaseStream(String? userId) { + if (userId == null || userId.isEmpty) { + return Stream.value(PhaseDisplayUtils.vegetatif); + } + + return _cyclesService + .getActiveCycleStream(userId: userId) + .map((data) => _parsePhase(data?['growth_phase'] as String?)); + } + + PhaseDisplayConfig parsePhase(String? phase) => _parsePhase(phase); + + // Get phase display name + String getPhaseName(PhaseDisplayConfig phase) { + return phase.name; + } + + // Get phase color + Color getPhaseColor(PhaseDisplayConfig phase) { + return phase.color; + } + + // Get TDS/nutrient target range for phase + String getTdsRange(PhaseDisplayConfig phase) { + return 'Target: ${phase.nutrientMin}-${phase.nutrientMax} ppm'; + } + + // Determine status (normal/abnormal) based on measurement and phase + MonitoringStatusData determineStatus({ + required String title, + required String value, + required PhaseDisplayConfig phase, + required String fallbackStatus, + required Color fallbackColor, + required String fallbackDescription, + }) { + final titleLower = title.toLowerCase(); + final numValue = + double.tryParse(value.replaceAll(RegExp(r'[^0-9\.]'), '')) ?? 0.0; + + if (titleLower.contains('ph')) { + if (numValue >= _phMin && numValue <= _phMax) { + return const MonitoringStatusData( + status: 'Normal', + color: Color(0xFF4CAF50), + description: 'pH berada dalam rentang ideal', + ); + } else { + return const MonitoringStatusData( + status: 'Abnormal', + color: Color(0xFFF44336), + description: 'pH di luar rentang ideal', + ); + } + } + + if (titleLower.contains('nutrient') || titleLower.contains('tds')) { + final min = phase.nutrientMin; + final max = phase.nutrientMax; + + if (numValue >= min && numValue <= max) { + return MonitoringStatusData( + status: 'Normal', + color: const Color(0xFF4CAF50), + description: 'Kadar nutrisi optimal untuk fase ${phase.name}', + ); + } else { + return const MonitoringStatusData( + status: 'Abnormal', + color: Color(0xFFF44336), + description: 'Kadar nutrisi di luar rentang ideal', + ); + } + } + + return MonitoringStatusData( + status: fallbackStatus, + color: fallbackColor, + description: fallbackDescription, + ); + } + + PhaseDisplayConfig _parsePhase(String? phase) { + return PhaseDisplayUtils.fromName(phase?.toLowerCase() ?? 'vegetatif'); + } +} diff --git a/lib/ui/widgets/widgets.dart b/lib/ui/widgets/widgets.dart new file mode 100644 index 0000000..019a231 --- /dev/null +++ b/lib/ui/widgets/widgets.dart @@ -0,0 +1,4 @@ +// Export semua widget services/logic dari UI layer +export 'graph_component_service.dart'; +export 'growth_phase_service.dart'; +export 'monitoring_card_service.dart'; diff --git a/linux/.gitignore b/linux/.gitignore new file mode 100644 index 0000000..d3896c9 --- /dev/null +++ b/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/linux/CMakeLists.txt b/linux/CMakeLists.txt new file mode 100644 index 0000000..b643354 --- /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 "mobile_monitoring") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "com.example.mobile_monitoring") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Load bundled libraries from the lib/ directory relative to the binary. +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Root filesystem for cross-building. +if(FLUTTER_TARGET_PLATFORM_SYSROOT) + set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +endif() + +# Define build configuration options. +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") +endif() + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_14) + target_compile_options(${TARGET} PRIVATE -Wall -Werror) + target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) + +# Only the install-generated bundle's copy of the executable will launch +# correctly, since the resources must in the right relative locations. To avoid +# people trying to run the unbundled copy, put it in a subdirectory instead of +# the default top-level location. +set_target_properties(${BINARY_NAME} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" +) + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +# Start with a clean build bundle directory every time. +install(CODE " + file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") + " COMPONENT Runtime) + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) + install(FILES "${bundled_library}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endforeach(bundled_library) + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/linux/flutter/CMakeLists.txt b/linux/flutter/CMakeLists.txt new file mode 100644 index 0000000..d5bd016 --- /dev/null +++ b/linux/flutter/CMakeLists.txt @@ -0,0 +1,88 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.10) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) +pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) +pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) + +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "fl_basic_message_channel.h" + "fl_binary_codec.h" + "fl_binary_messenger.h" + "fl_dart_project.h" + "fl_engine.h" + "fl_json_message_codec.h" + "fl_json_method_codec.h" + "fl_message_codec.h" + "fl_method_call.h" + "fl_method_channel.h" + "fl_method_codec.h" + "fl_method_response.h" + "fl_plugin_registrar.h" + "fl_plugin_registry.h" + "fl_standard_message_codec.h" + "fl_standard_method_codec.h" + "fl_string_codec.h" + "fl_value.h" + "fl_view.h" + "flutter_linux.h" +) +list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +target_link_libraries(flutter INTERFACE + PkgConfig::GTK + PkgConfig::GLIB + PkgConfig::GIO +) +add_dependencies(flutter flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/linux/flutter/generated_plugin_registrant.cc b/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..64a0ece --- /dev/null +++ b/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include + +void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) file_selector_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "FileSelectorPlugin"); + file_selector_plugin_register_with_registrar(file_selector_linux_registrar); +} diff --git a/linux/flutter/generated_plugin_registrant.h b/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..e0f0a47 --- /dev/null +++ b/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/linux/flutter/generated_plugins.cmake b/linux/flutter/generated_plugins.cmake new file mode 100644 index 0000000..2db3c22 --- /dev/null +++ b/linux/flutter/generated_plugins.cmake @@ -0,0 +1,24 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + file_selector_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 0000000..e97dabc --- /dev/null +++ b/linux/runner/CMakeLists.txt @@ -0,0 +1,26 @@ +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} + "main.cc" + "my_application.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the application ID. +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Add dependency libraries. Add any application-specific dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) + +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") diff --git a/linux/runner/main.cc b/linux/runner/main.cc new file mode 100644 index 0000000..e7c5c54 --- /dev/null +++ b/linux/runner/main.cc @@ -0,0 +1,6 @@ +#include "my_application.h" + +int main(int argc, char** argv) { + g_autoptr(MyApplication) app = my_application_new(); + return g_application_run(G_APPLICATION(app), argc, argv); +} diff --git a/linux/runner/my_application.cc b/linux/runner/my_application.cc new file mode 100644 index 0000000..4aceb15 --- /dev/null +++ b/linux/runner/my_application.cc @@ -0,0 +1,144 @@ +#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, "mobile_monitoring"); + 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, "mobile_monitoring"); + } + + 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 0000000..72271d5 --- /dev/null +++ b/linux/runner/my_application.h @@ -0,0 +1,18 @@ +#ifndef FLUTTER_MY_APPLICATION_H_ +#define FLUTTER_MY_APPLICATION_H_ + +#include + +G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION, + GtkApplication) + +/** + * my_application_new: + * + * Creates a new Flutter-based application. + * + * Returns: a new #MyApplication. + */ +MyApplication* my_application_new(); + +#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/macos/.gitignore b/macos/.gitignore new file mode 100644 index 0000000..746adbb --- /dev/null +++ b/macos/.gitignore @@ -0,0 +1,7 @@ +# Flutter-related +**/Flutter/ephemeral/ +**/Pods/ + +# Xcode-related +**/dgph +**/xcuserdata/ diff --git a/macos/Flutter/Flutter-Debug.xcconfig b/macos/Flutter/Flutter-Debug.xcconfig new file mode 100644 index 0000000..c2efd0b --- /dev/null +++ b/macos/Flutter/Flutter-Debug.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/macos/Flutter/Flutter-Release.xcconfig b/macos/Flutter/Flutter-Release.xcconfig new file mode 100644 index 0000000..c2efd0b --- /dev/null +++ b/macos/Flutter/Flutter-Release.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift new file mode 100644 index 0000000..df586ca --- /dev/null +++ b/macos/Flutter/GeneratedPluginRegistrant.swift @@ -0,0 +1,20 @@ +// +// Generated file. Do not edit. +// + +import FlutterMacOS +import Foundation + +import cloud_firestore +import file_selector_macos +import firebase_auth +import firebase_core +import path_provider_foundation + +func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + FLTFirebaseFirestorePlugin.register(with: registry.registrar(forPlugin: "FLTFirebaseFirestorePlugin")) + FileSelectorPlugin.register(with: registry.registrar(forPlugin: "FileSelectorPlugin")) + FLTFirebaseAuthPlugin.register(with: registry.registrar(forPlugin: "FLTFirebaseAuthPlugin")) + FLTFirebaseCorePlugin.register(with: registry.registrar(forPlugin: "FLTFirebaseCorePlugin")) + PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin")) +} diff --git a/macos/Runner.xcodeproj/project.pbxproj b/macos/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..8578551 --- /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 /* mobile_monitoring.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "mobile_monitoring.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 /* mobile_monitoring.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 /* mobile_monitoring.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.mobileMonitoring.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/mobile_monitoring.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/mobile_monitoring"; + }; + 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.mobileMonitoring.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/mobile_monitoring.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/mobile_monitoring"; + }; + 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.mobileMonitoring.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/mobile_monitoring.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/mobile_monitoring"; + }; + 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 0000000..18d9810 --- /dev/null +++ b/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..80be9f9 --- /dev/null +++ b/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,99 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macos/Runner.xcworkspace/contents.xcworkspacedata b/macos/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/macos/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/macos/Runner/AppDelegate.swift b/macos/Runner/AppDelegate.swift new file mode 100644 index 0000000..b3c1761 --- /dev/null +++ b/macos/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import Cocoa +import FlutterMacOS + +@main +class AppDelegate: FlutterAppDelegate { + override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { + return true + } + + override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { + return true + } +} diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..a2ec33f --- /dev/null +++ b/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,68 @@ +{ + "images" : [ + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_16.png", + "scale" : "1x" + }, + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "2x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "1x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_64.png", + "scale" : "2x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_128.png", + "scale" : "1x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "2x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "1x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "2x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "1x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_1024.png", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png new file mode 100644 index 0000000..82b6f9d Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png new file mode 100644 index 0000000..13b35eb Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png new file mode 100644 index 0000000..0a3f5fa Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png new file mode 100644 index 0000000..bdb5722 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png new file mode 100644 index 0000000..f083318 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png new file mode 100644 index 0000000..326c0e7 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png new file mode 100644 index 0000000..2f1632c Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png differ diff --git a/macos/Runner/Base.lproj/MainMenu.xib b/macos/Runner/Base.lproj/MainMenu.xib new file mode 100644 index 0000000..80e867a --- /dev/null +++ b/macos/Runner/Base.lproj/MainMenu.xib @@ -0,0 +1,343 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macos/Runner/Configs/AppInfo.xcconfig b/macos/Runner/Configs/AppInfo.xcconfig new file mode 100644 index 0000000..25fa1df --- /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 = mobile_monitoring + +// The application's bundle identifier +PRODUCT_BUNDLE_IDENTIFIER = com.example.mobileMonitoring + +// The copyright displayed in application information +PRODUCT_COPYRIGHT = Copyright © 2025 com.example. All rights reserved. diff --git a/macos/Runner/Configs/Debug.xcconfig b/macos/Runner/Configs/Debug.xcconfig new file mode 100644 index 0000000..36b0fd9 --- /dev/null +++ b/macos/Runner/Configs/Debug.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Debug.xcconfig" +#include "Warnings.xcconfig" diff --git a/macos/Runner/Configs/Release.xcconfig b/macos/Runner/Configs/Release.xcconfig new file mode 100644 index 0000000..dff4f49 --- /dev/null +++ b/macos/Runner/Configs/Release.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Release.xcconfig" +#include "Warnings.xcconfig" diff --git a/macos/Runner/Configs/Warnings.xcconfig b/macos/Runner/Configs/Warnings.xcconfig new file mode 100644 index 0000000..42bcbf4 --- /dev/null +++ b/macos/Runner/Configs/Warnings.xcconfig @@ -0,0 +1,13 @@ +WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings +GCC_WARN_UNDECLARED_SELECTOR = YES +CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES +CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE +CLANG_WARN__DUPLICATE_METHOD_MATCH = YES +CLANG_WARN_PRAGMA_PACK = YES +CLANG_WARN_STRICT_PROTOTYPES = YES +CLANG_WARN_COMMA = YES +GCC_WARN_STRICT_SELECTOR_MATCH = YES +CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES +CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES +GCC_WARN_SHADOW = YES +CLANG_WARN_UNREACHABLE_CODE = YES diff --git a/macos/Runner/DebugProfile.entitlements b/macos/Runner/DebugProfile.entitlements new file mode 100644 index 0000000..dddb8a3 --- /dev/null +++ b/macos/Runner/DebugProfile.entitlements @@ -0,0 +1,12 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.cs.allow-jit + + com.apple.security.network.server + + + diff --git a/macos/Runner/Info.plist b/macos/Runner/Info.plist new file mode 100644 index 0000000..4789daa --- /dev/null +++ b/macos/Runner/Info.plist @@ -0,0 +1,32 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIconFile + + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSMinimumSystemVersion + $(MACOSX_DEPLOYMENT_TARGET) + NSHumanReadableCopyright + $(PRODUCT_COPYRIGHT) + NSMainNibFile + MainMenu + NSPrincipalClass + NSApplication + + diff --git a/macos/Runner/MainFlutterWindow.swift b/macos/Runner/MainFlutterWindow.swift new file mode 100644 index 0000000..3cc05eb --- /dev/null +++ b/macos/Runner/MainFlutterWindow.swift @@ -0,0 +1,15 @@ +import Cocoa +import FlutterMacOS + +class MainFlutterWindow: NSWindow { + override func awakeFromNib() { + let flutterViewController = FlutterViewController() + let windowFrame = self.frame + self.contentViewController = flutterViewController + self.setFrame(windowFrame, display: true) + + RegisterGeneratedPlugins(registry: flutterViewController) + + super.awakeFromNib() + } +} diff --git a/macos/Runner/Release.entitlements b/macos/Runner/Release.entitlements new file mode 100644 index 0000000..852fa1a --- /dev/null +++ b/macos/Runner/Release.entitlements @@ -0,0 +1,8 @@ + + + + + com.apple.security.app-sandbox + + + diff --git a/macos/RunnerTests/RunnerTests.swift b/macos/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..61f3bd1 --- /dev/null +++ b/macos/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Cocoa +import FlutterMacOS +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/pubspec.lock b/pubspec.lock new file mode 100644 index 0000000..ab2a96a --- /dev/null +++ b/pubspec.lock @@ -0,0 +1,650 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + _flutterfire_internals: + dependency: transitive + description: + name: _flutterfire_internals + sha256: ff0a84a2734d9e1089f8aedd5c0af0061b82fb94e95260d943404e0ef2134b11 + url: "https://pub.dev" + source: hosted + version: "1.3.59" + 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" + 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" + cloud_firestore: + dependency: "direct main" + description: + name: cloud_firestore + sha256: "2d33da4465bdb81b6685c41b535895065adcb16261beb398f5f3bbc623979e9c" + url: "https://pub.dev" + source: hosted + version: "5.6.12" + cloud_firestore_platform_interface: + dependency: transitive + description: + name: cloud_firestore_platform_interface + sha256: "413c4e01895cf9cb3de36fa5c219479e06cd4722876274ace5dfc9f13ab2e39b" + url: "https://pub.dev" + source: hosted + version: "6.6.12" + cloud_firestore_web: + dependency: transitive + description: + name: cloud_firestore_web + sha256: c1e30fc4a0fcedb08723fb4b1f12ee4e56d937cbf9deae1bda43cbb6367bb4cf + url: "https://pub.dev" + source: hosted + version: "4.4.12" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.dev" + source: hosted + version: "1.19.1" + cross_file: + dependency: transitive + description: + name: cross_file + sha256: "28bb3ae56f117b5aec029d702a90f57d285cd975c3c5c281eaca38dbc47c5937" + url: "https://pub.dev" + source: hosted + version: "0.3.5+2" + crypto: + dependency: transitive + description: + name: crypto + sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf + url: "https://pub.dev" + source: hosted + version: "3.0.7" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + sha256: ba631d1c7f7bef6b729a622b7b752645a2d076dba9976925b8f25725a30e1ee6 + url: "https://pub.dev" + source: hosted + version: "1.0.8" + equatable: + dependency: transitive + description: + name: equatable + sha256: "567c64b3cb4cf82397aac55f4f0cbd3ca20d77c6c03bedbc4ceaddc08904aef7" + url: "https://pub.dev" + source: hosted + version: "2.0.7" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "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_selector_linux: + dependency: transitive + description: + name: file_selector_linux + sha256: "2567f398e06ac72dcf2e98a0c95df2a9edd03c2c2e0cacd4780f20cdf56263a0" + url: "https://pub.dev" + source: hosted + version: "0.9.4" + file_selector_macos: + dependency: transitive + description: + name: file_selector_macos + sha256: "5e0bbe9c312416f1787a68259ea1505b52f258c587f12920422671807c4d618a" + url: "https://pub.dev" + source: hosted + version: "0.9.5" + file_selector_platform_interface: + dependency: transitive + description: + name: file_selector_platform_interface + sha256: "35e0bd61ebcdb91a3505813b055b09b79dfdc7d0aee9c09a7ba59ae4bb13dc85" + url: "https://pub.dev" + source: hosted + version: "2.7.0" + file_selector_windows: + dependency: transitive + description: + name: file_selector_windows + sha256: "62197474ae75893a62df75939c777763d39c2bc5f73ce5b88497208bc269abfd" + url: "https://pub.dev" + source: hosted + version: "0.9.3+5" + firebase_auth: + dependency: "direct main" + description: + name: firebase_auth + sha256: "0fed2133bee1369ee1118c1fef27b2ce0d84c54b7819a2b17dada5cfec3b03ff" + url: "https://pub.dev" + source: hosted + version: "5.7.0" + firebase_auth_platform_interface: + dependency: transitive + description: + name: firebase_auth_platform_interface + sha256: "871c9df4ec9a754d1a793f7eb42fa3b94249d464cfb19152ba93e14a5966b386" + url: "https://pub.dev" + source: hosted + version: "7.7.3" + firebase_auth_web: + dependency: transitive + description: + name: firebase_auth_web + sha256: d9ada769c43261fd1b18decf113186e915c921a811bd5014f5ea08f4cf4bc57e + url: "https://pub.dev" + source: hosted + version: "5.15.3" + firebase_core: + dependency: "direct main" + description: + name: firebase_core + sha256: "7be63a3f841fc9663342f7f3a011a42aef6a61066943c90b1c434d79d5c995c5" + url: "https://pub.dev" + source: hosted + version: "3.15.2" + firebase_core_platform_interface: + dependency: transitive + description: + name: firebase_core_platform_interface + sha256: cccb4f572325dc14904c02fcc7db6323ad62ba02536833dddb5c02cac7341c64 + url: "https://pub.dev" + source: hosted + version: "6.0.2" + firebase_core_web: + dependency: transitive + description: + name: firebase_core_web + sha256: "0ed0dc292e8f9ac50992e2394e9d336a0275b6ae400d64163fdf0a8a8b556c37" + url: "https://pub.dev" + source: hosted + version: "2.24.1" + fl_chart: + dependency: "direct main" + description: + name: fl_chart + sha256: d0f0d49112f2f4b192481c16d05b6418bd7820e021e265a3c22db98acf7ed7fb + url: "https://pub.dev" + source: hosted + version: "0.68.0" + 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: "10f13781741a2e3972126fae08393d3c4e01fa4cd7473326b94b72cf594195e7" + url: "https://pub.dev" + source: hosted + version: "0.14.4" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: "5398f14efa795ffb7a33e9b6a08798b26a180edac4ad7db3f231e40f82ce11e1" + url: "https://pub.dev" + source: hosted + version: "5.0.0" + flutter_plugin_android_lifecycle: + dependency: transitive + description: + name: flutter_plugin_android_lifecycle + sha256: ee8068e0e1cd16c4a82714119918efdeed33b3ba7772c54b5d094ab53f9b7fd1 + url: "https://pub.dev" + source: hosted + version: "2.0.33" + 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" + 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: "direct main" + description: + name: image + sha256: "492bd52f6c4fbb6ee41f781ff27765ce5f627910e1e0cbecfa3d9add5562604c" + url: "https://pub.dev" + source: hosted + version: "4.7.2" + image_picker: + dependency: "direct main" + description: + name: image_picker + sha256: "784210112be18ea55f69d7076e2c656a4e24949fa9e76429fe53af0c0f4fa320" + url: "https://pub.dev" + source: hosted + version: "1.2.1" + image_picker_android: + dependency: transitive + description: + name: image_picker_android + sha256: "518a16108529fc18657a3e6dde4a043dc465d16596d20ab2abd49a4cac2e703d" + url: "https://pub.dev" + source: hosted + version: "0.8.13+13" + image_picker_for_web: + dependency: transitive + description: + name: image_picker_for_web + sha256: "66257a3191ab360d23a55c8241c91a6e329d31e94efa7be9cf7a212e65850214" + url: "https://pub.dev" + source: hosted + version: "3.1.1" + image_picker_ios: + dependency: transitive + description: + name: image_picker_ios + sha256: "956c16a42c0c708f914021666ffcd8265dde36e673c9fa68c81f7d085d9774ad" + url: "https://pub.dev" + source: hosted + version: "0.8.13+3" + image_picker_linux: + dependency: transitive + description: + name: image_picker_linux + sha256: "1f81c5f2046b9ab724f85523e4af65be1d47b038160a8c8deed909762c308ed4" + url: "https://pub.dev" + source: hosted + version: "0.2.2" + image_picker_macos: + dependency: transitive + description: + name: image_picker_macos + sha256: "86f0f15a309de7e1a552c12df9ce5b59fe927e71385329355aec4776c6a8ec91" + url: "https://pub.dev" + source: hosted + version: "0.2.2+1" + image_picker_platform_interface: + dependency: transitive + description: + name: image_picker_platform_interface + sha256: "567e056716333a1647c64bb6bd873cff7622233a5c3f694be28a583d4715690c" + url: "https://pub.dev" + source: hosted + version: "2.11.1" + image_picker_windows: + dependency: transitive + description: + name: image_picker_windows + sha256: d248c86554a72b5495a31c56f060cf73a41c7ff541689327b1a7dbccc33adfae + url: "https://pub.dev" + source: hosted + version: "0.2.2" + json_annotation: + dependency: transitive + description: + name: json_annotation + sha256: cb09e7dac6210041fad964ed7fbee004f14258b4eca4040f72d1234062ace4c8 + url: "https://pub.dev" + source: hosted + version: "4.11.0" + 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: c35bb79562d980e9a453fc715854e1ed39e24e7d0297a880ef54e17f9874a9d7 + url: "https://pub.dev" + source: hosted + version: "5.1.1" + matcher: + dependency: transitive + description: + name: matcher + sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2 + url: "https://pub.dev" + source: hosted + version: "0.12.17" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec + url: "https://pub.dev" + source: hosted + version: "0.11.1" + meta: + dependency: transitive + description: + name: meta + sha256: e3641ec5d63ebf0d9b41bd43201a66e3fc79a65db5f61fc181f04cd27aab950c + url: "https://pub.dev" + source: hosted + version: "1.16.0" + mime: + dependency: transitive + description: + name: mime + sha256: "41a20518f0cb1256669420fdba0cd90d21561e560ac240f26ef8322e45bb7ed6" + url: "https://pub.dev" + source: hosted + version: "2.0.0" + path: + dependency: transitive + description: + name: path + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.dev" + source: hosted + version: "1.9.1" + path_provider: + dependency: "direct main" + description: + name: path_provider + sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd" + url: "https://pub.dev" + source: hosted + version: "2.1.5" + path_provider_android: + dependency: transitive + description: + name: path_provider_android + sha256: f2c65e21139ce2c3dad46922be8272bb5963516045659e71bb16e151c93b580e + url: "https://pub.dev" + source: hosted + version: "2.2.22" + path_provider_foundation: + dependency: transitive + description: + name: path_provider_foundation + sha256: "6d13aece7b3f5c5a9731eaf553ff9dcbc2eff41087fd2df587fd0fed9a3eb0c4" + url: "https://pub.dev" + source: hosted + version: "2.5.1" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279 + url: "https://pub.dev" + source: hosted + version: "2.2.1" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 + url: "https://pub.dev" + source: hosted + version: "2.3.0" + 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" + posix: + dependency: transitive + description: + name: posix + sha256: "6323a5b0fa688b6a010df4905a56b00181479e6d10534cecfecede2aa55add61" + url: "https://pub.dev" + source: hosted + version: "6.0.3" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_span: + dependency: transitive + description: + name: source_span + sha256: "254ee5351d6cb365c859e20ee823c3bb479bf4a293c22d17a9f1bf144ce86f7c" + url: "https://pub.dev" + source: hosted + version: "1.10.1" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" + url: "https://pub.dev" + source: hosted + version: "1.12.1" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" + url: "https://pub.dev" + source: hosted + version: "1.4.1" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" + url: "https://pub.dev" + source: hosted + version: "1.2.2" + test_api: + dependency: transitive + description: + name: test_api + sha256: "522f00f556e73044315fa4585ec3270f1808a4b186c936e612cab0b565ff1e00" + url: "https://pub.dev" + source: hosted + version: "0.7.6" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: 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" + 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" +sdks: + dart: ">=3.9.2 <4.0.0" + flutter: ">=3.35.0" diff --git a/pubspec.yaml b/pubspec.yaml new file mode 100644 index 0000000..319b43a --- /dev/null +++ b/pubspec.yaml @@ -0,0 +1,70 @@ +name: mobile_monitoring +description: "HydroNutrify - IoT-based Hydroponic Monitoring Application" +# The following line prevents the package from being accidentally published to +# pub.dev using `flutter pub publish`. This is preferred for private packages. +publish_to: 'none' # Remove this line if you wish to publish to pub.dev + +# The following defines the version and build number for your application. +# A version number is three numbers separated by dots, like 1.2.43 +# followed by an optional build number separated by a +. +# Both the version and the builder number may be overridden in flutter +# build by specifying --build-name and --build-number, respectively. +# In Android, build-name is used as versionName while build-number used as versionCode. +# Read more about Android versioning at https://developer.android.com/studio/publish/versioning +# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion. +# Read more about iOS versioning at +# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html +# In Windows, build-name is used as the major, minor, and patch parts +# of the product and file versions while build-number is used as the build suffix. +version: 1.0.0+1 + +environment: + sdk: ^3.9.2 + +# Dependencies specify other packages that your package needs in order to work. +# To automatically upgrade your package dependencies to the latest versions +# consider running `flutter pub upgrade --major-versions`. Alternatively, +# dependencies can be manually updated by changing the version numbers below to +# the latest version available on pub.dev. To see which dependencies have newer +# versions available, run `flutter pub outdated`. +dependencies: + flutter: + sdk: flutter + fl_chart: ^0.68.0 + cupertino_icons: ^1.0.8 + cloud_firestore: ^5.0.0 + firebase_core: ^3.0.0 + firebase_auth: ^5.0.0 + image_picker: ^1.0.0 + image: ^4.1.0 + path_provider: ^2.1.0 + flutter_dotenv: ^5.1.0 + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_launcher_icons: ^0.14.3 + + # The "flutter_lints" package below contains a set of recommended lints to + # encourage good coding practices. The lint set provided by the package is + # activated in the `analysis_options.yaml` file located at the root of your + # package. See that file for information about deactivating specific lint + # rules and activating additional ones. + flutter_lints: ^5.0.0 + +flutter_launcher_icons: + android: true + ios: true + image_path: "assets/images/app_icon.png" + min_sdk_android: 21 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter packages. +flutter: + uses-material-design: true + assets: + - .env + - assets/images/bg-splashscreen.png + - assets/images/image-removebg-preview.png diff --git a/test/blackbox_equivalence_partition.md b/test/blackbox_equivalence_partition.md new file mode 100644 index 0000000..2f3a3e6 --- /dev/null +++ b/test/blackbox_equivalence_partition.md @@ -0,0 +1,114 @@ +# Blackbox Testing - Equivalence Partitioning + +Dokumen ini berisi test case blackbox berbasis Equivalence Partitioning untuk aplikasi `mobile_monitoring`. + +## Ruang Lingkup +- Login +- Register +- Forgot Password +- Profile Update +- Change Password +- Home Monitoring Section +- Flow Monitoring + Rekap +- Growth Phase +- Graph + +## Aturan Umum Equivalence Partition +- Setiap input dibagi ke kelas ekuivalen `valid` dan `invalid`. +- Satu test case mewakili satu kelas input. +- Fokus pada perilaku output UI (pesan, navigasi, tampilan data), bukan implementasi internal. + +## A. Login + +| ID | Kelas Ekuivalen | Data Uji | Langkah Uji | Expected Result | +|---|---|---|---|---| +| LGN-01 | Valid email + valid password | email: `user@test.com`, pass: `123456` | Isi form login, klik Masuk | Login sukses, navigasi ke Home | +| LGN-02 | Invalid email format | email: `usertest.com`, pass: `123456` | Isi form login, klik Masuk | Validasi gagal, tampil pesan error email | +| LGN-03 | Empty email | email: ``, pass: `123456` | Isi form login, klik Masuk | Validasi gagal, tidak submit | +| LGN-04 | Empty password | email: `user@test.com`, pass: `` | Isi form login, klik Masuk | Validasi gagal, tidak submit | +| LGN-05 | Wrong credential (kelas invalid backend) | email valid, pass salah | Isi form login, klik Masuk | Tetap di login, tampil error dari service | + +## B. Register + +| ID | Kelas Ekuivalen | Data Uji | Langkah Uji | Expected Result | +|---|---|---|---|---| +| REG-01 | Semua field valid | name: `Budi`, email valid, pass `123456`, confirm `123456` | Isi form register, klik Daftar | Register sukses, navigasi ke Home | +| REG-02 | Nama kosong | name: ``, email valid, pass valid | Isi form register, klik Daftar | Validasi gagal, pesan `Nama tidak boleh kosong` | +| REG-03 | Email tidak valid | email: `budi.com` | Isi form register, klik Daftar | Validasi gagal, pesan email tidak valid | +| REG-04 | Password < 6 karakter | pass: `12345`, confirm `12345` | Isi form register, klik Daftar | Validasi gagal, pesan minimal 6 karakter | +| REG-05 | Confirm password tidak sama | pass: `123456`, confirm: `123457` | Isi form register, klik Daftar | Validasi gagal, pesan konfirmasi password | +| REG-06 | Email sudah terdaftar | email existing | Isi form register, klik Daftar | Register gagal, tampil pesan error backend | + +## C. Forgot Password + +| ID | Kelas Ekuivalen | Data Uji | Langkah Uji | Expected Result | +|---|---|---|---|---| +| FGP-01 | Email valid terdaftar | `user@test.com` | Di login, klik lupa password | Tampil notifikasi sukses kirim reset | +| FGP-02 | Email kosong | `` | Klik lupa password tanpa isi email | Tampil error minta isi email | +| FGP-03 | Email format tidak valid | `user.com` | Klik lupa password | Tampil error email tidak valid | +| FGP-04 | Email valid tidak terdaftar | `none@test.com` | Klik lupa password | Tampil error dari auth provider | + +## D. Profile Update + +| ID | Kelas Ekuivalen | Data Uji | Langkah Uji | Expected Result | +|---|---|---|---|---| +| PRF-01 | Nama valid | `Nama Baru` | Buka profile, ubah nama, simpan | Update sukses, snackbar sukses | +| PRF-02 | Nama kosong/whitespace | ` ` | Ubah nama lalu simpan | Update gagal, tampil pesan error | +| PRF-03 | User belum login (invalid precondition) | - | Akses profile saat sesi tidak valid | Muncul error autentikasi / redirect sesuai alur | + +## E. Change Password + +| ID | Kelas Ekuivalen | Data Uji | Langkah Uji | Expected Result | +|---|---|---|---|---| +| CHP-01 | Old password benar + new password valid | old benar, new `abcdef` | Buka dialog, submit | Password berhasil diubah | +| CHP-02 | Old password salah | old salah, new valid | Submit dialog | Gagal, tampil error | +| CHP-03 | New password < 6 karakter | new `12345` | Submit dialog | Validasi gagal, tidak kirim request | +| CHP-04 | Confirm new password mismatch | new `123456`, confirm `123457` | Submit dialog | Validasi gagal, pesan mismatch | + +## F. Home Monitoring Section + +| ID | Kelas Ekuivalen | Data Uji/State | Langkah Uji | Expected Result | +|---|---|---|---|---| +| HOM-01 | Valid user + data tersedia | user login, data sensor ada | Buka Home | Muncul 2 `MonitoringCard` (pH dan Nutrisi) | +| HOM-02 | Valid user + data kosong | user login, koleksi kosong | Buka Home | Section monitoring kosong (tidak crash) | +| HOM-03 | User tidak terautentikasi | userId null/kosong | Buka Home | Stream error ditangani, UI tetap stabil | + +## G. Flow Monitoring + Rekap + +| ID | Kelas Ekuivalen | Data Uji/State | Langkah Uji | Expected Result | +|---|---|---|---|---| +| FLW-01 | Data sensor tersedia | data latest ada | Buka Flow | `MonitoringCard` pH dan Nutrisi tampil | +| FLW-02 | Data sensor tidak ada | latest null | Buka Flow | Bagian card tidak tampil, halaman tetap normal | +| FLW-03 | Histori tersedia | docs histori > 0 | Buka Flow | `MonitoringRecapTable` terisi data | +| FLW-04 | Histori kosong | docs histori = 0 | Buka Flow | `MonitoringRecapTable` tampil state kosong | +| FLW-05 | User tidak login | userId invalid | Buka Flow | Stream error, tidak crash | + +## H. Growth Phase + +| ID | Kelas Ekuivalen | Data Uji/State | Langkah Uji | Expected Result | +|---|---|---|---|---| +| GPH-01 | User login + belum ada siklus | cycle null | Buka Home | `GrowthPhaseCard` tampil tombol `Mulai Tanam` | +| GPH-02 | Set tanggal tanam valid | pilih tanggal 2020..hari ini | Klik `Mulai Tanam` | Data siklus tersimpan, snackbar sukses | +| GPH-03 | User batalkan date picker | cancel picker | Klik `Mulai Tanam` lalu batal | Tidak ada perubahan data | +| GPH-04 | Siklus aktif | start_date ada | Buka Home | Tampil fase aktif, progress, aksi Reset/Panen | +| GPH-05 | Reset siklus dikonfirmasi | pilih `Reset` + konfirmasi | Klik reset | Siklus dihapus/reset, snackbar hasil | +| GPH-06 | Panen pada siklus aktif | klik `Panen` | Klik panen | Status panen ter-update, snackbar hasil | + +## I. Graph + +| ID | Kelas Ekuivalen | Data Uji/State | Langkah Uji | Expected Result | +|---|---|---|---|---| +| GRF-01 | User valid + histori tersedia | docs > 0 | Buka menu Grafik | Muncul grafik pH dan TDS | +| GRF-02 | User valid + histori kosong | docs = 0 | Buka menu Grafik | Tampil state `Belum Memulai Tanam` | +| GRF-03 | User tidak login | userId kosong | Buka menu Grafik | Tampil state `Silakan Login` | +| GRF-04 | Error stream backend | putus koneksi/permission | Buka menu Grafik | Tampil state error + tombol `Coba Lagi` | + +## Prioritas Eksekusi +- P1: LGN-01..05, REG-01..06, FLW-01..05 +- P2: PRF-01..03, CHP-01..04, GRF-01..04 +- P3: GPH-01..06, HOM-01..03 + +## Catatan Eksekusi +- Gunakan 2 akun: `akun_valid` dan `akun_tidak_valid`. +- Siapkan 3 kondisi data Firestore: `kosong`, `normal`, `error/permission`. +- Dokumentasikan hasil actual per test case: `PASS/FAIL`, screenshot, dan timestamp. diff --git a/test/widget_test.dart b/test/widget_test.dart new file mode 100644 index 0000000..d33c878 --- /dev/null +++ b/test/widget_test.dart @@ -0,0 +1,11 @@ +// Basic Flutter widget test placeholder. +// Anda bisa menyesuaikan isi test ini nanti sesuai kebutuhan. + +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets('App builds without crashing', (WidgetTester tester) async { + // Placeholder test sederhana. + expect(1 + 1, 2); + }); +} diff --git a/web/favicon.png b/web/favicon.png new file mode 100644 index 0000000..8aaa46a Binary files /dev/null and b/web/favicon.png differ diff --git a/web/icons/Icon-192.png b/web/icons/Icon-192.png new file mode 100644 index 0000000..b749bfe Binary files /dev/null and b/web/icons/Icon-192.png differ diff --git a/web/icons/Icon-512.png b/web/icons/Icon-512.png new file mode 100644 index 0000000..88cfd48 Binary files /dev/null and b/web/icons/Icon-512.png differ diff --git a/web/icons/Icon-maskable-192.png b/web/icons/Icon-maskable-192.png new file mode 100644 index 0000000..eb9b4d7 Binary files /dev/null and b/web/icons/Icon-maskable-192.png differ diff --git a/web/icons/Icon-maskable-512.png b/web/icons/Icon-maskable-512.png new file mode 100644 index 0000000..d69c566 Binary files /dev/null and b/web/icons/Icon-maskable-512.png differ diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..61854db --- /dev/null +++ b/web/index.html @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + mobile_monitoring + + + + + + diff --git a/web/manifest.json b/web/manifest.json new file mode 100644 index 0000000..3838b42 --- /dev/null +++ b/web/manifest.json @@ -0,0 +1,35 @@ +{ + "name": "mobile_monitoring", + "short_name": "mobile_monitoring", + "start_url": ".", + "display": "standalone", + "background_color": "#0175C2", + "theme_color": "#0175C2", + "description": "A new Flutter project.", + "orientation": "portrait-primary", + "prefer_related_applications": false, + "icons": [ + { + "src": "icons/Icon-192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "icons/Icon-512.png", + "sizes": "512x512", + "type": "image/png" + }, + { + "src": "icons/Icon-maskable-192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "maskable" + }, + { + "src": "icons/Icon-maskable-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "maskable" + } + ] +} diff --git a/windows/.gitignore b/windows/.gitignore new file mode 100644 index 0000000..d492d0d --- /dev/null +++ b/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/windows/CMakeLists.txt b/windows/CMakeLists.txt new file mode 100644 index 0000000..8e5816b --- /dev/null +++ b/windows/CMakeLists.txt @@ -0,0 +1,108 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(mobile_monitoring 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 "mobile_monitoring") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(VERSION 3.14...3.25) + +# Define build configuration option. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() +# Define settings for the Profile build mode. +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/windows/flutter/CMakeLists.txt b/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000..903f489 --- /dev/null +++ b/windows/flutter/CMakeLists.txt @@ -0,0 +1,109 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# Set fallback configurations for older versions of the flutter tool. +if (NOT DEFINED FLUTTER_TARGET_PLATFORM) + set(FLUTTER_TARGET_PLATFORM "windows-x64") +endif() + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + ${FLUTTER_TARGET_PLATFORM} $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..4a46c81 --- /dev/null +++ b/windows/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 +#include + +void RegisterPlugins(flutter::PluginRegistry* registry) { + CloudFirestorePluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("CloudFirestorePluginCApi")); + FileSelectorWindowsRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FileSelectorWindows")); + FirebaseAuthPluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FirebaseAuthPluginCApi")); + FirebaseCorePluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FirebaseCorePluginCApi")); +} diff --git a/windows/flutter/generated_plugin_registrant.h b/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..dc139d8 --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake new file mode 100644 index 0000000..e0beee3 --- /dev/null +++ b/windows/flutter/generated_plugins.cmake @@ -0,0 +1,27 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + cloud_firestore + file_selector_windows + firebase_auth + firebase_core +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/windows/runner/CMakeLists.txt b/windows/runner/CMakeLists.txt new file mode 100644 index 0000000..394917c --- /dev/null +++ b/windows/runner/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/windows/runner/Runner.rc b/windows/runner/Runner.rc new file mode 100644 index 0000000..9eaa691 --- /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", "mobile_monitoring" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "mobile_monitoring" "\0" + VALUE "LegalCopyright", "Copyright (C) 2025 com.example. All rights reserved." "\0" + VALUE "OriginalFilename", "mobile_monitoring.exe" "\0" + VALUE "ProductName", "mobile_monitoring" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/windows/runner/flutter_window.cpp b/windows/runner/flutter_window.cpp new file mode 100644 index 0000000..955ee30 --- /dev/null +++ b/windows/runner/flutter_window.cpp @@ -0,0 +1,71 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + // Flutter can complete the first frame before the "show window" callback is + // registered. The following call ensures a frame is pending to ensure the + // window is shown. It is a no-op if the first frame hasn't completed yet. + flutter_controller_->ForceRedraw(); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/windows/runner/flutter_window.h b/windows/runner/flutter_window.h new file mode 100644 index 0000000..6da0652 --- /dev/null +++ b/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/windows/runner/main.cpp b/windows/runner/main.cpp new file mode 100644 index 0000000..a818afd --- /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"mobile_monitoring", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/windows/runner/resource.h b/windows/runner/resource.h new file mode 100644 index 0000000..66a65d1 --- /dev/null +++ b/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/windows/runner/resources/app_icon.ico b/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000..c04e20c Binary files /dev/null and b/windows/runner/resources/app_icon.ico differ diff --git a/windows/runner/runner.exe.manifest b/windows/runner/runner.exe.manifest new file mode 100644 index 0000000..153653e --- /dev/null +++ b/windows/runner/runner.exe.manifest @@ -0,0 +1,14 @@ + + + + + PerMonitorV2 + + + + + + + + + diff --git a/windows/runner/utils.cpp b/windows/runner/utils.cpp new file mode 100644 index 0000000..3a0b465 --- /dev/null +++ b/windows/runner/utils.cpp @@ -0,0 +1,65 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + unsigned int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, nullptr, 0, nullptr, nullptr) + -1; // remove the trailing null character + int input_length = (int)wcslen(utf16_string); + std::string utf8_string; + if (target_length == 0 || target_length > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, utf8_string.data(), target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/windows/runner/utils.h b/windows/runner/utils.h new file mode 100644 index 0000000..3879d54 --- /dev/null +++ b/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/windows/runner/win32_window.cpp b/windows/runner/win32_window.cpp new file mode 100644 index 0000000..60608d0 --- /dev/null +++ b/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#include "resource.h" + +namespace { + +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + } + FreeLibrary(user32_module); +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registrar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::Create(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + UpdateTheme(window); + + return OnCreate(); +} + +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/windows/runner/win32_window.h b/windows/runner/win32_window.h new file mode 100644 index 0000000..e901dde --- /dev/null +++ b/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates a win32 window with |title| that is positioned and sized using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_