Revision 1198

View differences:

org.gvsig.scripting/tags/org.gvsig.scripting-2.3.87/org.gvsig.scripting.app/org.gvsig.scripting.app.mainplugin/src/main/resources-plugin/plugin-persistence.def
1
<?xml version="1.0"?>
2
<!--
3
Definitions of plugin persistence org.gvsig.scripting.app.mainplugin.
4
 -->
5
<definitions>
6
  <version>1.0.0</version>
7
  <classes>
8
    <class name="org.gvsig.scripting.app.mainplugin">
9
      <description>Persistence of scripting plugin</description>
10
      <fields>
11
        <field name="ComposerUseHisWindowManager" type="boolean" mandatory="true" defaultValue="true">
12
          <description>When true the composer use his window manager instead of the gvSIG Window manager.</description>
13
        </field>
14
      </fields>
15
    </class>
16
  </classes>
17
</definitions>
org.gvsig.scripting/tags/org.gvsig.scripting-2.3.87/org.gvsig.scripting.app/org.gvsig.scripting.app.mainplugin/src/main/resources-plugin/i18n/text.properties
1
_Scripting=Scripting
2
_Show_scripting_launcher=Abrir lanzador de scripts
3
_Show_scripting_composer=Abrir editor de scripts
4
_Show_scripting_jython_console=Abrir consola Jython
5

  
6
User=Usuario
7
System=Sistema
8

  
9
Accept=Aceptar
10
Cancel=Cancelar
11
Apply=Aplicar
12

  
13
Retrieving_data=Recibiendo datos...
14

  
15
File=Fichero
16
New=Nuevo
17
Close_document=Cerrar documento
18
Close_all_documents=Cerrar todos los documentos
19
Run=Ejecutar
20
Save=Guardar
21
Close=Cerrar
22
Close_current_tab=Cerrar pesta\u00f1a actual
23
Open_edition_mode=Abrir modo edici\u00f3n
24
Run_selected_script=Ejecutar script seleccionado
25
Delete_selected_script=Borrar script seleccionado
26
Refresh_directories=Actualizar carpetas
27
Move_files=Mover ficheros
28
Set_file_preferences=Editar preferencias de fichero
29

  
30

  
31
Edit=Editar
32
Cut=Cortar
33
Copy=Copiar
34
Paste=Pegar
35
Select_all=Seleccionar todo
36

  
37
Tools=Herramientas
38
Launcher=Lanzador de scripts
39
Scripting_Launcher=Lanzador de scripts
40
Scripting_Composer=Editor de scripts
41
Jython_Console=Consola Jython
42
Import_JavaDoc=Importar JavaDoc
43
JavaDoc=Ayuda de Java (JavaDoc)
44
Remove_JavaDoc=Eliminar JavaDoc
45
Help_contents=Contenido de la ayuda
46
About_scripts_editor=Acerca del editor de scripts
47
Get_help=Ayuda
48
Help=Ayuda
49
_Package_script=Empaquetar script...
50
_Package_help=Empaquetar ayuda...
51

  
52
Problems=Errores
53
Console=Consola
54

  
55
Description=Descripci\u00f3n
56
Resource=Recurso
57
Location=Ubicaci\u00f3n
58

  
59
no_line=sin l\u00ednea
60
Line=L\u00ednea
61

  
62
Welcome_message=Bienvenido al entorno de scripting
63

  
64
Error_opening_in_edition_mode_title=Error al abrir fichero
65
Error_opening_in_edition_mode=No se pudo abrir el fichero en modo edici\u00f3n
66

  
67
New_Script=Nuevo elemento
68
New_Script_Description=Crea un nuevo script, di\u00e1logo, proyecto, directorio
69

  
70
Deleting_JavaDocs_successfully_title=Operaci\u00f3n realizada con \u00e9xito
71
Deleting_JavaDocs_successfully=Eliminaci\u00f3n de los JavaDocs exitosa
72

  
73
Import_JavaDoc_title=Importar JavaDocs desde los directorios de sistema al ScriptingFramework JavaDoc
74
Remove_JavaDoc_title=Eliminar JavaDocs del ScriptingFramework JavaDoc
75

  
76
projects_modified_title=Proyectos sin guardar
77
projects_modified=Algunos proyectos han sido modificados.\u00bfSalvar cambios?
78
project_modified=ha sido modificado.\u00bfSalvar cambios?
79

  
80
Delete_all_title=Borrar el documento
81
Delete_all_message=Esta acci\u00f3n elimina el documento o el directorio con todo su contenido. \u00bf Desea continuar ?
82

  
83
About_us_title=Informaci\u00f3n de todos los contribuidores al proyecto gvSIG
84

  
85
Success=Operaci\u00f3n realizada con \u00e9xito
86
Error=Error
87
Error_renaming=Inesperado error renombrando el fichero
88
Error_moving=Inesperado error moviendo el fichero
89
Error_help=Selecciona una ayuda
90
Rename_succesfully=Renombrado del fichero realizado con \u00e9xito
91
Select_first=Debe seleccionar un fichero primero
92
help_key=No hay ayuda para el texto
93

  
94

  
95
script_filesystem=script en el \u00e1rbol de directorio
96
Move=Mover
97
move_desc=Cambia la ubicaci\u00f3n del fichero seleccionado
98
Rename=Renombrar
99
rename_desc=Cambia el nombre y otras propiedades del fichero seleccionado
100
Moving_succesfully=Reubicaci\u00f3n del fichero realizado con \u00e9xito
101

  
102
Dialog=Di\u00e1logo
103
Code=C\u00f3digo
104
Properties=Propiedades
105

  
106
current_name=Nombre actual
107
new_name=Nuevo name
108
rename_name_title=Cambiar el nombre del fichero
109
more_properties=M\u00e1s propiedades
110

  
111
Javadoc_remove=Selecciona el JavaDoc a eliminar
112
no_Javadoc_remove=No hay JavaDoc para eliminar
113

  
114
Name=Nombre
115
Version=Versi\u00f3n
116
Created_by=Creado por
117
Description=Descripci\u00f3n
118
Type=Tipo
119
Language=Lenguaje
120
Author=Autor
121
Move_from=Mover desde
122
Move_to=Destino
123
Browse=Abrir
124
Import_from=Importar desde
125

  
126
Name_blank=El nombre no puede estar en blanco
127
Name_exists=Este nombre ya existe. Debe elegir otro
128
Import_success=Los JavaDocs se han importado satisfactoriamente
129
JavaDoc_Error=Selecciona JavaDoc a importar
130

  
131
go_to_line_Xhorizontal_ellipsisX=Ir a la l\u00ednea\u2026
132
find_Xhorizontal_ellipsisX=Buscar\u2026
133
replace_Xhorizontal_ellipsisX=Reemplazar\u2026
134
_Searching_autorun_scripts_Xhorizontal_ellipsisX=Buscando scripts de autoarranque...
135
_Starting_XnameX=Iniciando {0}...
136
_The_script_XscriptnameX_is_modified=El script "{0}" ha sido modificado.
137
_Save_changes_XquestionX=\u00bf Guardar cambios ?
138
_Do_you_want_to_save_changes_XquestionX=\u00bf Desea guardar los cambios ?
139

  
140
_notice=Aviso
141
_Initializing_the_scripting_plugin_Xhorizontal_ellipsisX=Inicializando el plugin de scripting...
142
_Waiting_to_terminate=Esperando que termine.
143

  
144
_Run_main_script=Ejecutar script principal
145
_Select_main_script=Seleccionar script pricipal
146
_Main_script_is_not_selected=No hay seleccionado un script como principal.
147
_The_selected_script_is_invalid=El script seleccionado no es valido.
148
_Do_you_want_to_select_one_and_execute_it=\u00bfDesea seleccionar uno y ejecutarlo ?
org.gvsig.scripting/tags/org.gvsig.scripting-2.3.87/org.gvsig.scripting.app/org.gvsig.scripting.app.mainplugin/src/main/resources-plugin/i18n/text_en.properties
1
_Scripting=Scripting
2
_Show_scripting_launcher=Show scripting launcher
3
_Show_scripting_composer=Show scripting composer
4
_Show_scripting_jython_console=Show Jython console
5

  
6
User=User
7
System=System
8

  
9
Accept=Accept
10
Cancel=Cancel
11
Apply=Apply
12

  
13
Retrieving_data=Retrieving data...
14

  
15
File=File
16
New=New
17
Close_document=Close document
18
Close_all_documents=Cloase all documents
19
Run=Run
20
Save=Save
21
Close=Close
22
Close_current_tab=Close current tab
23
Open_edition_mode=Open edition mode
24
Run_selected_script=Run selected script
25
Delete_selected_script=Delete selected script
26
Refresh_directories=Refresh directories
27
Move_files=Move files
28
Set_file_preferences=Set file preferences
29
_Running_autorun_script_from_XnameX=Running autorun script from {0}
30

  
31
Edit=Edit
32
Cut=Cut
33
Copy=Copy
34
Paste=Paste
35
Select_all=Select all
36

  
37
Tools=Tools
38
Launcher=Scripting Launcher
39
Scripting_Launcher=Scripting Launcher
40
Scripting_Composer=Scripting Composer
41
Jython_Console=Jython console
42
Import_JavaDoc=Import JavaDoc
43
JavaDoc=Java Help (JavaDoc)
44
Remove_JavaDoc=Remove JavaDoc
45
Help_contents=Help contents
46
About_scripts_editor=About scripts editor
47
Get_help=Help
48
Help=Help
49
_Package_script=Package script...
50
_Package_help=Package help...
51

  
52
Problems=Errors
53
Console=Console
54

  
55
Description=Description
56
Resource=Resource
57
Location=Location
58

  
59
no_line=no line
60
Line=Line
61

  
62
Welcome_message=Welcome to the scripting framework
63

  
64
Error_opening_in_edition_mode_title=Error opening file in edition mode
65
Error_opening_in_edition_mode=The file can't be opened in edition mode
66

  
67
New_Script=New element
68
New_Script_Description=Create a new script, dialog, project, directory
69

  
70
Deleting_JavaDocs_successfully_title=Operation successful
71
Deleting_JavaDocs_successfully=Deleting JavaDocs successfully
72

  
73
Import_JavaDoc_title=Import JavaDocs from filesystem to ScriptingFramework JavaDoc
74
Remove_JavaDoc_title=Remove JavaDocs from ScriptingFramework JavaDoc
75

  
76
projects_modified_title=Projects without saving
77
projects_modified=Some projects have been modified. Save changes?
78
project_modified=has been modified. Save changes?
79

  
80
Delete_all_title=Delete document
81
Delete_all_message=This action removes the document or directory with all its content. Do you wish to continue ?
82

  
83
About_us_title=Information about all the gvSIG's contributors
84

  
85
Success=Operation done successfully
86
Error=Error
87
Error_renaming=Unexpected error renaming the file
88
Error_moving=Unexpected error moving the file
89
Error_help=Select help
90
Rename_succesfully=Renaming successfully
91
Select_first=Select a file first
92
help_key=There isn't any help to this text
93

  
94

  
95
script_filesystem=script filesystem
96
Move=Move
97
move_desc=Change location of selected file
98
Rename=Rename
99
rename_desc=Change the name and more properties of the selected file
100
Moving_succesfully=File moved succesfully
101

  
102
Dialog=Dialog
103
Code=Code
104
Properties=Properties
105

  
106
current_name=Current name
107
new_name=New name
108
rename_name_title=Change filename
109
more_properties=more properties
110

  
111
Javadoc_remove=Choose JavaDoc to delete
112
no_Javadoc_remove=There's no JavaDoc to delete
113

  
114
Name=Name
115
Version=Version
116
Created_by=Create by
117
Description=Description
118
Type=Type
119
Language=Language
120
Author=Author
121
Move_from=Move from
122
Move_to=Move to
123
Browse=Browse
124
Import_from=Import from
125

  
126
Name_blank=Name can't be blank
127
Name_exists=This name already exists. Choose another one
128
Import_success=JavaDocs imported successfully
129
JavaDoc_Error=Select JavaDoc to import
130

  
131

  
132
go_to_line_Xhorizontal_ellipsisX=Go To Line\u2026
133
find_Xhorizontal_ellipsisX=Find\u2026
134
replace_Xhorizontal_ellipsisX=Replace\u2026
135

  
136
_Searching_autorun_scripts_Xhorizontal_ellipsisX=Searching autorun scripts...
137
_Starting_XnameX=Starting {0}...
138
_The_script_XscriptnameX_is_modified=The script "{0}" has been modified.
139
_Save_changes_XquestionX=Save changes ?
140
_Do_you_want_to_save_changes_XquestionX=Do you want to save changes ?
141

  
142
_notice=Notice
143
_Initializing_the_scripting_plugin_Xhorizontal_ellipsisX=Initializing the scripting plugin...
144
_Waiting_to_terminate=Waiting to terminate.
145

  
146
_Run_main_script=Run main script
147
_Select_main_script=Select main script
148
_Main_script_is_not_selected=Main script is not selected.
149
_The_selected_script_is_invalid=The selected script is not valid.
150
_Do_you_want_to_select_one_and_execute_it=Do you want to select one and execute it?
org.gvsig.scripting/tags/org.gvsig.scripting-2.3.87/org.gvsig.scripting.app/org.gvsig.scripting.app.mainplugin/src/main/resources-plugin/License_Chalkwork_icons.txt
1
----------------------------------------------
2
CHALKWORK BASIC
3
by Dave Shea
4
mezzoblue.com/icons/chalkwork/basic
5
----------------------------------------------
6
CHALKWORK COMMERCE
7
by Dave Shea
8
mezzoblue.com/icons/chalkwork/commerce
9
----------------------------------------------
10
CHALKWORK EDITING CONTROLS
11
by Dave Shea
12
mezzoblue.com/icons/chalkwork/editing-controls
13
----------------------------------------------
14
CHALKWORK INFORMATION MANAGEMENT
15
by Dave Shea
16
mezzoblue.com/icons/chalkwork/information-management
17
----------------------------------------------
18
CHALKWORK HTML (Free Version)
19
by Dave Shea
20
mezzoblue.com/icons/chalkwork/html
21
----------------------------------------------
22

  
23
Thanks for your interest in the Chalkwork Family. Please consider subscribing to the Chalkwork news feed, which will announce new releases in the family as well as inform existing users of updates if any occur.
24

  
25
	http://mezzoblue.com/icons/chalkwork/news.xml
26

  
27
- Dave Shea
28
  mezzoblue.com
29
  @mezzoblue on Twitter
30

  
31

  
32

  
33

  
34
LICENSE AGREEMENT
35
----------------------------------------------
36
By downloading this icon set, you agree to abide by the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License under which these icons are being made available for non-commercial use.
37

  
38
	Applicable Creative Commons License: http://creativecommons.org/licenses/by-nc-sa/3.0/
39
	Attribution and additional license information: http://www.mezzoblue.com/icons/license/#license-cc
40

  
41
By purchasing a Chalkwork Commercial License, you agree to abide by the Chalkwork Royalty-Free Stock Icon License Agreement under which these icons are being made available for commercial use.
42

  
43
	Chalkwork Commercial License: http://www.mezzoblue.com/icons/license/#license-cc
44

  
45
This notice must be included any time these icons are redistributed.
46

  
47

  
48

  
49

  
50
----------------------------------------------
51
ICON FOLDER INDEX
52
----------------------------------------------
53
The icon files are broken down by file format. Due to some formats resulting in higher quality results, those are considered the preferred files and are located in the folder titled 'High Quality'. This package should contain the following folders in this hierarchy:
54

  
55
High Quality
56
    ICNS (Mac)
57
    ICO (Windows)
58
    PNG
59
    TIF
60
Lower Quality
61
    BMP
62
    GIF
63

  
64
Within each of the second-level folders, you'll find 102 further folders, one for each icon and its variations. Depending on the file format, you may find multiple sizes within these folders along with any icon variations that may exist. Please note that ICO and ICNS files contain all applicable sizes within a single file, and that ICNS files do not support the 24x24 icon size.
65

  
66

  
67
----------------------------------------------
68
CHALKWORK INFORMATION MANAGEMENT ICON INDEX
69
* indicates that variations of this icon are provided within this set
70
---------------------------------------------------------------------
71

  
72
Ad
73
	- Ad (Dollars) *
74
	- Ad (Euros) *
75
	- Ad (Pounds) *
76
Address Book *
77
Announcement *
78
API
79
Archive *
80
Attachment *
81
Authenticate
82
Blog *
83
Bookmark *
84
Briefcase *
85
Category *
86
Chart (Area) *
87
Chart (Bar) *
88
Chart (Pie) *
89
Collapse
90
Colour Palette *
91
Continue
92
Control Panel
93
Conversation *
94
Create
95
Dashboard *
96
Database *
97
Dictionary *
98
Document (Area Chart) *
99
Document (Bar Chart) *
100
Document (Blank) *
101
Document (Form) *
102
Document (Photo) *
103
Document (Pie Chart) *
104
Document (Secure) *
105
Document (Shred)
106
Documents (x2) *
107
Documents (x3) *
108
Download
109
Draw
110
Entry *
111
Excerpt *
112
Expand
113
Export
114
Fax *
115
File *
116
	- File (Closed)
117
	- File (Open)
118
Filter *
119
Flag *
120
Flag (Black) *
121
Flag (Blue) *
122
Flag (Brown) *
123
Flag (Green) *
124
Flag (Light Blue) *
125
Flag (Orange) *
126
Flag (Pink) *
127
Flag (Purple) *
128
Flag (Red) *
129
Flag (White) *
130
Flag (Yellow) *
131
Formatting
132
Hierarchy *
133
Import
134
Inbox *
135
Index *
136
List *
137
Log *
138
Map *
139
Mobile Phone *
140
Moderate
141
Module *
142
News *
143
Notes *
144
Notification *
145
Office *
146
Package *
147
Password
148
Phone *
149
	- Phone (Batphone) *
150
	- Phone (Office) *
151
Plugin *
152
Preview
153
Publish
154
Read More
155
Rebuild
156
Relationship (Data) *
157
Relationship (People) *
158
Rotate Left
159
Rotate Right
160
Schedule *
161
	- Schedule (Noun)
162
	- Schedule (Verb)
163
Script *
164
Security *
165
Sign In
166
Sign Out
167
Sort Down
168
Sort Up
169
Spam *
170
Statistics *
171
Status *
172
	- Status (Green)
173
	- Status (Off)
174
	- Status (On)
175
	- Status (Red)
176
	- Status (Yellow)
177
Support *
178
Sync
179
Template *
180
Ticket *
181
Time Zone *
182
Tools *
183
Trackback
184
View (Columns)
185
View (Lists)
186
View (Thumbnails)
187
Weather *
188
Write
org.gvsig.scripting/tags/org.gvsig.scripting-2.3.87/org.gvsig.scripting.app/org.gvsig.scripting.app.mainplugin/src/main/resources-plugin/package.rst
1

  
2
This plugin provides support for scripting to gvSIG.
3
Among other things it contains:
4

  
5
- The gvSIG scripting engine
6
- The gvSIG script editor
7
- Script engines for:
8
   - Jython
9
   - Groovy
10
   - javascript
11
   - Renjin
12

  
13
- The script install module for the add-on manager.
14
- Utilities to generate packages of complements with our scripts.
15
- Python libraries as:
16
   - Six - Utilities for writing code that runs on Python 2 and 3
17
   - PyLint - Python source code analyzer
18
   - Pygments - syntax highlighting package
19
   - CSSUtils - CSS Cascading Style Sheets library
20
   - Docutils - Python Documentation Utilities
21
   - geopy - client for several popular geocoding web services
22
   - PyInliner - CSS-to-inline-styles conversion tool for HTML
23
   - Statistics - functions for calculating statistics of data
24
   - Cartodb - simple CartoDB client to perform requests against the CartoDB API
25

  
26
- Java libraries to use from scripting as:
27
   - Abeille forms deseigner
28
   - jOpenDocument
29
   - JNumeric
30
   - CSSBox
31

  
32
This plugin can be configured to be preinstalled automatically, allowing 
33
"Script" type plugins to be installed during the application installation process. 
34
To do this, the following entries must be added to the "packages.properties" 
35
of gvspks::
36

  
37
    installers=scripts
38
    installer.scripts.initializer=org.gvsig.scripting.app.extension.ScriptsInstallerInitializer
39
    installer.scripts.package.code=org.gvsig.scripting.app.mainplugin
40
    installer.scripts.factory.name=Script
41
    installer.scripts.libs=lib
42

  
43
If the "installers" entry already exists, add "scripts" to the end separating 
44
it with a space.
org.gvsig.scripting/tags/org.gvsig.scripting-2.3.87/org.gvsig.scripting.app/org.gvsig.scripting.app.mainplugin/src/main/resources-plugin/scripting/lib-2_0_0/commonsdialog.py
1
# -*- coding: utf-8 -*-
2
#
3
# File: commonsdialog.py
4
#
5
# Copyright (c) 2011 by Model Driven Development sl and Antonio Carrasco Valero
6
#
7
# GNU General Public License (GPL)
8
#
9
# This program is free software; you can redistribute it and/or
10
# modify it under the terms of the GNU General Public License
11
# as published by the Free Software Foundation; either version 2
12
# of the License, or (at your option) any later version.
13
#
14
# This program is distributed in the hope that it will be useful,
15
# but WITHOUT ANY WARRANTY; without even the implied warranty of
16
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17
# GNU General Public License for more details.
18
#
19
# You should have received a copy of the GNU General Public License
20
# along with this program; if not, write to the Free Software
21
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22
# 02110-1301, USA.
23
#
24
#
25

  
26
__author__ = """Antonio Carrasco Valero
27
Model Driven Development sl and Antonio Carrasco Valero
28
<carrasco@modeldd.org>
29
Victor Acevedo Royer <vacevedo@gvsig.com> <vacevedor@gmail.com>
30
"""
31
__docformat__ = 'plaintext'
32

  
33

  
34
from javax.swing import JFileChooser
35
from javax.swing.filechooser import FileNameExtensionFilter
36

  
37
#from org.gvsig.app import ApplicationLocator      
38

  
39
from org.gvsig.andami.ui.mdiFrame import DefaultThreadSafeDialogs
40

  
41
#====================================
42
# SWING
43

  
44
#
45
#messageType options
46
FORBIDEN = 0
47
IDEA= 1
48
WARNING= 2
49
QUESTION= 3
50

  
51
#
52
#Confirmdialog optionType Options
53
YES_NO = 0
54
YES_NO_CANCEL = 1
55
ACEPT_CANCEL = 2
56

  
57
#filechooser options
58
OPEN_FILE = 0
59
OPEN_DIRECTORY = 1
60
SAVE_FILE = 2
61

  
62
#filechooser selectionMode
63
FILES_ONLY = JFileChooser.FILES_ONLY
64
DIRECTORIES_ONLY = JFileChooser.DIRECTORIES_ONLY
65

  
66

  
67
def msgbox(message, title="", messageType=IDEA):
68
    """Shows a message dialog with ok button only
69
    :param message: text to present in the dialog
70
    :param title: title of the dialog
71
    :param messageType: type of icon to use.
72
    """
73
    DefaultThreadSafeDialogs().messageDialog(message, title, messageType)
74

  
75
   
76
def inputbox(message, title="", messageType=IDEA, initialValue=""):
77
    """
78
    Shows a input dialog.
79
    :param message: text to present in the dialog
80
    :param title: title of the dialog
81
    :messageType: type of icon to use
82
    :initialValue: Initial value of the inputbox  
83
    """
84
    return DefaultThreadSafeDialogs().inputDialog(message, title, 
85
        messageType, initialValue) 
86
  
87
  
88
def confirmDialog(message, title="", optionType=YES_NO, messageType=IDEA):
89
    """
90
    Create a message dialog with options button
91
    :param message: text to present in the dialog
92
    :param title: title of the dialog
93
    :optionType: bottons to show
94
    :param messageType: type of icon to use.    
95
    """
96
    #0: yes/no option
97
    #1: yes/no/cancelar
98
    #2: accept/cancel
99
    return DefaultThreadSafeDialogs().confirmDialog(message, title, 
100
        optionType, messageType) 
101

  
102
def filechooser(option, title="", initialPath=None, 
103
        multiselection=False, filter = None, fileHidingEnabled=True):
104
    """
105
    Allows configuration parameters to filechooser dialogs
106
    :int option: file chooser selection mode. Allowed values:
107
        OPEN_FILE, OPEN_DIRECTORY, SAVE_FILE
108
    :String title: Window title
109
    :String initialPath: Initial path to the directory to open in the dialog
110
    :boolean multiselection: Allow select more than one object.
111
    :String[] filter: list of acepted extension files ("jpg", "png", "gif")
112
    :boolean fileHidingEnabled: True if hidden files are not displayed
113
    """ 
114
    #
115
    #Values for open files dialog
116
    dialogType = JFileChooser.OPEN_DIALOG
117
    selectionMode = FILES_ONLY
118
    
119
    if option == SAVE_FILE:
120
        dialogType = JFileChooser.SAVE_DIALOG
121
    elif option == OPEN_DIRECTORY:
122
        selectionMode = DIRECTORIES_ONLY
123

  
124
    initialPath = getJavaFile(initialPath)
125
   
126
    if filter:
127
        filter = FileNameExtensionFilter("Files", filter)
128
       
129
    return DefaultThreadSafeDialogs().showChooserDialog(
130
            title,
131
            dialogType,
132
            selectionMode,
133
            multiselection,
134
            initialPath,
135
            filter,
136
            fileHidingEnabled)
137
   
138
def openFileDialog(title='', initialPath=None):
139
    """
140
    Shows a window dialog to choose one file. 
141
    :param title: Window title. Default ''
142
    :type title: string
143
    :param initialPath: Initial path to open in window dialog
144
    :type initialPath: string
145
    """
146
  
147
    return DefaultThreadSafeDialogs().showOpenFileDialog(
148
        title, 
149
        getJavaFile(initialPath))
150

  
151
def openFolderDialog(title='', initialPath=None):
152
    """
153
    Shows a window dialog to choose one folder. 
154
    :param title: Window title. Default ''
155
    :type title: string
156
    :param initialPath: Initial path to open in window dialog
157
    :type initialPath: string
158
    """    
159
  
160
    return DefaultThreadSafeDialogs().showOpenDirectoryDialog(
161
        title, 
162
        getJavaFile(initialPath))
163
  
164
def saveFileDialog(title='', initialPath=None):
165
    """
166
    Shows a window dialog to choose one file. 
167
    :param title: Window title. Default ''
168
    :type title: string
169
    :param initialPath: Initial path to open in window dialog
170
    :type initialPath: string
171
    """    
172
    
173
    return DefaultThreadSafeDialogs().showSaveFileDialog(
174
        title, 
175
        getJavaFile(initialPath)
176
    )
177
  
178
def getJavaFile(path):
179
    """Returns a java File using parameter path.
180
    If path doesn't exists looks for user home folder and if can not find it, 
181
    returns path will be gvSIG instance directory.
182
    """
183
    #
184
    #Needs because DefaultThreadSafeDialogs files methods use a java File 
185
    #instance as initialPath parameter
186
    #
187
    import os
188
    import java.io.File as JFile  
189
  
190
    if path:
191
        path = os.path.normpath(path)
192
        if os.path.exists(path):
193
            return JFile(path)
194
        
195
    if os.environ.has_key('HOME'):
196
        return JFile(os.environ.get('HOME', os.getcwd()))
197

  
198
    if os.path.exists(os.path.expanduser("~")):
199
        return JFile(os.path.expanduser("~"))
200
    
201
    return JFile(os.getcwd())
202
    
203
    
org.gvsig.scripting/tags/org.gvsig.scripting-2.3.87/org.gvsig.scripting.app/org.gvsig.scripting.app.mainplugin/src/main/resources-plugin/scripting/lib-2_0_0/console/runConsole.py
1
from console import main
2
main()
org.gvsig.scripting/tags/org.gvsig.scripting-2.3.87/org.gvsig.scripting.app/org.gvsig.scripting.app.mainplugin/src/main/resources-plugin/scripting/lib-2_0_0/console/introspect.py
1
"""Provides a variety of introspective-type support functions for
2
things like call tips and command auto completion.
3

  
4
NOTE: this file is a modification of Patrick O'Brien's version 1.62
5
"""
6

  
7
#from __future__ import nested_scopes
8

  
9
__author__ = "Patrick K. O'Brien <pobrien@orbtech.com>"
10
__cvsid__ = "$Id: introspect.py 5910 2006-06-20 10:03:31Z jmvivo $"
11
__revision__ = "$Revision: 5910 $"[11:-2]
12

  
13

  
14
import cStringIO
15
import inspect
16
import sys
17
import tokenize
18
import types
19

  
20
try:
21
    True
22
except NameError:
23
    True = 1==1
24
    False = 1==0
25

  
26
def getAutoCompleteList(command='', locals=None, includeMagic=1, 
27
                        includeSingle=1, includeDouble=1):
28
    """Return list of auto-completion options for command.
29
    
30
    The list of options will be based on the locals namespace."""
31
    attributes = []
32
    # Get the proper chunk of code from the command.
33
    root = getRoot(command, terminator='.')
34
    try:
35
        if locals is not None:
36
            object = eval(root, locals)
37
        else:
38
            object = eval(root)
39
    except:
40
        pass
41
    else:
42
        attributes = getAttributeNames(object, includeMagic, 
43
                                       includeSingle, includeDouble)
44
    return attributes
45
    
46
def getAttributeNames(object, includeMagic=1, includeSingle=1,
47
                      includeDouble=1):
48
    """Return list of unique attributes, including inherited, for object."""
49
    attributes = []
50
    dict = {}
51
    if not hasattrAlwaysReturnsTrue(object):
52
        # Add some attributes that don't always get picked up.  If
53
        # they don't apply, they'll get filtered out at the end.
54
        attributes += ['__bases__', '__class__', '__dict__', '__name__', 
55
                       'func_closure', 'func_code', 'func_defaults', 
56
                       'func_dict', 'func_doc', 'func_globals', 'func_name']
57
    if includeMagic:
58
        try: attributes += object._getAttributeNames()
59
        except: pass
60
    # Get all attribute names.
61
    attrdict = getAllAttributeNames(object)
62
    for attrlist in attrdict.values():
63
        attributes += attrlist
64
    # Remove duplicates from the attribute list.
65
    for item in attributes:
66
        dict[item] = None
67
    attributes = dict.keys()
68
    attributes.sort(lambda x, y: cmp(x.upper(), y.upper()))
69
    if not includeSingle:
70
        attributes = filter(lambda item: item[0]!='_' \
71
                            or item[1]=='_', attributes)
72
    if not includeDouble:
73
        attributes = filter(lambda item: item[:2]!='__', attributes)
74
    # Make sure we haven't picked up any bogus attributes somehow.
75
    attributes = [attribute for attribute in attributes \
76
                  if hasattr(object, attribute)]
77
    return attributes
78

  
79
def hasattrAlwaysReturnsTrue(object):
80
    return hasattr(object, 'bogu5_123_aTTri8ute')
81

  
82
def getAllAttributeNames(object):
83
    """Return dict of all attributes, including inherited, for an object.
84
    
85
    Recursively walk through a class and all base classes.
86
    """
87
    #print "getAllAttributeNames  1",repr(object), repr(str(object))
88
    attrdict = {}  # (object, technique, count): [list of attributes]
89
    # !!!
90
    # Do Not use hasattr() as a test anywhere in this function,
91
    # because it is unreliable with remote objects: xmlrpc, soap, etc.
92
    # They always return true for hasattr().
93
    # !!!
94
    #print "getAllAttributeNames  2"
95
    try:
96
        # Yes, this can fail if object is an instance of a class with
97
        # __str__ (or __repr__) having a bug or raising an
98
        # exception. :-(
99
        key = str(object)
100
    except:
101
        key = 'anonymous'
102
    # Wake up sleepy objects - a hack for ZODB objects in "ghost" state.
103
    #print "getAllAttributeNames  3"
104
    wakeupcall = dir(object)
105
    #print "getAllAttributeNames  4"
106
    del wakeupcall
107
    # Get attributes available through the normal convention.
108
    #print "getAllAttributeNames  5"
109
    attributes = dir(object)
110
    attrdict[(key, 'dir', len(attributes))] = attributes
111
    #print "getAllAttributeNames  6"
112
    # Get attributes from the object's dictionary, if it has one.
113
    try:
114
        attributes = object.__dict__.keys()
115
        attributes.sort()
116
    except:  # Must catch all because object might have __getattr__.
117
        pass
118
    else:
119
        attrdict[(key, '__dict__', len(attributes))] = attributes
120
    # For a class instance, get the attributes for the class.
121
    #print "getAllAttributeNames  7"
122
    try:
123
        klass = object.__class__
124
    except:  # Must catch all because object might have __getattr__.
125
        pass
126
    else:
127
        if klass is object or klass is type:
128
            # Break a circular reference. This happens with extension
129
            # classes.
130
            pass
131
        else:
132
            attrdict.update(getAllAttributeNames(klass))
133
    #print "getAllAttributeNames  8"
134
    # Also get attributes from any and all parent classes.
135
    try:
136
        bases = object.__bases__
137
    except:  # Must catch all because object might have __getattr__.
138
        pass
139
    else:
140
        if isinstance(bases, types.TupleType):
141
            for base in bases:
142
                if type(base) is types.TypeType:
143
                    # Break a circular reference. Happens in Python 2.2.
144
                    pass
145
                else:
146
                    attrdict.update(getAllAttributeNames(base))
147
    #print "getAllAttributeNames  attrdict=",repr(attrdict)
148
    return attrdict
149

  
150
def getCallTip(command='', locals=None):
151
    """For a command, return a tuple of object name, argspec, tip text.
152
    
153
    The call tip information will be based on the locals namespace."""
154
    calltip = ('', '', '')  # object name, argspec, tip text.
155
    # Get the proper chunk of code from the command.
156
    root = getRoot(command, terminator='(')
157
    try:
158
        if locals is not None:
159
            object = eval(root, locals)
160
        else:
161
            object = eval(root)
162
    except:
163
        return calltip
164
    name = ''
165
    object, dropSelf = getBaseObject(object)
166
    try:
167
        name = object.__name__
168
    except AttributeError:
169
        pass
170
    tip1 = ''
171
    argspec = ''
172
    if inspect.isbuiltin(object):
173
        # Builtin functions don't have an argspec that we can get.
174
        pass
175
    elif inspect.isfunction(object):
176
        # tip1 is a string like: "getCallTip(command='', locals=None)"
177
        argspec = apply(inspect.formatargspec, inspect.getargspec(object))
178
        if dropSelf:
179
            # The first parameter to a method is a reference to an
180
            # instance, usually coded as "self", and is usually passed
181
            # automatically by Python; therefore we want to drop it.
182
            temp = argspec.split(',')
183
            if len(temp) == 1:  # No other arguments.
184
                argspec = '()'
185
            else:  # Drop the first argument.
186
                argspec = '(' + ','.join(temp[1:]).lstrip()
187
        tip1 = name + argspec
188
    doc = ''
189
    if callable(object):
190
        doc = inspect.getdoc(object)
191
    if doc:
192
        # tip2 is the first separated line of the docstring, like:
193
        # "Return call tip text for a command."
194
        # tip3 is the rest of the docstring, like:
195
        # "The call tip information will be based on ... <snip>
196
        firstline = doc.split('\n')[0].lstrip()
197
        if tip1 == firstline:
198
            tip1 = ''
199
        else:
200
            tip1 += '\n\n'
201
        docpieces = doc.split('\n\n')
202
        tip2 = docpieces[0]
203
        tip3 = '\n\n'.join(docpieces[1:])
204
        tip = '%s%s\n\n%s' % (tip1, tip2, tip3)
205
    else:
206
        tip = tip1
207
    calltip = (name, argspec[1:-1], tip.strip())
208
    return calltip
209

  
210
def getRoot(command, terminator=None):
211
    """Return the rightmost root portion of an arbitrary Python command.
212
    
213
    Return only the root portion that can be eval()'d without side
214
    effects.  The command would normally terminate with a '(' or
215
    '.'. The terminator and anything after the terminator will be
216
    dropped."""
217
    command = command.split('\n')[-1]
218
    if command.startswith(sys.ps2):
219
        command = command[len(sys.ps2):]
220
    command = command.lstrip()
221
    command = rtrimTerminus(command, terminator)
222
    tokens = getTokens(command)
223
    if not tokens:
224
        return ''
225
    if tokens[-1][0] is tokenize.ENDMARKER:
226
        # Remove the end marker.
227
        del tokens[-1]
228
    if not tokens:
229
        return ''
230
    if terminator == '.' and \
231
           (tokens[-1][1] <> '.' or tokens[-1][0] is not tokenize.OP):
232
        # Trap decimals in numbers, versus the dot operator.
233
        return ''
234
    else:
235
        # Strip off the terminator.
236
        if terminator and command.endswith(terminator):
237
            size = 0 - len(terminator)
238
            command = command[:size]
239
    command = command.rstrip()
240
    tokens = getTokens(command)
241
    tokens.reverse()
242
    line = ''
243
    start = None
244
    prefix = ''
245
    laststring = '.'
246
    emptyTypes = ('[]', '()', '{}')
247
    for token in tokens:
248
        tokentype = token[0]
249
        tokenstring = token[1]
250
        line = token[4]
251
        if tokentype is tokenize.ENDMARKER:
252
            continue
253
        if tokentype in (tokenize.NAME, tokenize.STRING, tokenize.NUMBER) \
254
        and laststring != '.':
255
            # We've reached something that's not part of the root.
256
            if prefix and line[token[3][1]] != ' ':
257
                # If it doesn't have a space after it, remove the prefix.
258
                prefix = ''
259
            break
260
        if tokentype in (tokenize.NAME, tokenize.STRING, tokenize.NUMBER) \
261
        or (tokentype is tokenize.OP and tokenstring == '.'):
262
            if prefix:
263
                # The prefix isn't valid because it comes after a dot.
264
                prefix = ''
265
                break
266
            else:
267
                # start represents the last known good point in the line.
268
                start = token[2][1]
269
        elif len(tokenstring) == 1 and tokenstring in ('[({])}'):
270
            # Remember, we're working backwords.
271
            # So prefix += tokenstring would be wrong.
272
            if prefix in emptyTypes and tokenstring in ('[({'):
273
                # We've already got an empty type identified so now we
274
                # are in a nested situation and we can break out with
275
                # what we've got.
276
                break
277
            else:
278
                prefix = tokenstring + prefix
279
        else:
280
            # We've reached something that's not part of the root.
281
            break
282
        laststring = tokenstring
283
    if start is None:
284
        start = len(line)
285
    root = line[start:]
286
    if prefix in emptyTypes:
287
        # Empty types are safe to be eval()'d and introspected.
288
        root = prefix + root
289
    return root    
290

  
291
class _EaterTokens:
292
  def __init__(self,tokens):
293
    self.tokens = tokens
294

  
295
  def __call__(self,*args):
296
    self.tokens.append(args)
297

  
298
def getTokens(command):
299
    """Return list of token tuples for command."""
300
    command = str(command)  # In case the command is unicode, which fails.
301
    f = cStringIO.StringIO(command)
302
    # tokens is a list of token tuples, each looking like: 
303
    # (type, string, (srow, scol), (erow, ecol), line)
304
    tokens = []
305
    # Can't use list comprehension:
306
    #   tokens = [token for token in tokenize.generate_tokens(f.readline)]
307
    # because of need to append as much as possible before TokenError.
308
    try:
309
##        This code wasn't backward compatible with Python 2.1.3.
310
##
311
##        for token in tokenize.generate_tokens(f.readline):
312
##            tokens.append(token)
313
        # This works with Python 2.1.3 (with nested_scopes).
314
##        def eater(*args):
315
##            tokens.append(args)
316
##        tokenize.tokenize_loop(f.readline, eater)
317
        eater = _EaterTokens(tokens) #Con una lambda no se lo come 
318
        tokenize.tokenize_loop(f.readline, eater)
319
    except tokenize.TokenError:
320
        # This is due to a premature EOF, which we expect since we are
321
        # feeding in fragments of Python code.
322
        pass
323
    return tokens    
324

  
325
def rtrimTerminus(command, terminator=None):
326
    """Return command minus anything that follows the final terminator."""
327
    if terminator:
328
        pieces = command.split(terminator)
329
        if len(pieces) > 1:
330
            command = terminator.join(pieces[:-1]) + terminator
331
    return command
332

  
333
def getBaseObject(object):
334
    """Return base object and dropSelf indicator for an object."""
335
    if inspect.isbuiltin(object):
336
        # Builtin functions don't have an argspec that we can get.
337
        dropSelf = 0
338
    elif inspect.ismethod(object):
339
        # Get the function from the object otherwise
340
        # inspect.getargspec() complains that the object isn't a
341
        # Python function.
342
        try:
343
            if object.im_self is None:
344
                # This is an unbound method so we do not drop self
345
                # from the argspec, since an instance must be passed
346
                # as the first arg.
347
                dropSelf = 0
348
            else:
349
                dropSelf = 1
350
            object = object.im_func
351
        except AttributeError:
352
            dropSelf = 0
353
    elif inspect.isclass(object):
354
        # Get the __init__ method function for the class.
355
        constructor = getConstructor(object)
356
        if constructor is not None:
357
            object = constructor
358
            dropSelf = 1
359
        else:
360
            dropSelf = 0
361
    elif callable(object):
362
        # Get the __call__ method instead.
363
        try:
364
            call_method = object.__call__.im_func
365
            if call_method.__name__ == '__call__':
366
                # unbound jython method end up here, example: string.index(
367
                dropSelf = 0
368
            else:
369
                object = call_method
370
                dropSelf = 1
371
        except AttributeError:
372
            # unbound python methods end up here
373
            dropSelf = 0
374
    else:
375
        dropSelf = 0
376
    return object, dropSelf
377

  
378
def getConstructor(object):
379
    """Return constructor for class object, or None if there isn't one."""
380
    try:
381
        return object.__init__.im_func
382
    except AttributeError:
383
        for base in object.__bases__:
384
            constructor = getConstructor(base)
385
            if constructor is not None:
386
                return constructor
387
    return None
org.gvsig.scripting/tags/org.gvsig.scripting-2.3.87/org.gvsig.scripting.app/org.gvsig.scripting.app.mainplugin/src/main/resources-plugin/scripting/lib-2_0_0/console/problems.txt
1
==========================
2
Known problems
3
==========================
4

  
5
You must use the keyboard not the mouse to select methods.  (Due to focus problems.)
6

  
7
python.security.respectJavaAccessibility must be set to true in Jython's registry
8

  
9
You can't insert '(' and ')' in the middle of a line
10

  
11
Method popup displays names multiple times for overloaded methods
12

  
13
Method popup gets abandoned with too many backspaces.  (Use <ESC> to make it go away)
14

  
15
Builtin types don't work, like they do in PyCrust.  This is because they have a null __doc__ string in Jython.
16

  
17
Static methods and properties don't seem to work correctly.
18

  
19
<CTRL>+D (or <CRTL>+Z) to exit is not implemented
20

  
21
History doesn't quite work correctly
22

  
23
$Id: problems.txt 5782 2006-06-12 07:56:49Z jmvivo $
org.gvsig.scripting/tags/org.gvsig.scripting-2.3.87/org.gvsig.scripting.app/org.gvsig.scripting.app.mainplugin/src/main/resources-plugin/scripting/lib-2_0_0/console/testcase.py
1
import unittest
2
import introspect
3

  
4
class IntrospectTestCase(unittest.TestCase):
5

  
6
    def testUnboundMethod(self):
7
        import string
8
        method = 'string.index('
9
        (name, argspec, tip) = introspect.getCallTip(method, locals())
10

  
11
        self.assertEquals('index', name)
12
        self.assertEquals('s, *args', argspec)
13
        self.assertEquals('index(s, *args)\n\nindex(s, sub [,start [,end]]) -> int\n\nLike find but raises ValueError when the substring is not found.', tip)
14

  
15
    def testBuiltinFunction(self):
16
        method = 'len('
17
        print introspect.getCallTip(method, locals())
18
        
19
        (name, argspec, tip) = introspect.getCallTip(method, locals())
20
        
21
        self.assertEquals('len', name)
22
        # next 2 assertions fail in Jython!
23
        self.assertEquals('len(object) -> integer', argspec)
24
        self.assertEquals('len(object) -> integer\n\nReturn the number of items of a sequence or mapping', tip)
25

  
26

  
27
if __name__ == '__main__':
28
    unittest.main()
org.gvsig.scripting/tags/org.gvsig.scripting-2.3.87/org.gvsig.scripting.app/org.gvsig.scripting.app.mainplugin/src/main/resources-plugin/scripting/lib-2_0_0/console/tip.py
1
from java.awt import Color, Dimension
2
from javax.swing import JWindow, JTextArea, JScrollPane
3

  
4
__author__ = "Don Coleman <dcoleman@chariotsolutions.com>"
5
__cvsid__ = "$Id: tip.py 5782 2006-06-12 07:56:49Z jmvivo $"
6

  
7
class Tip(JWindow):
8
    """
9
    Window which provides the user with information about the method
10
    For Python, this shows arguments, and the documention
11
    For Java, this shows the signature(s) and return type
12
    """
13
    # TODO handle java methods with many overload more gracefully
14
    MAX_HEIGHT = 300
15
    MAX_WIDTH = 400
16
    
17
    def __init__(self, frame):
18
        JWindow.__init__(self, frame)
19
        #self.size = (300,150)
20
        self.textarea = JTextArea()
21
        # TODO put this color with all the other colors
22
        self.textarea.setBackground(Color(225,255,255))
23
        self.textarea.setEditable(0)
24
        self.jscrollpane = JScrollPane(self.textarea)
25
        self.getContentPane().add(self.jscrollpane)
26

  
27
    def setText(self, tip):
28
        self.textarea.setText(tip)
29
        self.textarea.setCaretPosition(0)
30
        #print >> sys.stderr, self.textarea.getPreferredScrollableViewportSize()
31
        self.setSize(self.getPreferredSize())
32

  
33
    def getPreferredSize(self):
34
        # need to add a magic amount to the size to avoid scrollbars
35
        # I'm sure there's a better way to do this
36
        MAGIC = 20
37
        size = self.textarea.getPreferredScrollableViewportSize()
38
        height = size.height + MAGIC
39
        width = size.width + MAGIC
40
        if height > Tip.MAX_HEIGHT:
41
            height = Tip.MAX_HEIGHT
42
        if width > Tip.MAX_WIDTH:
43
            width = Tip.MAX_WIDTH
44
        return Dimension(width, height)
45
        
org.gvsig.scripting/tags/org.gvsig.scripting-2.3.87/org.gvsig.scripting.app/org.gvsig.scripting.app.mainplugin/src/main/resources-plugin/scripting/lib-2_0_0/console/dis.py
1
"""Disassembler of Python byte code into mnemonics."""
2

  
3
import sys
4
import types
5

  
6
__all__ = ["dis","disassemble","distb","disco","opname","cmp_op",
7
           "hasconst","hasname","hasjrel","hasjabs","haslocal",
8
           "hascompare", "hasfree"]
9

  
10
def dis(x=None):
11
    """Disassemble classes, methods, functions, or code.
12

  
13
    With no argument, disassemble the last traceback.
14

  
15
    """
16
    if not x:
17
        distb()
18
        return
19
    if type(x) is types.InstanceType:
20
        x = x.__class__
21
    if hasattr(x, 'im_func'):
22
        x = x.im_func
23
    if hasattr(x, 'func_code'):
24
        x = x.func_code
25
    if hasattr(x, '__dict__'):
26
        items = x.__dict__.items()
27
        items.sort()
28
        for name, x1 in items:
29
            if type(x1) in (types.MethodType,
30
                            types.FunctionType,
31
                            types.CodeType):
32
                print "Disassembly of %s:" % name
33
                try:
34
                    dis(x1)
35
                except TypeError, msg:
36
                    print "Sorry:", msg
37
                print
38
    elif hasattr(x, 'co_code'):
39
        disassemble(x)
40
    else:
41
        raise TypeError, \
42
              "don't know how to disassemble %s objects" % \
43
              type(x).__name__
44

  
45
def distb(tb=None):
46
    """Disassemble a traceback (default: last traceback)."""
47
    if not tb:
48
        try:
49
            tb = sys.last_traceback
50
        except AttributeError:
51
            raise RuntimeError, "no last traceback to disassemble"
52
        while tb.tb_next: tb = tb.tb_next
53
    disassemble(tb.tb_frame.f_code, tb.tb_lasti)
54

  
55
def disassemble(co, lasti=-1):
56
    """Disassemble a code object."""
57
    code = co.co_code
58
    labels = findlabels(code)
59
    n = len(code)
60
    i = 0
61
    extended_arg = 0
62
    free = None
63
    while i < n:
64
        c = code[i]
65
        op = ord(c)
66
        if op == SET_LINENO and i > 0: print # Extra blank line
67
        if i == lasti: print '-->',
68
        else: print '   ',
69
        if i in labels: print '>>',
70
        else: print '  ',
71
        print `i`.rjust(4),
72
        print opname[op].ljust(20),
73
        i = i+1
74
        if op >= HAVE_ARGUMENT:
75
            oparg = ord(code[i]) + ord(code[i+1])*256 + extended_arg
76
            extended_arg = 0
77
            i = i+2
78
            if op == EXTENDED_ARG:
79
                extended_arg = oparg*65536L
80
            print `oparg`.rjust(5),
81
            if op in hasconst:
82
                print '(' + `co.co_consts[oparg]` + ')',
83
            elif op in hasname:
84
                print '(' + co.co_names[oparg] + ')',
85
            elif op in hasjrel:
86
                print '(to ' + `i + oparg` + ')',
87
            elif op in haslocal:
88
                print '(' + co.co_varnames[oparg] + ')',
89
            elif op in hascompare:
90
                print '(' + cmp_op[oparg] + ')',
91
            elif op in hasfree:
92
                if free is None:
93
                    free = co.co_cellvars + co.co_freevars
94
                print '(' + free[oparg] + ')',
95
        print
96

  
97
disco = disassemble                     # XXX For backwards compatibility
98

  
99
def findlabels(code):
100
    """Detect all offsets in a byte code which are jump targets.
101

  
102
    Return the list of offsets.
103

  
104
    """
105
    labels = []
106
    n = len(code)
107
    i = 0
108
    while i < n:
109
        c = code[i]
110
        op = ord(c)
111
        i = i+1
112
        if op >= HAVE_ARGUMENT:
113
            oparg = ord(code[i]) + ord(code[i+1])*256
114
            i = i+2
115
            label = -1
116
            if op in hasjrel:
117
                label = i+oparg
118
            elif op in hasjabs:
119
                label = oparg
120
            if label >= 0:
121
                if label not in labels:
122
                    labels.append(label)
123
    return labels
124

  
125
cmp_op = ('<', '<=', '==', '!=', '>', '>=', 'in', 'not in', 'is',
126
        'is not', 'exception match', 'BAD')
127

  
128
hasconst = []
129
hasname = []
130
hasjrel = []
131
hasjabs = []
132
haslocal = []
133
hascompare = []
134
hasfree = []
135

  
136
opname = [''] * 256
137
for op in range(256): opname[op] = '<' + `op` + '>'
138

  
139
def def_op(name, op):
140
    opname[op] = name
141

  
142
def name_op(name, op):
143
    opname[op] = name
144
    hasname.append(op)
145

  
146
def jrel_op(name, op):
147
    opname[op] = name
148
    hasjrel.append(op)
149

  
150
def jabs_op(name, op):
151
    opname[op] = name
152
    hasjabs.append(op)
153

  
154
# Instruction opcodes for compiled code
155

  
156
def_op('STOP_CODE', 0)
157
def_op('POP_TOP', 1)
158
def_op('ROT_TWO', 2)
159
def_op('ROT_THREE', 3)
160
def_op('DUP_TOP', 4)
161
def_op('ROT_FOUR', 5)
162

  
163
def_op('UNARY_POSITIVE', 10)
164
def_op('UNARY_NEGATIVE', 11)
165
def_op('UNARY_NOT', 12)
166
def_op('UNARY_CONVERT', 13)
167

  
168
def_op('UNARY_INVERT', 15)
169

  
170
def_op('BINARY_POWER', 19)
171

  
172
def_op('BINARY_MULTIPLY', 20)
173
def_op('BINARY_DIVIDE', 21)
174
def_op('BINARY_MODULO', 22)
175
def_op('BINARY_ADD', 23)
176
def_op('BINARY_SUBTRACT', 24)
177
def_op('BINARY_SUBSCR', 25)
178
def_op('BINARY_FLOOR_DIVIDE', 26)
179
def_op('BINARY_TRUE_DIVIDE', 27)
180
def_op('INPLACE_FLOOR_DIVIDE', 28)
181
def_op('INPLACE_TRUE_DIVIDE', 29)
182

  
183
def_op('SLICE+0', 30)
184
def_op('SLICE+1', 31)
185
def_op('SLICE+2', 32)
186
def_op('SLICE+3', 33)
187

  
188
def_op('STORE_SLICE+0', 40)
189
def_op('STORE_SLICE+1', 41)
190
def_op('STORE_SLICE+2', 42)
191
def_op('STORE_SLICE+3', 43)
192

  
193
def_op('DELETE_SLICE+0', 50)
194
def_op('DELETE_SLICE+1', 51)
195
def_op('DELETE_SLICE+2', 52)
196
def_op('DELETE_SLICE+3', 53)
197

  
198
def_op('INPLACE_ADD', 55)
199
def_op('INPLACE_SUBTRACT', 56)
200
def_op('INPLACE_MULTIPLY', 57)
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff