Creare una finestra mediante le funzioni del API di X11

Da Gambas-it.org - Wikipedia.

Con le risorse del API di X11 è possibile creare una finestra ed interagire con essa.

Sarà necessario richiamare nell'applicazione Gambas la libreria dinamica condivisa di X11: "libX11.so.6.4.0 ".

Gli Eventi nel sistema X11

Ogni tipo di Evento ha una propria Struttura, che in realtà è una "Union" tipica del linguaggio C. Nella libreria di X11 tutte le Strutture degli Eventi hanno in comune questi primi 5 membri: [Nota 1]

typedef struct {
        int type;
        unsigned long serial;
        Bool send_event;
        Display *display;
        Window window;
} XAnyEvent;

Pertanto, nella ricostruzione in Gambas della Struttura tipica (la "Union") di un determinato Evento bisognerà tenerne conto.
A questi primi 5 membri comuni seguiranno i restanti caratteristici dell'Evento specifico.

Poiché la dimensione totale della Union è pari a 192 byte, per evitare un errore alla chiusura della finestra creata, è necessario colmare la Struttura, ricostruita in Gambas, con un numero di byte sino a raggiungere la dimensione totale della Union medesima (192 byte).


Esempi pratici

Mostriamo di seguito alcuni esempi pratici, nei quali ssaranno create delle finestre, sulle quali si potrà agire attraverso la gestione di uno specifico Evento.

Creare semplicemente una finestra colorata

Mostriamo di seguito un breve codice con le risorse essenziali della libreria X11 per creare una semplice finestra di colore rosso. Se si cliccherà al suo interno con un qualsiasi tasto del mouse, la finestra verrà distrutta.

Library "libX11:6.4.0"

Private Const ButtonPressMask As Long = 4
Private Enum KeyPress = 2, KeyRelease, ButtonPress, ButtonRelease, MotionNotify, EnterNotify,
              LeaveNotify, FocusIn, FocusOut, KeymapNotify, Expose, GraphicsExpose, NoExpose

' Display *XOpenDisplay(char *display_name)
' Opens a connection to the X server that controls a display.
Private Extern XOpenDisplay(display As Pointer) As Pointer
 
' Window XDefaultRootWindow(Display *display)
' Return the root window for the default screen.
Private Extern XDefaultRootWindow(display As Pointer) As Integer

' Window XCreateSimpleWindow(Display *display, Window parent, int x, int y, unsigned int width, unsigned int height, unsigned int border_width, unsigned long border, unsigned long background)
' Creates an unmapped InputOutput subwindow for a specified parent window, returns the window ID of the created window.
Private Extern XCreateSimpleWindow(display As Pointer, parent As Long, x As Integer, y As Integer, width As Integer, height As Integer, border_width As Integer, border As Integer, background As Long) As Integer

' XSelectInput (Display *display, Window w, long event_mask)
' Requests that the X server report the events associated with the specified Event mask.
Private Extern XSelectInput(display As Pointer, w As Long, event_mask As Long)

' XMapRaised (Display *display, Window w)
' Raises the specified window to the top of the stack.
Private Extern XMapRaised(display As Pointer, w As Long)

' XNextEvent (Display *display, XEvent *event_return)
' Gets the next event and remove it from the queue
Private Extern XNextEvent(display As Pointer, event_return As Pointer)

' XDestroyWindow(Display *display, Window w)
' Destroys the specified window as well as all of its subwindows
Private Extern XDestroyWindow(display As Pointer, w As Long)

' XCloseDisplay(Display *display)
' Closes the connection to the X server for the display specified in the Display structure and destroys all windows.
Private Extern XCloseDisplay(display As Pointer)
  

Public Sub Main()

 Dim disp, ev As Pointer
 Dim screen As Integer
 Dim id As Long

' Apre la connessione con il server display del sistema grafico X:
 disp = XOpenDisplay(0)
 If disp == 0 Then Error.Raise("Impossibile aprire il server X !")
   
' Crea la finestra secondo i parametri previsti dalla funzione. L'ultimo parametro imposta il colore di fondo della finestra:
 id = XCreateSimpleWindow(disp, XDefaultRootWindow(disp), 0, 0, 300, 200, 0, 0, &FF0000)
 Print "ID della finestra creata: "; Hex(id, 6)

' Dice al server display quali eventi deve vedere:
 XSelectInput(disp, id, ButtonPressMask)
  
' Apre la finestra sullo schermo. Si può utilizzare anche la funzione "XMapWindow(display, w)":
 XMapRaised(disp, id)
  
' Alloca un'area di memoria pari alla Struttura esterna (192 byte).
' Poiché sarà utilizzato soltanto il valore del primo valore di detta Struttura esterna, si utilizzerà quest'area di memoria riservata al posto della Struttura predetta:
 ev = Alloc(SizeOf(gb.Byte), 192)
 
' Inizia il ciclo, restando in attesa di un evento stabilito con la precedente funzione XSelectInput():
 Repeat
   XNextEvent(disp, ev)
' Se si pone il puntatore del mouse all'interno della finestra e viene premuto un qualsiasi tasto del mouse, chiude la finestra:
 Until Int@(ev) == ButtonPress
 
' Chiude la finestra e libera la memoria:
 Free(ev)
 XDestroyWindow(disp, id)
 XCloseDisplay(disp)
   
End


In quest'altro esempio, molto simile al precedente, la chiusura della finestra avverrà solo se si premerà con il mouse sulla consueta X posta nell'angolo in alto a destra della finestra medesima:

Library "libX11:6.4.0"

Public Struct XButtonEvent
  type As Integer
  serial As Long
  send_event As Boolean
  display As Pointer
  window_ As Long
  root As Long
  subwindow As Long
  time_ As Long
  x As Integer
  y As Integer
  x_root As Integer
  y_root As Integer
  state As Integer
  keycode As Integer
  same_screen As Boolean
  pad[12] As Long         ' Completa la "Struttura" sino a 192 byte
End Struct

Private Const ButtonPressMask As Long = 4
Private Enum KeyPress = 2, KeyRelease, ButtonPress, ButtonRelease, MotionNotify, EnterNotify,
             LeaveNotify, FocusIn, FocusOut, KeymapNotify, Expose, GraphicsExpose, NoExpose

' Display *XOpenDisplay(char *display_name)
' Opens a connection to the X server that controls a display.
Private Extern XOpenDisplay(display As Pointer) As Pointer
 
' Window XRootWindow(Display *display, int screen_number)
' Return the root window.
Private Extern XDefaultRootWindow(display As Pointer) As Integer

' Window XCreateSimpleWindow(Display *display, Window parent, int x, int y, unsigned int width, unsigned int height, unsigned int border_width, unsigned long border, unsigned long background)
' Creates an unmapped InputOutput subwindow for a specified parent window, returns the window ID of the created window.
Private Extern XCreateSimpleWindow(display As Pointer, parent As Long, x As Integer, y As Integer, width As Integer, height As Integer, border_width As Integer, border As Integer, background As Long) As Integer

' XSelectInput (Display *display, Window w, long event_mask)
' Requests that the X server report the events associated with the specified Event mask.
Private Extern XSelectInput(display As Pointer, w As Long, event_mask As Long)

' XMapRaised (Display *display, Window w)
' Raises the specified window to the top of the stack.
Private Extern XMapRaised(display As Pointer, w As Long)

' Atom XInternAtom(Display *display, char *atom_name, Bool only_if_exists)
' Returns the atom identifier associated with the specified atom_name string.
Private Extern XInternAtom(display As Pointer, atom_name As String, only_if_exists As Boolean) As Long

' Status XSetWMProtocols(Display *display, Window w, Atom *protocols, int count)
' Replaces the WM_PROTOCOLS property on the specified window with the list of atoms specified by the protocols argument.
Private Extern XSetWMProtocols(display As Pointer, w As Long, protocols As Pointer, count As Integer) As Integer

' XNextEvent (Display *display, XEvent *event_return)
' Gets the next event and remove it from the queue
Private Extern XNextEvent(display As Pointer, event_return As XButtonEvent)

' XDestroyWindow(Display *display, Window w)
' Destroys the specified window as well as all of its subwindows
Private Extern XDestroyWindow(display As Pointer, w As Long)

' XCloseDisplay(Display *display)
' Closes the connection to the X server for the display specified in the Display structure and destroys all windows.
Private Extern XCloseDisplay(display As Pointer)
  

Public Sub Main()

 Dim disp As Pointer
 Dim ev As New XButtonEvent
 Dim id, atom As Long

' Apre la connessione con il server display del sistema grafico X:
 disp = XOpenDisplay(0)
 If disp == 0 Then Error.Raise("Impossibile aprire il server X !")
   
' Crea la finestra secondo i parametri previsti dalla funzione. L'ultimo parametro imposta il colore di fondo della finestra:
 id = XCreateSimpleWindow(disp, XDefaultRootWindow(disp), 0, 0, 300, 200, 0, 0, &FF0000)
 Print "ID della finestra creata: "; Hex(id, 6)

' Dice al server display quali eventi deve vedere:
 XSelectInput(disp, id, ButtonPressMask)
  
' Apre la finestra sullo schermo. Si può utilizzare anche la funzione "XMapWindow(display, w)":
 XMapRaised(disp, id)
  
' Ottiene il numero identificativo dell'evento della chiusura della finestra, quando si clicca sulla X in alto a destra:
 atom = XInternAtom(disp, "WM_DELETE_WINDOW", False)
  
 XSetWMProtocols(disp, id, VarPtr(atom), 1)
    
' Inizia il ciclo, restando in attesa di un evento stabilito con la precedente funzione XSelectInput():
 Repeat
   XNextEvent(disp, ev)
' Si esce dal ciclo, solo se si clicca con il mouse sulla X in alto a destra della finestra:
 Until ev.time_ == atom
   
' Chiude la finestra e libera la memoria:
 XDestroyWindow(disp, id)
 XCloseDisplay(disp)
  
End


Creare una finestra colorata contenente disegni geometrici e caratteri alfabetici, con impostazione del puntatore del mouse

In quest'altro esempio, più complesso, verrà creata una finestra di colore rosso, nella quale saranno disegnate figure geometriche e caratteri testuali. Sarà, inoltre, possibile intercettare alcuni eventi provenienti dalla tastiera e dal mouse. Verrà anche impostato un diverso aspetto del puntatore del mouse, impostato fra uno dei disegni previsti nel file header "x11/cursorfont.h".
Per chiudere la finestra, bisognerà premere il tasto "q" della tastiera.

Private disp As Pointer
Private wId As Long
Private gc As Pointer


Library "libX11:6.4.0"

Public Struct XKeyEvent
  type As Integer
  serial As Long
  send_event As Boolean
  display As Pointer
  window_ As Long
  root As Long
  subwindow As Long
  time_ As Long
  x As Integer
  y As Integer
  x_root As Integer
  y_root As Integer
  state As Integer
  keycode As Integer
  same_screen As Boolean
  pad[12] As Long         ' Completa la "Struttura" sino a 192 byte
End Struct

Public Struct XFont
  ext_data As Long
  fid As Pointer
  direction As Byte
  min_char_or_byte2 As Byte
  max_char_or_byte2 As Byte
  min_byte1 As Byte
  max_byte1 As Byte
  all_chars_exist As Boolean
  default_char As Byte
  n_properties As Byte
  properties As Pointer
  min_bounds As Pointer
  max_bounds As Pointer
  per_char As Pointer
  ascent As Integer
  descent As Integer
End Struct

Private Const ExposureMask As Long = 32768
Private Const KeyPressMask As Long = 1
Private Const ButtonPressMask As Long = 4
Private Enum KeyPress = 2, KeyRelease, ButtonPress, ButtonRelease, MotionNotify, EnterNotify, LeaveNotify, FocusIn, FocusOut, KeymapNotify, Expose, GraphicsExpose, NoExpose
Private Enum FillSolid = 0, FillTiled, FillStippled, FillOpaqueStippled   ' fillStyle

' Display *XOpenDisplay(char *display_name)
' Opens a connection to the X server that controls a display.
Private Extern XOpenDisplay(display As Pointer) As Pointer

' XCloseDisplay(Display *display)
' Closes the connection to the X server for the display specified in the Display structure and destroys all windows.
Private Extern XCloseDisplay(display As Pointer)

' int XDefaultScreen (Display *display)
' returns the default screen number referenced by the XOpenDisplay function.
Private Extern XDefaultScreen(display As Pointer) As Integer

' unsigned long XWhitePixel (Display *display, int screen_number)
' returns the white pixel value for the specified screen.
Private Extern XWhitePixel(display As Pointer, screen_number As Integer) As Long

' unsigned long XBlackPixel (Display *display, int screen_number)
' returns the black pixel value for the specified screen.
Private Extern XBlackPixel(display As Pointer, screen_number As Integer) As Long

' Window XDefaultRootWindow(Display *display)
' Return the root window for the default screen.
Private Extern XDefaultRootWindow(display As Pointer) As Integer

' Window XCreateSimpleWindow(Display *display,  Window parent, int x, int y, unsigned int width, unsigned int height, unsigned int border_width, unsigned long border, unsigned long background)
' creates an unmapped InputOutput subwindow for a specified parent window, returns the window ID of the created window.
Private Extern XCreateSimpleWindow(display As Pointer, parent As Long, x As Integer, y As Integer, width As Integer, height As Integer, border_width As Integer, border As Integer, background As Long) As Integer 

' XSetStandardProperties (Display *display, Window w, char *window_name, char *icon_name, Pixmap icon_pixmap, char **argv, int argc, XSizeHints *hints)
' specifies a minimum set of properties describing the simplest application.
Private Extern XSetStandardProperties(display As Pointer, w As Long, window_name As String, icon_name As String, icon_pixmap As Integer, argv As String, argc As Integer, hints As Pointer)

' XSelectInput (Display *display, Window w, long event_mask)
' requests that the X server report the events associated with the specified Event mask.
Private Extern XSelectInput(display As Pointer, w As Integer, event_mask As Long)

' GC XCreateGC(Display *display, Drawable d, unsigned long valuemask, XGCValues *values)
' creates a graphics context and returns a GC.
Private Extern XCreateGC(display As Pointer, w As Integer, valuemask As Long, values As Pointer) As Pointer

' XSetForeground (Display *display, GC gc, unsigned long foreground)
' sets the foreground.
Private Extern XSetForeground(display As Pointer, gc As Pointer, foreground As Long)

' char ** XListFonts(Display *display, char *pattern, int maxnames, int *actual_count_return)
' returns an array of available font names.
Private Extern XListFonts(display As Pointer, pattern As String, maxnames As Integer, actual_count_return As Pointer) As Pointer

' XFontStruct * XLoadQueryFont(Display *display, char *name)
' opens(loads)the specified font.
Private Extern XLoadQueryFont(display As Pointer, nameFont As String) As XFont

' XSetFont(Display *display, GC gc, Font font)
' Assigns a Font to a Graphics Context.
Private Extern XSetFont(display As Pointer, gcP As Pointer, fontP As Pointer)

' XSetFillStyle(Display *display, GC gc, int fill_style)
' changes the fill style of GC.
Private Extern XSetFillStyle(display As Pointer, gc As Pointer, fill_style As Integer)

' XClearWindow(Display *display, Window w)
' clears the entire area in the specified window.
Private Extern XClearWindow(display As Pointer, w As Long)

' XMapRaised (Display *display, Window w)
' raises the specified window to the top of the stack.
Private Extern XMapRaised(display As Pointer, w As Long)

' Cursor XCreateFontCursor(Display *display, unsigned int shape)
' Provides a set of standard cursor shapes in a special font named cursor.
Private Extern XCreateFontCursor(display As Pointer, shape As Integer) As Integer

' XDefineCursor(Display *display, Window w, Cursor cursor)
' If a cursor is set, it will be used when the pointer is in the window.
Private Extern XDefineCursor(display As Pointer, w As Long, cursorI As Integer) As Integer

' XNextEvent (Display *display, XEvent *event_return)
' gets the next event and remove it from the queue
Private Extern XNextEvent(display As Pointer, event_return As XKeyEvent)

' int XLookupString(XKeyEvent *event_struct, char *buffer_return, int bytes_buffer, KeySym *keysym_return, XComposeStatus *status_in_out)
' translates a key event to a KeySym and a string.
Private Extern XLookupString(event_struct As XKeyEvent, buffer_return As Byte[], bytes_buffer As Integer, keysym_return As Pointer, status_in_out As Pointer) As Integer

' XDrawPoint(Display *display, Drawable d, GC gc, int x, int y)
' draws a single point into the specified drawable
Private Extern XDrawPoint(display As Pointer, w As Long, gcP As Pointer, x1 As Integer, y1 As Integer)

' XDrawLine(Display *display, Drawable d, GC gc, int x1, int y1, int x2, int y2)
' draws a line between the specified set of points (x1, y1) and (x2, y2).
Private Extern XDrawLine(display As Pointer, w As Long, gc As Pointer, x1 As Integer, y1 As Integer, x2 As Integer, y2 As Integer)

' XDrawRectangle(Display *display, Drawable d, GC gc, int x, int y, unsigned int width, unsigned int height)
' draws the outlines of the specified rectangle.
Private Extern XDrawRectangle(display As Pointer, w As Integer, gc As Pointer, xI As Integer, yI As Integer, widthI As Integer, heightI As Integer)

' XFillRectangle(Display *display, Drawable d, GC gc, int x, int y, unsigned int width, unsigned int height)
' fills the specified rectangle
Private Extern XFillRectangle(display As Pointer, w As Long, gc As Pointer, xI As Integer, yI As Integer, widthI As Integer, heightI As Integer)

' XDrawArc(Display *display, Drawable d, GC gc, int x, int y, unsigned int width, unsigned int height, int angle1, int angle2)
' draws an arc.
Private Extern XDrawArc(display As Pointer, w As Long, gc As Pointer, xI As Integer, yI As Integer, widthI As Integer, heightI As Integer, angle1 As Integer, angle2 As Integer)

' XFillArc(Display *display, Drawable d, GC gc, int x, int y, unsigned int width, unsigned int height, int angle1, int angle2)
' fills the specified arc.
Private Extern XFillArc(display As Pointer, w As Long, gc As Pointer, xI As Integer, yI As Integer, widthI As Integer, heightI As Integer, angle1 As Integer, angle2 As Integer)

' XDrawString(Display *display, Drawable d, GC gc, int x, int y, char *string, int length)
' draws a text.
Private Extern XDrawString(display As Pointer, w As Long, gc As Pointer, x As Integer, y As Integer, string_ As Pointer, length As Integer)

' XFreeGC(Display *display, GC gc)
' destroys the specified GC as well as all the associated storage.
Private Extern XFreeGC(display As Pointer, gc As Pointer)

' XDestroyWindow(Display *display, Window w)
' destroys the specified window as well as all of its subwindows
Private Extern XDestroyWindow(display As Pointer, w As Long)
 

Public Sub Main()

 Dim screen, key, cursor As Integer
 Dim pxW, pxB As Long
 Dim testo As New Byte[255]
 Dim ev As New XKeyEvent
 Dim xfon As New XFont
 Dim scriptum As String = "testo qualsiasi"

' Apre la connessione con il server display del sistema grafico X:
 disp = XOpenDisplay(0)
 If disp == 0 Then Error.Raise("Impossibile aprire il server X !")
 
 screen = XDefaultScreen(disp)
 pxW = XWhitePixel(disp, screen)
 pxB = XBlackPixel(disp, screen)
    
' Crea la finestra secondo i parametri previsti dalla funzione.
' L'ultimo parametro imposta il colore di fondo della finestra:
 wId = XCreateSimpleWindow(disp, XDefaultRootWindow(disp), 0, 0, 300, 200, 5, pxW, &FF0000)
 Print "ID della finestra creata: "; Hex(wId, 6)
   
 XSetStandardProperties(disp, wId, "Prova creazione finestra", "Nome icona finestra", 0, Null, 0, Null)
   
' Dice al server display quali eventi deve vedere:
 XSelectInput(disp, wId, ExposureMask Or KeyPressMask Or ButtonPressMask)
   
' Crea un nuovo contesto grafico:
 gc = XCreateGC(disp, wId, 0, 0)
 If gc == 0 Then Error.Raise("Impossibile creare un nuovo contesto grafico !")

' Imposta il colore degli elementi grafici all'interno della finestra:
 XSetForeground(disp, gc, &00FF00)

 elencoFont()

' Imposta il font per i caratteri del testo grafico:
 xfon = XLoadQueryFont(disp, "*bitstream*")
 If IsNull(xFon) Then Error.Raise("Impossibile caricare il font !")
 
 XSetFont(disp, gc, xfon.fid)
 XSetFillStyle(disp, gc, FillSolid)
   
 redraw()
   
' Apre la finestra sullo schermo. Si può utilizzare anche la funzione "XMapWindow(display, w)":
 XMapRaised(disp, wId)

' Entrando il cursore del mouse nella finestra, esso cambia aspetto, impostando quello che nel file header ".../X11/cursorfont.h" ha il valore 10 tra quelli visibili nella pagina "http://tronche.com/gui/x/xlib/appendix/b/":
 cursor = XCreateFontCursor(disp, 10)

 XDefineCursor(disp, wId, cursor)
 
 While True
   XNextEvent(disp, ev)
   Select Case ev.type
     Case Expose
' La finestra mostrata deve essere ripulita:
       redraw()
' Disegna un punto all'interno del quadrato:
       XDrawPoint(disp, wId, gc, 70, 120)
' Disegna una linea:
       XDrawLine(disp, wId, gc, 10, 10, 40, 60)
' In questo caso disegna un quadrato:
       XDrawRectangle(disp, wId, gc, 50, 100, 40, 40)
' Disegna un rettangolo colorato di bianco:
       XFillRectangle(disp, wId, gc, 200, 30, 60, 40)
' Disegna un arco:
       XDrawArc(disp, wId, gc, 100, 150, 60, 40, 0, 360 * 20)
' Disegna un arco riempito di colore bianco:
       XFillArc(disp, wId, gc, 40, 20, 60, 40, 0, 360 * 20)
' Disegna un cerchio:
       XDrawArc(disp, wId, gc, 200, 100, 50, 50, 0, 360 * 64)
' Disegna un cerchio riempito di colore bianco:
       XFillArc(disp, wId, gc, 110, 40, 50, 50, 0, 360 * 64)
' Disegna una stringa di caratteri:
       XDrawString(disp, wId, gc, 20, 170, scriptum, Len(scriptum))
     Case KeyPress
       XLookupString(ev, testo, 255, VarPtr(key), Null)
       If testo[0] == Asc("q") Then
         chiude_X()
         Print "E' stato premuto il tasto: "; Chr(testo[0]), key
       Else
' Disegna il carattere del tasto premuto alle coordinate del puntatore del mouse:
         XDrawString(disp, wId, gc, ev.x, ev.y, Chr(key), 1)
       Endif
     Case ButtonPress     ' Indica le coordinate ove è stato premuto il tasto del mouse
       With ev
         Print "E' stato premuto il tasto del mouse alle seguenti coordinate:\n"; .x; " pixel dal margine sinistro della finestra;"
         Print .y; " pixel dal margine superiore della finestra;"
         Print .x_root; " pixel dal margine sinistro dello schermo;"
         Print .y_root; " pixel dal margine superiore dello schermo." 
       End With
       redraw()
   End Select
 Wend
   
End 

Private Procedure elencoFont()

 Dim po As Pointer
 Dim num_fonts, i As Integer
 Dim b As Byte
 
 po = XListFonts(disp, "*itstr*", 8196, VarPtr(num_fonts))
 If po == 0 Then Error.Raise("Impossibile caricare i font !")
 
 po = Pointer@(po)
  
' Dereferenziamo il "puntatore":
 For i = 0 To 8196
   b = Byte@(po + i)
   If b == 0 Then
     Print
   Else
     Print Chr(b);
   Endif
 Next
   
End 
 
Private Procedure redraw()
 
' Pulisce la superficie della finestra da ogni elemento presente:
 XClearWindow(disp, wId)
 
End


Private Procedure chiude_X()

 XFreeGC(disp, gc)
' Chiude la finestra:
 XDestroyWindow(disp, wId)
 XCloseDisplay(disp)
' "Quit" consente di terminare anche il programma medesimo:
 Quit
 
End


Creare una semplice finestra colorata, con il puntatore del mouse avente un disegno impostato liberamente da noi

In questo esempio quando si entrerà con il puntatore del mouse all'interno della finestra, l'aspetto del puntatore cambierà in quello di una matita, secondo un disegno da noi impostato.
Per chiudere la finestra, si dovrà cliccare al suo interno.

Library "libX11:6.4.0"

Public Struct XColor
  pixel As Long
  red As Short
  green As Short
  blue As Short
  flags As Byte
  pad As Byte
End Struct

Public Struct XButtonEvent
  type As Integer
  serial As Long
  send_event As Boolean
  display As Pointer
  window_ As Long
  root As Long
  subwindow As Long
  time_ As Long
  x As Integer
  y As Integer
  x_root As Integer
  y_root As Integer
  state As Integer
  keycode As Integer
  same_screen As Boolean
  pad[12] As Long         ' Completa la "Struttura" sino a 192 byte
End Struct

Private Const ButtonPressMask As Long = 4
Private Enum KeyPress = 2, KeyRelease, ButtonPress, ButtonRelease, MotionNotify, EnterNotify,
             LeaveNotify, FocusIn, FocusOut, KeymapNotify, Expose, GraphicsExpose, NoExpose

' Display *XOpenDisplay(char *display_name)
' Opens a connection to the X server that controls a display.
Private Extern XOpenDisplay(display As Pointer) As Pointer

' Screen *XDefaultScreenOfDisplay(Display *display)
' Returns a pointer to the default screen.
Private Extern XDefaultScreenOfDisplay(display As Pointer) As Pointer
 
' Window XDefaultRootWindow(Display *display)
' Return the root window for the default screen.
Private Extern XDefaultRootWindow(display As Pointer) As Integer

' Window XCreateSimpleWindow(Display *display, Window parent, int x, int y, unsigned int width, unsigned int height, unsigned int border_width, unsigned long border, unsigned long background)
' creates an unmapped InputOutput subwindow for a specified parent window, returns the window ID of the created window.
Private Extern XCreateSimpleWindow(display As Pointer, parent As Long, x As Integer, y As Integer, width As Integer, height As Integer, border_width As Integer, border As Integer, background As Long) As Integer
 
' XMapRaised (Display *display, Window w)
' raises the specified window to the top of the stack.
Private Extern XMapRaised(display As Pointer, w As Long)

' Pixmap XCreatePixmap(display *display, Drawable d, unsigned int width, unsigned int height, unsigned int depth)
' Creates a pixmap of the width, height, and depth you specified and returns a pixmap ID that identifies it.
Private Extern XCreatePixmap(display As Pointer, w As Long, width As Integer, height As Integer, depth As Integer) As Pointer

' Status XLookupColor(Display *display, Colormap colormap, char *color_name, XColor *exact_def_return, XColor *screen_def_return)
' Looks up the string name of a color with respect to the screen associated with the specified colormap.
Private Extern XLookupColor(display As Pointer, colormap As Pointer, color_name As String, exact_def_return As XColor, screen_def_return As XColor) As Integer

' Colormap XDefaultColormapOfScreen(Screen *screen)
' Returns the default colormap ID on the specified screen.
Private Extern XDefaultColormapOfScreen(scr As Pointer) As Pointer

' Pixmap XCreatePixmapFromBitmapData(display *display, Drawable d, char *data, unsigned int width, unsigned int height, unsigned long fg, unsigned long bg, unsigned int depth)
' Creates a pixmap of the given depth and then does a bitmap-format XPutImage() of the data into it.
Private Extern XCreatePixmapFromBitmapData(display As Pointer, w As Pointer, data As Byte[], width As Integer, height As Integer, fg As Long, bg As Long, depth As Integer) As Pointer

' Cursor XCreatePixmapCursor(Display *display, Pixmap source, Pixmap mask, XColor *foreground_color, XColor *background_color, unsigned int x, unsigned int y)
' Creates a cursor and returns the cursor ID associated with it.
Private Extern XCreatePixmapCursor(display As Pointer, source As Pointer, mask As Pointer, foreground_color As XColor, background_color As XColor, x As Integer, y As Integer) As Integer

' XDefineCursor(Display *display, Window w, Cursor cursor)
' If a cursor is set, it will be used when the pointer is in the window.
Private Extern XDefineCursor(display As Pointer, w As Long, cursorI As Integer) As Integer
 
' XSelectInput (Display *display, Window w, long event_mask)
' requests that the X server report the events associated with the specified Event mask.
Private Extern XSelectInput(display As Pointer, w As Long, event_mask As Long)
 
' XNextEvent (Display *display, XEvent *event_return)
' gets the next event and remove it from the queue
Private Extern XNextEvent(display As Pointer, event_return As XButtonEvent)

' XDestroyWindow(Display *display, Window w)
' destroys the specified window as well as all of its subwindows
Private Extern XDestroyWindow(display As Pointer, w As Long)

' XCloseDisplay(Display *display)
' Closes the connection to the X server for the display specified in the Display structure and destroys all windows.
Private Extern XCloseDisplay(display As Pointer)
 

Public Sub Main()

 Dim dsp, screen, pixmap, matita, matita_mask As Pointer
 Dim id, cursore_matita As Integer
 Dim inut, cursore_primopiano, sfondo_cursore As New XColor
 Dim ev As New XButtonEvent
 Dim matita_bits As Byte[] = [&00, &70, &00, &88, &00, &8C, &00, &96, &00, &69, &80, &30, &40, &10, &20, &08,
                              &10, &04, &08, &02, &08, &01, &94, &00, &64, &00, &1E, &00, &06, &00, &00, &00]
 Dim matita_mask_bits As Byte[] = [&00, &F8, &00, &FC, &00, &FE, &00, &FF, &80, &FF, &C0, &7F, &E0, &3F, &F0,
                                   &1F, &F8, &0F, &FC, &07, &FC, &03, &FE, &01, &FE, &00, &7F, &00, &1F, &00, &07, &00]
 Dim matita_width As Integer = 16
 Dim matita_height As Integer = 16
 Dim matita_X As Integer = 1
 Dim matita_Y As Integer = 15

 dsp = XOpenDisplay(0)
 If dsp == 0 Then Error.Raise("Impossibile connettersi al server X !")
 
 screen = XDefaultScreenOfDisplay(dsp)
 
 id = XCreateSimpleWindow(dsp, XDefaultRootWindow(dsp), 0, 0, 300, 200, 0, 0, &FF0000)
 Print "ID della finestra creata: "; Hex(id, 6)
 
 XMapRaised(dsp, id)
 
' Crea le pixmap per il cursore del mouse:
 pixmap = XCreatePixmap(dsp, XDefaultRootWindow(dsp), 1, 1, 1)
  
 XLookupColor(dsp, XDefaultColormapOfScreen(screen), "yellow", inut, cursore_primopiano)
 XLookupColor(dsp, XDefaultColormapOfScreen(screen), "blue", inut, sfondo_cursore)
 
 matita = XCreatePixmapFromBitmapData(dsp, pixmap, matita_bits, matita_width, matita_height, 1, 0, 1)
 matita_mask = XCreatePixmapFromBitmapData(dsp, pixmap, matita_mask_bits, matita_width, matita_height, 1, 0, 1)
   
 cursore_matita = XCreatePixmapCursor(dsp, matita, matita_mask, cursore_primopiano, sfondo_cursore, matita_X, matita_Y)
 
 XDefineCursor(dsp, id, cursore_matita)
 
 XSelectInput(dsp, id, ButtonPressMask)
 
 Repeat
   XNextEvent(dsp, ev)
 Until ev.type == ButtonPress
    
' Chiude la finestra:
 XDestroyWindow(dsp, id)
 XCloseDisplay(dsp)

End


Note

[1] Vedere questa pagina: https://tronche.com/gui/x/xlib/events/structures.html


Riferimenti