A fast way to find the offset of an item in a list. For example, itemOffset("e","a,b,c,d,e,f,g") would return "5"
Handlers: itemOffset (<item>,<list>)
Parameters:
<item>: The item whose offset you are looking for.
<list>: The list in which you are looking.
Note: to find out if the item is in the list, check if itemOffset is greater than 0.....
-- finds the offset of an item in a list.
to get itemOffset itm,lst
step i from 1 to itemcount(lst)
pop lst
if itm = it
return i
end
return 0
enddddddddddddddturn 0
Display 2-D array values
request2Darray
request2Darray x[][]
Zretval
dimensions(x)
x[i][j]
origPage
original
Display 2-D array values
label
Display 2-D array values
Often, when debugging a script using arrays, you may want to display the array at a certain point in your script. This page has a handler for displaying the contents of two-dimensional arrays.
Note that this also displays a standard method for walking through a 2D array.
The button to the right fills an array with the elements of the list in the field.
Once filled, it passes the array to the request2Darray handler (in this page script), which displays the contents of the array..ray.
arrayField
d,4,4/1/06
h,7,4/1/23
j,5,3/1/29
i,1,1/9/55
g,6,7/7/64
e,9,11/13/66
f,0,7/4/76
b,3,5/23/91
c,2,3/11/92
a,8,1/12/933
Display
krequest2DArray
arrayField
buttonClick
buttonClick
Zx[][]
fill x
"arrayField"
] order
request2DArray x
Display
Add number of days to date
Add number of days to date
This handler adds a specified number of days to a provided date. Note that a negative number of days can be supplied to subtract a number of days.
Handler: newDate (<original date>,<days to add>)
Parameters:
<original date>: Base date to which you want to add days
<days to add>: Number of days you want to add to <original date>
Returns the modified date.
-- function: newDate(<original date>,<number of days to add>)
-- Returns a date n days from a given date. Pass it a date
-- for the first parameter, followed by an integer (positive
-- or negative) representing the number of days from that date
-- Example: to find out the date 10 days ago
-- set x to newDate(sysdate,-10)
to get newDate origdate, days
format date origdate as "seconds"
increment origdate by (days*24*60*60)
format date origdate as sysdateformat from "seconds"
return origdate
endddddddddddddddddddddddddddddddddddddddddd
origPage
original
Add number of days to date
label
Controlling volume of clips
label
Controlling volume of clips
Clips have a property called mmVolume, which you can set before or during play of a clip. This example uses a dial widget to control the volume of a clip. The dial widget sends out a dialMove message, which the Play Clip button handles..with a no
Choose a clip, then play it while turning the dial to control the volume.
Play Clip
Play Clip
Clip to play
Clip Chooser
myStartAngle
myendAngle
myTallTicSpacing
scaleDial
tbk_wid_name
dialPos
dialMin
dialMax
startAngle
endAngle
numTics
tallTicSpacing
tbk_wid_props
tbk_wid_values
myNumTics
mydialMin
mydialMax
# lw@
myRotation
struct
structInfo
40433333333333333
605.6666666666667
10099999999999999
950tK
96199999999999999
Display
dialMove
notifybefore dialMove pos
550639676273476528
enterpage
dialMove
dialMove
enddialMove
clip "Asymetrix Logo"
clip "bird1"
clip "bird2"
clip "bird3"
clip "CD Audio"
clip "Chirp"
clip "lion"
clip "No No No"
clip "tiger"
clip "toad"
clip "Asymetrix Logo"
CdresetContents
enterpage
CdresetContents
clips
whatClip
resetContents
notifyBefore
resetContents
notifyAfter
[dropdownitems
clips = resourceList(
<> NULL
whatClip
&CRLF
r"&"E&
dropDownItems
description only
description and example
topicName
description and script
Untitled
enterpage
pageName
templateButtons
label
subtopicname
topicName
chosen
cancel
keychar
cancel
-- initialize dialog box
"Untitled"
"topicName"
B"description
buttonclick
-- sent
user presses OK
pageName
chosen
"templateButtons"
--
the specified
label
"subtopicname"
close
-- handles OK
escape
keyEnter
origPage
original
label
in,false
ThreeDeeRect
bottomLine
topLine
Topic name:
bottomLine
topLine
topicName
Play clip on enter page
templateButtons
chosen
templates
buttonclick
buttonclick
-- store selected
a property
chosen
"templates"
Description and Script
chosen
Description and Script
Description and &Script
Description Only
Description &Only
Description and Example
Description and &Example
Choose Template
templates
Description and script
This is a description. Blah, blah, blah. Boy could I use another cup of Joe. Nothing is worse than work coffee.
to handle buttonup
do this
do that
description only
description and script
This is a description. Blah, blah, blah. Boy could I use another cup of Joe. Nothing is worse than work coffee. I've had so many cups of it already that I can see through time. Maybe some decaf is in orderrican butt.
Description and example
This is a description. Blah, blah, blah. Boy could I use another cup of Joe. Nothing is worse than work coffee. I've had so many cups of it already that I can see through time. Maybe some decaf is in order
to handle buttonup
do this
do that
buttonclick
buttonclick
cancel
buttonclick
buttonclick
Cancel
description and script
Get number of days in month
Get number of days in month
This handler returns the number of days there are in a month of a given year. Note that this handler requires the isLeapYear() handler, supplied below.
Handler: daysInMonth (<month>,<year>)
Parameters:
<month>: An integer representing the month
<year>: A four-digit year
Returns the number of days in the supplied month for that year.
-- NOTE: this function requires 4 digits for the year.
-- This function calls the function leapYear() defined below.
-- example: to find out how many days are in February, 1992
-- set x to daysInMonth(2,1992)
to get daysInMonth m,y
if m <> 2
return item m of "31,28,31,30,31,30,31,31,30,31,30,31"
else
if leapYear(y)
return 29
else
return 28
end
-- Returns TRUE if y is a leap year, FALSE if not.
-- NOTE: this fuction requires a four digit year.
-- Example: Find out if 1992 is a leap year.
-- if leapYear(1992)
to get isLeapYear y
if ((y mod 4 = 0 and y mod 100 <> 0) or (y mod 400 = 0))
return TRUE
else
return FALSE
origPage
original
Get number of days in month
label
Create Full-Text Search Index
label
Create Full-Text Search Indexndex
Creates an index of the current book for full-text searches. The index will use the default settings file (found in the Multimedia ToolBook directory).
The index will be created in the same directory and have the same name as the the current book.
Example of use:
send buildIndexxxxxxxxxxxxxx
-- this handler builds a basic full-text search index of the current book.
to handle buildIndex
-- display an hourglass cursor... this can take a while.
sysCursor = 4
-- link the dlls required to build an index
linkDll "fts30mtb.dll"
STRING ftsRemoveIndex ( STRING )
DWORD ftsInitIndex ( STRING, STRING, WORD )
LONG ftsAddContext ( DWORD, STRING )
STRING ftsAddPage ( DWORD, STRING, STRING, STRING, LONG )
-- step through the list of fields and recordFields on this background
-- and add their text to the default section of the index
step j from 1 to itemCount(bgObs)
curObj = item j of bgObs
if object of curObj = "recordField"
-- to get the text of a recordField we have to refer to a page rather than the background
-- words 1 to 4 of a recordField reference are: "recordField id X of"
curObj = words 1 to 4 of curObj && pageRef
end
textExp = "richText of"&&curObj
get ftsAddTextToSection(indexHandle,textExp,"")
end
-- get a list of fields on this page and add their text to the default section of the index
pgObs = getObjectList(pageRef,"field",FALSE)
step j from 1 to itemcount(pgObs)
curObj = item j of pgObs
textExp = "richText of"&&curObj
get ftsAddTextToSection(indexHandle,textExp,"")
end
-- add the text placed into sections to the index
get ftsAddSectionsToPage(indexHandle)
--build the index
get ftsBuildIndex(indexHandle)
if it = NULL
request "Failed to build index."
else
request "Index successfully built."
send cleanExit
end buildIndex
-- this process will exit the build process cleanly
-- (removing the DLLs, etc.)
to handle cleanExit
sysCursor = 1
unlinkDLL "fts30mtb.dll"
break to system
end cleanExit
{{{{{{{p{
Perform Full-Text Search
label
Perform Full-Text Search
-- this handler performs a basic search procedure on a full-text search index
to get searchIndex queryString
system lastQuery
system DWORD numHits, currentHit
local pageRef
if queryString <> NULL
sysCursor = 4
-- link the functions required for the search
linkDll "fts30mtb.dll"
DWORD ftsOpenIndex ( STRING )
STRING ftsCloseIndex ( DWORD )
DWORD ftsQuery ( DWORD, STRING, DWORD )
STRING ftsMatchRef ( DWORD, DWORD, DWORD )
end
-- identify the index to search
indexName = name of this book
while "." is in indexName
clear last char of indexName
end
-- open the index
indexHandle = ftsOpenIndex(indexName)
if indexHandle = 0
request "Could not open index"
send cleanExit
return NULL
end
--make the query
numHits = ftsQuery(indexHandle,queryString,0)
if numHits > 0
-- there was at least one hit
if queryString = lastQuery
-- the user is searching for the same string as the last search
increment currentHit
if currentHit > numHits
currentHit = 1
end
else
currentHit = 1
lastQuery = queryString
end
-- get the page reference of the currentHit
pageRef = ftsMatchRef(indexHandle,currentHit,0)
end
-- close the index
get ftsCloseIndex(indexHandle)
send cleanExit
return pageRef
-- this handler exits the search process cleanly
-- (unlinking DLLs etc.)
to handle cleanExit
sysCursor = 1
unlinkDLL "fts30mtb.dll"
enddddd
get ftsCloseIndex(indexHandle)
send cleanExit
return pageRef
-- this handler exits the search process cleanly
-- (unlinking DLLs etc.)
to handle cleanExit
sysCursor = 1
unlinkDLL "fts30mtb.dll"
This handler performs a search using an existing full-text search index. The index is assumed to be in the same directory and have the same name as the current book.
This handler takes one parameter - the text for which to search - and returns a page reference for the first page on which that text appears. Searching with the same string again will return subsequent pages on which the text appears.
Example of use:
to handle buttonClick
system lastQuery
ask "Search For:" with lastQuery
queryString = it
pageRef = searchIndex(queryString)
if isObject(pageRef)
go to pageRef
else
request queryString&&"not found."
Playing MIDI Directly
label
Playing MIDI Directly
The button below plays MIDI sounds by making calls directly to the Windows Multimedia System DLL (mmsystem.dll)
Click and hold Play MIDI to play a MIDI sound.
Changing the Note field changes the note of the sound to be played.
Changing the Program field changes how the Note is played...
playMidi
Play MIDI
integerUp
,!J'"
program
spinUp
w%spinUp
buttonDown
w%spinUp
buttonDoubleClick
w%spinUp
buttonStillDown
spinUp
"program" < 39
integerDown
program
spinDown
|spinDown
buttonDown
|spinDown
buttonDoubleClick
|spinDown
buttonStillDown
spinDown
"program" > 0
program
integerUp
spinUp
w%spinUp
buttonDown
w%spinUp
buttonDoubleClick
w%spinUp
buttonStillDown
spinUp
"note" < 127
integerDown
spinDown
|spinDown
buttonDown
|spinDown
buttonDoubleClick
|spinDown
buttonStillDown
spinDown
"note" > 40
Program:
Note:am:
enterPage
reader
leavePage
author
Show all objects of page
label
Show all objects of page
The script below displays all objects on the current page regardless of whether they are in groups.
to handle showAll
show getObjectList(this page,null,false)
Disabling task switching
label
Disabling task switching#
The script below allows you to turn on or off task-switching. When task-switching is on the user may not change tasks by using Alt+Tab, Alt+Shift+Tab, or Ctrl+Esc. They may still activate other windows by clicking on them.
To turn off task-switching:
set taskSwitching() to FALSE
To turn task-switching back on:
set taskSwitching() to TRUE
to set taskSwitching to LOGICAL mode
if mode
untranslateWindowMessage 0x0112 for sysWindowHandle
else
translateWindowMessage for sysWindowHandle
on 0x0112 send WM_SYSCOMMAND
end
to handle WM_SYSCOMMAND hWnd, wMsg, wp, lpLo, lpHi
if wp <> 0xF050 and wp <> 0xF040 and wp <> 0xF130
--SC_PREVWINDOW, SC_NEXTWINDOW, and SC_TASKLIST
forward to system
Icon Resources
Save Text to a File (ASCII or RT
Search and replace in a string
Remove given char from string
Remove given char from stringg
This handler removes all instances of the specified character from the specified string.
Handler: stripChar(<character to strip>,<string to strip it from>)
Parameters:
<character to strip>: any single character
<string to strip it from>: the string from which to strip the character
Returns the stripped string...
-- removes all instances of chr from strng
to get stripChar chr,strng
set chrLoc to offset(chr,strng)
while chrLoc > 0
clear char chrLoc of strng
set chrLoc to offset(chr,strng)
return strng
stripChar
stripChar chr,strng
chrLoc
origPage
original
Remove given char from string
label
Play clip on enter page
label
Play clip on enter page
-- notifies for showing and closing clips
notifyAfter enterPage
-- these scripts could go in any object
-- on the page or background
-- clipRef of this page would
-- already have the necessary reference
clipRef = clipRef of this page
if clipRef <> NULL
mmOpen clipRef wait
-- use this if the media is on a cd-rom
-- mmCue clipRef wait
-- show the first frame
mmPlay clipRef in stage "myStage" of this background
end enterPage
notifyBefore leavePage
clipRef = clipRef of this page
if (clipRef <> null) and (mmIsOpen of clipRef)
mmClose clipRef
end if
end leavePage
These scripts play a clip upon entering a page and close it upon leaving the page. You could paste these scripts into any object. The clip to be played is identified by a user-property of the page and the clip is played in a stage object of the background.
Chirp
CD Audio
bird1
bird2
bird3
tiger
No No No
Asymetrix Logo
chirp.wav
animals.wav
animals.wav
animals.wav
animals.wav
animals.wav
animals.wav
animals.wav
asym01.avi
bitamp
sequencer
overlay
animation
digitalVideo
cdAudio
photoCD
videoDisk
waveAudio
Bring up the Command Window
Bring up the Command Window
This one line script brings up the Command Window without using the Command menu item or the Shift + F3 key. Often you will want to remove menu items that you aren't using at Author level, but you still need the Command window while working.
origPage
to handle buttonClick
show commandWindow
end buttonClick
original
Bring up the Command Window
label
Bring up the Command Window
Get day of week from date
Spin controls
origPage
original
Spin controls
label
Spin controls
Below are some standard spin controls for selecting an integer, date, or time. To use the date and time spinners, click on the segment of the date or time (e.g., month, minute) that you want to increment or decrement.
Try out the spinners on the right.
To use the date and time spinners, first click on the segment of the date or time (e.g., month, minute) that you want to increment or decrement.
integerUp
integer
spinUp
w%spinUp
buttonDown
w%spinUp
buttonDoubleClick
w%spinUp
buttonStillDown
spinUp
"integer"
integerDown
integer
spinDown
|spinDown
buttonDown
|spinDown
buttonDoubleClick
|spinDown
buttonStillDown
spinDown
"integer"
integer
dateButtons
decrement
dateUp
increment
month
month
actionItem
buttonDown
buttondoubleclick
buttonStillDown
"dateUp"
actionItem
selectedHotwords
"day"
"month"
"year"
dateUp
dateDown
increment
evaluate(day)
03 / 13 / 944
month
timeButtons
decrement
timeUp
;seconds
increment
seconds
minute
minute
actionItem
buttonDown
buttondoubleclick
buttonStillDown
"timeUp"
actionItem
selectedHotwords
"hour"
"Time"
"minute"
"AMPM"
timeUp
timeDown
increment
evaluate(day)
08 : 42 : 45 PMM
minute
seconds
Limit Length of Entry String
origPage
original
Limit Length of Entry String
label
Limit Length of Entry Stringr
This handler is to be installed into the script of a field. When a key is pressed, it checks that the charCount of the text of the field is within the limits specified in the script.
This is a handler for a built-in ToolBook message that is sent to a field each time the user presses a key. Along with the keyChar message, Toolbook passes a parameter containing the unique code for the key pressed.
Handler: keyChar keyPressedsseddddameters are:
keyPressed the key pressed by the user
-- does not allow entry of more than specified
-- amount of characters. Place this hander in a field.
to handle keyChar keyPressed
local INT maxCharAllowed
local INT currentCount
maxCharAllowed = 10
currentCount = charCount(my text)
if (currentCount >= maxCharAllowed) \
or (keyPressed = keyEnter and currentCount >= \
maxCharAllowed - 1)
beep 1
else
forward
Limit Length of Entry String
Cursor Resources
Add number of days to date
Check for Alpha Non-Numeric Data
origPage
original
Check for Alpha Non-Numeric Data
label
Check for Alpha Non-Numeric Data
This function checks each character to ensure that it is a letter from in the range of A-Z or a-z. To allow additional values or characters, you will need to add them to the string held in the variable "alphabet."
Handler: isStringAlpha (<testString>)
Parameters:
<testString>
Returns true if the string contains only alpha characters or null.
pha characters or null.
true testString contained only alpha characters (A-Z or a-z) or NULL
false testString contained at least one non-alpha character
-- tests each character of testString, returns TRUE
-- if all are alpha (non-numeric)
to get isStringAlpha testString
alphabet = "abcdefghijklmnopqrstuvwxyz"
step i from 1 to charcount(testString)
if char i of testString is not in alphabet
return FALSE
end
return TRUE
Bring ToolBook Window to Front
Bring ToolBook Window to Front
This script uses DDE to get the sysWindowHandle of another instance of ToolBook. It then calls Windows to bring that window to the front of the desktop. If that application is not running, it runs it.
Handler: bringWindowToFront <application>
Parameters:
<application>: the name of theToolBook file
to handle bringWindowToFront appNameToRun
linkDLL "user"
--bringWindowToTop is a Windows function that
--puts the Window whose window handle is passed to it
This function will run Excel if it is not running already. If a filename is passed to this function it will tell Excel to load that file if it is not loaded already.
Handler: InitializeExcel (<fileName>)
Parameters:
<filename> optional; makes sure the file is open in Excel
Returns true if it successfully established conversation with Excel
false couldn't load Excel or, if provided, the file name given
SysError values are those of the command executeRemote (see the OpenScript Encyclopedia).
OK Conversation was succesfully established
Failed:No Server Excel is not running with the expected file
Failed: xxxxx Excel is running, but something is wrong
-- only puts page on syshistory if navigation is *not* initiated by BACK
if targetWindow is mainWindow
if s_backMessageSent is false
push this page onto syshistory
else
s_backMessageSent = false
end
forward
to handle back
system s_backMessageSent
if itemcount(syshistory) > 0
s_backMessageSent = true
pop syshistory
in mainwindow
go to it
end
else
request "You are already all the way back."
Changing the behavior of BACK
Changing the behavior of BACK
These handlers, when placed in the book script of a ToolBook application, will make the BACK message behave like back behaves in WinHelp.
Note: be sure you forward any leavePage handlers located in a page or background script.
Handlers:
EnterApplication
LeavePage
Spin controls
Graphic slider control
Check for Valid File Name
Search Path for File
Verbose
Sorting a 1-D array
label
Sorting a 1-D array
-- The next three handlers make up a Standard recursive
-- QuickSort.
to handle quicksort fArray[] by reference
system s_noSwap
set s_noSwap to 0
send quicksrt fArray, 1, dimensions ( fArray )
to handle quicksrt fArray[] by reference, lo, hi
system s_noSwap
if hi > lo
send swap fArray, lo, ((lo+hi) div 2)
set lst to lo
step i from (lo+1) to hi
if fArray[i] < fArray[lo] as text
increment lst
send swap fArray, lst, i
else
increment s_noswap
end
end
send swap fArray,lo,lst
send quicksrt fArray, lo, lst-1
send quicksrt fArray, lst+1,hi
end
to handle swap fArray[] by reference, x, y
local temp
set temp to fArray[x]
set fArray[x] to fArray[y]
set fArray[y] to temp
end fArray[x]
set fArray[x] to fArray[y]
set fArray[y] to temp
This is an OpenScript implementation of the standard recursive quick sort.
Handler: quickSort <arrayRef>
Parameter:
<arrayRef>: A one-dimensional array.
Example:
local fArray[]
fill fArray with my text in [textline] order
send quickSort fArray
Search Path for File
origPage
Search Path for File
This script links to the function getDosEnvironmentString in TB30DOS.DLL to get the DOS path and then determines if the file is in that path.
Handler: fileInPath (<fileName>)
Parameters:
<fileName> file name to search for
Returns null if file is not found, or the first directory in the path that contains the file if found.
NULL file not found
currentPath the first directory in the path that contains the file
Null parameter no file name was passed to function
name was passed to function
to get FileInPath fileNameToCheck
--If fileNameToCheck is null then fail immediately
if fileNameToCheck is NULL then
return null
end if
--Link to the tb30dos dll
linkDLL "tb30dos.dll"
INT fileExists (STRING)
STRING getDOSEnvironmentString (STRING)
end linkDLL
--Get the path list
set currentPathList to getDOSEnvironmentString ("PATH")
--Clear the 'Path=' at the beginning of the path list
get offset("=",currentPathList)
if it > 0 then
clear chars 1 to it of currentPathList
end if
--Convert the path list to a list of items
get offset(";",currentPathList)
while it > 0
set char it of currentPathList to ","
get offset(";",currentPathList)
end while
--Search through the list, one path at a time
while currentPathList is not NULL
pop currentPathList into checkPath
if last char of checkPath is not "\"
put "\" after checkPath
end if
if fileExists(checkPath & fileNameToCheck) = 1
return checkPath
end if
end while
--Unable to find file in the path
return null
original
Search Path for File
label
Get Current Path Setting
origPage
original
Get Current Path Setting<
This script links to the function getDosEnvironmentString in TB30DOS.DLL to get the current DOS path setting. This handler returns the path currently specified in your DOS environment.
Handler: findCurrentPath
No parameters.
RRath setting
to get findCurrentPath
--Link to the tb30dos dll
linkDLL "tb30dos.dll"
STRING getDOSEnvironmentString (STRING)
end linkDLL
--Get the path list
set currentPathSetting to getDOSEnvironmentString ("PATH")
return currentPathSetting
end findCurrentPath
Get Current Path Setting
label
Get Current Path Setting
Remove given char from string
Convert textlines to list
Insert/Overwrite field
origPage
Insert/Overwrite fieldA
This field toggles between insert and overwrite mode when you press the insert key. All handlers are in the field.ndlers are in the field.
Type in the field to the right.
Pressing the insert key toggles between insert and overwrite modes.
overWriteFlag
false
keyDown
overWriteFlag
keyChar
overWriteFlag
enterpage
4logical overWriteFlag
Y <>
notifybefore
notifyafter
Now is the time for all good men to come to the aid of their country..............................................wwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
terpage
enterpage
original
Insert/Overwrite field
label
Auto-scroll field
Converting to Binary, Hex, Octal
intro
<Introduction>
Dragging Objects
label
Dragging Objects
to handle buttondown loc
local stack bnds,mouseOffset
linkdll "user"
int getsystemmetrics(int)
-- check if the user has swapped mouse buttons.
if getsystemmetrics(23) >0
set leftMouseButton to keyRightButton
else
set leftMouseButton to keyLeftButton
set bnds to bounds of target
set mouseOffset to item 1 of loc - item 1 of bnds,\
item 2 of loc - item 2 of bnds
leftMouseButton=keyLeftButton
while keystate(leftMouseButton)is down
newloc = sysMousePosition
if newLoc <> loc
set position of target to \
item 1 of newLoc-item 1 of mouseOffset,\
item 2 of newLoc-item 2 of mouseOffset
set loc to newLoc
end
Put the script below in an object that you want to drag with the mouse. Note: if you want to drag a group, change the references from arget
Display 2-D array values
Testola
description only
subtopicname
in,ms
ThreeDeeRect
bottomLine
topLine
explanation
Converting to Binary, Hex, Octal
Converting to Binary, Hex, Octal
The Format command has been extended to allow conversion between Binary, Hex, and Octal number systems. The following are the new format strings
Binary: "@b"
Octal: "@o"
Hex: "@h"
Decimal: "@d"
These strings precede the normal number format string. So to convert a variable "n" from decimal to hexidecimal, you could use the following command:
format number n as "@h0"
To convert it back to decimal, you'd do this:
format number n as "@d0"
n convertTo is "Hexidecimal"
format number numberEntered as "@h#"
else
format number numberEntered as "@o#"
end conditions
return numberEntered
end doConversion
origPage
original
Converting to Binary, Hex, Octal
label
Binary Insertion of Textline
origPage
original
Binary Insertion of Textline
label
Binary Insertion of Textline into Field
Inserts a textline into a string delimited by CRLFs, maintaining sorted order.
Handler: InsertLine (<txt>,<newLine>)
Parameters:
<txt> Text, sorted by textLine
<newLine> The new line to insert.
Example of use:
text of field "f" = insertLine(text of field "f",newLine)
-- use if inserting a single line. Will maintain sorted order
to get insertLine txt,newLine
if txt is null
return newLine
set start to 1 -- first textline
set tlc to textlinecount(txt)
set ending to tlc -- last textline
local insertSpot
while start <= ending
set midPoint to (start+ending) div 2
set middleLine to textline midPoint of txt
conditions
when newLine < middleLine as text
-- start looking at values less than current midPoint
set ending to midPoint-1
set insertSpot to midPoint
when newLine > middleLine as text
-- start looking at values greater than current midPoint
set start to midPoint+1
set insertSpot to midPoint+1
else
-- the item already exists
set insertSpot to midPoint
break while
end
if insertSpot > tlc
put newLine before textline insertSpot of txt
else
put newLine&crlf before textline insertSpot of txt
return txt
label
Making mmSource-paths book relative
If you've saved your clips with fully qualified paths to their source files, you will probably want to change them so that they are relative to the location of the book so that the clips can be easily found using the HDMediaPath or CDMediaPath when installed on another machine. This routine runs through your resources and makes them relative to the book path. For example:
The following functions are useful for dealing with windows functions that require or return a RECT structure.
setRect <vertices>,<pRect>
This sets the values of the RECT structure in pRect. Useful if you must pass a filled RECT structure to a Windows function.
Parameters:
<vertices>: The vertices of the rectangle.
<pRect>: The pointer to the RECT structure. (8 bytes)
getRect <pRect>
This extracts the vertices from a filled RECT structure.
Parameter: <pRect>: The pointer to a RECT structure. (8 bytes)
getWinPointer ( <nsize> )
Use this to get a locked pointer.
Parameter: <nsize>: the size in bytes to allocate
Return value: Returns a reference to a locked pointer that you can pass
to a windows function requiring a pointer.
freeWinPointer (<pointer Variable>)
Frees a locked pointer, recovering memory.
Parameter: <pointer variable>: the variable returned from
getWinPointer()
Return value: Returns 0 if successful, a positive integer if not.
linkMemFunctions
Links the functions necessary for the above handlers.
Parameters: None.....Functions
Links the functions necessary for the above handlers.
Parameters: None...e.y for the above handlers.
Parameters: None.
-- lst is a list of 4 integers
-- pRect is a locked pointer to 8 bytes
to handle setRect lst,pRect
step i from 0 to 6 by 2
pop lst
get pointerInt(i,pRect,it)
-- pRect is a locked pointer to 8 bytes
to get getRect pRect
local retval
step i from 6 to 0 by -2
push pointerInt(i,pRect) onto retval
return retval
-- the link statements for needed functions below
to handle linkMemFunctions
linkDLL "KERNEL"
WORD GlobalAlloc(WORD,DWORD)
WORD GlobalFree(WORD)
WORD GlobalHandle(WORD)
POINTER GlobalLock(WORD)
WORD GlobalUnlock(WORD)
to get getWinPointer nSize
local word hMem
local retValue
hMem = GlobalAlloc(66,nSize)
return GlobalLock(hMem)
to get freeWinPointer pMem
local word hMem, retValue
hMem = GlobalHandle(item 1 of pMem)
retValue = GlobalUnlock(hMem)
return GlobalFree(hMem)
enddddddddddddddddddd
return GlobalFree(hMem)
Sorting a 2-D array
origPage
original
Sorting a 2-D array
label
Sorting a 2-D array
Think of a 2-D array as a table in which the first dimension refers to rows and the second dimension refers to columns. This function sorts the "rows" of a two dimensional array by the values of one of its columns.
You pass it the array you want to sort, the column you want to sort by, and the "datatype" of the column you want to sort. (Either "text", "date", or "number")/
Click on the radio buttons to the right to sort the table by the associated column.
Note: the "table" to the right is a tab-delimited field with two vertical lines drawn over it. The handlers in the buttons load this text into a 2D array and pass it to a handler in this page, specifying the column and type for the sort. rt.
stwoDquickSort
sortField
buttonclick
buttonclick
Zretval
Zx[][]
fref
"sortField"
fill x
g] order
calls the sorting routine. Note
column
'array
specified,
be sorted
twoDquickSort x,1,"
part loads
dimensions(x)
x[i][j]
Number
stwoDquickSort
number
sortField
buttonclick
buttonclick
Zretval
Zx[][]
fref
"sortField"
fill x
g] order
twoDquickSort x,2,"
dimensions(x)
x[i][j]
Number
stwoDquickSort
sortField
buttonclick
buttonclick
Zretval
Zx[][]
fref
"sortField"
fill x
g] order
twoDquickSort x,3,"
dimensions(x)
x[i][j]
Sort by:
sortField
a 3 5/23/91
b 2 3/11/92
c 4 4/1/06
d 9 11/13/66
e 0 7/4/76
f 6 7/7/64
g 7 4/1/23
h 1 2/9/55
i 5 3/1/29
a 8 1/12/93
Using a RECT structure
isLeapYear()
Get number of days in month
Get path of current book
label
Get path of current book
to get myPath
get name of this book
step i from charcount(it) to 1 by -1
if char i of it is "\"
return chars 1 to i of it
end
return null -- happens only when the book is untitled
This function returns the path of the current book.
Example of calling this function in a book called c:\books\test.tbk:
get myPath(this book)
Returns "c:\books\""
resize
Get Free Disk Space on a Drive
origPage
original
Get Free Disk Space on a DriveB
This script links to the function called getFreeDiskSpace in the tb30dos.dll to get the amount of disk space currently available on a particular drive.
Handler: findDiskSpace (<drive>)
Parameters:
<drive> the name of the drive to check
Returns the amount of space available on a particular drive..ror
ve an error
to get findDiskSpace whatDrive
local LONG diskSpaceAvailable
--Link to the tb30dos dll
linkDLL "tb30dos.dll"
LONG getFreeDiskSpace(STRING)
end linkDLL
set diskSpaceAvailable to getFreeDiskSpace(whatDrive)
return diskSpaceAvailable
Get Free Disk Space on a Drive
label
Get Free Disk Space on a Drive
Exit and restart windows
Insert/Overwrite field
Recording wave files from CD
label
Recording wave files from CDq
You can record clips from a CD to wave files using the utility below. Copy the object to a book with some clips, and then specify the channels, sample rate, bits per sample, and file name.
This group of objects will record an existing CDAudio clip to a wave file on the disk.
NOTE: must have your CD Player connected to your sound board for this to function to work.
Clip Chooser
D:\HOOKWORK\CLIPS.TBK
lookBook
Channels
Stereo 2
Mono 1
Stereo 2
sample rate
22 kHz 22050
11 kHz 11025
22 kHz 22050
44 kHz 44100
bits/sample
16z 11025
22 kHz 22050
44 kHz 44100
Record Wavefile
Record Wavefile
CDAudio Clip to Record
Channels
Sample Rate
Bits/Sample
clip "CD Audio"
clip "CD Audio"
CdresetContents
enterpage
CdresetContents
clips
whatClip
CDAudio
resetContents
notifyBefore
resetContents
notifyAfter
[dropdownitems
clips = resourceList(
<> NULL
whatClip
mmSource
= "CDAudio"
6&CRLF
"&"E&
dropDownItems
enterpage
Convert textlines to list
origPage
original
Convert textlines to list
label
Convert textlines to list
This handler converts a string delimited by CRLFs to a list.
Handler: textLinesToList (<textLines>)
Parameters:
<textLines> a string delimited by CRLFs
Returns a list, each item representing a textline.................
-- converts string delimited by CRLFs to a list
to get textLinesToList txt
local stack lst
step i from textlinecount(txt) to 1 by - 1
push textline i of txt onto lst
return lst
Exit and restart windows
Exit and restart windows
label
--When restart is true, Windows will exit and restart.
--If if restart is null or false, Windows will just exit.
to handle exitWindows restart
linkDLL "user"
INT ExitWindows (DWORD, INT)
end linkDLL
if restart is true
get ExitWindows (66, 0)
else
get ExitWindows (67, 0)
end
end
dows (66, 0)
else
get ExitWindows (67, 0)
end
end
end
end buttonUp
nd buttonUp
nd buttonUp
Calling this handler will cause Windows to exit. You can optionally specify that Windows restarts after exiting.
Handler: exitWindows <restart>
Parameters:
<restart> True if you want to restart Windows
n Windows will just Exit.
origPage
original
Exit and restart windows
Get day of week from date
Get day of week from date
label
-- returns the weekday of any day beyond 1/1/1700:
-- note: requires full year. Example: get weekDay("1/1/1993")
-- also requires isLeapYear() function below
to get dayOfWeek pdate
-- make a list out of the date
format date pdate as "m,d,y" from "m/d/y"
set m to item 1 of pdate
set d to item 2 of pdate
set y to item 3 of pdate
-- the following list (1 item for each month) contains the
-- number of days that have passed before first day of
-- each month.
set days to "0,31,59,90,120,151,181,212,243,273,304,334"
-- set numdays to number of days elapsed since 1/1/1700
set numdays to (y-1700) div 4-(y-1700) div 100 +(y-1600) \
div 400 + 365 * (y - 1700) + item m of days + d -1
-- Returns TRUE if y is a leap year, FALSE if not.
-- NOTE: this fuction requires a four digit year.
-- Example: Find out if 1992 is a leap year.
-- if leapYear(1992)
to get isLeapYear y
if ((y mod 4 = 0 and y mod 100 <> 0) or (y mod 400 = 0))
return TRUE
else
return FALSE
urn TRUE
else
return FALSE
This handler returns the day of the week (Monday, Tuesday, etc) from any given date since 1/1/1700. Note that you must provide a four-digit year.
Note that this function requires the handler isLeapYear, included below.
Handler: dayOfWeek(<date>)
Parameters:
<date> A date in this format: "1/1/1994"
(Note a four-digit year is required.)
year is required.)
origPage
original
Get day of week from date
isLeapYear()
isLeapYear()
label
This function returns true if a given date is a leap year, false if not. Note that it requires a four digit year.
Handler: isLeapYear (<year>)
Parameters:
<year>: a four-digit number representing a year
-- Returns TRUE if y is a leap year, FALSE if not.
-- NOTE: this fuction requires a four digit year.
-- Example: Find out if 1992 is a leap year.
-- if leapYear(1992)
to get isLeapYear y
if ((y mod 4 = 0 and y mod 100 <> 0) or (y mod 400 = 0))
return TRUE
else
return FALSE
origPage
original
isLeapYear()
BitwiseAND, OR, and XOR
Notify Handler
Sorting a 2-D array
intro
SubtopicName
Simple Drop Down Field
Remove trailing spaces
<Introduction>
origPage
10,14
selectChars
original
<Introduction>
label
Introduction
This book is a library of scripts useful in OpenScript programming.
To go to a given topic, click a topic in the list.
To view topics related to a given category, choose the desired category.
Use the search button to search for a topic by key word.
Use the splitter bar to resize the navigation panel to the left.
Note: you can add new topics to this book by pressing F3 (to enter author mode) and using the topic buttons that appear at the lower left...tons that appear at the lower left.
Yes, this is a button.
buttonclick
buttonclick
"Yes,
Yes, this is a button.
buttonclick
buttonclick
"Yes,
h%|%~
out,true
ThreeDeeRect
bottomLine
topLine
OpenScript
Libraryy Base
<About this book>
Binary Insertion of Textline
scriptChooserDialog
ButtonStillDown Page Navigation
ButtonStillDown Page Navigation
These simple scripts implement multiple page navigation when the mouse button is held down.
Handlers:
buttonDown
buttonStillDown
No parameters
none
ering actions (ie - called XXbuttonDown rather than buttonDown)
Handlers in this script are:
buttonDown
Parameters are:
none
to handle buttonDown
go to next page
end buttonDown
to handle buttonStillDown
send buttondown
end buttonStillDown
tonDown
to handle XXbuttonStillDown
send buttondown
end XXbuttonStillDown
origPage
original
ButtonStillDown Page Navigation
label
Play clip in a loop
label
Play clip in a loop
If you want to have a wave or midi file constantly repeat in the background, use the scripts below.pts
Pressing the Play Clip button will play the specified clip continuously.uously.
Clip Chooser
CdresetContents
enterpage
CdresetContents
clips
whatClip
resetContents
Stop Clip
play clips
closed
jwhatClip
Play Clip
selectChange
notifyBefore
resetContents
notifyAfter
[dropdownitems
clips = resourceList(
<> NULL
whatClip
&CRLF
r"&"E&
dropDownItems
selectChange
B"play
" = "Stop
mmStatus
") <> "closed"
mmClose (
" = "Play
D:\HOOKWORK\CLIPS.TBK
lookBook
clip "bird1"rix Logo"
clip "Asymetrix Logo"
clip "bird1"
clip "bird2"
clip "bird3"
clip "CD Audio"
clip "Chirp"
clip "lion"
clip "No No No"
clip "tiger"
clip "toad"
Play Clips
clip "bird2"
whatClip
Play Clip
Clip to play continuously
enterpage
leavePage
Navigation
Check for State Abbreviation
Auto-scroll field
origPage
original
Auto-scroll field
label
Auto-scroll field
This field's scrollbar automatically appears when necessary.
Type in the field to the right.
When appropriate, scroll bars will automatically appear.
zashowOrHideScrollbar
enterPage
zashowOrHideScrollbar
leaveField
zashowOrHideScrollbar
keyUp
zashowOrHideScrollbar
paste
zashowOrHideScrollbar
zashowOrHideScrollbar
clear
showOrHideScrollbar
notifyBefore
showOrHideScrollbar
notifyAfter
Something for something, nothing for nothing.788sdf
enterPage
leaveField
keyUp
paste
clear
description and example
SubtopicName
in,ms
ThreeDeeRect
bottomLine
topLine
explanation
.&, "
scrolling
rectangle
explanation
enterpage
notifyBefore
fref
"explanation"
txtOver
8= 0
Example:
in,sculpted
ThreeDeeRect
bottomLine
topLine
View Scripts
author
reader
author
rectangle
enterpage
notifybefore
author
reader
author
dotted
enterpage
notifybefore
buttonclick
buttonclick
Copy objects
author
reader
enterpage
Search and replace in a string
As Word
label
This page contains a function that searches text for all occurrences of one string and replaces them with another. You can specify that you only want to replace the searched string if it's a whole word.
set curTxt to chars runningTotal to totalChars of txt
curOffset = offset(searchFor,curTxt)
if curOffset = 0
break while
else
startPos = (runningTotal+curOffset-1)
endPos = (runningTotal+curOffset+searchLen-2)
if asWord is true
-- test if this occurance is an isolated word:
if not ((startPos = 1 or char (startPos - 1) \
of txt is in wordDelimit) and\
(endPos = totalChars or char endPos + 1 \
of txt is in wordDelimit))
increment runningTotal by curOffset+searchLen-1
continue while
end
end
set chars startPos to endPos of txt to replaceWith
increment runningTotal by curOffset+replaceLen-1
increment totalChars by replaceLen - searchLen
end
return txt
replaceLen - searchLen
end
return txt
Search and replace in a string
The quick red fox jumped over the lumpy log. The fox, being inquisitive by nature and not really in any hurry, stopped to examine the underside of the log in an olfactory sort of way. "Those blasted dogs," he thought to himself. "Who do they think they are?" Seconds later he was ripped to shreds.hreds.
asWord
Search Textng
Replace Textng
Search and Replace
searchReplace
searchString
replaceString
asWord
searchReplace
searchString
/searchReplace
replaceString
buttonup
"searchReplace"
searchString
replaceString
asWord
rabbit
Try searching and replacing various words in the paragraph to the right.
Note: when the As Word button is checked, only strings that exist as whole words in the text will be substituted..............
searchAndReplace
origPage
original
Search and replace in a string
Playing random sounds
label
Playing random sounds
Here is an example of playing clips at random. This could be used if you wanted to create ambient background noises.
This button will randomly play the selected clips in the background.
Play Clips
FALSE
isPlaying
delay
1,2,3,4,5,6
clipList
clip "tiger"
whatClip
Play Clips
Select clips to play randomly
Clip Chooser
CdresetContents
enterpage
CdresetContents
.&+ +E
clips
whatClip
default
resetContents
notifyBefore
resetContents
notifyAfter
e= TRUE
clips = resourceList(
<> NULL
whatClip
SPACE&
i"&"E&
graphic
= bitmap (mmMediaType
CRLF
e= FALSE
= default
clip "Asymetrix Logo"
clip "No No No"
clip "toad"
clip "tiger"
clip "lion"
clip "bird3"
clip "bird2"
clip "bird1"
clip "CD Audio"
clip "Chirp"
animation
digitalVideo
bitmap
cdAudio
sequencer
photoCD
videoDisk
waveAudio
overlay
RadioButtons
play clips
delay
buttonclick
buttonclick
delay
B"play clips" =
Often
Normal
20000
Rarely
How often
enterPage
leavePage
Remove trailing spaces
Remove trailing spaces
label
This function removes all trailing spaces, as well as other undesirable characters.
Handler: trim(<string to trim>)
Parameters:
<string to trim> The string from which you want to remove the trailing stuff.
Returns the modified string
-- removes trailing spaces, tabs, and crlf's
to get trim strng
local charsToDrop
set charsToDrop to space & crlf & tab
while charcount(strng) > 0 and last char of strng is in charsToDrop