aboutsummaryrefslogtreecommitdiffstats
path: root/qt-cli/generator/funcs-cpp.go
blob: 85ea1cfc72f5bbd3e9dc4a55e905e1194db62a72 (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
// Copyright (C) 2024 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only

package generator

import (
	"fmt"
	"qtcli/util"
	"sort"
	"strings"
	"unicode"
)

type CppFuncs struct{}

func (cpp CppFuncs) ExtractClassName(fqcn string) string {
	return extractClassNameOnly(fqcn)
}

func (cpp CppFuncs) CreateNamespaceOpenings(fqcn string) string {
	splits := strings.Split(fqcn, "::")
	output := []string{}

	for i := 0; i < len(splits)-1; i++ {
		output = append(output, fmt.Sprintf("namespace %s {", splits[i]))
	}

	return strings.Join(output, "\n")
}

func (cpp CppFuncs) CreateNamespaceClosings(fqcn string) string {
	splits := strings.Split(fqcn, "::")
	output := []string{}

	for i := 0; i < len(splits)-1; i++ {
		output = append(output, fmt.Sprintf("} // namespace %s", splits[i]))
	}

	return strings.Join(output, "\n")
}

func (cpp CppFuncs) CreateHeaderGuard(fileName string) string {
	return strings.ReplaceAll(strings.ToUpper(fileName), ".", "_")
}

func (cpp CppFuncs) CreateIncludes(
	includes []string, macros []string) []string {
	all := []string{}

	sort.Strings(includes)
	hasModuleName := true

	for _, name := range includes {
		if !mightBeQtClass(name) {
			continue
		}

		item := name

		if hasModuleName {
			module := findModuleName(name)
			if module != "" {
				item = module + "/" + name
			}
		}

		all = append(all, item)
	}

	return all
}

func (cpp CppFuncs) CreateLicense(
	licenseTemplatePath string,
	className string,
	fileName string,
) string {
	str, _ := generateLicense(licenseTemplatePath, util.StringAnyMap{
		"ClassName": className,
		"FileName":  fileName,
	})

	return str
}

func mightBeQtClass(name string) bool {
	return len(name) >= 2 &&
		name[0] == 'Q' &&
		unicode.IsUpper(rune(name[1]))
}

func findModuleName(name string) string {
	switch name {
	case "QObject", "QSharedData":
		return "QtCore"

	case "QWidget", "QMainWindow":
		return "QtWidgets"

	case "QQuickItem":
		return "QtQuick"

	case "QQmlEngine":
		return "QtQml"
	}

	return ""
}

func extractClassNameOnly(fqcn string) string {
	splits := strings.Split(fqcn, "::")
	if len(splits) == 0 {
		return ""
	}
	return splits[len(splits)-1]
}