File: Menu.py

package info (click to toggle)
fofix-dfsg 3.121-2
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 27,016 kB
  • ctags: 4,131
  • sloc: python: 44,002; makefile: 99; perl: 42; sh: 39
file content (520 lines) | stat: -rwxr-xr-x 20,970 bytes parent folder | download | duplicates (4)
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
#####################################################################
# -*- coding: iso-8859-1 -*-                                        #
#                                                                   #
# Frets on Fire                                                     #
# Copyright (C) 2006 Sami Ky�stil�                                  #
#               2008 myfingershurt                                  #
#               2008 evilynux <evilynux@gmail.com>                  #
#                                                                   #
# This program is free software; you can redistribute it and/or     #
# modify it under the terms of the GNU General Public License       #
# as published by the Free Software Foundation; either version 2    #
# of the License, or (at your option) any later version.            #
#                                                                   #
# This program is distributed in the hope that it will be useful,   #
# but WITHOUT ANY WARRANTY; without even the implied warranty of    #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the     #
# GNU General Public License for more details.                      #
#                                                                   #
# You should have received a copy of the GNU General Public License #
# along with this program; if not, write to the Free Software       #
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,        #
# MA  02110-1301, USA.                                              #
#####################################################################

import pygame
from OpenGL.GL import *
import math
import os

from View import Layer
from Input import KeyListener
import Data
import Theme
import Dialogs
import Player

import Log

class Choice:
  def __init__(self, text, callback, name = None, values = None, valueIndex = 0, append_submenu_char = True, tipText = None):
    #Log.debug("Choice class init (Menu.py)...")
    self.text       = unicode(text)
    self.callback   = callback
    self.name       = name
    self.values     = values
    self.valueIndex = valueIndex
    self.append_submenu_char = append_submenu_char
    self.tipText    = tipText

    if self.text.endswith(" >"):
      self.text = text[:-2]
      self.isSubMenu = True
    else:
      self.isSubMenu = isinstance(self.callback, Menu) or isinstance(self.callback, list)
    
  #MFH - add support for passing position values to the callback "next menu"
  def trigger(self, engine = None):
    if engine and isinstance(self.callback, list):
      #MFH 
      if self.values:
        nextMenu = Menu(engine, self.callback, name = self.name, pos = self.values, selectedIndex = self.valueIndex )
      else:
        nextMenu = Menu(engine, self.callback, name = self.name)
    elif engine and isinstance(self.callback, Menu):
      nextMenu = self.callback
    elif self.values:
      nextMenu = self.callback(self.values[self.valueIndex])
    else:
      nextMenu = self.callback()
    if isinstance(nextMenu, Menu):
      engine.view.pushLayer(nextMenu)
      
  def selectNextValue(self):
    if self.values:
      self.valueIndex = (self.valueIndex + 1) % len(self.values)
      self.trigger()

  def selectPreviousValue(self):
    if self.values:
      self.valueIndex = (self.valueIndex - 1) % len(self.values)
      self.trigger()
      
  def getText(self, selected):
    if not self.values:
      if self.isSubMenu and self.append_submenu_char:
        return "%s >" % self.text
      return self.text
    if selected:
      return "%s: %s%s%s" % (self.text, Data.LEFT, self.values[self.valueIndex], Data.RIGHT)
    else:
      return "%s: %s" % (self.text, self.values[self.valueIndex])
          
class Menu(Layer, KeyListener):
  def __init__(self, engine, choices, name = None, onClose = None, onCancel = None, pos = (.2, .66 - .35), viewSize = 6, fadeScreen = False, font = "font", mainMenu = None, textColor = None, selectedColor = None, append_submenu_char = True, selectedIndex = None, showTips = True, selectedBox = False):
    self.engine       = engine

    self.logClassInits = self.engine.config.get("game", "log_class_inits")
    if self.logClassInits == 1:
      Log.debug("Menu class init (Menu.py)...")

    #Get theme
    self.themename = self.engine.data.themeLabel
    self.theme = self.engine.data.theme
    
    self.choices      = []
    self.currentIndex = 0
    #MFH
    if selectedIndex:
      self.currentIndex = selectedIndex
    self.time         = 0
    self.onClose      = onClose
    self.onCancel     = onCancel
    self.viewOffset   = 0
    self.name     = name # akedrou - for graphical support
    self.mainMenu = False
    self.graphicMenu = False
    self.useSelectedBox = selectedBox
    self.useGraphics = self.engine.config.get("game", "use_graphical_submenu")
    self.gfxText = None
    
    self.scrolling = 0
    self.delay     = 0
    self.rate      = 0
    self.scroller  = [0, self.scrollUp, self.scrollDown, self.scrollLeft, self.scrollRight]

    self.textColor = textColor
    self.selectedColor = selectedColor
    self.tipColor = Theme.menuTipTextColor

    #self.sfxVolume    = self.engine.config.get("audio", "SFX_volume")
    self.drumNav = self.engine.config.get("game", "drum_navigation")  #MFH
    
    if self.name and self.useGraphics > 0:
      try:
        try:
          self.engine.loadImgDrawing(self, "menuBackground", os.path.join("themes",self.themename,"menu","%s.png" % self.name))
          if self.menuBackground.height1() == 1:
            self.menuBackground = None
        except IOError:
          self.menuBackground = None
        self.gfxText = "%stext%d" % (self.name, len(choices))
        self.engine.loadImgDrawing(self, "menuText", os.path.join("themes",self.themename,"menu","%s.png" % self.gfxText))
        self.graphicMenu = True
        self.menux = Theme.submenuX[self.gfxText]
        self.menuy = Theme.submenuY[self.gfxText]
        self.menuScale = Theme.submenuScale[self.gfxText]
        self.vSpace = Theme.submenuVSpace[self.gfxText]
        if str(self.menux) != "None" and str(self.menuy) != "None":
          self.menux = float(self.menux)
          self.menuy = float(self.menuy)
        else:
          self.menux = .4
          self.menuy = .4
        if str(self.menuScale) != "None":
          self.menuScale = float(self.menuScale)
        else:
          self.menuScale = .5
        if str(self.vSpace) != "None":
          self.vSpace = float(self.vSpace)
        else:
          self.vSpace = .08
        Log.debug("Graphic menu enabled for submenu: %s" % self.name)
      except IOError:
        self.menuBackground = None
        self.menuText = None
      except KeyError:
        Log.warn("Your theme does not appear to properly support the %s graphical submenu. Check to be sure you have the latest version of your theme." % self.name)
        self.menuBackground = None
        self.menuText = None


    if pos == (.2, .66 - .35):  #MFH - default position, not called with a special one - this is a submenu:
      self.sub_menu_x = Theme.sub_menu_xVar
      self.sub_menu_y = Theme.sub_menu_yVar
  
      if engine.data.theme == 0:
        if self.sub_menu_x == None:
          self.sub_menu_x = .44
        if self.sub_menu_y == None:
          self.sub_menu_y = .14
      elif engine.data.theme == 1:
        if self.sub_menu_x == None:
          self.sub_menu_x = .38
        if self.sub_menu_y == None:
          self.sub_menu_y = .15
      elif engine.data.theme == 2:
        if self.sub_menu_x == None:
          self.sub_menu_x = .25
        if self.sub_menu_y == None:
          self.sub_menu_y = .14

      pos = (self.sub_menu_x, self.sub_menu_y)

    if viewSize == 6:   #MFH - default viewsize
      if self.theme == 0 or self.theme == 1 or self.theme == 2:#8bit
        viewSize = 10
    
    self.pos          = pos
    self.viewSize     = viewSize
    self.fadeScreen   = fadeScreen
    self.font         = font
    if self.font == "font":
      self.font = self.engine.data.font
    self.tipFont = Theme.menuTipTextFont
    if self.tipFont == "None":
      self.tipFont = self.font
    else:
      self.tipFont = self.engine.data.fontDict[self.tipFont]
    self.active = False
    self.mainMenu = mainMenu
    
    self.showTips = showTips
    if self.showTips:
      self.showTips = Theme.menuTipTextDisplay
    self.tipDelay = 700
    self.tipTimerEnabled = False
    self.tipScroll = 0
    self.tipScrollB = None
    self.tipScrollSpace = Theme.menuTipTextScrollSpace
    self.tipScale = Theme.menuTipTextScale
    self.tipDir = 0
    self.tipSize = 0
    self.tipY = Theme.menuTipTextY
    self.tipScrollMode = Theme.menuTipTextScrollMode # - 0 for constant scroll; 1 for back and forth
    
    for c in choices:
      try:
        text, callback = c
        if isinstance(text, tuple):
          if len(text) == 2: # a submenu's name
            c = Choice(text[0], callback, name = text[1], append_submenu_char = append_submenu_char)
          else: # Dialogs menus - FileChooser, NeckChooser, ItemChooser - this last to be changed soon
            c = Choice(text[0], callback, values = text[2], valueIndex = text[1], append_submenu_char = append_submenu_char)
        else:
          c = Choice(text, callback, append_submenu_char = append_submenu_char)
      except ValueError:
        text, callback, tipText = c
        if isinstance(text, tuple):
          if len(text) == 2: # a submenu's name
            c = Choice(text[0], callback, name = text[1], append_submenu_char = append_submenu_char, tipText = tipText)
          else: # Dialogs menus - FileChooser, NeckChooser, ItemChooser - this last to be changed soon
            c = Choice(text[0], callback, values = text[2], valueIndex = text[1], append_submenu_char = append_submenu_char, tipText = tipText)
        else:
          c = Choice(text, callback, append_submenu_char = append_submenu_char, tipText = tipText)
      except TypeError:
        pass
      self.choices.append(c)
    
    self.setTipScroll()
      
  def selectItem(self, index):
    self.currentIndex = index
    
  def shown(self):
    self.engine.input.addKeyListener(self)
    
  def hidden(self):
    self.engine.input.removeKeyListener(self)
    if self.onClose:
      self.onClose()

  def updateSelection(self):
    self.setTipScroll()
    if self.currentIndex > self.viewOffset + self.viewSize - 1:
      self.viewOffset = self.currentIndex - self.viewSize + 1
    if self.currentIndex < self.viewOffset:
      self.viewOffset = self.currentIndex
    
  #MFH added drum navigation conditional here to prevent drum nav if disabled
  #MFH updated SFX play logic to just play the new sound instead of setting volume
  def keyPressed(self, key, unicode): #racer: drum nav.
    choice = self.choices[self.currentIndex]
    c = self.engine.input.controls.getMapping(key)
    if c in Player.menuYes or key == pygame.K_RETURN:
      self.scrolling = 0
      choice.trigger(self.engine)
      #self.engine.data.acceptSound.setVolume(self.sfxVolume)  #MFH
      self.engine.data.acceptSound.play()
    elif c in Player.menuNo or key == pygame.K_ESCAPE:
      if self.onCancel:
        self.onCancel()
      self.engine.view.popLayer(self)
      self.engine.input.removeKeyListener(self)
      #self.engine.data.cancelSound.setVolume(self.sfxVolume)  #MFH
      self.engine.data.cancelSound.play()
    elif c in Player.menuDown or key == pygame.K_DOWN:
      self.scrolling = 2
      self.delay = self.engine.scrollDelay
      self.scrollDown()
    elif c in Player.menuUp or key == pygame.K_UP:
      self.scrolling = 1
      self.delay = self.engine.scrollDelay
      self.scrollUp()
    elif c in Player.menuNext or key == pygame.K_RIGHT:
      self.scrolling = 4
      self.delay = self.engine.scrollDelay
      self.scrollRight()
    elif c in Player.menuPrev or key == pygame.K_LEFT:
      self.scrolling = 3
      self.delay = self.engine.scrollDelay
      self.scrollLeft()
    return True
  
  def scrollDown(self):
    self.engine.data.selectSound.play()
    self.currentIndex = (self.currentIndex + 1) % len(self.choices)
    self.updateSelection()
  
  def scrollUp(self):
    self.engine.data.selectSound.play()
    self.currentIndex = (self.currentIndex - 1) % len(self.choices)
    self.updateSelection()
  
  def scrollLeft(self):
    self.choices[self.currentIndex].selectPreviousValue()
    
  def scrollRight(self):
    self.choices[self.currentIndex].selectNextValue()
  
  def keyReleased(self, key):
    self.scrolling = 0
    
  def run(self, ticks):
    self.time += ticks / 50.0
    if self.scrolling > 0:
      self.delay -= ticks
      self.rate += ticks
      if self.delay <= 0 and self.rate >= self.engine.scrollRate:
        self.rate = 0
        self.scroller[self.scrolling]()
    if self.tipTimerEnabled:
      if self.tipDelay > 0:
        self.tipDelay -= ticks
        if self.tipDelay <= 0:
          self.tipDelay = 0
          self.tipDir = (self.tipDir+1)&1
      elif self.tipDir == 1 and self.tipScrollMode == 1:
        self.tipScroll -= ticks/8000.0
        if self.tipScroll < -(self.tipSize-.98):
          self.tipScroll = -(self.tipSize-.98)
          self.tipDelay = 900
      elif self.tipDir == 0 and self.tipScrollMode == 1:
        self.tipScroll += ticks/8000.0
        if self.tipScroll > .02:
          self.tipScroll = .02
          self.tipDelay = 900
      elif self.tipScrollMode == 0:
        self.tipScroll  -= ticks/8000.0
        self.tipScrollB -= ticks/8000.0
        if self.tipScroll < -(self.tipSize):
          self.tipScroll = self.tipScrollB + self.tipSize + self.tipScrollSpace
        if self.tipScrollB < -(self.tipSize):
          self.tipScrollB = self.tipScroll + self.tipSize + self.tipScrollSpace

  def renderTriangle(self, up = (0, 1), s = .2):
    left = (-up[1], up[0])
    glBegin(GL_TRIANGLES)
    glVertex2f( up[0] * s,  up[1] * s)
    glVertex2f((-up[0] + left[0]) * s, (-up[1] + left[1]) * s)
    glVertex2f((-up[0] - left[0]) * s, (-up[1] - left[1]) * s)
    glEnd()
  
  def setTipScroll(self):
    if self.choices[self.currentIndex].tipText is None:
      return
    tipW, tipH = self.tipFont.getStringSize(self.choices[self.currentIndex].tipText, self.tipScale)
    if tipW > .99:
      self.tipSize = tipW
      self.tipDelay = 1000
      self.tipTimerEnabled = True
      self.tipScroll = 0.02
      self.tipScrollB = 0.02 + self.tipSize + self.tipScrollSpace
      self.tipWait = False
      self.tipDir = 0
    else:
      self.tipScroll = .5 - tipW/2
      self.tipScrollB = None
      self.tipTimerEnabled = False
      self.tipDir = 0
      self.tipSize = tipW
  
  def render(self, visibility, topMost):
    #MFH - display version in any menu:

    if not visibility:
      self.active = False
      return

    self.active = True
    if self.graphicMenu and self.menuBackground:
      self.engine.graphicMenuShown = True
    else:
      self.engine.graphicMenuShown = False
    
    self.engine.view.setOrthogonalProjection(normalize = True)
    try:
      v = (1 - visibility) ** 2
      # Default to this font if none was specified

      font = self.font
      tipFont = self.tipFont

      if self.fadeScreen:
        Dialogs.fadeScreen(v)
        
      wS, hS = self.engine.view.geometry[2:4]
        
      if self.graphicMenu and self.menuBackground:
        #volshebnyi - better menu scaling
        self.engine.drawImage(self.menuBackground, scale = (1.0,-1.0), coord = (wS/2,hS/2), stretched = 3)
      else:
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
        glEnable(GL_COLOR_MATERIAL)

      n = len(self.choices)
      x, y = self.pos

      for i, choice in enumerate(self.choices[self.viewOffset:self.viewOffset + self.viewSize]):
        if self.graphicMenu:
          if self.currentIndex == i:
            xpos = (.5,1)
          else:
            xpos = (0,.5)
          ypos = float(i+self.viewOffset)
          self.menuText.transform.reset()
          self.menuText.transform.scale(.5*self.menuScale,(-1.0/n*self.menuScale))
          self.menuText.transform.translate(wS*self.menux,(hS*self.menuy)-(hS*self.vSpace)*i)
          self.menuText.draw(rect = (xpos[0],xpos[1],ypos/n,(ypos+1.0)/n))
          #self.engine.drawImage(self.menuText, scale = (self.menuScale,-self.menuScale*2/n), coord = (wS*self.menux,hS*(self.menuy-self.vSpace*i)), rect = (xpos[0],xpos[1],ypos/n,(ypos+1.0)/n), stretched = 11)
        else:
          text = choice.getText(i + self.viewOffset == self.currentIndex)
          glPushMatrix()
          glRotate(v * 45, 0, 0, 1)

          scale = 0.002
          if self.mainMenu and self.theme < 2 and i % 2 == 1:#8bit
              scale = 0.0016

          w, h = font.getStringSize(" ", scale = scale)

          # Draw arrows if scrolling is needed to see all items
          if i == 0 and self.viewOffset > 0:
            Theme.setBaseColor((1 - v) * max(.1, 1 - (1.0 / self.viewOffset) / 3))
            glPushMatrix()
            glTranslatef(x - v / 4 - w * 2, y + h / 2, 0)
            self.renderTriangle(up = (0, -1), s = .015)
            glPopMatrix()
          elif i == self.viewSize - 1 and self.viewOffset + self.viewSize < n:
            Theme.setBaseColor((1 - v) * max(.1, 1 - (1.0 / (n - self.viewOffset - self.viewSize)) / 3))
            glPushMatrix()
            glTranslatef(x - v / 4 - w * 2, y + h / 2, 0)
            self.renderTriangle(up = (0, 1), s = .015)
            glPopMatrix()

          if i + self.viewOffset == self.currentIndex:
            if choice.tipText and self.showTips:
              if self.tipColor:
                c1, c2, c3 = self.tipColor
                glColor3f(c1,c2,c3)
              elif self.textColor:
                c1, c2, c3 = self.textColor
                glColor3f(c1,c2,c3)
              else:
                Theme.setBaseColor(1-v)
              tipScale = self.tipScale
              if self.tipScroll > -(self.tipSize) and self.tipScroll < 1:
                tipFont.render(choice.tipText, (self.tipScroll, self.tipY), scale = tipScale)
              if self.tipScrollMode == 0:
                if self.tipScrollB > -(self.tipSize) and self.tipScrollB < 1:
                  tipFont.render(choice.tipText, (self.tipScrollB, self.tipY), scale = tipScale)
            a = (math.sin(self.time) * .15 + .75) * (1 - v * 2)
            Theme.setSelectedColor(a)
            a *= -.005
            glTranslatef(a, a, a)
          else:
            Theme.setBaseColor(1 - v)      
        
          #MFH - settable color through Menu constructor
          if i + self.viewOffset == self.currentIndex and self.selectedColor:
            c1,c2,c3 = self.selectedColor
            glColor3f(c1,c2,c3)
          elif self.textColor:
            c1,c2,c3 = self.textColor
            glColor3f(c1,c2,c3)
        
          #MFH - now to catch " >" main menu options and blank them:
          if text == " >":
            text = ""
            
          if self.engine.data.submenuSelectFound and len(text) > 0 and not self.mainMenu and self.useSelectedBox:
            Tw, Th = font.getStringSize(text,scale)
            lineSpacing = font.getLineSpacing(scale)
            frameWidth = Tw*1.10
            #frameHeight = (Th+Th2)*1.10
            frameHeight = Th + lineSpacing
            boxXOffset = (x + (Tw/2))*wS
            boxYOffset = (1.0 - (y*4.0/3.0) - (Th*1.2/2))*hS
            subSelectHYFactor = 640.000/self.engine.view.aspectRatio
            subSelectHFactor = subSelectHYFactor/self.engine.data.subSelectImgH
            self.engine.data.submenuSelect.transform.reset()
            tempWScale = frameWidth*self.engine.data.subSelectWFactor
            tempHScale = -(frameHeight)*subSelectHFactor
            self.engine.data.submenuSelect.transform.scale(tempWScale,tempHScale)
            self.engine.data.submenuSelect.transform.translate(boxXOffset,boxYOffset)
            self.engine.data.submenuSelect.draw()
          
          font.render(text, (x - v / 4, y), scale = scale)
        
        
          v *= 2
          if self.theme == 1 and self.font == self.engine.data.pauseFont: # evilynux - Ugly workaround for Gh3
            y += h*.70      #Worldrave - Changed Pause menu spacing back to .70 from .65 for now.
          else:
            y += h
          glPopMatrix()
    
    
    finally:
      self.engine.view.resetProjection()