Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add an interactive Python command console #145

Merged
merged 1 commit into from
Nov 5, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions cpp/binary/viewer/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,8 @@ endif()
# See https://gitlab.kitware.com/cmake/cmake/-/merge_requests/777
file(WRITE "${viewer_BINARY_DIR}/.rcc/.clang-tidy" "---
Checks: '-*,llvm-twine-local'")
file(WRITE "${viewer_BINARY_DIR}/viewer_autogen/.clang-tidy" "---
Checks: '-bugprone-suspicious-include,llvm-twine-local'")

set_target_properties(
viewer PROPERTIES
Expand Down
8 changes: 8 additions & 0 deletions cpp/modmesh/python/common.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,14 @@ void Interpreter::preload_modules(std::vector<std::string> const & names)
}
}

// NOLINTNEXTLINE(readability-convert-member-functions-to-static)
void Interpreter::exec_code(std::string const & code)
{
// NOLINTNEXTLINE(misc-const-correctness)
pybind11::object mod_sys = pybind11::module_::import("modmesh.system");
mod_sys.attr("exec_code")(code);
}

} /* end namespace python */

} /* end namespace modmesh */
Expand Down
1 change: 1 addition & 0 deletions cpp/modmesh/python/common.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -490,6 +490,7 @@ class MODMESH_PYTHON_WRAPPER_VISIBILITY Interpreter
Interpreter & setup_process();

int enter_main();
void exec_code(std::string const & code);

private:

Expand Down
2 changes: 2 additions & 0 deletions cpp/modmesh/view/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ set(MODMESH_VIEW_HEADERS
${CMAKE_CURRENT_SOURCE_DIR}/RApplication.hpp
${CMAKE_CURRENT_SOURCE_DIR}/RAxisMark.hpp
${CMAKE_CURRENT_SOURCE_DIR}/RMainWindow.hpp
${CMAKE_CURRENT_SOURCE_DIR}/RPythonConsoleDockWidget.hpp
${CMAKE_CURRENT_SOURCE_DIR}/RPythonText.hpp
${CMAKE_CURRENT_SOURCE_DIR}/RStaticMesh.hpp
${CMAKE_CURRENT_SOURCE_DIR}/RMenu.hpp
Expand All @@ -21,6 +22,7 @@ set(MODMESH_VIEW_SOURCES
${CMAKE_CURRENT_SOURCE_DIR}/RApplication.cpp
${CMAKE_CURRENT_SOURCE_DIR}/RAxisMark.cpp
${CMAKE_CURRENT_SOURCE_DIR}/RMainWindow.cpp
${CMAKE_CURRENT_SOURCE_DIR}/RPythonConsoleDockWidget.cpp
${CMAKE_CURRENT_SOURCE_DIR}/RPythonText.cpp
${CMAKE_CURRENT_SOURCE_DIR}/RStaticMesh.cpp
${CMAKE_CURRENT_SOURCE_DIR}/RMenu.cpp
Expand Down
4 changes: 4 additions & 0 deletions cpp/modmesh/view/RMainWindow.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ void RMainWindow::setUp()
m_pytext->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
addDockWidget(Qt::RightDockWidgetArea, m_pytext);

m_pycon = new RPythonConsoleDockWidget(QString("Console"), this);
m_pycon->setAllowedAreas(Qt::BottomDockWidgetArea | Qt::TopDockWidgetArea);
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Allow the console to be at the bottom or the top. Having it in the left or right could make it too narrow.

addDockWidget(Qt::BottomDockWidgetArea, m_pycon);

m_viewer = new R3DWidget();
setCentralWidget(m_viewer);
}
Expand Down
2 changes: 2 additions & 0 deletions cpp/modmesh/view/RMainWindow.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
#include <modmesh/view/common_detail.hpp> // Must be the first include.

#include <modmesh/view/RPythonText.hpp>
#include <modmesh/view/RPythonConsoleDockWidget.hpp>
#include <modmesh/view/R3DWidget.hpp>

#include <Qt>
Expand Down Expand Up @@ -59,6 +60,7 @@ class RMainWindow
void setUp();

RPythonText * m_pytext = nullptr;
RPythonConsoleDockWidget * m_pycon = nullptr;
R3DWidget * m_viewer = nullptr;

}; /* end class RPythonText */
Expand Down
155 changes: 155 additions & 0 deletions cpp/modmesh/view/RPythonConsoleDockWidget.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
/*
* Copyright (c) 2022, Yung-Yu Chen <yyc@solvcon.net>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/

#include <modmesh/view/RPythonConsoleDockWidget.hpp>
#include <QVBoxLayout>
#include <QKeyEvent>

namespace modmesh
{

void RPythonConsoleDockWidget::appendPastCommand(const std::string & code)
{
if (code.size() > 0)
{
m_past_command_strings.push_back(code);
if (m_past_command_strings.size() > m_past_limit)
{
m_past_command_strings.pop_front();
}
}
}

void RPythonCommandTextEdit::keyPressEvent(QKeyEvent * event)
{
if (Qt::Key_Return == event->key())
{
execute();
}
else if (Qt::Key_Up == event->key())
{
navigate(/* offset */ -1);
}
else if (Qt::Key_Down == event->key())
{
navigate(/* offset */ 1);
}
else
{
QTextEdit::keyPressEvent(event);
}
}

RPythonConsoleDockWidget::RPythonConsoleDockWidget(const QString & title, QWidget * parent, Qt::WindowFlags flags)
: QDockWidget(title, parent, flags)
, m_history_edit(new QTextEdit)
, m_command_edit(new RPythonCommandTextEdit)
{
setWidget(new QWidget);
widget()->setLayout(new QVBoxLayout);

m_history_edit->setFont(QFont("Courier New"));
m_history_edit->setPlainText(QString(""));
m_history_edit->setReadOnly(true);
widget()->layout()->addWidget(m_history_edit);

m_command_edit->setFont(QFont("Courier New"));
m_command_edit->setPlainText(QString(""));
m_command_edit->setFixedHeight(40);
widget()->layout()->addWidget(m_command_edit);

connect(m_command_edit, &RPythonCommandTextEdit::execute, this, &RPythonConsoleDockWidget::executeCommand);
connect(m_command_edit, &RPythonCommandTextEdit::navigate, this, &RPythonConsoleDockWidget::navigateCommand);
}

void RPythonConsoleDockWidget::executeCommand()
{
std::string const code = m_command_edit->toPlainText().toStdString();
appendPastCommand(code);
m_history_edit->insertPlainText(m_command_edit->toPlainText());
m_history_edit->insertPlainText("\n");
m_command_edit->setPlainText("");
m_command_string = "";
m_current_command_index = static_cast<int>(m_past_command_strings.size());
auto & interp = modmesh::python::Interpreter::instance();
interp.exec_code(code);
}

void RPythonConsoleDockWidget::navigateCommand(int offset)
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Navigate through the history. Slight complexity.

{
int const cmdsize = static_cast<int>(m_past_command_strings.size()); // make msc happy.
if (cmdsize == m_current_command_index)
{
m_command_string = m_command_edit->toPlainText().toStdString();
}

int new_index = m_current_command_index + offset;
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Limit the range of new_index.

if (new_index > cmdsize)
{
new_index = cmdsize;
}
else if (new_index < 0)
{
new_index = 0;
}

if ((0 == m_past_command_strings.size()) || (new_index == m_current_command_index))
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If there's nothing in the history or the new index does not change, do nothing.

{
// do nothing
}
else
{
if (new_index > m_current_command_index)
{
if (new_index >= static_cast<int>(m_past_command_strings.size()))
{
m_command_edit->setPlainText(QString::fromStdString(m_command_string));
}
else
{
m_command_edit->setPlainText(QString::fromStdString(m_past_command_strings[new_index]));
}
m_current_command_index = new_index;
}
else // new_index < m_current_command_index
{
m_command_edit->setPlainText(QString::fromStdString(m_past_command_strings[new_index]));
m_current_command_index = new_index;
}
// Move cursor to the end of line.
{
QTextCursor cursor = m_command_edit->textCursor();
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

textCursor() returns a copy.

cursor.movePosition(QTextCursor::EndOfLine);
m_command_edit->setTextCursor(cursor);
}
}
}

} /* end namespace modmesh */

// vim: set ff=unix fenc=utf8 et sw=4 ts=4 sts=4:
91 changes: 91 additions & 0 deletions cpp/modmesh/view/RPythonConsoleDockWidget.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
#pragma once

/*
* Copyright (c) 2022, Yung-Yu Chen <yyc@solvcon.net>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/

#include <modmesh/python/common.hpp> // must be first.

#include <string>
#include <deque>

#include <Qt>
#include <QDockWidget>
#include <QTextEdit>

namespace modmesh
{

class RPythonCommandTextEdit
: public QTextEdit
{
Q_OBJECT

public:

void keyPressEvent(QKeyEvent * event) override;

signals:

void execute();
void navigate(int offset);

}; /* end class RPythonCommandTextEdit */

class RPythonConsoleDockWidget
: public QDockWidget
{
Q_OBJECT

public:

explicit RPythonConsoleDockWidget(
QString const & title = "Console",
QWidget * parent = nullptr,
Qt::WindowFlags flags = Qt::WindowFlags());

public slots:

void executeCommand();
void navigateCommand(int offset);

private:

void appendPastCommand(std::string const & code);

QTextEdit * m_history_edit = nullptr;
RPythonCommandTextEdit * m_command_edit = nullptr;
std::string m_command_string;
std::deque<std::string> m_past_command_strings;
int m_current_command_index = 0;
size_t m_past_limit = 1024;

}; /* end class RPythonConsoleDockWidget */

} /* end namespace modmesh */

// vim: set ff=unix fenc=utf8 et sw=4 ts=4 sts=4:
6 changes: 4 additions & 2 deletions modmesh/apputil.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,16 +52,18 @@ class AppEnvironment:
"""
Collects the environment for an application.

:ivar globals:
The global namespace of the application.
:ivar locals:
The local namespace of the application.
"""
def __init__(self, name):
self.globals = {}
self.locals = {
self.globals = {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Change to have the symbols to appear in the "module global".

# Give the application an alias of the top package.
'mm': importlib.import_module('modmesh'),
'appenv': self,
}
self.locals = {}
self.name = name
# Each run of the application appends a new environment.
environ[name] = self
Expand Down
13 changes: 13 additions & 0 deletions modmesh/system.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,17 @@
import sys
import os
import argparse
import traceback

import modmesh
from . import view
from . import apputil


__all__ = [
'setup_process',
'enter_main',
'exec_code',
]


Expand Down Expand Up @@ -111,4 +114,14 @@ def enter_main(argv):
sys.stderr.write('mode "{}" is not supported'.format(args.mode))
return ret


def exec_code(code):
try:
apputil.run_code(code)
except Exception as e:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this doesn't work well I think.
for example, I enter print(a) (with undefined a) in the console, it will just crash.

sys.stdout.write("code:\n{}\n".format(code))
sys.stdout.write("{}: {}\n".format(type(e).__name__, str(e)))
sys.stdout.write("traceback:\n")
traceback.print_stack()

# vim: set ff=unix fenc=utf8 et sw=4 ts=4 sts=4: