// Example on how to use the Launchpad Mini MkIII as an interface to LoopToGo
//			It should be see as a demo, not a perfect solution. You should adapt it to your own needs
// Arguments:  must be provided by the midi events from the LaunchPad Mini
//
// Author: LoopToGo
//
// Description  : 
//			This script must be linked to midi events from the LaunchPad Mini MKIII
//				To do so, open the Script manager dialog, select this script and press the "Link script to MIDI or keyboard event..." button
//				Check "Use MIDI event as arg."
//				Press the "MIDI learn..." button
// 				Check "Any event", "Device" and "Channel" but not "Status"
//				Press any button on the LaunchPad mini until an event is showmn then press OK
//				After the MIDI learn is completed for this script, you can also assigned the MidiLedEffects scripts. Make sure you are on page 5 before doing the midi learn.
//				For page 2 to work properly (Volume page), you will also want to do the MIDI learn for all the "Set volume for Track" shorcuts in Preferences/Shorcuts
//
//			Important, you must set the aDevice aliases (below) to match your LaunchPad Mini names as shown in the Midi list (Preferences/Midi). 
//
//			To test if the script is working, 
//				Make sure you have at least a colored track in the Looper view
//				Press the Session button on the LauncPad Mini
//				Then, press the second button (page 2) on the right (with an arrow). 
//				You should see some buttons turning blue on the LaunchPad. These are used to set the track's volume
//
//			This script is meant to be use with the midiLedEffects.ltgs script
//				Make sure you are in session mode (Session button is green)
//				Press the third button (page 3) on the right (with an arrow)
//				Open the Script manager dialog, select the midiLedEffects.ltgs script and press the "Link script to MIDI or keyboard event..." button
//				Check "Use MIDI event as arg."
//				Press the "MIDI learn..." button
// 				Check "Any event", "Device" and "Channel" but not "Status"
//				Press any button on the LaunchPad Mini (the 8x8 pas section) until an event is showmn then press OK
//
//			Here is a description of how the LaunchPad will behave when this script is installed and configured properly
//
//				Button Drums, Keys and User behave normally and can be configure using the Component software from Novation
//				Session button: enable all the features from this script
//				Right most buttons (with arrow): select the current LaunchPad page (1 to 7). The code for choosing more page has been commented and could be uncommented if you need more than 7 pages 
//				Botton right button (Stop/Solo/Mute): resume from the Jam Mode. Note that you could easily remove this functionality or change it for something else 
//				8x8 Pads: behavior depnds on which page the LaunchPad is
//					Page 1: Transport and various LoopToGo functionality (see transportLedLaunchPad.ltgs)
//						Row 1 (bottom)
//							Column 1 (Blue):	Rewind All
//							Column 2 (White):	Go to last start tick
//							Column 3 (Yellow):	Stop
//							Column 4 (Green):	Play/Pause
//							Column 5 (Red):		Record/Pause
//							Column 6 ():	
//							Column 7 (Green):	Load selected file from playlist
//							Column 8 (Yellow):	Select next file in playlist
//						Row 2
//							Column 1 (Blue):	Go to start of song					
//							Column 2 (Purple):	Previous start/end of loop					
//							Column 3 (Purple):	Next track					
//							Column 4 (Purple):	Next start/end of loop					
//							Column 5 (Blue):	Go to end of song
//							Column 6 ():	
//							Column 7 ():	
//							Column 8 (Yellow):	Select previous file in playlist					
//						Row 3
//							Column 1 (Yellow):	Load Preset A	
//							Column 2 (Yellow):	Load Preset B	
//							Column 3 (Purple):	Previous track	
//							Column 4 (Yellow):	Load Preset C	
//							Column 5 (Yellow):	Load Preset D	
//							Column 6 ():	
//							Column 7 (Blue):	Toggle Chain Editor/Looper	
//							Column 8 (Purple):	Show/Hide mixing console
//						Row 4
//							Column 1 ():	
//							Column 2 ():	
//							Column 3 (Pink):	Set playhead to current cursor
//							Column 4 ():	
//							Column 5 ():	
//							Column 6 ():	
//							Column 7 (Purple):	Toggle zoom horizontal (F2)
//							Column 8 (Purple):	Toggle zoom vertical (T)
//						Row 6
//							Column 1 ():	
//							Column 2 ():	
//							Column 3 ():	
//							Column 4 ():	
//							Column 5 ():	
//							Column 6 ():	
//							Column 7 (Blue):	Toggle Song structure view
//							Column 8 (Purple):	Toggle Plugin/Chain/Song/Playlist Browser
//						Row 7 and 8
//							Section leds. Colour will change when a section name is different from the previous one
//							Current section will flash and next jump section will pulse
//							Some section have predefined color: Intro, Verse, Chorus, etc. See aScriptTransportLEDScript script for more details 			
//
//					Page 2: Volume sliders
//						Arrow up and Down: change current bank (if more than 8 tracks)
//					Page 3: show an example a using the LaunchPad for Tempo (see tempoLedLaunchPad.ltgs)
//					Page 4: Jam mode (see jamModeLedNovationLaunchMini.ltgs for a full description)
//						Arrow up and Down: change current bank (if more than 8 tracks)
//					Page 5: show an example of led effects when pad are pressed (see midiLedEffects.ltgs)
//					Page 6-7: not implented
				
// You need to re-do the midi learn and reload all scripts (Scripts/Reload all scripts) after changing these mapped names
// You have to use the same mapping for the LaunchPad Mini in LoopToGo. You can define your own name if you want				
alias aDeviceIn LaunchPadMini		// This is a Mapped name. It accepts all MIDI channles for first midi port In 
alias aDeviceIn2 "LaunchPadMini Port 2"	// This is a mapped name. It accepts event from channel 1 only and is second midi port!!

alias aDeviceOut LaunchPadMini		// This is a MIDI OUT Mapped name. This is the first MIDI port! Channel 1
alias aDeviceOut2 "LaunchPadMini Port 2"	// This is a MIDI OUT mapped name. This is the second MIDI port! Channel 1

loadScript ..\aliases.txt

loadScript ..\libs\Novation\novationLaunchPadMiniUtilities.ltgl

alias aScriptJamModeScript "LoopToGo/ExamplesNovation/jamModeLedNovationLaunchMini.ltgs"
alias aScriptTempoLEDScript "LoopToGo/ExamplesNovation/tempoLedLaunchPad.ltgs"
alias aScriptTransportLEDScript "LoopToGo/ExamplesNovation/transportLedLaunchPad.ltgs"

//print $arg1 $arg2 $arg3 $arg4 $arg5 $arg6

//variable msg $arg1
variable status $arg2
variable channel $arg3
variable note $arg4
variable velocity $arg5

//print status: $status channel: $channel note: $note velocity: $velocity 


if $status = 128
	endScriptDynamic // This script only manage pressed event (Note on)
endIf



ifNot $gLaunchPadCurrentPage  // First time
	
	//print Initializing (first run)
	

	globalVariable gLaunchPadCurrentPage 1
	globalVariable gLaunchPadLastPage  1 

	globalVariable gCurrentMode -1  // -1 = None,  0 = Session, 1 = Drums, 2 = Keys, 3 = User
	
	// Make sure we are in Session and DAW mode  (Users must hit a pad for first time initialization)
	callFunction setLaunchPadLayout aDeviceOut 0  // 0 = Session, 1 = Drums, 2 = Keys, 3 = User, 4 = Faders (only in DAW mode), 5 = programmer Mode

	sendMidiRawBytes aDeviceOut "F0 00 20 29 02 0D 10 01 F7" // Daw mode
		
	callFunction initializePage1

	
	endScriptDynamic
	
endIf



variable cond1 $status = 176
variable cond2 $note > 18

if $cond1 * $cond2

	variable cond1 $note > 94
	variable cond2 $note < 99
	
	//print note : $note cond1 : $cond1 cond2 : $cond2
	
	if $cond1 * $cond2
		globalVariable gCurrentMode $note - 95 // -1 = None,  0 = Session, 1 = Drums, 2 = Keys, 3 = User
		//print gCurrentMode : $gCurrentMode
		endScriptDynamic
	endIf

	if $velocity = 0
		endScriptDynamic
	endIf
	
	if $note = 91
		shortcut "Shift+B"		// Previous bank
		callFunction updatePage $gLaunchPadCurrentPage $gLaunchPadCurrentPage
		endScriptDynamic
	endIf
	
	if $note = 92
		shortcut "B"		// Next bank
		callFunction updatePage $gLaunchPadCurrentPage $gLaunchPadCurrentPage
		endScriptDynamic
	endIf
	
			
	if $note = 19 // Solo buttons: various actions depending the actual state
		ifNot $isRecording 
		
			if $songBar = 1.0
				record				
			else
				rewindAll
			endIf	
			endScriptDynamic
		endIf
		
		if $isInJamMode
			shortcut O // We are in jam mode we go out of it!
		else
			shortcut J // We are not in jam mode we go in jam mode!
			shortcut J // Twice to go in Overdub!
			
			waitDelta .05
			
			ifNot $isInJamMode
				// If we are still not in Jam mode, it means we are not over a record loop. We pause;			
				pause
			endIf
			
		endIf
		
		endScriptDynamic
		
	endIf
	
	variable note10 $note/10 1
	variable note1 $note - $note10*10
		
	if $note1 = 9 // Right buttons change page!!! Notes re 89, 79, 69 .... 19 (we use 19 for something else!)
					
		globalVariable gLaunchPadLastPage  $gLaunchPadCurrentPage 

		globalVariable gLaunchPadCurrentPage 9 - $note10  
		
		// Uncomment if you need more than 7 pages. Page will be accessible with double click!
		//if $sysTime - $lastEventPressed < 300
		//	globalVariable gLaunchPadCurrentPage $gLaunchPadCurrentPage + 7
		//endIf
		
					
		callFunction updatePage $gLaunchPadLastPage $gLaunchPadCurrentPage
						
		
	endIf
	
	globalVariable lastEventPressed $sysTime
		
	//print gLaunchPadCurrentPage: $gLaunchPadCurrentPage
	endScriptDynamic
endIf



variable managePage managePage & $gLaunchPadCurrentPage


callFunction $managePage



function initializePage1 // Transport and various LoopToGo functionalities
	
	globalVariable gInitTransportLed true

	spawnScript scriptTransportLEDScript aScriptTransportLEDScript 1
	globalVariable gScriptTransportLEDScript $scriptTransportLEDScript  // This info will be needed after this script ends

endFunction

function initializePage2  // Volume sliders
	
	//print initializePage2
		
	
	if $nbTracks = 0
		// Display text only once
		callFunction setTextScrolling aDeviceOut false 10 aColorPaletteLightBlue "Volume" // device [in] textIsLooping [in] speed[in] colourSpec [in] text [in]
	endIf
	
	getBankInfo actualBank nbTrackPerBank
	
	variable firstTrackInBank 1 + $actualBank*$nbTrackPerBank - $nbTrackPerBank
		
	
	for track $firstTrackInBank 8*$actualBank 
		variable faderPosition $track - $firstTrackInBank
		variable controlChange $faderPosition + 7
		getTrackPosition trackPosition $track
		//print track $track position $trackPosition
		
		if $track < $nbTracks + 1	 
			variable trackName trackName & $track
					
			getTrackVolumeFader faderValue $$trackName // Volume (from slider) is quadratic since 2.14.0. We get the Fader position from 0 to 127 taking into account the maxScale
										
			callFunction setFader aDeviceOut aNovationVertical $faderPosition aNovationUnipolar $controlChange aColorPaletteLightBlue
			callFunction setFaderPosition aDeviceOut $controlChange $faderValue
			
			//print callFunction setFader aDeviceOut aNovationVertical $faderPosition aNovationUnipolar $controlChange aColorPaletteLightBlue
			//print callFunction setFaderPosition aDeviceOut $controlChange $faderValue
			
		else // No track at this position
			callFunction setFader aDeviceOut aNovationVertical $faderPosition aNovationUnipolar $controlChange aColorPaletteBlack
		endIf
	endFor
	
	callFunction setLaunchPadLayout aDeviceOut2 4  // 0 = Session, 1 = Drums, 2 = Keys, 3 = User, 4 = Faders (only in DAW mode), 5 = programmer Mode
	
	
	
endFunction


function initializePage3  // LED Metronome
	
	spawnScript scriptTempoID aScriptTempoLEDScript 1 // 1 is for continuous run
	globalVariable gScriptTempoID $scriptTempoID	// This info will be needed after this script ends
	
endFunction

function initializePage4  // Jam mode

	if $nbTracks = 0
		// Display text only once
		callFunction setTextScrolling aDeviceOut false 10 aColorPaletteYellow "Jam" // device [in] textIsLooping [in] speed[in] colourSpec [in] text [in]
	endIf

	spawnScript scriptLaunchPadLedsID aScriptJamModeScript 1
	globalVariable gScriptLaunchPadLedsID $scriptLaunchPadLedsID  // This info will be needed after this script ends

	//print Spawning : $scriptLaunchPadLedsID aScriptJamModeScript 1

endFunction

function initializePage5  // LED effects
	
	//print initializePage3
	addMidiMapper midiMapper aDeviceIn 144 11 88 aDeviceIn2 144 11
	
	// Display text only once
	callFunction setTextScrolling aDeviceOut false 10 aColorPalettePurple "Fx Demo" // device [in] textIsLooping [in] speed[in] colourSpec [in] text [in]

	
endFunction


function initializePage6
		
	// Display text repetetivly
	callFunction setTextScrolling aDeviceOut true 12 aColorPaletteOrange "Text scrolling demo" // device [in] textIsLooping [in] speed[in] colourSpec [in] text [in]

endFunction

function initializePage7
	// Print all colors
		
	for row 0 7
		for column 0 7
			variable pad 1 + $column + $row*9
			callFunction setPadColor aDeviceOut $pad $color
						
			variable color $color + 1 

		endFor
	endFor
	
endFunction


function managePage1 // Transport and various LoopToGo functionalities

	//print managePage1

	if $status = 128
		exitFunction
	endIf

	//if $note < 11 
	//	exitFunction
	//endIf

	//if $note > 88 
	//	exitFunction
	//endIf
	

	variable row $note/10 1
	variable column $note - $row*10
	variable pad $row*8 + $column - 8
	
	//print row: $row column: $column pad: $pad
	
	if $pad = 1
		rewindAll
		exitFunction
	endIf
	
	if $pad = 2
		gotoStartTick
		exitFunction
	endIf
	
	if $pad = 3
		stop // stop song 
		exitFunction
	endIf
	
	if $pad = 4	
		togglePlayPause
		exitFunction				
	endIf
	
	if $pad = 5
		toggleRecordPause
		exitFunction
	endIf
	
	if $pad = 7
		shortcutByID 129 // Force Load selected song in playlist
		exitFunction
	endIf
	
	if $pad = 8
		shortcutByID  72 // Select Next Song in playlist
		exitFunction
	endIf
	
	if $pad = 9
		shortcut Home // Beginning of song 
		exitFunction
	endIf
	
	if $pad = 10
		shortcut Left // Previous start or loop end 
		exitFunction
	endIf
	
	if $pad = 11
		shortcut Down // Next track
		exitFunction
	endIf	
	
	if $pad = 12
		shortcut Right // Previous start or loop end 
		exitFunction
	endIf
	
	if $pad = 13
		shortcut End // End of song 
		exitFunction
	endIf
	
	if $pad = 16
		shortcutByID  73 // Select Previous Song in playlist
		exitFunction
	endIf
	
	if $pad = 17
		shortcutByID  2100 // Recall preset A
		exitFunction
	endIf
	
	if $pad = 18
		shortcutByID  2101 // Recall preset A
		exitFunction
	endIf
	

	
	if $pad = 19
		shortcut Up // Previous track
		exitFunction
	endIf
	
	if $pad = 20
		shortcutByID  2102 // Recall preset A
		exitFunction
	endIf
		if $pad = 21
		shortcutByID  2103 // Recall preset A
		exitFunction
	endIf
	
	

	
	if $pad = 23
		shortcut L // Toggle views
		exitFunction
	endIf
	
	
	
	if $pad = 24
		shortcut "Ctrl+H" // Toggle Mixing console
		exitFunction
	endIf
	
	if $pad = 25				// Test
		userShortcut "Alt+H"
		exitFunction
	endIf
	
	
	if $pad = 26
		shortcutByID 128 // Set playhead  from Chord editor cursor position
		exitFunction
	endIf
	
	if $pad = 28
		shortcutByID 134 // Set Chord editor cursor position from Playhead
		exitFunction
	endIf
	
	if $pad = 31
		shortcutByID 116 // Toggle zoom horizontal
		exitFunction
	endIf
	
	if $pad = 32
		shortcut T // Toggle zoom vertical
		exitFunction
	endIf
	
	if $pad = 39
		shortcut "Ctrl+U" // Toggle structure console
		exitFunction
	endIf

	
	if $pad = 40
		shortcut "Ctrl+B" // Toggle Plugin/Chains/Song/Playlist view
		exitFunction
	endIf
	
	
	// Jump section 1 to 8
	variable cond1 $pad > 56
	variable cond2 $pad < 65	
	if $cond1 * $cond2
		shortcutByID 23528 + $pad - 57
		exitFunction
	endIf
	
	
	// Jump section 9 to 16. Note these don't have a direct shortcut
	variable cond1 $pad > 48
	variable cond2 $pad < 57	
	if $cond1 * $cond2
		setUserArgs 9 + $pad - 49	
		shortcutByID 99	// Select section marker specified by user args
		setUserArgs	// Make sure user args is empty!
		exitFunction
	endIf
	
	// Jump section 17 to 24. Note these don't have a direct shortcut
	variable cond1 $pad > 40
	variable cond2 $pad < 49	
	if $cond1 * $cond2
		setUserArgs 17 + $pad - 41	
		shortcutByID 99	// Select section marker specified by user args
		setUserArgs	// Make sure user args is empty!
		exitFunction
	endIf
	
	//print row: $row column: $column pad: $pad

endFunction

function managePage2 // Volume Sliders
	
	// Nothing to do, everything is done by Launchgpad Sliders feature

endFunction

function managePage3 // LED Metronome

	// Nothing to do, everything is done by tempoLedLaunchPad.ltgs
	
endFunction

function managePage4 // Jam mode

	if $status = 128
		exitFunction
	endIf

	if $note < 11 
		exitFunction
	endIf

	if $note > 88 
		exitFunction
	endIf
	
	getBankInfo actualBank nbTrackPerBank
	variable trackOffsetForBank $actualBank*$nbTrackPerBank - $nbTrackPerBank


	variable row $note/10 1
	variable track 9 - $row
	variable pad $note - $row*10

	//print row: $row track : $track pad : $pad

	if $track > $nbTracks
		exitFunction
	endIf

	if $pad = 1 // Select track
		selectTrack $track + $trackOffsetForBank
		exitFunction
	endIf

	if $pad = 2 // Record jam now

		selectTrack $track + $trackOffsetForBank
		
		ifNot $isInJamMode
			shortcut J
		endIf
	
		shortcutByID 17383 + $track
		exitFunction
	endIf

	if $pad = 3 // Overdub jam now

		selectTrack $track + $trackOffsetForBank
	
		ifNot $isInJamMode
			shortcut J
		endIf
		
		shortcutByID 19431 + $track
		exitFunction
	endIf

	if $pad = 4	// Lock now

		selectTrack $track + $trackOffsetForBank
	
		ifNot $isInJamMode
			shortcut J
		endIf
	
		shortcutByID 21479 + $track
		exitFunction
	endIf
	
	if $pad = 5	// Clear loop
		selectTrack $track + $trackOffsetForBank
		shortcutByID 123 // Select record loop crossing song tick
		shortcut E
		exitFunction
	endIf
	
	if $pad = 6	// Toggle mute
		selectTrack $track + $trackOffsetForBank
		shortcut "Ctrl+T"
		exitFunction
	endIf

endFunction

function managePage5 // LED effects
	
	// Nothing to do, everything is done by midiLedEffects.ltgs	
	
	// In fact, it will never be called since there is a event remapping in page 5
		
	
endFunction

function managePage6
	//print Please implement managePage6
endFunction

function managePage7
	//print Please implement managePage7
endFunction


function quitPage1 // Transport page

	//print quitPage1

	killScript aScriptTransportLEDScript

	callFunction clearPads aDeviceOut 
		
endFunction

function quitPage2 // Volume Sliders
		callFunction setLaunchPadLayout aDeviceOut2 0  // 0 = Session, 1 = Drums, 2 = Keys, 3 = User, 4 = Faders (only in DAW mode), 5 = programmer Mode
endFunction

function quitPage3 // Quit Tempo Led

	killScript aScriptTempoLEDScript
	callFunction clearPads aDeviceOut 
	
endFunction

function quitPage4 // Jam mode

	killScript aScriptJamModeScript
		
	callFunction clearPads aDeviceOut 

endFunction

function quitPage5 // LED effects

	deleteAllMidiMappers // To make sure we don't cummulate those created in page 3 or others
	
endFunction

function quitPage6
endFunction

function quitPage7

	for row 0 7
		for column 0 7
			variable pad 1 + $column + $row*9
			callFunction setPadColor aDeviceOut $pad 0					
		endFor
	endFor
	
endFunction

function updatePage // lastPage [in] currentPage [in]

	variable quitPage quitPage & $arg1

	callFunction $quitPage
				
	variable initializePage initializePage & $arg2

	// Make sure there is no text scrolling from other page
	callFunction endTextScrolling aDeviceOut

	callFunction $initializePage
		
endFunction




