File size: 11,133 Bytes
01ae70d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
import os
import shutil
import tempfile
import zipfile
from typing import List, Optional
from pydantic import BaseModel

import subprocess

class ProjectConfig(BaseModel):
    app_name: str
    package_name: str
    primary_color: str  # Hex
    secondary_color: str # Hex
    splash_screen: bool
    onboarding_count: int # 0 means none
    splash_screen: bool
    onboarding_count: int # 0 means none
    features: List[str] # ["auth", "bottom_nav", "profile"]
    platforms: List[str] = ["android", "ios"] # Default to mobile

class FlutterGenerator:
    def __init__(self):
        pass

    def generate(self, config: ProjectConfig) -> str:
        """
        Generates a Flutter project zip using 'flutter create'.
        Returns the path to the zip file.
        """
        # 1. Create Temp Directory
        temp_dir = tempfile.mkdtemp()
        
        try:
            # 2. Run flutter create
            # split package name into org and name if possible, or just use as is
            # flutter create --org com.example --project-name name .
            
            # Extract org from package name (e.g. com.example.app -> com.example)
            parts = config.package_name.split('.')
            if len(parts) >= 2:
                org = ".".join(parts[:-1])
            else:
                org = "com.example"

            # Sanitize app_name for flutter project name (must be snake_case)
            safe_app_name = config.app_name.lower().replace(" ", "_").replace("-", "_")
            # Basic validation to ensure it starts with a letter could be added, but handled by flutter create output mostly
                
            cmd = [
                "flutter", "create", 
                "--org", org,
                "--project-name", safe_app_name,
            ]
            
            # Add platforms if specified
            if config.platforms:
                cmd.extend(["--platforms", ",".join(config.platforms)])
                
            cmd.append(os.path.join(temp_dir, safe_app_name))
            
            subprocess.run(cmd, check=True, shell=True) # shell=True for windows path resolution
            
            project_root = os.path.join(temp_dir, safe_app_name)
            
            # 3. Inject Dependencies (Safe Insert)
            self._update_pubspec(project_root, config)
            
            # 4. Generate Code Structure
            self._generate_code_structure(project_root, config)
            
            # 5. Inject Permissions
            self._inject_permissions(project_root, config)

            # 6. Zip Result
            zip_path = shutil.make_archive(os.path.join(temp_dir, safe_app_name), 'zip', project_root)
            return zip_path
            
        except subprocess.CalledProcessError as e:
            shutil.rmtree(temp_dir)
            raise Exception(f"Flutter create failed: {e}")
        except Exception as e:
            shutil.rmtree(temp_dir)
            raise e

    def _rename_package(self, root: str, old_pkg: str, new_pkg: str):
        # No longer needed as flutter create handles this
        pass

    def _update_app_name(self, root: str, name: str):
        # No longer needed
        pass

    def _update_pubspec(self, root: str, config: ProjectConfig):
        # Use flutter pub add to ensure compatibility with the local flutter version
        dependencies = ["get", "google_fonts", "permission_handler"]
        
        if "auth" in config.features:
            dependencies.append("shared_preferences")
            
        cmd = ["flutter", "pub", "add"] + dependencies
        
        try:
            # We run this inside the project root
            subprocess.run(cmd, cwd=root, check=True, shell=True)
        except subprocess.CalledProcessError as e:
            # Fallback or log? For now let it raise so we know it failed
            raise Exception(f"Failed to add dependencies: {e}")


    def _generate_code_structure(self, root: str, config: ProjectConfig):
        lib_path = os.path.join(root, 'lib')
        
        # Create Directories
        os.makedirs(os.path.join(lib_path, 'core', 'theme'), exist_ok=True)
        os.makedirs(os.path.join(lib_path, 'core', 'services'), exist_ok=True)
        os.makedirs(os.path.join(lib_path, 'getx', 'routes'), exist_ok=True)
        os.makedirs(os.path.join(lib_path, 'modules'), exist_ok=True)
        
        # Generator Helpers (In a real app these would be separate files/templates)
        self._write_file(os.path.join(lib_path, 'main.dart'), self._get_main_dart(config))
        self._write_file(os.path.join(lib_path, 'core', 'theme', 'app_theme.dart'), self._get_app_theme(config))
        self._write_file(os.path.join(lib_path, 'getx', 'routes', 'app_pages.dart'), self._get_app_pages(config))
        self._write_file(os.path.join(lib_path, 'getx', 'routes', 'app_routes.dart'), self._get_app_routes(config))
        
        if "auth" in config.features:
            self._generate_auth_module(lib_path)
            
        if config.onboarding_count > 0:
            self._generate_onboarding_module(lib_path, config.onboarding_count)

    def _inject_permissions(self, root: str, config: ProjectConfig):
        # Android
        manifest_path = os.path.join(root, 'android/app/src/main/AndroidManifest.xml')
        if os.path.exists(manifest_path):
            with open(manifest_path, 'r') as f:
                content = f.read()
            
            perms = ""
            if "profile" in config.features:
                perms += '    <uses-permission android:name="android.permission.CAMERA"/>\n'
                perms += '    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>\n'
            
            content = content.replace('<!-- Permissions Placeholder -->', perms)
            with open(manifest_path, 'w') as f:
                f.write(content)

    def _write_file(self, path, content):
        with open(path, 'w', encoding='utf-8') as f:
            f.write(content)

    # --- Content Generators ---
    
    def _get_main_dart(self, config: ProjectConfig):
        return f"""
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'core/theme/app_theme.dart';
import 'getx/routes/app_pages.dart';

void main() {{
  runApp(const MyApp());
}}

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

  @override
  Widget build(BuildContext context) {{
    return GetMaterialApp(
      title: '{config.app_name}',
      theme: AppTheme.lightTheme,
      initialRoute: AppPages.INITIAL,
      getPages: AppPages.routes,
    );
  }}
}}
"""

    def _get_app_theme(self, config: ProjectConfig):
        return f"""
import 'package:flutter/material.dart';

class AppTheme {{
  static final lightTheme = ThemeData(
    primaryColor: Color(int.parse("0xFF{config.primary_color.replace('#', '')}")),
    colorScheme: ColorScheme.fromSwatch().copyWith(
      primary: Color(int.parse("0xFF{config.primary_color.replace('#', '')}")),
      secondary: Color(int.parse("0xFF{config.secondary_color.replace('#', '')}")),
    ),
    useMaterial3: true,
  );
}}
"""

    def _get_app_pages(self, config: ProjectConfig):
        initial = "Routes.HOME"
        imports = []
        pages = []
        
        # Always add specific feature imports and pages
        if config.onboarding_count > 0:
            initial = "Routes.ONBOARDING"
            imports.append("import '../../modules/onboarding/onboarding_view.dart';")
            pages.append("    GetPage(name: Routes.ONBOARDING, page: () => OnboardingView()),")
        elif "auth" in config.features:
            initial = "Routes.LOGIN"
            imports.append("import '../../modules/auth/login_view.dart';")
            imports.append("import '../../modules/auth/auth_controller.dart';")
            pages.append("    GetPage(name: Routes.LOGIN, page: () => LoginView(), binding: BindingsBuilder(() { Get.put(AuthController()); })),")

        # Join imports
        imports_str = "\n".join(imports)
        pages_str = "\n".join(pages)
            
        return f"""
import 'package:get/get.dart';
import 'app_routes.dart';
{imports_str}

class AppPages {{
  static const INITIAL = {initial};

  static final List<GetPage> routes = [
{pages_str}
  ];
}}
"""

    def _get_app_routes(self, config: ProjectConfig):
        return """
abstract class Routes {
  static const HOME = '/home';
  static const LOGIN = '/login';
  static const REGISTER = '/register';
  static const ONBOARDING = '/onboarding';
}
"""

    def _generate_auth_module(self, lib_path):
        auth_path = os.path.join(lib_path, 'modules', 'auth')
        os.makedirs(auth_path, exist_ok=True)
        # Controller
        self._write_file(os.path.join(auth_path, 'auth_controller.dart'), """
import 'package:get/get.dart';

class AuthController extends GetxController {
  var isLoading = false.obs;

  void login(String username, String password) {
    isLoading.value = true;
    Future.delayed(Duration(seconds: 2), () {
      isLoading.value = false;
      Get.snackbar("Success", "Logged in as $username");
    });
  }
}
""")
        # View
        self._write_file(os.path.join(auth_path, 'login_view.dart'), """
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'auth_controller.dart';

class LoginView extends GetView<AuthController> {
  final TextEditingController usernameController = TextEditingController();
  final TextEditingController passwordController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Login")),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(controller: usernameController, decoration: InputDecoration(labelText: "Username")),
            TextField(controller: passwordController, decoration: InputDecoration(labelText: "Password"), obscureText: true,),
            SizedBox(height: 20),
            Obx(() => controller.isLoading.value 
              ? CircularProgressIndicator() 
              : ElevatedButton(
                  onPressed: () => controller.login(usernameController.text, passwordController.text),
                  child: Text("Login")
                )
            )
          ],
        ),
      ),
    );
  }
}
""")

    def _generate_onboarding_module(self, lib_path, count):
        onboarding_path = os.path.join(lib_path, 'modules', 'onboarding')
        os.makedirs(onboarding_path, exist_ok=True)
        # View
        slide_widgets = ""
        for i in range(1, count + 1):
            slide_widgets += f"Center(child: Text('Onboarding Screen {i}')),\n"
            
        self._write_file(os.path.join(onboarding_path, 'onboarding_view.dart'), f"""
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class OnboardingView extends StatelessWidget {{
  @override
  Widget build(BuildContext context) {{
    return Scaffold(
      body: PageView(
        children: [
          {slide_widgets}
        ],
      ),
    );
  }}
}}
""")