github.com/wtfutil/wtf@v0.43.0/app/app_manager.go (about)

     1  package app
     2  
     3  import (
     4  	"errors"
     5  
     6  	"github.com/olebedev/config"
     7  	"github.com/rivo/tview"
     8  )
     9  
    10  // WtfAppManager handles the instances of WtfApp, ensuring that they're displayed as requested
    11  type WtfAppManager struct {
    12  	WtfApps []*WtfApp
    13  
    14  	selected int
    15  }
    16  
    17  // NewAppManager creates and returns an instance of AppManager
    18  func NewAppManager() WtfAppManager {
    19  	appMan := WtfAppManager{
    20  		WtfApps: []*WtfApp{},
    21  	}
    22  
    23  	return appMan
    24  }
    25  
    26  // MakeNewWtfApp creates and starts a new instance of WtfApp from a set of configuration params
    27  func (appMan *WtfAppManager) MakeNewWtfApp(config *config.Config, configFilePath string) {
    28  	wtfApp := NewWtfApp(tview.NewApplication(), config, configFilePath)
    29  	appMan.Add(wtfApp)
    30  
    31  	wtfApp.Start()
    32  }
    33  
    34  // Add adds a WtfApp to the collection of apps that the AppManager manages.
    35  // This app is then available for display onscreen.
    36  func (appMan *WtfAppManager) Add(wtfApp *WtfApp) {
    37  	appMan.WtfApps = append(appMan.WtfApps, wtfApp)
    38  }
    39  
    40  // Current returns the currently-displaying instance of WtfApp
    41  func (appMan *WtfAppManager) Current() (*WtfApp, error) {
    42  	if appMan.selected < 0 || appMan.selected >= len(appMan.WtfApps) {
    43  		return nil, errors.New("invalid app index selected")
    44  	}
    45  
    46  	return appMan.WtfApps[appMan.selected], nil
    47  }
    48  
    49  // Next cycles the WtfApps forward by one, making the next one in the list
    50  // the current one. If there are none after the current one, it wraps around.
    51  func (appMan *WtfAppManager) Next() (*WtfApp, error) {
    52  	appMan.selected++
    53  
    54  	if appMan.selected >= len(appMan.WtfApps) {
    55  		appMan.selected = 0
    56  	}
    57  
    58  	return appMan.Current()
    59  }
    60  
    61  // Prev cycles the WtfApps backwards by one, making the previous one in the
    62  // list the current one. If there are none before the current one, it wraps around.
    63  func (appMan *WtfAppManager) Prev() (*WtfApp, error) {
    64  	appMan.selected--
    65  
    66  	if appMan.selected < 0 {
    67  		appMan.selected = len(appMan.WtfApps) - 1
    68  	}
    69  
    70  	return appMan.Current()
    71  }