API Reference - Application

Index of All Documentation » Wing Pro Reference Manual » Scripting and Extending Wing » API Reference »


Class CAPIApplication

API for the top-level of IDE functionality. This should be accessed through wingapi.gApplication.

Signals

A callback can be connected to the following signals using Connect(signal, cb):

destroy: The application is closing. Calls cb(app:CAPIApplication)

editor-open: An editor was opened. Calls cb(editor: CAPIEditor)

document-open: A document was opened. Note that several editors may share a document. Calls cb(doc:CAPIDocument)

project-open: A project was opened. Calls cb(filename:str)

project-close: A project was closed. Calls cb(filename:str)

active-editor-changed: Active editor has changed. Calls cb(editor:CAPIEditor)

active-window-changed: Active window has changed. The window is None if Wing is no longer at front. Calls cb(window_name:str)

perspective-changed: Current perspective has been changed. Calls cb(perspective_name:str)

Use Disconnect(signal_id) to preemptively disconnect a signal handler, where signal_id is the signal ID previously returned from Connect.

Top-level Settings and Environment

CAPIApplication.GetProductInfo()

Returns the current Wing version, update, product code, product name, and release date.

If the full version of Wing is 1.2.3.4 then version will be '1.2.3' and update will be '4'. If the current version is a pre-release then update may be prepended with one letter as follows:

'a': alpha release
'b': beta release
'c': release candidate

The valid product codes and names are:

0x00000001 'Personal'
0x00000002 'Professional'
0x00000008 '101'

Example return values:

('5.1.3', '2', 0x00000002, 'Professional', 'Mar 17, 2014')
('7.0.0', 'a1', 0x00000001, 'Personal', 'Aug 1, 2018')

CAPIApplication.GetWingHome()

Returns the Install Directory from which Wing is running.

CAPIApplication.GetUserSettingsDir()

Returns the active User Settings directory.

CAPIApplication.GetStartingDirectory(force_local=True)

Get the most logical starting directory to use when browsing for files or directories. This varies based on the focus and selection on the user interface. When force_local is True, only a local starting directory is returned. Otherwise a starting directory on a remote host may be returned as a URL in the form ssh://hostname/path/to/dirname, where hostname is the Identifier of a Remote Host. Use IsUrl to distinguish urls from directory names.

CAPIApplication.FindPython()

Find the default Python interpreter that Wing will use if none is specified with Python Executable in Project Properties. Wing tries looking for it as follows:

On Linux:

  • Try python in the current environment
  • Search PATH for python* (such as python2.7 or python3.7)
  • As a last resort, use the last known working Python if there was one

On OS X:

  • Use /Library/Frameworks/Python.framework/Versions/Current/bin/python if is exists and is valid
  • Search as for Linux

On Windows:

  • Try python in the current environment
  • Look for the latest version in the registry using the keys HKEY_CURRENT_USER\SOFTWARE\PYTHON\PYTHONCORE\#.#\INSTALLPATH and HKEY_LOCAL_MACHINE\SOFTWARE\PYTHON\PYTHONCORE\#.#\INSTALLPATH
  • As a last resort, use the last known working Python if there was one

Return Value: the full path to the interpreter. The value is validated in that the interpreter is actually executed and sys.executable is returned.

NOTE: This call will ignore versions of Python that Wing does not support.

Command Execution

These methods are used to execute IDE commands that are documented in the Command Reference.

CAPIApplication.CommandAvailable(cmd, **args)

Check whether a command is available for execution.

The cmd can be the name of a command in Wing's Command Reference, or the name of a command added by an extension script.

Any arguments are passed as keyword arguments using the documented argument names for the command being invoked. In most cases the value of optional arguments won't affect command availability, so they may usually be omitted.

CAPIApplication.ExecuteCommand(cmd, **args)

Execute a command with the given keyword arguments.

The cmd can be the name of a command in Wing's Command Reference, or the name of a command added by an extension script.

Any arguments are passed as keyword arguments using the documented argument names for the command being invoked.

To execute an external command or command line, use ExecuteCommandLine, AsyncExecuteCommandLine*, or ExecuteOSCommand instead.

Asynchronous Timeouts

CAPIApplication.InstallTimeout(timeout, fct)

Install a function to be called as a timeout after a given number of milliseconds. The function is called repeatedly at the given interval until its return value evaluates to False or None.

Returns a timeout_id that may be sent to RemoveTimeout to remove the timeout prematurely.

Note that the timeout will be removed if its script module is reloaded, in order to avoid calling old byte code. For this reason, script modules must reinstall timeouts during initialization.

CAPIApplication.RemoveTimeout(timeout_id)

Remove a timeout previously installed with InstallTimeout.

Access to Key Objects

CAPIApplication.GetActiveWindow()

Get the internal name of the currently active window. This is None if no window in Wing has the focus.

CAPIApplication.GetActiveEditor()

Get the currently active CAPIEditor or None if no editor has the focus.

CAPIApplication.GetActiveDocument()

Get the CAPIDocument for the currently active editor, or None if no editor has the focus.

CAPIApplication.GetCurrentFiles()

Get a list of the the currently selected files. The list returned depends on the current focus and selection in the user interface. Files may be selected in the current editor, or in the Project, Source Browser, and other tools.

Returns a list of full path filenames for the file or files, or None if none are selected.

For untitled or scratch buffers, the file name is prefixed with unknown:. For remote files, the file name will be a URL. Use IsUrl to distinguish between file names and URLs.

CAPIApplication.GetCurrentSourceScopes()

Get the current source scopes, including file name, line number, and Python scope name. The value returned depends on the current focus and selection in the user interface. Source scopes may be selected in the current editor, or in the Project, Source Browser, or other tools.

Returns None if nothing is selected or a list of scopes, each of which is a list that contains a filename, a line number (0=first), and zero or more source symbol names indicating the nested scope that the user has selected.

For example, if Class1.Method1 on line 120 of the file /x/y/z.py is selected, the return value would be:

[["/x/y/z.py", 120, "Class1", "Method1"],]

Line 1 is used without any source symbols to indicate the whole file is selected. The following would be returned if multiple items in the Project or Open Files tools are selected:

[["/x/y/a.py", 1], ["/a/b/z.py", 1]]

For untitled or scratch buffers, the file name is prefixed with unknown:. For remote files, the file name will be a URL. Use IsUrl to distinguish between file names and URLs.

CAPIApplication.GetAnalysis(filename)

Get a CAPIStaticAnalysis object for the given Python file.

CAPIApplication.GetAllFiles(visible_only=False, sticky_only=False)

Get a list of the full path names of all currently open files, whether or not a CAPIDocument object or editor has been created for them.

Optionally filter the result to omit non-visible files or those that are opened in non-sticky transient mode. See Transient Non-Sticky Editors for details.

For untitled or scratch buffers, the file name is prefixed with unknown:. For remote files, the file name will be a URL. Use IsUrl to distinguish between file names and URLs.

CAPIApplication.GetOpenDocuments()

Get all currently open CAPIDocument objects. This includes only those documents that have already been shown in an editor, since documents are not created until they need to be shown.

Note that this may also include documents active for searching or source analysis, for which no editor is open.

CAPIApplication.GetProject()

Get the currently open CAPIProject. Returns None if no project is open.

CAPIApplication.NewProject(completed_cb, failure_cb=None)

Create a new project. complete_cb is called with no arguments when the new project has been created and opened and failure_cb is called with no arguments if the user cancels closing the current project.

CAPIApplication.GetDebugger()

Get the CAPIDebugger singleton, for access to debugger functionality.

CAPIApplication.ShowTool(name, flash=True, grab_focus=True)

Show the given tool in the user interface. The most recently used instance of the tools is shown, or a new instance is created at its default location.

The name can be one of:

'project', 'browser', 'batch-search', 'interactive-search', source-assistant', 'debug-data', 'debug-stack', 'debug-io', debug-exceptions', 'debug-breakpoints', 'debug-console', 'debug-watch', debug-modules', 'python-shell', 'about', 'messages', 'help', 'indent', bookmarks', 'testing', 'open-files', os-command', 'snippets', diff', 'uses', 'refactoring', 'code-warnings'

The tool title is flashed if flash is True and focus is moved to the tool if grab_focus is True.

CAPIApplication.OpenURL(url)

Open the given URL with an external viewer.

Manage Windows

CAPIApplication.CreateWindow(name)

Create a new window with given internal name. The window is initially blank. Use OpenEditor() with the given name to fill it.

CAPIApplication.CloseWindow(name, allow_cancel=True)

Close the window with given internal name, and all the editors in it. When allow_cancel is False, the window is closed without prompting to save any changes made there.

Manage Editors

CAPIApplication.OpenEditor(filename, window_name=None, raise_window=False, sticky=True)

Open the given file into an editor.

If the window_name is given, the editor opens into the window with that internal name. Otherwise the most recently visited window is used. If window_name is not the name of an existing window, a new window is created with that name.

The window is not brought to the front unless raise_window is True.

Set sticky to False to cause Wing to auto-close the editor when hidden and more than the configured number of non-sticky editors is open. See Transient Non-Sticky Editors for details.

Returns the CAPIEditor or None if opening the file failed.

Note that the file may open under a different name if symbolic links exist.

CAPIApplication.ScratchEditor(title='Scratch', mime_type='text/plain', raise_window=False, raise_view=True, sticky=True, window_name=None)

Create a scratch editor with the given title and mime type. The document can be edited but will never be marked as changed or requiring a save to disk. However, it can be saved with Save As if desired.

If title contains %d, a sequence number will be inserted automatically.

mime_type sets the file type to use. Use text/x-python for Python.

The window is raised only if raise_window is True.

The view is brought to front within the window only if raise_view is True.

Set sticky to False to cause Wing to auto-close the editor when hidden and more than the configured number of non-sticky editors is open. See Transient Non-Sticky Editors for details.

If the window_name is given, the editor opens into the window with that internal name. Otherwise the most recently visited window is used. If window_name is not the name of an existing window, a new window is created with that name.

Returns the CAPIEditor or None if the scratch buffer failed to create.

CAPIApplication.GetMimeType(filename)

Get the mime type Wing is using for the given filename, based on the file name, contents, and Files > File Types > Extra File Types preference.

Clipboard

CAPIApplication.SetClipboard(txt)

Store the given text to the clipboard. The text should be a utf-8 string or unicode object.

CAPIApplication.GetClipboard()

Get the text currently on the clipboard, as a unicode string.

Application State

CAPIApplication.GetVisualState(errs=[], style='all')

Get the application's visual state.

The style of the state may be one of:

'all' to capture all of the application visual state

'tools-and-editors' to capture which tools are visible, the overall layout of the windows, and which editors are open (but not details like scroll positions, selection, or current search string)

'tools-only' to capture only which tools are visible and the overall layout of the windows (but not which editors are open).

Returns an opaque dictionary with the state, for later use with SetVisualState.

Any errors encountered are added to errs as strings.

CAPIApplication.SetVisualState(state, errs=[])

Restore saved application state, as previously obtained from GetVisualState. Any errors encountered are added to errs as strings.

Preferences

CAPIApplication.GetPreference(pref)

Get the value of the given preference.

The pref argument should be the fully qualified name of the preference, as given in the Preferences Reference.

CAPIApplication.SetPreference(pref, value)

Set value for the given preference.

The pref argument should be the fully qualified name of the preference, as given in the Preferences Reference.

The value must conform to the documentation for the preference.

CAPIApplication.ConnectToPreference(pref, cb)

Connect to the given preference so that the given callback is called whenever the value of the preference changes.

The pref argument should be the fully qualified name of the preference, as given in the Preferences Reference.

cb is called with no arguments. It may obtain the new value of the preference with GetPreference.

The callback will be uninstalled automatically if the caller's script is reloaded.

Returns a signal id that can be used with later DisconnectFromPreference.

CAPIApplication.DisconnectFromPreference(pref, id)

Disconnect a preference value callback.

The pref argument should be the fully qualified name of the preference, as given in the Preferences Reference.

id is the signal id that was returned from ConnectToPreference.

CAPIApplication.ShowPreference(prefname)

Show the given preference by name in the preference manager dialog.

prefname should be the fully qualified name of the preference, as given in the Preferences Reference.

Messages and Status

CAPIApplication.ShowMessageDialog(title, text, checks=[], buttons=[('OK', None)], modal=True, sheet=False)

Display a message dialog to the user with the given title and text.

If checks is non-empty it contains a list of (label, default, callback) tuples for extra check boxes to add below the message and above the buttons. The callback is called with the label and check state immediately when the checkbox is used.

Set buttons to a list of (label, action) pairs to override the default of a single OK button. The button action can be None to simply close the dialog or it can be a callable taking no arguments that returns True to prevent closing of the dialog or False to allow it to close when the button is pressed.

The dialog is modal unless modal is set to False.

sheet is deprecated in Wing 7.0 and should no longer be used.

CAPIApplication.SetStatusMessage(text, timeout=5)

Display a transient status message in the status area at the bottom of the IDE window. The message persists for the given timeout (in seconds) or until another status message is shown.

CAPIApplication.ClearStatusMessage()

Clear the status message area at the bottom of the IDE window to blank.

Sub-Process Control

CAPIApplication.ExecuteCommandLine(cmd, dirname, input, timeout, env=None, bufsize=100000, return_stderr=False)

Run a command line synchronously until it completes.

cmd can either be a command line (as a string) or a list containing the executable and any arguments.

The command is run in the directory specified by dirname.

input is any text to send to the sub-process, or None to send nothing.

timeout sets the maximum number of seconds to wait for the command to complete.

Unless env is given, the command is run in the environment configured in the current project. Otherwise, env should be in the same form as os.environ.

The bufsize is used for the I/O buffer to the sub-process, as follows: If < 0, system default is used; if 0, I/O is unbuffered; if 1, line buffering is used if the OS supports it; if >1, the buffer is set to that number of bytes.

When return_stderr is True, both stderr and stdout are returned. Otherwise only stdout is returned.

Returns (err, output_txt) where err is one of:

0 -- Success
1 -- Command could not be launched
2 -- Command timed out

And output_txt is either a string containing stdout or, a tuple (stdout, stderr) (when return_stderr was set to True).

Use AsyncExecuteCommandLine to avoid locking up Wing while the command runs, or to access process exit status.

CAPIApplication.AsyncExecuteCommandLine(cmd, dirname, *args)

Run the given command asynchronously in the given directory.

cmd contains the executable to run, either the full path or the name on the PATH.

Additional command line arguments are passed as extra parameters via args.

Returns a handler instance that is used asynchronously to monitor the progress of the command and to obtain its output and exit status. This can be placed into a timeout function installed with InstallTimeout. For example:

handler = wingapi.AsyncExecuteCommandLine('ls', '/path/to/dir', '-al')
def watch():
  if handler.Iterate():
    stdout, stderr, err, exit_status = handler.Terminate()
    print "Done"
    print stdout
    return False
  else:
    print "Start time (relative to time.time()):", handler.time
    print "Iteration #", handler.count
    print "Output so far: %i characters", len(handler.stdout)
    return True
wingapi.InstallTimeout(500, watch)

Be sure that the timeout function returns True until the handler has completed, so that the timeout is called again and Terminate is eventually called.

The return values from Terminate are as follows:

stdout      -- The text received from child process stdout
stderr      -- The text received from child process stderr
err         -- Error code if execution failed, or ``None`` on success
exit_status -- Exit status of the child process, or ``None`` if it was
               never launched or could not be determined

The environment specified in the project is used for the sub-process. Use AsyncExecuteCommandLineE to specify a different environment.

To send input to the sub-process, use handler.pipes.tochild.write() optionally followed by handler.pipes.tochild.flush(). When I/O to the child is complete, call handler.pipes.tochild.close(). Some processes wait for the pipe to be closed before continuing.

CAPIApplication.AsyncExecuteCommandLineE(cmd, dirname, env, *args)

Same as AsyncExecuteCommandLine but accepts also the environment to send into the debug process.

CAPIApplication.AsyncExecuteCommandLineEB(cmd, dirname, env, bufsize, *args)

Same as AsyncExecuteCommandLineE but accepts also the I/O buffer size: if < 0, system default is used; if 0, I/O is unbuffered; if 1, line buffering is used if the OS supports it; if >1, the buffer is set to that number of bytes. To pass the project-defined environment to this call, use CAPIProject.GetEnvironment.

Sub-Process Control with OS Commands

CAPIApplication.AddOSCommand(cmd, dirname, env, flags, *args)

Add the given command line to the OS Commands tool. The cmd can be the whole command line as a list, or just the executable if its arguments are passed through args.

dirname can be None to indicate using the project-defined default starting directory.

env can be None to use the project defaults, or a dictionary to add values to the project-defined environment.

flags is a dictionary containing zero or more of the following:

title: The display title for the command Default: same as cmd argument.

hostname: The name of the configured remote host to run on, or '' to indicate local host. Default: None which indicates that project settings will be used.

io-encoding: Encoding name for I/O (such as utf-8). Default: None

key-binding: Textual representation of key binding to assign (such as "Ctrl-X Ctrl-Shift-T"). Default: None

raise-panel: True to raise the OS Commands tool when this command is executed. Default: True

auto-save: True to auto-save files before executing the command. Default: False

pseudo-tty: True to use a Pseudo TTY for the command. Default: False

line-mode: True to set buffering to line mode. Default: False

Returns the internal command ID for the added command.

This adds a Command Line style OS Command. Adding Python File and Named Entry Point style OS Commands is not supported by the API.

CAPIApplication.RemoveOSCommand(cmd_id)

Remove an OS Command.

cmd_id is the internal command ID returned from AddOSCommand.

The command is terminated first if it is currently running.

CAPIApplication.ExecuteOSCommand(cmd_id, show=True)

Execute the given command in the OS Commands tool, using the internal command ID returned from previous call to AddOSCommand.

If show is True then the OS Commands tool will be shown. Otherwise, the tool is shown only if the command was configured to always show the tool when executed.

CAPIApplication.TerminateOSCommand(cmd_id)

Terminate an OS Command if it is currently running.

cmd_id is the internal command ID returned from AddOSCommand.

Scripting Framework Utilities

CAPIApplication.ReloadScript(module)

Reload the script file(s) associated with the given module or filename.

CAPIApplication.EnablePlugin(plugin_id, enable)

Enable to disable a plugin.

This may be called from plugins that auto-enable in response to signals, to indicate whether the plugin should be active or not.

Note that the user can override the plugin-determined state to either set a plugin as always enabled or never enabled, either in preferences or in project properties.

Returns True if the plugin was enabled, False if not.