aboutsummaryrefslogtreecommitdiffstats
path: root/sources/pyside-tools/project/newproject.py
blob: c363a9fc0b395b9d054b114fd167c484c04bf396 (plain)
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
# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

import json
import os
import sys
from enum import Enum
from pathlib import Path
from typing import List, Tuple

"""New project generation code."""


Project = List[Tuple[str, str]]  # tuple of (filename, contents).


class ProjectType(Enum):
    WIDGET_FORM = 1
    WIDGET = 2
    QUICK = 3


_WIDGET_MAIN = """if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())
"""


_WIDGET_IMPORTS = """import sys
from PySide6.QtWidgets import QApplication, QMainWindow
"""


_WIDGET_CLASS_DEFINITION = """class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
"""


_WIDGET_SETUP_UI_CODE = """        self._ui = Ui_MainWindow()
        self._ui.setupUi(self)
"""


_MAINWINDOW_FORM = """<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>800</width>
    <height>600</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralwidget"/>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>800</width>
     <height>22</height>
    </rect>
   </property>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
</ui>
"""


_QUICK_FORM = """import QtQuick
import QtQuick.Controls

ApplicationWindow {
    id: window
    width: 1024
    height: 600
    visible: true
}
"""

_QUICK_MAIN = """import sys
from pathlib import Path

from PySide6.QtGui import QGuiApplication
from PySide6.QtCore import QUrl
from PySide6.QtQml import QQmlApplicationEngine


if __name__ == "__main__":
    app = QGuiApplication()
    engine = QQmlApplicationEngine()
    qml_file = Path(__file__).parent / 'main.qml'
    engine.load(QUrl.fromLocalFile(qml_file))
    if not engine.rootObjects():
        sys.exit(-1)
    exit_code = app.exec()
    del engine
    sys.exit(exit_code)
"""


def _write_project(directory: Path, files: Project):
    """Write out the project."""
    file_list = []
    for file, contents in files:
        (directory / file).write_text(contents)
        print(f"Wrote {directory.name}{os.sep}{file}.")
        file_list.append(file)
    pyproject = {"files": file_list}
    pyproject_file = f"{directory}.pyproject"
    (directory / pyproject_file).write_text(json.dumps(pyproject))
    print(f"Wrote {directory.name}{os.sep}{pyproject_file}.")


def _widget_project() -> Project:
    """Create a (form-less) widgets project."""
    main_py = (_WIDGET_IMPORTS + "\n\n" + _WIDGET_CLASS_DEFINITION + "\n\n"
               + _WIDGET_MAIN)
    return [("main.py", main_py)]


def _ui_form_project() -> Project:
    """Create a Qt Designer .ui form based widgets project."""
    main_py = (_WIDGET_IMPORTS
               + "\nfrom ui_mainwindow import Ui_MainWindow\n\n\n"
               + _WIDGET_CLASS_DEFINITION + _WIDGET_SETUP_UI_CODE
               + "\n\n" + _WIDGET_MAIN)
    return [("main.py", main_py),
            ("mainwindow.ui", _MAINWINDOW_FORM)]


def _qml_project() -> Project:
    """Create a QML project."""
    return [("main.py", _QUICK_MAIN),
            ("main.qml", _QUICK_FORM)]


def new_project(directory_s: str,
                project_type: ProjectType = ProjectType.WIDGET_FORM) -> int:
    directory = Path(directory_s)
    if directory.exists():
        print(f"{directory_s} already exists.", file=sys.stderr)
        return -1
    directory.mkdir(parents=True)

    if project_type == ProjectType.WIDGET_FORM:
        project = _ui_form_project()
    elif project_type == ProjectType.QUICK:
        project = _qml_project()
    else:
        project = _widget_project()
    _write_project(directory, project)
    if project_type == ProjectType.WIDGET_FORM:
        print(f'Run "pyside6-project build {directory_s}" to build the project')
    print(f'Run "python {directory.name}{os.sep}main.py" to run the project')
    return 0