Photoshop Javascript: How to get / set current tool? - photoshop-script

How does one get / set the current tool using Javascript in Photoshop?
#target photoshop
if (app.currentTool == BRUSH_TOOL) {
app.currentTool = ERASE_TOOL;
} else {
app.currentTool = BRUSH_TOOL;
}

I found a solution, but I wish it was simpler. Basically I'm using this to select the brush tool and toggle the eraser tool, using only one button. That way I only have to use one button on my Wacom Tablet.
#target photoshop
if (getTool() == 'paintbrushTool') {
setTool('eraserTool');
} else {
setTool('paintbrushTool');
}
// https://forums.adobe.com/thread/579195
function getTool(){
var ref = new ActionReference();
ref.putEnumerated( charIDToTypeID("capp"), charIDToTypeID("Ordn"), charIDToTypeID("Trgt") );
var cTool = typeIDToStringID(executeActionGet(ref).getEnumerationType(stringIDToTypeID('tool')));
return cTool;
}
// https://www.ps-scripts.com/viewtopic.php?f=68&t=11342&p=152772
function setTool(tool) {
var desc9 = new ActionDescriptor();
var ref7 = new ActionReference();
ref7.putClass( app.stringIDToTypeID(tool) );
desc9.putReference( app.charIDToTypeID('null'), ref7 );
executeAction( app.charIDToTypeID('slct'), desc9, DialogModes.NO );
}
// Tool names (use quoted strings, e.g. 'moveTool')
// moveTool
// marqueeRectTool
// marqueeEllipTool
// marqueeSingleRowTool
// marqueeSingleColumnTool
// lassoTool
// polySelTool
// magneticLassoTool
// quickSelectTool
// magicWandTool
// cropTool
// sliceTool
// sliceSelectTool
// spotHealingBrushTool
// magicStampTool
// patchSelection
// redEyeTool
// paintbrushTool
// pencilTool
// colorReplacementBrushTool
// cloneStampTool
// patternStampTool
// historyBrushTool
// artBrushTool
// eraserTool
// backgroundEraserTool
// magicEraserTool
// gradientTool
// bucketTool
// blurTool
// sharpenTool
// smudgeTool
// dodgeTool
// burnInTool
// saturationTool
// penTool
// freeformPenTool
// addKnotTool
// deleteKnotTool
// convertKnotTool
// typeCreateOrEditTool
// typeVerticalCreateOrEditTool
// typeCreateMaskTool
// typeVerticalCreateMaskTool
// pathComponentSelectTool
// directSelectTool
// rectangleTool
// roundedRectangleTool
// ellipseTool
// polygonTool
// lineTool
// customShapeTool
// textAnnotTool
// soundAnnotTool
// eyedropperTool
// colorSamplerTool
// rulerTool
// handTool
// zoomTool

It's simpler in AppleScript. This is my little library script that I use with my Wacom:
-- put into ~/Library/Script\ Libraries
-- use as set currentTool to script "Photoshop_ScriptLibrary"'s toggleCurrentTool("lassoTool", "eraserTool")
on writeVar(theName, theVar)
do shell script "echo " & theVar & " > /tmp/" & theName & ".txt"
end writeVar
on readVar(theName)
try
return do shell script "cat /tmp/" & theName & ".txt"
end try
return ""
end readVar
on getGroupPath()
set thelayer to ""
tell application "Adobe Photoshop CC 2019" to tell the current document
set thelayer to current layer
end tell
return thelayer
end getGroupPath
on getCurrentTool()
tell application "Adobe Photoshop CC 2019" to return current tool
end getCurrentTool
on deselect()
tell application "Adobe Photoshop CC 2019" to tell the current document to deselect
setFeathered(false)
end deselect
on toggleCurrentTool(tool1, tool2)
setFeathered(false)
set currentTool to tool1
tell application "Adobe Photoshop CC 2019"
if current tool is equal to currentTool then set currentTool to tool2
set current tool to currentTool
end tell
return currentTool
end toggleCurrentTool
on getAllLayers(layerName)
set allLayerNames to {}
tell application "Adobe Photoshop CC 2019"
set allLayers to the layers of current document
repeat with thelayer in allLayers
set theName to the name of thelayer
if theName starts with the first word of layerName then set end of allLayerNames to theName
end repeat
end tell
return allLayerNames
end getAllLayers
on getPrevLayer(targetLayerName, currentLayer)
set currentLayerId to id of currentLayer
tell application "Adobe Photoshop CC 2019"
return the first art layer of the current document whose name is targetLayerName and id is not currentLayerId
return the first art layer of the current document whose name is targetLayerName
end tell
end getPrevLayer
on getPrevious(layerName)
set suffix to the last word of layerName
set suffixlength to get (length of suffix) + 2
log "getPrevious(" & layerName & "), suffix: " & suffix
-- remove the last word from the layer name. Unless we're dealing with numbered copies
set targetLayerName to (text 1 thru (-1 * suffixlength)) of layerName
-- first: Check if layer name ends in number. If number > 2, we want the layer with the next-smaller number
-- WIP copy 16 -> WIP copy 15
-- WIP copy 1 -> WIP copy
-- second: If the layer does not end in a number,
try
set thenumber to (suffix as number)
if thenumber is greater than 2 then set targetLayerName to targetLayerName & " " & thenumber - 1
on error -- if layer doesn't end in a number: remove "copy"
if layerName ends with "copy" then set targetLayerName to text 1 thru -6 of layerName
end try
return targetLayerName
end getPrevious
on getPreviousLayer(currentLayer)
return getPrevLayer((getPrevious(name of currentLayer)), currentLayer)
end getPreviousLayer
on getFeathered()
return "true" is equal to readVar("feathered")
end getFeathered
on setFeathered(b)
writeVar("feathered", b)
end setFeathered
on isOnLayerMask()
try
set windowName to ""
tell application "System Events" to tell process "Adobe Photoshop CC 2019"
tell (1st window whose value of attribute "AXMain" is true)
set windowName to value of attribute "AXTitle"
end tell
end tell
end try
return windowName contains "Layer Mask"
end isOnLayerMask
on isSelected()
try
tell application "Adobe Photoshop CC 2019" to tell current document
set props to properties of selection
if bounds of props is not equal to missing value then return true
end tell
end try
return false
end isSelected
on tryFeather()
if getFeathered() or not isSelected() then return
try
tell application "Adobe Photoshop CC 2019" to tell current document
feather selection by 5
end tell
setFeathered(true)
on error
setFeathered(false)
end try
end tryFeather
on tryBlur(_radius)
if isSelected() then
try
tell application "Adobe Photoshop CC 2019" to tell current document
filter current layer using gaussian blur with options {radius:_radius}
end tell
end try
end if
end tryBlur

you can try to use photoshop-python-api
from photoshop import Session
with Session() as ps:
print(ps.app.currentTool)
https://github.com/loonghao/photoshop-python-api

Old question, but still relevant so I wanted to simplify it further. The OP was on the right track with the code, it needed only the necessary string values for various tools, which were provided by #skibulk above.
According to the Photoshop Javascript Reference PDF, currentTool is a read-write string property of the Application object. This means we can get the value of the current tool, but also set the value of the current tool.
#target photoshop
if (app.currentTool == "paintbrushTool") {
app.currentTool = "eraserTool";
} else {
app.currentTool = "paintbrushTool";
}
// Tool names (use quoted strings, e.g. 'moveTool')
// moveTool
// marqueeRectTool
// marqueeEllipTool
// marqueeSingleRowTool
// marqueeSingleColumnTool
// lassoTool
// polySelTool
// magneticLassoTool
// quickSelectTool
// magicWandTool
// cropTool
// sliceTool
// sliceSelectTool
// spotHealingBrushTool
// magicStampTool
// patchSelection
// redEyeTool
// paintbrushTool
// pencilTool
// colorReplacementBrushTool
// cloneStampTool
// patternStampTool
// historyBrushTool
// artBrushTool
// eraserTool
// backgroundEraserTool
// magicEraserTool
// gradientTool
// bucketTool
// blurTool
// sharpenTool
// smudgeTool
// dodgeTool
// burnInTool
// saturationTool
// penTool
// freeformPenTool
// addKnotTool
// deleteKnotTool
// convertKnotTool
// typeCreateOrEditTool
// typeVerticalCreateOrEditTool
// typeCreateMaskTool
// typeVerticalCreateMaskTool
// pathComponentSelectTool
// directSelectTool
// rectangleTool
// roundedRectangleTool
// ellipseTool
// polygonTool
// lineTool
// customShapeTool
// textAnnotTool
// soundAnnotTool
// eyedropperTool
// colorSamplerTool
// rulerTool
// handTool
// zoomTool

Related

How to get if the drawing sketch is being edited? (Autodesk Inventor C++ API)

I need to add a drawing sketch in Inventor and edit it. However, if another sketch is already being edited, my program terminates and even try/catch does not help. I can't find a property of the sketch showing if it is being edited or not. My main part of code is here:
// All of these three functions pass try/catch perfectly. Program never terminates
Inventor::Application^ App = (Inventor::Application^)Marshal::GetActiveObject("Inventor.Application");
DrawingDocument^ Doc = (DrawingDocument^)App->ActiveDocument;
Sheet^ Sh = Doc->ActiveSheet;
DrawingSketch^ Sk;
try
{
Sh->Sketches->Add();
Sk = Sh->Sketches[Sh->Sketches->Count];
Sk->Edit(); // Crushes the program completely if another sketch is being edited
}
catch (...)
{
return;
}
I tried to cycle through all the sketches and close them all. This behaves in a way I cannot understand.
try
{
// Note: in Inventor indexes definitely start from 1
for (int i = 1; i <= Sh->Sketches->Count; i++)
{
Sk = Sh->Sketches[i];
Sk->ExitEdit();
}
}
catch (...)
{
return;
}
For example, when the sketch 2 is open, the first cycle (i = 1) that tries to close the sketch 1, somehow closes the sketch 2. And the second iteration (i = 2) that now cannot close the sketch 2, as it is already closed, calls 'catch' and further 'return'.
I'm not familiar with C++, but here is VBA sample how to detect the drawing sketch is in edit mode
Dim oDrawing As DrawingDocument
Set oDrawing = ThisApplication.ActiveDocument
Dim oSheet As Sheet
Set oSheet = oDrawing.ActiveSheet
Dim editedObject As Variant
Set editedObject = ThisApplication.ActiveEditObject
If editedObject.Type = ObjectTypeEnum.kDrawingSketchObject Then
Dim activeEditSketch As DrawingSketch
Set activeEditSketch = editedObject
activeEditSketch.ExitEdit
End If
Dim oSketch As DrawingSketch
Set oSketch = oSheet.Sketches.Add()
I hope, you can convert this code to C++

Adding a feature to this Hangman Game

I have a hangman game and I am having trouble adding in a feature. I want to make it if the whole word is guessed, it will display "You guessed the word!!!", but I cant seem to find a spot to put it. This is the code
hangman's init()
script hangman
property stdin : missing value
property stdout : missing value
property dict : missing value
on init()
--starting up the game
set stdin to parent's hangmanStdin's alloc()'s init()
set stdout to parent's hangmanStdout's alloc()'s init()
set dict to parent's hangmanDictionary's alloc()'s init()
my mainLoop()
end init
on mainLoop()
repeat --endless
set option to stdin's getOptions("Lobby", "What would you like to do?", {"New Game", "Quit"})
if option is "New Game" then
set difficulty to stdin's getOptions("New Game", "Choose your difficulty", {"Normal", "Easy", "Hard"})
--replace this line with an automatic word generator
set x to parent's hangmanGame's alloc()'s initWithWordAndDifficulty(dict's getWord(), difficulty)
if x's startgame() is false then
return
else
stdout's printf("You've scored " & x's score & " points.")
end if
--game is over so clear it
set x to missing value
else
exit repeat
end if
end repeat
end mainLoop
on shouldTerminate()
return true
end shouldTerminate
on alloc()
copy me to x
return x
end alloc
end script
script hangmanGame
property parent : hangman
property wordToGuess : missing value
property maxFaults : missing value
property usedChars : missing value
property faults : missing value
property score : 0
on initWithWordAndDifficulty(theWord, theDifficulty)
if theDifficulty = "Hard" then
set my maxFaults to 5
else if theDifficulty = "Normal" then
set my maxFaults to 8
else --easy or any other value will be handled as easy
set my maxFaults to 10
end if
set my wordToGuess to theWord
set my usedChars to {}
set my faults to 0
set my score to 0
return me
end initWithWordAndDifficulty
on startgame()
repeat --endless
set __prompt to "Faults Left: " & maxFaults - faults & return & "The Word: " & my makeHiddenField()
set c to parent's stdin's getChar(__prompt)
if c = false then
return false
end if
--first check if getChar did give us any result
if length of c is not 0 then
--check if teh character is valid
if c is in "abcdefghijklmnopqrstuvwxyz" then
--check if we already checked this before
if c is not in my usedChars then
set end of my usedChars to c
--check if player guessed wrong character
if c is not in wordToGuess then
set faults to faults + 1
end if
end if
end if
end if
--check if player guessed all characters of word
if my wordGuessed() then
set my score to ((25 * (26 / (length of my usedChars))) as integer)
return true
end if
--check if player reached the max faults he's allowed to make
if my faults = my maxFaults then
display dialog "The word was " & quoted form of wordToGuess
return 0
end if
end repeat
end startgame
on wordGuessed()
repeat with aChar in every text item of my wordToGuess
if aChar is not in my usedChars then
return false
end if
end repeat
return true
end wordGuessed
on makeHiddenField()
set characterArray to {}
repeat with aChar in every text item of my wordToGuess
if aChar is in my usedChars then
set end of characterArray to aChar as string
else
set end of characterArray to "_"
end if
end repeat
set AppleScript's text item delimiters to space
set hiddenField to characterArray as string
set AppleScript's text item delimiters to ""
return hiddenField
end makeHiddenField
end script
script hangmanDictionary
property parent : hangman
property wordsPlayed : missing value
property allWords : missing value
on init()
set wordsPlayed to {}
--try to get more words from a file for example
set allWords to {"Hangman", "Police", "Officer", "Desktop", "Pencil", "Window", "Language", "Wealthy", "Trauma", "Spell", "Rival", "Tactical", "Thin", "Salty", "Bluish", "Falcon", "Distilery", "Ballistics", "Fumbling", "Limitless", "South", "Humble", "Foreign", "Affliction", "Retreat", "Agreeable", "Poisoner", "Flirt", "Fearsome", "Deepwater", "Bottom", "Twisted", "Morsel", "Filament", "Winter", "Contempt", "Drimys", "Grease", "Awesome", "Compulsive", "Crayon", "Prayer", "Blonde", "Backbone", "Dreamland", "Ballet", "Continuous", "Aerobatic", "Hideous", "Harmonic", "Lottery", "Encrypt", "Cable", "Aluminium", "Hunter", "National", "Hunter", "Mechanical", "Deadbeat", "Opposition", "Threat", "Decadent", "Gazelle", "Guild", "Authoritive", "Deliverance", "Severe", "Jerid", "Alarm", "Monochrome", "Cyanide", "External", "Potential", "Section", "Innocent", "Drifting", "Amnesia", "Domino", "Flimsy", "Flamethrowing", "Advocate", "Hirsute", "Brother", "Ephemeral", "Brutal", "Decade", "Drauma", "Dilemma", "Exquisite", "Glimmer", "Fugitive", "Digital", "Associate", "Ambivalent", "Ambulatory", "Apology", "Brawler", "Molecular", "Insurance", "Contractual", "Initial", "Calibration", "Heretical", "Disclosure", "Guerilla", "Dismember", "Minimal", "Altercation", "Eastern", "Integrate", "Femur", "Metallic", "Ambition", "Auxiliary", "Esoteric", "Converse", "Accepting", "Juvenile", "Efficacious", "Complex", "Imperil", "Division", "Onerous", "Astonish", "Scandalous", "Quaint", "Dominate", "Contrary", "Conspiracy", "Earthquake", "Embarrassment", "Exclude", "Ambiguous", "Captivate", "Compliance", "Migration", "Embryo", "Abandon", "Conservation", "Appreciate", "Applaud", "Pension", "Voyage", "Influence", "Consensus", "Incapable", "Economy", "Parameter", "Contrast", "Sensitive", "Meadow", "Chimney", "Familiar", "Serious", "Credibility", "Infrastructure", "Museum", "Relinquish", "Merit", "Coalition", "Retirement", "Transaction", "Official", "Composer", "Magnitude", "Committee", "Privilege", "Diamond", "Obligation", "Transition", "Jockey", "Reinforce", "Conflict", "Offensive", "Detective", "Effective", "Detector", "Abhorrent", "Fragile", "Feigned", "Addition", "Jealous", "Irritating", "Grotesque", "Hesitant", "Adaptable", "Highfalutin", "Defiant", "Ceaseless", "Aquatic", "Voracious", "Separate", "Phobic", "Scientific", "Cluttered", "Intelligent", "Garrulous", "Rhetorical", "Obtainable", "Bawdy", "Outstanding", "Synonymous", "Gleaming", "Ambitious", "Agonizing", "Fallacious", "Lamister", "Fugitive", "Individualism", "Archaic", "Paramount", "Pannose", "Pretermit", "Retorse", "Versability", "Demonomancy", "Vagile", "Reflation", "Foliate", "Guignol", "Agacerie", "Theopneustic", "Glumiferous", "Optative", "Scrivello", "Unifarious", "Ordonnance", "Dithyrambic", "Locative", "Locomotive", "Mirabilia", "Keyline", "Mellification", "Theomicrist", "Ireless", "Commonition", "Dragoon", "Webster", "Utinam", "Obumbrate", "Inceptive"}
return me
end init
on getWord()
set randomNr to (random number from 1 to (length of (my allWords))) as integer
--you could do somethinh here when a word is used again
return item randomNr of my allWords as string
end getWord
end script
script hangmanStdin
property parent : hangman
on init()
return me
end init
on getChar(__prompt)
set x to display dialog __prompt buttons {"Go", "Quit"} default button "Go" default answer ""
if button returned of x = "Quit" then
return false
end if
if length of x's text returned = 0 then
return ""
end if
return character 1 of x's text returned
end getChar
on getOptions(__title, __message, __options)
return button returned of (display alert __title message __message buttons __options default button 1)
end getOptions
end script
script hangmanStdout
property parent : hangman
on init()
return me
end init
on printf(__message)
display dialog __message buttons {"OK"} default button 1
end printf
end script
This is similar to your other topic, you just need to follow the flow of your script.
In the hangmanGame script’s startGame() handler, you are using the wordGuessed() handler to determine if the word was guessed, so the dialog can go where you are getting that result, for example:
if my wordGuessed() then
display dialog "You guessed the word!!!"
set my score to ((25 * (26 / (length of my usedChars))) as integer)
return true
end if

How to add new features to my Hangman game?

I am working on a game, Hangman. I have the code down, I just want to display the word if you lose. How can I do that?
hangman's init()--by Londres on Stack Overflow
script hangman
property stdin : missing value
property stdout : missing value
property dict : missing value
on init()
--starting up the game
set stdin to parent's hangmanStdin's alloc()'s init()
set stdout to parent's hangmanStdout's alloc()'s init()
set dict to parent's hangmanDictionary's alloc()'s init()
my mainLoop()
end init
on mainLoop()
repeat --endless
set option to stdin's getOptions("Lobby", "What would you like to do?", {"New Game", "Quit"})
if option is "New Game" then
set difficulty to stdin's getOptions("New Game", "Choose your difficulty", {"Normal", "Easy", "Hard"})
--replace this line with an automatic word generator
set x to parent's hangmanGame's alloc()'s initWithWordAndDifficulty(dict's getWord(), difficulty)
if x's startgame() is false then
return
else
stdout's printf("You've scored " & x's score & " points.")
end if
--game is over so clear it
set x to missing value
else
exit repeat
end if
end repeat
end mainLoop
on shouldTerminate()
return true
end shouldTerminate
on alloc()
copy me to x
return x
end alloc
end script
script hangmanGame
property parent : hangman
property wordToGuess : missing value
property maxFaults : missing value
property usedChars : missing value
property faults : missing value
property score : 0
on initWithWordAndDifficulty(theWord, theDifficulty)
if theDifficulty = "Hard" then
set my maxFaults to 5
else if theDifficulty = "Normal" then
set my maxFaults to 8
else --easy or any other value will be handled as easy
set my maxFaults to 12
end if
set my wordToGuess to theWord
set my usedChars to {}
set my faults to 0
set my score to 0
return me
end initWithWordAndDifficulty
on startgame()
repeat --endless
set __prompt to "Faults Left: " & maxFaults - faults & return & "The Word: " & my makeHiddenField()
set c to parent's stdin's getChar(__prompt)
if c = false then
return false
end if
--first check if getChar did give us any result
if length of c is not 0 then
--check if teh character is valid
if c is in "abcdefghijklmnopqrstuvwxyz" then
--check if we already checked this before
if c is not in my usedChars then
set end of my usedChars to c
--check if player guessed wrong character
if c is not in wordToGuess then
set faults to faults + 1
end if
end if
end if
end if
--check if player guessed all characters of word
if my wordGuessed() then
set my score to ((25 * (26 / (length of my usedChars))) as integer)
return true
end if
--check if player reached the max faults he's allowed to make
if my faults = my maxFaults then
return 0
end if
end repeat
end startgame
on wordGuessed()
repeat with aChar in every text item of my wordToGuess
if aChar is not in my usedChars then
return false
end if
end repeat
return true
end wordGuessed
on makeHiddenField()
set characterArray to {}
repeat with aChar in every text item of my wordToGuess
if aChar is in my usedChars then
set end of characterArray to aChar as string
else
set end of characterArray to "_"
end if
end repeat
set AppleScript's text item delimiters to space
set hiddenField to characterArray as string
set AppleScript's text item delimiters to ""
return hiddenField
end makeHiddenField
end script
script hangmanDictionary
property parent : hangman
property wordsPlayed : missing value
property allWords : missing value
on init()
set wordsPlayed to {}
--try to get more words from a file for example
set allWords to {"Hangman", "Police", "Officer", "Desktop", "Pencil", "Window", "Language", "Wealthy", "Trauma", "Spell", "Rival", "Tactical", "Thin", "Salty", "Bluish", "Falcon", "Distilery", "Ballistics", "Fumbling", "Limitless", "South", "Humble", "Foreign", "Affliction", "Retreat", "Agreeable", "Poisoner", "Flirt", "Fearsome", "Deepwater", "Bottom", "Twisted", "Morsel", "Filament", "Winter", "Contempt", "Drimys", "Grease", "Awesome", "Compulsive", "Crayon", "Prayer", "Blonde", "Backbone", "Dreamland", "Ballet", "Continuous", "Aerobatic", "Hideous", "Harmonic", "Lottery", "Encrypt", "Cable", "Aluminium", "Hunter", "National", "Hunter", "Mechanical", "Deadbeat", "Opposition", "Threat", "Decadent", "Gazelle", "Guild", "Authoritive", "Deliverance", "Severe", "Jerid", "Alarm", "Monochrome", "Cyanide", "External", "Potential", "Section", "Innocent", "Drifting", "Amnesia", "Domino", "Flimsy", "Flamethrowing", "Advocate", "Hirsute", "Brother", "Ephemeral", "Brutal", "Decade", "Drauma", "Dilemma", "Exquisite", "Glimmer", "Fugitive", "Digital", "Associate", "Ambivalent", "Ambulatory", "Apology", "Brawler", "Molecular", "Insurance", "Contractual", "Initial", "Calibration", "Heretical", "Disclosure", "Guerilla", "Dismember", "Minimal", "Altercation", "Eastern", "Integrate", "Femur", "Metallic", "Ambition", "Auxiliary", "Esoteric", "Converse", "Accepting", "Juvenile", "Efficacious", "Complex", "Imperil", "Division", "Onerous", "Astonish", "Scandalous", "Quaint", "Dominate", "Contrary", "Conspiracy", "Earthquake", "Embarrassment", "Exclude", "Ambiguous", "Captivate", "Compliance", "Migration", "Embryo", "Abandon", "Conservation", "Appreciate", "Applaud", "Pension", "Voyage", "Influence", "Consensus", "Incapable", "Economy", "Parameter", "Contrast", "Sensitive", "Meadow", "Chimney", "Familiar", "Serious", "Credibility", "Infrastructure", "Museum", "Relinquish", "Merit", "Coalition", "Retirement", "Transaction", "Official", "Composer", "Magnitude", "Committee", "Privilege", "Diamond", "Obligation", "Transition", "Jockey", "Reinforce", "Conflict", "Offensive", "Detective", "Effective", "Detector"}
return me
end init
on getWord()
set randomNr to (random number from 1 to (length of (my allWords))) as integer
--you could do somethinh here when a word is used again
return item randomNr of my allWords as string
end getWord
end script
script hangmanStdin
property parent : hangman
on init()
return me
end init
on getChar(__prompt)
set x to display dialog __prompt buttons {"Go", "Quit"} default button "Go" default answer ""
if button returned of x = "Quit" then
return false
end if
if length of x's text returned = 0 then
return ""
end if
return character 1 of x's text returned
end getChar
on getOptions(__title, __message, __options)
return button returned of (display alert __title message __message buttons __options default button 1)
end getOptions
end script
script hangmanStdout
property parent : hangman
on init()
return me
end init
on printf(__message)
display dialog __message buttons {"OK"} default button 1
end printf
end script
How can I make it so if you lose the game, not only does it say the you got 0 points but also say the word that they missed. I'm trying my best to get this done. It's a project that I'm doing to get the basics of coding. Took me awhile.
You are only checking the return result from hangmanGame’s startGame() handler for false or otherwise, but the handler returns 0 if all the faults are used. You could add an additional check in there, but the easiest way would probably be to add a dialog in the startGame() comparison, for example:
if my faults = my maxFaults then
display dialog "The word was " & quoted form of wordToGuess
return 0
end if

How to translate this slider value change from AppleScript to JavaScript

This bit of AppleScript works. If I have the System Preferences Sound panel open, and run it in the Script Editor app, it changes the volume to be at 50%.
tell application "System Events"
tell process "System Preferences"
set v to value of slider 0 of window 0
log v
set value of slider 0 of window 0 to 0.5
end tell
end tell
This, which tries to be the same thing, fails. Anyone know how to fix it?
var se = Application("System Events");
var spp = se.processes["System Preferences"];
spp.windows[0].sliders[0].value = 0.5
var curr = spp.windows[0].sliders[0].value();
console.log("Current value: " + curr + " - " + typeof(curr));
It ends up setting it to 0. It seems I can only set the volume to 0 or 1. In reality I'm trying to script another application, but this boils down the problem.
As I noted in my comment, I'm 90% sure this is a bug.
Here's a workaround:
app = Application.currentApplication();
app.includeStandardAdditions = true;
try {
app.doShellScript('osascript -e \'tell application "System Events" to set value of slider 0 of window 0 of process "System Preferences" to 0.2\'');
} catch (error ) {
-1;
}

How to put breakpoint in every function of .cpp file?

Is there a macro that does it? Which DTE objects to use?
(This is not quite what you're asking for, but almost:)
You can put a breakpoint on every member function of a class in Visual Studio by bringing up the New Breakpoint dialog and entering:
CMyClass::*
See http://blogs.msdn.com/b/habibh/archive/2009/09/10/class-breakpoint-how-to-set-a-breakpoint-on-a-c-class-in-the-visual-studio-debugger.aspx for more details.
Here's a quick implementation of 1800 INFORMATION's idea:
Sub TemporaryMacro()
DTE.ActiveDocument.Selection.StartOfDocument()
Dim returnValue As vsIncrementalSearchResult
While True
DTE.ActiveDocument.ActiveWindow.Object.ActivePane.IncrementalSearch.StartForward()
returnValue = DTE.ActiveDocument.ActiveWindow.Object.ActivePane.IncrementalSearch.AppendCharAndSearch(AscW("{"))
DTE.ActiveDocument.ActiveWindow.Object.ActivePane.IncrementalSearch.Exit()
If Not (returnValue = vsIncrementalSearchResult.vsIncrementalSearchResultFound) Then
Return
End If
DTE.ExecuteCommand("Debug.ToggleBreakpoint")
DTE.ExecuteCommand("Edit.GotoBrace")
DTE.ActiveDocument.Selection.CharRight()
End While
End Sub
I don't know what DTE functions to use, but you could very simply record a macro that could pretty much do it:
Go to the top of the file
ctrl - shift - R (start recording)
ctrl - I (incremental search)
{ (search for the first { character).
F9 (set breakpoint)
ctrl - ] (go to matching } character)
ctrl - shift - R (stop recording)
Now just run this over and over (ctrl - shift P repeatedly) until you reach the end of the file.
If you have namespaces, then change 4. to:
( (search for "(" at the start of the function definition)
esc (stop incremental search)
ctrl - I (incremental search again)
{ (start of function body)
This kind of thing can be infinitely modified to suit your codebase
Like Constantin's method... This seems like windbg territory.
Since you have the cpp, (even if you didn't you could script something to get by), it should be no problem to use logger part of the debugging tools for windows... it's a very handy tool, shame so few people use it.
logger debug's C/COM/C++ easily, with rich symbolic info, hooks/profiling/flexible instrumentation;
One way to activate Logger is to start CDB or WinDbg and attach to a user-mode target application as usual. Then, use the !logexts.logi or !logexts.loge extension command.
This will insert code at the current breakpoint that will jump off to a routine that loads and initializes Logexts.dll in the target application process. This is referred to as "injecting Logger into the target application."
Here's how something similar could be achieved in WinDbg:
bm mymodule!CSpam::*
This puts breakpoint in every method of class (or namespace) CSpam in module mymodule.
I'm still looking for anything close to this functionality in Visual Studio.
There is a macro, but I tested it only with c#.
Sub BreakAtEveryFunction()
For Each project In DTE.Solution.Projects
SetBreakpointOnEveryFunction(project)
Next project
End Sub
Sub SetBreakpointOnEveryFunction(ByVal project As Project)
Dim cm = project.CodeModel
' Look for all the namespaces and classes in the
' project.
Dim list As List(Of CodeFunction)
list = New List(Of CodeFunction)
Dim ce As CodeElement
For Each ce In cm.CodeElements
If (TypeOf ce Is CodeNamespace) Or (TypeOf ce Is CodeClass) Then
' Determine whether that namespace or class
' contains other classes.
GetClass(ce, list)
End If
Next
For Each cf As CodeFunction In list
DTE.Debugger.Breakpoints.Add(cf.FullName)
Next
End Sub
Sub GetClass(ByVal ct As CodeElement, ByRef list As List(Of CodeFunction))
' Determine whether there are nested namespaces or classes that
' might contain other classes.
Dim aspace As CodeNamespace
Dim ce As CodeElement
Dim cn As CodeNamespace
Dim cc As CodeClass
Dim elements As CodeElements
If (TypeOf ct Is CodeNamespace) Then
cn = CType(ct, CodeNamespace)
elements = cn.Members
Else
cc = CType(ct, CodeClass)
elements = cc.Members
End If
Try
For Each ce In elements
If (TypeOf ce Is CodeNamespace) Or (TypeOf ce Is CodeClass) Then
GetClass(ce, list)
End If
If (TypeOf ce Is CodeFunction) Then
list.Add(ce)
End If
Next
Catch
End Try
End Sub
Here's one way to do it (I warn you it is hacky):
EnvDTE.TextSelection textSelection = (EnvDTE.TextSelection)dte.ActiveWindow.Selection;
// I'm sure there's a better way to get the line count than this...
var lines = File.ReadAllLines(dte.ActiveDocument.FullName).Length;
var methods = new List<CodeElement>();
var oldLine = textSelection.AnchorPoint.Line;
var oldLineOffset = textSelection.AnchorPoint.LineCharOffset;
EnvDTE.CodeElement codeElement = null;
for (var i = 0; i < lines; i++)
{
try
{
textSelection.MoveToLineAndOffset(i, 1);
// I'm sure there's a better way to get a code element by point than this...
codeElement = textSelection.ActivePoint.CodeElement[vsCMElement.vsCMElementFunction];
if (codeElement != null)
{
if (!methods.Contains(codeElement))
{
methods.Add(codeElement);
}
}
}
catch
{
//MessageBox.Show("Add error handling here.");
}
}
// Restore cursor position
textSelection.MoveToLineAndOffset(oldLine, oldLineOffset);
// This could be in the for-loop above, but it's here instead just for
// clarity of the two separate jobs; find all methods, then add the
// breakpoints
foreach (var method in methods)
{
dte.Debugger.Breakpoints.Add(
Line: method.StartPoint.Line,
File: dte.ActiveDocument.FullName);
}
Put this at the top of the file:
#define WANT_BREAK_IN_EVERY_FUNCTION
#ifdef WANT_BREAK_IN_EVERY_FUNCTION
#define DEBUG_BREAK DebugBreak();
#else
#define DEBUG_BREAK
#endif
then insert DEBUG_BREAK in the beginning of every function, like this:
void function1()
{
DEBUG_BREAK
// the rest of the function
}
void function2()
{
DEBUG_BREAK
// the rest of the function
}
When you no longer want the debug breaks, comment the line
// #define WANT_BREAK_IN_EVERY_FUNCTION
at the top of the file.

Resources