-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathshortcut.go
392 lines (342 loc) · 10.4 KB
/
shortcut.go
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
package main
import (
"embed"
"fmt"
"github.com/charmbracelet/huh"
"github.com/charmbracelet/huh/spinner"
"github.com/charmbracelet/log"
"github.com/go-ole/go-ole"
"github.com/go-ole/go-ole/oleutil"
"os"
"path"
"path/filepath"
"regexp"
)
//go:embed "Game Icons/*.ico"
var embeddedIcons embed.FS
type shortcutLocation int
const (
desktop shortcutLocation = iota
currentDir
startMenu
)
func showShortcutMenu(games []string) {
var createShortcuts bool
var selectedInstallations []string
var prompt, mst string
if len(games) == 1 {
prompt = fmt.Sprintf(
"Would you like to create a desktop shortcut for %s (Pipsi for %s)?",
config.getInstallationFolder(games[0]), games[0],
)
mst = "Select the Pipsi installation for which you would like to create a desktop shortcut"
} else if len(games) > 1 {
prompt = fmt.Sprintf("Would you like to create desktop shortcuts for Pipsi across %d games?", len(games))
mst = "Select the Pipsi installations for which you would like to create desktop shortcuts"
} else {
return
}
var shortcutOptions []huh.Option[string]
action := func() {
addedTitles := make(map[string]bool)
for _, title := range games {
option := fmt.Sprintf("%s", title)
shortcutOptions = append(
shortcutOptions,
huh.NewOption(fmt.Sprintf("%s (%s)", config.getInstallationFolder(title), title), option).
Selected(true),
)
addedTitles[title] = true
}
additionalInstalledTitles := cheatInstallationData.getInstalledTitles()
for _, title := range additionalInstalledTitles {
if !addedTitles[title] {
option := fmt.Sprintf("%s", title)
shortcutOptions = append(
shortcutOptions,
huh.NewOption(fmt.Sprintf("%s (%s)", config.getInstallationFolder(title), title), option).
Selected(false),
)
}
}
}
if err := spinner.New().Title("Preparing shortcut options...").Action(action).Run(); err != nil {
log.Errorf("Spinner widget error: %v", err)
pauseAndReturnToMainMenu()
}
form := huh.NewForm(
huh.NewGroup(
huh.NewConfirm().
Title(prompt).
Value(&createShortcuts).
Affirmative("Yes").
Negative("No"),
),
huh.NewGroup(
huh.NewMultiSelect[string]().
Title(mst).
Options(shortcutOptions...).
Value(&selectedInstallations),
).WithHideFunc(
func() bool {
return !createShortcuts
},
),
).WithAccessible(IsAccessible())
if err := form.Run(); err != nil {
log.Fatal(err)
}
if !createShortcuts {
return
}
if len(selectedInstallations) < 1 {
log.Infof("No installations were selected to create shortcuts for %s. Skipping shortcut creation.", mst)
return
}
if scs := createPipsiShortcuts(selectedInstallations, desktop); len(scs) > 0 {
log.Infof(
"Shortcut(s) created successfully for %s.",
formatGameList(scs),
)
} else {
log.Infof("No shortcuts were created for %s.", formatGameList(selectedInstallations))
}
}
func showAdvancedShortcutMenu() {
installedTitles := cheatInstallationData.getInstalledTitles()
if len(installedTitles) == 0 {
fmt.Print(
HighlightText.Render("No Pipsi installations detected.\n\n") +
"Please return to the main menu and select " +
BoldCyan.Render("\"Install Pipsi\"") +
" to get started.\n\n",
)
pauseAndReturnToMainMenu()
return
}
/* fmt.Println(
NoticePrefix.Render("NOTE: ") +
HighlightText.Render("If the Pipsi installation you're looking for isn't listed here, ") +
HighlightText.Render("ensure it is installed first.\n") +
WarningText.Render("Quick return: Press Enter three times without selections to go back.\n"),
)*/
type optionData struct {
display string
value string
}
var optionsData []optionData
action := func() {
for _, title := range installedTitles {
display := fmt.Sprintf("%s (%s)", config.getInstallationFolder(title), title)
optionsData = append(
optionsData, optionData{
display: display,
value: title,
},
)
}
}
if err := spinner.New().Title("Preparing shortcut options...").Action(action).Run(); err != nil {
log.Errorf("Spinner error: %v", err)
pauseAndReturnToMainMenu()
return
}
generateOptions := func(data []optionData) []huh.Option[string] {
options := make([]huh.Option[string], len(data))
for i, d := range data {
options[i] = huh.NewOption(d.display, d.value)
}
return options
}
var (
desktopSelections, dirSelections, menuSelections []string
)
form := huh.NewForm(
huh.NewGroup(
huh.NewMultiSelect[string]().
Title("Select installations for desktop shortcuts").
Options(generateOptions(optionsData)...).
Value(&desktopSelections),
huh.NewMultiSelect[string]().
Title("Create shortcuts in current directory").
Description("Makes shortcuts adjacent to this executable").
Options(generateOptions(optionsData)...).
Value(&dirSelections),
huh.NewMultiSelect[string]().
Title("Start Menu shortcuts").
Description("Creates in Windows Start Menu Programs folder").
Options(generateOptions(optionsData)...).
Value(&menuSelections),
),
).WithAccessible(IsAccessible())
if err := form.Run(); err != nil {
log.Fatal(err)
}
totalSelections := len(desktopSelections) + len(dirSelections) + len(menuSelections)
if totalSelections == 0 {
returnToMainMenu()
return
}
var createdShortcuts []string
createAction := func() {
createdShortcuts = append(
createdShortcuts,
createPipsiShortcuts(desktopSelections, desktop)...,
)
createdShortcuts = append(
createdShortcuts,
createPipsiShortcuts(dirSelections, currentDir)...,
)
createdShortcuts = append(
createdShortcuts,
createPipsiShortcuts(menuSelections, startMenu)...,
)
}
if err := spinner.New().Title("Creating shortcuts...").Action(createAction).Run(); err != nil {
log.Errorf("Creation failed: %v", err)
}
if len(createdShortcuts) > 0 {
log.Infof(
"Successfully created shortcuts for: %s",
formatGameList(createdShortcuts),
)
}
pauseAndReturnToMainMenu()
}
func createPipsiShortcuts(selectedInstallations []string, location shortcutLocation) []string {
err := extractGameIcons()
if err != nil {
log.Errorf("Failed to prepare icons for shortcuts: %v", err)
return nil
}
var scs []string
for _, game := range selectedInstallations {
exePath, err := os.Executable()
if err != nil {
log.Errorf("Failed to get executable path: %v", err)
pauseAndReturnToMainMenu()
return nil
}
exeDir := filepath.Dir(exePath)
cif := config.getInstallationFolder(game)
installationFolderPath := filepath.Join(exeDir, cif)
appPath := filepath.Join(filepath.Join(exeDir, "Pipsi Installations", cif), "Launcher.exe")
iconPath := filepath.Join(os.TempDir(), "Game Icons", fmt.Sprintf("%s.ico", cif))
if err = createShortcut(cif, appPath, iconPath, installationFolderPath, location); err != nil {
log.Errorf("Failed to create shortcut for %s: %v", game, err)
} else {
scs = append(scs, game)
}
}
return scs
}
func createShortcut(shortcutName, appPath, iconPath, workingDir string, location shortcutLocation) error {
shortcutName = regexp.MustCompile(`[<>:"/\\|?*]`).ReplaceAllString(shortcutName, "")
var shortcutPath string
switch location {
case desktop:
shortcutPath = filepath.Join(filepath.Join(os.Getenv("USERPROFILE"), "Desktop"), shortcutName+".lnk")
case currentDir:
exePath, err := os.Executable()
if err != nil {
return fmt.Errorf("error getting executable path: %v", err)
}
shortcutPath = filepath.Join(filepath.Dir(exePath), shortcutName+".lnk")
case startMenu:
shortcutPath = filepath.Join(
filepath.Join(
os.Getenv("APPDATA"),
"Microsoft", "Windows", "Start Menu", "Programs",
), shortcutName+".lnk",
)
default:
return fmt.Errorf("invalid shortcut location: %v", location)
}
if err := ole.CoInitializeEx(0, ole.COINIT_APARTMENTTHREADED); err != nil {
return fmt.Errorf("error initializing OLE: %v", err)
}
defer ole.CoUninitialize()
shellLink, err := oleutil.CreateObject("WScript.Shell")
if err != nil {
return fmt.Errorf("error creating WScript.Shell object: %v", err)
}
defer shellLink.Release()
wshell, err := shellLink.QueryInterface(ole.IID_IDispatch)
if err != nil {
return fmt.Errorf("error querying IDispatch: %v", err)
}
defer wshell.Release()
cs, err := oleutil.CallMethod(wshell, "CreateShortcut", shortcutPath)
if err != nil {
return fmt.Errorf("error creating shortcut: %v", err)
}
shortcut := cs.ToIDispatch()
defer shortcut.Release()
if _, err := oleutil.PutProperty(shortcut, "TargetPath", appPath); err != nil {
return fmt.Errorf("error setting TargetPath: %v", err)
}
if _, err := oleutil.PutProperty(shortcut, "IconLocation", iconPath); err != nil {
return fmt.Errorf("error setting IconLocation: %v", err)
}
if _, err := oleutil.PutProperty(shortcut, "WorkingDirectory", workingDir); err != nil {
return fmt.Errorf("error setting WorkingDirectory: %v", err)
}
if _, err := oleutil.CallMethod(shortcut, "Save"); err != nil {
return fmt.Errorf("error saving shortcut: %v", err)
}
return nil
}
func extractGameIcons() error {
targetDir := filepath.Join(os.TempDir(), "Game Icons")
extractionNeeded := false
if _, err := os.Stat(targetDir); os.IsNotExist(err) {
extractionNeeded = true
} else {
entries, err := embeddedIcons.ReadDir("Game Icons")
if err != nil {
log.Warn("Corrupted icon manifest, regenerating icons")
extractionNeeded = true
} else {
for _, entry := range entries {
if entry.IsDir() {
continue
}
targetPath := filepath.Join(targetDir, entry.Name())
if _, err := os.Stat(targetPath); os.IsNotExist(err) {
extractionNeeded = true
break
}
}
}
}
if !extractionNeeded {
log.Debug("Icons already cached")
return nil
}
if err := os.MkdirAll(targetDir, 0755); err != nil {
log.Error("Failed to create icon cache directory", "path", targetDir, "error", err)
return err
}
entries, err := embeddedIcons.ReadDir("Game Icons")
if err != nil {
log.Error("Failed to read embedded icons", "error", err)
return err
}
for _, entry := range entries {
if entry.IsDir() {
continue
}
data, err := embeddedIcons.ReadFile(path.Join("Game Icons", entry.Name()))
if err != nil {
log.Error("Failed to read embedded icon", "file", entry.Name(), "error", err)
return err
}
targetPath := filepath.Join(targetDir, entry.Name())
if err := os.WriteFile(targetPath, data, 0644); err != nil {
log.Error("Failed to write icon cache", "path", targetPath, "error", err)
return err
}
}
log.Debug("Icon cache updated")
return nil
}