This repository has been archived by the owner on Sep 15, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
App.tsx
362 lines (337 loc) · 15 KB
/
App.tsx
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
const { ipcRenderer } = require('electron')
import { Api } from '../api/Api'
import * as React from 'react'
import { remote } from 'electron'
import { Content } from 'react-photonkit'
import { Button, ButtonGroup, Pane, PaneGroup, RetractableSidebar, Toolbar, ToolbarActions, Window } from './photon-fix/Components'
import { UnicodeIcon } from './generic-components/Components'
import { Administration } from './Administration'
import { GameCreation } from './GameCreation'
import { GameCreationOptions, GameType, Replay } from '../api/rules/GameCreationOptions'
import { Game } from './Game'
import { LogConsole } from './LogConsole'
import { Logger } from '../api/Logger'
import { ErrorPage } from './ErrorPage'
import { Hotfix } from './Hotfix'
import * as v from 'validate-typescript'
import { loadFromStorage, saveToStorage } from '../helpers/Cache'
import { GameInfo } from '../api/synchronous/GameInfo'
import { ExecutableStatus } from '../api/rules/ExecutableStatus'
import { NavGroup, NavItem, NavTitle } from './photon-fix/NavComponents'
import promiseRetry from 'promise-retry'
const dialog = remote.dialog
const shell = remote.shell
const appSettingsKey = 'appSettings'
enum AppContent {
Empty,
Blank,
GameCreation,
GameLive,
GameWaiting,
Administration,
Error,
Log,
Help,
Rules,
Quickstart,
JavaDocs
}
interface State {
menuRetracted: boolean
consoleRetracted: boolean
contentState: AppContent
activeGameId: number
serverPort: number
settings: AppSettings
}
export interface AppSettings {
animateMoves: boolean
animateWater: boolean
logDir: string
}
export class App extends React.Component<any, State> {
constructor(props) {
super(props)
let remote = require('electron').remote
this.state = {
menuRetracted: remote.getGlobal('kioskMode'),
consoleRetracted: true,
contentState: Hotfix.isGameReload() ? AppContent.GameWaiting : (require('electron')
.remote
.app
.commandLine
.hasSwitch('kiosk') ? AppContent.GameCreation : AppContent.Empty),
activeGameId: null,
serverPort: null,
settings: loadFromStorage(appSettingsKey, {
animateMoves: v.Type(Boolean),
animateWater: v.Type(Boolean),
logDir: v.Type(String),
}, {
animateMoves: true,
animateWater: true,
logDir: '.',
}),
}
ipcRenderer.on('showGame', (event, gameId) => {
this.showGame(gameId)
})
ipcRenderer.on('closeGame', (event, gameId) => {
this.closeGame(gameId)
})
}
private loadReplay() {
dialog.showOpenDialog(
null,
{
title: 'Wähle ein Replay',
properties: ['openFile'],
}).then(result => {
// dialog returns undefined when user clicks cancel or an array of strings (paths) if user selected a file
if (!result.canceled && result.filePaths.length > 0 && result.filePaths[0]) {
//window.localStorage[localStorageProgramPath] = filenames[0]
console.log('Attempting to load ' + result.filePaths[0])
let liofs = result.filePaths[0].lastIndexOf('/')
if (liofs == -1) {
liofs = result.filePaths[0].lastIndexOf('\\')
}
let replayName = result.filePaths[0]
if (liofs != -1) {
replayName = replayName.substring(liofs + 1)
}
const liofp = replayName.lastIndexOf('.')
if (liofp != -1) {
replayName = replayName.substring(0, liofp)
}
let gco: Replay = {
gameId: Api.getGameManager().createGameId(replayName, true),
gameName: replayName,
kind: GameType.Replay,
path: result.filePaths[0],
}
//new GameCreationOptions(null, null, filenames[0], StartType.Replay, null, null, null, null, replayName)
this.startGameWithOptions(gco)
}
})
}
private startGameWithOptions(o: GameCreationOptions): Promise<GameInfo> {
//Hotfix.reloadIntoGame(o)
Logger.getLogger().log('App', 'startGameWithOptions', 'starting game with options: ' + JSON.stringify(o))
return Api.getGameManager().createGame(o).then(info => {
this.showGame(info.id)
return info
})
}
private toggleMenu() {
this.setState({ menuRetracted: !this.state.menuRetracted })
}
private toggleConsole() {
this.setState({ consoleRetracted: !this.state.consoleRetracted })
}
private showGame(gameId: number) {
console.log('Switching to game with id', gameId)
/* FIXME: Game.tsx depends on a componentWillUnmount call when switching to
another game. But React doesn't unmount the Game component if we are just
switching between two games (keeping contentState at AppContent.GameLive).
So we are switching to GameWaiting before to trigger an unmount. The
expectation was that changing the props always unmounts the component, but
this seems not to be true. Better move the code out of the unmount callback
and research how to listen for property changes. */
this.show(AppContent.GameWaiting, () =>
this.setState({
contentState: AppContent.GameLive,
activeGameId: gameId,
}),
)
}
private show(content: AppContent, callback?: () => void) {
this.setState({
contentState: content,
}, callback)
}
private refreshContent(inbetween: AppContent = AppContent.Blank) {
const previousState = this.state.contentState
this.show(inbetween, () => {
this.show(previousState)
})
}
componentDidMount() {
promiseRetry(retry => Api.getGameManager().getGameServerStatus().then(info => {
this.setState({ serverPort: info.port })
if (info.status == ExecutableStatus.Status.ERROR || info.status == ExecutableStatus.Status.EXITED) {
Logger.getLogger().logError('App', 'server', 'Server status ' + info.status.toString() + ': ' + info.error, info.error)
alert('Es gab einen Fehler beim Starten des Game-Servers, das Programm wird wahrscheinlich nicht funktionieren!\n' +
(info.error ? 'Fehler: ' + info.error : 'Ist Java installiert?'))
}
}).catch(retry))
}
closeGame(id: number) {
console.log('Closing game ' + id)
Api.getGameManager().deleteGame(id)
if (require('electron').remote.app.commandLine.hasSwitch('kioskMode')) {
this.show(AppContent.GameCreation)
} else {
this.show(AppContent.Empty)
}
}
showHtml(url: string) {
return <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
<button className="top-wide" onClick={() => shell.openExternal(url)}>Extern öffnen</button>
<iframe style={{ flex: 1, border: 0 }} src={url}/>
</div>
}
render() {
let mainPaneContent
switch (this.state.contentState) {
case AppContent.Administration:
mainPaneContent =
<Administration settings={this.state.settings} setter={(newSettings: Partial<AppSettings>) => {
this.setState({ settings: { ...this.state.settings, ...newSettings } },
() => saveToStorage(appSettingsKey, this.state.settings))
if (newSettings.logDir != null) {
window.localStorage['logDir'] = newSettings.logDir
}
}}/>
break
case AppContent.GameCreation:
mainPaneContent =
<GameCreation serverPort={this.state.serverPort} createGame={o => this.startGameWithOptions(o)}/>
break
case AppContent.GameLive:
console.log('activeGameId: ' + this.state.activeGameId)
mainPaneContent =
<Game gameId={this.state.activeGameId} name={Api.getGameManager().getGameInfo(this.state.activeGameId).name}
isReplay={Api.getGameManager().getGameInfo(this.state.activeGameId).isReplay}
settings={this.state.settings}/>
break
case AppContent.Blank:
mainPaneContent = <div/>
break
case AppContent.Error:
mainPaneContent = <ErrorPage Title="Schlimmer Fehler" Message="Das Programm ist kaputt."/>
break
case AppContent.Rules:
mainPaneContent = this.showHtml('https://cau-kiel-tech-inf.github.io/socha-enduser-docs/spiele/hive/')
break
case AppContent.Help:
mainPaneContent = this.showHtml('https://cau-kiel-tech-inf.github.io/socha-enduser-docs/server.html#die-programmoberfl%C3%A4che')
break
case AppContent.Quickstart:
mainPaneContent = this.showHtml('https://cau-kiel-tech-inf.github.io/socha-enduser-docs/getting-started')
break
case AppContent.JavaDocs:
mainPaneContent = this.showHtml('https://www.software-challenge.de/javadocs/')
break
case AppContent.Log:
const logger = Logger.getLogger()
mainPaneContent = <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
<button className="top-wide" onClick={() => {
logger.clearLog()
this.refreshContent()
}}>Log leeren
</button>
<div style={{
position: 'absolute',
top: '2em',
width: 'calc(100% - 230px)',
backgroundColor: '#eee',
}}>Logdatei: {logger.getLogFilePath()}</div>
<iframe style={{ flex: 1, border: 0, overflow: 'scroll' }}
src={logger.getLogFilePath()}
onLoad={() => {
document.querySelector('iframe')
.contentWindow
.document
.querySelector('body').style.overflowY = 'scroll'
}}/>
</div>
break
case AppContent.GameWaiting:
mainPaneContent = <div>
<h1>Warte auf Spielstart</h1>
<div id="errors"/>
</div>
break
default:
mainPaneContent =
<div className="main-container">
<div className="content">
<h1>Willkommen bei der Software-Challenge!</h1>
<p>Klicken Sie links auf "Neues Spiel" um zu beginnen.</p>
<p>Diese frühe Version hat noch einige Fehler. Bitte melden Sie Fehler, die Sie finden, im Forum oder im
Discord. Hinweise zur Ursache von Fehlern finden sich im Log, aufrufbar über "Programm-Log" auf der
linken Seite.</p>
<p><a href="https://cau-kiel-tech-inf.github.io/socha-enduser-docs/#die-programmoberfl%C3%A4che"
target="_blank">Bedienungsanleitung (aus der allgemeinen Dokumentation)</a></p>
</div>
</div>
break
}
const app = this
function ContentNavItem(props: { icon: string, text: string, content: AppContent }) {
return <NavItem icon={props.icon} text={props.text} onClick={() => app.show(props.content)}
active={app.state.contentState == props.content}/>
}
if (require('electron').remote.getGlobal('kioskMode')) {
return <Window>
<Content>
<PaneGroup>
<Pane>
{mainPaneContent}
</Pane>
</PaneGroup>
</Content>
</Window>
}
return <Window>
<Toolbar>
<ToolbarActions>
<ButtonGroup>
<Button icon="menu" onClick={() => this.toggleMenu()} active={!this.state.menuRetracted}/>
</ButtonGroup>
{this.state.contentState == AppContent.GameLive ?
<button title="Close Game" className="svg-button close-game"
onClick={() => this.closeGame(this.state.activeGameId)}>
<img className="svg-icon" src={'resources/x-circled.svg'} alt="Close Game"/>
</button> : null}
<Button icon="doc-text" onClick={() => { this.toggleConsole() }} pullRight={true}/>
</ToolbarActions>
</Toolbar>
<Content>
<PaneGroup>
<RetractableSidebar retracted={this.state.menuRetracted}>
<NavGroup>
<NavTitle title="Spiele"/>
<ContentNavItem key="new" content={AppContent.GameCreation} icon="+" text="Neues Spiel"/>
<NavItem key="replay" onClick={() => this.loadReplay()} icon="↥" text="Replay laden"/>
{Api.getGameManager().getGameInfos().map(
t => (<NavItem key={t.id} onClick={() => this.showGame(t.id)}
active={this.state.contentState == AppContent.GameLive && this.state.activeGameId == t.id}>
<UnicodeIcon icon="🎳"/>{t.name} ({t.id})
<span className="close-button-container">
<button title="Close Game" className="svg-button close-game" onClick={e => {
this.closeGame(t.id)
e.stopPropagation()
}}>
<img className="svg-icon" src={'resources/x-circled.svg'} alt={'Close Game'}/></button></span></NavItem>
))}
<NavTitle title="Informationen"/>
<ContentNavItem key="settings" content={AppContent.Administration} icon="⚙" text="Einstellungen"/>
<ContentNavItem key="rules" content={AppContent.Rules} icon="❔" text="Spielregeln"/>
<ContentNavItem key="help" content={AppContent.Help} icon="❔" text="Hilfe"/>
<ContentNavItem key="quickstart" content={AppContent.Quickstart} icon="❔" text="Getting Started"/>
<ContentNavItem key="javadocs" content={AppContent.JavaDocs} icon="❔" text="JavaDocs"/>
<ContentNavItem key="log" content={AppContent.Log} icon="📜" text="Logs"/>
</NavGroup>
</RetractableSidebar>
<Pane>
{mainPaneContent}
</Pane>
<RetractableSidebar className="wide" retracted={this.state.consoleRetracted}>
{this.state.activeGameId ? <LogConsole gameId={this.state.activeGameId}/> : <div/>}
</RetractableSidebar>
</PaneGroup>
</Content>
</Window>
}
}