aseprite/docs/jinete._tx
2007-12-05 01:53:03 +00:00

1487 lines
45 KiB
Plaintext

@#
@# Documentation for Jinete library in the _tx Allegro format.
@#
@document_title=Jinete Manual
@rtfh=Jinete - a GUI library
@manh="version 0.4" "Jinete" "Jinete Manual"
@mans=#include <jinete.h>
@$\input texinfo
@$@documentlanguage en
@$@setfilename jinete.info
@$@settitle Jinete Manual
@$@setchapternewpage odd
@$@paragraphindent 0
@$@setchapternewpage off
@# This should remain commented at the moment (dvi output) @$@finalout
@$
@$@ifinfo
@$@dircategory Libraries
@$@direntry
@$* Jinete: (jinete). A GUI library
@$@end direntry
@$This is the Info version of the Jinete manual
@$
@$By David A. Capello
@$@end ifinfo
@$
@$@node Top, , (dir), (dir)
@titlepage
@<pre>
@!indent
Jinete 0.4
A GUI library.
By <a href="http://www.davidcapello.com.ar/">David A. Capello</a>, 2005.
@indent
@</pre>
#include &ltstd_disclaimer.h&gt
<blockquote class="text"><i>
"I do not accept responsibility for any effects, adverse or otherwise,
that this code may have on you, your computer, your sanity, your dog,
and anything else that you can think of. Use it at your own risk."
</i></blockquote>
@!titlepage
@!text
@heading
Contents
@contents
@text
@text
@heading
Introduction
Jinete es una librería que proporciona un Interfaz Gráfico de
Usuario (GUI por sus siglas en inglés), sencilla y rápida tanto de
usar, como de programar y diseñar diálogos. Conjuntamente con la
librería Allegro, se encarga de controlar los eventos que produce el
usuario a través del ratón (mouse) y el teclado.
@heading
Copyright
Jinete es gift-ware (software-regalo). Puede usar, modificar,
redistribuir, y generalmente modificarlo de cualquier forma que
desee, y no debe darme nada a cambio. Si redistribuye partes de este
código o hace una aplicación con él, sería bonito que mencionase
Jinete en alguna parte de los créditos, pero no está obligado a
hacerlo.
@heading
Funcionamiento General
@xref jmanager_new, ji_manager_free
@xref jmanager_send_message, ji_manager_dispatch_messages
El GUI se maneja a través de widgets (controles u objetos gráficos).
Cada widget puede contener varios widgets hijos, donde cada uno de
éstos tiene un puntero a su único padre; siendo el padre raíz de
todos los widgets: el manager (gestor) principal del GUI (el cual
también es un widget).
Jinete es controlado con el manager principal, el cual es creado por
primera y única vez a través de la primer llamada de jmanager_new,
y deberá ser eliminado mediante jmanager_free.
Los managers sólo pueden contener ventanas dentro, mientras que las
ventanas pueden contener todo tipo de widgets, inclusive otros
managers alternativos (o sub-managers) los cuales a su vez pueden
contener otras ventanas (con Jinete puede lograr algo así como la
MDI de Windows).
El manager principal controla los mensajes y los despacha a los
demás widgets. Cabe destacar que todo mensaje enviado a través de
jmanager_send_message no es procesado de inmediato, dicho mensaje
solo se guardará en una cola para luego ser despachado (si espera
una respuesta inmediata, vea jmanager_dispatch_messages o
jwidget_send_message).
@tallbullets
<ul><li>
Foco de entrada (jmanager_get_focus):<br>
Es un puntero a un widget que indica que será el encargado de
recibir la entrada del teclado. Por lo menos, será el primero en
tener la oportunidad de procesarla, si él no la utiliza, se enviará
el mensaje a otros widgets. El foco de entrada se mueve con la tecla
TAB.
<li>
Widget con el mouse (jmanager_get_mouse):<br>
Un puntero al widget que tiene el mouse encima.
<li>
Widget con el mouse capturado (jmanager_get_capture):<br>
Un puntero al widget que capturó el mouse. Generalmente cuando se le
hace click encima de un widget, éste captura el mouse para que siga
recibiendo la entrada del mouse hasta que el usuario suelte el
botón.
</ul>
@heading
Rutinas Básicas
@@void *@jmalloc (unsigned long n_bytes);
@@void *@jmalloc0 (unsigned long n_bytes);
@@void *@jrealloc (void *mem, unsigned long n_bytes);
@@void @jfree (void *mem);
Equivalentes a malloc, calloc, realloc, y free respectivamente.
@@#define @jnew(struct_type, n_structs)
@@#define @jnew0(struct_type, n_structs)
@@#define @jrenew(struct_type, mem, n_structs)
Equivalente a usar:
<codeblock>
struct_type *mem1 = malloc (sizeof (struct_type) * n_structs).
<endblock>
@heading
Widget
Los widgets son los componentes, objetos o controles del interfaz
gráfico; un botón, o una ventana son ejemplos de widgets. En Jinete,
el tipo JWidget representa dicho controles:
<codeblock>
typedef struct jwidget *JWidget;
<endblock>
Es decir que JWidget en realidad se trata de un puntero a una
estructura jwidget definida en el archivo "jinete/widget.h".
En general, la gran mayoría de los tipos en Jinete (definidos en
"jinete/base.h") se tratan de punteros a estructuras definidas en
cada uno de los archivos de cabecera particulares.
Para modificar el comportamiento de un widget, se deben agregar
ganchos ("hooks", JHook en Jinete), los cuales se encargan de
interceptar mensajes.
Los campos de la estructura jwidget son:
@tallbullets
<ul><li>
JID id;<br>
Código de identificación. Es un número con el cual puede identificar
a un widget (por lo menos mientras éste exista). Al liberar el widget
(con jwidget_free), su ID quedará disponible para un próximo widget
que se cree (mediante jwidget_new).
<li>
int type;<br>
Tipo de widget. Puede ser JI_WIDGET para indicar un tipo de widget
anónimo, o puede ser JI_BUTTON si se creó desde jbutton_new, o
JI_WINDOW si se utilizó jwindow_new, etc.
<p>
Es el valor que se le pasa a la función jwidget_new (puede tratarse
de un valor devuelto por ji_register_widget_type).
<li>
char *name;
Nombre del widget (generalmente NULL si no es que es un widget
cargado desde un archivo .jid). Es útil para buscar el widget
desde su padre utilizando la rutina jwidget_find_name.
<li>
JRect pos;<br>
Ubicación del widget: esquina superior-izquierda (x, y) y tamaño (w, h).
Es una posición ABSOLUTA en la pantalla, NO ES UNA POSICIÓN RELATIVA.
<li>
struct { int l, t, r, b; } border_width;<br>
Tamaño de los bordes izquierdo, superior, derecho e inferior (left,
top, right, bottom).
<li>
int child_spacing;<br>
Separación entre los hijos del widget.
<li>
int flags;<br>
Banderas o propiedades del widget.
<li>
int emit_signals;<br>
Contador que indica si el widget debe o no generar señales (si
emit_signals es igual a 0, las señales se emiten).
<li>
int static_w, static_h;<br>
Tamaño estático del widget por defecto (si es que no se intercepta
el mensaje JM_REQSIZE, se utilizará este tamaño como el tamaño
necesario por el widget).
<li>
JList children;<br>
Lista de widgets hijos. Son los controles que están contenidos en
este widget. La función jwidget_add_child sirve para agregar hijos
dentro de un widget.
<li>
JTheme theme;<br>
Tema o estilo que utiliza el widget (inicializándolo al tema por
defecto a través de la función ji_get_theme).
<li>
JWidget parent;<br>
Puntero al widget padre.
<li>
JList hooks;<br>
Lista de ganchos (JHook).
<li>
JDrawWidget draw_method;<br>
Función encargada de dibujar el widget, al inicializar un widget,
se intenta extraer desde el tema activo (ji_get_theme) un método
correspondiente para este tipo de widget (widget->draw_type).
Si el mensaje JM_DRAW no es interceptado, esta rutina será utilizada
para dibujar el widget.
<li>
int align;<br>
Alineamiento u orientación del widget (generalmente alineación del texto).
<li>
int text_size;<br>
char *text;<br>
Texto del widget.
<li>
FONT *text_font;<br>
Tipo de fuente para dibujar texto (este campo es inicializado con
el valor "ji_get_theme ()->default_font").
<li>
int bg_color;<br>
Color de fondo del widget (si es -1, se utiliza el del padre, y así
sucesivamente).
<li>
BITMAP *icon;<br>
Ícono del widget (XXX).
<li>
int icon_align;<br>
Alineamiento del ícono (XXX).
<li>
void *theme_data[4];<br>
Datos para el tema.
<li>
void *user_data[4];<br>
Datos para el usuario.
</ul>
@@int @ji_register_widget_type (void);
Retorna un número entero positivo para identificar un nuevo tipo de
widget. Debería utilizarlo sólo si necesita conocer en alguna parte
de su código que un determinado widget es del tipo que debería ser.
Retornará valores continuos a JI_USER_WIDGET.
@@JWidget @jwidget_new (int type);
@xref jwidget_free
Crea un nuevo "widget" de tipo "type" listo para ser utilizado.
@@void @jwidget_free (JWidget widget);
@xref jwidget_new, _ji_free_all_widgets, Manager, JM_DESTROY
Libera el "widget", dejando su espacio disponible para próximos
controles que así lo necesiten. Note que esta función no libera
memoria, solo deja su espacio disponible para que otro posible
futuro widget lo utilice. Sólo la función _ji_free_all_widgets
libera toda la memoria ocupada por todos los widgets. Dicha función
es llamada al borrar el primer "manager" creado.
Los widgets hijos también son eliminados (recursivamente). El campo
"widget->specific_data" también es eliminado (mediante jfree).
Envía el mensaje JM_DESTROY al widget inmediatamente.
@@void @jwidget_init_theme (JWidget widget);
Inicializa el widget a su tema (estilo) correspondiente haciendo uso
de la función init_widget de la estructura jtheme.
@\void @jwidget_add_hook (JWidget widget, int type,
@@ JMessageFunc msg_proc, void *data);
@xref ji_register_widget_type, jwidget_get_hook, jwidget_get_data
Crea un nuevo gancho (hook) para interceptar mensajes. Cada gancho
tiene un tipo ("type"), que puede ser anónimo (JI_WIDGET) o puede
ser de un tipo personalizado (algún tipo devuelto mediante
ji_register_widget_type). Este tipo luego es utilizado para obtener
los datos "data".
El "msg_proc" es un puntero a una función encargada de recibir cada
mensaje y procesarlo. Esta función debe retornar FALSE si no utiliza
un determinado mensaje y/o quiere dejarle el paso a un posible
"msg_proc" padre que se encuentre en el widget.
@@JHook @jwidget_get_hook (JWidget widget, int type);
@@void *@jwidget_get_data (JWidget widget, int type);
@@int @jwidget_get_type (JWidget widget);
@xref ji_register_widget_type
Devuelve el tipo de widget que es "widget". Puede ser igual a
JI_WIDGET si se trata de un tipo anónimo de widget, o alguno de los
widgets estándares (como JI_BOX, JI_BUTTON, JI_WINDOW, etc.), o
finalmente debería tratarse de algún tipo creado por el usuario
mediante ji_register_widget_type ().
@@const char *@jwidget_get_name (JWidget widget);
@xref jwidget_set_name, ji_load_widget, Archivos JID
Obtiene el nombre del widget. Generalmente los widgets nunca tendrán
nombre al menos que sean cargados desde un archivo .jid.
@@const char *@jwidget_get_text (JWidget widget);
@xref jwidget_set_text
Retorna un puntero al texto actual del widget, el cual puede ser
tanto una etiqueta que lleve un botón, el título de una ventana,
etc.
No utilice el puntero si es que lo consiguió antes de una llamada a
jwidget_set_text. EVITE SIEMPRE hacer esto:
<codeblock>
const char *text = jwidget_get_text (widget);
jwidget_set_text (widget, "Hola");
printf (text);
<endblock>
@@int @jwidget_get_align (JWidget widget);
@xref jwidget_set_align
Devuelve el alineamiento del widget (widget->align).
@@FONT *@jwidget_get_font (JWidget widget);
@@void @jwidget_set_name (JWidget widget, const char *name);
@xref jwidget_find_name
Cambia el nombre del widget, generalmente útil si piensa luego usar
jwidget_find_name desde otra función o gancho.
@@void @jwidget_set_text (JWidget widget, const char *text);
@xref jwidget_get_text, jwidget_dirty
Cambia el texto del widget. Está función también se encarga de
ensuciar el widget mediante jwidget_dirty.
@@void @jwidget_set_align (JWidget widget, int align);
@xref jwidget_get_align
Cambia el alineamiento del widget (widget->align = align).
@@void @jwidget_set_font (JWidget widget, FONT *font);
@@void @jwidget_magnetic (JWidget widget, bool state);
@xref jwidget_is_magnetic, jmanager_attract_focus
Cambia el estado de magnetismo del widget. Un widget magnética es
la que obtiene el foco de entrada por defecto. Generalmente los
botones de "Aceptar" o "Continuar" suelen tener esta propiedad,
teniendo la posibilidad de capturar la tecla <Enter> y utilizarla
para suponer que se quiso presionar dicho botón (sin necesidad de
poseer el foco de entrada).
@@void @jwidget_expansive (JWidget widget, bool state);
@xref jwidget_is_expansive, jbox_new
Cambia el estado de expansión del widget. Un widget expansivo es
el que acapara mayor espacio en el widget padre. Útil únicamente
cuando el widget padre es una caja (box).
@@void @jwidget_decorative (JWidget widget, bool state);
@xref jwidget_is_decorative, Window (ventana), Theme (tema)
Cambia el estado de decoración del widget. Un widget decorativo es
un objeto especial el cual sirve para decorar las ventanas. Sólo
los temas deberían utilizar esta función, ya que es útil para
agregar un botón que cierre la ventana, o para minimizarla, o
para maximizarla/restaurarla, etc.
@@void @jwidget_autodestroy (JWidget widget, bool state);
@@void @jwidget_focusrest (JWidget widget, bool state);
@@bool @jwidget_is_magnetic (JWidget widget);
@@bool @jwidget_is_expansive (JWidget widget);
@@bool @jwidget_is_decorative (JWidget widget);
@@bool @jwidget_is_autodestroy (JWidget widget);
@xref jwidget_magnetic, jwidget_expansive
@xref jwidget_decorative, jwidget_autodestroy
Devuelve TRUE si el widget es lo que preguntamos que sea (magnética,
expansiva, decorativa, o autodestructiva).
@@bool @jwidget_is_focusrest (JWidget widget);
@xref jwidget_focusrest
@@void @jwidget_dirty (JWidget widget);
@xref jmanager_poll, JI_SIGNAL_DIRTY
Ensucia el widget para que sea redibujado en una próxima llamada a
jmanager_poll. Sólo colocará una bandera que le dirá al manager
que genere los mensajes necesarios para dibujar las partes visibles
del widget. Emite la señal JM_DIRTY.
Si desea redibujar un widget de forma instantánea:
<codeblock>
jwidget_dirty (widget);
jwidget_flush_redraw (widget);
jmanager_dispatch_draw_messages ();
<endblock>
Tenga en cuenta, que muchas funciones que cambian el estado del
widget, suelen llamar a jwidget_dirty para redibujar el widget con
su nuevo estado.
@@void @jwidget_show (JWidget widget);
@@void @jwidget_hide (JWidget widget);
@@void @jwidget_enable (JWidget widget);
@@void @jwidget_disable (JWidget widget);
@@void @jwidget_select (JWidget widget);
@@void @jwidget_deselect (JWidget widget);
@@bool @jwidget_is_visible (JWidget widget);
@@bool @jwidget_is_hidden (JWidget widget);
@@bool @jwidget_is_enabled (JWidget widget);
@@bool @jwidget_is_disabled (JWidget widget);
@@bool @jwidget_is_selected (JWidget widget);
@@bool @jwidget_is_deselected (JWidget widget);
@@bool @jwidget_has_focus (JWidget widget);
@@bool @jwidget_has_mouse (JWidget widget);
@@bool @jwidget_has_capture (JWidget widget);
@@void @jwidget_add_child (JWidget widget, JWidget child);
@xref jwidget_remove_child, jwidget_replace_child
@xref JI_SIGNAL_NEW_PARENT, JI_SIGNAL_ADD_CHILD
Agrega un nuevo widget hijo "child" dentro del widget padre
"widget".
Emite la señal JI_SIGNAL_NEW_PARENT para "child", y
JI_SIGNAL_ADD_CHILD para "widget".
@@void @jwidget_add_childs (JWidget widget, ...);
@xref jwidget_add_child
@@void @jwidget_remove_child (JWidget widget, JWidget child);
@xref jwidget_add_child, jwidget_replace_child
@@void @jwidget_replace_child (JWidget widget, JWidget old, JWidget new);
@xref jwidget_add_child, jwidget_remove_child
@@JWidget @jwidget_get_parent (JWidget widget);
@xref jwidget_get_parents
Devuelve un puntero al widget padre. Es equivalente a utilizar
widget->parent directamente.
@@JWidget @jwidget_get_window (JWidget widget);
@xref jwindow_get_manager
Recorre los padres del widget hasta encontrar la ventana a la que
pertenece, devolviendo dicho puntero o NULL si es que no se pudo
encontrar una ventana padre.
@@JList @jwidget_get_parents (JWidget widget, bool ascendant);
@xref jwidget_get_parent, jlist_free
Retornar una list de los padres de "widget". Si "ascendant" es TRUE
retorna desde el widget hasta el padre. Si "ascendant" es FALSE
retorna desde el padre hasta "widget".
Deberá liberar la lista devuelta mediante jlist_free.
@@JList @jwidget_get_children (JWidget widget);
Deberá liberar la lista devuelta mediante jlist_free.
@@JWidget @jwidget_pick (JWidget widget, int x, int y);
Busca un widget dentro de "widget" que se encuentre en la posición
(x, y), partiendo desde el "widget", pasando por todos sus hijos.
Devolverá el widget más lejano de "widget" (el hijo más profundo) si
es que éste se abarca el punto (x, y).
@@bool @jwidget_has_child (JWidget widget, JWidget child);
Devuelve TRUE si el "widget" posee dentro el widget hijo "child".
Está función sólo mira por los hijos de "widget", nunca baja a los
hijos de sus hijos.
@@void @jwidget_request_size (JWidget widget, int *w, int *h);
@@JRect @jwidget_get_position (JWidget widget);
@xref jwidget_get_region, jrect_free
Retorna la posición del widget.
El rectángulo devuelto JRect deberá ser liberado mediante jrect_free.
@@JRect @jwidget_get_child_position (JWidget widget);
@@JRegion @jwidget_get_region (JWidget widget);
@xref jwidget_get_position, jwidget_get_drawable_region
@xref jregion_free
Deberá liberar la región devuelta mediante jregion_free.
@@JRegion @jwidget_get_drawable_region (JWidget widget, int flags);
@xref jwidget_get_region, jregion_free
Deberá liberar la región devuelta mediante jregion_free.
@@int @jwidget_get_bg_color (JWidget widget);
Devuelve el color de fondo de este widget (o si es -1 pregunta por
el color del padre).
@@JTheme @jwidget_get_theme (JWidget widget);
Devuelve un puntero al tema que utiliza dicho widget.
@@int @jwidget_get_text_length (JWidget widget);
@@int @jwidget_get_text_height (JWidget widget);
@xref ji_font_text_len
Retorna las medidas del texto del widget en píxeles. Puede ser
equivalente a utilizar:
<codeblock>
int length = ji_font_text_len (widget->text_font, widget->text);
int height = text_height (widget->text_font);
<endblock>
@\void @jwidget_get_texticon_info (JWidget widget,
@\ JRect box, JRect text, JRect icon,
@@ int icon_w, int icon_h);
@@void @jwidget_noborders (JWidget widget);
@@void @jwidget_set_border (JWidget widget, int l, int t, int r, int b);
@@void @jwidget_set_position (JWidget widget, JRect rect);
@@void @jwidget_set_static_size (JWidget widget, int w, int h);
@@void @jwidget_set_bg_color (JWidget widget, int color);
@@void @jwidget_set_theme (JWidget widget, JTheme theme);
@@void @jwidget_flush_redraw (JWidget widget);
@@void @jwidget_redraw_region (JWidget widget, const JRegion region);
@@void @jwidget_signal_on (JWidget widget);
@@void @jwidget_signal_off (JWidget widget);
@@int @jwidget_emit_signal (JWidget widget, int signal_num);
@@bool @jwidget_send_message (JWidget widget, JMessage msg);
@\bool @jwidget_send_message_after_type (JWidget widget,
@@ JMessage msg, int type);
@@void @jwidget_close_window (JWidget widget);
@@void @jwidget_capture_mouse (JWidget widget);
@@void @jwidget_hard_capture_mouse (JWidget widget);
@@void @jwidget_release_mouse (JWidget widget);
@@JWidget @jwidget_find_name (JWidget widget, const char *name);
@xref jwidget_set_name, Archivos JID
Busca por el widget hijo con el nombre "name" dentro del widget
"widget". Útil para obtener widgets hijos cargados desde un archivo
.jid.
@@bool @jwidget_check_underscored (JWidget widget, int ascii);
@hnode Widget's flags
Valores posibles para las banderas widget->flags. Evite usar estos
valores directamente, en su lugar intente usar las funciones
"jwidget_is_..." donde sea posible.
<ul><li>
JI_DIRTY<br>
El widget está "sucio" (necesita ser redibujado en su totalidad).
<li>
JI_HIDDEN<br>
El widget está escondido.
<li>
JI_SELECTED<br>
El widget está seleccinado.
<li>
JI_DISABLED<br>
El widget está deshabilitado.
<li>
JI_HASFOCUS<br>
El widget tiene el foco de entrada (o alguno de sus hijos lo
tiene). Esta bandera sólo la pueden conseguir widgets que sean
JI_FOCUSREST.
<li>
JI_HASMOUSE<br>
El widget tiene el mouse (o alguno de sus hijos lo tiene).
<li>
JI_HASCAPTURE<br>
El widget tiene el mouse capturado.
<li>
JI_FOCUSREST<br>
El widget es un descanso para el foco, es decir, puede recibir el
foco de entrada ya que lo utilizará para algo. Por ejemplo: un botón
es focus-rest, pero una etiqueta (label) o una caja (box) no lo son.
<li>
JI_MAGNETIC<br>
El widget es magnético (recibe el foco de entrada por defecto).
<li>
JI_EXPANSIVE<br>
El widget es expansivo: intenta obtener el mayor lugar posible si su
padre es una caja (box).
<li>
JI_DECORATIVE<br>
@xref jwidget_decorative
El widget es decorativo (ver jwidget_decorative).
<li>
JI_AUTODESTROY<br>
@xref jwidget_autodestroy
El widget es auto-destructivo (ver jwidget_autodestroy).
<li>
JI_HARDCAPTURE<br>
@xref jwidget_hard_capture_mouse
El widget capturó el mouse en una forma "dura". Cuando se utiliza
jwidget_hard_capture_mouse, el widget con el mouse
(jmanager_get_mouse) será siempre el mismo widget que capturó el
mouse, es imposible que cambie a otro widget.
Cuando utiliza jwidget_capture_mouse, el widget con el mouse puede
cambiar a otro widget, pero los mensajes del mouse siguen siendo
enviados al que posee la captura.
</ul>
@heading
JHook (gancho)
@tallbullets
<ul><li>
int type;<br>
<li>
JMessageFunc msg_proc;<br>
Función encargada de procesar los mensajes, debe retornar TRUE si el
mensaje se utilizó y no se desea que el mismo sea procesado por los
siguientes "ganchos" consecutivos, o FALSE en caso contrario.
<li>
void *data;<br>
</ul>
@heading
Message (mensaje)
Cuando se genera un mensaje, al ser despachado se comienza enviando
el mismo a los ganchos de los widgets receptores, comenzando del
primer gancho (el cual sería el último gancho agregado) hasta el
último gancho del widget.
Recuerde que si intercepta un mensaje, debe retornar TRUE indicando
que el mensaje fue utilizado, así frena el enviado de mensajes a
otros ganchos. Esto es válido para todos los mensajes menos para
JM_DESTROY. Ya que devolviendo TRUE, los ganchos próximos no
recibirán dicho mensaje y es posible que algo de memoria no se
libere.
@hnode JM_OPEN
@xref JM_CLOSE
Es enviado a todos los widgets de una ventana cuando está es abierta
en un determinado manager.
@hnode JM_CLOSE
@xref JM_OPEN, JM_DESTROY
Cuando una ventana es cerrada, este mensaje se envía a todos los
widgets de la misma.
@hnode JM_DESTROY
@xref JM_CLOSE
Se envía al eliminar el widget mediante jwidget_free. Un widget
recibe una única vez este mensaje (siendo además el último mensaje
que recibirá). Recuerde retornar FALSE para no frenar el envío del
mensaje a los ganchos próximos.
@hnode JM_DRAW
@hnode JM_IDLE
@hnode JM_SIGNAL
@hnode JM_REQSIZE
@xref jwidget_request_size
Mensaje utilizado para obtener el tamaño necesario para el widget.
Debe rellenar las variables msg->reqsize.w y msg->reqsize.h, y
retornar TRUE si así lo hizo.
@hnode JM_SETPOS
@xref jwidget_set_position
Mensaje utilizado para cambiar el tamaño del widget, si lo intercepta,
deberá hacer un "jrect_copy (widget->pos, &msg->setpos.rect)".
Enganchar este mensaje es útil solamente si piensa reacomodar los
hijos cada vez que cambie la posición del widget (es decir, siempre
que un widget acepte hijos, deberá hacer su propio comportamiento
para acomodar el widget y a sus respectivos widgets hijos).
@hnode JM_DRAWRGN
Puede cambiar la forma de redibujar una región de un widget
(jwidget_redraw_region). Por ahora sólo los managers necesitan
interceptar este mensaje.
@hnode JM_DIRTYCHILDREN
También puede cambiar la forma de "ensuciar" los widgets hijos. Por
ejemplo, las list-boxes (cuadros de lista) necesitan enganchar este
mensaje para redibujar únicamente los ítems que estén dentro del
área de visible (para optimizar la velocidad de proceso).
@hnode JM_CHAR
@hnode JM_KEYPRESSED
@hnode JM_KEYRELEASED
@hnode JM_FOCUSENTER
@hnode JM_FOCUSLEAVE
@hnode JM_BUTTONPRESSED
@hnode JM_BUTTONRELEASED
@hnode JM_DOUBLECLICK
@hnode JM_MOUSEENTER
@hnode JM_MOUSELEAVE
@hnode JM_MOTION
@hnode JM_WHEEL
@heading
Signal (señales)
Las señales son un buen método de enganchar determinadas funciones
que controlan a las widgets. Es decir que podemos saber cuando
ocurre determinado cambio en un widget (por ejemplo si un widget fue
eliminado, o si un botón cambio de estado).
@hnode JI_SIGNAL_DIRTY
@xref jwidget_dirty
Se envia cuando un widget determinado es ensuciado.
@hnode JI_SIGNAL_ENABLE
@xref jwidget_enable
Al cambiar el estado de un widget a activado.
@hnode JI_SIGNAL_DISABLE
@xref jwidget_disable
Al cambiar el estado de un widget a desactivado.
@hnode JI_SIGNAL_SELECT
@xref jwidget_select
@hnode JI_SIGNAL_DESELECT
@xref jwidget_deselect
@hnode JI_SIGNAL_SHOW
@xref jwidget_show
@hnode JI_SIGNAL_HIDE
@xref jwidget_hide
@hnode JI_SIGNAL_ADD_CHILD
@xref jwidget_add_child
@hnode JI_SIGNAL_REMOVE_CHILD
@xref jwidget_remove_child
@hnode JI_SIGNAL_NEW_PARENT
@xref jwidget_add_child, jwidget_remove_child
@hnode JI_SIGNAL_GET_TEXT
@xref JI_SIGNAL_SET_TEXT
@hnode JI_SIGNAL_SET_TEXT
@xref JI_SIGNAL_GET_TEXT
@hnode JI_SIGNAL_INIT_THEME
@xref jwidget_init_theme
@hnode JI_SIGNAL_CHECK_CHANGE
@hnode JI_SIGNAL_RADIO_CHANGE
@hnode JI_SIGNAL_ENTRY_CHANGE
@hnode JI_SIGNAL_LISTBOX_CHANGE
@hnode JI_SIGNAL_LISTBOX_SELECT
@hnode JI_SIGNAL_MENUITEM_SELECT
@hnode JI_SIGNAL_SLIDER_CHANGE
@heading
Manager (gestor)
@@JWidget @ji_get_default_manager (void);
@xref jmanager_new
Retorna un puntero del manager principal, el primer manager creado
con jmanager_new.
@@JWidget @jmanager_new (void);
@xref jmanager_free
@@void @jmanager_free (JWidget manager);
@xref jmanager_new
@@void @jmanager_run (JWidget manager);
@xref jmanager_poll
@@bool @jmanager_poll (JWidget manager, bool all_windows);
@xref jmanager_run
@@void @jmanager_send_message (const JMessage msg);
@xref jmanager_dispatch_messages
@@JWidget @jmanager_get_focus (void);
@xref jmanager_set_focus
@@JWidget @jmanager_get_mouse (void);
@xref jmanager_set_mouse
@@JWidget @jmanager_get_capture (void);
@xref jmanager_set_capture
@@void @jmanager_set_focus (JWidget widget);
@xref jmanager_get_focus
@@void @jmanager_set_mouse (JWidget widget);
@xref jmanager_get_mouse
@@void @jmanager_set_capture (JWidget widget);
@xref jmanager_get_capture
@@void @jmanager_attract_focus (JWidget widget);
@xref jwidget_magnetic
@@void @jmanager_free_focus (void);
@@void @jmanager_free_mouse (void);
@@void @jmanager_free_capture (void);
@xref jmanager_set_focus, ji_manager_set_mouse, ji_manager_set_capture
@@void @jmanager_free_widget (JWidget widget);
@@void @jmanager_remove_message (JMessage msg);
@@void @jmanager_remove_messages_for (JWidget widget);
@@void @jmanager_refresh_screen (void);
@@void @jmanager_dispatch_messages (void);
@@void @jmanager_dispatch_draw_messages (void);
@@void @jmanager_open_window (JWidget manager, JWidget window);
@@void @jmanager_close_window (JWidget manager, JWidget window, bool sendtokill);
@hnode JI_SIGNAL_MANAGER_EXTERNAL_CLOSE
@hnode JI_SIGNAL_MANAGER_ADD_WINDOW
@hnode JI_SIGNAL_MANAGER_REMOVE_WINDOW
@hnode JI_SIGNAL_MANAGER_IDLE
@hnode JI_SIGNAL_MANAGER_LOSTCHAR
@heading
Window (ventana)
Una ventana es un tipo de widget especial en una caja rectangular que
representa un cuadro de diálogo (entre el usuario y el programa) el
cual el usuario puede mover o cambiar de tamaño a su antojo.
En Jinete, la ventana incluye sólo los rebordes y la barra de título,
usted debe agregarle los widgets hijos mediante jwidget_add_child.
La posición de los hijos es puesta en el área cliente (el área dentro
de los bordes de la ventana), por lo que deberá agregar sólo un widget
dentro de la ventana (generalmente una caja (box)) la cual contendrá
los demás widgets.
@@JWidget @jwindow_new (const char *text);
Crea una nueva ventana con el texto "text" en la barra de título.
@@JWidget @jwindow_new_desktop (void);
@xref jwindow_is_desktop
Crea una nueva ventana de tipo desktop (escritorio). Los escritorios
ocupan toda la pantalla (o mejor dicho, todo el tamaño del manager
padre).
@@JWidget @jwindow_get_killer (JWidget window);
@xref jwindow_close
Devuelve el puntero al widget que "mató" (cerró) la ventana
"window". Puede que este puntero sea NULL en el caso de que algún
ente anónimo haya cerrado la ventana (como el botón "x" para
cerrarla, o la tecla <Esc>).
@@JWidget @jwindow_get_manager (JWidget window);
@xref jwindow_open, jmanager_open_window
Devuelve el manager en el cual la ventana "window" se encuentra
dentro.
@@void @jwindow_mobile (JWidget window, bool mobile);
Cambia el estado de movilidad de la ventana "window". Si una ventana
es móvil, significa que el usuario puede cambiarle la posición y su
tamaño.
@@void @jwindow_remap (JWidget window);
XXX
Esta función generalmente no es necesaria utilizarla si usted usa
jwindow_center o jwindow_position antes. Será necesaria en casos
especiales donde usted necesite saber el tamaño mínimo que necesita
la ventana antes de abrirla.
@@void @jwindow_center (JWidget window);
@xref jwindow_position
Cambia la posición de la ventana "window" al centro el manager
principal (el manager principal tiene el tamaño de la pantalla
física, o mejor dicho, del modo de video actual).
@@void @jwindow_position (JWidget window, int x, int y);
Posiciona la ventana a otro punto (x, y). Note que esta función
difiere de jwidget_set_position en el sentido de que sólo desplaza
la ventana (y sus widgets hijos) a la nueva posición.
@@void @jwindow_open (JWidget window);
@xref jwindow_open_fg, jwindow_open_bg
@xref ji_get_default_manager, jmanager_poll
Abre la ventana en el manager por defecto para ser procesadas por
próximas llamadas a jmanager_poll.
No debería usar esta función a menos que sepa lo que está
haciendo. Generalmente nunca la deberá llamar directamente, en
cambio, las funciones jwindow_open_fg o jwindow_open_bg son las
comúnmente utilizadas (y las mismas suelen utilizar jwindow_open).
@@void @jwindow_open_fg (JWidget window);
@xref jwindow_open_bg, jwindow_get_killer
@xref jwidget_free
Abre la ventana en primer plano (foreground), paralizando las demás
ventanas abiertas, y esperando una respuesta del usuario
inmediata. Cuando la ventana se cierra se vuelve a donde la función
se llamó.
Útil cuando necesita hacer cosas como:
<codeblock>
jwindow_open_fg (window);
if (jwindow_get_killer (window) == boton_aceptar) {
...
}
jwidget_free (window);
<endblock>
@@void @jwindow_open_bg (JWidget window);
@xref jwindow_open, jwindow_open_fg
@xref jwidget_free, jwidget_autodestroy
Abre la ventana y la deja ejecutándose en segundo plano
(background).
Esta función sólo coloca la bandera auto-destroy a la ventana y
llama a la función jwindow_open. La bandera auto-destroy hace que
la ventana, al ser cerrada, sea automáticamente liberada
(jwidget_free) por el mismo manager antes que por nosotros.
@@void @jwindow_close (JWidget window, JWidget killer);
@xref jwindow_open, jwindow_get_killer
Cierra la ventana "window" forzosamente. El paramentro "killer"
indica quien "mató" (cerró) la ventana, esto es debido a que esta
función generalmente se utiliza dentro de un "msg_proc" de un widget
especial que se encarga de cerrar la ventana (por ejemplo un botón,
que al presionarlo, su acción por defecto es matar a su ventana
padre).
@@bool @jwindow_is_toplevel (JWidget window);
Retorna TRUE si la ventana "window" se encuentra encima de todas las
ventanas.
@@bool @jwindow_is_foreground (JWidget window);
@xref jwindow_open_fg
Retorna TRUE si la ventana se ejecuta en primer plano (foreground).
@@bool @jwindow_is_desktop (JWidget window);
@xref jwindow_new_desktop
Retorna TRUE si la ventana es de tipo escritorio (desktop).
@hnode JI_SIGNAL_WINDOW_CLOSE
@hnode JI_SIGNAL_WINDOW_RESIZE
@heading
Box (caja)
Una caja (box) es uno de los widgets más sencillos de manejar y a su
vez, uno de los más útiles. Sirve para disponer los widgets hijos de
forma horizontal o vertical, acomodándolos a nuestro antojo, pero sin
tener que preocuparnos por el tamaño que necesita cada widget
en particular.
@@JWidget @jbox_new (int align);
Crea una nueva caja (box) con las propiedades de alineamiento de "align".
"align" debe poseer uno de estos dos valores:
<ul><li>
JI_HORIZONTAL o JI_VERTICAL:<br>
Indica si queremos ordenar los widgets de forma horizontal o
vertical respectivamente.
</ul>
Y puede o no estar en combinación con:
<ul><li>
JI_HOMOGENEOUS<br>
Indica que todos los widgets hijos deben poseer el mismo tamaño.
Generalmente el máximo tamaño necesario por el widget hijo más
grande que se encuentre dentro de la caja (box).
</ul>
@heading
Label (etiqueta)
@@JWidget @jlabel_new (const char *text);
Crea una nueva widget de tipo etiqueta (label) con el texto "text".
Las etiquetas sirven para mostrar un mensaje, o indicar qué
significa un widget de al lado.
@heading
Button (botón)
Un botón es un widget que al ser presionado cierra la ventana donde
está, ó ejecuta alguna acción o comando (como abrir otra nueva ventana).
Un botón, sin que usted intercepte ninguna señal, ni mensaje,
siempre cerrará la ventana, tal es así, que luego puede preguntar
por jwindow_get_killer() y le devolverá un puntero a dicho botón.
Hay muchas formas de cambiar este comportamiento por defecto, la más
cómoda es utilizando las funciones jbutton_add_command, así la
ventana no será cerrada y en su lugar se llamará al comando
especificado. También, utilizando jwidget_add_hook() puede
interceptar el mensaje JM_SIGNAL cuando se envía la señal
JI_SIGNAL_BUTTON_SELECT.
Para que no queden dudas, cuando un botón es presionado:
@tallbullets
<ul><li>
Primero se envía la señal JI_SIGNAL_BUTTON_SELECT<br>
<li>
Si retorna FALSE, significa que la señal no fue utilizada, por lo
tanto debemos ejecutar el comportamiento por defecto: si se agregaron
comandos al botón mediante jbutton_add_command(), se ejecutarán los
comandos, ahora, si el botón no tiene comando alguno, se cerrará la
ventana.
</ul>
@@JWidget @jbutton_new (const char *text);
@xref jbutton_add_command, jwindow_get_killer
Crea un nuevo botón con el texto "text". Recuerde que por defecto,
si es que no agrega ningún comando, los botones cierran la ventana
Puede saber que botón cerró la ventana utilizando jwindow_get_killer.
@@void @jbutton_set_icon (JWidget button, struct BITMAP *icon);
@@void @jbutton_set_icon_align (JWidget button, int icon_align);
@@void @jbutton_set_bevel (JWidget button, int b0, int b1, int b2, int b3);
@@void @jbutton_get_bevel (JWidget button, int *b4);
@\void @jbutton_add_command (JWidget button,
@@ void (*command) (JWidget button));
@xref jbutton_add_command_data, JI_SIGNAL_BUTTON_SELECT
@\void @jbutton_add_command_data (JWidget button,
@\ void (*command) (JWidget button,
@\ void *data),
@@ void *data);
@xref jbutton_add_command, JI_SIGNAL_BUTTON_SELECT
@hnode JI_SIGNAL_BUTTON_SELECT
@xref Button (botón), jwidget_add_hook
Esta señal se envía a los handlers del botón cuando el mismo es
presionado (seleccionado). Deberá retornar TRUE para indicar que
utilizó dicha señal, si es que no quiere ejecutar el comportamiento
por defecto del botón: llamar los comandos si es que existen o
cerrar la ventana en caso contrario.
@heading
Check (caja de comprobación)
@@JWidget @jcheck_new (const char *text);
Crea una nueva caja de comprobación. Sirven para representar
opciones booleanas (valores verdadero o falso).
@@void @jcheck_set_icon_align (JWidget check, int icon_align);
@heading
Theme (tema)
@heading
Archivos JID
En un archivo .jid puede definir la estructura de una ventana (o de
cualquier tipo de widget).
Ejemplo:
En "archivo.jid":
<codeblock>
&ltwindow desktop name="ventana1" text="Mi Ventana"&gt
&ltbox vertical>
&ltlabel expansive name="mensaje" text="Su mensaje" /&gt
&ltbox horizontal homogeneous&gt
&ltbutton text="&Aceptar" name="boton_aceptar" /&gt
&ltbutton text="&Cancelar" /&gt
&lt/box&gt
&lt/box&gt
&lt/window&gt
<endblock>
En un "archivo.c":
<codeblock>
JWidget ventana1 = ji_load_widget ("archivo.jid", "ventana1");
JWidget boton_aceptar = jwidget_find_name (ventana1, "boton_aceptar");
jwindow_open_fg (ventana1);
if (jwindow_get_killer (ventana1) == boton_aceptar) {
...
}
<endblock>
@@JWidget @ji_load_widget (const char *filename, const char *name);
@heading
Font (fuente)
@@FONT *@ji_font_load (const char *filepathname);
@@int @ji_font_get_size (FONT *f);
@@int @ji_font_set_size (FONT *f, int height);
@@int @ji_font_get_aa_mode (FONT *f);
@@int @ji_font_set_aa_mode (FONT *f, int mode);
@@bool @ji_font_is_fixed (FONT *f);
@@bool @ji_font_is_scalable (FONT *f);
@@const int *@ji_font_get_available_fixed_sizes (FONT *f, int *n);
@@int @ji_font_get_char_extra_spacing (FONT *f);
@@void @ji_font_set_char_extra_spacing (FONT *f, int spacing);
@@int @ji_font_char_len (FONT *f, int chr);
Retorna la longitud (ancho) de un caracter en pixeles.
@@int @ji_font_text_len (FONT *f, const char *text);
Retorna la longitud (ancho) del texto "text" en pixeles. Recuerde
que esta función interpreta el caracter '&' como un subrayado.
Ejemplo: La longitud "&OK" es igual a la de "OK".
@heading
Listas Enlazadas
Las listas enlazadas se manejan a través de dos punteros:
<codeblock>
typedef struct jlink *JLink;
typedef struct jlist *JList;
<endblock>
Donde JList representa la lista y JLink representa un ítem
perteneciente a la lista:
<codeblock>
struct jlink
{
void *data;
JLink prev;
JLink next;
};
struct jlist
{
JLink end;
unsigned int length;
};
<endblock>
Ejemplo:
<codeblock>
JList lista = jlist_new();
jlist_append(lista, (void *)2);
jlist_append(lista, (void *)3);
jlist_prepend(lista, (void *)1);
jlist_free(lista);
<endblock>
Crea la lista (1, 2, 3).
@@JLink @jlink_new(void *data);
@xref jlink_free
@@JList @jlist_new(void);
@xref jlist_free
@@void @jlink_free(JLink link);
@xref jlink_new
Libera la memoria utilizada únicamente por el nodo "link". Esta
función no borra los datos contenidos en el puntero link->data.
@@void @jlist_free(JList list);
@xref jlist_new
Libera la memoria utilizada por toda la lista "list". Esta función no
borra los datos contenidos en cada nodo (se supone que antes de
llamar esta rutina, usted ya se encargó de eso).
@@void @jlist_clear(JList list);
@@void @jlist_append(JList list, void *data);
Agrega un nuevo elemento con los datos "data" al final de la lista.
@@void @jlist_prepend(JList list, void *data);
Agrega un nuevo elemento con los datos "data" al comienzo de la lista.
@@void @jlist_insert(JList list, void *data, int position);
@@void @jlist_insert_before(JList list, JLink sibling, void *data);
@@void @jlist_remove(JList list, const void *data);
Remueve la primer ocurrencia de "data" en la lista (comenzando de
principio a fin). El nodo es eliminado (mediante jlink_free), los
datos no.
@@void @jlist_remove_all(JList list, const void *data);
Remueve todas las ocurrencias de "data" en la lista recorriéndola
hacia delante. Los nodos son eliminados (mediante free), los datos
no.
@@void @jlist_remove_link(JList list, JLink link);
@xref jlist_delete_link, jlink_free
Remueve el nodo "link" de la lista "list". El nodo NO es liberado
(aquí se supone que luego usted llamará un jlink_free).
@@void @jlist_delete_link(JList list, JLink link);
@xref jlist_remove_link
Remueve el nodo "link" de la lista "list". El nodo será eliminado
(mediante jlink_free), los datos no.
@@JList @jlist_copy(JList list);
Copia la lista generando una completamente nueva con cada elemento
apuntado a los mismos datos que la anterior lista.
@@JLink @jlist_nth_link(JList list, unsigned int n);
@@void *@jlist_nth_data(JList list, unsigned int n);
@@JLink @jlist_find(JList list, const void *data);
Busca el primer nodo en el cual los datos son igual a "data".
Esta función recorre la lista de principio a fin.
@@JList @jlist_first (JList list);
Retorna el primer elemento de la lista.
Devuelve list->end si no hay elementos en la lista.
@@JList @jlist_last (JList list);
Retorna un puntero al último elemento de la lista.
Devuelve list->end si no hay elementos en la lista.
@@unsigned int @jlist_length (JList list);
Retorna la cantidad de nodos que contiene la lista "list".
@hnode JI_LIST_FOR_EACH
@hnode JI_LIST_FOR_EACH_BACK
@hnode JI_LIST_FOR_EACH_SAFE
@heading
JRect - Rectángulos
<codeblock>
struct jrect
{
int x, y, w, h;
};
<endblock>
@@JRect @jrect_new (int x, int y, int w, int h);
@xref jrect_free
@@JRect @jrect_new_copy (const JRect rect);
@xref jrect_new, jrect_copy
@@void @jrect_free (JRect rect);
@xref jrect_new
@@void @jrect_copy (JRect dst, const JRect src);
@xref jrect_new_copy
@@void @jrect_replace (JRect rect, int x, int y, int w, int h);
@@void @jrect_add (JRect rect, const JRect other);
@@bool @jrect_intersect (JRect rect, const JRect other);
@xref jrect_has_intersection
@@void @jrect_shrink (JRect rect, int border);
@xref jrect_stretch
@@void @jrect_stretch (JRect rect, int border);
@xref jrect_shrink
@@#define @jrect_has_intersection(rect, other)
@xref jrect_intersect
@heading
JRegion - Regiones
Las regiones son útiles para representar áreas o porciones de pantalla
no rectangulares.
@@JRegion @jregion_new(JRect rect, int size);
@@void @jregion_init(JRegion reg, JRect rect, int size);
@@void @jregion_free(JRegion reg);
@@void @jregion_uninit(JRegion reg);
@@bool @jregion_copy(JRegion dst, JRegion src);
@@bool @jregion_intersect(JRegion new, JRegion reg1, JRegion reg2);
@@bool @jregion_union(JRegion new, JRegion reg1, JRegion reg2);
@@bool @jregion_append(JRegion dstrgn, JRegion rgn);
@@bool @jregion_validate(JRegion badreg, bool *overlap);
@@bool @jregion_subtract(JRegion regD, JRegion regM, JRegion regS);
@@bool @jregion_inverse(JRegion newReg, JRegion reg1, JRect invRect);
@@int @jregion_rect_in(JRegion region, JRect rect);
@@void @jregion_translate(JRegion reg, int x, int y);
@@void @jregion_reset(JRegion reg, JRect box);
@@bool @jregion_break(JRegion reg);
@@bool @jregion_point_in(JRegion reg, int x, int y, JRect box);
@@bool @jregion_equal(JRegion reg1, JRegion reg2);
@@bool @jregion_notempty(JRegion reg);
@@void @jregion_empty(JRegion reg);
@@JRect @jregion_extents(JRegion reg);
@heading
Funciones Internas
@@JWidget @_ji_get_widget_by_id (JID widget_id);
@@JWidget *@_ji_get_widget_array (int *nwidgets);
Devuelve un puntero al arreglo interno que maneja todos los widgets.
A "nwidgets" le será asignado la cantidad de elementos del arreglo de
widgets.
@@JWidget @_ji_get_new_widget (void);
@@void @_ji_free_widget (JWidget widget);
Libera el widget para que pueda ser utilizado por otro nuevo
widget. Esta función no borra nada del widget, es utilizada por
jwidget_free, así que no debería utilizarla NUNCA.
@@void @_ji_free_all_widgets (void);
Libera la memoria utilizada por todas las widgets. Nunca llame esta
función directamente. Usted no debería preocuparse por utilizarla
debido a que se llama internamente cuando sea necesario (cuando se
elimina el primer "manager" creado).
@@bool @_ji_is_valid_widget (JWidget widget);
@@int @_ji_system_init (void);
@@void @_ji_system_exit (void);
@@int @_ji_font_init (void);
@@void @_ji_font_exit (void);
@@bool @_jwindow_is_moving (void);
Devuelve TRUE si en este momento el usuario está moviendo una
ventana.
@heading
Actualizaciones
Jinete comenzó con Allegro Sprite Editor (ASE) y continuará muy cerca
de él. Vea la página de ASE para tener noticias sobre esta librería:
<link>http://ase.sourceforge.net/</a>
Si quiere saber más sobre el autor:
<link>http://www.davidcapello.com.ar/</a>
@heading
Agradecimientos
Gracias a:
<ul><li>
Shawn Hargreaves y a todos los que ayudaron con Allegro.
<li>
Richard M. Stallman y todo el mundo que participa en las proyectos GNU
como GCC, Emacs, etc.
<li>
David Turner, Robert Wilhelm, y Werner Lemberg por The FreeType library.
</ul>
@!text
@$@ifinfo
@headingnocontent
Índice
@index
@$@end ifinfo
@$@contents
@$@bye
@text