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)

python-runtime-changed: The effective Python version or installation being used by the currently open project has changed. Calls cb().

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 macOS:

  • 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. Returns None if the file is not a 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.InspectFiles(filenames, result_cb, force=False)

Inspect all the given files, where filenames is a list of full path filenames or ssh:// urls for remote files. When all inspections are complete, result_cb(exc, result) is called where exc is True if inspection failed and otherwise result is a dictionary from each filename/url to a named tuple containing:

modtime -- modification time or None if it does not exist readable -- True if disk permissions allow reading the file directory writable -- True if disk permisions allow writing to the file or directory bytecount -- For files, the size of the file files -- For directories, the names of any files in the directory dirs -- For directories, the name of any child directories

Set force=True to force inspection without using cached values.

CAPIApplication.ReadFile(filename, result_cb, encoding=None)

Read from the given filename, which may either be a full path for a local file or an ssh:// url for a remote file.

Calls result_cb(err, content, encoding) with the result of the read where err is an error if one occurred or None otherwise, content is the contents of the file, and encoding is the encoding that was used when reading the file.

The encoding may optionally be set explicitly; otherwise it is inferred from the contents of the file, previously made user settings, and the default encoding for the host where the file resides.

To read a binary file, set encoding='binary'. In that case the content passed to result_cb is bytes and not str.

CAPIApplication.WriteFile(filename, data, result_cb, encoding='utf-8', ensure_dir=False)

Write to the given filename, which may either be a full path for a local file or an ssh:// url for a remote file.

Calls result_cb(err) with the result of the operation, where err is None on success or otherwise a string describing the error.

The encoding may be set explicitly; otherwise it is inferred from the contents of the file, previously made user settings, and the default encoding for the host where the file resides.

To write a binary file, set encoding='binary' and pass data as bytes and not str.

Set ensure_dir=True to case creation of the enclosing directories before write the file, if they do not yet exist.

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.GetWindowEditorSplits(name)

Get the number of splits and current split for the window with the given internal name. Returns (num_splits, current_split) to indicate the total number of editor splits and current editor split in the window (0=first or None if there is none).

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, split_num=None)

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.

Set split_num to the editor split in which to open the file (0=first). When unspecified, the split is determined by the Editor > Split Reuse Policy preference.

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)

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.

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, encoding=...)

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.

The encoding is the encoding used to encode / decode text sent / received from the child command. It defaults to the default OS Commands encoding; use encoding=None to disable encoding / decoding and return bytes instances with the command output.

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, encoding=...)

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.

The encoding is the encoding used to encode/decode text sent or received from the child command. It defaults to the default OS Commands encoding; use encoding=None to disable encoding/decoding and return bytes instances with the command output.

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 the handler.SendToChild() method. The signature of the method is WriteToChild(self, s, flush=True, close_after=False): and the flush and close_after arguments control whether to stream to the child will be flushed and closed after writing. The string passed will be encoded unless it is a bytes instance. Some processes wait for the pipe to be closed before continuing.

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

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

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

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.

CAPIApplication.GetExecutionTarget()

Get the default execution target for commands run by the IDE with CreateChildProcess(). This is determined by the Python Executable setting in Project Properties. Returns one of:

('host', host_id) -- Runs the command on the remote host configuration with given host_id or the local host when host_id is ''

('container', container_id) -- Runs the command on the given container configuration.

('cluster, cluster_id, service, in_cluster) -- Runs the command on the given cluster service, either in-cluster or in a synthesized out-of-cluster instance of the given cluster service.

Note that remote hosts, containers, and clusters are only available in Wing Pro.

CAPIApplication.CreateChildProcess(args, terminated_cb, io_cb=None, target=None, env=None, dirname=None, separate_stderr=True, timeout=None, encoding='utf-8')

Create a child process that runs asynchronously and communicates with the caller through the given callbacks.

CreateChildProcess() is a more flexible replacement for the AsyncExecute* and Execute* API calls, with support for executing commands on a remote host, container, or cluster service, as well as the local host.

Arguments

args is a list that contains all the arguments for the child process, including the executable name or path as the first list item.

terminated_cb(timeout, exc, exit_code) is called when the process exits. If the process timed out then timeout is set to True. When the process failed to start, exc is set to a string describing the reason for failure. Otherwise, exc is None and exit_code contains the exit code given by the child process (usually 0 indicates success and other codes indicate failure, but this is defined by the implementation of the child process)

io_cb(stdout, stderr) is called (if given) with any output from the child process. If output to stderr and stdout is not being kept separate, all output will be reported through the first argument. The output is a string or bytes, depending on the value for encoding (see below).

target indicates where the command should be run. When this is None, it is the host or container used by the current project's Python Executable. Otherwise, see GetExecutionTarget() for allowable values.

env is a dictionary containing the environment to use, or None for the default environment on the selected target.

dirname is the starting directory for the process, or None to use the default for the selected target.

seperate_stderr is True when stderr output should be kept separate from stdout.

timeout is the time in seconds after which the command should automatically be terminated, or None not to terminate. The encoding is the encoding used to encode/decode text sent or received from the child command. Use None to disable encoding/decoding. When an encoding is given, output returned from the process will be in str instances. When None is used, output is instead returned as bytes.

Return Value

GetChildProcess returns a process control instance with the following available methods:

GetOutput() -- returns all the output seen so far from the child process. The output is a string unless an output encoding was given using the encoding argument to CreateChildProcess().

GetStdErrOutput() -- like GetOutput() but returns all the stderr output seen so far from the child process. This should only be called when separate_stderr was set to True when calling CreateChildProcess().

_SendInputToChild(text, close) -- Sends the given text to the child process, optionally closing the socket after doing so.

GetExitCode() -- Gets the child process exit code, or None if the process is still running.

Kill() -- Terminates the child process.

These methods can only be called before terminate_cb exits. After that the process control instance is destroyed and may no longer be used.

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.