Skip to content

gui

tuprolog.gui

The toolkit-neutral core of tuProlog's graphical user interfaces (GUIs) and IDEs.

2P-Kt's GUI core models an IDE for logic programs without depending on any toolkit: user interfaces only render its state, send it actions, and fulfil its effects. Its notions:

  • the state (GuiState, immutable): the open pages (PageState, each with a theory to edit, a query, its current resolution, history, console and diagnostics) and documents (DocumentState, the files pages edit);
  • actions (GuiAction): what users ask for, e.g. editing a theory (PageAction.ChangeScratchText) or solving a query (PageAction.Solve);
  • effects (GuiEffect): what the application asks its user interface to do, as it cannot do it itself, e.g. asking where to save a file (GuiEffect.PickSaveDestination), or writing it (GuiEffect.WriteDocument); the user interface reports the outcome back as actions.

Solutions, warnings and diagnostics come formatted for display (SolutionPresentation, ...). gui_application creates a GuiFacade, a running application whose pages solve with the solvers of a profile (solver_profile: the language, libraries, initial dynamic knowledge base, ...), and prolog_gui one with Prolog solvers; tuprolog.tui is a terminal user interface built on it.

Examples:

>>> states = []
>>> gui = prolog_gui(on_state=states.append, on_effect=print)
>>> gui.start().get()
>>> gui.dispatch(WorkspaceAction.NewScratchPage(None, "p(1).")).get()
>>> page = gui.state.workspace.pages[0]
>>> str(page.content.text)
'p(1).'
>>> gui.close()
See Also

tuprolog.tui, the terminal IDE.

PATH_PROVIDER module-attribute

PATH_PROVIDER = 'path'

The provider id of the DocumentOrigins of files, whose reference is the file's path.

GuiFacade module-attribute

GuiFacade = _ppy_gui.GuiFacade

A running GUI application, driven by actions and observed through callbacks.

It runs 2P-Kt's GUI controller on JVM threads, hiding its coroutines: start() starts it, dispatch(action) enqueues a GuiAction (actions are applied one at a time, in order), and close() shuts it down (it is idempotent, and the facade is a context manager). start() and dispatch(action) return a java.util.concurrent.CompletableFuture, completing once the action is applied (e.g. facade.dispatch(action).get() waits for it). The state property is the current GuiState. The state and effect callbacks run on JVM threads: user interfaces must forward them to their own thread. Create one with tuprolog.gui.prolog_gui.

Note

The JVM class it.unibo.tuprolog.ppy.gui.GuiFacade of 2PPy (see jvm/ in its repository), wrapping 2P-Kt's GuiApplication.

PROLOG_PROFILE_ID module-attribute

PROLOG_PROFILE_ID = str(GuiFacade.PROLOG_PROFILE_ID)

The id of the solver profile of Prolog pages, i.e. "prolog".

SolverProfile module-attribute

SolverProfile = _solver.SolverProfile

A kind of solver pages can query (e.g. Prolog), with its id, display name and capabilities.

GuiState module-attribute

GuiState = _model.GuiState

The whole state of a GUI application, at one point in time (immutable).

Members: application (whether it started, or an exit was requested) and workspace (a WorkspaceState).

WorkspaceState module-attribute

WorkspaceState = _model.WorkspaceState

The open documents and pages of a GUI application (immutable).

Members: pages (the PageStates, in tab order), documents (a map from DocumentIds to DocumentStates), selected_page_id, and the lookups page(page_id) and document(document_id) (None if missing).

PageState module-attribute

PageState = _model.PageState

One page of a GUI application: a theory to edit, and queries to solve against it (immutable).

Members: id (a PageId), title, content (a PageContent), query (its text), resolution (a ResolutionState), history (its resolutions, ResolutionHistoryEntrys), console (stdin, stdout.text, stderr.text, warnings.values), diagnostics (its values, Diagnostics) and semantic_tokens (from parsing the theory).

PageContent module-attribute

PageContent = _model.PageContent

What a page edits: PageContent.Scratch (the page's own text) or PageContent.DocumentReference (the document_id of a document, possibly shared by pages).

DocumentState module-attribute

DocumentState = _model.DocumentState

An open document (immutable): its id, display_name, text, origin (a DocumentOrigin, None if never saved), revision, and whether it is_dirty (it has unsaved changes).

DocumentOrigin module-attribute

DocumentOrigin = _model.DocumentOrigin

Where a document is read from and saved to: a provider_id (e.g. "path", for files), an opaque_reference (e.g. the file's path) and a display_name.

ResolutionState module-attribute

ResolutionState = _model.ResolutionState

The current resolution of a page (immutable).

Members: status (a ResolutionStatus), query, solutions (SolutionPresentations so far), error, and the commands it allows: can_solve, can_continue (more solutions may be asked for) and can_stop.

ResolutionStatus module-attribute

ResolutionStatus = _model.ResolutionStatus

The status of a resolution: IDLE, RUNNING, AWAITING_CONTINUATION, COMPLETED, FAILED, or CANCELLED.

ResolutionHistoryEntry module-attribute

ResolutionHistoryEntry = _model.ResolutionHistoryEntry

A concluded resolution: its query, solutions, terminal_status and error.

PanelId module-attribute

PanelId = _model.PanelId

A panel of a page, which may have unread changes: SOLUTIONS, STDIN, STDOUT, STDERR, WARNINGS, DIAGNOSTICS, ...

SolutionPresentation module-attribute

SolutionPresentation = _presentation.SolutionPresentation

A solution of a query, formatted for display: SolutionPresentation.Yes (with bindings, BindingPresentations, and solved_query), SolutionPresentation.No, or SolutionPresentation.Halt (with a message, and is_timeout).

BindingPresentation module-attribute

BindingPresentation = _presentation.BindingPresentation

The value of a variable in a solution, formatted for display: variable and value.

WarningPresentation module-attribute

WarningPresentation = _presentation.WarningPresentation

A warning of a solver, formatted for display: message and logic_stack_trace.

OperatorPresentation module-attribute

OperatorPresentation = _presentation.OperatorPresentation

An operator, formatted for display: name, priority and specifier (e.g. "XFX"); built as OperatorPresentation(name, priority, specifier).

SemanticCategory module-attribute

SemanticCategory = _presentation.SemanticCategory

The syntactic role of a token of Prolog text, for syntax highlighting: COMMENT, OPERATOR, PARENTHESIS, BRACE, BRACKET, FUNCTOR, ATOM, VARIABLE, NUMBER, STRING, FULL_STOP, DIRECTIVE, or ERROR.

SemanticToken module-attribute

SemanticToken = _presentation.SemanticToken

A classified span of Prolog text: range (its start and end_exclusive positions, each with an offset and zero-based line and column), category (a SemanticCategory), and modifiers.

PrologSyntaxAnalyzer module-attribute

PrologSyntaxAnalyzer = (
    _presentation.PrologSyntaxAnalyzer.INSTANCE
)

Classifies the tokens of Prolog text, for syntax highlighting: PrologSyntaxAnalyzer.analyze(source, operators) (with a JVM list of OperatorPresentations on top of the standard ones, e.g. built by tuprolog.jvmutils.jlist) returns its tokens (SemanticTokens) and diagnostics (syntax errors).

Examples:

>>> from tuprolog.jvmutils import jlist
>>> analysis = PrologSyntaxAnalyzer.analyze("p(X).", jlist([]))
>>> [str(token.category) for token in analysis.tokens]
['FUNCTOR', 'PARENTHESIS', 'VARIABLE', 'PARENTHESIS', 'FULL_STOP']

Diagnostic module-attribute

Diagnostic = _presentation.Diagnostic

A problem in a page's theory or query (e.g. a syntax error): severity (a DiagnosticSeverity), message, and range (its start and end_exclusive positions, each with zero-based line and column; None if unknown).

DiagnosticSeverity module-attribute

DiagnosticSeverity = _presentation.DiagnosticSeverity

The severity of a Diagnostic: INFO, WARNING, or ERROR.

PageId module-attribute

PageId = _identity.PageId

The identifier of a page, e.g. PageId("page-1"); str() gives its value.

DocumentId module-attribute

DocumentId = _identity.DocumentId

The identifier of a document, e.g. DocumentId("document-1"); str() gives its value.

EffectId module-attribute

EffectId = _identity.EffectId

The identifier of a GuiEffect.

GuiAction module-attribute

GuiAction = _controller.GuiAction

Something a user interface asks a GUI application to do: an ApplicationAction, a WorkspaceAction, a PageAction or a DocumentAction, dispatched by GuiFacade.dispatch.

ApplicationAction module-attribute

ApplicationAction = _controller.ApplicationAction

Actions about the whole application: Start, RequestExit, ExitConfirmed, and ExitCancelled (singletons, e.g. ApplicationAction.RequestExit.INSTANCE).

WorkspaceAction module-attribute

WorkspaceAction = _controller.WorkspaceAction

Actions about pages: e.g. NewScratchPage(title, text), NewDocumentPage(name, text), SelectPage(page_id), RequestOpenDocument.INSTANCE, OpenDocumentLoaded(origin, text, pending), RequestClosePage(page_id), and ClosePageDecisionProvided(page_id, decision).

PageAction module-attribute

PageAction = _controller.PageAction

Actions about one page: e.g. ChangeScratchText(page_id, text), ChangeQuery(page_id, query), ChangeStdin(page_id, stdin), Solve(page_id, mode), Next(page_id, mode), Stop(page_id), Reset(page_id), and MarkPanelRead(page_id, panel).

DocumentAction module-attribute

DocumentAction = _controller.DocumentAction

Actions about one document: e.g. ChangeText(document_id, text), RequestSave(document_id, force_save_as), SaveDestinationSelected(document_id, origin), SaveSucceeded(document_id, origin, revision), SaveFailed(document_id, message), RequestReload(document_id), ReloadSucceeded(document_id, text), and so on.

GuiEffect module-attribute

GuiEffect = _controller.GuiEffect

Something a GUI application asks its user interface to do, as it cannot do it itself.

E.g. PickOpenDocument, PickSaveDestination, WriteDocument, ReadDocument, ConfirmCloseDirtyPage, ConfirmReloadDirtyDocument, ConfirmExitWithDirtyDocuments, CopyTextToClipboard, and ExitApplication: the user interface reports the outcome back with the matching actions (e.g. DocumentAction.SaveSucceeded).

ConsumptionMode module-attribute

ConsumptionMode = _controller.ConsumptionMode

How many solutions PageAction.Solve and PageAction.Next ask for: ONE, TEN, HUNDRED, or ALL.

CloseDecision module-attribute

CloseDecision = _controller.CloseDecision

How to close a page with unsaved changes: SAVE, DISCARD, or CANCEL.

ReloadDecision module-attribute

ReloadDecision = _controller.ReloadDecision

Whether to reload a document with unsaved changes: DISCARD_CHANGES or CANCEL.

solver_profile

solver_profile(
    dialect: Dialect = "prolog",
    libraries: Iterable[Library] | None = None,
    dynamic_kb: Theory | None = None,
    unificator: Unificator | None = None,
    builtins: bool = True,
) -> SolverProfile

Creates a solver profile: how the solvers of GUI pages are built.

The static knowledge base of each page's solver is the page's text; everything else comes from the profile, every time a solver is (re)built, e.g. after a reset.

Parameters:

Name Type Description Default
dialect Dialect

The logic language: "prolog" (ISO Prolog) or "problog" (probabilistic logic programming: solutions show their probability).

'prolog'
libraries Iterable[Library] | None

The libraries loaded on top of the standard one; by default, tuprolog.solve.libs.IOLib and tuprolog.solve.libs.OOPLib (Python objects).

None
dynamic_kb Theory | None

The initial dynamic knowledge base of every solver; empty by default.

None
unificator Unificator | None

The unificator of the solvers; by default, the standard one.

None
builtins bool

Whether the solvers have the standard library (e.g. member/2, is/2).

True

Returns:

Type Description
SolverProfile

The profile, for gui_application.

Examples:

>>> from tuprolog.theory.parsing import parse_theory
>>> profile = solver_profile(dynamic_kb=parse_theory("counter(0)."))
>>> str(profile.display_name)
'Prolog'
Note

Wraps 2PPy's SolverProfiles.of, on top of 2P-Kt's solverFactoryProfile.

gui_application

gui_application(
    on_state: Callable[[Any], Any],
    on_effect: Callable[[Any], Any],
    on_error: Callable[[Any], Any] | None = None,
    profiles: Iterable[SolverProfile] | None = None,
    timeout: float = 5.0,
    flags: Mapping[str, str | Term] | None = None,
    scheduling: Scheduling = "concurrent",
) -> GuiFacade

Creates a GUI application, whose pages solve queries with the solvers of a profile.

The application is not started: call its start() method, then dispatch(action) actions to it, and eventually close() it (or use it as a context manager).

Parameters:

Name Type Description Default
on_state Callable[[Any], Any]

Called with every new GuiState (intermediate states may be skipped, the latest one never is), on a JVM thread.

required
on_effect Callable[[Any], Any]

Called with every GuiEffect, in order, on a JVM thread.

required
on_error Callable[[Any], Any] | None

Called with the exceptions raised by actions or by the callbacks; by default, they are logged on the tuprolog.gui logger.

None
profiles Iterable[SolverProfile] | None

The solver profiles (see solver_profile): new pages use the first one; by default, solver_profile()'s.

None
timeout float

The default timeout of resolutions, in seconds.

5.0
flags Mapping[str, str | Term] | None

The flags of every solver (names to values, as terms or their Prolog text, e.g. {"unknown": "fail"}).

None
scheduling Scheduling

Whether resolutions of different pages may run concurrently ("concurrent"), or starting one stops the others ("single").

'concurrent'

Returns:

Type Description
GuiFacade

The application, a GuiFacade.

Examples:

>>> from tuprolog.gui import ConsumptionMode, PageAction, WorkspaceAction
>>> with gui_application(on_state=lambda state: None, on_effect=print) as gui:
...     gui.start().get()
...     gui.dispatch(WorkspaceAction.NewScratchPage("demo", "p(1).")).get()
...     page = gui.state.workspace.pages[0]
...     gui.dispatch(PageAction.ChangeQuery(page.id, "p(X)")).get()
...     page = gui.state.workspace.page(page.id)
>>> page.title, page.query.text
('demo', 'p(X)')
Note

Wraps 2PPy's GuiFacade.of, on top of 2P-Kt's buildGuiApplication.

prolog_gui

prolog_gui(
    on_state: Callable[[Any], Any],
    on_effect: Callable[[Any], Any],
    on_error: Callable[[Any], Any] | None = None,
    timeout: float = 5.0,
) -> GuiFacade

Creates a GUI application whose pages solve queries with Prolog solvers.

A shorthand for gui_application with the default profile (see solver_profile).

Parameters:

Name Type Description Default
on_state Callable[[Any], Any]

Called with every new GuiState, on a JVM thread.

required
on_effect Callable[[Any], Any]

Called with every GuiEffect, in order, on a JVM thread.

required
on_error Callable[[Any], Any] | None

Called with the exceptions raised by actions or by the callbacks; by default, they are logged on the tuprolog.gui logger.

None
timeout float

The default timeout of resolutions, in seconds.

5.0

Returns:

Type Description
GuiFacade

The application, a GuiFacade.

Examples:

>>> with prolog_gui(on_state=lambda state: None, on_effect=print) as gui:
...     gui.start().get()
>>> gui.is_closed
True

path_origin

path_origin(path: str | PathLike[str]) -> DocumentOrigin

The DocumentOrigin of a file, whose provider is PATH_PROVIDER.

Parameters:

Name Type Description Default
path str | PathLike[str]

The path of the file; it is made absolute.

required

Returns:

Type Description
DocumentOrigin

The origin, displayed as the file's name.

Examples:

>>> origin = path_origin("theory.pl")
>>> origin.display_name, origin.provider_id
('theory.pl', 'path')

origin_path

origin_path(origin: DocumentOrigin) -> Path | None

The path of the file a DocumentOrigin refers to, if its provider is PATH_PROVIDER.

Parameters:

Name Type Description Default
origin DocumentOrigin

The origin.

required

Returns:

Type Description
Path | None

The path, or None for origins of other providers.

Examples:

>>> origin_path(path_origin("theory.pl")).name
'theory.pl'

documentation_preview

documentation_preview(
    markdown: str, max_length: int = 200
) -> str

A short preview of the Markdown documentation of a symbol (e.g. a flag, or a predicate of a library), as 2P-Kt's IDEs show it: the first paragraph after its signature.

Parameters:

Name Type Description Default
markdown str

The documentation (e.g. the help of a flag, or a value of the documentation of a library, in a solver's inspection).

required
max_length int

The maximum length of the preview.

200

Returns:

Type Description
str

The preview.

Examples:

>>> documentation_preview("`p(?X)`\n\nTrue of every `X`.\n\n**Examples**\n\n...")
'True of every X.'
Note

Wraps 2P-Kt's documentationPreview.