Answer command and Javascript

Anything beyond the basics in using the LiveCode language. Share your handlers, functions and magic here.

Moderators: FourthWorld, heatherlaine, Klaus, kevinmiller, robinmiller

Post Reply
adxsoft
Posts: 26
Joined: Wed Apr 11, 2018 12:25 pm

Answer command and Javascript

Post by adxsoft » Sat Jan 26, 2019 5:13 am

Hi

I have a variable that happens to contain a javascript function as well as other normal text.

When I do

Code: Select all

answer tMyTextContainingJavaScriptAndText
I get a model dialog that is way wider than the screen with no buttons.

Seems like a bug

Using LiveCode Community Edition 9.0.0

The variable contents are shown below

Cheers
Allan

Code: Select all

ADDebugger
2017-08-12
ADDebugger is a piece of code that can be included in before any Jython code and provides break points via code snippets within the code under test
`
#=======================================================================================
#  DBG V1 - DEBUG TOOL FOR USE WITH JYTHON EMBEDDED IN A JAVA PROGRAM
#  This simple tool provides snapshots of all local variables in a Jython script
#  Simply Include all this code from here until END OF DBG comment lines
#  at the start of your jython script
#
# place command dbg(argument) at points in the code where you wish to perform
# a debug action
#
# ACTIONS IN THIS VERSION
#
# dbg("break") -  stops and displays a dialog with all the variables
# dbg("stop")  -  cancels any remaining dbg breaks from occuring
# dbg("clear") -  resets the Debugger and clears all previous results
#=======================================================================================

from javax.swing import *
from java.awt import *
from javax.swing import JFrame, JEditorPane, JTable, JScrollPane
from javax.swing.table import DefaultTableModel, DefaultTableCellRenderer
import javax.swing.JRootPane;
import javax.swing.JComponent;
from java.awt.event import MouseAdapter
from java.awt.event import KeyEvent, KeyAdapter

# Global variables
global d #debug object

# ---------- CONSTANTS -----------------------
# set remote debug point
# import pydevd; pydevd.settrace()

#true and false variables to keep Jython happy
true=1
false=0

# --------- PRIVATE VARIABLES -----------------
_rowdata=[] # Used to store a snapshot of local variavles in this module
_debug=true # set to true or false to activate Debugger
_vars=[]

#---------- FUNCTIONS -------------------------
#
# Deliberately not included in dialogDebug class to ensure the functions
# operate at the same scope level as the program under test

def dbg(mode,name='',value='',refinfo=''):
    global _rowdata,d, _vars,_debug

    if mode=='stop':
        # prevent any remaining breaks from executing
        _debug=false
        print "Debugging STOPPED"

    if mode=='resume':
        # allow any remaining breaks from this point to occur
        _debug=true
        print "Debugging RESUMED",_debug

        if _debug==false:
            return

    if mode=="clear":
        _vars={}

    if mode=="build":
        _rowdata.append([str(name),"  "+str(value)])

    if mode=="break" and _debug==true:

        # output current values of local variables to the display array
        for _v in _vars.keys():

            # skip variables used by debugger
            if _v in ["_v","_rowdata","_mode","_debug","_vars","true","false"]: continue
            if _v.startswith("__"): continue

            # for each
            _mode="build" # tells dbg to build global array rowdata for display in the debug dialog
            if type(_vars[_v])==type(""):
                dbg(_mode,_v,_vars[_v])
            if type(_vars[_v])==type([]): dbg(_mode,_v,_vars[_v])
            if type(_vars[_v])==type(0): dbg(_mode,_v,_vars[_v])
            if type(_vars[_v])==type(0.00): dbg(_mode,_v,_vars[_v])
            if type(_vars[_v])==type({}) and _v<>"_vars": dbg(_mode,_v,_vars[_v])

        f=open('/Users/allandavies/Desktop/debugbreak.txt','w')
        f.write('Debug info for reference: '+refinfo)
        for r in _rowdata:
            f.write(showit(r[0],r[1])+'\n')
        f.close()

        # show debug dialog
        d=dialogDebug(_rowdata,"Debug: break - ref "+str(refinfo))
        print "============================="
        print "Debug: break - ref "+str(refinfo)
        for r in _rowdata:
            showit(r[0],r[1])
        print "============================="
        print ""
        _vars=[]
        _rowdata=[]


    if mode=="close":
        d.close()

def showit(name,value):

    # handle an array list which can include other array lists (one level deep)
    if value.startswith("[") and value.endswith("]"):
        print name,"contents"
        values=value[1:-1].split(",")
        innerarray=false
        indent='    '
        for v in values:
            v=v.strip()
            if v.startswith("["):
                innerarray=true
                print indent+'['
                print indent+indent+v[1:]
            elif v.endswith("]"):
                innerarray=false
                print indent+indent+v[:-1]
                print indent+']'
            elif innerarray==true:
                print indent+indent+v
            else:
                print v

    # handle a  dictionary with key,value pairs
    if value.startswith("{") and value.endswith("}"):
        print name,"contents"
        values=value[1:-1].split(',')
        innerarray=false

        for var in values:

            v=var.strip()

            try:
                name=v.split(":")[0].strip()
            except:
                name="?"

            try:
                value=v.split(":")[1].strip()
            except:
                value="?"


            if value.startswith('{') or value.startswith('['):
                print v
                innerarray=true
                continue

            if value.endswith('}') or value.endswith(']'):
                print '           ',name+":",value
                innerarray=false
                continue

            if innerarray==true:
                #print "INNER value is ",value
                print '           ',v
                continue

            print name,value

    else:
        print name+" = "+value

        return name+" = "+value

#--- Classes ----------------------------------

#--------------------------------
class dialogDebug:
# Debugger Dialog Window
#--------------------------------

    def __init__(self, rowdata,title):

        self.title=title
        self.rowdata=rowdata

        window_width=600
        window_height=800
        window_xpos=0
        window_ypos=100
        namecell_width=150
        valuecellwidth=450

        self.dlg = JDialog()

        self.dlg.setSize(window_width, window_height)
        self.dlg.setLocation(window_xpos,window_ypos)
        self.dlg.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE)
        self.dlg.getContentPane().layout=GridLayout(0,1)

        self.debugpanel = JPanel()
        self.debugpanel.setLayout(FlowLayout(FlowLayout.CENTER, 5, 5))
        self.debugpanel.setEnabled(true)
        self.debugpanel.setFocusable(true)
        self.debugpanel.setMaximumSize(Dimension(window_width, window_height))
        self.debugpanel.setMinimumSize(Dimension(window_width, window_height))
        self.debugpanel.setOpaque(true)
        self.debugpanel.setPreferredSize(Dimension(window_width, window_height))


        resultsTableData = [
        ]
        colNames = ['<HTML><B>Name</B></HTML>',
                    '<HTML><B>Value</B></HTML>',
                    ]
        dataModel2 = DefaultTableModel(resultsTableData, colNames)

        self.debugtable = JTable(dataModel2)
        self.debugtable.setAutoCreateRowSorter(true)
        self.debugtable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF)
        self.debugtable.setBackground(Color(-1444168))
        self.debugtable.setFillsViewportHeight(true)
        self.debugtable.setForeground(Color(0,0,0))
        self.debugtable.setGridColor(Color(193,193,153))
        self.debugtable.setShowGrid(true)
        # self.debugtable.setSelectionForeground(Color(-16711679))
        self.debugtable.setSelectionBackground(Color(233,233,71))
        self.debugtable.setSelectionForeground(Color(0,0,255))

        self.debugtable.setRowHeight(24)
        self.debugtable.setRowSelectionAllowed(true);


        self.debugtable.getColumnModel().getColumn(0).setPreferredWidth(namecell_width)  #Variable Name
        self.debugtable.getColumnModel().getColumn(1).setPreferredWidth(valuecellwidth)  #Value of Variable

        self.debugtable.setAutoCreateRowSorter(0) #Sort on column zero Variable Name


        self.scrollPanel1 = JScrollPane()
        self.scrollPanel1.setPreferredSize(Dimension(window_width,window_height))
        self.scrollPanel1.getViewport().setView((self.debugtable))

        self.debugpanel.add(self.scrollPanel1)

        self.dlg.add(self.debugpanel)


        datamodel=self.debugtable.getModel()

        for row in self.rowdata:
            datamodel.addRow(row)

        mouseAdapter=tableMouseListener(self.debugtable)
        self.debugtable.addMouseListener(mouseAdapter)
        self.debugtable.addKeyListener(Tap(self.debugtable))

        self.dlg.setTitle(self.title)

        self.dlg.setModal(true)
        self.dlg.show()
        self.dlg.toFront()

    def close(self):
        self.dlg.setVisible(false)
        self.dispose()
        self.dlg.setVisible(false)

# --------------------------------
class Tap(KeyAdapter):
    # --------------------------------
    def __init__(self, table):
        self.table = table

    def keyPressed(self, event):
        global _debug

        keyCode = event.getKeyCode()

        if KeyEvent.VK_V == keyCode:
            clickedrow=self.table.getSelectedRow()
            datamodel = self.table.getModel()
            name=datamodel.getValueAt(clickedrow, 0)
            value=datamodel.getValueAt(clickedrow, 1).strip()
            showit(name,value)
            event.consume() # AVOID propagation to other key listeners

        if KeyEvent.VK_Q == keyCode:
            # quit execution
            _debug=false
            print "DEBUG ABORTED"
            event.consume() # AVOID propagation to other key listeners



#--------------------------------
class tableMouseListener(MouseAdapter):
    # --------------------------------
    def __init__(self, table):
        self.table = table

    def mousePressed(self, e):
        # does nothing at the moment

        numRows = self.table.rowCount
        numCols = self.table.columnCount
        model = self.table.model

        clickedrow=self.table.getSelectedRow()
        datamodel = self.table.getModel()
        name=datamodel.getValueAt(clickedrow, 0)
        value=datamodel.getValueAt(clickedrow, 1).strip()
        showit(name,value)

#=======================================================================================
#   END OF DEBUGGER CODE
#=======================================================================================


#=======================================================================================
#   PLACE YOUR SCRIPT HERE
#=======================================================================================

# SAMPLE SCRIPT WITH DEBUG COMMANDS
a_int=1
a_float=123.00
b="Letter B"
array1=["123",4,"DEF",5,["1","2"]]
array2=["ABCDEF","GHIJK","JKLMN","OPQRST",["Z","X"]]
testdict1={
    "keya":1,
    "keyb":1234.0,
    "keyc":'abcedf',
    "keyd":['aa','bb','cc'],
    "keye":{'k1':1,'k2':2,'k3':'defghij'},
}
testdict2={
    "keya":1,
    "keyb":1234.0,
    "keyc":'abcedf',
}

dbg("clear")

_vars=locals()
dbg("stop")
dbg("break", refinfo='line 264')

print "do stuff.."
print "do stuff.."
print "do stuff.."
print "do stuff.."
print "do stuff.."
a_int=2

dbg("resume")
_vars=locals()
dbg("break", refinfo='line 274')

print "do more stuff.."
print "do more stuff.."
print "do more stuff.."
print "do more stuff.."
print "do more stuff.."
print "do more stuff.."
a_int=3
z=33

_vars=locals()
dbg("break", refinfo='line 286')

print "do even more stuff.."
print "do even more stuff.."
print "do even more stuff.."
print "do even more stuff.."
print "do even more stuff.."

#=======================
# END OF ADDebugger CODE
#=======================
`
Last edited by adxsoft on Sun Jan 27, 2019 5:30 am, edited 1 time in total.

bogs
Posts: 5435
Joined: Sat Feb 25, 2017 10:45 pm

Re: Answer command and Javascript

Post by bogs » Sat Jan 26, 2019 12:47 pm

Hi adxsoft ,

Not for nothing, and while I don't have an answer to your immediate question, I would suggest that if your going to post a block of code that long, you wrap it in the 'Code display' tags (the button just above the post composition box that looks like [</>]) so that it doesn't take up so much space on screen.

If you edit your post, you can do this simply by going to the line before the first line of code and typing in
Selection_001.png
code!
Selection_001.png (2.39 KiB) Viewed 2909 times
While this isn't necessary for small runs of code, on large ones like yours the resulting block keeps the place a little neater :D

Good luck solving the issue!
Image

[-hh]
VIP Livecode Opensource Backer
VIP Livecode Opensource Backer
Posts: 2262
Joined: Thu Feb 28, 2013 11:52 pm
Location: Göttingen, DE

Re: Answer command and Javascript

Post by [-hh] » Sat Jan 26, 2019 8:04 pm

This has nothing to do with javaScript, string is string, it doesn't care which language it contains.

You determine the line width by your "===" lines.
But LC does word wrapping, no number of chars wrapping. At which number of chars should it break? You can easily implement this by yourself...

Answering your current string works here. The box is at about 1024 px wide.
(Click the screenshot to enlarge it)
Attachments
answer.png
shiftLock happens

adxsoft
Posts: 26
Joined: Wed Apr 11, 2018 12:25 pm

Re: Answer command and Javascript

Post by adxsoft » Sun Jan 27, 2019 5:36 am

Hi bogs .. tsk for advice re code tags I've now updated the post which is now much smaller

bogs
Posts: 5435
Joined: Sat Feb 25, 2017 10:45 pm

Re: Answer command and Javascript

Post by bogs » Sun Jan 27, 2019 11:45 am

Very much better, thank you adxsoft. As a side benefit, anyone needing to copy all that can now just click the [select all] link and not worry about missing some of it :wink:
Image

Post Reply

Return to “Talking LiveCode”