LCOV - code coverage report
Current view: top level - widgets/messagewindow - window.go Coverage Total Hit
Test: coverage.lcov Lines: 99.0 % 191 189
Test Date: 2026-11-19 00:25:22 Functions: - 0 0

            Line data    Source code
       1              : package messagewindow
       2              : 
       3              : import (
       4              :         "fmt"
       5              : 
       6              :         "github.com/hajimehoshi/ebiten/v2"
       7              :         "github.com/kijimaD/ruins/internal/hooks"
       8              :         "github.com/kijimaD/ruins/internal/inputmapper"
       9              :         "github.com/kijimaD/ruins/internal/keybind"
      10              :         "github.com/kijimaD/ruins/internal/messagedata"
      11              :         "github.com/kijimaD/ruins/internal/widgets/theme"
      12              :         "github.com/kijimaD/ruins/internal/widgets/uicore"
      13              :         w "github.com/kijimaD/ruins/internal/world"
      14              : )
      15              : 
      16              : // Window はメッセージウィンドウを表す。
      17              : //
      18              : // 描画は uicore のツリーで組み、グローバル可変状態に触れない。UI は保持せず
      19              : // 毎フレーム buildTree で組み直す。フォーカスやページの差分追跡は不要で、現在の状態から都度描く
      20              : type Window struct {
      21              :         config      windowConfig
      22              :         content     messageContent
      23              :         world       w.World
      24              :         onClose     func()
      25              :         onChoice    func(choice choiceOption)
      26              :         isOpen      bool
      27              :         initialized bool
      28              :         body        uicore.Widget
      29              : 
      30              :         // 選択肢がある場合、ページング可能な選択肢一覧を表示する。ナビゲーションは hooks Store が持ち、
      31              :         // 描画に要る現在位置を choiceState に写す
      32              :         hasChoices   bool
      33              :         choiceConfig tabMenuConfig
      34              :         choiceState  viewState
      35              :         choiceStore  *hooks.Store
      36              : 
      37              :         // 複数メッセージを順番に表示
      38              :         queueManager   *queueManager
      39              :         currentMessage *messagedata.MessageData
      40              : }
      41              : 
      42              : // Update はウィンドウを更新する
      43              : func (w *Window) Update() error {
      44            1 :         if !w.isOpen {
      45            1 :                 return nil
      46            1 :         }
      47              : 
      48            1 :         if !w.initialized {
      49            1 :                 w.hasChoices = len(w.content.Choices) > 0
      50            1 :                 if w.hasChoices {
      51            1 :                         w.initChoiceMenu()
      52            1 :                 }
      53            1 :                 w.initialized = true
      54              :         }
      55              : 
      56            1 :         if w.hasChoices {
      57            1 :                 if err := w.handleChoiceInput(); err != nil {
      58            0 :                         return err
      59            0 :                 }
      60              :         } else {
      61            1 :                 if action, ok := w.HandleInput(); ok {
      62            1 :                         w.DoAction(action)
      63            1 :                 }
      64              :         }
      65              : 
      66              :         // 状態が確定してから現在の見た目を組み直す。閉じた、または次メッセージへ切り替えた直後は
      67              :         // 組まずに次フレームの再初期化へ譲る
      68            1 :         if w.isOpen && w.initialized {
      69            1 :                 w.body = w.buildTree()
      70            1 :         }
      71              : 
      72            1 :         return nil
      73              : }
      74              : 
      75              : // Draw はウィンドウを描画する
      76              : func (w *Window) Draw(screen *ebiten.Image) {
      77            1 :         if !w.isOpen || w.body == nil {
      78            1 :                 return
      79            1 :         }
      80            1 :         w.body.Draw(uicore.NewEbitenCanvas(screen))
      81              : }
      82              : 
      83              : // IsOpen はウィンドウが開いているかを返す
      84              : func (w *Window) IsOpen() bool {
      85            1 :         return w.isOpen
      86            1 : }
      87              : 
      88              : // IsClosed はウィンドウが閉じているかを返す
      89              : func (w *Window) IsClosed() bool {
      90            1 :         return !w.isOpen
      91            1 : }
      92              : 
      93              : // CurrentMessage は現在表示中のメッセージデータを返す
      94              : func (w *Window) CurrentMessage() *messagedata.MessageData {
      95            1 :         return w.currentMessage
      96            1 : }
      97              : 
      98              : // Close はウィンドウを閉じる
      99              : // キューに次のメッセージがある場合は閉じずに次を表示する
     100              : func (w *Window) Close() {
     101            1 :         if !w.isOpen {
     102            1 :                 return
     103            1 :         }
     104              : 
     105            1 :         if w.currentMessage != nil && w.currentMessage.OnComplete != nil {
     106            1 :                 w.currentMessage.OnComplete()
     107            1 :         }
     108              : 
     109            1 :         if w.queueManager != nil && w.queueManager.HasNext() {
     110            1 :                 w.showNextMessage()
     111            1 :                 return
     112            1 :         }
     113              : 
     114            1 :         w.isOpen = false
     115            1 : 
     116            1 :         if w.onClose != nil {
     117            1 :                 w.onClose()
     118            1 :         }
     119              : }
     120              : 
     121              : // showNextMessage はキューから次のメッセージを取り出して表示する
     122              : func (w *Window) showNextMessage() {
     123            1 :         if w.queueManager == nil {
     124            1 :                 return
     125            1 :         }
     126              : 
     127            1 :         nextMessage := w.queueManager.Dequeue()
     128            1 :         if nextMessage == nil {
     129            1 :                 w.isOpen = false
     130            1 :                 if w.onClose != nil {
     131            1 :                         w.onClose()
     132            1 :                 }
     133            1 :                 return
     134              :         }
     135              : 
     136            1 :         w.currentMessage = nextMessage
     137            1 :         w.updateContentFromMessage(nextMessage)
     138            1 : 
     139              :         // 次フレームで再初期化させる
     140            1 :         w.initialized = false
     141            1 :         w.body = nil
     142            1 :         w.choiceStore = nil
     143              : }
     144              : 
     145              : // updateContentFromMessage はMessageDataから表示コンテンツを更新する
     146              : func (w *Window) updateContentFromMessage(msg *messagedata.MessageData) {
     147            1 :         w.content.SpeakerName = msg.Speaker
     148            1 :         w.content.TextSegmentLines = msg.TextSegmentLines
     149            1 : 
     150            1 :         w.content.Choices = make([]choiceOption, len(msg.Choices))
     151            1 :         for i, choice := range msg.Choices {
     152            1 :                 w.content.Choices[i] = choiceOption{
     153            1 :                         Text: choice.Text,
     154            1 :                         Action: func() error {
     155            1 :                                 if choice.Action != nil {
     156            1 :                                         if err := choice.Action(w.world); err != nil {
     157            1 :                                                 return err
     158            1 :                                         }
     159              :                                 }
     160              :                                 // 選択肢に関連メッセージがある場合はキュー先頭に追加して即座に表示
     161            1 :                                 if choice.MessageData != nil {
     162            1 :                                         if w.queueManager == nil {
     163            1 :                                                 w.queueManager = newQueueManager()
     164            1 :                                         }
     165            1 :                                         w.queueManager.EnqueueFront(choice.MessageData)
     166              :                                 }
     167            1 :                                 return nil
     168              :                         },
     169              :                 }
     170              :         }
     171              : }
     172              : 
     173              : // calculateWindowPosition はウィンドウの表示位置を計算する。
     174              : // 横は画面中央、上端は他のウィンドウと同じ MenuWindowTop で揃える
     175              : func (w *Window) calculateWindowPosition(windowSize windowSize) (x, y int) {
     176            1 :         screenWidth := w.world.Resources.ScreenDimensions.Width
     177            1 :         screenHeight := w.world.Resources.ScreenDimensions.Height
     178            1 : 
     179            1 :         x = (screenWidth - windowSize.Width) / 2
     180            1 :         y = theme.MenuWindowTop
     181            1 : 
     182            1 :         margin := 30
     183            1 :         if y+windowSize.Height > screenHeight-margin {
     184            1 :                 y = screenHeight - windowSize.Height - margin
     185            1 :         }
     186            1 :         if y < margin {
     187            1 :                 y = margin
     188            1 :         }
     189              : 
     190            1 :         return x, y
     191              : }
     192              : 
     193              : // calculateWindowSize は選択肢に応じてウィンドウサイズを計算する
     194              : func (w *Window) calculateWindowSize() windowSize {
     195              :         // 内容が収まる高さと設定の最小高の大きいほうを採る。内容が少なくても窓は痩せず、
     196              :         // 選択肢が増えれば必要なぶんだけ伸びる
     197            1 :         height := max(w.config.Size.Height, w.requiredHeight())
     198            1 :         // 画面高の8割で頭を打つ。窓が画面を覆い尽くさないようにする
     199            1 :         height = min(height, int(float64(w.world.Resources.ScreenDimensions.Height)*maxHeightRatio))
     200            1 : 
     201            1 :         return windowSize{
     202            1 :                 Width:  w.config.Size.Width,
     203            1 :                 Height: height,
     204            1 :         }
     205              : }
     206              : 
     207              : // hasMessage はメッセージがあるかどうかを判定する
     208              : func (w *Window) hasMessage() bool {
     209            1 :         for _, lineSegments := range w.content.TextSegmentLines {
     210            1 :                 if !lineIsBlank(lineSegments) {
     211            1 :                         return true
     212            1 :                 }
     213              :         }
     214            1 :         return false
     215              : }
     216              : 
     217              : // HandleInput はキーボード入力をActionに変換する。束縛表は設定の SkippableKeys から導出し、
     218              : // 供給源があればそこから読むので再生ドライバでも駆動できる
     219              : func (w *Window) HandleInput() (inputmapper.ActionID, bool) {
     220            1 :         return keybind.ReadInput(w.world, skipBindings(w.config.SkippableKeys))
     221            1 : }
     222              : 
     223              : // skipBindings は読み飛ばしキーの一覧から束縛表を導出する。Enter だけは確定として区別する
     224              : func skipBindings(keys []ebiten.Key) []keybind.Binding {
     225            1 :         rows := make([]keybind.Binding, 0, len(keys))
     226            1 :         for _, key := range keys {
     227            1 :                 action := inputmapper.ActionSkip
     228            1 :                 if key == ebiten.KeyEnter {
     229            1 :                         action = inputmapper.ActionConfirm
     230            1 :                 }
     231            1 :                 rows = append(rows, keybind.Binding{Key: key, Action: action})
     232              :         }
     233            1 :         return rows
     234              : }
     235              : 
     236              : // DoAction はActionを実行する
     237              : func (w *Window) DoAction(action inputmapper.ActionID) {
     238            1 :         switch action {
     239              :         case inputmapper.ActionConfirm, inputmapper.ActionSkip:
     240            1 :                 w.Close()
     241              :         default:
     242            1 :                 panic(fmt.Sprintf("invalid action: %s", action))
     243              :         }
     244              : }
     245              : 
     246              : // initChoiceMenu は選択肢メニューを初期化する
     247              : func (w *Window) initChoiceMenu() {
     248            1 :         if len(w.content.Choices) == 0 {
     249            1 :                 return
     250            1 :         }
     251              : 
     252            1 :         items := make([]item, len(w.content.Choices))
     253            1 :         for i, choice := range w.content.Choices {
     254            1 :                 items[i] = item{
     255            1 :                         ID:       choice.Text,
     256            1 :                         Label:    choice.Text,
     257            1 :                         UserData: i,
     258            1 :                 }
     259              :         }
     260              : 
     261            1 :         itemsPerPage := w.calculateItemsPerPage(len(w.content.Choices))
     262            1 : 
     263            1 :         w.choiceConfig = tabMenuConfig{
     264            1 :                 Tabs: []tabItem{
     265            1 :                         {ID: "choices", Label: "", Items: items},
     266            1 :                 },
     267            1 :                 ItemsPerPage: itemsPerPage,
     268            1 :         }
     269              : 
     270              :         // hooks で Skip 込みのナビゲーションを管理する
     271            1 :         skips := make([]bool, len(w.currentMessage.Choices))
     272            1 :         for i, choice := range w.currentMessage.Choices {
     273            1 :                 skips[i] = choice.Action == nil
     274            1 :         }
     275              : 
     276            1 :         w.choiceStore = hooks.NewStore()
     277            1 :         menuState := hooks.UseTabMenu(w.choiceStore, "choices", hooks.TabMenuConfig{
     278            1 :                 TabCount:     1,
     279            1 :                 ItemCounts:   []int{len(items)},
     280            1 :                 ItemsPerPage: itemsPerPage,
     281            1 :                 Skips:        [][]bool{skips},
     282            1 :         })
     283            1 : 
     284            1 :         w.choiceState = viewState{
     285            1 :                 TabIndex:  menuState.TabIndex,
     286            1 :                 ItemIndex: menuState.ItemIndex,
     287            1 :         }
     288              : }
     289              : 
     290              : // handleChoiceInput はキー入力を hooks Store にディスパッチし、描画状態を同期する
     291              : func (w *Window) handleChoiceInput() error {
     292            1 :         action, ok := keybind.ReadInput(w.world, choiceBindings)
     293            1 :         if !ok {
     294            1 :                 return nil
     295            1 :         }
     296              : 
     297            1 :         switch action {
     298              :         case inputmapper.ActionMenuSelect:
     299            1 :                 menuState, _ := hooks.GetStoreState[hooks.TabMenuState](w.choiceStore, "choices")
     300            1 :                 return w.selectChoice(menuState.ItemIndex)
     301              :         case inputmapper.ActionMenuCancel:
     302            1 :                 w.Close()
     303            1 :                 return nil
     304              :         default:
     305            1 :                 w.choiceStore.Dispatch(action)
     306            1 :                 menuState, _ := hooks.GetStoreState[hooks.TabMenuState](w.choiceStore, "choices")
     307            1 :                 w.choiceState = viewState{
     308            1 :                         TabIndex:  menuState.TabIndex,
     309            1 :                         ItemIndex: menuState.ItemIndex,
     310            1 :                 }
     311            1 :                 return nil
     312              :         }
     313              : }
     314              : 
     315              : // choiceBindings は選択肢メニューの束縛表
     316              : var choiceBindings = []keybind.Binding{
     317              :         {Key: ebiten.KeyArrowUp, Press: keybind.PressRepeat, Action: inputmapper.ActionMenuUp},
     318              :         {Key: ebiten.KeyArrowDown, Press: keybind.PressRepeat, Action: inputmapper.ActionMenuDown},
     319              :         {Key: ebiten.KeyEnter, Action: inputmapper.ActionMenuSelect},
     320              :         {Key: ebiten.KeyEscape, Action: inputmapper.ActionMenuCancel},
     321              : }
     322              : 
     323              : // calculateItemsPerPage は1ページあたりの選択肢の件数を返す。窓の上限高から選択肢以外の
     324              : // 取り分を引いた残りを、実際に描く行高で割る。取り分と行高は描画と同じ値を使うので、
     325              : // 計算した件数がそのまま収まる。
     326              : func (w *Window) calculateItemsPerPage(totalItems int) int {
     327            1 :         maxHeight := int(float64(w.world.Resources.ScreenDimensions.Height) * maxHeightRatio)
     328            1 : 
     329              :         // 選択肢の塊を除いた取り分。requiredHeight から選択肢1行ぶんを引いて求める
     330            1 :         overhead := w.chromeHeight() + pageRowH
     331            1 :         perPage := (maxHeight - overhead) / choiceRowH
     332            1 :         perPage = min(max(perPage, minItemsPerPage), maxItemsPerPage)
     333            1 : 
     334            1 :         return min(totalItems, perPage)
     335            1 : }
     336              : 
     337              : // selectChoice は選択肢を選択する
     338              : func (w *Window) selectChoice(index int) error {
     339            1 :         if index < 0 || index >= len(w.content.Choices) {
     340            1 :                 return nil
     341            1 :         }
     342              : 
     343            1 :         choice := w.content.Choices[index]
     344            1 : 
     345              :         // コールバック実行
     346            1 :         if w.onChoice != nil {
     347            1 :                 w.onChoice(choice)
     348            1 :         }
     349              : 
     350              :         // アクション実行
     351            1 :         if choice.Action != nil {
     352            1 :                 if err := choice.Action(); err != nil {
     353            1 :                         return err
     354            1 :                 }
     355              :         }
     356              : 
     357              :         // ウィンドウを閉じる
     358            1 :         w.Close()
     359            1 :         return nil
     360              : }
        

Generated by: LCOV version 2.0-1