diff --git a/basic_flutter/.metadata b/basic_flutter/.metadata index cb12308..f941867 100644 --- a/basic_flutter/.metadata +++ b/basic_flutter/.metadata @@ -4,7 +4,7 @@ # This file should be version controlled and should not be manually edited. version: - revision: 3595343e20a61ff16d14e8ecc25f364276bb1b8b - channel: stable + revision: 4b330ddbedab445481cc73d50a4695b9154b4e4f + channel: dev project_type: app diff --git a/basic_flutter/.vscode/cpx.json b/basic_flutter/.vscode/cpx.json new file mode 100644 index 0000000..9e26dfe --- /dev/null +++ b/basic_flutter/.vscode/cpx.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/basic_flutter/.vscode/launch.json b/basic_flutter/.vscode/launch.json new file mode 100644 index 0000000..22bab79 --- /dev/null +++ b/basic_flutter/.vscode/launch.json @@ -0,0 +1,13 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": "basic_flutter", + "request": "launch", + "type": "dart", + } + ] +} \ No newline at end of file diff --git a/basic_flutter/.vscode/settings.json b/basic_flutter/.vscode/settings.json new file mode 100644 index 0000000..3442d14 --- /dev/null +++ b/basic_flutter/.vscode/settings.json @@ -0,0 +1,6 @@ +{ + "python.linting.pylintArgs": [ + "--init-hook", + "import sys; sys.path.extend([\"\"c:\\\\Users\\\\tdalmaz\\\\.vscode\\\\extensions\\\\ms-python.devicesimulatorexpress-2020.0.36321\\\\out\"\",\"\"c:\\\\Users\\\\tdalmaz\\\\.vscode\\\\extensions\\\\ms-python.devicesimulatorexpress-2020.0.36321\\\\out\\\\micropython\"\",\"\"c:\\\\Users\\\\tdalmaz\\\\.vscode\\\\extensions\\\\ms-python.devicesimulatorexpress-2020.0.36321\\\\out\\\\clue\"\",\"\"c:\\\\Users\\\\tdalmaz\\\\.vscode\\\\extensions\\\\ms-python.devicesimulatorexpress-2020.0.36321\\\\out\\\\base_circuitpython\"\"])" + ] +} \ No newline at end of file diff --git a/basic_flutter/README.md b/basic_flutter/README.md index 3a78cb5..4ccaf3b 100644 --- a/basic_flutter/README.md +++ b/basic_flutter/README.md @@ -1,4 +1,4 @@ -# basic_flutter +# basic-flutter A new Flutter project. diff --git a/basic_flutter/analysis_options.yaml b/basic_flutter/analysis_options.yaml index 7e6af4e..61b6c4d 100644 --- a/basic_flutter/analysis_options.yaml +++ b/basic_flutter/analysis_options.yaml @@ -22,55 +22,6 @@ linter: # `// ignore_for_file: name_of_lint` syntax on the line or in the file # producing the lint. rules: - - always_require_non_null_named_parameters - - annotate_overrides - - avoid_function_literals_in_foreach_calls - - avoid_init_to_null - - avoid_null_checks_in_equality_operators - - avoid_renaming_method_parameters - - avoid_return_types_on_setters - - avoid_returning_null_for_void - - avoid_single_cascade_in_expression_statements - - constant_identifier_names - - control_flow_in_finally - - empty_constructor_bodies - - empty_statements - - exhaustive_cases - - implementation_imports - - library_names - - library_prefixes - - null_closures - - overridden_fields - - package_names - - prefer_adjacent_string_concatenation - - prefer_collection_literals - - prefer_conditional_assignment - - prefer_contains - - prefer_equal_for_default_values - - prefer_final_fields - - prefer_for_elements_to_map_fromIterable - - prefer_function_declarations_over_variables - - prefer_if_null_operators - - prefer_initializing_formals - - prefer_inlined_adds - - prefer_is_not_operator - - prefer_null_aware_operators - - prefer_spread_collections - - prefer_void_to_null - - recursive_getters - - slash_for_doc_comments - - type_init_formals - - unnecessary_brace_in_string_interps - - unnecessary_const - - unnecessary_getters_setters - - unnecessary_new - - unnecessary_null_in_if_null_operators - - unnecessary_string_escapes - - unnecessary_string_interpolations - - unnecessary_this - - use_function_type_syntax_for_parameters - - use_rethrow_when_possible - # avoid_print: false # Uncomment to disable the `avoid_print` rule # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule diff --git a/basic_flutter/android/app/build.gradle b/basic_flutter/android/app/build.gradle index 471c5b7..6aee08d 100644 --- a/basic_flutter/android/app/build.gradle +++ b/basic_flutter/android/app/build.gradle @@ -43,7 +43,7 @@ android { defaultConfig { // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). - applicationId "com.example.basic_flutter" + applicationId "com.example.employee_dialog1" minSdkVersion 16 targetSdkVersion 30 versionCode flutterVersionCode.toInteger() diff --git a/basic_flutter/android/app/src/debug/AndroidManifest.xml b/basic_flutter/android/app/src/debug/AndroidManifest.xml index 209a133..8785717 100644 --- a/basic_flutter/android/app/src/debug/AndroidManifest.xml +++ b/basic_flutter/android/app/src/debug/AndroidManifest.xml @@ -1,5 +1,5 @@ + package="com.example.employee_dialog1"> diff --git a/basic_flutter/android/app/src/main/AndroidManifest.xml b/basic_flutter/android/app/src/main/AndroidManifest.xml index f822091..7ca29d1 100644 --- a/basic_flutter/android/app/src/main/AndroidManifest.xml +++ b/basic_flutter/android/app/src/main/AndroidManifest.xml @@ -1,7 +1,7 @@ + package="com.example.employee_dialog1"> - - diff --git a/basic_flutter/android/app/src/main/kotlin/com/example/employee_dialog1/MainActivity.kt b/basic_flutter/android/app/src/main/kotlin/com/example/employee_dialog1/MainActivity.kt new file mode 100644 index 0000000..c5366e9 --- /dev/null +++ b/basic_flutter/android/app/src/main/kotlin/com/example/employee_dialog1/MainActivity.kt @@ -0,0 +1,6 @@ +package com.example.employee_dialog1 + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity: FlutterActivity() { +} diff --git a/basic_flutter/android/app/src/main/kotlin/com/example/workspaces/MainActivity.kt b/basic_flutter/android/app/src/main/kotlin/com/example/workspaces/MainActivity.kt new file mode 100644 index 0000000..c8ec676 --- /dev/null +++ b/basic_flutter/android/app/src/main/kotlin/com/example/workspaces/MainActivity.kt @@ -0,0 +1,6 @@ +package com.example.workspaces + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity: FlutterActivity() { +} diff --git a/basic_flutter/android/app/src/profile/AndroidManifest.xml b/basic_flutter/android/app/src/profile/AndroidManifest.xml index 209a133..8785717 100644 --- a/basic_flutter/android/app/src/profile/AndroidManifest.xml +++ b/basic_flutter/android/app/src/profile/AndroidManifest.xml @@ -1,5 +1,5 @@ + package="com.example.employee_dialog1"> diff --git a/basic_flutter/assets/employee1.jpg b/basic_flutter/assets/employee1.jpg new file mode 100644 index 0000000..263a135 Binary files /dev/null and b/basic_flutter/assets/employee1.jpg differ diff --git a/basic_flutter/assets/employee2.jpg b/basic_flutter/assets/employee2.jpg new file mode 100644 index 0000000..c3fe52e Binary files /dev/null and b/basic_flutter/assets/employee2.jpg differ diff --git a/basic_flutter/assets/employee3.jpg b/basic_flutter/assets/employee3.jpg new file mode 100644 index 0000000..1a86a77 Binary files /dev/null and b/basic_flutter/assets/employee3.jpg differ diff --git a/basic_flutter/ios/Runner.xcodeproj/project.pbxproj b/basic_flutter/ios/Runner.xcodeproj/project.pbxproj index 4b45840..37e8cf9 100644 --- a/basic_flutter/ios/Runner.xcodeproj/project.pbxproj +++ b/basic_flutter/ios/Runner.xcodeproj/project.pbxproj @@ -3,7 +3,7 @@ archiveVersion = 1; classes = { }; - objectVersion = 46; + objectVersion = 50; objects = { /* Begin PBXBuildFile section */ @@ -127,7 +127,7 @@ 97C146E61CF9000F007C117D /* Project object */ = { isa = PBXProject; attributes = { - LastUpgradeCheck = 1020; + LastUpgradeCheck = 1300; ORGANIZATIONNAME = ""; TargetAttributes = { 97C146ED1CF9000F007C117D = { @@ -290,8 +290,11 @@ 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.basicFlutter; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.example.employeeDialog1; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_VERSION = 5.0; @@ -399,7 +402,8 @@ MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; }; @@ -414,8 +418,11 @@ 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.basicFlutter; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.example.employeeDialog1; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; @@ -433,8 +440,11 @@ 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.basicFlutter; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.example.employeeDialog1; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_VERSION = 5.0; diff --git a/basic_flutter/ios/Runner/Info.plist b/basic_flutter/ios/Runner/Info.plist index d06e9da..641021b 100644 --- a/basic_flutter/ios/Runner/Info.plist +++ b/basic_flutter/ios/Runner/Info.plist @@ -11,7 +11,7 @@ CFBundleInfoDictionaryVersion 6.0 CFBundleName - basic_flutter + employee_dialog1 CFBundlePackageType APPL CFBundleShortVersionString diff --git a/basic_flutter/lib/data/employee.dart b/basic_flutter/lib/data/employee.dart index 835e1dd..e7438aa 100644 --- a/basic_flutter/lib/data/employee.dart +++ b/basic_flutter/lib/data/employee.dart @@ -1,19 +1,75 @@ class Employee { - late String firstName; - late String lastName; - late int id; - late String email; + final String imagePath; + final String id; + final String firstName; + final String lastName; + final String profession; + final String country; + final String email; + final String phone; + final String location; + final bool isDarkMode; - Employee( - {required this.firstName, - required this.email, - required this.id, - required this.lastName}); + const Employee({ + required this.imagePath, + required this.id, + required this.firstName, + required this.lastName, + required this.profession, + required this.country, + required this.email, + required this.phone, + required this.location, + required this.isDarkMode, + }); - Employee.fromJson(Map json) { - firstName = json['name']; - lastName = json['surname']; - id = json['employeeId']; - email = json['email']; - } + Employee copy({ + String? imagePath, + String? id, + String? firstName, + String? lastName, + String? profession, + String? country, + String? email, + String? phone, + String? location, + bool? isDarkMode, + }) => + Employee( + imagePath: imagePath ?? this.imagePath, + id: id ?? this.id, + firstName: firstName ?? this.firstName, + lastName: lastName ?? this.lastName, + profession: profession ?? this.profession, + country: country ?? this.country, + email: email ?? this.email, + phone: phone ?? this.phone, + location: location ?? this.location, + isDarkMode: isDarkMode ?? this.isDarkMode); + + static Employee fromJson(Map json) => Employee( + imagePath: json['imagePath'], + id: json['ID'], + firstName: json['First Name'], + lastName: json['last Name'], + profession: json['profession'], + country: json['country'], + email: json['email'], + phone: json['phone'], + location: json['location'], + isDarkMode: json['isDarkMode'], + ); + + Map toJson() => { + 'imagePath': imagePath, + 'ID': id, + 'First Name': firstName, + 'Last Name': lastName, + 'profession': profession, + 'country': country, + 'email': email, + 'phone': phone, + 'location': location, + 'isDarkMode': isDarkMode, + }; } diff --git a/basic_flutter/lib/main.dart b/basic_flutter/lib/main.dart index c46d61a..931fc72 100644 --- a/basic_flutter/lib/main.dart +++ b/basic_flutter/lib/main.dart @@ -1,72 +1,32 @@ -import 'package:basic_flutter/presentation/screens/employee_dialog.dart'; - -import '/presentation/screens/employees_list_screen.dart'; import 'package:flutter/material.dart'; -import './data/routes.dart'; - -import '/presentation/screens/employees_list_screen.dart'; -import './data/routes.dart'; -import '/presentation/screens/employee_dialog.dart'; - -void main() { +import 'package:animated_theme_switcher/animated_theme_switcher.dart'; +import '../themes.dart'; +import '../../presentation/screens/profile_page.dart'; +import '../../presentation/screens/employee_preferences.dart'; + +Future main() async { + WidgetsFlutterBinding.ensureInitialized(); + EmployeePreferences.init(); + await EmployeePreferences.init(); runApp(const MyApp()); } class MyApp extends StatelessWidget { + static const String title = 'Employee Profile'; const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { - return MaterialApp( - - title: "Employee App", - home: const MyHomePage(), - routes: { - Routes.employeeListScreenRouteName: (context) => - const EmployeesListScreen(), - Routes.employeeDialogRouteName: (context) => const EmployeeDialog(), - }, - theme: ThemeData( - primaryColor: Colors.blue.shade900, - splashColor: Colors.blue, - textTheme: ThemeData.light().textTheme.copyWith( - headline6: const TextStyle( - fontFamily: 'Raleway-Bold', - fontSize: 20, - color: Colors.black, - ), - ), - ), - ); - } -} - -class MyHomePage extends StatefulWidget { - const MyHomePage({Key? key}) : super(key: key); - - @override - _MyHomePageState createState() => _MyHomePageState(); -} - -class _MyHomePageState extends State { - @override - Widget build(BuildContext context) { - return Scaffold( - appBar: AppBar( - title: const Text('Employee App'), - backgroundColor: Theme.of(context).primaryColor, - centerTitle: true, - ), - body: Center( - child: ElevatedButton( - onPressed: () { - Navigator.pushNamed(context, Routes.employeeListScreenRouteName); - }, - child: const Text('Get Employees List'), - style: ButtonStyle( - backgroundColor: - MaterialStateProperty.all(Theme.of(context).primaryColor), - ), + const employee = EmployeePreferences.myEmployee; + + return ThemeProvider( + initTheme: employee.isDarkMode ? MyThemes.darkTheme : MyThemes.lightTheme, + child: Builder( + builder: (context) => MaterialApp( + debugShowCheckedModeBanner: false, + theme: ThemeProvider.of(context), + title: title, + home: const ProfilePage(employee: EmployeePreferences.myEmployee), ), ), ); diff --git a/basic_flutter/lib/presentation/screens/edit_profile_page.dart b/basic_flutter/lib/presentation/screens/edit_profile_page.dart new file mode 100644 index 0000000..e7ba42d --- /dev/null +++ b/basic_flutter/lib/presentation/screens/edit_profile_page.dart @@ -0,0 +1,193 @@ +import 'dart:io'; +import 'package:path/path.dart'; +import 'package:flutter/material.dart'; +import 'package:image_picker/image_picker.dart'; +import 'package:path_provider/path_provider.dart'; +import 'package:animated_theme_switcher/animated_theme_switcher.dart'; +import '../../data/employee.dart'; +import '../../presentation/screens/employee_preferences.dart'; +import '../../presentation/widget/button_widget.dart'; +import '../../presentation/widget/profile_widget.dart'; +import '../../presentation/widget/textfield_widget.dart'; +import '../../themes.dart'; + +class EditProfilePage extends StatefulWidget { + const EditProfilePage({Key? key}) : super(key: key); + + @override + _EditProfilePageState createState() => _EditProfilePageState(); +} + +class _EditProfilePageState extends State { + late Employee employee; + + @override + void initState() { + super.initState(); + employee = EmployeePreferences.getEmployee(); + } + + Widget buildEditIcon(Color color, BuildContext context) => buildCircle( + color: Colors.white, + all: 3, + child: buildCircle( + color: color, + all: 10, + child: GestureDetector( + onTap: () async { + final image = + await ImagePicker().getImage(source: ImageSource.gallery); + + if (image == null) return; + + final directory = await getApplicationDocumentsDirectory(); + final name = basename(image.path); + final imageFile = File('${directory.path}/$name'); + final newImage = await File(image.path).copy(imageFile.path); + + setState( + () => employee = employee.copy(imagePath: newImage.path)); + }, + child: const Icon( + Icons.add_a_photo, + color: Colors.white, + size: 20, + ), + ), + ), + ); + + Widget buildCircle({ + required Widget child, + required double all, + required Color color, + }) => + ClipOval( + child: Container( + padding: EdgeInsets.all(all), + color: color, + child: child, + ), + ); + + @override + Widget build(BuildContext context) => Scaffold( + appBar: buildEditAppBar(context), + body: SingleChildScrollView( + child: Container( + padding: EdgeInsets.symmetric( + horizontal: MediaQuery.of(context).size.width * 0.1), + child: Column( + children: [ + SizedBox( + width: double.infinity, + height: MediaQuery.of(context).size.height, + child: ListView( + children: [ + SizedBox( + width: double.infinity, + height: MediaQuery.of(context).size.height * 0.28, + child: ProfileWidget( + imagePath: employee.imagePath, + isEdit: true, + onClicked: () {}, + sentWidget: Positioned( + bottom: 0, + right: 4, + child: + buildEditIcon(Colors.blue.shade900, context), + ), + )), + const SizedBox(height: 40), + TextFieldWidget( + label: 'First Name', + text: employee.firstName, + onChanged: (firstName) => + employee = employee.copy(firstName: firstName), + ), + const SizedBox(height: 40), + TextFieldWidget( + label: 'Last Name', + text: employee.lastName, + onChanged: (lastName) => + employee = employee.copy(lastName: lastName), + ), + const SizedBox(height: 20), + TextFieldWidget( + label: 'Profession', + text: employee.profession, + onChanged: (profession) => + employee = employee.copy(profession: profession), + ), + const SizedBox(height: 20), + TextFieldWidget( + label: 'Country', + text: employee.country, + onChanged: (country) => + employee = employee.copy(country: country), + ), + const SizedBox(height: 20), + TextFieldWidget( + label: 'Phone number', + text: employee.phone, + onChanged: (phone) => + employee = employee.copy(phone: phone), + ), + const SizedBox(height: 20), + TextFieldWidget( + label: 'Email address', + text: employee.email, + onChanged: (email) => + employee = employee.copy(email: email), + ), + const SizedBox(height: 20), + TextFieldWidget( + label: 'Location', + text: employee.location, + onChanged: (location) => + employee = employee.copy(location: location), + ), + const SizedBox(height: 40), + ButtonWidget( + text: 'Save', + onClicked: () { + EmployeePreferences.setEmployee(employee); + Navigator.of(context).pop(); + }), + const SizedBox(height: 150), + ], + ), + ), + ], + ), + ), + ), + ); +} + +AppBar buildEditAppBar(BuildContext context) { + final isDarkMode = Theme.of(context).brightness == Brightness.dark; + final icon = isDarkMode ? Icons.light_mode : Icons.dark_mode; + + return AppBar( + backgroundColor: Colors.blue.shade900, + title: const Text('Employee dialog'), + centerTitle: true, + leading: const BackButton( + color: Colors.white, + ), + elevation: 0, + actions: [ + ThemeSwitcher( + builder: (context) => IconButton( + icon: Icon(icon), + onPressed: () { + final theme = isDarkMode ? MyThemes.lightTheme : MyThemes.darkTheme; + final switcher = ThemeSwitcher.of(context)!; + switcher.changeTheme(theme: theme); + }, + ), + ), + ], + ); +} diff --git a/basic_flutter/lib/presentation/screens/employee_preferences.dart b/basic_flutter/lib/presentation/screens/employee_preferences.dart new file mode 100644 index 0000000..cc8851e --- /dev/null +++ b/basic_flutter/lib/presentation/screens/employee_preferences.dart @@ -0,0 +1,37 @@ +import 'dart:convert'; +import 'package:shared_preferences/shared_preferences.dart'; +import '../../data/employee.dart'; + +class EmployeePreferences { + static late SharedPreferences _preferences; + + static const _keyEmployee = 'employee'; + static const myEmployee = Employee( + imagePath: + 'https://raw.githubusercontent.com/devonfw-sample/basic-flutter/d988700d786af494b2b2ef4877cb6a06fc545dda/employee_dialog/assets/employee1.jpg', + id: '123456789', + firstName: 'Max', + lastName: 'Mustermann', + profession: 'Senior Delivery Architect CSS', + country: 'Germany', + email: 'max.mustermann@muster.com', + phone: '+490123456789', + location: 'DE-HH-K', + isDarkMode: false, + ); + + static Future init() async => + _preferences = await SharedPreferences.getInstance(); + + static Future setEmployee(Employee employee) async { + final json = jsonEncode(employee.toJson()); + + await _preferences.setString(_keyEmployee, json); + } + + static Employee getEmployee() { + final json = _preferences.getString(_keyEmployee); + + return json == null ? myEmployee : Employee.fromJson(jsonDecode(json)); + } +} diff --git a/basic_flutter/lib/presentation/screens/profile_page.dart b/basic_flutter/lib/presentation/screens/profile_page.dart new file mode 100644 index 0000000..70e0bac --- /dev/null +++ b/basic_flutter/lib/presentation/screens/profile_page.dart @@ -0,0 +1,86 @@ +import 'package:animated_theme_switcher/animated_theme_switcher.dart'; +import 'package:basic_flutter/presentation/widget/build_name_widget.dart'; +import 'package:flutter/material.dart'; +import '../../data/employee.dart'; +import '../../presentation/screens/employee_preferences.dart'; +import '../../presentation/widget/profile_widget.dart'; +import '../../presentation/widget/build_contact_widget.dart'; +import '../../presentation/screens/edit_profile_page.dart'; +import '../../themes.dart'; + +class ProfilePage extends StatelessWidget { + final Employee employee; + const ProfilePage({Key? key, required this.employee}) : super(key: key); + + @override + Widget build(BuildContext context) { + final employee = EmployeePreferences.getEmployee(); + + return Scaffold( + appBar: buildAppBar(context), + body: SingleChildScrollView( + child: Column( + children: [ + SizedBox( + width: double.infinity, + height: MediaQuery.of(context).size.height, + child: Column( + children: [ + SizedBox( + width: double.infinity, + height: MediaQuery.of(context).size.height * 0.30, + child: ProfileWidget( + imagePath: employee.imagePath, + onClicked: () {}, + sentWidget: const SizedBox( + width: 0.0, + height: 0.0, + ), + ), + ), + const SizedBox(height: 24), + BuildNameWidget(employee: employee), + const SizedBox(height: 5), + BuildContactWidget(employee: employee), + ], + ), + ), + ], + ), + ), + ); + } +} + +AppBar buildAppBar(BuildContext context) { + final isDarkMode = Theme.of(context).brightness == Brightness.dark; + final icon = isDarkMode ? Icons.light_mode : Icons.dark_mode; + + return AppBar( + backgroundColor: Colors.blue.shade900, + title: const Text('Employee dialog'), + centerTitle: true, + leading: const BackButton( + color: Colors.white, + ), + elevation: 0, + actions: [ + IconButton( + icon: const Icon(Icons.edit), + onPressed: () { + Navigator.of(context).push(MaterialPageRoute( + builder: (context) => const EditProfilePage())); + }), + ThemeSwitcher( + builder: (context) => IconButton( + icon: Icon(icon), + onPressed: () { + final theme = isDarkMode ? MyThemes.lightTheme : MyThemes.darkTheme; + final switcher = ThemeSwitcher.of(context)!; + switcher.changeTheme(theme: theme); + }, + ), + ), + ], + ); +} diff --git a/basic_flutter/lib/presentation/widget/build_contact_widget.dart b/basic_flutter/lib/presentation/widget/build_contact_widget.dart new file mode 100644 index 0000000..9a44185 --- /dev/null +++ b/basic_flutter/lib/presentation/widget/build_contact_widget.dart @@ -0,0 +1,41 @@ +import 'package:flutter/material.dart'; +import '../../data/employee.dart'; + +class BuildContactWidget extends StatelessWidget { + const BuildContactWidget({Key? key, required this.employee}) + : super(key: key); + final Employee employee; + + @override + Widget build(BuildContext context) { + return Container( + padding: EdgeInsets.symmetric( + horizontal: MediaQuery.of(context).size.width * 0.1), + child: SizedBox( + height: MediaQuery.of(context).size.height * 0.3, + child: ListView( + children: [ + const Padding( + padding: EdgeInsets.symmetric(horizontal: 15), + child: Text("Contact", + textAlign: TextAlign.left, + style: TextStyle(fontSize: 16, fontWeight: FontWeight.w700)), + ), + ListTile( + leading: const Icon(Icons.phone), + title: Text(employee.phone.toString()), + ), + ListTile( + leading: const Icon(Icons.email), + title: Text(employee.email.toString()), + ), + ListTile( + leading: const Icon(Icons.location_on), + title: Text(employee.location.toString()), + ), + ], + ), + ), + ); + } +} diff --git a/basic_flutter/lib/presentation/widget/build_name_widget.dart b/basic_flutter/lib/presentation/widget/build_name_widget.dart new file mode 100644 index 0000000..79c2c20 --- /dev/null +++ b/basic_flutter/lib/presentation/widget/build_name_widget.dart @@ -0,0 +1,41 @@ +import 'package:flutter/material.dart'; +import '../../data/employee.dart'; + +class BuildNameWidget extends StatelessWidget { + const BuildNameWidget({Key? key, required this.employee}) : super(key: key); + final Employee employee; + + @override + Widget build(BuildContext context) { + return SizedBox( + width: double.infinity, + height: MediaQuery.of(context).size.height * + 0.18, // Abstand zwischen Detail und Contact + child: Column( + children: [ + Text( + employee.firstName, + style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 24), + ), + Text( + employee.lastName, + style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 24), + ), + const SizedBox(height: 5), + Column( + children: [ + ListTile( + title: Column( + children: [ + Text(employee.profession.toString()), + Text(employee.country.toString()), + ], + ), + ) + ], + ) + ], + ), + ); + } +} diff --git a/basic_flutter/lib/presentation/widget/button_widget.dart b/basic_flutter/lib/presentation/widget/button_widget.dart new file mode 100644 index 0000000..fdf24e6 --- /dev/null +++ b/basic_flutter/lib/presentation/widget/button_widget.dart @@ -0,0 +1,23 @@ +import 'package:flutter/material.dart'; + +class ButtonWidget extends StatelessWidget { + final String text; + final VoidCallback onClicked; + + const ButtonWidget({ + Key? key, + required this.text, + required this.onClicked, + }) : super(key: key); + + @override + Widget build(BuildContext context) => ElevatedButton( + style: ElevatedButton.styleFrom( + shape: const StadiumBorder(), + onPrimary: Colors.white, + padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 12), + ), + child: Text(text), + onPressed: onClicked, + ); +} diff --git a/basic_flutter/lib/presentation/widget/profile_widget.dart b/basic_flutter/lib/presentation/widget/profile_widget.dart new file mode 100644 index 0000000..1768e1f --- /dev/null +++ b/basic_flutter/lib/presentation/widget/profile_widget.dart @@ -0,0 +1,82 @@ +import 'dart:io'; +import 'package:flutter/material.dart'; +import '../../presentation/screens/edit_profile_page.dart'; + +class ProfileWidget extends StatelessWidget { + final String imagePath; + final bool isEdit; + final VoidCallback onClicked; + final Widget sentWidget; + + const ProfileWidget( + {Key? key, + required this.imagePath, + this.isEdit = false, + required this.onClicked, + required this.sentWidget}) + : super(key: key); + + @override + Widget build(BuildContext context) { + return Center( + child: Stack( + children: [ + buildImage(), + sentWidget, + ], + ), + ); + } + + Widget buildImage() { + final image = imagePath.contains('https://') + ? NetworkImage(imagePath) + : FileImage(File(imagePath)); + + return ClipOval( + child: Material( + color: Colors.transparent, + child: Ink.image( + image: image as ImageProvider, + fit: BoxFit.cover, + width: 200, + height: 200, + child: InkWell(onTap: onClicked), + ), + ), + ); + } + + Widget buildEditIcon(Color color, BuildContext context) => buildCircle( + color: Colors.white, + all: 3, + child: buildCircle( + color: color, + all: 10, + child: GestureDetector( + onTap: () { + Navigator.of(context).push(MaterialPageRoute( + builder: (context) => const EditProfilePage())); + }, + child: Icon( + isEdit ? Icons.add_a_photo : Icons.edit, + color: Colors.white, + size: 20, + ), + ), + ), + ); + + Widget buildCircle({ + required Widget child, + required double all, + required Color color, + }) => + ClipOval( + child: Container( + padding: EdgeInsets.all(all), + color: color, + child: child, + ), + ); +} diff --git a/basic_flutter/lib/presentation/widget/textfield_widget.dart b/basic_flutter/lib/presentation/widget/textfield_widget.dart new file mode 100644 index 0000000..656dbb8 --- /dev/null +++ b/basic_flutter/lib/presentation/widget/textfield_widget.dart @@ -0,0 +1,59 @@ +import 'package:flutter/material.dart'; + +class TextFieldWidget extends StatefulWidget { + final int maxLines; + final String label; + final String text; + final ValueChanged onChanged; + + const TextFieldWidget({ + Key? key, + this.maxLines = 1, + required this.label, + required this.text, + required this.onChanged, + }) : super(key: key); + + @override + _TextFieldWidgetState createState() => _TextFieldWidgetState(); +} + +class _TextFieldWidgetState extends State { + late final TextEditingController controller; + + @override + void initState() { + super.initState(); + + controller = TextEditingController(text: widget.text); + } + + @override + void dispose() { + controller.dispose(); + + super.dispose(); + } + + @override + Widget build(BuildContext context) => Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + widget.label, + style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16), + ), + const SizedBox(height: 8), + TextField( + controller: controller, + decoration: InputDecoration( + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + ), + ), + maxLines: widget.maxLines, + onChanged: widget.onChanged, + ), + ], + ); +} diff --git a/basic_flutter/lib/themes.dart b/basic_flutter/lib/themes.dart new file mode 100644 index 0000000..902b952 --- /dev/null +++ b/basic_flutter/lib/themes.dart @@ -0,0 +1,20 @@ +import 'package:flutter/material.dart'; + +class MyThemes { + static final primary = Colors.blue.shade900; + static final primaryColor = Colors.blue.shade900; + + static final darkTheme = ThemeData( + scaffoldBackgroundColor: Colors.black, + primaryColorDark: primaryColor, + colorScheme: ColorScheme.dark(primary: primary), + dividerColor: Colors.white, + ); + + static final lightTheme = ThemeData( + scaffoldBackgroundColor: Colors.white, + primaryColor: primaryColor, + colorScheme: ColorScheme.light(primary: primary), + dividerColor: Colors.black, + ); +} diff --git a/basic_flutter/pubspec.lock b/basic_flutter/pubspec.lock index c8b89cf..c519b31 100644 --- a/basic_flutter/pubspec.lock +++ b/basic_flutter/pubspec.lock @@ -1,20 +1,20 @@ # Generated by pub # See https://dart.dev/tools/pub/glossary#lockfile packages: - async: - dependency: transitive + animated_theme_switcher: + dependency: "direct main" description: - name: async + name: animated_theme_switcher url: "https://pub.dartlang.org" source: hosted - version: "2.8.1" - bloc: - dependency: "direct main" + version: "2.0.1" + async: + dependency: transitive description: - name: bloc + name: async url: "https://pub.dartlang.org" source: hosted - version: "7.2.1" + version: "2.8.2" boolean_selector: dependency: transitive description: @@ -28,7 +28,7 @@ packages: name: characters url: "https://pub.dartlang.org" source: hosted - version: "1.1.0" + version: "1.2.0" charcode: dependency: transitive description: @@ -50,13 +50,13 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "1.15.0" - cupertino_icons: - dependency: "direct main" + cross_file: + dependency: transitive description: - name: cupertino_icons + name: cross_file url: "https://pub.dartlang.org" source: hosted - version: "1.0.3" + version: "0.3.2" fake_async: dependency: transitive description: @@ -64,18 +64,25 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "1.2.0" + ffi: + dependency: transitive + description: + name: ffi + url: "https://pub.dartlang.org" + source: hosted + version: "1.1.2" + file: + dependency: transitive + description: + name: file + url: "https://pub.dartlang.org" + source: hosted + version: "6.1.2" flutter: dependency: "direct main" description: flutter source: sdk version: "0.0.0" - flutter_bloc: - dependency: "direct main" - description: - name: flutter_bloc - url: "https://pub.dartlang.org" - source: hosted - version: "7.3.3" flutter_lints: dependency: "direct dev" description: @@ -83,13 +90,25 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "1.0.4" + flutter_plugin_android_lifecycle: + dependency: transitive + description: + name: flutter_plugin_android_lifecycle + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.5" 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: "direct main" + dependency: transitive description: name: http url: "https://pub.dartlang.org" @@ -102,13 +121,34 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "4.0.0" - lint: - dependency: "direct dev" + image_picker: + dependency: "direct main" + description: + name: image_picker + url: "https://pub.dartlang.org" + source: hosted + version: "0.7.5+4" + image_picker_for_web: + dependency: transitive + description: + name: image_picker_for_web + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.4" + image_picker_platform_interface: + dependency: transitive + description: + name: image_picker_platform_interface + url: "https://pub.dartlang.org" + source: hosted + version: "2.4.1" + js: + dependency: transitive description: - name: lint + name: js url: "https://pub.dartlang.org" source: hosted - version: "1.7.2" + version: "0.6.3" lints: dependency: transitive description: @@ -122,7 +162,7 @@ packages: name: matcher url: "https://pub.dartlang.org" source: hosted - version: "0.12.10" + version: "0.12.11" meta: dependency: transitive description: @@ -130,27 +170,139 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "1.7.0" - nested: + path: dependency: transitive description: - name: nested + name: path url: "https://pub.dartlang.org" source: hosted - version: "1.0.0" - path: + version: "1.8.0" + path_provider: + dependency: "direct main" + description: + name: path_provider + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.8" + path_provider_android: dependency: transitive description: - name: path + name: path_provider_android url: "https://pub.dartlang.org" source: hosted - version: "1.8.0" - provider: + version: "2.0.11" + path_provider_ios: + dependency: transitive + description: + name: path_provider_ios + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.7" + path_provider_linux: dependency: transitive description: - name: provider + name: path_provider_linux url: "https://pub.dartlang.org" source: hosted - version: "6.0.1" + version: "2.1.4" + path_provider_macos: + dependency: transitive + description: + name: path_provider_macos + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.4" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.1" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.4" + platform: + dependency: transitive + description: + name: platform + url: "https://pub.dartlang.org" + source: hosted + version: "3.1.0" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.2" + process: + dependency: transitive + description: + name: process + url: "https://pub.dartlang.org" + source: hosted + version: "4.2.4" + shared_preferences: + dependency: "direct main" + description: + name: shared_preferences + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.11" + shared_preferences_android: + dependency: transitive + description: + name: shared_preferences_android + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.9" + shared_preferences_ios: + dependency: transitive + description: + name: shared_preferences_ios + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.8" + shared_preferences_linux: + dependency: transitive + description: + name: shared_preferences_linux + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.3" + shared_preferences_macos: + dependency: transitive + description: + name: shared_preferences_macos + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.2" + shared_preferences_platform_interface: + dependency: transitive + description: + name: shared_preferences_platform_interface + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.0" + shared_preferences_web: + dependency: transitive + description: + name: shared_preferences_web + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.2" + shared_preferences_windows: + dependency: transitive + description: + name: shared_preferences_windows + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.3" sky_engine: dependency: transitive description: flutter @@ -197,7 +349,7 @@ packages: name: test_api url: "https://pub.dartlang.org" source: hosted - version: "0.4.2" + version: "0.4.3" typed_data: dependency: transitive description: @@ -211,7 +363,21 @@ packages: name: vector_math url: "https://pub.dartlang.org" source: hosted - version: "2.1.0" + version: "2.1.1" + win32: + dependency: transitive + description: + name: win32 + url: "https://pub.dartlang.org" + source: hosted + version: "2.3.3" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + url: "https://pub.dartlang.org" + source: hosted + version: "0.2.0" sdks: dart: ">=2.14.0 <3.0.0" - flutter: ">=1.16.0" + flutter: ">=2.5.0" diff --git a/basic_flutter/pubspec.yaml b/basic_flutter/pubspec.yaml index d603bc2..036be02 100644 --- a/basic_flutter/pubspec.yaml +++ b/basic_flutter/pubspec.yaml @@ -27,20 +27,40 @@ environment: # the latest version available on pub.dev. To see which dependencies have newer # versions available, run `flutter pub outdated`. dependencies: - bloc: ^7.2.1 - cupertino_icons: ^1.0.2 flutter: sdk: flutter - flutter_bloc: ^7.3.3 - http: ^0.13.4 + + + # The following adds the Cupertino Icons font to your application. + # Use with the CupertinoIcons class for iOS style icons. + # cupertino_icons: ^1.0.2 + + # switch animation between light and dark theme + animated_theme_switcher: ^2.0.1-nullsafety.0 + + # persist locally data + shared_preferences: ^2.0.7 + + # pick image + image_picker: ^0.7.4 + + # store image + path_provider: ^2.0.1 + dev_dependencies: - flutter_lints: ^1.0.0 flutter_test: sdk: flutter - lint: ^1.0.0 + + # 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: ^1.0.0 # For information on the generic Dart part of this file, see the # following page: https://dart.dev/tools/pub/pubspec + # The following section is specific to Flutter. flutter: @@ -48,29 +68,28 @@ flutter: # included with your application, so that you can use the icons in # the material Icons class. uses-material-design: true + # To add assets to your application, add an assets section, like this: # assets: - # - images/a_dot_burr.jpeg - # - images/a_dot_ham.jpeg + # - assets/employee1.jpg + # An image asset can refer to one or more resolution-specific "variants", see # https://flutter.dev/assets-and-images/#resolution-aware. + # For details regarding adding assets from package dependencies, see # https://flutter.dev/assets-and-images/#from-packages + # To add custom fonts to your application, add a fonts section here, # in this "flutter" section. Each entry in this list should have a # "family" key with the font family name, and a "fonts" key with a # list giving the asset and other descriptors for the font. For # example: - fonts: - - family: Raleway - fonts: - - asset: assets/fonts/Raleway-Black.ttf - - asset: assets/fonts/Raleway-Bold.ttf - weight: 700 - - asset: assets/fonts/Raleway-ExtraBold.ttf - weight: 800 - - asset: assets/fonts/Raleway-Italic.ttf - style: italic + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic # - family: Trajan Pro # fonts: # - asset: fonts/TrajanPro.ttf diff --git a/basic_flutter/test/widget_test.dart b/basic_flutter/test/widget_test.dart index 3b43fa4..c5aaac8 100644 --- a/basic_flutter/test/widget_test.dart +++ b/basic_flutter/test/widget_test.dart @@ -4,10 +4,8 @@ // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. - import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; - import 'package:basic_flutter/main.dart'; void main() { diff --git a/basic_flutter/windows/.gitignore b/basic_flutter/windows/.gitignore new file mode 100644 index 0000000..d492d0d --- /dev/null +++ b/basic_flutter/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/basic_flutter/windows/CMakeLists.txt b/basic_flutter/windows/CMakeLists.txt new file mode 100644 index 0000000..4c38764 --- /dev/null +++ b/basic_flutter/windows/CMakeLists.txt @@ -0,0 +1,95 @@ +cmake_minimum_required(VERSION 3.14) +project(employee_dialog1 LANGUAGES CXX) + +set(BINARY_NAME "employee_dialog1") + +cmake_policy(SET CMP0063 NEW) + +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Configure build options. +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() + +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. +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() + +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") + +# Flutter library and tool build rules. +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build +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() + +# 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/basic_flutter/windows/flutter/CMakeLists.txt b/basic_flutter/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000..b2e4bd8 --- /dev/null +++ b/basic_flutter/windows/flutter/CMakeLists.txt @@ -0,0 +1,103 @@ +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") + +# === 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" + windows-x64 $ + 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/basic_flutter/windows/flutter/generated_plugin_registrant.cc b/basic_flutter/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..8b6d468 --- /dev/null +++ b/basic_flutter/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,11 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + + +void RegisterPlugins(flutter::PluginRegistry* registry) { +} diff --git a/basic_flutter/windows/flutter/generated_plugin_registrant.h b/basic_flutter/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..dc139d8 --- /dev/null +++ b/basic_flutter/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/basic_flutter/windows/flutter/generated_plugins.cmake b/basic_flutter/windows/flutter/generated_plugins.cmake new file mode 100644 index 0000000..4d10c25 --- /dev/null +++ b/basic_flutter/windows/flutter/generated_plugins.cmake @@ -0,0 +1,15 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_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) diff --git a/basic_flutter/windows/runner/CMakeLists.txt b/basic_flutter/windows/runner/CMakeLists.txt new file mode 100644 index 0000000..de2d891 --- /dev/null +++ b/basic_flutter/windows/runner/CMakeLists.txt @@ -0,0 +1,17 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +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_standard_settings(${BINARY_NAME}) +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/basic_flutter/windows/runner/Runner.rc b/basic_flutter/windows/runner/Runner.rc new file mode 100644 index 0000000..9f4c8e8 --- /dev/null +++ b/basic_flutter/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 +// + +#ifdef FLUTTER_BUILD_NUMBER +#define VERSION_AS_NUMBER FLUTTER_BUILD_NUMBER +#else +#define VERSION_AS_NUMBER 1,0,0 +#endif + +#ifdef FLUTTER_BUILD_NAME +#define VERSION_AS_STRING #FLUTTER_BUILD_NAME +#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", "A new Flutter project." "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "employee_dialog1" "\0" + VALUE "LegalCopyright", "Copyright (C) 2021 com.example. All rights reserved." "\0" + VALUE "OriginalFilename", "employee_dialog1.exe" "\0" + VALUE "ProductName", "employee_dialog1" "\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/basic_flutter/windows/runner/flutter_window.cpp b/basic_flutter/windows/runner/flutter_window.cpp new file mode 100644 index 0000000..b43b909 --- /dev/null +++ b/basic_flutter/windows/runner/flutter_window.cpp @@ -0,0 +1,61 @@ +#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()); + 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/basic_flutter/windows/runner/flutter_window.h b/basic_flutter/windows/runner/flutter_window.h new file mode 100644 index 0000000..6da0652 --- /dev/null +++ b/basic_flutter/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/basic_flutter/windows/runner/main.cpp b/basic_flutter/windows/runner/main.cpp new file mode 100644 index 0000000..ac2dd51 --- /dev/null +++ b/basic_flutter/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.CreateAndShow(L"employee_dialog1", 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/basic_flutter/windows/runner/resource.h b/basic_flutter/windows/runner/resource.h new file mode 100644 index 0000000..66a65d1 --- /dev/null +++ b/basic_flutter/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/basic_flutter/windows/runner/resources/app_icon.ico b/basic_flutter/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000..c04e20c Binary files /dev/null and b/basic_flutter/windows/runner/resources/app_icon.ico differ diff --git a/basic_flutter/windows/runner/runner.exe.manifest b/basic_flutter/windows/runner/runner.exe.manifest new file mode 100644 index 0000000..c977c4a --- /dev/null +++ b/basic_flutter/windows/runner/runner.exe.manifest @@ -0,0 +1,20 @@ + + + + + PerMonitorV2 + + + + + + + + + + + + + + + diff --git a/basic_flutter/windows/runner/utils.cpp b/basic_flutter/windows/runner/utils.cpp new file mode 100644 index 0000000..d19bdbb --- /dev/null +++ b/basic_flutter/windows/runner/utils.cpp @@ -0,0 +1,64 @@ +#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(); + } + int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, nullptr, 0, nullptr, nullptr); + if (target_length == 0) { + return std::string(); + } + std::string utf8_string; + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, utf8_string.data(), + target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/basic_flutter/windows/runner/utils.h b/basic_flutter/windows/runner/utils.h new file mode 100644 index 0000000..3879d54 --- /dev/null +++ b/basic_flutter/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/basic_flutter/windows/runner/win32_window.cpp b/basic_flutter/windows/runner/win32_window.cpp new file mode 100644 index 0000000..c10f08d --- /dev/null +++ b/basic_flutter/windows/runner/win32_window.cpp @@ -0,0 +1,245 @@ +#include "win32_window.h" + +#include + +#include "resource.h" + +namespace { + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +// 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 registar 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::CreateAndShow(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 | WS_VISIBLE, + 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; + } + + return OnCreate(); +} + +// 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; + } + + 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. +} diff --git a/basic_flutter/windows/runner/win32_window.h b/basic_flutter/windows/runner/win32_window.h new file mode 100644 index 0000000..17ba431 --- /dev/null +++ b/basic_flutter/windows/runner/win32_window.h @@ -0,0 +1,98 @@ +#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 and shows a win32 window with |title| and position and size 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 to will treat the width height passed in to this function + // as logical pixels and scale to appropriate for the default monitor. Returns + // true if the window was created successfully. + bool CreateAndShow(const std::wstring& title, + const Point& origin, + const Size& size); + + // 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 + // responsponds 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; + + 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_