Este foro usa cookies
Este foro utiliza cookies para almacenar su información de inicio de sesión si está registrado y su última visita si no lo está. Las cookies son pequeños documentos de texto almacenados en su computadora; las cookies establecidas por este foro solo se pueden usar en este sitio web y no representan ningún riesgo de seguridad. Las cookies en este foro también rastrean los temas específicos que ha leído y la última vez que los leyó. Si Ud. continúa navegando, entenderemos que acepta todas las cookies.

Se almacenará una cookie en su navegador, independientemente de la elección, para evitar que se le vuelva a hacer esta pregunta. Podrá cambiar la configuración de sus cookies en cualquier momento utilizando el enlace en el pie de página.

El foro antiguo se encuentra accesible desde https://foro.gambas-es.org en modo de solo lectura.

Calificación:
  • 0 voto(s) - 0 Media
  • 1
  • 2
  • 3
  • 4
  • 5

Calculadora simple utilizando los recursos de API de X11
#1

El siguiente código es un ejemplo simple del uso de los recursos externos del API de X11.
Sólo funciona con sistemas de 64 bits.
El presente código es la traducción a Gambas con variaciones y integraciones, del código original, escrito en lenguaje C, del proyecto de Kjetil Erga, llamado: "Xlib Calculator ".

GAMBAS
  1. Private Const BLOCCHI_X As Integer = 4
  2. Private Const BLOCCHI_Y As Integer = 6
  3. Private Const SPAZIO As Integer = 5
  4. Private valore_mostrato As Float
  5. Private valore_buffer As Float
  6. Private operazione As Byte
  7. Private modo_decimale As Integer
  8. Private disp_mod As Integer
  9. Private simboli As String[][] = [["C", "/", "*", "-"], ["7", "8", "9", "+"], ["4", "5", "6", " "], ["1", "2", "3", " "], ["0", " ", ".", "="]]
  10.  
  11.  
  12. Library "libX11:6.3.0"
  13.  
  14. Private Const ExposureMask As Long = 32768
  15. Private Const KeyPressMask As Long = 1
  16. Private Const ButtonPressMask As Long = 4
  17. Private Const ClientMessage As Integer = 33
  18.  
  19. Private Enum KeyPress = 2, KeyRelease, ButtonPress, ButtonRelease, MotionNotify, EnterNotify, LeaveNotify,
  20.              FocusIn, FocusOut, KeymapNotify, Expose, GraphicsExpose, NoExpose
  21.  
  22. ' Display *XOpenDisplay(char *display_name)
  23. ' Opens a connection to the X server that controls a display.
  24. Private Extern XOpenDisplay(display As Pointer) As Pointer
  25.  
  26. ' int XDefaultScreen(Display *display)
  27. ' Return the default screen number referenced by the XOpenDisplay() function.
  28. Private Extern XDefaultScreen(display As Pointer) As Integer
  29.  
  30. ' Window XRootWindow(Display *display, int screen_number)
  31. ' Return the root window for the default screen.
  32. Private Extern XRootWindow(display As Pointer, screen_number As Integer) As Integer
  33.  
  34. ' 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)
  35. ' creates an unmapped InputOutput subwindow for a specified parent window, returns the window ID of the created window.
  36. 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
  37.  
  38. ' XSelectInput (Display *display, Window w, long event_mask)
  39. ' requests that the X server report the events associated with the specified Event mask.
  40. Private Extern XSelectInput(display As Pointer, w As Long, event_mask As Long)
  41.  
  42. ' XMapRaised (Display *display, Window w)
  43. ' raises the specified window to the top of the stack.
  44. Private Extern XMapRaised(display As Pointer, w As Long)
  45.  
  46. ' Atom XInternAtom(Display *display, char *atom_name, Bool only_if_exists)
  47. ' Returns the atom identifier associated with the specified atom_name string.
  48. Private Extern XInternAtom(display As Pointer, atom_name As String, only_if_exists As Boolean) As Long
  49.  
  50. ' Status XSetWMProtocols(Display *display, Window w, Atom *protocols, int count)
  51. ' Replaces the WM_PROTOCOLS property on the specified window with the list of atoms specified by the protocols argument.
  52. Private Extern XSetWMProtocols(display As Pointer, w As Long, protocols As Pointer, count As Integer) As Integer
  53.  
  54. ' XNextEvent (Display *display, XEvent *event_return)
  55. ' gets the next event and remove it from the queue
  56. Private Extern XNextEvent(display As Pointer, event_return As Pointer)
  57.  
  58. ' KeySym XkbKeycodeToKeysym (Display *dpy, KeyCode kc, unsigned int group, unsigned int level)
  59. ' Returns the keysym bound to a particular group and shift level for a particular key on the core keyboard.
  60. Private Extern XkbKeycodeToKeysym(dpy As Pointer, kc As Integer, group As Integer, level As Integer) As Long
  61.  
  62. ' Status XSendEvent(Display *display, Window w, Bool propagate, long event_mask, XEvent *event_send)
  63. ' Identifies the destination window, determines which clients should receive the specified events.
  64. Private Extern XSendEvent(display As Pointer, w As Long, propagate As Boolean, event_mask As Long, event_send As Pointer) As Integer
  65.  
  66. ' Status XGetWindowAttributes(Display *display, Window w, XWindowAttributes *window_attributes_return)
  67. ' Returns the current attributes for the specified window to an XWindowAttributes structure.
  68. Private Extern XGetWindowAttributes(display As Pointer, w As Long, window_attributes As Pointer) As Integer
  69.  
  70. ' GC XDefaultGC(Display *display, int screen_number)
  71. ' Returns the default graphics context for the root window of the specified screen.
  72. Private Extern XDefaultGC(display As Pointer, screen_number As Integer) As Pointer
  73.  
  74. ' int XClearArea(Display *display, Window w, int x, int y, unsigned int width, unsigned int height, Bool exposures)
  75. ' Paints a rectangular area in the specified window.
  76. Private Extern XClearArea(display As Pointer, w As Long, x As Integer, y As Integer, width As Integer, height As Integer, exposures As Boolean) As Integer
  77.  
  78. ' int XDrawRectangle(Display *display, Drawable d, GC gc, int x, int y, unsigned int width, unsigned int height)
  79. ' Draw the outlines of the specified rectangle.
  80. Private Extern XDrawRectangle(display As Pointer, d As Long, gc As Pointer, x As Integer, y As Integer, width As Integer, height As Integer) As Integer
  81.  
  82. ' int XDrawString(Display *display, Drawable d, GC gc, int x, int y, char *string, int length)
  83. ' Treats each character image as an additional mask for a fill operation on the drawable.
  84. Private Extern XDrawString(display As Pointer, d As Long, gc As Pointer, x As Integer, y As Integer, stringc As String, length As Integer) As Integer
  85.  
  86. ' XDestroyWindow(Display *display, Window w)
  87. ' destroys the specified window as well as all of its subwindows
  88. Private Extern XDestroyWindow(display As Pointer, w As Long)
  89.  
  90. ' XCloseDisplay(Display *display)
  91. ' Closes the connection to the X server for the display specified in the Display structure and destroys all windows.
  92. Private Extern XCloseDisplay(display As Pointer)
  93.  
  94.  
  95. Public Sub Main()
  96.  
  97.  Dim disp, ev As Pointer
  98.  Dim scr As Integer
  99.  Dim id, atom, ks As Long
  100.  
  101. ' Apre la connessione con il server display del sistema grafico X:
  102.   disp = XOpenDisplay(0)
  103.   If disp = 0 Then Error.Raise("Impossibile aprire il server X !")
  104.  
  105.   scr = XDefaultScreen(disp)
  106.    
  107. ' Crea la finestra secondo i parametri previsti dalla funzione. L'ultimo parametro imposta il colore di fondo della finestra:
  108.   id = XCreateSimpleWindow(disp, XRootWindow(disp, scr), 0, 0, 200, 300, 0, 0, &FFEFDF)
  109.   Print "ID della finestra creata: "; Hex(id, 6)
  110.  
  111. ' Dice al server display quali eventi deve vedere:
  112.   XSelectInput(disp, id, ExposureMask Or KeyPressMask Or ButtonPressMask)
  113.  
  114. ' Apre la finestra sullo schermo. Si può utilizzare anche la funzione "XMapWindow(display, w)":
  115.   XMapRaised(disp, id)
  116.  
  117.   atom = XInternAtom(disp, "WM_DELETE_WINDOW", False)
  118.  
  119.   XSetWMProtocols(disp, id, VarPtr(atom), 1)
  120.  
  121. ' Alloca un'area di memoria pari alla Struttura esterna 'XEvent' (192 byte):
  122.   ev = Alloc(192)
  123.  
  124. ' Inizia il ciclo, restando in attesa di un evento stabilito con la precedente funzione XSelectInput():
  125.  
  126.     XNextEvent(disp, ev)
  127.  
  128.     Select Case Int@(ev)
  129. ' Se viene premuta la X nell'angolo alto a destra, chiude la finestra:
  130.       Case ClientMessage
  131.         If Short@(ev + 56) = atom Then Break
  132.       Case Expose
  133.         DisegnaCalc(disp, id, scr)
  134.       Case KeyPress
  135.         ks = XkbKeycodeToKeysym(disp, Int@(ev + 84), 0, 0)
  136. ' Se viene premuto il tasto "q" della tastiera, la finestra viene chiusa:
  137.         If CByte(ks) = 113 Then
  138.           Break
  139.         Else
  140.           Calcolo(ks)
  141. ' Ridisegna la finestra:
  142.           st = Memory ev For Write
  143.           Write #st, Expose As Integer
  144.           st.Close
  145.           XSendEvent(disp, id, False, 0, ev)
  146.         Endif
  147.       Case ButtonPress
  148.         Pressione_Tasti(disp, id, Int@(ev + 64), Int@(ev + 68))
  149.         st = Memory ev For Write
  150.         Write #st, Expose As Integer
  151.         st.Close
  152.         XSendEvent(disp, id, False, 0, ev)
  153.     End Select
  154.  
  155.   Wend
  156.  
  157.  
  158. ' Chiude la finestra e libera la memoria:
  159.   Free(ev)
  160.   XDestroyWindow(disp, id)
  161.   XCloseDisplay(disp)
  162.  
  163.  
  164.  
  165. Private Procedure DisegnaCalc(dis As Pointer, idW As Long, sc As Integer)
  166.  
  167.   Dim i, j, buf_len As Integer
  168.   Dim buf As String
  169.   Dim attributes, gc As Pointer
  170.  
  171.     
  172. ' Alloca un'area di memoria pari alla Struttura esterna 'XWindowAttributes' (192 byte):
  173.     attributes = Alloc(136)
  174.  
  175.     If XGetWindowAttributes(dis, idW, attributes) = 0 Then Return
  176.     gc = XDefaultGC(dis, sc)
  177.     XClearArea(dis, idW, SPAZIO, SPAZIO, Int@(attributes + 8) - (SPAZIO * 2), (Int@(attributes + 12) - ((BLOCCHI_Y - 1 + 2) * SPAZIO)) / BLOCCHI_Y, False)
  178.     XDrawRectangle(dis, idW, gc, SPAZIO, SPAZIO, Int@(attributes + 8) - (SPAZIO * 2), (Int@(attributes + 12) - ((BLOCCHI_Y - 1 + 2) * SPAZIO)) / BLOCCHI_Y)
  179.  
  180.     buf = Format(valore_mostrato, "0.000000")
  181.     buf_len = Len(buf)
  182.     XDrawString(dis, idW, gc, 30, 30, buf, buf_len)
  183.     
  184.     For i = 0 To BLOCCHI_X - 1
  185.       For j = 1 To BLOCCHI_Y - 1
  186.         XDrawRectangle(dis, idW, gc, (((Int@(attributes + 8) - (BLOCCHI_X - 1)) / BLOCCHI_X) * i) + SPAZIO,
  187.           (((Int@(attributes + 12) - (BLOCCHI_Y - 1)) / BLOCCHI_Y) * j) + SPAZIO,
  188.           (Int@(attributes + 8) - ((BLOCCHI_X - 1 + 2) * SPAZIO)) / BLOCCHI_X, (Int@(attributes + 12) - ((BLOCCHI_Y - 1 + 2) * SPAZIO)) / BLOCCHI_Y)    
  189.         XDrawString(dis, idW, gc, (((Int@(attributes + 8) / BLOCCHI_X) * (i + 1))) - Int@(attributes + 8) / BLOCCHI_X / 2,
  190.           ((Int@(attributes + 12) / BLOCCHI_Y) * (j + 1)) - Int@(attributes + 12) / BLOCCHI_Y / 2, simboli[j - 1][i], 1)
  191.       Next
  192.  
  193.     Next
  194.  
  195.     Free(attributes)
  196.  
  197.  
  198.  
  199. Private Procedure Calcolo(lo As Long)
  200.  
  201.     Case 8, Asc("C"), Asc("c")
  202.       valore_mostrato = 0.0
  203.       valore_buffer = 0.0
  204.       modo_decimale = 0
  205.       operazione = 0
  206.       disp_mod = 0
  207.     Case 48 To 57
  208.       If disp_mod Then
  209.         valore_mostrato = 0.0
  210.         disp_mod = 0
  211.       Endif
  212.       If modo_decimale Then
  213.         If modo_decimale <= 6 Then
  214.           valore_mostrato += ((lo - &30) / CFloat(Decimali(10, modo_decimale)))
  215.           Inc modo_decimale
  216.         Endif
  217.       Else
  218.         valore_mostrato *= 10
  219.         valore_mostrato += (lo - &30)
  220.       Endif
  221.     Case 44, 46
  222.       If modo_decimale = 0 Then modo_decimale = 1
  223.     Case 42, 43, 45, 47
  224.       If operazione <> 0 Then
  225.         Select Case operazione
  226.           Case 42
  227.             valore_mostrato = valore_buffer * valore_mostrato
  228.           Case 43
  229.             valore_mostrato = valore_buffer + valore_mostrato
  230.           Case 45
  231.             valore_mostrato = valore_buffer - valore_mostrato
  232.           Case 47
  233.             valore_mostrato = valore_buffer / valore_mostrato
  234.         End Select
  235.       Endif
  236.       valore_buffer = valore_mostrato
  237.       operazione = lo
  238.       disp_mod = 1
  239.       modo_decimale = 0
  240.     Case &0D, 61
  241.       If operazione <> 0 Then
  242.         Select Case operazione
  243.           Case 42
  244.            valore_mostrato = valore_buffer * valore_mostrato
  245.           Case 43
  246.             valore_mostrato = valore_buffer + valore_mostrato
  247.           Case 45
  248.             valore_mostrato = valore_buffer - valore_mostrato
  249.           Case 47
  250.             valore_mostrato = valore_buffer / valore_mostrato
  251.         End Select
  252.       Endif
  253.       operazione = 0
  254.       disp_mod = 1
  255.       modo_decimale = 0
  256.  
  257.  
  258.  
  259.  
  260.     Return i ^ n
  261.  
  262.  
  263.  
  264. Private Procedure Pressione_Tasti(di As Pointer, wi As Long, x As Integer, y As Integer)
  265.  
  266.   Dim i, j, x1, x2, y1, y2 As Integer
  267.   Dim attributes As Pointer
  268.  
  269.     attributes = Alloc(136)
  270.  
  271.     If XGetWindowAttributes(di, wi, attributes) = 0 Then Return
  272.  
  273.     For i = 0 To BLOCCHI_X - 1
  274.       For j = 1 To BLOCCHI_Y - 1
  275.         x1 = (((Int@(attributes + 8) - (BLOCCHI_X - 1)) / BLOCCHI_X) * i) + SPAZIO
  276.         y1 = (((Int@(attributes + 12) - (BLOCCHI_Y - 1)) / BLOCCHI_Y) * j) + SPAZIO
  277.         x2 = x1 + (Int@(attributes + 8) - ((BLOCCHI_X - 1 + 2) * SPAZIO)) / BLOCCHI_X
  278.         y2 = y1 + (Int@(attributes + 12) - ((BLOCCHI_Y - 1 + 2) * SPAZIO)) / BLOCCHI_Y
  279.         If (x > x1) And (x < x2) And (y > y1) And (y < y2) Then Calcolo(CLong(Asc(simboli[j - 1][i])))
  280.       Next
  281.     Next
  282.  
  283.     Free(attributes)
  284.  



"Los horizontes perdidos nunca regresan. " (F. Battiato, La stagione dell'amore, 1983)

"Las ondas nunca regresan. " (Genesis: Ripples - A trick of the tail, 1976)
    ¡Gracias!
#2

Gracias por el ejemplo.
[Imagen: av09RE2.png]
Saludos.

1 Saludo.
    ¡Gracias!
#3

(03-09-2020, 03:26)vuott escribió:  El siguiente código es un ejemplo simple del uso de los recursos externos del API de X11.
Sólo funciona con sistemas de 64 bits.
El presente código es la traducción a Gambas con variaciones y integraciones, del código original, escrito en lenguaje C, del proyecto de Kjetil Erga, llamado: "Xlib Calculator ".

Muy interesante el código. He visto cosas que aun no había utilizado.

Una pregunta:

¿Procedure sería lo mismo que Sub para que yo lo entienda?

Saludos Smile
    ¡Gracias!
#4

(03-09-2020, 21:04)gambafeliz escribió:  ¿Procedure sería lo mismo que Sub para que yo lo entienda?

Sì, es lo mismo.
Yo uso Sub para los Eventos.
Por ejemplo: Public Sub Button1_Click( )


https://gambaswiki.org/wiki/lang/procedure

"Los horizontes perdidos nunca regresan. " (F. Battiato, La stagione dell'amore, 1983)

"Las ondas nunca regresan. " (Genesis: Ripples - A trick of the tail, 1976)
    ¡Gracias!
#5

(03-09-2020, 23:22)vuott escribió:  
(03-09-2020, 21:04)gambafeliz escribió:  ¿Procedure sería lo mismo que Sub para que yo lo entienda?

Sì, es lo mismo.

Entonces por que crees tu que existe Procedure, ¿quizás por agradar a programadores de otros lenguajes como COBOL?

Te lo pregunto por que no entiendo que existan sinónimos en un lenguaje de programación.
    ¡Gracias!
#6

(04-09-2020, 10:34)gambafeliz escribió:  Entonces por que crees tu que existe Procedure, ¿quizás por agradar a programadores de otros lenguajes como COBOL?

No se.  Confused

"Los horizontes perdidos nunca regresan. " (F. Battiato, La stagione dell'amore, 1983)

"Las ondas nunca regresan. " (Genesis: Ripples - A trick of the tail, 1976)
    ¡Gracias!


Posibles temas similares…
Tema / Autor Respuestas Vistas Último mensaje
Último mensaje por vuott
04-12-2021, 01:02

Salto de foro:


Usuarios navegando en este tema: 1 invitado(s)