ソースコード source code

下記アプリの主要なソースコードを公開しています。アプリ開発の参考になれば幸いです。

● ご注意 ● このページで公開しているのはDartコードのみです。アプリの動作には画像・音声・多言語テキストなどの追加データが必要なため、ここに掲載している情報だけではアプリを完全に再現することはできません。 ● アプリは継続的に機能拡張しているため、ストアで公開している最新版とコード内容が異なる場合があります。 ● コードはコピーして自由にご利用いただけますが、著作権は放棄していません。そのため、コード全体の再掲載はご遠慮ください。一部の引用や改変しての再掲載は問題ありません。個人利用・商用利用を問わず、アプリ開発の参考として自由にお使いください。 ● このコードは「お手本」として公開しているものではありません。ミニアプリとして作成しているため、変数名など細部に配慮していない箇所や誤りが含まれる可能性があります。参考程度にご覧ください。 ● 他の開発者の公開コードを参考にした部分も含まれています。アプリ開発の熟練者が書いたコードではない点もご了承ください。 ● ここはエンジニア向けの技術情報共有サービスではないため、詳細な説明は省略しています。GitHub などでの公開予定はありません。 ● 本コードは無保証であり、動作や品質を保証するものではありません。
Copyright© エーオーシステム株式会社

● Notice ● Only the Dart source code is provided on this page. Additional assets such as images, audio files, and multilingual text are required for the application to function. Therefore, the information here alone is not sufficient to fully reproduce the app. ● The app is continuously being improved, so the code published here may differ from the latest version available on the app stores. ● You are free to copy and use the code, but the copyright is not waived. For this reason, please refrain from redistributing (reposting) the entire code. Partial quotation or redistribution of modified portions is allowed. You may use the code freely for reference in your own app development, whether for personal or commercial use. ● This code is not intended to serve as a coding example or best practice. As this is a small sample app, some variable names and details may lack refinement, and there may be mistakes. Please use it only as a reference. ● Some parts of the code are based on publicly available examples from other developers. Please note that this code was not written by an expert in Android app development. ● This is not a technical knowledge-sharing service for engineers, so detailed explanations are omitted. There are no plans to publish the code on GitHub. ● The code is provided "as is" without any warranty of any kind.
Copyright© ao-system, Inc.

下記コードの最終ビルド日: 2026-02-12

name: qranalyzer
description: "qranalyzer"

publish_to: 'none'

version: 1.0.3+4

environment:
  sdk: ^3.10.7

dependencies:  # flutter pub upgrade --major-versions
  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.8
  flutter_localizations:      #flutter gen-l10n
    sdk: flutter
  intl: ^0.20.2
  shared_preferences: ^2.3.2
  google_mobile_ads: ^7.0.0
  camera: ^0.11.3
  image: ^4.1.3
  zxing_lib: ^1.1.4
  image_picker: ^1.1.2

dev_dependencies:
  flutter_lints: ^6.0.0
  flutter_launcher_icons: ^0.14.3    #flutter pub run flutter_launcher_icons
  flutter_native_splash: ^2.3.6     #flutter pub run flutter_native_splash:create

flutter_icons:
  android: "launcher_icon"
  ios: true
  image_path: "assets/icon/icon.png"
  adaptive_icon_background: "assets/icon/icon_back.png"
  adaptive_icon_foreground: "assets/icon/icon_fore.png"

flutter_native_splash:
  color: '#10005f'
  image: 'assets/image/splash.png'
  color_dark: '#10005f'
  image_dark: 'assets/image/splash.png'
  fullscreen: true
  android_12:
    icon_background_color: '#10005f'
    image: 'assets/image/splash.png'
    icon_background_color_dark: '#10005f'
    image_dark: 'assets/image/splash.png'

flutter:
  generate: true
  uses-material-design: true

  assets:
    - assets/icon/
    - assets/image/

import 'package:flutter/cupertino.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';

import 'package:qranalyzer/ad_manager.dart';

class AdBannerWidget extends StatefulWidget {
  final AdManager adManager;
  const AdBannerWidget({super.key, required this.adManager});
  @override
  State<AdBannerWidget> createState() => _AdBannerWidgetState();
}

class _AdBannerWidgetState extends State<AdBannerWidget> {
  int _lastBannerWidthDp = 0;
  bool _isAdLoaded = false;
  bool _isLoading = false;
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: LayoutBuilder(
        builder: (context, constraints) {
          final int width = constraints.maxWidth.isFinite ? constraints.maxWidth.truncate() : MediaQuery.of(context).size.width.truncate();
          final bannerAd = widget.adManager.bannerAd;
          if (width > 0) {
            WidgetsBinding.instance.addPostFrameCallback((_) {
              if (mounted) {
                final bannerAd = widget.adManager.bannerAd;
                final bool widthChanged = _lastBannerWidthDp != width;
                final bool sizeMismatch = bannerAd == null || bannerAd.size.width != width;
                if ((widthChanged || !_isAdLoaded || sizeMismatch) && !_isLoading) {
                  _lastBannerWidthDp = width;
                  setState(() { _isAdLoaded = false; _isLoading = true; });
                  widget.adManager.loadAdaptiveBannerAd(width, () {
                    if (mounted) {
                      setState(() { _isAdLoaded = true; _isLoading = false; });
                    }
                  });
                }
              }
            });
          }
          if (_isAdLoaded && bannerAd != null) {
            return Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                SizedBox(height: 10),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    SizedBox(
                      width: bannerAd.size.width.toDouble(),
                      height: bannerAd.size.height.toDouble(),
                      child: AdWidget(ad: bannerAd),
                    ),
                  ],
                )
              ]
            );
          } else {
            return const SizedBox.shrink();
          }
        },
      ),
    );
  }
}
/*
 *	mainへの記述
 *	void main() async {
 *		WidgetsFlutterBinding.ensureInitialized();
 *		if (!kIsWeb) {
 *			//AdMob初期化
 *			MobileAds.instance.initialize();
 *			//NPAポリシーの集中設定(将来拡張もここで) 現時点は使用していないので記述しなくても良い
 *			await AdManager.initForNPA();
 *		}
 *		runApp(const MyApp());
 *	}
 */

import 'dart:async';
import 'dart:io' show Platform;
import 'dart:ui';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:google_mobile_ads/google_mobile_ads.dart';

class AdManager {
  //Test IDs
  //static const String _androidAdUnitId = "ca-app-pub-3940256099942544/6300978111";
  //static const String _iosAdUnitId     = "ca-app-pub-3940256099942544/2934735716";

  //Production IDs
  static const String _androidAdUnitId = "ca-app-pub-0/0";
  static const String _iosAdUnitId     = "ca-app-pub-0/0";

  static String get _adUnitId => Platform.isIOS ? _iosAdUnitId : _androidAdUnitId;

  BannerAd? _bannerAd;
  int _lastWidthPx = 0;
  VoidCallback? _onLoadedCb;
  Timer? _retryTimer;
  int _retryAttempt = 0;

  BannerAd? get bannerAd => _bannerAd;

  //(任意)アプリ起動時などに呼ぶ。将来のCMP/NPA関連設定を集中管理。
  static Future<void> initForNPA() async {
    if (kIsWeb) {
      return;
    }
    //ここでグローバルなRequestConfigurationを設定しておく(必要に応じて拡張)
    await MobileAds.instance.updateRequestConfiguration(
      RequestConfiguration(
        //例:最大コンテンツレーティング等を付けたい場合はここに追加
        //maxAdContentRating: MaxAdContentRating.g,	//例
        //tagForChildDirectedTreatment: TagForChildDirectedTreatment.unspecified,
        //tagForUnderAgeOfConsent: TagForUnderAgeOfConsent.unspecified,
      ),
    );
  }

  Future<void> loadAdaptiveBannerAd(
      int widthPx,
      VoidCallback onAdLoaded,
      ) async {
    if (kIsWeb) {
      return;
    }
    _onLoadedCb = onAdLoaded;
    _lastWidthPx = widthPx;
    _retryAttempt = 0;
    _retryTimer?.cancel();
    _startLoad(widthPx);
  }

  Future<void> _startLoad(int widthPx) async {
    if (kIsWeb) {
      return;
    }
    _bannerAd?.dispose();

    AnchoredAdaptiveBannerAdSize? adaptiveSize;
    try {
      adaptiveSize =
      await AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(
        widthPx,
      );
    } catch (_) {
      adaptiveSize = null;
    }
    final AdSize size = adaptiveSize ?? AdSize.fullBanner;

    //常にNPAで配信(CMP対応)
    const adRequest = AdRequest(
      nonPersonalizedAds: true,	//NPA Non-Personalized Ads(非パーソナライズ広告)指定
    );

    _bannerAd = BannerAd(
      adUnitId: _adUnitId,
      request: adRequest,
      size: size,
      listener: BannerAdListener(
        onAdLoaded: (ad) {
          _retryTimer?.cancel();
          _retryAttempt = 0;
          final cb = _onLoadedCb;
          if (cb != null) {
            cb();
          }
        },
        onAdFailedToLoad: (ad, err) {
          ad.dispose();
          _scheduleRetry();
        },
      ),
    )..load();
  }

  void _scheduleRetry() {
    if (kIsWeb) {
      return;
    }
    _retryTimer?.cancel();
    // Exponential backoff: 3s, 6s, 12s, max 30s
    _retryAttempt = (_retryAttempt + 1).clamp(1, 5);
    final seconds = _retryAttempt >= 4 ? 30 : (3 << (_retryAttempt - 1));
    _retryTimer = Timer(Duration(seconds: seconds), () {
      _startLoad(_lastWidthPx > 0 ? _lastWidthPx : 320);
    });
  }

  void dispose() {
    _bannerAd?.dispose();
    _retryTimer?.cancel();
  }
}

/*
広告配信について
本アプリでは、Google AdMob を利用して広告を表示しています。
当アプリの広告はすべて「非パーソナライズ広告(NPA)」として配信しており、ユーザーの行動履歴や個人情報をもとにしたパーソナライズは一切行っていません。
Google AdMob によって、広告の表示のために以下の情報が利用される場合があります:
- 端末情報(例:OSの種類、画面サイズなど)
- おおまかな位置情報(国・地域レベル)
これらの情報は、パーソナライズを目的としたトラッキングやプロファイリングには使用されません。
詳しくは、Google のプライバシーポリシーをご覧ください:
https://policies.google.com/privacy


Advertising
This app uses Google AdMob to display advertisements.
All ads in this app are served as non-personalized ads (NPA).
This means that we do not use personal data or user behavior information to personalize the ads you see.
Google AdMob may use certain information in order to display ads properly, such as:
- Device information (e.g., OS type, screen size)
- Approximate location information (country/region level)
This information is not used for tracking or profiling for advertising purposes.
For more details, please refer to Google Privacy Policy:
https://policies.google.com/privacy
*/
/*
  CMP(Consent Management Platform)「同意管理プラットフォーム」
  UMP とは、Google AdMobでGDPRの同意を取得するために使用されるライブラリ User Messaging Platform (UMP) SDK

  ad_manager.dart で NPA Non-Personalized Ads(非パーソナライズ広告)指定 している。

  必要な変数
  late final UmpConsentController _adUmp;
  AdUmpState _adUmpState = AdUmpState.initial;

  @override
  void initState() {
    super.initState();
    _adUmp = UmpConsentController();
    _refreshConsentInfo();
  }

  必要な関数
  Future<void> _refreshConsentInfo() async {
    _adUmpState = await _adUmp.updateConsentInfo(current: _adUmpState);
    if (mounted) {
      setState(() {});
    }
  }
  Future<void> _onTapPrivacyOptions() async {
    final err = await _adUmp.showPrivacyOptions();
    await _refreshConsentInfo();
    if (err != null && mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('プライバシー設定画面を表示できませんでした: ${err.message}')),
      );
    }
  }
 */

import 'dart:async';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:flutter/widgets.dart';

import 'package:qranalyzer/l10n/app_localizations.dart';

/// UMP状態格納用
class AdUmpState {
  final PrivacyOptionsRequirementStatus privacyStatus;
  final ConsentStatus consentStatus;
  final bool privacyOptionsRequired;
  final bool isChecking;
  const AdUmpState({
    required this.privacyStatus,
    required this.consentStatus,
    required this.privacyOptionsRequired,
    required this.isChecking,
  });

  AdUmpState copyWith({
    PrivacyOptionsRequirementStatus? privacyStatus,
    ConsentStatus? consentStatus,
    bool? privacyOptionsRequired,
    bool? isChecking,
  }) {
    return AdUmpState(
      privacyStatus: privacyStatus ?? this.privacyStatus,
      consentStatus: consentStatus ?? this.consentStatus,
      privacyOptionsRequired:
      privacyOptionsRequired ?? this.privacyOptionsRequired,
      isChecking: isChecking ?? this.isChecking,
    );
  }

  static const initial = AdUmpState(
    privacyStatus: PrivacyOptionsRequirementStatus.unknown,
    consentStatus: ConsentStatus.unknown,
    privacyOptionsRequired: false,
    isChecking: false,
  );
}

//UMPコントローラ
class UmpConsentController {
  //デバッグ用:EEA地域を強制するか(本番ではfalseにすること)
  final bool forceEeaForDebug = false;
  //埋め込みのテストデバイスID
  static const List<String> _testDeviceIds = [
    '608970392F100B87D62A1174996C952C', //arrows We2 (M07)
  ];

  ConsentRequestParameters _buildParams() {
    if (forceEeaForDebug && _testDeviceIds.isNotEmpty) {
      return ConsentRequestParameters(
        consentDebugSettings: ConsentDebugSettings(
          debugGeography: DebugGeography.debugGeographyEea,
          testIdentifiers: _testDeviceIds,
        ),
      );
    }
    return ConsentRequestParameters();
  }

  //同意情報を更新して状態を返す
  Future<AdUmpState> updateConsentInfo({AdUmpState current = AdUmpState.initial}) async {
    if (kIsWeb) return current;
    var state = current.copyWith(isChecking: true);

    try {
      final params = _buildParams();
      final completer = Completer<AdUmpState>();

      ConsentInformation.instance.requestConsentInfoUpdate(
        params,
            () async {
          final s = await ConsentInformation.instance.getPrivacyOptionsRequirementStatus();
          final c = await ConsentInformation.instance.getConsentStatus();
          completer.complete(
            state.copyWith(
              privacyStatus: s,
              consentStatus: c,
              privacyOptionsRequired: s == PrivacyOptionsRequirementStatus.required,
              isChecking: false,
            ),
          );
        },
            (FormError e) {
          completer.complete(
            state.copyWith(
              privacyStatus: PrivacyOptionsRequirementStatus.unknown,
              consentStatus: ConsentStatus.unknown,
              privacyOptionsRequired: false,
              isChecking: false,
            ),
          );
        },
      );

      state = await completer.future;
      return state;
    } catch (_) {
      return state.copyWith(isChecking: false);
    }
  }

  //プライバシーオプションフォームを表示
  Future<FormError?> showPrivacyOptions() async {
    if (kIsWeb) return null;
    final completer = Completer<FormError?>();
    ConsentForm.showPrivacyOptionsForm((FormError? e) {
      completer.complete(e);
    });
    return completer.future;
  }
}

extension ConsentStatusL10n on ConsentStatus {
  String localized(BuildContext context) {
    final l = AppLocalizations.of(context)!;
    switch (this) {
      case ConsentStatus.obtained:
        return l.cmpConsentStatusObtained;
      case ConsentStatus.required:
        return l.cmpConsentStatusRequired;
      case ConsentStatus.notRequired:
        return l.cmpConsentStatusNotRequired;
      case ConsentStatus.unknown:
        return l.cmpConsentStatusUnknown;
    }
  }
}
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';

class CameraPage extends StatefulWidget {
  const CameraPage({super.key});

  @override
  State<CameraPage> createState() => _CameraPageState();
}

class _CameraPageState extends State<CameraPage> {
  CameraController? _controller;
  bool _isReady = false;
  double _currentZoom = 1.0;
  double _baseZoom = 1.0;
  double _maxZoom = 1.0;
  double _minZoom = 1.0;

  @override
  void initState() {
    super.initState();
    _initCamera();
  }

  @override
  void dispose() {
    _controller?.dispose();
    super.dispose();
  }

  Future<void> _initCamera() async {
    try {
      final cameras = await availableCameras();
      final camera = cameras.first;
      final controller = CameraController(
        camera,
        ResolutionPreset.medium,
        enableAudio: false,
      );
      await controller.initialize();
      _maxZoom = await controller.getMaxZoomLevel();
      _minZoom = await controller.getMinZoomLevel();
      setState(() {
        _controller = controller;
        _isReady = true;
      });
    } catch (e) {
      debugPrint("カメラ初期化エラー: $e");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Camera')),
      body: _isReady
          ? GestureDetector(
        onScaleStart: (details) {
          _baseZoom = _currentZoom;
        },
        onScaleUpdate: (details) async {
          if (_controller == null) return;

          final newZoom = (_baseZoom * details.scale)
              .clamp(_minZoom, _maxZoom);

          await _controller!.setZoomLevel(newZoom);
          setState(() {
            _currentZoom = newZoom;
          });
        },
        child: CameraPreview(_controller!),
      )
          : const Center(child: CircularProgressIndicator()),
      floatingActionButton: _isReady
          ? FloatingActionButton(
        onPressed: _takePhoto,
        child: const Icon(Icons.camera_alt),
      )
          : null,
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
    );
  }

  Future<void> _takePhoto() async {
    if (_controller == null || !_controller!.value.isInitialized) {
      return;
    }
    try {
      final XFile file = await _controller!.takePicture();
      Navigator.pop(context, file);
    } catch (e) {
      debugPrint('撮影エラー: $e');
    }
  }
}
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
import 'package:image/image.dart' as img;

import 'package:qranalyzer/instruction_panel.dart';
import 'package:qranalyzer/qr_info.dart';
import 'package:qranalyzer/qr_matrix_painter.dart';
import 'package:qranalyzer/parse_locale_tag.dart';
import 'package:qranalyzer/qr_original_painter.dart';
import 'package:qranalyzer/setting_page.dart';
import 'package:qranalyzer/theme_color.dart';
import 'package:qranalyzer/theme_mode_number.dart';
import 'package:qranalyzer/ad_manager.dart';
import 'package:qranalyzer/loading_screen.dart';
import 'package:qranalyzer/model.dart';
import 'package:qranalyzer/main.dart';
import 'package:qranalyzer/ad_banner_widget.dart';
import 'package:qranalyzer/qr_region.dart';
import 'package:qranalyzer/legend_panel.dart';
import 'package:qranalyzer/unmasked_painter.dart';
import 'package:qranalyzer/mask_painter.dart';
import 'package:qranalyzer/camera_page.dart';
import 'package:qranalyzer/info_panel.dart';
import 'package:qranalyzer/image_select_page.dart';
import 'package:qranalyzer/qr_processor.dart';

class MainHomePage extends StatefulWidget {
  const MainHomePage({super.key});
  @override
  State<MainHomePage> createState() => _MainHomePageState();
}

class _MainHomePageState extends State<MainHomePage> {
  late AdManager _adManager;
  late ThemeColor _themeColor;
  bool _isReady = false;
  bool _isFirst = true;
  //
  final QrProcessor _processor = QrProcessor();
  bool _isProcessing = false;
  List<List<bool>>? _matrix;
  String? _error;
  QrInfo? _info;
  List<List<QrRegion>>? _regionMap;
  List<List<bool>>? _unmasked;
  int? _maskPattern;

  @override
  void initState() {
    super.initState();
    _initState();
  }

  void _initState() async {
    _adManager = AdManager();
    if (mounted) {
      setState(() {
        _isReady = true;
      });
    }
  }

  @override
  void dispose() {
    _adManager.dispose();
    super.dispose();
  }

  Future<void> _captureAndAnalyze(XFile photo) async {
    // 1. 解析開始前にすべての結果をクリアする
    setState(() {
      _isProcessing = true;
      _matrix = null;      // QR行列をクリア
      _info = null;        // 解析情報をクリア
      _regionMap = null;   // 領域マップをクリア
      _unmasked = null;    // マスク解除ビットをクリア
      _maskPattern = null; // マスクパターンをクリア
      _error = null;       // エラーメッセージをクリア
    });

    try {
      final bytes = await photo.readAsBytes();
      img.Image? image = img.decodeImage(bytes);
      if (image == null) throw Exception("Decode failed");

      if (image.width > 1000) {
        image = img.copyResize(image, width: 1000, interpolation: img.Interpolation.nearest);
      }

      // 1. ビット抽出
      final (matrix, info) = await _processor.extractRawPattern(image);

      // 2. 領域分類
      final regionMap = _processor.classifyModules(info.version, info.dataCodewords, info.eccCodewords);

      // 3. マスク解除
      final unmasked = _processor.unmaskMatrix(matrix, regionMap, info.maskPattern);

      if (!mounted) return;

      // 4. 解析完了後に新しい結果をセットする
      setState(() {
        _matrix = matrix;
        _info = info;
        _regionMap = regionMap;
        _unmasked = unmasked;
        _maskPattern = info.maskPattern;
      });

    } catch (e) {
      if (!mounted) return;
      setState(() {
        final String errorStr = e.toString();
        //メッセージをカスタマイズ
        if (errorStr.contains('NotFoundException')) {
          _error = 'No QR code found.';
        } else if (errorStr.contains('Format not found')) {
          _error = 'QR code detected, but data reading failed.';
        } else {
          _error = 'Analysis failed.';
        }
      });
    } finally {
      if (mounted) {
        setState(() => _isProcessing = false);
      }
    }
  }

  void _openSetting() async {
    final updatedSettings = await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => SettingPage(),
      ),
    );
    if (updatedSettings != null) {
      if (mounted) {
        final mainState = context.findAncestorStateOfType<MainAppState>();
        if (mainState != null) {
          mainState
            ..locale = parseLocaleTag(Model.languageCode)
            ..themeMode = ThemeModeNumber.numberToThemeMode(Model.themeNumber)
            ..setState(() {});
        }
      }
      if (mounted) {
        setState(() {
          _isFirst = true;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_isReady == false) {
      return const LoadingScreen();
    }
    if (_isFirst) {
      _isFirst = false;
      _themeColor = ThemeColor(context: context);
    }
    return Scaffold(
      backgroundColor: _themeColor.mainBackColor,
      body: Stack(children:[
        _buildBackground(),
        SafeArea(
          child: Column(
            children: [
              _buildAppBar(),
              _buildButton(),
              const SizedBox(height: 16),
              Expanded(
                child: SingleChildScrollView(
                  padding: const EdgeInsets.all(8),
                  child: Column(
                    children: [
                      if (_matrix != null) ...[
                        _buildQrOriginalPainter(),
                        const LegendPanel(),
                        _buildQrMatrixPainter(),  // QR本体
                        _buildMaskPainter(),  //マスクパターン
                      ]
                      else if (_error != null)
                        Container(
                          margin: const EdgeInsets.only(left: 12, right: 12),
                          child: Text(_error!),
                        )
                      else
                        const SizedBox.shrink(),
                      //
                      if (_unmasked != null)
                        _buildUnmaskedPainter(),  // 生ビット(マスク解除後)
                      // 情報表示
                      if (_info != null) ...[
                        InfoPanel(info: _info!),
                      ],
                      InstructionPanel(),
                    ]
                  )
                )
              )
            ]
          )
        )
      ]),
      bottomNavigationBar: AdBannerWidget(adManager: _adManager)
    );
  }

  Widget _buildBackground() {
    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [_themeColor.mainBack2Color, _themeColor.mainBackColor],
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
        ),
        image: DecorationImage(
          image: AssetImage('assets/image/tile.png'),
          repeat: ImageRepeat.repeat,
          opacity: 0.1,
        ),
      ),
    );
  }

  Widget _buildAppBar() {
    final t = Theme.of(context).textTheme;
    return SizedBox(
      height: 52,
      child: Row(
        children: [
          const SizedBox(width: 16),
          Text('QR Analyzer', style: t.titleSmall?.copyWith(color: _themeColor.mainForeColor)),
          const Spacer(),
          IconButton(
            onPressed: _openSetting,
            icon: Icon(Icons.settings,color: _themeColor.mainForeColor.withValues(alpha: 0.6)),
          ),
        ],
      )
    );
  }

  Widget _buildButton() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16), // ← 左右に余白
      child: Column(
        children: [
          SizedBox(
            width: double.infinity,
            child: ElevatedButton(
              style: ElevatedButton.styleFrom(
                elevation: 0,
                side: const BorderSide(color: Colors.grey, width: 1),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
                padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 20),
              ),
              onPressed: _isProcessing ? null : () async {
                final XFile? photo = await Navigator.push(
                  context,
                  MaterialPageRoute(builder: (_) => const CameraPage()),
                );
                if (photo != null) _captureAndAnalyze(photo);
              },
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const Icon(Icons.camera_alt),
                  const SizedBox(width: 8),
                  Text(_isProcessing ? 'Analyzing...' : 'Capture the QR code.'),
                ],
              ),
            ),
          ),

          const SizedBox(height: 6),

          SizedBox(
            width: double.infinity,
            child: ElevatedButton(
              style: ElevatedButton.styleFrom(
                elevation: 0,
                side: const BorderSide(color: Colors.grey, width: 1),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
                padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 20),
              ),
              onPressed: _isProcessing ? null : () async {
                final XFile? photo = await Navigator.push(
                  context,
                  MaterialPageRoute(builder: (_) => const ImageSelectPage()),
                );
                if (photo != null) _captureAndAnalyze(photo);
              },
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const Icon(Icons.image_search),
                  const SizedBox(width: 8),
                  Text(_isProcessing ? 'Analyzing...' : 'Select an image.'),
                ],
              ),
            ),
          ),
        ],
      )
    );
  }

  Widget _buildQrOriginalPainter() {
    if (_matrix == null || _regionMap == null) {
      return const SizedBox.shrink();
    }
    return Padding(
      padding: const EdgeInsets.only(left: 12, right: 12, top: 8),
      child: AspectRatio(
        aspectRatio: 1,
        child: LayoutBuilder(
          builder: (context, constraints) {
            final size = constraints.biggest; // 最大サイズを取得
            return CustomPaint(
              size: size,
              painter: QrOriginalPainter(
                _matrix!,
                _regionMap!,
              ),
            );
          },
        ),
      ),
    );
  }

  Widget _buildQrMatrixPainter() {
    if (_matrix == null || _regionMap == null) {
      return const SizedBox.shrink();
    }
    return Padding(
      padding: const EdgeInsets.only(left: 12, right: 12, top: 8),
      child: AspectRatio(
        aspectRatio: 1,
        child: LayoutBuilder(
          builder: (context, constraints) {
            final size = constraints.biggest; // 最大サイズを取得
            return CustomPaint(
              size: size,
              painter: QrMatrixPainter(
                _matrix!,
                _regionMap!,
              ),
            );
          },
        ),
      ),
    );
  }

  Widget _buildMaskPainter() {
    return Padding(
      padding: const EdgeInsets.only(left: 12, right: 12, top: 8),
      child: AspectRatio(
        aspectRatio: 1,
        child: LayoutBuilder(
          builder: (context, constraints) {
            final size = constraints.biggest;
            return CustomPaint(
              size: size,
              painter: MaskPainter(
                _maskPattern!,
                _matrix!.length,
              ),
            );
          },
        ),
      ),
    );
  }

  Widget _buildUnmaskedPainter() {
    return Padding(
      padding: const EdgeInsets.only(left: 12, right: 12, top: 8),
      child: AspectRatio(
        aspectRatio: 1,
        child: LayoutBuilder(
          builder: (context, constraints) {
            final size = constraints.biggest;
            return CustomPaint(
              size: size,
              painter: UnmaskedPainter(_unmasked!,_regionMap!),
            );
          },
        ),
      ),
    );
  }

}
import 'dart:async';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:image/image.dart' as img;

class ImageSelectPage extends StatefulWidget {
  const ImageSelectPage({super.key});

  @override
  State<ImageSelectPage> createState() => _ImageSelectPageState();
}

class _ImageSelectPageState extends State<ImageSelectPage> {
  XFile? _selectedImage;
  bool _isProcessing = false;

  int? _imgWidth;
  int? _imgHeight;

  Future<void> _pickImage() async {
    if (kIsWeb) return;

    final picker = ImagePicker();
    final XFile? image = await picker.pickImage(source: ImageSource.gallery);

    if (image == null) return;

    // Read image size
    final bytes = await image.readAsBytes();
    final decoded = img.decodeImage(bytes);
    if (decoded != null) {
      _imgWidth = decoded.width;
      _imgHeight = decoded.height;
    }

    setState(() {
      _selectedImage = image;
    });
  }

  Future<void> _returnImage() async {
    if (_selectedImage == null) return;

    setState(() => _isProcessing = true);

    try {
      Navigator.pop(context, _selectedImage);
    } finally {
      setState(() => _isProcessing = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Select Image"),
        centerTitle: true,
      ),
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            children: [
              Row(
                children: [
                  Expanded(
                    child: FilledButton.icon(
                      onPressed: _isProcessing ? null : _pickImage,
                      icon: const Icon(Icons.photo_library_outlined),
                      label: const Text("Choose Image"),
                    ),
                  ),
                  const SizedBox(width: 8),
                  Expanded(
                    child: FilledButton.icon(
                      onPressed: _selectedImage == null || _isProcessing
                          ? null
                          : _returnImage,
                      icon: const Icon(Icons.check),
                      label: const Text("Confirm"),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 16),
              if (_isProcessing) const LinearProgressIndicator(),
              const SizedBox(height: 16),

              Expanded(
                child: _selectedImage == null
                    ? const Center(child: Text("No image selected"))
                    : Column(
                  children: [
                    Expanded(
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(12),
                        child: Image.file(
                          File(_selectedImage!.path),
                          fit: BoxFit.contain,
                        ),
                      ),
                    ),

                    if (_imgWidth != null && _imgHeight != null)
                      Padding(
                        padding: const EdgeInsets.only(top: 8),
                        child: Text(
                          "Image size: ${_imgWidth} × ${_imgHeight}",
                          style: const TextStyle(fontSize: 14),
                        ),
                      ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
import 'package:flutter/material.dart';

import 'package:qranalyzer/qr_info.dart';
import 'package:qranalyzer/l10n/app_localizations.dart';

class InfoPanel extends StatelessWidget {
  final QrInfo info;

  const InfoPanel({super.key, required this.info});

  @override
  Widget build(BuildContext context) {
    final l = AppLocalizations.of(context)!;
    return Column(children:[
      Card(
        elevation: 0,
        margin: const EdgeInsets.only(left: 12, right: 12, top: 12),
        child: Container(
          width: double.infinity,
          padding: const EdgeInsets.symmetric(horizontal: 12,vertical: 8),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text("Decoded Result: ${info.decodedText ?? ''}"),
              Text("Version: ${info.version}"),
              Text("Error Correction Level: ${info.ecLevel}"),
              Text("Mask Pattern: ${info.maskPattern}"),
              Text("Size: ${info.size} × ${info.size}"),
              Text("Data Codewords: ${info.dataCodewords}"),
              Text("ECC Codewords: ${info.eccCodewords}"),
            ],
          )
        )
      ),
      Card(
        margin: const EdgeInsets.only(left: 12, right: 12, top: 12),
        elevation: 0,
        child: Container(
          width: double.infinity,
          padding: const EdgeInsets.symmetric(horizontal: 12,vertical: 8),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(l.infoImageFirst),
              const SizedBox(height: 12),
              Text(l.infoImageSecond),
              const SizedBox(height: 12),
              Text(l.infoImageThird),
            ],
          )
        )
      ),
    ]);
  }

}
import 'package:flutter/material.dart';

import 'package:qranalyzer/l10n/app_localizations.dart';

class InstructionPanel extends StatelessWidget {

  const InstructionPanel({super.key});

  @override
  Widget build(BuildContext context) {
    final l = AppLocalizations.of(context)!;
    return Column(children:[
      _buildCard("Version:\n${l.infoVersion}"),
      _buildCard("Error Correction Level:\n${l.infoECL}"),
      _buildCard("Data:\n${l.infoData}"),
      _buildCard("Finder Pattern:\n${l.infoFinderPattern}"),
      _buildCard("Format Info:\n${l.infoFormatInfo}"),
      _buildCard("Unused:\n${l.infoUnused}"),
      _buildCard("ECC: Error Correction Code\n${l.infoECC}"),
      _buildCard("Timing Pattern:\n${l.infoTimingPattern}"),
      _buildCard("Version Info:\n${l.infoVersionInfo}"),
      _buildCard("Dark Module:\n${l.infoDarkModule}"),
      const SizedBox(height: 100),
    ]);
  }

  Widget _buildCard(String text) {
    return Card(
      margin: const EdgeInsets.only(left: 12, right: 12, top: 12),
      elevation: 0,
      child: Container(
        width: double.infinity,
        padding: const EdgeInsets.symmetric(horizontal: 12,vertical: 8),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(text),
          ],
        )
      )
    );
  }
}
bool isMasked(int maskPattern, int x, int y) {
  switch (maskPattern) {
    case 0:
      return (y + x) % 2 == 0;
    case 1:
      return y % 2 == 0;
    case 2:
      return x % 3 == 0;
    case 3:
      return (y + x) % 3 == 0;
    case 4:
      return ((y ~/ 2) + (x ~/ 3)) % 2 == 0;
    case 5:
      return ((y * x) % 2 + (y * x) % 3) == 0;
    case 6:
      return (((y * x) % 2) + ((y * x) % 3)) % 2 == 0;
    case 7:
      return (((y + x) % 2) + ((y * x) % 3)) % 2 == 0;
    default:
      return false;
  }
}
import 'package:flutter/material.dart';

class LegendItem extends StatelessWidget {
  final Color color;
  final String label;

  const LegendItem({super.key, required this.color, required this.label});

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Container(
          width: 16,
          height: 16,
          color: color,
        ),
        const SizedBox(width: 8),
        Text(label),
      ],
    );
  }
}
import 'package:flutter/material.dart';

import 'package:qranalyzer/legend_item.dart';

class LegendPanel extends StatelessWidget {
  const LegendPanel({super.key});

  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: 0,
      margin: const EdgeInsets.only(left: 12, right: 12, top: 8),
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 12,vertical: 4),
        child: GridView.count(
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          crossAxisCount: 2,
          mainAxisSpacing: 1,
          crossAxisSpacing: 0,
          childAspectRatio: 6,
          children: const [
            LegendItem(color: Colors.green, label: "Finder Pattern"),
            LegendItem(color: Colors.cyan, label: "Alignment Pattern"),
            LegendItem(color: Colors.yellow, label: "Timing Pattern"),
            LegendItem(color: Colors.purple, label: "Format Info"),
            LegendItem(color: Colors.orange, label: "Version Info"),
            LegendItem(color: Colors.blue, label: "Data"),
            LegendItem(color: Colors.red, label: "ECC"),
            LegendItem(color: Colors.white, label: "Unused"),
            LegendItem(color: Colors.black, label: "Dark Module"),
          ],
        ),
      ),
    );
  }
}
import 'package:flutter/material.dart';

class LoadingScreen extends StatelessWidget {
  const LoadingScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color.fromRGBO(16,0,95,1),
      body: const Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            CircularProgressIndicator(
              valueColor: AlwaysStoppedAnimation<Color>(Colors.blue),
              backgroundColor: Colors.white,
            ),
            SizedBox(height: 16),
            Text(
              'Loading...',
              style: TextStyle(
                color: Colors.white,
                fontSize: 16,
              ),
            ),
          ],
        ),
      ),
    );
  }

}
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';

import "package:qranalyzer/home_page.dart";
import 'package:qranalyzer/l10n/app_localizations.dart';
import 'package:qranalyzer/loading_screen.dart';
import 'package:qranalyzer/model.dart';
import 'package:qranalyzer/parse_locale_tag.dart';
import 'package:qranalyzer/theme_mode_number.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
  SystemChrome.setSystemUIOverlayStyle(
    const SystemUiOverlayStyle(
      systemNavigationBarColor: Colors.transparent,
      statusBarColor: Colors.transparent,
      systemNavigationBarContrastEnforced: false,
      systemStatusBarContrastEnforced: false,
    ),
  );
  MobileAds.instance.initialize();
  runApp(const MainApp());
}

class MainApp extends StatefulWidget {
  const MainApp({super.key});
  @override
  State<MainApp> createState() => MainAppState();
}

class MainAppState extends State<MainApp> {
  ThemeMode themeMode = ThemeMode.light;
  Locale? locale;
  bool _isReady = false;

  @override
  void initState() {
    super.initState();
    _initState();
  }

  void _initState() async {
    await Model.ensureReady();
    themeMode = ThemeModeNumber.numberToThemeMode(Model.themeNumber);
    locale = parseLocaleTag(Model.languageCode);
    if (!mounted) {
      return;
    }
    setState(() {
      _isReady = true;
    });
  }

  Color _getRainbowAccentColor(int hue) {
    return HSVColor.fromAHSV(1.0, hue.toDouble(), 1.0, 1.0).toColor();
  }

  @override
  Widget build(BuildContext context) {
    if (!_isReady) {
      return MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Scaffold(body: Center(child: LoadingScreen())),
      );
    }
    final seed = _getRainbowAccentColor(Model.schemeColor);
    final colorSchemeLight = ColorScheme.fromSeed(seedColor: seed, brightness: Brightness.light);
    final colorSchemeDark = ColorScheme.fromSeed(seedColor: seed, brightness: Brightness.dark);
    //アイコンテーマを生成する関数、または直接指定
    IconThemeData buildIconTheme(ColorScheme colors) => IconThemeData(
      color: colors.primary,
      size: 24,
    );
    final commonElevatedButtonTheme = ElevatedButtonThemeData(
      style: ElevatedButton.styleFrom(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8),
        ),
      ),
    );
    final commonSliderTheme = SliderThemeData(
      activeTrackColor: null,
      thumbColor: null,
      showValueIndicator: ShowValueIndicator.onDrag,
      thumbShape: RoundSliderThumbShape(enabledThumbRadius: 10),
      valueIndicatorTextStyle: TextStyle(color: Colors.black),
    );
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      localizationsDelegates: AppLocalizations.localizationsDelegates,
      supportedLocales: AppLocalizations.supportedLocales,
      locale: locale,
      themeMode: themeMode,
      theme: ThemeData(
        useMaterial3: true,
        colorScheme: ColorScheme.fromSeed(seedColor: seed, brightness: Brightness.light),
        sliderTheme: commonSliderTheme,
        elevatedButtonTheme: commonElevatedButtonTheme,
        iconTheme: buildIconTheme(colorSchemeLight),
      ),
      darkTheme: ThemeData(
        useMaterial3: true,
        colorScheme: ColorScheme.fromSeed(seedColor: seed, brightness: Brightness.dark),
        sliderTheme: commonSliderTheme,
        elevatedButtonTheme: commonElevatedButtonTheme,
        iconTheme: buildIconTheme(colorSchemeDark),
      ),
      home: const MainHomePage(),
    );
  }
}
import 'package:flutter/material.dart';

import 'package:qranalyzer/is_masked.dart';

class MaskPainter extends CustomPainter {
  final int maskPattern;
  final int size;

  MaskPainter(this.maskPattern, this.size);

  @override
  void paint(Canvas canvas, Size s) {
    final cell = s.width / size;
    final paintMask = Paint()..color = Colors.grey.withValues(alpha: 0.5);

    for (int y = 0; y < size; y++) {
      for (int x = 0; x < size; x++) {
        if (isMasked(maskPattern, x, y)) {
          final rect = Rect.fromLTWH(x * cell, y * cell, cell, cell);
          canvas.drawRect(rect, paintMask);
        }
      }
    }
  }

  @override
  bool shouldRepaint(_) => true;
}
import 'dart:ui' as ui;
import 'package:shared_preferences/shared_preferences.dart';

import 'package:qranalyzer/l10n/app_localizations.dart';

class Model {
  Model._();

  static const String _prefSchemeColor = 'schemeColor';
  static const String _prefThemeNumber = 'themeNumber';
  static const String _prefLanguageCode = 'languageCode';

  static bool _ready = false;
  static int _schemeColor = 260;
  static int _themeNumber = 0;
  static String _languageCode = '';

  static int get schemeColor => _schemeColor;
  static int get themeNumber => _themeNumber;
  static String get languageCode => _languageCode;

  static Future<void> ensureReady() async {
    if (_ready) {
      return;
    }
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    //
    _schemeColor = (prefs.getInt(_prefSchemeColor) ?? 250).clamp(0, 360);
    _themeNumber = (prefs.getInt(_prefThemeNumber) ?? 0).clamp(0, 2);
    _languageCode = prefs.getString(_prefLanguageCode) ?? ui.PlatformDispatcher.instance.locale.languageCode;
    _languageCode = _resolveLanguageCode(_languageCode);
    _ready = true;
  }

  static String _resolveLanguageCode(String code) {
    final supported = AppLocalizations.supportedLocales;
    if (supported.any((l) => l.languageCode == code)) {
      return code;
    } else {
      return '';
    }
  }

  static Future<void> setSchemeColor(int value) async {
    _schemeColor = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_prefSchemeColor, value);
  }

  static Future<void> setThemeNumber(int value) async {
    _themeNumber = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_prefThemeNumber, value);
  }

  static Future<void> setLanguageCode(String value) async {
    _languageCode = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString(_prefLanguageCode, value);
  }

}
import 'dart:ui';

Locale? parseLocaleTag(String tag) {
  if (tag.isEmpty) {
    return null;
  }
  final parts = tag.split('-');
  final language = parts[0];
  String? script, country;
  if (parts.length >= 2) {
    parts[1].length == 4 ? script = parts[1] : country = parts[1];
  }
  if (parts.length >= 3) {
    parts[2].length == 4 ? script = parts[2] : country = parts[2];
  }
  return Locale.fromSubtags(
    languageCode: language,
    scriptCode: script,
    countryCode: country,
  );
}
class QrInfo {
  final int version;
  final String ecLevel;
  final int maskPattern;
  final int size;
  final int dataCodewords;
  final int eccCodewords;
  final String? decodedText;

  QrInfo({
    required this.version,
    required this.ecLevel,
    required this.maskPattern,
    required this.size,
    required this.dataCodewords,
    required this.eccCodewords,
    required this.decodedText,
  });
}
import 'package:flutter/material.dart';

import 'package:qranalyzer/qr_region.dart';

class QrMatrixPainter extends CustomPainter {
  final List<List<bool>> matrix;
  final List<List<QrRegion>> regionMap;

  QrMatrixPainter(this.matrix, this.regionMap);

  @override
  void paint(Canvas canvas, Size size) {
    final paintData = Paint()..color = Colors.blue;
    final paintECC = Paint()..color = Colors.red;
    final paintOther = Paint()..color = Colors.white;
    final paintDark = Paint()..color = Colors.black;
    final paintFinder = Paint()..color = Colors.green;
    final paintTiming = Paint()..color = Colors.yellow;
    final paintFormat = Paint()..color = Colors.purple;
    final paintVersion = Paint()..color = Colors.orange;
    final paintAlignment = Paint()..color = Colors.cyan;

    final n = matrix.length;
    final cell = size.width / n;

    for (int y = 0; y < n; y++) {
      for (int x = 0; x < n; x++) {
        final rect = Rect.fromLTWH(x * cell, y * cell, cell, cell);

        Paint bg;
        switch (regionMap[y][x]) {
          case QrRegion.data:
            bg = paintData;
            break;
          case QrRegion.ecc:
            bg = paintECC;
            break;
          case QrRegion.finder:
            bg = paintFinder;
            break;
          case QrRegion.timing:
            bg = paintTiming;
            break;
          case QrRegion.format:
            bg = paintFormat;
            break;
          case QrRegion.version:
            bg = paintVersion;
            break;
          case QrRegion.alignment:
            bg = paintAlignment;
            break;
          default:
            bg = paintOther;
        }

        canvas.drawRect(rect, matrix[y][x] ? paintDark : bg);
      }
    }
  }

  @override
  bool shouldRepaint(_) => true;
}
import 'package:flutter/material.dart';

import 'package:qranalyzer/qr_region.dart';

class QrOriginalPainter extends CustomPainter {
  final List<List<bool>> matrix;
  final List<List<QrRegion>> regionMap;

  QrOriginalPainter(this.matrix, this.regionMap);

  @override
  void paint(Canvas canvas, Size size) {
    final paintWhite = Paint()..color = Colors.white;
    final paintBlack = Paint()..color = Colors.black;

    final n = matrix.length;
    final cell = size.width / n;

    for (int y = 0; y < n; y++) {
      for (int x = 0; x < n; x++) {
        final rect = Rect.fromLTWH(x * cell, y * cell, cell, cell);

        Paint bg = paintBlack;
        switch (regionMap[y][x]) {
          case QrRegion.data:
          case QrRegion.ecc:
          case QrRegion.finder:
          case QrRegion.timing:
          case QrRegion.format:
          case QrRegion.version:
          case QrRegion.alignment:
          case QrRegion.unused:
            bg = paintWhite;
        }

        canvas.drawRect(rect, matrix[y][x] ? paintBlack : bg);
      }
    }
  }

  @override
  bool shouldRepaint(_) => true;
}
import 'dart:typed_data';
import 'package:image/image.dart' as img;
import 'package:zxing_lib/zxing.dart';
import 'package:zxing_lib/qrcode.dart';
import 'package:zxing_lib/common.dart';

import 'package:qranalyzer/qr_info.dart';
import 'package:qranalyzer/qr_region.dart';
import 'package:qranalyzer/qr_spec.dart';
import 'package:qranalyzer/is_masked.dart';

class QrProcessor {

  static const Map<int, List<int>> _alignmentTable = {
    2: [6, 18],
    3: [6, 22],
    4: [6, 26],
    5: [6, 30],
    6: [6, 34],
    7: [6, 22, 38],
    8: [6, 24, 42],
    9: [6, 26, 46],
    10: [6, 28, 50],
    11: [6, 30, 54],
    12: [6, 32, 58],
    13: [6, 34, 62],
    14: [6, 26, 46, 66],
    15: [6, 26, 48, 70],
    16: [6, 26, 50, 74],
    17: [6, 30, 54, 78],
    18: [6, 30, 56, 82],
    19: [6, 30, 58, 86],
    20: [6, 34, 62, 90],
    21: [6, 28, 50, 72, 94],
    22: [6, 26, 50, 74, 98],
    23: [6, 30, 54, 78, 102],
    24: [6, 28, 54, 80, 106],
    25: [6, 32, 58, 84, 110],
    26: [6, 30, 58, 86, 114],
    27: [6, 34, 62, 90, 118],
    28: [6, 26, 50, 74, 98, 122],
    29: [6, 30, 54, 78, 102, 126],
    30: [6, 26, 52, 78, 104, 130],
    31: [6, 30, 56, 82, 108, 134],
    32: [6, 34, 60, 86, 112, 138],
    33: [6, 30, 58, 86, 114, 142],
    34: [6, 34, 62, 90, 118, 146],
    35: [6, 30, 54, 78, 102, 126, 150],
    36: [6, 24, 50, 76, 102, 128, 154],
    37: [6, 28, 54, 80, 106, 132, 158],
    38: [6, 32, 58, 84, 110, 136, 162],
    39: [6, 26, 54, 82, 110, 138, 166],
    40: [6, 30, 58, 86, 114, 142, 170],
  };

  /// メイン解析フロー (前処理リトライ機能付き)
  Future<(List<List<bool>> matrix, QrInfo info)> extractRawPattern(img.Image originalImage) async {
    Object? lastError;

    for (int attempt = 0; attempt < 3; attempt++) {
      try {
        img.Image processed = _applyPreprocess(originalImage, attempt);
        final Int32List argb = _convertToArgb(processed);
        final source = RGBLuminanceSource(processed.width, processed.height, argb);
        final bitmap = BinaryBitmap(HybridBinarizer(source));

        // 検出の実行
        final detectorResult = Detector(bitmap.blackMatrix).detect();
        final bm = detectorResult.bits;
        final int size = bm.width;

        final matrix = List.generate(
          size, (y) => List.generate(size, (x) => bm.get(x, y)),
        );

        // フォーマット情報の読み取り
        final int raw1 = _readFormatLocation1(matrix);
        final int raw2 = _readFormatLocation2(matrix);
        // zxing_lib の標準デコーダーに丸投げする (これが最も堅牢です)
        final formatInfo = FormatInformation.decodeFormatInformation(raw1, raw2);
        if (formatInfo == null) {
          //print("Warning: BCH error correction failed. Falling back to raw bit read.");
        }
        // 2. 失敗した場合、生データを 0x5412 で XOR して強引に EC を引っこ抜く (デバッグ用)
        String ecLevel;
        int maskPattern;
        if (formatInfo != null) {
          ecLevel = formatInfo.errorCorrectionLevel.name;
          maskPattern = formatInfo.dataMask.toInt();
        } else {
          // BCH訂正が効かないほど汚れているか、座標がズレている
          // 暫定的に raw1 からマスクを剥がして EC を推測する
          final unmasked = raw1 ^ 0x5412;
          final ecBits = (unmasked >> 13) & 0x03;
          ecLevel = ["M", "L", "H", "Q"][ecBits]; // 規格順: 00, 01, 10, 11
          maskPattern = (unmasked >> 10) & 0x07;
        }
        final int version = ((size - 21) ~/ 4) + 1;

        if (version < 1 || version > 40) {
          throw Exception("Invalid version: $version");
        }

        final (int dataCW, int eccCW) = QrSpec.get(version, ecLevel);

        return (matrix, QrInfo(
          version: version,
          ecLevel: ecLevel,
          maskPattern: maskPattern,
          size: size,
          dataCodewords: dataCW,
          eccCodewords: eccCW,
          decodedText: _tryDecodeText(bitmap),
        ));

      } catch (e) {
        lastError = e;
        continue; // 次の前処理 attempt へ
      }
    }
    throw lastError ?? Exception("Analysis failed after 3 attempts.");
  }

  /// 試行回数(attempt)に応じて画像の前処理を切り替える
  img.Image _applyPreprocess(img.Image originalImage, int attempt) {
    switch (attempt) {
      case 0:
      // 1回目: そのまま(リサイズのみ済みの状態)
        return originalImage;

      case 1:
      // 2回目: コントラスト強調 + シャープ化
      // 境界線をはっきりさせて検出率を上げる
        var processed = img.contrast(originalImage.clone(), contrast: 1.5);
        return img.convolution(processed, filter: [0, -1, 0, -1, 5, -1, 0, -1, 0]);

      case 2:
      // 3回目: 輝度による二値化
      // 露出オーバーや影が強い場合に有効
        return img.luminanceThreshold(originalImage.clone(), threshold: 0.5);

      default:
        return originalImage;
    }
  }

  /// 領域の分類(Painter用)
  List<List<QrRegion>> classifyModules(int version, int dataCW, int eccCW) {
    final size = 21 + 4 * (version - 1);
    final map = List.generate(size, (_) => List.filled(size, QrRegion.unused));

    _markFinderPatterns(map);
    _markTimingPatterns(map);
    _markFormatInfo(map);
    _markVersionInfo(map, version);
    _markAlignmentPatterns(map, version);
    _markDarkModule(map, version);

    int totalBits = (dataCW + eccCW) * 8;
    int dataBits = dataCW * 8;
    int bitIndex = 0;
    int col = size - 1;
    bool upward = true;

    while (col > 0) {
      if (col == 6) col--;
      for (int i = 0; i < size; i++) {
        int row = upward ? (size - 1 - i) : i;
        for (int c = col; c >= col - 1; c--) {
          if (map[row][c] == QrRegion.unused) {
            if (bitIndex < totalBits) {
              map[row][c] = (bitIndex < dataBits) ? QrRegion.data : QrRegion.ecc;
              bitIndex++;
            }
          }
        }
      }
      col -= 2;
      upward = !upward;
    }
    return map;
  }

  /// マスク解除
  List<List<bool>> unmaskMatrix(List<List<bool>> matrix, List<List<QrRegion>> regionMap, int mask) {
    final n = matrix.length;
    return List.generate(n, (y) => List.generate(n, (x) {
      final isData = regionMap[y][x] == QrRegion.data || regionMap[y][x] == QrRegion.ecc;
      if (!isData) return matrix[y][x];
      return isMasked(mask, x, y) ? !matrix[y][x] : matrix[y][x];
    }));
  }

  void _markAlignmentPatterns(List<List<QrRegion>> map, int version) {
    final positions = _alignmentTable[version];
    if (positions == null || positions.isEmpty) {
      return;
    }

    final n = map.length;

    for (final cy in positions) {
      for (final cx in positions) {
        // 既存の Finder Pattern 領域(周辺1セル含む)を避ける判定
        // 0〜8 (左上), n-9〜n-1 (右上/左下) あたりをカバー
        if ((cx <= 8 && cy <= 8) ||
            (cx >= n - 9 && cy <= 8) ||
            (cx <= 8 && cy >= n - 9)) {
          continue;
        }

        // 5x5 の範囲をマーク
        for (int dy = -2; dy <= 2; dy++) {
          for (int dx = -2; dx <= 2; dx++) {
            final y = cy + dy;
            final x = cx + dx;
            if (x >= 0 && x < n && y >= 0 && y < n) {
              map[y][x] = QrRegion.alignment;
            }
          }
        }
      }
    }
  }

  // 型番情報のマーク(Version 7以上)
  void _markVersionInfo(List<List<QrRegion>> map, int version) {
    if (version < 7) return;
    final size = map.length;
    // 左下の 6x3 ブロック (縦6 x 横3)
    for (int x = 0; x < 6; x++) {
      for (int y = size - 11; y < size - 8; y++) {
        map[y][x] = QrRegion.version;
      }
    }
    // 右上の 3x6 ブロック (縦3 x 横6)
    for (int y = 0; y < 6; y++) {
      for (int x = size - 11; x < size - 8; x++) {
        map[y][x] = QrRegion.version;
      }
    }
  }

  // ダークモジュールのマーク(Versionに関わらず固定位置)
  void _markDarkModule(List<List<QrRegion>> map, int version) {
    // 座標は常に (size - 8, 8)
    final size = map.length;
    map[size - 8][8] = QrRegion.format; // 役割としてはフォーマット情報に近い
  }

  Int32List _convertToArgb(img.Image image) {
    final length = image.width * image.height;
    final result = Int32List(length);
    int i = 0;
    for (final pixel in image) {
      final r = pixel.r.toInt();
      final g = pixel.g.toInt();
      final b = pixel.b.toInt();
      result[i++] = (0xFF << 24) | (r << 16) | (g << 8) | b;
    }
    return result;
  }

  /// Location 1 (左上) の読み取り: Bit 14 (MSB) -> Bit 0 (LSB)
  int _readFormatLocation1(List<List<bool>> m) {
    final List<List<int>> pixelCoordinates = [
      [0, 8], [1, 8], [2, 8], [3, 8], [4, 8], [5, 8], [7, 8], [8, 8], // 14-7
      [8, 7], [8, 5], [8, 4], [8, 3], [8, 2], [8, 1], [8, 0]          // 6-0
    ];
    int v = 0;
    for (final c in pixelCoordinates) {
      v = (v << 1) | (m[c[0]][c[1]] ? 1 : 0);
    }
    return v;
  }

  /// Location 2 (右上・左下) の読み取り: Bit 14 (MSB) -> Bit 0 (LSB)
  int _readFormatLocation2(List<List<bool>> m) {
    final int size = m.length;
    final List<List<int>> pixelCoordinates = [
      // 左下の垂直ライン (Bit 14-8)
      [size - 1, 8], [size - 2, 8], [size - 3, 8], [size - 4, 8],
      [size - 5, 8], [size - 6, 8], [size - 7, 8],
      // 右上の水平ライン (Bit 7-0)
      [8, size - 8], [8, size - 7], [8, size - 6], [8, size - 5],
      [8, size - 4], [8, size - 3], [8, size - 2], [8, size - 1]
    ];
    int v = 0;
    for (final c in pixelCoordinates) {
      v = (v << 1) | (m[c[0]][c[1]] ? 1 : 0);
    }
    return v;
  }

  String? _tryDecodeText(BinaryBitmap bitmap) {
    try {
      return QRCodeReader().decode(bitmap).text;
    } catch (_) {
      return null;
    }
  }

  void _markFinderPatterns(List<List<QrRegion>> map) {
    final size = map.length;
    void mark(int ox, int oy) {
      for (int y = oy; y < oy + 7; y++) {
        for (int x = ox; x < ox + 7; x++) { map[y][x] = QrRegion.finder; }
      }
    }
    mark(0, 0);
    mark(size - 7, 0);
    mark(0, size - 7);
  }

  void _markTimingPatterns(List<List<QrRegion>> map) {
    final size = map.length;
    for (int i = 0; i < size; i++) {
      map[6][i] = QrRegion.timing;
      map[i][6] = QrRegion.timing;
    }
  }

  void _markFormatInfo(List<List<QrRegion>> map) {
    final size = map.length;
    for (int i = 0; i <= 5; i++) {
      map[8][i] = QrRegion.format;
    }
    map[8][7] = QrRegion.format;
    map[8][8] = QrRegion.format;
    for (int i = size - 1; i >= size - 7; i--) {
      map[i][8] = QrRegion.format;
    }
  }

}
enum QrRegion {
  finder,
  alignment,
  timing,
  format,
  version,
  data,
  ecc,
  unused,
}
class QrSpec {
  // 形式: version -> ecLevel -> (dataCodewords, eccCodewords)
  static const Map<int, Map<String, (int, int)>> table = {
    1: {"L": (19, 7), "M": (16, 10), "Q": (13, 13), "H": (9, 17)},
    2: {"L": (34, 10), "M": (28, 16), "Q": (22, 22), "H": (16, 28)},
    3: {"L": (55, 15), "M": (44, 26), "Q": (34, 18), "H": (26, 22)},
    4: {"L": (80, 20), "M": (64, 18), "Q": (48, 26), "H": (36, 16)},
    5: {"L": (108, 26), "M": (86, 24), "Q": (62, 18), "H": (46, 22)},
    6: {"L": (136, 18), "M": (108, 16), "Q": (76, 24), "H": (60, 28)},
    7: {"L": (156, 20), "M": (124, 18), "Q": (88, 18), "H": (66, 26)},
    8: {"L": (194, 24), "M": (154, 22), "Q": (110, 22), "H": (86, 26)},
    9: {"L": (232, 30), "M": (182, 22), "Q": (132, 20), "H": (100, 24)},
    10: {"L": (274, 18), "M": (216, 26), "Q": (154, 24), "H": (122, 28)},
    11: {"L": (324, 20), "M": (254, 30), "Q": (180, 28), "H": (140, 24)},
    12: {"L": (370, 24), "M": (290, 22), "Q": (206, 26), "H": (158, 28)},
    13: {"L": (428, 26), "M": (334, 22), "Q": (244, 24), "H": (180, 22)},
    14: {"L": (461, 30), "M": (365, 24), "Q": (261, 20), "H": (197, 24)},
    15: {"L": (523, 22), "M": (415, 24), "Q": (295, 30), "H": (223, 24)},
    16: {"L": (589, 24), "M": (453, 28), "Q": (325, 24), "H": (253, 30)},
    17: {"L": (647, 28), "M": (507, 28), "Q": (367, 28), "H": (283, 28)},
    18: {"L": (721, 30), "M": (563, 26), "Q": (397, 28), "H": (313, 28)},
    19: {"L": (795, 28), "M": (627, 26), "Q": (445, 26), "H": (341, 26)},
    20: {"L": (861, 28), "M": (669, 26), "Q": (485, 30), "H": (385, 28)},
    21: {"L": (932, 28), "M": (714, 26), "Q": (512, 28), "H": (406, 30)},
    22: {"L": (1006, 28), "M": (782, 28), "Q": (568, 30), "H": (442, 24)},
    23: {"L": (1094, 30), "M": (860, 30), "Q": (614, 30), "H": (464, 30)},
    24: {"L": (1174, 30), "M": (914, 28), "Q": (664, 28), "H": (514, 30)},
    25: {"L": (1276, 26), "M": (1000, 30), "Q": (718, 30), "H": (538, 30)},
    26: {"L": (1370, 28), "M": (1062, 28), "Q": (754, 28), "H": (596, 30)},
    27: {"L": (1468, 30), "M": (1128, 30), "Q": (808, 30), "H": (628, 30)},
    28: {"L": (1531, 30), "M": (1193, 26), "Q": (871, 28), "H": (661, 30)},
    29: {"L": (1631, 30), "M": (1267, 28), "Q": (911, 30), "H": (701, 30)},
    30: {"L": (1735, 30), "M": (1373, 30), "Q": (985, 30), "H": (745, 30)},
    31: {"L": (1843, 30), "M": (1455, 30), "Q": (1033, 30), "H": (793, 30)},
    32: {"L": (1955, 30), "M": (1541, 30), "Q": (1115, 30), "H": (845, 30)},
    33: {"L": (2071, 30), "M": (1631, 30), "Q": (1171, 30), "H": (901, 30)},
    34: {"L": (2191, 30), "M": (1725, 30), "Q": (1231, 30), "H": (961, 30)},
    35: {"L": (2306, 30), "M": (1812, 30), "Q": (1286, 30), "H": (986, 30)},
    36: {"L": (2434, 30), "M": (1914, 30), "Q": (1354, 30), "H": (1054, 30)},
    37: {"L": (2566, 30), "M": (1992, 30), "Q": (1426, 30), "H": (1096, 30)},
    38: {"L": (2702, 30), "M": (2102, 30), "Q": (1502, 30), "H": (1142, 30)},
    39: {"L": (2812, 30), "M": (2216, 30), "Q": (1582, 30), "H": (1222, 30)},
    40: {"L": (2956, 30), "M": (2334, 30), "Q": (1666, 30), "H": (1276, 30)},
  };

  static (int dataCW, int eccCW) get(int version, String ec) {
    final versionData = table[version];
    if (versionData == null) {
      throw Exception("Unsupported QR Version: $version.");
    }

    final spec = versionData[ec];
    if (spec == null) {
      throw Exception("Unsupported EC Level: $ec for Version $version.");
    }

    return spec;
  }
}
import "package:flutter/material.dart";
import 'package:google_mobile_ads/google_mobile_ads.dart';

import "package:qranalyzer/l10n/app_localizations.dart";
import "package:qranalyzer/ad_banner_widget.dart";
import "package:qranalyzer/ad_manager.dart";
import "package:qranalyzer/ad_ump_status.dart";
import 'package:qranalyzer/loading_screen.dart';
import 'package:qranalyzer/theme_color.dart';
import 'package:qranalyzer/model.dart';

class SettingPage extends StatefulWidget {
  const SettingPage({super.key});

  @override
  State<SettingPage> createState() => _SettingPageState();
}

class _SettingPageState extends State<SettingPage> {
  late AdManager _adManager;
  late UmpConsentController _adUmp;
  AdUmpState _adUmpState = AdUmpState.initial;
  int _themeNumber = 0;
  String _languageCode = '';
  late ThemeColor _themeColor;
  bool _isReady = false;
  bool _isFirst = true;
  //
  int _schemeColor = 0;
  Color _accentColor = Colors.red;

  @override
  void initState() {
    super.initState();
    _initState();
  }

  void _initState() async {
    _adManager = AdManager();
    _themeNumber = Model.themeNumber;
    _languageCode = Model.languageCode;
    //
    _adUmp = UmpConsentController();
    _refreshConsentInfo();
    //
    _schemeColor = Model.schemeColor;
    _accentColor = _getRainbowAccentColor(_schemeColor);
    setState(() {
      _isReady = true;
    });
  }

  @override
  void dispose() {
    _adManager.dispose();
    super.dispose();
  }

  Future<void> _refreshConsentInfo() async {
    _adUmpState = await _adUmp.updateConsentInfo(current: _adUmpState);
    if (mounted) {
      setState(() {});
    }
  }

  Future<void> _onTapPrivacyOptions() async {
    final err = await _adUmp.showPrivacyOptions();
    await _refreshConsentInfo();
    if (err != null && mounted) {
      final l = AppLocalizations.of(context)!;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('${l.cmpErrorOpeningSettings} ${err.message}')),
      );
    }
  }

  Color _getRainbowAccentColor(int hue) {
    return HSVColor.fromAHSV(1.0, hue.toDouble(), 1.0, 1.0).toColor();
  }

  void _onApply() async {
    await Model.setSchemeColor(_schemeColor);
    await Model.setThemeNumber(_themeNumber);
    await Model.setLanguageCode(_languageCode);
    if (!mounted) {
      return;
    }
    Navigator.of(context).pop(true);
  }

  @override
  Widget build(BuildContext context) {
    if (!_isReady) {
      return LoadingScreen();
    }
    if (_isFirst) {
      _isFirst = false;
      _themeColor = ThemeColor(themeNumber: Model.themeNumber, context: context);
    }
    final l = AppLocalizations.of(context)!;
    return Scaffold(
      backgroundColor: _themeColor.backColor,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        leading: IconButton(
          icon: const Icon(Icons.close),
          onPressed: () => Navigator.of(context).pop(false)
        ),
        actions: [
          Padding(
            padding: const EdgeInsets.only(right: 10),
            child:IconButton(
              icon: const Icon(Icons.check),
              onPressed: _onApply,
            )
          ),
        ],
      ),
      body: SafeArea(
        child: Column(children:[
          Expanded(
            child: GestureDetector(
              onTap: () => FocusScope.of(context).unfocus(),  //背景タップでキーボードを仕舞う
              child: SingleChildScrollView(
                child: Padding(
                  padding: const EdgeInsets.only(left: 16, right: 16, top: 0, bottom: 100),
                  child: Column(children: [
                    _buildBackgroundColor(l),
                    _buildTheme(l),
                    _buildLanguage(l),
                    _buildCmp(l),
                    _buildUsage(l),
                  ]),
                ),
              ),
            ),
          ),
        ])
      ),
      bottomNavigationBar: AdBannerWidget(adManager: _adManager),
    );
  }

  Widget _buildBackgroundColor(AppLocalizations l) {
    return Card(
      margin: const EdgeInsets.only(left: 0, top: 12, right: 0, bottom: 0),
      color: _themeColor.cardColor,
      elevation: 0,
      shadowColor: Colors.transparent,
      surfaceTintColor: Colors.transparent,
      child: Column(
        children: [
          Padding(
            padding: const EdgeInsets.only(left: 16, right: 16, top: 16),
            child: Row(
              children: [
                Text(l.colorScheme),
                const Spacer(),
              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(left: 16, right: 16),
            child: Row(
              children: <Widget>[
                Text(_schemeColor.toStringAsFixed(0)),
                Expanded(
                  child: SliderTheme(
                    data: SliderTheme.of(context).copyWith(
                      activeTrackColor: _accentColor,
                      inactiveTrackColor: _accentColor.withValues(alpha: 0.3),
                      thumbColor: _accentColor,
                      overlayColor: _accentColor.withValues(alpha: 0.2),
                      valueIndicatorColor: _accentColor,
                    ),
                    child: Slider(
                      value: _schemeColor.toDouble(),
                      min: 0,
                      max: 360,
                      divisions: 360,
                      label: _schemeColor.toString(),
                      onChanged: (double value) {
                        setState(() {
                          _schemeColor = value.toInt();
                          _accentColor = _getRainbowAccentColor(_schemeColor);
                        });
                      }
                    )
                  )
                ),
              ],
            ),
          ),
        ],
      )
    );
  }

  Widget _buildTheme(AppLocalizations l) {
    final TextTheme t = Theme.of(context).textTheme;
    return Card(
      margin: const EdgeInsets.only(left: 0, top: 12, right: 0, bottom: 0),
      color: _themeColor.cardColor,
      elevation: 0,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
        child: Row(
          children: [
            Expanded(
              child: Text(
                l.theme,
                style: t.bodyMedium,
              ),
            ),
            DropdownButton<int>(
              value: _themeNumber,
              items: [
                DropdownMenuItem(value: 0, child: Text(l.systemSetting)),
                DropdownMenuItem(value: 1, child: Text(l.lightTheme)),
                DropdownMenuItem(value: 2, child: Text(l.darkTheme)),
              ],
              onChanged: (value) {
                if (value != null) {
                  setState(() {
                    _themeNumber = value;
                  });
                }
              },
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildLanguage(AppLocalizations l) {
    final Map<String,String> languageNames = {
      'af': 'af: Afrikaans',
      'ar': 'ar: العربية',
      'bg': 'bg: Български',
      'bn': 'bn: বাংলা',
      'bs': 'bs: Bosanski',
      'ca': 'ca: Català',
      'cs': 'cs: Čeština',
      'da': 'da: Dansk',
      'de': 'de: Deutsch',
      'el': 'el: Ελληνικά',
      'en': 'en: English',
      'es': 'es: Español',
      'et': 'et: Eesti',
      'fa': 'fa: فارسی',
      'fi': 'fi: Suomi',
      'fil': 'fil: Filipino',
      'fr': 'fr: Français',
      'gu': 'gu: ગુજરાતી',
      'he': 'he: עברית',
      'hi': 'hi: हिन्दी',
      'hr': 'hr: Hrvatski',
      'hu': 'hu: Magyar',
      'id': 'id: Bahasa Indonesia',
      'it': 'it: Italiano',
      'ja': 'ja: 日本語',
      //'jv': 'jv: Basa Jawa',    //flutterのサポート外
      'km': 'km: ខ្មែរ',
      'kn': 'kn: ಕನ್ನಡ',
      'ko': 'ko: 한국어',
      'lt': 'lt: Lietuvių',
      'lv': 'lv: Latviešu',
      'ml': 'ml: മലയാളം',
      'mr': 'mr: मराठी',
      'ms': 'ms: Bahasa Melayu',
      'my': 'my: မြန်မာ',
      'ne': 'ne: नेपाली',
      'nl': 'nl: Nederlands',
      'or': 'or: ଓଡ଼ିଆ',
      'pa': 'pa: ਪੰਜਾਬੀ',
      'pl': 'pl: Polski',
      'pt': 'pt: Português',
      'ro': 'ro: Română',
      'ru': 'ru: Русский',
      'si': 'si: සිංහල',
      'sk': 'sk: Slovenčina',
      'sr': 'sr: Српски',
      'sv': 'sv: Svenska',
      'sw': 'sw: Kiswahili',
      'ta': 'ta: தமிழ்',
      'te': 'te: తెలుగు',
      'th': 'th: ไทย',
      'tl': 'tl: Tagalog',
      'tr': 'tr: Türkçe',
      'uk': 'uk: Українська',
      'ur': 'ur: اردو',
      'uz': 'uz: Oʻzbekcha',
      'vi': 'vi: Tiếng Việt',
      'zh': 'zh: 中文',
      'zu': 'zu: isiZulu',
    };
    final TextTheme t = Theme.of(context).textTheme;
    return Card(
      margin: const EdgeInsets.only(left: 0, top: 12, right: 0, bottom: 0),
      color: _themeColor.cardColor,
      elevation: 0,
      shadowColor: Colors.transparent,
      surfaceTintColor: Colors.transparent,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
        child: Row(
          children: [
            Expanded(
              child: Text(
                l.language,
                style: t.bodyMedium,
              ),
            ),
            DropdownButton<String?>(
              value: _languageCode,
              items: [
                DropdownMenuItem(value: '', child: Text('Default')),
                ...languageNames.entries.map((entry) => DropdownMenuItem<String?>(
                  value: entry.key,
                  child: Text(entry.value),
                )),
              ],
              onChanged: (String? value) {
                setState(() {
                  _languageCode = value ?? '';
                });
              },
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildCmp(AppLocalizations l) {
    final TextTheme t = Theme.of(context).textTheme;
    final showButton = _adUmpState.privacyStatus == PrivacyOptionsRequirementStatus.required;
    String statusLabel = l.cmpCheckingRegion;
    IconData statusIcon = Icons.help_outline;
    switch (_adUmpState.privacyStatus) {
      case PrivacyOptionsRequirementStatus.required:
        statusLabel = l.cmpRegionRequiresSettings;
        statusIcon = Icons.privacy_tip_outlined;
        break;
      case PrivacyOptionsRequirementStatus.notRequired:
        statusLabel = l.cmpRegionNoSettingsRequired;
        statusIcon = Icons.check_circle_outline;
        break;
      case PrivacyOptionsRequirementStatus.unknown:
        statusLabel = l.cmpRegionCheckFailed;
        statusIcon = Icons.error_outline;
        break;
    }
    return Card(
      margin: const EdgeInsets.only(left: 0, top: 12, right: 0, bottom: 0),
      color: _themeColor.cardColor,
      elevation: 0,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              l.cmpSettingsTitle,
              style: t.bodyMedium,
            ),
            const SizedBox(height: 8),
            Text(
              l.cmpConsentDescription,
              style: t.bodySmall,
            ),
            const SizedBox(height: 16),
            Center(
              child: Column(
                children: [
                  Chip(
                    avatar: Icon(statusIcon, size: 18),
                    label: Text(statusLabel),
                  ),
                  const SizedBox(height: 6),
                  Text(
                    '${l.cmpConsentStatusLabel} ${_adUmpState.consentStatus.localized(context)}',
                    style: t.bodySmall,
                  ),
                  if (showButton) ...[
                    const SizedBox(height: 16),
                    ElevatedButton.icon(
                      onPressed: _adUmpState.isChecking
                          ? null
                          : _onTapPrivacyOptions,
                      icon: const Icon(Icons.settings),
                      label: Text(
                        _adUmpState.isChecking
                            ? l.cmpConsentStatusChecking
                            : l.cmpOpenConsentSettings,
                      ),
                    ),
                    const SizedBox(height: 12),
                    OutlinedButton.icon(
                      onPressed: _adUmpState.isChecking
                          ? null
                          : _refreshConsentInfo,
                      icon: const Icon(Icons.refresh),
                      label: Text(l.cmpRefreshStatus),
                    ),
                    const SizedBox(height: 12),
                    OutlinedButton.icon(
                      onPressed: () async {
                        final messenger = ScaffoldMessenger.of(context);
                        final message = l.cmpResetStatusDone;
                        await ConsentInformation.instance.reset();
                        await _refreshConsentInfo();
                        if (!mounted) {
                          return;
                        }
                        messenger.showSnackBar(
                          SnackBar(content: Text(message)),
                        );
                      },
                      icon: const Icon(Icons.delete_sweep_outlined),
                      label: Text(l.cmpResetStatus),
                    ),
                  ],
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildUsage(AppLocalizations l) {
    final TextTheme t = Theme.of(context).textTheme;
    return SizedBox(
      width: double.infinity,
      child: Card(
        margin: const EdgeInsets.only(left: 0, top: 12, right: 0, bottom: 0),
        color: _themeColor.cardColor,
        elevation: 0,
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(l.usage1, style: t.bodyMedium),
            ],
          ),
        ),
      )
    );
  }

}
import 'package:flutter/material.dart';

import 'package:qranalyzer/model.dart';

class ThemeColor {
  final int? themeNumber;
  final BuildContext context;

  ThemeColor({this.themeNumber, required this.context});

  Brightness get _effectiveBrightness {
    switch (themeNumber) {
      case 1:
        return Brightness.light;
      case 2:
        return Brightness.dark;
      default:
        return Theme.of(context).brightness;
    }
  }

  Color _getRainbowAccentColor(int hue, double saturation) {
    return HSVColor.fromAHSV(1.0, hue.toDouble(), saturation, 1.0).toColor();
  }

  bool get _isLight => _effectiveBrightness == Brightness.light;

  //main page
  Color get mainBackColor => _isLight ? Color.fromRGBO(200,200,200, 1.0) : Color.fromRGBO(30,30,30, 1.0);
  Color get mainBack2Color => _isLight ? Color.fromRGBO(255,255,255, 1.0) : Color.fromRGBO(50,50,50, 1.0);
  Color get mainCardColor => _isLight ? Color.fromRGBO(255, 255, 255, 1.0) : Color.fromRGBO(51, 51, 51, 1.0);
  Color get mainForeColor => _isLight ? Color.fromRGBO(17, 17, 17, 1.0) : Color.fromRGBO(200, 200, 200, 1.0);
  Color get mainAccentForeColor => _getRainbowAccentColor(Model.schemeColor,0.6);
  //setting page
  Color get backColor => _isLight ? Colors.grey[200]! : Colors.grey[900]!;
  Color get cardColor => _isLight ? Colors.white : Colors.grey[800]!;
  Color get appBarForegroundColor => _isLight ? Colors.grey[700]! : Colors.white70;
  Color get dropdownColor => cardColor;
  Color get borderColor => _isLight ? Colors.grey[300]! : Colors.grey[700]!;
  Color get inputFillColor => _isLight ? Colors.grey[50]! : Colors.grey[900]!;
}
import 'package:flutter/material.dart';

class ThemeModeNumber {
  static ThemeMode numberToThemeMode(int value) {
    switch (value) {
      case 1:
        return ThemeMode.light;
      case 2:
        return ThemeMode.dark;
      default:
        return ThemeMode.system;
    }
  }
}
import 'package:flutter/material.dart';

import 'package:qranalyzer/qr_region.dart';

class UnmaskedPainter extends CustomPainter {
  final List<List<bool>> matrix;
  final List<List<QrRegion>> regionMap;

  UnmaskedPainter(this.matrix, this.regionMap);

  @override
  void paint(Canvas canvas, Size size) {
    final int n = matrix.length;
    final double cell = size.width / n;
    final Paint paintDark = Paint()..color = Colors.black;
    final Paint paintLight = Paint()..color = Colors.white;
    for (int y = 0; y < n; y++) {
      for (int x = 0; x < n; x++) {
        final region = regionMap[y][x];
        final rect = Rect.fromLTWH(x * cell, y * cell, cell, cell);
        Paint p = matrix[y][x] ? paintDark : paintLight;
        if (region == QrRegion.unused || region == QrRegion.finder || region == QrRegion.alignment) {   // unused,finder,alignment を除外
          p = paintDark;
        }
        canvas.drawRect(rect, p);
      }
    }
  }

  @override
  bool shouldRepaint(_) => true;
}