Window creation/X11: Difference between revisions

Added Yabasic
(Rename Perl 6 -> Raku, alphabetize, minor clean-up)
(Added Yabasic)
 
(21 intermediate revisions by 10 users not shown)
Line 9:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program creatFenX1164.s */
Line 156:
.include "../includeARM64.inc"
 
</syntaxhighlight>
</lang>
 
=={{header|ALGOL 68}}==
Line 163:
Using the X11 & plotutil libraries is not part of any of the original UNESCO/IFIP [[ALGOL 68]]
reports. As at December 2008 only [[ALGOL 68G]] comes with these built in.
<langsyntaxhighlight lang="algol68">FILE window;
draw device (window, "X", "600x400");
open (window, "Hello, World!", stand draw channel);
Line 172:
draw show (window);
VOID (read char);
close (window)</langsyntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
 
/* ARM assembly Raspberry PI */
Line 650:
bx lr @ leave function
iMagicNumber: .int 0xCCCCCCCD
</syntaxhighlight>
</lang>
 
 
=={{header|BaCon}}==
 
<syntaxhighlight lang="c">
'--- added a flush to exit cleanly
PRAGMA LDFLAGS `pkg-config --cflags --libs x11`
PRAGMA INCLUDE <X11/Xlib.h>
PRAGMA INCLUDE <X11/Xutil.h>
 
OPTION PARSE FALSE
'---XLIB is so ugly
ALIAS XNextEvent TO EVENT
ALIAS XOpenDisplay TO DISPLAY
ALIAS DefaultScreen TO SCREEN
ALIAS XCreateSimpleWindow TO CREATE
ALIAS XCloseDisplay TO CLOSE_DISPLAY
ALIAS XSelectInput TO EVENT_TYPE
ALIAS XMapWindow TO MAP_EVENT
ALIAS XFillRectangle TO FILL_RECTANGLE
ALIAS XDrawString TO DRAW_STRING
ALIAS XFlush TO FLUSH
 
'---pointer to X Display structure
DECLARE d TYPE Display*
'---pointer to the newly created window
'DECLARE w TYPE WINDOW
'---pointer to the XEvent
DECLARE e TYPE XEvent
DECLARE msg TYPE char*
'--- number of screen to place the window on
DECLARE s TYPE int
msg = "Hello, World!"
d = DISPLAY(NULL)
IF d == NULL THEN
EPRINT "Cannot open display" FORMAT "%s%s\n"
END
END IF
s = SCREEN(d)
w = CREATE(d, RootWindow(d, s), 10, 10, 100, 100, 1,BlackPixel(d, s), WhitePixel(d, s))
EVENT_TYPE(d, w, ExposureMask | KeyPressMask)
MAP_EVENT(d, w)
WHILE (1)
EVENT(d, &e)
IF e.type == Expose THEN
FILL_RECTANGLE(d, w, DefaultGC(d, s), 20, 20, 10, 10)
DRAW_STRING(d, w, DefaultGC(d, s), 10, 50, msg, strlen(msg))
END IF
IF e.type == KeyPress THEN
BREAK
END IF
WEND
FLUSH(d)
CLOSE_DISPLAY(d)
</syntaxhighlight>
 
=={{header|C}}==
Line 659 ⟶ 728:
* gcc hello-x.c -L/usr/X11R6/lib -lX11 -o hello-x
 
<langsyntaxhighlight lang="c">#include <X11/Xlib.h>
#include <stdio.h>
#include <stdlib.h>
Line 695 ⟶ 764:
XCloseDisplay(d);
return 0;
}</langsyntaxhighlight>
 
=== XCB ===
Line 703 ⟶ 772:
* gcc -o helloxcb helloxcb.c -lxcb
 
<langsyntaxhighlight lang="c">#include <stdlib.h>
#include <stdio.h>
#include <string.h>
Line 785 ⟶ 854:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|COBOL}}==
Tested with GnuCOBOL, and only on 64bit architecture, GNU/Linux. Nods to the C XLib version.
 
<langsyntaxhighlight lang="cobol"> identification division.
program-id. x11-hello.
installation. cobc -x x11-hello.cob -lX11
Line 964 ⟶ 1,033:
 
goback.
end program x11-hello.</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
Line 977 ⟶ 1,046:
This example uses CLX, which is the de facto standard X11 library for Common Lisp. CLX is not a binding to Xlib; it is a Lisp library implementing the X11 protocol.
 
<langsyntaxhighlight lang="lisp">;;; Single-file/interactive setup; large applications should define an ASDF system instead
 
(let* ((display (open-default-display))
Line 1,007 ⟶ 1,076:
(close-display display)))
 
</syntaxhighlight>
</lang>
=={{header|Forth}}==
Running Ubuntu 20.04 64-bit
Using : Gforth 0.7.9_20211014
 
<syntaxhighlight lang="forth">
warnings off
require xlib.fs
 
0 value X11-D \ Display
0 value X11-S \ Screen
0 value X11-root
0 value X11-GC
0 value X11-W \ Window
0 value X11-Black
0 value X11-White
9 value X11-Top
0 value X11-Left
create X11-ev 96 allot
 
variable wm_delete
 
: X11-D-S X11-D X11-S ;
: X11-D-G X11-D X11-GC ;
: X11-D-W X11-D X11-W ;
: X11-D-W-G X11-D-W X11-GC ;
 
: open-X11 ( -- )
X11-D 0= if 0 XOpendisplay to X11-D
X11-D 0= abort" can't connect to X server"
X11-D XDefaultscreen to X11-S
X11-D-S XRootwindow to X11-root
X11-D-S XDefaultGC to X11-GC
X11-D-S XBlackPixel to X11-Black
X11-D-S XWhitePixel to X11-White
then
X11-W 0= if X11-D X11-root X11-top X11-left 400 220 0 0 $808080 XCreateSimplewindow to X11-W
X11-W 0= abort" failed to create X11-window"
X11-D-W $28043 XSelectInput drop
X11-D s" WM_DELETE_WEINDOW" 1 XInternAtom wm_delete !
X11-D-W wm_delete 1 XSetWMProtocols drop
X11-D-W XMapwindow drop
X11-D XFlush drop
then ;
 
: close-graphics ( -- )
X11-W if X11-D-W XDestroywindow drop 0 to X11-W
then
X11-D if X11-D XClosedisplay 0 to X11-D
then ;
 
: foreground >r X11-D-G r> XSetForeground drop ;
: background >r X11-D-G r> XSetBackground drop ;
: keysym X11-ev 0 XLookupKeysym ;
 
: ev-loop
begin X11-D X11-ev XNextEvent throw
X11-White foreground
X11-Black background
X11-D-W-G 100 100 s" Hello World" XDrawString drop
X11-D-W-G 100 120 150 25 XDrawRectangle drop
X11-D-W-G 110 135 s" Press ESC to exit ..." XDrawString drop
case X11-ev @ $ffffffff and
3 of keysym XK_Escape = if exit then endof
endcase
again ;
\ #### Test #####
0 open-X11
ev-loop
close-graphics
bye
</syntaxhighlight>
 
=={{header|FreeBASIC}}==
=== Xlib ===
{{libheader|Xlib}}
<syntaxhighlight lang="vbnet">#include once "X11/Xlib.bi"
 
Dim As Display Ptr dpy
Dim As Window win
Dim As GC gc
Dim As XEvent ev
 
dpy = XOpenDisplay(NULL)
win = XCreateSimpleWindow(dpy, XDefaultRootWindow(dpy), 0, 0, 400, 300, 0, 0, 0)
gc = XCreateGC(dpy, win, 0, NULL)
XSelectInput(dpy, win, ExposureMask Or KeyPressMask)
XMapWindow(dpy, win)
 
While XNextEvent(dpy, @ev) = 0
If ev.type = Expose Then
XDrawString(dpy, win, gc, 200, 150, "Hello World", 11)
EndIf
Wend
 
XCloseDisplay(dpy)</syntaxhighlight>
 
=={{header|Go}}==
{{trans|C}}
<langsyntaxhighlight lang="go">package main
 
// Copyright (c) 2013 Alex Kesling
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
 
import (
"log"
"code.google.com/p/x-go-binding/xgb"
"fmtgithub.com/jezek/xgb"
"github.com/jezek/xgb/xproto"
)
 
func main() {
// Open the connection to the X server
c, err := xgb.Dial("")
X, err := xgb.NewConn()
if err != nil {
fmtlog.PrintlnFatal(err)
return
}
defer c.Close()
 
// geometric objects
strBytes := []byte("Hello XGB!")
rectanglespoints := []xgbxproto.RectanglePoint{{40, 40, 20, 20}}
{10, 10},
{10, 20},
{20, 10},
{20, 20}};
 
polyline := []xproto.Point{
// get the first screen
s := c.DefaultScreen() {50, 10},
{ 5, 20}, // rest of points are relative
{25,-20},
{10, 10}};
 
segments := []xproto.Segment{
// root window
{100, 10, 140, 30},
win := s.Root
{110, 25, 130, 60}};
 
rectangles := []xproto.Rectangle{
// create black (foreground) graphic context
{ 10, 50, 40, 20},
fg := c.NewId()
{ 80, 50, 10, 40}};
mask := uint32(xgb.GCForeground | xgb.GCGraphicsExposures)
values := []uint32{s.BlackPixel, 0}
c.CreateGC(fg, win, mask, values)
 
arcs := []xproto.Arc{
// create white (background) graphic context
{10, 100, 60, 40, 0, 90 << 6},
bg := c.NewId()
{90, 100, 55, 40, 0, 270 << 6}};
mask = uint32(xgb.GCBackground | xgb.GCGraphicsExposures)
values[0] = s.WhitePixel // (values[1] still 0)
c.CreateGC(bg, win, mask, values)
 
setup := xproto.Setup(X)
// create the window
win// =Get c.NewId()the first screen
screen := setup.DefaultScreen(X)
mask = xgb.CWBackPixel | xgb.CWEventMask
 
// values[0] still s.WhitePixel
// Create black (foreground) graphic context
values[1] = xgb.EventMaskExposure | xgb.EventMaskKeyPress
foreground, _ := xproto.NewGcontextId(X)
c.CreateWindow(0, win, s.Root, 0, 0, 150, 150, 10,
mask := uint32(xproto.GcForeground | xproto.GcGraphicsExposures)
xgb.WindowClassInputOutput, s.RootVisual, mask, values)
values := []uint32{screen.BlackPixel, 0}
c.MapWindow(win)
xproto.CreateGC(X, foreground, xproto.Drawable(screen.Root), mask, values)
 
// Ask for our window's Id
win, _ := xproto.NewWindowId(X)
winDrawable := xproto.Drawable(win)
 
// Create the window
mask = uint32(xproto.CwBackPixel | xproto.CwEventMask)
values = []uint32{screen.WhitePixel, xproto.EventMaskExposure}
xproto.CreateWindow(X, // Connection
screen.RootDepth, // Depth
win, // Window Id
screen.Root, // Parent Window
0, 0, // x, y
150, 150, // width, height
10, // border_width
xproto.WindowClassInputOutput, // class
screen.RootVisual, // visual
mask, values) // masks
 
// Map the window on the screen
xproto.MapWindow(X, win)
 
for {
eventevt, err := cX.WaitForEvent()
ifswitch err != nilevt.(type) {
fmtcase xproto.Println(err)ExposeEvent:
return /* We draw the points */
xproto.PolyPoint(X, xproto.CoordModeOrigin, winDrawable, foreground, points)
 
/* We draw the polygonal line */
xproto.PolyLine(X, xproto.CoordModePrevious, winDrawable, foreground, polyline)
 
/* We draw the segments */
xproto.PolySegment(X, winDrawable, foreground, segments)
 
/* We draw the rectangles */
xproto.PolyRectangle(X, winDrawable, foreground, rectangles)
 
/* We draw the arcs */
xproto.PolyArc(X, winDrawable, foreground, arcs)
 
default:
/* Unknown event type, ignore it */
}
 
switch event.(type) {
caseif xgb.ExposeEvent:err != nil {
clog.PolyRectangleFatal(win, fg, rectangleserr)
c.ImageText8(win, bg, 20, 20, strBytes)
case xgb.KeyPressEvent:
return
}
}
return
}</lang>
}</syntaxhighlight>
Screen capture:
 
Line 1,079 ⟶ 1,300:
groovy WindowCreation.groovy
 
<langsyntaxhighlight lang="groovy">import javax.swing.*
import java.awt.*
import java.awt.event.WindowAdapter
Line 1,109 ⟶ 1,330:
}
}
}</langsyntaxhighlight>
 
=={{header|GUISS}}==
Graphical User Interface Support Script is really a language for operating a computer, rather than programming one, so we cannot do this via X11 libraries. The example uses leafpad for our open window, and the box symbols to enclose our text:
 
<langsyntaxhighlight lang="guiss">Start,Programs,Applications,Editors,Leafpad,Textbox,
Type:[openbox]Hello World[pling][closebox]</langsyntaxhighlight>
 
=={{header|Haskell}}==
Using {{libheader|X11}} from [http://hackage.haskell.org/packages/hackage.html HackageDB]
<langsyntaxhighlight lang="haskell">import Graphics.X11.Xlib
import Control.Concurrent (threadDelay)
 
Line 1,141 ⟶ 1,362:
destroyWindow display xwin
closeDisplay display
</syntaxhighlight>
</lang>
 
=={{header|Icon}} and {{header|Unicon}}==
Icon and Unicon provide a portable graphics implementation that does not rely upon a toolkit. The intent is to be platform independent and the same code runs on multiple platforms without change and producing results with only minor variations. Icon and Unicon graphics are implemented in X-Windows as well as MS-Windows and others. There are additional 3D graphics capabilities implemented using opengl.
<langsyntaxhighlight Iconlang="icon">procedure main()
W1 := open("X-Window","g","size=250,250","bg=black","fg=red") | stop("unable to open window")
FillRectangle(W1,50,50,150,150)
Line 1,151 ⟶ 1,372:
end
 
link graphics</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
Line 1,163 ⟶ 1,384:
run
java WindowExample
<langsyntaxhighlight lang="java">import javax.swing.JFrame;
import javax.swing.SwingUtilities;
 
Line 1,183 ⟶ 1,404:
frame.setVisible(true);
}
}</langsyntaxhighlight>The previous example works but doesn't write any text or draw any box; the following does both.<langsyntaxhighlight lang="java">import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
Line 1,209 ⟶ 1,430:
f.setVisible(true);
}
}</langsyntaxhighlight>
 
=={{header|Julia}}==
This was based on https://en.wikipedia.org/wiki/Xlib, and mostly quoted from from the XLib.jl test2() testing code function.
<langsyntaxhighlight lang="julia">
using Xlib
 
Line 1,254 ⟶ 1,475:
 
x11demo()
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
{{trans|C}}
{{libheader|Xlib}}
<langsyntaxhighlight lang="scala">// Kotlin Native v0.3
 
import kotlinx.cinterop.*
Line 1,290 ⟶ 1,511:
XCloseDisplay(d)
nativeHeap.free(e)
}</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
Line 1,297 ⟶ 1,518:
Ao for this task we use the M2000 way to make a form and do something on it.
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
\\ M2000 froms (windows) based on a flat, empty with no title bar, vb6 window and a user control.
\\ title bar is a user control in M2000 form
Line 1,339 ⟶ 1,560:
}
SquareAndText2Window
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Note that GUIKit is a high-level wrapper for Swing.
<syntaxhighlight lang="text">Needs["GUIKit`"]
 
<lang>
Needs["GUIKit`"]
ref = GUIRun[Widget["Panel", {
Widget[
Line 1,352 ⟶ 1,571:
"GIF"]]}],
Widget["Label", { "text" -> "Hello World!"}]}
]]</syntaxhighlight>
 
</lang>
=={{header|Nim}}==
<syntaxhighlight lang="nim">import x11/[xlib,xutil,x]
 
const
windowWidth = 1000
windowHeight = 600
borderWidth = 5
eventMask = ButtonPressMask or KeyPressMask or ExposureMask
 
var
display: PDisplay
window: Window
deleteMessage: Atom
graphicsContext: GC
 
proc init() =
display = XOpenDisplay(nil)
if display == nil:
quit "Failed to open display"
 
let
screen = XDefaultScreen(display)
rootWindow = XRootWindow(display, screen)
foregroundColor = XBlackPixel(display, screen)
backgroundColor = XWhitePixel(display, screen)
 
window = XCreateSimpleWindow(display, rootWindow, -1, -1, windowWidth,
windowHeight, borderWidth, foregroundColor, backgroundColor)
 
discard XSetStandardProperties(display, window, "X11 Example", "window", 0,
nil, 0, nil)
 
discard XSelectInput(display, window, eventMask)
discard XMapWindow(display, window)
 
deleteMessage = XInternAtom(display, "WM_DELETE_WINDOW", false.XBool)
discard XSetWMProtocols(display, window, deleteMessage.addr, 1)
 
graphicsContext = XDefaultGC(display, screen)
 
 
proc drawWindow() =
const text = "Hello, Nim programmers."
discard XDrawString(display, window, graphicsContext, 10, 50, text, text.len)
discard XFillRectangle(display, window, graphicsContext, 20, 20, 10, 10)
 
 
proc mainLoop() =
## Process events until the quit event is received
var event: XEvent
while true:
discard XNextEvent(display, event.addr)
case event.theType
of Expose:
drawWindow()
of ClientMessage:
if cast[Atom](event.xclient.data.l[0]) == deleteMessage:
break
of KeyPress:
let key = XLookupKeysym(cast[PXKeyEvent](event.addr), 0)
if key != 0:
echo "Key ", key, " pressed"
of ButtonPressMask:
echo "Mouse button ", event.xbutton.button, " pressed at ",
event.xbutton.x, ",", event.xbutton.y
else:
discard
 
 
proc main() =
init()
mainLoop()
discard XDestroyWindow(display, window)
discard XCloseDisplay(display)
 
 
main()</syntaxhighlight>
 
=={{header|OCaml}}==
Line 1,368 ⟶ 1,664:
#load "Xlib.cma"
 
<langsyntaxhighlight lang="ocaml">open Xlib
 
let () =
Line 1,391 ⟶ 1,687:
main_loop();
xCloseDisplay d;
;;</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 1,398 ⟶ 1,694:
from wiki.freepascal.org/X11#Examples.
Compiled with Freepascal 2.6.4-32
<langsyntaxhighlight lang="pascal">program xshowwindow;
{$mode objfpc}{$H+}
 
Line 1,455 ⟶ 1,751:
ModalShowX11Window('Hello, World!');
end.
</syntaxhighlight>
</lang>
 
=={{header|Perl}}==
=== X11::Protocol ===
<langsyntaxhighlight lang="perl">#!/usr/bin/perl -w
use strict;
use X11::Protocol;
Line 1,503 ⟶ 1,799:
for (;;) {
$X->handle_input;
}</langsyntaxhighlight>
 
=={{header|Phix}}==
Line 1,511 ⟶ 1,807:
=={{header|PicoLisp}}==
The following script works in the 32-bit version, using inlined C code
<langsyntaxhighlight PicoLisplang="picolisp">#!/usr/bin/picolisp /usr/lib/picolisp/lib.l
 
(load "@lib/misc.l" "@lib/gcc.l")
Line 1,558 ⟶ 1,854:
 
(simpleWin 300 200 "Hello World")
(bye)</langsyntaxhighlight>
 
=={{header|PythonPureBasic}}==
PureBasic does not have direct support for the X11 library like Xlib or XCB.
 
See [[Window_creation#PureBasic]].
 
=={{header|Python}}==
=== Xlib ===
{{field attention|Python|X11|Note (stolen from CLX example): This example was written in near-total ignorance of X11 by consulting the python-xlib's examples (included in its distribution) to find equivalents for the parts of the C example.}}
Line 1,574 ⟶ 1,874:
* python xlib_hello_world.py
 
<langsyntaxhighlight lang="python">from Xlib import X, display
 
class Window:
Line 1,607 ⟶ 1,907:
if __name__ == "__main__":
Window(display.Display(), "Hello, World!").loop()</langsyntaxhighlight>
 
=== XCB ===
{{libheader|python-xcb}}
 
<langsyntaxhighlight lang="python">import xcb
from xcb.xproto import *
import xcb.render
Line 1,654 ⟶ 1,954:
conn.disconnect()
 
main()</langsyntaxhighlight>
 
=={{header|Racket}}==
Using Racket's GUI which is implemented using gtk. It's not low level, but OTOH it works on Windows and OS X too.
 
<langsyntaxhighlight Racketlang="racket">#lang racket/gui
 
(define frame (new frame%
Line 1,671 ⟶ 1,971:
(send dc set-text-foreground "blue")
(send dc draw-text "Don't Panic!" 0 0))])
(send frame show #t)</langsyntaxhighlight>
 
=={{header|Raku}}==
Line 1,677 ⟶ 1,977:
{{trans|C}}
 
There is not yet a X11 library in Perl 6Raku but we can write the minimal C mappings for this task.
 
<syntaxhighlight lang="raku" perl6line>use NativeCall;
 
class Display is repr('CStruct') {
Line 1,740 ⟶ 2,040:
}
}
XCloseDisplay($display);</langsyntaxhighlight>
 
=={{header|Scala}}==
{{libheader|Scala}}<langsyntaxhighlight Scalalang="scala">import scala.swing.{ MainFrame, SimpleSwingApplication }
import scala.swing.Swing.pair2Dimension
 
Line 1,752 ⟶ 2,052:
preferredSize = ((200, 150))
}
}</langsyntaxhighlight>
 
=={{header|Standard ML}}==
Works with PolyML
<syntaxhighlight lang="standard ml">open XWindows ;
val dp = XOpenDisplay "" ;
val w = XCreateSimpleWindow (RootWindow dp) origin (Area {x=0,y=0,w=400,h=300}) 3 0 0xffffff ;
XMapWindow w;
XFlush dp ;
XDrawString w (DefaultGC dp) (XPoint {x=10,y=50}) "Hello World!" ;
XFlush dp ;</syntaxhighlight>
 
=={{header|Tcl}}==
Line 1,759 ⟶ 2,069:
===Low level interface===
{{libheader|critcl}}
<langsyntaxhighlight lang="tcl">package provide xlib 1
package require critcl
 
Line 1,823 ⟶ 2,133:
const char *str = Tcl_GetStringFromObj(msg, &len);
XDrawString(d, (Window)w, gc, x, y, str, len);
}</langsyntaxhighlight>
Note that this only does enough for this demo. A full adaptation is too long for RosettaCode...
 
This could then be used like this:
<langsyntaxhighlight lang="tcl">package require xlib
 
XOpenDisplay {}
Line 1,837 ⟶ 2,147:
}
XDestroyWindow $w
XCloseDisplay</langsyntaxhighlight>
===Higher level interface===
Just because there is a low level package does not mean that it is pleasant to use from Tcl code. Therefore this second package wraps it up inside a higher-level package that provides a more natural way of interacting.
<br>
{{works with|Tcl|8.6}} or {{libheader|TclOO}}
<langsyntaxhighlight lang="tcl">package require TclOO
package provide x11 1
 
Line 1,894 ⟶ 2,204:
}
}
}</langsyntaxhighlight>
This script puts the pieces together to carry out the details of the task.
<langsyntaxhighlight lang="tcl">package require x11
 
# With a display connection open, create and map a window
Line 1,916 ⟶ 2,226:
 
$w destroy
}</langsyntaxhighlight>
Improving this by adding more sophisticated event handling and more window methods is left as an exercise.
 
Line 1,922 ⟶ 2,232:
 
See [[Window_creation#TXR]].
 
=={{header|Wren}}==
{{trans|C}}
{{libheader|Xlib}}
<br>
As it's not currently possible for Wren-cli to access Xlib directly, we embed a Wren script in a C application to complete this task.
<syntaxhighlight lang="wren">/* Window_creation_X11.wren */
 
var KeyPressMask = 1 << 0
var ExposureMask = 1 << 15
var KeyPress = 2
var Expose = 12
 
foreign class XGC {
construct default(display, screenNumber) {}
}
 
foreign class XEvent {
construct new() {}
 
foreign eventType
}
 
foreign class XDisplay {
construct openDisplay(displayName) {}
 
foreign defaultScreen()
 
foreign rootWindow(screenNumber)
 
foreign blackPixel(screenNumber)
 
foreign whitePixel(screenNumber)
 
foreign selectInput(w, eventMask)
 
foreign mapWindow(w)
 
foreign closeDisplay()
 
foreign nextEvent(eventReturn)
 
foreign createSimpleWindow(parent, x, y, width, height, borderWidth, border, background)
 
foreign fillRectangle(d, gc, x, y, width, height)
 
foreign drawString(d, gc, x, y, string, length)
}
 
var xd = XDisplay.openDisplay("")
if (xd == 0) {
System.print("Cannot open display.")
return
}
var s = xd.defaultScreen()
var w = xd.createSimpleWindow(xd.rootWindow(s), 10, 10, 100, 100, 1, xd.blackPixel(s), xd.whitePixel(s))
xd.selectInput(w, ExposureMask | KeyPressMask)
xd.mapWindow(w)
var msg = "Hello, World!"
var e = XEvent.new()
while (true) {
xd.nextEvent(e)
var gc = XGC.default(xd, s)
if (e.eventType == Expose) {
xd.fillRectangle(w, gc, 20, 20, 10, 10)
xd.drawString(w, gc, 10, 50, msg, msg.count)
}
if (e.eventType == KeyPress) break
}
xd.closeDisplay()</syntaxhighlight>
<br>
We now embed this Wren script in the following C program, compile and run it.
<syntaxhighlight lang="c">/* gcc Window_creation_X11.c -o Window_creation_X11 -lX11 -lwren -lm */
 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <X11/Xlib.h>
#include "wren.h"
 
/* C <=> Wren interface functions */
 
void C_displayAllocate(WrenVM* vm) {
Display** pdisplay = (Display**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(Display*));
const char *displayName = wrenGetSlotString(vm, 1);
if (displayName == "") {
*pdisplay = XOpenDisplay(NULL);
} else {
*pdisplay = XOpenDisplay(displayName);
}
}
 
void C_gcAllocate(WrenVM* vm) {
GC *pgc = (GC *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(GC));
Display* display = *(Display**)wrenGetSlotForeign(vm, 1);
int s = (int)wrenGetSlotDouble(vm, 2);
*pgc = DefaultGC(display, s);
}
 
void C_eventAllocate(WrenVM* vm) {
wrenSetSlotNewForeign(vm, 0, 0, sizeof(XEvent));
}
 
void C_eventType(WrenVM* vm) {
XEvent e = *(XEvent *)wrenGetSlotForeign(vm, 0);
wrenSetSlotDouble(vm, 0, (double)e.type);
}
 
void C_defaultScreen(WrenVM* vm) {
Display* display = *(Display**)wrenGetSlotForeign(vm, 0);
int screenNumber = DefaultScreen(display);
wrenSetSlotDouble(vm, 0, (double)screenNumber);
}
 
void C_rootWindow(WrenVM* vm) {
Display* display = *(Display**)wrenGetSlotForeign(vm, 0);
int screenNumber = (int)wrenGetSlotDouble(vm, 1);
Window w = RootWindow(display, screenNumber);
wrenSetSlotDouble(vm, 0, (double)w);
}
 
void C_blackPixel(WrenVM* vm) {
Display* display = *(Display**)wrenGetSlotForeign(vm, 0);
int screenNumber = (int)wrenGetSlotDouble(vm, 1);
unsigned long p = BlackPixel(display, screenNumber);
wrenSetSlotDouble(vm, 0, (double)p);
}
 
void C_whitePixel(WrenVM* vm) {
Display* display = *(Display**)wrenGetSlotForeign(vm, 0);
int screenNumber = (int)wrenGetSlotDouble(vm, 1);
unsigned long p = WhitePixel(display, screenNumber);
wrenSetSlotDouble(vm, 0, (double)p);
}
 
void C_selectInput(WrenVM* vm) {
Display* display = *(Display**)wrenGetSlotForeign(vm, 0);
Window w = (Window)wrenGetSlotDouble(vm, 1);
long eventMask = (long)wrenGetSlotDouble(vm, 2);
XSelectInput(display, w, eventMask);
}
 
void C_mapWindow(WrenVM* vm) {
Display* display = *(Display**)wrenGetSlotForeign(vm, 0);
Window w = (Window)wrenGetSlotDouble(vm, 1);
XMapWindow(display, w);
}
 
void C_closeDisplay(WrenVM* vm) {
Display* display = *(Display**)wrenGetSlotForeign(vm, 0);
XCloseDisplay(display);
}
 
void C_nextEvent(WrenVM* vm) {
Display* display = *(Display**)wrenGetSlotForeign(vm, 0);
XEvent* pe = (XEvent*)wrenGetSlotForeign(vm, 1);
XNextEvent(display, pe);
}
 
void C_createSimpleWindow(WrenVM* vm) {
Display *display = *(Display**)wrenGetSlotForeign(vm, 0);
Window parent = (Window)wrenGetSlotDouble(vm, 1);
int x = (int)wrenGetSlotDouble(vm, 2);
int y = (int)wrenGetSlotDouble(vm, 3);
unsigned int width = (unsigned int)wrenGetSlotDouble(vm, 4);
unsigned int height = (unsigned int)wrenGetSlotDouble(vm, 5);
unsigned int borderWidth = (unsigned int)wrenGetSlotDouble(vm, 6);
unsigned long border = (unsigned long)wrenGetSlotDouble(vm, 7);
unsigned long background = (unsigned long)wrenGetSlotDouble(vm, 8);
Window w = XCreateSimpleWindow(display, parent, x, y, width, height, borderWidth, border, background);
wrenSetSlotDouble(vm, 0, (double)w);
}
 
void C_fillRectangle(WrenVM* vm) {
Display *display = *(Display**)wrenGetSlotForeign(vm, 0);
Drawable d = (Drawable)wrenGetSlotDouble(vm, 1);
GC gc = *(GC *)wrenGetSlotForeign(vm, 2);
int x = (int)wrenGetSlotDouble(vm, 3);
int y = (int)wrenGetSlotDouble(vm, 4);
unsigned int width = (unsigned int)wrenGetSlotDouble(vm, 5);
unsigned int height = (unsigned int)wrenGetSlotDouble(vm, 6);
XFillRectangle(display, d, gc, x, y, width, height);
}
 
void C_drawString(WrenVM* vm) {
Display *display = *(Display**)wrenGetSlotForeign(vm, 0);
Drawable d = (Drawable)wrenGetSlotDouble(vm, 1);
GC gc = *(GC *)wrenGetSlotForeign(vm, 2);
int x = (int)wrenGetSlotDouble(vm, 3);
int y = (int)wrenGetSlotDouble(vm, 4);
const char *string = wrenGetSlotString(vm, 5);
int length = (int)wrenGetSlotDouble(vm, 6);
XDrawString(display, d, gc, x, y, string, length);
}
 
WrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {
WrenForeignClassMethods methods;
methods.finalize = NULL;
if (strcmp(className, "XDisplay") == 0) {
methods.allocate = C_displayAllocate;
} else if (strcmp(className, "XGC") == 0) {
methods.allocate = C_gcAllocate;
} else if (strcmp(className, "XEvent") == 0) {
methods.allocate = C_eventAllocate;
} else {
methods.allocate = NULL;
}
return methods;
}
 
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "XEvent") == 0) {
if (!isStatic && strcmp(signature, "eventType") == 0) return C_eventType;
} else if (strcmp(className, "XDisplay") == 0) {
if (!isStatic && strcmp(signature, "defaultScreen()") == 0) return C_defaultScreen;
if (!isStatic && strcmp(signature, "rootWindow(_)") == 0) return C_rootWindow;
if (!isStatic && strcmp(signature, "blackPixel(_)") == 0) return C_blackPixel;
if (!isStatic && strcmp(signature, "whitePixel(_)") == 0) return C_whitePixel;
if (!isStatic && strcmp(signature, "selectInput(_,_)") == 0) return C_selectInput;
if (!isStatic && strcmp(signature, "mapWindow(_)") == 0) return C_mapWindow;
if (!isStatic && strcmp(signature, "closeDisplay()") == 0) return C_closeDisplay;
if (!isStatic && strcmp(signature, "nextEvent(_)") == 0) return C_nextEvent;
if (!isStatic && strcmp(signature, "createSimpleWindow(_,_,_,_,_,_,_,_)") == 0) return C_createSimpleWindow;
if (!isStatic && strcmp(signature, "fillRectangle(_,_,_,_,_,_)") == 0) return C_fillRectangle;
if (!isStatic && strcmp(signature, "drawString(_,_,_,_,_,_)") == 0) return C_drawString;
}
}
return NULL;
}
 
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
 
void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {
switch (errorType) {
case WREN_ERROR_COMPILE:
printf("[%s line %d] [Error] %s\n", module, line, msg);
break;
case WREN_ERROR_STACK_TRACE:
printf("[%s line %d] in %s\n", module, line, msg);
break;
case WREN_ERROR_RUNTIME:
printf("[Runtime Error] %s\n", msg);
break;
}
}
 
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
 
int main(int argc, char **argv) {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.errorFn = &errorFn;
config.bindForeignClassFn = &bindForeignClass;
config.bindForeignMethodFn = &bindForeignMethod;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "Window_creation_X11.wren";
char *script = readFile(fileName);
WrenInterpretResult result = wrenInterpret(vm, module, script);
switch (result) {
case WREN_RESULT_COMPILE_ERROR:
printf("Compile Error!\n");
break;
case WREN_RESULT_RUNTIME_ERROR:
printf("Runtime Error!\n");
break;
case WREN_RESULT_SUCCESS:
break;
}
wrenFreeVM(vm);
free(script);
return 0;
}</syntaxhighlight>
 
{{out}}
<pre>Same as C example.</pre>
 
=={{header|Yabasic}}==
<syntaxhighlight lang="vbnet">open window 300,200
 
text 150, 100, "Hello World"
 
rectangle 10,10 to 90,90
fill rectangle 40,40,60,60
 
clear screen
 
inkey$
close window</syntaxhighlight>
 
{{omit from|ACL2}}
2,122

edits