code
stringlengths 501
5.19M
| package
stringlengths 2
81
| path
stringlengths 9
304
| filename
stringlengths 4
145
|
---|---|---|---|
SequenceTable
-------------
A sequence table can be used if we need to provide a table for a sequence
of items instead of a mapping. Define the same sequence of items we used before
we added the other 1000 items:
>>> from z3c.table.testing import Content
>>> dataSequence = []
>>> dataSequence.append(Content('Zero', 0))
>>> dataSequence.append(Content('First', 1))
>>> dataSequence.append(Content('Second', 2))
>>> dataSequence.append(Content('Third', 3))
>>> dataSequence.append(Content('Fourth', 4))
>>> dataSequence.append(Content('Fifth', 5))
>>> dataSequence.append(Content('Sixth', 6))
>>> dataSequence.append(Content('Seventh', 7))
>>> dataSequence.append(Content('Eighth', 8))
>>> dataSequence.append(Content('Ninth', 9))
>>> dataSequence.append(Content('Tenth', 10))
>>> dataSequence.append(Content('Eleventh', 11))
>>> dataSequence.append(Content('Twelfth', 12))
>>> dataSequence.append(Content('Thirteenth', 13))
>>> dataSequence.append(Content('Fourteenth', 14))
>>> dataSequence.append(Content('Fifteenth', 15))
>>> dataSequence.append(Content('Sixteenth', 16))
>>> dataSequence.append(Content('Seventeenth', 17))
>>> dataSequence.append(Content('Eighteenth', 18))
>>> dataSequence.append(Content('Nineteenth', 19))
>>> dataSequence.append(Content('Twentieth', 20))
Now let's define a new SequenceTable:
>>> from z3c.table import table, column
>>> from z3c.table.testing import (TitleColumn, NumberColumn, cellRenderer,
... headCellRenderer)
>>> class SequenceTable(table.SequenceTable):
...
... def setUpColumns(self):
... return [
... column.addColumn(self, TitleColumn, u'title',
... cellRenderer=cellRenderer,
... headCellRenderer=headCellRenderer,
... weight=1),
... column.addColumn(self, NumberColumn, name=u'number',
... weight=2, header=u'Number')
... ]
Now we can create our table adapting our sequence:
>>> from zope.publisher.browser import TestRequest
>>> sequenceRequest = TestRequest(form={'table-batchStart': '0',
... 'table-sortOn': 'table-number-1'})
>>> sequenceTable = SequenceTable(dataSequence, sequenceRequest)
>>> sequenceTable.cssClassSortedOn = None
We also need to give the table a location and a name like we normally setup
in traversing:
>>> from z3c.table.testing import Container
>>> container = Container()
>>> root['container-1'] = container
>>> sequenceTable.__parent__ = container
>>> sequenceTable.__name__ = u'sequenceTable.html'
We need to configure our batch provider for the next step first. See the
section ``BatchProvider`` below for more infos about batch rendering:
>>> from zope.configuration.xmlconfig import XMLConfig
>>> import z3c.table
>>> import zope.component
>>> XMLConfig('meta.zcml', zope.component)()
>>> XMLConfig('configure.zcml', z3c.table)()
And update and render the sequence table:
>>> sequenceTable.update()
>>> print(sequenceTable.render())
<table>
<thead>
<tr>
<th>My items</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>Zero item</td>
<td>number: 0</td>
</tr>
<tr>
<td>First item</td>
<td>number: 1</td>
</tr>
<tr>
<td>Second item</td>
<td>number: 2</td>
</tr>
<tr>
<td>Third item</td>
<td>number: 3</td>
</tr>
<tr>
<td>Fourth item</td>
<td>number: 4</td>
</tr>
<tr>
<td>Fifth item</td>
<td>number: 5</td>
</tr>
<tr>
<td>Sixth item</td>
<td>number: 6</td>
</tr>
<tr>
<td>Seventh item</td>
<td>number: 7</td>
</tr>
<tr>
<td>Eighth item</td>
<td>number: 8</td>
</tr>
<tr>
<td>Ninth item</td>
<td>number: 9</td>
</tr>
<tr>
<td>Tenth item</td>
<td>number: 10</td>
</tr>
<tr>
<td>Eleventh item</td>
<td>number: 11</td>
</tr>
<tr>
<td>Twelfth item</td>
<td>number: 12</td>
</tr>
<tr>
<td>Thirteenth item</td>
<td>number: 13</td>
</tr>
<tr>
<td>Fourteenth item</td>
<td>number: 14</td>
</tr>
<tr>
<td>Fifteenth item</td>
<td>number: 15</td>
</tr>
<tr>
<td>Sixteenth item</td>
<td>number: 16</td>
</tr>
<tr>
<td>Seventeenth item</td>
<td>number: 17</td>
</tr>
<tr>
<td>Eighteenth item</td>
<td>number: 18</td>
</tr>
<tr>
<td>Nineteenth item</td>
<td>number: 19</td>
</tr>
<tr>
<td>Twentieth item</td>
<td>number: 20</td>
</tr>
</tbody>
</table>
As you can see, the items get rendered based on a data sequence. Now we set
the ``start batch at`` size to ``5``:
>>> sequenceTable.startBatchingAt = 5
And the ``batchSize`` to ``5``:
>>> sequenceTable.batchSize = 5
Now we can update and render the table again. But you will see that we only get
a table size of 5 rows:
>>> sequenceTable.update()
>>> print(sequenceTable.render())
<table>
<thead>
<tr>
<th>My items</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>Zero item</td>
<td>number: 0</td>
</tr>
<tr>
<td>First item</td>
<td>number: 1</td>
</tr>
<tr>
<td>Second item</td>
<td>number: 2</td>
</tr>
<tr>
<td>Third item</td>
<td>number: 3</td>
</tr>
<tr>
<td>Fourth item</td>
<td>number: 4</td>
</tr>
</tbody>
</table>
And we set the sort order to ``reverse`` even if we use batching:
>>> sequenceTable.sortOrder = u'reverse'
>>> sequenceTable.update()
>>> print(sequenceTable.render())
<table>
<thead>
<tr>
<th>My items</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>Twentieth item</td>
<td>number: 20</td>
</tr>
<tr>
<td>Nineteenth item</td>
<td>number: 19</td>
</tr>
<tr>
<td>Eighteenth item</td>
<td>number: 18</td>
</tr>
<tr>
<td>Seventeenth item</td>
<td>number: 17</td>
</tr>
<tr>
<td>Sixteenth item</td>
<td>number: 16</td>
</tr>
</tbody>
</table>
| z3c.table | /z3c.table-3.0.tar.gz/z3c.table-3.0/src/z3c/table/sequence.rst | sequence.rst |
import zope.contentprovider.interfaces
import zope.interface
import zope.schema
from z3c.table.i18n import _
class IValues(zope.interface.Interface):
"""Table value adapter."""
values = zope.interface.Attribute("Iterable table row data sequence.")
class ITable(zope.contentprovider.interfaces.IContentProvider):
"""Table provider"""
columnCounter = zope.schema.Int(
title=_("Column counter"),
description=_("Column counter"),
default=0
)
columnIndexById = zope.interface.Attribute(
"Dict of column index number by id"
)
columnByName = zope.interface.Attribute("Dict of columns by name")
columns = zope.interface.Attribute("Sequence of columns")
rows = zope.interface.Attribute("Sequence of rows")
selectedItems = zope.interface.Attribute("Sequence of selected items")
# customize this part if needed
prefix = zope.schema.BytesLine(
title=_("Prefix"),
description=_("The prefix of the table used to uniquely identify it."),
default=b"table",
)
# css classes
cssClasses = zope.interface.Attribute(
"Dict of element name and CSS classes"
)
# additional (row) css
cssClassEven = zope.schema.TextLine(
title="Even css row class",
description=("CSS class for even rows."),
default="even",
required=False,
)
cssClassOdd = zope.schema.TextLine(
title="Odd css row class",
description=("CSS class for odd rows."),
default="odd",
required=False,
)
cssClassSelected = zope.schema.TextLine(
title="Selected css row class",
description=("CSS class for selected rows."),
default="selected",
required=False,
)
# sort attributes
sortOn = zope.schema.Int(
title=_("Sort on table index"),
description=_("Sort on table index"),
default=0,
)
sortOrder = zope.schema.TextLine(
title=_("Sort order"),
description=_("Row sort order"),
default="ascending",
)
reverseSortOrderNames = zope.schema.List(
title="Selected css row class",
description=("CSS class for selected rows."),
value_type=zope.schema.TextLine(
title=_("Reverse sort order name"),
description=_("Reverse sort order name"),
),
default=["descending", "reverse", "down"],
required=False,
)
# batch attributes
batchStart = zope.schema.Int(
title=_("Batch start index"),
description=_("Index the batch starts with"),
default=0,
)
batchSize = zope.schema.Int(
title=_("Batch size"),
description=_("The batch size"),
default=50
)
startBatchingAt = zope.schema.Int(
title=_("Batch start size"),
description=_("The minimal size the batch starts to get used"),
default=50,
)
values = zope.interface.Attribute("Iterable table row data sequence.")
def getCSSClass(element, cssClass=None):
"""Return the css class if any or an empty string."""
def setUpColumns():
"""Setup table column renderer."""
def updateColumns():
"""Update columns."""
def initColumns():
"""Initialize columns definitions used by the table"""
def orderColumns():
"""Order columns."""
def setUpRow(item):
"""Setup table row."""
def setUpRows():
"""Setup table rows."""
def getSortOn():
"""Return sort on column id."""
def getSortOrder():
"""Return sort order criteria."""
def sortRows():
"""Sort rows."""
def getBatchSize():
"""Return the batch size."""
def getBatchStart():
"""Return the batch start index."""
def batchRows():
"""Batch rows."""
def isSelectedRow(row):
"""Return `True for selected row."""
def renderTable():
"""Render the table."""
def renderHead():
"""Render the thead."""
def renderHeadRow():
"""Render the table header rows."""
def renderHeadCell(column):
"""Setup the table header rows."""
def renderBody():
"""Render the table body."""
def renderRows():
"""Render the table body rows."""
def renderRow(row, cssClass=None):
"""Render the table body rows."""
def renderCell(item, column, colspan=0):
"""Render a single table body cell."""
def render():
"""Plain render method without keyword arguments."""
class ISequenceTable(ITable):
"""Sequence table adapts a sequence as context.
This table can be used for adapting a z3c.indexer.search.ResultSet or
z3c.batching.batch.Batch instance as context. Batch which wraps a
ResultSet sequence.
"""
class IColumn(zope.interface.Interface):
"""Column provider"""
id = zope.schema.TextLine(
title=_("Id"),
description=_("The column id"),
default=None
)
# customize this part if needed
colspan = zope.schema.Int(
title=_("Colspan"),
description=_("The colspan value"),
default=0
)
weight = zope.schema.Int(
title=_("Weight"),
description=_("The column weight"),
default=0
)
header = zope.schema.TextLine(
title=_("Header name"),
description=_("The header name"),
default=""
)
cssClasses = zope.interface.Attribute(
"Dict of element name and CSS classes"
)
def getColspan(item):
"""Colspan value based on the given item."""
def renderHeadCell():
"""Render the column header label."""
def renderCell(item):
"""Render the column content."""
class INoneCell(IColumn):
"""None cell used for colspan."""
class IBatchProvider(zope.contentprovider.interfaces.IContentProvider):
"""Batch content provider"""
def renderBatchLink(batch, cssClass=None):
"""Render batch links."""
def render():
"""Plain render method without keyword arguments."""
class IColumnHeader(zope.interface.Interface):
"""Multi-adapter for header rendering."""
def update():
"""Override this method in subclasses if required"""
def render():
"""Return the HTML output for the header
Make sure HTML special chars are escaped.
Override this method in subclasses"""
def getQueryStringArgs():
"""
Because the header will most often be used to add links for sorting the
columns it may also be necessary to collect other query arguments from
the request.
The initial use case here is to maintain a search term.
""" | z3c.table | /z3c.table-3.0.tar.gz/z3c.table-3.0/src/z3c/table/interfaces.py | interfaces.py |
=============
Table Columns
=============
Let's show the different columns we offer by default. But first take a look at
the README.txt which explains the Table and Column concepts.
Sample data setup
-----------------
Let's create a sample container that we can use as our iterable context:
>>> from zope.container import btree
>>> class Container(btree.BTreeContainer):
... """Sample container."""
>>> container = Container()
>>> root['container'] = container
and create a sample content object that we use as container item:
>>> class Content(object):
... """Sample content."""
... def __init__(self, title, number, email):
... self.title = title
... self.number = number
... self.email = email
Now setup some items:
>>> container[u'zero'] = Content('Zero', 0, '[email protected]')
>>> container[u'first'] = Content('First', 1, '[email protected]')
>>> container[u'second'] = Content('Second', 2, '[email protected]')
>>> container[u'third'] = Content('Third', 3, '[email protected]')
>>> container[u'fourth'] = Content('Fourth', 4, None)
Let's also create a simple number sortable column:
>>> from z3c.table import column
>>> class NumberColumn(column.Column):
...
... header = u'Number'
... weight = 20
...
... def getSortKey(self, item):
... return item.number
...
... def renderCell(self, item):
... return 'number: %s' % item.number
NameColumn
----------
Let's define a table using the NameColumn:
>>> from z3c.table import table
>>> class NameTable(table.Table):
... cssClassSortedOn = None
...
... def setUpColumns(self):
... return [
... column.addColumn(self, column.NameColumn, u'name',
... weight=1),
... column.addColumn(self, NumberColumn, name=u'number',
... weight=2, header=u'Number')
... ]
Now create, update and render our table and you can see that the NameColumn
renders the name of the item using the zope.traversing.api.getName() concept:
>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest()
>>> nameTable = NameTable(container, request)
>>> nameTable.update()
>>> print(nameTable.render())
<table>
<thead>
<tr>
<th>Name</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>first</td>
<td>number: 1</td>
</tr>
<tr>
<td>fourth</td>
<td>number: 4</td>
</tr>
<tr>
<td>second</td>
<td>number: 2</td>
</tr>
<tr>
<td>third</td>
<td>number: 3</td>
</tr>
<tr>
<td>zero</td>
<td>number: 0</td>
</tr>
</tbody>
</table>
RadioColumn
-----------
Let's define a table using the RadioColumn:
>>> class RadioTable(table.Table):
... cssClassSortedOn = None
...
... def setUpColumns(self):
... return [
... column.addColumn(self, column.RadioColumn, u'radioColumn',
... weight=1),
... column.addColumn(self, NumberColumn, name=u'number',
... weight=2, header=u'Number')
... ]
Now create, update and render our table:
>>> request = TestRequest()
>>> radioTable = RadioTable(container, request)
>>> radioTable.update()
>>> print(radioTable.render())
<table>
<thead>
<tr>
<th>X</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="radio" class="radio-widget" name="table-radioColumn-0-selectedItem" value="first" /></td>
<td>number: 1</td>
</tr>
<tr>
<td><input type="radio" class="radio-widget" name="table-radioColumn-0-selectedItem" value="fourth" /></td>
<td>number: 4</td>
</tr>
<tr>
<td><input type="radio" class="radio-widget" name="table-radioColumn-0-selectedItem" value="second" /></td>
<td>number: 2</td>
</tr>
<tr>
<td><input type="radio" class="radio-widget" name="table-radioColumn-0-selectedItem" value="third" /></td>
<td>number: 3</td>
</tr>
<tr>
<td><input type="radio" class="radio-widget" name="table-radioColumn-0-selectedItem" value="zero" /></td>
<td>number: 0</td>
</tr>
</tbody>
</table>
As you can see, we can force to render the radio input field as selected with a
given request value:
>>> radioRequest = TestRequest(form={'table-radioColumn-0-selectedItem': 'third'})
>>> radioTable = RadioTable(container, radioRequest)
>>> radioTable.update()
>>> print(radioTable.render())
<table>
<thead>
<tr>
<th>X</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="radio" class="radio-widget" name="table-radioColumn-0-selectedItem" value="first" /></td>
<td>number: 1</td>
</tr>
<tr>
<td><input type="radio" class="radio-widget" name="table-radioColumn-0-selectedItem" value="fourth" /></td>
<td>number: 4</td>
</tr>
<tr>
<td><input type="radio" class="radio-widget" name="table-radioColumn-0-selectedItem" value="second" /></td>
<td>number: 2</td>
</tr>
<tr>
<td><input type="radio" class="radio-widget" name="table-radioColumn-0-selectedItem" value="third" checked="checked" /></td>
<td>number: 3</td>
</tr>
<tr>
<td><input type="radio" class="radio-widget" name="table-radioColumn-0-selectedItem" value="zero" /></td>
<td>number: 0</td>
</tr>
</tbody>
</table>
CheckBoxColumn
--------------
Let's define a table using the RadioColumn:
>>> class CheckBoxTable(table.Table):
... cssClassSortedOn = None
...
... def setUpColumns(self):
... return [
... column.addColumn(self, column.CheckBoxColumn, u'checkBoxColumn',
... weight=1),
... column.addColumn(self, NumberColumn, name=u'number',
... weight=2, header=u'Number')
... ]
Now create, update and render our table:
>>> request = TestRequest()
>>> checkBoxTable = CheckBoxTable(container, request)
>>> checkBoxTable.update()
>>> print(checkBoxTable.render())
<table>
<thead>
<tr>
<th>X</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="table-checkBoxColumn-0-selectedItems" value="first" /></td>
<td>number: 1</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="table-checkBoxColumn-0-selectedItems" value="fourth" /></td>
<td>number: 4</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="table-checkBoxColumn-0-selectedItems" value="second" /></td>
<td>number: 2</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="table-checkBoxColumn-0-selectedItems" value="third" /></td>
<td>number: 3</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="table-checkBoxColumn-0-selectedItems" value="zero" /></td>
<td>number: 0</td>
</tr>
</tbody>
</table>
And again you can set force to render the checkbox input field as selected with
a given request value:
>>> checkBoxRequest = TestRequest(form={'table-checkBoxColumn-0-selectedItems':
... ['first', 'third']})
>>> checkBoxTable = CheckBoxTable(container, checkBoxRequest)
>>> checkBoxTable.update()
>>> print(checkBoxTable.render())
<table>
<thead>
<tr>
<th>X</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="table-checkBoxColumn-0-selectedItems" value="first" checked="checked" /></td>
<td>number: 1</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="table-checkBoxColumn-0-selectedItems" value="fourth" /></td>
<td>number: 4</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="table-checkBoxColumn-0-selectedItems" value="second" /></td>
<td>number: 2</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="table-checkBoxColumn-0-selectedItems" value="third" checked="checked" /></td>
<td>number: 3</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="table-checkBoxColumn-0-selectedItems" value="zero" /></td>
<td>number: 0</td>
</tr>
</tbody>
</table>
If you select a row, you can also give them an additional CSS style. This could
be used in combination with alternating ``even`` and ``odd`` styles:
>>> checkBoxRequest = TestRequest(form={'table-checkBoxColumn-0-selectedItems':
... ['first', 'third']})
>>> checkBoxTable = CheckBoxTable(container, checkBoxRequest)
>>> checkBoxTable.cssClasses = {'tr': 'tr'}
>>> checkBoxTable.cssClassSelected = u'selected'
>>> checkBoxTable.cssClassEven = u'even'
>>> checkBoxTable.cssClassOdd = u'odd'
>>> checkBoxTable.update()
>>> print(checkBoxTable.render())
<table>
<thead>
<tr class="tr">
<th>X</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr class="selected even tr">
<td><input type="checkbox" class="checkbox-widget" name="table-checkBoxColumn-0-selectedItems" value="first" checked="checked" /></td>
<td>number: 1</td>
</tr>
<tr class="odd tr">
<td><input type="checkbox" class="checkbox-widget" name="table-checkBoxColumn-0-selectedItems" value="fourth" /></td>
<td>number: 4</td>
</tr>
<tr class="even tr">
<td><input type="checkbox" class="checkbox-widget" name="table-checkBoxColumn-0-selectedItems" value="second" /></td>
<td>number: 2</td>
</tr>
<tr class="selected odd tr">
<td><input type="checkbox" class="checkbox-widget" name="table-checkBoxColumn-0-selectedItems" value="third" checked="checked" /></td>
<td>number: 3</td>
</tr>
<tr class="even tr">
<td><input type="checkbox" class="checkbox-widget" name="table-checkBoxColumn-0-selectedItems" value="zero" /></td>
<td>number: 0</td>
</tr>
</tbody>
</table>
Let's test the ``cssClassSelected`` without any other css class:
>>> checkBoxRequest = TestRequest(form={'table-checkBoxColumn-0-selectedItems':
... ['first', 'third']})
>>> checkBoxTable = CheckBoxTable(container, checkBoxRequest)
>>> checkBoxTable.cssClassSelected = u'selected'
>>> checkBoxTable.update()
>>> print(checkBoxTable.render())
<table>
<thead>
<tr>
<th>X</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr class="selected">
<td><input type="checkbox" class="checkbox-widget" name="table-checkBoxColumn-0-selectedItems" value="first" checked="checked" /></td>
<td>number: 1</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="table-checkBoxColumn-0-selectedItems" value="fourth" /></td>
<td>number: 4</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="table-checkBoxColumn-0-selectedItems" value="second" /></td>
<td>number: 2</td>
</tr>
<tr class="selected">
<td><input type="checkbox" class="checkbox-widget" name="table-checkBoxColumn-0-selectedItems" value="third" checked="checked" /></td>
<td>number: 3</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox-widget" name="table-checkBoxColumn-0-selectedItems" value="zero" /></td>
<td>number: 0</td>
</tr>
</tbody>
</table>
CreatedColumn
-------------
Let's define a table using the CreatedColumn:
>>> class CreatedColumnTable(table.Table):
... cssClassSortedOn = None
...
... def setUpColumns(self):
... return [
... column.addColumn(self, column.CreatedColumn, u'createdColumn',
... weight=1),
... ]
Now create, update and render our table. Note, we use a Dublin Core stub
adapter which only returns ``01/01/01 01:01`` as created date:
>>> request = TestRequest()
>>> createdColumnTable = CreatedColumnTable(container, request)
>>> createdColumnTable.update()
>>> print(createdColumnTable.render())
<table>
<thead>
<tr>
<th>Created</th>
</tr>
</thead>
<tbody>
<tr>
<td>01/01/01 01:01</td>
</tr>
<tr>
<td>01/01/01 01:01</td>
</tr>
<tr>
<td>01/01/01 01:01</td>
</tr>
<tr>
<td>01/01/01 01:01</td>
</tr>
<tr>
<td>01/01/01 01:01</td>
</tr>
</tbody>
</table>
ModifiedColumn
--------------
Let's define a table using the CreatedColumn:
>>> class ModifiedColumnTable(table.Table):
... cssClassSortedOn = None
...
... def setUpColumns(self):
... return [
... column.addColumn(self, column.ModifiedColumn,
... u'modifiedColumn', weight=1),
... ]
Now create, update and render our table. Note, we use a Dublin Core stub
adapter which only returns ``02/02/02 02:02`` as modified date:
>>> request = TestRequest()
>>> modifiedColumnTable = ModifiedColumnTable(container, request)
>>> modifiedColumnTable.update()
>>> print(modifiedColumnTable.render())
<table>
<thead>
<tr>
<th>Modified</th>
</tr>
</thead>
<tbody>
<tr>
<td>02/02/02 02:02</td>
</tr>
<tr>
<td>02/02/02 02:02</td>
</tr>
<tr>
<td>02/02/02 02:02</td>
</tr>
<tr>
<td>02/02/02 02:02</td>
</tr>
<tr>
<td>02/02/02 02:02</td>
</tr>
</tbody>
</table>
GetAttrColumn
-------------
The ``GetAttrColumn`` column is a handy column that retrieves the value from
the item by attribute access.
It also provides a ``defaultValue`` in case an exception happens.
>>> class GetTitleColumn(column.GetAttrColumn):
...
... attrName = 'title'
... defaultValue = u'missing'
>>> class GetAttrColumnTable(table.Table):
... cssClassSortedOn = None
...
... def setUpColumns(self):
... return [
... column.addColumn(self, GetTitleColumn, u'title'),
... ]
Render and update the table:
>>> request = TestRequest()
>>> getAttrColumnTable = GetAttrColumnTable(container, request)
>>> getAttrColumnTable.update()
>>> print(getAttrColumnTable.render())
<table>
<thead>
<tr>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>First</td>
</tr>
<tr>
<td>Fourth</td>
</tr>
<tr>
<td>Second</td>
</tr>
<tr>
<td>Third</td>
</tr>
<tr>
<td>Zero</td>
</tr>
</tbody>
</table>
If we use a non-existing Attribute, we do not raise an AttributeError, we will
get the default value:
>>> class UndefinedAttributeColumn(column.GetAttrColumn):
...
... attrName = 'undefined'
... defaultValue = u'missing'
>>> class GetAttrColumnTable(table.Table):
... cssClassSortedOn = None
...
... def setUpColumns(self):
... return [
... column.addColumn(self, UndefinedAttributeColumn, u'missing'),
... ]
Render and update the table:
>>> request = TestRequest()
>>> getAttrColumnTable = GetAttrColumnTable(container, request)
>>> getAttrColumnTable.update()
>>> print(getAttrColumnTable.render())
<table>
<thead>
<tr>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>missing</td>
</tr>
<tr>
<td>missing</td>
</tr>
<tr>
<td>missing</td>
</tr>
<tr>
<td>missing</td>
</tr>
<tr>
<td>missing</td>
</tr>
</tbody>
</table>
A missing ``attrName`` in ``GetAttrColumn`` would also end in return the
``defaultValue``:
>>> class BadAttributeColumn(column.GetAttrColumn):
...
... defaultValue = u'missing'
>>> firstItem = container[u'first']
>>> simpleTable = table.Table(container, request)
>>> badColumn = column.addColumn(simpleTable, BadAttributeColumn, u'bad')
>>> badColumn.renderCell(firstItem)
u'missing'
If we try to access a protected attribute the object raises an ``Unauthorized``.
In this case we also return the defaultValue. Let's setup an object which
raises such an error if we access the title:
>>> from zope.security.interfaces import Unauthorized
>>> class ProtectedItem(object):
...
... @property
... def forbidden(self):
... raise Unauthorized('forbidden')
Setup and test the item:
>>> protectedItem = ProtectedItem()
>>> protectedItem.forbidden
Traceback (most recent call last):
...
Unauthorized: forbidden
Now define a column:
>>> class ForbiddenAttributeColumn(column.GetAttrColumn):
...
... attrName = 'forbidden'
... defaultValue = u'missing'
And test the attribute access:
>>> simpleTable = table.Table(container, request)
>>> badColumn = column.addColumn(simpleTable, ForbiddenAttributeColumn, u'x')
>>> badColumn.renderCell(protectedItem)
u'missing'
GetItemColumn
-------------
The ``GetItemColumn`` column is a handy column that retrieves the value from
the item by index or key access. That means the item can be a tuple, list, dict
or anything that implements that.
It also provides a ``defaultValue`` in case an exception happens.
Dict-ish
.........
>>> sampleDictData = [
... dict(name='foo', value=1),
... dict(name='bar', value=7),
... dict(name='moo', value=42),]
>>> class GetDictColumnTable(table.Table):
... cssClassSortedOn = None
...
... def setUpColumns(self):
... return [
... column.addColumn(self, column.GetItemColumn, u'name',
... header=u'Name',
... idx='name', defaultValue='missing'),
... column.addColumn(self, column.GetItemColumn, u'value',
... header=u'Value',
... idx='value', defaultValue='missing'),
... ]
... @property
... def values(self):
... return sampleDictData
Render and update the table:
>>> request = TestRequest()
>>> getDictColumnTable = GetDictColumnTable(sampleDictData, request)
>>> getDictColumnTable.update()
>>> print(getDictColumnTable.render())
<table>
<thead>
<tr>
<th>Name</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>bar</td>
<td>7</td>
</tr>
<tr>
<td>foo</td>
<td>1</td>
</tr>
<tr>
<td>moo</td>
<td>42</td>
</tr>
</tbody>
</table>
If we use a non-existing index/key, we do not raise an exception, we will
get the default value:
>>> class GetDictColumnTable(table.Table):
... cssClassSortedOn = None
...
... def setUpColumns(self):
... return [
... column.addColumn(self, column.GetItemColumn, u'name',
... idx='not-existing', defaultValue='missing'),
... ]
... @property
... def values(self):
... return sampleDictData
Render and update the table:
>>> request = TestRequest()
>>> getDictColumnTable = GetDictColumnTable(container, request)
>>> getDictColumnTable.update()
>>> print(getDictColumnTable.render())
<table>
<thead>
<tr>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>missing</td>
</tr>
<tr>
<td>missing</td>
</tr>
<tr>
<td>missing</td>
</tr>
</tbody>
</table>
A missing ``idx`` in ``GetItemColumn`` would also end in return the
``defaultValue``:
>>> class BadIdxColumn(column.GetItemColumn):
...
... defaultValue = u'missing'
>>> firstItem = sampleDictData[0]
>>> simpleTable = table.Table(sampleDictData, request)
>>> badColumn = column.addColumn(simpleTable, BadIdxColumn, u'bad')
>>> badColumn.renderCell(firstItem)
u'missing'
Tuple/List-ish
...............
>>> sampleTupleData = [
... (50, 'bar'),
... (42, 'cent'),
... (7, 'bild'),]
>>> class GetTupleColumnTable(table.Table):
... cssClassSortedOn = None
...
... def setUpColumns(self):
... return [
... column.addColumn(self, column.GetItemColumn, u'name',
... header=u'Name',
... idx=1, defaultValue='missing'),
... column.addColumn(self, column.GetItemColumn, u'value',
... header=u'Value',
... idx=0, defaultValue='missing'),
... ]
... @property
... def values(self):
... return sampleTupleData
Render and update the table:
>>> request = TestRequest()
>>> getTupleColumnTable = GetTupleColumnTable(sampleTupleData, request)
>>> getTupleColumnTable.update()
>>> print(getTupleColumnTable.render())
<table>
<thead>
<tr>
<th>Name</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>bar</td>
<td>50</td>
</tr>
<tr>
<td>bild</td>
<td>7</td>
</tr>
<tr>
<td>cent</td>
<td>42</td>
</tr>
</tbody>
</table>
If we use a non-existing index/key, we do not raise an exception, we will
get the default value:
>>> class GetTupleColumnTable(table.Table):
... cssClassSortedOn = None
...
... def setUpColumns(self):
... return [
... column.addColumn(self, column.GetItemColumn, u'name',
... idx=42, defaultValue='missing'),
... ]
... @property
... def values(self):
... return sampleTupleData
Render and update the table:
>>> request = TestRequest()
>>> getTupleColumnTable = GetTupleColumnTable(container, request)
>>> getTupleColumnTable.update()
>>> print(getTupleColumnTable.render())
<table>
<thead>
<tr>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>missing</td>
</tr>
<tr>
<td>missing</td>
</tr>
<tr>
<td>missing</td>
</tr>
</tbody>
</table>
A missing ``idx`` in ``GetItemColumn`` would also end in return the
``defaultValue``:
>>> class BadIdxColumn(column.GetItemColumn):
...
... defaultValue = u'missing'
>>> firstItem = sampleTupleData[0]
>>> simpleTable = table.Table(sampleTupleData, request)
>>> badColumn = column.addColumn(simpleTable, BadIdxColumn, u'bad')
>>> badColumn.renderCell(firstItem)
u'missing'
GetAttrFormatterColumn
----------------------
The ``GetAttrFormatterColumn`` column is a get attr column which is able to
format the value. Let's use the Dublin Core adapter for our sample:
>>> from zope.dublincore.interfaces import IZopeDublinCore
>>> class GetCreatedColumn(column.GetAttrFormatterColumn):
...
... def getValue(self, item):
... dc = IZopeDublinCore(item, None)
... return dc.created
>>> class GetAttrFormatterColumnTable(table.Table):
... cssClassSortedOn = None
...
... def setUpColumns(self):
... return [
... column.addColumn(self, GetCreatedColumn, u'created'),
... ]
Render and update the table:
>>> request = TestRequest()
>>> getAttrFormatterColumnTable = GetAttrFormatterColumnTable(container,
... request)
>>> getAttrFormatterColumnTable.update()
>>> print(getAttrFormatterColumnTable.render())
<table>
<thead>
<tr>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>2001 1 1 01:01:01 </td>
</tr>
<tr>
<td>2001 1 1 01:01:01 </td>
</tr>
<tr>
<td>2001 1 1 01:01:01 </td>
</tr>
<tr>
<td>2001 1 1 01:01:01 </td>
</tr>
<tr>
<td>2001 1 1 01:01:01 </td>
</tr>
</tbody>
</table>
We can also change the formatter settings in such a column:
>>> class LongCreatedColumn(column.GetAttrFormatterColumn):
...
... formatterCategory = u'dateTime'
... formatterLength = u'long'
... formatterCalendar = u'gregorian'
...
... def getValue(self, item):
... dc = IZopeDublinCore(item, None)
... return dc.created
>>> class LongFormatterColumnTable(table.Table):
... cssClassSortedOn = None
...
... def setUpColumns(self):
... return [
... column.addColumn(self, LongCreatedColumn, u'created'),
... ]
Render and update the table:
>>> request = TestRequest()
>>> longFormatterColumnTable = LongFormatterColumnTable(container,
... request)
>>> longFormatterColumnTable.update()
>>> print(longFormatterColumnTable.render())
<table>
<thead>
<tr>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>2001 1 1 01:01:01 +000</td>
</tr>
<tr>
<td>2001 1 1 01:01:01 +000</td>
</tr>
<tr>
<td>2001 1 1 01:01:01 +000</td>
</tr>
<tr>
<td>2001 1 1 01:01:01 +000</td>
</tr>
<tr>
<td>2001 1 1 01:01:01 +000</td>
</tr>
</tbody>
</table>
EMailColumn
-----------
The ``EMailColumn`` column is ``GetAttrColumn`` which is used to
display a mailto link. By default in the link content the e-mail
address is displayed, too.
>>> class EMailColumn(column.EMailColumn):
...
... attrName = 'email'
... defaultValue = u'missing'
>>> class EMailColumnTable(table.Table):
... cssClassSortedOn = None
...
... def setUpColumns(self):
... return [
... column.addColumn(self, EMailColumn, u'email'),
... ]
When a cell does not contain an e-mail address, the ``defaultValue``
is rendered:
>>> request = TestRequest()
>>> eMailColumnTable = EMailColumnTable(container, request)
>>> eMailColumnTable.update()
>>> print(eMailColumnTable.render())
<table>
<thead>
<tr>
<th>E-Mail</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="mailto:[email protected]">[email protected]</a></td>
</tr>
<tr>
<td><a href="mailto:[email protected]">[email protected]</a></td>
</tr>
<tr>
<td><a href="mailto:[email protected]">[email protected]</a></td>
</tr>
<tr>
<td><a href="mailto:[email protected]">[email protected]</a></td>
</tr>
<tr>
<td>missing</td>
</tr>
</tbody>
</table>
The link content can be overwriten by setting the ``linkContent`` attribute:
>>> class StaticEMailColumn(column.EMailColumn):
...
... attrName = 'email'
... defaultValue = u'missing'
... linkContent = 'Mail me'
>>> class StaticEMailColumnTable(table.Table):
... cssClassSortedOn = None
...
... def setUpColumns(self):
... return [
... column.addColumn(self, StaticEMailColumn, u'mail'),
... ]
Render and update the table:
>>> request = TestRequest()
>>> staticEMailColumnTable = StaticEMailColumnTable(container, request)
>>> staticEMailColumnTable.update()
>>> print(staticEMailColumnTable.render())
<table>
<thead>
<tr>
<th>E-Mail</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="mailto:[email protected]">Mail me</a></td>
</tr>
<tr>
<td><a href="mailto:[email protected]">Mail me</a></td>
</tr>
<tr>
<td><a href="mailto:[email protected]">Mail me</a></td>
</tr>
<tr>
<td><a href="mailto:[email protected]">Mail me</a></td>
</tr>
<tr>
<td>missing</td>
</tr>
</tbody>
</table>
LinkColumn
----------
Let's define a table using the LinkColumn. This column allows us to write
columns which can point to a page with the item as context:
>>> class MyLinkColumns(column.LinkColumn):
... linkName = 'myLink.html'
... linkTarget = '_blank'
... linkCSS = 'myClass'
... linkTitle = 'Click >'
>>> class MyLinkTable(table.Table):
... cssClassSortedOn = None
...
... def setUpColumns(self):
... return [
... column.addColumn(self, MyLinkColumns, u'link',
... weight=1),
... column.addColumn(self, NumberColumn, name=u'number',
... weight=2, header=u'Number')
... ]
Now create, update and render our table:
>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest()
>>> myLinkTable = MyLinkTable(container, request)
>>> myLinkTable.__parent__ = container
>>> myLinkTable.__name__ = u'myLinkTable.html'
>>> myLinkTable.update()
>>> print(myLinkTable.render())
<table>
<thead>
<tr>
<th>Name</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="http://127.0.0.1/container/first/myLink.html" target="_blank" class="myClass" title="Click >">first</a></td>
<td>number: 1</td>
</tr>
<tr>
<td><a href="http://127.0.0.1/container/fourth/myLink.html" target="_blank" class="myClass" title="Click >">fourth</a></td>
<td>number: 4</td>
</tr>
<tr>
<td><a href="http://127.0.0.1/container/second/myLink.html" target="_blank" class="myClass" title="Click >">second</a></td>
<td>number: 2</td>
</tr>
<tr>
<td><a href="http://127.0.0.1/container/third/myLink.html" target="_blank" class="myClass" title="Click >">third</a></td>
<td>number: 3</td>
</tr>
<tr>
<td><a href="http://127.0.0.1/container/zero/myLink.html" target="_blank" class="myClass" title="Click >">zero</a></td>
<td>number: 0</td>
</tr>
</tbody>
</table>
ContentsLinkColumn
------------------
There are some predefined link columns available. This one will generate a
``contents.html`` link for each item:
>>> class ContentsLinkTable(table.Table):
... cssClassSortedOn = None
...
... def setUpColumns(self):
... return [
... column.addColumn(self, column.ContentsLinkColumn, u'link',
... weight=1),
... column.addColumn(self, NumberColumn, name=u'number',
... weight=2, header=u'Number')
... ]
>>> contentsLinkTable = ContentsLinkTable(container, request)
>>> contentsLinkTable.__parent__ = container
>>> contentsLinkTable.__name__ = u'contentsLinkTable.html'
>>> contentsLinkTable.update()
>>> print(contentsLinkTable.render())
<table>
<thead>
<tr>
<th>Name</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="http://127.0.0.1/container/first/contents.html">first</a></td>
<td>number: 1</td>
</tr>
<tr>
<td><a href="http://127.0.0.1/container/fourth/contents.html">fourth</a></td>
<td>number: 4</td>
</tr>
<tr>
<td><a href="http://127.0.0.1/container/second/contents.html">second</a></td>
<td>number: 2</td>
</tr>
<tr>
<td><a href="http://127.0.0.1/container/third/contents.html">third</a></td>
<td>number: 3</td>
</tr>
<tr>
<td><a href="http://127.0.0.1/container/zero/contents.html">zero</a></td>
<td>number: 0</td>
</tr>
</tbody>
</table>
IndexLinkColumn
---------------
This one will generate a ``index.html`` link for each item:
>>> class IndexLinkTable(table.Table):
... cssClassSortedOn = None
...
... def setUpColumns(self):
... return [
... column.addColumn(self, column.IndexLinkColumn, u'link',
... weight=1),
... column.addColumn(self, NumberColumn, name=u'number',
... weight=2, header=u'Number')
... ]
>>> indexLinkTable = IndexLinkTable(container, request)
>>> indexLinkTable.__parent__ = container
>>> indexLinkTable.__name__ = u'indexLinkTable.html'
>>> indexLinkTable.update()
>>> print(indexLinkTable.render())
<table>
<thead>
<tr>
<th>Name</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="http://127.0.0.1/container/first/index.html">first</a></td>
<td>number: 1</td>
</tr>
<tr>
<td><a href="http://127.0.0.1/container/fourth/index.html">fourth</a></td>
<td>number: 4</td>
</tr>
<tr>
<td><a href="http://127.0.0.1/container/second/index.html">second</a></td>
<td>number: 2</td>
</tr>
<tr>
<td><a href="http://127.0.0.1/container/third/index.html">third</a></td>
<td>number: 3</td>
</tr>
<tr>
<td><a href="http://127.0.0.1/container/zero/index.html">zero</a></td>
<td>number: 0</td>
</tr>
</tbody>
</table>
EditLinkColumn
--------------
And this one will generate a ``edit.html`` link for each item:
>>> class EditLinkTable(table.Table):
... cssClassSortedOn = None
...
... def setUpColumns(self):
... return [
... column.addColumn(self, column.EditLinkColumn, u'link',
... weight=1),
... column.addColumn(self, NumberColumn, name=u'number',
... weight=2, header=u'Number')
... ]
>>> editLinkTable = EditLinkTable(container, request)
>>> editLinkTable.__parent__ = container
>>> editLinkTable.__name__ = u'editLinkTable.html'
>>> editLinkTable.update()
>>> print(editLinkTable.render())
<table>
<thead>
<tr>
<th>Name</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="http://127.0.0.1/container/first/edit.html">first</a></td>
<td>number: 1</td>
</tr>
<tr>
<td><a href="http://127.0.0.1/container/fourth/edit.html">fourth</a></td>
<td>number: 4</td>
</tr>
<tr>
<td><a href="http://127.0.0.1/container/second/edit.html">second</a></td>
<td>number: 2</td>
</tr>
<tr>
<td><a href="http://127.0.0.1/container/third/edit.html">third</a></td>
<td>number: 3</td>
</tr>
<tr>
<td><a href="http://127.0.0.1/container/zero/edit.html">zero</a></td>
<td>number: 0</td>
</tr>
</tbody>
</table>
| z3c.table | /z3c.table-3.0.tar.gz/z3c.table-3.0/src/z3c/table/column.rst | column.rst |
from urllib.parse import urlencode
import zope.i18nmessageid
import zope.interface
from z3c.batching.batch import first_neighbours_last
from zope.traversing.browser import absoluteURL
from z3c.table import interfaces
_ = zope.i18nmessageid.MessageFactory("z3c")
@zope.interface.implementer(interfaces.IBatchProvider)
class BatchProvider:
"""Batch content provider.
A batch provider is responsible for rendering the batch HTML and not for
batching. The batch setup is directly done in the table. A batch provider
get only used if the table rows is a batch.
This batch provider offers a batch presentation for a given table. The
batch provides different configuration options which can be overriden in
custom implementations:
The batch acts like this. If we have more batches than
(prevBatchSize + nextBatchSize + 3) then the advanced batch subset is used.
Otherwise, we will render all batch links.
Note, the additional factor 3 is the placeholder for the first, current and
last item.
Such a batch looks like:
Renders the link for the first batch, spacers, the amount of links for
previous batches, the current batch link, spacers, the amount of links for
previous batches and the link for the last batch.
Sample for 1000 items with 100 batches with batchSize of 10 and a
prevBatchSize of 3 and a nextBatchSize of 3:
For the first item:
[*1*][2][3][4] ... [100]
In the middle:
[1] ... [6][7][8][*9*][10][11][12] ... [100]
At the end:
[1] ... [97][98][99][*100*]
"""
batchItems = []
prevBatchSize = 3
nextBatchSize = 3
batchSpacer = "..."
_request_args = ["%(prefix)s-sortOn", "%(prefix)s-sortOrder"]
def __init__(self, context, request, table):
self.__parent__ = context
self.context = context
self.request = request
self.table = table
self.batch = table.rows
self.batches = table.rows.batches
def getQueryStringArgs(self):
"""Collect additional terms from the request to include in links.
API borrowed from z3c.table.header.ColumnHeader.
"""
args = {}
for key in self._request_args:
key = key % dict(prefix=self.table.prefix)
value = self.request.get(key, None)
if value:
args.update({key: value})
return args
def renderBatchLink(self, batch, cssClass=None):
args = self.getQueryStringArgs()
args[self.table.prefix + "-batchStart"] = batch.start
args[self.table.prefix + "-batchSize"] = batch.size
query = urlencode(sorted(args.items()))
tableURL = absoluteURL(self.table, self.request)
idx = batch.index + 1
css = ' class="%s"' % cssClass
cssClass = cssClass and css or ""
return f'<a href="{tableURL}?{query}"{cssClass}>{idx}</a>'
def update(self):
# 3 is is the placeholder for the first, current and last item.
total = self.prevBatchSize + self.nextBatchSize + 3
if self.batch.total <= total:
# give all batches
self.batchItems = self.batch.batches
else:
# switch to an advanced batch subset
self.batchItems = first_neighbours_last(
self.batches,
self.batch.index,
self.prevBatchSize,
self.nextBatchSize,
)
def render(self):
self.update()
res = []
append = res.append
idx = 0
lastIdx = len(self.batchItems)
for batch in self.batchItems:
idx += 1
# build css class
cssClasses = []
if batch and batch == self.batch:
cssClasses.append("current")
if idx == 1:
cssClasses.append("first")
if idx == lastIdx:
cssClasses.append("last")
if cssClasses:
css = " ".join(cssClasses)
else:
css = None
# render spaces
if batch is None:
append(self.batchSpacer)
elif idx == 1:
# render first
append(self.renderBatchLink(batch, css))
elif batch == self.batch:
# render current
append(self.renderBatchLink(batch, css))
elif idx == lastIdx:
# render last
append(self.renderBatchLink(batch, css))
else:
append(self.renderBatchLink(batch))
return "\n".join(res) | z3c.table | /z3c.table-3.0.tar.gz/z3c.table-3.0/src/z3c/table/batch.py | batch.py |
Batching
--------
Our table implements batching out of the box. If the amount of
row items is smaller than the given ``startBatchingAt`` size, the table starts
to batch at this size. Let's define a new Table.
We need to configure our batch provider for the next step first. See the
section ``BatchProvider`` below for more infos about batch rendering:
>>> from zope.configuration.xmlconfig import XMLConfig
>>> import z3c.table
>>> import zope.component
>>> XMLConfig('meta.zcml', zope.component)()
>>> XMLConfig('configure.zcml', z3c.table)()
Now we can create our table:
>>> from zope.publisher.browser import TestRequest
>>> from z3c.table.testing import Container, Content, SimpleTable
>>> container = Container()
>>> root['container-1'] = container
>>> request = TestRequest()
>>> batchingTable = SimpleTable(container, request)
>>> batchingTable.cssClassSortedOn = None
We also need to give the table a location and a name like we normally setup
in traversing:
>>> batchingTable.__parent__ = container
>>> batchingTable.__name__ = u'batchingTable.html'
Now setup some items:
>>> container[u'zero'] = Content('Zero', 0)
>>> container[u'first'] = Content('First', 1)
>>> container[u'second'] = Content('Second', 2)
>>> container[u'third'] = Content('Third', 3)
>>> container[u'fourth'] = Content('Fourth', 4)
>>> container[u'sixth'] = Content('Sixth', 6)
>>> container[u'seventh'] = Content('Seventh', 7)
>>> container[u'eighth'] = Content('Eighth', 8)
>>> container[u'ninth'] = Content('Ninth', 9)
>>> container[u'tenth'] = Content('Tenth', 10)
>>> container[u'eleventh'] = Content('Eleventh', 11)
>>> container[u'twelfth '] = Content('Twelfth', 12)
>>> container[u'thirteenth'] = Content('Thirteenth', 13)
>>> container[u'fourteenth'] = Content('Fourteenth', 14)
>>> container[u'fifteenth '] = Content('Fifteenth', 15)
>>> container[u'sixteenth'] = Content('Sixteenth', 16)
>>> container[u'seventeenth'] = Content('Seventeenth', 17)
>>> container[u'eighteenth'] = Content('Eighteenth', 18)
>>> container[u'nineteenth'] = Content('Nineteenth', 19)
>>> container[u'twentieth'] = Content('Twentieth', 20)
Now let's show the full table without batching:
>>> batchingTable.update()
>>> print(batchingTable.render())
<table>
<thead>
<tr>
<th>My items</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>Eighteenth item</td>
<td>number: 18</td>
</tr>
<tr>
<td>Eighth item</td>
<td>number: 8</td>
</tr>
<tr>
<td>Eleventh item</td>
<td>number: 11</td>
</tr>
<tr>
<td>Fifteenth item</td>
<td>number: 15</td>
</tr>
<tr>
<td>First item</td>
<td>number: 1</td>
</tr>
<tr>
<td>Fourteenth item</td>
<td>number: 14</td>
</tr>
<tr>
<td>Fourth item</td>
<td>number: 4</td>
</tr>
<tr>
<td>Nineteenth item</td>
<td>number: 19</td>
</tr>
<tr>
<td>Ninth item</td>
<td>number: 9</td>
</tr>
<tr>
<td>Second item</td>
<td>number: 2</td>
</tr>
<tr>
<td>Seventeenth item</td>
<td>number: 17</td>
</tr>
<tr>
<td>Seventh item</td>
<td>number: 7</td>
</tr>
<tr>
<td>Sixteenth item</td>
<td>number: 16</td>
</tr>
<tr>
<td>Sixth item</td>
<td>number: 6</td>
</tr>
<tr>
<td>Tenth item</td>
<td>number: 10</td>
</tr>
<tr>
<td>Third item</td>
<td>number: 3</td>
</tr>
<tr>
<td>Thirteenth item</td>
<td>number: 13</td>
</tr>
<tr>
<td>Twelfth item</td>
<td>number: 12</td>
</tr>
<tr>
<td>Twentieth item</td>
<td>number: 20</td>
</tr>
<tr>
<td>Zero item</td>
<td>number: 0</td>
</tr>
</tbody>
</table>
As you can see, the table is not ordered and it uses all items. If we like
to use the batch, we need to set the startBatchingAt size to a lower value than
it is set by default.
The default value which a batch is used is set to ``50``:
>>> batchingTable.startBatchingAt
50
We will set the batch start to ``5`` for now. This means the first 5 items
do not get used:
>>> batchingTable.startBatchingAt = 5
>>> batchingTable.startBatchingAt
5
There is also a ``batchSize`` value which we need to set to ``5``. By default
the value gets initialized by the ``batchSize`` value:
>>> batchingTable.batchSize
50
>>> batchingTable.batchSize = 5
>>> batchingTable.batchSize
5
Now we can update and render the table again. But you will see that we only get
a table size of 5 rows, which is correct. But the order doesn't depend on the
numbers we see in cells:
>>> batchingTable.update()
>>> print(batchingTable.render())
<table>
<thead>
<tr>
<th>My items</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>Eighteenth item</td>
<td>number: 18</td>
</tr>
<tr>
<td>Eighth item</td>
<td>number: 8</td>
</tr>
<tr>
<td>Eleventh item</td>
<td>number: 11</td>
</tr>
<tr>
<td>Fifteenth item</td>
<td>number: 15</td>
</tr>
<tr>
<td>First item</td>
<td>number: 1</td>
</tr>
</tbody>
</table>
I think we should order the table by the second column before we show the next
batch values. We do this by simply set the ``defaultSortOn``:
>>> batchingTable.sortOn = u'table-number-1'
Now we should see a nice ordered and batched table:
>>> batchingTable.update()
>>> print(batchingTable.render())
<table>
<thead>
<tr>
<th>My items</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>Zero item</td>
<td>number: 0</td>
</tr>
<tr>
<td>First item</td>
<td>number: 1</td>
</tr>
<tr>
<td>Second item</td>
<td>number: 2</td>
</tr>
<tr>
<td>Third item</td>
<td>number: 3</td>
</tr>
<tr>
<td>Fourth item</td>
<td>number: 4</td>
</tr>
</tbody>
</table>
The batch concept allows us to choose from all batches and render the rows
for this batched items. We can do this by set any batch as rows. as you can see
we have ``4`` batched row data available:
>>> len(batchingTable.rows.batches)
4
We can set such a batch as row values, then this batch data are used for
rendering. But take care, if we update the table, our rows get overridden
and reset to the previous values. this means you can set any batch as rows
data and only render them. This is possible since the update method sorted all
items and all batch contain ready-to-use data. This concept could be important
if you need to cache batches etc. :
>>> batchingTable.rows = batchingTable.rows.batches[1]
>>> print(batchingTable.render())
<table>
<thead>
<tr>
<th>My items</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>Sixth item</td>
<td>number: 6</td>
</tr>
<tr>
<td>Seventh item</td>
<td>number: 7</td>
</tr>
<tr>
<td>Eighth item</td>
<td>number: 8</td>
</tr>
<tr>
<td>Ninth item</td>
<td>number: 9</td>
</tr>
<tr>
<td>Tenth item</td>
<td>number: 10</td>
</tr>
</tbody>
</table>
And like described above, if you call ``update`` our batch to rows setup get
reset:
>>> batchingTable.update()
>>> print(batchingTable.render())
<table>
<thead>
<tr>
<th>My items</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>Zero item</td>
<td>number: 0</td>
</tr>
<tr>
<td>First item</td>
<td>number: 1</td>
</tr>
<tr>
<td>Second item</td>
<td>number: 2</td>
</tr>
<tr>
<td>Third item</td>
<td>number: 3</td>
</tr>
<tr>
<td>Fourth item</td>
<td>number: 4</td>
</tr>
</tbody>
</table>
This means you can probably update all batches, cache them and use them after.
But this is not useful for normal usage in a page without an enhanced concept
which is not a part of this implementation. This also means, there must be
another way to set the batch index. Yes there is, there are two other ways how
we can set the batch position. We can set a batch position by setting the
``batchStart`` value in our table or we can use a request variable. Let's show
the first one first:
>>> batchingTable.batchStart = 6
>>> batchingTable.update()
>>> print(batchingTable.render())
<table>
<thead>
<tr>
<th>My items</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>Seventh item</td>
<td>number: 7</td>
</tr>
<tr>
<td>Eighth item</td>
<td>number: 8</td>
</tr>
<tr>
<td>Ninth item</td>
<td>number: 9</td>
</tr>
<tr>
<td>Tenth item</td>
<td>number: 10</td>
</tr>
<tr>
<td>Eleventh item</td>
<td>number: 11</td>
</tr>
</tbody>
</table>
We can also set the batch position by using the batchStart value in a request.
Note that we need the table ``prefix`` and column ``__name__`` like we use in
the sorting concept:
>>> batchingRequest = TestRequest(form={'table-batchStart': '11',
... 'table-batchSize': '5',
... 'table-sortOn': 'table-number-1'})
>>> requestBatchingTable = SimpleTable(container, batchingRequest)
>>> requestBatchingTable.cssClassSortedOn = None
We also need to give the table a location and a name like we normally set up
in traversing:
>>> requestBatchingTable.__parent__ = container
>>> requestBatchingTable.__name__ = u'requestBatchingTable.html'
Note: our table needs to start batching at smaller amount of items than we
have by default otherwise we don't get a batch:
>>> requestBatchingTable.startBatchingAt = 5
>>> requestBatchingTable.update()
>>> print(requestBatchingTable.render())
<table>
<thead>
<tr>
<th>My items</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>Twelfth item</td>
<td>number: 12</td>
</tr>
<tr>
<td>Thirteenth item</td>
<td>number: 13</td>
</tr>
<tr>
<td>Fourteenth item</td>
<td>number: 14</td>
</tr>
<tr>
<td>Fifteenth item</td>
<td>number: 15</td>
</tr>
<tr>
<td>Sixteenth item</td>
<td>number: 16</td>
</tr>
</tbody>
</table>
BatchProvider
-------------
The batch provider allows us to render the batch HTML independently of our
table. This means by default the batch gets not rendered in the render method.
You can change this in your custom table implementation and return the batch
and the table in the render method.
As we can see, our table rows provides IBatch if it comes to batching:
>>> from z3c.batching.interfaces import IBatch
>>> IBatch.providedBy(requestBatchingTable.rows)
True
Let's check some batch variables before we render our test. This let us compare
the rendered result. For more information about batching see the README.txt in
z3c.batching:
>>> requestBatchingTable.rows.start
11
>>> requestBatchingTable.rows.index
2
>>> requestBatchingTable.rows.batches
<z3c.batching.batch.Batches object at ...>
>>> len(requestBatchingTable.rows.batches)
4
We use our previous batching table and render the batch with the built-in
``renderBatch`` method:
>>> requestBatchingTable.update()
>>> print(requestBatchingTable.renderBatch())
<a href="...html?table-batchSize=5&table-batchStart=0&..." class="first">1</a>
<a href="...html?table-batchSize=5&table-batchStart=5&...">2</a>
<a href="...html?table-batchSize=5&table-batchStart=11&..." class="current">3</a>
<a href="...html?table-batchSize=5&table-batchStart=15&..." class="last">4</a>
Now let's add more items so that we can test the skipped links in large
batches:
>>> for i in range(1000):
... idx = i+20
... container[str(idx)] = Content(str(idx), idx)
Now let's test the batching table again with the new amount of items and
the same ``startBatchingAt`` of 5 but starting the batch at item ``100``
and sorted on the second numbered column:
>>> batchingRequest = TestRequest(form={'table-batchStart': '100',
... 'table-batchSize': '5',
... 'table-sortOn': 'table-number-1'})
>>> requestBatchingTable = SimpleTable(container, batchingRequest)
>>> requestBatchingTable.startBatchingAt = 5
>>> requestBatchingTable.cssClassSortedOn = None
We also need to give the table a location and a name like we normally setup
in traversing:
>>> requestBatchingTable.__parent__ = container
>>> requestBatchingTable.__name__ = u'requestBatchingTable.html'
>>> requestBatchingTable.update()
>>> print(requestBatchingTable.render())
<table>
<thead>
<tr>
<th>My items</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>100 item</td>
<td>number: 100</td>
</tr>
<tr>
<td>101 item</td>
<td>number: 101</td>
</tr>
<tr>
<td>102 item</td>
<td>number: 102</td>
</tr>
<tr>
<td>103 item</td>
<td>number: 103</td>
</tr>
<tr>
<td>104 item</td>
<td>number: 104</td>
</tr>
</tbody>
</table>
And test the batch. Note the three dots between the links are rendered by the
batch provider and are not a part of the doctest:
>>> print(requestBatchingTable.renderBatch())
<a href="...html?table-batchSize=5&table-batchStart=0&table-sortOn=table-number-1" class="first">1</a>
...
<a href="...html?table-batchSize=5&table-batchStart=85&table-sortOn=table-number-1">18</a>
<a href="...html?table-batchSize=5&table-batchStart=90&table-sortOn=table-number-1">19</a>
<a href="...html?table-batchSize=5&table-batchStart=95&table-sortOn=table-number-1">20</a>
<a href="...html?table-batchSize=5&table-batchStart=100&table-sortOn=table-number-1" class="current">21</a>
<a href="...html?table-batchSize=5&table-batchStart=105&table-sortOn=table-number-1">22</a>
<a href="...html?table-batchSize=5&table-batchStart=110&table-sortOn=table-number-1">23</a>
<a href="...html?table-batchSize=5&table-batchStart=115&table-sortOn=table-number-1">24</a>
...
<a href="...html?table-batchSize=5&table-batchStart=1015&table-sortOn=table-number-1" class="last">204</a>
You can change the spacer in the batch provider if you set the ``batchSpacer``
value:
>>> from z3c.table.batch import BatchProvider
>>> from z3c.table.interfaces import IBatchProvider
>>> from zope.interface import implementer
>>> @implementer(IBatchProvider)
... class XBatchProvider(BatchProvider):
... """Just another batch provider."""
... batchSpacer = u'xxx'
Now register the new batch provider for our batching table:
>>> import zope.publisher.interfaces.browser
>>> from zope.component import getSiteManager
>>> sm = getSiteManager(container)
>>> sm.registerAdapter(XBatchProvider,
... (zope.interface.Interface,
... zope.publisher.interfaces.browser.IBrowserRequest,
... SimpleTable), name='batch')
If we update and render our table, the new batch provider should get used.
As you can see the spacer get changed now:
>>> requestBatchingTable.update()
>>> requestBatchingTable.batchProvider
<...XBatchProvider object at ...>
>>> print(requestBatchingTable.renderBatch())
<a href="...html?table-batchSize=5&table-batchStart=0&table-sortOn=table-number-1" class="first">1</a>
xxx
<a href="...html?table-batchSize=5&table-batchStart=85&table-sortOn=table-number-1">18</a>
<a href="...html?table-batchSize=5&table-batchStart=90&table-sortOn=table-number-1">19</a>
<a href="...html?table-batchSize=5&table-batchStart=95&table-sortOn=table-number-1">20</a>
<a href="...html?table-batchSize=5&table-batchStart=100&table-sortOn=table-number-1" class="current">21</a>
<a href="...html?table-batchSize=5&table-batchStart=105&table-sortOn=table-number-1">22</a>
<a href="...html?table-batchSize=5&table-batchStart=110&table-sortOn=table-number-1">23</a>
<a href="...html?table-batchSize=5&table-batchStart=115&table-sortOn=table-number-1">24</a>
xxx
<a href="...html?table-batchSize=5&table-batchStart=1015&table-sortOn=table-number-1" class="last">204</a>
Now test the extremities, need to define a new batchingRequest:
Beginning by the left end point:
>>> leftBatchingRequest = TestRequest(form={'table-batchStart': '10',
... 'table-batchSize': '5',
... 'table-sortOn': 'table-number-1'})
>>> leftRequestBatchingTable = SimpleTable(container, leftBatchingRequest)
>>> leftRequestBatchingTable.__parent__ = container
>>> leftRequestBatchingTable.__name__ = u'leftRequestBatchingTable.html'
>>> leftRequestBatchingTable.update()
>>> print(leftRequestBatchingTable.renderBatch())
<a href="http://...html?table-batchSize=5&table-batchStart=0&table-sortOn=table-number-1" class="first">1</a>
<a href="http://...html?table-batchSize=5&table-batchStart=5&table-sortOn=table-number-1">2</a>
<a href="http://...html?table-batchSize=5&table-batchStart=10&table-sortOn=table-number-1" class="current">3</a>
<a href="http://...html?table-batchSize=5&table-batchStart=15&table-sortOn=table-number-1">4</a>
<a href="http://...html?table-batchSize=5&table-batchStart=20&table-sortOn=table-number-1">5</a>
<a href="http://...html?table-batchSize=5&table-batchStart=25&table-sortOn=table-number-1">6</a>
xxx
<a href="http://...html?table-batchSize=5&table-batchStart=1015&table-sortOn=table-number-1" class="last">204</a>
Go on with the right extremity:
>>> rightBatchingRequest = TestRequest(form={'table-batchStart': '1005',
... 'table-batchSize': '5',
... 'table-sortOn': 'table-number-1'})
>>> rightRequestBatchingTable = SimpleTable(container, rightBatchingRequest)
>>> rightRequestBatchingTable.__parent__ = container
>>> rightRequestBatchingTable.__name__ = u'rightRequestBatchingTable.html'
>>> rightRequestBatchingTable.update()
>>> print(rightRequestBatchingTable.renderBatch())
<a href="http://...html?table-batchSize=5&table-batchStart=0&table-sortOn=table-number-1" class="first">1</a>
xxx
<a href="http://...html?table-batchSize=5&table-batchStart=990&table-sortOn=table-number-1">199</a>
<a href="http://...html?table-batchSize=5&table-batchStart=995&table-sortOn=table-number-1">200</a>
<a href="http://...html?table-batchSize=5&table-batchStart=1000&table-sortOn=table-number-1">201</a>
<a href="http://...html?table-batchSize=5&table-batchStart=1005&table-sortOn=table-number-1" class="current">202</a>
<a href="http://...html?table-batchSize=5&table-batchStart=1010&table-sortOn=table-number-1">203</a>
<a href="http://...html?table-batchSize=5&table-batchStart=1015&table-sortOn=table-number-1" class="last">204</a>
None previous and next batch size. Probably it doesn't make sense but let's
show what happens if we set the previous and next batch size to 0 (zero):
>>> from z3c.table.batch import BatchProvider
>>> class ZeroBatchProvider(BatchProvider):
... """Just another batch provider."""
... batchSpacer = u'xxx'
... previousBatchSize = 0
... nextBatchSize = 0
Now register the new batch provider for our batching table:
>>> import zope.publisher.interfaces.browser
>>> sm.registerAdapter(ZeroBatchProvider,
... (zope.interface.Interface,
... zope.publisher.interfaces.browser.IBrowserRequest,
... SimpleTable), name='batch')
Update the table and render the batch:
>>> requestBatchingTable.update()
>>> print(requestBatchingTable.renderBatch())
<a href="...html?table-batchSize=5&table-batchStart=0&table-sortOn=table-number-1" class="first">1</a>
xxx
<a href="...html?table-batchSize=5&table-batchStart=100&table-sortOn=table-number-1" class="current">21</a>
xxx
<a href="...html?table-batchSize=5&table-batchStart=1015&table-sortOn=table-number-1" class="last">204</a>
Edge cases, do not fail hard when someone tries some weird batching values:
>>> batchingRequest = TestRequest(form={'table-batchStart': '11',
... 'table-batchSize': 'foobar',
... 'table-sortOn': 'table-number-1'})
>>> requestBatchingTable = SimpleTable(container, batchingRequest)
>>> requestBatchingTable.cssClassSortedOn = None
>>> requestBatchingTable.__parent__ = container
>>> requestBatchingTable.__name__ = u'requestBatchingTable.html'
>>> requestBatchingTable.batchSize = 3
>>> requestBatchingTable.startBatchingAt = 5
>>> requestBatchingTable.update()
>>> print(requestBatchingTable.render())
<table>
<thead>
<tr>
<th>My items</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>Twelfth item</td>
<td>number: 12</td>
</tr>
<tr>
<td>Thirteenth item</td>
<td>number: 13</td>
</tr>
<tr>
<td>Fourteenth item</td>
<td>number: 14</td>
</tr>
</tbody>
</table>
>>> batchingRequest = TestRequest(form={'table-batchStart': '0',
... 'table-batchSize': '-10',
... 'table-sortOn': 'table-number-1'})
>>> requestBatchingTable = SimpleTable(container, batchingRequest)
>>> requestBatchingTable.cssClassSortedOn = None
>>> requestBatchingTable.__parent__ = container
>>> requestBatchingTable.__name__ = u'requestBatchingTable.html'
>>> requestBatchingTable.startBatchingAt = 5
>>> requestBatchingTable.batchSize = 3
>>> requestBatchingTable.update()
>>> print(requestBatchingTable.render())
<table>
<thead>
<tr>
<th>My items</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>Zero item</td>
<td>number: 0</td>
</tr>
<tr>
<td>First item</td>
<td>number: 1</td>
</tr>
<tr>
<td>Second item</td>
<td>number: 2</td>
</tr>
</tbody>
</table>
>>> batchingRequest = TestRequest(form={'table-batchStart': 'foobar',
... 'table-batchSize': '3',
... 'table-sortOn': 'table-number-1'})
>>> requestBatchingTable = SimpleTable(container, batchingRequest)
>>> requestBatchingTable.cssClassSortedOn = None
>>> requestBatchingTable.__parent__ = container
>>> requestBatchingTable.__name__ = u'requestBatchingTable.html'
>>> requestBatchingTable.startBatchingAt = 5
>>> requestBatchingTable.update()
>>> print(requestBatchingTable.render())
<table>
<thead>
<tr>
<th>My items</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>Zero item</td>
<td>number: 0</td>
</tr>
<tr>
<td>First item</td>
<td>number: 1</td>
</tr>
<tr>
<td>Second item</td>
<td>number: 2</td>
</tr>
</tbody>
</table>
>>> batchingRequest = TestRequest(form={'table-batchStart': '99999',
... 'table-batchSize': '3',
... 'table-sortOn': 'table-number-1'})
>>> requestBatchingTable = SimpleTable(container, batchingRequest)
>>> requestBatchingTable.cssClassSortedOn = None
>>> requestBatchingTable.__parent__ = container
>>> requestBatchingTable.__name__ = u'requestBatchingTable.html'
>>> requestBatchingTable.startBatchingAt = 5
>>> requestBatchingTable.update()
>>> print(requestBatchingTable.render())
<table>
<thead>
<tr>
<th>My items</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>1017 item</td>
<td>number: 1017</td>
</tr>
<tr>
<td>1018 item</td>
<td>number: 1018</td>
</tr>
<tr>
<td>1019 item</td>
<td>number: 1019</td>
</tr>
</tbody>
</table>
>>> batchingRequest = TestRequest(form={'table-batchStart': '-10',
... 'table-batchSize': 'foobar',
... 'table-sortOn': 'table-number-1'})
>>> requestBatchingTable = SimpleTable(container, batchingRequest)
>>> requestBatchingTable.cssClassSortedOn = None
>>> requestBatchingTable.__parent__ = container
>>> requestBatchingTable.__name__ = u'requestBatchingTable.html'
>>> requestBatchingTable.batchSize = 3
>>> requestBatchingTable.startBatchingAt = 5
>>> requestBatchingTable.update()
>>> print(requestBatchingTable.render())
<table>
<thead>
<tr>
<th>My items</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>Zero item</td>
<td>number: 0</td>
</tr>
<tr>
<td>First item</td>
<td>number: 1</td>
</tr>
<tr>
<td>Second item</td>
<td>number: 2</td>
</tr>
</tbody>
</table>
| z3c.table | /z3c.table-3.0.tar.gz/z3c.table-3.0/src/z3c/table/batch.rst | batch.rst |
from xml.sax.saxutils import quoteattr
import zope.component
import zope.interface
import zope.location
from z3c.batching.batch import Batch
from z3c.batching.interfaces import IBatch
from z3c.table import column
from z3c.table import interfaces
def getWeight(column):
try:
return int(column.weight)
except AttributeError:
return 0
def getSortMethod(idx):
def getSortKey(item):
sublist = item[idx]
def getColumnSortKey(sublist):
return sublist[1].getSortKey(sublist[0])
return getColumnSortKey(sublist)
return getSortKey
def getCurrentSortID(sortOn):
# this may return a string 'id-name-idx' if coming from request,
# otherwise in Table class it is intialised as a integer string
try:
currentSortID = int(sortOn)
except ValueError:
currentSortID = sortOn.rsplit("-", 1)[-1]
try:
currentSortID = int(currentSortID)
except ValueError:
return None
return currentSortID
def nameColumn(column, name):
"""Give a column a __name__."""
column.__name__ = name
return column
@zope.interface.implementer(interfaces.ITable)
class Table(zope.location.Location):
"""Generic usable table implementation."""
# customize this part if needed
prefix = "table"
# css classes
cssClasses = {}
# additional (row) css
cssClassEven = ""
cssClassOdd = ""
cssClassSelected = ""
# css to show sorting, set to None to turn off
cssClassSortedOn = "sorted-on"
# sort attributes
sortOn = 0
sortOrder = "ascending"
reverseSortOrderNames = ["descending", "reverse", "down"]
# batch attributes
batchProviderName = "batch"
batchStart = 0
batchSize = 50
startBatchingAt = 50
def __init__(self, context, request):
self.context = context
self.request = request
self.__parent__ = context
# private variables will be set in update call
self.batchProvider = None
self.columnCounter = 0
self.columnIndexById = {}
self.columnByName = {}
self.columns = None
self.rows = []
self.selectedItems = []
def initColumns(self):
# setup columns
self.columns = self.setUpColumns()
# order columns
self.orderColumns()
@property
def values(self):
adapter = zope.component.getMultiAdapter(
(self.context, self.request, self), interfaces.IValues
)
return adapter.values
# CSS helpers
def getCSSHighlightClass(self, column, item, cssClass):
"""Provide a highlight option for any cell"""
return cssClass
def getCSSSortClass(self, column, cssClass):
"""Add CSS class based on current sorting"""
if self.cssClassSortedOn and self.sortOn is not None:
currentSortID = getCurrentSortID(self.sortOn)
sortID = column.id.rsplit("-", 1)[-1]
if int(sortID) == currentSortID:
klass = self.cssClassSortedOn + " " + self.sortOrder
if cssClass:
cssClass += " " + klass
else:
cssClass = klass
return cssClass
def getCSSClass(self, element, cssClass=None):
"""Add CSS class based on HTML tag, make a `class=` attribute"""
klass = self.cssClasses.get(element)
if klass and cssClass:
klass = "{} {}".format(cssClass, klass)
elif cssClass:
klass = cssClass
return " class=%s" % quoteattr(klass) if klass else ""
# setup
def setUpColumns(self):
cols = list(
zope.component.getAdapters(
(self.context, self.request, self), interfaces.IColumn
)
)
# use the adapter name as column name
return [nameColumn(col, name) for name, col in cols]
def updateColumns(self):
for col in self.columns:
col.update()
def orderColumns(self):
self.columnCounter = 0
self.columns = sorted(self.columns, key=getWeight)
for col in self.columns:
self.columnByName[col.__name__] = col
idx = self.columnCounter
col.id = "{}-{}-{}".format(self.prefix, col.__name__, idx)
self.columnIndexById[col.id] = idx
self.columnCounter += 1
def setUpRow(self, item):
cols = []
append = cols.append
colspanCounter = 0
countdown = len(self.columns)
for col in self.columns:
countdown -= 1
colspan = 0
if colspanCounter == 0:
colspan = colspanCounter = col.getColspan(item)
# adjust colspan because we define 0, 2, 3, etc.
if colspanCounter > 0:
colspanCounter -= 1
if colspan == 0 and colspanCounter > 0:
# override col if colspan is 0 and colspan coutner not 0
colspanCounter -= 1
colspan = 0
# now we are ready to setup dummy colspan cells
col = column.NoneCell(self.context, self.request, self)
# we reached the end of the table and have still colspan
if (countdown - colspan) < 0:
raise ValueError(
"Colspan for column '%s' is larger than the table." % col
)
append((item, col, colspan))
return cols
def setUpRows(self):
return [self.setUpRow(item) for item in self.values]
# sort
def getSortOn(self):
"""Returns sort on column id."""
return self.request.get(self.prefix + "-sortOn", self.sortOn)
def getSortOrder(self):
"""Returns sort order criteria."""
return self.request.get(self.prefix + "-sortOrder", self.sortOrder)
def sortRows(self):
if self.sortOn is not None and self.rows and self.columns:
sortOnIdx = self.columnIndexById.get(self.sortOn, 0)
sortKeyGetter = getSortMethod(sortOnIdx)
rows = sorted(self.rows, key=sortKeyGetter)
if self.sortOrder in self.reverseSortOrderNames:
rows.reverse()
self.rows = rows
# batch
def getBatchSize(self):
try:
newSize = int(
self.request.get(self.prefix + "-batchSize", self.batchSize)
)
except ValueError:
newSize = self.batchSize
if newSize < 1:
newSize = self.batchSize
return newSize
def getBatchStart(self):
try:
return int(
self.request.get(self.prefix + "-batchStart", self.batchStart)
)
except ValueError:
return self.batchStart
def batchRows(self):
length = len(self.rows)
if length > self.startBatchingAt:
if self.batchStart >= length:
self.batchStart = length - self.batchSize
if self.batchStart < 0:
self.batchStart = 0
self.rows = Batch(
self.rows, start=self.batchStart, size=self.batchSize
)
def updateBatch(self):
if IBatch.providedBy(self.rows):
self.batchProvider = zope.component.getMultiAdapter(
(self.context, self.request, self),
interfaces.IBatchProvider,
name=self.batchProviderName,
)
self.batchProvider.update()
def isSelectedRow(self, row):
item, col, colspan = row[0]
if item in self.selectedItems:
return True
return False
# render
def renderBatch(self):
if self.batchProvider is None:
return ""
return self.batchProvider.render()
def renderTable(self):
if self.columns:
cssClass = self.getCSSClass("table")
head = self.renderHead()
body = self.renderBody()
return "<table{}>{}{}\n</table>".format(cssClass, head, body)
return ""
def renderHead(self):
cssClass = self.getCSSClass("thead")
rStr = self.renderHeadRow()
return "\n <thead{}>{}\n </thead>".format(cssClass, rStr)
def renderHeadRow(self):
cssClass = self.getCSSClass("tr")
cells = [self.renderHeadCell(col) for col in self.columns]
return "\n <tr{}>{}\n </tr>".format(cssClass, "".join(cells))
def renderHeadCell(self, column):
cssClass = column.cssClasses.get("th")
cssClass = self.getCSSSortClass(column, cssClass)
cssClass = self.getCSSClass("th", cssClass)
return f"\n <th{cssClass}>{column.renderHeadCell()}</th>"
def renderBody(self):
cssClass = self.getCSSClass("tbody")
rStr = self.renderRows()
return f"\n <tbody{cssClass}>{rStr}\n </tbody>"
def renderRows(self):
counter = 0
rows = []
cssClasses = (self.cssClassEven, self.cssClassOdd)
append = rows.append
for row in self.rows:
append(self.renderRow(row, cssClasses[counter % 2]))
counter += 1
return "".join(rows)
def renderRow(self, row, cssClass=None):
isSelected = self.isSelectedRow(row)
if isSelected and self.cssClassSelected and cssClass:
cssClass = "{} {}".format(self.cssClassSelected, cssClass)
elif isSelected and self.cssClassSelected:
cssClass = self.cssClassSelected
cssClass = self.getCSSClass("tr", cssClass)
cells = [
self.renderCell(item, col, colspan) for item, col, colspan in row
]
return "\n <tr{}>{}\n </tr>".format(cssClass, "".join(cells))
def renderCell(self, item, column, colspan=0):
if interfaces.INoneCell.providedBy(column):
return ""
cssClass = column.cssClasses.get("td")
cssClass = self.getCSSHighlightClass(column, item, cssClass)
cssClass = self.getCSSSortClass(column, cssClass)
cssClass = self.getCSSClass("td", cssClass)
colspanStr = ' colspan="%s"' % colspan if colspan else ""
return "\n <td{}{}>{}</td>".format(
cssClass,
colspanStr,
column.renderCell(item),
)
def update(self):
# reset values
self.columnCounter = 0
self.columnByIndex = {}
self.selectedItems = []
# use batch values from request or the existing ones
self.batchSize = self.getBatchSize()
self.batchStart = self.getBatchStart()
# use sorting values from request or the existing ones
self.sortOn = self.getSortOn()
self.sortOrder = self.getSortOrder()
# initialize columns
self.initColumns()
# update columns
self.updateColumns()
# setup headers based on columns
self.rows = self.setUpRows()
# sort items on columns
self.sortRows()
# batch sorted rows
self.batchRows()
self.updateBatch()
def render(self):
# allow to use a template for rendering the table, this will allow
# to position the batch before and after the table
return self.renderTable()
def __repr__(self):
return "<{} {!r}>".format(self.__class__.__name__, self.__name__)
@zope.interface.implementer(interfaces.ISequenceTable)
class SequenceTable(Table):
"""Sequence table adapts a sequence as context.
This table can be used for adapting a z3c.indexer.search.ResultSet or
z3c.batching.batch.Batch instance as context. Batch which wraps a
ResultSet sequence.
""" | z3c.table | /z3c.table-3.0.tar.gz/z3c.table-3.0/src/z3c/table/table.py | table.py |
Sorting Table
-------------
Another table feature is the support for sorting data given from columns. Since
sorting table data is an important feature, we offer this by default. But it
only gets used if there is a ``sortOn`` value set. You can set this value at
class level by adding a ``defaultSortOn`` value or set it as a request value.
We show you how to do this later. We also need a columns which allows us to do
a better sort sample. Our new sorting column will use the content items number
value for sorting:
>>> from z3c.table import column, table
>>> class NumberColumn(column.Column):
...
... header = u'Number'
... weight = 20
...
... def getSortKey(self, item):
... return item.number
...
... def renderCell(self, item):
... return 'number: %s' % item.number
Now let's set up a table:
>>> from z3c.table.testing import TitleColumn
>>> class SortingTable(table.Table):
...
... def setUpColumns(self):
... firstColumn = TitleColumn(self.context, self.request, self)
... firstColumn.__name__ = u'title'
... firstColumn.__parent__ = self
... secondColumn = NumberColumn(self.context, self.request, self)
... secondColumn.__name__ = u'number'
... secondColumn.__parent__ = self
... return [firstColumn, secondColumn]
Create a container:
>>> from z3c.table.testing import OrderedContainer
>>> container = OrderedContainer()
We also need some container items that we can use for sorting:
>>> from z3c.table.testing import Content
>>> container[u'first'] = Content('First', 1)
>>> container[u'second'] = Content('Second', 2)
>>> container[u'third'] = Content('Third', 3)
>>> container[u'fourth'] = Content('Fourth', 4)
>>> container[u'zero'] = Content('Zero', 0)
And render them without set a ``sortOn`` value:
>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest()
>>> sortingTable = SortingTable(container, request)
>>> sortingTable.update()
>>> print(sortingTable.render())
<table>
<thead>
<tr>
<th class="sorted-on ascending">Title</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td class="sorted-on ascending">Title: First</td>
<td>number: 1</td>
</tr>
<tr>
<td class="sorted-on ascending">Title: Fourth</td>
<td>number: 4</td>
</tr>
<tr>
<td class="sorted-on ascending">Title: Second</td>
<td>number: 2</td>
</tr>
<tr>
<td class="sorted-on ascending">Title: Third</td>
<td>number: 3</td>
</tr>
<tr>
<td class="sorted-on ascending">Title: Zero</td>
<td>number: 0</td>
</tr>
</tbody>
</table>
Ooops, well, by default the table is sorted on the first column, ascending.
>>> sortingTable.sortOn
0
Now switch off sorting, now we get the original order:
>>> sortingTable.sortOn = None
>>> sortingTable.update()
>>> print(sortingTable.render())
<table>
<thead>
<tr>
<th>Title</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>Title: First</td>
<td>number: 1</td>
</tr>
<tr>
<td>Title: Second</td>
<td>number: 2</td>
</tr>
<tr>
<td>Title: Third</td>
<td>number: 3</td>
</tr>
<tr>
<td>Title: Fourth</td>
<td>number: 4</td>
</tr>
<tr>
<td>Title: Zero</td>
<td>number: 0</td>
</tr>
</tbody>
</table>
As you can see this table doesn't provide any explicit order. Let's find out
the index of our column that we like to sort on:
>>> sortOnId = sortingTable.rows[0][1][1].id
>>> sortOnId
u'table-number-1'
And let's use this id as ``sortOn`` value:
>>> sortingTable.sortOn = sortOnId
An important thing is to update the table after set an ``sortOn`` value:
>>> sortingTable.update()
>>> print(sortingTable.render())
<table>
<thead>
<tr>
<th>Title</th>
<th class="sorted-on ascending">Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>Title: Zero</td>
<td class="sorted-on ascending">number: 0</td>
</tr>
<tr>
<td>Title: First</td>
<td class="sorted-on ascending">number: 1</td>
</tr>
<tr>
<td>Title: Second</td>
<td class="sorted-on ascending">number: 2</td>
</tr>
<tr>
<td>Title: Third</td>
<td class="sorted-on ascending">number: 3</td>
</tr>
<tr>
<td>Title: Fourth</td>
<td class="sorted-on ascending">number: 4</td>
</tr>
</tbody>
</table>
We can also reverse the sorting order:
>>> sortingTable.sortOrder = 'reverse'
>>> sortingTable.update()
>>> print(sortingTable.render())
<table>
<thead>
<tr>
<th>Title</th>
<th class="sorted-on reverse">Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>Title: Fourth</td>
<td class="sorted-on reverse">number: 4</td>
</tr>
<tr>
<td>Title: Third</td>
<td class="sorted-on reverse">number: 3</td>
</tr>
<tr>
<td>Title: Second</td>
<td class="sorted-on reverse">number: 2</td>
</tr>
<tr>
<td>Title: First</td>
<td class="sorted-on reverse">number: 1</td>
</tr>
<tr>
<td>Title: Zero</td>
<td class="sorted-on reverse">number: 0</td>
</tr>
</tbody>
</table>
The table implementation is also able to get the sorting criteria given from a
request. Let's setup such a request:
>>> sorterRequest = TestRequest(form={'table-sortOn': 'table-number-1',
... 'table-sortOrder':'descending'})
and another time, update and render. As you can see the new table gets sorted
by the second column and ordered in reverse order:
>>> requestSortedTable = SortingTable(container, sorterRequest)
>>> requestSortedTable.update()
>>> print(requestSortedTable.render())
<table>
<thead>
<tr>
<th>Title</th>
<th class="sorted-on descending">Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>Title: Fourth</td>
<td class="sorted-on descending">number: 4</td>
</tr>
<tr>
<td>Title: Third</td>
<td class="sorted-on descending">number: 3</td>
</tr>
<tr>
<td>Title: Second</td>
<td class="sorted-on descending">number: 2</td>
</tr>
<tr>
<td>Title: First</td>
<td class="sorted-on descending">number: 1</td>
</tr>
<tr>
<td>Title: Zero</td>
<td class="sorted-on descending">number: 0</td>
</tr>
</tbody>
</table>
There's a header renderer, which provides a handy link rendering for sorting:
>>> import zope.component
>>> from z3c.table import interfaces
>>> from z3c.table.header import SortingColumnHeader
>>> zope.component.provideAdapter(SortingColumnHeader,
... (None, None, interfaces.ITable, interfaces.IColumn),
... provides=interfaces.IColumnHeader)
Let's see now various sortings:
>>> request = TestRequest()
>>> sortingTable = SortingTable(container, request)
>>> sortingTable.update()
>>> sortingTable.sortOn
0
>>> sortingTable.sortOrder
u'ascending'
>>> print(sortingTable.render())
<table>
<thead>
<tr>
<th class="sorted-on ascending"><a href="?table-sortOn=table-title-0&table-sortOrder=descending" title="Sort">Title</a></th>
<th><a href="?table-sortOn=table-number-1&table-sortOrder=ascending" title="Sort">Number</a></th>
</tr>
</thead>
<tbody>
<tr>
<td class="sorted-on ascending">Title: First</td>
<td>number: 1</td>
</tr>
<tr>
<td class="sorted-on ascending">Title: Fourth</td>
<td>number: 4</td>
</tr>
<tr>
<td class="sorted-on ascending">Title: Second</td>
<td>number: 2</td>
</tr>
<tr>
<td class="sorted-on ascending">Title: Third</td>
<td>number: 3</td>
</tr>
<tr>
<td class="sorted-on ascending">Title: Zero</td>
<td>number: 0</td>
</tr>
</tbody>
</table>
Let's see the `number` column:
>>> sortingTable.sortOn = u'table-number-1'
>>> sortingTable.update()
>>> print(sortingTable.render())
<table>
<thead>
<tr>
<th><a href="?table-sortOn=table-title-0&table-sortOrder=ascending" title="Sort">Title</a></th>
<th class="sorted-on ascending"><a href="?table-sortOn=table-number-1&table-sortOrder=descending" title="Sort">Number</a></th>
</tr>
</thead>
<tbody>
<tr>
<td>Title: Zero</td>
<td class="sorted-on ascending">number: 0</td>
</tr>
<tr>
<td>Title: First</td>
<td class="sorted-on ascending">number: 1</td>
</tr>
<tr>
<td>Title: Second</td>
<td class="sorted-on ascending">number: 2</td>
</tr>
<tr>
<td>Title: Third</td>
<td class="sorted-on ascending">number: 3</td>
</tr>
<tr>
<td>Title: Fourth</td>
<td class="sorted-on ascending">number: 4</td>
</tr>
</tbody>
</table>
Let's see the `title` column but descending:
>>> sortingTable.sortOn = u'table-title-0'
>>> sortingTable.sortOrder = 'descending'
>>> sortingTable.update()
>>> print(sortingTable.render())
<table>
<thead>
<tr>
<th class="sorted-on descending"><a href="?table-sortOn=table-title-0&table-sortOrder=ascending" title="Sort">Title</a></th>
<th><a href="?table-sortOn=table-number-1&table-sortOrder=descending" title="Sort">Number</a></th>
</tr>
</thead>
<tbody>
<tr>
<td class="sorted-on descending">Title: Zero</td>
<td>number: 0</td>
</tr>
<tr>
<td class="sorted-on descending">Title: Third</td>
<td>number: 3</td>
</tr>
<tr>
<td class="sorted-on descending">Title: Second</td>
<td>number: 2</td>
</tr>
<tr>
<td class="sorted-on descending">Title: Fourth</td>
<td>number: 4</td>
</tr>
<tr>
<td class="sorted-on descending">Title: First</td>
<td>number: 1</td>
</tr>
</tbody>
</table>
Edge case, do not fail hard when someone tries some weird sortOn value:
>>> sortingTable.sortOn = u'table-title-foobar'
>>> sortingTable.sortOrder = 'ascending'
>>> sortingTable.update()
>>> print(sortingTable.render())
<table>
<thead>
<tr>
<th><a href="?table-sortOn=table-title-0&table-sortOrder=ascending" title="Sort">Title</a></th>
<th><a href="?table-sortOn=table-number-1&table-sortOrder=ascending" title="Sort">Number</a></th>
</tr>
</thead>
<tbody>
<tr>
<td>Title: First</td>
<td>number: 1</td>
</tr>
<tr>
<td>Title: Fourth</td>
<td>number: 4</td>
</tr>
<tr>
<td>Title: Second</td>
<td>number: 2</td>
</tr>
<tr>
<td>Title: Third</td>
<td>number: 3</td>
</tr>
<tr>
<td>Title: Zero</td>
<td>number: 0</td>
</tr>
</tbody>
</table>
| z3c.table | /z3c.table-3.0.tar.gz/z3c.table-3.0/src/z3c/table/sort.rst | sort.rst |
==========
Form Table
==========
The goal of this package is to offer a modular table rendering library which
includes built in support for update forms. This will allow us to adapt items
rendered as table row items to forms. This could prevent to use traversable
exposed forms for such items. But this is just one of the benefits. See more
below.
Form support
------------
We need to setup the form defaults first:
>>> from z3c.form.testing import setupFormDefaults
>>> setupFormDefaults()
And load the formui confguration, which will make sure that all macros get
registered correctly.
>>> from zope.configuration import xmlconfig
>>> import zope.component
>>> import zope.viewlet
>>> import zope.component
>>> import zope.app.publisher.browser
>>> import z3c.macro
>>> import z3c.template
>>> import z3c.formui
>>> xmlconfig.XMLConfig('meta.zcml', zope.component)()
>>> xmlconfig.XMLConfig('meta.zcml', zope.viewlet)()
>>> xmlconfig.XMLConfig('meta.zcml', zope.app.publisher.browser)()
>>> xmlconfig.XMLConfig('meta.zcml', z3c.macro)()
>>> xmlconfig.XMLConfig('meta.zcml', z3c.template)()
>>> xmlconfig.XMLConfig('configure.zcml', z3c.formui)()
And load the z3c.tabular configure.zcml:
>>> import z3c.tabular
>>> xmlconfig.XMLConfig('configure.zcml', z3c.tabular)()
Sample data setup
-----------------
Let's create a sample container which we can use as our iterable context:
>>> from zope.container import btree
>>> class Container(btree.BTreeContainer):
... """Sample container."""
... __name__ = u'container'
>>> container = Container()
and set a parent for the container:
>>> root['container'] = container
and create a sample content object which we use as container item:
>>> import zope.interface
>>> import zope.schema
>>> class IContent(zope.interface.Interface):
... """Content interface."""
...
... title = zope.schema.TextLine(title=u'Title')
... number = zope.schema.Int(title=u'Number')
>>> class Content(object):
... """Sample content."""
... zope.interface.implements(IContent)
... def __init__(self, title, number):
... self.__name__ = title.lower()
... self.title = title
... self.number = number
Now setup some items:
>>> container[u'first'] = Content('First', 1)
>>> container[u'second'] = Content('Second', 2)
>>> container[u'third'] = Content('Third', 3)
FormTable setup
---------------
The ``FormTable`` offers a sub form setup for rendering items within a form.
Let's first define a form for our used items:
>>> from z3c.form import form
>>> from z3c.form import field
>>> class ContentEditForm(form.EditForm):
... fields = field.Fields(IContent)
Now we can define our ``FormTable`` including the SelectedItemColumn:
>>> from z3c.table import column
>>> import z3c.tabular.table
>>> class ContentFormTable(z3c.tabular.table.SubFormTable):
...
... subFormClass = ContentEditForm
...
... def setUpColumns(self):
... return [
... column.addColumn(self, column.SelectedItemColumn,
... u'selectedItem', weight=1),
... ]
And support the div form layer for our request:
>>> from z3c.formui.interfaces import IDivFormLayer
>>> from zope.interface import alsoProvides
>>> from z3c.form.testing import TestRequest
>>> request = TestRequest()
>>> alsoProvides(request, IDivFormLayer)
Now we can render our table. As you can see the ``SelectedItemColumn`` renders
a link which knows hot to select the item:
>>> contentSubFormTable = ContentFormTable(container, request)
>>> contentSubFormTable.__name__ = 'view.html'
>>> contentSubFormTable.update()
>>> print contentSubFormTable.render()
<form action="http://127.0.0.1" method="post"
enctype="multipart/form-data" class="edit-form"
name="subFormTable" id="subFormTable">
<div class="viewspace">
<div>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td valign="top">
<div>
<table class="contents">
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr class="even">
<td><a href="http://127.0.0.1/container/view.html?subFormTable-selectedItem-0-selectedItems=first">first</a></td>
</tr>
<tr class="odd">
<td><a href="http://127.0.0.1/container/view.html?subFormTable-selectedItem-0-selectedItems=second">second</a></td>
</tr>
<tr class="even">
<td><a href="http://127.0.0.1/container/view.html?subFormTable-selectedItem-0-selectedItems=third">third</a></td>
</tr>
</tbody>
</table>
</div>
</td>
<td valign="top">
</td>
</tr>
</table>
</div>
</div>
<div>
<div class="buttons">
<input id="subFormTable-buttons-delete"
name="subFormTable.buttons.delete"
class="submit-widget button-field" value="Delete"
type="submit" />
<input id="subFormTable-buttons-edit"
name="subFormTable.buttons.edit"
class="submit-widget button-field" value="Edit"
type="submit" />
<input id="subFormTable-buttons-cancel"
name="subFormTable.buttons.cancel"
class="submit-widget button-field" value="Cancel"
type="submit" />
</div>
</div>
</form>
Now we are ready to select an item by click on the link. We simulate this by
set the relevant data in the request:
>>> selectRequest = TestRequest(form={
... 'subFormTable-selectedItem-0-selectedItems': 'second'})
>>> alsoProvides(selectRequest, IDivFormLayer)
>>> selectedItemTable = ContentFormTable(container, selectRequest)
>>> selectedItemTable.__name__ = 'view.html'
>>> selectedItemTable.update()
>>> print selectedItemTable.render()
<form action="http://127.0.0.1" method="post" enctype="multipart/form-data" class="edit-form" name="subFormTable" id="subFormTable">
<div class="viewspace">
<div>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td valign="top">
<div>
<table class="contents">
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr class="even">
<td><a href="http://127.0.0.1/container/view.html?subFormTable-selectedItem-0-selectedItems=first">first</a></td>
</tr>
<tr class="selected odd">
<td><a href="http://127.0.0.1/container/view.html?subFormTable-selectedItem-0-selectedItems=second">second</a></td>
</tr>
<tr class="even">
<td><a href="http://127.0.0.1/container/view.html?subFormTable-selectedItem-0-selectedItems=third">third</a></td>
</tr>
</tbody>
</table>
</div>
</td>
<td valign="top">
<div class="tableForm">
<form action="http://127.0.0.1" method="post" enctype="multipart/form-data" class="edit-form" name="form" id="form">
<div class="viewspace">
<div class="required-info">
<span class="required">*</span>– required
</div>
<div>
<div id="form-widgets-title-row" class="row required">
<div class="label">
<label for="form-widgets-title">
<span>Title</span>
<span class="required">*</span>
</label>
</div>
<div class="widget">
<input id="form-widgets-title" name="form.widgets.title" class="text-widget required textline-field" value="Second" type="text" />
</div>
</div>
<div id="form-widgets-number-row" class="row required">
<div class="label">
<label for="form-widgets-number">
<span>Number</span>
<span class="required">*</span>
</label>
</div>
<div class="widget">
<input id="form-widgets-number" name="form.widgets.number" class="text-widget required int-field" value="2" type="text" />
</div>
</div>
</div>
</div>
<div>
<div class="buttons">
<input id="form-buttons-apply" name="form.buttons.apply" class="submit-widget button-field" value="Apply" type="submit" />
</div>
</div>
</form>
</div>
</td>
</tr>
</table>
</div>
</div>
<div>
<div class="buttons">
<input id="subFormTable-buttons-delete" name="subFormTable.buttons.delete" class="submit-widget button-field" value="Delete" type="submit" />
<input id="subFormTable-buttons-edit" name="subFormTable.buttons.edit" class="submit-widget button-field" value="Edit" type="submit" />
<input id="subFormTable-buttons-cancel" name="subFormTable.buttons.cancel" class="submit-widget button-field" value="Cancel" type="submit" />
</div>
</div>
</form>
Clicking the ``Edit`` button at the same time should hold the same result:
>>> selectRequest = TestRequest(form={
... 'subFormTable-selectedItem-0-selectedItems': 'second',
... 'subFormTable.buttons.edit': 'Edit'})
>>> alsoProvides(selectRequest, IDivFormLayer)
>>> selectedItemTable = ContentFormTable(container, selectRequest)
>>> selectedItemTable.__name__ = 'view.html'
>>> selectedItemTable.update()
>>> print selectedItemTable.render()
<form action="http://127.0.0.1" method="post" enctype="multipart/form-data" class="edit-form" name="subFormTable" id="subFormTable">
<div class="viewspace">
<div>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td valign="top">
<div>
<table class="contents">
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr class="even">
<td><a href="http://127.0.0.1/container/view.html?subFormTable-selectedItem-0-selectedItems=first">first</a></td>
</tr>
<tr class="selected odd">
<td><a href="http://127.0.0.1/container/view.html?subFormTable-selectedItem-0-selectedItems=second">second</a></td>
</tr>
<tr class="even">
<td><a href="http://127.0.0.1/container/view.html?subFormTable-selectedItem-0-selectedItems=third">third</a></td>
</tr>
</tbody>
</table>
</div>
</td>
<td valign="top">
<div class="tableForm">
<form action="http://127.0.0.1" method="post" enctype="multipart/form-data" class="edit-form" name="form" id="form">
<div class="viewspace">
<div class="required-info">
<span class="required">*</span>– required
</div>
<div>
<div id="form-widgets-title-row" class="row required">
<div class="label">
<label for="form-widgets-title">
<span>Title</span>
<span class="required">*</span>
</label>
</div>
<div class="widget">
<input id="form-widgets-title" name="form.widgets.title" class="text-widget required textline-field" value="Second" type="text" />
</div>
</div>
<div id="form-widgets-number-row" class="row required">
<div class="label">
<label for="form-widgets-number">
<span>Number</span>
<span class="required">*</span>
</label>
</div>
<div class="widget">
<input id="form-widgets-number" name="form.widgets.number" class="text-widget required int-field" value="2" type="text" />
</div>
</div>
</div>
</div>
<div>
<div class="buttons">
<input id="form-buttons-apply" name="form.buttons.apply" class="submit-widget button-field" value="Apply" type="submit" />
</div>
</div>
</form>
</div>
</td>
</tr>
</table>
</div>
</div>
<div>
<div class="buttons">
<input id="subFormTable-buttons-delete" name="subFormTable.buttons.delete" class="submit-widget button-field" value="Delete" type="submit" />
<input id="subFormTable-buttons-edit" name="subFormTable.buttons.edit" class="submit-widget button-field" value="Edit" type="submit" />
<input id="subFormTable-buttons-cancel" name="subFormTable.buttons.cancel" class="submit-widget button-field" value="Cancel" type="submit" />
</div>
</div>
</form>
Unless ``allowEdit`` is ``False``.
In this case the editform won't appear.
>>> selectRequest = TestRequest(form={
... 'subFormTable-selectedItem-0-selectedItems': 'second',
... 'subFormTable.buttons.edit': 'Edit'})
>>> alsoProvides(selectRequest, IDivFormLayer)
>>> selectedItemTable = ContentFormTable(container, selectRequest)
>>> selectedItemTable.__name__ = 'view.html'
>>> selectedItemTable.allowEdit = False
>>> selectedItemTable.update()
>>> print selectedItemTable.render()
<form action="http://127.0.0.1" method="post"
enctype="multipart/form-data" class="edit-form"
name="subFormTable" id="subFormTable">
<div class="viewspace">
<div>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td valign="top">
<div>
<table class="contents">
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr class="even">
<td><a href="http://127.0.0.1/container/view.html?subFormTable-selectedItem-0-selectedItems=first">first</a></td>
</tr>
<tr class="selected odd">
<td><a href="http://127.0.0.1/container/view.html?subFormTable-selectedItem-0-selectedItems=second">second</a></td>
</tr>
<tr class="even">
<td><a href="http://127.0.0.1/container/view.html?subFormTable-selectedItem-0-selectedItems=third">third</a></td>
</tr>
</tbody>
</table>
</div>
</td>
<td valign="top">
</td>
</tr>
</table>
</div>
</div>
<div>
<div class="buttons">
<input id="subFormTable-buttons-delete"
name="subFormTable.buttons.delete"
class="submit-widget button-field" value="Delete"
type="submit" />
<input id="subFormTable-buttons-cancel"
name="subFormTable.buttons.cancel"
class="submit-widget button-field" value="Cancel"
type="submit" />
</div>
</div>
</form>
| z3c.tabular | /z3c.tabular-0.6.2.zip/z3c.tabular-0.6.2/src/z3c/tabular/README.txt | README.txt |
__docformat__ = "reStructuredText"
import transaction
import zope.interface
import zope.i18nmessageid
from z3c.form import button
from z3c.formui import form
from z3c.table import table
from z3c.template.template import getPageTemplate
from z3c.tabular import interfaces
_ = zope.i18nmessageid.MessageFactory('z3c')
# simple template rendering aware table base class
class TemplateTable(table.Table):
"""Template aware teble."""
zope.interface.implements(interfaces.ITemplateTable)
template = getPageTemplate()
def render(self):
"""Render the template."""
return self.template()
# simple form aware table base class
class TableBase(TemplateTable):
"""Generic table class with form action support used as form mixin base.
This table base class allows you to mixin custom forms as base.
"""
prefix = 'formTable'
# internal defaults
actions = None
hasContent = False
nextURL = None
selectedItems = []
ignoreContext = False
# table defaults
cssClasses = {'table': 'contents'}
cssClassEven = u'even'
cssClassOdd = u'odd'
cssClassSelected = u'selected'
batchSize = 25
startBatchingAt = 25
# customize this part
allowCancel = True
supportsCancel = False
def update(self):
# 1. setup widgets
self.updateWidgets()
# 2. setup search values, generate rows, setup headers and columns
super(TableBase, self).update()
# 3. setup conditions
self.setupConditions()
# 4. setup form part
self.updateActions()
if self.actions is not None:
self.actions.execute()
def setupConditions(self):
self.hasContent = bool(self.rows)
if self.allowCancel:
self.supportsCancel = self.hasContent
def updateAfterActionExecution(self):
"""Update table data if subform changes soemthing."""
# first update table data which probably changed
super(TableBase, self).update()
# second setup conditions
self.setupConditions()
# third update action which we have probably different conditions for
self.updateActions()
@button.buttonAndHandler(_('Cancel'), name='cancel',
condition=lambda form:form.supportsCancel)
def handleCancel(self, action):
self.nextURL = self.request.getURL()
def render(self):
"""Render the template."""
if self.nextURL is not None:
self.request.response.redirect(self.nextURL)
return ""
return self.template()
class FormTable(TableBase, form.Form):
"""Generic table class with form action support based on IForm."""
zope.interface.implements(interfaces.IFormTable)
template = getPageTemplate()
class DeleteFormTable(FormTable):
"""Table class with form action support based on IForm."""
zope.interface.implements(interfaces.IDeleteFormTable)
prefix = 'deleteFormTable'
# internal defaults
supportsCancel = False
supportsDelete = False
deleteErrorMessage = _('Could not delete the selected items')
deleteNoItemsMessage = _('No items selected for delete')
deleteSuccessMessage = _('Data successfully deleted')
# customize this part
allowCancel = True
allowDelete = True
def executeDelete(self, item):
raise NotImplementedError('Subclass must implement executeDelete')
def setupConditions(self):
self.hasContent = bool(self.rows)
if self.allowCancel:
self.supportsCancel = self.hasContent
if self.allowDelete:
self.supportsDelete = self.hasContent
def doDelete(self, action):
if not len(self.selectedItems):
self.status = self.deleteNoItemsMessage
return
try:
for item in self.selectedItems:
self.executeDelete(item)
# update the table rows before we start with rendering
self.updateAfterActionExecution()
if self.status is None:
# probably execute delete or updateAfterAction already set a
# status
self.status = self.deleteSuccessMessage
except KeyError:
self.status = self.deleteErrorMessage
transaction.doom()
@button.buttonAndHandler(_('Delete'), name='delete',
condition=lambda form:form.supportsDelete)
def handleDelete(self, action):
self.doDelete(action)
# form table including a sub form
class SubFormTable(DeleteFormTable):
"""Form table including a sub form based on IForm."""
zope.interface.implements(interfaces.ISubFormTable)
buttons = DeleteFormTable.buttons.copy()
handlers = DeleteFormTable.handlers.copy()
prefix = 'subFormTable'
# internal defaults
subForm = None
supportsEdit = False
# error messages
subFormNoItemMessage = _('No item selected for edit')
subFormToManyItemsMessage = _('Only one item could be selected for edit')
subFormNotFoundMessage = _('No edit form found for selected item')
# customize this part
# use subFormClass or use subFormName. If you set both it will end in
# using subFormClass. See updateSubForm for details.
subFormClass = None
subFormName = u''
allowEdit = True
def update(self):
# 1. setup widgets
super(SubFormTable, self).update()
# 2. setup form after we set probably a selectedItem
self.updateSubForm()
def setupConditions(self):
super(SubFormTable, self).setupConditions()
if self.allowEdit:
self.supportsEdit = self.hasContent
@property
def selectedItem(self):
if len(self.selectedItems) == 0:
return None
if len(self.selectedItems) > 1:
self.status = self.subFormToManyItemsMessage
return None
return self.selectedItems[0]
def setUpSubForm(self, selectedItem):
if self.subFormClass is not None:
return self.subFormClass(selectedItem, self.request)
elif self.subFormName is not None:
return zope.component.queryMultiAdapter((selectedItem,
self.request), name=self.subFormName)
def updateSubForm(self):
if not self.supportsEdit:
return
selectedItem = self.selectedItem
if selectedItem is None:
return
# set table as parent
self.subForm = self.setUpSubForm(selectedItem)
if self.subForm is None:
self.status = self.subFormNotFoundMessage
return
self.subForm.__parent__ = self
# udpate edit form
self.subForm.update()
def doSubForm(self, action):
if self.subForm is None:
return
# set ignore request and update again
self.subForm.ignoreRequest = True
self.subForm.update()
@button.buttonAndHandler(u'Edit', condition=lambda form:form.supportsEdit)
def handleSubForm(self, action):
self.updateSubForm()
self.doSubForm(action)
@button.buttonAndHandler(_('Cancel'), name='cancel',
condition=lambda form:form.supportsCancel)
def handleCancel(self, action):
self.nextURL = self.request.getURL() | z3c.tabular | /z3c.tabular-0.6.2.zip/z3c.tabular-0.6.2/src/z3c/tabular/table.py | table.py |
import os, shutil, sys, tempfile, urllib, urllib2, subprocess
from optparse import OptionParser
if sys.platform == 'win32':
def quote(c):
if ' ' in c:
return '"%s"' % c # work around spawn lamosity on windows
else:
return c
else:
quote = str
# See zc.buildout.easy_install._has_broken_dash_S for motivation and comments.
stdout, stderr = subprocess.Popen(
[sys.executable, '-Sc',
'try:\n'
' import ConfigParser\n'
'except ImportError:\n'
' print 1\n'
'else:\n'
' print 0\n'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
has_broken_dash_S = bool(int(stdout.strip()))
# In order to be more robust in the face of system Pythons, we want to
# run without site-packages loaded. This is somewhat tricky, in
# particular because Python 2.6's distutils imports site, so starting
# with the -S flag is not sufficient. However, we'll start with that:
if not has_broken_dash_S and 'site' in sys.modules:
# We will restart with python -S.
args = sys.argv[:]
args[0:0] = [sys.executable, '-S']
args = map(quote, args)
os.execv(sys.executable, args)
# Now we are running with -S. We'll get the clean sys.path, import site
# because distutils will do it later, and then reset the path and clean
# out any namespace packages from site-packages that might have been
# loaded by .pth files.
clean_path = sys.path[:]
import site # imported because of its side effects
sys.path[:] = clean_path
for k, v in sys.modules.items():
if k in ('setuptools', 'pkg_resources') or (
hasattr(v, '__path__') and
len(v.__path__) == 1 and
not os.path.exists(os.path.join(v.__path__[0], '__init__.py'))):
# This is a namespace package. Remove it.
sys.modules.pop(k)
is_jython = sys.platform.startswith('java')
setuptools_source = 'http://peak.telecommunity.com/dist/ez_setup.py'
distribute_source = 'http://python-distribute.org/distribute_setup.py'
# parsing arguments
def normalize_to_url(option, opt_str, value, parser):
if value:
if '://' not in value: # It doesn't smell like a URL.
value = 'file://%s' % (
urllib.pathname2url(
os.path.abspath(os.path.expanduser(value))),)
if opt_str == '--download-base' and not value.endswith('/'):
# Download base needs a trailing slash to make the world happy.
value += '/'
else:
value = None
name = opt_str[2:].replace('-', '_')
setattr(parser.values, name, value)
usage = '''\
[DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options]
Bootstraps a buildout-based project.
Simply run this script in a directory containing a buildout.cfg, using the
Python that you want bin/buildout to use.
Note that by using --setup-source and --download-base to point to
local resources, you can keep this script from going over the network.
'''
parser = OptionParser(usage=usage)
parser.add_option("-v", "--version", dest="version",
help="use a specific zc.buildout version")
parser.add_option("-d", "--distribute",
action="store_true", dest="use_distribute", default=False,
help="Use Distribute rather than Setuptools.")
parser.add_option("--setup-source", action="callback", dest="setup_source",
callback=normalize_to_url, nargs=1, type="string",
help=("Specify a URL or file location for the setup file. "
"If you use Setuptools, this will default to " +
setuptools_source + "; if you use Distribute, this "
"will default to " + distribute_source + "."))
parser.add_option("--download-base", action="callback", dest="download_base",
callback=normalize_to_url, nargs=1, type="string",
help=("Specify a URL or directory for downloading "
"zc.buildout and either Setuptools or Distribute. "
"Defaults to PyPI."))
parser.add_option("--eggs",
help=("Specify a directory for storing eggs. Defaults to "
"a temporary directory that is deleted when the "
"bootstrap script completes."))
parser.add_option("-t", "--accept-buildout-test-releases",
dest='accept_buildout_test_releases',
action="store_true", default=False,
help=("Normally, if you do not specify a --version, the "
"bootstrap script and buildout gets the newest "
"*final* versions of zc.buildout and its recipes and "
"extensions for you. If you use this flag, "
"bootstrap and buildout will get the newest releases "
"even if they are alphas or betas."))
parser.add_option("-c", None, action="store", dest="config_file",
help=("Specify the path to the buildout configuration "
"file to be used."))
options, args = parser.parse_args()
if options.eggs:
eggs_dir = os.path.abspath(os.path.expanduser(options.eggs))
else:
eggs_dir = tempfile.mkdtemp()
if options.setup_source is None:
if options.use_distribute:
options.setup_source = distribute_source
else:
options.setup_source = setuptools_source
if options.accept_buildout_test_releases:
args.insert(0, 'buildout:accept-buildout-test-releases=true')
try:
import pkg_resources
import setuptools # A flag. Sometimes pkg_resources is installed alone.
if not hasattr(pkg_resources, '_distribute'):
raise ImportError
except ImportError:
ez_code = urllib2.urlopen(
options.setup_source).read().replace('\r\n', '\n')
ez = {}
exec ez_code in ez
setup_args = dict(to_dir=eggs_dir, download_delay=0)
if options.download_base:
setup_args['download_base'] = options.download_base
if options.use_distribute:
setup_args['no_fake'] = True
if sys.version_info[:2] == (2, 4):
setup_args['version'] = '0.6.32'
ez['use_setuptools'](**setup_args)
if 'pkg_resources' in sys.modules:
reload(sys.modules['pkg_resources'])
import pkg_resources
# This does not (always?) update the default working set. We will
# do it.
for path in sys.path:
if path not in pkg_resources.working_set.entries:
pkg_resources.working_set.add_entry(path)
cmd = [quote(sys.executable),
'-c',
quote('from setuptools.command.easy_install import main; main()'),
'-mqNxd',
quote(eggs_dir)]
if not has_broken_dash_S:
cmd.insert(1, '-S')
find_links = options.download_base
if not find_links:
find_links = os.environ.get('bootstrap-testing-find-links')
if not find_links and options.accept_buildout_test_releases:
find_links = 'http://downloads.buildout.org/'
if find_links:
cmd.extend(['-f', quote(find_links)])
if options.use_distribute:
setup_requirement = 'distribute'
else:
setup_requirement = 'setuptools'
ws = pkg_resources.working_set
setup_requirement_path = ws.find(
pkg_resources.Requirement.parse(setup_requirement)).location
env = dict(
os.environ,
PYTHONPATH=setup_requirement_path)
requirement = 'zc.buildout'
version = options.version
if version is None and not options.accept_buildout_test_releases:
# Figure out the most recent final version of zc.buildout.
import setuptools.package_index
_final_parts = '*final-', '*final'
def _final_version(parsed_version):
for part in parsed_version:
if (part[:1] == '*') and (part not in _final_parts):
return False
return True
index = setuptools.package_index.PackageIndex(
search_path=[setup_requirement_path])
if find_links:
index.add_find_links((find_links,))
req = pkg_resources.Requirement.parse(requirement)
if index.obtain(req) is not None:
best = []
bestv = None
for dist in index[req.project_name]:
distv = dist.parsed_version
if distv >= pkg_resources.parse_version('2dev'):
continue
if _final_version(distv):
if bestv is None or distv > bestv:
best = [dist]
bestv = distv
elif distv == bestv:
best.append(dist)
if best:
best.sort()
version = best[-1].version
if version:
requirement += '=='+version
else:
requirement += '<2dev'
cmd.append(requirement)
if is_jython:
import subprocess
exitcode = subprocess.Popen(cmd, env=env).wait()
else: # Windows prefers this, apparently; otherwise we would prefer subprocess
exitcode = os.spawnle(*([os.P_WAIT, sys.executable] + cmd + [env]))
if exitcode != 0:
sys.stdout.flush()
sys.stderr.flush()
print ("An error occurred when trying to install zc.buildout. "
"Look above this message for any errors that "
"were output by easy_install.")
sys.exit(exitcode)
ws.add_entry(eggs_dir)
ws.require(requirement)
import zc.buildout.buildout
# If there isn't already a command in the args, add bootstrap
if not [a for a in args if '=' not in a]:
args.append('bootstrap')
# if -c was provided, we push it back into args for buildout's main function
if options.config_file is not None:
args[0:0] = ['-c', options.config_file]
zc.buildout.buildout.main(args)
if not options.eggs: # clean up temporary egg directory
shutil.rmtree(eggs_dir) | z3c.taskqueue | /z3c.taskqueue-0.2.1.zip/z3c.taskqueue-0.2.1/bootstrap.py | bootstrap.py |
__docformat__ = 'restructuredtext'
from zope import interface
from zope import schema
from zope.configuration import fields
from zope.container.interfaces import IContained
QUEUED = 'queued'
PROCESSING = 'processing'
CANCELLED = 'cancelled'
ERROR = 'error'
COMPLETED = 'completed'
DELAYED = 'delayed'
CRONJOB = 'cronjob'
DELAYED = 'delayed'
STARTLATER = 'start later'
class ITask(interface.Interface):
"""A task available in the task service"""
inputSchema = schema.Object(
title=u'Input Schema',
description=u'A schema describing the task input signature.',
schema=interface.Interface,
required=False)
outputSchema = schema.Object(
title=u'Output Schema',
description=u'A schema describing the task output signature.',
schema=interface.Interface,
required=False)
def __call__(service, jobid, input):
"""Execute the task.
The ``service`` argument is the task service object. It allows access
to service wide data and the system as a whole.
Tasks do not live in a vacuum, but are tightly coupled to the job
executing it. The ``jobid`` argument provides the id of the job being
processed.
The ``input`` object must conform to the input schema (if
specified). The return value must conform to the output schema.
"""
class ITaskService(IContained):
"""A service for managing and executing tasks."""
jobs = schema.Object(
title=u'Jobs',
description=u'A mapping of all jobs by job id.',
schema=interface.common.mapping.IMapping)
taskInterface = fields.GlobalInterface(
title=u'Task Interface',
description=u'The interface to lookup task utilities',
default=ITask,
)
def getAvailableTasks():
"""Return a mapping of task name to the task."""
def add(task, input=None, startLater=False):
"""Add a new job for the specified task.
* task argument is a string specifying the task.
* input are arguments for the task.
* startLater, if True job will be added (gets a jobid) but needs
to be started with startJob later
"""
def addCronJob(task, input,
minute=(),
hour=(),
dayOfMonth=(),
month=(),
dayOfWeek=(),
):
"""Add a new cron job."""
def startJob(jobid):
"""Start a job previously added job with add(..., startLater=True)
"""
def reschedule(jobid):
"""Rescheudle a cron job.
This is neccessary if the cron jobs parameters are changed.
"""
def clean(status=[CANCELLED, ERROR, COMPLETED]):
"""removes all jobs which are completed or canceled or have errors."""
def cancel(jobid):
"""Cancel a particular job."""
def getStatus(jobid):
"""Get the status of a job."""
def getResult(jobid):
"""Get the result data structure of the job."""
def getError(jobid):
"""Get the error of the job."""
def hasJobsWaiting(now=None):
"""Determine whether there are jobs that need to be processed.
Returns a simple boolean.
"""
def processNext():
"""Process the next job in the queue."""
def process():
"""Process all scheduled jobs.
This call blocks the thread it is running in.
"""
def startProcessing():
"""Start processing jobs.
This method has to be called after every server restart.
"""
def stopProcessing():
"""Stop processing jobs."""
def isProcessing():
"""Check whether the jobs are being processed.
Return a boolean representing the state.
"""
class IJob(interface.Interface):
"""An internal job object."""
id = schema.Int(
title=u'Id',
description=u'The job id.',
required=True)
task = schema.TextLine(
title=u'Task',
description=u'The task to be completed.',
required=True)
status = schema.Choice(
title=u'Status',
description=u'The current status of the job.',
values=[QUEUED, PROCESSING, CANCELLED, ERROR,
COMPLETED, DELAYED, CRONJOB, STARTLATER],
required=True)
input = schema.Object(
title=u'Input',
description=u'The input for the task.',
schema=interface.Interface,
required=False)
output = schema.Object(
title=u'Output',
description=u'The output of the task.',
schema=interface.Interface,
required=False,
default=None)
error = schema.Object(
title=u'Error',
description=u'The error object when the task failed.',
schema=interface.Interface,
required=False,
default=None)
created = schema.Datetime(
title=u'Creation Date',
description=u'The date/time at which the job was created.',
required=True)
started = schema.Datetime(
title=u'Start Date',
description=u'The date/time at which the job was started.')
completed = schema.Datetime(
title=u'Completion Date',
description=u'The date/time at which the job was completed.')
class ICronJob(IJob):
"""Parameters for cron jobs"""
minute = schema.Tuple(
title=u'minute(s)',
default=(),
required=False,
)
hour = schema.Tuple(
title=u'hour(s)',
default=(),
required=False,
)
dayOfMonth = schema.Tuple(
title=u'day of month',
default=(),
required=False,
)
month = schema.Tuple(
title=u'month(s)',
default=(),
required=False,
)
dayOfWeek = schema.Tuple(
title=u'day of week',
default=(),
required=False,
)
delay = schema.Int(
title=u'delay',
default=0,
required=False,
)
scheduledFor = schema.Datetime(
title=u'scheduled',
default=None,
required=False,
)
def update(minute, hour, dayOfMonth, month, dayOfWeek, delay):
"""Update the cron job.
The job must be rescheduled in the containing service.
"""
def timeOfNextCall(now=None):
"""Calculate the time for the next call of the job.
now is a convenience parameter for testing.
"""
class IProcessor(interface.Interface):
"""Job Processor
Process the jobs that are waiting in the queue. A processor is meant to
be run in a separate thread. To complete a job, it simply calls back into
the task server. This works, since it does not use up any Web server
threads.
Processing a job can take a long time. However, we do not have to worry
about transaction conflicts, since no other request is touching the job
object.
"""
running = schema.Bool(
title=u"Running Flag",
description=u"Tells whether the processor is currently running.",
readonly=True)
def __call__(db, servicePath):
"""Run the processor.
The ``db`` is a ZODB instance that is used to call back into the task
service. The ``servicePath`` specifies how to traverse to the task
service itself.
""" | z3c.taskqueue | /z3c.taskqueue-0.2.1.zip/z3c.taskqueue-0.2.1/src/z3c/taskqueue/interfaces.py | interfaces.py |
__docformat__ = 'restructuredtext'
from zope import component
from zope.container import contained
from zope.component.interfaces import ComponentLookupError
import threading
import datetime
import logging
import persistent
import random
import time
import zc.queue
import zope.interface
from z3c.taskqueue import interfaces, job, task
from z3c.taskqueue import processor
import z3c.taskqueue
log = logging.getLogger('z3c.taskqueue')
storage = threading.local()
class BaseTaskService(contained.Contained, persistent.Persistent):
"""A persistent task service.
The available tasks for this service are managed as utilities.
"""
zope.interface.implements(interfaces.ITaskService)
taskInterface = interfaces.ITask
_v_nextid = None
containerClass = None
processorFactory = processor.SimpleProcessor
processorArguments = {'waitTime': 1.0}
def __init__(self):
super(BaseTaskService, self).__init__()
self.jobs = self.containerClass()
self._scheduledJobs = self.containerClass()
self._queue = zc.queue.Queue()
self._scheduledQueue = zc.queue.Queue()
def getAvailableTasks(self):
"""See interfaces.ITaskService"""
return dict(component.getUtilitiesFor(self.taskInterface))
def add(self, task, input=None, startLater=False):
"""See interfaces.ITaskService"""
if task not in self.getAvailableTasks():
raise ValueError('Task does not exist')
jobid = self._generateId()
newjob = job.Job(jobid, task, input)
self.jobs[jobid] = newjob
if startLater:
newjob.status = interfaces.STARTLATER
else:
self._queue.put(newjob)
newjob.status = interfaces.QUEUED
return jobid
def addCronJob(self, task, input=None,
minute=(),
hour=(),
dayOfMonth=(),
month=(),
dayOfWeek=(),
delay=None,
):
jobid = self._generateId()
newjob = job.CronJob(jobid, task, input,
minute, hour, dayOfMonth, month, dayOfWeek, delay)
self.jobs[jobid] = newjob
if newjob.delay is None:
newjob.status = interfaces.CRONJOB
else:
newjob.status = interfaces.DELAYED
self._scheduledQueue.put(newjob)
return jobid
def startJob(self, jobid):
job = self.jobs[jobid]
if job.status == interfaces.STARTLATER:
self._queue.put(job)
job.status = interfaces.QUEUED
return True
return False
def reschedule(self, jobid):
self._scheduledQueue.put(self.jobs[jobid])
def clean(self, status=[interfaces.CANCELLED, interfaces.ERROR,
interfaces.COMPLETED]):
"""See interfaces.ITaskService"""
allowed = [interfaces.CANCELLED, interfaces.ERROR,
interfaces.COMPLETED]
for key in list(self.jobs.keys()):
job = self.jobs[key]
if job.status in status:
if job.status not in allowed:
raise ValueError('Not allowed status for removing. %s' %
job.status)
del self.jobs[key]
def cancel(self, jobid):
"""See interfaces.ITaskService"""
for idx, job in enumerate(self._queue):
if job.id == jobid:
job.status = interfaces.CANCELLED
self._queue.pull(idx)
break
if jobid in self.jobs:
job = self.jobs[jobid]
if (job.status == interfaces.CRONJOB
or job.status == interfaces.DELAYED
or job.status == interfaces.STARTLATER):
job.status = interfaces.CANCELLED
def getStatus(self, jobid):
"""See interfaces.ITaskService"""
return self.jobs[jobid].status
def getResult(self, jobid):
"""See interfaces.ITaskService"""
return self.jobs[jobid].output
def getError(self, jobid):
"""See interfaces.ITaskService"""
return self.jobs[jobid].error
def hasJobsWaiting(self, now=None):
"""
are there jobs waiting ?
"""
# If there is are any simple jobs in the queue, we have work to do.
if self._queue:
return True
# First, move new cron jobs from the scheduled queue into the cronjob
# list.
if now is None:
now = int(time.time())
while len(self._scheduledQueue) > 0:
job = self._scheduledQueue.pull()
if job.status is not interfaces.CANCELLED:
self._insertCronJob(job, now)
# Now get all jobs that should be done now or earlier; if there are
# any that do not have errors or are cancelled, then we have jobs to
# do.
for key in self._scheduledJobs.keys(max=now):
jobs = [job for job in self._scheduledJobs[key]
if job.status not in (interfaces.CANCELLED,
interfaces.ERROR)]
if jobs:
return True
return False
def claimNextJob(self, now=None):
"""
claim next hob
"""
job = self._pullJob(now)
return job and job.id or None
def processNext(self, now=None, jobid=None):
"""
process next job in the queue
"""
if jobid is None:
job = self._pullJob(now)
else:
job = self.jobs[jobid]
if job is None:
return False
if job.status == interfaces.COMPLETED:
return True
try:
jobtask = component.getUtility(self.taskInterface, name=job.task)
except ComponentLookupError, error:
log.error('Task "%s" not found!' % job.task)
log.exception(error)
job.setError(error)
if job.status != interfaces.CRONJOB:
job.status = interfaces.ERROR
return True
job.started = datetime.datetime.now()
if not hasattr(storage, 'runCount'):
storage.runCount = 0
storage.runCount += 1
try:
job.output = jobtask(self, job.id, job.input)
if job.status != interfaces.CRONJOB:
job.status = interfaces.COMPLETED
except task.TaskError, error:
job.setError(error)
if job.status != interfaces.CRONJOB:
job.status = interfaces.ERROR
except Exception, error:
if storage.runCount <= 3:
log.error('Caught a generic exception, preventing thread '
'from crashing')
log.exception(str(error))
raise
else:
job.setError(error)
if job.status != interfaces.CRONJOB:
job.status = interfaces.ERROR
else:
storage.runCount = 0
job.completed = datetime.datetime.now()
return True
def process(self, now=None):
"""See interfaces.ITaskService"""
while self.processNext(now):
pass
def _pullJob(self, now=None):
# first move new cron jobs from the scheduled queue into the cronjob
# list
if now is None:
now = int(time.time())
while len(self._scheduledQueue) > 0:
job = self._scheduledQueue.pull()
if job.status is not interfaces.CANCELLED:
self._insertCronJob(job, now)
# try to get the next cron job
while True:
try:
first = self._scheduledJobs.minKey()
except ValueError:
break
else:
if first > now:
break
jobs = self._scheduledJobs[first]
job = jobs[0]
self._scheduledJobs[first] = jobs[1:]
if len(self._scheduledJobs[first]) == 0:
del self._scheduledJobs[first]
if (job.status != interfaces.CANCELLED
and job.status != interfaces.ERROR):
if job.status != interfaces.DELAYED:
self._insertCronJob(job, now)
return job
# get a job from the input queue
if self._queue:
return self._queue.pull()
return None
def _insertCronJob(self, job, now):
for callTime, scheduled in list(self._scheduledJobs.items()):
if job in scheduled:
scheduled = list(scheduled)
scheduled.remove(job)
if len(scheduled) == 0:
del self._scheduledJobs[callTime]
else:
self._scheduledJobs[callTime] = tuple(scheduled)
break
nextCallTime = job.timeOfNextCall(now)
job.scheduledFor = datetime.datetime.fromtimestamp(nextCallTime)
set = self._scheduledJobs.get(nextCallTime)
if set is None:
self._scheduledJobs[nextCallTime] = ()
jobs = self._scheduledJobs[nextCallTime]
self._scheduledJobs[nextCallTime] = jobs + (job,)
def _generateId(self):
"""Generate an id which is not yet taken.
This tries to allocate sequential ids so they fall into the
same BTree bucket, and randomizes if it stumbles upon a
used one.
"""
while True:
if self._v_nextid is None:
self._v_nextid = random.randrange(0, self.maxint)
uid = self._v_nextid
self._v_nextid += 1
if uid not in self.jobs:
return uid
self._v_nextid = None
def startProcessing(self):
"""See interfaces.ITaskService"""
if self.__parent__ is None:
return
if self._scheduledJobs is None:
self._scheduledJobs = self.containerClass()
if self._scheduledQueue is None:
self._scheduledQueue = zc.queue.PersistentQueue()
# Create the path to the service within the DB.
servicePath = self.getServicePath()
log.info('starting service %s' % ".".join(servicePath))
# Start the thread running the processor inside.
#
db = z3c.taskqueue.GLOBALDB
if db is None:
raise ValueError('z3c.taskqueue.GLOBALDB is not initialized; '
'should be done with IDatabaseOpenedWithRootEvent')
processor = self.processorFactory(
db, servicePath, **self.processorArguments)
threadName = self._threadName()
thread = threading.Thread(target=processor, name=threadName)
thread.setDaemon(True)
thread.running = True
thread.start()
def stopProcessing(self):
"""See interfaces.ITaskService"""
if self.__name__ is None:
return
servicePath = self.getServicePath()
log.info('stopping service %s' % ".".join(servicePath))
threadName = self._threadName()
for thread in threading.enumerate():
if thread.getName() == threadName:
thread.running = False
break
def isProcessing(self):
"""See interfaces.ITaskService"""
if self.__name__ is not None:
name = self._threadName()
for thread in threading.enumerate():
if thread.getName() == name:
if thread.running:
return True
break
return False
def getServicePath(self):
raise NotImplemented
THREADNAME_PREFIX = 'taskqueue'
def _threadName(self):
"""Return name of the processing thread."""
# This name isn't unique based on the path to self, but this doesn't
# change the name that's been used in past versions.
path = self.getServicePath()
path.insert(0, self.THREADNAME_PREFIX)
return '.'.join(path) | z3c.taskqueue | /z3c.taskqueue-0.2.1.zip/z3c.taskqueue-0.2.1/src/z3c/taskqueue/baseservice.py | baseservice.py |
=====================
Remote Task Execution
=====================
.. contents::
This package provides an implementation of a task queue service
It is also possible to run cron jobs at specific times.
Usage
_____
>>> STOP_SLEEP_TIME = 0.02
Let's now start by creating a single service:
>>> from z3c import taskqueue
>>> service = taskqueue.service.TaskService()
We can discover the available tasks:
>>> service.getAvailableTasks()
{}
This list is initially empty, because we have not registered any tasks. Let's
now define a task that simply echos an input string:
>>> def echo(input):
... return input
>>> echoTask = taskqueue.task.SimpleTask(echo)
The only API requirement on the converter is to be callable. Now we make sure
that the task works:
>>> echoTask(service, 1, input={'foo': 'blah'})
{'foo': 'blah'}
Let's now register the task as a utility:
>>> import zope.component
>>> zope.component.provideUtility(echoTask, name='echo')
The echo task is now available in the service:
>>> service.getAvailableTasks()
{u'echo': <SimpleTask <function echo ...>>}
Since the service cannot instantaneously complete a task, incoming jobs are
managed by a queue. First we request the echo task to be executed:
>>> jobid = service.add(u'echo', {'foo': 'bar'})
>>> jobid
1392637175
The ``add()`` function schedules the task called "echo" to be executed with
the specified arguments. The method returns a job id with which we can inquire
about the job.
By default the ``add()`` function adds and starts the job ASAP. Sometimes we need
to have a jobid but not to start the job yet. See startlater.txt how.
>>> service.getStatus(jobid)
'queued'
Since the job has not been processed, the status is set to "queued". Further,
there is no result available yet:
>>> service.getResult(jobid) is None
True
As long as the job is not being processed, it can be cancelled:
>>> service.cancel(jobid)
>>> service.getStatus(jobid)
'cancelled'
Let's add another job:
>>> jobid = service.add(u'echo', {'foo': 'bar'})
>>> service.processNext()
True
>>> service.getStatus(jobid)
'completed'
>>> service.getResult(jobid)
{'foo': 'bar'}
Now, let's define a new task that causes an error:
>>> def error(input):
... raise taskqueue.task.TaskError('An error occurred.')
>>> zope.component.provideUtility(
... taskqueue.task.SimpleTask(error), name='error')
Now add and execute it:
>>> jobid = service.add(u'error')
>>> service.processNext()
True
Let's now see what happened:
>>> service.getStatus(jobid)
'error'
>>> service.getError(jobid)
'An error occurred.'
For management purposes, the service also allows you to inspect all jobs:
>>> dict(service.jobs)
{1392637176: <Job 1392637176>, 1392637177: <Job 1392637177>, 1392637175: <Job 1392637175>}
To get rid of jobs not needed anymore one can use the clean method.
>>> jobid = service.add(u'echo', {'blah': 'blah'})
>>> sorted([job.status for job in service.jobs.values()])
['cancelled', 'completed', 'error', 'queued']
>>> service.clean()
>>> sorted([job.status for job in service.jobs.values()])
['queued']
Cron jobs
---------
Cron jobs execute on specific times.
>>> import time
>>> from z3c.taskqueue.job import CronJob
>>> now = 0
>>> time.gmtime(now)
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)
We set up a job to be executed once an hour at the current minute. The next
call time is the one our from now.
Minutes
>>> cronJob = CronJob(-1, u'echo', (), minute=(0, 10))
>>> time.gmtime(cronJob.timeOfNextCall(0))
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=10, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)
>>> time.gmtime(cronJob.timeOfNextCall(10*60))
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=1, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)
Hour
>>> cronJob = CronJob(-1, u'echo', (), hour=(2, 13))
>>> time.gmtime(cronJob.timeOfNextCall(0))
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=2, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)
>>> time.gmtime(cronJob.timeOfNextCall(2*60*60))
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=13, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)
Month
>>> cronJob = CronJob(-1, u'echo', (), month=(1, 5, 12))
>>> time.gmtime(cronJob.timeOfNextCall(0))
time.struct_time(tm_year=1970, tm_mon=5, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=4, tm_yday=121, tm_isdst=0)
>>> time.gmtime(cronJob.timeOfNextCall(cronJob.timeOfNextCall(0)))
time.struct_time(tm_year=1970, tm_mon=12, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=335, tm_isdst=0)
Day of week [0..6], jan 1 1970 is a wednesday.
>>> cronJob = CronJob(-1, u'echo', (), dayOfWeek=(0, 2, 4, 5))
>>> time.gmtime(cronJob.timeOfNextCall(0))
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=2, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=4, tm_yday=2, tm_isdst=0)
>>> time.gmtime(cronJob.timeOfNextCall(60*60*24))
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=3, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=3, tm_isdst=0)
>>> time.gmtime(cronJob.timeOfNextCall(2*60*60*24))
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=5, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=5, tm_isdst=0)
>>> time.gmtime(cronJob.timeOfNextCall(4*60*60*24))
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=7, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=7, tm_isdst=0)
DayOfMonth [1..31]
>>> cronJob = CronJob(-1, u'echo', (), dayOfMonth=(1, 12, 21, 30))
>>> time.gmtime(cronJob.timeOfNextCall(0))
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=12, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=12, tm_isdst=0)
>>> time.gmtime(cronJob.timeOfNextCall(12*24*60*60))
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=21, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=21, tm_isdst=0)
Combined
>>> cronJob = CronJob(-1, u'echo', (), minute=(10,),
... dayOfMonth=(1, 12, 21, 30))
>>> time.gmtime(cronJob.timeOfNextCall(0))
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=10, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)
>>> time.gmtime(cronJob.timeOfNextCall(10*60))
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=1, tm_min=10, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)
>>> cronJob = CronJob(-1, u'echo', (), minute=(10,),
... hour=(4,),
... dayOfMonth=(1, 12, 21, 30))
>>> time.gmtime(cronJob.timeOfNextCall(0))
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=4, tm_min=10, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)
>>> time.gmtime(cronJob.timeOfNextCall(10*60))
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=4, tm_min=10, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)
A cron job can also be used to delay the execution of a job.
>>> cronJob = CronJob(-1, u'echo', (), delay=10,)
>>> time.gmtime(cronJob.timeOfNextCall(0))
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=10, tm_wday=3, tm_yday=1, tm_isdst=0)
>>> time.gmtime(cronJob.timeOfNextCall(1))
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=11, tm_wday=3, tm_yday=1, tm_isdst=0)
Creating Delayed Jobs
---------------------
A delayed job is executed once after the given delay time in seconds.
>>> count = 0
>>> def counting(input):
... global count
... count += 1
... return count
>>> countingTask = taskqueue.task.SimpleTask(counting)
>>> zope.component.provideUtility(countingTask, name='counter')
>>> jobid = service.addCronJob(u'counter',
... {'foo': 'bar'},
... delay = 10,
... )
>>> service.getStatus(jobid)
'delayed'
>>> service.processNext(0)
True
>>> service.getStatus(jobid)
'delayed'
>>> service.processNext(9)
False
>>> service.getStatus(jobid)
'delayed'
At 10 seconds the job is executed and completed.
>>> service.processNext(10)
True
>>> service.getStatus(jobid)
'completed'
Creating Cron Jobs
------------------
Here we create a cron job which runs 10 minutes and 13 minutes past the hour.
>>> count = 0
>>> jobid = service.addCronJob(u'counter',
... {'foo': 'bar'},
... minute = (10, 13),
... )
>>> service.getStatus(jobid)
'cronjob'
We process the remote task but our cron job is not executed because we are too
early in time.
>>> service.processNext(0)
False
>>> service.getStatus(jobid)
'cronjob'
>>> service.getResult(jobid) is None
True
Now we run the remote task 10 minutes later and get a result.
>>> service.processNext(10*60)
True
>>> service.getStatus(jobid)
'cronjob'
>>> service.getResult(jobid)
1
And 1 minutes later it is not called.
>>> service.processNext(11*60)
False
>>> service.getResult(jobid)
1
But 3 minutes later it is called again.
>>> service.processNext(13*60)
True
>>> service.getResult(jobid)
2
A job can be rescheduled.
>>> job = service.jobs[jobid]
>>> job.update(minute = (11, 13))
After the update the job must be rescheduled in the service.
>>> service.reschedule(jobid)
Now the job is not executed at the old registration minute which was 10.
>>> service.processNext(10*60+60*60)
False
>>> service.getResult(jobid)
2
But it executes at the new minute which is set to 11.
>>> service.processNext(11*60+60*60)
True
>>> service.getResult(jobid)
3
Check Interfaces and stuff
--------------------------
>>> from z3c.taskqueue import interfaces
>>> from zope.interface.verify import verifyClass, verifyObject
>>> verifyClass(interfaces.ITaskService, taskqueue.service.TaskService)
True
>>> verifyObject(interfaces.ITaskService, service)
True
>>> interfaces.ITaskService.providedBy(service)
True
>>> from z3c.taskqueue.job import Job
>>> fakejob = Job(1, u'echo', {})
>>> verifyClass(interfaces.IJob, Job)
True
>>> verifyObject(interfaces.IJob, fakejob)
True
>>> interfaces.IJob.providedBy(fakejob)
True
>>> fakecronjob = CronJob(1, u'echo', {})
>>> verifyClass(interfaces.ICronJob, CronJob)
True
>>> verifyObject(interfaces.ICronJob, fakecronjob)
True
>>> interfaces.IJob.providedBy(fakecronjob)
True
| z3c.taskqueue | /z3c.taskqueue-0.2.1.zip/z3c.taskqueue-0.2.1/src/z3c/taskqueue/README.txt | README.txt |
__docformat__ = 'restructuredtext'
from z3c.taskqueue import interfaces
from zope import component
from zope.app.publication.zopepublication import ZopePublication
import logging
import zope.interface
import zope.location
import z3c.taskqueue
log = logging.getLogger('z3c.taskqueue')
def databaseOpened(event, productName='z3c.taskqueue'):
"""Start the queue processing services based on the
settings in zope.conf"""
log.info('handling event IDatabaseOpenedEvent')
storeDBReference(event)
root_folder = getRootFolder(event)
from zope.app.appsetup.product import getProductConfiguration
configuration = getProductConfiguration(productName)
startSpecifications = getStartSpecifications(configuration)
for sitesIdentifier, servicesIdentifier in startSpecifications:
sites = getSites(sitesIdentifier, root_folder)
for site in sites:
startOneService(site, servicesIdentifier)
def getRootFolder(event):
db = event.database
connection = db.open()
root = connection.root()
root_folder = root.get(ZopePublication.root_name, None)
return root_folder
def getStartSpecifications(configuration):
"""get a list of sites/services to start"""
if configuration is not None:
autostart = configuration.get('autostart', '')
autostartParts = [name.strip()
for name in autostart.split(',')]
specs = [name.split('@') for name in autostartParts if name]
return specs
else:
return []
def getSites(sitesIdentifier, root_folder):
# we search only for sites at the database root level
if sitesIdentifier == '':
return [root_folder]
elif sitesIdentifier == '*':
return getAllSites(root_folder)
else:
site = getSite(sitesIdentifier, root_folder)
if site is not None:
return [site]
else:
return []
def getAllSites(root_folder):
sites = []
# do not forget to include root folder as it might have registered services
sites.append(root_folder)
root_values = root_folder.values()
for folder in root_values:
if zope.location.interfaces.ISite.providedBy(folder):
sites.append(folder)
return sites
def getSite(siteName, root_folder):
site = root_folder.get(siteName)
if site is None:
log.error('site %s not found' % siteName)
return site
def getAllServices(site, root_folder):
sm = site.getSiteManager()
services = list(
sm.getUtilitiesFor(interfaces.ITaskService))
# filter out services registered in root
root_sm = root_folder.getSiteManager()
if sm != root_sm:
rootServices = list(root_sm.getUtilitiesFor(
interfaces.ITaskService))
services = [s for s in services
if s not in rootServices]
services = [service for name, service in services]
return services
def getSiteName(site):
siteName = getattr(site, '__name__', '')
if siteName is None:
siteName = 'root'
return siteName
def startOneService(site, serviceName):
service = getService(site, serviceName)
if service is not None:
if not service.isProcessing():
service.startProcessing()
if service.isProcessing():
siteName = getSiteName(site)
msg = 'service %s on site %s started'
log.info(msg % (serviceName, siteName))
return service
else:
return None
def getService(site, serviceName):
service = component.queryUtility(interfaces.ITaskService,
context=site, name=serviceName)
if service is not None:
return service
else:
siteName = getSiteName(site)
msg = 'service %s on site %s not found'
log.error(msg % (serviceName, siteName))
return None
def storeDBReference(db):
z3c.taskqueue.GLOBALDB = db
def storeDBReferenceOnDBOpened(event):
storeDBReference(event.database) | z3c.taskqueue | /z3c.taskqueue-0.2.1.zip/z3c.taskqueue-0.2.1/src/z3c/taskqueue/startup.py | startup.py |
__docformat__ = 'restructuredtext'
import time
import datetime
import persistent
import zope.interface
from zope.schema.fieldproperty import FieldProperty
from z3c.taskqueue import interfaces
class Job(persistent.Persistent):
"""A simple, non-persistent task implementation."""
zope.interface.implements(interfaces.IJob)
id = FieldProperty(interfaces.IJob['id'])
task = FieldProperty(interfaces.IJob['task'])
status = FieldProperty(interfaces.IJob['status'])
input = FieldProperty(interfaces.IJob['input'])
output = FieldProperty(interfaces.IJob['output'])
error = FieldProperty(interfaces.IJob['error'])
created = FieldProperty(interfaces.IJob['created'])
started = FieldProperty(interfaces.IJob['started'])
completed = FieldProperty(interfaces.IJob['completed'])
def __init__(self, id, task, input):
self.id = id
self.task = task
self.input = input
self.created = datetime.datetime.now()
def __repr__(self):
return '<%s %r>' % (self.__class__.__name__, self.id)
def setError(self, error):
self.error = str(error)
class CronJob(Job):
"""A job for reocuring tasks"""
zope.interface.implements(interfaces.ICronJob)
minute = FieldProperty(interfaces.ICronJob['minute'])
hour = FieldProperty(interfaces.ICronJob['hour'])
dayOfMonth = FieldProperty(interfaces.ICronJob['dayOfMonth'])
month = FieldProperty(interfaces.ICronJob['month'])
dayOfWeek = FieldProperty(interfaces.ICronJob['dayOfWeek'])
scheduledFor = FieldProperty(interfaces.ICronJob['scheduledFor'])
def __init__(self, id, task, input,
minute=(),
hour=(),
dayOfMonth=(),
month=(),
dayOfWeek=(),
delay=None,
):
super(CronJob, self).__init__(id, task, input)
self.update(minute, hour, dayOfMonth, month, dayOfWeek, delay)
def update(self,
minute=(),
hour=(),
dayOfMonth=(),
month=(),
dayOfWeek=(),
delay=None,
):
self.minute = minute
self.hour = hour
self.dayOfMonth = dayOfMonth
self.month = month
self.dayOfWeek = dayOfWeek
if delay == 0:
delay = None
self.delay = delay
def timeOfNextCall(self, now=None):
if now is None:
now = int(time.time())
next = now
if self.delay is not None:
next += self.delay
return int(next)
inc = lambda t: 60
lnow = list(time.gmtime(now)[:5])
if self.minute:
pass
elif self.hour:
inc = lambda t: 60 * 60
lnow = lnow[:4]
elif self.dayOfMonth:
inc = lambda t: 24 * 60 * 60
lnow = lnow[:3]
elif self.dayOfWeek:
inc = lambda t: 24 * 60 * 60
lnow = lnow[:3]
elif self.month:
mlen = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
def minc(t):
m = time.gmtime(t)[1] - 1
if m == 1:
# see if we have a leap year
y = time.gmtime(t)[0]
if y % 4 != 0:
d = 28
elif y % 400 == 0:
d = 29
elif y % 100 == 0:
d = 28
else:
d = 29
return d * 24 * 60 * 60
return mlen[m] * 24 * 60 * 60
inc = minc
lnow = lnow[:3]
lnow[2] = 1
while len(lnow) < 9:
lnow.append(0)
while next <= now + 365 * 24 * 60 * 60:
next += inc(next)
fields = time.gmtime(next)
if ((self.month and fields[1] not in self.month) or
(self.dayOfMonth and fields[2] not in self.dayOfMonth) or
(self.dayOfWeek and fields[6] % 7 not in self.dayOfWeek) or
(self.hour and fields[3] not in self.hour) or
(self.minute and fields[4] not in self.minute)):
continue
return int(next)
return None | z3c.taskqueue | /z3c.taskqueue-0.2.1.zip/z3c.taskqueue-0.2.1/src/z3c/taskqueue/job.py | job.py |
__docformat__ = 'restructuredtext'
import logging
import threading
import time
import transaction
import zope.interface
import zope.publisher.base
import zope.publisher.publish
from zope.app.publication.zopepublication import ZopePublication
from zope.security import management
from zope.security.proxy import removeSecurityProxy
from zope.traversing.api import traverse
from z3c.taskqueue import interfaces
THREAD_STARTUP_WAIT = 0.05
ERROR_MARKER = object()
log = logging.getLogger('z3c.taskqueue')
class ProcessorPublication(ZopePublication):
"""A custom publication to process the next job."""
def beforeTraversal(self, request):
# Overwrite this method, so that the publication does not attempt to
# authenticate; we assume that the processor is allowed to do
# everything. Note that the DB is not exposed to the job callable.
management.newInteraction(request)
transaction.begin()
def traverseName(self, request, ob, name):
# Provide a very simple traversal mechanism.
return traverse(removeSecurityProxy(ob), name, None)
class ProcessorRequest(zope.publisher.base.BaseRequest):
"""A custome publisher request for the processor."""
def __init__(self, *args):
super(ProcessorRequest, self).__init__(None, {}, positional=args)
class BaseSimpleProcessor(object):
"""Simple Job Processor
This processor only processes one job at a time.
"""
zope.interface.implements(interfaces.IProcessor)
@property
def running(self):
thread = threading.currentThread()
if thread is not None:
return thread.running
log.error('SimpleProcessor: no currentThread')
return False
def __init__(self, db, servicePath, waitTime=1.0):
self.db = db
self.servicePath = servicePath
self.waitTime = waitTime
def call(self, method, args=(), errorValue=ERROR_MARKER):
raise NotImplemented
def processNext(self, jobid=None):
result = self.call('processNext', args=(None, jobid))
return result
def __call__(self):
while self.running:
try:
result = self.processNext()
except Exception, error:
log.exception(error)
result = None
# If there are no jobs available, sleep a little bit and then
# check again.
if not result:
time.sleep(self.waitTime)
class Z3PublisherMixin(object):
def call(self, method, args=(), errorValue=ERROR_MARKER):
# Create the path to the method.
path = self.servicePath[:] + [method]
path.reverse()
# Produce a special processor event to be sent to the publisher.
request = ProcessorRequest(*args)
request.setPublication(ProcessorPublication(self.db))
request.setTraversalStack(path)
# Publish the request, making sure that *all* exceptions are
# handled. The processor should *never* crash.
try:
zope.publisher.publish.publish(request, False)
return request.response._result
except Exception, error:
# This thread should never crash, thus a blank except
log.error('Processor: ``%s()`` caused an error!' % method)
log.exception(error)
return errorValue is ERROR_MARKER and error or errorValue
class SimpleProcessor(Z3PublisherMixin, BaseSimpleProcessor):
""" Z3 compatible processor"""
class BaseMultiProcessor(BaseSimpleProcessor):
"""Multi-threaded Job Processor
This processor can work on multiple jobs at the same time.
"""
zope.interface.implements(interfaces.IProcessor)
def __init__(self, *args, **kwargs):
self.maxThreads = kwargs.pop('maxThreads', 5)
super(BaseMultiProcessor, self).__init__(*args, **kwargs)
self.threads = []
def hasJobsWaiting(self):
return self.call('hasJobsWaiting', errorValue=False)
def claimNextJob(self):
return self.call('claimNextJob', errorValue=None)
def __call__(self):
# Start the processing loop
while self.running:
# Remove all dead threads
for thread in self.threads:
if not thread.isAlive():
self.threads.remove(thread)
# If the number of threads equals the number of maximum threads,
# wait a little bit and then start over
if len(self.threads) == self.maxThreads:
time.sleep(self.waitTime)
continue
# Let's wait for jobs to become available
while not self.hasJobsWaiting() and self.running:
time.sleep(self.waitTime)
# Okay, we have to do some work, so let's do that now. Since we
# are working with threads, we first have to claim a job and then
# execute it.
jobid = self.claimNextJob()
# If we got a job, let's work on it in a new thread.
if jobid is not None:
thread = threading.Thread(
target=self.processNext, args=(jobid,))
self.threads.append(thread)
thread.start()
# Give the thread some time to start up:
time.sleep(THREAD_STARTUP_WAIT)
class MultiProcessor(Z3PublisherMixin, BaseMultiProcessor):
""" Z3 compatible processor""" | z3c.taskqueue | /z3c.taskqueue-0.2.1.zip/z3c.taskqueue-0.2.1/src/z3c/taskqueue/processor.py | processor.py |
===============
Z3C Templates
===============
This package allows us to separate the registration of the view code and the
layout.
A template is used for separate the HTML part from a view. This is done in
z3 via a page templates. Such page template are implemented in the view,
registered included in a page directive etc. But they do not use the adapter
pattern which makes it hard to replace existing templates.
Another part of template is, that they normaly separate one part presenting
content from a view and another part offer a layout used by the content
template.
How can this package make it simpler to use templates?
Templates can be registered as adapters adapting context, request where the
context is a view implementation. Such a template get adapted from the view
if the template is needed. This adaption makes it very pluggable and modular.
We offer two base template directive for register content producing templates
and layout producing tempaltes. This is most the time enough but you also
can register different type of templates using a specific interface. This
could be usefull if your view implementation needs to separate HTMl in
more then one template. Now let's take a look how we an use this templates.
Content template
================
First let's show how we use a template for produce content from a view:
>>> import os, tempfile
>>> temp_dir = tempfile.mkdtemp()
>>> contentTemplate = os.path.join(temp_dir, 'contentTemplate.pt')
>>> with open(contentTemplate, 'w') as file:
... _ = file.write('<div>demo content</div>')
And register a view class implementing a interface:
>>> import zope.interface
>>> from z3c.template import interfaces
>>> from zope.pagetemplate.interfaces import IPageTemplate
>>> from zope.publisher.browser import BrowserPage
>>> class IMyView(zope.interface.Interface):
... pass
>>> @zope.interface.implementer(IMyView)
... class MyView(BrowserPage):
... template = None
... def render(self):
... if self.template is None:
... template = zope.component.getMultiAdapter(
... (self, self.request), interfaces.IContentTemplate)
... return template(self)
... return self.template()
Let's call the view and check the output:
>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest()
>>> view = MyView(root, request)
Since the template is not yet registered, rendering the view will fail:
>>> print(view.render())
Traceback (most recent call last):
...
zope.interface.interfaces.ComponentLookupError: ......
Let's now register the template (commonly done using ZCML):
>>> from zope import component
>>> from zope.publisher.interfaces.browser import IDefaultBrowserLayer
>>> from z3c.template.template import TemplateFactory
The template factory allows us to create a ViewPageTeplateFile instance.
>>> factory = TemplateFactory(contentTemplate, 'text/html')
>>> factory
<z3c.template.template.TemplateFactory object at ...>
We register the factory on a view interface and a layer.
>>> component.provideAdapter(
... factory,
... (zope.interface.Interface, IDefaultBrowserLayer),
... interfaces.IContentTemplate)
>>> template = component.getMultiAdapter((view, request),
... interfaces.IPageTemplate)
>>> template
<...ViewPageTemplateFile...>
Now that we have a registered layout template for the default layer we can
call our view again.
>>> print(view.render())
<div>demo content</div>
Now we register a new template on the specific interface of our view.
>>> myTemplate = os.path.join(temp_dir, 'myTemplate.pt')
>>> with open(myTemplate, 'w') as file:
... _ = file.write('<div>My content</div>')
>>> factory = TemplateFactory(myTemplate, 'text/html')
>>> component.provideAdapter(
... factory,
... (IMyView, IDefaultBrowserLayer), interfaces.IContentTemplate)
>>> print(view.render())
<div>My content</div>
It is possible to provide the template directly.
We create a new template.
>>> viewContent = os.path.join(temp_dir, 'viewContent.pt')
>>> with open(viewContent, 'w') as file:
... _ = file.write('<div>view content</div>')
and a view:
>>> from z3c.template import ViewPageTemplateFile
>>> @zope.interface.implementer(IMyView)
... class MyViewWithTemplate(BrowserPage):
... template = ViewPageTemplateFile(viewContent)
... def render(self):
... if self.template is None:
... template = zope.component.getMultiAdapter(
... (self, self.request), interfaces.IContentTemplate)
... return template(self)
... return self.template()
>>> contentView = MyViewWithTemplate(root, request)
If we render this view we get the implemented layout template and not the
registered one.
>>> print(contentView.render())
<div>view content</div>
Layout template
===============
First we nee to register a new view class calling a layout template. Note,
that this view uses the __call__ method for invoke a layout template:
>>> class ILayoutView(zope.interface.Interface):
... pass
>>> @zope.interface.implementer(ILayoutView)
... class LayoutView(BrowserPage):
... layout = None
... def __call__(self):
... if self.layout is None:
... layout = zope.component.getMultiAdapter(
... (self, self.request), interfaces.ILayoutTemplate)
... return layout(self)
... return self.layout()
>>> view2 = LayoutView(root, request)
Define and register a new layout template:
>>> layoutTemplate = os.path.join(temp_dir, 'layoutTemplate.pt')
>>> with open(layoutTemplate, 'w') as file:
... _ = file.write('<div>demo layout</div>')
>>> factory = TemplateFactory(layoutTemplate, 'text/html')
We register the template factory on a view interface and a layer providing the
ILayoutTemplate interface.
>>> component.provideAdapter(factory,
... (zope.interface.Interface, IDefaultBrowserLayer),
... interfaces.ILayoutTemplate)
>>> layout = component.getMultiAdapter(
... (view2, request), interfaces.ILayoutTemplate)
>>> layout
<...ViewPageTemplateFile...>
Now that we have a registered layout template for the default layer we can
call our view again.
>>> print(view2())
<div>demo layout</div>
Now we register a new layout template on the specific interface of our view.
>>> myLayout = os.path.join(temp_dir, 'myLayout.pt')
>>> with open(myLayout, 'w') as file:
... _ = file.write('<div>My layout</div>')
>>> factory = TemplateFactory(myLayout, 'text/html')
>>> component.provideAdapter(factory,
... (ILayoutView, IDefaultBrowserLayer),
... interfaces.ILayoutTemplate)
>>> print(view2())
<div>My layout</div>
It is possible to provide the layout template directly.
We create a new template.
>>> viewLayout = os.path.join(temp_dir, 'viewLayout.pt')
>>> with open(viewLayout, 'w') as file:
... _ = file.write('''<div>view layout</div>''')
>>> @zope.interface.implementer(ILayoutView)
... class LayoutViewWithLayoutTemplate(BrowserPage):
... layout = ViewPageTemplateFile(viewLayout)
... def __call__(self):
... if self.layout is None:
... layout = zope.component.getMultiAdapter((self, self.request),
... interfaces.ILayoutTemplate)
... return layout(self)
... return self.layout()
>>> layoutView = LayoutViewWithLayoutTemplate(root, request)
If we render this view we get the implemented layout template and not the
registered one.
>>> print(layoutView())
<div>view layout</div>
Since we return the layout template in the sample views above, how can we get
the content from the used view? This is not directly a part of this package
but let's show some pattern were can be used for render content in a used
layout template. Note, since we offer to register each layout template for
a specific view, you can always very selectiv this layout pattern. This means
you can use the defualt z3 macro based layout registration in combination with
this layout concept if you register a own layout template.
The simplest concept is calling the content from the view in the layout
template is to call it from a method. Let's define a view providing a layout
template and offer a method for call content.
>>> class IFullView(zope.interface.Interface):
... pass
>>> @zope.interface.implementer(IFullView)
... class FullView(BrowserPage):
... layout = None
... def render(self):
... return u'rendered content'
... def __call__(self):
... if self.layout is None:
... layout = zope.component.getMultiAdapter((self, self.request),
... interfaces.ILayoutTemplate)
... return layout(self)
... return self.layout()
>>> completeView = FullView(root, request)
Now define a layout for the view and register them:
>>> completeLayout = os.path.join(temp_dir, 'completeLayout.pt')
>>> with open(completeLayout, 'w') as file:
... _ = file.write('''
... <div tal:content="view/render">
... Full layout
... </div>
... ''')
>>> factory = TemplateFactory(completeLayout, 'text/html')
>>> component.provideAdapter(factory,
... (IFullView, IDefaultBrowserLayer), interfaces.ILayoutTemplate)
Now let's see if the layout template can call the content via calling render
on the view:
>>> print(completeView.__call__())
<div>rendered content</div>
Content and Layout
==================
Now let's show how we combine this two templates in a real use case:
>>> class IDocumentView(zope.interface.Interface):
... pass
>>> @zope.interface.implementer(IDocumentView)
... class DocumentView(BrowserPage):
... template = None
... layout = None
... attr = None
... def update(self):
... self.attr = u'content updated'
... def render(self):
... if self.template is None:
... template = zope.component.getMultiAdapter(
... (self, self.request), IPageTemplate)
... return template(self)
... return self.template()
... def __call__(self):
... self.update()
... if self.layout is None:
... layout = zope.component.getMultiAdapter((self, self.request),
... interfaces.ILayoutTemplate)
... return layout(self)
... return self.layout()
Define and register a content template...
>>> template = os.path.join(temp_dir, 'template.pt')
>>> with open(template, 'w') as file:
... _ = file.write('''
... <div tal:content="view/attr">
... here comes the value of attr
... </div>
... ''')
>>> factory = TemplateFactory(template, 'text/html')
>>> component.provideAdapter(factory,
... (IDocumentView, IDefaultBrowserLayer), IPageTemplate)
and define and register a layout template:
>>> layout = os.path.join(temp_dir, 'layout.pt')
>>> with open(layout, 'w') as file:
... _ = file.write('''
... <html>
... <body>
... <div tal:content="structure view/render">
... here comes the rendered content
... </div>
... </body>
... </html>
... ''')
>>> factory = TemplateFactory(layout, 'text/html')
>>> component.provideAdapter(factory,
... (IDocumentView, IDefaultBrowserLayer), interfaces.ILayoutTemplate)
Now call the view and check the result:
>>> documentView = DocumentView(root, request)
>>> print(documentView())
<html>
<body>
<div>
<div>content updated</div>
</div>
</body>
</html>
Macros
======
Use of macros.
>>> macroTemplate = os.path.join(temp_dir, 'macroTemplate.pt')
>>> with open(macroTemplate, 'w') as file:
... _ = file.write('''
... <metal:block define-macro="macro1">
... <div>macro1</div>
... </metal:block>
... <metal:block define-macro="macro2">
... <div>macro2</div>
... <div tal:content="options/div2">the content of div 2</div>
... </metal:block>
... ''')
>>> factory = TemplateFactory(macroTemplate, 'text/html', 'macro1')
>>> print(factory(view, request)())
<div>macro1</div>
>>> m2factory = TemplateFactory(macroTemplate, 'text/html', 'macro2')
>>> print(m2factory(view, request)(div2="from the options"))
<div>macro2</div>
<div>from the options</div>
Why didn't we use named templates from the ``zope.formlib`` package?
While named templates allow us to separate the view code from the template
registration, they are not registrable for a particular layer making it
impossible to implement multiple skins using named templates.
Use case ``simple template``
============================
And for the simplest possible use we provide a hook for call registered
templates. Such page templates can get called with the getPageTemplate method
and return a registered bound ViewTemplate a la ViewPageTemplateFile or
NamedTemplate.
The getViewTemplate allows us to use the new template registration
system with all existing implementations such as `zope.formlib` and
`zope.viewlet`.
>>> from z3c.template.template import getPageTemplate
>>> class IUseOfViewTemplate(zope.interface.Interface):
... pass
>>> @zope.interface.implementer(IUseOfViewTemplate)
... class UseOfViewTemplate(object):
...
... template = getPageTemplate()
...
... def __init__(self, context, request):
... self.context = context
... self.request = request
By defining the "template" property as a "getPageTemplate" a lookup for
a registered template is done when it is called.
>>> simple = UseOfViewTemplate(root, request)
>>> print(simple.template())
<div>demo content</div>
Because the demo template was registered for any ("None") interface we see the
demo template when rendering our new view. We register a new template
especially for the new view. Also note that the "macroTemplate" has been
created earlier in this test.
>>> factory = TemplateFactory(contentTemplate, 'text/html')
>>> component.provideAdapter(factory,
... (IUseOfViewTemplate, IDefaultBrowserLayer), IPageTemplate)
>>> print(simple.template())
<div>demo content</div>
Context-specific templates
==========================
The ``TemplateFactory`` can be also used for (view, request, context)
lookup. It's useful when you want to override a template for specific
content object or type.
Let's define a sample content type and instantiate a view for it.
>>> class IContent(zope.interface.Interface):
... pass
>>> @zope.interface.implementer(IContent)
... class Content(object):
... pass
>>> content = Content()
>>> view = UseOfViewTemplate(content, request)
Now, let's provide a (view, request, context) adapter using TemplateFactory.
>>> contextTemplate = os.path.join(temp_dir, 'context.pt')
>>> with open(contextTemplate, 'w') as file:
... _ = file.write('<div>context-specific</div>')
>>> factory = TemplateFactory(contextTemplate, 'text/html')
>>> component.provideAdapter(factory,
... (IUseOfViewTemplate, IDefaultBrowserLayer, IContent),
... interfaces.IContentTemplate)
First. Let's try to simply get it as a multi-adapter.
>>> template = zope.component.getMultiAdapter((view, request, content),
... interfaces.IContentTemplate)
>>> print(template(view))
<div>context-specific</div>
The ``getPageTemplate`` and friends will try to lookup a context-specific
template before doing more generic (view, request) lookup, so our view
should already use our context-specific template:
>>> print(view.template())
<div>context-specific</div>
Use case ``template by interface``
==================================
Templates can also get registered on different interfaces then IPageTemplate
or ILayoutTemplate.
>>> from z3c.template.template import getViewTemplate
>>> class IMyTemplate(zope.interface.Interface):
... """My custom tempalte marker."""
>>> factory = TemplateFactory(contentTemplate, 'text/html')
>>> component.provideAdapter(factory,
... (zope.interface.Interface, IDefaultBrowserLayer), IMyTemplate)
Now define a view using such a custom template registration:
>>> class IMyTemplateView(zope.interface.Interface):
... pass
>>> @zope.interface.implementer(IMyTemplateView)
... class MyTemplateView(object):
...
... template = getViewTemplate(IMyTemplate)
...
... def __init__(self, context, request):
... self.context = context
... self.request = request
>>> myTempalteView = MyTemplateView(root, request)
>>> print(myTempalteView.template())
<div>demo content</div>
Use case ``named template``
===========================
Templates can also get registered on names. In this expample we use a named
template combined with a custom template marker interface.
>>> class IMyNamedTemplate(zope.interface.Interface):
... """My custom template marker."""
>>> factory = TemplateFactory(contentTemplate, 'text/html')
>>> component.provideAdapter(factory,
... (zope.interface.Interface, IDefaultBrowserLayer), IMyNamedTemplate,
... name='my template')
Now define a view using such a custom named template registration:
>>> class IMyNamedTemplateView(zope.interface.Interface):
... pass
>>> @zope.interface.implementer(IMyNamedTemplateView)
... class MyNamedTemplateView(object):
...
... template = getViewTemplate(IMyNamedTemplate, 'my template')
...
... def __init__(self, context, request):
... self.context = context
... self.request = request
>>> myNamedTempalteView = MyNamedTemplateView(root, request)
>>> print(myNamedTempalteView.template())
<div>demo content</div>
Use case ``named layout template``
==================================
We can also register a new layout template by name and use it in a view:
>>> from z3c.template.template import getLayoutTemplate
>>> editLayout = os.path.join(temp_dir, 'editLayout.pt')
>>> with open(editLayout, 'w') as file:
... _ = file.write('''
... <div>Edit layout</div>
... <div tal:content="view/render">content</div>
... ''')
>>> factory = TemplateFactory(editLayout, 'text/html')
>>> component.provideAdapter(factory,
... (zope.interface.Interface, IDefaultBrowserLayer),
... interfaces.ILayoutTemplate, name='edit')
Now define a view using such a custom named template registration:
>>> class MyEditView(BrowserPage):
...
... layout = getLayoutTemplate('edit')
...
... def render(self):
... return u'edit content'
...
... def __call__(self):
... if self.layout is None:
... layout = zope.component.getMultiAdapter((self, self.request),
... interfaces.ILayoutTemplate)
... return layout(self)
... return self.layout()
>>> myEditView = MyEditView(root, request)
>>> print(myEditView())
<div>Edit layout</div>
<div>edit content</div>
Cleanup
=======
>>> import shutil
>>> shutil.rmtree(temp_dir)
Pagelet
=======
See ``z3c.pagelet`` for another template based layout generating implementation.
| z3c.template | /z3c.template-4.0-py3-none-any.whl/z3c/template/README.rst | README.rst |
====================
Template directive
====================
Show how we can use the template directive. Register the meta configuration for
the directive.
>>> import sys
>>> from zope.configuration import xmlconfig
>>> import z3c.template
>>> context = xmlconfig.file('meta.zcml', z3c.template)
PageTemplate
============
We need a custom content template
>>> import os, tempfile
>>> temp_dir = tempfile.mkdtemp()
>>> content_file = os.path.join(temp_dir, 'content.pt')
>>> with open(content_file, 'w') as file:
... _ = file.write('''<div>content</div>''')
and a interface
>>> import zope.interface
>>> class IView(zope.interface.Interface):
... """Marker interface"""
and a view class:
>>> from zope.publisher.browser import TestRequest
>>> @zope.interface.implementer(IView)
... class View(object):
... def __init__(self, context, request):
... self.context = context
... self.request = request
>>> request = TestRequest()
>>> view = View(object(), request)
Make them available under the fake package ``custom``:
>>> sys.modules['custom'] = type(
... 'Module', (),
... {'IView': IView})()
and register them as a template within the ``z3c:template`` directive:
>>> context = xmlconfig.string("""
... <configure
... xmlns:z3c="http://namespaces.zope.org/z3c">
... <z3c:template
... template="%s"
... for="custom.IView"
... />
... </configure>
... """ % content_file, context=context)
Let's get the template
>>> import zope.component
>>> from z3c.template.interfaces import IContentTemplate
>>> template = zope.component.queryMultiAdapter(
... (view, request),
... interface=IContentTemplate)
and check them:
>>> from z3c.template.template import ViewPageTemplateFile
>>> isinstance(template, ViewPageTemplateFile)
True
>>> isinstance(template.content_type, str)
True
>>> print(template(view))
<div>content</div>
Errors
------
If we try to use a path to a template that does not exist, we
get an error:
>>> context = xmlconfig.string("""
... <configure
... xmlns:z3c="http://namespaces.zope.org/z3c">
... <z3c:template
... template="this_file_does_not_exist"
... for="custom.IView"
... />
... </configure>
... """, context=context)
Traceback (most recent call last):
...
ConfigurationError: ('No such file', '...this_file_does_not_exist')
File "<string>", line 4.2-7.8
Layout template
===============
Define a layout template
>>> layout_file = os.path.join(temp_dir, 'layout.pt')
>>> with open(layout_file, 'w') as file:
... _ = file.write('''<div>layout</div>''')
and register them as a layout template within the ``z3c:layout`` directive:
>>> context = xmlconfig.string("""
... <configure
... xmlns:z3c="http://namespaces.zope.org/z3c">
... <z3c:layout
... template="%s"
... for="custom.IView"
... />
... </configure>
... """ % layout_file, context=context)
Let's get the template
>>> from z3c.template.interfaces import ILayoutTemplate
>>> layout = zope.component.queryMultiAdapter((view, request),
... interface=ILayoutTemplate)
and check them:
>>> isinstance(layout, ViewPageTemplateFile)
True
>>> isinstance(layout.content_type, str)
True
>>> print(layout(view))
<div>layout</div>
Context-specific template
=========================
Most of views have some object as their context and it's ofter very
useful to be able register context-specific template. We can do that
using the ``context`` argument of the ZCML directive.
Let's define some content type:
>>> class IContent(zope.interface.Interface):
... pass
>>> @zope.interface.implementer(IContent)
... class Content(object):
... pass
>>> sys.modules['custom'].IContent = IContent
Now, we can register a template for this class. Let's create one and
register:
>>> context_file = os.path.join(temp_dir, 'context.pt')
>>> with open(context_file, 'w') as file:
... _ = file.write('''<div>i'm context-specific</div>''')
>>> context = xmlconfig.string("""
... <configure
... xmlns:z3c="http://namespaces.zope.org/z3c">
... <z3c:template
... template="%s"
... for="custom.IView"
... context="custom.IContent"
... />
... </configure>
... """ % context_file, context=context)
We can now lookup it using the (view, request, context) discriminator:
>>> content = Content()
>>> view = View(content, request)
>>> template = zope.component.queryMultiAdapter((view, request, content),
... interface=IContentTemplate)
>>> print(template(view))
<div>i'm context-specific</div>
The same will work with layout registration directive:
>>> context_layout_file = os.path.join(temp_dir, 'context_layout.pt')
>>> with open(context_layout_file, 'w') as file:
... _ = file.write('''<div>context-specific layout</div>''')
>>> context = xmlconfig.string("""
... <configure
... xmlns:z3c="http://namespaces.zope.org/z3c">
... <z3c:layout
... template="%s"
... for="custom.IView"
... context="custom.IContent"
... />
... </configure>
... """ % context_layout_file, context=context)
>>> layout = zope.component.queryMultiAdapter((view, request, content),
... interface=ILayoutTemplate)
>>> print(layout(view))
<div>context-specific layout</div>
Named template
==============
Its possible to register template by name. Let us register a pagelet with the
name edit:
>>> editTemplate = os.path.join(temp_dir, 'edit.pt')
>>> with open(editTemplate, 'w') as file:
... _ = file.write('''<div>edit</div>''')
>>> context = xmlconfig.string("""
... <configure
... xmlns:z3c="http://namespaces.zope.org/z3c">
... <z3c:template
... name="edit"
... template="%s"
... for="custom.IView"
... />
... </configure>
... """ % editTemplate, context=context)
And call it:
>>> from z3c.template.interfaces import ILayoutTemplate
>>> template = zope.component.queryMultiAdapter(
... (view, request),
... interface=IContentTemplate, name='edit')
>>> print(template(view))
<div>edit</div>
Custom template
===============
Or you can define own interfaces and register templates for them:
>>> from zope.pagetemplate.interfaces import IPageTemplate
>>> class IMyTemplate(IPageTemplate):
... """My template"""
Make the template interface available as a custom module class.
>>> sys.modules['custom'].IMyTemplate = IMyTemplate
Dfine a new template
>>> interfaceTemplate = os.path.join(temp_dir, 'interface.pt')
>>> with open(interfaceTemplate, 'w') as file:
... _ = file.write('''<div>interface</div>''')
>>> context = xmlconfig.string("""
... <configure
... xmlns:z3c="http://namespaces.zope.org/z3c">
... <z3c:template
... template="%s"
... for="custom.IView"
... provides="custom.IMyTemplate"
... />
... </configure>
... """ % interfaceTemplate, context=context)
Let's see if we get the template by the new interface:
>>> from z3c.template.interfaces import ILayoutTemplate
>>> template = zope.component.queryMultiAdapter((view, request),
... interface=IMyTemplate,)
>>> print(template(view))
<div>interface</div>
Cleanup
=======
Now we need to clean up the custom module.
>>> del sys.modules['custom']
| z3c.template | /z3c.template-4.0-py3-none-any.whl/z3c/template/zcml.rst | zcml.rst |
"""ZCML Directives
"""
import os
import zope.component.zcml
import zope.configuration.fields
import zope.interface
import zope.schema
from zope.configuration.exceptions import ConfigurationError
from zope.publisher.interfaces.browser import IDefaultBrowserLayer
import z3c.template.interfaces
from z3c.template.template import TemplateFactory
class ITemplateDirective(zope.interface.Interface):
"""Parameters for the template directive."""
template = zope.configuration.fields.Path(
title='Layout template.',
description="Refers to a file containing a page template (should "
"end in extension ``.pt`` or ``.html``).",
required=True,
)
name = zope.schema.TextLine(
title="The name of the template.",
description="The name is used to look up the template.",
default='',
required=False)
macro = zope.schema.TextLine(
title='Macro',
description="""
The macro to be used.
This allows us to define different macros in one template.
The template designer can now create a whole site, the
ViewTemplate can then extract the macros for single viewlets
or views.
If no macro is given the whole template is used for rendering.
""",
default='',
required=False,
)
for_ = zope.configuration.fields.GlobalObject(
title='View',
description='The view for which the template should be available',
default=zope.interface.Interface,
required=False,
)
layer = zope.configuration.fields.GlobalObject(
title='Layer',
description='The layer for which the template should be available',
required=False,
default=IDefaultBrowserLayer,
)
context = zope.configuration.fields.GlobalObject(
title='Context',
description='The context for which the template should be available',
required=False,
)
provides = zope.configuration.fields.GlobalInterface(
title="Interface the template provides",
description="This attribute specifies the interface the template"
" instance will provide.",
default=z3c.template.interfaces.IContentTemplate,
required=False,
)
contentType = zope.schema.ASCIILine(
title='Content Type',
description='The content type identifies the type of data.',
default='text/html',
required=False,
)
class ILayoutTemplateDirective(ITemplateDirective):
"""Parameters for the layout template directive."""
provides = zope.configuration.fields.GlobalInterface(
title="Interface the template provides",
description="This attribute specifies the interface the template"
" instance will provide.",
default=z3c.template.interfaces.ILayoutTemplate,
required=False,
)
def templateDirective(
_context, template, name='',
for_=zope.interface.Interface, layer=IDefaultBrowserLayer,
provides=z3c.template.interfaces.IContentTemplate,
contentType='text/html', macro=None, context=None):
# Make sure that the template exists
template = os.path.abspath(str(_context.path(template)))
if not os.path.isfile(template):
raise ConfigurationError("No such file", template)
factory = TemplateFactory(template, contentType, macro)
zope.interface.directlyProvides(factory, provides)
if context is not None:
for_ = (for_, layer, context)
else:
for_ = (for_, layer)
# register the template
if name:
zope.component.zcml.adapter(_context, (factory,), provides,
for_, name=name)
else:
zope.component.zcml.adapter(_context, (factory,), provides,
for_)
def layoutTemplateDirective(
_context, template, name='',
for_=zope.interface.Interface, layer=IDefaultBrowserLayer,
provides=z3c.template.interfaces.ILayoutTemplate,
contentType='text/html', macro=None, context=None):
templateDirective(_context, template, name, for_, layer, provides,
contentType, macro, context) | z3c.template | /z3c.template-4.0-py3-none-any.whl/z3c/template/zcml.py | zcml.py |
from zope import component
from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile
from zope.pagetemplate.interfaces import IPageTemplate
from zope.pagetemplate.pagetemplate import PageTemplate
from z3c.template import interfaces
class Macro:
# XXX: We can't use Zope's `TALInterpreter` class directly
# because it (obviously) only supports the Zope page template
# implementation. As a workaround or trick we use a wrapper
# template.
wrapper = PageTemplate()
wrapper.write(
'<metal:main use-macro="python: options[\'macro\']" />'
)
def __init__(self, template, name, view, request, contentType):
self.macro = template.macros[name]
self.contentType = contentType
self.view = view
self.request = request
def __call__(self, **kwargs):
kwargs['macro'] = self.macro
kwargs.setdefault('view', self.view)
kwargs.setdefault('request', self.request)
result = self.wrapper(**kwargs)
if not self.request.response.getHeader("Content-Type"):
self.request.response.setHeader(
"Content-Type", self.contentType)
return result
class TemplateFactory:
"""Template factory."""
template = None
def __init__(self, filename, contentType, macro=None):
self.contentType = contentType
self.template = ViewPageTemplateFile(
filename, content_type=contentType)
self.macro = macro
def __call__(self, view, request, context=None):
if self.macro is None:
return self.template
return Macro(
self.template, self.macro, view, request, self.contentType)
class BoundViewTemplate:
__self__ = None
__func__ = None
def __init__(self, pt, ob):
object.__setattr__(self, '__func__', pt)
object.__setattr__(self, '__self__', ob)
im_self = property(lambda self: self.__self__)
im_func = property(lambda self: self.__func__)
def __call__(self, *args, **kw):
if self.__self__ is None:
im_self, args = args[0], args[1:]
else:
im_self = self.__self__
return self.__func__(im_self, *args, **kw)
def __setattr__(self, name, v):
raise AttributeError("Can't set attribute", name)
def __repr__(self):
return "<BoundViewTemplate of %r>" % self.__self__
class ViewTemplate:
def __init__(self, provides=IPageTemplate, name=''):
self.provides = provides
self.name = name
def __call__(self, instance, *args, **keywords):
template = component.queryMultiAdapter(
(instance, instance.request, instance.context),
self.provides, name=self.name)
if template is None:
template = component.getMultiAdapter(
(instance, instance.request),
self.provides, name=self.name)
return template(instance, *args, **keywords)
def __get__(self, instance, type):
return BoundViewTemplate(self, instance)
getViewTemplate = ViewTemplate
class GetPageTemplate(ViewTemplate):
def __init__(self, name=''):
self.provides = interfaces.IContentTemplate
self.name = name
getPageTemplate = GetPageTemplate
class GetLayoutTemplate(ViewTemplate):
def __init__(self, name=''):
self.provides = interfaces.ILayoutTemplate
self.name = name
getLayoutTemplate = GetLayoutTemplate | z3c.template | /z3c.template-4.0-py3-none-any.whl/z3c/template/template.py | template.py |
import os
import shutil
import sys
import tempfile
from optparse import OptionParser
__version__ = '2015-07-01'
# See zc.buildout's changelog if this version is up to date.
tmpeggs = tempfile.mkdtemp(prefix='bootstrap-')
usage = '''\
[DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options]
Bootstraps a buildout-based project.
Simply run this script in a directory containing a buildout.cfg, using the
Python that you want bin/buildout to use.
Note that by using --find-links to point to local resources, you can keep
this script from going over the network.
'''
parser = OptionParser(usage=usage)
parser.add_option("--version",
action="store_true", default=False,
help=("Return bootstrap.py version."))
parser.add_option("-t", "--accept-buildout-test-releases",
dest='accept_buildout_test_releases',
action="store_true", default=False,
help=("Normally, if you do not specify a --version, the "
"bootstrap script and buildout gets the newest "
"*final* versions of zc.buildout and its recipes and "
"extensions for you. If you use this flag, "
"bootstrap and buildout will get the newest releases "
"even if they are alphas or betas."))
parser.add_option("-c", "--config-file",
help=("Specify the path to the buildout configuration "
"file to be used."))
parser.add_option("-f", "--find-links",
help=("Specify a URL to search for buildout releases"))
parser.add_option("--allow-site-packages",
action="store_true", default=False,
help=("Let bootstrap.py use existing site packages"))
parser.add_option("--buildout-version",
help="Use a specific zc.buildout version")
parser.add_option("--setuptools-version",
help="Use a specific setuptools version")
parser.add_option("--setuptools-to-dir",
help=("Allow for re-use of existing directory of "
"setuptools versions"))
options, args = parser.parse_args()
if options.version:
print("bootstrap.py version %s" % __version__)
sys.exit(0)
######################################################################
# load/install setuptools
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
ez = {}
if os.path.exists('ez_setup.py'):
exec(open('ez_setup.py').read(), ez)
else:
exec(urlopen('https://bootstrap.pypa.io/ez_setup.py').read(), ez)
if not options.allow_site_packages:
# ez_setup imports site, which adds site packages
# this will remove them from the path to ensure that incompatible versions
# of setuptools are not in the path
import site
# inside a virtualenv, there is no 'getsitepackages'.
# We can't remove these reliably
if hasattr(site, 'getsitepackages'):
for sitepackage_path in site.getsitepackages():
# Strip all site-packages directories from sys.path that
# are not sys.prefix; this is because on Windows
# sys.prefix is a site-package directory.
if sitepackage_path != sys.prefix:
sys.path[:] = [x for x in sys.path
if sitepackage_path not in x]
setup_args = dict(to_dir=tmpeggs, download_delay=0)
if options.setuptools_version is not None:
setup_args['version'] = options.setuptools_version
if options.setuptools_to_dir is not None:
setup_args['to_dir'] = options.setuptools_to_dir
ez['use_setuptools'](**setup_args)
import setuptools
import pkg_resources
# This does not (always?) update the default working set. We will
# do it.
for path in sys.path:
if path not in pkg_resources.working_set.entries:
pkg_resources.working_set.add_entry(path)
######################################################################
# Install buildout
ws = pkg_resources.working_set
setuptools_path = ws.find(
pkg_resources.Requirement.parse('setuptools')).location
# Fix sys.path here as easy_install.pth added before PYTHONPATH
cmd = [sys.executable, '-c',
'import sys; sys.path[0:0] = [%r]; ' % setuptools_path +
'from setuptools.command.easy_install import main; main()',
'-mZqNxd', tmpeggs]
find_links = os.environ.get(
'bootstrap-testing-find-links',
options.find_links or
('http://downloads.buildout.org/'
if options.accept_buildout_test_releases else None)
)
if find_links:
cmd.extend(['-f', find_links])
requirement = 'zc.buildout'
version = options.buildout_version
if version is None and not options.accept_buildout_test_releases:
# Figure out the most recent final version of zc.buildout.
import setuptools.package_index
_final_parts = '*final-', '*final'
def _final_version(parsed_version):
try:
return not parsed_version.is_prerelease
except AttributeError:
# Older setuptools
for part in parsed_version:
if (part[:1] == '*') and (part not in _final_parts):
return False
return True
index = setuptools.package_index.PackageIndex(
search_path=[setuptools_path])
if find_links:
index.add_find_links((find_links,))
req = pkg_resources.Requirement.parse(requirement)
if index.obtain(req) is not None:
best = []
bestv = None
for dist in index[req.project_name]:
distv = dist.parsed_version
if _final_version(distv):
if bestv is None or distv > bestv:
best = [dist]
bestv = distv
elif distv == bestv:
best.append(dist)
if best:
best.sort()
version = best[-1].version
if version:
requirement = '=='.join((requirement, version))
cmd.append(requirement)
import subprocess
if subprocess.call(cmd) != 0:
raise Exception(
"Failed to execute command:\n%s" % repr(cmd)[1:-1])
######################################################################
# Import and run buildout
ws.add_entry(tmpeggs)
ws.require(requirement)
import zc.buildout.buildout
if not [a for a in args if '=' not in a]:
args.append('bootstrap')
# if -c was provided, we push it back into args for buildout' main function
if options.config_file is not None:
args[0:0] = ['-c', options.config_file]
zc.buildout.buildout.main(args)
shutil.rmtree(tmpeggs) | z3c.testing | /z3c.testing-1.0.0a4.tar.gz/z3c.testing-1.0.0a4/bootstrap.py | bootstrap.py |
import os
import transaction
import shutil
from ZODB.FileStorage import FileStorage
from zope.app.appsetup import database
from zope.app.testing import functional
from zope.app.publication.zopepublication import ZopePublication
import sys
from zope.site import hooks
class BufferedDatabaseTestLayer(object):
"""A test layer which creates a filestorage database.
The created database is later used without the need to run through the
setup again.
This speeds up functional tests.
"""
__name__ = "BufferedTestLayer"
__bases__ = ()
path = None
def __init__(self, config_file=None, module=__module__, # noqa
name="BufferedTestLayer", path=None, clean=False):
self.config_file = config_file or functional.Functional.config_file
self.__module__ = module
self.__name__ = name
self.path = path
self.dbDir = os.path.join(self.path,
'var_%s' % self.__module__)
if clean and os.path.isdir(self.dbDir):
shutil.rmtree(self.dbDir)
def setUpApplication(self, app):
# to be overridden by subclass
pass
def setUp(self):
if not os.path.exists(self.dbDir):
os.mkdir(self.dbDir)
filename = os.path.join(self.dbDir, 'TestData.fs')
fsetup = functional.FunctionalTestSetup(self.config_file)
self.original = fsetup.base_storage
if not os.path.exists(filename):
# Generate a new database from scratch and fill it
db = database(filename)
connection = db.open()
root = connection.root()
app = root[ZopePublication.root_name]
# store the site, because the connection gets closed
site = hooks.getSite()
self.setUpApplication(app)
transaction.commit()
connection.close()
db.close()
hooks.setSite(site)
# sets up the db stuff normal
fsetup.setUp()
# replace the storage with our filestorage
fsetup.base_storage = FileStorage(filename)
# override close on this instance, so files dont get closed on
# setup/teardown of functionsetup
fsetup.base_storage.close = lambda: None
def tearDown(self):
fsetup = functional.FunctionalTestSetup(self.config_file)
# close the filestorage files now by calling the original
# close on our storage instance
FileStorage.close(fsetup.base_storage)
# replace the storage with the original, so functionalsetup
# can do what it wants with it
fsetup.base_storage = self.original
fsetup.tearDown()
fsetup.tearDownCompletely()
def defineLayer(name, zcml=None, appSetUp=None, clean=False):
"""Helper function for defining layers.
Defines a new buffered database layer
:name: the name of the layer in the module
:zcml: optional zcml file relative to package dir
:appSetUp: a callable which takes an application object as argument
:clean: if True the database directory is deleted on init
"""
globals = sys._getframe(1).f_globals
if zcml is not None:
zcml = os.path.join(os.path.split(globals['__file__'])[0], zcml)
l = BufferedDatabaseTestLayer(
zcml, globals['__name__'], name,
path=os.path.dirname(globals['__file__']),
clean=clean)
if appSetUp is not None:
l.setUpApplication = appSetUp
globals[name] = l | z3c.testing | /z3c.testing-1.0.0a4.tar.gz/z3c.testing-1.0.0a4/src/z3c/testing/layer.py | layer.py |
import os
from ZODB.FileStorage import FileStorage
from ZODB.DB import DB
from ZODB.DemoStorage import DemoStorage
import doctest
from zope.app.publication.zopepublication import ZopePublication
from zope.app.testing import setup
###############################################################################
#
# Test component
#
###############################################################################
class ContextStub(object):
"""Stub for the context argument passed to evolve scripts.
>>> from zope.app.zopeappgenerations import getRootFolder
>>> context = ContextStub()
>>> getRootFolder(context) is context.root_folder
True
"""
class ConnectionStub(object):
def __init__(self, root_folder, db):
self.root_folder = root_folder
self.db = db
def root(self):
return {ZopePublication.root_name: self.root_folder}
@property
def _storage(self):
return self.db._storage._base
def get(self, oid):
return self.db.open().get(oid)
def __init__(self, rootFolder, db):
self.root_folder = rootFolder
self.connection = self.ConnectionStub(self.root_folder, db)
def getDBRoot(db):
"""Return the Zope root folder."""
connection = db.open()
root = connection.root()
return root[ZopePublication.root_name]
def getDB(filename, package=None):
"""Return a DB by it's path."""
if package is not None:
filename = doctest._module_relative_path(package, filename)
package = package.__file__
else:
package = __file__
filename = os.path.join(os.path.dirname(package), filename)
fileStorage = FileStorage(filename)
storage = DemoStorage("Demo Storage", fileStorage)
return DB(storage)
###############################################################################
#
# Test setup
#
###############################################################################
def setUpGeneration(test):
setup.placefulSetUp()
def tearDownGeneration(test):
setup.placefulTearDown() | z3c.testing | /z3c.testing-1.0.0a4.tar.gz/z3c.testing-1.0.0a4/src/z3c/testing/generation.py | generation.py |
import unittest
from zope.container.tests.test_icontainer import BaseTestIContainer as BTIC
from zope.container.tests.test_icontainer import DefaultTestData
from zope.interface.verify import verifyObject, verifyClass
###############################################################################
#
# TestCase
#
###############################################################################
marker_pos = object()
marker_kws = object()
class TestCase(unittest.TestCase):
iface = None
klass = None
pos = marker_pos
kws = marker_kws
def getTestInterface(self):
if self.iface is not None:
return self.iface
msg = 'Subclasses has to implement getTestInterface()'
raise NotImplementedError(msg)
def getTestClass(self):
if self.klass is not None:
return self.klass
raise NotImplementedError('Subclasses has to implement getTestClass()')
def getTestPos(self):
return self.pos
def getTestKws(self):
return self.kws
def makeTestObject(self, object=None, *pos, **kws):
# provide default positional or keyword arguments
ourpos = self.getTestPos()
if ourpos is not marker_pos and not pos:
pos = ourpos
ourkws = self.getTestKws()
if ourkws is not marker_kws and not kws:
kws = ourkws
testclass = self.getTestClass()
if object is None:
# a class instance itself is the object to be tested.
return testclass(*pos, **kws)
else:
# an adapted instance is the object to be tested.
return testclass(object, *pos, **kws)
###############################################################################
#
# Public Base Tests
#
###############################################################################
class InterfaceBaseTest(TestCase):
"""Base test for IContainer including interface test."""
def test_verifyClass(self):
# class test
self.assertTrue(
verifyClass(self.getTestInterface(), self.getTestClass()))
def test_verifyObject(self):
# object test
self.assertTrue(
verifyObject(self.getTestInterface(), self.makeTestObject()))
###############################################################################
#
# IContainer Base Tests
#
###############################################################################
class BaseTestIContainer(InterfaceBaseTest, BTIC):
def makeTestData(self):
return DefaultTestData()
def getUnknownKey(self):
return '10'
def getBadKeyTypes(self):
return [None, ['foo'], 1, b'\xf3abc'] | z3c.testing | /z3c.testing-1.0.0a4.tar.gz/z3c.testing-1.0.0a4/src/z3c/testing/app.py | app.py |
Zope Public License (ZPL) Version 2.1
A copyright notice accompanies this license document that identifies the
copyright holders.
This license has been certified as open source. It has also been designated as
GPL compatible by the Free Software Foundation (FSF).
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions in source code must retain the accompanying copyright
notice, this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the accompanying copyright
notice, this list of conditions, and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Names of the copyright holders must not be used to endorse or promote
products derived from this software without prior written permission from the
copyright holders.
4. The right to distribute this software or to use it for any purpose does not
give you the right to use Servicemarks (sm) or Trademarks (tm) of the
copyright
holders. Use of them is covered by separate agreement with the copyright
holders.
5. If any files are modified, you must cause the modified files to carry
prominent notices stating that you changed the files and the date of any
change.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESSED
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
| z3c.traverser | /z3c.traverser-2.0-py3-none-any.whl/z3c.traverser-2.0.dist-info/LICENSE.rst | LICENSE.rst |
====================
Pluggable Traversers
====================
Traversers are Zope's mechanism to convert URI paths to an object of the
application. They provide an extremly flexible mechanism to make decisions
based on the policies of the application. Unfortunately the default traverser
implementation is not flexible enough to deal with arbitrary extensions (via
adapters) of objects that also wish to participate in the traversal decision
process.
The pluggable traverser allows developers, especially third-party developers,
to add new traversers to an object without altering the original traversal
implementation.
>>> from z3c.traverser.traverser import PluggableTraverser
Let's say that we have an object
>>> from zope.interface import Interface, implementer
>>> class IContent(Interface):
... pass
>>> @implementer(IContent)
... class Content(object):
... var = True
>>> content = Content()
that we wish to traverse to. Since traversers are presentation-type specific,
they are implemented as views and must thus be initiated using a request:
>>> from zope.publisher.base import TestRequest
>>> request = TestRequest('')
>>> traverser = PluggableTraverser(content, request)
We can now try to lookup the variable:
>>> traverser.publishTraverse(request, 'var')
Traceback (most recent call last):
...
NotFound: Object: <Content object at ...>, name: 'var'
But it failed. Why? Because we have not registered a plugin traverser yet that
knows how to lookup attributes. This package provides such a traverser
already, so we just have to register it:
>>> from zope.component import provideSubscriptionAdapter
>>> from zope.publisher.interfaces import IPublisherRequest
>>> from z3c.traverser.traverser import AttributeTraverserPlugin
>>> provideSubscriptionAdapter(AttributeTraverserPlugin,
... (IContent, IPublisherRequest))
If we now try to lookup the attribute, we the value:
>>> traverser.publishTraverse(request, 'var')
True
However, an incorrect variable name will still return a ``NotFound`` error:
>>> traverser.publishTraverse(request, 'bad')
Traceback (most recent call last):
...
NotFound: Object: <Content object at ...>, name: 'bad'
Every traverser should also make sure that the passed in name is not a
view. (This allows us to not specify the ``@@`` in front of a view.) So let's
register one:
>>> class View(object):
... def __init__(self, context, request):
... pass
>>> from zope.component import provideAdapter
>>> from zope.publisher.interfaces import IPublisherRequest
>>> provideAdapter(View,
... adapts=(IContent, IPublisherRequest),
... provides=Interface,
... name='view.html')
Now we can lookup the view as well:
>>> traverser.publishTraverse(request, 'view.html')
<View object at ...>
Advanced Uses
-------------
A more interesting case to consider is a traverser for a container. If you
really dislike the Zope 3 traversal namespace notation ``++namespace++`` and
you can control the names in the container, then the pluggable traverser will
also provide a viable solution. Let's say we have a container
>>> from zope.container.interfaces import IContainer
>>> class IMyContainer(IContainer):
... pass
>>> from zope.container.btree import BTreeContainer
>>> @implementer(IMyContainer)
... class MyContainer(BTreeContainer):
... foo = True
... bar = False
>>> myContainer = MyContainer()
>>> myContainer['blah'] = 123
and we would like to be able to traverse
* all items of the container, as well as
>>> from z3c.traverser.traverser import ContainerTraverserPlugin
>>> from z3c.traverser.interfaces import ITraverserPlugin
>>> provideSubscriptionAdapter(ContainerTraverserPlugin,
... (IMyContainer, IPublisherRequest),
... ITraverserPlugin)
* the ``foo`` attribute. Luckily we also have a predeveloped traverser for
this:
>>> from z3c.traverser.traverser import \
... SingleAttributeTraverserPlugin
>>> provideSubscriptionAdapter(SingleAttributeTraverserPlugin('foo'),
... (IMyContainer, IPublisherRequest))
We can now use the pluggable traverser
>>> traverser = PluggableTraverser(myContainer, request)
to look up items
>>> traverser.publishTraverse(request, 'blah')
123
and the ``foo`` attribute:
>>> traverser.publishTraverse(request, 'foo')
True
However, we cannot lookup the ``bar`` attribute or any other non-existent
item:
>>> traverser.publishTraverse(request, 'bar')
Traceback (most recent call last):
...
NotFound: Object: <MyContainer object at ...>, name: 'bar'
>>> traverser.publishTraverse(request, 'bad')
Traceback (most recent call last):
...
NotFound: Object: <MyContainer object at ...>, name: 'bad'
You can also add traversers that return an adapted object. For example, let's
take the following adapter:
>>> class ISomeAdapter(Interface):
... pass
>>> from zope.component import adapts
>>> @implementer(ISomeAdapter)
... class SomeAdapter(object):
... adapts(IMyContainer)
...
... def __init__(self, context):
... pass
>>> from zope.component import adapts, provideAdapter
>>> provideAdapter(SomeAdapter)
Now we register this adapter under the traversal name ``some``:
>>> from z3c.traverser.traverser import AdapterTraverserPlugin
>>> provideSubscriptionAdapter(
... AdapterTraverserPlugin('some', ISomeAdapter),
... (IMyContainer, IPublisherRequest))
So here is the result:
>>> traverser.publishTraverse(request, 'some')
<SomeAdapter object at ...>
If the object is not adaptable, we'll get NotFound. Let's register a
plugin that tries to query a named adapter for ISomeAdapter. The third
argument for AdapterTraverserPlugin is used to specify the adapter name.
>>> provideSubscriptionAdapter(
... AdapterTraverserPlugin('badadapter', ISomeAdapter, 'other'),
... (IMyContainer, IPublisherRequest))
>>> traverser.publishTraverse(request, 'badadapter')
Traceback (most recent call last):
...
NotFound: Object: <MyContainer object at ...>, name: 'badadapter'
Traverser Plugins
-----------------
The `traverser` package comes with several default traverser plugins; three of
them were already introduced above: `SingleAttributeTraverserPlugin`,
`AdapterTraverserPlugin`, and `ContainerTraverserPlugin`. Another plugin is
the the `NullTraverserPlugin`, which always just returns the object itself:
>>> from z3c.traverser.traverser import NullTraverserPlugin
>>> SomethingPlugin = NullTraverserPlugin('something')
>>> plugin = SomethingPlugin(content, request)
>>> plugin.publishTraverse(request, 'something')
<Content object at ...>
>>> plugin.publishTraverse(request, 'something else')
Traceback (most recent call last):
...
NotFound: Object: <Content object at ...>, name: 'something else'
All of the above traversers with exception of the `ContainerTraverserPlugin`
are implementation of the abstract `NameTraverserPlugin` class. Name traversers
are traversers that can resolve one particular name. By using the abstract
`NameTraverserPlugin` class, all of the traverser boilerplate can be
avoided. Here is a simple example that always returns a specific value for a
traversed name:
>>> from z3c.traverser.traverser import NameTraverserPlugin
>>> class TrueTraverserPlugin(NameTraverserPlugin):
... traversalName = 'true'
... def _traverse(self, request, name):
... return True
As you can see realized name traversers must implement the ``_traverse()``
method, which is only responsible for returning the result. Of course it can
also raise the `NotFound` error if something goes wrong during the
computation. LEt's check it out:
>>> plugin = TrueTraverserPlugin(content, request)
>>> plugin.publishTraverse(request, 'true')
True
>>> plugin.publishTraverse(request, 'false')
Traceback (most recent call last):
...
NotFound: Object: <Content object at ...>, name: 'false'
A final traverser that is offered by the package is the
`AttributeTraverserPlugin``, which simply allows one to traverse all
accessible attributes of an object:
>>> from z3c.traverser.traverser import AttributeTraverserPlugin
>>> plugin = AttributeTraverserPlugin(myContainer, request)
>>> plugin.publishTraverse(request, 'foo')
True
>>> plugin.publishTraverse(request, 'bar')
False
>>> plugin.publishTraverse(request, 'blah')
Traceback (most recent call last):
...
NotFound: Object: <MyContainer object at ...>, name: 'blah'
>>> plugin.publishTraverse(request, 'some')
Traceback (most recent call last):
...
NotFound: Object: <MyContainer object at ...>, name: 'some'
Browser traverser
-----------------
There's also a special subclass of the PluggableTraverser that
implements the ``IBrowserPublisher`` interface, thus providing the
``browserDefault`` method that returns a default object and a view
name to traverse and use if there's no more steps to traverse.
Let's provide a view name registered as an IDefaultView adapter. This
is usually done by zope.publisher's browser:defaultView directive.
>>> from zope.publisher.interfaces import IDefaultViewName
>>> provideAdapter('view.html', (IContent, Interface), IDefaultViewName)
>>> from z3c.traverser.browser import PluggableBrowserTraverser
>>> traverser = PluggableBrowserTraverser(content, request)
>>> traverser.browserDefault(request)
(<Content object at 0x...>, ('@@view.html',))
| z3c.traverser | /z3c.traverser-2.0-py3-none-any.whl/z3c/traverser/README.rst | README.rst |
"""Pluggable Traverser Implementation
"""
from zope.component import queryAdapter
from zope.component import queryMultiAdapter
from zope.component import subscribers
from zope.interface import implementer
from zope.publisher.interfaces import NotFound
from z3c.traverser import interfaces
_marker = object()
@implementer(interfaces.IPluggableTraverser)
class BasePluggableTraverser:
def __init__(self, context, request):
self.context = context
self.request = request
def publishTraverse(self, request, name):
# Look at all the traverser plugins, whether they have an answer.
for traverser in subscribers((self.context, request),
interfaces.ITraverserPlugin):
try:
return traverser.publishTraverse(request, name)
except NotFound:
pass
raise NotFound(self.context, name, request)
class PluggableTraverser(BasePluggableTraverser):
"""Generic Pluggable Traverser."""
def publishTraverse(self, request, name):
try:
return super().publishTraverse(
request, name)
except NotFound:
pass
# The traversers did not have an answer, so let's see whether it is a
# view.
view = queryMultiAdapter((self.context, request), name=name)
if view is not None:
return view
raise NotFound(self.context, name, request)
@implementer(interfaces.ITraverserPlugin)
class NameTraverserPlugin:
"""Abstract class that traverses an object by name."""
traversalName = None
def __init__(self, context, request):
self.context = context
self.request = request
def publishTraverse(self, request, name):
if name == self.traversalName:
return self._traverse(request, name)
raise NotFound(self.context, name, request)
def _traverse(self, request, name):
raise NotImplementedError('Method must be implemented by subclasses.')
class NullTraverserPluginTemplate(NameTraverserPlugin):
"""Traverse to an adapter by name."""
def _traverse(self, request, name):
return self.context
def NullTraverserPlugin(traversalName):
return type('NullTraverserPlugin', (NullTraverserPluginTemplate,),
{'traversalName': traversalName})
class SingleAttributeTraverserPluginTemplate(NameTraverserPlugin):
"""Allow only a single attribute to be traversed."""
def _traverse(self, request, name):
return getattr(self.context, name)
def SingleAttributeTraverserPlugin(name):
return type('SingleAttributeTraverserPlugin',
(SingleAttributeTraverserPluginTemplate,),
{'traversalName': name})
class AdapterTraverserPluginTemplate(NameTraverserPlugin):
"""Traverse to an adapter by name."""
interface = None
adapterName = ''
def _traverse(self, request, name):
adapter = queryAdapter(self.context, self.interface,
name=self.adapterName)
if adapter is None:
raise NotFound(self.context, name, request)
return adapter
def AdapterTraverserPlugin(traversalName, interface, adapterName=''):
return type('AdapterTraverserPlugin',
(AdapterTraverserPluginTemplate,),
{'traversalName': traversalName,
'adapterName': adapterName,
'interface': interface})
@implementer(interfaces.ITraverserPlugin)
class ContainerTraverserPlugin:
"""A traverser that knows how to look up objects by name in a container."""
def __init__(self, container, request):
self.context = container
self.request = request
def publishTraverse(self, request, name):
"""See zope.publisher.interfaces.IPublishTraverse"""
subob = self.context.get(name, None)
if subob is None:
raise NotFound(self.context, name, request)
return subob
@implementer(interfaces.ITraverserPlugin)
class AttributeTraverserPlugin:
"""A simple traverser plugin that traverses an attribute by name"""
def __init__(self, context, request):
self.context = context
self.request = request
def publishTraverse(self, request, name):
try:
obj = getattr(self.context, name)
except AttributeError:
raise NotFound(self.context, name, request)
else:
return obj | z3c.traverser | /z3c.traverser-2.0-py3-none-any.whl/z3c/traverser/traverser.py | traverser.py |
=====================
Additional Namespaces
=====================
Principal
---------
The ``principal`` namespace allows to differentiate between usernames
in the url. This is usefull for caching on a per principal basis. The
namespace itself doesn't change anything. It just checks if the
principal is the one that is logged in.
>>> from z3c.traverser import namespace
>>> from zope.publisher.browser import TestRequest
>>> class Request(TestRequest):
... principal = None
...
... def shiftNameToApplication(self):
... pass
>>> class Principal(object):
... def __init__(self, id):
... self.id = id
>>> pid = 'something'
>>> r = Request()
>>> r.principal = Principal('anonymous')
If we have the wrong principal we get an Unauthorized exception.
>>> ns = namespace.principal(object(), r)
>>> ns.traverse('another', None) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
Unauthorized: ++principal++another
Otherwise not
>>> ns.traverse('anonymous', None)
<object object at ...>
| z3c.traverser | /z3c.traverser-2.0-py3-none-any.whl/z3c/traverser/namespace.rst | namespace.rst |
===================
Traversing Viewlets
===================
This package allows to traverse viewlets and viewletmanagers. It also
provides absolute url views for those objects which are described in
this file, for traversers see BROWSER.rst.
>>> from z3c.traverser.viewlet import browser
Let us define some test classes.
>>> import zope.component
>>> from zope.viewlet import manager
>>> from zope.viewlet import interfaces
>>> from zope.publisher.interfaces.browser import IDefaultBrowserLayer
>>> import zope.interface
>>> class ILeftColumn(interfaces.IViewletManager):
... """Viewlet manager located in the left column."""
>>> LeftColumn = manager.ViewletManager('left', ILeftColumn)
>>> zope.component.provideAdapter(
... LeftColumn,
... (zope.interface.Interface,
... IDefaultBrowserLayer, zope.interface.Interface),
... interfaces.IViewletManager, name='left')
You can then create a viewlet manager using this interface now:
>>> from zope.viewlet import viewlet
>>> from zope.container.contained import Contained
>>> class Content(Contained):
... pass
>>> root['content'] = Content()
>>> content = root['content']
>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest()
>>> from zope.publisher.interfaces.browser import IBrowserView
>>> from zope.publisher.browser import BrowserView
>>> class View(BrowserView):
... pass
We have to set the name, this is normally done in zcml.
>>> view = View(content, request)
>>> view.__name__ = 'test.html'
>>> leftColumn = LeftColumn(content, request, view)
Let us create a simple viewlet. Note that we need a __name__ attribute
in order to make the viewlet traversable. Normally you don't have to
take care of this, because the zcml directive sets the name upon
registration.
>>> class MyViewlet(viewlet.ViewletBase):
... __name__ = 'myViewlet'
... def render(self):
... return u'<div>My Viewlet</div>'
>>> from zope.security.checker import NamesChecker, defineChecker
>>> viewletChecker = NamesChecker(('update', 'render'))
>>> defineChecker(MyViewlet, viewletChecker)
>>> zope.component.provideAdapter(
... MyViewlet,
... (zope.interface.Interface, IDefaultBrowserLayer,
... IBrowserView, ILeftColumn),
... interfaces.IViewlet, name='myViewlet')
We should now be able to get the absolute url of the viewlet and the
manager. We have to register the adapter for the test.
>>> from zope.traversing.browser.interfaces import IAbsoluteURL
>>> from zope.traversing.browser import absoluteurl
>>> zope.component.provideAdapter(
... browser.ViewletAbsoluteURL,
... (interfaces.IViewlet, IDefaultBrowserLayer),
... IAbsoluteURL)
>>> zope.component.provideAdapter(
... browser.ViewletManagerAbsoluteURL,
... (interfaces.IViewletManager, IDefaultBrowserLayer),
... IAbsoluteURL, name="absolute_url")
>>> zope.component.provideAdapter(
... browser.ViewletManagerAbsoluteURL,
... (interfaces.IViewletManager, IDefaultBrowserLayer),
... IAbsoluteURL)
>>> myViewlet = MyViewlet(content, request, view, leftColumn)
>>> absoluteurl.absoluteURL(leftColumn, request)
'http://127.0.0.1/content/test.html/++manager++left'
>>> absoluteurl.absoluteURL(myViewlet, request)
'.../content/test.html/++manager++left/++viewlet++myViewlet'
| z3c.traverser | /z3c.traverser-2.0-py3-none-any.whl/z3c/traverser/viewlet/README.rst | README.rst |
"""Viewlet Traverser Browser Supprot
"""
from urllib.parse import quote
import zope.component
from zope import event
from zope.contentprovider.interfaces import BeforeUpdateEvent
from zope.publisher.browser import BrowserView
from zope.security.proxy import removeSecurityProxy
from zope.traversing.browser import absoluteurl
class ViewletAbsoluteURL(absoluteurl.AbsoluteURL):
def __str__(self):
context = removeSecurityProxy(self.context)
request = self.request
# The application URL contains all the namespaces that are at the
# beginning of the URL, such as skins, virtual host specifications and
# so on.
container = getattr(context, 'manager', None)
if container is None:
raise TypeError(absoluteurl._insufficientContext)
url = str(zope.component.getMultiAdapter((container, request),
name='absolute_url'))
name = self._getContextName(context)
if name is None:
raise TypeError(absoluteurl._insufficientContext)
if name:
url += '/' + quote(name.encode('utf-8'), absoluteurl._safe)
return url
def _getContextName(self, context):
name = getattr(context, '__name__', None)
return '++viewlet++' + name
__call__ = __str__
class ViewletManagerAbsoluteURL(absoluteurl.AbsoluteURL):
def __str__(self):
context = self.context
request = self.request
container = getattr(context, '__parent__', None)
if container is None:
raise TypeError(absoluteurl._insufficientContext)
url = str(zope.component.getMultiAdapter((container, request),
name='absolute_url'))
name = self._getContextName(context)
if name is None:
raise TypeError(absoluteurl._insufficientContext)
if name:
url += '/' + quote(name.encode('utf-8'), absoluteurl._safe)
return url
def _getContextName(self, context):
name = getattr(context, '__name__', None)
return '++manager++' + name
__call__ = __str__
class ViewletView(BrowserView):
def __call__(self):
event.notify(BeforeUpdateEvent(self.context, self.request))
self.context.update()
return self.context.render() | z3c.traverser | /z3c.traverser-2.0-py3-none-any.whl/z3c/traverser/viewlet/browser.py | browser.py |
====================
Viewlet Traversing
====================
Traversing to viewlets is done via namespaces.
>>> from webtest.app import TestApp
>>> browser = TestApp(wsgi_app)
>>> res = browser.get('http://localhost/@@test.html')
We have a test page registered that contains our viewlet. The viewlet
itself just renders a link to its location (this is just for testing).
>>> print(res.html)
<html>
<body>
<div><div><a
href="http://localhost/test.html/++manager++IMyManager/++viewlet++MyViewlet">My
Viewlet</a></div></div>
</body>
</html>
Let's follow the link to traverse the viewlet directly.
>>> res = res.click('My Viewlet')
>>> res.request.url
'http://localhost/test.html/++manager++IMyManager/++viewlet++MyViewlet'
>>> print(res.body.decode())
<div><a href="http://localhost/test.html/++manager++IMyManager/++viewlet++MyViewlet">My Viewlet</a></div>
What happens if a viewlet managers is nested into another viewlet? To test
this we will create another manager and another viewlet::
>>> res = browser.get('http://localhost/@@nested.html')
>>> print(res.html)
<html>
<body>
<div><div><a href="http://localhost/nested.html/++manager++IOuterManager/++viewlet++OuterViewlet/++manager++IInnerManager/++viewlet++InnerViewlet/++manager++IMostInnerManager/++viewlet++MostInnerViewlet">Most inner viewlet</a></div></div>
</body>
</html>
Let's follow the link to traverse the viewlet directly.
>>> res = res.click('Most inner viewlet')
>>> res.request.url
'http://localhost/nested.html/++manager++IOuterManager/++viewlet++OuterViewlet/++manager++IInnerManager/++viewlet++InnerViewlet/++manager++IMostInnerManager/++viewlet++MostInnerViewlet'
>>> print(res.body.decode())
<div><a href="http://localhost/nested.html/++manager++IOuterManager/++viewlet++OuterViewlet/++manager++IInnerManager/++viewlet++InnerViewlet/++manager++IMostInnerManager/++viewlet++MostInnerViewlet">Most inner viewlet</a></div>
Caveats
-------
Update of the manager is not called, because this may be too expensive
and normally the managers update just collects viewlets.
| z3c.traverser | /z3c.traverser-2.0-py3-none-any.whl/z3c/traverser/viewlet/BROWSER.rst | BROWSER.rst |
===============================================
Extracting Information from the Traversal Stack
===============================================
This package allows to define virtual traversal paths for collecting
arbitrary information from the traversal stack instead of, for
example, query strings.
In contrast to the common way of defining custom Traversers, this
implementation does not require to go through the whole traversal
process step by step. The traversal information needed is taken from
the traversalstack directly and the used parts of the stack are
consumed. This way one don't have to define proxy classes just for
traversal.
This implementation does not work in tales because it requires the
traversalstack of the request.
For each name in the traversal stack a named multiadapter is looked up
for ITraversalStackConsumer, if found the item gets removed from the
stack and the adapter is added to the request annotation.
>>> from z3c.traverser.stackinfo import traversing
>>> from z3c.traverser.stackinfo import interfaces
If there are no adapters defined, the traversalstack is kept as is. To
show this behaviour we define some sample classes.
>>> from zope import interface
>>> class IContent(interface.Interface):
... pass
>>> from zope.site.folder import Folder
>>> @interface.implementer(IContent)
... class Content(Folder):
... pass
There is a convinience function which returns an iterator which
iterates over tuples of adapterName, adapter. Additionally the
traversal stack of the request is consumed if needed.
>>> from zope.publisher.browser import TestRequest
>>> from zope.publisher.interfaces.browser import IBrowserRequest
>>> request = TestRequest()
We set the traversal stack manually for testing here.
>>> request.setTraversalStack(['index.html', 'path', 'some'])
>>> content = Content()
So if no ITraversalStackConsumer adapters are found the stack is left
untouched.
>>> list(traversing.getStackConsumers(content, request))
[]
>>> request.getTraversalStack()
['index.html', 'path', 'some']
There is a base class for consumer implementations which implements
the ITraversalStackConsumer interface.
>>> from z3c.traverser.stackinfo import consumer
>>> from zope.interface.verify import verifyObject
>>> o = consumer.BaseConsumer(None, None)
>>> verifyObject(interfaces.ITraversalStackConsumer,o)
True
Let us define a custom consumer.
>>> from zope import component
>>> class DummyConsumer(consumer.BaseConsumer):
... component.adapts(IContent, IBrowserRequest)
>>> component.provideAdapter(DummyConsumer, name='some')
Now we will find the newly registered consumer and the 'some' part of
the stack is consumed.
>>> consumers = list(traversing.getStackConsumers(content, request))
>>> consumers
[('some', <DummyConsumer named 'some'>)]
>>> request.getTraversalStack()
['index.html', 'path']
Each consumer at least has to consume one element, which is always
the name under which the adapter was registered under.
>>> name, cons = consumers[0]
>>> cons.__name__
'some'
Let us provide another adapter, to demonstrate that the adpaters
always have the reverse order of the traversal stack. This is actually
the order in the url.
>>> component.provideAdapter(DummyConsumer, name='other')
>>> stack = ['index.html', 'path', 'some', 'other']
>>> request.setTraversalStack(stack)
>>> consumers = list(traversing.getStackConsumers(content, request))
>>> consumers
[('other', <DummyConsumer named 'other'>),
('some', <DummyConsumer named 'some'>)]
>>> [c.__name__ for name, c in consumers]
['other', 'some']
The arguments attribute of the consumer class defines how many
arguments are consumed/needed from the stack. Let us create a KeyValue
consumer, that should extract key value pairs from the stack.
>>> class KeyValueConsumer(DummyConsumer):
... arguments=('key', 'value')
>>> component.provideAdapter(KeyValueConsumer, name='kv')
>>> stack = ['index.html', 'value', 'key', 'kv']
>>> request.setTraversalStack(stack)
>>> consumers = list(traversing.getStackConsumers(content, request))
>>> consumers
[('kv', <KeyValueConsumer named 'kv'>)]
>>> request.getTraversalStack()
['index.html']
>>> name, cons = consumers[0]
>>> cons.key
'key'
>>> cons.value
'value'
We can of course use multiple consumers of the same type.
>>> stack = ['index.html', 'v2', 'k2', 'kv', 'v1', 'k1', 'kv']
>>> request.setTraversalStack(stack)
>>> consumers = list(traversing.getStackConsumers(content, request))
>>> [(c.__name__, c.key, c.value) for name, c in consumers]
[('kv', 'k1', 'v1'), ('kv', 'k2', 'v2')]
If we have too less arguments a NotFound exception.
>>> stack = ['k2', 'kv', 'v1', 'k1', 'kv']
>>> request.setTraversalStack(stack)
>>> consumers = list(traversing.getStackConsumers(content, request))
Traceback (most recent call last):
...
NotFound: Object: <Content object at ...>, name: 'kv'
In order to actually use the stack consumers to retrieve information,
there is another convinience function which stores the consumers in
the requests annotations. This should noramlly be called on
BeforeTraverseEvents.
>>> stack = ['index.html', 'v2', 'k2', 'kv', 'v1', 'k1', 'kv']
>>> request.setTraversalStack(stack)
>>> traversing.applyStackConsumers(content, request)
>>> request.annotations[traversing.CONSUMERS_ANNOTATION_KEY]
[<KeyValueConsumer named 'kv'>,
<KeyValueConsumer named 'kv'>]
Instead of messing with the annotations one just can adapt the request
to ITraversalStackInfo.
>>> component.provideAdapter(consumer.requestTraversalStackInfo)
>>> ti = interfaces.ITraversalStackInfo(request)
>>> ti
(<KeyValueConsumer named 'kv'>, <KeyValueConsumer named 'kv'>)
>>> len(ti)
2
The adapter always returs an empty TraversalStackInfoObject if there
is no traversalstack information.
>>> request = TestRequest()
>>> ti = interfaces.ITraversalStackInfo(request)
>>> len(ti)
0
Virtual Host
------------
If virtual hosts are used the traversal stack contains aditional information
for the virtual host which will interfere which the stack consumer.
>>> stack = ['index.html', 'value', 'key',
... 'kv', '++', 'inside vh', '++vh++something']
>>> request.setTraversalStack(stack)
>>> consumers = list(traversing.getStackConsumers(content, request))
>>> consumers
[('kv', <KeyValueConsumer named 'kv'>)]
>>> request.getTraversalStack()
['index.html', '++', 'inside vh', '++vh++something']
URL Handling
------------
Let us try these things with a real url, in our test the root is the site.
>>> from zope.traversing.browser.absoluteurl import absoluteURL
>>> absoluteURL(root, request)
'http://127.0.0.1'
There is an unconsumedURL function which returns the url of an object
with the traversal information, which is normally omitted.
>>> request = TestRequest()
>>> root['content'] = content
>>> absoluteURL(root['content'], request)
'http://127.0.0.1/content'
>>> stack = ['index.html', 'v2 space', 'k2', 'kv', 'v1', 'k1', 'kv']
>>> request.setTraversalStack(stack)
>>> traversing.applyStackConsumers(root['content'], request)
>>> traversing.unconsumedURL(root['content'], request)
'http://127.0.0.1/content/kv/k1/v1/kv/k2/v2%20space'
Let us have more than one content object
>>> under = content['under'] = Content()
>>> request = TestRequest()
>>> traversing.unconsumedURL(under, request)
'http://127.0.0.1/content/under'
We add some consumers to the above object
>>> request = TestRequest()
>>> stack = ['index.html', 'value1', 'key1', 'kv']
>>> request.setTraversalStack(stack)
>>> traversing.applyStackConsumers(root['content'], request)
>>> traversing.unconsumedURL(root['content'], request)
'http://127.0.0.1/content/kv/key1/value1'
>>> traversing.unconsumedURL(under, request)
'http://127.0.0.1/content/kv/key1/value1/under'
And now to the object below too.
>>> request = TestRequest()
>>> stack = ['index.html', 'value1', 'key1', 'kv']
>>> request.setTraversalStack(stack)
>>> traversing.applyStackConsumers(root['content'], request)
>>> stack = ['index.html', 'value2', 'key2', 'kv']
>>> request.setTraversalStack(stack)
>>> traversing.applyStackConsumers(under, request)
>>> traversing.unconsumedURL(root['content'], request)
'http://127.0.0.1/content/kv/key1/value1'
>>> traversing.unconsumedURL(under, request)
'http://127.0.0.1/content/kv/key1/value1/under/kv/key2/value2'
Or only the object below.
>>> request = TestRequest()
>>> traversing.applyStackConsumers(root['content'], request)
>>> stack = ['index.html', 'value2', 'key2', 'kv']
>>> request.setTraversalStack(stack)
>>> traversing.applyStackConsumers(under, request)
>>> traversing.unconsumedURL(root['content'], request)
'http://127.0.0.1/content'
>>> traversing.unconsumedURL(under, request)
'http://127.0.0.1/content/under/kv/key2/value2'
The unconsumedURL function is also available as a view, named
``unconsumed_url``, similar to ``absolute_url`` one.
>>> from zope.component import getMultiAdapter
>>> url = getMultiAdapter((under, request), name='unconsumed_url')
>>> str(url)
'http://127.0.0.1/content/under/kv/key2/value2'
>>> url()
'http://127.0.0.1/content/under/kv/key2/value2'
| z3c.traverser | /z3c.traverser-2.0-py3-none-any.whl/z3c/traverser/stackinfo/README.rst | README.rst |
===============================================
Extracting Information from the Traversal Stack
===============================================
This is a simple example to demonstrate the usage of this
package. Please take a look into the testing directory to see how
things should be set up.
>>> from webtest.app import TestApp
>>> browser = TestApp(wsgi_app,
... extra_environ={'wsgi.handleErrors': False,
... 'paste.throw_errors': True,
... 'x-wsgiorg.throw_errors': True})
>>> res = browser.get('http://localhost/@@stackinfo.html')
So basically we have no stack info.
>>> print(res.body.decode())
Stack Info from object at http://localhost/stackinfo.html:
Let us try to set foo to bar.
>>> res = browser.get('http://localhost/kv/foo/bar/@@stackinfo.html')
>>> print(res.body.decode())
Stack Info from object at http://localhost/stackinfo.html:
consumer kv:
key = 'foo'
value = 'bar'
Two consumers.
>>> res = browser.get(
... 'http://localhost/kv/foo/bar/kv/time/late/@@stackinfo.html')
>>> print(res.body.decode())
Stack Info from object at http://localhost/stackinfo.html:
consumer kv:
key = 'foo'
value = 'bar'
consumer kv:
key = 'time'
value = 'late'
Invalid url:
>>> browser.get('http://localhost/kv/foo/bar/kv/@@stackinfo.html') \
... # doctes: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
NotFound: Object: <...Folder object at ...>, name: 'kv'
| z3c.traverser | /z3c.traverser-2.0-py3-none-any.whl/z3c/traverser/stackinfo/BROWSER.rst | BROWSER.rst |
from urllib.parse import quote
from zope import component
from zope.proxy import sameProxiedObjects
from zope.publisher.browser import BrowserView
from zope.publisher.interfaces import NotFound
from zope.traversing.browser.absoluteurl import absoluteURL
from . import interfaces
CONSUMERS_ANNOTATION_KEY = 'z3c.traverser.consumers'
CONSUMED_ANNOTATION_KEY = 'z3c.traverser.consumed'
def getStackConsumers(context, request):
"""consumes the stack"""
vhStack = VHStack(request)
while True:
vhStack.prepare()
stack = request.getTraversalStack()
if not stack:
break
name = stack[-1]
consumer = component.queryMultiAdapter(
(context, request),
interface=interfaces.ITraversalStackConsumer,
name=name)
if consumer is None:
break
try:
consumer.consume()
except IndexError:
raise NotFound(context, name, request)
vhStack.reset()
yield (name, consumer)
vhStack.reset()
def applyStackConsumers(context, request):
if CONSUMED_ANNOTATION_KEY not in request.annotations:
request.annotations[CONSUMED_ANNOTATION_KEY] = []
request.annotations[CONSUMERS_ANNOTATION_KEY] = []
else:
for obj, consumed in request.annotations[CONSUMED_ANNOTATION_KEY]:
if sameProxiedObjects(obj, context):
return
orgStack = request.getTraversalStack()
cons = [cons for name, cons in getStackConsumers(
context, request)]
newStack = request.getTraversalStack()
if newStack != orgStack:
consumed = request.annotations[CONSUMED_ANNOTATION_KEY]
numItems = len(orgStack)-len(newStack)
vhStack = VHStack(request)
vhStack.prepare()
stack = request.getTraversalStack()
items = orgStack[len(stack):len(stack)+numItems]
vhStack.reset()
items.reverse()
consumed.append((context, items))
request.annotations[CONSUMERS_ANNOTATION_KEY].extend(cons)
def _encode(v, _safe='@+'):
return quote(v.encode('utf-8'), _safe)
def unconsumedURL(context, request):
url = absoluteURL(context, request)
consumed = request.annotations.get(CONSUMED_ANNOTATION_KEY)
if not consumed:
return url
inserts = []
for obj, names in consumed:
if obj is context:
# only calculate once
objURL = url
else:
objURL = absoluteURL(obj, request)
if not url.startswith(objURL):
# we are further down
break
names = '/' + '/'.join(map(_encode, names))
inserts.append((len(objURL), names))
offset = 0
for i, s in inserts:
oi = i + offset
pre = url[:oi]
post = url[oi:]
url = pre + s + post
offset += len(s)
return url
class UnconsumedURL(BrowserView):
def __str__(self):
return unconsumedURL(self.context, self.request)
__call__ = __str__
class VHStack:
"""Helper class to work around the special case with virtual hosts"""
def __init__(self, request):
self.request = request
self.vh = []
def prepare(self):
if not self.vh:
stack = self.request.getTraversalStack()
if not stack:
return
name = stack[-1]
if name.startswith('++vh++'):
while True:
self.vh.append(stack.pop())
if name == '++':
break
if not stack:
break
name = stack[-1]
# set stack without virtual host entries
self.request.setTraversalStack(stack)
def reset(self):
if self.vh:
stack = self.request.getTraversalStack()
while self.vh:
stack.append(self.vh.pop())
self.request.setTraversalStack(stack) | z3c.traverser | /z3c.traverser-2.0-py3-none-any.whl/z3c/traverser/stackinfo/traversing.py | traversing.py |
"""The 'unconfigure' grouping directive
"""
import zope.component.zcml
from zope.configuration import config
from zope.configuration.interfaces import IConfigurationContext
from zope.configuration.zopeconfigure import ZopeConfigure
from zope.security import adapter
def groupingDirectiveAllNS(_context, name, schema, handler,
usedIn=IConfigurationContext):
"""Registers a grouping directive with all namespaces.
"""
config.defineGroupingDirective(_context, name, schema, handler,
namespace="*", usedIn=usedIn)
def is_subscriber(discriminator, callable=None, args=(), kw={},
includepath=(), info='', order=0, **extra):
"""Determines whether the action has been emitted from the
<subscriber /> directive.
"""
return (discriminator is None and
callable is zope.component.zcml.handler and
args[0] == 'registerHandler')
def real_subscriber_factory(discriminator, callable=None, args=(), kw={},
includepath=(), info='', order=0, **extra):
"""Returns the real subscriber factory[#] and type of even that
the subscriber is registered for ('for' parameter).
This function assumes that the action in question is a subscriber
action. In other words, is_subscriber(**args) is True.
[#] Under certain circumstances, <subscriber /> wraps factories in
some security- or location-related adapter factory.
"""
factory = args[1]
for_ = args[2]
if isinstance(factory, (adapter.LocatingTrustedAdapterFactory,
adapter.LocatingUntrustedAdapterFactory,
adapter.TrustedAdapterFactory)):
factory = factory.factory
return factory, for_
class Unconfigure(ZopeConfigure):
def __init__(self, context, **kw):
super().__init__(context, **kw)
# Make a new actions list here. This will shadow
# context.actions which would otherwise be "inherited" by our
# superclass's __getattr__. By shadowing the original list,
# all actions within 'unconfigure' will be added to this list
# here, not the global actions list.
self.actions = []
# The same logic applies to _seen_files. It's normally used to
# avoid configuration conflicts by ignoring duplicated <include/>
# directives, but in this case we don't want to ignore an <include/>
# placed inside an <unconfigure> group that tries to undo a previous
# <include/>.
self._seen_files = set()
def after(self):
# Get a discriminator -> action representation of all the
# actions that have been churned out so far.
unique = {action['discriminator']: action
for action in self.context.actions
if action['discriminator'] is not None}
# Special-case subscriber actions: Find all subscriber actions
# and store them as (factory, for) -> action. They're a
# special case because their discriminators are None, so we
# can't pull the same trick as with other directives.
subscribers = {real_subscriber_factory(**action): action
for action in self.context.actions
if is_subscriber(**action)}
# Now let's go through the actions within 'unconfigure' and
# use their discriminator to remove the real actions
for unaction in self.actions:
# Special-case subscriber actions.
if is_subscriber(**unaction):
factory, for_ = real_subscriber_factory(**unaction)
action = subscribers.get((factory, for_))
if action is None:
continue
self.remove_action(action)
del subscribers[(factory, for_)]
# Generic from here
discriminator = unaction['discriminator']
if discriminator is None:
continue
action = unique.get(discriminator)
if action is None:
# Trying to unconfigure something that hasn't been
# configured in the first place. Ignore.
continue
self.remove_action(action)
del unique[discriminator]
def remove_action(self, action):
# We can't actually remove actions because we mustn't change
# the length of the actions list. The main reason is that
# includeOverrides relies on the length of the action list
# (and we could easily be included via includeOverrides and
# therefore run into this problem). So let's simply replace
# actions with a null value. Actions whose callable is None
# won't be executed.
i = self.context.actions.index(action)
self.context.actions[i] = dict(discriminator=None, callable=None,
args=(), kw={}, order=0) | z3c.unconfigure | /z3c.unconfigure-2.0.tar.gz/z3c.unconfigure-2.0/src/z3c/unconfigure/config.py | config.py |
Introduction
------------
This package allows you to disable specific bits of ZCML configuration
that may occur in other packages. For instance, let's consider a
simple ZCML directive that prints strings and a silly one that prints
lolcat messages:
>>> zcml("""
... <print msg="Hello World!" />
... <lolcat who="I" canhas="cheezburger" />
... """)
Hello World!
I can has cheezburger?
Now let's say this directive were used a bunch of times, but we wanted
to prevent one or two of its occurrences. To do that we simply repeat
the directive inside the ``unconfigure`` grouping directive. This
grouping directive will look at all the previous directives and filter
out the ones we want to exclude:
>>> zcml("""
... <configure>
... <print msg="Hello World!" />
... <lolcat who="I" canhas="cheezburger" />
... <print msg="Goodbye World!" />
... <print msg="LOL!" />
...
... <include package="z3c.unconfigure" file="meta.zcml" />
... <unconfigure>
... <lolcat who="I" canhas="cheezburger" />
... <print msg="LOL!" />
... </unconfigure>
... </configure>
... """)
Hello World!
Goodbye World!
If you're trying to unconfigure something that hasn't been configured
in the first place, nothing will happen:
>>> zcml("""
... <configure>
... <include package="z3c.unconfigure" file="meta.zcml" />
... <unconfigure>
... <lolcat who="I" canhas="cheezburger" />
... </unconfigure>
... </configure>
... """)
Where to place "unconfiguration"
--------------------------------
What's a good place to add the ``unconfigure`` directives, you may
ask. Certainly, the example from above is not very realistic because
both the original directives and the filters are in one file. What
typically happens is that you have some third party package that has
much configuration of which you'd like to disable just one or two
directives. Like this file, for instance:
>>> cat('lolcat.zcml')
<configure>
<print msg="Hello World!" />
<print msg="Important configuration here." />
<lolcat who="I" canhas="cheezburger" />
<print msg="Goodbye World!" />
<print msg="LOL!" />
<print msg="This is the last directive" />
</configure>
What you can do now is write a separate ZCML file in *your* package.
A good name for it would be ``overrides.zcml`` (which is the naming
convention for ZCML files containing overriding directives, a
technique not unlike to what ``unconfigure`` does). For example,
let's say we wanted to undo some silly configuration in the above
third party file:
>>> cat('overrides.zcml')
<configure>
<include package="z3c.unconfigure" file="meta.zcml" />
<unconfigure>
<lolcat who="I" canhas="cheezburger" />
<print msg="LOL!" />
</unconfigure>
</configure>
What you would do now is include first that third party package's
configuration and then load your overrides (which is typically done
using ``includeOverrides``, either explicitly by you or for you by
``site.zcml``):
>>> zcml("""
... <configure>
... <include file="lolcat.zcml" />
... <includeOverrides file="overrides.zcml" />
... </configure>
... """)
Hello World!
Important configuration here.
Goodbye World!
This is the last directive
In this case, simply including the file with the ``<include />``
directive would've sufficed as well. What matters is that the
"unconfiguration" happens *after* the original configuration, and
override files are a good place to ensure this.
It can also be conveniend to unconfigure an entire zcml file. This can
be done without using z3c.unconfigure, if you use the ``<exclude />``
directive before you include that file:
>>> zcml("""
... <configure>
... <exclude file="lolcat.zcml" />
... <print msg="The new hello" />
... <include file="lolcat.zcml" />
... <include package="z3c.unconfigure" file="meta.zcml" />
... <print msg="The final goodbye" />
... </configure>
... """)
The new hello
The final goodbye
Or you can try to use an include statement inside an unconfigure block:
>>> zcml("""
... <configure>
... <print msg="The new hello" />
... <include file="lolcat.zcml" />
... <include package="z3c.unconfigure" file="meta.zcml" />
... <unconfigure>
... <include file="lolcat.zcml" />
... </unconfigure>
... <print msg="The final goodbye" />
... </configure>
... """)
The new hello
The final goodbye
| z3c.unconfigure | /z3c.unconfigure-2.0.tar.gz/z3c.unconfigure-2.0/src/z3c/unconfigure/README.txt | README.txt |
Readme
------
Takes an arbitrary object and syncs it through SVN.
This means a serialization to text, and a deserialization from text.
The text is stored in a SVN checkout. Newly appeared texts are svn added,
removed texts are svn removed. svn move and svn copy are not supported. They
will instead cause a svn delete/svn add combination.
An svn up can be performed. Any conflicting files will be noted and
can be resolved (automatically?).
An svn up always takes place before an svn commit.
An svn sync from the server will main all files that have changed will
be updated in the ZODB, and all files that have been deleted will be
removed in the ZODB. Added files will be added in the ZODB.
Note
----
Currently it is not recommended to use this package in a non-Grok Zope
3 application. This is because Grok turns off certain security checks,
and this is not a behavior you likely wish for in your application.
We are working on ways to make this package work better in an
otherwise non-Grok Zope 3 application, but we're not there yet.
| z3c.vcsync | /z3c.vcsync-0.17.tar.gz/z3c.vcsync-0.17/README.txt | README.txt |
from zope.interface import Interface, Attribute
class ISerializer(Interface):
"""Serialize an object to a file object.
Implement this interface for your objects (or through an adapter) to
let vcsync serialize it.
"""
def serialize(f):
"""Serialize object to file object.
f - an open file object to serialize this object to
"""
class IParser(Interface):
"""Load object from the filesystem into existing object.
Implement this interface as a (global) utility, registered with
the extension (ie .foo) it can load. The empty string extension is
reserved for containers.
vcsync will use this utility to overwrite objects that have been
changed on the filesystem.
"""
def __call__(object, path):
"""Update object with information in path.
object - the object to update with the filesystem information
path - the path to update from
"""
class IFactory(Interface):
"""Load object from the filesystem into a new object.
Implement this interface as a (global) utility, registered with
the extension (ie .foo) it can load. The empty string extension is
reserved for containers.
vcsync will use this utility to create new objects based on
objects in the filesystem.
Typically this can be implemented in terms of IParser.
"""
def __call__(path):
"""Create new instance of object.
path - a py.path reference to the object to load from the filesystem
Returns the newly created object.
"""
class IState(Interface):
"""Information about Python object state.
This is object represents the state and contains information about
what objects in the state have been changed/added, or
removed. This information is used to determine what to synchronize
to the filesystem. It also keeps track of the last revision
number used to synchronize.
Implement this for the state structure (such as a container tree)
you want to export.
"""
root = Attribute('The root container')
def get_revision_nr():
"""The last revision number that this state was synchronized with.
"""
def set_revision_nr(nr):
"""Store the last revision number that this state was synchronized
with.
"""
def objects(revision_nr):
"""Objects modified/added in state since revision_nr.
Ideally, only those objects that have been modified or added
since the synchronisation marked by revision_nr should be
returned. Returning more objects (as long as they exist) is
safe, however, though less efficient.
"""
def removed(revision_nr):
"""Paths removed since revision_nr.
The path is a path from the state root object to the actual
object that was removed. It is therefore not the same as the
physically locatable path. These paths always use the forward
slash as the seperator, and thus are not subject to os.path.sep
like filesystem paths are.
Ideally, only those paths that have been removed since the
synchronisation marked by revision_nr should be returned. It
is safe to return paths that were added again later, so it is
safe to return paths of objects returned by the 'objects'
method.
"""
class ICheckout(Interface):
"""A version control system checkout.
Implement this for our version control system. A version for
SVN has been implemented in z3c.vcsync.svn
"""
path = Attribute('Path to checkout root')
def up():
"""Update the checkout with the state of the version control system.
"""
def revision_nr():
"""Current revision number of the checkout.
"""
def resolve():
"""Resolve all conflicts that may be in the checkout.
"""
def commit(message):
"""Commit checkout to version control system.
"""
def files(revision_nr):
"""Files added/modified in state since revision_nr.
Returns paths to files that were added/modified since revision_nr.
"""
def removed(revision_nr):
"""Files removed in state since revision_nr.
Returns filesystem (py) paths to files that were removed.
"""
class ISynchronizer(Interface):
"""Synchronizer between state and version control.
This object needs to have a 'checkout' attribute (that implements
ICheckout) and a 'state' attribute (that implements IState).
The 'sync' method drives the synchronization.
"""
checkout = Attribute('Version control system checkout')
state = Attribute('Persistent state')
def sync(revision_nr, message='', modified_function=None):
"""Synchronize persistent Python state with version control system.
revision_nr - Revision number since when we want to synchronize.
Revision number are assumed to increment over time as new
revisions are made (through synchronisation). It is
possible to identify changes to both the checkout as well
as the ZODB by this revision number. Normally a version
control system such as SVN controls these.
message - message to commit any version control changes.
modified_function - a function that takes a single parameter.
It is called for each object that is modified or created
in the state during the synchronization process. (optional)
Returns a ISynchronizationInfo object with a report of the
synchronization, including the new revision number after
synchronization.
"""
def save(revision_nr):
"""Save state to filesystem location of checkout.
revision_nr - revision_nr since when there have been state changes.
"""
def load(revision_nr):
"""Load the filesystem information into persistent state.
revision_nr - revision_nr after which to look for filesystem changes.
Returns all the objects in the state that were modified/created due
to the synchronization process.
"""
class ISynchronizationInfo(Interface):
"""Information on what happened during a synchronization.
"""
revision_nr = Attribute("""
The revision number of the version control system that
we have synchronized with.
""")
def objects_removed():
"""Paths of objects removed in synchronization.
The paths are state internal paths.
"""
def objects_changed():
"""Paths of objects added or changed in synchronization.
The paths are state internal paths.
"""
def files_removed():
"""Paths of files removed in synchronization.
The paths are filesystem paths (py.path objects)
"""
def files_changed():
"""The paths of files added or changed in synchronization.
The paths are filesystem paths (py.path objects)
"""
class IDump(Interface):
"""Dump an object to the filesystem.
Usually there should be no need to implement this interface in your
application.
"""
def save(checkout, path):
"""Save context object to path in checkout.
checkout - an ICheckout object
path - a py.path object referring to directory to save in.
This might result in the creation of a new file or directory under
the path, or alternatively to the modification of an existing file
or directory.
Returns the path just created.
"""
def save_bytes(checkout):
"""Save context object to bytes.
Returns the name of the file to be created as well as the bytes to
write.
""" | z3c.vcsync | /z3c.vcsync-0.17.tar.gz/z3c.vcsync-0.17/src/z3c/vcsync/interfaces.py | interfaces.py |
Version Control Synchronization
===============================
This package contains code that helps with handling synchronization of
persistent content with a version control system.
This can be useful in software that needs to be able to work
offline. The web application runs on a user's laptop that may be away
from an internet connection. When connected again, the user syncs with
a version control server, receiving updates that may have been made by
others, and committing their own changes.
Another advantage is that the version control system always contains a
history of how content developed over time. The version-control based
content can also be used for other purposes independent of the
application.
While this package has been written with other version control systems
in mind, it has only been developed to work with SVN so far. Examples
below are all given with SVN.
The synchronization sequence is as follows:
1) save persistent state (IState) to svn checkout (ICheckout) on the
same machine as the Zope application.
2) ``svn up``. Subversion merges in changed made by others users that
were checked into the svn server.
3) Any svn conflicts are automatically resolved.
4) reload changes in svn checkout into persistent Python objects
5) ``svn commit``.
This is all happening in a single step. It can happen over and over
again in a reasonably safe manner, as after the synchronization has
concluded, the state of the persistent objects and that of the local
SVN checkout will always be in sync.
During synchronisation, the system tries to take care only to
synchronize those objects and files that have changed. That is, in
step 1) only applies those objects that have been modified, added or
removed will have an effect on the checkout. In step 4) only those
files that have been changed, added or removed on the filesystem due
to the ``up`` action will change the persistent object state.
State
-----
Content to synchronize is represented by an object that provides
``IState``. A state represents a container object, which should
contain a ``data`` object (a container that contains the actual data
to be synchronized) and a ``found`` object (a container that contains
objects that would otherwise be lost during conflict resolution).
The following methods need to be implemented:
* ``get_revision_nr()``: return the last revision number that the
application was synchronized with. The state typically stores this
the application object.
* ``set_revision_nr(nr)``: store the last revision number that the
application was synchronized with.
* ``objects(revision_nr)``: any object that has been modified (or
added) since the synchronization for ``revision_nr``. Returning 'too
many' objects (objects that weren't modified) is safe, though less
efficient as they will then be re-exported.
Typically in your application this would be implemented by doing
a catalog search, so that they can be looked up quickly.
* ``removed(revision_nr)``: any path that has had an object removed
from it since revision_nr. It is safe to return paths that have
been removed and have since been replaced by a different object with
the same name. It is also safe to return 'too many' paths, though
less efficient as the objects in these paths may be re-exported
unnecessarily.
Typically in your application you would maintain a list of removed
objects by hooking into ``IObjectMovedEvent`` and
``IObjectRemovedEvent`` and recording the paths of all objects that
were moved or removed. After an export it is safe to purge this
list.
In this example, we will use a simpler, less efficient, implementation
that goes through a content to find changes. It tracks the
revision number as a special attribute of the root object::
>>> from z3c.vcsync.tests import TestState
The content
-----------
Now that we have something that can synchronize a tree of content in
containers, let's actually build ourselves a tree of content.
An item contains some payload data, and maintains the SVN revision
after which it was changed. In a real application you would typically
maintain the revision number of objects by using an annotation and
listening to ``IObjectModifiedEvent``, but we will use a property
here::
>>> from z3c.vcsync.tests import Item
This code needs a ``get_revision_nr`` method available to get access
to the revision number of last synchronization. For now we'll just define
this to return 0, but we will change this later::
>>> def get_revision_nr(self):
... return 0
>>> Item.get_revision_nr = get_revision_nr
Besides the ``Item`` class, we also have a ``Container`` class::
>>> from z3c.vcsync.tests import Container
It is a class that implements enough of the dictionary API and
implements the ``IContainer`` interface. A normal Zope 3 folder or
Grok container will also work.
Let's create a container now::
>>> root = Container()
>>> root.__name__ = 'root'
The container has two subcontainers (``data`` and ``found``).
>>> root['data'] = data = Container()
>>> root['found'] = Container()
>>> data['foo'] = Item(payload=1)
>>> data['bar'] = Item(payload=2)
>>> data['sub'] = Container()
>>> data['sub']['qux'] = Item(payload=3)
As part of the synchronization procedure we need the ability to export
persistent python objects to the version control checkout directory in
the form of files and directories.
Now that we have an implementation of ``IState`` that works for our
state, let's create our ``state`` object::
>>> state = TestState(root)
Reading from and writing to the filesystem
------------------------------------------
To integrate with the synchronization machinery, we need a way to dump
a Python object to the filesystem (to an SVN working copy), and to
parse it back to an object again.
Let's grok this package first, as it provides some of the required
infrastructure::
>>> import grokcore.component as grok
>>> grok.testing.grok('z3c.vcsync')
We need to provide a serializer for the Item class that takes an item
and writes it to the filesystem to a file with a particular extension
(``.test``)::
>>> from z3c.vcsync.tests import ItemSerializer
We also need to provide a parser to load an object from the filesystem
back into Python, overwriting the previously existing object::
>>> from z3c.vcsync.tests import ItemParser
Sometimes there is no previously existing object in the Python tree,
and we need to add it. To do this we implement a factory (where we use
the parser for the real work)::
>>> from z3c.vcsync.tests import ItemFactory
Both parser and factory are registered per extension, in this case
``.test``. This is the name of the utility.
We register these components::
>>> grok.testing.grok_component('ItemSerializer', ItemSerializer)
True
>>> grok.testing.grok_component('ItemParser', ItemParser)
True
>>> grok.testing.grok_component('ItemFactory', ItemFactory)
True
We also need a parser and factory for containers, registered for the
empty extension (thus no special utility name). These can be very
simple::
>>> from z3c.vcsync.tests import ContainerParser, ContainerFactory
>>> grok.testing.grok_component('ContainerParser', ContainerParser)
True
>>> grok.testing.grok_component('ContainerFactory', ContainerFactory)
True
Setting up the SVN repository
-----------------------------
Now we need an SVN repository to synchronize with. We create a test
SVN repository now and create a svn path to a checkout::
>>> from z3c.vcsync.tests import svn_repo_wc
>>> repo, wc = svn_repo_wc()
We can now initialize the ``SvnCheckout`` object with the SVN path to
the checkout we just created::
>>> from z3c.vcsync.svn import SvnCheckout
>>> checkout = SvnCheckout(wc)
The root directory of the working copy will be synchronized with the
root container of the state. The checkout will therefore contain
``data`` and a ``found`` sub-directories.
Constructing the synchronizer
-----------------------------
Now that we have the checkout and the state, we can set up a synchronizer::
>>> from z3c.vcsync import Synchronizer
>>> s = Synchronizer(checkout, state)
Let's make ``s`` the current synchronizer as well. We need this in
this example to get back to the last revision number::
>>> current_synchronizer = s
It's now time to set up our ``get_revision_nr`` method a bit better,
making use of the information in the current synchronizer. In actual
applications we'd probably get the revision number directly from the
content, and there would be no need to get back to the synchronizer
(it doesn't need to be persistent but can be constructed on demand)::
>>> def get_revision_nr(self):
... return current_synchronizer.state.get_revision_nr()
>>> Item.get_revision_nr = get_revision_nr
Synchronization
---------------
We'll synchronize for the first time now::
>>> info = s.sync("synchronize")
We will now examine the SVN checkout to see whether the
synchronization was successful.
To do this we'll introduce some helper functions that help us present
the paths in a more readable form, relative to the base of the
checkout::
>>> def pretty_path(path):
... return path.relto(wc)
>>> def pretty_paths(paths):
... return sorted([pretty_path(path) for path in paths])
We see that the Python object structure of containers and items has
been translated to the same structure of directories and ``.test``
files on the filesystem::
>>> pretty_paths(wc.listdir())
['data']
>>> pretty_paths(wc.join('data').listdir())
['data/bar.test', 'data/foo.test', 'data/sub']
>>> pretty_paths(wc.join('data').join('sub').listdir())
['data/sub/qux.test']
The ``.test`` files have the payload data we expect::
>>> print wc.join('data').join('foo.test').read()
1
>>> print wc.join('data').join('bar.test').read()
2
>>> print wc.join('data').join('sub').join('qux.test').read()
3
Synchronization back into objects
---------------------------------
Let's now try the reverse: we will change the SVN content from another
checkout, and synchronize the changes back into the object tree.
We have a second, empty tree that we will load objects into::
>>> root2 = Container()
>>> root2.__name__ = 'root'
>>> state2 = TestState(root2)
We make another checkout of the repository::
>>> import py
>>> wc2 = py.test.ensuretemp('wc2')
>>> wc2 = py.path.svnwc(wc2)
>>> wc2.checkout(repo)
>>> checkout2 = SvnCheckout(wc2)
Let's make a synchronizer for this new checkout and state::
>>> s2 = Synchronizer(checkout2, state2)
This is now the current synchronizer (so that our ``get_revision_nr``
works properly)::
>>> current_synchronizer = s2
Now we'll synchronize::
>>> info = s2.sync("synchronize")
The state of objects in the tree must now mirror that of the original state::
>>> sorted(root2.keys())
['data']
>>> sorted(root2['data'].keys())
['bar', 'foo', 'sub']
Now we will change some of these objects, and synchronize again::
>>> root2['data']['bar'].payload = 20
>>> root2['data']['sub']['qux'].payload = 30
>>> info2 = s2.sync("synchronize")
We can now synchronize the original tree again::
>>> current_synchronizer = s
>>> info = s.sync("synchronize")
We should see the changes reflected into the original tree::
>>> root2['data']['bar'].payload
20
>>> root2['data']['sub']['qux'].payload
30
More information
----------------
To learn more about the APIs you can use and need to implement, see
``interfaces.py``.
To learn about using ``z3c.vcsync`` to import and export content, see
``importexport.txt``.
More low-level information may be gleaned from ``conflicts.txt`` and
``internal.txt``.
| z3c.vcsync | /z3c.vcsync-0.17.tar.gz/z3c.vcsync-0.17/src/z3c/vcsync/README.txt | README.txt |
def apply_monkey_patches():
"""Apply all monkey-patches
"""
svn_r_status_support()
def svn_r_status_support():
"""monkey-patch py 0.9.1 with support for SVN 'R' status flag.
this should be fixed in py 0.9.2, so the monkey patch should go
away when we start using that.
"""
from py.__.path.svn import wccommand
wccommand.WCStatus.attrnames = wccommand.WCStatus.attrnames + ('replaced',)
wccommand.SvnWCCommandPath.status = status
from py.__.path.svn.wccommand import WCStatus
# taken from py.path.svn.wccommand
def status(self, updates=0, rec=0, externals=0):
""" return (collective) Status object for this file. """
# http://svnbook.red-bean.com/book.html#svn-ch-3-sect-4.3.1
# 2201 2192 jum test
# XXX
if externals:
raise ValueError("XXX cannot perform status() "
"on external items yet")
else:
#1.2 supports: externals = '--ignore-externals'
externals = ''
if rec:
rec= ''
else:
rec = '--non-recursive'
# XXX does not work on all subversion versions
#if not externals:
# externals = '--ignore-externals'
if updates:
updates = '-u'
else:
updates = ''
update_rev = None
cmd = 'status -v %s %s %s' % (updates, rec, externals)
out = self._authsvn(cmd)
rootstatus = WCStatus(self)
for line in out.split('\n'):
if not line.strip():
continue
#print "processing %r" % line
flags, rest = line[:8], line[8:]
# first column
c0,c1,c2,c3,c4,c5,x6,c7 = flags
#if '*' in line:
# print "flags", repr(flags), "rest", repr(rest)
if c0 in '?XI':
fn = line.split(None, 1)[1]
if c0 == '?':
wcpath = self.join(fn, abs=1)
rootstatus.unknown.append(wcpath)
elif c0 == 'X':
wcpath = self.__class__(self.localpath.join(fn, abs=1),
auth=self.auth)
rootstatus.external.append(wcpath)
elif c0 == 'I':
wcpath = self.join(fn, abs=1)
rootstatus.ignored.append(wcpath)
continue
#elif c0 in '~!' or c4 == 'S':
# raise NotImplementedError("received flag %r" % c0)
m = self._rex_status.match(rest)
if not m:
if c7 == '*':
fn = rest.strip()
wcpath = self.join(fn, abs=1)
rootstatus.update_available.append(wcpath)
continue
if line.lower().find('against revision:')!=-1:
update_rev = int(rest.split(':')[1].strip())
continue
# keep trying
raise ValueError, "could not parse line %r" % line
else:
rev, modrev, author, fn = m.groups()
wcpath = self.join(fn, abs=1)
#assert wcpath.check()
if c0 == 'M':
assert wcpath.check(file=1), "didn't expect a directory with changed content here"
rootstatus.modified.append(wcpath)
elif c0 == 'A' or c3 == '+' :
rootstatus.added.append(wcpath)
elif c0 == 'D':
rootstatus.deleted.append(wcpath)
elif c0 == 'C':
rootstatus.conflict.append(wcpath)
# XXX following two lines added by monkey-patch
elif c0 == 'R':
rootstatus.replaced.append(wcpath)
elif c0 == '~':
rootstatus.kindmismatch.append(wcpath)
elif c0 == '!':
rootstatus.incomplete.append(wcpath)
elif not c0.strip():
rootstatus.unchanged.append(wcpath)
else:
raise NotImplementedError("received flag %r" % c0)
if c1 == 'M':
rootstatus.prop_modified.append(wcpath)
# XXX do we cover all client versions here?
if c2 == 'L' or c5 == 'K':
rootstatus.locked.append(wcpath)
if c7 == '*':
rootstatus.update_available.append(wcpath)
if wcpath == self:
rootstatus.rev = rev
rootstatus.modrev = modrev
rootstatus.author = author
if update_rev:
rootstatus.update_rev = update_rev
continue
return rootstatus | z3c.vcsync | /z3c.vcsync-0.17.tar.gz/z3c.vcsync-0.17/src/z3c/vcsync/monkey.py | monkey.py |
import grokcore.component as grok
import py
from datetime import datetime
from z3c.vcsync.interfaces import ICheckout
SVN_ERRORS = [("svn: Failed to add file '",
"': object of the same name already exists\n"),
("svn: Failed to add file '",
"': object of the same name is already scheduled for addition")]
class SvnCheckout(object):
"""A checkout for SVN.
It is assumed to be initialized with py.path.svnwc
"""
grok.implements(ICheckout)
def __init__(self, path):
self.path = path
self._files = set()
self._removed = set()
self._revision_nr = None
self._updated_revision_nr = None
def _repository_url(self):
prefix = 'Repository Root: '
lines = self.path._svn('info').splitlines()
for line in lines:
if line.startswith(prefix):
break
return line[len(prefix):].strip()
def _checkout_path(self):
"""Path to checkout from SVN's perspective.
"""
checkout_url = self.path.info().url
repos_url = self._repository_url()
return checkout_url[len(repos_url):]
def up(self):
# these need to be initialized here and will be used
# here and in resolve
self._found_files = set()
while True:
try:
self.path.update()
except py.process.cmdexec.Error, e:
# if an added file is in the way of doing an update...
err = e.err
for start, end in SVN_ERRORS:
if err.startswith(start) and err.endswith(end):
err_path = err[len(start):-len(end)]
path = self._svn_path(py.path.local(err_path))
self._found(path, path.read())
path.remove()
break
# loop again, try another SVN update
else:
raise
else:
# we're done
break
self._updated_revision_nr = None
def resolve(self):
self._resolve_helper(self.path)
def commit(self, message):
revision_nr = self.path.commit(message)
if revision_nr is None:
revision_nr = int(self.path.status().rev)
self._revision_nr = revision_nr
def files(self, revision_nr):
self._update_files(revision_nr)
return list(self._files)
def removed(self, revision_nr):
self._update_files(revision_nr)
return list(self._removed)
def revision_nr(self):
return self._revision_nr
def _found(self, path, content):
"""Store conflicting/lost content in found directory.
path - the path in the original tree. This is translated to
a found path with the same structure.
content - the file content
"""
save_path = self._found_path(path)
save_path.ensure()
save_path.write(content)
self._add_parts(save_path)
def _found_container(self, path):
"""Store conflicting/lost container in found directory.
path - the path in the original tree. This is translated to
a found path with the same structure.
"""
save_path = self._found_path(path)
py.path.local(path.strpath).copy(save_path)
save_path.add()
self._add_parts(save_path)
for new_path in save_path.visit():
new_path.add()
self._found_files.add(new_path)
def _add_parts(self, path):
"""Given a path, add containing folders if necessary to found files.
"""
self._found_files.add(path)
for part in path.parts()[:-1]:
if self._is_new(part):
self._found_files.add(part)
def _is_new(self, path):
"""Determine whether path is new to SVN.
"""
# if we're above the path in the tree, we're not new
if path <= self.path:
return False
return path in path.status().added
def _update_files(self, revision_nr):
"""Go through svn log and update self._files and self._removed.
"""
new_revision_nr = int(self.path.status().rev)
if self._updated_revision_nr == new_revision_nr:
return
if new_revision_nr > revision_nr:
# we don't want logs to include the entry for revision_nr itself
# so we add + 1 to it
logs = self.path.log(revision_nr + 1, new_revision_nr,
verbose=True)
else:
# the log function always seem to return at least one log
# entry (the latest one). This way we skip that check if not
# needed
logs = []
checkout_path = self._checkout_path()
files, removed = self._info_from_logs(logs, checkout_path)
self._files = files.union(self._found_files)
self._removed = removed
self._updated_revision_nr = new_revision_nr
def _info_from_logs(self, logs, checkout_path):
"""Get files and removed lists from logs.
"""
files = set()
removed = set()
# go from newest to oldest
logs.reverse()
for log in logs:
for p in log.strpaths:
rel_path = p.strpath[len(checkout_path):]
steps = rel_path.split(self.path.sep)
# construct py.path to file
path = self.path.join(*steps)
if p.action == 'D':
removed.add(path)
else:
files.add(path)
return files, removed
def _resolve_path(self, path):
# resolve any direct conflicts
for conflict in path.status().conflict:
mine, other = conflict_info(conflict)
conflict.write(mine.read())
self._found(conflict, other.read())
conflict._svn('resolved')
# move any status unknown directories away
for unknown in path.status().unknown:
if unknown.check(dir=True):
self._found_container(unknown)
unknown.remove()
def _resolve_helper(self, path):
if not path.check(dir=True):
return
# resolve paths in this dir
self._resolve_path(path)
for p in path.listdir():
self._resolve_helper(p)
def _svn_path(self, path):
"""Turn a (possibly local) path into an SVN path.
"""
rel_path = path.relto(self.path)
return self.path.join(*rel_path.split(path.sep))
def _found_path(self, path):
"""Turn a path into a found path.
"""
found = self.path.ensure('found', dir=True)
rel_path = path.relto(self.path)
return found.join(*rel_path.split(path.sep))
def is_descendant(path, path2):
"""Determine whether path2 is a true descendant of path.
a path is not a descendant of itself.
"""
return path2 > path
def conflict_info(conflict):
path = conflict.dirpath()
name = conflict.basename
mine = path.join(name + '.mine')
name_pattern = name + '.r'
revs = []
for rev in path.listdir(name_pattern + '*'):
revs.append((int(rev.basename[len(name_pattern):]), rev))
# find the most recent rev
rev_nr, other = sorted(revs)[-1]
return mine, other | z3c.vcsync | /z3c.vcsync-0.17.tar.gz/z3c.vcsync-0.17/src/z3c/vcsync/svn.py | svn.py |
import py
import tempfile, zipfile
from zope.app.container.interfaces import IContainer
from z3c.vcsync.interfaces import IDump, IFactory
from zope.component import getUtility
def export(root, path):
for obj in root.values():
IDump(obj).save(path)
if IContainer.providedBy(obj):
export(obj, path.join(obj.__name__))
def export_zip(root, name, zippath):
zf = zipfile.ZipFile(zippath.strpath, 'w')
zf.writestr('data/', '')
_export_zip_helper(root, zf, 'data')
zf.close()
def _export_zip_helper(root, zf, save_path):
for obj in root.values():
name, bytes = IDump(obj).save_bytes()
if save_path:
sub_path = save_path + '/' + name
else:
sub_path = name
sub_path = sub_path.encode('cp437')
if IContainer.providedBy(obj):
# create a directory
zf.writestr(sub_path + '/', '')
_export_zip_helper(obj, zf, sub_path)
else:
zf.writestr(sub_path, bytes)
def import_(root, path, modified_function=None):
modified_objects = _import_helper(root, path)
if modified_function is not None:
for obj in modified_objects:
modified_function(obj)
def _import_helper(obj, path):
modified_objects = []
for p in path.listdir():
factory = getUtility(IFactory, name=p.ext)
name = p.purebasename
if name not in obj:
obj[name] = new_obj = factory(p)
modified_objects.append(new_obj)
else:
new_obj = obj[name]
if p.check(dir=True) and IContainer.providedBy(new_obj):
r = _import_helper(new_obj, p)
modified_objects.extend(r)
return modified_objects
def import_zip(root, name, zippath, modified_function=None):
tmp_dir = py.path.local(tempfile.mkdtemp())
try:
zf = zipfile.ZipFile(zippath.strpath, 'r')
for p in zf.namelist():
if p.endswith('/'):
p = p[:-1]
dir = True
else:
dir = False
new_path = tmp_dir.join(*p.split('/'))
if not dir:
new_path.ensure()
new_path.write(zf.read(p))
else:
new_path.ensure(dir=True)
import_(root, tmp_dir.join(name),
modified_function=modified_function)
zf.close()
finally:
tmp_dir.remove() | z3c.vcsync | /z3c.vcsync-0.17.tar.gz/z3c.vcsync-0.17/src/z3c/vcsync/importexport.py | importexport.py |
import os
import py
from StringIO import StringIO
from datetime import datetime
from zope.interface import Interface
from zope.component import queryUtility, getUtility, queryAdapter
from zope.app.container.interfaces import IContainer
from zope.traversing.interfaces import IPhysicallyLocatable
from z3c.vcsync.interfaces import (IDump, ISerializer, IParser,
IState, IFactory, ISynchronizer,
ISynchronizationInfo)
import grokcore.component as grok
class Dump(grok.Adapter):
"""General dump for arbitrary objects.
Can be overridden for specific objects (such as containers).
"""
grok.provides(IDump)
grok.context(Interface)
def save(self, path):
serializer = ISerializer(self.context)
path = path.join(serializer.name())
path.ensure()
f = path.open('w')
serializer.serialize(f)
f.close()
return path
def save_bytes(self):
serializer = ISerializer(self.context)
name = serializer.name()
f = StringIO()
serializer.serialize(f)
bytes = f.getvalue()
f.close()
return name, bytes
class ContainerDump(grok.Adapter):
grok.provides(IDump)
grok.context(IContainer)
def save(self, path):
path = path.join(self.context.__name__)
path.ensure(dir=True)
def save_bytes(self):
return self.context.__name__, ''
def resolve(root, root_path, path):
"""Resolve checkout path to obj in state.
root - the root container in the state
root_path - a py.path reference to the checkout
path - a py.path reference to the file in the checkout
Returns the object in the state, or None.
"""
rel_path = path.relto(root_path)
steps = rel_path.split(os.path.sep)
steps = [step for step in steps if step != '']
obj = root
for step in steps:
name, ex = os.path.splitext(step)
try:
obj = obj[name]
except KeyError:
return None
return obj
def resolve_container(root, root_path, path):
"""Resolve checkout path to container in state.
root - the root container in the state
root_path - a py.path reference to the checkout
path - a py.path reference to the directory in the checkout
Returns the container in the state, or None.
"""
rel_path = path.relto(root_path)
steps = rel_path.split(os.path.sep)
steps = [step for step in steps if step != '']
if not steps:
return None
steps = steps[:-1]
obj = root
for step in steps:
try:
obj = obj[step]
except KeyError:
return None
return obj
def get_object_path(root, obj):
"""Return state-specific path for obj.
Given state root container and obj, return internal path to this obj.
"""
steps = []
while obj is not root:
steps.append(obj.__name__)
obj = obj.__parent__
steps.reverse()
return '/' + '/'.join(steps)
class Synchronizer(object):
grok.implements(ISynchronizer)
def __init__(self, checkout, state):
self.checkout = checkout
self.state = state
self._to_remove = []
def sync(self, message='', modified_function=None):
revision_nr = self.state.get_revision_nr()
# store some information for the synchronization info
objects_changed, object_paths_changed, object_paths_removed =\
self._get_changed_removed(revision_nr)
# save the state to the checkout
self.save(revision_nr)
# update the checkout
self.checkout.up()
# resolve any conflicts
self.checkout.resolve()
# now after doing an up, remove dirs that can be removed
# it is not safe to do this during safe, as an 'svn up' will
# then recreate the directories again. We do want them
# well and gone though, as we don't want them to reappear in
# the ZODB when we do a load.
for to_remove in self._to_remove:
p = py.path.local(to_remove)
if p.check():
p.remove(rec=True)
# store what was removed and modified in checkout now
files_removed = self.checkout.removed(revision_nr)
files_changed = self.checkout.files(revision_nr)
# now load the checkout state back into the ZODB state
modified_objects = self.load(revision_nr)
# do a final pass with the modified_function if necessary
if modified_function is not None:
for obj in modified_objects:
modified_function(obj)
# and commit the checkout state
self.checkout.commit(message)
# we retrieve the revision number to which we just synchronized
revision_nr = self.checkout.revision_nr()
# we store the new revision number in the state
self.state.set_revision_nr(revision_nr)
# and we return some information about what happened
return SynchronizationInfo(revision_nr,
object_paths_removed, object_paths_changed,
files_removed, files_changed)
def _get_changed_removed(self, revision_nr):
"""Construct the true lists of objects that are changed and removed.
Returns tuple with:
* actual objects changed
* object paths changed
* object paths removed
"""
# store these to report in SynchronizationInfo below
object_paths_removed = list(self.state.removed(revision_nr))
root = self.state.root
objects_changed = list(self.state.objects(revision_nr))
object_paths_changed = [get_object_path(root, obj) for obj in
objects_changed]
return objects_changed, object_paths_changed, object_paths_removed
def save(self, revision_nr):
"""Save objects to filesystem.
"""
objects_changed, object_paths_changed, object_paths_removed =\
self._get_changed_removed(revision_nr)
# remove all files that have been removed in the database
path = self.checkout.path
for removed_path in object_paths_removed:
# construct path to directory containing file/dir to remove
# note: this is a state-specific path which always uses /, so we
# shouldn't use os.path.sep here
steps = removed_path.split('/')
container_dir_path = path.join(*steps[:-1])
# construct path to potential directory to remove
name = steps[-1]
potential_dir_path = container_dir_path.join(name)
if potential_dir_path.check():
# the directory exists, so remove it
potential_dir_path.remove()
# this only marks the directory for vc deletion, so let's
# truly get rid of it later
self._to_remove.append(potential_dir_path.strpath)
else:
# there is no directory, so it must be a file to remove
# the container might not exist for whatever reason
if not container_dir_path.check():
continue
# find the file and remove it
file_paths = list(container_dir_path.listdir(
str('%s.*' % name)))
# (could be 0 files in some cases)
for file_path in file_paths:
file_path.remove()
# now save all files that have been modified/added
root = self.state.root
for obj in objects_changed:
if obj is not root:
IDump(obj).save(self._get_container_path(root, obj))
def load(self, revision_nr):
# remove all objects that have been removed in the checkout
root = self.state.root
# sort to ensure that containers are deleted before items in them
removed_paths = self.checkout.removed(revision_nr)
removed_paths.sort()
for removed_path in removed_paths:
obj = resolve(root, self.checkout.path, removed_path)
if obj is root:
continue
if obj is not None:
del obj.__parent__[obj.__name__]
# now modify/add all objects that have been modified/added in the
# checkout
file_paths = self.checkout.files(revision_nr)
# to ensure that containers are created before items we sort them
file_paths.sort()
modified_objects = []
for file_path in file_paths:
# we might get something that doesn't actually exist anymore
# as it was since removed, so skip it
if not file_path.check():
continue
container = resolve_container(root, self.checkout.path, file_path)
if container is None:
continue
name = file_path.purebasename
ext = file_path.ext
# we always use the factory to create an item
factory = getUtility(IFactory, name=ext)
created = factory(file_path)
# we observe the stored item in the container
stored = container.get(name, None)
# if the object stored is not the object just created, we need
# to remove the stored object first
if stored is not None and type(stored) is not type(created):
del container[name]
stored = None
# if we already have the object, overwrite it, otherwise
# create a new one
if stored is not None:
parser = getUtility(IParser, name=ext)
parser(stored, file_path)
else:
container[name] = created
modified_objects.append(container[name])
return modified_objects
def _get_container_path(self, root, obj):
steps = []
assert root is not obj, "No container exists for the root"
obj = obj.__parent__
while obj is not root:
steps.append(obj.__name__)
obj = obj.__parent__
steps.reverse()
return self.checkout.path.join(*steps)
class AllState(object):
"""Report all state as changed.
It reports all objects in the state as modified, and reports nothing
removed. It actually completely ignores revision numbers. This
implementation is not something you'd typically want to use in your
own applications, but is useful for testing purposes.
"""
grok.implements(IState)
def __init__(self, root):
self.root = root
def set_revision_nr(self, revision_nr):
pass
def get_revision_nr(self):
return 0
def objects(self, revision_nr):
for container in self._containers():
for item in container.values():
if not IContainer.providedBy(item):
yield item
yield container
def removed(self, revision_nr):
return []
def _containers(self):
return self._containers_helper(self.root)
def _containers_helper(self, container):
yield container
for obj in container.values():
if not IContainer.providedBy(obj):
continue
for sub_container in self._containers_helper(obj):
yield sub_container
class SynchronizationInfo(object):
grok.implements(ISynchronizationInfo)
def __init__(self, revision_nr,
objects_removed, objects_changed,
files_removed, files_changed):
self.revision_nr = revision_nr
self._objects_removed = objects_removed
self._objects_changed = objects_changed
self._files_removed = files_removed
self._files_changed = files_changed
def objects_removed(self):
"""Paths of objects removed in synchronization.
The paths are state internal paths.
"""
return self._objects_removed
def objects_changed(self):
"""Paths of objects added or changed in synchronization.
The paths are state internal paths.
"""
return self._objects_changed
def files_removed(self):
"""Paths of files removed in synchronization.
The paths are filesystem paths (py.path objects)
"""
return self._files_removed
def files_changed(self):
"""The paths of files added or changed in synchronization.
The paths are filesystem paths (py.path objects)
"""
return self._files_changed | z3c.vcsync | /z3c.vcsync-0.17.tar.gz/z3c.vcsync-0.17/src/z3c/vcsync/vc.py | vc.py |
__docformat__ = 'restructuredtext'
import gzip
import optparse
import os
import sys
import zope.component
import zope.interface
from zope.configuration import xmlconfig
from zope.publisher.browser import TestRequest
from z3c.versionedresource import interfaces, resource
from z3c.versionedresource.resource import DirectoryResource
EXCLUDED_NAMES = ('.svn',)
def removeExcludedNames(list):
for name in EXCLUDED_NAMES:
if name in list:
list.remove(name)
def getResources(layerPaths, url='http://localhost/'):
resources = ()
for layerPath in layerPaths:
# Get the layer interface
moduleName, layerName = layerPath.rsplit('.', 1)
module = __import__(moduleName, {}, {}, ['None'])
layer = getattr(module, layerName)
# Now we create a test request with that layer and our custom base URL.
request = TestRequest(environ={'SERVER_URL': url})
zope.interface.alsoProvides(request, layer)
# Next we look up all the resources
resources += tuple(
zope.component.getAdapters(
(request,), interfaces.IVersionedResource))
return resources
def getResourceUrls(resources):
paths = []
for name, res in resources:
# For file-based resources, just report their URL.
if not isinstance(res, DirectoryResource):
# Avoid duplicate paths
if res() not in paths:
paths.append(unicode(res()))
# For directory resources, we want to walk the tree.
baseURL = res()
path = res.context.path
for root, dirs, files in os.walk(path):
# Ignore unwanted names.
removeExcludedNames(dirs)
removeExcludedNames(files)
# Produce a path for the resource
relativePath = root.replace(path, '')
for file in files:
fullPath = baseURL + relativePath + '/' + file
# Avoid duplicate paths
if fullPath not in paths:
paths.append(fullPath)
return paths
def storeResource(dir, name, resource, zip=False):
outputPath = os.path.join(dir, name)
# For directory resources, we create the directory and walk through the
# children.
if isinstance(resource, DirectoryResource):
if not os.path.exists(outputPath):
os.mkdir(outputPath)
for name in [name for name in os.listdir(resource.context.path)
if name not in EXCLUDED_NAMES]:
subResource = resource.get(name, None)
if subResource is not None:
storeResource(outputPath, name, subResource, zip)
# For file-based resources, get the path, load it and store it at the new
# location.
else:
inFile = open(resource.context.path, 'r')
openFile = open
if zip:
openFile = gzip.open
outFile = openFile(outputPath, 'w')
outFile.write(inFile.read())
inFile.close()
outFile.close()
def produceResources(options):
# Run the configuration
context = xmlconfig.file(options.zcml)
# Get resource list
resources = getResources(options.layers, options.url)
# If we only want to list the paths
if options.listOnly:
paths = getResourceUrls(resources)
print '\n'.join(paths)
return
# Now we can produce the version directory with all resources in it
version = zope.component.getUtility(interfaces.IVersionManager).version
outputdir = os.path.join(options.dir, version)
if not os.path.exists(outputdir):
os.mkdir(outputdir)
for name, resource in resources:
storeResource(outputdir, name, resource, options.zip)
print outputdir
###############################################################################
# Command-line UI
parser = optparse.OptionParser("%prog [options] ROOT-ZCML-FILE")
config = optparse.OptionGroup(
parser, "Configuration", "Configuration of lookup and reporting parameters.")
config.add_option(
'--layer', '-l', action="append", dest='layers',
help="""The layer for which to lookup the resources.""")
config.add_option(
'--zip', '-z', action="store_true", dest='zip', default=False,
help="""When set, resources are stored in GZIP format.""")
config.add_option(
'--output-dir', '-d', action="store", dest='dir',
default=os.path.abspath(os.curdir),
help="""The directory in which the resources will be stored.""")
parser.add_option_group(config)
list = optparse.OptionGroup(
parser, "List", "Options for list only result.")
list.add_option(
'--list-only', action="store_true", dest='listOnly', default=False,
help="When specified causes no directory with the resources "
"to be created.")
list.add_option(
'--url', '-u', action="store", dest='url', default='http://localhost/',
help="""The base URL that is used to produce the resource URLs.""")
parser.add_option_group(list)
def get_options(args=None):
if args is None:
args = sys.argv
original_args = args
options, positional = parser.parse_args(args)
options.original_args = original_args
if not positional or len(positional) < 1:
parser.error("No target user and/or packages specified.")
options.zcml = positional[0]
return options
# Command-line UI
###############################################################################
def main(args=None):
options = get_options(args)
try:
produceResources(options)
except Exception, err:
print err
sys.exit(1)
sys.exit(0) | z3c.versionedresource | /z3c.versionedresource-0.5.0.tar.gz/z3c.versionedresource-0.5.0/src/z3c/versionedresource/list.py | list.py |
__docformat__ = "reStructuredText"
import zope.component
import zope.interface
import zope.site.hooks
import zope.traversing.browser.absoluteurl
from zope.publisher.interfaces import NotFound
from zope.publisher.interfaces.browser import IBrowserRequest
from zope.app.publisher.browser import resource, resources
from zope.app.publisher.browser import directoryresource
from zope.app.publisher.browser import fileresource
from zope.app.publisher.browser import pagetemplateresource
from zope.traversing.browser.interfaces import IAbsoluteURL
from z3c.versionedresource import interfaces
class Resources(resources.Resources):
def publishTraverse(self, request, name):
'''See interface IBrowserPublisher'''
try:
return super(Resources, self).publishTraverse(request, name)
except NotFound:
pass
vm = zope.component.queryUtility(interfaces.IVersionManager)
if vm is None or vm.version != name:
raise NotFound(self, name)
res = resources.Resources(self.context, self.request)
res.__name__ = vm.version
return res
class AbsoluteURL(zope.traversing.browser.absoluteurl.AbsoluteURL):
zope.interface.implementsOnly(IAbsoluteURL)
zope.component.adapts(interfaces.IVersionedResource, IBrowserRequest)
def __init__(self, context, request):
self.context = context
self.request = request
def __str__(self):
name = self.context.__name__
if name.startswith('++resource++'):
name = name[12:]
site = zope.site.hooks.getSite()
base = zope.component.queryMultiAdapter(
(site, self.request), IAbsoluteURL, name="resource")
if base is None:
url = str(zope.component.getMultiAdapter(
(site, self.request), IAbsoluteURL))
else:
url = str(base)
vm = zope.component.queryUtility(interfaces.IVersionManager)
return '%s/@@/%s/%s' % (url, vm.version, name)
class Resource(resource.Resource):
zope.interface.implements(interfaces.IVersionedResource)
class FileResource(fileresource.FileResource):
zope.interface.implements(interfaces.IVersionedResource)
# 10 years expiration date
cacheTimeout = 10 * 365 * 24 * 3600
def __repr__(self):
return '<%s %r>' %(self.__class__.__name__, self.context.path)
class FileResourceFactory(fileresource.FileResourceFactory):
resourceClass = FileResource
class ImageResourceFactory(fileresource.ImageResourceFactory):
resourceClass = FileResource
class DirectoryResource(directoryresource.DirectoryResource):
zope.interface.implements(interfaces.IVersionedResource)
resource_factories = {
'.gif': ImageResourceFactory,
'.png': ImageResourceFactory,
'.jpg': ImageResourceFactory,
'.pt': pagetemplateresource.PageTemplateResourceFactory,
'.zpt': pagetemplateresource.PageTemplateResourceFactory,
}
default_factory = FileResourceFactory
directory_factory = None
def __repr__(self):
return '<%s %r>' %(self.__class__.__name__, self.context.path)
class DirectoryResourceFactory(directoryresource.DirectoryResourceFactory):
factoryClass = DirectoryResource
DirectoryResource.directory_factory = DirectoryResourceFactory | z3c.versionedresource | /z3c.versionedresource-0.5.0.tar.gz/z3c.versionedresource-0.5.0/src/z3c/versionedresource/resource.py | resource.py |
__docformat__ = 'restructuredtext'
import os
from zope.app.publisher.browser.resourcemeta import ResourceFactoryWrapper
from zope.app.publisher.browser.resourcemeta import allowed_names
from zope.app.publisher.browser.pagetemplateresource import \
PageTemplateResourceFactory
from zope.component.zcml import handler
from zope.configuration.exceptions import ConfigurationError
from zope.interface import Interface
from zope.publisher.interfaces.browser import IBrowserRequest
from zope.publisher.interfaces.browser import IDefaultBrowserLayer
from zope.security.checker import CheckerPublic, NamesChecker
from z3c.versionedresource import interfaces
from z3c.versionedresource.resource import DirectoryResourceFactory
from z3c.versionedresource.resource import FileResourceFactory
from z3c.versionedresource.resource import ImageResourceFactory
def resource(_context, name, layer=IDefaultBrowserLayer,
permission='zope.Public', factory=None,
file=None, image=None, template=None):
if permission == 'zope.Public':
permission = CheckerPublic
checker = NamesChecker(allowed_names, permission)
if (factory and (file or image or template)) or \
(file and (factory or image or template)) or \
(image and (factory or file or template)) or \
(template and (factory or file or image)):
raise ConfigurationError(
"Must use exactly one of factory or file or image or template"
" attributes for resource directives"
)
if factory is not None:
factory = ResourceFactoryWrapper(factory, checker, name)
elif file:
factory = FileResourceFactory(file, checker, name)
elif image:
factory = ImageResourceFactory(image, checker, name)
else:
factory = PageTemplateResourceFactory(template, checker, name)
_context.action(
discriminator = ('resource', name, IBrowserRequest, layer),
callable = handler,
args = ('registerAdapter', factory, (layer,),
interfaces.IVersionedResource, name, _context.info),
)
def resourceDirectory(_context, name, directory, layer=IDefaultBrowserLayer,
permission='zope.Public'):
if permission == 'zope.Public':
permission = CheckerPublic
checker = NamesChecker(allowed_names + ('__getitem__', 'get'),
permission)
if not os.path.isdir(directory):
raise ConfigurationError(
"Directory %s does not exist" % directory
)
factory = DirectoryResourceFactory(directory, checker, name)
_context.action(
discriminator = ('resource', name, IBrowserRequest, layer),
callable = handler,
args = ('registerAdapter', factory, (layer,),
interfaces.IVersionedResource, name, _context.info),
) | z3c.versionedresource | /z3c.versionedresource-0.5.0.tar.gz/z3c.versionedresource-0.5.0/src/z3c/versionedresource/zcml.py | zcml.py |
===================
Versioned Resources
===================
When deploying scalable Web applications, it is important to serve all static
resources such as Javascript code, CSS, and images as quickly as possible
using as little resources as possible. On the hand, the resources must be
known within the application, so that they can be properly referenced.
Additionally, we want to set the expiration date as far in the future as
possible. However, sometimes we need or want to update a resource before the
expiration date has arrived. Yahoo has solved this problem by including a
version number into the URL, which then allowed them to set the expiration
date effectively to infinity.
However, maintaining the versions manually is a nightmare, since you would not
only need to change file or directory names all the time as you change them,
but also adjust your code. This package aims to solve this problem by
providing a central component to manage the versions of the resources and make
versioning transparent to the developer.
The Version Manager
-------------------
The Version Manager is a central component that provides the version to the
system. It is up to the version manager to decide whether the version is for
example based on a tag, a revision number, the package version number or a
manually entered version.
>>> from z3c.versionedresource import version
This package provides only a simple version manager, since I have found no
other good version indicator that is available generically.
>>> manager = version.VersionManager('1.0.0')
>>> manager
<VersionManager '1.0.0'>
The only constructor argument is the version itself. Versions must be ASCII
strings. Let's now register the version manager, so that it is available for
later use:
>>> import zope.component
>>> zope.component.provideUtility(manager)
Clearly, there is not much to version managers and they are only interesting
within the larger context of this package.
An advanced implementation of the version manager uses the SVN revision number
to produce the version string. You simply pass in a working path and the
version is computed:
>>> import os
>>> manager = version.SVNVersionManager(os.path.dirname(__file__))
>>> manager
<SVNVersionManager 'r...'>
Versioned Resource Traversal
----------------------------
Zope uses a special, empty-named view to traverse resources from a site like
this::
<site>/@@/<resource-path>
We would like to support URLs like this now::
<site>/@@/<version>/<resource-path>
That means that we need a custom implementation of the resources view that can
handle the version.
>>> from zope.publisher.browser import TestRequest
>>> from z3c.versionedresource import resource
>>> request = TestRequest()
>>> context = object()
>>> resources = resource.Resources(context, request)
The resources object is a browser view:
>>> resources.__parent__ is context
True
>>> resources.__name__
The view is also a browser publisher. But it does not support a default:
>>> resources.browserDefault(request)
(<function empty at ...>, ())
When traversing to a sub-item, the version can be specified:
>>> resources.publishTraverse(request, '1.0.0')
<zope.app.publisher.browser.resources.Resources ...>
The result of the traversal is the original resources object. When asking for
an unknown resource or version, a ``NotFound`` is raised:
>>> resources.publishTraverse(request, 'error')
Traceback (most recent call last):
...
NotFound: Object: <z3c.versionedresource.resource.Resources ...>, name: 'error'
Let's now register a resource, just to show that traversing to it works:
>>> import zope.interface
>>> from zope.app.publisher.browser.resource import Resource
>>> zope.component.provideAdapter(
... Resource, (TestRequest,), zope.interface.Interface, 'resource.css')
We can now ask the resources object to traverse the resource:
>>> css = resources.publishTraverse(request, 'resource.css')
>>> css
<zope.app.publisher.browser.resource.Resource object at ...>
Calling it will return the URL:
>>> css()
'http://127.0.0.1/@@/resource.css'
Mmmh, so a regular resource does not honor the version element. That's because
it's ``__call__()`` method defines how the URL is constructed, which is
ignorant of the version.
So let's use this package's implementation of a resource:
>>> zope.component.provideAdapter(
... resource.Resource,
... (TestRequest,), zope.interface.Interface, 'resource2.css')
>>> css = resources.publishTraverse(request, 'resource2.css')
>>> css
<z3c.versionedresource.resource.Resource object at ...>
>>> css()
'http://127.0.0.1/@@/1.0.0/resource2.css'
Custom Resource Classes
-----------------------
The ``zope.app.publisher.browser`` package defines three major
resources. As pointed out above, they have to be adjusted to produce a
versioned URL and set the cache header to a long time.
File Resource
~~~~~~~~~~~~~
The versioned file resource is identical to the default file resource, except
that it has a versioned URL and a 10 year cache timeout.
>>> import os.path
>>> import z3c.versionedresource.tests
>>> filesdir = os.path.join(
... os.path.dirname(z3c.versionedresource.tests.__file__),
... 'testfiles')
>>> from zope.app.publisher.fileresource import File
>>> file = File(os.path.join(filesdir, 'test.txt'), 'test.txt')
>>> request = TestRequest()
>>> res = resource.FileResource(file, request)
>>> res.__name__ = 'ajax.js'
>>> res
<FileResource '.../z3c/versionedresource/tests/testfiles/test.txt'>
>>> res.cacheTimeout
315360000
>>> res()
'http://127.0.0.1/@@/1.0.0/ajax.js'
Two factories, one for files and one for images is used:
>>> factory = resource.FileResourceFactory(
... os.path.join(filesdir, 'test.txt'), None, 'test.txt')
>>> factory
<z3c.versionedresource.resource.FileResourceFactory object at ...>
>>> factory(request)
<FileResource '.../z3c/versionedresource/tests/testfiles/test.txt'>
>>> factory = resource.ImageResourceFactory(
... os.path.join(filesdir, 'test.gif'), None, 'test.gif')
>>> factory
<z3c.versionedresource.resource.ImageResourceFactory object at ...>
>>> factory(request)
<FileResource '.../z3c/versionedresource/tests/testfiles/test.gif'>
Directory Resource
~~~~~~~~~~~~~~~~~~
Let's now turn to directories. The trick here is that we need to set all the
factories correctly. So let's create the resource first:
>>> from zope.app.publisher.browser.directoryresource import Directory
>>> request = TestRequest()
>>> res = resource.DirectoryResource(
... Directory(os.path.join(filesdir, 'subdir'), None, 'subdir'), request)
>>> res.__name__ = 'subdir'
>>> res
<DirectoryResource '.../z3c/versionedresource/tests/testfiles/subdir'>
>>> res()
'http://127.0.0.1/@@/1.0.0/subdir'
Let's try to traverse to some files in the directory:
>>> res.publishTraverse(request, 'test.gif')
<FileResource '.../z3c/versionedresource/tests/testfiles/subdir/test.gif'>
We also have a factory for it:
>>> factory = resource.DirectoryResourceFactory(
... os.path.join(filesdir, 'subdir'), None, 'subdir')
>>> factory
<z3c.versionedresource.resource.DirectoryResourceFactory object at ...>
>>> factory(request)
<DirectoryResource '.../z3c/versionedresource/tests/testfiles/subdir'>
Custom ZCML Directives
----------------------
To make the new resources easily usable, we also need custom resource
directives:
>>> from zope.configuration import xmlconfig
>>> import z3c.versionedresource
>>> context = xmlconfig.file('meta.zcml', z3c.versionedresource)
Let's register simple versioned resource:
>>> context = xmlconfig.string("""
... <configure
... xmlns:browser="http://namespaces.zope.org/browser">
... <browser:versionedResource
... name="zcml-test.gif"
... image="%s"
... />
... </configure>
... """ %os.path.join(filesdir, 'test.gif') , context=context)
Now we can access the resource:
>>> resources.publishTraverse(request, '1.0.0')\
... .publishTraverse(request, 'zcml-test.gif')()
'http://127.0.0.1/@@/1.0.0/zcml-test.gif'
You can also specify a simple file resource,
>>> context = xmlconfig.string("""
... <configure
... xmlns:browser="http://namespaces.zope.org/browser">
... <browser:versionedResource
... name="zcml-test.txt"
... file="%s"
... />
... </configure>
... """ %os.path.join(filesdir, 'test.txt') , context=context)
>>> resources.publishTraverse(request, '1.0.0')\
... .publishTraverse(request, 'zcml-test.txt').context
<zope.app.publisher.fileresource.File object at ...>
>>> unregister('zcml-test.txt')
as well as a page template.
>>> context = xmlconfig.string("""
... <configure
... xmlns:browser="http://namespaces.zope.org/browser">
... <browser:versionedResource
... name="zcml-test.html"
... template="%s"
... />
... </configure>
... """ %os.path.join(filesdir, 'test.pt') , context=context)
>>> resources.publishTraverse(request, '1.0.0')\
... .publishTraverse(request, 'zcml-test.html').context
<zope.app.publisher.pagetemplateresource.PageTemplate object at ...>
Note that the page template resource cannot be a versioned resource, since it
has dynamic components:
>>> resources.publishTraverse(request, '1.0.0')\
... .publishTraverse(request, 'zcml-test.html')()
u'<h1>Test</h1>\n'
Note: Eeek, `zope.app.publisher.browser` is broken here. We should have
gotten a URL back.
>>> unregister('zcml-test.html')
Finally, a factory can also be passed in:
>>> context = xmlconfig.string("""
... <configure
... xmlns:browser="http://namespaces.zope.org/browser">
... <browser:versionedResource
... name="zcml-dyn.html"
... factory="z3c.versionedresource.tests.test_doc.ResourceFactory"
... />
... </configure>
... """, context=context)
>>> resources.publishTraverse(request, '1.0.0')\
... .publishTraverse(request, 'zcml-dyn.html')
<ResourceFactory>
>>> unregister('zcml-dyn.html')
Let's now create a directory resource:
>>> context = xmlconfig.string("""
... <configure
... xmlns:browser="http://namespaces.zope.org/browser">
... <browser:versionedResourceDirectory
... name="zcml-subdir"
... directory="%s"
... />
... </configure>
... """ %os.path.join(filesdir, 'subdir') , context=context)
And access it:
>>> resources.publishTraverse(request, '1.0.0')\
... .publishTraverse(request, 'zcml-subdir')()
'http://127.0.0.1/@@/1.0.0/zcml-subdir'
The directives also have some error handling built-in. So let's have a
look. In the ``browser:versionedResource`` directive, you can only specify
either a template, file, image or factory:
>>> context = xmlconfig.string("""
... <configure
... xmlns:browser="http://namespaces.zope.org/browser">
... <browser:versionedResource
... name="zcml-test.gif"
... file="test.gif"
... image="test.gif"
... />
... </configure>
... """, context=context)
Traceback (most recent call last):
...
ZopeXMLConfigurationError: File "<string>", line 4.2-8.8
ConfigurationError: Must use exactly one of factory or file or
image or template attributes for resource directives
The resource directive on the other hand, ensures that the specified path is a
directory:
>>> context = xmlconfig.string("""
... <configure
... xmlns:browser="http://namespaces.zope.org/browser">
... <browser:versionedResourceDirectory
... name="zcml-subdir"
... directory="/foo"
... />
... </configure>
... """, context=context)
Traceback (most recent call last):
...
ZopeXMLConfigurationError: File "<string>", line 4.2-7.8
ConfigurationError: Directory /foo does not exist
Listing All Resources
---------------------
Finally, there exists a script that will list all resources registered as
versioned resources with the system.
>>> from z3c.versionedresource import list
>>> list.produceResources(list.get_options(
... ['-u', 'http://zope.org',
... '-l', 'z3c.versionedresource.tests.test_doc.ITestLayer',
... '--list-only',
... os.path.join(os.path.dirname(list.__file__), 'tests', 'simple.zcml')]
... ))
http://zope.org/@@/1.0.0/zcml-subdir/test.gif
http://zope.org/@@/1.0.0/zcml-subdir/subsubdir/subtest.gif
http://zope.org/@@/1.0.0/zcml-test.gif
You can also produce the resources in a directory:
>>> import tempfile
>>> outdir = tempfile.mkdtemp()
>>> list.produceResources(list.get_options(
... ['-u', 'http://zope.org',
... '-l', 'z3c.versionedresource.tests.test_doc.ITestLayer',
... '-d', outdir,
... os.path.join(os.path.dirname(list.__file__), 'tests', 'simple.zcml')]
... ))
/.../1.0.0
>>> ls(outdir)
d 1.0.0 4096
>>> ls(os.path.join(outdir, '1.0.0'))
d zcml-subdir 4096
f zcml-test.gif 909
>>> ls(os.path.join(outdir, '1.0.0', 'zcml-subdir'))
d subsubdir 4096
f test.gif 909
>>> ls(os.path.join(outdir, '1.0.0', 'zcml-subdir', 'subsubdir'))
f subtest.gif 909
The module consists of several small helper functions, so let's look at them
to verify their correct behavior.
`getResources(layerPath, url='http://localhost/')` Function
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This function retrieves all versioned resources from the system for a given
layer. Optionally a URL can be passed in to alter the resource URLs.
>>> resources = list.getResources(
... ['z3c.versionedresource.tests.test_doc.ITestLayer',
... 'z3c.versionedresource.tests.test_doc.ITestLayer2'])
>>> sorted(resources)
[(u'zcml-subdir', <DirectoryResource u'.../testfiles/subdir'>),
(u'zcml-test.gif', <FileResource u'.../testfiles/test.gif'>)]
As you can see, this list only provides the first layer. It is the
responsibility of the consuming code to digg deeper into the directory
resources.
`getResourceUrls(resources)` Function
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Once we have the list of resources, we can produce a full list of all
available paths.
>>> sorted(list.getResourceUrls(resources))
[u'http://localhost/@@/1.0.0/zcml-subdir/subsubdir/subtest.gif',
u'http://localhost/@@/1.0.0/zcml-subdir/test.gif',
u'http://localhost/@@/1.0.0/zcml-test.gif']
`storeResource(dir, name, resource, zip=False)` Function
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The more interesting use case, however, is this function, which stores the
resources in a directory. First we need to create an output directory:
>>> outdir = tempfile.mkdtemp()
We can now store a resource to it:
>>> list.storeResource(outdir, resources[1][0], resources[1][1])
>>> ls(outdir)
f zcml-test.gif 909
Let's now zip it:
>>> list.storeResource(outdir, resources[1][0], resources[1][1], True)
>>> ls(outdir)
f zcml-test.gif 252
When storing a directory resource, all sub-items are stored as well:
>>> list.storeResource(outdir, resources[0][0], resources[0][1], True)
>>> ls(outdir)
d zcml-subdir 4096
f zcml-test.gif 252
>>> ls(os.path.join(outdir, 'zcml-subdir'))
d subsubdir 4096
f test.gif 259
>>> ls(os.path.join(outdir, 'zcml-subdir', 'subsubdir'))
f subtest.gif 272
Some odds and ends
~~~~~~~~~~~~~~~~~~
Let's use the `main()` function too. It is the one used by the script, but
always raises a system exist:
>>> list.main()
Traceback (most recent call last):
...
SystemExit: 2
>>> list.main(['foo'])
Traceback (most recent call last):
...
SystemExit: 1
>>> list.main(
... ['-l', 'z3c.versionedresource.tests.test_doc.ITestLayer',
... '--list-only',
... os.path.join(os.path.dirname(list.__file__), 'tests', 'simple.zcml')]
... )
Traceback (most recent call last):
...
SystemExit: 0
If the positional argument is missing, then we get a parser error:
>>> list.main(
... ['-l', 'z3c.versionedresource.tests.test_doc.ITestLayer',
... '--list-only'])
Traceback (most recent call last):
...
SystemExit: 2
| z3c.versionedresource | /z3c.versionedresource-0.5.0.tar.gz/z3c.versionedresource-0.5.0/src/z3c/versionedresource/README.txt | README.txt |
==================
Viewlet Extensions
==================
This package provides extensions to the basic ``zope.viewlet`` package
functionality.
Weight-Ordered Viewlet Manager
------------------------------
The viewlet manager in ``zope.viewlet`` does not implement a particular way of
sorting the viewlets it represents. This was intentional, since the authors
did not want to suggest a particular method of sorting viewlets. Over time,
however, it turns out that sorting viewlets by a relative weight is very
useful and sufficient for most situations.
>>> from z3c.viewlet import manager
Every viewlet displayed by a weight-ordered viewlet manager is expected to
have a ``weight`` attribute that is an integer; it can also be a string that
can be converted to an integer. If a viewlet does not have this attribute, a
weight of zero is assumed.
The manager uses a helper function to extract the weight. So let's create a
dummy viewlet:
>>> class Viewlet(object):
... pass
>>> viewlet = Viewlet()
Initially, there is no weight attribute, so the weight is zero.
>>> manager.getWeight(('viewlet', viewlet))
0
If the viewlet has a weight, ...
>>> viewlet.weight = 1
... it is returned:
>>> manager.getWeight(('viewlet', viewlet))
1
As mentioned before, the weight can also be a string representation of an
integer:
>>> viewlet.weight = '2'
>>> manager.getWeight(('viewlet', viewlet))
2
Let's now check that the sorting works correctly for the manager:
>>> zero = Viewlet()
>>> one = Viewlet()
>>> one.weight = 1
>>> two = Viewlet()
>>> two.weight = '2'
>>> viewlets = manager.WeightOrderedViewletManager(None, None, None)
>>> viewlets.sort([ ('zero', zero), ('one', one), ('two', two) ])
[('zero', <Viewlet object at ...>),
('one', <Viewlet object at ...>),
('two', <Viewlet object at ...>)]
| z3c.viewlet | /z3c.viewlet-1.1.0.tar.gz/z3c.viewlet-1.1.0/src/z3c/viewlet/README.txt | README.txt |
This package allows us to separate the registration of the view code and the
view templates.
Why is this a good thing?
While developing customizable applications that require us to develop multiple
customer UIs for one particular application, we noticed there is a fine but
clear distinction between skins and layers. Layers contain the logic to
prepare data for presentation output, namely the view classes. Skins, on the
other hand contain the resources to generate the UI, for example templates,
images and CSS files.
The problem of the existing infrastructure is that code, template and layer
are all hardlinked in one zcml configuration directive of the view component
-- page, content provider, viewlet. This package separates this triplet --
code, template, layer -- into two pairs, code/layer and template/skin. No
additional components are introduced, since skins and layers are physically
the same components.
| z3c.viewtemplate | /z3c.viewtemplate-0.4.1.tar.gz/z3c.viewtemplate-0.4.1/README.txt | README.txt |
__docformat__ = "reStructuredText"
import os
from zope import interface
from zope import component
from zope import schema
from zope.component import zcml
from zope.configuration.exceptions import ConfigurationError
import zope.configuration.fields
from zope.publisher.interfaces.browser import IDefaultBrowserLayer
from zope.pagetemplate.interfaces import IPageTemplate
from zope.configuration.fields import GlobalObject
from zope import schema
from zope.app.pagetemplate.viewpagetemplatefile import ViewPageTemplateFile
from z3c.viewtemplate.macro import Macro
from zope.i18nmessageid import MessageFactory
_ = MessageFactory('zope')
class ITemplateDirective(interface.Interface):
"""Parameters for the template directive."""
template = zope.configuration.fields.Path(
title=_("Content-generating template."),
description=_("Refers to a file containing a page template (should "
"end in extension ``.pt`` or ``.html``)."),
required=False,
)
macro = schema.TextLine(
title = _(u'Macro'),
description = _(u"""
The macro to be used.
This allows us to define different macros in on template.
The template designer can now create macros for the whole site
in a single page template, and ViewTemplate can then extract
the macros for single viewlets or views.
If no macro is given the whole template is used for rendering.
"""),
required = False,
default = u'',
)
for_ = GlobalObject(
title = _(u'View'),
description = _(u'The view for which the template should be used'),
required = False,
default=interface.Interface,
)
layer = GlobalObject(
title = _(u'Layer'),
description = _(u'The layer for which the template should be used'),
required = False,
default=IDefaultBrowserLayer,
)
contentType = schema.BytesLine(
title = _(u'Content Type'),
description=_(u'The content type identifies the type of data.'),
default='text/html',
required=False,
)
class TemplateFactory(object):
template = None
def __init__(self, filename, macro, contentType):
self.filename = filename
self.macro = macro
self.contentType = contentType
def __call__(self, view, request):
if self.template is None:
self.template= ViewPageTemplateFile(self.filename,
content_type=self.contentType)
if self.macro is None:
return self.template
return Macro(self.template, self.macro, view,
request, self.contentType)
def templateDirective(_context,
template,
macro=None,
for_=interface.Interface,
layer=IDefaultBrowserLayer,
contentType='text/html',
):
# Make sure that the template exists
template = os.path.abspath(str(_context.path(template)))
if not os.path.isfile(template):
raise ConfigurationError("No such file", template)
factory = TemplateFactory(template, macro, contentType)
# register the template
zcml.adapter(_context, (factory,), IPageTemplate, (for_, layer)) | z3c.viewtemplate | /z3c.viewtemplate-0.4.1.tar.gz/z3c.viewtemplate-0.4.1/src/z3c/viewtemplate/zcml.py | zcml.py |
============
ViewTemplate
============
This package allows us to separate the registration of the view code and the
view templates.
Why is this a good thing?
While developing customizable applications that require us to develop multiple
customer UIs for one particular application, we noticed there is a fine but
clear distinction between skins and layers. Layers contain the logic to
prepare data for presentation output, namely the view classes. Skins, on the
other hand contain the resources to generate the UI, for example templates,
images and CSS files.
The problem of the existing infrastructure is that code, template and layer
are all hardlinked in one zcml configuration directive of the view component
-- page, content provider, viewlet. This package separates this triplet --
code, template, layer -- into two pairs, code/layer and template/skin. No
additional components are introduced, since skins and layers are physically
the same components.
Before we can setup a view component using this new method, we have to first
create a template ...
>>> import os, tempfile
>>> temp_dir = tempfile.mkdtemp()
>>> template = os.path.join(temp_dir, 'demoTemplate.pt')
>>> open(template, 'w').write('''<div>demo</div>''')
and the view code:
>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest()
>>> from zope import interface
>>> from z3c.viewtemplate.baseview import BaseView
>>> class IMyView(interface.Interface):
... pass
>>> class MyView(BaseView):
... interface.implements(IMyView)
>>> view = MyView(root, request)
Since the template is not yet registered, rendering the view will fail:
>>> print view()
Traceback (most recent call last):
...
ComponentLookupError: ......
Let's now register the template (commonly done using ZCML):
>>> from zope import component
>>> from zope.publisher.interfaces.browser import IDefaultBrowserLayer
>>> from z3c.viewtemplate.zcml import TemplateFactory
>>> from zope.pagetemplate.interfaces import IPageTemplate
The template factory allows us to create a ViewPageTeplateFile instance.
>>> factory = TemplateFactory(template, None, 'text/html')
We register the factory on a view interface and a layer.
>>> component.provideAdapter(factory,
... (interface.Interface, IDefaultBrowserLayer),
... IPageTemplate)
>>> template = component.getMultiAdapter(
... (view, request), IPageTemplate)
>>> template
<zope...viewpagetemplatefile.ViewPageTemplateFile ...>
Now that we have a registered template for the default layer we can
call our view again. The view is a contentprovider so a
BeforeUpdateEvent is fired before its update method is called.
>>> events = []
>>> component.provideHandler(events.append, (None,))
>>> print view()
<div>demo</div>
>>> events
[<zope.contentprovider.interfaces.BeforeUpdateEvent object at ...>]
Now we register a new template on the specific interface of our view.
>>> myTemplate = os.path.join(temp_dir, 'myViewTemplate.pt')
>>> open(myTemplate, 'w').write('''<div>IMyView</div>''')
>>> factory = TemplateFactory(myTemplate, None, 'text/html')
>>> component.provideAdapter(factory,
... (IMyView, IDefaultBrowserLayer),
... IPageTemplate)
>>> print view()
<div>IMyView</div>
We can also render the view with debug flags set.
>>> request.debug.sourceAnnotations = True
>>> print view()
<!--
==============================================================================
...myViewTemplate.pt
==============================================================================
--><div>IMyView</div>
>>> request.debug.sourceAnnotations = False
It is possible to provide the template directly.
We create a new template.
>>> viewTemplate = os.path.join(temp_dir, 'viewTemplate.pt')
>>> open(viewTemplate, 'w').write('''<div>view</div>''')
>>> from zope.app.pagetemplate.viewpagetemplatefile import ViewPageTemplateFile
>>> class MyViewWithTemplate(BaseView):
... interface.implements(IMyView)
... template = ViewPageTemplateFile(viewTemplate)
>>> templatedView = MyViewWithTemplate(root, request)
If we render this view we get the original template and not the registered
one.
>>> print templatedView()
<div>view</div>
Use of macros.
>>> macroTemplate = os.path.join(temp_dir, 'macroTemplate.pt')
>>> open(macroTemplate, 'w').write('''
... <metal:block define-macro="macro1">
... <div>macro1</div>
... </metal:block>
... <metal:block define-macro="macro2">
... <div tal:content="options/foo">macro2</div>
... </metal:block>
... ''')
>>> factory = TemplateFactory(macroTemplate, 'macro1', 'text/html')
>>> print factory(view, request)()
<div>macro1</div>
Since it is possible to pass options to the viewlet let's prove if this
is possible for macros as well:
>>> factory = TemplateFactory(macroTemplate, 'macro2', 'text/html')
>>> print factory(view, request)(foo='bar')
<div>bar</div>
Why didn't we use named templates from the ``zope.formlib`` package?
While named templates allow us to separate the view code from the template
registration, they are not registrable for a particular layer making it
impossible to implement multiple skins using named templates.
Page Template
-------------
And for the simplest possible use we provide a RegisteredPageTemplate a la
ViewPageTemplateFile or NamedTemplate.
The RegisteredPageTemplate allows us to use the new template registration
system with all existing implementations such as `zope.formlib` and
`zope.viewlet`.
>>> from z3c.viewtemplate.pagetemplate import RegisteredPageTemplate
>>> class IMyUseOfView(interface.Interface):
... pass
>>> class UseOfRegisteredPageTemplate(object):
... interface.implements(IMyUseOfView)
...
... template = RegisteredPageTemplate()
...
... def __init__(self, context, request):
... self.context = context
... self.request = request
By defining the "template" property as a "RegisteredPageTemplate" a lookup for
a registered template is done when it is called. Also notice that it is no
longer necessary to derive the view from BaseView!
>>> simple = UseOfRegisteredPageTemplate(root, request)
>>> print simple.template()
<div>demo</div>
Because the demo template was registered for any ("None") interface we see the
demo template when rendering our new view. We register a new template
especially for the new view. Also not that the "macroTemplate" has been
created earlier in this test.
>>> factory = TemplateFactory(macroTemplate, 'macro2', 'text/html')
>>> component.provideAdapter(factory,
... (IMyUseOfView, IDefaultBrowserLayer),
... IPageTemplate)
>>> print simple.template(foo='bar')
<div>bar</div>
| z3c.viewtemplate | /z3c.viewtemplate-0.4.1.tar.gz/z3c.viewtemplate-0.4.1/src/z3c/viewtemplate/README.txt | README.txt |
z3c.webdriver
=============
This package provides tools and wrappers around ``selenium.webdriver``.
We specially care about ``selenium.webdriver.PhantomJS``, because:
- it's easy to deploy, it's a single executable, ``gp.recipe.phantomjs`` works
- it's built on ``webkit``
- it can be debugged with a ``Chromium`` / ``Chrome`` browser, incl. breakpoints
Things to watch out for:
- any single instance of PhantomJS acts as a single browser instance
that means cookies and whatnot are *shared* if you intantiate more
browsers for a single driver.
Workaround could be to start more drivers.
- the headless browser is truly ``async``, that means an AJAX click does NOT
wait for the AJAX request to complete, you explicitely need to wait for it
- any single call to PhantomJS via selenium takes TIME
- zope.testbrowser supporting methods like ``getControl`` are slow now
- there are 2 options for setUp/tearDown, either the driver is started and torn
down with the layer or with each test. Starting and stopping takes around
1.5-2 secs, so you decide whether you need separation or speed.
WARNING
========
This is WORK IN PROGRESS
| z3c.webdriver | /z3c.webdriver-0.0.1.zip/z3c.webdriver-0.0.1/README.txt | README.txt |
import os, shutil, sys, tempfile, urllib, urllib2, subprocess
from optparse import OptionParser
if sys.platform == 'win32':
def quote(c):
if ' ' in c:
return '"%s"' % c # work around spawn lamosity on windows
else:
return c
else:
quote = str
# See zc.buildout.easy_install._has_broken_dash_S for motivation and comments.
stdout, stderr = subprocess.Popen(
[sys.executable, '-Sc',
'try:\n'
' import ConfigParser\n'
'except ImportError:\n'
' print 1\n'
'else:\n'
' print 0\n'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
has_broken_dash_S = bool(int(stdout.strip()))
# In order to be more robust in the face of system Pythons, we want to
# run without site-packages loaded. This is somewhat tricky, in
# particular because Python 2.6's distutils imports site, so starting
# with the -S flag is not sufficient. However, we'll start with that:
if not has_broken_dash_S and 'site' in sys.modules:
# We will restart with python -S.
args = sys.argv[:]
args[0:0] = [sys.executable, '-S']
args = map(quote, args)
os.execv(sys.executable, args)
# Now we are running with -S. We'll get the clean sys.path, import site
# because distutils will do it later, and then reset the path and clean
# out any namespace packages from site-packages that might have been
# loaded by .pth files.
clean_path = sys.path[:]
import site # imported because of its side effects
sys.path[:] = clean_path
for k, v in sys.modules.items():
if k in ('setuptools', 'pkg_resources') or (
hasattr(v, '__path__') and
len(v.__path__) == 1 and
not os.path.exists(os.path.join(v.__path__[0], '__init__.py'))):
# This is a namespace package. Remove it.
sys.modules.pop(k)
is_jython = sys.platform.startswith('java')
setuptools_source = 'http://peak.telecommunity.com/dist/ez_setup.py'
distribute_source = 'http://python-distribute.org/distribute_setup.py'
# parsing arguments
def normalize_to_url(option, opt_str, value, parser):
if value:
if '://' not in value: # It doesn't smell like a URL.
value = 'file://%s' % (
urllib.pathname2url(
os.path.abspath(os.path.expanduser(value))),)
if opt_str == '--download-base' and not value.endswith('/'):
# Download base needs a trailing slash to make the world happy.
value += '/'
else:
value = None
name = opt_str[2:].replace('-', '_')
setattr(parser.values, name, value)
usage = '''\
[DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options]
Bootstraps a buildout-based project.
Simply run this script in a directory containing a buildout.cfg, using the
Python that you want bin/buildout to use.
Note that by using --setup-source and --download-base to point to
local resources, you can keep this script from going over the network.
'''
parser = OptionParser(usage=usage)
parser.add_option("-v", "--version", dest="version",
help="use a specific zc.buildout version")
parser.add_option("-d", "--distribute",
action="store_true", dest="use_distribute", default=False,
help="Use Distribute rather than Setuptools.")
parser.add_option("--setup-source", action="callback", dest="setup_source",
callback=normalize_to_url, nargs=1, type="string",
help=("Specify a URL or file location for the setup file. "
"If you use Setuptools, this will default to " +
setuptools_source + "; if you use Distribute, this "
"will default to " + distribute_source + "."))
parser.add_option("--download-base", action="callback", dest="download_base",
callback=normalize_to_url, nargs=1, type="string",
help=("Specify a URL or directory for downloading "
"zc.buildout and either Setuptools or Distribute. "
"Defaults to PyPI."))
parser.add_option("--eggs",
help=("Specify a directory for storing eggs. Defaults to "
"a temporary directory that is deleted when the "
"bootstrap script completes."))
parser.add_option("-t", "--accept-buildout-test-releases",
dest='accept_buildout_test_releases',
action="store_true", default=False,
help=("Normally, if you do not specify a --version, the "
"bootstrap script and buildout gets the newest "
"*final* versions of zc.buildout and its recipes and "
"extensions for you. If you use this flag, "
"bootstrap and buildout will get the newest releases "
"even if they are alphas or betas."))
parser.add_option("-c", None, action="store", dest="config_file",
help=("Specify the path to the buildout configuration "
"file to be used."))
options, args = parser.parse_args()
if options.eggs:
eggs_dir = os.path.abspath(os.path.expanduser(options.eggs))
else:
eggs_dir = tempfile.mkdtemp()
if options.setup_source is None:
if options.use_distribute:
options.setup_source = distribute_source
else:
options.setup_source = setuptools_source
if options.accept_buildout_test_releases:
args.insert(0, 'buildout:accept-buildout-test-releases=true')
try:
import pkg_resources
import setuptools # A flag. Sometimes pkg_resources is installed alone.
if not hasattr(pkg_resources, '_distribute'):
raise ImportError
except ImportError:
ez_code = urllib2.urlopen(
options.setup_source).read().replace('\r\n', '\n')
ez = {}
exec ez_code in ez
setup_args = dict(to_dir=eggs_dir, download_delay=0)
if options.download_base:
setup_args['download_base'] = options.download_base
if options.use_distribute:
setup_args['no_fake'] = True
if sys.version_info[:2] == (2, 4):
setup_args['version'] = '0.6.32'
ez['use_setuptools'](**setup_args)
if 'pkg_resources' in sys.modules:
reload(sys.modules['pkg_resources'])
import pkg_resources
# This does not (always?) update the default working set. We will
# do it.
for path in sys.path:
if path not in pkg_resources.working_set.entries:
pkg_resources.working_set.add_entry(path)
cmd = [quote(sys.executable),
'-c',
quote('from setuptools.command.easy_install import main; main()'),
'-mqNxd',
quote(eggs_dir)]
if not has_broken_dash_S:
cmd.insert(1, '-S')
find_links = options.download_base
if not find_links:
find_links = os.environ.get('bootstrap-testing-find-links')
if not find_links and options.accept_buildout_test_releases:
find_links = 'http://downloads.buildout.org/'
if find_links:
cmd.extend(['-f', quote(find_links)])
if options.use_distribute:
setup_requirement = 'distribute'
else:
setup_requirement = 'setuptools'
ws = pkg_resources.working_set
setup_requirement_path = ws.find(
pkg_resources.Requirement.parse(setup_requirement)).location
env = dict(
os.environ,
PYTHONPATH=setup_requirement_path)
requirement = 'zc.buildout'
version = options.version
if version is None and not options.accept_buildout_test_releases:
# Figure out the most recent final version of zc.buildout.
import setuptools.package_index
_final_parts = '*final-', '*final'
def _final_version(parsed_version):
for part in parsed_version:
if (part[:1] == '*') and (part not in _final_parts):
return False
return True
index = setuptools.package_index.PackageIndex(
search_path=[setup_requirement_path])
if find_links:
index.add_find_links((find_links,))
req = pkg_resources.Requirement.parse(requirement)
if index.obtain(req) is not None:
best = []
bestv = None
for dist in index[req.project_name]:
distv = dist.parsed_version
if distv >= pkg_resources.parse_version('2dev'):
continue
if _final_version(distv):
if bestv is None or distv > bestv:
best = [dist]
bestv = distv
elif distv == bestv:
best.append(dist)
if best:
best.sort()
version = best[-1].version
if version:
requirement += '=='+version
else:
requirement += '<2dev'
cmd.append(requirement)
if is_jython:
import subprocess
exitcode = subprocess.Popen(cmd, env=env).wait()
else: # Windows prefers this, apparently; otherwise we would prefer subprocess
exitcode = os.spawnle(*([os.P_WAIT, sys.executable] + cmd + [env]))
if exitcode != 0:
sys.stdout.flush()
sys.stderr.flush()
print ("An error occurred when trying to install zc.buildout. "
"Look above this message for any errors that "
"were output by easy_install.")
sys.exit(exitcode)
ws.add_entry(eggs_dir)
ws.require(requirement)
import zc.buildout.buildout
# If there isn't already a command in the args, add bootstrap
if not [a for a in args if '=' not in a]:
args.append('bootstrap')
# if -c was provided, we push it back into args for buildout's main function
if options.config_file is not None:
args[0:0] = ['-c', options.config_file]
zc.buildout.buildout.main(args)
if not options.eggs: # clean up temporary egg directory
shutil.rmtree(eggs_dir) | z3c.webdriver | /z3c.webdriver-0.0.1.zip/z3c.webdriver-0.0.1/bootstrap.py | bootstrap.py |
#
#
# BIG NOTE: make as LESS calls to any WebElement/WebDriver object,
# because every call goes to the java browser
#
#
import re
import time
from urllib2 import URLError
import os.path
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
RE_CHARSET = re.compile('.*;charset=(.*)')
UPLOAD_FILE_TEMPFOLDER = '/tmp'
class AmbiguityError(ValueError):
pass
def _getControlElementFactory(elements, driver, index):
if elements[0].tag_name == 'input':
typ = elements[0].get_attribute('type').lower()
if typ == 'checkbox':
return WrappedSeleniumCheckboxes(elements, driver)
elif typ == 'radio':
return WrappedSeleniumRadios(elements, driver)
if len(elements) > 1 and index is None:
raise AmbiguityError('Ambiguity: Multiple elements found')
else:
elements = elements[index or 0]
return WrappedSeleniumElement(elements, driver)
def _getControl(base, driver, label=None, name=None, index=None):
"""
Mimic zope.testbrowser's getControl
"""
assert ((label is not None) or (name is not None)), 'Either label or name must be specified'
if name is not None:
elements = base.find_elements_by_name(name)
return _getControlElementFactory(elements, driver, index)
if label is not None:
# find all <label...
elements = base.find_elements_by_tag_name('label')
elements = [(e.text, e, 'label') for e in elements]
# also find <input type="submit' value=".. + type="button" value="...
for e in base.find_elements_by_tag_name('input'):
typ = e.get_attribute('type')
if typ in ('submit', 'button'):
elements.append((e.get_attribute('value'), e, typ))
for e in base.find_elements_by_tag_name('button'):
typ = e.get_attribute('type')
if typ in ('submit', 'button'):
elements.append((e.text, e, typ))
found = []
for element in elements:
value = element[0] # the text of the element, e.text above
if value and label in value: # XXX: implement REGEX
found.append(element)
if found:
if len(found) > 1 and index is None:
raise AmbiguityError('Ambiguity: Multiple elements found')
element = found[index or 0]
if element[2] == 'label':
target = element[1].get_attribute('for')
if target:
child = driver.find_element_by_id(target)
else:
types = ('input', 'select', 'textarea', 'button', 'submit')
child = None
for typ in types:
try:
child = element[1].find_element_by_tag_name(typ)
break
except NoSuchElementException:
pass
if child is None:
raise AttributeError('No contained input found')
else:
#button or whatever that itself has the label
child = element[1]
else:
raise AssertionError('control not found (got the right label?)')
return _getControlElementFactory([child], driver, 0)
class WrappedSeleniumCheckboxes(object):
def __init__(self, elements, driver):
self.elements = elements
self.driver = driver
def getControl(*args):
raise RuntimeError('getControl().getControl() not supported, use getControl().value() or implement yourself')
def __getitem__(self, idx):
return WrappedSeleniumElement(self.elements[idx], self.driver)
@apply
def value():
"""See zope.testbrowser.interfaces.IControl"""
def fget(self):
if (len(self.elements) == 1 and not
self.elements[0].get_attribute('value')):
return bool(self.elements[0].get_attribute('checked'))
return [x.get_attribute('value')
for x in self.elements if x.get_attribute('checked')]
def fset(self, value):
if len(self.elements) == 1:
state = self.element.get_attribute('checked')
if bool(value) != bool(state):
self.element.click()
else:
if not isinstance(value, list):
value = [value]
for box in self.elements:
boxvalue = box.get_attribute('value')
checked = box.get_attribute('checked')
if boxvalue in value:
if not checked:
box.click()
else:
if checked:
box.click()
return property(fget, fset)
class WrappedSeleniumRadios(object):
def __init__(self, elements, driver):
self.elements = elements
self.driver = driver
def getControl(*args):
raise RuntimeError('getControl().getControl() not supported, use getControl().value() or implement yourself')
def __getitem__(self, idx):
return WrappedSeleniumElement(self.elements[idx], self.driver)
@apply
def value():
"""See zope.testbrowser.interfaces.IControl"""
def fget(self):
for r in self.elements:
if r.is_selected():
return r.get_attribute('value')
return None
def fset(self, value):
for r in self.elements:
rvalue = r.get_attribute('value')
if rvalue == value:
r.click()
return property(fget, fset)
class WrappedSeleniumElement(object):
"""
Wrap a selenium webdriver element, so we can add some methods
that we expect from porting over the zope.testbrowser based tests.
"""
def __init__(self, element, driver):
self.element = element
self.driver = driver
def __getattr__(self, name):
return getattr(self.element, name)
@apply
def value():
"""See zope.testbrowser.interfaces.IControl"""
def fget(self):
if self.element.tag_name.lower() == 'select':
select = Select(self.element)
rv = []
for opt in select.options:
if opt.is_selected():
rv.append(opt.get_attribute('value'))
if self.element.get_attribute('multiple'):
return rv
else:
return rv[0] if rv else None
return self.element.get_attribute('value')
def fset(self, value):
if self.element.tag_name.lower() == 'file':
pass
# if self.mech_control.type == 'file':
# self.mech_control.add_file(value,
# content_type=self.content_type,
# filename=self.filename)
# select
elif self.element.tag_name.lower() == 'select':
select = Select(self.element)
if self.element.get_attribute('multiple'):
select.deselect_all()
else:
value = [value]
for opt in select.options:
v = opt.get_attribute('value')
if v in value:
value.remove(v)
if not opt.is_selected():
opt.click()
if value:
raise AttributeError('Options not found: %s' % ','.join(value))
else:
# textarea, input type=text
self.element.clear()
self.element.send_keys(value)
return property(fget, fset)
def add_file(self, stringio, contentType, fileName):
try:
# assert that we have the right input type
assert (self.element.tag_name.lower() == 'input' and
self.element.get_attribute('type') == 'file')
except AssertionError:
raise AssertionError('File upload works only on input type=file')
path = os.path.join(UPLOAD_FILE_TEMPFOLDER, fileName)
# write stringio to temp file
with open(path, 'w') as tmpfile:
tmpfile.write(stringio.getvalue())
self.value = path
def getControl(self, label=None, name=None, index=None):
return _getControl(base=self.element, driver=self.driver,
label=label, name=name, index=index)
def passthrough(func):
name = "find_elements_%s" % func.__name__
def inner(self, *args, **kw):
els = getattr(self.driver, name)(*args, **kw)
return els._wrap_returned(els)
inner.__name__ = func.__name__
return inner
class SeleniumBrowser(object):
"""
We add a layer of translation around a Selenium Webdriver
to make transition from mechanize tests easier.
"""
def __init__(self, driver, time_to_wait=0.5):
"""
Implicitly wait for page elements to turn up:
This means that when you do a browser.get('#selector'),
the driver will wait some seconds for this thing to turn up if
it isn't there. This is meant so that any js that might manipulate
it has time to do its job. It makes testing for not-existing
elements slow though.
"""
self.driver = driver
self.driver.implicitly_wait(time_to_wait)
self.driver.set_page_load_timeout(10)
self.driver.set_script_timeout(10)
# lxml support
self.xmlStrict = False
self._etree = None
def open(self, url):
return self.driver.get(url)
def close(self):
return self.driver.quit()
quit = close
@property
def url(self):
return self.driver.current_url
@property
def html(self):
return self.driver.page_source
@property
def contents(self):
return self.driver.page_source.encode('utf-8')
########################################
# zope.testbrowser -ish support
def getLink(self, text):
return self.driver.find_element_by_partial_link_text(text)
def getControl(self, label=None, name=None, index=None):
return _getControl(base=self.driver, driver=self.driver,
label=label, name=name, index=index)
#
########################################
########################################
# shorter names for webdriver methods
# returns:
# - single element if there's ONE element
# - list of elements if there are MORE
# because in tests you'll anyway except a specific number of elements
def _wrap_returned(self, items):
# XXX: wrap the result with a WrappedSeleniumElement,
# mostly input elements
if len(items) == 1:
return items[0]
return items
def by_class_name(self, name):
"""Finds elements by class name.
"""
els = self.driver.find_elements_by_class_name(name)
return self._wrap_returned(els)
def by_css_selector(self, css_selector):
"""Finds elements by css selector.
"""
els = self.driver.find_elements_by_css_selector(css_selector)
return self._wrap_returned(els)
def by_id(self, id):
"""Finds multiple elements by id.
"""
els = self.driver.find_elements_by_id(id)
return self._wrap_returned(els)
def by_link_text(self, text):
"""Finds elements by link text.
"""
els = self.driver.find_elements_by_link_text(text)
return self._wrap_returned(els)
def by_name(self, name):
"""Finds elements by name.
"""
els = self.driver.find_elements_by_name(name)
return self._wrap_returned(els)
def by_partial_link_text(self, link_text):
"""Finds elements by a partial match of their link text.
"""
els = self.driver.find_elements_by_partial_link_text(link_text)
return self._wrap_returned(els)
def by_tag_name(self, name):
"""Finds elements by tag name.
"""
els = self.driver.find_elements_by_tag_name(name)
return self._wrap_returned(els)
def by_xpath(self, xpath):
"""Finds multiple elements by xpath.
"""
els = self.driver.find_elements_by_xpath(xpath)
return self._wrap_returned(els)
#
########################################
########################################
# handy shortcuts -- who wants to type
get = by_css_selector
__getitem__ = by_css_selector
#
########################################
def getForm(self, id=None, name=None, action=None, index=None):
pass
# >>> hrmanager.getForm(name='filterform').submit()
def getCookies(self):
return self.driver.get_cookies()
def addCookie(self, cookie):
return self.driver.add_cookie(cookie)
def delCookie(self, name):
return self.driver.delete_cookie(name)
deleteCookie = delCookie
def delAllCookies(self):
return self.driver.delete_all_cookies()
deleteAllCookies = delAllCookies
def addHeader(self, name, value):
"""
Selenium Webdriver does not support adding headers,
we can fake it for Accept-Language to 'en-us', because
that's the default for Selenium Webdriver.
"""
try:
assert(name == 'Accept-Language')
assert(value in ['en-us', 'en-us,en'])
except AssertionError:
raise AssertionError('No addHeader support, except for Accept-Language/en-us')
# lxml API
@property
def etree(self):
# import lxml only if used... just in case we do not want to have lxml
# as a dependency
import lxml.etree
import lxml.html
if self._etree is not None:
return self._etree
if self.xmlStrict:
self._etree = lxml.etree.fromstring(self.html,
parser=lxml.etree.XMLParser(resolve_entities=False))
else:
encoding = 'utf-8'
# currently we can't get the headers from Selenium Webdriver:
contentType = None # self.headers.get('Content-Type')
if contentType is not None:
match = RE_CHARSET.match(contentType)
if match is not None:
encoding = match.groups()[0]
parser = lxml.etree.HTMLParser(encoding=encoding,
remove_blank_text=True, remove_comments=True, recover=True)
html_as_utf8 = self.html.encode('utf-8')
self._etree = lxml.etree.fromstring(html_as_utf8, parser=parser)
return self._etree
def js(self, command):
rv = self.driver.execute_script(command)
return rv | z3c.webdriver | /z3c.webdriver-0.0.1.zip/z3c.webdriver-0.0.1/src/z3c/webdriver/browser.py | browser.py |
======
README
======
This package provides a setup and teardown concept for WSGI server
applications and a test headless Selenium Webdriver browser. This is
usefull for real application tests using an almost real browser.
We use Selenium Webdriver, which uses the HtmlBrowser headless browser
with the Rhino JavaScript engine. This can be set to use a "real" browser
like Firefox or IE with little more work.
Mechanize and other mechanize based zope testbrowser can not execute
javascript.
>>> from z3c.webdriver.browser import SeleniumBrowser
Testing
-------
This test uses a realistic setup like you will us in your application tests.
Let's setup a WSGIBrowser and start accessing our server:
>>> browser = SeleniumBrowser(driver)
>>> appURL = 'http://localhost:9090/'
>>> browser.open(appURL + 'test.html')
>>> browser.url
u'http://localhost:9090/test.html'
>>> print browser.html
<html>Test Response</html>
Let's setup a second browser before we close the first one:
>>> browser2 = SeleniumBrowser(driver)
>>> browser2.open(appURL + 'hello.html')
>>> browser2.url
u'http://localhost:9090/hello.html'
#Now close them:
#
# >>> browser.close()
#
# >>> browser2.close()
#
#As you can see, our browser is no available anymore. Another call after close
#a browser will end with a RuntimeError:
#
# >>> browser.open(appURL + 'test.html')
# Traceback (most recent call last):
# ...
# URLError: <urlopen error [Errno 111] Connection refused>
#
#Close a browser twice will not raise any error:
#
#Don't close unless the driver was started by this test
#
# >>> browser.close()
| z3c.webdriver | /z3c.webdriver-0.0.1.zip/z3c.webdriver-0.0.1/src/z3c/webdriver/README.txt | README.txt |
import threading
import logging
import time
import wsgiref.simple_server
from urlparse import urlparse
from SocketServer import ThreadingMixIn
from zope.testing import cleanup
LOGGER = logging.getLogger('z3c.webdriver.server')
class WSGIRequestHandler(wsgiref.simple_server.WSGIRequestHandler):
"""WSGI request handler with HTTP/1.1 and automatic keepalive"""
# set to HTTP/1.1 to enable automatic keepalive
protocol_version = "HTTP/1.1"
def address_string(self):
"""Return the client address formatted for logging.
We only use host and port without socket.getfqdn(host) for a
simpler test output.
"""
host, port = self.client_address[:2]
return '%s:%s' % (host, port)
#######################################
# comment those log methods to write the access log to stderr!
def _log(self, level, msg):
"""write log to our logger"""
LOGGER.log(level, msg)
def log_error(self, format, *args):
"""Write error message log to our logger using ERROR level"""
msg = "%s - - [%s] %s\n" % (self.address_string(),
self.log_date_time_string(), format % args)
self._log(logging.ERROR, msg)
def log_message(self, format, *args):
"""Write simple message log to our logger using INFO level"""
msg = "%s - - [%s] %s\n" % (self.address_string(),
self.log_date_time_string(), format % args)
self._log(logging.INFO, msg)
#
#######################################
# Must mix here ThreadingMixIn, otherwise quick concurrent requests
# seem to lock up the server
class MyWSGIServer(ThreadingMixIn, wsgiref.simple_server.WSGIServer):
pass
class ServerThread(threading.Thread):
""" Run WSGI server on a background thread.
Pass in WSGI app object and serve pages from it for Selenium browser.
"""
def __init__(self, app, url):
threading.Thread.__init__(self)
self.app = app
self.url = url
self.srv = None
def run(self):
"""
Open WSGI server to listen to HOST_BASE address
"""
parts = urlparse(self.url)
domain, port = parts.netloc.split(":")
self.srv = wsgiref.simple_server.make_server(
domain, int(port), self.app,
server_class=MyWSGIServer,
handler_class=WSGIRequestHandler)
self.srv.timeout = 0.5
try:
self.srv.serve_forever()
except:
import traceback
traceback.print_exc()
# Failed to start
self.srv = None
def quit(self):
"""
"""
if self.srv:
self.srv.shutdown()
self.srv.server_close()
time.sleep(0.1) # give it a bit of time to stop
self.srv = None
def start_server(app, url='http://localhost:9090'):
server = ServerThread(app, url)
server.daemon = True # don't hang on exceptions
server.start()
time.sleep(0.1) # give it a bit of time to start
return server
WSGI_SERVERS = None
def startWSGIServer(name, app, url='http://localhost:9090'):
"""Serve a WSGI aplication on the given host and port referenced by name"""
global WSGI_SERVERS
if WSGI_SERVERS is None:
WSGI_SERVERS = {}
server = start_server(app, url)
WSGI_SERVERS[name] = {'url': url, 'server': server}
return server
def stopWSGIServer(name):
"""Stop WSGI server by given name reference"""
global WSGI_SERVERS
if WSGI_SERVERS is not None:
server = WSGI_SERVERS[name]['server']
server.quit()
server.join(1)
del WSGI_SERVERS[name]
def getWSGIApplication(name):
"""Returns the application refenced by name"""
global WSGI_SERVERS
if WSGI_SERVERS is not None:
server = WSGI_SERVERS[name]['server']
return server.app
def stopServers():
global WSGI_SERVERS
if WSGI_SERVERS is not None:
names = list(WSGI_SERVERS.keys())
for n in names:
stopWSGIServer(n)
cleanup.addCleanUp(stopServers) | z3c.webdriver | /z3c.webdriver-0.0.1.zip/z3c.webdriver-0.0.1/src/z3c/webdriver/server.py | server.py |
from z3c.i18n import MessageFactory as _
from zope.app.form import browser
from zope.app.form.browser.interfaces import IBrowserWidget
from zope.app.form.browser.interfaces import IWidgetInputErrorView
from zope.app.form.interfaces import IInputWidget
from zope.app.form.interfaces import WidgetInputError
from zope.app.pagetemplate import ViewPageTemplateFile
from zope.formlib import form
import datetime
import zope.component
import zope.interface
import zope.schema
class DropdownWidget(browser.SelectWidget):
"""Variation of the SelectWidget that uses a drop-down list.
This widget renders no div tags arround the select tag. This is needed
for rendering select tags as sub widgets in the DateSelectWidget.
"""
size = 1
def __call__(self):
"""See IBrowserWidget."""
value = self._getFormValue()
contents = []
have_results = False
contents.append(self.renderValue(value))
contents.append(self._emptyMarker())
return "".join(contents)
class WidgetDataSource(object):
"""Provides a cofigurable date range source."""
zope.interface.implements(zope.schema.interfaces.IContextSourceBinder)
def __call__(self, context):
"""Returns a data range vocabulary."""
yearRange = context.yearRange
return zope.schema.vocabulary.SimpleVocabulary.fromValues(yearRange)
class IDateSelectData(zope.interface.Interface):
"""A schema used to generate a date widget."""
year = zope.schema.Choice(
title=_('Year'),
description=_('The year.'),
source=WidgetDataSource(),
required=True)
month = zope.schema.Choice(
title=_('Month'),
description=_('The month.'),
values=range(1, 13),
required=True)
day = zope.schema.Choice(
title=_('Day'),
description=_('The day.'),
values=range(1, 32),
required=True)
yearRange = zope.interface.Attribute(u"Year range.")
class DateSelectDataForDateSelectWidget(object):
"""DateSelectData for DateSelectWidget adapter
This adapter knows how to handle get and set the day, month and year
for a DateSelectWidget and is also able to set a the right values in
the year vocabulary given from the yearRange attribute in the
DateSelectWidget.
Note: this adapter is internal used for setUpEditWidget in formlib and
not registred in the adapter registry.
"""
zope.interface.implements(IDateSelectData)
def __init__(self, context, date):
self.context = context
self.date = date
@apply
def day():
def get(self):
return self.date.day
def set(self, value):
self.date.day = value
return property(get, set)
@apply
def month():
def get(self):
return self.date.month
def set(self, value):
self.date.month = value
return property(get, set)
@apply
def year():
def get(self):
return self.date.year
def set(self, value):
self.date.year = value
return property(get, set)
@property
def yearRange(self):
return self.context.yearRange
class DateSelectWidget(object):
"""Date Widget with multi select options."""
zope.interface.implements(IBrowserWidget, IInputWidget)
template = ViewPageTemplateFile('widget-date.pt')
_prefix = 'field.'
_error = None
widgets = {}
# See zope.app.form.interfaces.IWidget
name = None
label = property(lambda self: self.context.title)
hint = property(lambda self: self.context.description)
visible = True
# See zope.app.form.interfaces.IInputWidget
required = property(lambda self: self.context.required)
# See smart.field.IDateSelect
yearRange = property(lambda self: self.context.yearRange)
def __init__(self, field, request):
self.context = field
self.request = request
if self.context.initialDate:
self.initialDate = self.context.initialDate
else:
self.initialDate = datetime.date.today()
value = field.query(field.context, default=self.initialDate)
if value is None:
# can't be None, set given start date, which is a valid value
value = self.initialDate
self.name = self._prefix + field.__name__
adapters = {}
adapters[IDateSelectData] = DateSelectDataForDateSelectWidget(self,
value)
self.widgets = form.setUpEditWidgets(form.FormFields(IDateSelectData),
self.name, value, request, adapters=adapters)
def setRenderedValue(self, value):
"""See zope.app.form.interfaces.IWidget"""
if isinstance(value, datetime.date):
self.widgets['year'].setRenderedValue(value.year)
self.widgets['month'].setRenderedValue(value.month)
self.widgets['day'].setRenderedValue(value.day)
def setPrefix(self, prefix):
"""See zope.app.form.interfaces.IWidget"""
# Set the prefix locally
if not prefix.endswith("."):
prefix += '.'
self._prefix = prefix
self.name = prefix + self.context.__name__
# Now distribute it to the sub-widgets
for widget in [self.widgets[name]
for name in ['year', 'month', 'day']]:
widget.setPrefix(self.name+'.')
def getInputValue(self):
"""See zope.app.form.interfaces.IInputWidget"""
self._error = None
year = self.widgets['year'].getInputValue()
month = self.widgets['month'].getInputValue()
day = self.widgets['day'].getInputValue()
try:
return datetime.date(year, month, day)
except ValueError, v:
self._error = WidgetInputError(
self.context.__name__, self.label, _(v))
raise self._error
def applyChanges(self, content):
"""See zope.app.form.interfaces.IInputWidget"""
field = self.context
new_value = self.getInputValue()
old_value = field.query(content, self)
# The selection has not changed
if new_value == old_value:
return False
field.set(content, new_value)
return True
def hasInput(self):
"""See zope.app.form.interfaces.IInputWidget"""
return (self.widgets['year'].hasInput() and
(self.widgets['month'].hasInput() and
self.widgets['day'].hasInput()))
def hasValidInput(self):
"""See zope.app.form.interfaces.IInputWidget"""
return (self.widgets['year'].hasValidInput() and
self.widgets['month'].hasValidInput() and
self.widgets['day'].hasValidInput())
def hidden(self):
"""See zope.app.form.browser.interfaces.IBrowserWidget"""
output = []
output.append(self.widgets['year'].hidden())
output.append(self.widgets['month'].hidden())
output.append(self.widgets['day'].hidden())
return '\n'.join(output)
def error(self):
"""See zope.app.form.browser.interfaces.IBrowserWidget"""
if self._error:
return zope.component.getMultiAdapter(
(self._error, self.request),
IWidgetInputErrorView).snippet()
year_error = self.widgets['year'].error()
if year_error:
return year_error
month_error = self.widgets['month'].error()
if month_error:
return month_error
day_error = self.widgets['day'].error()
if day_error:
return day_error
return ""
def __call__(self):
"""See zope.app.form.browser.interfaces.IBrowserWidget"""
return self.template() | z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/dateselect/browser.py | browser.py |
=====================
Date Selection Widget
=====================
The ``DateSelectWidget`` widget provides three select boxes presenting the
day, month and year.
First we have to create a field and a request. Note that we can set the
year range in this widget:
>>> import datetime
>>> from z3c.schema.dateselect import DateSelect
>>> from z3c.widget.dateselect.browser import DateSelectWidget
>>> field = DateSelect(
... title=u'Birthday',
... description=u'Somebodys birthday',
... yearRange=range(1930, 2007),
... required=True)
>>> field.__name__ = 'field'
>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest()
Now we can initialize widget.
>>> widget = DateSelectWidget(field, request)
Let's make sure that all fields have the correct value:
>>> widget.name
'field.field'
>>> widget.label
u'Birthday'
>>> widget.hint
u'Somebodys birthday'
>>> widget.visible
True
>>> widget.required
True
The constructor should have also created 3 widgets:
>>> widget.widgets['year']
<z3c.widget.dateselect.browser.DropdownWidget object at ...>
>>> widget.widgets['month']
<z3c.widget.dateselect.browser.DropdownWidget object at ...>
>>> widget.widgets['day']
<z3c.widget.dateselect.browser.DropdownWidget object at ...>
let's also test the year range:
>>> '1929' in widget.widgets['year'].vocabulary.by_token.keys()
False
>>> '1930' in widget.widgets['year'].vocabulary.by_token.keys()
True
>>> '2006' in widget.widgets['year'].vocabulary.by_token.keys()
True
>>> '2007' in widget.widgets['year'].vocabulary.by_token.keys()
False
Test another year range:
>>> field2 = DateSelect(
... title=u'Another Birthday',
... yearRange=range(2000, 2010))
>>> field2.__name__ = 'field'
>>> widget2 = DateSelectWidget(field2, request)
>>> '1930' in widget2.widgets['year'].vocabulary.by_token.keys()
False
>>> '2000' in widget2.widgets['year'].vocabulary.by_token.keys()
True
>>> '2009' in widget2.widgets['year'].vocabulary.by_token.keys()
True
>>> '2010' in widget2.widgets['year'].vocabulary.by_token.keys()
False
``setRenderedValue(value)`` Method
==================================
The first method is ``setRenderedValue()``. The widget has two use cases,
based on the type of value. If the value is a custom score system, it will
send the information to the custom, min and max widget:
>>> widget = DateSelectWidget(field, request)
>>> year = 2000
>>> month = 12
>>> day = 31
>>> data = datetime.date(year, month, day)
>>> widget.setRenderedValue(data)
>>> 'value="2000"' in widget()
True
>>> 'value="12"' in widget()
True
>>> 'value="31"' in widget()
True
``setPrefix(prefix)`` Method
============================
The prefix determines the name of the widget and all its sub-widgets.
>>> widget.name
'field.field'
>>> widget.widgets['year'].name
'field.field.year'
>>> widget.widgets['month'].name
'field.field.month'
>>> widget.widgets['day'].name
'field.field.day'
>>> widget.setPrefix('test.')
>>> widget.name
'test.field'
>>> widget.widgets['year'].name
'test.field.year'
>>> widget.widgets['month'].name
'test.field.month'
>>> widget.widgets['day'].name
'test.field.day'
If the prefix does not end in a dot, one is added:
>>> widget.setPrefix('test')
>>> widget.name
'test.field'
>>> widget.widgets['year'].name
'test.field.year'
>>> widget.widgets['month'].name
'test.field.month'
>>> widget.widgets['day'].name
'test.field.day'
``getInputValue()`` Method
==========================
This method returns a date object:
>>> request = TestRequest(form={
... 'field.field.year': '2006',
... 'field.field.month': '2',
... 'field.field.day': '24'})
>>> widget = DateSelectWidget(field, request)
>>> value = widget.getInputValue()
>>> value.year
2006
>>> value.month
2
>>> value.day
24
If a set of values does not produce a valid date object, a value error is
raised:
>>> request = TestRequest(form={
... 'field.field.year': '2006',
... 'field.field.month': '2',
... 'field.field.day': '29'})
>>> widget = DateSelectWidget(field, request)
>>> widget.getInputValue()
Traceback (most recent call last):
...
WidgetInputError: ('field', u'Birthday', u'day is out of range for month')
>>> widget._error.__class__
<class 'zope.formlib.interfaces.WidgetInputError'>
``applyChanges(content)`` Method
================================
This method applies the new date to the passed content. However, it
must be smart enough to detect whether the values really changed.
>>> class Content(object):
... field = None
>>> content = Content()
>>> request = TestRequest(form={
... 'field.field.year': '2006',
... 'field.field.month': '2',
... 'field.field.day': '24'})
>>> widget = DateSelectWidget(field, request)
>>> widget.applyChanges(content)
True
>>> content.field
datetime.date(2006, 2, 24)
>>> widget.applyChanges(content)
False
``hasInput()`` Method
=====================
This method checks for any input, but does not validate it.
>>> request = TestRequest()
>>> widget = DateSelectWidget(field, request)
>>> widget.hasInput()
False
>>> request = TestRequest(form={
... 'field.field.year': '2006'})
>>> widget = DateSelectWidget(field, request)
>>> widget.hasInput()
False
>>> request = TestRequest(form={
... 'field.field.month': '2'})
>>> widget = DateSelectWidget(field, request)
>>> widget.hasInput()
False
>>> request = TestRequest(form={
... 'field.field.day': '24'})
>>> widget = DateSelectWidget(field, request)
>>> widget.hasInput()
False
>>> request = TestRequest(form={
... 'field.field.year': '2006',
... 'field.field.month': '2',
... 'field.field.day': '24'})
>>> widget = DateSelectWidget(field, request)
>>> widget.hasInput()
True
``hasValidInput()`` Method
==========================
Additionally to checking for any input, this method also checks whether the
input is valid:
>>> request = TestRequest()
>>> widget = DateSelectWidget(field, request)
>>> widget.hasValidInput()
False
>>> request = TestRequest(form={
... 'field.field.year': '2006'})
>>> widget = DateSelectWidget(field, request)
>>> widget.hasValidInput()
False
>>> request = TestRequest(form={
... 'field.field.month': '2'})
>>> widget = DateSelectWidget(field, request)
>>> widget.hasValidInput()
False
>>> request = TestRequest(form={
... 'field.field.day': '24'})
>>> widget = DateSelectWidget(field, request)
>>> widget.hasValidInput()
False
>>> request = TestRequest(form={
... 'field.field.year': '2006',
... 'field.field.month': '2',
... 'field.field.day': '24'})
>>> widget = DateSelectWidget(field, request)
>>> widget.hasValidInput()
True
``hidden()`` Method
===================
This method is renders the output as hidden fields:
>>> request = TestRequest(form={
... 'field.field.year': '2006',
... 'field.field.month': '2',
... 'field.field.day': '24'})
>>> widget = DateSelectWidget(field, request)
>>> print widget.hidden()
<input class="hiddenType" id="field.field.year" name="field.field.year"
type="hidden" value="2006" />
<input class="hiddenType" id="field.field.month" name="field.field.month"
type="hidden" value="2" />
<input class="hiddenType" id="field.field.day" name="field.field.day"
type="hidden" value="24" />
``error()`` Method
==================
Let's test some bad data and check the error handling.
The day field contains an invalid value:
>>> request = TestRequest(form={
... 'field.field.year': '2006',
... 'field.field.month': '2',
... 'field.field.day': '99'})
>>> widget = DateSelectWidget(field, request)
>>> widget.getInputValue()
Traceback (most recent call last):
...
ConversionError: (u'Invalid value', InvalidValue("token '99' not found in vocabulary"))
>>> print widget.error()
<span class="error">Invalid value</span>
The month field contains an invalid value:
>>> request = TestRequest(form={
... 'field.field.year': '2006',
... 'field.field.month': '0',
... 'field.field.day': '31'})
>>> widget = DateSelectWidget(field, request)
>>> widget.getInputValue()
Traceback (most recent call last):
...
ConversionError: (u'Invalid value', InvalidValue("token '0' not found in vocabulary"))
>>> print widget.error()
<span class="error">Invalid value</span>
The year field contains an invalid value:
>>> request = TestRequest(form={
... 'field.field.year': '1900',
... 'field.field.month': '1',
... 'field.field.day': '31'})
>>> widget = DateSelectWidget(field, request)
>>> widget.getInputValue()
Traceback (most recent call last):
...
ConversionError: (u'Invalid value', InvalidValue("token '1900' not found in vocabulary"))
>>> print widget.error()
<span class="error">Invalid value</span>
The single inputs were correct, but did not create a valid date.
>>> request = TestRequest(form={
... 'field.field.year': '1980',
... 'field.field.month': '2',
... 'field.field.day': '31'})
>>> widget = DateSelectWidget(field, request)
>>> widget.getInputValue()
Traceback (most recent call last):
...
WidgetInputError: ('field', u'Birthday', u'day is out of range for month')
>>> print widget.error()
<span class="error">day is out of range for month</span>
No error occurred:
>>> request = TestRequest(form={
... 'field.field.year': '1980',
... 'field.field.month': '1',
... 'field.field.day': '31'})
>>> widget = DateSelectWidget(field, request)
>>> widget.getInputValue()
datetime.date(1980, 1, 31)
>>> widget.error()
''
``__call__()`` Method
=====================
This method renders the widget using the sub-widgets. Let's see the output:
>>> request = TestRequest(form={
... 'field.field.year': '2006',
... 'field.field.month': '2',
... 'field.field.day': '24'})
>>> widget = DateSelectWidget(field, request)
>>> print widget()
<select id="field.field.day" name="field.field.day" size="1" >
<option value="1">1</option>
...
<option value="23">23</option>
<option selected="selected" value="24">24</option>
<option value="25">25</option>
...
<option value="31">31</option>
</select><input name="field.field.day-empty-marker" type="hidden"
value="1" />
<select id="field.field.month" name="field.field.month" size="1" >
<option value="1">1</option>
<option selected="selected" value="2">2</option>
<option value="3">3</option>
...
<option value="12">12</option>
</select><input name="field.field.month-empty-marker" type="hidden"
value="1" />
<select id="field.field.year" name="field.field.year" size="1" >
<option value="1930">1930</option>
...
<option value="2005">2005</option>
<option selected="selected" value="2006">2006</option>
</select><input
name="field.field.year-empty-marker" type="hidden" value="1" />
<BLANKLINE>
| z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/dateselect/README.txt | README.txt |
import datetime
from zope.app.form.browser.widget import SimpleInputWidget, renderElement
from zope.app.form.interfaces import ConversionError
from zope.app.i18n import ZopeMessageFactory as _
class DropDownDateWidget(SimpleInputWidget):
_missing = None
day = [str(i+1).zfill(2) for i in range(31)]
month = [str(i+1).zfill(2) for i in range(12)]
year = [str(i+1900) for i in range(130)]
elements = [[day,'day'],[month,'month'],[year,'year']]
def __call__(self, *args, **kw):
html = ''
data = self._getFormValue()
if data is None or data == self._data_marker:
data = datetime.date.today()
# day
contents = self.renderItemsWithValues(self.elements[0][0], data.day)
name = self.name+'.'+self.elements[0][1]
html += renderElement('select',
name=name,
id=name,
contents=contents,
cssClass='dayField')
html += '\n'
# month
contents = self.renderItemsWithValues(self.elements[1][0],data.month)
name = self.name+'.'+self.elements[1][1]
html += renderElement('select',
name=name,
id=name,
contents=contents,
cssClass='monthField')
html += '\n'
# year
contents = self.renderItemsWithValues(self.elements[2][0],data.year)
name = self.name+'.'+self.elements[2][1]
html += renderElement('select',
name=name,
id=name,
contents=contents,
cssClass='yearField')
html += '\n'
return renderElement('div',contents=html,cssClass='dropDownDateWidget')
def renderItemsWithValues(self, values, selected=None):
""" Render all values from a dropdown """
html = ''
for value in values:
if selected==int(value):
html += renderElement('option',
value=value,
selected='selected',
contents=value)
else:
html += renderElement('option',
value=value,
contents=value)
return html
def hasInput(self):
prefix = self.name + '.'
requestForm = self.request.form
return prefix + self.elements[0][1] in requestForm and \
prefix + self.elements[1][1] in requestForm and \
prefix + self.elements[2][1] in requestForm
def _getFormInput(self):
prefix = self.name + '.'
year = int(self.request.form.get(prefix+self.elements[2][1],None))
month = int(self.request.form.get(prefix+self.elements[1][1],None))
day = int(self.request.form.get(prefix+self.elements[0][1],None))
if year and month and day:
try:
return datetime.date(year, month, day)
except ValueError, v:
raise ConversionError(_("Invalid datetime data"), v)
else:
return None | z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/dropdowndatewidget/widget.py | widget.py |
DropDownDateWidget
==================
>>> from z3c.widget.dropdowndatewidget.widget import DropDownDateWidget
>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest()
Widgets are use for fields.
>>> from zope.schema import Date
>>> dateField = Date(__name__='foo', title=u'Foo')
>>> widget = DropDownDateWidget(dateField, request)
>>> widget.name
'field.foo'
>>> widget.label
u'Foo'
>>> widget.hasInput()
False
We need to provide some input.
>>> request.form['field.foo.day'] = '1'
>>> widget.hasInput()
False
>>> request.form['field.foo.month'] = '6'
>>> widget.hasInput()
False
>>> request.form['field.foo.year'] = '1963'
>>> widget.hasInput()
True
Read the value.
>>> widget.getInputValue()
datetime.date(1963, 6, 1)
Let's render the widget.
>>> print widget()
<div class="dropDownDateWidget"><select class="dayField" id="field.foo.day" name="field.foo.day">...</select>
<select class="monthField" id="field.foo.month" name="field.foo.month">...</select>
<select class="yearField" id="field.foo.year" name="field.foo.year">...</select>
</div>
And if we set a value.
>>> from datetime import date
>>> widget.setRenderedValue(date(1977, 4, 3))
>>> print widget()
<div class="dropDownDateWidget"><select ...<option selected="selected" value="03">...
<select ...<option selected="selected" value="04">...
<select ...<option selected="selected" value="1977">...
...
| z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/dropdowndatewidget/README.txt | README.txt |
====================
The Widget Namespace
====================
The widget namespace provides a way to traverse to the widgets of a
formlib form.
>>> from z3c.widget.namespace.namespace import WidgetHandler
Let us define a form to test this behaviour.
>>> from zope.formlib import form
>>> from zope import interface, schema
>>> class IMyContent(interface.Interface):
... title = schema.TextLine(title=u'Title')
>>> class MyContent(object):
... interface.implements(IMyContent)
... title=None
>>> content = MyContent()
>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest()
>>> class MyForm(form.EditForm):
... form_fields = form.Fields(IMyContent)
>>> view = MyForm(content,request)
>>> handler = WidgetHandler(view,request)
>>> handler.traverse('title',None)
<zope.formlib.textwidgets.TextWidget object at ...>
| z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/namespace/README.txt | README.txt |
__docformat__ = 'reStructuredText'
from z3c.i18n import MessageFactory as _
from zope.app.form import browser
from zope.app.form.browser.interfaces import IBrowserWidget
from zope.app.form.browser.interfaces import IWidgetInputErrorView
from zope.app.form.interfaces import IInputWidget
from zope.app.form.interfaces import WidgetInputError
from zope.app.pagetemplate import ViewPageTemplateFile
from zope.formlib import form
import datetime
import re
import zope.component
import zope.interface
import zope.schema
class ISSNData(zope.interface.Interface):
"""A schema used to generate a SSN widget."""
first = zope.schema.TextLine(
title=_('Frst three digits'),
description=_('The first three digits of the SSN.'),
min_length=3,
max_length=3,
constraint=re.compile(r'^[0-9]{3}$').search,
required=True)
second = zope.schema.TextLine(
title=_('Second two digits'),
description=_('The second two digits of the SSN.'),
min_length=2,
max_length=2,
constraint=re.compile(r'^[0-9]{2}$').search,
required=True)
third = zope.schema.TextLine(
title=_('Third four digits'),
description=_('The third four digits of the SSN.'),
min_length=4,
max_length=4,
constraint=re.compile(r'^[0-9]{4}$').search,
required=True)
class SSNWidgetData(object):
"""Social Security Number Data"""
zope.interface.implements(ISSNData)
first = None
second = None
third = None
def __init__(self, context, number=None):
self.context = context
if number:
self.first, self.second, self.third = number.split('-')
@property
def number(self):
return u'-'.join((self.first, self.second, self.third))
class SSNWidget(object):
"""Social Security Number Widget"""
zope.interface.implements(IBrowserWidget, IInputWidget)
template = ViewPageTemplateFile('widget-ssn.pt')
_prefix = 'field.'
_error = None
widgets = {}
# See zope.app.form.interfaces.IWidget
name = None
label = property(lambda self: self.context.title)
hint = property(lambda self: self.context.description)
visible = True
# See zope.app.form.interfaces.IInputWidget
required = property(lambda self: self.context.required)
def __init__(self, field, request):
self.context = field
self.request = request
self.name = self._prefix + field.__name__
value = field.query(field.context)
adapters = {}
adapters[ISSNData] = SSNWidgetData(self, value)
self.widgets = form.setUpEditWidgets(
form.FormFields(ISSNData),
self.name, value, request, adapters=adapters)
self.widgets['first'].displayWidth = 3
self.widgets['second'].displayWidth = 2
self.widgets['third'].displayWidth = 4
def setRenderedValue(self, value):
"""See zope.app.form.interfaces.IWidget"""
if isinstance(value, unicode):
first, second, third = value.split('-')
self.widgets['first'].setRenderedValue(first)
self.widgets['second'].setRenderedValue(second)
self.widgets['third'].setRenderedValue(third)
def setPrefix(self, prefix):
"""See zope.app.form.interfaces.IWidget"""
# Set the prefix locally
if not prefix.endswith("."):
prefix += '.'
self._prefix = prefix
self.name = prefix + self.context.__name__
# Now distribute it to the sub-widgets
for widget in [
self.widgets[name] for name in ['first', 'second', 'third']]:
widget.setPrefix(self.name+'.')
def getInputValue(self):
"""See zope.app.form.interfaces.IInputWidget"""
self._error = None
try:
return u'-'.join((
self.widgets['first'].getInputValue(),
self.widgets['second'].getInputValue(),
self.widgets['third'].getInputValue() ))
except ValueError, v:
self._error = WidgetInputError(
self.context.__name__, self.label, _(v))
raise self._error
except WidgetInputError, e:
self._error = e
raise e
def applyChanges(self, content):
"""See zope.app.form.interfaces.IInputWidget"""
field = self.context
new_value = self.getInputValue()
old_value = field.query(content, self)
# The selection has not changed
if new_value == old_value:
return False
field.set(content, new_value)
return True
def hasInput(self):
"""See zope.app.form.interfaces.IInputWidget"""
return (self.widgets['first'].hasInput() and
(self.widgets['second'].hasInput() and
self.widgets['third'].hasInput()))
def hasValidInput(self):
"""See zope.app.form.interfaces.IInputWidget"""
return (self.widgets['first'].hasValidInput() and
self.widgets['second'].hasValidInput() and
self.widgets['third'].hasValidInput())
def hidden(self):
"""See zope.app.form.browser.interfaces.IBrowserWidget"""
output = []
output.append(self.widgets['first'].hidden())
output.append(self.widgets['second'].hidden())
output.append(self.widgets['third'].hidden())
return '\n'.join(output)
def error(self):
"""See zope.app.form.browser.interfaces.IBrowserWidget"""
if self._error:
return zope.component.getMultiAdapter(
(self._error, self.request),
IWidgetInputErrorView).snippet()
first_error = self.widgets['first'].error()
if first_error:
return first_error
second_error = self.widgets['second'].error()
if second_error:
return second_error
third_error = self.widgets['third'].error()
if third_error:
return third_error
return ""
def __call__(self):
"""See zope.app.form.browser.interfaces.IBrowserWidget"""
return self.template() | z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/ssn/browser.py | browser.py |
==========
SSN Widget
==========
The social security number widget can be used as a custom widget for text line
fields, enforcing a particular layout.
First we have to create a field and a request:
>>> import datetime
>>> import zope.schema
>>> field = zope.schema.TextLine(
... title=u'SSN',
... description=u'Social Security Number',
... required=True)
>>> field.__name__ = 'field'
>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest()
Now we can initialize widget.
>>> from z3c.widget.ssn.browser import SSNWidget
>>> widget = SSNWidget(field, request)
Let's make sure that all fields have the correct value:
>>> widget.name
'field.field'
>>> widget.label
u'SSN'
>>> widget.hint
u'Social Security Number'
>>> widget.visible
True
>>> widget.required
True
The constructor should have also created 3 sub-widgets:
>>> widget.widgets['first']
<zope.formlib.textwidgets.TextWidget object at ...>
>>> widget.widgets['second']
<zope.formlib.textwidgets.TextWidget object at ...>
>>> widget.widgets['third']
<zope.formlib.textwidgets.TextWidget object at ...>
``setRenderedValue(value)`` Method
==================================
The first method is ``setRenderedValue()``. The widget has two use cases,
based on the type of value:
>>> widget = SSNWidget(field, request)
>>> widget.setRenderedValue(u'123-45-6789')
>>> print widget()
<input class="textType" id="field.field.first" name="field.field.first"
size="3" type="text" value="123" /> —
<input class="textType" id="field.field.second" name="field.field.second"
size="2" type="text" value="45" /> —
<input class="textType" id="field.field.third" name="field.field.third"
size="4" type="text" value="6789" />
``setPrefix(prefix)`` Method
============================
The prefix determines the name of the widget and all its sub-widgets.
>>> widget.name
'field.field'
>>> widget.widgets['first'].name
'field.field.first'
>>> widget.widgets['second'].name
'field.field.second'
>>> widget.widgets['third'].name
'field.field.third'
>>> widget.setPrefix('test.')
>>> widget.name
'test.field'
>>> widget.widgets['first'].name
'test.field.first'
>>> widget.widgets['second'].name
'test.field.second'
>>> widget.widgets['third'].name
'test.field.third'
If the prefix does not end in a dot, one is added:
>>> widget.setPrefix('test')
>>> widget.name
'test.field'
>>> widget.widgets['first'].name
'test.field.first'
>>> widget.widgets['second'].name
'test.field.second'
>>> widget.widgets['third'].name
'test.field.third'
``getInputValue()`` Method
==========================
This method returns the full SSN string:
>>> request = TestRequest(form={
... 'field.field.first': '123',
... 'field.field.second': '45',
... 'field.field.third': '6789'})
>>> widget = SSNWidget(field, request)
>>> value = widget.getInputValue()
>>> value
u'123-45-6789'
If a set of values does not produce a valid string, a value error is
raised:
>>> request = TestRequest(form={
... 'field.field.first': '1234',
... 'field.field.second': '56',
... 'field.field.third': '7890'})
>>> widget = SSNWidget(field, request)
>>> widget.getInputValue()
Traceback (most recent call last):
...
WidgetInputError: ('first', u'Frst three digits', ConstraintNotSatisfied(u'1234'))
>>> widget._error.__class__
<class 'zope.formlib.interfaces.WidgetInputError'>
``applyChanges(content)`` Method
================================
This method applies the new SSN to the passed content. However, it
must be smart enough to detect whether the values really changed.
>>> class Content(object):
... field = None
>>> content = Content()
>>> request = TestRequest(form={
... 'field.field.first': '123',
... 'field.field.second': '45',
... 'field.field.third': '6789'})
>>> widget = SSNWidget(field, request)
>>> widget.applyChanges(content)
True
>>> content.field
u'123-45-6789'
>>> widget.applyChanges(content)
False
``hasInput()`` Method
=====================
This method checks for any input, but does not validate it.
>>> request = TestRequest()
>>> widget = SSNWidget(field, request)
>>> widget.hasInput()
False
>>> request = TestRequest(form={
... 'field.field.first': '123'})
>>> widget = SSNWidget(field, request)
>>> widget.hasInput()
False
>>> request = TestRequest(form={
... 'field.field.second': '45'})
>>> widget = SSNWidget(field, request)
>>> widget.hasInput()
False
>>> request = TestRequest(form={
... 'field.field.third': '6789'})
>>> widget = SSNWidget(field, request)
>>> widget.hasInput()
False
>>> request = TestRequest(form={
... 'field.field.first': '123',
... 'field.field.second': '45',
... 'field.field.third': '6789'})
>>> widget = SSNWidget(field, request)
>>> widget.hasInput()
True
``hasValidInput()`` Method
==========================
Additionally to checking for any input, this method also checks whether the
input is valid:
>>> request = TestRequest()
>>> widget = SSNWidget(field, request)
>>> widget.hasValidInput()
False
>>> request = TestRequest(form={
... 'field.field.first': '123'})
>>> widget = SSNWidget(field, request)
>>> widget.hasValidInput()
False
>>> request = TestRequest(form={
... 'field.field.second': '45'})
>>> widget = SSNWidget(field, request)
>>> widget.hasValidInput()
False
>>> request = TestRequest(form={
... 'field.field.third': '6789'})
>>> widget = SSNWidget(field, request)
>>> widget.hasValidInput()
False
>>> request = TestRequest(form={
... 'field.field.first': '123',
... 'field.field.second': '45',
... 'field.field.third': '6789'})
>>> widget = SSNWidget(field, request)
>>> widget.hasValidInput()
True
``hidden()`` Method
===================
This method is renders the output as hidden fields:
>>> request = TestRequest(form={
... 'field.field.first': '123',
... 'field.field.second': '45',
... 'field.field.third': '6789'})
>>> widget = SSNWidget(field, request)
>>> print widget.hidden()
<input class="hiddenType" id="field.field.first" name="field.field.first"
type="hidden" value="123" />
<input class="hiddenType" id="field.field.second" name="field.field.second"
type="hidden" value="45" />
<input class="hiddenType" id="field.field.third" name="field.field.third"
type="hidden" value="6789" />
``error()`` Method
==================
Let's test some bad data and check the error handling.
The third field contains an invalid value:
>>> request = TestRequest(form={
... 'field.field.first': '123',
... 'field.field.second': '45',
... 'field.field.third': '678'})
>>> widget = SSNWidget(field, request)
>>> widget.getInputValue()
Traceback (most recent call last):
...
WidgetInputError: ('third', u'Third four digits', ConstraintNotSatisfied(u'678'))
>>> print widget.error()
<span class="error">Constraint not satisfied</span>
The second field contains an invalid value:
>>> request = TestRequest(form={
... 'field.field.first': '123',
... 'field.field.second': '4-',
... 'field.field.third': '6789'})
>>> widget = SSNWidget(field, request)
>>> widget.getInputValue()
Traceback (most recent call last):
...
WidgetInputError: ('second', u'Second two digits', ConstraintNotSatisfied(u'4-'))
>>> print widget.error()
<span class="error">Constraint not satisfied</span>
The first field contains an invalid value:
>>> request = TestRequest(form={
... 'field.field.first': 'xxx',
... 'field.field.second': '45',
... 'field.field.third': '6789'})
>>> widget = SSNWidget(field, request)
>>> widget.getInputValue()
Traceback (most recent call last):
...
WidgetInputError: ('first', u'Frst three digits', ConstraintNotSatisfied(u'xxx'))
>>> print widget.error()
<span class="error">Constraint not satisfied</span>
No error occurred:
>>> request = TestRequest(form={
... 'field.field.first': '123',
... 'field.field.second': '45',
... 'field.field.third': '6789'})
>>> widget = SSNWidget(field, request)
>>> widget.getInputValue()
u'123-45-6789'
>>> widget.error()
''
``__call__()`` Method
=====================
This method renders the widget using the sub-widgets. Let's see the output:
>>> request = TestRequest(form={
... 'field.field.first': '123',
... 'field.field.second': '45',
... 'field.field.third': '6789'})
>>> widget = SSNWidget(field, request)
>>> print widget()
<input class="textType" id="field.field.first" name="field.field.first"
size="3" type="text" value="123" /> —
<input class="textType" id="field.field.second" name="field.field.second"
size="2" type="text" value="45" /> —
<input class="textType" id="field.field.third" name="field.field.third"
size="4" type="text" value="6789" />
| z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/ssn/README.txt | README.txt |
================
The Image Widget
================
this image widget should be used as a custom_widget for image fields.
comparing to the default widget in zope3 it does not delete the
data in the field if the "delete" checkbox is not explicitly selected.
Adding an Image
===============
>>> import zope.schema
>>> from zope.publisher.browser import TestRequest
>>> from zope import interface
>>> from zope.schema.fieldproperty import FieldProperty
>>> from zope.app.file.interfaces import IImage
>>> from z3c.widget.image.widget import ImageWidget
>>> from zope.app.file.image import Image
create a content type with an image field.
>>> class ITestObject(interface.Interface):
... image = zope.schema.Object(
... title=u'Image',
... schema=IImage)
>>> class TestObject(object):
... interface.implements(ITestObject)
... image = FieldProperty(ITestObject['image'])
>>> obj = TestObject()
>>> field = ITestObject['image'].bind(obj)
Send the request without any image information. the empty field
should not be changed...
>>> request = TestRequest(form={'field.image' : u''})
>>> widget = ImageWidget(field, request)
>>> widget._getFormInput() is None
True
Send some Image information to the field. the image information
should be stored in the field as a Image Object
>>> request = TestRequest(form={'field.image' : u'PNG123Test'})
>>> widget = ImageWidget(field, request)
>>> widget._getFormInput()
<zope.app.file.image.Image object at ...>
Now we save the field again, but without any new image data.
the old image information should not be lost
>>> obj.image = Image(u'PNG123Test')
>>> request = TestRequest(form={'field.image' : u''})
>>> widget = ImageWidget(field, request)
>>> widget._getFormInput() is obj.image
True
Now we want to delete the image. the forminput should be None now.
>>> request = TestRequest(form={'field.image' : u'',
... 'field.image.delete': u'true'})
>>> widget = ImageWidget(field, request)
>>> widget._getFormInput() is None
True
>>> print widget()
<div class="z3cImageWidget">
<input type="file" name="field.image" id="field.image" /><br/>
<input type="checkbox" name="field.image.delete" value="true" />delete image
</div>
| z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/image/README.txt | README.txt |
===================
FLASH UPLOAD WIDGET
===================
the flashupload vars page configures the flash frontend
>>> from z3c.widget.flashupload import upload
>>> from zope.publisher.browser import TestRequest
>>> from zope.app.pagetemplate import ViewPageTemplateFile
>>> from zope.app.pagetemplate.simpleviewclass import SimpleViewClass
>>> request = TestRequest()
>>> context = object()
>>> viewClass = SimpleViewClass(
... 'flashuploadvars.pt', bases=(upload.FlashUploadVars,))
>>> view = viewClass(context, request)
>>> print view()
<?xml version="1.0" ?>
<var>
<var name="file_progress">File Progress</var>
<var name="overall_progress">Overall Progress</var>
<var name="error">Error on uploading files</var>
<var name="uploadcomplete">all files uploaded</var>
<var name="uploadpartial">files uploaded</var>
<var name="notuploaded">files were not uploaded because
they're too big</var>
<var name="maxfilesize">maximum file size is</var>
</var>
>>> view.allowedFileTypes = ('.jpg', '.gif')
>>> print view()
<?xml version="1.0" ?>
<var>
...
<var name="allowedFileType">.jpg</var>
<var name="allowedFileType">.gif</var>
</var>
| z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/flashupload/README.txt | README.txt |
from zope.app.container.interfaces import INameChooser
from ticket import validateTicket, invalidateTicket
from zope.security.interfaces import Unauthorized
from zope.publisher.browser import BrowserView
from zope import interface
from zope.traversing.browser.absoluteurl import absoluteURL
from zope.security.proxy import removeSecurityProxy
from zope.filerepresentation.interfaces import IFileFactory
from zope.app.pagetemplate import ViewPageTemplateFile
from zope.app.container.constraints import checkObject
from zope import event
from zope.app.component.interfaces import ISite
from z3c.widget.flashupload.interfaces import (IFlashUploadForm,
IUploadFileView,
FlashUploadedEvent)
try:
from zc import resourcelibrary
haveResourceLibrary = True
except ImportError:
haveResourceLibrary = False
class FlashUploadVars(BrowserView):
"""simple view for the flashupload.pt
to configure the flash upload swf"""
allowedFileTypes = () # empty tuple for all file types
class UploadFile(object):
"""handles file upload for the flash client.
flash client sends the data via post as u'Filedata'
the filename gets sent as: u'Filename'
"""
interface.implements(IUploadFileView)
def __call__(self):
ticket = self.request.form.get('ticket',None)
url = None
if ticket is None:
# we cannot set post headers in flash, so get the
# querystring manually
qs = self.request.get('QUERY_STRING','ticket=')
ticket = qs.split('=')[-1] or None
if ticket is None:
raise Unauthorized
else:
url = absoluteURL(self,self.request)
if not validateTicket(url,ticket):
raise Unauthorized
invalidateTicket(url,ticket)
if self.request.form.get('Filedata', None) is None:
# flash sends a emtpy form in a pre request in flash version 8.0
return ""
fileUpload = self.request.form['Filedata']
fileName = self.request.form['Filename']
contentType = self.request.form.get('Content-Type',None)
factory = IFileFactory(self.context)
f = factory(fileName, contentType, fileUpload)
# get the namechooser for the container by adapting the
# container to INameChooser
nameChooser = INameChooser(self.context)
# namechooser selects a name for us
name = nameChooser.chooseName(fileName, f)
# check precondition
checkObject(self.context, name, f)
# store the file inside the container
removeSecurityProxy(self.context)[name]=f
event.notify(FlashUploadedEvent(f))
return "filename=%s" %name
class UploadForm(BrowserView):
"""displays the swf for uploading files
"""
template = ViewPageTemplateFile('uploadform.pt')
interface.implements(IFlashUploadForm)
@property
def configUrl(self):
return '%s/@@flashuploadvars.xml' % self.siteUrl
@property
def siteUrl(self):
return absoluteURL(ISite(None), self.request)
def __call__(self, *args, **kw):
if haveResourceLibrary:
resourcelibrary.need('z3c.widget.flashupload')
return self.template(*args, **kw) | z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/flashupload/upload.py | upload.py |
if(typeof deconcept=="undefined"){var deconcept=new Object();}
if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}
if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}
deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a,_b){
if(!document.createElement||!document.getElementById){return;}
this.DETECT_KEY=_b?_b:"detectflash";
this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);
this.params=new Object();
this.variables=new Object();
this.attributes=new Array();
if(_1){this.setAttribute("swf",_1);}
if(id){this.setAttribute("id",id);}
if(w){this.setAttribute("width",w);}
if(h){this.setAttribute("height",h);}
if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}
this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion(this.getAttribute("version"),_7);
if(c){this.addParam("bgcolor",c);}
var q=_8?_8:"high";
this.addParam("quality",q);
this.setAttribute("useExpressInstall",_7);
this.setAttribute("doExpressInstall",false);
var _d=(_9)?_9:window.location;
this.setAttribute("xiRedirectUrl",_d);
this.setAttribute("redirectUrl","");
if(_a){this.setAttribute("redirectUrl",_a);}};
deconcept.SWFObject.prototype={setAttribute:function(_e,_f){
this.attributes[_e]=_f;
},getAttribute:function(_10){
return this.attributes[_10];
},addParam:function(_11,_12){
this.params[_11]=_12;
},getParams:function(){
return this.params;
},addVariable:function(_13,_14){
this.variables[_13]=_14;
},getVariable:function(_15){
return this.variables[_15];
},getVariables:function(){
return this.variables;
},getVariablePairs:function(){
var _16=new Array();
var key;
var _18=this.getVariables();
for(key in _18){
_16.push(key+"="+_18[key]);}
return _16;
},getSWFHTML:function(){
var _19="";
if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){
if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");}
_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\"";
_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";
var _1a=this.getParams();
for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}
var _1c=this.getVariablePairs().join("&");
if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}
_19+="/>";
}else{
if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");}
_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\">";
_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";
var _1d=this.getParams();
for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}
var _1f=this.getVariablePairs().join("&");
if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}
_19+="</object>";}
return _19;
},write:function(_20){
if(this.getAttribute("useExpressInstall")){
var _21=new deconcept.PlayerVersion([6,0,65]);
if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){
this.setAttribute("doExpressInstall",true);
this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));
document.title=document.title.slice(0,47)+" - Flash Player Installation";
this.addVariable("MMdoctitle",document.title);}}
if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){
var n=(typeof _20=="string")?document.getElementById(_20):_20;
n.innerHTML=this.getSWFHTML();
return true;
}else{
if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}
return false;}};
deconcept.SWFObjectUtil.getPlayerVersion=function(_23,_24){
var _25=new deconcept.PlayerVersion([0,0,0]);
if(navigator.plugins&&navigator.mimeTypes.length){
var x=navigator.plugins["Shockwave Flash"];
if(x&&x.description){_25=new deconcept.PlayerVersion(x.description.replace(/([a-z]|[A-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}
}else{try{
var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
for(var i=15;i>6;i--){
try{
axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+i);
_25=new deconcept.PlayerVersion([i,0,0]);
break;}
catch(e){}}}
catch(e){}
if(_23&&_25.major>_23.major){return _25;}
if(!_23||((_23.minor!=0||_23.rev!=0)&&_25.major==_23.major)||_25.major!=6||_24){
try{_25=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}
catch(e){}}}
return _25;};
deconcept.PlayerVersion=function(_29){
this.major=parseInt(_29[0])!=null?parseInt(_29[0]):0;
this.minor=parseInt(_29[1])||0;
this.rev=parseInt(_29[2])||0;};
deconcept.PlayerVersion.prototype.versionIsValid=function(fv){
if(this.major<fv.major){return false;}
if(this.major>fv.major){return true;}
if(this.minor<fv.minor){return false;}
if(this.minor>fv.minor){return true;}
if(this.rev<fv.rev){return false;}return true;};
deconcept.util={getRequestParameter:function(_2b){
var q=document.location.search||document.location.hash;
if(q){
var _2d=q.indexOf(_2b+"=");
var _2e=(q.indexOf("&",_2d)>-1)?q.indexOf("&",_2d):q.length;
if(q.length>1&&_2d>-1){
return q.substring(q.indexOf("=",_2d)+1,_2e);
}}return "";}};
if(Array.prototype.push==null){
Array.prototype.push=function(_2f){
this[this.length]=_2f;
return this.length;};}
var getQueryParamValue=deconcept.util.getRequestParameter;
var FlashObject=deconcept.SWFObject; // for backwards compatibility
var SWFObject=deconcept.SWFObject; | z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/flashupload/resources/swfobject.js | swfobject.js |
function z3cFlashUploadStartBrowsing(){
// tells flash to start with browsing
if(window.fuploader){
window.document["fuploader"].SetVariable("startBrowse", "go");
}else if(document.fuploader){
document.fuploader.SetVariable("startBrowse", "go");
}
}
function z3cFlashUploadEnableBrowseButton(){
document.getElementById("flash.start.browsing").style.visibility = "visible";
document.getElementById("flash.start.browsing").disabled = false;
}
function z3cFlashUploadDisableBrowseButton(){
document.getElementById("flash.start.browsing").style.visibility = "hidden";
document.getElementById("flash.start.browsing").disabled = "disabled";
}
function z3cFlashUploadOnUploadCompleteFEvent(status){
// always fired from flash
if (typeof(z3cFlashUploadOnUploadComplete) == "function"){
z3cFlashUploadOnUploadComplete(status);
}
}
function z3cFlashUploadOnFileCompleteFEvent(filename){
// always fired from flash
if (typeof(z3cFlashUploadOnFileComplete) =="function"){
z3cFlashUploadOnFileComplete(filename);
}
}
/**
called when the user presses the cancel button while browsing
*/
function z3cFlashUploadOnCancelFEvent(){
if (typeof(z3cFlashUploadOnCancelEvent) =="function"){
z3cFlashUploadOnCancelEvent();
}
}
/**
called if an error occured during the upload progress
*/
function z3cFlashUploadOnErrorFEvent(error_str){
if (typeof(z3cFlashUploadOnErrorEvent) =="function"){
z3cFlashUploadOnErrorEvent(error_str);
}
}
function prepareUrlForFlash(url){
return escape(url).split("+").join("%2B");
}
/**
creates a instance of the multifile upload widget
insidde the target div.
Required global variable: swf_upload_target_path
*/
function createFlashUpload()
{
var so = new SWFObject(swf_upload_url, "fuploader", "100%", "100%", "8.0.33", "#f8f8f8");
so.addParam("allowScriptAccess", "sameDomain");
so.addParam("wmode", "transparent");
// we need to manually quote the "+" signs to make sure they do not
// result in a " " sign inside flash
so.addVariable("target_path", swf_upload_target_path);
so.addVariable("site_path", prepareUrlForFlash(swf_upload_site_url));
so.addVariable("config_path", prepareUrlForFlash(swf_upload_config_url));
var success = so.write("flashuploadtarget");
if (!success){
$("#flashuploadtarget").load("noflashupload.html")
}
}
if (window.addEventListener){
window.addEventListener('load', createFlashUpload, false);
}
else if(window.attachEvent){
window.attachEvent('onload', createFlashUpload);
} | z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/flashupload/resources/upload.js | upload.js |
__docformat__ = "reStructuredText"
import zope.component
import zope.schema.interfaces
from zope.app import form
from zope.app.form import browser
from zope.app.form.browser.itemswidgets import ItemDisplayWidget
from zope.app.form.interfaces import MissingInputError
class OptionalDisplayWidget(ItemDisplayWidget):
def __call__(self):
"""See IBrowserWidget."""
value = self._getFormValue()
if not value:
return self.translate(self._messageNoValue)
elif value not in self.vocabulary:
return value
else:
term = self.vocabulary.getTerm(value)
return self.textForValue(term)
class OptionalDropdownWidget(object):
"""Optional Dropdown Widget"""
zope.interface.implements(browser.interfaces.IBrowserWidget,
form.interfaces.IInputWidget)
connector = u'<br />\n'
_prefix = 'field.'
# See zope.app.form.interfaces.IWidget
name = None
label = property(lambda self: self.context.title)
hint = property(lambda self: self.context.description)
visible = True
# See zope.app.form.interfaces.IInputWidget
required = property(lambda self: self.context.required)
def __init__(self, field, request):
self.context = field
self.request = request
# Clone field again, because we change the ``require`` options
clone = field.bind(field.context)
clone.required = False
clone.value_type.required = False
# Setup the custom value widget
clone.value_type.__name__ = 'custom'
self.customWidget = zope.component.getMultiAdapter(
(clone.value_type, request), form.interfaces.IInputWidget)
# Setup the dropdown widget
self.dropdownWidget = form.browser.DropdownWidget(
clone, clone.vocabulary, request)
# Setting the prefix again, sets everything up correctly
self.setPrefix(self._prefix)
def setRenderedValue(self, value):
"""See zope.app.form.interfaces.IWidget"""
if value in self.context.vocabulary:
self.dropdownWidget.setRenderedValue(value)
self.customWidget.setRenderedValue(
self.context.value_type.missing_value)
else:
self.customWidget.setRenderedValue(value)
self.dropdownWidget.setRenderedValue(
self.context.missing_value)
def setPrefix(self, prefix):
"""See zope.app.form.interfaces.IWidget"""
# Set the prefix locally
if not prefix.endswith("."):
prefix += '.'
self._prefix = prefix
self.name = prefix + self.context.__name__
self.customWidget.setPrefix(self.name+'.')
self.dropdownWidget.setPrefix(self.name+'.')
def getInputValue(self):
"""See zope.app.form.interfaces.IInputWidget"""
customMissing = self.context.value_type.missing_value
if (self.customWidget.hasInput() and
self.customWidget.getInputValue() != customMissing):
return self.customWidget.getInputValue()
dropdownMissing = self.context.value_type.missing_value
if (self.dropdownWidget.hasInput() and
self.dropdownWidget.getInputValue() != dropdownMissing):
return self.dropdownWidget.getInputValue()
raise MissingInputError(self.name, self.label,
zope.schema.interfaces.RequiredMissing())
def applyChanges(self, content):
"""See zope.app.form.interfaces.IInputWidget"""
field = self.context
new_value = self.getInputValue()
old_value = field.query(content, self)
# The selection of an existing scoresystem has not changed
if new_value == old_value:
return False
field.set(content, new_value)
return True
def hasInput(self):
"""See zope.app.form.interfaces.IInputWidget"""
return self.dropdownWidget.hasInput() or self.customWidget.hasInput()
def hasValidInput(self):
"""See zope.app.form.interfaces.IInputWidget"""
customValid = self.customWidget.hasValidInput()
customMissing = self.context.value_type.missing_value
dropdownValid = self.dropdownWidget.hasValidInput()
dropdownMissing = self.context.missing_value
# If the field is required and both values are missing, then the input
# is invalid
if self.context.required:
return (
(customValid and
self.customWidget.getInputValue() != customMissing)
or
(dropdownValid and
self.dropdownWidget.getInputValue() != dropdownMissing)
)
# If the field is not required, we just need either input to be valid,
# since both generated widgets have non-required fields.
return customValid or dropdownValid
def hidden(self):
"""See zope.app.form.browser.interfaces.IBrowserWidget"""
return '\n'.join((self.dropdownWidget.hidden(),
self.customWidget.hidden()))
def error(self):
"""See zope.app.form.browser.interfaces.IBrowserWidget"""
dropdownError = self.dropdownWidget.error()
if dropdownError:
return dropdownError
return self.customWidget.error()
def __call__(self):
"""See zope.app.form.browser.interfaces.IBrowserWidget"""
return self.connector.join((self.dropdownWidget(), self.customWidget())) | z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/optdropdown/widget.py | widget.py |
=========================
Optional Dropdown Widgets
=========================
The Optional Dropdown Widget simulates the common desktop widget of a combo
box, which can also receive a custom entry.
Before we can start, we have to do a little bit of setup:
>>> import zope.component
>>> import zope.schema
>>> import zope.app.form.browser
>>> from zope.publisher.interfaces.browser import IBrowserRequest
>>> zope.component.provideAdapter(
... zope.app.form.browser.TextWidget,
... (zope.schema.interfaces.ITextLine, IBrowserRequest),
... zope.app.form.interfaces.IInputWidget)
First we have to create a field and a request:
>>> from z3c.schema.optchoice import OptionalChoice
>>> optchoice = OptionalChoice(
... __name__='occupation',
... title=u'Occupation',
... description=u'The Occupation',
... values=(u'Programmer', u'Designer', u'Project Manager'),
... value_type=zope.schema.TextLine())
>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest()
Now we can initialize widget.
>>> class Content(object):
... occupation = None
>>> content = Content()
>>> boundOptChoice = optchoice.bind(content)
>>> from z3c.widget.optdropdown import OptionalDropdownWidget
>>> widget = OptionalDropdownWidget(boundOptChoice, request)
Let's make sure that all fields have the correct value:
>>> widget.name
'field.occupation'
>>> widget.label
u'Occupation'
>>> widget.hint
u'The Occupation'
>>> widget.visible
True
>>> widget.required
True
The constructor should have also created 2 widgets:
>>> widget.customWidget
<zope.formlib.textwidgets.TextWidget object at ...>
>>> widget.dropdownWidget
<zope.formlib.itemswidgets.DropdownWidget object at ...>
``setRenderedValue(value)`` Method
==================================
The first method is ``setRenderedValue()``. The widget has two use cases,
based on the type of value. If the value is a custom value, it will
send the information to the custom widget:
>>> print widget.customWidget()
<... value="" />
>>> 'selected=""' in widget.dropdownWidget()
False
>>> widget.setRenderedValue(u'Scientist')
>>> print widget.customWidget()
<... value="Scientist" />
>>> 'selected=""' in widget.dropdownWidget()
False
After resetting the widget passing in one of the choices in the
vocabulary, the value should be displayed in the dropdown:
>>> widget.setRenderedValue(u'Designer')
>>> print widget.customWidget()
<... value="" />
>>> print widget.dropdownWidget()
<div>
...
<option selected="selected" value="Designer">Designer</option>
...
</div>
``setPrefix(prefix)`` Method
============================
The prefix determines the name of the widget and the sub-widgets.
>>> widget.name
'field.occupation'
>>> widget.dropdownWidget.name
'field.occupation.occupation'
>>> widget.customWidget.name
'field.occupation.custom'
>>> widget.setPrefix('test.')
>>> widget.name
'test.occupation'
>>> widget.dropdownWidget.name
'test.occupation.occupation'
>>> widget.customWidget.name
'test.occupation.custom'
``getInputValue()`` Method
==========================
This method returns a value based on the input; the data is assumed to
be valid. In our case that means, if we entered a custom value, it is
returned:
>>> request = TestRequest(form={
... 'field.occupation.custom': u'Teacher'})
>>> widget = OptionalDropdownWidget(boundOptChoice, request)
>>> widget.getInputValue()
u'Teacher'
On the other hand, if we selected a choice from the vocabulary, it should be
returned:
>>> request = TestRequest(form={
... 'field.occupation.occupation': u'Designer'})
>>> widget = OptionalDropdownWidget(boundOptChoice, request)
>>> widget.getInputValue()
u'Designer'
``applyChanges(content)`` Method
================================
This method applies the new value to the passed content. However, it
must be smart enough to detect whether the values really changed.
>>> request = TestRequest(form={
... 'field.occupation.custom': u'Teacher'})
>>> widget = OptionalDropdownWidget(boundOptChoice, request)
>>> widget.applyChanges(content)
True
>>> content.occupation
u'Teacher'
>>> widget.applyChanges(content)
False
>>> request = TestRequest(form={
... 'field.occupation.occupation': u'Designer'})
>>> widget = OptionalDropdownWidget(boundOptChoice, request)
>>> widget.applyChanges(content)
True
>>> content.occupation
u'Designer'
>>> widget.applyChanges(content)
False
``hasInput()`` Method
=====================
This mehtod checks for any input, but does not validate it. In our case this
means that either a choice has been selected or the the custom value has been
entered.
>>> request = TestRequest()
>>> widget = OptionalDropdownWidget(boundOptChoice, request)
>>> widget.hasInput()
False
>>> request = TestRequest(form={
... 'field.occupation.custom': u'Teacher\nBad Stuff'})
>>> widget = OptionalDropdownWidget(boundOptChoice, request)
>>> widget.hasInput()
True
>>> request = TestRequest(form={
... 'field.occupation.occupation': u'Waitress'})
>>> widget = OptionalDropdownWidget(boundOptChoice, request)
>>> widget.hasInput()
True
``hasValidInput()`` Method
==========================
Additionally to checking for any input, this method also checks whether the
input is valid:
>>> request = TestRequest()
>>> widget = OptionalDropdownWidget(boundOptChoice, request)
>>> widget.hasValidInput()
False
>>> request = TestRequest(form={
... 'field.occupation.occupation': u'Waitress'})
>>> widget = OptionalDropdownWidget(boundOptChoice, request)
>>> widget.hasValidInput()
False
>>> request = TestRequest(form={
... 'field.occupation.occupation': u'Designer'})
>>> widget = OptionalDropdownWidget(boundOptChoice, request)
>>> widget.hasValidInput()
True
>>> request = TestRequest(form={
... 'field.occupation.custom': u'Teacher\nBad Stuff'})
>>> widget = OptionalDropdownWidget(boundOptChoice, request)
>>> widget.hasValidInput()
False
>>> request = TestRequest(form={
... 'field.occupation.custom': u'Teacher'})
>>> widget = OptionalDropdownWidget(boundOptChoice, request)
>>> widget.hasValidInput()
True
hidden() Method
===============
This method is implemented by simply concatenating the two widget's hidden
output:
>>> request = TestRequest()
>>> widget = OptionalDropdownWidget(boundOptChoice, request)
>>> widget.setRenderedValue(u'Designer')
>>> print widget.hidden()
<input class="hiddenType" id="field.occupation.occupation"
name="field.occupation.occupation" type="hidden" value="Designer" />
<input class="hiddenType" id="field.occupation.custom"
name="field.occupation.custom" type="hidden" value="" />
>>> widget.setRenderedValue(u'Teacher')
>>> print widget.hidden()
<input class="hiddenType" id="field.occupation.occupation"
name="field.occupation.occupation" type="hidden" value="" />
<input class="hiddenType" id="field.occupation.custom"
name="field.occupation.custom" type="hidden" value="Teacher" />
error() Method
==============
Again, we have our two cases. If an error occured in the dropdown, it is
reported:
>>> from zope.app.form.interfaces import IWidgetInputError
>>> from zope.app.form.browser.exception import WidgetInputErrorView
>>> from zope.app.form.browser.interfaces import IWidgetInputErrorView
>>> zope.component.provideAdapter(
... WidgetInputErrorView,
... (IWidgetInputError, IBrowserRequest), IWidgetInputErrorView)
>>> request = TestRequest(form={
... 'field.occupation.occupation': u'Designer'})
>>> widget = OptionalDropdownWidget(boundOptChoice, request)
>>> widget.getInputValue()
u'Designer'
>>> widget.error()
''
>>> request = TestRequest(form={
... 'field.occupation.occupation': u'Waitress'})
>>> widget = OptionalDropdownWidget(boundOptChoice, request)
>>> widget.getInputValue()
Traceback (most recent call last):
...
ConversionError: (u'Invalid value', InvalidValue("token u'Waitress' not found in vocabulary"))
>>> widget.error()
u'<span class="error">Invalid value</span>'
Otherwise the custom widget's errors are reported:
>>> request = TestRequest(form={
... 'field.occupation.custom': u'Teacher'})
>>> widget = OptionalDropdownWidget(boundOptChoice, request)
>>> widget.getInputValue()
u'Teacher'
>>> widget.error()
''
>>> request = TestRequest(form={
... 'field.occupation.custom': u'Teacher\nBad Stuff'})
>>> widget = OptionalDropdownWidget(boundOptChoice, request)
>>> widget.getInputValue()
Traceback (most recent call last):
...
WidgetInputError: ('custom', u'', ConstraintNotSatisfied(u'Teacher\nBad Stuff'))
>>> widget.error()
u'<span class="error">Constraint not satisfied</span>'
__call__() Method
=================
This method renders the widget using the sub-widgets. It simply adds the two
widgets' output placing the ``connector`` between them:
>>> request = TestRequest(form={
... 'field.occupation.custom': u'Teacher'})
>>> widget = OptionalDropdownWidget(boundOptChoice, request)
>>> widget.connector
u'<br />\n'
>>> print widget()
<div>
<div class="value">
<select id="field.occupation.occupation"
name="field.occupation.occupation" size="1" >
<option selected="selected" value="">(nothing selected)</option>
<option value="Programmer">Programmer</option>
<option value="Designer">Designer</option>
<option value="Project Manager">Project Manager</option>
</select>
</div>
<input name="field.occupation.occupation-empty-marker" type="hidden"
value="1" />
</div><br />
<input class="textType" id="field.occupation.custom"
name="field.occupation.custom" size="20" type="text" value="Teacher" />
| z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/optdropdown/README.txt | README.txt |
from z3c.i18n import MessageFactory as _
from zope.app.form import browser
from zope.app.form.browser.interfaces import IBrowserWidget
from zope.app.form.browser.interfaces import IWidgetInputErrorView
from zope.app.form.interfaces import IInputWidget
from zope.app.form.interfaces import WidgetInputError
from zope.app.pagetemplate import ViewPageTemplateFile
from zope.formlib import form
import datetime
import re
import zope.component
import zope.interface
import zope.schema
class IPhoneData(zope.interface.Interface):
"""A schema used to generate a Phone widget."""
first = zope.schema.TextLine(
title=_('Area Code'),
description=_('The area code of the phone number.'),
min_length=3,
max_length=3,
constraint=re.compile(r'^[0-9]{3}$').search,
required=True)
second = zope.schema.TextLine(
title=_('Three Digits'),
description=_('The first three digits of the phone number.'),
min_length=3,
max_length=3,
constraint=re.compile(r'^[0-9]{3}$').search,
required=True)
third = zope.schema.TextLine(
title=_('Four Digits'),
description=_('The second four digits of the phone number.'),
min_length=4,
max_length=4,
constraint=re.compile(r'^[0-9]{4}$').search,
required=True)
class PhoneWidgetData(object):
"""Social Security Number Data"""
zope.interface.implements(IPhoneData)
first = None
second = None
third = None
def __init__(self, context, number=None):
self.context = context
if number:
self.first, self.second, self.third = number.split('-')
@property
def number(self):
return u'-'.join((self.first, self.second, self.third))
class PhoneWidget(object):
"""Social Security Number Widget"""
zope.interface.implements(IBrowserWidget, IInputWidget)
template = ViewPageTemplateFile('widget-phone.pt')
_prefix = 'field.'
_error = None
widgets = {}
# See zope.app.form.interfaces.IWidget
name = None
label = property(lambda self: self.context.title)
hint = property(lambda self: self.context.description)
visible = True
# See zope.app.form.interfaces.IInputWidget
required = property(lambda self: self.context.required)
def __init__(self, field, request):
self.context = field
self.request = request
self.name = self._prefix + field.__name__
value = field.query(field.context)
adapters = {}
adapters[IPhoneData] = PhoneWidgetData(self, value)
self.widgets = form.setUpEditWidgets(
form.FormFields(IPhoneData),
self.name, value, request, adapters=adapters)
self.widgets['first'].displayWidth = 3
self.widgets['second'].displayWidth = 3
self.widgets['third'].displayWidth = 4
def setRenderedValue(self, value):
"""See zope.app.form.interfaces.IWidget"""
if isinstance(value, unicode):
first, second, third = value.split('-')
self.widgets['first'].setRenderedValue(first)
self.widgets['second'].setRenderedValue(second)
self.widgets['third'].setRenderedValue(third)
def setPrefix(self, prefix):
"""See zope.app.form.interfaces.IWidget"""
# Set the prefix locally
if not prefix.endswith("."):
prefix += '.'
self._prefix = prefix
self.name = prefix + self.context.__name__
# Now distribute it to the sub-widgets
for widget in [
self.widgets[name] for name in ['first', 'second', 'third']]:
widget.setPrefix(self.name+'.')
def getInputValue(self):
"""See zope.app.form.interfaces.IInputWidget"""
self._error = None
try:
return u'-'.join((
self.widgets['first'].getInputValue(),
self.widgets['second'].getInputValue(),
self.widgets['third'].getInputValue() ))
except ValueError, v:
self._error = WidgetInputError(
self.context.__name__, self.label, _(v))
raise self._error
except WidgetInputError, e:
self._error = e
raise e
def applyChanges(self, content):
"""See zope.app.form.interfaces.IInputWidget"""
field = self.context
new_value = self.getInputValue()
old_value = field.query(content, self)
# The selection has not changed
if new_value == old_value:
return False
field.set(content, new_value)
return True
def hasInput(self):
"""See zope.app.form.interfaces.IInputWidget"""
return (self.widgets['first'].hasInput() and
(self.widgets['second'].hasInput() and
self.widgets['third'].hasInput()))
def hasValidInput(self):
"""See zope.app.form.interfaces.IInputWidget"""
return (self.widgets['first'].hasValidInput() and
self.widgets['second'].hasValidInput() and
self.widgets['third'].hasValidInput())
def hidden(self):
"""See zope.app.form.browser.interfaces.IBrowserWidget"""
output = []
output.append(self.widgets['first'].hidden())
output.append(self.widgets['second'].hidden())
output.append(self.widgets['third'].hidden())
return '\n'.join(output)
def error(self):
"""See zope.app.form.browser.interfaces.IBrowserWidget"""
if self._error:
return zope.component.getMultiAdapter(
(self._error, self.request),
IWidgetInputErrorView).snippet()
first_error = self.widgets['first'].error()
if first_error:
return first_error
second_error = self.widgets['second'].error()
if second_error:
return second_error
third_error = self.widgets['third'].error()
if third_error:
return third_error
return ""
def __call__(self):
"""See zope.app.form.browser.interfaces.IBrowserWidget"""
return self.template() | z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/usphone/browser.py | browser.py |
===============
US Phone Widget
===============
The US phone number widget can be used as a custom widget for text line
fields, enforcing a particular layout.
First we have to create a field and a request:
>>> import datetime
>>> import zope.schema
>>> field = zope.schema.TextLine(
... title=u'Phone',
... description=u'Phone Number',
... required=True)
>>> field.__name__ = 'field'
>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest()
Now we can initialize widget.
>>> from z3c.widget.usphone.browser import PhoneWidget
>>> widget = PhoneWidget(field, request)
Let's make sure that all fields have the correct value:
>>> widget.name
'field.field'
>>> widget.label
u'Phone'
>>> widget.hint
u'Phone Number'
>>> widget.visible
True
>>> widget.required
True
The constructor should have also created 3 sub-widgets:
>>> widget.widgets['first']
<zope.formlib.textwidgets.TextWidget object at ...>
>>> widget.widgets['second']
<zope.formlib.textwidgets.TextWidget object at ...>
>>> widget.widgets['third']
<zope.formlib.textwidgets.TextWidget object at ...>
``setRenderedValue(value)`` Method
==================================
The first method is ``setRenderedValue()``. The widget has two use cases,
based on the type of value:
>>> widget = PhoneWidget(field, request)
>>> widget.setRenderedValue(u'123-456-7890')
>>> print widget()
(<input class="textType" id="field.field.first" name="field.field.first"
size="3" type="text" value="123" />)
<input class="textType" id="field.field.second" name="field.field.second"
size="3" type="text" value="456" /> —
<input class="textType" id="field.field.third" name="field.field.third"
size="4" type="text" value="7890" />
``setPrefix(prefix)`` Method
============================
The prefix determines the name of the widget and all its sub-widgets.
>>> widget.name
'field.field'
>>> widget.widgets['first'].name
'field.field.first'
>>> widget.widgets['second'].name
'field.field.second'
>>> widget.widgets['third'].name
'field.field.third'
>>> widget.setPrefix('test.')
>>> widget.name
'test.field'
>>> widget.widgets['first'].name
'test.field.first'
>>> widget.widgets['second'].name
'test.field.second'
>>> widget.widgets['third'].name
'test.field.third'
If the prefix does not end in a dot, one is added:
>>> widget.setPrefix('test')
>>> widget.name
'test.field'
>>> widget.widgets['first'].name
'test.field.first'
>>> widget.widgets['second'].name
'test.field.second'
>>> widget.widgets['third'].name
'test.field.third'
``getInputValue()`` Method
==========================
This method returns the full phone string:
>>> request = TestRequest(form={
... 'field.field.first': '123',
... 'field.field.second': '456',
... 'field.field.third': '7890'})
>>> widget = PhoneWidget(field, request)
>>> value = widget.getInputValue()
>>> value
u'123-456-7890'
If a set of values does not produce a valid string, a value error is
raised:
>>> request = TestRequest(form={
... 'field.field.first': '1234',
... 'field.field.second': '56',
... 'field.field.third': '7890'})
>>> widget = PhoneWidget(field, request)
>>> widget.getInputValue()
Traceback (most recent call last):
...
WidgetInputError: ('first', u'Area Code', ConstraintNotSatisfied(u'1234'))
>>> widget._error.__class__
<class 'zope.formlib.interfaces.WidgetInputError'>
``applyChanges(content)`` Method
================================
This method applies the new phone number to the passed content. However, it
must be smart enough to detect whether the values really changed.
>>> class Content(object):
... field = None
>>> content = Content()
>>> request = TestRequest(form={
... 'field.field.first': '123',
... 'field.field.second': '456',
... 'field.field.third': '7890'})
>>> widget = PhoneWidget(field, request)
>>> widget.applyChanges(content)
True
>>> content.field
u'123-456-7890'
>>> widget.applyChanges(content)
False
``hasInput()`` Method
=====================
This method checks for any input, but does not validate it.
>>> request = TestRequest()
>>> widget = PhoneWidget(field, request)
>>> widget.hasInput()
False
>>> request = TestRequest(form={
... 'field.field.first': '123'})
>>> widget = PhoneWidget(field, request)
>>> widget.hasInput()
False
>>> request = TestRequest(form={
... 'field.field.second': '456'})
>>> widget = PhoneWidget(field, request)
>>> widget.hasInput()
False
>>> request = TestRequest(form={
... 'field.field.third': '7890'})
>>> widget = PhoneWidget(field, request)
>>> widget.hasInput()
False
>>> request = TestRequest(form={
... 'field.field.first': '123',
... 'field.field.second': '456',
... 'field.field.third': '7890'})
>>> widget = PhoneWidget(field, request)
>>> widget.hasInput()
True
``hasValidInput()`` Method
==========================
Additionally to checking for any input, this method also checks whether the
input is valid:
>>> request = TestRequest()
>>> widget = PhoneWidget(field, request)
>>> widget.hasValidInput()
False
>>> request = TestRequest(form={
... 'field.field.first': '123'})
>>> widget = PhoneWidget(field, request)
>>> widget.hasValidInput()
False
>>> request = TestRequest(form={
... 'field.field.second': '456'})
>>> widget = PhoneWidget(field, request)
>>> widget.hasValidInput()
False
>>> request = TestRequest(form={
... 'field.field.third': '7890'})
>>> widget = PhoneWidget(field, request)
>>> widget.hasValidInput()
False
>>> request = TestRequest(form={
... 'field.field.first': '123',
... 'field.field.second': '456',
... 'field.field.third': '7890'})
>>> widget = PhoneWidget(field, request)
>>> widget.hasValidInput()
True
``hidden()`` Method
===================
This method is renders the output as hidden fields:
>>> request = TestRequest(form={
... 'field.field.first': '123',
... 'field.field.second': '456',
... 'field.field.third': '7890'})
>>> widget = PhoneWidget(field, request)
>>> print widget.hidden()
<input class="hiddenType" id="field.field.first" name="field.field.first"
type="hidden" value="123" />
<input class="hiddenType" id="field.field.second" name="field.field.second"
type="hidden" value="456" />
<input class="hiddenType" id="field.field.third" name="field.field.third"
type="hidden" value="7890" />
``error()`` Method
==================
Let's test some bad data and check the error handling.
The third field contains an invalid value:
>>> request = TestRequest(form={
... 'field.field.first': '123',
... 'field.field.second': '456',
... 'field.field.third': '78901'})
>>> widget = PhoneWidget(field, request)
>>> widget.getInputValue()
Traceback (most recent call last):
...
WidgetInputError: ('third', u'Four Digits', ConstraintNotSatisfied(u'78901'))
>>> print widget.error()
<span class="error">Constraint not satisfied</span>
The second field contains an invalid value:
>>> request = TestRequest(form={
... 'field.field.first': '123',
... 'field.field.second': '45-',
... 'field.field.third': '7890'})
>>> widget = PhoneWidget(field, request)
>>> widget.getInputValue()
Traceback (most recent call last):
...
WidgetInputError: ('second', u'Three Digits', ConstraintNotSatisfied(u'45-'))
>>> print widget.error()
<span class="error">Constraint not satisfied</span>
The first field contains an invalid value:
>>> request = TestRequest(form={
... 'field.field.first': 'xxx',
... 'field.field.second': '456',
... 'field.field.third': '7890'})
>>> widget = PhoneWidget(field, request)
>>> widget.getInputValue()
Traceback (most recent call last):
...
WidgetInputError: ('first', u'Area Code', ConstraintNotSatisfied(u'xxx'))
>>> print widget.error()
<span class="error">Constraint not satisfied</span>
No error occurred:
>>> request = TestRequest(form={
... 'field.field.first': '123',
... 'field.field.second': '456',
... 'field.field.third': '7890'})
>>> widget = PhoneWidget(field, request)
>>> widget.getInputValue()
u'123-456-7890'
>>> widget.error()
''
``__call__()`` Method
=====================
This method renders the widget using the sub-widgets. Let's see the output:
>>> request = TestRequest(form={
... 'field.field.first': '123',
... 'field.field.second': '456',
... 'field.field.third': '7890'})
>>> widget = PhoneWidget(field, request)
>>> print widget()
(<input class="textType" id="field.field.first" name="field.field.first"
size="3" type="text" value="123" />)
<input class="textType" id="field.field.second" name="field.field.second"
size="3" type="text" value="456" /> —
<input class="textType" id="field.field.third" name="field.field.third"
size="4" type="text" value="7890" />
| z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/usphone/README.txt | README.txt |
from zope.app.form.browser import SequenceDisplayWidget, SequenceWidget
from zope.app.form.interfaces import IInputWidget
from zope.app.pagetemplate.viewpagetemplatefile import ViewPageTemplateFile
from zope.i18n import translate
import zope.component
try:
from zc import resourcelibrary
haveResourceLibrary = True
except ImportError:
haveResourceLibrary = False
def _getSubWidget(sequenceWidget, prefix="%s."):
field = sequenceWidget.context.value_type
if sequenceWidget.subwidget is not None:
widget = sequenceWidget.subwidget(field, sequenceWidget.request)
else:
widget = zope.component.getMultiAdapter((field, sequenceWidget.request),
IInputWidget)
widget.setPrefix(prefix % (sequenceWidget.name))
return widget
class SequenceDisplayTableWidget(SequenceDisplayWidget):
template = ViewPageTemplateFile('sequencedisplaytablewidget.pt')
def __call__(self):
return self.template()
def mainWidget(self):
return _getSubWidget(self)
def haveMessage(self):
if self._renderedValueSet():
data = self._data
else:
data = self.context.get(self.context.context)
# deal with special cases:
if data == self.context.missing_value:
return translate(self._missingValueMessage, self.request)
data = list(data)
if not data:
return translate(self._emptySequenceMessage, self.request)
return None
def widgets(self):
# get the data to display:
if self._renderedValueSet():
data = self._data
else:
data = self.context.get(self.context.context)
# deal with special cases:
if data == self.context.missing_value:
return translate(self._missingValueMessage, self.request)
data = list(data)
if not data:
return translate(self._emptySequenceMessage, self.request)
widgets = []
for i, item in enumerate(data):
#widget = self._getSubWidget(i)
widget = self._getWidget(i)
widget.setRenderedValue(item)
widgets.append(widget)
return widgets
class SequenceTableWidget(SequenceWidget):
template = ViewPageTemplateFile('sequencetablewidget.pt')
def mainWidget(self):
return _getSubWidget(self)
class TupleSequenceTableWidget(SequenceTableWidget):
_type = tuple
class ListSequenceTableWidget(SequenceTableWidget):
_type = list
class SequenceTableJSWidget(SequenceWidget):
template = ViewPageTemplateFile('sequencetablejswidget.pt')
haveResourceLibrary = haveResourceLibrary
def mainWidget(self):
return _getSubWidget(self)
def emptyWidget(self):
widget = _getSubWidget(self, prefix="%s._default_rowid_")
widget.setRenderedValue(None)
return widget
def _getPresenceMarker(self, count=0):
maxval = self.context.max_length
if maxval:
maxval=str(maxval)
else:
maxval=''
minval = self.context.min_length
if minval:
minval=str(minval)
else:
minval=''
rv = ('<input type="hidden" name="%s.count" id="%s.count" value="%d" />'
% (self.name, self.name, count))
rv = rv+('<input type="hidden" name="%s.max_length" id="%s.max_length" value="%s" />'
% (self.name, self.name, maxval))
rv = rv+('<input type="hidden" name="%s.min_length" id="%s.min_length" value="%s" />'
% (self.name, self.name, minval))
return rv
def __call__(self, *args, **kw):
if haveResourceLibrary:
resourcelibrary.need('sequencetable')
return super(SequenceTableJSWidget, self).__call__(*args, **kw)
class TupleSequenceTableJSWidget(SequenceTableJSWidget):
_type = tuple
class ListSequenceTableJSWidget(SequenceTableJSWidget):
_type = list | z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/sequence/widget.py | widget.py |
====================
SequenceTable Widget
====================
This package provides a Sequence Widget just as
zope.app.form.browser.sequencewidget.
The main difference is that it places the subobject's fields horizontally in
a table. That means a kind of voucher-item forms are piece of cake to do.
There is also a widget (SequenceTableJSWidget) which does the add/remove item
in the browser with javascript.
The trick is to embed an invisible template of an empty row in the HTML,
add that each time a new row is required.
Drawbacks of JS:
* Validation is done ONLY when the complete form is submitted to the server.
* Submitting the form and using the Back button of the browser does not work.
WARNING!
========
The subobject MUST have subwidgets. That is usually the case if the subobject
is based on zope.schema.Object.
TODO
====
Tests.
Some are there, some are copied from z.a.form.browser and need fix. | z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/sequence/README.txt | README.txt |
function sequencetable_moveChildren(srcNode, destNode){
var count = 0;
while(srcNode.hasChildNodes()){
destNode.appendChild(srcNode.firstChild);
count++;
}
return count;
}
function sequencetable_copyChildren(srcNode, destNode){
var clonedNode = srcNode.cloneNode(true);
return sequencetable_moveChildren(clonedNode, destNode);
}
function sequencetable_addRow(sPrefix) {
var sTableID = sPrefix+".tbody";
var sRowID = sPrefix+"_row#_default_rowid_";
var tbodyElem = document.getElementById(sTableID);
var oRow = document.getElementById(sRowID);
var trElem, tdElem;
trElem = tbodyElem.insertRow(tbodyElem.rows.length);
var sHtml = new String(oRow.innerHTML);
sequencetable_copyChildren(oRow, trElem);
var oCount = document.getElementById(sPrefix+".count");
var nMaxLen = Number(document.getElementById(sPrefix+".max_length").value);
var sNewId = oCount.value;
oCount.value = String(Number(oCount.value)+1);
if (nMaxLen > 0){
if (Number(oCount.value) >= nMaxLen) {
var oAddButton = document.getElementById(sPrefix+".addbutton");
oAddButton.disabled = true;
}
}
var sNewtrId = oRow.id.replace(/_default_rowid_/g, sNewId);
trElem.id = oRow.id;
sequencetable_reName(trElem, "_default_rowid_", sNewId);
return false;
}
function sequencetable_replChild(startNode, oRegEx, sRepl){
try {
startNode.id = startNode.id.replace(oRegEx, sRepl);
} catch(E) {}
try {
startNode.name = startNode.name.replace(oRegEx, sRepl);
} catch(E) {}
//replacing in innerHTML breaks havoc
//try {
// var si = startNode.innerHTML;
// var aMatch = si.match(oRegEx);
// startNode.innerHTML = startNode.innerHTML.replace(oRegEx, sRepl);
//} catch(E) {}
for (var i = 0; i < startNode.childNodes.length; i++) {
sequencetable_replChild(startNode.childNodes[i], oRegEx, sRepl);
}
}
function sequencetable_reName(node, sOldID, sNewID){
var regexp = eval("/"+sOldID+"/g");
sequencetable_replChild(node, regexp, sNewID);
}
function sequencetable_delRow(oCell, sPrefix) {
var oCount = document.getElementById(sPrefix+".count");
var nCount = Number(oCount.value);
var nMinLen = Number(document.getElementById(sPrefix+".min_length").value);
if (nCount <= nMinLen) {
//alert("Cannot remove any more items!");
return false;
}
var node = oCell;
var regexp = eval("/"+sPrefix+"_row#(\\d+)/");
while (node.id.search(regexp) < 0) {
node = node.parentNode;
}
var oRow = node;
var sTableID = sPrefix+".tbody";
var tbodyElem = document.getElementById(sTableID);
var aMatch = node.id.match(/_row#(\d+)/);
var nToDel = Number(aMatch[1]);
oRow.parentNode.removeChild(oRow);
for (var i = nToDel+1; i < nCount; i++) {
sequencetable_reName(tbodyElem, sPrefix+"_row#"+i, sPrefix+"_row#"+(i-1));
sequencetable_reName(tbodyElem, sPrefix+"."+i+".", sPrefix+"."+(i-1)+".");
}
oCount.value = String(nCount-1);
var oAddButton = document.getElementById(sPrefix+".addbutton");
oAddButton.disabled = false;
return false;
} | z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/sequence/sequencetable.js | sequencetable.js |
======================
Autocomplete Widgets
======================
Autocomplete widgets are an alternative to normal select widgets.
>>> from z3c.widget.autocomplete.widget import AutoCompleteWidget
Let us create a vocabulary.
>>> from zope.schema.vocabulary import SimpleVocabulary
>>> from zope.publisher.browser import TestRequest
>>> from zope import schema, component, interface
>>> items = ((u'value1',1,u'Title1'),
... (u'value2',2,u'Title2'),
... (u'value3',3,u'Title3'))
>>> terms = map(lambda i: SimpleVocabulary.createTerm(*i),items)
>>> voc = SimpleVocabulary(terms)
>>> [term.title for term in voc]
[u'Title1', u'Title2', u'Title3']
>>> field = schema.Choice(__name__='foo',
... missing_value=None,
... vocabulary=voc)
>>> request = TestRequest()
>>> widget = AutoCompleteWidget(field, request)
>>> widget
<z3c.widget.autocomplete.widget.AutoCompleteWidget object at ...>
>>> print widget()
<input class="textType" id="field.foo" name="field.foo" type="text" value="" />
<div id="field.foo.target" class="autoComplete"></div>
<script type="text/javascript">
new Ajax.Autocompleter('field.foo','field.foo.target',
'http://127.0.0.1/++widget++field.foo/suggestions'
,options={
paramName: 'value'
});
</script>
Let's add some input. Note that the input must match the title of the
vocabulary term.
>>> request.form['field.foo']=u'Title1'
>>> widget.getInputValue()
u'value1'
If we have no matching title a ConversionError is raised.
>>> request.form['field.foo']=u'Unknown'
>>> widget.getInputValue()
Traceback (most recent call last):
...
ConversionError: ('Invalid value', u'Unknown')
Also the form value is the title of the term with the given value.
>>> widget._toFormValue('value1')
u'Title1'
>>> suggestions = widget.getSuggestions('Title')
>>> [title for title in suggestions]
[u'Title1', u'Title2', u'Title3']
>>> suggestions = widget.getSuggestions('Title1')
>>> [title for title in suggestions]
[u'Title1']
>>> suggestions = widget.getSuggestions('ABC')
>>> [title for title in suggestions]
[]
>>> suggestions = widget.getSuggestions('title')
>>> [title for title in suggestions]
[u'Title1', u'Title2', u'Title3']
| z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/autocomplete/README.txt | README.txt |
=======================
AutoCompleteWidget Demo
=======================
This demo packe provides a simple content class which uses the
z3c autocomplete widget.
>>> from zope.testbrowser.testing import Browser
>>> browser = Browser()
>>> browser.handleErrors = False
>>> browser.addHeader('Authorization', 'Basic mgr:mgrpw')
>>> browser.open('http://localhost/@@contents.html')
It can be added by clicking on the "Autocomplete Widget Demo" link in the
add menu. And giving it a name.
>>> link = browser.getLink('Autocomplete Widget Demo')
>>> link.click()
>>> nameCtrl = browser.getControl(name='new_value')
>>> nameCtrl.value = 'mydemo'
>>> applyCtrl = browser.getControl('Apply')
>>> applyCtrl.click()
>>> link = browser.getLink('mydemo')
>>> link.click()
>>> browser.url
'http://localhost/mydemo/@@edit.html'
Let us test the widget rendering by direct access.
>>> browser.open('http://localhost/mydemo/@@edit.html/++widget++country')
>>> print browser.contents
<input class="textType" ...
</script>
The suggestions are proveded by its own view.
>>> browser.open('http://localhost/mydemo/@@edit.html/++widget++country/suggestions')
>>> print browser.contents
>>> browser.open('http://localhost/++lang++en/mydemo/@@edit.html/++widget++country/suggestions?value=a')
>>> print browser.contents
<BLANKLINE>
<ul>
<li>Algeria</li>
<li>Andorra</li>
<li>Antigua and Barbuda</li>
<li>Afghanistan</li>
<li>Anguilla</li>
<li>Armenia</li>
<li>Albania</li>
<li>Angola</li>
<li>Antarctica</li>
<li>American Samoa</li>
<li>Argentina</li>
<li>Australia</li>
<li>Austria</li>
<li>Aruba</li>
<li>Azerbaijan</li>
</ul>
<BLANKLINE>
<BLANKLINE>
Suggestions are translated.
>>> browser.open('http://localhost/++lang++de/mydemo/@@edit.html/++widget++country/suggestions?value=a')
>>> print browser.contents
<BLANKLINE>
<ul>
<li>Amerikanische Jungferninseln</li>
<li>Amerikanisch-Ozeanien</li>
<li>Algerien</li>
<li>Andorra</li>
<li>Antigua und Barbuda</li>
<li>Afghanistan</li>
<li>Anguilla</li>
<li>Armenien</li>
<li>Albanien</li>
<li>Angola</li>
<li>Antarktis</li>
<li>Amerikanisch-Samoa</li>
<li>Argentinien</li>
<li>Australien</li>
<li>Aruba</li>
<li>Aserbaidschan</li>
</ul>
<BLANKLINE>
<BLANKLINE>
| z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/autocomplete/demo/README.txt | README.txt |
from zope.i18n.locales import locales,LOCALEDIR
from zope.interface import implements
from zope.i18n.interfaces import ITranslationDomain,INegotiator
from zope.i18nmessageid.message import MessageFactory
from zope.schema.vocabulary import SimpleVocabulary,SimpleTerm
from zope.i18n import interpolate
from zope.component import getUtility
import glob
import os
# the whole module is copied from z3c.i18n.iso
# get the locales list
# XXX maybe we should load variants too?
LANGS = []
for name in glob.glob(os.path.join(LOCALEDIR,'??.xml')):
LANGS.append(os.path.basename(name)[:2])
class DisplayNameTranslationDomain(object):
"""base class for displayname based translation domains"""
implements(ITranslationDomain)
def translate(self, msgid, mapping=None, context=None,
target_language=None, default=None):
'''See interface ITranslationDomain'''
# Find out what the target language should be
if target_language is None and context is not None:
# Let's negotiate the language to translate to. :)
negotiator = getUtility(INegotiator)
target_language = negotiator.getLanguage(LANGS, context)
# Find a translation; if nothing is found, use the default
# value
if default is None:
default = msgid
displayNames = locales.getLocale(target_language).displayNames
text = getattr(displayNames,
self.displayNameAttr).get(msgid,None)
if text is None:
text = default
return interpolate(text, mapping)
class TerritoryTranslationDomain(DisplayNameTranslationDomain):
"""a translation domain which translates territory codes
>>> d = TerritoryTranslationDomain()
>>> d.translate('DE',target_language='de')
u'Deutschland'
>>> d.translate('DE',target_language='en')
u'Germany'
"""
domain='autocomplete.demo.countries'
displayNameAttr = 'territories'
territoryTranslationDomain = TerritoryTranslationDomain()
_territories = MessageFactory(TerritoryTranslationDomain.domain)
class TerritoryVocabularyFactory(object):
"""a territory vocabulary factory
The factory has a class attribute with messages from the
iso.territory domain as titles
>>> fac = TerritoryVocabularyFactory()
>>> voc = fac(None)
>>> voc
<zope.schema.vocabulary.SimpleVocabulary object at ...>
>>> 'DE' in voc
True
>>> term = voc.getTerm('DE')
>>> term.title.default
u'Germany'
"""
def __init__(self):
self.terms = []
# excluding fallback etc
for key,value in [(key,value) for key,value in
locales.getLocale('en').displayNames.territories.items()
if key.upper()==key and len(key)==2]:
term = SimpleTerm(key,title=_territories(key,value))
self.terms.append(term)
self.vocab = SimpleVocabulary(self.terms)
def __call__(self,context):
return self.vocab
territoryVocabularyFactory = TerritoryVocabularyFactory() | z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/autocomplete/demo/countries.py | countries.py |
from zope.app.form.browser.itemswidgets import DropdownWidget
from zope.app.form.browser.itemswidgets import SelectWidget
from zope.app.form.browser.itemswidgets import RadioWidget
def _renderItemsWithValues(self, values):
"""Render the list of possible values, with those found in
`values` being marked as selected."""
cssClass = self.cssClass
# multiple items with the same value are not allowed from a
# vocabulary, so that need not be considered here
rendered_items = []
count = 0
# Handle case of missing value
missing = self._toFormValue(self.context.missing_value)
if self._displayItemForMissingValue and not self.context.required:
if missing in values:
render = self.renderSelectedItem
else:
render = self.renderItem
missing_item = render(count,
self.translate(self._messageNoValue),
missing,
self.name,
cssClass)
rendered_items.append(missing_item)
count += 1
texts = sorted([(self.textForValue(term), term)
for term in self.vocabulary])
# Render normal values
for item_text, term in texts:
if term.value in values:
render = self.renderSelectedItem
else:
render = self.renderItem
rendered_item = render(count,
item_text,
term.token,
self.name,
cssClass)
rendered_items.append(rendered_item)
count += 1
return rendered_items
class CountryInputDropdown(DropdownWidget):
def renderItemsWithValues(self, values):
"""Render the list of possible values, with those found in
`values` being marked as selected."""
return _renderItemsWithValues(self, values)
class CountryInputSelect(SelectWidget):
def renderItemsWithValues(self, values):
"""Render the list of possible values, with those found in
`values` being marked as selected."""
return _renderItemsWithValues(self, values)
class CountryInputRadio(RadioWidget):
def renderItemsWithValues(self, values):
"""Render the list of possible values, with those found in
`values` being marked as selected."""
return _renderItemsWithValues(self, values) | z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/country/widget.py | widget.py |
=========================
Country selection Widgets
=========================
This package provides widgets to select a country.
The dropdown type is registered as a default for the Country schema.
The pain was to sort the options after the translation.
Before we can start, we have to do a little bit of setup:
>>> import zope.component
>>> import zope.schema
>>> import zope.app.form.browser
>>> from z3c.widget.country.widget import CountryInputDropdown
>>> from z3c.widget.country import ICountry
>>> from z3c.i18n.iso import territoryVocabularyFactory
>>> from zope.publisher.interfaces.browser import IBrowserRequest
First we have to create a field and a request:
>>> from z3c.widget.country import Country
>>> countryFld = Country(
... __name__='country',
... title=u'Country',
... description=u'Select a Country')
>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest()
Now we can initialize the widget.
>>> class Content(object):
... country = None
>>> content = Content()
>>> boundCountry = countryFld.bind(content)
>>> widget = CountryInputDropdown(boundCountry,
... territoryVocabularyFactory(None), request)
Let's make sure that all fields have the correct value:
>>> widget.name
'field.country'
>>> widget.label
u'Country'
>>> widget.hint
u'Select a Country'
>>> widget.visible
True
Let's see how the widget is rendered:
>>> print widget()
<div>
<div class="value">
<select id="field.country" name="field.country" size="1" >
<option value="AF">Afghanistan</option>
<option value="AL">Albania</option>
<option value="DZ">Algeria</option>
...
<option value="HU">Hungary</option>
<option value="IS">Iceland</option>
<option value="IN">India</option>
...
<option value="ZM">Zambia</option>
<option value="ZW">Zimbabwe</option>
</select>
...
#Let's see the german translation:
#z3c.i18n registrations required!!!
#
# >>> request = TestRequest(HTTP_ACCEPT_LANGUAGE='de')
#
# >>> widget = CountryInputDropdown(boundCountry,
# ... territoryVocabularyFactory(None), request)
#
# >>> print widget()
# <div>
# <div class="value">
# <select id="field.country" name="field.country" size="1" >
# <option value="AF">Afghanistan</option>
# <option value="AL">Albania</option>
# <option value="DZ">Algeria</option>
# ...
# <option value="HU">Hungary</option>
# <option value="IS">Iceland</option>
# <option value="IN">India</option>
# ...
# <option value="ZM">Zambia</option>
# <option value="ZW">Zimbabwe</option>
# </select>
# ...
| z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/country/README.txt | README.txt |
__docformat__ = "reStructuredText"
try:
from zc import resourcelibrary
haveResourceLibrary = True
except ImportError:
haveResourceLibrary = False
from zope.app.form.browser import TextAreaWidget
template = """%(widget_html)s<script type="text/javascript">
tinyMCE.init({
mode : "exact", %(options)s
elements : "%(name)s"
}
);
</script>
"""
OPT_PREFIX="mce_"
OPT_PREFIX_LEN = len(OPT_PREFIX)
MCE_LANGS=[]
import glob
import os
# initialize the language files
for langFile in glob.glob(
os.path.join(os.path.dirname(__file__),'tiny_mce','langs') + '/??.js'):
MCE_LANGS.append(os.path.basename(langFile)[:2])
class TinyWidget(TextAreaWidget):
"""A WYSIWYG input widget for editing html which uses tinymce
editor.
>>> from zope.publisher.browser import TestRequest
>>> from zope.schema import Text
>>> field = Text(__name__='foo', title=u'on')
>>> request = TestRequest(
... form={'field.foo': u'Hello\\r\\nworld!'})
By default, only the needed options to MCE are passed to
the init method.
>>> widget = TinyWidget(field, request)
>>> print widget()
<textarea cols="60" id="field.foo" name="field.foo" rows="15" >Hello
world!</textarea><script type="text/javascript">
tinyMCE.init({
mode : "exact",
elements : "field.foo"
}
);
</script>
All variables defined on the object which start with ``mce_`` are
passed to the init method. Python booleans are converted
automatically to their js counterparts.
For a complete list of options see:
http://tinymce.moxiecode.com/tinymce/docs/reference_configuration.html
>>> widget = TinyWidget(field, request)
>>> widget.mce_theme="advanced"
>>> widget.mce_ask=True
>>> print widget()
<textarea ...
tinyMCE.init({
mode : "exact", ask : true, theme : "advanced",
elements : "field.foo"
}
);
</script>
Also the string literals "true" and "false" are converted to js
booleans. This is usefull for widgets created by zcml.
>>> widget = TinyWidget(field, request)
>>> widget.mce_ask='true'
>>> print widget()
<textarea ...
mode : "exact", ask : true,
...
</script>
Languages are taken from the tiny_mce/langs directory (currently
only the ones with an iso name are registered).
>>> print sorted(MCE_LANGS)
['ar', 'ca', 'cs', 'cy', 'da', 'de', 'el', 'en', 'es', 'fa', \
'fi', 'fr', 'he', 'hu', 'is', 'it', 'ja', 'ko', 'nb', 'nl', \
'nn', 'pl', 'pt', 'ru', 'si', 'sk', 'sv', 'th', 'tr', 'vi']
If the language is found it is added to the mce options. To test
this behaviour we simply set the language directly, even though it
is a readonly attribute (don't try this at home)
>>> request.locale.id.language='de'
>>> print widget()
<textarea ...
mode : "exact", ask : true, language : "de",
...
</script>
"""
def __call__(self,*args,**kw):
if haveResourceLibrary:
resourcelibrary.need('tiny_mce')
mceOptions = []
for k in dir(self):
if k.startswith(OPT_PREFIX):
v = getattr(self,k,None)
v = v==True and 'true' or v==False and 'false' or v
if v in ['true','false']:
mceOptions.append('%s : %s' % (k[OPT_PREFIX_LEN:],v))
elif v is not None:
mceOptions.append('%s : "%s"' % (k[OPT_PREFIX_LEN:],v))
mceOptions = ', '.join(mceOptions)
if mceOptions:
mceOptions += ', '
if self.request.locale.id.language in MCE_LANGS:
mceOptions += ('language : "%s", ' % \
self.request.locale.id.language)
widget_html = super(TinyWidget,self).__call__(*args,**kw)
return template % {"widget_html": widget_html,
"name": self.name,
"options": mceOptions} | z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/widget.py | widget.py |
function TinyMCE_Engine() {
this.majorVersion = "2";
this.minorVersion = "0.5.1";
this.releaseDate = "2006-03-22";
this.instances = new Array();
this.switchClassCache = new Array();
this.windowArgs = new Array();
this.loadedFiles = new Array();
this.configs = new Array();
this.currentConfig = 0;
this.eventHandlers = new Array();
// Browser check
var ua = navigator.userAgent;
this.isMSIE = (navigator.appName == "Microsoft Internet Explorer");
this.isMSIE5 = this.isMSIE && (ua.indexOf('MSIE 5') != -1);
this.isMSIE5_0 = this.isMSIE && (ua.indexOf('MSIE 5.0') != -1);
this.isGecko = ua.indexOf('Gecko') != -1;
this.isSafari = ua.indexOf('Safari') != -1;
this.isOpera = ua.indexOf('Opera') != -1;
this.isMac = ua.indexOf('Mac') != -1;
this.isNS7 = ua.indexOf('Netscape/7') != -1;
this.isNS71 = ua.indexOf('Netscape/7.1') != -1;
this.dialogCounter = 0;
this.plugins = new Array();
this.themes = new Array();
this.menus = new Array();
this.loadedPlugins = new Array();
this.buttonMap = new Array();
this.isLoaded = false;
// Fake MSIE on Opera and if Opera fakes IE, Gecko or Safari cancel those
if (this.isOpera) {
this.isMSIE = true;
this.isGecko = false;
this.isSafari = false;
}
// TinyMCE editor id instance counter
this.idCounter = 0;
};
TinyMCE_Engine.prototype = {
init : function(settings) {
var theme;
this.settings = settings;
// Check if valid browser has execcommand support
if (typeof(document.execCommand) == 'undefined')
return;
// Get script base path
if (!tinyMCE.baseURL) {
var elements = document.getElementsByTagName('script');
for (var i=0; i<elements.length; i++) {
if (elements[i].src && (elements[i].src.indexOf("tiny_mce.js") != -1 || elements[i].src.indexOf("tiny_mce_dev.js") != -1 || elements[i].src.indexOf("tiny_mce_src.js") != -1 || elements[i].src.indexOf("tiny_mce_gzip") != -1)) {
var src = elements[i].src;
tinyMCE.srcMode = (src.indexOf('_src') != -1 || src.indexOf('_dev') != -1) ? '_src' : '';
tinyMCE.gzipMode = src.indexOf('_gzip') != -1;
src = src.substring(0, src.lastIndexOf('/'));
if (settings.exec_mode == "src" || settings.exec_mode == "normal")
tinyMCE.srcMode = settings.exec_mode == "src" ? '_src' : '';
tinyMCE.baseURL = src;
break;
}
}
}
// Get document base path
this.documentBasePath = document.location.href;
if (this.documentBasePath.indexOf('?') != -1)
this.documentBasePath = this.documentBasePath.substring(0, this.documentBasePath.indexOf('?'));
this.documentURL = this.documentBasePath;
this.documentBasePath = this.documentBasePath.substring(0, this.documentBasePath.lastIndexOf('/'));
// If not HTTP absolute
if (tinyMCE.baseURL.indexOf('://') == -1 && tinyMCE.baseURL.charAt(0) != '/') {
// If site absolute
tinyMCE.baseURL = this.documentBasePath + "/" + tinyMCE.baseURL;
}
// Set default values on settings
this._def("mode", "none");
this._def("theme", "advanced");
this._def("plugins", "", true);
this._def("language", "en");
this._def("docs_language", this.settings['language']);
this._def("elements", "");
this._def("textarea_trigger", "mce_editable");
this._def("editor_selector", "");
this._def("editor_deselector", "mceNoEditor");
this._def("valid_elements", "+a[id|style|rel|rev|charset|hreflang|dir|lang|tabindex|accesskey|type|name|href|target|title|class|onfocus|onblur|onclick|ondblclick|onmousedown|onmouseup|onmouseover|onmousemove|onmouseout|onkeypress|onkeydown|onkeyup],-strong/-b[class|style],-em/-i[class|style],-strike[class|style],-u[class|style],#p[id|style|dir|class|align],-ol[class|style],-ul[class|style],-li[class|style],br,img[id|dir|lang|longdesc|usemap|style|class|src|onmouseover|onmouseout|border|alt=|title|hspace|vspace|width|height|align],-sub[style|class],-sup[style|class],-blockquote[dir|style],-table[border=0|cellspacing|cellpadding|width|height|class|align|summary|style|dir|id|lang|bgcolor|background|bordercolor],-tr[id|lang|dir|class|rowspan|width|height|align|valign|style|bgcolor|background|bordercolor],tbody[id|class],thead[id|class],tfoot[id|class],-td[id|lang|dir|class|colspan|rowspan|width|height|align|valign|style|bgcolor|background|bordercolor|scope],-th[id|lang|dir|class|colspan|rowspan|width|height|align|valign|style|scope],caption[id|lang|dir|class|style],-div[id|dir|class|align|style],-span[style|class|align],-pre[class|align|style],address[class|align|style],-h1[id|style|dir|class|align],-h2[id|style|dir|class|align],-h3[id|style|dir|class|align],-h4[id|style|dir|class|align],-h5[id|style|dir|class|align],-h6[id|style|dir|class|align],hr[class|style],-font[face|size|style|id|class|dir|color],dd[id|class|title|style|dir|lang],dl[id|class|title|style|dir|lang],dt[id|class|title|style|dir|lang]");
this._def("extended_valid_elements", "");
this._def("invalid_elements", "");
this._def("encoding", "");
this._def("urlconverter_callback", tinyMCE.getParam("urlconvertor_callback", "TinyMCE_Engine.prototype.convertURL"));
this._def("save_callback", "");
this._def("debug", false);
this._def("force_br_newlines", false);
this._def("force_p_newlines", true);
this._def("add_form_submit_trigger", true);
this._def("relative_urls", true);
this._def("remove_script_host", true);
this._def("focus_alert", true);
this._def("document_base_url", this.documentURL);
this._def("visual", true);
this._def("visual_table_class", "mceVisualAid");
this._def("setupcontent_callback", "");
this._def("fix_content_duplication", true);
this._def("custom_undo_redo", true);
this._def("custom_undo_redo_levels", -1);
this._def("custom_undo_redo_keyboard_shortcuts", true);
this._def("custom_undo_redo_restore_selection", true);
this._def("verify_html", true);
this._def("apply_source_formatting", false);
this._def("directionality", "ltr");
this._def("cleanup_on_startup", false);
this._def("inline_styles", false);
this._def("convert_newlines_to_brs", false);
this._def("auto_reset_designmode", true);
this._def("entities", "160,nbsp,161,iexcl,162,cent,163,pound,164,curren,165,yen,166,brvbar,167,sect,168,uml,169,copy,170,ordf,171,laquo,172,not,173,shy,174,reg,175,macr,176,deg,177,plusmn,178,sup2,179,sup3,180,acute,181,micro,182,para,183,middot,184,cedil,185,sup1,186,ordm,187,raquo,188,frac14,189,frac12,190,frac34,191,iquest,192,Agrave,193,Aacute,194,Acirc,195,Atilde,196,Auml,197,Aring,198,AElig,199,Ccedil,200,Egrave,201,Eacute,202,Ecirc,203,Euml,204,Igrave,205,Iacute,206,Icirc,207,Iuml,208,ETH,209,Ntilde,210,Ograve,211,Oacute,212,Ocirc,213,Otilde,214,Ouml,215,times,216,Oslash,217,Ugrave,218,Uacute,219,Ucirc,220,Uuml,221,Yacute,222,THORN,223,szlig,224,agrave,225,aacute,226,acirc,227,atilde,228,auml,229,aring,230,aelig,231,ccedil,232,egrave,233,eacute,234,ecirc,235,euml,236,igrave,237,iacute,238,icirc,239,iuml,240,eth,241,ntilde,242,ograve,243,oacute,244,ocirc,245,otilde,246,ouml,247,divide,248,oslash,249,ugrave,250,uacute,251,ucirc,252,uuml,253,yacute,254,thorn,255,yuml,402,fnof,913,Alpha,914,Beta,915,Gamma,916,Delta,917,Epsilon,918,Zeta,919,Eta,920,Theta,921,Iota,922,Kappa,923,Lambda,924,Mu,925,Nu,926,Xi,927,Omicron,928,Pi,929,Rho,931,Sigma,932,Tau,933,Upsilon,934,Phi,935,Chi,936,Psi,937,Omega,945,alpha,946,beta,947,gamma,948,delta,949,epsilon,950,zeta,951,eta,952,theta,953,iota,954,kappa,955,lambda,956,mu,957,nu,958,xi,959,omicron,960,pi,961,rho,962,sigmaf,963,sigma,964,tau,965,upsilon,966,phi,967,chi,968,psi,969,omega,977,thetasym,978,upsih,982,piv,8226,bull,8230,hellip,8242,prime,8243,Prime,8254,oline,8260,frasl,8472,weierp,8465,image,8476,real,8482,trade,8501,alefsym,8592,larr,8593,uarr,8594,rarr,8595,darr,8596,harr,8629,crarr,8656,lArr,8657,uArr,8658,rArr,8659,dArr,8660,hArr,8704,forall,8706,part,8707,exist,8709,empty,8711,nabla,8712,isin,8713,notin,8715,ni,8719,prod,8721,sum,8722,minus,8727,lowast,8730,radic,8733,prop,8734,infin,8736,ang,8743,and,8744,or,8745,cap,8746,cup,8747,int,8756,there4,8764,sim,8773,cong,8776,asymp,8800,ne,8801,equiv,8804,le,8805,ge,8834,sub,8835,sup,8836,nsub,8838,sube,8839,supe,8853,oplus,8855,otimes,8869,perp,8901,sdot,8968,lceil,8969,rceil,8970,lfloor,8971,rfloor,9001,lang,9002,rang,9674,loz,9824,spades,9827,clubs,9829,hearts,9830,diams,34,quot,38,amp,60,lt,62,gt,338,OElig,339,oelig,352,Scaron,353,scaron,376,Yuml,710,circ,732,tilde,8194,ensp,8195,emsp,8201,thinsp,8204,zwnj,8205,zwj,8206,lrm,8207,rlm,8211,ndash,8212,mdash,8216,lsquo,8217,rsquo,8218,sbquo,8220,ldquo,8221,rdquo,8222,bdquo,8224,dagger,8225,Dagger,8240,permil,8249,lsaquo,8250,rsaquo,8364,euro", true);
this._def("entity_encoding", "named");
this._def("cleanup_callback", "");
this._def("add_unload_trigger", true);
this._def("ask", false);
this._def("nowrap", false);
this._def("auto_resize", false);
this._def("auto_focus", false);
this._def("cleanup", true);
this._def("remove_linebreaks", true);
this._def("button_tile_map", false);
this._def("submit_patch", true);
this._def("browsers", "msie,safari,gecko,opera", true);
this._def("dialog_type", "window");
this._def("accessibility_warnings", true);
this._def("accessibility_focus", true);
this._def("merge_styles_invalid_parents", "");
this._def("force_hex_style_colors", true);
this._def("trim_span_elements", true);
this._def("convert_fonts_to_spans", false);
this._def("doctype", '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">');
this._def("font_size_classes", '');
this._def("font_size_style_values", 'xx-small,x-small,small,medium,large,x-large,xx-large', true);
this._def("event_elements", 'a,img', true);
this._def("convert_urls", true);
this._def("table_inline_editing", false);
this._def("object_resizing", true);
this._def("custom_shortcuts", true);
this._def("convert_on_click", false);
this._def("content_css", '');
this._def("fix_list_elements", false);
this._def("fix_table_elements", false);
// Browser check IE
if (this.isMSIE && this.settings['browsers'].indexOf('msie') == -1)
return;
// Browser check Gecko
if (this.isGecko && this.settings['browsers'].indexOf('gecko') == -1)
return;
// Browser check Safari
if (this.isSafari && this.settings['browsers'].indexOf('safari') == -1)
return;
// Browser check Opera
if (this.isOpera && this.settings['browsers'].indexOf('opera') == -1)
return;
// If not super absolute make it so
var baseHREF = tinyMCE.settings['document_base_url'];
var h = document.location.href;
var p = h.indexOf('://');
if (p > 0 && document.location.protocol != "file:") {
p = h.indexOf('/', p + 3);
h = h.substring(0, p);
if (baseHREF.indexOf('://') == -1)
baseHREF = h + baseHREF;
tinyMCE.settings['document_base_url'] = baseHREF;
tinyMCE.settings['document_base_prefix'] = h;
}
// Trim away query part
if (baseHREF.indexOf('?') != -1)
baseHREF = baseHREF.substring(0, baseHREF.indexOf('?'));
this.settings['base_href'] = baseHREF.substring(0, baseHREF.lastIndexOf('/')) + "/";
theme = this.settings['theme'];
this.blockRegExp = new RegExp("^(h[1-6]|p|div|address|pre|form|table|li|ol|ul|td|blockquote|center|dl|dir|fieldset|form|noscript|noframes|menu|isindex)$", "i");
this.posKeyCodes = new Array(13,45,36,35,33,34,37,38,39,40);
this.uniqueURL = 'http://tinymce.moxiecode.cp/mce_temp_url'; // Make unique URL non real URL
this.uniqueTag = '<div id="mceTMPElement" style="display: none">TMP</div>';
this.callbacks = new Array('onInit', 'getInfo', 'getEditorTemplate', 'setupContent', 'onChange', 'onPageLoad', 'handleNodeChange', 'initInstance', 'execCommand', 'getControlHTML', 'handleEvent', 'cleanup');
// Theme url
this.settings['theme_href'] = tinyMCE.baseURL + "/themes/" + theme;
if (!tinyMCE.isMSIE)
this.settings['force_br_newlines'] = false;
if (tinyMCE.getParam("popups_css", false)) {
var cssPath = tinyMCE.getParam("popups_css", "");
// Is relative
if (cssPath.indexOf('://') == -1 && cssPath.charAt(0) != '/')
this.settings['popups_css'] = this.documentBasePath + "/" + cssPath;
else
this.settings['popups_css'] = cssPath;
} else
this.settings['popups_css'] = tinyMCE.baseURL + "/themes/" + theme + "/css/editor_popup.css";
if (tinyMCE.getParam("editor_css", false)) {
var cssPath = tinyMCE.getParam("editor_css", "");
// Is relative
if (cssPath.indexOf('://') == -1 && cssPath.charAt(0) != '/')
this.settings['editor_css'] = this.documentBasePath + "/" + cssPath;
else
this.settings['editor_css'] = cssPath;
} else
this.settings['editor_css'] = tinyMCE.baseURL + "/themes/" + theme + "/css/editor_ui.css";
if (tinyMCE.settings['debug']) {
var msg = "Debug: \n";
msg += "baseURL: " + this.baseURL + "\n";
msg += "documentBasePath: " + this.documentBasePath + "\n";
msg += "content_css: " + this.settings['content_css'] + "\n";
msg += "popups_css: " + this.settings['popups_css'] + "\n";
msg += "editor_css: " + this.settings['editor_css'] + "\n";
alert(msg);
}
// Only do this once
if (this.configs.length == 0) {
// Is Safari enabled
if (this.isSafari && this.getParam('safari_warning', false))
alert("Safari support is very limited and should be considered experimental.\nSo there is no need to even submit bugreports on this early version.\nYou can disable this message by setting: safari_warning option to false");
if (typeof(TinyMCECompressed) == "undefined") {
tinyMCE.addEvent(window, "DOMContentLoaded", TinyMCE_Engine.prototype.onLoad);
if (tinyMCE.isMSIE && !tinyMCE.isOpera) {
if (document.body)
tinyMCE.addEvent(document.body, "readystatechange", TinyMCE_Engine.prototype.onLoad);
else
tinyMCE.addEvent(document, "readystatechange", TinyMCE_Engine.prototype.onLoad);
}
tinyMCE.addEvent(window, "load", TinyMCE_Engine.prototype.onLoad);
tinyMCE._addUnloadEvents();
}
}
this.loadScript(tinyMCE.baseURL + '/themes/' + this.settings['theme'] + '/editor_template' + tinyMCE.srcMode + '.js');
this.loadScript(tinyMCE.baseURL + '/langs/' + this.settings['language'] + '.js');
this.loadCSS(this.settings['editor_css']);
// Add plugins
var p = tinyMCE.getParam('plugins', '', true, ',');
if (p.length > 0) {
for (var i=0; i<p.length; i++) {
if (p[i].charAt(0) != '-')
this.loadScript(tinyMCE.baseURL + '/plugins/' + p[i] + '/editor_plugin' + tinyMCE.srcMode + '.js');
}
}
// Setup entities
settings['cleanup_entities'] = new Array();
var entities = tinyMCE.getParam('entities', '', true, ',');
for (var i=0; i<entities.length; i+=2)
settings['cleanup_entities']['c' + entities[i]] = entities[i+1];
// Save away this config
settings['index'] = this.configs.length;
this.configs[this.configs.length] = settings;
},
_addUnloadEvents : function() {
if (tinyMCE.isMSIE) {
if (tinyMCE.settings['add_unload_trigger']) {
tinyMCE.addEvent(window, "unload", TinyMCE_Engine.prototype.unloadHandler);
tinyMCE.addEvent(window.document, "beforeunload", TinyMCE_Engine.prototype.unloadHandler);
}
} else {
if (tinyMCE.settings['add_unload_trigger'])
tinyMCE.addEvent(window, "unload", function () {tinyMCE.triggerSave(true, true);});
}
},
_def : function(key, def_val, t) {
var v = tinyMCE.getParam(key, def_val);
v = t ? v.replace(/\s+/g,"") : v;
this.settings[key] = v;
},
hasPlugin : function(n) {
return typeof(this.plugins[n]) != "undefined" && this.plugins[n] != null;
},
addPlugin : function(n, p) {
var op = this.plugins[n];
// Use the previous plugin object base URL used when loading external plugins
p.baseURL = op ? op.baseURL : tinyMCE.baseURL + "/plugins/" + n;
this.plugins[n] = p;
},
setPluginBaseURL : function(n, u) {
var op = this.plugins[n];
if (op)
op.baseURL = u;
else
this.plugins[n] = {baseURL : u};
},
loadPlugin : function(n, u) {
u = u.indexOf('.js') != -1 ? u.substring(0, u.lastIndexOf('/')) : u;
u = u.charAt(u.length-1) == '/' ? u.substring(0, u.length-1) : u;
this.plugins[n] = {baseURL : u};
this.loadScript(u + "/editor_plugin" + (tinyMCE.srcMode ? '_src' : '') + ".js");
},
hasTheme : function(n) {
return typeof(this.themes[n]) != "undefined" && this.themes[n] != null;
},
addTheme : function(n, t) {
this.themes[n] = t;
},
addMenu : function(n, m) {
this.menus[n] = m;
},
hasMenu : function(n) {
return typeof(this.plugins[n]) != "undefined" && this.plugins[n] != null;
},
loadScript : function(url) {
for (var i=0; i<this.loadedFiles.length; i++) {
if (this.loadedFiles[i] == url)
return;
}
document.write('<sc'+'ript language="javascript" type="text/javascript" src="' + url + '"></script>');
this.loadedFiles[this.loadedFiles.length] = url;
},
loadCSS : function(url) {
var ar = url.replace(/\s+/, '').split(',');
var lflen = 0, csslen = 0;
var skip = false;
var x = 0, i = 0;
for (x = 0,csslen = ar.length; x<csslen; x++) {
ignore_css = false;
if (ar[x] != null && ar[x] != 'null' && ar[x].length > 0) {
/* Make sure it doesn't exist. */
for (i=0, lflen=this.loadedFiles.length; i<lflen; i++) {
if (this.loadedFiles[i] == ar[x]) {
skip = true;
break;
}
}
if (!skip) {
document.write('<link href="' + ar[x] + '" rel="stylesheet" type="text/css" />');
this.loadedFiles[this.loadedFiles.length] = ar[x];
}
}
}
},
importCSS : function(doc, css) {
var css_ary = css.replace(/\s+/, '').split(',');
var csslen, elm, headArr, x, css_file;
for (x = 0, csslen = css_ary.length; x<csslen; x++) {
css_file = css_ary[x];
if (css_file != null && css_file != 'null' && css_file.length > 0) {
// Is relative, make absolute
if (css_file.indexOf('://') == -1 && css_file.charAt(0) != '/')
css_file = this.documentBasePath + "/" + css_file;
if (typeof(doc.createStyleSheet) == "undefined") {
elm = doc.createElement("link");
elm.rel = "stylesheet";
elm.href = css_file;
if ((headArr = doc.getElementsByTagName("head")) != null && headArr.length > 0)
headArr[0].appendChild(elm);
} else
doc.createStyleSheet(css_file);
}
}
},
confirmAdd : function(e, settings) {
var elm = tinyMCE.isMSIE ? event.srcElement : e.target;
var elementId = elm.name ? elm.name : elm.id;
tinyMCE.settings = settings;
if (tinyMCE.settings['convert_on_click'] || (!elm.getAttribute('mce_noask') && confirm(tinyMCELang['lang_edit_confirm'])))
tinyMCE.addMCEControl(elm, elementId);
elm.setAttribute('mce_noask', 'true');
},
updateContent : function(form_element_name) {
// Find MCE instance linked to given form element and copy it's value
var formElement = document.getElementById(form_element_name);
for (var n in tinyMCE.instances) {
var inst = tinyMCE.instances[n];
if (!tinyMCE.isInstance(inst))
continue;
inst.switchSettings();
if (inst.formElement == formElement) {
var doc = inst.getDoc();
tinyMCE._setHTML(doc, inst.formElement.value);
if (!tinyMCE.isMSIE)
doc.body.innerHTML = tinyMCE._cleanupHTML(inst, doc, this.settings, doc.body, inst.visualAid);
}
}
},
addMCEControl : function(replace_element, form_element_name, target_document) {
var id = "mce_editor_" + tinyMCE.idCounter++;
var inst = new TinyMCE_Control(tinyMCE.settings);
inst.editorId = id;
this.instances[id] = inst;
inst._onAdd(replace_element, form_element_name, target_document);
},
removeMCEControl : function(editor_id) {
var inst = tinyMCE.getInstanceById(editor_id);
if (inst) {
inst.switchSettings();
editor_id = inst.editorId;
var html = tinyMCE.getContent(editor_id);
// Remove editor instance from instances array
var tmpInstances = new Array();
for (var instanceName in tinyMCE.instances) {
var instance = tinyMCE.instances[instanceName];
if (!tinyMCE.isInstance(instance))
continue;
if (instanceName != editor_id)
tmpInstances[instanceName] = instance;
}
tinyMCE.instances = tmpInstances;
tinyMCE.selectedElement = null;
tinyMCE.selectedInstance = null;
// Remove element
var replaceElement = document.getElementById(editor_id + "_parent");
var oldTargetElement = inst.oldTargetElement;
var targetName = oldTargetElement.nodeName.toLowerCase();
if (targetName == "textarea" || targetName == "input") {
// Just show the old text area
replaceElement.parentNode.removeChild(replaceElement);
oldTargetElement.style.display = "inline";
oldTargetElement.value = html;
} else {
oldTargetElement.innerHTML = html;
oldTargetElement.style.display = 'block';
replaceElement.parentNode.insertBefore(oldTargetElement, replaceElement);
replaceElement.parentNode.removeChild(replaceElement);
}
}
},
triggerSave : function(skip_cleanup, skip_callback) {
var inst, n;
// Default to false
if (typeof(skip_cleanup) == "undefined")
skip_cleanup = false;
// Default to false
if (typeof(skip_callback) == "undefined")
skip_callback = false;
// Cleanup and set all form fields
for (n in tinyMCE.instances) {
inst = tinyMCE.instances[n];
if (!tinyMCE.isInstance(inst))
continue;
inst.triggerSave(skip_cleanup, skip_callback);
}
},
resetForm : function(form_index) {
var i, inst, n, formObj = document.forms[form_index];
for (n in tinyMCE.instances) {
inst = tinyMCE.instances[n];
if (!tinyMCE.isInstance(inst))
continue;
inst.switchSettings();
for (i=0; i<formObj.elements.length; i++) {
if (inst.formTargetElementId == formObj.elements[i].name)
inst.getBody().innerHTML = inst.startContent;
}
}
},
execInstanceCommand : function(editor_id, command, user_interface, value, focus) {
var inst = tinyMCE.getInstanceById(editor_id);
if (inst) {
if (typeof(focus) == "undefined")
focus = true;
if (focus)
inst.contentWindow.focus();
// Reset design mode if lost
inst.autoResetDesignMode();
this.selectedElement = inst.getFocusElement();
this.selectedInstance = inst;
tinyMCE.execCommand(command, user_interface, value);
// Cancel event so it doesn't call onbeforeonunlaod
if (tinyMCE.isMSIE && window.event != null)
tinyMCE.cancelEvent(window.event);
}
},
execCommand : function(command, user_interface, value) {
// Default input
user_interface = user_interface ? user_interface : false;
value = value ? value : null;
if (tinyMCE.selectedInstance)
tinyMCE.selectedInstance.switchSettings();
switch (command) {
case 'mceHelp':
tinyMCE.openWindow({
file : 'about.htm',
width : 480,
height : 380
}, {
tinymce_version : tinyMCE.majorVersion + "." + tinyMCE.minorVersion,
tinymce_releasedate : tinyMCE.releaseDate,
inline : "yes"
});
return;
case 'mceFocus':
var inst = tinyMCE.getInstanceById(value);
if (inst)
inst.contentWindow.focus();
return;
case "mceAddControl":
case "mceAddEditor":
tinyMCE.addMCEControl(tinyMCE._getElementById(value), value);
return;
case "mceAddFrameControl":
tinyMCE.addMCEControl(tinyMCE._getElementById(value['element'], value['document']), value['element'], value['document']);
return;
case "mceRemoveControl":
case "mceRemoveEditor":
tinyMCE.removeMCEControl(value);
return;
case "mceResetDesignMode":
// Resets the designmode state of the editors in Gecko
if (!tinyMCE.isMSIE) {
for (var n in tinyMCE.instances) {
if (!tinyMCE.isInstance(tinyMCE.instances[n]))
continue;
try {
tinyMCE.instances[n].getDoc().designMode = "on";
} catch (e) {
// Ignore any errors
}
}
}
return;
}
if (this.selectedInstance) {
this.selectedInstance.execCommand(command, user_interface, value);
} else if (tinyMCE.settings['focus_alert'])
alert(tinyMCELang['lang_focus_alert']);
},
_createIFrame : function(replace_element, doc, win) {
var iframe, id = replace_element.getAttribute("id");
var aw, ah;
if (typeof(doc) == "undefined")
doc = document;
if (typeof(win) == "undefined")
win = window;
iframe = doc.createElement("iframe");
aw = "" + tinyMCE.settings['area_width'];
ah = "" + tinyMCE.settings['area_height'];
if (aw.indexOf('%') == -1) {
aw = parseInt(aw);
aw = aw < 0 ? 300 : aw;
aw = aw + "px";
}
if (ah.indexOf('%') == -1) {
ah = parseInt(ah);
ah = ah < 0 ? 240 : ah;
ah = ah + "px";
}
iframe.setAttribute("id", id);
iframe.setAttribute("className", "mceEditorIframe");
iframe.setAttribute("border", "0");
iframe.setAttribute("frameBorder", "0");
iframe.setAttribute("marginWidth", "0");
iframe.setAttribute("marginHeight", "0");
iframe.setAttribute("leftMargin", "0");
iframe.setAttribute("topMargin", "0");
iframe.setAttribute("width", aw);
iframe.setAttribute("height", ah);
iframe.setAttribute("allowtransparency", "true");
if (tinyMCE.settings["auto_resize"])
iframe.setAttribute("scrolling", "no");
// Must have a src element in MSIE HTTPs breaks aswell as absoute URLs
if (tinyMCE.isMSIE && !tinyMCE.isOpera)
iframe.setAttribute("src", this.settings['default_document']);
iframe.style.width = aw;
iframe.style.height = ah;
// MSIE 5.0 issue
if (tinyMCE.isMSIE && !tinyMCE.isOpera)
replace_element.outerHTML = iframe.outerHTML;
else
replace_element.parentNode.replaceChild(iframe, replace_element);
if (tinyMCE.isMSIE && !tinyMCE.isOpera)
return win.frames[id];
else
return iframe;
},
setupContent : function(editor_id) {
var inst = tinyMCE.instances[editor_id];
var doc = inst.getDoc();
var head = doc.getElementsByTagName('head').item(0);
var content = inst.startContent;
inst.switchSettings();
// Not loaded correctly hit it again, Mozilla bug #997860
if (!tinyMCE.isMSIE && tinyMCE.getParam("setupcontent_reload", false) && doc.title != "blank_page") {
// This part will remove the designMode status
// Failes first time in Firefox 1.5b2 on Mac
try {doc.location.href = tinyMCE.baseURL + "/blank.htm";} catch (ex) {}
window.setTimeout("tinyMCE.setupContent('" + editor_id + "');", 1000);
return;
}
if (!head) {
window.setTimeout("tinyMCE.setupContent('" + editor_id + "');", 10);
return;
}
// Import theme specific content CSS the user specific
tinyMCE.importCSS(inst.getDoc(), tinyMCE.baseURL + "/themes/" + inst.settings['theme'] + "/css/editor_content.css");
tinyMCE.importCSS(inst.getDoc(), inst.settings['content_css']);
tinyMCE.dispatchCallback(inst, 'init_instance_callback', 'initInstance', inst);
// Setup keyboard shortcuts
if (tinyMCE.getParam('custom_undo_redo_keyboard_shortcuts')) {
inst.addShortcut('ctrl', 'z', 'lang_undo_desc', 'Undo');
inst.addShortcut('ctrl', 'y', 'lang_redo_desc', 'Redo');
}
// Add default shortcuts for gecko
if (tinyMCE.isGecko) {
inst.addShortcut('ctrl', 'b', 'lang_bold_desc', 'Bold');
inst.addShortcut('ctrl', 'i', 'lang_italic_desc', 'Italic');
inst.addShortcut('ctrl', 'u', 'lang_underline_desc', 'Underline');
}
// Setup span styles
if (tinyMCE.getParam("convert_fonts_to_spans"))
inst.getDoc().body.setAttribute('id', 'mceSpanFonts');
if (tinyMCE.settings['nowrap'])
doc.body.style.whiteSpace = "nowrap";
doc.body.dir = this.settings['directionality'];
doc.editorId = editor_id;
// Add on document element in Mozilla
if (!tinyMCE.isMSIE)
doc.documentElement.editorId = editor_id;
inst.setBaseHREF(tinyMCE.settings['base_href']);
// Replace new line characters to BRs
if (tinyMCE.settings['convert_newlines_to_brs']) {
content = tinyMCE.regexpReplace(content, "\r\n", "<br />", "gi");
content = tinyMCE.regexpReplace(content, "\r", "<br />", "gi");
content = tinyMCE.regexpReplace(content, "\n", "<br />", "gi");
}
// Open closed anchors
// content = content.replace(new RegExp('<a(.*?)/>', 'gi'), '<a$1></a>');
// Call custom cleanup code
content = tinyMCE.storeAwayURLs(content);
content = tinyMCE._customCleanup(inst, "insert_to_editor", content);
if (tinyMCE.isMSIE) {
// Ugly!!!
window.setInterval('try{tinyMCE.getCSSClasses(tinyMCE.instances["' + editor_id + '"].getDoc(), "' + editor_id + '");}catch(e){}', 500);
if (tinyMCE.settings["force_br_newlines"])
doc.styleSheets[0].addRule("p", "margin: 0;");
var body = inst.getBody();
body.editorId = editor_id;
}
content = tinyMCE.cleanupHTMLCode(content);
// Fix for bug #958637
if (!tinyMCE.isMSIE) {
var contentElement = inst.getDoc().createElement("body");
var doc = inst.getDoc();
contentElement.innerHTML = content;
// Remove weridness!
if (tinyMCE.isGecko && tinyMCE.settings['remove_lt_gt'])
content = content.replace(new RegExp('<>', 'g'), "");
if (tinyMCE.settings['cleanup_on_startup'])
tinyMCE.setInnerHTML(inst.getBody(), tinyMCE._cleanupHTML(inst, doc, this.settings, contentElement));
else {
// Convert all strong/em to b/i
content = tinyMCE.regexpReplace(content, "<strong", "<b", "gi");
content = tinyMCE.regexpReplace(content, "<em(/?)>", "<i$1>", "gi");
content = tinyMCE.regexpReplace(content, "<em ", "<i ", "gi");
content = tinyMCE.regexpReplace(content, "</strong>", "</b>", "gi");
content = tinyMCE.regexpReplace(content, "</em>", "</i>", "gi");
tinyMCE.setInnerHTML(inst.getBody(), content);
}
tinyMCE.convertAllRelativeURLs(inst.getBody());
} else {
if (tinyMCE.settings['cleanup_on_startup']) {
tinyMCE._setHTML(inst.getDoc(), content);
// Produces permission denied error in MSIE 5.5
eval('try {tinyMCE.setInnerHTML(inst.getBody(), tinyMCE._cleanupHTML(inst, inst.contentDocument, this.settings, inst.getBody()));} catch(e) {}');
} else
tinyMCE._setHTML(inst.getDoc(), content);
}
// Fix for bug #957681
//inst.getDoc().designMode = inst.getDoc().designMode;
// Setup element references
var parentElm = inst.targetDoc.getElementById(inst.editorId + '_parent');
inst.formElement = tinyMCE.isGecko ? parentElm.previousSibling : parentElm.nextSibling;
tinyMCE.handleVisualAid(inst.getBody(), true, tinyMCE.settings['visual'], inst);
tinyMCE.dispatchCallback(inst, 'setupcontent_callback', 'setupContent', editor_id, inst.getBody(), inst.getDoc());
// Re-add design mode on mozilla
if (!tinyMCE.isMSIE)
tinyMCE.addEventHandlers(inst);
// Add blur handler
if (tinyMCE.isMSIE) {
tinyMCE.addEvent(inst.getBody(), "blur", TinyMCE_Engine.prototype._eventPatch);
tinyMCE.addEvent(inst.getBody(), "beforedeactivate", TinyMCE_Engine.prototype._eventPatch); // Bug #1439953
// Workaround for drag drop/copy paste base href bug
if (!tinyMCE.isOpera) {
tinyMCE.addEvent(doc.body, "mousemove", TinyMCE_Engine.prototype.onMouseMove);
tinyMCE.addEvent(doc.body, "beforepaste", TinyMCE_Engine.prototype._eventPatch);
tinyMCE.addEvent(doc.body, "drop", TinyMCE_Engine.prototype._eventPatch);
}
}
// Trigger node change, this call locks buttons for tables and so forth
tinyMCE.selectedInstance = inst;
tinyMCE.selectedElement = inst.contentWindow.document.body;
// Call custom DOM cleanup
tinyMCE._customCleanup(inst, "insert_to_editor_dom", inst.getBody());
tinyMCE._customCleanup(inst, "setup_content_dom", inst.getBody());
tinyMCE._setEventsEnabled(inst.getBody(), false);
tinyMCE.cleanupAnchors(inst.getDoc());
if (tinyMCE.getParam("convert_fonts_to_spans"))
tinyMCE.convertSpansToFonts(inst.getDoc());
inst.startContent = tinyMCE.trim(inst.getBody().innerHTML);
inst.undoRedo.add({ content : inst.startContent });
tinyMCE.selectedInstance = inst;
tinyMCE.triggerNodeChange(false, true);
},
storeAwayURLs : function(s) {
// Remove all mce_src, mce_href and replace them with new ones
// s = s.replace(new RegExp('mce_src\\s*=\\s*\"[^ >\"]*\"', 'gi'), '');
// s = s.replace(new RegExp('mce_href\\s*=\\s*\"[^ >\"]*\"', 'gi'), '');
if (!s.match(/(mce_src|mce_href)/gi, s)) {
s = s.replace(new RegExp('src\\s*=\\s*\"([^ >\"]*)\"', 'gi'), 'src="$1" mce_src="$1"');
s = s.replace(new RegExp('href\\s*=\\s*\"([^ >\"]*)\"', 'gi'), 'href="$1" mce_href="$1"');
}
return s;
},
removeTinyMCEFormElements : function(form_obj) {
// Check if form is valid
if (typeof(form_obj) == "undefined" || form_obj == null)
return;
// If not a form, find the form
if (form_obj.nodeName != "FORM") {
if (form_obj.form)
form_obj = form_obj.form;
else
form_obj = tinyMCE.getParentElement(form_obj, "form");
}
// Still nothing
if (form_obj == null)
return;
// Disable all UI form elements that TinyMCE created
for (var i=0; i<form_obj.elements.length; i++) {
var elementId = form_obj.elements[i].name ? form_obj.elements[i].name : form_obj.elements[i].id;
if (elementId.indexOf('mce_editor_') == 0)
form_obj.elements[i].disabled = true;
}
},
handleEvent : function(e) {
var inst = tinyMCE.selectedInstance;
// Remove odd, error
if (typeof(tinyMCE) == "undefined")
return true;
//tinyMCE.debug(e.type + " " + e.target.nodeName + " " + (e.relatedTarget ? e.relatedTarget.nodeName : ""));
if (tinyMCE.executeCallback(tinyMCE.selectedInstance, 'handle_event_callback', 'handleEvent', e))
return false;
switch (e.type) {
case "beforedeactivate": // Was added due to bug #1439953
case "blur":
if (tinyMCE.selectedInstance)
tinyMCE.selectedInstance.execCommand('mceEndTyping');
tinyMCE.hideMenus();
return;
// Workaround for drag drop/copy paste base href bug
case "drop":
case "beforepaste":
if (tinyMCE.selectedInstance)
tinyMCE.selectedInstance.setBaseHREF(null);
window.setTimeout("tinyMCE.selectedInstance.setBaseHREF(tinyMCE.settings['base_href']);", 1);
return;
case "submit":
tinyMCE.removeTinyMCEFormElements(tinyMCE.isMSIE ? window.event.srcElement : e.target);
tinyMCE.triggerSave();
tinyMCE.isNotDirty = true;
return;
case "reset":
var formObj = tinyMCE.isMSIE ? window.event.srcElement : e.target;
for (var i=0; i<document.forms.length; i++) {
if (document.forms[i] == formObj)
window.setTimeout('tinyMCE.resetForm(' + i + ');', 10);
}
return;
case "keypress":
if (inst && inst.handleShortcut(e))
return false;
if (e.target.editorId) {
tinyMCE.selectedInstance = tinyMCE.instances[e.target.editorId];
} else {
if (e.target.ownerDocument.editorId)
tinyMCE.selectedInstance = tinyMCE.instances[e.target.ownerDocument.editorId];
}
if (tinyMCE.selectedInstance)
tinyMCE.selectedInstance.switchSettings();
// Insert P element
if (tinyMCE.isGecko && tinyMCE.settings['force_p_newlines'] && e.keyCode == 13 && !e.shiftKey) {
// Insert P element instead of BR
if (TinyMCE_ForceParagraphs._insertPara(tinyMCE.selectedInstance, e)) {
// Cancel event
tinyMCE.execCommand("mceAddUndoLevel");
tinyMCE.cancelEvent(e);
return false;
}
}
// Handle backspace
if (tinyMCE.isGecko && tinyMCE.settings['force_p_newlines'] && (e.keyCode == 8 || e.keyCode == 46) && !e.shiftKey) {
// Insert P element instead of BR
if (TinyMCE_ForceParagraphs._handleBackSpace(tinyMCE.selectedInstance, e.type)) {
// Cancel event
tinyMCE.execCommand("mceAddUndoLevel");
tinyMCE.cancelEvent(e);
return false;
}
}
// Return key pressed
if (tinyMCE.isMSIE && tinyMCE.settings['force_br_newlines'] && e.keyCode == 13) {
if (e.target.editorId)
tinyMCE.selectedInstance = tinyMCE.instances[e.target.editorId];
if (tinyMCE.selectedInstance) {
var sel = tinyMCE.selectedInstance.getDoc().selection;
var rng = sel.createRange();
if (tinyMCE.getParentElement(rng.parentElement(), "li") != null)
return false;
// Cancel event
e.returnValue = false;
e.cancelBubble = true;
// Insert BR element
rng.pasteHTML("<br />");
rng.collapse(false);
rng.select();
tinyMCE.execCommand("mceAddUndoLevel");
tinyMCE.triggerNodeChange(false);
return false;
}
}
// Backspace or delete
if (e.keyCode == 8 || e.keyCode == 46) {
tinyMCE.selectedElement = e.target;
tinyMCE.linkElement = tinyMCE.getParentElement(e.target, "a");
tinyMCE.imgElement = tinyMCE.getParentElement(e.target, "img");
tinyMCE.triggerNodeChange(false);
}
return false;
break;
case "keyup":
case "keydown":
tinyMCE.hideMenus();
tinyMCE.hasMouseMoved = false;
if (inst && inst.handleShortcut(e))
return false;
if (e.target.editorId)
tinyMCE.selectedInstance = tinyMCE.instances[e.target.editorId];
else
return;
if (tinyMCE.selectedInstance)
tinyMCE.selectedInstance.switchSettings();
var inst = tinyMCE.selectedInstance;
// Handle backspace
if (tinyMCE.isGecko && tinyMCE.settings['force_p_newlines'] && (e.keyCode == 8 || e.keyCode == 46) && !e.shiftKey) {
// Insert P element instead of BR
if (TinyMCE_ForceParagraphs._handleBackSpace(tinyMCE.selectedInstance, e.type)) {
// Cancel event
tinyMCE.execCommand("mceAddUndoLevel");
e.preventDefault();
return false;
}
}
tinyMCE.selectedElement = null;
tinyMCE.selectedNode = null;
var elm = tinyMCE.selectedInstance.getFocusElement();
tinyMCE.linkElement = tinyMCE.getParentElement(elm, "a");
tinyMCE.imgElement = tinyMCE.getParentElement(elm, "img");
tinyMCE.selectedElement = elm;
// Update visualaids on tabs
if (tinyMCE.isGecko && e.type == "keyup" && e.keyCode == 9)
tinyMCE.handleVisualAid(tinyMCE.selectedInstance.getBody(), true, tinyMCE.settings['visual'], tinyMCE.selectedInstance);
// Fix empty elements on return/enter, check where enter occured
if (tinyMCE.isMSIE && e.type == "keydown" && e.keyCode == 13)
tinyMCE.enterKeyElement = tinyMCE.selectedInstance.getFocusElement();
// Fix empty elements on return/enter
if (tinyMCE.isMSIE && e.type == "keyup" && e.keyCode == 13) {
var elm = tinyMCE.enterKeyElement;
if (elm) {
var re = new RegExp('^HR|IMG|BR$','g'); // Skip these
var dre = new RegExp('^H[1-6]$','g'); // Add double on these
if (!elm.hasChildNodes() && !re.test(elm.nodeName)) {
if (dre.test(elm.nodeName))
elm.innerHTML = " ";
else
elm.innerHTML = " ";
}
}
}
// Check if it's a position key
var keys = tinyMCE.posKeyCodes;
var posKey = false;
for (var i=0; i<keys.length; i++) {
if (keys[i] == e.keyCode) {
posKey = true;
break;
}
}
// MSIE custom key handling
if (tinyMCE.isMSIE && tinyMCE.settings['custom_undo_redo']) {
var keys = new Array(8,46); // Backspace,Delete
for (var i=0; i<keys.length; i++) {
if (keys[i] == e.keyCode) {
if (e.type == "keyup")
tinyMCE.triggerNodeChange(false);
}
}
}
// If Ctrl key
if (e.keyCode == 17)
return true;
// Handle Undo/Redo when typing content
// Start typing (non position key)
if (!posKey && e.type == "keyup")
tinyMCE.execCommand("mceStartTyping");
// Store undo bookmark
if (e.type == "keydown" && (posKey || e.ctrlKey) && inst)
inst.undoBookmark = inst.selection.getBookmark();
// End typing (position key) or some Ctrl event
if (e.type == "keyup" && (posKey || e.ctrlKey))
tinyMCE.execCommand("mceEndTyping");
if (posKey && e.type == "keyup")
tinyMCE.triggerNodeChange(false);
if (tinyMCE.isMSIE && e.ctrlKey)
window.setTimeout('tinyMCE.triggerNodeChange(false);', 1);
break;
case "mousedown":
case "mouseup":
case "click":
case "focus":
tinyMCE.hideMenus();
if (tinyMCE.selectedInstance) {
tinyMCE.selectedInstance.switchSettings();
tinyMCE.selectedInstance.isFocused = true;
}
// Check instance event trigged on
var targetBody = tinyMCE.getParentElement(e.target, "body");
for (var instanceName in tinyMCE.instances) {
if (!tinyMCE.isInstance(tinyMCE.instances[instanceName]))
continue;
var inst = tinyMCE.instances[instanceName];
// Reset design mode if lost (on everything just in case)
inst.autoResetDesignMode();
if (inst.getBody() == targetBody) {
tinyMCE.selectedInstance = inst;
tinyMCE.selectedElement = e.target;
tinyMCE.linkElement = tinyMCE.getParentElement(tinyMCE.selectedElement, "a");
tinyMCE.imgElement = tinyMCE.getParentElement(tinyMCE.selectedElement, "img");
break;
}
}
// Add first bookmark location
if (!tinyMCE.selectedInstance.undoRedo.undoLevels[0].bookmark)
tinyMCE.selectedInstance.undoRedo.undoLevels[0].bookmark = tinyMCE.selectedInstance.selection.getBookmark();
if (tinyMCE.isSafari) {
tinyMCE.selectedInstance.lastSafariSelection = tinyMCE.selectedInstance.selection.getBookmark();
tinyMCE.selectedInstance.lastSafariSelectedElement = tinyMCE.selectedElement;
var lnk = tinyMCE.getParentElement(tinyMCE.selectedElement, "a");
// Patch the darned link
if (lnk && e.type == "mousedown") {
lnk.setAttribute("mce_real_href", lnk.getAttribute("href"));
lnk.setAttribute("href", "javascript:void(0);");
}
// Patch back
if (lnk && e.type == "click") {
window.setTimeout(function() {
lnk.setAttribute("href", lnk.getAttribute("mce_real_href"));
lnk.removeAttribute("mce_real_href");
}, 10);
}
}
// Reset selected node
if (e.type != "focus")
tinyMCE.selectedNode = null;
tinyMCE.triggerNodeChange(false);
tinyMCE.execCommand("mceEndTyping");
if (e.type == "mouseup")
tinyMCE.execCommand("mceAddUndoLevel");
// Just in case
if (!tinyMCE.selectedInstance && e.target.editorId)
tinyMCE.selectedInstance = tinyMCE.instances[e.target.editorId];
return false;
break;
}
},
getButtonHTML : function(id, lang, img, cmd, ui, val) {
var h = '', m, x;
cmd = 'tinyMCE.execInstanceCommand(\'{$editor_id}\',\'' + cmd + '\'';
if (typeof(ui) != "undefined" && ui != null)
cmd += ',' + ui;
if (typeof(val) != "undefined" && val != null)
cmd += ",'" + val + "'";
cmd += ');';
// Use tilemaps when enabled and found and never in MSIE since it loads the tile each time from cache if cahce is disabled
if (tinyMCE.getParam('button_tile_map') && (!tinyMCE.isMSIE || tinyMCE.isOpera) && (m = this.buttonMap[id]) != null && (tinyMCE.getParam("language") == "en" || img.indexOf('$lang') == -1)) {
// Tiled button
x = 0 - (m * 20) == 0 ? '0' : 0 - (m * 20);
h += '<a id="{$editor_id}_' + id + '" href="javascript:' + cmd + '" onclick="' + cmd + 'return false;" onmousedown="return false;" class="mceTiledButton mceButtonNormal" target="_self">';
h += '<img src="{$themeurl}/images/spacer.gif" style="background-position: ' + x + 'px 0" title="{$' + lang + '}" />';
h += '</a>';
} else {
// Normal button
h += '<a id="{$editor_id}_' + id + '" href="javascript:' + cmd + '" onclick="' + cmd + 'return false;" onmousedown="return false;" class="mceButtonNormal" target="_self">';
h += '<img src="' + img + '" title="{$' + lang + '}" />';
h += '</a>';
}
return h;
},
addButtonMap : function(m) {
var i, a = m.replace(/\s+/, '').split(',');
for (i=0; i<a.length; i++)
this.buttonMap[a[i]] = i;
},
submitPatch : function() {
tinyMCE.removeTinyMCEFormElements(this);
tinyMCE.triggerSave();
this.mceOldSubmit();
tinyMCE.isNotDirty = true;
},
onLoad : function() {
if (tinyMCE.isMSIE && !tinyMCE.isOpera && window.event.type == "readystatechange" && document.readyState != "complete")
return true;
if (tinyMCE.isLoaded)
return true;
tinyMCE.isLoaded = true;
tinyMCE.dispatchCallback(null, 'onpageload', 'onPageLoad');
for (var c=0; c<tinyMCE.configs.length; c++) {
tinyMCE.settings = tinyMCE.configs[c];
var selector = tinyMCE.getParam("editor_selector");
var deselector = tinyMCE.getParam("editor_deselector");
var elementRefAr = new Array();
// Add submit triggers
if (document.forms && tinyMCE.settings['add_form_submit_trigger'] && !tinyMCE.submitTriggers) {
for (var i=0; i<document.forms.length; i++) {
var form = document.forms[i];
tinyMCE.addEvent(form, "submit", TinyMCE_Engine.prototype.handleEvent);
tinyMCE.addEvent(form, "reset", TinyMCE_Engine.prototype.handleEvent);
tinyMCE.submitTriggers = true; // Do it only once
// Patch the form.submit function
if (tinyMCE.settings['submit_patch']) {
try {
form.mceOldSubmit = form.submit;
form.submit = TinyMCE_Engine.prototype.submitPatch;
} catch (e) {
// Do nothing
}
}
}
}
// Add editor instances based on mode
var mode = tinyMCE.settings['mode'];
switch (mode) {
case "exact":
var elements = tinyMCE.getParam('elements', '', true, ',');
for (var i=0; i<elements.length; i++) {
var element = tinyMCE._getElementById(elements[i]);
var trigger = element ? element.getAttribute(tinyMCE.settings['textarea_trigger']) : "";
if (tinyMCE.getAttrib(element, "class").indexOf(deselector) != -1)
continue;
if (trigger == "false")
continue;
if ((tinyMCE.settings['ask'] || tinyMCE.settings['convert_on_click']) && element) {
elementRefAr[elementRefAr.length] = element;
continue;
}
if (element)
tinyMCE.addMCEControl(element, elements[i]);
else if (tinyMCE.settings['debug'])
alert("Error: Could not find element by id or name: " + elements[i]);
}
break;
case "specific_textareas":
case "textareas":
var nodeList = document.getElementsByTagName("textarea");
for (var i=0; i<nodeList.length; i++) {
var elm = nodeList.item(i);
var trigger = elm.getAttribute(tinyMCE.settings['textarea_trigger']);
if (selector != '' && tinyMCE.getAttrib(elm, "class").indexOf(selector) == -1)
continue;
if (selector != '')
trigger = selector != "" ? "true" : "";
if (tinyMCE.getAttrib(elm, "class").indexOf(deselector) != -1)
continue;
if ((mode == "specific_textareas" && trigger == "true") || (mode == "textareas" && trigger != "false"))
elementRefAr[elementRefAr.length] = elm;
}
break;
}
for (var i=0; i<elementRefAr.length; i++) {
var element = elementRefAr[i];
var elementId = element.name ? element.name : element.id;
if (tinyMCE.settings['ask'] || tinyMCE.settings['convert_on_click']) {
// Focus breaks in Mozilla
if (tinyMCE.isGecko) {
var settings = tinyMCE.settings;
tinyMCE.addEvent(element, "focus", function (e) {window.setTimeout(function() {TinyMCE_Engine.prototype.confirmAdd(e, settings);}, 10);});
if (element.nodeName != "TEXTAREA" && element.nodeName != "INPUT")
tinyMCE.addEvent(element, "click", function (e) {window.setTimeout(function() {TinyMCE_Engine.prototype.confirmAdd(e, settings);}, 10);});
// tinyMCE.addEvent(element, "mouseover", function (e) {window.setTimeout(function() {TinyMCE_Engine.prototype.confirmAdd(e, settings);}, 10);});
} else {
var settings = tinyMCE.settings;
tinyMCE.addEvent(element, "focus", function () { TinyMCE_Engine.prototype.confirmAdd(null, settings); });
tinyMCE.addEvent(element, "click", function () { TinyMCE_Engine.prototype.confirmAdd(null, settings); });
// tinyMCE.addEvent(element, "mouseenter", function () { TinyMCE_Engine.prototype.confirmAdd(null, settings); });
}
} else
tinyMCE.addMCEControl(element, elementId);
}
// Handle auto focus
if (tinyMCE.settings['auto_focus']) {
window.setTimeout(function () {
var inst = tinyMCE.getInstanceById(tinyMCE.settings['auto_focus']);
inst.selection.selectNode(inst.getBody(), true, true);
inst.contentWindow.focus();
}, 10);
}
tinyMCE.dispatchCallback(null, 'oninit', 'onInit');
}
},
isInstance : function(o) {
return o != null && typeof(o) == "object" && o.isTinyMCE_Control;
},
getParam : function(name, default_value, strip_whitespace, split_chr) {
var value = (typeof(this.settings[name]) == "undefined") ? default_value : this.settings[name];
// Fix bool values
if (value == "true" || value == "false")
return (value == "true");
if (strip_whitespace)
value = tinyMCE.regexpReplace(value, "[ \t\r\n]", "");
if (typeof(split_chr) != "undefined" && split_chr != null) {
value = value.split(split_chr);
var outArray = new Array();
for (var i=0; i<value.length; i++) {
if (value[i] && value[i] != "")
outArray[outArray.length] = value[i];
}
value = outArray;
}
return value;
},
getLang : function(name, default_value, parse_entities, va) {
var v = (typeof(tinyMCELang[name]) == "undefined") ? default_value : tinyMCELang[name], n;
if (parse_entities)
v = tinyMCE.entityDecode(v);
if (va) {
for (n in va)
v = this.replaceVar(v, n, va[n]);
}
return v;
},
entityDecode : function(s) {
var e = document.createElement("div");
e.innerHTML = s;
return e.innerHTML;
},
addToLang : function(prefix, ar) {
for (var key in ar) {
if (typeof(ar[key]) == 'function')
continue;
tinyMCELang[(key.indexOf('lang_') == -1 ? 'lang_' : '') + (prefix != '' ? (prefix + "_") : '') + key] = ar[key];
}
// for (var key in ar)
// tinyMCELang[(key.indexOf('lang_') == -1 ? 'lang_' : '') + (prefix != '' ? (prefix + "_") : '') + key] = "|" + ar[key] + "|";
},
triggerNodeChange : function(focus, setup_content) {
if (tinyMCE.selectedInstance) {
var inst = tinyMCE.selectedInstance;
var editorId = inst.editorId;
var elm = (typeof(setup_content) != "undefined" && setup_content) ? tinyMCE.selectedElement : inst.getFocusElement();
var undoIndex = -1;
var undoLevels = -1;
var anySelection = false;
var selectedText = inst.selection.getSelectedText();
if (setup_content && tinyMCE.isGecko && inst.isHidden())
elm = inst.getBody();
inst.switchSettings();
if (tinyMCE.settings["auto_resize"]) {
var doc = inst.getDoc();
inst.iframeElement.style.width = doc.body.offsetWidth + "px";
inst.iframeElement.style.height = doc.body.offsetHeight + "px";
}
if (tinyMCE.selectedElement)
anySelection = (tinyMCE.selectedElement.nodeName.toLowerCase() == "img") || (selectedText && selectedText.length > 0);
if (tinyMCE.settings['custom_undo_redo']) {
undoIndex = inst.undoRedo.undoIndex;
undoLevels = inst.undoRedo.undoLevels.length;
}
tinyMCE.dispatchCallback(inst, 'handle_node_change_callback', 'handleNodeChange', editorId, elm, undoIndex, undoLevels, inst.visualAid, anySelection, setup_content);
}
if (this.selectedInstance && (typeof(focus) == "undefined" || focus))
this.selectedInstance.contentWindow.focus();
},
_customCleanup : function(inst, type, content) {
var pl, po, i;
// Call custom cleanup
var customCleanup = tinyMCE.settings['cleanup_callback'];
if (customCleanup != "" && eval("typeof(" + customCleanup + ")") != "undefined")
content = eval(customCleanup + "(type, content, inst);");
// Trigger plugin cleanups
pl = inst.plugins;
for (i=0; i<pl.length; i++) {
po = tinyMCE.plugins[pl[i]];
if (po && po.cleanup)
content = po.cleanup(type, content, inst);
}
return content;
},
setContent : function(h) {
if (tinyMCE.selectedInstance) {
tinyMCE.selectedInstance.execCommand('mceSetContent', false, h);
tinyMCE.selectedInstance.repaint();
}
},
importThemeLanguagePack : function(name) {
if (typeof(name) == "undefined")
name = tinyMCE.settings['theme'];
tinyMCE.loadScript(tinyMCE.baseURL + '/themes/' + name + '/langs/' + tinyMCE.settings['language'] + '.js');
},
importPluginLanguagePack : function(name, valid_languages) {
var lang = "en", b = tinyMCE.baseURL + '/plugins/' + name;
valid_languages = valid_languages.split(',');
for (var i=0; i<valid_languages.length; i++) {
if (tinyMCE.settings['language'] == valid_languages[i])
lang = tinyMCE.settings['language'];
}
if (this.plugins[name])
b = this.plugins[name].baseURL;
tinyMCE.loadScript(b + '/langs/' + lang + '.js');
},
applyTemplate : function(h, as) {
var i, s, ar = h.match(new RegExp('\\{\\$[a-z0-9_]+\\}', 'gi'));
if (ar && ar.length > 0) {
for (i=ar.length-1; i>=0; i--) {
s = ar[i].substring(2, ar[i].length-1);
if (s.indexOf('lang_') == 0 && tinyMCELang[s])
h = tinyMCE.replaceVar(h, s, tinyMCELang[s]);
else if (as && as[s])
h = tinyMCE.replaceVar(h, s, as[s]);
else if (tinyMCE.settings[s])
h = tinyMCE.replaceVar(h, s, tinyMCE.settings[s]);
}
}
h = tinyMCE.replaceVar(h, "themeurl", tinyMCE.themeURL);
return h;
},
replaceVar : function(h, r, v) {
return h.replace(new RegExp('{\\\$' + r + '}', 'g'), v);
},
openWindow : function(template, args) {
var html, width, height, x, y, resizable, scrollbars, url;
args['mce_template_file'] = template['file'];
args['mce_width'] = template['width'];
args['mce_height'] = template['height'];
tinyMCE.windowArgs = args;
html = template['html'];
if (!(width = parseInt(template['width'])))
width = 320;
if (!(height = parseInt(template['height'])))
height = 200;
// Add to height in M$ due to SP2 WHY DON'T YOU GUYS IMPLEMENT innerWidth of windows!!
if (tinyMCE.isMSIE)
height += 40;
else
height += 20;
x = parseInt(screen.width / 2.0) - (width / 2.0);
y = parseInt(screen.height / 2.0) - (height / 2.0);
resizable = (args && args['resizable']) ? args['resizable'] : "no";
scrollbars = (args && args['scrollbars']) ? args['scrollbars'] : "no";
if (template['file'].charAt(0) != '/' && template['file'].indexOf('://') == -1)
url = tinyMCE.baseURL + "/themes/" + tinyMCE.getParam("theme") + "/" + template['file'];
else
url = template['file'];
// Replace all args as variables in URL
for (var name in args) {
if (typeof(args[name]) == 'function')
continue;
url = tinyMCE.replaceVar(url, name, escape(args[name]));
}
if (html) {
html = tinyMCE.replaceVar(html, "css", this.settings['popups_css']);
html = tinyMCE.applyTemplate(html, args);
var win = window.open("", "mcePopup" + new Date().getTime(), "top=" + y + ",left=" + x + ",scrollbars=" + scrollbars + ",dialog=yes,minimizable=" + resizable + ",modal=yes,width=" + width + ",height=" + height + ",resizable=" + resizable);
if (win == null) {
alert(tinyMCELang['lang_popup_blocked']);
return;
}
win.document.write(html);
win.document.close();
win.resizeTo(width, height);
win.focus();
} else {
if ((tinyMCE.isMSIE && !tinyMCE.isOpera) && resizable != 'yes' && tinyMCE.settings["dialog_type"] == "modal") {
height += 10;
var features = "resizable:" + resizable
+ ";scroll:"
+ scrollbars + ";status:yes;center:yes;help:no;dialogWidth:"
+ width + "px;dialogHeight:" + height + "px;";
window.showModalDialog(url, window, features);
} else {
var modal = (resizable == "yes") ? "no" : "yes";
if (tinyMCE.isGecko && tinyMCE.isMac)
modal = "no";
if (template['close_previous'] != "no")
try {tinyMCE.lastWindow.close();} catch (ex) {}
var win = window.open(url, "mcePopup" + new Date().getTime(), "top=" + y + ",left=" + x + ",scrollbars=" + scrollbars + ",dialog=" + modal + ",minimizable=" + resizable + ",modal=" + modal + ",width=" + width + ",height=" + height + ",resizable=" + resizable);
if (win == null) {
alert(tinyMCELang['lang_popup_blocked']);
return;
}
if (template['close_previous'] != "no")
tinyMCE.lastWindow = win;
eval('try { win.resizeTo(width, height); } catch(e) { }');
// Make it bigger if statusbar is forced
if (tinyMCE.isGecko) {
if (win.document.defaultView.statusbar.visible)
win.resizeBy(0, tinyMCE.isMac ? 10 : 24);
}
win.focus();
}
}
},
closeWindow : function(win) {
win.close();
},
getVisualAidClass : function(class_name, state) {
var aidClass = tinyMCE.settings['visual_table_class'];
if (typeof(state) == "undefined")
state = tinyMCE.settings['visual'];
// Split
var classNames = new Array();
var ar = class_name.split(' ');
for (var i=0; i<ar.length; i++) {
if (ar[i] == aidClass)
ar[i] = "";
if (ar[i] != "")
classNames[classNames.length] = ar[i];
}
if (state)
classNames[classNames.length] = aidClass;
// Glue
var className = "";
for (var i=0; i<classNames.length; i++) {
if (i > 0)
className += " ";
className += classNames[i];
}
return className;
},
handleVisualAid : function(el, deep, state, inst) {
if (!el)
return;
var tableElement = null;
switch (el.nodeName) {
case "TABLE":
var oldW = el.style.width;
var oldH = el.style.height;
var bo = tinyMCE.getAttrib(el, "border");
bo = bo == "" || bo == "0" ? true : false;
tinyMCE.setAttrib(el, "class", tinyMCE.getVisualAidClass(tinyMCE.getAttrib(el, "class"), state && bo));
el.style.width = oldW;
el.style.height = oldH;
for (var y=0; y<el.rows.length; y++) {
for (var x=0; x<el.rows[y].cells.length; x++) {
var cn = tinyMCE.getVisualAidClass(tinyMCE.getAttrib(el.rows[y].cells[x], "class"), state && bo);
tinyMCE.setAttrib(el.rows[y].cells[x], "class", cn);
}
}
break;
case "A":
var anchorName = tinyMCE.getAttrib(el, "name");
if (anchorName != '' && state) {
el.title = anchorName;
el.className = 'mceItemAnchor';
} else if (anchorName != '' && !state)
el.className = '';
break;
}
if (deep && el.hasChildNodes()) {
for (var i=0; i<el.childNodes.length; i++)
tinyMCE.handleVisualAid(el.childNodes[i], deep, state, inst);
}
},
/*
applyClassesToFonts : function(doc, size) {
var f = doc.getElementsByTagName("font");
for (var i=0; i<f.length; i++) {
var s = tinyMCE.getAttrib(f[i], "size");
if (s != "")
tinyMCE.setAttrib(f[i], 'class', "mceItemFont" + s);
}
if (typeof(size) != "undefined") {
var css = "";
for (var x=0; x<doc.styleSheets.length; x++) {
for (var i=0; i<doc.styleSheets[x].rules.length; i++) {
if (doc.styleSheets[x].rules[i].selectorText == '#mceSpanFonts .mceItemFont' + size) {
css = doc.styleSheets[x].rules[i].style.cssText;
break;
}
}
if (css != "")
break;
}
if (doc.styleSheets[0].rules[0].selectorText == "FONT")
doc.styleSheets[0].removeRule(0);
doc.styleSheets[0].addRule("FONT", css, 0);
}
},
*/
fixGeckoBaseHREFBug : function(m, e, h) {
var nl, i;
if (tinyMCE.isGecko) {
if (m == 1) {
h = h.replace(/\ssrc=/gi, " xsrc=");
h = h.replace(/\shref=/gi, " xhref=");
return h;
} else {
var el = new Array('a','img','select','area','iframe','base','input','script','embed','object','link');
for (var a=0; a<el.length; a++) {
var n = e.getElementsByTagName(el[a]);
for (i=0; i<n.length; i++) {
var xsrc = tinyMCE.getAttrib(n[i], "xsrc");
var xhref = tinyMCE.getAttrib(n[i], "xhref");
if (xsrc != "") {
n[i].src = tinyMCE.convertRelativeToAbsoluteURL(tinyMCE.settings['base_href'], xsrc);
n[i].removeAttribute("xsrc");
}
if (xhref != "") {
n[i].href = tinyMCE.convertRelativeToAbsoluteURL(tinyMCE.settings['base_href'], xhref);
n[i].removeAttribute("xhref");
}
}
}
}
}
return h;
},
_setHTML : function(doc, html_content) {
// Force closed anchors open
//html_content = html_content.replace(new RegExp('<a(.*?)/>', 'gi'), '<a$1></a>');
html_content = tinyMCE.cleanupHTMLCode(html_content);
// Try innerHTML if it fails use pasteHTML in MSIE
try {
tinyMCE.setInnerHTML(doc.body, html_content);
} catch (e) {
if (this.isMSIE)
doc.body.createTextRange().pasteHTML(html_content);
}
// Content duplication bug fix
if (tinyMCE.isMSIE && tinyMCE.settings['fix_content_duplication']) {
// Remove P elements in P elements
var paras = doc.getElementsByTagName("P");
for (var i=0; i<paras.length; i++) {
var node = paras[i];
while ((node = node.parentNode) != null) {
if (node.nodeName == "P")
node.outerHTML = node.innerHTML;
}
}
// Content duplication bug fix (Seems to be word crap)
var html = doc.body.innerHTML;
/*
if (html.indexOf('="mso') != -1) {
for (var i=0; i<doc.body.all.length; i++) {
var el = doc.body.all[i];
el.removeAttribute("className","",0);
el.removeAttribute("style","",0);
}
html = doc.body.innerHTML;
html = tinyMCE.regexpReplace(html, "<o:p><\/o:p>", "<br />");
html = tinyMCE.regexpReplace(html, "<o:p> <\/o:p>", "");
html = tinyMCE.regexpReplace(html, "<st1:.*?>", "");
html = tinyMCE.regexpReplace(html, "<p><\/p>", "");
html = tinyMCE.regexpReplace(html, "<p><\/p>\r\n<p><\/p>", "");
html = tinyMCE.regexpReplace(html, "<p> <\/p>", "<br />");
html = tinyMCE.regexpReplace(html, "<p>\s*(<p>\s*)?", "<p>");
html = tinyMCE.regexpReplace(html, "<\/p>\s*(<\/p>\s*)?", "</p>");
}*/
// Always set the htmlText output
tinyMCE.setInnerHTML(doc.body, html);
}
tinyMCE.cleanupAnchors(doc);
if (tinyMCE.getParam("convert_fonts_to_spans"))
tinyMCE.convertSpansToFonts(doc);
},
getEditorId : function(form_element) {
var inst = this.getInstanceById(form_element);
if (!inst)
return null;
return inst.editorId;
},
getInstanceById : function(editor_id) {
var inst = this.instances[editor_id];
if (!inst) {
for (var n in tinyMCE.instances) {
var instance = tinyMCE.instances[n];
if (!tinyMCE.isInstance(instance))
continue;
if (instance.formTargetElementId == editor_id) {
inst = instance;
break;
}
}
}
return inst;
},
queryInstanceCommandValue : function(editor_id, command) {
var inst = tinyMCE.getInstanceById(editor_id);
if (inst)
return inst.queryCommandValue(command);
return false;
},
queryInstanceCommandState : function(editor_id, command) {
var inst = tinyMCE.getInstanceById(editor_id);
if (inst)
return inst.queryCommandState(command);
return null;
},
setWindowArg : function(n, v) {
this.windowArgs[n] = v;
},
getWindowArg : function(n, d) {
return (typeof(this.windowArgs[n]) == "undefined") ? d : this.windowArgs[n];
},
getCSSClasses : function(editor_id, doc) {
var output = new Array();
// Is cached, use that
if (typeof(tinyMCE.cssClasses) != "undefined")
return tinyMCE.cssClasses;
if (typeof(editor_id) == "undefined" && typeof(doc) == "undefined") {
var instance;
for (var instanceName in tinyMCE.instances) {
instance = tinyMCE.instances[instanceName];
if (!tinyMCE.isInstance(instance))
continue;
break;
}
doc = instance.getDoc();
}
if (typeof(doc) == "undefined") {
var instance = tinyMCE.getInstanceById(editor_id);
doc = instance.getDoc();
}
if (doc) {
var styles = tinyMCE.isMSIE ? doc.styleSheets : doc.styleSheets;
if (styles && styles.length > 0) {
for (var x=0; x<styles.length; x++) {
var csses = null;
// Just ignore any errors
eval("try {var csses = tinyMCE.isMSIE ? doc.styleSheets(" + x + ").rules : doc.styleSheets[" + x + "].cssRules;} catch(e) {}");
if (!csses)
return new Array();
for (var i=0; i<csses.length; i++) {
var selectorText = csses[i].selectorText;
// Can be multiple rules per selector
if (selectorText) {
var rules = selectorText.split(',');
for (var c=0; c<rules.length; c++) {
// Invalid rule
if (rules[c].indexOf(' ') != -1 || rules[c].indexOf(':') != -1 || rules[c].indexOf('mceItem') != -1)
continue;
if (rules[c] == "." + tinyMCE.settings['visual_table_class'] || rules[c].indexOf('mceEditable') != -1 || rules[c].indexOf('mceNonEditable') != -1)
continue;
// Is class rule
if (rules[c].indexOf('.') != -1) {
//alert(rules[c].substring(rules[c].indexOf('.')));
output[output.length] = rules[c].substring(rules[c].indexOf('.')+1);
}
}
}
}
}
}
}
// Cache em
if (output.length > 0)
tinyMCE.cssClasses = output;
return output;
},
regexpReplace : function(in_str, reg_exp, replace_str, opts) {
if (in_str == null)
return in_str;
if (typeof(opts) == "undefined")
opts = 'g';
var re = new RegExp(reg_exp, opts);
return in_str.replace(re, replace_str);
},
trim : function(s) {
return s.replace(/^\s*|\s*$/g, "");
},
cleanupEventStr : function(s) {
s = "" + s;
s = s.replace('function anonymous()\n{\n', '');
s = s.replace('\n}', '');
s = s.replace(/^return true;/gi, ''); // Remove event blocker
return s;
},
getControlHTML : function(c) {
var i, l, n, o, v;
l = tinyMCE.plugins;
for (n in l) {
o = l[n];
if (o.getControlHTML && (v = o.getControlHTML(c)) != '')
return tinyMCE.replaceVar(v, "pluginurl", o.baseURL);
}
o = tinyMCE.themes[tinyMCE.settings['theme']];
if (o.getControlHTML && (v = o.getControlHTML(c)) != '')
return v;
return '';
},
evalFunc : function(f, idx, a) {
var s = '(', i;
for (i=idx; i<a.length; i++) {
s += 'a[' + i + ']';
if (i < a.length-1)
s += ',';
}
s += ');';
return eval("f" + s);
},
dispatchCallback : function(i, p, n) {
return this.callFunc(i, p, n, 0, this.dispatchCallback.arguments);
},
executeCallback : function(i, p, n) {
return this.callFunc(i, p, n, 1, this.executeCallback.arguments);
},
execCommandCallback : function(i, p, n) {
return this.callFunc(i, p, n, 2, this.execCommandCallback.arguments);
},
callFunc : function(ins, p, n, m, a) {
var l, i, on, o, s, v;
s = m == 2;
l = tinyMCE.getParam(p, '');
if (l != '' && (v = tinyMCE.evalFunc(typeof(l) == "function" ? l : eval(l), 3, a)) == s && m > 0)
return true;
if (ins != null) {
for (i=0, l = ins.plugins; i<l.length; i++) {
o = tinyMCE.plugins[l[i]];
if (o[n] && (v = tinyMCE.evalFunc(o[n], 3, a)) == s && m > 0)
return true;
}
}
l = tinyMCE.themes;
for (on in l) {
o = l[on];
if (o[n] && (v = tinyMCE.evalFunc(o[n], 3, a)) == s && m > 0)
return true;
}
return false;
},
xmlEncode : function(s) {
s = "" + s;
s = s.replace(/&/g, '&');
s = s.replace(new RegExp('"', 'g'), '"');
s = s.replace(/\'/g, '''); // ' is not working in MSIE
s = s.replace(/</g, '<');
s = s.replace(/>/g, '>');
return s;
},
extend : function(p, np) {
var o = {};
o.parent = p;
for (n in p)
o[n] = p[n];
for (n in np)
o[n] = np[n];
return o;
},
hideMenus : function() {
var e = tinyMCE.lastSelectedMenuBtn;
if (tinyMCE.lastMenu) {
tinyMCE.lastMenu.hide();
tinyMCE.lastMenu = null;
}
if (e) {
tinyMCE.switchClass(e, tinyMCE.lastMenuBtnClass);
tinyMCE.lastSelectedMenuBtn = null;
}
}
};
// Global instances
var TinyMCE = TinyMCE_Engine; // Compatiblity with gzip compressors
var tinyMCE = new TinyMCE_Engine();
var tinyMCELang = {};
/* file:jscripts/tiny_mce/classes/TinyMCE_Control.class.js */
function TinyMCE_Control(settings) {
var t, i, to, fu, p, x, fn, fu, pn, s = settings;
this.undoRedoLevel = true;
this.isTinyMCE_Control = true;
// Default settings
this.settings = s;
this.settings['theme'] = tinyMCE.getParam("theme", "default");
this.settings['width'] = tinyMCE.getParam("width", -1);
this.settings['height'] = tinyMCE.getParam("height", -1);
this.selection = new TinyMCE_Selection(this);
this.undoRedo = new TinyMCE_UndoRedo(this);
this.cleanup = new TinyMCE_Cleanup();
this.shortcuts = new Array();
this.hasMouseMoved = false;
this.cleanup.init({
valid_elements : s.valid_elements,
extended_valid_elements : s.extended_valid_elements,
entities : s.entities,
entity_encoding : s.entity_encoding,
debug : s.cleanup_debug,
url_converter : 'TinyMCE_Cleanup.prototype._urlConverter',
indent : s.apply_source_formatting,
invalid_elements : s.invalid_elements,
verify_html : s.verify_html,
fix_content_duplication : s.fix_content_duplication
});
// Wrap old theme
t = this.settings['theme'];
if (!tinyMCE.hasTheme(t)) {
fn = tinyMCE.callbacks;
to = {};
for (i=0; i<fn.length; i++) {
if ((fu = window['TinyMCE_' + t + "_" + fn[i]]))
to[fn[i]] = fu;
}
tinyMCE.addTheme(t, to);
}
// Wrap old plugins
this.plugins = new Array();
p = tinyMCE.getParam('plugins', '', true, ',');
if (p.length > 0) {
for (i=0; i<p.length; i++) {
pn = p[i];
if (pn.charAt(0) == '-')
pn = pn.substring(1);
if (!tinyMCE.hasPlugin(pn)) {
fn = tinyMCE.callbacks;
to = {};
for (x=0; x<fn.length; x++) {
if ((fu = window['TinyMCE_' + pn + "_" + fn[x]]))
to[fn[x]] = fu;
}
tinyMCE.addPlugin(pn, to);
}
this.plugins[this.plugins.length] = pn;
}
}
};
TinyMCE_Control.prototype = {
hasPlugin : function(n) {
var i;
for (i=0; i<this.plugins.length; i++) {
if (this.plugins[i] == n)
return true;
}
return false;
},
addPlugin : function(n, p) {
if (!this.hasPlugin(n)) {
tinyMCE.addPlugin(n, p);
this.plugins[this.plugins.length] = n;
}
},
repaint : function() {
if (tinyMCE.isMSIE && !tinyMCE.isOpera)
return;
try {
var s = this.selection;
var b = s.getBookmark(true);
this.getBody().style.display = 'none';
this.getDoc().execCommand('selectall', false, null);
this.getSel().collapseToStart();
this.getBody().style.display = 'block';
s.moveToBookmark(b);
} catch (ex) {
// Ignore
}
},
switchSettings : function() {
if (tinyMCE.configs.length > 1 && tinyMCE.currentConfig != this.settings['index']) {
tinyMCE.settings = this.settings;
tinyMCE.currentConfig = this.settings['index'];
}
},
getBody : function() {
return this.getDoc().body;
},
getDoc : function() {
return this.contentWindow.document;
},
getWin : function() {
return this.contentWindow;
},
addShortcut : function(m, k, d, cmd, ui, va) {
var n = typeof(k) == "number", ie = tinyMCE.isMSIE, c, sc, i;
var scl = this.shortcuts;
if (!tinyMCE.getParam('custom_shortcuts'))
return false;
m = m.toLowerCase();
k = ie && !n ? k.toUpperCase() : k;
c = n ? null : k.charCodeAt(0);
d = d && d.indexOf('lang_') == 0 ? tinyMCE.getLang(d) : d;
sc = {
alt : m.indexOf('alt') != -1,
ctrl : m.indexOf('ctrl') != -1,
shift : m.indexOf('shift') != -1,
charCode : c,
keyCode : n ? k : (ie ? c : null),
desc : d,
cmd : cmd,
ui : ui,
val : va
};
for (i=0; i<scl.length; i++) {
if (sc.alt == scl[i].alt && sc.ctrl == scl[i].ctrl && sc.shift == scl[i].shift
&& sc.charCode == scl[i].charCode && sc.keyCode == scl[i].keyCode) {
return false;
}
}
scl[scl.length] = sc;
return true;
},
handleShortcut : function(e) {
var i, s = this.shortcuts, o;
for (i=0; i<s.length; i++) {
o = s[i];
if (o.alt == e.altKey && o.ctrl == e.ctrlKey && (o.keyCode == e.keyCode || o.charCode == e.charCode)) {
if (o.cmd && (e.type == "keydown" || (e.type == "keypress" && !tinyMCE.isOpera)))
tinyMCE.execCommand(o.cmd, o.ui, o.val);
tinyMCE.cancelEvent(e);
return true;
}
}
return false;
},
autoResetDesignMode : function() {
// Add fix for tab/style.display none/block problems in Gecko
if (!tinyMCE.isMSIE && this.isHidden() && tinyMCE.getParam('auto_reset_designmode'))
eval('try { this.getDoc().designMode = "On"; } catch(e) {}');
},
isHidden : function() {
if (tinyMCE.isMSIE)
return false;
var s = this.getSel();
// Weird, wheres that cursor selection?
return (!s || !s.rangeCount || s.rangeCount == 0);
},
isDirty : function() {
// Is content modified and not in a submit procedure
return this.startContent != tinyMCE.trim(this.getBody().innerHTML) && !tinyMCE.isNotDirty;
},
_mergeElements : function(scmd, pa, ch, override) {
if (scmd == "removeformat") {
pa.className = "";
pa.style.cssText = "";
ch.className = "";
ch.style.cssText = "";
return;
}
var st = tinyMCE.parseStyle(tinyMCE.getAttrib(pa, "style"));
var stc = tinyMCE.parseStyle(tinyMCE.getAttrib(ch, "style"));
var className = tinyMCE.getAttrib(pa, "class");
className += " " + tinyMCE.getAttrib(ch, "class");
if (override) {
for (var n in st) {
if (typeof(st[n]) == 'function')
continue;
stc[n] = st[n];
}
} else {
for (var n in stc) {
if (typeof(stc[n]) == 'function')
continue;
st[n] = stc[n];
}
}
tinyMCE.setAttrib(pa, "style", tinyMCE.serializeStyle(st));
tinyMCE.setAttrib(pa, "class", tinyMCE.trim(className));
ch.className = "";
ch.style.cssText = "";
ch.removeAttribute("class");
ch.removeAttribute("style");
},
_setUseCSS : function(b) {
var d = this.getDoc();
try {d.execCommand("useCSS", false, !b);} catch (ex) {}
try {d.execCommand("styleWithCSS", false, b);} catch (ex) {}
if (!tinyMCE.getParam("table_inline_editing"))
try {d.execCommand('enableInlineTableEditing', false, "false");} catch (ex) {}
if (!tinyMCE.getParam("object_resizing"))
try {d.execCommand('enableObjectResizing', false, "false");} catch (ex) {}
},
execCommand : function(command, user_interface, value) {
var doc = this.getDoc();
var win = this.getWin();
var focusElm = this.getFocusElement();
// Is non udno specific command
if (!new RegExp('mceStartTyping|mceEndTyping|mceBeginUndoLevel|mceEndUndoLevel|mceAddUndoLevel', 'gi').test(command))
this.undoBookmark = null;
if (this.lastSafariSelection && !new RegExp('mceStartTyping|mceEndTyping|mceBeginUndoLevel|mceEndUndoLevel|mceAddUndoLevel', 'gi').test(command)) {
this.selection.moveToBookmark(this.lastSafariSelection);
tinyMCE.selectedElement = this.lastSafariSelectedElement;
}
// Mozilla issue
if (!tinyMCE.isMSIE && !this.useCSS) {
this._setUseCSS(false);
this.useCSS = true;
}
//debug("command: " + command + ", user_interface: " + user_interface + ", value: " + value);
this.contentDocument = doc; // <-- Strange, unless this is applied Mozilla 1.3 breaks
if (tinyMCE.execCommandCallback(this, 'execcommand_callback', 'execCommand', this.editorId, this.getBody(), command, user_interface, value))
return;
// Fix align on images
if (focusElm && focusElm.nodeName == "IMG") {
var align = focusElm.getAttribute('align');
var img = command == "JustifyCenter" ? focusElm.cloneNode(false) : focusElm;
switch (command) {
case "JustifyLeft":
if (align == 'left')
img.removeAttribute('align');
else
img.setAttribute('align', 'left');
// Remove the div
var div = focusElm.parentNode;
if (div && div.nodeName == "DIV" && div.childNodes.length == 1 && div.parentNode)
div.parentNode.replaceChild(img, div);
this.selection.selectNode(img);
this.repaint();
tinyMCE.triggerNodeChange();
return;
case "JustifyCenter":
img.removeAttribute('align');
// Is centered
var div = tinyMCE.getParentElement(focusElm, "div");
if (div && div.style.textAlign == "center") {
// Remove div
if (div.nodeName == "DIV" && div.childNodes.length == 1 && div.parentNode)
div.parentNode.replaceChild(img, div);
} else {
// Add div
var div = this.getDoc().createElement("div");
div.style.textAlign = 'center';
div.appendChild(img);
focusElm.parentNode.replaceChild(div, focusElm);
}
this.selection.selectNode(img);
this.repaint();
tinyMCE.triggerNodeChange();
return;
case "JustifyRight":
if (align == 'right')
img.removeAttribute('align');
else
img.setAttribute('align', 'right');
// Remove the div
var div = focusElm.parentNode;
if (div && div.nodeName == "DIV" && div.childNodes.length == 1 && div.parentNode)
div.parentNode.replaceChild(img, div);
this.selection.selectNode(img);
this.repaint();
tinyMCE.triggerNodeChange();
return;
}
}
if (tinyMCE.settings['force_br_newlines']) {
var alignValue = "";
if (doc.selection.type != "Control") {
switch (command) {
case "JustifyLeft":
alignValue = "left";
break;
case "JustifyCenter":
alignValue = "center";
break;
case "JustifyFull":
alignValue = "justify";
break;
case "JustifyRight":
alignValue = "right";
break;
}
if (alignValue != "") {
var rng = doc.selection.createRange();
if ((divElm = tinyMCE.getParentElement(rng.parentElement(), "div")) != null)
divElm.setAttribute("align", alignValue);
else if (rng.pasteHTML && rng.htmlText.length > 0)
rng.pasteHTML('<div align="' + alignValue + '">' + rng.htmlText + "</div>");
tinyMCE.triggerNodeChange();
return;
}
}
}
switch (command) {
case "mceRepaint":
this.repaint();
return true;
case "InsertUnorderedList":
case "InsertOrderedList":
var tag = (command == "InsertUnorderedList") ? "ul" : "ol";
if (tinyMCE.isSafari)
this.execCommand("mceInsertContent", false, "<" + tag + "><li> </li><" + tag + ">");
else
this.getDoc().execCommand(command, user_interface, value);
tinyMCE.triggerNodeChange();
break;
case "Strikethrough":
if (tinyMCE.isSafari)
this.execCommand("mceInsertContent", false, "<strike>" + this.selection.getSelectedHTML() + "</strike>");
else
this.getDoc().execCommand(command, user_interface, value);
tinyMCE.triggerNodeChange();
break;
case "mceSelectNode":
this.selection.selectNode(value);
tinyMCE.triggerNodeChange();
tinyMCE.selectedNode = value;
break;
case "FormatBlock":
if (value == null || value == "") {
var elm = tinyMCE.getParentElement(this.getFocusElement(), "p,div,h1,h2,h3,h4,h5,h6,pre,address");
if (elm)
this.execCommand("mceRemoveNode", false, elm);
} else {
if (value == '<div>' && tinyMCE.isGecko)
value = 'div';
this.getDoc().execCommand("FormatBlock", false, value);
}
tinyMCE.triggerNodeChange();
break;
case "mceRemoveNode":
if (!value)
value = tinyMCE.getParentElement(this.getFocusElement());
if (tinyMCE.isMSIE) {
value.outerHTML = value.innerHTML;
} else {
var rng = value.ownerDocument.createRange();
rng.setStartBefore(value);
rng.setEndAfter(value);
rng.deleteContents();
rng.insertNode(rng.createContextualFragment(value.innerHTML));
}
tinyMCE.triggerNodeChange();
break;
case "mceSelectNodeDepth":
var parentNode = this.getFocusElement();
for (var i=0; parentNode; i++) {
if (parentNode.nodeName.toLowerCase() == "body")
break;
if (parentNode.nodeName.toLowerCase() == "#text") {
i--;
parentNode = parentNode.parentNode;
continue;
}
if (i == value) {
this.selection.selectNode(parentNode, false);
tinyMCE.triggerNodeChange();
tinyMCE.selectedNode = parentNode;
return;
}
parentNode = parentNode.parentNode;
}
break;
case "SetStyleInfo":
var rng = this.getRng();
var sel = this.getSel();
var scmd = value['command'];
var sname = value['name'];
var svalue = value['value'] == null ? '' : value['value'];
//var svalue = value['value'] == null ? '' : value['value'];
var wrapper = value['wrapper'] ? value['wrapper'] : "span";
var parentElm = null;
var invalidRe = new RegExp("^BODY|HTML$", "g");
var invalidParentsRe = tinyMCE.settings['merge_styles_invalid_parents'] != '' ? new RegExp(tinyMCE.settings['merge_styles_invalid_parents'], "gi") : null;
// Whole element selected check
if (tinyMCE.isMSIE) {
// Control range
if (rng.item)
parentElm = rng.item(0);
else {
var pelm = rng.parentElement();
var prng = doc.selection.createRange();
prng.moveToElementText(pelm);
if (rng.htmlText == prng.htmlText || rng.boundingWidth == 0) {
if (invalidParentsRe == null || !invalidParentsRe.test(pelm.nodeName))
parentElm = pelm;
}
}
} else {
var felm = this.getFocusElement();
if (sel.isCollapsed || (new RegExp('td|tr|tbody|table', 'gi').test(felm.nodeName) && sel.anchorNode == felm.parentNode))
parentElm = felm;
}
// Whole element selected
if (parentElm && !invalidRe.test(parentElm.nodeName)) {
if (scmd == "setstyle")
tinyMCE.setStyleAttrib(parentElm, sname, svalue);
if (scmd == "setattrib")
tinyMCE.setAttrib(parentElm, sname, svalue);
if (scmd == "removeformat") {
parentElm.style.cssText = '';
tinyMCE.setAttrib(parentElm, 'class', '');
}
// Remove style/attribs from all children
var ch = tinyMCE.getNodeTree(parentElm, new Array(), 1);
for (var z=0; z<ch.length; z++) {
if (ch[z] == parentElm)
continue;
if (scmd == "setstyle")
tinyMCE.setStyleAttrib(ch[z], sname, '');
if (scmd == "setattrib")
tinyMCE.setAttrib(ch[z], sname, '');
if (scmd == "removeformat") {
ch[z].style.cssText = '';
tinyMCE.setAttrib(ch[z], 'class', '');
}
}
} else {
this._setUseCSS(false); // Bug in FF when running in fullscreen
doc.execCommand("FontName", false, "#mce_temp_font#");
var elementArray = tinyMCE.getElementsByAttributeValue(this.getBody(), "font", "face", "#mce_temp_font#");
// Change them all
for (var x=0; x<elementArray.length; x++) {
elm = elementArray[x];
if (elm) {
var spanElm = doc.createElement(wrapper);
if (scmd == "setstyle")
tinyMCE.setStyleAttrib(spanElm, sname, svalue);
if (scmd == "setattrib")
tinyMCE.setAttrib(spanElm, sname, svalue);
if (scmd == "removeformat") {
spanElm.style.cssText = '';
tinyMCE.setAttrib(spanElm, 'class', '');
}
if (elm.hasChildNodes()) {
for (var i=0; i<elm.childNodes.length; i++)
spanElm.appendChild(elm.childNodes[i].cloneNode(true));
}
spanElm.setAttribute("mce_new", "true");
elm.parentNode.replaceChild(spanElm, elm);
// Remove style/attribs from all children
var ch = tinyMCE.getNodeTree(spanElm, new Array(), 1);
for (var z=0; z<ch.length; z++) {
if (ch[z] == spanElm)
continue;
if (scmd == "setstyle")
tinyMCE.setStyleAttrib(ch[z], sname, '');
if (scmd == "setattrib")
tinyMCE.setAttrib(ch[z], sname, '');
if (scmd == "removeformat") {
ch[z].style.cssText = '';
tinyMCE.setAttrib(ch[z], 'class', '');
}
}
}
}
}
// Cleaup wrappers
var nodes = doc.getElementsByTagName(wrapper);
for (var i=nodes.length-1; i>=0; i--) {
var elm = nodes[i];
var isNew = tinyMCE.getAttrib(elm, "mce_new") == "true";
elm.removeAttribute("mce_new");
// Is only child a element
if (elm.childNodes && elm.childNodes.length == 1 && elm.childNodes[0].nodeType == 1) {
//tinyMCE.debug("merge1" + isNew);
this._mergeElements(scmd, elm, elm.childNodes[0], isNew);
continue;
}
// Is I the only child
if (elm.parentNode.childNodes.length == 1 && !invalidRe.test(elm.nodeName) && !invalidRe.test(elm.parentNode.nodeName)) {
//tinyMCE.debug("merge2" + isNew + "," + elm.nodeName + "," + elm.parentNode.nodeName);
if (invalidParentsRe == null || !invalidParentsRe.test(elm.parentNode.nodeName))
this._mergeElements(scmd, elm.parentNode, elm, false);
}
}
// Remove empty wrappers
var nodes = doc.getElementsByTagName(wrapper);
for (var i=nodes.length-1; i>=0; i--) {
var elm = nodes[i];
var isEmpty = true;
// Check if it has any attribs
var tmp = doc.createElement("body");
tmp.appendChild(elm.cloneNode(false));
// Is empty span, remove it
tmp.innerHTML = tmp.innerHTML.replace(new RegExp('style=""|class=""', 'gi'), '');
//tinyMCE.debug(tmp.innerHTML);
if (new RegExp('<span>', 'gi').test(tmp.innerHTML)) {
for (var x=0; x<elm.childNodes.length; x++) {
if (elm.parentNode != null)
elm.parentNode.insertBefore(elm.childNodes[x].cloneNode(true), elm);
}
elm.parentNode.removeChild(elm);
}
}
// Re add the visual aids
if (scmd == "removeformat")
tinyMCE.handleVisualAid(this.getBody(), true, this.visualAid, this);
tinyMCE.triggerNodeChange();
break;
case "FontName":
if (value == null) {
var s = this.getSel();
// Find font and select it
if (tinyMCE.isGecko && s.isCollapsed) {
var f = tinyMCE.getParentElement(this.getFocusElement(), "font");
if (f != null)
this.selection.selectNode(f, false);
}
// Remove format
this.getDoc().execCommand("RemoveFormat", false, null);
// Collapse range if font was found
if (f != null && tinyMCE.isGecko) {
var r = this.getRng().cloneRange();
r.collapse(true);
s.removeAllRanges();
s.addRange(r);
}
} else
this.getDoc().execCommand('FontName', false, value);
if (tinyMCE.isGecko)
window.setTimeout('tinyMCE.triggerNodeChange(false);', 1);
return;
case "FontSize":
this.getDoc().execCommand('FontSize', false, value);
if (tinyMCE.isGecko)
window.setTimeout('tinyMCE.triggerNodeChange(false);', 1);
return;
case "forecolor":
this.getDoc().execCommand('forecolor', false, value);
break;
case "HiliteColor":
if (tinyMCE.isGecko) {
this._setUseCSS(true);
this.getDoc().execCommand('hilitecolor', false, value);
this._setUseCSS(false);
} else
this.getDoc().execCommand('BackColor', false, value);
break;
case "Cut":
case "Copy":
case "Paste":
var cmdFailed = false;
// Try executing command
eval('try {this.getDoc().execCommand(command, user_interface, value);} catch (e) {cmdFailed = true;}');
if (tinyMCE.isOpera && cmdFailed)
alert('Currently not supported by your browser, use keyboard shortcuts instead.');
// Alert error in gecko if command failed
if (tinyMCE.isGecko && cmdFailed) {
// Confirm more info
if (confirm(tinyMCE.entityDecode(tinyMCE.getLang('lang_clipboard_msg'))))
window.open('http://www.mozilla.org/editor/midasdemo/securityprefs.html', 'mceExternal');
return;
} else
tinyMCE.triggerNodeChange();
break;
case "mceSetContent":
if (!value)
value = "";
// Call custom cleanup code
value = tinyMCE.storeAwayURLs(value);
value = tinyMCE._customCleanup(this, "insert_to_editor", value);
tinyMCE._setHTML(doc, value);
tinyMCE.setInnerHTML(doc.body, tinyMCE._cleanupHTML(this, doc, tinyMCE.settings, doc.body));
tinyMCE.convertAllRelativeURLs(doc.body);
// When editing always use fonts internaly
if (tinyMCE.getParam("convert_fonts_to_spans"))
tinyMCE.convertSpansToFonts(doc);
tinyMCE.handleVisualAid(doc.body, true, this.visualAid, this);
tinyMCE._setEventsEnabled(doc.body, false);
return true;
case "mceCleanup":
var b = this.selection.getBookmark();
tinyMCE._setHTML(this.contentDocument, this.getBody().innerHTML);
tinyMCE.setInnerHTML(this.getBody(), tinyMCE._cleanupHTML(this, this.contentDocument, this.settings, this.getBody(), this.visualAid));
tinyMCE.convertAllRelativeURLs(doc.body);
// When editing always use fonts internaly
if (tinyMCE.getParam("convert_fonts_to_spans"))
tinyMCE.convertSpansToFonts(doc);
tinyMCE.handleVisualAid(this.getBody(), true, this.visualAid, this);
tinyMCE._setEventsEnabled(this.getBody(), false);
this.repaint();
this.selection.moveToBookmark(b);
tinyMCE.triggerNodeChange();
break;
case "mceReplaceContent":
// Force empty string
if (!value)
value = '';
this.getWin().focus();
var selectedText = "";
if (tinyMCE.isMSIE) {
var rng = doc.selection.createRange();
selectedText = rng.text;
} else
selectedText = this.getSel().toString();
if (selectedText.length > 0) {
value = tinyMCE.replaceVar(value, "selection", selectedText);
tinyMCE.execCommand('mceInsertContent', false, value);
}
tinyMCE.triggerNodeChange();
break;
case "mceSetAttribute":
if (typeof(value) == 'object') {
var targetElms = (typeof(value['targets']) == "undefined") ? "p,img,span,div,td,h1,h2,h3,h4,h5,h6,pre,address" : value['targets'];
var targetNode = tinyMCE.getParentElement(this.getFocusElement(), targetElms);
if (targetNode) {
targetNode.setAttribute(value['name'], value['value']);
tinyMCE.triggerNodeChange();
}
}
break;
case "mceSetCSSClass":
this.execCommand("SetStyleInfo", false, {command : "setattrib", name : "class", value : value});
break;
case "mceInsertRawHTML":
var key = 'tiny_mce_marker';
this.execCommand('mceBeginUndoLevel');
// Insert marker key
this.execCommand('mceInsertContent', false, key);
// Store away scroll pos
var scrollX = this.getDoc().body.scrollLeft + this.getDoc().documentElement.scrollLeft;
var scrollY = this.getDoc().body.scrollTop + this.getDoc().documentElement.scrollTop;
// Find marker and replace with RAW HTML
var html = this.getBody().innerHTML;
if ((pos = html.indexOf(key)) != -1)
tinyMCE.setInnerHTML(this.getBody(), html.substring(0, pos) + value + html.substring(pos + key.length));
// Restore scoll pos
this.contentWindow.scrollTo(scrollX, scrollY);
this.execCommand('mceEndUndoLevel');
break;
case "mceInsertContent":
// Force empty string
if (!value)
value = '';
var insertHTMLFailed = false;
this.getWin().focus();
if (tinyMCE.isGecko || tinyMCE.isOpera) {
try {
// Is plain text or HTML, &, etc will be encoded wrong in FF
if (value.indexOf('<') == -1 && !value.match(/(&| |<|>)/g)) {
var r = this.getRng();
var n = this.getDoc().createTextNode(tinyMCE.entityDecode(value));
var s = this.getSel();
var r2 = r.cloneRange();
// Insert text at cursor position
s.removeAllRanges();
r.deleteContents();
r.insertNode(n);
// Move the cursor to the end of text
r2.selectNode(n);
r2.collapse(false);
s.removeAllRanges();
s.addRange(r2);
} else {
value = tinyMCE.fixGeckoBaseHREFBug(1, this.getDoc(), value);
this.getDoc().execCommand('inserthtml', false, value);
tinyMCE.fixGeckoBaseHREFBug(2, this.getDoc(), value);
}
} catch (ex) {
insertHTMLFailed = true;
}
if (!insertHTMLFailed) {
tinyMCE.triggerNodeChange();
return;
}
}
// Ugly hack in Opera due to non working "inserthtml"
if (tinyMCE.isOpera && insertHTMLFailed) {
this.getDoc().execCommand("insertimage", false, tinyMCE.uniqueURL);
var ar = tinyMCE.getElementsByAttributeValue(this.getBody(), "img", "src", tinyMCE.uniqueURL);
ar[0].outerHTML = value;
return;
}
if (!tinyMCE.isMSIE) {
var isHTML = value.indexOf('<') != -1;
var sel = this.getSel();
var rng = this.getRng();
if (isHTML) {
if (tinyMCE.isSafari) {
var tmpRng = this.getDoc().createRange();
tmpRng.setStart(this.getBody(), 0);
tmpRng.setEnd(this.getBody(), 0);
value = tmpRng.createContextualFragment(value);
} else
value = rng.createContextualFragment(value);
} else {
// Setup text node
var el = document.createElement("div");
el.innerHTML = value;
value = el.firstChild.nodeValue;
value = doc.createTextNode(value);
}
// Insert plain text in Safari
if (tinyMCE.isSafari && !isHTML) {
this.execCommand('InsertText', false, value.nodeValue);
tinyMCE.triggerNodeChange();
return true;
} else if (tinyMCE.isSafari && isHTML) {
rng.deleteContents();
rng.insertNode(value);
tinyMCE.triggerNodeChange();
return true;
}
rng.deleteContents();
// If target node is text do special treatment, (Mozilla 1.3 fix)
if (rng.startContainer.nodeType == 3) {
var node = rng.startContainer.splitText(rng.startOffset);
node.parentNode.insertBefore(value, node);
} else
rng.insertNode(value);
if (!isHTML) {
// Removes weird selection trails
sel.selectAllChildren(doc.body);
sel.removeAllRanges();
// Move cursor to end of content
var rng = doc.createRange();
rng.selectNode(value);
rng.collapse(false);
sel.addRange(rng);
} else
rng.collapse(false);
tinyMCE.fixGeckoBaseHREFBug(2, this.getDoc(), value);
} else {
var rng = doc.selection.createRange();
var c = value.indexOf('<!--') != -1;
// Fix comment bug, add tag before comments
if (c)
value = tinyMCE.uniqueTag + value;
if (rng.item)
rng.item(0).outerHTML = value;
else
rng.pasteHTML(value);
// Remove unique tag
if (c) {
var e = this.getDoc().getElementById('mceTMPElement');
e.parentNode.removeChild(e);
}
}
tinyMCE.triggerNodeChange();
break;
case "mceStartTyping":
if (tinyMCE.settings['custom_undo_redo'] && this.undoRedo.typingUndoIndex == -1) {
this.undoRedo.typingUndoIndex = this.undoRedo.undoIndex;
this.execCommand('mceAddUndoLevel');
//tinyMCE.debug("mceStartTyping");
}
break;
case "mceEndTyping":
if (tinyMCE.settings['custom_undo_redo'] && this.undoRedo.typingUndoIndex != -1) {
this.execCommand('mceAddUndoLevel');
this.undoRedo.typingUndoIndex = -1;
//tinyMCE.debug("mceEndTyping");
}
break;
case "mceBeginUndoLevel":
this.undoRedoLevel = false;
break;
case "mceEndUndoLevel":
this.undoRedoLevel = true;
this.execCommand('mceAddUndoLevel');
break;
case "mceAddUndoLevel":
if (tinyMCE.settings['custom_undo_redo'] && this.undoRedoLevel) {
if (this.undoRedo.add())
tinyMCE.triggerNodeChange(false);
}
break;
case "Undo":
if (tinyMCE.settings['custom_undo_redo']) {
tinyMCE.execCommand("mceEndTyping");
this.undoRedo.undo();
tinyMCE.triggerNodeChange();
} else
this.getDoc().execCommand(command, user_interface, value);
break;
case "Redo":
if (tinyMCE.settings['custom_undo_redo']) {
tinyMCE.execCommand("mceEndTyping");
this.undoRedo.redo();
tinyMCE.triggerNodeChange();
} else
this.getDoc().execCommand(command, user_interface, value);
break;
case "mceToggleVisualAid":
this.visualAid = !this.visualAid;
tinyMCE.handleVisualAid(this.getBody(), true, this.visualAid, this);
tinyMCE.triggerNodeChange();
break;
case "Indent":
this.getDoc().execCommand(command, user_interface, value);
tinyMCE.triggerNodeChange();
if (tinyMCE.isMSIE) {
var n = tinyMCE.getParentElement(this.getFocusElement(), "blockquote");
do {
if (n && n.nodeName == "BLOCKQUOTE") {
n.removeAttribute("dir");
n.removeAttribute("style");
}
} while (n != null && (n = n.parentNode) != null);
}
break;
case "removeformat":
var text = this.selection.getSelectedText();
if (tinyMCE.isOpera) {
this.getDoc().execCommand("RemoveFormat", false, null);
return;
}
if (tinyMCE.isMSIE) {
try {
var rng = doc.selection.createRange();
rng.execCommand("RemoveFormat", false, null);
} catch (e) {
// Do nothing
}
this.execCommand("SetStyleInfo", false, {command : "removeformat"});
} else {
this.getDoc().execCommand(command, user_interface, value);
this.execCommand("SetStyleInfo", false, {command : "removeformat"});
}
// Remove class
if (text.length == 0)
this.execCommand("mceSetCSSClass", false, "");
tinyMCE.triggerNodeChange();
break;
default:
this.getDoc().execCommand(command, user_interface, value);
if (tinyMCE.isGecko)
window.setTimeout('tinyMCE.triggerNodeChange(false);', 1);
else
tinyMCE.triggerNodeChange();
}
// Add undo level after modification
if (command != "mceAddUndoLevel" && command != "Undo" && command != "Redo" && command != "mceStartTyping" && command != "mceEndTyping")
tinyMCE.execCommand("mceAddUndoLevel");
},
queryCommandValue : function(c) {
try {
return this.getDoc().queryCommandValue(c);
} catch (e) {
return null;
}
},
queryCommandState : function(c) {
return this.getDoc().queryCommandState(c);
},
_onAdd : function(replace_element, form_element_name, target_document) {
var hc, th, to, editorTemplate;
th = this.settings['theme'];
to = tinyMCE.themes[th];
var targetDoc = target_document ? target_document : document;
this.targetDoc = targetDoc;
tinyMCE.themeURL = tinyMCE.baseURL + "/themes/" + this.settings['theme'];
this.settings['themeurl'] = tinyMCE.themeURL;
if (!replace_element) {
alert("Error: Could not find the target element.");
return false;
}
if (to.getEditorTemplate)
editorTemplate = to.getEditorTemplate(this.settings, this.editorId);
var deltaWidth = editorTemplate['delta_width'] ? editorTemplate['delta_width'] : 0;
var deltaHeight = editorTemplate['delta_height'] ? editorTemplate['delta_height'] : 0;
var html = '<span id="' + this.editorId + '_parent" class="mceEditorContainer">' + editorTemplate['html'];
html = tinyMCE.replaceVar(html, "editor_id", this.editorId);
this.settings['default_document'] = tinyMCE.baseURL + "/blank.htm";
this.settings['old_width'] = this.settings['width'];
this.settings['old_height'] = this.settings['height'];
// Set default width, height
if (this.settings['width'] == -1)
this.settings['width'] = replace_element.offsetWidth;
if (this.settings['height'] == -1)
this.settings['height'] = replace_element.offsetHeight;
// Try the style width
if (this.settings['width'] == 0)
this.settings['width'] = replace_element.style.width;
// Try the style height
if (this.settings['height'] == 0)
this.settings['height'] = replace_element.style.height;
// If no width/height then default to 320x240, better than nothing
if (this.settings['width'] == 0)
this.settings['width'] = 320;
if (this.settings['height'] == 0)
this.settings['height'] = 240;
this.settings['area_width'] = parseInt(this.settings['width']);
this.settings['area_height'] = parseInt(this.settings['height']);
this.settings['area_width'] += deltaWidth;
this.settings['area_height'] += deltaHeight;
// Special % handling
if (("" + this.settings['width']).indexOf('%') != -1)
this.settings['area_width'] = "100%";
if (("" + this.settings['height']).indexOf('%') != -1)
this.settings['area_height'] = "100%";
if (("" + replace_element.style.width).indexOf('%') != -1) {
this.settings['width'] = replace_element.style.width;
this.settings['area_width'] = "100%";
}
if (("" + replace_element.style.height).indexOf('%') != -1) {
this.settings['height'] = replace_element.style.height;
this.settings['area_height'] = "100%";
}
html = tinyMCE.applyTemplate(html);
this.settings['width'] = this.settings['old_width'];
this.settings['height'] = this.settings['old_height'];
this.visualAid = this.settings['visual'];
this.formTargetElementId = form_element_name;
// Get replace_element contents
if (replace_element.nodeName == "TEXTAREA" || replace_element.nodeName == "INPUT")
this.startContent = replace_element.value;
else
this.startContent = replace_element.innerHTML;
// If not text area or input
if (replace_element.nodeName != "TEXTAREA" && replace_element.nodeName != "INPUT") {
this.oldTargetElement = replace_element;
// Debug mode
if (tinyMCE.settings['debug']) {
hc = '<textarea wrap="off" id="' + form_element_name + '" name="' + form_element_name + '" cols="100" rows="15"></textarea>';
} else {
hc = '<input type="hidden" type="text" id="' + form_element_name + '" name="' + form_element_name + '" />';
this.oldTargetElement.style.display = "none";
}
html += '</span>';
if (tinyMCE.isGecko)
html = hc + html;
else
html += hc;
// Output HTML and set editable
if (tinyMCE.isGecko) {
var rng = replace_element.ownerDocument.createRange();
rng.setStartBefore(replace_element);
var fragment = rng.createContextualFragment(html);
tinyMCE.insertAfter(fragment, replace_element);
} else
replace_element.insertAdjacentHTML("beforeBegin", html);
} else {
html += '</span>';
// Just hide the textarea element
this.oldTargetElement = replace_element;
if (!tinyMCE.settings['debug'])
this.oldTargetElement.style.display = "none";
// Output HTML and set editable
if (tinyMCE.isGecko) {
var rng = replace_element.ownerDocument.createRange();
rng.setStartBefore(replace_element);
var fragment = rng.createContextualFragment(html);
tinyMCE.insertAfter(fragment, replace_element);
} else
replace_element.insertAdjacentHTML("beforeBegin", html);
}
// Setup iframe
var dynamicIFrame = false;
var tElm = targetDoc.getElementById(this.editorId);
if (!tinyMCE.isMSIE) {
if (tElm && tElm.nodeName == "SPAN") {
tElm = tinyMCE._createIFrame(tElm, targetDoc);
dynamicIFrame = true;
}
this.targetElement = tElm;
this.iframeElement = tElm;
this.contentDocument = tElm.contentDocument;
this.contentWindow = tElm.contentWindow;
//this.getDoc().designMode = "on";
} else {
if (tElm && tElm.nodeName == "SPAN")
tElm = tinyMCE._createIFrame(tElm, targetDoc, targetDoc.parentWindow);
else
tElm = targetDoc.frames[this.editorId];
this.targetElement = tElm;
this.iframeElement = targetDoc.getElementById(this.editorId);
if (tinyMCE.isOpera) {
this.contentDocument = this.iframeElement.contentDocument;
this.contentWindow = this.iframeElement.contentWindow;
dynamicIFrame = true;
} else {
this.contentDocument = tElm.window.document;
this.contentWindow = tElm.window;
}
this.getDoc().designMode = "on";
}
// Setup base HTML
var doc = this.contentDocument;
if (dynamicIFrame) {
var html = tinyMCE.getParam('doctype') + '<html><head xmlns="http://www.w3.org/1999/xhtml"><base href="' + tinyMCE.settings['base_href'] + '" /><title>blank_page</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head><body class="mceContentBody"></body></html>';
try {
if (!this.isHidden())
this.getDoc().designMode = "on";
doc.open();
doc.write(html);
doc.close();
} catch (e) {
// Failed Mozilla 1.3
this.getDoc().location.href = tinyMCE.baseURL + "/blank.htm";
}
}
// This timeout is needed in MSIE 5.5 for some odd reason
// it seems that the document.frames isn't initialized yet?
if (tinyMCE.isMSIE)
window.setTimeout("tinyMCE.addEventHandlers(tinyMCE.instances[\"" + this.editorId + "\"]);", 1);
tinyMCE.setupContent(this.editorId, true);
return true;
},
setBaseHREF : function(u) {
var h, b, d, nl;
d = this.getDoc();
nl = d.getElementsByTagName("base");
b = nl.length > 0 ? nl[0] : null;
if (!b) {
nl = d.getElementsByTagName("head");
h = nl.length > 0 ? nl[0] : null;
b = d.createElement("base");
b.setAttribute('href', u);
h.appendChild(b);
} else {
if (u == "" || u == null)
b.parentNode.removeChild(b);
else
b.setAttribute('href', u);
}
},
getFocusElement : function() {
return this.selection.getFocusElement();
},
getSel : function() {
return this.selection.getSel();
},
getRng : function() {
return this.selection.getRng();
},
triggerSave : function(skip_cleanup, skip_callback) {
this.switchSettings();
tinyMCE.settings['preformatted'] = false;
// Default to false
if (typeof(skip_cleanup) == "undefined")
skip_cleanup = false;
// Default to false
if (typeof(skip_callback) == "undefined")
skip_callback = false;
tinyMCE._setHTML(this.getDoc(), this.getBody().innerHTML);
// Remove visual aids when cleanup is disabled
if (this.settings['cleanup'] == false) {
tinyMCE.handleVisualAid(this.getBody(), true, false, this);
tinyMCE._setEventsEnabled(this.getBody(), true);
}
tinyMCE._customCleanup(this, "submit_content_dom", this.contentWindow.document.body);
var htm = skip_cleanup ? this.getBody().innerHTML : tinyMCE._cleanupHTML(this, this.getDoc(), this.settings, this.getBody(), tinyMCE.visualAid, true, true);
htm = tinyMCE._customCleanup(this, "submit_content", htm);
if (!skip_callback && tinyMCE.settings['save_callback'] != "")
var content = eval(tinyMCE.settings['save_callback'] + "(this.formTargetElementId,htm,this.getBody());");
// Use callback content if available
if ((typeof(content) != "undefined") && content != null)
htm = content;
// Replace some weird entities (Bug: #1056343)
htm = tinyMCE.regexpReplace(htm, "(", "(", "gi");
htm = tinyMCE.regexpReplace(htm, ")", ")", "gi");
htm = tinyMCE.regexpReplace(htm, ";", ";", "gi");
htm = tinyMCE.regexpReplace(htm, """, """, "gi");
htm = tinyMCE.regexpReplace(htm, "^", "^", "gi");
if (this.formElement)
this.formElement.value = htm;
if (tinyMCE.isSafari && this.formElement)
this.formElement.innerText = htm;
}
};
/* file:jscripts/tiny_mce/classes/TinyMCE_Cleanup.class.js */
TinyMCE_Engine.prototype.cleanupHTMLCode = function(s) {
s = s.replace(/<p \/>/gi, '<p> </p>');
s = s.replace(/<p>\s*<\/p>/gi, '<p> </p>');
// Open closed tags like <b/> to <b></b>
// tinyMCE.debug("f:" + s);
s = s.replace(/<(h[1-6]|p|div|address|pre|form|table|li|ol|ul|td|b|font|em|strong|i|strike|u|span|a|ul|ol|li|blockquote)([a-z]*)([^\\|>]*?)\/>/gi, '<$1$2$3></$1$2>');
// tinyMCE.debug("e:" + s);
// Remove trailing space <b > to <b>
s = s.replace(new RegExp('\\s+></', 'gi'), '></');
// Close tags <img></img> to <img/>
s = s.replace(/<(img|br|hr)(.*?)><\/(img|br|hr)>/gi, '<$1$2 />');
// Weird MSIE bug, <p><hr /></p> breaks runtime?
if (tinyMCE.isMSIE)
s = s.replace(/<p><hr \/><\/p>/gi, "<hr>");
// Convert relative anchors to absolute URLs ex: #something to file.htm#something
if (tinyMCE.getParam('convert_urls'))
s = s.replace(new RegExp('(href=\"?)(\\s*?#)', 'gi'), '$1' + tinyMCE.settings['document_base_url'] + "#");
return s;
};
TinyMCE_Engine.prototype.parseStyle = function(str) {
var ar = new Array();
if (str == null)
return ar;
var st = str.split(';');
tinyMCE.clearArray(ar);
for (var i=0; i<st.length; i++) {
if (st[i] == '')
continue;
var re = new RegExp('^\\s*([^:]*):\\s*(.*)\\s*$');
var pa = st[i].replace(re, '$1||$2').split('||');
//tinyMCE.debug(str, pa[0] + "=" + pa[1], st[i].replace(re, '$1||$2'));
if (pa.length == 2)
ar[pa[0].toLowerCase()] = pa[1];
}
return ar;
};
TinyMCE_Engine.prototype.compressStyle = function(ar, pr, sf, res) {
var box = new Array();
box[0] = ar[pr + '-top' + sf];
box[1] = ar[pr + '-left' + sf];
box[2] = ar[pr + '-right' + sf];
box[3] = ar[pr + '-bottom' + sf];
for (var i=0; i<box.length; i++) {
if (box[i] == null)
return;
for (var a=0; a<box.length; a++) {
if (box[a] != box[i])
return;
}
}
// They are all the same
ar[res] = box[0];
ar[pr + '-top' + sf] = null;
ar[pr + '-left' + sf] = null;
ar[pr + '-right' + sf] = null;
ar[pr + '-bottom' + sf] = null;
};
TinyMCE_Engine.prototype.serializeStyle = function(ar) {
var str = "";
// Compress box
tinyMCE.compressStyle(ar, "border", "", "border");
tinyMCE.compressStyle(ar, "border", "-width", "border-width");
tinyMCE.compressStyle(ar, "border", "-color", "border-color");
for (var key in ar) {
var val = ar[key];
if (typeof(val) == 'function')
continue;
if (key.indexOf('mso-') == 0)
continue;
if (val != null && val != '') {
val = '' + val; // Force string
// Fix style URL
val = val.replace(new RegExp("url\\(\\'?([^\\']*)\\'?\\)", 'gi'), "url('$1')");
// Convert URL
if (val.indexOf('url(') != -1 && tinyMCE.getParam('convert_urls')) {
var m = new RegExp("url\\('(.*?)'\\)").exec(val);
if (m.length > 1)
val = "url('" + eval(tinyMCE.getParam('urlconverter_callback') + "(m[1], null, true);") + "')";
}
// Force HEX colors
if (tinyMCE.getParam("force_hex_style_colors"))
val = tinyMCE.convertRGBToHex(val, true);
if (val != "url('')")
str += key.toLowerCase() + ": " + val + "; ";
}
}
if (new RegExp('; $').test(str))
str = str.substring(0, str.length - 2);
return str;
};
TinyMCE_Engine.prototype.convertRGBToHex = function(s, k) {
if (s.toLowerCase().indexOf('rgb') != -1) {
var re = new RegExp("(.*?)rgb\\s*?\\(\\s*?([0-9]+).*?,\\s*?([0-9]+).*?,\\s*?([0-9]+).*?\\)(.*?)", "gi");
var rgb = s.replace(re, "$1,$2,$3,$4,$5").split(',');
if (rgb.length == 5) {
r = parseInt(rgb[1]).toString(16);
g = parseInt(rgb[2]).toString(16);
b = parseInt(rgb[3]).toString(16);
r = r.length == 1 ? '0' + r : r;
g = g.length == 1 ? '0' + g : g;
b = b.length == 1 ? '0' + b : b;
s = "#" + r + g + b;
if (k)
s = rgb[0] + s + rgb[4];
}
}
return s;
};
TinyMCE_Engine.prototype.convertHexToRGB = function(s) {
if (s.indexOf('#') != -1) {
s = s.replace(new RegExp('[^0-9A-F]', 'gi'), '');
return "rgb(" + parseInt(s.substring(0, 2), 16) + "," + parseInt(s.substring(2, 4), 16) + "," + parseInt(s.substring(4, 6), 16) + ")";
}
return s;
};
TinyMCE_Engine.prototype.convertSpansToFonts = function(doc) {
var sizes = tinyMCE.getParam('font_size_style_values').replace(/\s+/, '').split(',');
var h = doc.body.innerHTML;
h = h.replace(/<span/gi, '<font');
h = h.replace(/<\/span/gi, '</font');
doc.body.innerHTML = h;
var s = doc.getElementsByTagName("font");
for (var i=0; i<s.length; i++) {
var size = tinyMCE.trim(s[i].style.fontSize).toLowerCase();
var fSize = 0;
for (var x=0; x<sizes.length; x++) {
if (sizes[x] == size) {
fSize = x + 1;
break;
}
}
if (fSize > 0) {
tinyMCE.setAttrib(s[i], 'size', fSize);
s[i].style.fontSize = '';
}
var fFace = s[i].style.fontFamily;
if (fFace != null && fFace != "") {
tinyMCE.setAttrib(s[i], 'face', fFace);
s[i].style.fontFamily = '';
}
var fColor = s[i].style.color;
if (fColor != null && fColor != "") {
tinyMCE.setAttrib(s[i], 'color', tinyMCE.convertRGBToHex(fColor));
s[i].style.color = '';
}
}
};
TinyMCE_Engine.prototype.convertFontsToSpans = function(doc) {
var sizes = tinyMCE.getParam('font_size_style_values').replace(/\s+/, '').split(',');
var h = doc.body.innerHTML;
h = h.replace(/<font/gi, '<span');
h = h.replace(/<\/font/gi, '</span');
doc.body.innerHTML = h;
var fsClasses = tinyMCE.getParam('font_size_classes');
if (fsClasses != '')
fsClasses = fsClasses.replace(/\s+/, '').split(',');
else
fsClasses = null;
var s = doc.getElementsByTagName("span");
for (var i=0; i<s.length; i++) {
var fSize, fFace, fColor;
fSize = tinyMCE.getAttrib(s[i], 'size');
fFace = tinyMCE.getAttrib(s[i], 'face');
fColor = tinyMCE.getAttrib(s[i], 'color');
if (fSize != "") {
fSize = parseInt(fSize);
if (fSize > 0 && fSize < 8) {
if (fsClasses != null)
tinyMCE.setAttrib(s[i], 'class', fsClasses[fSize-1]);
else
s[i].style.fontSize = sizes[fSize-1];
}
s[i].removeAttribute('size');
}
if (fFace != "") {
s[i].style.fontFamily = fFace;
s[i].removeAttribute('face');
}
if (fColor != "") {
s[i].style.color = fColor;
s[i].removeAttribute('color');
}
}
};
TinyMCE_Engine.prototype.cleanupAnchors = function(doc) {
var i, cn, x, an = doc.getElementsByTagName("a");
for (i=0; i<an.length; i++) {
if (tinyMCE.getAttrib(an[i], "name") != "" && tinyMCE.getAttrib(an[i], "href") == "") {
cn = an[i].childNodes;
for (x=cn.length-1; x>=0; x--)
tinyMCE.insertAfter(cn[x], an[i]);
}
}
};
TinyMCE_Engine.prototype.getContent = function(editor_id) {
var h;
if (typeof(editor_id) != "undefined")
tinyMCE.selectedInstance = tinyMCE.getInstanceById(editor_id);
if (tinyMCE.selectedInstance) {
h = tinyMCE._cleanupHTML(this.selectedInstance, this.selectedInstance.getDoc(), tinyMCE.settings, this.selectedInstance.getBody(), false, true);
// When editing always use fonts internaly
if (tinyMCE.getParam("convert_fonts_to_spans"))
tinyMCE.convertSpansToFonts(this.selectedInstance.getDoc());
return h;
}
return null;
};
TinyMCE_Engine.prototype._fixListElements = function(d) {
var nl, x, a = ['ol', 'ul'], i, n, p, r = new RegExp('^(OL|UL)$'), np;
for (x=0; x<a.length; x++) {
nl = d.getElementsByTagName(a[x]);
for (i=0; i<nl.length; i++) {
n = nl[i];
p = n.parentNode;
if (r.test(p.nodeName)) {
np = tinyMCE.prevNode(n, 'LI');
if (!np) {
np = d.createElement('li');
np.innerHTML = ' ';
np.appendChild(n);
p.insertBefore(np, p.firstChild);
} else
np.appendChild(n);
}
}
}
};
TinyMCE_Engine.prototype._fixTables = function(d) {
var nl, i, n, p, np, x, t;
nl = d.getElementsByTagName('table');
for (i=0; i<nl.length; i++) {
n = nl[i];
if ((p = tinyMCE.getParentElement(n, 'p,div,h1,h2,h3,h4,h5,h6')) != null) {
np = p.cloneNode(false);
np.removeAttribute('id');
t = n;
while ((n = n.nextSibling))
np.appendChild(n);
tinyMCE.insertAfter(np, p);
tinyMCE.insertAfter(t, p);
}
}
};
TinyMCE_Engine.prototype._cleanupHTML = function(inst, doc, config, elm, visual, on_save, on_submit) {
var h, d, t1, t2, t3, t4, t5, c, s;
if (!tinyMCE.getParam('cleanup'))
return elm.innerHTML;
on_save = typeof(on_save) == 'undefined' ? false : on_save;
c = inst.cleanup;
s = inst.settings;
d = c.settings.debug;
if (d)
t1 = new Date().getTime();
if (tinyMCE.getParam("convert_fonts_to_spans"))
tinyMCE.convertFontsToSpans(doc);
if (tinyMCE.getParam("fix_list_elements"))
tinyMCE._fixListElements(doc);
if (tinyMCE.getParam("fix_table_elements"))
tinyMCE._fixTables(doc);
// Call custom cleanup code
tinyMCE._customCleanup(inst, on_save ? "get_from_editor_dom" : "insert_to_editor_dom", doc.body);
if (d)
t2 = new Date().getTime();
c.settings.on_save = on_save;
//for (var i=0; i<100; i++)
c.idCount = 0;
c.serializationId++;
c.serializedNodes = new Array();
c.sourceIndex = -1;
if (s.cleanup_serializer == "xml")
h = c.serializeNodeAsXML(elm);
else
h = c.serializeNodeAsHTML(elm);
if (d)
t3 = new Date().getTime();
// Post processing
h = h.replace(/<\/?(body|head|html)[^>]*>/gi, '');
h = h.replace(new RegExp(' (rowspan="1"|colspan="1")', 'g'), '');
h = h.replace(/<p><hr \/><\/p>/g, '<hr />');
h = h.replace(/<p>( | )<\/p><hr \/><p>( | )<\/p>/g, '<hr />');
h = h.replace(/<td>\s*<br \/>\s*<\/td>/g, '<td> </td>');
h = h.replace(/<p>\s*<br \/>\s*<\/p>/g, '<p> </p>');
h = h.replace(/<p>\s*( | )\s*<br \/>\s*( | )\s*<\/p>/g, '<p> </p>');
h = h.replace(/<p>\s*( | )\s*<br \/>\s*<\/p>/g, '<p> </p>');
h = h.replace(/<p>\s*<br \/>\s* \s*<\/p>/g, '<p> </p>');
h = h.replace(/<a>(.*?)<\/a>/g, '$1');
h = h.replace(/<p([^>]*)>\s*<\/p>/g, '<p$1> </p>');
// Clean body
if (/^\s*(<br \/>|<p> <\/p>|<p> <\/p>|<p><\/p>)\s*$/.test(h))
h = '';
// If preformatted
if (s.preformatted) {
h = h.replace(/^<pre>/, '');
h = h.replace(/<\/pre>$/, '');
h = '<pre>' + h + '</pre>';
}
// Gecko specific processing
if (tinyMCE.isGecko) {
h = h.replace(/<o:p _moz-userdefined="" \/>/g, '');
h = h.replace(/<td([^>]*)>\s*<br \/>\s*<\/td>/g, '<td$1> </td>');
}
if (s.force_br_newlines)
h = h.replace(/<p>( | )<\/p>/g, '<br />');
// Call custom cleanup code
h = tinyMCE._customCleanup(inst, on_save ? "get_from_editor" : "insert_to_editor", h);
// Remove internal classes
if (on_save) {
h = h.replace(new RegExp(' ?(mceItem[a-zA-Z0-9]*|' + s.visual_table_class + ')', 'g'), '');
h = h.replace(new RegExp(' ?class=""', 'g'), '');
}
if (s.remove_linebreaks && !c.settings.indent)
h = h.replace(/\n|\r/g, ' ');
if (d)
t4 = new Date().getTime();
if (on_save && c.settings.indent)
h = c.formatHTML(h);
// If encoding (not recommended option)
if (on_submit && (s.encoding == "xml" || s.encoding == "html"))
h = c.xmlEncode(h);
if (d)
t5 = new Date().getTime();
if (c.settings.debug)
tinyMCE.debug("Cleanup in ms: Pre=" + (t2-t1) + ", Serialize: " + (t3-t2) + ", Post: " + (t4-t3) + ", Format: " + (t5-t4) + ", Sum: " + (t5-t1) + ".");
return h;
};
function TinyMCE_Cleanup() {
this.isMSIE = (navigator.appName == "Microsoft Internet Explorer");
this.rules = tinyMCE.clearArray(new Array());
// Default config
this.settings = {
indent_elements : 'head,table,tbody,thead,tfoot,form,tr,ul,ol,blockquote,object',
newline_before_elements : 'h1,h2,h3,h4,h5,h6,pre,address,div,ul,ol,li,meta,option,area,title,link,base,script,td',
newline_after_elements : 'br,hr,p,pre,address,div,ul,ol,meta,option,area,link,base,script',
newline_before_after_elements : 'html,head,body,table,thead,tbody,tfoot,tr,form,ul,ol,blockquote,p,object,param,hr,div',
indent_char : '\t',
indent_levels : 1,
entity_encoding : 'raw',
valid_elements : '*[*]',
entities : '',
url_converter : '',
invalid_elements : '',
verify_html : false
};
this.vElements = tinyMCE.clearArray(new Array());
this.vElementsRe = '';
this.closeElementsRe = /^(IMG|BR|HR|LINK|META|BASE|INPUT|BUTTON)$/;
this.codeElementsRe = /^(SCRIPT|STYLE)$/;
this.serializationId = 0;
this.mceAttribs = {
href : 'mce_href',
src : 'mce_src',
type : 'mce_type'
};
}
TinyMCE_Cleanup.prototype = {
init : function(s) {
var n, a, i, ir, or, st;
for (n in s)
this.settings[n] = s[n];
// Setup code formating
s = this.settings;
// Setup regexps
this.inRe = this._arrayToRe(s.indent_elements.split(','), '', '^<(', ')[^>]*');
this.ouRe = this._arrayToRe(s.indent_elements.split(','), '', '^<\\/(', ')[^>]*');
this.nlBeforeRe = this._arrayToRe(s.newline_before_elements.split(','), 'gi', '<(', ')([^>]*)>');
this.nlAfterRe = this._arrayToRe(s.newline_after_elements.split(','), 'gi', '<(', ')([^>]*)>');
this.nlBeforeAfterRe = this._arrayToRe(s.newline_before_after_elements.split(','), 'gi', '<(\\/?)(', ')([^>]*)>');
if (s.invalid_elements != '')
this.iveRe = this._arrayToRe(s.invalid_elements.toUpperCase().split(','), 'g', '^(', ')$');
else
this.iveRe = null;
// Setup separator
st = '';
for (i=0; i<s.indent_levels; i++)
st += s.indent_char;
this.inStr = st;
// If verify_html if false force *[*]
if (!s.verify_html) {
s.valid_elements = '*[*]';
s.extended_valid_elements = '';
}
this.fillStr = s.entity_encoding == "named" ? " " : " ";
this.idCount = 0;
},
addRuleStr : function(s) {
var r = this.parseRuleStr(s);
var n;
for (n in r) {
if (r[n])
this.rules[n] = r[n];
}
this.vElements = tinyMCE.clearArray(new Array());
for (n in this.rules) {
if (this.rules[n])
this.vElements[this.vElements.length] = this.rules[n].tag;
}
this.vElementsRe = this._arrayToRe(this.vElements, '');
},
parseRuleStr : function(s) {
var ta, p, r, a, i, x, px, t, tn, y, av, or = tinyMCE.clearArray(new Array()), dv;
if (s == null || s.length == 0)
return or;
ta = s.split(',');
for (x=0; x<ta.length; x++) {
s = ta[x];
if (s.length == 0)
continue;
// Split tag/attrs
p = this.split(/\[|\]/, s);
if (p == null || p.length < 1)
t = s.toUpperCase();
else
t = p[0].toUpperCase();
// Handle all tag names
tn = this.split('/', t);
for (y=0; y<tn.length; y++) {
r = {};
r.tag = tn[y];
r.forceAttribs = null;
r.defaultAttribs = null;
r.validAttribValues = null;
// Handle prefixes
px = r.tag.charAt(0);
r.forceOpen = px == '+';
r.removeEmpty = px == '-';
r.fill = px == '#';
r.tag = r.tag.replace(/\+|-|#/g, '');
r.oTagName = tn[0].replace(/\+|-|#/g, '').toLowerCase();
r.isWild = new RegExp('\\*|\\?|\\+', 'g').test(r.tag);
r.validRe = new RegExp(this._wildcardToRe('^' + r.tag + '$'));
// Setup valid attributes
if (p.length > 1) {
r.vAttribsRe = '^(';
a = this.split(/\|/, p[1]);
for (i=0; i<a.length; i++) {
t = a[i];
av = /(=|:|<)(.*?)$/.exec(t);
t = t.replace(/(=|:|<).*?$/, '');
if (av && av.length > 0) {
if (av[0].charAt(0) == ':') {
if (!r.forceAttribs)
r.forceAttribs = tinyMCE.clearArray(new Array());
r.forceAttribs[t.toLowerCase()] = av[0].substring(1);
} else if (av[0].charAt(0) == '=') {
if (!r.defaultAttribs)
r.defaultAttribs = tinyMCE.clearArray(new Array());
dv = av[0].substring(1);
r.defaultAttribs[t.toLowerCase()] = dv == "" ? "mce_empty" : dv;
} else if (av[0].charAt(0) == '<') {
if (!r.validAttribValues)
r.validAttribValues = tinyMCE.clearArray(new Array());
r.validAttribValues[t.toLowerCase()] = this._arrayToRe(this.split('?', av[0].substring(1)), '');
}
}
r.vAttribsRe += '' + t.toLowerCase() + (i != a.length - 1 ? '|' : '');
a[i] = t.toLowerCase();
}
r.vAttribsRe += ')$';
r.vAttribsRe = this._wildcardToRe(r.vAttribsRe);
r.vAttribsReIsWild = new RegExp('\\*|\\?|\\+', 'g').test(r.vAttribsRe);
r.vAttribsRe = new RegExp(r.vAttribsRe);
r.vAttribs = a.reverse();
//tinyMCE.debug(r.tag, r.oTagName, r.vAttribsRe, r.vAttribsReWC);
} else {
r.vAttribsRe = '';
r.vAttribs = tinyMCE.clearArray(new Array());
r.vAttribsReIsWild = false;
}
or[r.tag] = r;
}
}
return or;
},
serializeNodeAsXML : function(n) {
var s, b;
if (!this.xmlDoc) {
if (this.isMSIE) {
try {this.xmlDoc = new ActiveXObject('MSXML2.DOMDocument');} catch (e) {}
if (!this.xmlDoc)
try {this.xmlDoc = new ActiveXObject('Microsoft.XmlDom');} catch (e) {}
} else
this.xmlDoc = document.implementation.createDocument('', '', null);
if (!this.xmlDoc)
alert("Error XML Parser could not be found.");
}
if (this.xmlDoc.firstChild)
this.xmlDoc.removeChild(this.xmlDoc.firstChild);
b = this.xmlDoc.createElement("html");
b = this.xmlDoc.appendChild(b);
this._convertToXML(n, b);
if (this.isMSIE)
return this.xmlDoc.xml;
else
return new XMLSerializer().serializeToString(this.xmlDoc);
},
_convertToXML : function(n, xn) {
var xd, el, i, l, cn, at, no, hc = false;
if (this._isDuplicate(n))
return;
xd = this.xmlDoc;
switch (n.nodeType) {
case 1: // Element
hc = n.hasChildNodes();
el = xd.createElement(n.nodeName.toLowerCase());
at = n.attributes;
for (i=at.length-1; i>-1; i--) {
no = at[i];
if (no.specified && no.nodeValue)
el.setAttribute(no.nodeName.toLowerCase(), no.nodeValue);
}
if (!hc && !this.closeElementsRe.test(n.nodeName))
el.appendChild(xd.createTextNode(""));
xn = xn.appendChild(el);
break;
case 3: // Text
xn.appendChild(xd.createTextNode(n.nodeValue));
return;
case 8: // Comment
xn.appendChild(xd.createComment(n.nodeValue));
return;
}
if (hc) {
cn = n.childNodes;
for (i=0, l=cn.length; i<l; i++)
this._convertToXML(cn[i], xn);
}
},
serializeNodeAsHTML : function(n) {
var en, no, h = '', i, l, r, cn, va = false, f = false, at, hc;
this._setupRules(); // Will initialize cleanup rules
if (this._isDuplicate(n))
return '';
switch (n.nodeType) {
case 1: // Element
hc = n.hasChildNodes();
// MSIE sometimes produces <//tag>
if ((tinyMCE.isMSIE && !tinyMCE.isOpera) && n.nodeName.indexOf('/') != -1)
break;
if (this.vElementsRe.test(n.nodeName) && (!this.iveRe || !this.iveRe.test(n.nodeName))) {
va = true;
r = this.rules[n.nodeName];
if (!r) {
at = this.rules;
for (no in at) {
if (at[no] && at[no].validRe.test(n.nodeName)) {
r = at[no];
break;
}
}
}
en = r.isWild ? n.nodeName.toLowerCase() : r.oTagName;
f = r.fill;
if (r.removeEmpty && !hc)
return "";
h += '<' + en;
if (r.vAttribsReIsWild) {
// Serialize wildcard attributes
at = n.attributes;
for (i=at.length-1; i>-1; i--) {
no = at[i];
if (no.specified && r.vAttribsRe.test(no.nodeName))
h += this._serializeAttribute(n, r, no.nodeName);
}
} else {
// Serialize specific attributes
for (i=r.vAttribs.length-1; i>-1; i--)
h += this._serializeAttribute(n, r, r.vAttribs[i]);
}
// Serialize mce_ atts
if (!this.settings.on_save) {
at = this.mceAttribs;
for (no in at) {
if (at[no])
h += this._serializeAttribute(n, r, at[no]);
}
}
// Close these
if (this.closeElementsRe.test(n.nodeName))
return h + ' />';
h += '>';
if (this.isMSIE && this.codeElementsRe.test(n.nodeName))
h += n.innerHTML;
}
break;
case 3: // Text
if (n.parentNode && this.codeElementsRe.test(n.parentNode.nodeName))
return this.isMSIE ? '' : n.nodeValue;
return this.xmlEncode(n.nodeValue);
case 8: // Comment
return "<!--" + this._trimComment(n.nodeValue) + "-->";
}
if (hc) {
cn = n.childNodes;
for (i=0, l=cn.length; i<l; i++)
h += this.serializeNodeAsHTML(cn[i]);
}
// Fill empty nodes
if (f && !hc)
h += this.fillStr;
// End element
if (va)
h += '</' + en + '>';
return h;
},
_serializeAttribute : function(n, r, an) {
var av = '', t, os = this.settings.on_save;
if (os && (an.indexOf('mce_') == 0 || an.indexOf('_moz') == 0))
return '';
if (os && this.mceAttribs[an])
av = this._getAttrib(n, this.mceAttribs[an]);
if (av.length == 0)
av = this._getAttrib(n, an);
if (av.length == 0 && r.defaultAttribs && (t = r.defaultAttribs[an])) {
av = t;
if (av == "mce_empty")
return " " + an + '=""';
}
if (r.forceAttribs && (t = r.forceAttribs[an]))
av = t;
if (os && av.length != 0 && this.settings.url_converter.length != 0 && /^(src|href|longdesc)$/.test(an))
av = eval(this.settings.url_converter + '(this, n, av)');
if (av.length != 0 && r.validAttribValues && r.validAttribValues[an] && !r.validAttribValues[an].test(av))
return "";
if (av.length != 0 && av == "{$uid}")
av = "uid_" + (this.idCount++);
if (av.length != 0)
return " " + an + "=" + '"' + this.xmlEncode(av) + '"';
return "";
},
formatHTML : function(h) {
var s = this.settings, p = '', i = 0, li = 0, o = '', l;
h = h.replace(/\r/g, ''); // Windows sux, isn't carriage return a thing of the past :)
h = '\n' + h;
h = h.replace(new RegExp('\\n\\s+', 'gi'), '\n'); // Remove previous formatting
h = h.replace(this.nlBeforeRe, '\n<$1$2>');
h = h.replace(this.nlAfterRe, '<$1$2>\n');
h = h.replace(this.nlBeforeAfterRe, '\n<$1$2$3>\n');
h += '\n';
//tinyMCE.debug(h);
while ((i = h.indexOf('\n', i + 1)) != -1) {
if ((l = h.substring(li + 1, i)).length != 0) {
if (this.ouRe.test(l) && p.length >= s.indent_levels)
p = p.substring(s.indent_levels);
o += p + l + '\n';
if (this.inRe.test(l))
p += this.inStr;
}
li = i;
}
//tinyMCE.debug(h);
return o;
},
xmlEncode : function(s) {
var i, l, e, o = '', c;
this._setupEntities(); // Will intialize lookup table
switch (this.settings.entity_encoding) {
case "raw":
return tinyMCE.xmlEncode(s);
case "named":
for (i=0, l=s.length; i<l; i++) {
c = s.charCodeAt(i);
e = this.entities[c];
// ' is not working in MSIE
// More info: http://www.w3.org/TR/xhtml1/#C_16
if (c == 39) {
o += "'";
continue;
}
if (e && e != '')
o += '&' + e + ';';
else
o += String.fromCharCode(c);
}
return o;
case "numeric":
for (i=0, l=s.length; i<l; i++) {
c = s.charCodeAt(i);
if (c > 127 || c == 60 || c == 62 || c == 38 || c == 39 || c == 34)
o += '&#' + c + ";";
else
o += String.fromCharCode(c);
}
return o;
}
return s;
},
split : function(re, s) {
var c = s.split(re);
var i, l, o = new Array();
for (i=0, l=c.length; i<l; i++) {
if (c[i] != '')
o[i] = c[i];
}
return o;
},
_trimComment : function(s) {
// Make xsrc, xhref as src and href again
if (tinyMCE.isGecko) {
s = s.replace(/\sxsrc=/gi, " src=");
s = s.replace(/\sxhref=/gi, " href=");
}
// Remove mce_src, mce_href
s = s.replace(new RegExp('\\smce_src=\"[^\"]*\"', 'gi'), "");
s = s.replace(new RegExp('\\smce_href=\"[^\"]*\"', 'gi'), "");
return s;
},
_getAttrib : function(e, n, d) {
if (typeof(d) == "undefined")
d = "";
if (!e || e.nodeType != 1)
return d;
var v = e.getAttribute(n, 0);
if (n == "class" && !v)
v = e.className;
if (this.isMSIE && n == "http-equiv")
v = e.httpEquiv;
if (n == "style" && !tinyMCE.isOpera)
v = e.style.cssText;
if (n == 'style')
v = tinyMCE.serializeStyle(tinyMCE.parseStyle(v));
if (this.settings.on_save && n.indexOf('on') != -1 && this.settings.on_save && v && v != "")
v = tinyMCE.cleanupEventStr(v);
return (v && v != "") ? '' + v : d;
},
_urlConverter : function(c, n, v) {
if (!c.settings.on_save)
return tinyMCE.convertRelativeToAbsoluteURL(tinyMCE.settings.base_href, v);
else if (tinyMCE.getParam('convert_urls'))
return eval(tinyMCE.settings.urlconverter_callback + "(v, n, true);");
return v;
},
_arrayToRe : function(a, op, be, af) {
var i, r;
op = typeof(op) == "undefined" ? "gi" : op;
be = typeof(be) == "undefined" ? "^(" : be;
af = typeof(af) == "undefined" ? ")$" : af;
r = be;
for (i=0; i<a.length; i++)
r += this._wildcardToRe(a[i]) + (i != a.length-1 ? "|" : "");
r += af;
return new RegExp(r, op);
},
_wildcardToRe : function(s) {
s = s.replace(/\?/g, '(\\S?)');
s = s.replace(/\+/g, '(\\S+)');
s = s.replace(/\*/g, '(\\S*)');
return s;
},
_setupEntities : function() {
var n, a, i, s = this.settings;
// Setup entities
if (!this.entitiesDone) {
if (s.entity_encoding == "named") {
n = tinyMCE.clearArray(new Array());
a = this.split(',', s.entities);
for (i=0; i<a.length; i+=2)
n[a[i]] = a[i+1];
this.entities = n;
}
this.entitiesDone = true;
}
},
_setupRules : function() {
var s = this.settings;
// Setup default rule
if (!this.rulesDone) {
this.addRuleStr(s.valid_elements);
this.addRuleStr(s.extended_valid_elements);
this.rulesDone = true;
}
},
_isDuplicate : function(n) {
var i;
if (!this.settings.fix_content_duplication)
return false;
if (tinyMCE.isMSIE && !tinyMCE.isOpera && n.nodeType == 1) {
// Mark elements
if (n.mce_serialized == this.serializationId)
return true;
n.setAttribute('mce_serialized', this.serializationId);
} else {
// Search lookup table for text nodes and comments
for (i=0; i<this.serializedNodes.length; i++) {
if (this.serializedNodes[i] == n)
return true;
}
this.serializedNodes[this.serializedNodes.length] = n;
}
return false;
}
};
/* file:jscripts/tiny_mce/classes/TinyMCE_DOMUtils.class.js */
TinyMCE_Engine.prototype.getElementByAttributeValue = function(n, e, a, v) {
return (n = this.getElementsByAttributeValue(n, e, a, v)).length == 0 ? null : n[0];
};
TinyMCE_Engine.prototype.getElementsByAttributeValue = function(n, e, a, v) {
var i, nl = n.getElementsByTagName(e), o = new Array();
for (i=0; i<nl.length; i++) {
if (tinyMCE.getAttrib(nl[i], a).indexOf(v) != -1)
o[o.length] = nl[i];
}
return o;
};
TinyMCE_Engine.prototype.isBlockElement = function(n) {
return n != null && n.nodeType == 1 && this.blockRegExp.test(n.nodeName);
};
TinyMCE_Engine.prototype.getParentBlockElement = function(n) {
while (n) {
if (this.isBlockElement(n))
return n;
n = n.parentNode;
}
return null;
};
TinyMCE_Engine.prototype.insertAfter = function(n, r){
if (r.nextSibling)
r.parentNode.insertBefore(n, r.nextSibling);
else
r.parentNode.appendChild(n);
};
TinyMCE_Engine.prototype.setInnerHTML = function(e, h) {
var i, nl, n;
if (tinyMCE.isMSIE && !tinyMCE.isOpera) {
// Since MSIE handles invalid HTML better that valid XHTML we
// need to make some things invalid. <hr /> gets converted to <hr>.
h = h.replace(/\s\/>/g, '>');
// Since MSIE auto generated emtpy P tags some times we must tell it to keep the real ones
h = h.replace(/<p([^>]*)>\u00A0?<\/p>/gi, '<p$1 mce_keep="true"> </p>'); // Keep empty paragraphs
h = h.replace(/<p([^>]*)> <\/p>/gi, '<p$1 mce_keep="true"> </p>'); // Keep empty paragraphs
// Remove first comment
e.innerHTML = tinyMCE.uniqueTag + h;
e.firstChild.removeNode(true);
// Remove weird auto generated empty paragraphs unless it's supposed to be there
nl = e.getElementsByTagName("p");
for (i=nl.length-1; i>=0; i--) {
n = nl[i];
if (n.nodeName == 'P' && !n.hasChildNodes() && !n.mce_keep)
n.parentNode.removeChild(n);
}
} else {
h = this.fixGeckoBaseHREFBug(1, e, h);
e.innerHTML = h;
this.fixGeckoBaseHREFBug(2, e, h);
}
};
TinyMCE_Engine.prototype.getOuterHTML = function(e) {
if (tinyMCE.isMSIE)
return e.outerHTML;
var d = e.ownerDocument.createElement("body");
d.appendChild(e);
return d.innerHTML;
};
TinyMCE_Engine.prototype.setOuterHTML = function(e, h) {
if (tinyMCE.isMSIE) {
e.outerHTML = h;
return;
}
var d = e.ownerDocument.createElement("body");
d.innerHTML = h;
e.parentNode.replaceChild(d.firstChild, e);
};
TinyMCE_Engine.prototype._getElementById = function(id, d) {
var e, i, j, f;
if (typeof(d) == "undefined")
d = document;
e = d.getElementById(id);
if (!e) {
f = d.forms;
for (i=0; i<f.length; i++) {
for (j=0; j<f[i].elements.length; j++) {
if (f[i].elements[j].name == id) {
e = f[i].elements[j];
break;
}
}
}
}
return e;
};
TinyMCE_Engine.prototype.getNodeTree = function(n, na, t, nn) {
var i;
if (typeof(t) == "undefined" || n.nodeType == t && (typeof(nn) == "undefined" || n.nodeName == nn))
na[na.length] = n;
if (n.hasChildNodes()) {
for (i=0; i<n.childNodes.length; i++)
tinyMCE.getNodeTree(n.childNodes[i], na, t, nn);
}
return na;
};
TinyMCE_Engine.prototype.getParentElement = function(node, names, attrib_name, attrib_value) {
if (typeof(names) == "undefined") {
if (node.nodeType == 1)
return node;
// Find parent node that is a element
while ((node = node.parentNode) != null && node.nodeType != 1) ;
return node;
}
if (node == null)
return null;
var namesAr = names.toUpperCase().split(',');
do {
for (var i=0; i<namesAr.length; i++) {
if (node.nodeName == namesAr[i] || names == "*") {
if (typeof(attrib_name) == "undefined")
return node;
else if (node.getAttribute(attrib_name)) {
if (typeof(attrib_value) == "undefined") {
if (node.getAttribute(attrib_name) != "")
return node;
} else if (node.getAttribute(attrib_name) == attrib_value)
return node;
}
}
}
} while ((node = node.parentNode) != null);
return null;
};
TinyMCE_Engine.prototype.getAttrib = function(elm, name, default_value) {
if (typeof(default_value) == "undefined")
default_value = "";
// Not a element
if (!elm || elm.nodeType != 1)
return default_value;
var v = elm.getAttribute(name);
// Try className for class attrib
if (name == "class" && !v)
v = elm.className;
// Workaround for a issue with Firefox 1.5rc2+
if (tinyMCE.isGecko && name == "src" && elm.src != null && elm.src != "")
v = elm.src;
// Workaround for a issue with Firefox 1.5rc2+
if (tinyMCE.isGecko && name == "href" && elm.href != null && elm.href != "")
v = elm.href;
if (name == "http-equiv" && tinyMCE.isMSIE)
v = elm.httpEquiv;
if (name == "style" && !tinyMCE.isOpera)
v = elm.style.cssText;
return (v && v != "") ? v : default_value;
};
TinyMCE_Engine.prototype.setAttrib = function(element, name, value, fix_value) {
if (typeof(value) == "number" && value != null)
value = "" + value;
if (fix_value) {
if (value == null)
value = "";
var re = new RegExp('[^0-9%]', 'g');
value = value.replace(re, '');
}
if (name == "style")
element.style.cssText = value;
if (name == "class")
element.className = value;
if (value != null && value != "" && value != -1)
element.setAttribute(name, value);
else
element.removeAttribute(name);
};
TinyMCE_Engine.prototype.setStyleAttrib = function(elm, name, value) {
eval('elm.style.' + name + '=value;');
// Style attrib deleted
if (tinyMCE.isMSIE && value == null || value == '') {
var str = tinyMCE.serializeStyle(tinyMCE.parseStyle(elm.style.cssText));
elm.style.cssText = str;
elm.setAttribute("style", str);
}
};
TinyMCE_Engine.prototype.switchClass = function(ei, c) {
var e;
if (tinyMCE.switchClassCache[ei])
e = tinyMCE.switchClassCache[ei];
else
e = tinyMCE.switchClassCache[ei] = document.getElementById(ei);
if (e) {
// Keep tile mode
if (tinyMCE.settings.button_tile_map && e.className && e.className.indexOf('mceTiledButton') == 0)
c = 'mceTiledButton ' + c;
e.className = c;
}
};
TinyMCE_Engine.prototype.getAbsPosition = function(n) {
var p = {absLeft : 0, absTop : 0};
while (n) {
p.absLeft += n.offsetLeft;
p.absTop += n.offsetTop;
n = n.offsetParent;
}
return p;
};
TinyMCE_Engine.prototype.prevNode = function(e, n) {
var a = n.split(','), i;
while ((e = e.previousSibling) != null) {
for (i=0; i<a.length; i++) {
if (e.nodeName == a[i])
return e;
}
}
return null;
};
TinyMCE_Engine.prototype.nextNode = function(e, n) {
var a = n.split(','), i;
while ((e = e.nextSibling) != null) {
for (i=0; i<a.length; i++) {
if (e.nodeName == a[i])
return e;
}
}
return null;
};
/* file:jscripts/tiny_mce/classes/TinyMCE_URL.class.js */
TinyMCE_Engine.prototype.parseURL = function(url_str) {
var urlParts = new Array();
if (url_str) {
var pos, lastPos;
// Parse protocol part
pos = url_str.indexOf('://');
if (pos != -1) {
urlParts['protocol'] = url_str.substring(0, pos);
lastPos = pos + 3;
}
// Find port or path start
for (var i=lastPos; i<url_str.length; i++) {
var chr = url_str.charAt(i);
if (chr == ':')
break;
if (chr == '/')
break;
}
pos = i;
// Get host
urlParts['host'] = url_str.substring(lastPos, pos);
// Get port
urlParts['port'] = "";
lastPos = pos;
if (url_str.charAt(pos) == ':') {
pos = url_str.indexOf('/', lastPos);
urlParts['port'] = url_str.substring(lastPos+1, pos);
}
// Get path
lastPos = pos;
pos = url_str.indexOf('?', lastPos);
if (pos == -1)
pos = url_str.indexOf('#', lastPos);
if (pos == -1)
pos = url_str.length;
urlParts['path'] = url_str.substring(lastPos, pos);
// Get query
lastPos = pos;
if (url_str.charAt(pos) == '?') {
pos = url_str.indexOf('#');
pos = (pos == -1) ? url_str.length : pos;
urlParts['query'] = url_str.substring(lastPos+1, pos);
}
// Get anchor
lastPos = pos;
if (url_str.charAt(pos) == '#') {
pos = url_str.length;
urlParts['anchor'] = url_str.substring(lastPos+1, pos);
}
}
return urlParts;
};
TinyMCE_Engine.prototype.serializeURL = function(up) {
var o = "";
if (up['protocol'])
o += up['protocol'] + "://";
if (up['host'])
o += up['host'];
if (up['port'])
o += ":" + up['port'];
if (up['path'])
o += up['path'];
if (up['query'])
o += "?" + up['query'];
if (up['anchor'])
o += "#" + up['anchor'];
return o;
};
TinyMCE_Engine.prototype.convertAbsoluteURLToRelativeURL = function(base_url, url_to_relative) {
var baseURL = this.parseURL(base_url);
var targetURL = this.parseURL(url_to_relative);
var strTok1;
var strTok2;
var breakPoint = 0;
var outPath = "";
var forceSlash = false;
if (targetURL.path == "")
targetURL.path = "/";
else
forceSlash = true;
// Crop away last path part
base_url = baseURL.path.substring(0, baseURL.path.lastIndexOf('/'));
strTok1 = base_url.split('/');
strTok2 = targetURL.path.split('/');
if (strTok1.length >= strTok2.length) {
for (var i=0; i<strTok1.length; i++) {
if (i >= strTok2.length || strTok1[i] != strTok2[i]) {
breakPoint = i + 1;
break;
}
}
}
if (strTok1.length < strTok2.length) {
for (var i=0; i<strTok2.length; i++) {
if (i >= strTok1.length || strTok1[i] != strTok2[i]) {
breakPoint = i + 1;
break;
}
}
}
if (breakPoint == 1)
return targetURL.path;
for (var i=0; i<(strTok1.length-(breakPoint-1)); i++)
outPath += "../";
for (var i=breakPoint-1; i<strTok2.length; i++) {
if (i != (breakPoint-1))
outPath += "/" + strTok2[i];
else
outPath += strTok2[i];
}
targetURL.protocol = null;
targetURL.host = null;
targetURL.port = null;
targetURL.path = outPath == "" && forceSlash ? "/" : outPath;
// Remove document prefix from local anchors
var fileName = baseURL.path;
var pos;
if ((pos = fileName.lastIndexOf('/')) != -1)
fileName = fileName.substring(pos + 1);
// Is local anchor
if (fileName == targetURL.path && targetURL.anchor != "")
targetURL.path = "";
// If empty and not local anchor force slash
if (targetURL.path == "" && !targetURL.anchor)
targetURL.path = "/";
return this.serializeURL(targetURL);
};
TinyMCE_Engine.prototype.convertRelativeToAbsoluteURL = function(base_url, relative_url) {
var baseURL = this.parseURL(base_url);
var relURL = this.parseURL(relative_url);
if (relative_url == "" || relative_url.charAt(0) == '/' || relative_url.indexOf('://') != -1 || relative_url.indexOf('mailto:') != -1 || relative_url.indexOf('javascript:') != -1)
return relative_url;
// Split parts
baseURLParts = baseURL['path'].split('/');
relURLParts = relURL['path'].split('/');
// Remove empty chunks
var newBaseURLParts = new Array();
for (var i=baseURLParts.length-1; i>=0; i--) {
if (baseURLParts[i].length == 0)
continue;
newBaseURLParts[newBaseURLParts.length] = baseURLParts[i];
}
baseURLParts = newBaseURLParts.reverse();
// Merge relURLParts chunks
var newRelURLParts = new Array();
var numBack = 0;
for (var i=relURLParts.length-1; i>=0; i--) {
if (relURLParts[i].length == 0 || relURLParts[i] == ".")
continue;
if (relURLParts[i] == '..') {
numBack++;
continue;
}
if (numBack > 0) {
numBack--;
continue;
}
newRelURLParts[newRelURLParts.length] = relURLParts[i];
}
relURLParts = newRelURLParts.reverse();
// Remove end from absolute path
var len = baseURLParts.length-numBack;
var absPath = (len <= 0 ? "" : "/") + baseURLParts.slice(0, len).join('/') + "/" + relURLParts.join('/');
var start = "", end = "";
// Build output URL
relURL.protocol = baseURL.protocol;
relURL.host = baseURL.host;
relURL.port = baseURL.port;
// Re-add trailing slash if it's removed
if (relURL.path.charAt(relURL.path.length-1) == "/")
absPath += "/";
relURL.path = absPath;
return this.serializeURL(relURL);
};
TinyMCE_Engine.prototype.convertURL = function(url, node, on_save) {
var prot = document.location.protocol;
var host = document.location.hostname;
var port = document.location.port;
// Pass through file protocol
if (prot == "file:")
return url;
// Something is wrong, remove weirdness
url = tinyMCE.regexpReplace(url, '(http|https):///', '/');
// Mailto link or anchor (Pass through)
if (url.indexOf('mailto:') != -1 || url.indexOf('javascript:') != -1 || tinyMCE.regexpReplace(url,'[ \t\r\n\+]|%20','').charAt(0) == "#")
return url;
// Fix relative/Mozilla
if (!tinyMCE.isMSIE && !on_save && url.indexOf("://") == -1 && url.charAt(0) != '/')
return tinyMCE.settings['base_href'] + url;
// Handle relative URLs
if (on_save && tinyMCE.getParam('relative_urls')) {
var curl = tinyMCE.convertRelativeToAbsoluteURL(tinyMCE.settings['base_href'], url);
if (curl.charAt(0) == '/')
curl = tinyMCE.settings['document_base_prefix'] + curl;
var urlParts = tinyMCE.parseURL(curl);
var tmpUrlParts = tinyMCE.parseURL(tinyMCE.settings['document_base_url']);
// Force relative
if (urlParts['host'] == tmpUrlParts['host'] && (urlParts['port'] == tmpUrlParts['port']))
return tinyMCE.convertAbsoluteURLToRelativeURL(tinyMCE.settings['document_base_url'], curl);
}
// Handle absolute URLs
if (!tinyMCE.getParam('relative_urls')) {
var urlParts = tinyMCE.parseURL(url);
var baseUrlParts = tinyMCE.parseURL(tinyMCE.settings['base_href']);
// Force absolute URLs from relative URLs
url = tinyMCE.convertRelativeToAbsoluteURL(tinyMCE.settings['base_href'], url);
// If anchor and path is the same page
if (urlParts['anchor'] && urlParts['path'] == baseUrlParts['path'])
return "#" + urlParts['anchor'];
}
// Remove current domain
if (tinyMCE.getParam('remove_script_host')) {
var start = "", portPart = "";
if (port != "")
portPart = ":" + port;
start = prot + "//" + host + portPart + "/";
if (url.indexOf(start) == 0)
url = url.substring(start.length-1);
}
return url;
};
TinyMCE_Engine.prototype.convertAllRelativeURLs = function(body) {
// Convert all image URL:s to absolute URL
var elms = body.getElementsByTagName("img");
for (var i=0; i<elms.length; i++) {
var src = tinyMCE.getAttrib(elms[i], 'src');
var msrc = tinyMCE.getAttrib(elms[i], 'mce_src');
if (msrc != "")
src = msrc;
if (src != "") {
src = tinyMCE.convertRelativeToAbsoluteURL(tinyMCE.settings['base_href'], src);
elms[i].setAttribute("src", src);
}
}
// Convert all link URL:s to absolute URL
var elms = body.getElementsByTagName("a");
for (var i=0; i<elms.length; i++) {
var href = tinyMCE.getAttrib(elms[i], 'href');
var mhref = tinyMCE.getAttrib(elms[i], 'mce_href');
if (mhref != "")
href = mhref;
if (href && href != "") {
href = tinyMCE.convertRelativeToAbsoluteURL(tinyMCE.settings['base_href'], href);
elms[i].setAttribute("href", href);
}
}
};
/* file:jscripts/tiny_mce/classes/TinyMCE_Array.class.js */
TinyMCE_Engine.prototype.clearArray = function(a) {
for (var k in a)
a[k] = null;
return a;
};
/* file:jscripts/tiny_mce/classes/TinyMCE_Event.class.js */
TinyMCE_Engine.prototype._setEventsEnabled = function(node, state) {
var events = new Array('onfocus','onblur','onclick','ondblclick',
'onmousedown','onmouseup','onmouseover','onmousemove',
'onmouseout','onkeypress','onkeydown','onkeydown','onkeyup');
var evs = tinyMCE.settings['event_elements'].split(',');
for (var y=0; y<evs.length; y++){
var elms = node.getElementsByTagName(evs[y]);
for (var i=0; i<elms.length; i++) {
var event = "";
for (var x=0; x<events.length; x++) {
if ((event = tinyMCE.getAttrib(elms[i], events[x])) != '') {
event = tinyMCE.cleanupEventStr("" + event);
if (!state)
event = "return true;" + event;
else
event = event.replace(/^return true;/gi, '');
elms[i].removeAttribute(events[x]);
elms[i].setAttribute(events[x], event);
}
}
}
}
};
TinyMCE_Engine.prototype._eventPatch = function(editor_id) {
var n, inst, win, e;
// Remove odd, error
if (typeof(tinyMCE) == "undefined")
return true;
try {
// Try selected instance first
if (tinyMCE.selectedInstance) {
win = tinyMCE.selectedInstance.getWin();
if (win && win.event) {
e = win.event;
if (!e.target)
e.target = e.srcElement;
TinyMCE_Engine.prototype.handleEvent(e);
return;
}
}
// Search for it
for (n in tinyMCE.instances) {
inst = tinyMCE.instances[n];
if (!tinyMCE.isInstance(inst))
continue;
tinyMCE.selectedInstance = inst;
win = inst.getWin();
if (win && win.event) {
e = win.event;
if (!e.target)
e.target = e.srcElement;
TinyMCE_Engine.prototype.handleEvent(e);
return;
}
}
} catch (ex) {
// Ignore error if iframe is pointing to external URL
}
};
TinyMCE_Engine.prototype.unloadHandler = function() {
tinyMCE.triggerSave(true, true);
};
TinyMCE_Engine.prototype.addEventHandlers = function(inst) {
var doc = inst.getDoc();
inst.switchSettings();
if (tinyMCE.isMSIE) {
tinyMCE.addEvent(doc, "keypress", TinyMCE_Engine.prototype._eventPatch);
tinyMCE.addEvent(doc, "keyup", TinyMCE_Engine.prototype._eventPatch);
tinyMCE.addEvent(doc, "keydown", TinyMCE_Engine.prototype._eventPatch);
tinyMCE.addEvent(doc, "mouseup", TinyMCE_Engine.prototype._eventPatch);
tinyMCE.addEvent(doc, "click", TinyMCE_Engine.prototype._eventPatch);
} else {
tinyMCE.addEvent(doc, "keypress", tinyMCE.handleEvent);
tinyMCE.addEvent(doc, "keydown", tinyMCE.handleEvent);
tinyMCE.addEvent(doc, "keyup", tinyMCE.handleEvent);
tinyMCE.addEvent(doc, "click", tinyMCE.handleEvent);
tinyMCE.addEvent(doc, "mouseup", tinyMCE.handleEvent);
tinyMCE.addEvent(doc, "mousedown", tinyMCE.handleEvent);
tinyMCE.addEvent(doc, "focus", tinyMCE.handleEvent);
tinyMCE.addEvent(doc, "blur", tinyMCE.handleEvent);
eval('try { doc.designMode = "On"; } catch(e) {}'); // Force designmode
}
};
TinyMCE_Engine.prototype.onMouseMove = function() {
var inst;
if (!tinyMCE.hasMouseMoved) {
inst = tinyMCE.selectedInstance;
// Workaround for bug #1437457 (Odd MSIE bug)
if (inst.isFocused) {
inst.undoBookmark = inst.selection.getBookmark();
tinyMCE.hasMouseMoved = true;
}
}
// tinyMCE.cancelEvent(inst.getWin().event);
// return false;
};
TinyMCE_Engine.prototype.cancelEvent = function(e) {
if (tinyMCE.isMSIE) {
e.returnValue = false;
e.cancelBubble = true;
} else
e.preventDefault();
};
TinyMCE_Engine.prototype.addEvent = function(o, n, h) {
if (o.attachEvent)
o.attachEvent("on" + n, h);
else
o.addEventListener(n, h, false);
};
TinyMCE_Engine.prototype.addSelectAccessibility = function(e, s, w) {
// Add event handlers
if (!s._isAccessible) {
s.onkeydown = tinyMCE.accessibleEventHandler;
s.onblur = tinyMCE.accessibleEventHandler;
s._isAccessible = true;
s._win = w;
}
return false;
};
TinyMCE_Engine.prototype.accessibleEventHandler = function(e) {
var win = this._win;
e = tinyMCE.isMSIE ? win.event : e;
var elm = tinyMCE.isMSIE ? e.srcElement : e.target;
// Unpiggyback onchange on blur
if (e.type == "blur") {
if (elm.oldonchange) {
elm.onchange = elm.oldonchange;
elm.oldonchange = null;
}
return true;
}
// Piggyback onchange
if (elm.nodeName == "SELECT" && !elm.oldonchange) {
elm.oldonchange = elm.onchange;
elm.onchange = null;
}
// Execute onchange and remove piggyback
if (e.keyCode == 13 || e.keyCode == 32) {
elm.onchange = elm.oldonchange;
elm.onchange();
elm.oldonchange = null;
tinyMCE.cancelEvent(e);
return false;
}
return true;
};
/* file:jscripts/tiny_mce/classes/TinyMCE_Selection.class.js */
function TinyMCE_Selection(inst) {
this.instance = inst;
};
TinyMCE_Selection.prototype = {
getSelectedHTML : function() {
var inst = this.instance;
var e, r = this.getRng(), h;
if (tinyMCE.isSafari) {
// Not realy perfect!!
return r.toString();
}
e = document.createElement("body");
if (tinyMCE.isGecko)
e.appendChild(r.cloneContents());
else
e.innerHTML = r.htmlText;
h = tinyMCE._cleanupHTML(inst, inst.contentDocument, inst.settings, e, e, false, true, false);
// When editing always use fonts internaly
if (tinyMCE.getParam("convert_fonts_to_spans"))
tinyMCE.convertSpansToFonts(inst.getDoc());
return h;
},
getSelectedText : function() {
var inst = this.instance;
var d, r, s, t;
if (tinyMCE.isMSIE) {
d = inst.getDoc();
if (d.selection.type == "Text") {
r = d.selection.createRange();
t = r.text;
} else
t = '';
} else {
s = this.getSel();
if (s && s.toString)
t = s.toString();
else
t = '';
}
return t;
},
getBookmark : function(simple) {
var rng = this.getRng();
var doc = this.instance.getDoc();
var sp, le, s, e, nl, i, si, ei;
var trng, sx, sy, xx = -999999999;
// Skip Opera for now
if (tinyMCE.isOpera)
return null;
sx = doc.body.scrollLeft + doc.documentElement.scrollLeft;
sy = doc.body.scrollTop + doc.documentElement.scrollTop;
if (tinyMCE.isSafari || tinyMCE.isGecko)
return {rng : rng, scrollX : sx, scrollY : sy};
if (tinyMCE.isMSIE) {
if (simple)
return {rng : rng};
if (rng.item) {
e = rng.item(0);
nl = doc.getElementsByTagName(e.nodeName);
for (i=0; i<nl.length; i++) {
if (e == nl[i]) {
sp = i;
break;
}
}
return {
tag : e.nodeName,
index : sp,
scrollX : sx,
scrollY : sy
};
} else {
trng = rng.duplicate();
trng.collapse(true);
sp = Math.abs(trng.move('character', xx));
trng = rng.duplicate();
trng.collapse(false);
le = Math.abs(trng.move('character', xx)) - sp;
return {
start : sp,
length : le,
scrollX : sx,
scrollY : sy
};
}
}
if (tinyMCE.isGecko) {
s = tinyMCE.getParentElement(rng.startContainer);
for (si=0; si<s.childNodes.length && s.childNodes[si] != rng.startContainer; si++) ;
nl = doc.getElementsByTagName(s.nodeName);
for (i=0; i<nl.length; i++) {
if (s == nl[i]) {
sp = i;
break;
}
}
e = tinyMCE.getParentElement(rng.endContainer);
for (ei=0; ei<e.childNodes.length && e.childNodes[ei] != rng.endContainer; ei++) ;
nl = doc.getElementsByTagName(e.nodeName);
for (i=0; i<nl.length; i++) {
if (e == nl[i]) {
le = i;
break;
}
}
//tinyMCE.debug(s.nodeName, sp, rng.startOffset, '-' , e.nodeName, le, rng.endOffset);
//tinyMCE.debug(sx, sy);
return {
startTag : s.nodeName,
start : sp,
startIndex : si,
endTag : e.nodeName,
end : le,
endIndex : ei,
startOffset : rng.startOffset,
endOffset : rng.endOffset,
scrollX : sx,
scrollY : sy
};
}
return null;
},
moveToBookmark : function(bookmark) {
var rng, nl, i;
var inst = this.instance;
var doc = inst.getDoc();
var win = inst.getWin();
var sel = this.getSel();
if (!bookmark)
return false;
if (tinyMCE.isSafari) {
sel.setBaseAndExtent(bookmark.startContainer, bookmark.startOffset, bookmark.endContainer, bookmark.endOffset);
return true;
}
if (tinyMCE.isMSIE) {
if (bookmark.rng) {
bookmark.rng.select();
return true;
}
win.focus();
if (bookmark.tag) {
rng = inst.getBody().createControlRange();
nl = doc.getElementsByTagName(bookmark.tag);
if (nl.length > bookmark.index)
rng.addElement(nl[bookmark.index]);
} else {
rng = inst.getSel().createRange();
rng.moveToElementText(inst.getBody());
rng.collapse(true);
rng.moveStart('character', bookmark.start);
rng.moveEnd('character', bookmark.length);
}
rng.select();
win.scrollTo(bookmark.scrollX, bookmark.scrollY);
return true;
}
if (tinyMCE.isGecko && bookmark.rng) {
sel.removeAllRanges();
sel.addRange(bookmark.rng);
win.scrollTo(bookmark.scrollX, bookmark.scrollY);
return true;
}
if (tinyMCE.isGecko) {
// try {
rng = doc.createRange();
nl = doc.getElementsByTagName(bookmark.startTag);
if (nl.length > bookmark.start)
rng.setStart(nl[bookmark.start].childNodes[bookmark.startIndex], bookmark.startOffset);
nl = doc.getElementsByTagName(bookmark.endTag);
if (nl.length > bookmark.end)
rng.setEnd(nl[bookmark.end].childNodes[bookmark.endIndex], bookmark.endOffset);
sel.removeAllRanges();
sel.addRange(rng);
/* } catch {
// Ignore
}*/
win.scrollTo(bookmark.scrollX, bookmark.scrollY);
return true;
}
return false;
},
selectNode : function(node, collapse, select_text_node, to_start) {
var inst = this.instance, sel, rng, nodes;
if (!node)
return;
if (typeof(collapse) == "undefined")
collapse = true;
if (typeof(select_text_node) == "undefined")
select_text_node = false;
if (typeof(to_start) == "undefined")
to_start = true;
if (tinyMCE.isMSIE) {
rng = inst.getBody().createTextRange();
try {
rng.moveToElementText(node);
if (collapse)
rng.collapse(to_start);
rng.select();
} catch (e) {
// Throws illigal agrument in MSIE some times
}
} else {
sel = this.getSel();
if (!sel)
return;
if (tinyMCE.isSafari) {
sel.setBaseAndExtent(node, 0, node, node.innerText.length);
if (collapse) {
if (to_start)
sel.collapseToStart();
else
sel.collapseToEnd();
}
this.scrollToNode(node);
return;
}
rng = inst.getDoc().createRange();
if (select_text_node) {
// Find first textnode in tree
nodes = tinyMCE.getNodeTree(node, new Array(), 3);
if (nodes.length > 0)
rng.selectNodeContents(nodes[0]);
else
rng.selectNodeContents(node);
} else
rng.selectNode(node);
if (collapse) {
// Special treatment of textnode collapse
if (!to_start && node.nodeType == 3) {
rng.setStart(node, node.nodeValue.length);
rng.setEnd(node, node.nodeValue.length);
} else
rng.collapse(to_start);
}
sel.removeAllRanges();
sel.addRange(rng);
}
this.scrollToNode(node);
// Set selected element
tinyMCE.selectedElement = null;
if (node.nodeType == 1)
tinyMCE.selectedElement = node;
},
scrollToNode : function(node) {
var inst = this.instance;
var pos, doc, scrollX, scrollY, height;
// Scroll to node position
pos = tinyMCE.getAbsPosition(node);
doc = inst.getDoc();
scrollX = doc.body.scrollLeft + doc.documentElement.scrollLeft;
scrollY = doc.body.scrollTop + doc.documentElement.scrollTop;
height = tinyMCE.isMSIE ? document.getElementById(inst.editorId).style.pixelHeight : inst.targetElement.clientHeight;
// Only scroll if out of visible area
if (!tinyMCE.settings['auto_resize'] && !(pos.absTop > scrollY && pos.absTop < (scrollY - 25 + height)))
inst.contentWindow.scrollTo(pos.absLeft, pos.absTop - height + 25);
},
getSel : function() {
var inst = this.instance;
if (tinyMCE.isMSIE && !tinyMCE.isOpera)
return inst.getDoc().selection;
return inst.contentWindow.getSelection();
},
getRng : function() {
var inst = this.instance;
var sel = this.getSel();
if (sel == null)
return null;
if (tinyMCE.isMSIE && !tinyMCE.isOpera)
return sel.createRange();
if (tinyMCE.isSafari && !sel.getRangeAt)
return '' + window.getSelection();
return sel.getRangeAt(0);
},
getFocusElement : function() {
var inst = this.instance;
if (tinyMCE.isMSIE && !tinyMCE.isOpera) {
var doc = inst.getDoc();
var rng = doc.selection.createRange();
// if (rng.collapse)
// rng.collapse(true);
var elm = rng.item ? rng.item(0) : rng.parentElement();
} else {
if (inst.isHidden())
return inst.getBody();
var sel = this.getSel();
var rng = this.getRng();
if (!sel || !rng)
return null;
var elm = rng.commonAncestorContainer;
//var elm = (sel && sel.anchorNode) ? sel.anchorNode : null;
// Handle selection a image or other control like element such as anchors
if (!rng.collapsed) {
// Is selection small
if (rng.startContainer == rng.endContainer) {
if (rng.startOffset - rng.endOffset < 2) {
if (rng.startContainer.hasChildNodes())
elm = rng.startContainer.childNodes[rng.startOffset];
}
}
}
// Get the element parent of the node
elm = tinyMCE.getParentElement(elm);
//if (tinyMCE.selectedElement != null && tinyMCE.selectedElement.nodeName.toLowerCase() == "img")
// elm = tinyMCE.selectedElement;
}
return elm;
}
};
/* file:jscripts/tiny_mce/classes/TinyMCE_UndoRedo.class.js */
function TinyMCE_UndoRedo(inst) {
this.instance = inst;
this.undoLevels = new Array();
this.undoIndex = 0;
this.typingUndoIndex = -1;
this.undoRedo = true;
};
TinyMCE_UndoRedo.prototype = {
add : function(l) {
var b;
if (l) {
this.undoLevels[this.undoLevels.length] = l;
return true;
}
var inst = this.instance;
if (this.typingUndoIndex != -1) {
this.undoIndex = this.typingUndoIndex;
// tinyMCE.debug("Override: " + this.undoIndex);
}
var newHTML = tinyMCE.trim(inst.getBody().innerHTML);
if (this.undoLevels[this.undoIndex] && newHTML != this.undoLevels[this.undoIndex].content) {
//tinyMCE.debug(newHTML, this.undoLevels[this.undoIndex]);
tinyMCE.dispatchCallback(inst, 'onchange_callback', 'onChange', inst);
// Time to compress
var customUndoLevels = tinyMCE.settings['custom_undo_redo_levels'];
if (customUndoLevels != -1 && this.undoLevels.length > customUndoLevels) {
for (var i=0; i<this.undoLevels.length-1; i++) {
//tinyMCE.debug(this.undoLevels[i] + "=" + this.undoLevels[i+1]);
this.undoLevels[i] = this.undoLevels[i+1];
}
this.undoLevels.length--;
this.undoIndex--;
}
b = inst.undoBookmark;
if (!b)
b = inst.selection.getBookmark();
this.undoIndex++;
this.undoLevels[this.undoIndex] = {
content : newHTML,
bookmark : b
};
this.undoLevels.length = this.undoIndex + 1;
//tinyMCE.debug("level added" + this.undoIndex);
return true;
// tinyMCE.debug(this.undoIndex + "," + (this.undoLevels.length-1));
}
return false;
},
undo : function() {
var inst = this.instance;
// Do undo
if (this.undoIndex > 0) {
this.undoIndex--;
tinyMCE.setInnerHTML(inst.getBody(), this.undoLevels[this.undoIndex].content);
inst.repaint();
if (inst.settings.custom_undo_redo_restore_selection)
inst.selection.moveToBookmark(this.undoLevels[this.undoIndex].bookmark);
}
// tinyMCE.debug("Undo - undo levels:" + this.undoLevels.length + ", undo index: " + this.undoIndex);
},
redo : function() {
var inst = this.instance;
tinyMCE.execCommand("mceEndTyping");
if (this.undoIndex < (this.undoLevels.length-1)) {
this.undoIndex++;
tinyMCE.setInnerHTML(inst.getBody(), this.undoLevels[this.undoIndex].content);
inst.repaint();
// if (this.undoIndex > 0)
// inst.selection.moveToBookmark(this.undoLevels[this.undoIndex-1].bookmark);
if (inst.settings.custom_undo_redo_restore_selection)
inst.selection.moveToBookmark(this.undoLevels[this.undoIndex].bookmark);
// tinyMCE.debug("Redo - undo levels:" + this.undoLevels.length + ", undo index: " + this.undoIndex);
}
tinyMCE.triggerNodeChange();
}
};
/* file:jscripts/tiny_mce/classes/TinyMCE_ForceParagraphs.class.js */
var TinyMCE_ForceParagraphs = {
_insertPara : function(inst, e) {
function isEmpty(para) {
function isEmptyHTML(html) {
return html.replace(new RegExp('[ \t\r\n]+', 'g'), '').toLowerCase() == "";
}
// Check for images
if (para.getElementsByTagName("img").length > 0)
return false;
// Check for tables
if (para.getElementsByTagName("table").length > 0)
return false;
// Check for HRs
if (para.getElementsByTagName("hr").length > 0)
return false;
// Check all textnodes
var nodes = tinyMCE.getNodeTree(para, new Array(), 3);
for (var i=0; i<nodes.length; i++) {
if (!isEmptyHTML(nodes[i].nodeValue))
return false;
}
// No images, no tables, no hrs, no text content then it's empty
return true;
}
var doc = inst.getDoc();
var sel = inst.getSel();
var win = inst.contentWindow;
var rng = sel.getRangeAt(0);
var body = doc.body;
var rootElm = doc.documentElement;
var blockName = "P";
// tinyMCE.debug(body.innerHTML);
// debug(e.target, sel.anchorNode.nodeName, sel.focusNode.nodeName, rng.startContainer, rng.endContainer, rng.commonAncestorContainer, sel.anchorOffset, sel.focusOffset, rng.toString());
// Setup before range
var rngBefore = doc.createRange();
rngBefore.setStart(sel.anchorNode, sel.anchorOffset);
rngBefore.collapse(true);
// Setup after range
var rngAfter = doc.createRange();
rngAfter.setStart(sel.focusNode, sel.focusOffset);
rngAfter.collapse(true);
// Setup start/end points
var direct = rngBefore.compareBoundaryPoints(rngBefore.START_TO_END, rngAfter) < 0;
var startNode = direct ? sel.anchorNode : sel.focusNode;
var startOffset = direct ? sel.anchorOffset : sel.focusOffset;
var endNode = direct ? sel.focusNode : sel.anchorNode;
var endOffset = direct ? sel.focusOffset : sel.anchorOffset;
startNode = startNode.nodeName == "BODY" ? startNode.firstChild : startNode;
endNode = endNode.nodeName == "BODY" ? endNode.firstChild : endNode;
// tinyMCE.debug(startNode, endNode);
// Get block elements
var startBlock = tinyMCE.getParentBlockElement(startNode);
var endBlock = tinyMCE.getParentBlockElement(endNode);
// Use current block name
if (startBlock != null) {
blockName = startBlock.nodeName;
// Use P instead
if (blockName == "TD" || blockName == "TABLE" || (blockName == "DIV" && new RegExp('left|right', 'gi').test(startBlock.style.cssFloat)))
blockName = "P";
}
// Within a list use normal behaviour
if (tinyMCE.getParentElement(startBlock, "OL,UL") != null)
return false;
// Within a table create new paragraphs
if ((startBlock != null && startBlock.nodeName == "TABLE") || (endBlock != null && endBlock.nodeName == "TABLE"))
startBlock = endBlock = null;
// Setup new paragraphs
var paraBefore = (startBlock != null && startBlock.nodeName == blockName) ? startBlock.cloneNode(false) : doc.createElement(blockName);
var paraAfter = (endBlock != null && endBlock.nodeName == blockName) ? endBlock.cloneNode(false) : doc.createElement(blockName);
// Is header, then force paragraph under
if (/^(H[1-6])$/.test(blockName))
paraAfter = doc.createElement("p");
// Setup chop nodes
var startChop = startNode;
var endChop = endNode;
// Get startChop node
node = startChop;
do {
if (node == body || node.nodeType == 9 || tinyMCE.isBlockElement(node))
break;
startChop = node;
} while ((node = node.previousSibling ? node.previousSibling : node.parentNode));
// Get endChop node
node = endChop;
do {
if (node == body || node.nodeType == 9 || tinyMCE.isBlockElement(node))
break;
endChop = node;
} while ((node = node.nextSibling ? node.nextSibling : node.parentNode));
// Fix when only a image is within the TD
if (startChop.nodeName == "TD")
startChop = startChop.firstChild;
if (endChop.nodeName == "TD")
endChop = endChop.lastChild;
// If not in a block element
if (startBlock == null) {
// Delete selection
rng.deleteContents();
sel.removeAllRanges();
if (startChop != rootElm && endChop != rootElm) {
// Insert paragraph before
rngBefore = rng.cloneRange();
if (startChop == body)
rngBefore.setStart(startChop, 0);
else
rngBefore.setStartBefore(startChop);
paraBefore.appendChild(rngBefore.cloneContents());
// Insert paragraph after
if (endChop.parentNode.nodeName == blockName)
endChop = endChop.parentNode;
// If not after image
//if (rng.startContainer.nodeName != "BODY" && rng.endContainer.nodeName != "BODY")
rng.setEndAfter(endChop);
if (endChop.nodeName != "#text" && endChop.nodeName != "BODY")
rngBefore.setEndAfter(endChop);
var contents = rng.cloneContents();
if (contents.firstChild && (contents.firstChild.nodeName == blockName || contents.firstChild.nodeName == "BODY"))
paraAfter.innerHTML = contents.firstChild.innerHTML;
else
paraAfter.appendChild(contents);
// Check if it's a empty paragraph
if (isEmpty(paraBefore))
paraBefore.innerHTML = " ";
// Check if it's a empty paragraph
if (isEmpty(paraAfter))
paraAfter.innerHTML = " ";
// Delete old contents
rng.deleteContents();
rngAfter.deleteContents();
rngBefore.deleteContents();
// Insert new paragraphs
paraAfter.normalize();
rngBefore.insertNode(paraAfter);
paraBefore.normalize();
rngBefore.insertNode(paraBefore);
// tinyMCE.debug("1: ", paraBefore.innerHTML, paraAfter.innerHTML);
} else {
body.innerHTML = "<" + blockName + "> </" + blockName + "><" + blockName + "> </" + blockName + ">";
paraAfter = body.childNodes[1];
}
inst.selection.selectNode(paraAfter, true, true);
return true;
}
// Place first part within new paragraph
if (startChop.nodeName == blockName)
rngBefore.setStart(startChop, 0);
else
rngBefore.setStartBefore(startChop);
rngBefore.setEnd(startNode, startOffset);
paraBefore.appendChild(rngBefore.cloneContents());
// Place secound part within new paragraph
rngAfter.setEndAfter(endChop);
rngAfter.setStart(endNode, endOffset);
var contents = rngAfter.cloneContents();
if (contents.firstChild && contents.firstChild.nodeName == blockName) {
/* var nodes = contents.firstChild.childNodes;
for (var i=0; i<nodes.length; i++) {
//tinyMCE.debug(nodes[i].nodeName);
if (nodes[i].nodeName != "BODY")
paraAfter.appendChild(nodes[i]);
}
*/
paraAfter.innerHTML = contents.firstChild.innerHTML;
} else
paraAfter.appendChild(contents);
// Check if it's a empty paragraph
if (isEmpty(paraBefore))
paraBefore.innerHTML = " ";
// Check if it's a empty paragraph
if (isEmpty(paraAfter))
paraAfter.innerHTML = " ";
// Create a range around everything
var rng = doc.createRange();
if (!startChop.previousSibling && startChop.parentNode.nodeName.toUpperCase() == blockName) {
rng.setStartBefore(startChop.parentNode);
} else {
if (rngBefore.startContainer.nodeName.toUpperCase() == blockName && rngBefore.startOffset == 0)
rng.setStartBefore(rngBefore.startContainer);
else
rng.setStart(rngBefore.startContainer, rngBefore.startOffset);
}
if (!endChop.nextSibling && endChop.parentNode.nodeName.toUpperCase() == blockName)
rng.setEndAfter(endChop.parentNode);
else
rng.setEnd(rngAfter.endContainer, rngAfter.endOffset);
// Delete all contents and insert new paragraphs
rng.deleteContents();
rng.insertNode(paraAfter);
rng.insertNode(paraBefore);
//tinyMCE.debug("2", paraBefore.innerHTML, paraAfter.innerHTML);
// Normalize
paraAfter.normalize();
paraBefore.normalize();
inst.selection.selectNode(paraAfter, true, true);
return true;
},
_handleBackSpace : function(inst) {
var r = inst.getRng();
var sn = r.startContainer;
if (sn && sn.nextSibling && sn.nextSibling.nodeName == "BR")
sn.nextSibling.parentNode.removeChild(sn.nextSibling);
return false;
}
};
/* file:jscripts/tiny_mce/classes/TinyMCE_Layer.class.js */
function TinyMCE_Layer(id, bm) {
this.id = id;
this.blockerElement = null;
this.events = false;
this.element = null;
this.blockMode = typeof(bm) != 'undefined' ? bm : true;
};
TinyMCE_Layer.prototype = {
moveRelativeTo : function(re, p) {
var rep = this.getAbsPosition(re);
var w = parseInt(re.offsetWidth);
var h = parseInt(re.offsetHeight);
var e = this.getElement();
var ew = parseInt(e.offsetWidth);
var eh = parseInt(e.offsetHeight);
var x, y;
switch (p) {
case "tl":
x = rep.absLeft;
y = rep.absTop;
break;
case "tr":
x = rep.absLeft + w;
y = rep.absTop;
break;
case "bl":
x = rep.absLeft;
y = rep.absTop + h;
break;
case "br":
x = rep.absLeft + w;
y = rep.absTop + h;
break;
case "cc":
x = rep.absLeft + (w / 2) - (ew / 2);
y = rep.absTop + (h / 2) - (eh / 2);
break;
}
this.moveTo(x, y);
},
moveBy : function(x, y) {
var e = this.getElement();
this.moveTo(parseInt(e.style.left) + x, parseInt(e.style.top) + y);
},
moveTo : function(x, y) {
var e = this.getElement();
e.style.left = x + "px";
e.style.top = y + "px";
this.updateBlocker();
},
resizeBy : function(w, h) {
var e = this.getElement();
this.resizeTo(parseInt(e.style.width) + w, parseInt(e.style.height) + h);
},
resizeTo : function(w, h) {
var e = this.getElement();
e.style.width = w + "px";
e.style.height = h + "px";
this.updateBlocker();
},
show : function() {
this.getElement().style.display = 'block';
this.updateBlocker();
},
hide : function() {
this.getElement().style.display = 'none';
this.updateBlocker();
},
isVisible : function() {
return this.getElement().style.display == 'block';
},
getElement : function() {
if (!this.element)
this.element = document.getElementById(this.id);
return this.element;
},
setBlockMode : function(s) {
this.blockMode = s;
},
updateBlocker : function() {
var e, b, x, y, w, h;
b = this.getBlocker();
if (b) {
if (this.blockMode) {
e = this.getElement();
x = this.parseInt(e.style.left);
y = this.parseInt(e.style.top);
w = this.parseInt(e.offsetWidth);
h = this.parseInt(e.offsetHeight);
b.style.left = x + 'px';
b.style.top = y + 'px';
b.style.width = w + 'px';
b.style.height = h + 'px';
b.style.display = e.style.display;
} else
b.style.display = 'none';
}
},
getBlocker : function() {
var d, b;
if (!this.blockerElement && this.blockMode) {
d = document;
b = d.createElement("iframe");
b.style.cssText = 'display: none; position: absolute; left: 0; top: 0';
b.src = 'javascript:false;';
b.frameBorder = '0';
b.scrolling = 'no';
d.body.appendChild(b);
this.blockerElement = b;
}
return this.blockerElement;
},
getAbsPosition : function(n) {
var p = {absLeft : 0, absTop : 0};
while (n) {
p.absLeft += n.offsetLeft;
p.absTop += n.offsetTop;
n = n.offsetParent;
}
return p;
},
create : function(n, c, p) {
var d = document, e = d.createElement(n);
e.setAttribute('id', this.id);
if (c)
e.className = c;
if (!p)
p = d.body;
p.appendChild(e);
return this.element = e;
},
/*
addCSSClass : function(e, c) {
this.removeCSSClass(e, c);
var a = this.explode(' ', e.className);
a[a.length] = c;
e.className = a.join(' ');
},
removeCSSClass : function(e, c) {
var a = this.explode(' ', e.className), i;
for (i=0; i<a.length; i++) {
if (a[i] == c)
a[i] = '';
}
e.className = a.join(' ');
},
explode : function(d, s) {
var ar = s.split(d);
var oar = new Array();
for (var i = 0; i<ar.length; i++) {
if (ar[i] != "")
oar[oar.length] = ar[i];
}
return oar;
},
*/
parseInt : function(s) {
if (s == null || s == '')
return 0;
return parseInt(s);
}
};
/* file:jscripts/tiny_mce/classes/TinyMCE_Menu.class.js */
function TinyMCE_Menu() {
var id;
if (typeof(tinyMCE.menuCounter) == "undefined")
tinyMCE.menuCounter = 0;
id = "mc_menu_" + tinyMCE.menuCounter++;
TinyMCE_Layer.call(this, id, true);
this.id = id;
this.items = new Array();
this.needsUpdate = true;
};
// Extends the TinyMCE_Layer class
TinyMCE_Menu.prototype = tinyMCE.extend(TinyMCE_Layer.prototype, {
init : function(s) {
var n;
// Default params
this.settings = {
separator_class : 'mceMenuSeparator',
title_class : 'mceMenuTitle',
disabled_class : 'mceMenuDisabled',
menu_class : 'mceMenu',
drop_menu : true
};
for (n in s)
this.settings[n] = s[n];
this.create('div', this.settings.menu_class);
},
clear : function() {
this.items = new Array();
},
addTitle : function(t) {
this.add({type : 'title', text : t});
},
addDisabled : function(t) {
this.add({type : 'disabled', text : t});
},
addSeparator : function() {
this.add({type : 'separator'});
},
addItem : function(t, js) {
this.add({text : t, js : js});
},
add : function(mi) {
this.items[this.items.length] = mi;
this.needsUpdate = true;
},
update : function() {
var e = this.getElement(), h = '', i, t, m = this.items, s = this.settings;
if (this.settings.drop_menu)
h += '<span class="mceMenuLine"></span>';
h += '<table border="0" cellpadding="0" cellspacing="0">';
for (i=0; i<m.length; i++) {
t = tinyMCE.xmlEncode(m[i].text);
c = m[i].class_name ? ' class="' + m[i].class_name + '"' : '';
switch (m[i].type) {
case 'separator':
h += '<tr class="' + s.separator_class + '"><td>';
break;
case 'title':
h += '<tr class="' + s.title_class + '"><td><span' + c +'>' + t + '</span>';
break;
case 'disabled':
h += '<tr class="' + s.disabled_class + '"><td><span' + c +'>' + t + '</span>';
break;
default:
h += '<tr><td><a href="javascript:void(0);" onmousedown="' + tinyMCE.xmlEncode(m[i].js) + ';return false;"><span' + c +'>' + t + '</span></a>';
}
h += '</td></tr>';
}
h += '</table>';
e.innerHTML = h;
this.needsUpdate = false;
this.updateBlocker();
},
show : function() {
var nl, i;
if (tinyMCE.lastMenu == this)
return;
if (this.needsUpdate)
this.update();
if (tinyMCE.lastMenu && tinyMCE.lastMenu != this)
tinyMCE.lastMenu.hide();
this.parent.show.call(this);
if (!tinyMCE.isOpera) {
// Accessibility stuff
/* nl = this.getElement().getElementsByTagName("a");
if (nl.length > 0)
nl[0].focus();*/
}
tinyMCE.lastMenu = this;
}
});
/* file:jscripts/tiny_mce/classes/TinyMCE_Debug.class.js */
TinyMCE_Engine.prototype.debug = function() {
var m = "", e, a, i;
e = document.getElementById("tinymce_debug");
if (!e) {
var d = document.createElement("div");
d.setAttribute("className", "debugger");
d.className = "debugger";
d.innerHTML = 'Debug output:<textarea id="tinymce_debug" style="width: 100%; height: 300px" wrap="nowrap" mce_editable="false"></textarea>';
document.body.appendChild(d);
e = document.getElementById("tinymce_debug");
}
a = this.debug.arguments;
for (i=0; i<a.length; i++) {
m += a[i];
if (i<a.length-1)
m += ', ';
}
e.value += m + "\n";
}; | z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/tiny_mce_src.js | tiny_mce_src.js |
var tinyMCE = null, tinyMCELang = null;
function TinyMCE_Popup() {
};
TinyMCE_Popup.prototype.init = function() {
var win = window.opener ? window.opener : window.dialogArguments;
var inst;
if (!win) {
// Try parent
win = parent.parent;
// Try top
if (typeof(win.tinyMCE) == "undefined")
win = top;
}
window.opener = win;
this.windowOpener = win;
this.onLoadEval = "";
// Setup parent references
tinyMCE = win.tinyMCE;
tinyMCELang = win.tinyMCELang;
if (!tinyMCE) {
alert("tinyMCE object reference not found from popup.");
return;
}
inst = tinyMCE.selectedInstance;
this.isWindow = tinyMCE.getWindowArg('mce_inside_iframe', false) == false;
this.storeSelection = (tinyMCE.isMSIE && !tinyMCE.isOpera) && !this.isWindow && tinyMCE.getWindowArg('mce_store_selection', true);
if (this.isWindow)
window.focus();
// Store selection
if (this.storeSelection)
inst.selectionBookmark = inst.selection.getBookmark(true);
// Setup dir
if (tinyMCELang['lang_dir'])
document.dir = tinyMCELang['lang_dir'];
// Setup title
var re = new RegExp('{|\\\$|}', 'g');
var title = document.title.replace(re, "");
if (typeof tinyMCELang[title] != "undefined") {
var divElm = document.createElement("div");
divElm.innerHTML = tinyMCELang[title];
document.title = divElm.innerHTML;
if (tinyMCE.setWindowTitle != null)
tinyMCE.setWindowTitle(window, divElm.innerHTML);
}
// Output Popup CSS class
document.write('<link href="' + tinyMCE.getParam("popups_css") + '" rel="stylesheet" type="text/css">');
tinyMCE.addEvent(window, "load", this.onLoad);
};
TinyMCE_Popup.prototype.onLoad = function() {
var dir, i, elms, body = document.body;
if (tinyMCE.getWindowArg('mce_replacevariables', true))
body.innerHTML = tinyMCE.applyTemplate(body.innerHTML, tinyMCE.windowArgs);
dir = tinyMCE.selectedInstance.settings['directionality'];
if (dir == "rtl" && document.forms && document.forms.length > 0) {
elms = document.forms[0].elements;
for (i=0; i<elms.length; i++) {
if ((elms[i].type == "text" || elms[i].type == "textarea") && elms[i].getAttribute("dir") != "ltr")
elms[i].dir = dir;
}
}
if (body.style.display == 'none')
body.style.display = 'block';
// Execute real onload (Opera fix)
if (tinyMCEPopup.onLoadEval != "")
eval(tinyMCEPopup.onLoadEval);
};
TinyMCE_Popup.prototype.executeOnLoad = function(str) {
if (tinyMCE.isOpera)
this.onLoadEval = str;
else
eval(str);
};
TinyMCE_Popup.prototype.resizeToInnerSize = function() {
// Netscape 7.1 workaround
if (this.isWindow && tinyMCE.isNS71) {
window.resizeBy(0, 10);
return;
}
if (this.isWindow) {
var doc = document;
var body = doc.body;
var oldMargin, wrapper, iframe, nodes, dx, dy;
if (body.style.display == 'none')
body.style.display = 'block';
// Remove margin
oldMargin = body.style.margin;
body.style.margin = '0';
// Create wrapper
wrapper = doc.createElement("div");
wrapper.id = 'mcBodyWrapper';
wrapper.style.display = 'none';
wrapper.style.margin = '0';
// Wrap body elements
nodes = doc.body.childNodes;
for (var i=nodes.length-1; i>=0; i--) {
if (wrapper.hasChildNodes())
wrapper.insertBefore(nodes[i].cloneNode(true), wrapper.firstChild);
else
wrapper.appendChild(nodes[i].cloneNode(true));
nodes[i].parentNode.removeChild(nodes[i]);
}
// Add wrapper
doc.body.appendChild(wrapper);
// Create iframe
iframe = document.createElement("iframe");
iframe.id = "mcWinIframe";
iframe.src = document.location.href.toLowerCase().indexOf('https') == -1 ? "about:blank" : tinyMCE.settings['default_document'];
iframe.width = "100%";
iframe.height = "100%";
iframe.style.margin = '0';
// Add iframe
doc.body.appendChild(iframe);
// Measure iframe
iframe = document.getElementById('mcWinIframe');
dx = tinyMCE.getWindowArg('mce_width') - iframe.clientWidth;
dy = tinyMCE.getWindowArg('mce_height') - iframe.clientHeight;
// Resize window
// tinyMCE.debug(tinyMCE.getWindowArg('mce_width') + "," + tinyMCE.getWindowArg('mce_height') + " - " + dx + "," + dy);
window.resizeBy(dx, dy);
// Hide iframe and show wrapper
body.style.margin = oldMargin;
iframe.style.display = 'none';
wrapper.style.display = 'block';
}
};
TinyMCE_Popup.prototype.resizeToContent = function() {
var isMSIE = (navigator.appName == "Microsoft Internet Explorer");
var isOpera = (navigator.userAgent.indexOf("Opera") != -1);
if (isOpera)
return;
if (isMSIE) {
try { window.resizeTo(10, 10); } catch (e) {}
var elm = document.body;
var width = elm.offsetWidth;
var height = elm.offsetHeight;
var dx = (elm.scrollWidth - width) + 4;
var dy = elm.scrollHeight - height;
try { window.resizeBy(dx, dy); } catch (e) {}
} else {
window.scrollBy(1000, 1000);
if (window.scrollX > 0 || window.scrollY > 0) {
window.resizeBy(window.innerWidth * 2, window.innerHeight * 2);
window.sizeToContent();
window.scrollTo(0, 0);
var x = parseInt(screen.width / 2.0) - (window.outerWidth / 2.0);
var y = parseInt(screen.height / 2.0) - (window.outerHeight / 2.0);
window.moveTo(x, y);
}
}
};
TinyMCE_Popup.prototype.getWindowArg = function(name, default_value) {
return tinyMCE.getWindowArg(name, default_value);
};
TinyMCE_Popup.prototype.restoreSelection = function() {
if (this.storeSelection) {
var inst = tinyMCE.selectedInstance;
inst.getWin().focus();
if (inst.selectionBookmark)
inst.selection.moveToBookmark(inst.selectionBookmark);
}
};
TinyMCE_Popup.prototype.execCommand = function(command, user_interface, value) {
var inst = tinyMCE.selectedInstance;
this.restoreSelection();
inst.execCommand(command, user_interface, value);
// Store selection
if (this.storeSelection)
inst.selectionBookmark = inst.selection.getBookmark(true);
};
TinyMCE_Popup.prototype.close = function() {
tinyMCE.closeWindow(window);
};
TinyMCE_Popup.prototype.pickColor = function(e, element_id) {
tinyMCE.selectedInstance.execCommand('mceColorPicker', true, {
element_id : element_id,
document : document,
window : window,
store_selection : false
});
};
TinyMCE_Popup.prototype.openBrowser = function(element_id, type, option) {
var cb = tinyMCE.getParam(option, tinyMCE.getParam("file_browser_callback"));
var url = document.getElementById(element_id).value;
tinyMCE.setWindowArg("window", window);
tinyMCE.setWindowArg("document", document);
// Call to external callback
if (eval('typeof(tinyMCEPopup.windowOpener.' + cb + ')') == "undefined")
alert("Callback function: " + cb + " could not be found.");
else
eval("tinyMCEPopup.windowOpener." + cb + "(element_id, url, type, window);");
};
// Setup global instance
var tinyMCEPopup = new TinyMCE_Popup();
tinyMCEPopup.init(); | z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/tiny_mce_popup.js | tiny_mce_popup.js |
tinyMCE.importPluginLanguagePack('directionality','en,tr,sv,fr_ca,zh_cn,cs,da,he,nb,de,hu,ru,ru_KOI8-R,ru_UTF-8,nn,es,cy,is,pl,nl,fr,pt_br');var TinyMCE_DirectionalityPlugin={getInfo:function(){return{longname:'Directionality',author:'Moxiecode Systems',authorurl:'http://tinymce.moxiecode.com',infourl:'http://tinymce.moxiecode.com/tinymce/docs/plugin_directionality.html',version:tinyMCE.majorVersion+"."+tinyMCE.minorVersion};},getControlHTML:function(cn){switch(cn){case"ltr":return tinyMCE.getButtonHTML(cn,'lang_directionality_ltr_desc','{$pluginurl}/images/ltr.gif','mceDirectionLTR');case"rtl":return tinyMCE.getButtonHTML(cn,'lang_directionality_rtl_desc','{$pluginurl}/images/rtl.gif','mceDirectionRTL');}return"";},execCommand:function(editor_id,element,command,user_interface,value){switch(command){case"mceDirectionLTR":var inst=tinyMCE.getInstanceById(editor_id);var elm=tinyMCE.getParentElement(inst.getFocusElement(),"p,div,td,h1,h2,h3,h4,h5,h6,pre,address");if(elm)elm.setAttribute("dir","ltr");tinyMCE.triggerNodeChange(false);return true;case"mceDirectionRTL":var inst=tinyMCE.getInstanceById(editor_id);var elm=tinyMCE.getParentElement(inst.getFocusElement(),"p,div,td,h1,h2,h3,h4,h5,h6,pre,address");if(elm)elm.setAttribute("dir","rtl");tinyMCE.triggerNodeChange(false);return true;}return false;},handleNodeChange:function(editor_id,node,undo_index,undo_levels,visual_aid,any_selection){function getAttrib(elm,name){return elm.getAttribute(name)?elm.getAttribute(name):"";}if(node==null)return;var elm=tinyMCE.getParentElement(node,"p,div,td,h1,h2,h3,h4,h5,h6,pre,address");if(!elm){tinyMCE.switchClass(editor_id+'_ltr','mceButtonDisabled');tinyMCE.switchClass(editor_id+'_rtl','mceButtonDisabled');return true;}tinyMCE.switchClass(editor_id+'_ltr','mceButtonNormal');tinyMCE.switchClass(editor_id+'_rtl','mceButtonNormal');var dir=getAttrib(elm,"dir");if(dir=="ltr"||dir=="")tinyMCE.switchClass(editor_id+'_ltr','mceButtonSelected');else tinyMCE.switchClass(editor_id+'_rtl','mceButtonSelected');return true;}};tinyMCE.addPlugin("directionality",TinyMCE_DirectionalityPlugin); | z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/plugins/directionality/editor_plugin.js | editor_plugin.js |
tinyMCE.importPluginLanguagePack('fullpage','en,tr,sv');var TinyMCE_FullPagePlugin={getInfo:function(){return{longname:'Fullpage',author:'Moxiecode Systems',authorurl:'http://tinymce.moxiecode.com',infourl:'http://tinymce.moxiecode.com/tinymce/docs/plugin_fullpage.html',version:tinyMCE.majorVersion+"."+tinyMCE.minorVersion};},getControlHTML:function(cn){switch(cn){case"fullpage":return tinyMCE.getButtonHTML(cn,'lang_fullpage_desc','{$pluginurl}/images/fullpage.gif','mceFullPageProperties');}return"";},execCommand:function(editor_id,element,command,user_interface,value){switch(command){case"mceFullPageProperties":var template=new Array();template['file']='../../plugins/fullpage/fullpage.htm';template['width']=430;template['height']=485+(tinyMCE.isOpera?5:0);template['width']+=tinyMCE.getLang('lang_fullpage_delta_width',0);template['height']+=tinyMCE.getLang('lang_fullpage_delta_height',0);tinyMCE.openWindow(template,{editor_id:editor_id,inline:"yes"});return true;case"mceFullPageUpdate":TinyMCE_FullPagePlugin._addToHead(tinyMCE.getInstanceById(editor_id));return true;}return false;},cleanup:function(type,content,inst){switch(type){case"insert_to_editor":var tmp=content.toLowerCase();var pos=tmp.indexOf('<body'),pos2;if(pos!=-1){pos=tmp.indexOf('>',pos);pos2=tmp.lastIndexOf('</body>');inst.fullpageTopContent=content.substring(0,pos+1);content=content.substring(pos+1,pos2);}else{if(!inst.fullpageTopContent){var docType=tinyMCE.getParam("fullpage_default_doctype",'<!DOCTYPE html PUBLIC "-/'+'/W3C//DTD XHTML 1.0 Transitional/'+'/EN" "http:/'+'/www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">');var enc=tinyMCE.getParam("fullpage_default_encoding",'utf-8');var title=tinyMCE.getParam("fullpage_default_title",'Untitled document');var lang=tinyMCE.getParam("fullpage_default_langcode",'en');var pi=tinyMCE.getParam("fullpage_default_xml_pi",true);var ff=tinyMCE.getParam("fullpage_default_font_family","");var fz=tinyMCE.getParam("fullpage_default_font_size","");var ds=tinyMCE.getParam("fullpage_default_style","");var dtc=tinyMCE.getParam("fullpage_default_text_color","");title=title.replace(/&/g,'&');title=title.replace(/\"/g,'"');title=title.replace(/</g,'<');title=title.replace(/>/g,'>');tmp='';if(pi)tmp+='<?xml version="1.0" encoding="'+enc+'"?>\n';tmp+=docType+'\n';tmp+='<html xmlns="http:/'+'/www.w3.org/1999/xhtml" lang="'+lang+'" xml:lang="'+lang+'">\n';tmp+='<head>\n';tmp+='\t<title>'+title+'</title>\n';tmp+='\t<meta http-equiv="Content-Type" content="text/html; charset='+enc+'" />\n';tmp+='</head>\n';tmp+='<body';if(ff!=''||fz!=''){tmp+=' style="';if(ds!='')tmp+=ds+";";if(ff!='')tmp+='font-family: '+ff+";";if(fz!='')tmp+='font-size: '+fz+";";tmp+='"';}if(dtc!='')tmp+=' text="'+dtc+'"';tmp+='>\n';inst.fullpageTopContent=tmp;}}this._addToHead(inst);break;case"get_from_editor":if(inst.fullpageTopContent)content=inst.fullpageTopContent+content+"\n</body>\n</html>";break;}return content;},_addToHead:function(inst){var doc=inst.getDoc();var head=doc.getElementsByTagName("head")[0];var body=doc.body;var h=inst.fullpageTopContent;var e=doc.createElement("body");var nl,i,le,tmp;h=h.replace(/(\r|\n)/gi,'');h=h.replace(/<\?[^\>]*\>/gi,'');h=h.replace(/<\/?(!DOCTYPE|head|html)[^\>]*\>/gi,'');h=h.replace(/<script(.*?)<\/script>/gi,'');h=h.replace(/<title(.*?)<\/title>/gi,'');h=h.replace(/<(meta|base)[^>]*>/gi,'');h=h.replace(/<link([^>]*)\/>/gi,'<pre mce_type="link" $1></pre>');h=h.replace(/<body/gi,'<div mce_type="body"');h+='</div>';e.innerHTML=h;body.vLink=body.aLink=body.link=body.text='';body.style.cssText='';nl=head.getElementsByTagName('link');for(i=0;i<nl.length;i++){if(tinyMCE.getAttrib(nl[i],'mce_head')=="true")nl[i].parentNode.removeChild(nl[i]);}nl=e.getElementsByTagName('pre');for(i=0;i<nl.length;i++){tmp=tinyMCE.getAttrib(nl[i],'media');if(tinyMCE.getAttrib(nl[i],'mce_type')=="link"&&(tmp==""||tmp=="screen"||tmp=="all")&&tinyMCE.getAttrib(nl[i],'rel')=="stylesheet"){le=doc.createElement("link");le.rel="stylesheet";le.href=tinyMCE.getAttrib(nl[i],'href');le.setAttribute("mce_head","true");head.appendChild(le);}}nl=e.getElementsByTagName('div');if(nl.length>0){body.style.cssText=tinyMCE.getAttrib(nl[0],'style');if((tmp=tinyMCE.getAttrib(nl[0],'leftmargin'))!=''&&body.style.marginLeft=='')body.style.marginLeft=tmp+"px";if((tmp=tinyMCE.getAttrib(nl[0],'rightmargin'))!=''&&body.style.marginRight=='')body.style.marginRight=tmp+"px";if((tmp=tinyMCE.getAttrib(nl[0],'topmargin'))!=''&&body.style.marginTop=='')body.style.marginTop=tmp+"px";if((tmp=tinyMCE.getAttrib(nl[0],'bottommargin'))!=''&&body.style.marginBottom=='')body.style.marginBottom=tmp+"px";body.dir=tinyMCE.getAttrib(nl[0],'dir');body.vLink=tinyMCE.getAttrib(nl[0],'vlink');body.aLink=tinyMCE.getAttrib(nl[0],'alink');body.link=tinyMCE.getAttrib(nl[0],'link');body.text=tinyMCE.getAttrib(nl[0],'text');if((tmp=tinyMCE.getAttrib(nl[0],'background'))!='')body.style.backgroundImage=tmp;if((tmp=tinyMCE.getAttrib(nl[0],'bgcolor'))!='')body.style.backgroundColor=tmp;}}};tinyMCE.addPlugin("fullpage",TinyMCE_FullPagePlugin); | z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/plugins/fullpage/editor_plugin.js | editor_plugin.js |
tinyMCE.addToLang('fullpage',{
title : 'Thuộc tính văn bản',
desc : 'Thuộc tính văn bản',
meta_tab : 'Chung',
appearance_tab : 'Xuất hiện',
advanced_tab : 'Nâng cao',
meta_props : 'Thông tin siêu dữ liệu',
langprops : 'Ngôn ngữ và bộ mã',
meta_title : 'Tiêu đề',
meta_keywords : 'Từ khóa',
meta_description : 'Mô tả',
meta_robots : 'Robots',
doctypes : 'Doctype',
langcode : 'Mã ngôn ngữ',
langdir : 'Hướng ngôn ngữ',
ltr : 'Trái sang phải',
rtl : 'Phải sang trái',
xml_pi : 'Khai báo XML',
encoding : 'Bộ mã ký tự',
appearance_bgprops : 'Thuộc tính nền',
appearance_marginprops : 'Lề',
appearance_linkprops : 'Màu liên kết',
appearance_textprops : 'Thuộc tính văn bản',
bgcolor : 'Màu nền',
bgimage : 'Ảnh nền',
left_margin : 'Lề trái',
right_margin : 'Lề phải',
top_margin : 'Lề trên',
bottom_margin : 'Lề dưới',
text_color : 'Màu văn bản',
font_size : 'Kích thước font chữ',
font_face : 'Tên font',
link_color : 'Màu liên kết',
hover_color : 'Màu khi di chuột lên',
visited_color : 'Màu khi đã ghé thăm',
active_color : 'Màu khi nhấn',
textcolor : 'Màu chữ',
fontsize : 'Kích thước font chữ',
fontface : 'Tên font',
meta_index_follow : 'Chỉ mục và theo các liên kết',
meta_index_nofollow : 'Chỉ mục và không theo các liên kết',
meta_noindex_follow : 'Không phải chỉ mục nhưng theo các liên kết',
meta_noindex_nofollow : 'Không phải chỉ mục và không theo các liên kết',
appearance_style : 'Đinh dạng phong cách và thuộc tính phong cách',
stylesheet : 'Định dạng phong cách',
style : 'Phong cách',
author : 'Tác giả',
copyright : 'Bản quyền',
add : 'Thêm một thành phần mới',
remove : 'Xóa thành phần đã chọn',
moveup : 'Di chuyển thành phần đã chọn lên trên',
movedown : 'Di chuyển thành phần đã chọn xuống dưới',
head_elements : 'Mục đầu',
info : 'Thông tin',
info_text : '',
add_title : 'Thành phần tiêu đề',
add_meta : 'Thành phần siêu dữ liệu',
add_script : 'Thành phần Script',
add_style : 'Thành phần phong cách',
add_link : 'Thành phần liên kết',
add_base : 'Thành phần cơ sở',
add_comment : 'Nút chú thích',
title_element : 'Thành phần tiêu đề',
script_element : 'Thành phần Script',
style_element : 'Thành phần phong cách',
base_element : 'Thành phần cơ sở',
link_element : 'Thành phần liên kết',
meta_element : 'Thành phần siêu dữ liệu',
comment_element : 'Chú thích',
src : 'Src',
language : 'Ngôn ngữ',
href : 'Href',
target : 'Target',
rel : 'Rel',
type : 'Type',
charset : 'Charset',
defer : 'Defer',
media : 'Media',
properties : 'Properties',
name : 'Name',
value : 'Value',
content : 'Content',
rel : 'Rel',
rev : 'Rev',
hreflang : 'Href lang',
general_props : 'General',
advanced_props : 'Advanced',
delta_width : 0,
delta_height : 0
}); | z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/plugins/fullpage/langs/vi.js | vi.js |
tinyMCE.addToLang('fullpage',{
title : 'Document properties',
desc : 'Document properties',
meta_tab : 'General',
appearance_tab : 'Appearance',
advanced_tab : 'Advanced',
meta_props : 'Meta information',
langprops : 'Language and encoding',
meta_title : 'Title',
meta_keywords : 'Keywords',
meta_description : 'Description',
meta_robots : 'Robots',
doctypes : 'Doctype',
langcode : 'Language code',
langdir : 'Language direction',
ltr : 'Left to right',
rtl : 'Right to left',
xml_pi : 'XML declaration',
encoding : 'Character encoding',
appearance_bgprops : 'Background properties',
appearance_marginprops : 'Body margins',
appearance_linkprops : 'Link colors',
appearance_textprops : 'Text properties',
bgcolor : 'Background color',
bgimage : 'Background image',
left_margin : 'Left margin',
right_margin : 'Right margin',
top_margin : 'Top margin',
bottom_margin : 'Bottom margin',
text_color : 'Text color',
font_size : 'Font size',
font_face : 'Font face',
link_color : 'Link color',
hover_color : 'Hover color',
visited_color : 'Visited color',
active_color : 'Active color',
textcolor : 'Color',
fontsize : 'Font size',
fontface : 'Font family',
meta_index_follow : 'Index and follow the links',
meta_index_nofollow : 'Index and don\'t follow the links',
meta_noindex_follow : 'Do not index but follow the links',
meta_noindex_nofollow : 'Do not index and don\'t follow the links',
appearance_style : 'Stylesheet and style properties',
stylesheet : 'Stylesheet',
style : 'Style',
author : 'Author',
copyright : 'Copyright',
add : 'Add new element',
remove : 'Remove selected element',
moveup : 'Move selected element up',
movedown : 'Move selected element down',
head_elements : 'Head elements',
info : 'Information',
info_text : '',
add_title : 'Title element',
add_meta : 'Meta element',
add_script : 'Script element',
add_style : 'Style element',
add_link : 'Link element',
add_base : 'Base element',
add_comment : 'Comment node',
title_element : 'Title element',
script_element : 'Script element',
style_element : 'Style element',
base_element : 'Base element',
link_element : 'Link element',
meta_element : 'Meta element',
comment_element : 'Comment',
src : 'Src',
language : 'Language',
href : 'Href',
target : 'Target',
rel : 'Rel',
type : 'Type',
charset : 'Charset',
defer : 'Defer',
media : 'Media',
properties : 'Properties',
name : 'Name',
value : 'Value',
content : 'Content',
rel : 'Rel',
rev : 'Rev',
hreflang : 'Href lang',
general_props : 'General',
advanced_props : 'Advanced',
delta_width : 0,
delta_height : 0
}); | z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/plugins/fullpage/langs/en.js | en.js |
var defaultDocTypes =
'XHTML 1.0 Transitional=<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">,' +
'XHTML 1.0 Frameset=<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">,' +
'XHTML 1.0 Strict=<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">,' +
'XHTML 1.1=<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">">,' +
'HTML 4.01 Transitional=<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">,' +
'HTML 4.01 Strict=<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">,' +
'HTML 4.01 Frameset=<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">';
var defaultEncodings =
'Western european (iso-8859-1)=iso-8859-1,' +
'Central European (iso-8859-2)=iso-8859-2,' +
'Unicode (UTF-8)=utf-8,' +
'Chinese traditional (Big5)=big5,' +
'Cyrillic (iso-8859-5)=iso-8859-5,' +
'Japanese (iso-2022-jp)=iso-2022-jp,' +
'Greek (iso-8859-7)=iso-8859-7,' +
'Korean (iso-2022-kr)=iso-2022-kr,' +
'ASCII (us-ascii)=us-ascii';
var defaultMediaTypes =
'all=all,' +
'screen=screen,' +
'print=print,' +
'tty=tty,' +
'tv=tv,' +
'projection=projection,' +
'handheld=handheld,' +
'braille=braille,' +
'aural=aural';
var defaultFontNames = 'Arial=arial,helvetica,sans-serif;Courier New=courier new,courier,monospace;Georgia=georgia,times new roman,times,serif;Tahoma=tahoma,arial,helvetica,sans-serif;Times New Roman=times new roman,times,serif;Verdana=verdana,arial,helvetica,sans-serif;Impact=impact;WingDings=wingdings';
var defaultFontSizes = '10px,11px,12px,13px,14px,15px,16px';
var addMenuLayer = new MCLayer("addmenu");
var lastElementType = null;
var topDoc;
function init() {
var f = document.forms['fullpage'];
var i, p, doctypes, encodings, mediaTypes, fonts;
var inst = tinyMCE.getInstanceById(tinyMCE.getWindowArg('editor_id'));
// Setup doctype select box
doctypes = tinyMCE.getParam("fullpage_doctypes", defaultDocTypes).split(',');
for (i=0; i<doctypes.length; i++) {
p = doctypes[i].split('=');
if (p.length > 1)
addSelectValue(f, 'doctypes', p[0], p[1]);
}
// Setup fonts select box
fonts = tinyMCE.getParam("fullpage_fonts", defaultFontNames).split(';');
for (i=0; i<fonts.length; i++) {
p = fonts[i].split('=');
if (p.length > 1)
addSelectValue(f, 'fontface', p[0], p[1]);
}
// Setup fontsize select box
fonts = tinyMCE.getParam("fullpage_fontsizes", defaultFontSizes).split(',');
for (i=0; i<fonts.length; i++)
addSelectValue(f, 'fontsize', fonts[i], fonts[i]);
// Setup mediatype select boxs
mediaTypes = tinyMCE.getParam("fullpage_media_types", defaultMediaTypes).split(',');
for (i=0; i<mediaTypes.length; i++) {
p = mediaTypes[i].split('=');
if (p.length > 1) {
addSelectValue(f, 'element_style_media', p[0], p[1]);
addSelectValue(f, 'element_link_media', p[0], p[1]);
}
}
// Setup encodings select box
encodings = tinyMCE.getParam("fullpage_encodings", defaultEncodings).split(',');
for (i=0; i<encodings.length; i++) {
p = encodings[i].split('=');
if (p.length > 1) {
addSelectValue(f, 'docencoding', p[0], p[1]);
addSelectValue(f, 'element_script_charset', p[0], p[1]);
addSelectValue(f, 'element_link_charset', p[0], p[1]);
}
}
document.getElementById('bgcolor_pickcontainer').innerHTML = getColorPickerHTML('bgcolor_pick','bgcolor');
document.getElementById('link_color_pickcontainer').innerHTML = getColorPickerHTML('link_color_pick','link_color');
//document.getElementById('hover_color_pickcontainer').innerHTML = getColorPickerHTML('hover_color_pick','hover_color');
document.getElementById('visited_color_pickcontainer').innerHTML = getColorPickerHTML('visited_color_pick','visited_color');
document.getElementById('active_color_pickcontainer').innerHTML = getColorPickerHTML('active_color_pick','active_color');
document.getElementById('textcolor_pickcontainer').innerHTML = getColorPickerHTML('textcolor_pick','textcolor');
document.getElementById('stylesheet_browsercontainer').innerHTML = getBrowserHTML('stylesheetbrowser','stylesheet','file','fullpage');
document.getElementById('link_href_pickcontainer').innerHTML = getBrowserHTML('link_href_browser','element_link_href','file','fullpage');
document.getElementById('script_src_pickcontainer').innerHTML = getBrowserHTML('script_src_browser','element_script_src','file','fullpage');
document.getElementById('bgimage_pickcontainer').innerHTML = getBrowserHTML('bgimage_browser','bgimage','image','fullpage');
// Resize some elements
if (isVisible('stylesheetbrowser'))
document.getElementById('stylesheet').style.width = '220px';
if (isVisible('link_href_browser'))
document.getElementById('element_link_href').style.width = '230px';
if (isVisible('bgimage_browser'))
document.getElementById('bgimage').style.width = '210px';
// Create iframe
var iframe = document.createElement('iframe');
iframe.id = 'tempFrame';
iframe.style.display = 'none';
iframe.src = tinyMCE.baseURL + "/plugins/fullpage/blank.htm";
document.body.appendChild(iframe);
tinyMCEPopup.resizeToInnerSize();
}
function setupIframe(doc) {
var inst = tinyMCE.getInstanceById(tinyMCE.getWindowArg('editor_id'));
var hc = inst.fullpageTopContent;
var f = document.forms[0];
var xmlVer, xmlEnc, docType;
var nodes, i, x, name, value, tmp, l;
// Keep it from not loading/executing stuff
hc = hc.replace(/<script>/gi, '<script type="text/javascript">');
hc = hc.replace(/\ssrc=/gi, " mce_src=");
hc = hc.replace(/\shref=/gi, " mce_href=");
hc = hc.replace(/\stype=/gi, " mce_type=");
hc = hc.replace(/<script/gi, '<script type="text/unknown" ');
// Add end to make it DOM parseable
hc += '</body></html>';
topDoc = doc;
doc.open();
doc.write(hc);
doc.close();
// ------- Setup options for genral tab
// Parse xml and doctype
xmlVer = getReItem(/<\?\s*?xml.*?version\s*?=\s*?"(.*?)".*?\?>/gi, hc, 1);
xmlEnc = getReItem(/<\?\s*?xml.*?encoding\s*?=\s*?"(.*?)".*?\?>/gi, hc, 1);
docType = getReItem(/<\!DOCTYPE.*?>/gi, hc, 0);
f.langcode.value = getReItem(/lang="(.*?)"/gi, hc, 1);
// Get title
f.metatitle.value = tinyMCE.entityDecode(getReItem(/<title>(.*?)<\/title>/gi, hc, 1));
// Check for meta encoding
nodes = doc.getElementsByTagName("meta");
for (i=0; i<nodes.length; i++) {
name = tinyMCE.getAttrib(nodes[i], 'name');
value = tinyMCE.getAttrib(nodes[i], 'content');
httpEquiv = tinyMCE.getAttrib(nodes[i], 'httpEquiv');
switch (name.toLowerCase()) {
case "keywords":
f.metakeywords.value = value;
break;
case "description":
f.metadescription.value = value;
break;
case "author":
f.metaauthor.value = value;
break;
case "copyright":
f.metacopyright.value = value;
break;
case "robots":
selectByValue(f, 'metarobots', value, true, true);
break;
}
switch (httpEquiv.toLowerCase()) {
case "content-type":
tmp = getReItem(/charset\s*=\s*(.*)\s*/gi, value, 1);
// Override XML encoding
if (tmp != "")
xmlEnc = tmp;
break;
}
}
selectByValue(f, 'doctypes', docType, true, true);
selectByValue(f, 'docencoding', xmlEnc, true, true);
selectByValue(f, 'langdir', tinyMCE.getAttrib(doc.body, 'dir'), true, true);
if (xmlVer != '')
f.xml_pi.checked = true;
// ------- Setup options for appearance tab
// Get primary stylesheet
nodes = doc.getElementsByTagName("link");
for (i=0; i<nodes.length; i++) {
l = nodes[i];
tmp = tinyMCE.getAttrib(l, 'media');
if (tinyMCE.getAttrib(l, 'mce_type') == "text/css" && (tmp == "" || tmp == "screen" || tmp == "all") && tinyMCE.getAttrib(l, 'rel') == "stylesheet") {
f.stylesheet.value = tinyMCE.getAttrib(l, 'mce_href');
break;
}
}
// Get from style elements
nodes = doc.getElementsByTagName("style");
for (i=0; i<nodes.length; i++) {
tmp = parseStyleElement(nodes[i]);
for (x=0; x<tmp.length; x++) {
// if (tmp[x].rule.indexOf('a:hover') != -1 && tmp[x].data['color'])
// f.hover_color.value = tmp[x].data['color'];
if (tmp[x].rule.indexOf('a:visited') != -1 && tmp[x].data['color'])
f.visited_color.value = tmp[x].data['color'];
if (tmp[x].rule.indexOf('a:link') != -1 && tmp[x].data['color'])
f.link_color.value = tmp[x].data['color'];
if (tmp[x].rule.indexOf('a:active') != -1 && tmp[x].data['color'])
f.active_color.value = tmp[x].data['color'];
}
}
// Get from body attribs
/* f.leftmargin.value = tinyMCE.getAttrib(doc.body, "leftmargin");
f.rightmargin.value = tinyMCE.getAttrib(doc.body, "rightmargin");
f.topmargin.value = tinyMCE.getAttrib(doc.body, "topmargin");
f.bottommargin.value = tinyMCE.getAttrib(doc.body, "bottommargin");*/
f.textcolor.value = convertRGBToHex(tinyMCE.getAttrib(doc.body, "text"));
f.active_color.value = convertRGBToHex(tinyMCE.getAttrib(doc.body, "alink"));
f.link_color.value = convertRGBToHex(tinyMCE.getAttrib(doc.body, "link"));
f.visited_color.value = convertRGBToHex(tinyMCE.getAttrib(doc.body, "vlink"));
f.bgcolor.value = convertRGBToHex(tinyMCE.getAttrib(doc.body, "bgcolor"));
f.bgimage.value = convertRGBToHex(tinyMCE.getAttrib(doc.body, "background"));
// Get from style info
var style = tinyMCE.parseStyle(tinyMCE.getAttrib(doc.body, 'style'));
if (style['font-family'])
selectByValue(f, 'fontface', style['font-family'], true, true);
else
selectByValue(f, 'fontface', tinyMCE.getParam("fullpage_default_fontface", ""), true, true);
if (style['font-size'])
selectByValue(f, 'fontsize', style['font-size'], true, true);
else
selectByValue(f, 'fontsize', tinyMCE.getParam("fullpage_default_fontsize", ""), true, true);
if (style['color'])
f.textcolor.value = convertRGBToHex(style['color']);
if (style['background-image'])
f.bgimage.value = style['background-image'].replace(new RegExp("url\\('?([^']*)'?\\)", 'gi'), "$1");
if (style['background-color'])
f.bgcolor.value = convertRGBToHex(style['background-color']);
if (style['margin']) {
tmp = style['margin'].replace(/[^0-9 ]/g, '');
tmp = tmp.split(/ +/);
f.topmargin.value = tmp.length > 0 ? tmp[0] : '';
f.rightmargin.value = tmp.length > 1 ? tmp[1] : tmp[0];
f.bottommargin.value = tmp.length > 2 ? tmp[2] : tmp[0];
f.leftmargin.value = tmp.length > 3 ? tmp[3] : tmp[0];
}
if (style['margin-left'])
f.leftmargin.value = style['margin-left'].replace(/[^0-9]/g, '');
if (style['margin-right'])
f.rightmargin.value = style['margin-right'].replace(/[^0-9]/g, '');
if (style['margin-top'])
f.topmargin.value = style['margin-top'].replace(/[^0-9]/g, '');
if (style['margin-bottom'])
f.bottommargin.value = style['margin-bottom'].replace(/[^0-9]/g, '');
f.style.value = tinyMCE.serializeStyle(style);
updateColor('textcolor_pick', 'textcolor');
updateColor('bgcolor_pick', 'bgcolor');
updateColor('visited_color_pick', 'visited_color');
updateColor('active_color_pick', 'active_color');
updateColor('link_color_pick', 'link_color');
//updateColor('hover_color_pick', 'hover_color');
}
function updateAction() {
var inst = tinyMCE.getInstanceById(tinyMCE.getWindowArg('editor_id'));
var f = document.forms[0];
var nl, i, h, v, s, head, html, l, tmp, addlink = true;
head = topDoc.getElementsByTagName('head')[0];
// Fix scripts without a type
nl = topDoc.getElementsByTagName('script');
for (i=0; i<nl.length; i++) {
if (tinyMCE.getAttrib(nl[i], 'mce_type') == '')
nl[i].setAttribute('mce_type', 'text/javascript');
}
// Get primary stylesheet
nl = topDoc.getElementsByTagName("link");
for (i=0; i<nl.length; i++) {
l = nl[i];
tmp = tinyMCE.getAttrib(l, 'media');
if (tinyMCE.getAttrib(l, 'mce_type') == "text/css" && (tmp == "" || tmp == "screen" || tmp == "all") && tinyMCE.getAttrib(l, 'rel') == "stylesheet") {
addlink = false;
if (f.stylesheet.value == '')
l.parentNode.removeChild(l);
else
l.setAttribute('mce_href', f.stylesheet.value);
break;
}
}
// Add new link
if (f.stylesheet.value != '') {
l = topDoc.createElement('link');
l.setAttribute('mce_type', 'text/css');
l.setAttribute('mce_href', f.stylesheet.value);
l.setAttribute('rel', 'stylesheet');
head.appendChild(l);
}
setMeta(head, 'keywords', f.metakeywords.value);
setMeta(head, 'description', f.metadescription.value);
setMeta(head, 'author', f.metaauthor.value);
setMeta(head, 'copyright', f.metacopyright.value);
setMeta(head, 'robots', getSelectValue(f, 'metarobots'));
setMeta(head, 'Content-Type', getSelectValue(f, 'docencoding'));
topDoc.body.dir = getSelectValue(f, 'langdir');
topDoc.body.style.cssText = f.style.value;
topDoc.body.setAttribute('vLink', f.visited_color.value);
topDoc.body.setAttribute('link', f.link_color.value);
topDoc.body.setAttribute('text', f.textcolor.value);
topDoc.body.setAttribute('aLink', f.active_color.value);
topDoc.body.style.fontFamily = getSelectValue(f, 'fontface');
topDoc.body.style.fontSize = getSelectValue(f, 'fontsize');
topDoc.body.style.backgroundColor = f.bgcolor.value;
if (f.leftmargin.value != '')
topDoc.body.style.marginLeft = f.leftmargin.value + 'px';
if (f.rightmargin.value != '')
topDoc.body.style.marginRight = f.rightmargin.value + 'px';
if (f.bottommargin.value != '')
topDoc.body.style.marginBottom = f.bottommargin.value + 'px';
if (f.topmargin.value != '')
topDoc.body.style.marginTop = f.topmargin.value + 'px';
html = topDoc.getElementsByTagName('html')[0];
html.setAttribute('lang', f.langcode.value);
html.setAttribute('xml:lang', f.langcode.value);
if (f.bgimage.value != '')
topDoc.body.style.backgroundImage = "url('" + f.bgimage.value + "')";
else
topDoc.body.style.backgroundImage = '';
inst.cleanup.addRuleStr('-title,meta[http-equiv|name|content],base[href|target],link[href|rel|type|title|media],style[type],script[type|language|src],html[lang|xml:lang|xmlns],body[style|dir|vlink|link|text|alink],head');
h = inst.cleanup.serializeNodeAsHTML(topDoc.documentElement);
h = h.substring(0, h.lastIndexOf('</body>'));
if (h.indexOf('<title>') == -1)
h = h.replace(/<head.*?>/, '$&\n' + '<title>' + inst.cleanup.xmlEncode(f.metatitle.value) + '</title>');
else
h = h.replace(/<title>(.*?)<\/title>/, '<title>' + inst.cleanup.xmlEncode(f.metatitle.value) + '</title>');
if ((v = getSelectValue(f, 'doctypes')) != '')
h = v + '\n' + h;
if (f.xml_pi.checked) {
s = '<?xml version="1.0"';
if ((v = getSelectValue(f, 'docencoding')) != '')
s += ' encoding="' + v + '"';
s += '?>\n';
h = s + h;
}
inst.fullpageTopContent = h;
tinyMCEPopup.execCommand('mceFullPageUpdate', false, '');
tinyMCEPopup.close();
}
function setMeta(he, k, v) {
var nl, i, m;
nl = he.getElementsByTagName('meta');
for (i=0; i<nl.length; i++) {
if (k == 'Content-Type' && tinyMCE.getAttrib(nl[i], 'http-equiv') == k) {
if (v == '')
nl[i].parentNode.removeChild(nl[i]);
else
nl[i].setAttribute('content', "text/html; charset=" + v);
return;
}
if (tinyMCE.getAttrib(nl[i], 'name') == k) {
if (v == '')
nl[i].parentNode.removeChild(nl[i]);
else
nl[i].setAttribute('content', v);
return;
}
}
if (v == '')
return;
m = topDoc.createElement('meta');
if (k == 'Content-Type')
m.httpEquiv = k;
else
m.setAttribute('name', k);
m.setAttribute('content', v);
he.appendChild(m);
}
function parseStyleElement(e) {
var v = e.innerHTML;
var p, i, r;
v = v.replace(/<!--/gi, '');
v = v.replace(/-->/gi, '');
v = v.replace(/[\n\r]/gi, '');
v = v.replace(/\s+/gi, ' ');
r = new Array();
p = v.split(/{|}/);
for (i=0; i<p.length; i+=2) {
if (p[i] != "")
r[r.length] = {rule : tinyMCE.trim(p[i]), data : tinyMCE.parseStyle(p[i+1])};
}
return r;
}
function serializeStyleElement(d) {
var i, s, st;
s = '<!--\n';
for (i=0; i<d.length; i++) {
s += d[i].rule + ' {\n';
st = tinyMCE.serializeStyle(d[i].data);
if (st != '')
st += ';';
s += st.replace(/;/g, ';\n');
s += '}\n';
if (i != d.length - 1)
s += '\n';
}
s += '\n-->';
return s;
}
function getReItem(r, s, i) {
var c = r.exec(s);
if (c && c.length > i)
return c[i];
return '';
}
function changedStyleField(field) {
//alert(field.id);
}
function showAddMenu() {
var re = document.getElementById('addbutton');
addMenuLayer.moveRelativeTo(re, 'tr');
if (addMenuLayer.isMSIE)
addMenuLayer.moveBy(2, 0);
addMenuLayer.show();
addMenuLayer.setAutoHide(true, hideAddMenu);
addMenuLayer.addCSSClass(re, 'selected');
}
function hideAddMenu(l, e, mx, my) {
var re = document.getElementById('addbutton');
addMenuLayer.removeCSSClass(re, 'selected');
}
function addHeadElm(type) {
var le = document.getElementById('headlist');
var re = document.getElementById('addbutton');
var te = document.getElementById(type + '_element');
if (lastElementType)
lastElementType.style.display = 'none';
te.style.display = 'block';
lastElementType = te;
addMenuLayer.hide();
addMenuLayer.removeCSSClass(re, 'selected');
document.getElementById(type + '_updateelement').value = tinyMCE.getLang('lang_insert', 'Insert', true);
le.size = 10;
}
function updateHeadElm(item) {
var type = item.substring(0, item.indexOf('_'));
var le = document.getElementById('headlist');
var re = document.getElementById('addbutton');
var te = document.getElementById(type + '_element');
if (lastElementType)
lastElementType.style.display = 'none';
te.style.display = 'block';
lastElementType = te;
addMenuLayer.hide();
addMenuLayer.removeCSSClass(re, 'selected');
document.getElementById(type + '_updateelement').value = tinyMCE.getLang('lang_update', 'Update', true);
le.size = 10;
}
function cancelElementUpdate() {
var le = document.getElementById('headlist');
if (lastElementType)
lastElementType.style.display = 'none';
le.size = 26;
} | z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/plugins/fullpage/jscripts/fullpage.js | fullpage.js |
tinyMCE.importPluginLanguagePack('save','en,tr,sv,zh_cn,cs,fa,fr_ca,fr,de,pl,pt_br,nl,he,nb,hu,ru,ru_KOI8-R,ru_UTF-8,nn,fi,da,es,cy,is,zh_tw,zh_tw_utf8,sk');var TinyMCE_SavePlugin={getInfo:function(){return{longname:'Save',author:'Moxiecode Systems',authorurl:'http://tinymce.moxiecode.com',infourl:'http://tinymce.moxiecode.com/tinymce/docs/plugin_save.html',version:tinyMCE.majorVersion+"."+tinyMCE.minorVersion};},initInstance:function(inst){inst.addShortcut('ctrl','s','lang_save_desc','mceSave');},getControlHTML:function(cn){switch(cn){case"save":return tinyMCE.getButtonHTML(cn,'lang_save_desc','{$pluginurl}/images/save.gif','mceSave');}return"";},execCommand:function(editor_id,element,command,user_interface,value){switch(command){case"mceSave":if(tinyMCE.getParam("fullscreen_is_enabled"))return true;var inst=tinyMCE.selectedInstance;var formObj=inst.formElement.form;if(tinyMCE.getParam("save_enablewhendirty")&&!inst.isDirty())return true;if(formObj){tinyMCE.triggerSave();var os;if((os=tinyMCE.getParam("save_onsavecallback"))){if(eval(os+'(inst);')){inst.startContent=tinyMCE.trim(inst.getBody().innerHTML);tinyMCE.triggerNodeChange(false,true);}return true;}for(var i=0;i<formObj.elements.length;i++){var elementId=formObj.elements[i].name?formObj.elements[i].name:formObj.elements[i].id;if(elementId.indexOf('mce_editor_')==0)formObj.elements[i].disabled=true;}tinyMCE.isNotDirty=true;if(formObj.onsubmit==null||formObj.onsubmit()!=false)inst.formElement.form.submit();}else alert("Error: No form element found.");return true;}return false;},handleNodeChange:function(editor_id,node,undo_index,undo_levels,visual_aid,any_selection){if(tinyMCE.getParam("fullscreen_is_enabled")){tinyMCE.switchClass(editor_id+'_save','mceButtonDisabled');return true;}if(tinyMCE.getParam("save_enablewhendirty")){var inst=tinyMCE.getInstanceById(editor_id);if(inst.isDirty()){tinyMCE.switchClass(editor_id+'_save','mceButtonNormal');return true;}tinyMCE.switchClass(editor_id+'_save','mceButtonDisabled');}return true;}};tinyMCE.addPlugin("save",TinyMCE_SavePlugin); | z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/plugins/save/editor_plugin.js | editor_plugin.js |
var templates = {
"window.open" : "window.open('${url}','${target}','${options}')"
};
function preinit() {
// Initialize
tinyMCE.setWindowArg('mce_windowresize', false);
// Import external list url javascript
var url = tinyMCE.getParam("external_link_list_url");
if (url != null) {
// Fix relative
if (url.charAt(0) != '/' && url.indexOf('://') == -1)
url = tinyMCE.documentBasePath + "/" + url;
document.write('<sc'+'ript language="javascript" type="text/javascript" src="' + url + '"></sc'+'ript>');
}
}
function changeClass() {
var formObj = document.forms[0];
formObj.classes.value = getSelectValue(formObj, 'classlist');
}
function init() {
tinyMCEPopup.resizeToInnerSize();
var formObj = document.forms[0];
var inst = tinyMCE.getInstanceById(tinyMCE.getWindowArg('editor_id'));
var elm = inst.getFocusElement();
var action = "insert";
var html;
document.getElementById('hrefbrowsercontainer').innerHTML = getBrowserHTML('hrefbrowser','href','file','advlink');
document.getElementById('popupurlbrowsercontainer').innerHTML = getBrowserHTML('popupurlbrowser','popupurl','file','advlink');
document.getElementById('linklisthrefcontainer').innerHTML = getLinkListHTML('linklisthref','href');
document.getElementById('anchorlistcontainer').innerHTML = getAnchorListHTML('anchorlist','href');
document.getElementById('targetlistcontainer').innerHTML = getTargetListHTML('targetlist','target');
// Link list
html = getLinkListHTML('linklisthref','href');
if (html == "")
document.getElementById("linklisthrefrow").style.display = 'none';
else
document.getElementById("linklisthrefcontainer").innerHTML = html;
// Resize some elements
if (isVisible('hrefbrowser'))
document.getElementById('href').style.width = '260px';
if (isVisible('popupurlbrowser'))
document.getElementById('popupurl').style.width = '180px';
elm = tinyMCE.getParentElement(elm, "a");
if (elm != null && elm.nodeName == "A")
action = "update";
formObj.insert.value = tinyMCE.getLang('lang_' + action, 'Insert', true);
setPopupControlsDisabled(true);
if (action == "update") {
var href = tinyMCE.getAttrib(elm, 'href');
href = convertURL(href, elm, true);
// Use mce_href if found
var mceRealHref = tinyMCE.getAttrib(elm, 'mce_href');
if (mceRealHref != "") {
href = mceRealHref;
if (tinyMCE.getParam('convert_urls'))
href = convertURL(href, elm, true);
}
var onclick = tinyMCE.cleanupEventStr(tinyMCE.getAttrib(elm, 'onclick'));
// Setup form data
setFormValue('href', href);
setFormValue('title', tinyMCE.getAttrib(elm, 'title'));
setFormValue('id', tinyMCE.getAttrib(elm, 'id'));
setFormValue('style', tinyMCE.serializeStyle(tinyMCE.parseStyle(tinyMCE.getAttrib(elm, "style"))));
setFormValue('rel', tinyMCE.getAttrib(elm, 'rel'));
setFormValue('rev', tinyMCE.getAttrib(elm, 'rev'));
setFormValue('charset', tinyMCE.getAttrib(elm, 'charset'));
setFormValue('hreflang', tinyMCE.getAttrib(elm, 'hreflang'));
setFormValue('dir', tinyMCE.getAttrib(elm, 'dir'));
setFormValue('lang', tinyMCE.getAttrib(elm, 'lang'));
setFormValue('tabindex', tinyMCE.getAttrib(elm, 'tabindex', typeof(elm.tabindex) != "undefined" ? elm.tabindex : ""));
setFormValue('accesskey', tinyMCE.getAttrib(elm, 'accesskey', typeof(elm.accesskey) != "undefined" ? elm.accesskey : ""));
setFormValue('type', tinyMCE.getAttrib(elm, 'type'));
setFormValue('onfocus', tinyMCE.cleanupEventStr(tinyMCE.getAttrib(elm, 'onfocus')));
setFormValue('onblur', tinyMCE.cleanupEventStr(tinyMCE.getAttrib(elm, 'onblur')));
setFormValue('onclick', onclick);
setFormValue('ondblclick', tinyMCE.cleanupEventStr(tinyMCE.getAttrib(elm, 'ondblclick')));
setFormValue('onmousedown', tinyMCE.cleanupEventStr(tinyMCE.getAttrib(elm, 'onmousedown')));
setFormValue('onmouseup', tinyMCE.cleanupEventStr(tinyMCE.getAttrib(elm, 'onmouseup')));
setFormValue('onmouseover', tinyMCE.cleanupEventStr(tinyMCE.getAttrib(elm, 'onmouseover')));
setFormValue('onmousemove', tinyMCE.cleanupEventStr(tinyMCE.getAttrib(elm, 'onmousemove')));
setFormValue('onmouseout', tinyMCE.cleanupEventStr(tinyMCE.getAttrib(elm, 'onmouseout')));
setFormValue('onkeypress', tinyMCE.cleanupEventStr(tinyMCE.getAttrib(elm, 'onkeypress')));
setFormValue('onkeydown', tinyMCE.cleanupEventStr(tinyMCE.getAttrib(elm, 'onkeydown')));
setFormValue('onkeyup', tinyMCE.cleanupEventStr(tinyMCE.getAttrib(elm, 'onkeyup')));
setFormValue('target', tinyMCE.getAttrib(elm, 'target'));
setFormValue('classes', tinyMCE.getAttrib(elm, 'class'));
// Parse onclick data
if (onclick != null && onclick.indexOf('window.open') != -1)
parseWindowOpen(onclick);
else
parseFunction(onclick);
// Select by the values
selectByValue(formObj, 'dir', tinyMCE.getAttrib(elm, 'dir'));
selectByValue(formObj, 'rel', tinyMCE.getAttrib(elm, 'rel'));
selectByValue(formObj, 'rev', tinyMCE.getAttrib(elm, 'rev'));
selectByValue(formObj, 'linklisthref', href);
if (href.charAt(0) == '#')
selectByValue(formObj, 'anchorlist', href);
addClassesToList('classlist', 'advlink_styles');
selectByValue(formObj, 'classlist', tinyMCE.getAttrib(elm, 'class'), true);
selectByValue(formObj, 'targetlist', tinyMCE.getAttrib(elm, 'target'), true);
} else
addClassesToList('classlist', 'advlink_styles');
window.focus();
}
function setFormValue(name, value) {
document.forms[0].elements[name].value = value;
}
function convertURL(url, node, on_save) {
return eval("tinyMCEPopup.windowOpener." + tinyMCE.settings['urlconverter_callback'] + "(url, node, on_save);");
}
function parseWindowOpen(onclick) {
var formObj = document.forms[0];
// Preprocess center code
if (onclick.indexOf('return false;') != -1) {
formObj.popupreturn.checked = true;
onclick = onclick.replace('return false;', '');
} else
formObj.popupreturn.checked = false;
var onClickData = parseLink(onclick);
if (onClickData != null) {
formObj.ispopup.checked = true;
setPopupControlsDisabled(false);
var onClickWindowOptions = parseOptions(onClickData['options']);
var url = onClickData['url'];
if (tinyMCE.getParam('convert_urls'))
url = convertURL(url, null, true);
formObj.popupname.value = onClickData['target'];
formObj.popupurl.value = url;
formObj.popupwidth.value = getOption(onClickWindowOptions, 'width');
formObj.popupheight.value = getOption(onClickWindowOptions, 'height');
formObj.popupleft.value = getOption(onClickWindowOptions, 'left');
formObj.popuptop.value = getOption(onClickWindowOptions, 'top');
if (formObj.popupleft.value.indexOf('screen') != -1)
formObj.popupleft.value = "c";
if (formObj.popuptop.value.indexOf('screen') != -1)
formObj.popuptop.value = "c";
formObj.popuplocation.checked = getOption(onClickWindowOptions, 'location') == "yes";
formObj.popupscrollbars.checked = getOption(onClickWindowOptions, 'scrollbars') == "yes";
formObj.popupmenubar.checked = getOption(onClickWindowOptions, 'menubar') == "yes";
formObj.popupresizable.checked = getOption(onClickWindowOptions, 'resizable') == "yes";
formObj.popuptoolbar.checked = getOption(onClickWindowOptions, 'toolbar') == "yes";
formObj.popupstatus.checked = getOption(onClickWindowOptions, 'status') == "yes";
formObj.popupdependent.checked = getOption(onClickWindowOptions, 'dependent') == "yes";
buildOnClick();
}
}
function parseFunction(onclick) {
var formObj = document.forms[0];
var onClickData = parseLink(onclick);
// TODO: Add stuff here
}
function getOption(opts, name) {
return typeof(opts[name]) == "undefined" ? "" : opts[name];
}
function setPopupControlsDisabled(state) {
var formObj = document.forms[0];
formObj.popupname.disabled = state;
formObj.popupurl.disabled = state;
formObj.popupwidth.disabled = state;
formObj.popupheight.disabled = state;
formObj.popupleft.disabled = state;
formObj.popuptop.disabled = state;
formObj.popuplocation.disabled = state;
formObj.popupscrollbars.disabled = state;
formObj.popupmenubar.disabled = state;
formObj.popupresizable.disabled = state;
formObj.popuptoolbar.disabled = state;
formObj.popupstatus.disabled = state;
formObj.popupreturn.disabled = state;
formObj.popupdependent.disabled = state;
setBrowserDisabled('popupurlbrowser', state);
}
function parseLink(link) {
link = link.replace(new RegExp(''', 'g'), "'");
var fnName = link.replace(new RegExp("\\s*([A-Za-z0-9\.]*)\\s*\\(.*", "gi"), "$1");
// Is function name a template function
var template = templates[fnName];
if (template) {
// Build regexp
var variableNames = template.match(new RegExp("'?\\$\\{[A-Za-z0-9\.]*\\}'?", "gi"));
var regExp = "\\s*[A-Za-z0-9\.]*\\s*\\(";
var replaceStr = "";
for (var i=0; i<variableNames.length; i++) {
// Is string value
if (variableNames[i].indexOf("'${") != -1)
regExp += "'(.*)'";
else // Number value
regExp += "([0-9]*)";
replaceStr += "$" + (i+1);
// Cleanup variable name
variableNames[i] = variableNames[i].replace(new RegExp("[^A-Za-z0-9]", "gi"), "");
if (i != variableNames.length-1) {
regExp += "\\s*,\\s*";
replaceStr += "<delim>";
} else
regExp += ".*";
}
regExp += "\\);?";
// Build variable array
var variables = new Array();
variables["_function"] = fnName;
var variableValues = link.replace(new RegExp(regExp, "gi"), replaceStr).split('<delim>');
for (var i=0; i<variableNames.length; i++)
variables[variableNames[i]] = variableValues[i];
return variables;
}
return null;
}
function parseOptions(opts) {
if (opts == null || opts == "")
return new Array();
// Cleanup the options
opts = opts.toLowerCase();
opts = opts.replace(/;/g, ",");
opts = opts.replace(/[^0-9a-z=,]/g, "");
var optionChunks = opts.split(',');
var options = new Array();
for (var i=0; i<optionChunks.length; i++) {
var parts = optionChunks[i].split('=');
if (parts.length == 2)
options[parts[0]] = parts[1];
}
return options;
}
function buildOnClick() {
var formObj = document.forms[0];
if (!formObj.ispopup.checked) {
formObj.onclick.value = "";
return;
}
var onclick = "window.open('";
var url = formObj.popupurl.value;
if (tinyMCE.getParam('convert_urls'))
url = convertURL(url, null, true);
onclick += url + "','";
onclick += formObj.popupname.value + "','";
if (formObj.popuplocation.checked)
onclick += "location=yes,";
if (formObj.popupscrollbars.checked)
onclick += "scrollbars=yes,";
if (formObj.popupmenubar.checked)
onclick += "menubar=yes,";
if (formObj.popupresizable.checked)
onclick += "resizable=yes,";
if (formObj.popuptoolbar.checked)
onclick += "toolbar=yes,";
if (formObj.popupstatus.checked)
onclick += "status=yes,";
if (formObj.popupdependent.checked)
onclick += "dependent=yes,";
if (formObj.popupwidth.value != "")
onclick += "width=" + formObj.popupwidth.value + ",";
if (formObj.popupheight.value != "")
onclick += "height=" + formObj.popupheight.value + ",";
if (formObj.popupleft.value != "") {
if (formObj.popupleft.value != "c")
onclick += "left=" + formObj.popupleft.value + ",";
else
onclick += "left='+(screen.availWidth/2-" + (formObj.popupwidth.value/2) + ")+',";
}
if (formObj.popuptop.value != "") {
if (formObj.popuptop.value != "c")
onclick += "top=" + formObj.popuptop.value + ",";
else
onclick += "top='+(screen.availHeight/2-" + (formObj.popupheight.value/2) + ")+',";
}
if (onclick.charAt(onclick.length-1) == ',')
onclick = onclick.substring(0, onclick.length-1);
onclick += "');";
if (formObj.popupreturn.checked)
onclick += "return false;";
// tinyMCE.debug(onclick);
formObj.onclick.value = onclick;
if (formObj.href.value == "")
formObj.href.value = url;
}
function setAttrib(elm, attrib, value) {
var formObj = document.forms[0];
var valueElm = formObj.elements[attrib.toLowerCase()];
if (typeof(value) == "undefined" || value == null) {
value = "";
if (valueElm)
value = valueElm.value;
}
if (value != "") {
elm.setAttribute(attrib.toLowerCase(), value);
if (attrib == "style")
attrib = "style.cssText";
if (attrib.substring(0, 2) == 'on')
value = 'return true;' + value;
if (attrib == "class")
attrib = "className";
eval('elm.' + attrib + "=value;");
} else
elm.removeAttribute(attrib);
}
function getAnchorListHTML(id, target) {
var inst = tinyMCE.getInstanceById(tinyMCE.getWindowArg('editor_id'));
var nodes = inst.getBody().getElementsByTagName("a");
var html = "";
html += '<select id="' + id + '" name="' + id + '" class="mceAnchorList" onfocus="tinyMCE.addSelectAccessibility(event, this, window);" onchange="this.form.' + target + '.value=';
html += 'this.options[this.selectedIndex].value;">';
html += '<option value="">---</option>';
for (var i=0; i<nodes.length; i++) {
if ((name = tinyMCE.getAttrib(nodes[i], "name")) != "")
html += '<option value="#' + name + '">' + name + '</option>';
}
html += '</select>';
return html;
}
function insertAction() {
var inst = tinyMCE.getInstanceById(tinyMCE.getWindowArg('editor_id'));
var elm = inst.getFocusElement();
elm = tinyMCE.getParentElement(elm, "a");
tinyMCEPopup.execCommand("mceBeginUndoLevel");
// Create new anchor elements
if (elm == null) {
if (tinyMCE.isSafari)
tinyMCEPopup.execCommand("mceInsertContent", false, '<a href="#mce_temp_url#">' + inst.selection.getSelectedHTML() + '</a>');
else
tinyMCEPopup.execCommand("createlink", false, "#mce_temp_url#");
var elementArray = tinyMCE.getElementsByAttributeValue(inst.getBody(), "a", "href", "#mce_temp_url#");
for (var i=0; i<elementArray.length; i++) {
var elm = elementArray[i];
// Move cursor behind the new anchor
if (tinyMCE.isGecko) {
var sp = inst.getDoc().createTextNode(" ");
if (elm.nextSibling)
elm.parentNode.insertBefore(sp, elm.nextSibling);
else
elm.parentNode.appendChild(sp);
// Set range after link
var rng = inst.getDoc().createRange();
rng.setStartAfter(elm);
rng.setEndAfter(elm);
// Update selection
var sel = inst.getSel();
sel.removeAllRanges();
sel.addRange(rng);
}
setAllAttribs(elm);
}
} else
setAllAttribs(elm);
tinyMCE._setEventsEnabled(inst.getBody(), false);
tinyMCEPopup.execCommand("mceEndUndoLevel");
tinyMCEPopup.close();
}
function setAllAttribs(elm) {
var formObj = document.forms[0];
var href = formObj.href.value;
var target = getSelectValue(formObj, 'targetlist');
// Make anchors absolute
if (href.charAt(0) == '#' && tinyMCE.getParam('convert_urls'))
href = tinyMCE.settings['document_base_url'] + href;
setAttrib(elm, 'href', convertURL(href, elm));
setAttrib(elm, 'mce_href', href);
setAttrib(elm, 'title');
setAttrib(elm, 'target', target == '_self' ? '' : target);
setAttrib(elm, 'id');
setAttrib(elm, 'style');
setAttrib(elm, 'class', getSelectValue(formObj, 'classlist'));
setAttrib(elm, 'rel');
setAttrib(elm, 'rev');
setAttrib(elm, 'charset');
setAttrib(elm, 'hreflang');
setAttrib(elm, 'dir');
setAttrib(elm, 'lang');
setAttrib(elm, 'tabindex');
setAttrib(elm, 'accesskey');
setAttrib(elm, 'type');
setAttrib(elm, 'onfocus');
setAttrib(elm, 'onblur');
setAttrib(elm, 'onclick');
setAttrib(elm, 'ondblclick');
setAttrib(elm, 'onmousedown');
setAttrib(elm, 'onmouseup');
setAttrib(elm, 'onmouseover');
setAttrib(elm, 'onmousemove');
setAttrib(elm, 'onmouseout');
setAttrib(elm, 'onkeypress');
setAttrib(elm, 'onkeydown');
setAttrib(elm, 'onkeyup');
// Refresh in old MSIE
if (tinyMCE.isMSIE5)
elm.outerHTML = elm.outerHTML;
}
function getSelectValue(form_obj, field_name) {
var elm = form_obj.elements[field_name];
if (elm == null || elm.options == null)
return "";
return elm.options[elm.selectedIndex].value;
}
function getLinkListHTML(elm_id, target_form_element, onchange_func) {
if (typeof(tinyMCELinkList) == "undefined" || tinyMCELinkList.length == 0)
return "";
var html = "";
html += '<select id="' + elm_id + '" name="' + elm_id + '"';
html += ' class="mceLinkList" onfocus="tinyMCE.addSelectAccessibility(event, this, window);" onchange="this.form.' + target_form_element + '.value=';
html += 'this.options[this.selectedIndex].value;';
if (typeof(onchange_func) != "undefined")
html += onchange_func + '(\'' + target_form_element + '\',this.options[this.selectedIndex].text,this.options[this.selectedIndex].value);';
html += '"><option value="">---</option>';
for (var i=0; i<tinyMCELinkList.length; i++)
html += '<option value="' + tinyMCELinkList[i][1] + '">' + tinyMCELinkList[i][0] + '</option>';
html += '</select>';
return html;
// tinyMCE.debug('-- image list start --', html, '-- image list end --');
}
function getTargetListHTML(elm_id, target_form_element) {
var targets = tinyMCE.getParam('theme_advanced_link_targets', '').split(';');
var html = '';
html += '<select id="' + elm_id + '" name="' + elm_id + '" onfocus="tinyMCE.addSelectAccessibility(event, this, window);" onchange="this.form.' + target_form_element + '.value=';
html += 'this.options[this.selectedIndex].value;">';
html += '<option value="_self">' + tinyMCE.getLang('lang_advlink_target_same') + '</option>';
html += '<option value="_blank">' + tinyMCE.getLang('lang_advlink_target_blank') + ' (_blank)</option>';
html += '<option value="_parent">' + tinyMCE.getLang('lang_advlink_target_parent') + ' (_parent)</option>';
html += '<option value="_top">' + tinyMCE.getLang('lang_advlink_target_top') + ' (_top)</option>';
for (var i=0; i<targets.length; i++) {
var key, value;
if (targets[i] == "")
continue;
key = targets[i].split('=')[0];
value = targets[i].split('=')[1];
html += '<option value="' + key + '">' + value + ' (' + key + ')</option>';
}
html += '</select>';
return html;
}
// While loading
preinit(); | z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/plugins/advlink/jscripts/functions.js | functions.js |
tinyMCE.importPluginLanguagePack('advhr','en,tr,de,sv,zh_cn,cs,fa,fr_ca,fr,pl,pt_br,nl,da,he,nb,hu,ru,ru_KOI8-R,ru_UTF-8,nn,fi,es,cy,is,zh_tw,zh_tw_utf8,sk');var TinyMCE_AdvancedHRPlugin={getInfo:function(){return{longname:'Advanced HR',author:'Moxiecode Systems',authorurl:'http://tinymce.moxiecode.com',infourl:'http://tinymce.moxiecode.com/tinymce/docs/plugin_advhr.html',version:tinyMCE.majorVersion+"."+tinyMCE.minorVersion}},getControlHTML:function(cn){switch(cn){case"advhr":return tinyMCE.getButtonHTML(cn,'lang_insert_advhr_desc','{$pluginurl}/images/advhr.gif','mceAdvancedHr');}return"";},execCommand:function(editor_id,element,command,user_interface,value){switch(command){case"mceAdvancedHr":var template=new Array();template['file']='../../plugins/advhr/rule.htm';template['width']=250;template['height']=160;template['width']+=tinyMCE.getLang('lang_advhr_delta_width',0);template['height']+=tinyMCE.getLang('lang_advhr_delta_height',0);var size="",width="",noshade="";if(tinyMCE.selectedElement!=null&&tinyMCE.selectedElement.nodeName.toLowerCase()=="hr"){tinyMCE.hrElement=tinyMCE.selectedElement;if(tinyMCE.hrElement){size=tinyMCE.hrElement.getAttribute('size')?tinyMCE.hrElement.getAttribute('size'):"";width=tinyMCE.hrElement.getAttribute('width')?tinyMCE.hrElement.getAttribute('width'):"";noshade=tinyMCE.hrElement.getAttribute('noshade')?tinyMCE.hrElement.getAttribute('noshade'):"";}tinyMCE.openWindow(template,{editor_id:editor_id,size:size,width:width,noshade:noshade,mceDo:'update'});}else{if(tinyMCE.isMSIE){tinyMCE.execInstanceCommand(editor_id,'mceInsertContent',false,'<hr />');}else{tinyMCE.openWindow(template,{editor_id:editor_id,inline:"yes",size:size,width:width,noshade:noshade,mceDo:'insert'});}}return true;}return false;},handleNodeChange:function(editor_id,node,undo_index,undo_levels,visual_aid,any_selection){if(node==null)return;do{if(node.nodeName=="HR"){tinyMCE.switchClass(editor_id+'_advhr','mceButtonSelected');return true;}}while((node=node.parentNode));tinyMCE.switchClass(editor_id+'_advhr','mceButtonNormal');return true;}};tinyMCE.addPlugin("advhr",TinyMCE_AdvancedHRPlugin); | z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/plugins/advhr/editor_plugin.js | editor_plugin.js |
tinyMCE.importPluginLanguagePack('flash','en,tr,de,sv,zh_cn,cs,fa,fr_ca,fr,pl,pt_br,nl,da,he,nb,hu,ru,ru_KOI8-R,ru_UTF-8,nn,es,cy,is,zh_tw,zh_tw_utf8,sk,pt_br');var TinyMCE_FlashPlugin={getInfo:function(){return{longname:'Flash',author:'Moxiecode Systems',authorurl:'http://tinymce.moxiecode.com',infourl:'http://tinymce.moxiecode.com/tinymce/docs/plugin_flash.html',version:tinyMCE.majorVersion+"."+tinyMCE.minorVersion};},initInstance:function(inst){if(!tinyMCE.settings['flash_skip_plugin_css'])tinyMCE.importCSS(inst.getDoc(),tinyMCE.baseURL+"/plugins/flash/css/content.css");},getControlHTML:function(cn){switch(cn){case"flash":return tinyMCE.getButtonHTML(cn,'lang_flash_desc','{$pluginurl}/images/flash.gif','mceFlash');}return"";},execCommand:function(editor_id,element,command,user_interface,value){switch(command){case"mceFlash":var name="",swffile="",swfwidth="",swfheight="",action="insert";var template=new Array();var inst=tinyMCE.getInstanceById(editor_id);var focusElm=inst.getFocusElement();template['file']='../../plugins/flash/flash.htm';template['width']=430;template['height']=175;template['width']+=tinyMCE.getLang('lang_flash_delta_width',0);template['height']+=tinyMCE.getLang('lang_flash_delta_height',0);if(focusElm!=null&&focusElm.nodeName.toLowerCase()=="img"){name=tinyMCE.getAttrib(focusElm,'class');if(name.indexOf('mceItemFlash')==-1)return true;swffile=tinyMCE.getAttrib(focusElm,'alt');if(tinyMCE.getParam('convert_urls'))swffile=eval(tinyMCE.settings['urlconverter_callback']+"(swffile, null, true);");swfwidth=tinyMCE.getAttrib(focusElm,'width');swfheight=tinyMCE.getAttrib(focusElm,'height');action="update";}tinyMCE.openWindow(template,{editor_id:editor_id,inline:"yes",swffile:swffile,swfwidth:swfwidth,swfheight:swfheight,action:action});return true;}return false;},cleanup:function(type,content){switch(type){case"insert_to_editor_dom":if(tinyMCE.getParam('convert_urls')){var imgs=content.getElementsByTagName("img");for(var i=0;i<imgs.length;i++){if(tinyMCE.getAttrib(imgs[i],"class")=="mceItemFlash"){var src=tinyMCE.getAttrib(imgs[i],"alt");if(tinyMCE.getParam('convert_urls'))src=eval(tinyMCE.settings['urlconverter_callback']+"(src, null, true);");imgs[i].setAttribute('alt',src);imgs[i].setAttribute('title',src);}}}break;case"get_from_editor_dom":var imgs=content.getElementsByTagName("img");for(var i=0;i<imgs.length;i++){if(tinyMCE.getAttrib(imgs[i],"class")=="mceItemFlash"){var src=tinyMCE.getAttrib(imgs[i],"alt");if(tinyMCE.getParam('convert_urls'))src=eval(tinyMCE.settings['urlconverter_callback']+"(src, null, true);");imgs[i].setAttribute('alt',src);imgs[i].setAttribute('title',src);}}break;case"insert_to_editor":var startPos=0;var embedList=new Array();content=content.replace(new RegExp('<[ ]*embed','gi'),'<embed');content=content.replace(new RegExp('<[ ]*/embed[ ]*>','gi'),'</embed>');content=content.replace(new RegExp('<[ ]*object','gi'),'<object');content=content.replace(new RegExp('<[ ]*/object[ ]*>','gi'),'</object>');while((startPos=content.indexOf('<embed',startPos+1))!=-1){var endPos=content.indexOf('>',startPos);var attribs=TinyMCE_FlashPlugin._parseAttributes(content.substring(startPos+6,endPos));embedList[embedList.length]=attribs;}var index=0;while((startPos=content.indexOf('<object',startPos))!=-1){if(index>=embedList.length)break;var attribs=embedList[index];endPos=content.indexOf('</object>',startPos);endPos+=9;var contentAfter=content.substring(endPos);content=content.substring(0,startPos);content+='<img width="'+attribs["width"]+'" height="'+attribs["height"]+'"';content+=' src="'+(tinyMCE.getParam("theme_href")+'/images/spacer.gif')+'" title="'+attribs["src"]+'"';content+=' alt="'+attribs["src"]+'" class="mceItemFlash" />'+content.substring(endPos);content+=contentAfter;index++;startPos++;}var index=0;while((startPos=content.indexOf('<embed',startPos))!=-1){if(index>=embedList.length)break;var attribs=embedList[index];endPos=content.indexOf('>',startPos);endPos+=9;var contentAfter=content.substring(endPos);content=content.substring(0,startPos);content+='<img width="'+attribs["width"]+'" height="'+attribs["height"]+'"';content+=' src="'+(tinyMCE.getParam("theme_href")+'/images/spacer.gif')+'" title="'+attribs["src"]+'"';content+=' alt="'+attribs["src"]+'" class="mceItemFlash" />'+content.substring(endPos);content+=contentAfter;index++;startPos++;}break;case"get_from_editor":var startPos=-1;while((startPos=content.indexOf('<img',startPos+1))!=-1){var endPos=content.indexOf('/>',startPos);var attribs=TinyMCE_FlashPlugin._parseAttributes(content.substring(startPos+4,endPos));if(attribs['class']!="mceItemFlash")continue;endPos+=2;var embedHTML='';var wmode=tinyMCE.getParam("flash_wmode","");var quality=tinyMCE.getParam("flash_quality","high");var menu=tinyMCE.getParam("flash_menu","false");embedHTML+='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"';embedHTML+=' codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0"';embedHTML+=' width="'+attribs["width"]+'" height="'+attribs["height"]+'">';embedHTML+='<param name="movie" value="'+attribs["title"]+'" />';embedHTML+='<param name="quality" value="'+quality+'" />';embedHTML+='<param name="menu" value="'+menu+'" />';embedHTML+='<param name="wmode" value="'+wmode+'" />';embedHTML+='<embed src="'+attribs["title"]+'" wmode="'+wmode+'" quality="'+quality+'" menu="'+menu+'" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="'+attribs["width"]+'" height="'+attribs["height"]+'"></embed></object>';chunkBefore=content.substring(0,startPos);chunkAfter=content.substring(endPos);content=chunkBefore+embedHTML+chunkAfter;}break;}return content;},handleNodeChange:function(editor_id,node,undo_index,undo_levels,visual_aid,any_selection){if(node==null)return;do{if(node.nodeName=="IMG"&&tinyMCE.getAttrib(node,'class').indexOf('mceItemFlash')==0){tinyMCE.switchClass(editor_id+'_flash','mceButtonSelected');return true;}}while((node=node.parentNode));tinyMCE.switchClass(editor_id+'_flash','mceButtonNormal');return true;},_parseAttributes:function(attribute_string){var attributeName="";var attributeValue="";var withInName;var withInValue;var attributes=new Array();var whiteSpaceRegExp=new RegExp('^[ \n\r\t]+','g');if(attribute_string==null||attribute_string.length<2)return null;withInName=withInValue=false;for(var i=0;i<attribute_string.length;i++){var chr=attribute_string.charAt(i);if((chr=='"'||chr=="'")&&!withInValue)withInValue=true;else if((chr=='"'||chr=="'")&&withInValue){withInValue=false;var pos=attributeName.lastIndexOf(' ');if(pos!=-1)attributeName=attributeName.substring(pos+1);attributes[attributeName.toLowerCase()]=attributeValue.substring(1);attributeName="";attributeValue="";}else if(!whiteSpaceRegExp.test(chr)&&!withInName&&!withInValue)withInName=true;if(chr=='='&&withInName)withInName=false;if(withInName)attributeName+=chr;if(withInValue)attributeValue+=chr;}return attributes;}};tinyMCE.addPlugin("flash",TinyMCE_FlashPlugin); | z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/plugins/flash/editor_plugin.js | editor_plugin.js |
var url = tinyMCE.getParam("flash_external_list_url");
if (url != null) {
// Fix relative
if (url.charAt(0) != '/' && url.indexOf('://') == -1)
url = tinyMCE.documentBasePath + "/" + url;
document.write('<sc'+'ript language="javascript" type="text/javascript" src="' + url + '"></sc'+'ript>');
}
function init() {
tinyMCEPopup.resizeToInnerSize();
document.getElementById("filebrowsercontainer").innerHTML = getBrowserHTML('filebrowser','file','flash','flash');
// Image list outsrc
var html = getFlashListHTML('filebrowser','file','flash','flash');
if (html == "")
document.getElementById("linklistrow").style.display = 'none';
else
document.getElementById("linklistcontainer").innerHTML = html;
var formObj = document.forms[0];
var swffile = tinyMCE.getWindowArg('swffile');
var swfwidth = '' + tinyMCE.getWindowArg('swfwidth');
var swfheight = '' + tinyMCE.getWindowArg('swfheight');
if (swfwidth.indexOf('%')!=-1) {
formObj.width2.value = "%";
formObj.width.value = swfwidth.substring(0,swfwidth.length-1);
} else {
formObj.width2.value = "px";
formObj.width.value = swfwidth;
}
if (swfheight.indexOf('%')!=-1) {
formObj.height2.value = "%";
formObj.height.value = swfheight.substring(0,swfheight.length-1);
} else {
formObj.height2.value = "px";
formObj.height.value = swfheight;
}
formObj.file.value = swffile;
formObj.insert.value = tinyMCE.getLang('lang_' + tinyMCE.getWindowArg('action'), 'Insert', true);
selectByValue(formObj, 'linklist', swffile);
// Handle file browser
if (isVisible('filebrowser'))
document.getElementById('file').style.width = '230px';
// Auto select flash in list
if (typeof(tinyMCEFlashList) != "undefined" && tinyMCEFlashList.length > 0) {
for (var i=0; i<formObj.linklist.length; i++) {
if (formObj.linklist.options[i].value == tinyMCE.getWindowArg('swffile'))
formObj.linklist.options[i].selected = true;
}
}
}
function getFlashListHTML() {
if (typeof(tinyMCEFlashList) != "undefined" && tinyMCEFlashList.length > 0) {
var html = "";
html += '<select id="linklist" name="linklist" style="width: 250px" onfocus="tinyMCE.addSelectAccessibility(event, this, window);" onchange="this.form.file.value=this.options[this.selectedIndex].value;">';
html += '<option value="">---</option>';
for (var i=0; i<tinyMCEFlashList.length; i++)
html += '<option value="' + tinyMCEFlashList[i][1] + '">' + tinyMCEFlashList[i][0] + '</option>';
html += '</select>';
return html;
}
return "";
}
function insertFlash() {
var formObj = document.forms[0];
var html = '';
var file = formObj.file.value;
var width = formObj.width.value;
var height = formObj.height.value;
if (formObj.width2.value=='%') {
width = width + '%';
}
if (formObj.height2.value=='%') {
height = height + '%';
}
if (width == "")
width = 100;
if (height == "")
height = 100;
html += ''
+ '<img src="' + (tinyMCE.getParam("theme_href") + "/images/spacer.gif") + '" mce_src="' + (tinyMCE.getParam("theme_href") + "/images/spacer.gif") + '" '
+ 'width="' + width + '" height="' + height + '" '
+ 'border="0" alt="' + file + '" title="' + file + '" class="mceItemFlash" />';
tinyMCEPopup.execCommand("mceInsertContent", true, html);
tinyMCE.selectedInstance.repaint();
tinyMCEPopup.close();
} | z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/plugins/flash/jscripts/flash.js | flash.js |
tinyMCE.importPluginLanguagePack('advimage','en,tr,de,sv,zh_cn,cs,fa,fr_ca,fr,pl,pt_br,nl,he,nb,ru,ru_KOI8-R,ru_UTF-8,nn,cy,es,is,zh_tw,zh_tw_utf8,sk,da');var TinyMCE_AdvancedImagePlugin={getInfo:function(){return{longname:'Advanced image',author:'Moxiecode Systems',authorurl:'http://tinymce.moxiecode.com',infourl:'http://tinymce.moxiecode.com/tinymce/docs/plugin_advimage.html',version:tinyMCE.majorVersion+"."+tinyMCE.minorVersion};},getControlHTML:function(cn){switch(cn){case"image":return tinyMCE.getButtonHTML(cn,'lang_image_desc','{$themeurl}/images/image.gif','mceAdvImage');}return"";},execCommand:function(editor_id,element,command,user_interface,value){switch(command){case"mceAdvImage":var template=new Array();template['file']='../../plugins/advimage/image.htm';template['width']=480;template['height']=380;template['width']+=tinyMCE.getLang('lang_advimage_delta_width',0);template['height']+=tinyMCE.getLang('lang_advimage_delta_height',0);var inst=tinyMCE.getInstanceById(editor_id);var elm=inst.getFocusElement();if(elm!=null&&tinyMCE.getAttrib(elm,'class').indexOf('mceItem')!=-1)return true;tinyMCE.openWindow(template,{editor_id:editor_id,inline:"yes"});return true;}return false;},cleanup:function(type,content){switch(type){case"insert_to_editor_dom":var imgs=content.getElementsByTagName("img");for(var i=0;i<imgs.length;i++){var onmouseover=tinyMCE.cleanupEventStr(tinyMCE.getAttrib(imgs[i],'onmouseover'));var onmouseout=tinyMCE.cleanupEventStr(tinyMCE.getAttrib(imgs[i],'onmouseout'));if((src=this._getImageSrc(onmouseover))!=""){if(tinyMCE.getParam('convert_urls'))src=tinyMCE.convertRelativeToAbsoluteURL(tinyMCE.settings['base_href'],src);imgs[i].setAttribute('onmouseover',"this.src='"+src+"';");}if((src=this._getImageSrc(onmouseout))!=""){if(tinyMCE.getParam('convert_urls'))src=tinyMCE.convertRelativeToAbsoluteURL(tinyMCE.settings['base_href'],src);imgs[i].setAttribute('onmouseout',"this.src='"+src+"';");}}break;case"get_from_editor_dom":var imgs=content.getElementsByTagName("img");for(var i=0;i<imgs.length;i++){var onmouseover=tinyMCE.cleanupEventStr(tinyMCE.getAttrib(imgs[i],'onmouseover'));var onmouseout=tinyMCE.cleanupEventStr(tinyMCE.getAttrib(imgs[i],'onmouseout'));if((src=this._getImageSrc(onmouseover))!=""){if(tinyMCE.getParam('convert_urls'))src=eval(tinyMCE.settings['urlconverter_callback']+"(src, null, true);");imgs[i].setAttribute('onmouseover',"this.src='"+src+"';");}if((src=this._getImageSrc(onmouseout))!=""){if(tinyMCE.getParam('convert_urls'))src=eval(tinyMCE.settings['urlconverter_callback']+"(src, null, true);");imgs[i].setAttribute('onmouseout',"this.src='"+src+"';");}}break;}return content;},handleNodeChange:function(editor_id,node,undo_index,undo_levels,visual_aid,any_selection){if(node==null)return;do{if(node.nodeName=="IMG"&&tinyMCE.getAttrib(node,'class').indexOf('mceItem')==-1){tinyMCE.switchClass(editor_id+'_advimage','mceButtonSelected');return true;}}while((node=node.parentNode));tinyMCE.switchClass(editor_id+'_advimage','mceButtonNormal');return true;},_getImageSrc:function(s){var sr,p=-1;if(!s)return"";if((p=s.indexOf('this.src='))!=-1){sr=s.substring(p+10);sr=sr.substring(0,sr.indexOf('\''));return sr;}return"";}};tinyMCE.addPlugin("advimage",TinyMCE_AdvancedImagePlugin); | z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/plugins/advimage/editor_plugin.js | editor_plugin.js |
var preloadImg = null;
var orgImageWidth, orgImageHeight;
function preinit() {
// Initialize
tinyMCE.setWindowArg('mce_windowresize', false);
// Import external list url javascript
var url = tinyMCE.getParam("external_image_list_url");
if (url != null) {
// Fix relative
if (url.charAt(0) != '/' && url.indexOf('://') == -1)
url = tinyMCE.documentBasePath + "/" + url;
document.write('<sc'+'ript language="javascript" type="text/javascript" src="' + url + '"></sc'+'ript>');
}
}
function convertURL(url, node, on_save) {
return eval("tinyMCEPopup.windowOpener." + tinyMCE.settings['urlconverter_callback'] + "(url, node, on_save);");
}
function getImageSrc(str) {
var pos = -1;
if (!str)
return "";
if ((pos = str.indexOf('this.src=')) != -1) {
var src = str.substring(pos + 10);
src = src.substring(0, src.indexOf('\''));
if (tinyMCE.getParam('convert_urls'))
src = convertURL(src, null, true);
return src;
}
return "";
}
function init() {
tinyMCEPopup.resizeToInnerSize();
var formObj = document.forms[0];
var inst = tinyMCE.getInstanceById(tinyMCE.getWindowArg('editor_id'));
var elm = inst.getFocusElement();
var action = "insert";
var html = "";
// Image list src
html = getImageListHTML('imagelistsrc','src','onSelectMainImage');
if (html == "")
document.getElementById("imagelistsrcrow").style.display = 'none';
else
document.getElementById("imagelistsrccontainer").innerHTML = html;
// Image list oversrc
html = getImageListHTML('imagelistover','onmouseoversrc');
if (html == "")
document.getElementById("imagelistoverrow").style.display = 'none';
else
document.getElementById("imagelistovercontainer").innerHTML = html;
// Image list outsrc
html = getImageListHTML('imagelistout','onmouseoutsrc');
if (html == "")
document.getElementById("imagelistoutrow").style.display = 'none';
else
document.getElementById("imagelistoutcontainer").innerHTML = html;
// Src browser
html = getBrowserHTML('srcbrowser','src','image','advimage');
document.getElementById("srcbrowsercontainer").innerHTML = html;
// Over browser
html = getBrowserHTML('oversrcbrowser','onmouseoversrc','image','advimage');
document.getElementById("onmouseoversrccontainer").innerHTML = html;
// Out browser
html = getBrowserHTML('outsrcbrowser','onmouseoutsrc','image','advimage');
document.getElementById("onmouseoutsrccontainer").innerHTML = html;
// Longdesc browser
html = getBrowserHTML('longdescbrowser','longdesc','file','advimage');
document.getElementById("longdesccontainer").innerHTML = html;
// Resize some elements
if (isVisible('srcbrowser'))
document.getElementById('src').style.width = '260px';
if (isVisible('oversrcbrowser'))
document.getElementById('onmouseoversrc').style.width = '260px';
if (isVisible('outsrcbrowser'))
document.getElementById('onmouseoutsrc').style.width = '260px';
if (isVisible('longdescbrowser'))
document.getElementById('longdesc').style.width = '180px';
// Check action
if (elm != null && elm.nodeName == "IMG")
action = "update";
formObj.insert.value = tinyMCE.getLang('lang_' + action, 'Insert', true);
if (action == "update") {
var src = tinyMCE.getAttrib(elm, 'src');
var onmouseoversrc = getImageSrc(tinyMCE.cleanupEventStr(tinyMCE.getAttrib(elm, 'onmouseover')));
var onmouseoutsrc = getImageSrc(tinyMCE.cleanupEventStr(tinyMCE.getAttrib(elm, 'onmouseout')));
src = convertURL(src, elm, true);
// Use mce_src if found
var mceRealSrc = tinyMCE.getAttrib(elm, 'mce_src');
if (mceRealSrc != "") {
src = mceRealSrc;
if (tinyMCE.getParam('convert_urls'))
src = convertURL(src, elm, true);
}
if (onmouseoversrc != "" && tinyMCE.getParam('convert_urls'))
onmouseoversrc = convertURL(onmouseoversrc, elm, true);
if (onmouseoutsrc != "" && tinyMCE.getParam('convert_urls'))
onmouseoutsrc = convertURL(onmouseoutsrc, elm, true);
// Setup form data
var style = tinyMCE.parseStyle(tinyMCE.getAttrib(elm, "style"));
// Store away old size
orgImageWidth = trimSize(getStyle(elm, 'width'))
orgImageHeight = trimSize(getStyle(elm, 'height'));
formObj.src.value = src;
formObj.alt.value = tinyMCE.getAttrib(elm, 'alt');
formObj.title.value = tinyMCE.getAttrib(elm, 'title');
formObj.border.value = trimSize(getStyle(elm, 'border', 'borderWidth'));
formObj.vspace.value = tinyMCE.getAttrib(elm, 'vspace');
formObj.hspace.value = tinyMCE.getAttrib(elm, 'hspace');
formObj.width.value = orgImageWidth;
formObj.height.value = orgImageHeight;
formObj.onmouseoversrc.value = onmouseoversrc;
formObj.onmouseoutsrc.value = onmouseoutsrc;
formObj.id.value = tinyMCE.getAttrib(elm, 'id');
formObj.dir.value = tinyMCE.getAttrib(elm, 'dir');
formObj.lang.value = tinyMCE.getAttrib(elm, 'lang');
formObj.longdesc.value = tinyMCE.getAttrib(elm, 'longdesc');
formObj.usemap.value = tinyMCE.getAttrib(elm, 'usemap');
formObj.style.value = tinyMCE.serializeStyle(style);
// Select by the values
if (tinyMCE.isMSIE)
selectByValue(formObj, 'align', getStyle(elm, 'align', 'styleFloat'));
else
selectByValue(formObj, 'align', getStyle(elm, 'align', 'cssFloat'));
addClassesToList('classlist', 'advimage_styles');
selectByValue(formObj, 'classlist', tinyMCE.getAttrib(elm, 'class'));
selectByValue(formObj, 'imagelistsrc', src);
selectByValue(formObj, 'imagelistover', onmouseoversrc);
selectByValue(formObj, 'imagelistout', onmouseoutsrc);
updateStyle();
showPreviewImage(src, true);
changeAppearance();
window.focus();
} else
addClassesToList('classlist', 'advimage_styles');
// If option enabled default contrain proportions to checked
if (tinyMCE.getParam("advimage_constrain_proportions", true))
formObj.constrain.checked = true;
// Check swap image if valid data
if (formObj.onmouseoversrc.value != "" || formObj.onmouseoutsrc.value != "")
setSwapImageDisabled(false);
else
setSwapImageDisabled(true);
}
function setSwapImageDisabled(state) {
var formObj = document.forms[0];
formObj.onmousemovecheck.checked = !state;
setBrowserDisabled('overbrowser', state);
setBrowserDisabled('outbrowser', state);
if (formObj.imagelistover)
formObj.imagelistover.disabled = state;
if (formObj.imagelistout)
formObj.imagelistout.disabled = state;
formObj.onmouseoversrc.disabled = state;
formObj.onmouseoutsrc.disabled = state;
}
function setAttrib(elm, attrib, value) {
var formObj = document.forms[0];
var valueElm = formObj.elements[attrib];
if (typeof(value) == "undefined" || value == null) {
value = "";
if (valueElm)
value = valueElm.value;
}
if (value != "") {
elm.setAttribute(attrib, value);
if (attrib == "style")
attrib = "style.cssText";
if (attrib == "longdesc")
attrib = "longDesc";
if (attrib == "width") {
attrib = "style.width";
value = value + "px";
}
if (attrib == "height") {
attrib = "style.height";
value = value + "px";
}
if (attrib == "class")
attrib = "className";
eval('elm.' + attrib + "=value;");
} else
elm.removeAttribute(attrib);
}
function makeAttrib(attrib, value) {
var formObj = document.forms[0];
var valueElm = formObj.elements[attrib];
if (typeof(value) == "undefined" || value == null) {
value = "";
if (valueElm)
value = valueElm.value;
}
if (value == "")
return "";
// XML encode it
value = value.replace(/&/g, '&');
value = value.replace(/\"/g, '"');
value = value.replace(/</g, '<');
value = value.replace(/>/g, '>');
return ' ' + attrib + '="' + value + '"';
}
function insertAction() {
var inst = tinyMCE.getInstanceById(tinyMCE.getWindowArg('editor_id'));
var elm = inst.getFocusElement();
var formObj = document.forms[0];
var src = formObj.src.value;
var onmouseoversrc = formObj.onmouseoversrc.value;
var onmouseoutsrc = formObj.onmouseoutsrc.value;
if (tinyMCE.getParam("accessibility_warnings")) {
if (formObj.alt.value == "") {
var answer = confirm(tinyMCE.getLang('lang_advimage_missing_alt', '', true));
if (answer == true) {
formObj.alt.value = " ";
}
} else {
var answer = true;
}
if (!answer)
return;
}
if (onmouseoversrc && onmouseoversrc != "")
onmouseoversrc = "this.src='" + convertURL(onmouseoversrc, tinyMCE.imgElement) + "';";
if (onmouseoutsrc && onmouseoutsrc != "")
onmouseoutsrc = "this.src='" + convertURL(onmouseoutsrc, tinyMCE.imgElement) + "';";
if (elm != null && elm.nodeName == "IMG") {
setAttrib(elm, 'src', convertURL(src, tinyMCE.imgElement));
setAttrib(elm, 'mce_src', src);
setAttrib(elm, 'alt');
setAttrib(elm, 'title');
setAttrib(elm, 'border');
setAttrib(elm, 'vspace');
setAttrib(elm, 'hspace');
setAttrib(elm, 'width');
setAttrib(elm, 'height');
setAttrib(elm, 'onmouseover', onmouseoversrc);
setAttrib(elm, 'onmouseout', onmouseoutsrc);
setAttrib(elm, 'id');
setAttrib(elm, 'dir');
setAttrib(elm, 'lang');
setAttrib(elm, 'longdesc');
setAttrib(elm, 'usemap');
setAttrib(elm, 'style');
setAttrib(elm, 'class', getSelectValue(formObj, 'classlist'));
setAttrib(elm, 'align', getSelectValue(formObj, 'align'));
//tinyMCEPopup.execCommand("mceRepaint");
// Repaint if dimensions changed
if (formObj.width.value != orgImageWidth || formObj.height.value != orgImageHeight)
inst.repaint();
// Refresh in old MSIE
if (tinyMCE.isMSIE5)
elm.outerHTML = elm.outerHTML;
} else {
var html = "<img";
html += makeAttrib('src', convertURL(src, tinyMCE.imgElement));
html += makeAttrib('mce_src', src);
html += makeAttrib('alt');
html += makeAttrib('title');
html += makeAttrib('border');
html += makeAttrib('vspace');
html += makeAttrib('hspace');
html += makeAttrib('width');
html += makeAttrib('height');
html += makeAttrib('onmouseover', onmouseoversrc);
html += makeAttrib('onmouseout', onmouseoutsrc);
html += makeAttrib('id');
html += makeAttrib('dir');
html += makeAttrib('lang');
html += makeAttrib('longdesc');
html += makeAttrib('usemap');
html += makeAttrib('style');
html += makeAttrib('class', getSelectValue(formObj, 'classlist'));
html += makeAttrib('align', getSelectValue(formObj, 'align'));
html += " />";
tinyMCEPopup.execCommand("mceInsertContent", false, html);
}
tinyMCE._setEventsEnabled(inst.getBody(), false);
tinyMCEPopup.close();
}
function cancelAction() {
tinyMCEPopup.close();
}
function changeAppearance() {
var formObj = document.forms[0];
var img = document.getElementById('alignSampleImg');
if (img) {
img.align = formObj.align.value;
img.border = formObj.border.value;
img.hspace = formObj.hspace.value;
img.vspace = formObj.vspace.value;
}
}
function changeMouseMove() {
var formObj = document.forms[0];
setSwapImageDisabled(!formObj.onmousemovecheck.checked);
}
function updateStyle() {
var formObj = document.forms[0];
var st = tinyMCE.parseStyle(formObj.style.value);
if (tinyMCE.getParam('inline_styles', false)) {
st['width'] = formObj.width.value == '' ? '' : formObj.width.value + "px";
st['height'] = formObj.height.value == '' ? '' : formObj.height.value + "px";
st['border-width'] = formObj.border.value == '' ? '' : formObj.border.value + "px";
st['margin-top'] = formObj.vspace.value == '' ? '' : formObj.vspace.value + "px";
st['margin-bottom'] = formObj.vspace.value == '' ? '' : formObj.vspace.value + "px";
st['margin-left'] = formObj.hspace.value == '' ? '' : formObj.hspace.value + "px";
st['margin-right'] = formObj.hspace.value == '' ? '' : formObj.hspace.value + "px";
} else {
st['width'] = st['height'] = st['border-width'] = null;
if (st['margin-top'] == st['margin-bottom'])
st['margin-top'] = st['margin-bottom'] = null;
if (st['margin-left'] == st['margin-right'])
st['margin-left'] = st['margin-right'] = null;
}
formObj.style.value = tinyMCE.serializeStyle(st);
}
function styleUpdated() {
var formObj = document.forms[0];
var st = tinyMCE.parseStyle(formObj.style.value);
if (st['width'])
formObj.width.value = st['width'].replace('px', '');
if (st['height'])
formObj.height.value = st['height'].replace('px', '');
if (st['margin-top'] && st['margin-top'] == st['margin-bottom'])
formObj.vspace.value = st['margin-top'].replace('px', '');
if (st['margin-left'] && st['margin-left'] == st['margin-right'])
formObj.hspace.value = st['margin-left'].replace('px', '');
if (st['border-width'])
formObj.border.value = st['border-width'].replace('px', '');
}
function changeHeight() {
var formObj = document.forms[0];
if (!formObj.constrain.checked || !preloadImg) {
updateStyle();
return;
}
if (formObj.width.value == "" || formObj.height.value == "")
return;
var temp = (formObj.width.value / preloadImg.width) * preloadImg.height;
formObj.height.value = temp.toFixed(0);
updateStyle();
}
function changeWidth() {
var formObj = document.forms[0];
if (!formObj.constrain.checked || !preloadImg) {
updateStyle();
return;
}
if (formObj.width.value == "" || formObj.height.value == "")
return;
var temp = (formObj.height.value / preloadImg.height) * preloadImg.width;
formObj.width.value = temp.toFixed(0);
updateStyle();
}
function onSelectMainImage(target_form_element, name, value) {
var formObj = document.forms[0];
formObj.alt.value = name;
formObj.title.value = name;
resetImageData();
showPreviewImage(formObj.elements[target_form_element].value, false);
}
function showPreviewImage(src, start) {
var formObj = document.forms[0];
selectByValue(document.forms[0], 'imagelistsrc', src);
var elm = document.getElementById('prev');
var src = src == "" ? src : tinyMCE.convertRelativeToAbsoluteURL(tinyMCE.settings['base_href'], src);
if (!start && tinyMCE.getParam("advimage_update_dimensions_onchange", true))
resetImageData();
if (src == "")
elm.innerHTML = "";
else
elm.innerHTML = '<img src="' + src + '" border="0" />'
getImageData(src);
}
function getImageData(src) {
preloadImg = new Image();
tinyMCE.addEvent(preloadImg, "load", updateImageData);
tinyMCE.addEvent(preloadImg, "error", resetImageData);
preloadImg.src = src;
}
function updateImageData() {
var formObj = document.forms[0];
if (formObj.width.value == "")
formObj.width.value = preloadImg.width;
if (formObj.height.value == "")
formObj.height.value = preloadImg.height;
updateStyle();
}
function resetImageData() {
var formObj = document.forms[0];
formObj.width.value = formObj.height.value = "";
}
function getSelectValue(form_obj, field_name) {
var elm = form_obj.elements[field_name];
if (elm == null || elm.options == null)
return "";
return elm.options[elm.selectedIndex].value;
}
function getImageListHTML(elm_id, target_form_element, onchange_func) {
if (typeof(tinyMCEImageList) == "undefined" || tinyMCEImageList.length == 0)
return "";
var html = "";
html += '<select id="' + elm_id + '" name="' + elm_id + '"';
html += ' class="mceImageList" onfocus="tinyMCE.addSelectAccessibility(event, this, window);" onchange="this.form.' + target_form_element + '.value=';
html += 'this.options[this.selectedIndex].value;';
if (typeof(onchange_func) != "undefined")
html += onchange_func + '(\'' + target_form_element + '\',this.options[this.selectedIndex].text,this.options[this.selectedIndex].value);';
html += '"><option value="">---</option>';
for (var i=0; i<tinyMCEImageList.length; i++)
html += '<option value="' + tinyMCEImageList[i][1] + '">' + tinyMCEImageList[i][0] + '</option>';
html += '</select>';
return html;
// tinyMCE.debug('-- image list start --', html, '-- image list end --');
}
// While loading
preinit(); | z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/plugins/advimage/jscripts/functions.js | functions.js |
tinyMCE.importPluginLanguagePack('insertdatetime','en,tr,cs,el,fr_ca,it,ko,sv,zh_cn,fa,fr,de,pl,pt_br,nl,da,he,nb,ru,ru_KOI8-R,ru_UTF-8,nn,fi,es,cy,is,pl');var TinyMCE_InsertDateTimePlugin={getInfo:function(){return{longname:'Insert date/time',author:'Moxiecode Systems',authorurl:'http://tinymce.moxiecode.com',infourl:'http://tinymce.moxiecode.com/tinymce/docs/plugin_insertdatetime.html',version:tinyMCE.majorVersion+"."+tinyMCE.minorVersion};},getControlHTML:function(cn){switch(cn){case"insertdate":return tinyMCE.getButtonHTML(cn,'lang_insertdate_desc','{$pluginurl}/images/insertdate.gif','mceInsertDate');case"inserttime":return tinyMCE.getButtonHTML(cn,'lang_inserttime_desc','{$pluginurl}/images/inserttime.gif','mceInsertTime');}return"";},execCommand:function(editor_id,element,command,user_interface,value){function addZeros(value,len){value=""+value;if(value.length<len){for(var i=0;i<(len-value.length);i++)value="0"+value;}return value;}function getDateTime(date,format){format=tinyMCE.regexpReplace(format,"%D","%m/%d/%y");format=tinyMCE.regexpReplace(format,"%r","%I:%M:%S %p");format=tinyMCE.regexpReplace(format,"%Y",""+date.getFullYear());format=tinyMCE.regexpReplace(format,"%y",""+date.getYear());format=tinyMCE.regexpReplace(format,"%m",addZeros(date.getMonth()+1,2));format=tinyMCE.regexpReplace(format,"%d",addZeros(date.getDate(),2));format=tinyMCE.regexpReplace(format,"%H",""+addZeros(date.getHours(),2));format=tinyMCE.regexpReplace(format,"%M",""+addZeros(date.getMinutes(),2));format=tinyMCE.regexpReplace(format,"%S",""+addZeros(date.getSeconds(),2));format=tinyMCE.regexpReplace(format,"%I",""+((date.getHours()+11)%12+1));format=tinyMCE.regexpReplace(format,"%p",""+(date.getHours()<12?"AM":"PM"));format=tinyMCE.regexpReplace(format,"%B",""+tinyMCE.getLang("lang_inserttime_months_long")[date.getMonth()]);format=tinyMCE.regexpReplace(format,"%b",""+tinyMCE.getLang("lang_inserttime_months_short")[date.getMonth()]);format=tinyMCE.regexpReplace(format,"%A",""+tinyMCE.getLang("lang_inserttime_day_long")[date.getDay()]);format=tinyMCE.regexpReplace(format,"%a",""+tinyMCE.getLang("lang_inserttime_day_short")[date.getDay()]);format=tinyMCE.regexpReplace(format,"%%","%");return format;}switch(command){case"mceInsertDate":tinyMCE.execInstanceCommand(editor_id,'mceInsertContent',false,getDateTime(new Date(),tinyMCE.getParam("plugin_insertdate_dateFormat",tinyMCE.getLang('lang_insertdate_def_fmt'))));return true;case"mceInsertTime":tinyMCE.execInstanceCommand(editor_id,'mceInsertContent',false,getDateTime(new Date(),tinyMCE.getParam("plugin_insertdate_timeFormat",tinyMCE.getLang('lang_inserttime_def_fmt'))));return true;}return false;}};tinyMCE.addPlugin("insertdatetime",TinyMCE_InsertDateTimePlugin); | z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/plugins/insertdatetime/editor_plugin.js | editor_plugin.js |
tinyMCE.importPluginLanguagePack('table','en,tr,ar,cs,da,de,el,es,fi,fr_ca,hu,it,ja,ko,nl,nb,pl,pt,pt_br,sv,tw,zh_cn,fr,de,he,nb,ru,ru_KOI8-R,ru_UTF-8,nn,cy,is,zh_tw,zh_tw_utf8,sk');var TinyMCE_TablePlugin={getInfo:function(){return{longname:'Tables',author:'Moxiecode Systems',authorurl:'http://tinymce.moxiecode.com',infourl:'http://tinymce.moxiecode.com/tinymce/docs/plugin_table.html',version:tinyMCE.majorVersion+"."+tinyMCE.minorVersion};},initInstance:function(inst){if(tinyMCE.isGecko){var doc=inst.getDoc();tinyMCE.addEvent(doc,"mouseup",TinyMCE_TablePlugin._mouseDownHandler);}inst.tableRowClipboard=null;},getControlHTML:function(control_name){var controls=new Array(['table','table.gif','lang_table_desc','mceInsertTable',true],['delete_col','table_delete_col.gif','lang_table_delete_col_desc','mceTableDeleteCol'],['delete_row','table_delete_row.gif','lang_table_delete_row_desc','mceTableDeleteRow'],['col_after','table_insert_col_after.gif','lang_table_col_after_desc','mceTableInsertColAfter'],['col_before','table_insert_col_before.gif','lang_table_col_before_desc','mceTableInsertColBefore'],['row_after','table_insert_row_after.gif','lang_table_row_after_desc','mceTableInsertRowAfter'],['row_before','table_insert_row_before.gif','lang_table_row_before_desc','mceTableInsertRowBefore'],['row_props','table_row_props.gif','lang_table_row_desc','mceTableRowProps',true],['cell_props','table_cell_props.gif','lang_table_cell_desc','mceTableCellProps',true],['split_cells','table_split_cells.gif','lang_table_split_cells_desc','mceTableSplitCells',true],['merge_cells','table_merge_cells.gif','lang_table_merge_cells_desc','mceTableMergeCells',true]);for(var i=0;i<controls.length;i++){var but=controls[i];var cmd='tinyMCE.execInstanceCommand(\'{$editor_id}\',\''+but[3]+'\', '+(but.length>4?but[4]:false)+(but.length>5?', \''+but[5]+'\'':'')+');return false;';if(but[0]==control_name)return tinyMCE.getButtonHTML(control_name,but[2],'{$pluginurl}/images/'+but[1],but[3],(but.length>4?but[4]:false));}if(control_name=="tablecontrols"){var html="";html+=tinyMCE.getControlHTML("table");html+=tinyMCE.getControlHTML("separator");html+=tinyMCE.getControlHTML("row_props");html+=tinyMCE.getControlHTML("cell_props");html+=tinyMCE.getControlHTML("separator");html+=tinyMCE.getControlHTML("row_before");html+=tinyMCE.getControlHTML("row_after");html+=tinyMCE.getControlHTML("delete_row");html+=tinyMCE.getControlHTML("separator");html+=tinyMCE.getControlHTML("col_before");html+=tinyMCE.getControlHTML("col_after");html+=tinyMCE.getControlHTML("delete_col");html+=tinyMCE.getControlHTML("separator");html+=tinyMCE.getControlHTML("split_cells");html+=tinyMCE.getControlHTML("merge_cells");return html;}return"";},execCommand:function(editor_id,element,command,user_interface,value){switch(command){case"mceInsertTable":case"mceTableRowProps":case"mceTableCellProps":case"mceTableSplitCells":case"mceTableMergeCells":case"mceTableInsertRowBefore":case"mceTableInsertRowAfter":case"mceTableDeleteRow":case"mceTableInsertColBefore":case"mceTableInsertColAfter":case"mceTableDeleteCol":case"mceTableCutRow":case"mceTableCopyRow":case"mceTablePasteRowBefore":case"mceTablePasteRowAfter":case"mceTableDelete":var inst=tinyMCE.getInstanceById(editor_id);inst.execCommand('mceBeginUndoLevel');TinyMCE_TablePlugin._doExecCommand(editor_id,element,command,user_interface,value);inst.execCommand('mceEndUndoLevel');return true;}return false;},handleNodeChange:function(editor_id,node,undo_index,undo_levels,visual_aid,any_selection){var colspan="1",rowspan="1";var inst=tinyMCE.getInstanceById(editor_id);tinyMCE.switchClass(editor_id+'_table','mceButtonNormal');tinyMCE.switchClass(editor_id+'_row_props','mceButtonDisabled');tinyMCE.switchClass(editor_id+'_cell_props','mceButtonDisabled');tinyMCE.switchClass(editor_id+'_row_before','mceButtonDisabled');tinyMCE.switchClass(editor_id+'_row_after','mceButtonDisabled');tinyMCE.switchClass(editor_id+'_delete_row','mceButtonDisabled');tinyMCE.switchClass(editor_id+'_col_before','mceButtonDisabled');tinyMCE.switchClass(editor_id+'_col_after','mceButtonDisabled');tinyMCE.switchClass(editor_id+'_delete_col','mceButtonDisabled');tinyMCE.switchClass(editor_id+'_split_cells','mceButtonDisabled');tinyMCE.switchClass(editor_id+'_merge_cells','mceButtonDisabled');if(tdElm=tinyMCE.getParentElement(node,"td,th")){tinyMCE.switchClass(editor_id+'_cell_props','mceButtonSelected');tinyMCE.switchClass(editor_id+'_row_before','mceButtonNormal');tinyMCE.switchClass(editor_id+'_row_after','mceButtonNormal');tinyMCE.switchClass(editor_id+'_delete_row','mceButtonNormal');tinyMCE.switchClass(editor_id+'_col_before','mceButtonNormal');tinyMCE.switchClass(editor_id+'_col_after','mceButtonNormal');tinyMCE.switchClass(editor_id+'_delete_col','mceButtonNormal');colspan=tinyMCE.getAttrib(tdElm,"colspan");rowspan=tinyMCE.getAttrib(tdElm,"rowspan");colspan=colspan==""?"1":colspan;rowspan=rowspan==""?"1":rowspan;if(colspan!="1"||rowspan!="1")tinyMCE.switchClass(editor_id+'_split_cells','mceButtonNormal');}if(tinyMCE.getParentElement(node,"tr"))tinyMCE.switchClass(editor_id+'_row_props','mceButtonSelected');if(tinyMCE.getParentElement(node,"table")){tinyMCE.switchClass(editor_id+'_table','mceButtonSelected');tinyMCE.switchClass(editor_id+'_merge_cells','mceButtonNormal');}},_mouseDownHandler:function(e){var elm=tinyMCE.isMSIE?event.srcElement:e.target;var focusElm=tinyMCE.selectedInstance.getFocusElement();if(elm.nodeName=="BODY"&&(focusElm.nodeName=="TD"||focusElm.nodeName=="TH"||(focusElm.parentNode&&focusElm.parentNode.nodeName=="TD")||(focusElm.parentNode&&focusElm.parentNode.nodeName=="TH"))){window.setTimeout(function(){var tableElm=tinyMCE.getParentElement(focusElm,"table");tinyMCE.handleVisualAid(tableElm,true,tinyMCE.settings['visual'],tinyMCE.selectedInstance);},10);}},_doExecCommand:function(editor_id,element,command,user_interface,value){var inst=tinyMCE.getInstanceById(editor_id);var focusElm=inst.getFocusElement();var trElm=tinyMCE.getParentElement(focusElm,"tr");var tdElm=tinyMCE.getParentElement(focusElm,"td,th");var tableElm=tinyMCE.getParentElement(focusElm,"table");var doc=inst.contentWindow.document;var tableBorder=tableElm?tableElm.getAttribute("border"):"";if(trElm&&tdElm==null)tdElm=trElm.cells[0];function inArray(ar,v){for(var i=0;i<ar.length;i++){if(ar[i].length>0&&inArray(ar[i],v))return true;if(ar[i]==v)return true;}return false;}function makeTD(){var newTD=doc.createElement("td");newTD.innerHTML=" ";}function getColRowSpan(td){var colspan=tinyMCE.getAttrib(td,"colspan");var rowspan=tinyMCE.getAttrib(td,"rowspan");colspan=colspan==""?1:parseInt(colspan);rowspan=rowspan==""?1:parseInt(rowspan);return{colspan:colspan,rowspan:rowspan};}function getCellPos(grid,td){for(var y=0;y<grid.length;y++){for(var x=0;x<grid[y].length;x++){if(grid[y][x]==td)return{cellindex:x,rowindex:y};}}return null;}function getCell(grid,row,col){if(grid[row]&&grid[row][col])return grid[row][col];return null;}function getTableGrid(table){var grid=new Array();var rows=table.rows;for(var y=0;y<rows.length;y++){for(var x=0;x<rows[y].cells.length;x++){var td=rows[y].cells[x];var sd=getColRowSpan(td);for(xstart=x;grid[y]&&grid[y][xstart];xstart++);for(var y2=y;y2<y+sd['rowspan'];y2++){if(!grid[y2])grid[y2]=new Array();for(var x2=xstart;x2<xstart+sd['colspan'];x2++){grid[y2][x2]=td;}}}}return grid;}function trimRow(table,tr,td,new_tr){var grid=getTableGrid(table);var cpos=getCellPos(grid,td);if(new_tr.cells.length!=tr.childNodes.length){var cells=tr.childNodes;var lastElm=null;for(var x=0;td=getCell(grid,cpos.rowindex,x);x++){var remove=true;var sd=getColRowSpan(td);if(inArray(cells,td)){new_tr.childNodes[x]._delete=true;}else if((lastElm==null||td!=lastElm)&&sd.colspan>1){for(var i=x;i<x+td.colSpan;i++)new_tr.childNodes[i]._delete=true;}if((lastElm==null||td!=lastElm)&&sd.rowspan>1)td.rowSpan=sd.rowspan+1;lastElm=td;}deleteMarked(tableElm);}}function prevElm(node,name){while((node=node.previousSibling)!=null){if(node.nodeName==name)return node;}return null;}function nextElm(node,names){var namesAr=names.split(',');while((node=node.nextSibling)!=null){for(var i=0;i<namesAr.length;i++){if(node.nodeName.toLowerCase()==namesAr[i].toLowerCase())return node;}}return null;}function deleteMarked(tbl){if(tbl.rows==0)return;var tr=tbl.rows[0];do{var next=nextElm(tr,"TR");if(tr._delete){tr.parentNode.removeChild(tr);continue;}var td=tr.cells[0];if(td.cells>1){do{var nexttd=nextElm(td,"TD,TH");if(td._delete)td.parentNode.removeChild(td);}while((td=nexttd)!=null);}}while((tr=next)!=null);}function addRows(td_elm,tr_elm,rowspan){td_elm.rowSpan=1;var trNext=nextElm(tr_elm,"TR");for(var i=1;i<rowspan&&trNext;i++){var newTD=doc.createElement("td");newTD.innerHTML=" ";if(tinyMCE.isMSIE)trNext.insertBefore(newTD,trNext.cells(td_elm.cellIndex));else trNext.insertBefore(newTD,trNext.cells[td_elm.cellIndex]);trNext=nextElm(trNext,"TR");}}function copyRow(doc,table,tr){var grid=getTableGrid(table);var newTR=tr.cloneNode(false);var cpos=getCellPos(grid,tr.cells[0]);var lastCell=null;var tableBorder=tinyMCE.getAttrib(table,"border");var tdElm=null;for(var x=0;tdElm=getCell(grid,cpos.rowindex,x);x++){var newTD=null;if(lastCell!=tdElm){for(var i=0;i<tr.cells.length;i++){if(tdElm==tr.cells[i]){newTD=tdElm.cloneNode(true);break;}}}if(newTD==null){newTD=doc.createElement("td");newTD.innerHTML=" ";}newTD.colSpan=1;newTD.rowSpan=1;newTR.appendChild(newTD);lastCell=tdElm;}return newTR;}switch(command){case"mceTableRowProps":if(trElm==null)return true;if(user_interface){var template=new Array();template['file']='../../plugins/table/row.htm';template['width']=380;template['height']=295;template['width']+=tinyMCE.getLang('lang_table_rowprops_delta_width',0);template['height']+=tinyMCE.getLang('lang_table_rowprops_delta_height',0);tinyMCE.openWindow(template,{editor_id:inst.editorId,inline:"yes"});}return true;case"mceTableCellProps":if(tdElm==null)return true;if(user_interface){var template=new Array();template['file']='../../plugins/table/cell.htm';template['width']=380;template['height']=295;template['width']+=tinyMCE.getLang('lang_table_cellprops_delta_width',0);template['height']+=tinyMCE.getLang('lang_table_cellprops_delta_height',0);tinyMCE.openWindow(template,{editor_id:inst.editorId,inline:"yes"});}return true;case"mceInsertTable":if(user_interface){var template=new Array();template['file']='../../plugins/table/table.htm';template['width']=380;template['height']=295;template['width']+=tinyMCE.getLang('lang_table_table_delta_width',0);template['height']+=tinyMCE.getLang('lang_table_table_delta_height',0);tinyMCE.openWindow(template,{editor_id:inst.editorId,inline:"yes",action:value});}return true;case"mceTableDelete":var table=tinyMCE.getParentElement(inst.getFocusElement(),"table");if(table){table.parentNode.removeChild(table);inst.repaint();}return true;case"mceTableSplitCells":case"mceTableMergeCells":case"mceTableInsertRowBefore":case"mceTableInsertRowAfter":case"mceTableDeleteRow":case"mceTableInsertColBefore":case"mceTableInsertColAfter":case"mceTableDeleteCol":case"mceTableCutRow":case"mceTableCopyRow":case"mceTablePasteRowBefore":case"mceTablePasteRowAfter":if(!tableElm)return true;if(tableElm!=trElm.parentNode)tableElm=trElm.parentNode;if(tableElm&&trElm){switch(command){case"mceTableInsertRowBefore":if(!trElm||!tdElm)return true;var grid=getTableGrid(tableElm);var cpos=getCellPos(grid,tdElm);var newTR=doc.createElement("tr");var lastTDElm=null;cpos.rowindex--;if(cpos.rowindex<0)cpos.rowindex=0;for(var x=0;tdElm=getCell(grid,cpos.rowindex,x);x++){if(tdElm!=lastTDElm){var sd=getColRowSpan(tdElm);if(sd['rowspan']==1){var newTD=doc.createElement("td");newTD.innerHTML=" ";newTD.colSpan=tdElm.colSpan;newTR.appendChild(newTD);}else tdElm.rowSpan=sd['rowspan']+1;lastTDElm=tdElm;}}trElm.parentNode.insertBefore(newTR,trElm);break;case"mceTableCutRow":if(!trElm||!tdElm)return true;inst.tableRowClipboard=copyRow(doc,tableElm,trElm);inst.execCommand("mceTableDeleteRow");break;case"mceTableCopyRow":if(!trElm||!tdElm)return true;inst.tableRowClipboard=copyRow(doc,tableElm,trElm);break;case"mceTablePasteRowBefore":if(!trElm||!tdElm)return true;var newTR=inst.tableRowClipboard.cloneNode(true);var prevTR=prevElm(trElm,"TR");if(prevTR!=null)trimRow(tableElm,prevTR,prevTR.cells[0],newTR);trElm.parentNode.insertBefore(newTR,trElm);break;case"mceTablePasteRowAfter":if(!trElm||!tdElm)return true;var nextTR=nextElm(trElm,"TR");var newTR=inst.tableRowClipboard.cloneNode(true);trimRow(tableElm,trElm,tdElm,newTR);if(nextTR==null)trElm.parentNode.appendChild(newTR);else nextTR.parentNode.insertBefore(newTR,nextTR);break;case"mceTableInsertRowAfter":if(!trElm||!tdElm)return true;var grid=getTableGrid(tableElm);var cpos=getCellPos(grid,tdElm);var newTR=doc.createElement("tr");var lastTDElm=null;for(var x=0;tdElm=getCell(grid,cpos.rowindex,x);x++){if(tdElm!=lastTDElm){var sd=getColRowSpan(tdElm);if(sd['rowspan']==1){var newTD=doc.createElement("td");newTD.innerHTML=" ";newTD.colSpan=tdElm.colSpan;newTR.appendChild(newTD);}else tdElm.rowSpan=sd['rowspan']+1;lastTDElm=tdElm;}}if(newTR.hasChildNodes()){var nextTR=nextElm(trElm,"TR");if(nextTR)nextTR.parentNode.insertBefore(newTR,nextTR);else tableElm.appendChild(newTR);}break;case"mceTableDeleteRow":if(!trElm||!tdElm)return true;var grid=getTableGrid(tableElm);var cpos=getCellPos(grid,tdElm);if(grid.length==1){tableElm.parentNode.removeChild(tableElm);return true;}var cells=trElm.cells;var nextTR=nextElm(trElm,"TR");for(var x=0;x<cells.length;x++){if(cells[x].rowSpan>1){var newTD=cells[x].cloneNode(true);var sd=getColRowSpan(cells[x]);newTD.rowSpan=sd.rowspan-1;var nextTD=nextTR.cells[x];if(nextTD==null)nextTR.appendChild(newTD);else nextTR.insertBefore(newTD,nextTD);}}var lastTDElm=null;for(var x=0;tdElm=getCell(grid,cpos.rowindex,x);x++){if(tdElm!=lastTDElm){var sd=getColRowSpan(tdElm);if(sd.rowspan>1){tdElm.rowSpan=sd.rowspan-1;}else{trElm=tdElm.parentNode;if(trElm.parentNode)trElm._delete=true;}lastTDElm=tdElm;}}deleteMarked(tableElm);cpos.rowindex--;if(cpos.rowindex<0)cpos.rowindex=0;inst.selection.selectNode(getCell(grid,cpos.rowindex,0),true,true);break;case"mceTableInsertColBefore":if(!trElm||!tdElm)return true;var grid=getTableGrid(tableElm);var cpos=getCellPos(grid,tdElm);var lastTDElm=null;for(var y=0;tdElm=getCell(grid,y,cpos.cellindex);y++){if(tdElm!=lastTDElm){var sd=getColRowSpan(tdElm);if(sd['colspan']==1){var newTD=doc.createElement(tdElm.nodeName);newTD.innerHTML=" ";newTD.rowSpan=tdElm.rowSpan;tdElm.parentNode.insertBefore(newTD,tdElm);}else tdElm.colSpan++;lastTDElm=tdElm;}}break;case"mceTableInsertColAfter":if(!trElm||!tdElm)return true;var grid=getTableGrid(tableElm);var cpos=getCellPos(grid,tdElm);var lastTDElm=null;for(var y=0;tdElm=getCell(grid,y,cpos.cellindex);y++){if(tdElm!=lastTDElm){var sd=getColRowSpan(tdElm);if(sd['colspan']==1){var newTD=doc.createElement(tdElm.nodeName);newTD.innerHTML=" ";newTD.rowSpan=tdElm.rowSpan;var nextTD=nextElm(tdElm,"TD,TH");if(nextTD==null)tdElm.parentNode.appendChild(newTD);else nextTD.parentNode.insertBefore(newTD,nextTD);}else tdElm.colSpan++;lastTDElm=tdElm;}}break;case"mceTableDeleteCol":if(!trElm||!tdElm)return true;var grid=getTableGrid(tableElm);var cpos=getCellPos(grid,tdElm);var lastTDElm=null;if(grid.length>1&&grid[0].length<=1){tableElm.parentNode.removeChild(tableElm);return true;}for(var y=0;tdElm=getCell(grid,y,cpos.cellindex);y++){if(tdElm!=lastTDElm){var sd=getColRowSpan(tdElm);if(sd['colspan']>1)tdElm.colSpan=sd['colspan']-1;else{if(tdElm.parentNode)tdElm.parentNode.removeChild(tdElm);}lastTDElm=tdElm;}}cpos.cellindex--;if(cpos.cellindex<0)cpos.cellindex=0;inst.selection.selectNode(getCell(grid,0,cpos.cellindex),true,true);break;case"mceTableSplitCells":if(!trElm||!tdElm)return true;var spandata=getColRowSpan(tdElm);var colspan=spandata["colspan"];var rowspan=spandata["rowspan"];if(colspan>1||rowspan>1){tdElm.colSpan=1;for(var i=1;i<colspan;i++){var newTD=doc.createElement("td");newTD.innerHTML=" ";trElm.insertBefore(newTD,nextElm(tdElm,"TD,TH"));if(rowspan>1)addRows(newTD,trElm,rowspan);}addRows(tdElm,trElm,rowspan);}tableElm=tinyMCE.getParentElement(inst.getFocusElement(),"table");break;case"mceTableMergeCells":var rows=new Array();var sel=inst.getSel();var grid=getTableGrid(tableElm);if(tinyMCE.isMSIE||sel.rangeCount==1){if(user_interface){var template=new Array();var sp=getColRowSpan(tdElm);template['file']='../../plugins/table/merge_cells.htm';template['width']=250;template['height']=105+(tinyMCE.isNS7?25:0);template['width']+=tinyMCE.getLang('lang_table_merge_cells_delta_width',0);template['height']+=tinyMCE.getLang('lang_table_merge_cells_delta_height',0);tinyMCE.openWindow(template,{editor_id:inst.editorId,inline:"yes",action:"update",numcols:sp.colspan,numrows:sp.rowspan});return true;}else{var numRows=parseInt(value['numrows']);var numCols=parseInt(value['numcols']);var cpos=getCellPos(grid,tdElm);if((""+numRows)=="NaN")numRows=1;if((""+numCols)=="NaN")numCols=1;var tRows=tableElm.rows;for(var y=cpos.rowindex;y<grid.length;y++){var rowCells=new Array();for(var x=cpos.cellindex;x<grid[y].length;x++){var td=getCell(grid,y,x);if(td&&!inArray(rows,td)&&!inArray(rowCells,td)){var cp=getCellPos(grid,td);if(cp.cellindex<cpos.cellindex+numCols&&cp.rowindex<cpos.rowindex+numRows)rowCells[rowCells.length]=td;}}if(rowCells.length>0)rows[rows.length]=rowCells;}}}else{var cells=new Array();var sel=inst.getSel();var lastTR=null;var curRow=null;var x1=-1,y1=-1,x2,y2;if(sel.rangeCount<2)return true;for(var i=0;i<sel.rangeCount;i++){var rng=sel.getRangeAt(i);var tdElm=rng.startContainer.childNodes[rng.startOffset];if(!tdElm)break;if(tdElm.nodeName=="TD")cells[cells.length]=tdElm;}var tRows=tableElm.rows;for(var y=0;y<tRows.length;y++){var rowCells=new Array();for(var x=0;x<tRows[y].cells.length;x++){var td=tRows[y].cells[x];for(var i=0;i<cells.length;i++){if(td==cells[i]){rowCells[rowCells.length]=td;}}}if(rowCells.length>0)rows[rows.length]=rowCells;}var curRow=new Array();var lastTR=null;for(var y=0;y<grid.length;y++){for(var x=0;x<grid[y].length;x++){grid[y][x]._selected=false;for(var i=0;i<cells.length;i++){if(grid[y][x]==cells[i]){if(x1==-1){x1=x;y1=y;}x2=x;y2=y;grid[y][x]._selected=true;}}}}for(var y=y1;y<=y2;y++){for(var x=x1;x<=x2;x++){if(!grid[y][x]._selected){alert("Invalid selection for merge.");return true;}}}}var rowSpan=1,colSpan=1;var lastRowSpan=-1;for(var y=0;y<rows.length;y++){var rowColSpan=0;for(var x=0;x<rows[y].length;x++){var sd=getColRowSpan(rows[y][x]);rowColSpan+=sd['colspan'];if(lastRowSpan!=-1&&sd['rowspan']!=lastRowSpan){alert("Invalid selection for merge.");return true;}lastRowSpan=sd['rowspan'];}if(rowColSpan>colSpan)colSpan=rowColSpan;lastRowSpan=-1;}var lastColSpan=-1;for(var x=0;x<rows[0].length;x++){var colRowSpan=0;for(var y=0;y<rows.length;y++){var sd=getColRowSpan(rows[y][x]);colRowSpan+=sd['rowspan'];if(lastColSpan!=-1&&sd['colspan']!=lastColSpan){alert("Invalid selection for merge.");return true;}lastColSpan=sd['colspan'];}if(colRowSpan>rowSpan)rowSpan=colRowSpan;lastColSpan=-1;}tdElm=rows[0][0];tdElm.rowSpan=rowSpan;tdElm.colSpan=colSpan;for(var y=0;y<rows.length;y++){for(var x=0;x<rows[y].length;x++){var html=rows[y][x].innerHTML;var chk=tinyMCE.regexpReplace(html,"[ \t\r\n]","");if(chk!="<br/>"&&chk!="<br>"&&chk!=" "&&(x+y>0))tdElm.innerHTML+=html;if(rows[y][x]!=tdElm&&!rows[y][x]._deleted){var cpos=getCellPos(grid,rows[y][x]);var tr=rows[y][x].parentNode;tr.removeChild(rows[y][x]);rows[y][x]._deleted=true;if(!tr.hasChildNodes()){tr.parentNode.removeChild(tr);var lastCell=null;for(var x=0;cellElm=getCell(grid,cpos.rowindex,x);x++){if(cellElm!=lastCell&&cellElm.rowSpan>1)cellElm.rowSpan--;lastCell=cellElm;}if(tdElm.rowSpan>1)tdElm.rowSpan--;}}}}break;}tableElm=tinyMCE.getParentElement(inst.getFocusElement(),"table");tinyMCE.handleVisualAid(tableElm,true,tinyMCE.settings['visual'],tinyMCE.selectedInstance);tinyMCE.triggerNodeChange();inst.repaint();}return true;}return false;}};tinyMCE.addPlugin("table",TinyMCE_TablePlugin); | z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/plugins/table/editor_plugin.js | editor_plugin.js |
tinyMCE.addToLang('table',{
general_tab : 'Yleiset',
advanced_tab : 'Edistyneemmät',
general_props : 'Yleisasetukset',
advanced_props : 'Edistyneemmät asetukset',
desc : 'Lisää uusi taulukko',
row_before_desc : 'Lisää rivi edelle',
row_after_desc : 'Lisää rivi jälkeen',
delete_row_desc : 'Poista rivi',
col_before_desc : 'Lisää sarake edelle',
col_after_desc : 'Lisää sarake jälkeen',
delete_col_desc : 'Poista sarake',
rowtype : 'Row in table part',
title : 'Lisää/Muokkaa taulukkoa',
width : 'Leveys',
height : 'Korkeus',
cols : 'Saraketta',
rows : 'Riviä',
cellspacing : 'Cellspacing',
cellpadding : 'Cellpadding',
border : 'Reuna',
align : 'Asettelu',
align_default : 'Oletus',
align_left : 'Vasen',
align_right : 'Oikea',
align_middle : 'Keskelle',
row_title : 'Rivin ominaisuudet',
cell_title : 'Sarakkeen ominaisuudet',
cell_type : 'Solun tyyppi',
row_desc : 'Rivin ominaisuudet',
cell_desc : 'Solun ominaisuudet',
valign : 'Pystysuora asettelu',
align_top : 'Yläreuna',
align_bottom : 'Alareuna',
props_desc : 'Taulukon ominaisuudet',
bordercolor : 'Reunan väri',
bgcolor : 'Taustaväri',
merge_cells_title : 'Yhdistä taulukon solut',
split_cells_desc : 'Erota taulukon solut',
merge_cells_desc : 'Yhdistä taulukon solut',
cut_row_desc : 'Leikkaa taulukon rivi',
copy_row_desc : 'Kopioi taulukon rivi',
paste_row_before_desc : 'Liitä taulukon rivi edelle',
paste_row_after_desc : 'Liitä taulukon rivi jälkeen',
id : 'Id',
style: 'Tyyli',
langdir : 'Kielen suunta',
langcode : 'Kielikoodi',
mime : 'Kohteen MIME-tyyppi',
ltr : 'Vasemmalta oikealle',
rtl : 'Oikealta vasemmalle',
bgimage : 'Taustakuva',
summary : 'Yhteenveto',
td : "Data",
th : "Otsikko",
cell_cell : 'Päivitä kyseinen solu',
cell_row : 'Päivitä kaikki solut rivissä',
cell_all : 'Päivitä kaikki solut taulukossa',
row_row : 'Päivitä kyseinen rivi',
row_odd : 'Päivitä parittomat rivit',
row_even : 'Päivitä parilliset rivit',
row_all : 'Päivitä kaikki rivit',
thead : 'Table Head',
tbody : 'Table Body',
tfoot : 'Table Foot',
del : 'Poista taulukko',
scope : 'Scope',
row : 'Rivi',
col : 'Sarake',
rowgroup : 'Riviryhmä',
colgroup : 'Sarakeryhmä',
missing_scope: 'Are you sure you want to continue without specifying a scope for this table header cell. Without it, it may be difficult for some users with disabilities to understand the content or data displayed of the table.',
cellprops_delta_width : 50
}); | z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/plugins/table/langs/fi.js | fi.js |
tinyMCE.addToLang('table',{
general_tab : 'Generelt',
advanced_tab : 'Avansert',
general_props : 'Generelle egenskaper',
advanced_props : 'Avanserte egenskaper',
desc : 'Opprett/endre tabell',
row_before_desc : 'Opprett rad foran',
row_after_desc : 'Opprett rad etter',
delete_row_desc : 'Fjern rad',
col_before_desc : 'Opprett kolonne foran',
col_after_desc : 'Opprett kolonne etter',
delete_col_desc : 'Fjern kolonne',
rowtype : 'Rad i tabell',
title : 'Opprett/endre tabell',
width : 'Bredde',
height : 'Høyde',
cols : 'Kolonner',
rows : 'Rader',
cellspacing : 'Celle mellomrom',
cellpadding : 'Celle fylling',
border : 'Rammebredde',
align : 'Justering',
align_default : 'Ingen',
align_left : 'Venstre',
align_right : 'Høyre',
align_middle : 'Midtstilt',
row_title : 'tabell rad egenskaper',
cell_title : 'tabell celle egenskaper',
cell_type : 'Celle type',
row_desc : 'tabell rad egenskaper',
cell_desc : 'tabell celle egenskaper',
valign : 'Vertikal justering',
align_top : 'Topp',
align_bottom : 'Bunn',
props_desc : 'tabell egenskaper',
bordercolor : 'Rammefarge',
bgcolor : 'Bakgrunnsfarge',
merge_cells_title : 'Slå sammen tabell celler',
split_cells_desc : 'Splitt tabell celler',
merge_cells_desc : 'Slå sammen tabell celler',
cut_row_desc : 'Fjern tabell rad',
copy_row_desc : 'Kopier tabell rad',
paste_row_before_desc : 'Lim inn tabell rad foran',
paste_row_after_desc : 'Lim inn tabell rad etter',
id : 'Id',
style: 'Stil',
langdir : 'Språk retning',
langcode : 'Språk kode',
mime : 'Målets MIME type',
ltr : 'Venstre mot høyre',
rtl : 'Høyre mot venstre',
bgimage : 'Bakgrunnsbilde',
summary : 'Sum',
td : "Data",
th : "Overskrift",
cell_cell : 'Oppdater valgt celle',
cell_row : 'Oppdater alle celler i raden',
cell_all : 'Oppdater alle celler i tabellen',
row_row : 'Oppdater valgt rad',
row_odd : 'Oppdater ulike rader i tabellen',
row_even : 'Oppdater like rader i tabellen',
row_all : 'Oppdater alle rader i tabellen',
thead : 'Tabell Hode',
tbody : 'Tabell Kropp',
tfoot : 'Tabell Fot',
del : 'Slett tabell',
scope : 'Hensikt',
row : 'Rad',
col : 'Kolonne',
rowgroup : 'Rad gruppe',
colgroup : 'Kolonne gruppe',
missing_scope: 'Er du sikker på at du vil fortsette uten å oppgi hensikten med denne tabellens hode celle.'
}); | z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/plugins/table/langs/nb.js | nb.js |
tinyMCE.addToLang('table',{
general_tab : 'Generelt',
advanced_tab : 'Avanceret',
general_props : 'Generelle egenskaber',
advanced_props : 'Avancerede egenskaber',
desc : 'Indsætter ny tabel',
row_before_desc : 'Indsæt række foran',
row_after_desc : 'Indsæt række efter',
delete_row_desc : 'Slet række',
col_before_desc : 'Indsæt kolonne foran',
col_after_desc : 'Indsæt kolonner efter',
delete_col_desc : 'Fjern kolonne',
rowtype : 'Række i tabeldelen',
title : 'Indsæt eller rediger tabel',
width : 'Bredde',
height : 'Højde',
cols : 'Kolonner',
rows : 'Rækker',
cellspacing : 'Cellemargin',
cellpadding : 'Indvendig margin',
border : 'Kant',
align : 'Justering',
align_default : 'Standard',
align_left : 'Venstre',
align_right : 'Højre',
align_middle : 'Centreret',
row_title : 'Rækkeegenskaber',
cell_title : 'Celleegenskaber',
cell_type : 'Celletype',
row_desc : 'Rækkeegenskaber',
cell_desc : 'Celleegenskaber',
valign : 'Vertikal justering',
align_top : 'Top',
align_bottom : 'Bund',
props_desc : 'Tabelegenskaber',
bordercolor : 'Kantfarve',
bgcolor : 'Baggrundsfarve',
merge_cells_title : 'Flet celler',
split_cells_desc : 'Del celler',
merge_cells_desc : 'Flet celler',
cut_row_desc : 'Del kolonne',
copy_row_desc : 'Kopier kolonne',
paste_row_before_desc : 'Indsæt kolonne foran',
paste_row_after_desc : 'Indsæt kolonne efter',
id : 'Tabel id',
style: 'Style',
langdir : 'Tekstretning',
langcode : 'Sprogkode',
mime : 'Target MIME type',
ltr : 'Venstre til højre',
rtl : 'Højre til venstre',
bgimage : 'Baggrundsbillede',
summary : 'Opsummering',
td : "Data",
th : "Overskrift",
cell_cell : 'Opdater aktuel celle',
cell_row : 'Opdater alle celler i kolonnen',
cell_all : 'Opdater alle celler i tabellen',
row_row : 'Opdater aktuel kolonne',
row_odd : 'Opdater ulige kolonner i tabellen',
row_even : 'Opdater lige kolonner i tabellen',
row_all : 'Opdater alle kolonner i tabellen',
thead : 'Tabeloverskrift',
tbody : 'Tabelindhold',
tfoot : 'Tabelfodnote',
del : 'Slet tabel',
scope : 'Område',
row : 'Række',
col : 'Kolonne',
rowgroup : 'Flere rækker',
colgroup : 'Flere kolonner',
missing_scope: 'Er du sikker på at du vil fortsætte uden at angive et område for denne celle overskrift. Hvis du undlader den, kan det være svært for nogle brugere at forstå indholdet i tabellen.',
cellprops_delta_width : 30
}); | z3c.widget | /z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/plugins/table/langs/da.js | da.js |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.