Today, the main programming language used on Haiku is C++, which is working great with Genio or QtCreator IDE.
Last time we have reviewed also the possibility to use Java with the NetBeans IDE.
Today we will review another language : Python which offers the possibility to use the Haiku API through PyAPI bindings.
Python3 is available out of the box when you install the Haiku system.
In a Terminal type :
python3 --version
This is the current version available. Now let's write a basic "Hello World" program.
In a Terminal, type the below :
mkdir HaikuPython
cd HaikuPython
lpe Hello.py
In Pe editor, enter the below text :
print("Hello, World!")
Save the file. To launch it, as you can see it's easy :
python3 Hello.py
In order to be able to use the Haiku API through python, you need to install the PyAPI bindings.
The details are available on the Haiku PyAPI bindings github page.
Install the required package with the below command :
pkgman install haiku_pyapi_python310
Ok we are good to start !
Before doing a showcase of Python using the Haiku API, let's write a simple C++ program for Haiku and compare it to the same Python program.
The C++ program will be a "Hello World!" using the Haiku API.
Open Pe editor and copy/paste the source code provided :
The source code is using the BApplication, BWindow, BView, BStringView classes:
#include <Application.h>
#include <Window.h>
#include <View.h>
#include <StringView.h>
class HelloWorldWindow : public BWindow {
public:
HelloWorldWindow()
: BWindow(BRect(100, 100, 400, 200),
"Hello World App",
B_TITLED_WINDOW,
B_NOT_RESIZABLE |
B_QUIT_ON_WINDOW_CLOSE) {
BView* panel = new BView(Bounds(), "panel", B_FOLLOW_ALL, 0);
BStringView* label = new BStringView(BRect(20, 20, 200, 50),
"label",
"Hello World!");
label->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));
panel->AddChild(label);
AddChild(panel);
}
};
class HelloWorldApp : public BApplication {
public:
HelloWorldApp()
: BApplication("application/x-vnd.HelloWorldApp") {}
void ReadyToRun() override {
HelloWorldWindow* window = new HelloWorldWindow();
window->Show();
}
};
int main() {
HelloWorldApp app;
app.Run();
return 0;
}
Save the file under the "HelloHaiku.cpp" name. Now compile and execute it :
g++ HelloHaiku.cpp -o HelloHaiku -lbe
./HelloHaiku
Ok the famous "Hello World!" message is correctly displayed.
Now let's do the same but in Python.
In Pe editor copy/paste the source code provided for python :
Nothing new here, the source code is also using the BApplication, BWindow, BView, BStringView classes:
from Be import *
class HelloWorldWindow(BWindow):
def __init__(self):
# Creer une fenêtre
BWindow.__init__(self,
BRect(100, 100, 400, 200),
"Hello World App",
B_TITLED_WINDOW_LOOK,
B_NORMAL_WINDOW_FEEL,
B_NOT_RESIZABLE |
B_QUIT_ON_WINDOW_CLOSE)
self.panel = BView(self.Bounds(), "panel", B_FOLLOW_ALL_SIDES, B_WILL_DRAW)
self.label = BStringView(BRect(20, 20, 200, 50),
"label",
"Hello World!")
self.label.SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR))
self.panel.AddChild(self.label, None)
self.AddChild(self.panel, None)
class App(BApplication):
def __init__(self):
BApplication.__init__(self, "application/x-python.HelloWorldApp")
def ReadyToRun(self):
self.window = HelloWorldWindow()
self.window.Show()
def main():
global be_app
be_app = App()
be_app.Run()
if __name__ == "__main__":
main()
Save the file under the "HelloHaiku.py" name Execute it with the python3 interpreter :
python3 HelloHaiku.py
As you can see the C++ and Python source codes look quite similar, meaning if you are curious, you can check existing C++ programs using the Haiku API to write your own Python programs using Haiku API.
Ok now let's showcase a Python program for Haiku.
If you remember the scripting commands article, we have learn how to use the "alert" command via a bash script.
What about replacing the "alert" command by your own python program ?
Note that it's not really useful to replace an existing command (except if you do some enhancements), so this example is only given as a showcase for the article.
The aim is to demonstrate how to enhance the user's interaction with bash scripts because the script will communicate with a Python program using the Haiku API.
And of course, you can extend this showcase to others usages.
Ok, now let's create a new file named "HaikuChoice.py" :
lpe HaikuChoice.py
Copy and paste the below source code :
from Be import *
class ChoiceWindow(BWindow):
def __init__(self, window_title="Information"):
# Create Window
BWindow.__init__(self,
BRect(100, 100, 420, 240),
window_title,
B_TITLED_WINDOW_LOOK,
B_NORMAL_WINDOW_FEEL,
B_NOT_RESIZABLE |
B_QUIT_ON_WINDOW_CLOSE)
# Add main view
self.panel = BView(self.Bounds(), "panel", B_FOLLOW_ALL_SIDES, B_WILL_DRAW)
# Add question
self.label = BStringView(BRect(20, 20, 280, 50),
"instruction",
"Do you confirm your choice ? ")
self.panel.SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR))
self.panel.AddChild(self.label, None)
# Add choice buttons
self.choices = ["Yes", "No", "Abort"]
self.add_choice_buttons(self.choices)
self.AddChild(self.panel, None)
def add_choice_buttons(self, choices):
# Add a button for each choice
x_offset = 20
for i, choice in enumerate(choices):
button = BButton(BRect(x_offset, 80 , 80 + x_offset, 110),
f"button_{i}",
choice,
BMessage(i)) # Add message with choice ID
self.panel.AddChild(button, None)
x_offset += 100
def MessageReceived(self, message):
# Handle message from button
if message.what in range(len(self.choices)): # choice ID
choice_text = self.choices[message.what] # get the string from the choice ID
print(f"{choice_text}") # return the choice string
be_app.PostMessage(B_QUIT_REQUESTED) # quit
# Main application class
class ChoiceApp(BApplication):
def __init__(self, window_title):
BApplication.__init__(self, "application/x-python")
self.window_title = window_title
def ReadyToRun(self):
self.window = ChoiceWindow(self.window_title)
self.window.Show()
def main():
global be_app
window_title = "Information"
# Use window title if provided
import sys
if len(sys.argv) > 1:
window_title = sys.argv[1]
be_app = ChoiceApp(window_title)
be_app.Run()
if __name__ == "__main__":
main()
As you can see, it's a simple program which
Now, let's call the python script, and use the "choice" variable under the bash to memorize the user's choice :
export choice=`python3 HaikuChoice.py "Installation"`
The window displayed for the choice requested should be like below :
As you can see, the title of the window is "Installation" because this parameter was passed from the bash to the python program.
Now indicate your choice.
The bash is retrieving the answer and you can display it :
echo $choice
Working as expected :)
If you are more comfortable with Python than C++, then the usage of Python with PyAPI bindings can be a good choice.
Another advantage of Python is that it's an interpreted language, meaning you don't need to provide a binary for your program.
Do you want to deliver your program for both Haiku 32 bits or 64 bits ?
It will be only one program.
The drawback I can see today -to confirm-, is that I'm not sure the current bindings are covering 100% of the Haiku API.
Another one is that it's not easy to start directly with Python and Haiku API because there are not so much programs using the PyAPI bindings.
For instance, the below mistake can be done easily on the AddChild() method in a Python program, because the C++ version doesn't require to indicate a NULL as second parameter :
Hence the "self.panel.AddChild(self.label)" is raising an error as below :
To fix that, you need to explicitly indicate "self.panel.AddChild(self.label, None)".
Looking at the Haiku API on the BView.AddChild(), it's clear that 2 parameters are expected for the second signature :
If you would like to check additional programs using the PyAPI bindings, you can consult the Haiku PyAPI bindings github page and check the "Example projects" section.
You can also visit the Haiku Book on the official website to understand more on how to use the Haiku API.
If you need to have code completion or debug feature during your development with Python and PyAPI, my advice is to use the PyCharm Community Edition IDE under Haiku.
As you can see, a debug button is available :
And you can put breakpoints and do step into/over in the source code :
Code completion is also great when you are not sure about the exact signature in the Haiku API or if you would like to facilitate your coding :
The PyCharm Community Edtion might be part of a dedicated article soon :)