gtk2.tex 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975
  1. \documentclass[10pt]{article}
  2. \usepackage{a4}
  3. \usepackage{epsfig}
  4. \usepackage{listings}
  5. \lstset{language=Delphi}%
  6. \lstset{basicstyle=\sffamily\small}%
  7. \lstset{commentstyle=\itshape}%
  8. \lstset{keywordstyle=\bfseries}%
  9. %\lstset{blankstring=true}%
  10. \newif\ifpdf
  11. \ifx\pdfoutput\undefined
  12. \pdffalse
  13. \else
  14. \pdfoutput=1
  15. \pdftrue
  16. \fi
  17. \begin{document}
  18. \title{Programming GTK in Free Pascal}
  19. \author{Florian Kl\"ampfl\\and\\Micha\"el Van Canneyt}
  20. \date{September 2000}
  21. \maketitle
  22. \section{Introduction}
  23. In this second article on programming the GTK toolkit, a more advanced use
  24. of the GTK library is presented. Techniques to create a new GTK widget
  25. are discussed by creating two custom widgets.
  26. The first widget is realized by combining existing GTK widgets to create
  27. a new widget, a GTKFileEdit component, modeled after the TFileEdit component
  28. found in the RXLib library for Delphi.
  29. When constructing the second widget, the focus will be on how a widget
  30. should draw itself in GTK.
  31. \section{Preliminaries}
  32. Whatever the method used when creating new GTK widgets, it is necessary to
  33. split the functionality of the widget in 2 parts.
  34. The first part is the functionality that is common to all instances of the
  35. new widget. This part is by far the most important one, and is implemented
  36. in the 'class record'. This record will be initialized with a class
  37. initialization function. It will also contain pointers to callbacks to
  38. draw a particular instance or callbacks to react on user events.
  39. The second part concerns the particular instance of the widget that is
  40. created, it contains the data that determines the state of an instance
  41. after it is created, it is the actual object created by the user. This
  42. part of the widget is implemented in the 'Object record'. For this record
  43. also there is a initalization function.
  44. When the two records have been defined, some standard methods must be
  45. implemented in order to integrate the new widget in the GTK library.
  46. Implementing some methods for the user to manipulate the properties
  47. of the new widget finishes the creation of a new widget.
  48. Since GTK is implemented in C, the programmer must obey some rules in order
  49. to preserve the object-oriented aspect of the GTK library. More precisely,
  50. when defining the class and object records, care must be taken to specify
  51. the parent object or class as the first element in the newly created structure. This
  52. will allow typecasting of the widget to its parent objects.
  53. Taking a look at the \lstinline|TGtkContainer| widget, we see that the declaration
  54. of the object record starts with the declaration of its parent widget
  55. \lstinline|TGtkWidget|:
  56. \begin{lstlisting}{}
  57. TGtkContainer = record
  58. widget : TGtkWidget;
  59. focus_child : PGtkWidget;
  60. flag0 : longint;
  61. resize_widgets : PGSList;
  62. end;
  63. \end{lstlisting}
  64. The same is true for the \lstinline|TGtkContainerClass| record:
  65. \begin{lstlisting}{}
  66. TGtkContainerClass = record
  67. parent_class : TGtkWidgetClass;
  68. n_child_args : guint;
  69. // ...
  70. end;
  71. \end{lstlisting}
  72. For both the components that will be made, such records will be made.
  73. \section{A filename edit component}
  74. The \lstinline|TGTKFileEdit| component presented here is composed out of three
  75. other components; first of all a single line edit control, in which the
  76. user can type a filename if he wishes. The second is a button. The button
  77. is always placed on the right edge of the edit control, and has the same
  78. height. The third component is an image component, which is used to display
  79. an image on the button\footnote{In GTK a button does not necessarily contains a
  80. caption, it is an empty placeholder, which can be filled with whatever
  81. you want, in this case an image. To have the button display a caption,
  82. a label is placed in it.}
  83. Since the edit and button component must be kept together, we use a
  84. \lstinline|TGtkHBox| as the 'Parent' component, and this component will be
  85. used to keep the edit and button control. There is no need to consider the
  86. image component, since it will be placed inside the button.
  87. Having decided that, the structure of the record for the instance of the
  88. component is more or less determined:
  89. \begin{lstlisting}{}
  90. Type
  91. PGtkFileEdit = ^TGtkFileEdit;
  92. TGtkFileEdit = Record
  93. Box : TGtkHBox;
  94. Edit : PGtkEntry;
  95. Button : PGtkButton;
  96. Image : PGtkPixmap;
  97. Dialog : PGtkFileSelection;
  98. end;
  99. \end{lstlisting}
  100. The first field of the record contains the parent record, as required
  101. by the OOP structure of GTK. The other fields are used to contain references
  102. to the other controls used. The \lstinline|Dialog| field will be filled with the
  103. reference to the file selection dialog which is created when the user clicks
  104. the button, at all other times it will contain a \lstinline|nil| pointer.
  105. Remark that the first field is a record, and all other fields are pointers.
  106. Since the fields of the record are 'Public' the user can access the button
  107. and edit components, and set or read their properties, and set additional
  108. signals. (e.g. a 'change' signal for the edit component)
  109. The class record for the {TGTKFileEdit} component should contain as a first
  110. field the parent class record, in this case \lstinline|TgtkHBoxClass|. Furthermore
  111. in the class record the default bitmap that will be displayed on the button
  112. will be stored. For this two fields are needed; one to keep the bitmap
  113. (\lstinline|DefaultPixmap|, and
  114. another one to keep a bitmask that is used to determine the transparant
  115. pixels in the bitmap (\lstinline|DefaultBitMap|):
  116. \begin{lstlisting}{}
  117. PGtkFileEditClass = ^TGtkFileEditClass;
  118. TGtkFileEditClass = Record
  119. Parent_Class : TgtkHBoxClass;
  120. DefaultPixmap : PGdkPixmap;
  121. DefaultBitMap : PGdkBitmap;
  122. end;
  123. \end{lstlisting}
  124. As usual, a pointer type is defined which points to the record. The fields
  125. of the class record will be filled in by the initialization code for our
  126. component, as will be shown below.
  127. A new widget must be registered with GTK by calling the
  128. \lstinline|gtk_type_unique| function. This function returns a unique
  129. identifier that can be used to refer to your new widget. This value
  130. must be accessible when creating new instances.
  131. Usually, this is done by registering the component with the GTK library
  132. inside a function which returns this unique ID to the user:
  133. The \lstinline|GtkFileEdit_get_type| function.
  134. When this function is called for the first time, it will register
  135. the new class with GTK, which will in turn supply a unique ID for the
  136. new component. This ID is returned and also stored, and will be returned
  137. the next times when the \lstinline|GTKFileEdit_get_type| function is called.
  138. The \lstinline|GTKFileEdit_get_type| function looks like this
  139. \lstinline|gtk\_type\_unique|:
  140. \begin{lstlisting}{}
  141. Function GtkFileEdit_get_type : Guint;cdecl;
  142. Const
  143. GtkFileEditInfo : TGtkTypeInfo =
  144. (type_name : 'GtkFileEdit';
  145. object_size : SizeOf(TGtkFileEdit);
  146. class_size : SizeOf(TGtkFileEditClass);
  147. class_init_func : TGtkClassInitFunc(@GtkFileEditClassInit);
  148. object_init_func : TGtkObjectInitFunc(@GtkFileEditInit);
  149. reserved_1 : Nil;
  150. reserved_2 : Nil;
  151. base_class_init_func : Nil
  152. );
  153. begin
  154. if (GtkFileEditType=0) then
  155. GtkFileEditType:=gtk_type_unique(gtk_hbox_get_type,@GtkFileEditInfo);
  156. Result:=GtkFileEditType;
  157. end;
  158. \end{lstlisting}
  159. Registering the new widget is done by passing a \lstinline|TGtkTypeInfo|
  160. record to \lstinline|gtk_type_unique|, where the fields of this record
  161. are filled with the following information:
  162. \begin{description}
  163. \item[type\_name] Contains the name of the type that must be registered.
  164. \item[object\_size] The size of the object record. GTK itself will allocate
  165. the memory when an new instance of the object is created, so it must know the
  166. size of the object.
  167. \item[class\_size] The size of the class object. Only one instance of this
  168. record will be created (by GTK)
  169. \item[class\_init\_func] The address of a function that will initialize the
  170. class record. This function accepts as a single arument a pointer to the
  171. class record to be initialized. This function will normally be called only
  172. once.
  173. \item[object\_init\_func] The address of a function that will initialize
  174. an instance of the object. The function must accept as a single argument
  175. a pointer to an instance of the object. This instance will be created by
  176. GTK. This function is called for each instance of the object.
  177. \end{description}
  178. The other three fields of the record are unfortunately not documented, so
  179. they are left blank.
  180. Along with the \lstinline|TGtkTypeInfo| record, the tyoe the type of the
  181. parent class (acquired with its own \lstinline|gtk_hbox_get_type|
  182. function) is passed to the \lstinline|gtk_type_unique| function.
  183. If a \lstinline|class_init_func| was specified when registering the new type,
  184. then GTK will call this method; it should initialize any class-specific
  185. data in the class record. In the case of the \lstinline|GTKFileEdit|, the bitmap
  186. which is used to fill the button is loaded:
  187. \begin{lstlisting}{}
  188. Procedure GtkFileEditClassInit (CObj : PGtkFileEditClass);cdecl;
  189. begin
  190. With Cobj^ do
  191. DefaultPixMap:=gdk_pixmap_create_from_xpm(Nil,@DefaultBitmap,
  192. Nil,'fileopen.xpm');
  193. end;
  194. \end{lstlisting}
  195. The \lstinline|gdk_pixmap_create_from_xpm| does 2 things: It loads a bitmap
  196. from the \textsf{fileopen.xpm} file and returns a PGdkPixmap pointer.
  197. At the same time it returns a pointer to a bitmask which designates the
  198. transparant regions of the bitmap.
  199. The result of this function is stored in the class record, so the bitmap
  200. is available when a new instance of the class is created.
  201. The \lstinline|GtkFileEditClassInit| and \lstinline|GtkFileEdit_get_type|
  202. functions are not called automatically by GTK. There are basically
  203. 2 solutions to do this as described below.
  204. The first one is specific to Free Pascal: the \lstinline|GtkFileEdit_get_type|
  205. can be called from the unit initialization code; This means that the objects
  206. are registered with GTK, even if they're not used. It also means that the
  207. GTK library must be initialized first, and hence should also be initialized
  208. in the initialization code of some unit.
  209. The second method is the method used in C: The function to create a new
  210. instance of the \lstinline|TGTKFileEdit| class, \lstinline|GTKFileEdit_new|,
  211. calls the \lstinline|get_type| function to register the class if needed,
  212. as follows:
  213. \begin{lstlisting}{}
  214. Function GtkFileEdit_new : PGtkWidget;cdecl;
  215. begin
  216. Result:=gtk_type_new(GtkFIleEdit_get_type)
  217. end;
  218. \end{lstlisting}
  219. When the first instance of the \lstinline|GTKFileEdit| widget is created, the
  220. call to \lstinline|GtkFileEdit_get_type| will register the widget class
  221. first. Subsequent calls to create a new instance will just use the stored
  222. value of the ID that identifies the \lstinline|GTKFileEdit| class.
  223. To be able to create an instance of the \lstinline|GTKFileEdit| class, one
  224. more procedure must be implemented, as can be seen from the class
  225. registration code: \lstinline|GtkFileEditInit|. This procedure will
  226. initialize (i.e. create) a new instance of the class; it should do
  227. whatever is necessary so the instance is ready for use.
  228. In the case of the \lstinline|GTKFileEdit| class, this simply means that
  229. all widgets of which the class is composed, must be created and placed to
  230. gether. This is shown in the following code:
  231. \begin{lstlisting}{}
  232. Procedure GtkFileEditInit (Obj : PGtkFileEdit);cdecl;
  233. Var
  234. PClass : PGtkFileEditClass;
  235. begin
  236. PClass:=PGtkFileEditClass(PGtkObject(Obj)^.klass);
  237. With Obj^ do
  238. begin
  239. Edit := PgtkEntry(gtk_entry_new);
  240. Button := PgtkButton(gtk_button_new);
  241. Image := PgtkPixMap(gtk_pixmap_new(PClass^.DefaultPixmap,
  242. PClass^.DefaultBitmap));
  243. gtk_container_add(PGtkContainer(Button),PGtkWidget(Image));
  244. gtk_box_pack_start(PgtkBox(Obj),PGtkWidget(Edit),True,True,0);
  245. gtk_box_pack_start(PgtkBox(Obj),PGtkWidget(Button),False,True,0);
  246. gtk_signal_connect(PgtkObject(Button),'clicked',
  247. TGtkSignalFunc(@GtkFileEditButtonClick),Obj);
  248. end;
  249. gtk_widget_show_all(PGtkWidget(Obj));
  250. end;
  251. \end{lstlisting}
  252. The code is self explanatory; the sub-widgets are created, and a reference
  253. to them is stored in the fields of our instance record. Note that the
  254. ancestor (a \lstinline|gtkHbox|) is not initialized, this has been done
  255. already by the OOP mechanism of GTK.
  256. After the objects are created, they are put together in the horizontal
  257. box, with the options chosen in such a way that the composed widget scales
  258. well if needed. The bitmap image is of course placed in the button.
  259. Lastly, a signal handler is added to the button, so that when it is clicked,
  260. we can take appropriate action (i.e. show a dialog to select a file).
  261. Note that as the \lstinline|Data| parameter for the signal, the reference
  262. to the \lstinline|GTKFileEdit| instance is passed.
  263. Now the class is ready to be created and shown. However, it doesn't do
  264. anything useful yet. The callback for the button click must still be used.
  265. The callback for the button must create a file selection dialog, show it,
  266. and when it has been closed by a click on the 'OK' button, it should set
  267. the text of the edit widget to the name of the selected file.
  268. In order to do this, some extra callbacks are needed, as can be seen in the
  269. following code:
  270. \begin{lstlisting}{}
  271. Procedure GtkFileEditButtonClick (Obj : PGtkObject; Data : PgtkFileEdit);cdecl;
  272. Var
  273. Dialog : PGtkFileSelection;
  274. begin
  275. Dialog := PGtkFileSelection(gtk_file_selection_new('Please select a file'));
  276. Data^.Dialog:=Dialog;
  277. gtk_signal_connect(PGTKObject(Dialog^.ok_button),'clicked',
  278. TGTKSignalFunc(@GtkStoreFileName),data);
  279. gtk_signal_connect_object (PGtkObject((Dialog)^.ok_button),'clicked',
  280. TGTKSIGNALFUNC (@gtk_widget_destroy), PgtkObject(Dialog));
  281. gtk_signal_connect_object (PGtkObject((Dialog)^.cancel_button),'clicked',
  282. TGTKSIGNALFUNC (@gtk_widget_destroy), PgtkObject(Dialog));
  283. gtk_widget_show(PgtkWidget(dialog));
  284. end;
  285. \end{lstlisting}
  286. The listing shows that an instance of the file selection dialog is created,
  287. and that its signals are set up so that when the user clicks the 'Cancel'
  288. button, the file selection dialog is simply destroyed, and when the 'OK'
  289. button is selected, first a callback is called in which the name of the
  290. selected file will be retrieved, and secondly the file selection dialog
  291. is destroyed.
  292. Two remarks concerning this code are in order:
  293. \begin{enumerate}
  294. \item The order in which the signals are connected to the 'clicked' event of
  295. the OK button is important, since they will be triggered in the order that
  296. they were connected.
  297. \item A reference to the dialog is stored in the \lstinline|GTKFileEdit|
  298. instance, and the reference to the \lstinline|GTKFileEdit| is passed as the
  299. \lstinline|Data| parameter of the signal.
  300. \end{enumerate}
  301. Finally, when the 'OK' button of the file selection dialog is clicked, the
  302. following callback is executed to store the filename in the edit widget of
  303. the \lstinline|GTKFileEdit| widget:
  304. \begin{lstlisting}{}
  305. Procedure GtkStoreFileName(Button : PgtkButton;
  306. TheRec : PGtkFileEdit); cdecl;
  307. begin
  308. With TheRec^ do
  309. begin
  310. gtk_entry_set_text(Edit,gtk_file_selection_get_filename(Dialog));
  311. Dialog:=Nil;
  312. end;
  313. end;
  314. \end{lstlisting}
  315. The callback also removes the reference to the file selection dialog. This
  316. could also have been done by explicitly setting a 'destroy' signal handler
  317. for the dialog, but since the dialog is destroyed after the 'OK' button is
  318. clicked, it is done here.
  319. Now the \lstinline|GTKFileEdit| is ready for use. It is possible to add
  320. some utility functions to the class, for instance one to get or set set
  321. the filename:
  322. \begin{lstlisting}{}
  323. Procedure GtkFileEdit_set_filename (Obj : PGtkFileEdit; FileName : String);cdecl;
  324. begin
  325. gtk_entry_set_text(Obj^.Edit,PChar(FileName));
  326. end;
  327. Function GtkFileEdit_get_filename (Obj : PGtkFileEdit) : String;cdecl;
  328. begin
  329. Result:=StrPas(gtk_entry_get_text(Obj^.Edit));
  330. end;
  331. \end{lstlisting}
  332. The widget can now be used like any other GTK widget:
  333. \begin{lstlisting}{}
  334. program ex1;
  335. {$mode objfpc}
  336. uses
  337. glib,gtk,fileedit;
  338. procedure destroy(widget : pGtkWidget ; data: pgpointer ); cdecl;
  339. begin
  340. gtk_main_quit();
  341. end;
  342. var
  343. window,
  344. fileed,
  345. box,
  346. Button : PgtkWidget;
  347. begin
  348. gtk_init (@argc, @argv);
  349. window := gtk_window_new (GTK_WINDOW_TOPLEVEL);
  350. fileed := gtkfileedit_new;
  351. gtk_container_set_border_width(GTK_CONTAINER(Window),5);
  352. box:=gtk_vbox_new(true,10);
  353. button:=gtk_button_new_with_label('Quit');
  354. gtk_box_pack_start(pgtkbox(box),PGtkWidget(fileed),False,False,0);
  355. gtk_box_pack_start(pgtkbox(box),pgtkWidget(button),True,False,0);
  356. gtk_container_add(GTK_Container(window),box);
  357. gtk_signal_connect (PGTKOBJECT (window), 'destroy',
  358. GTK_SIGNAL_FUNC (@destroy), NULL);
  359. gtk_signal_connect_object(PgtkObject(button),'clicked',
  360. GTK_SIGNAL_FUNC(@gtk_widget_destroy),
  361. PGTKOBJECT(window));
  362. gtk_widget_show_all (window);
  363. gtk_main ();
  364. end.
  365. \end{lstlisting}
  366. The result will look something like figure \ref{fig:fileedit}
  367. \begin{figure}[h]
  368. \begin{center}
  369. \caption{The GTKFileEdit in action}\label{fig:fileedit}
  370. \vspace{3mm}
  371. \epsfig{file=gtk2ex/ex1.png}
  372. \end{center}
  373. \end{figure}
  374. This widget is of course not finished, it can be enhanced in many ways:
  375. Some additional functionality would be to provide a filter for the dialog,
  376. or to set the directory initialiy displayed, provide a title for the dialog,
  377. set a different image on the button, verify that the selected file exists,
  378. and so on. these can be added in much the same way that the
  379. \lstinline|GTKFileEdit_get_filename| and
  380. \lstinline|GTKFileEdit_set_filename| were implemented.
  381. The fact that the parts making up the widget, such as the button and the edit
  382. widgets, are available as fields in the instance record makes it possible
  383. for the user to set additional properties, provided by these widgets. One
  384. could imagine the user connecting to the 'changed' signal of the edit, to
  385. check whether or not the filename being typed exists, and enabling or
  386. disabling other widgets accordingly. The usage of the file selection dialog
  387. itself also makes this clear.
  388. \section{A LED digit widget}
  389. The second widget to be presented in this article is a widget displaying
  390. a LED digit; such as found in many CD-Player displays or digital clocks.
  391. This will demonstrate how to draw a widget on the screen.
  392. A descendent which reacts to mouse clicks will also be created, which will
  393. demonstrate how to react to user events such as mouse clicks.
  394. A digit consists out of 7 segments, which can be either lit or not lit
  395. (dimmed). For each of the 10 digits (0..9) the state of each of the segments
  396. must be specified. For this we introduce some types and constants:
  397. \begin{lstlisting}{}
  398. Type
  399. TLEDSegment = (lsTop,lsCenter,lsBottom,
  400. lsLeftTop,lsRightTop,
  401. lsLeftBottom, lsRightBottom);
  402. TLedSegments = Array[TLedSegment] of boolean;
  403. Const
  404. DigitSegments : Array[0..9] of TLEDSegments =
  405. (
  406. (true,false,true,true,true,true,true), // 0
  407. (false,false,false,false,true,false,true), // 1
  408. (true,true,true,false,true,true,false), // 2
  409. (true,true,true,false,true,false,true), // 3
  410. (false,true,false,true,true,false,true), // 4
  411. (true,true,true,true,false,false,true), // 5
  412. (true,true,true,true,false,true,true), // 6
  413. (true,false,false,false,true,false,true), // 7
  414. (true,true,true,true,true,true,true), // 8
  415. (true,true,true,true,true,false,true) // 9
  416. );
  417. \end{lstlisting}
  418. The meaning of each of these types and the constant is obvious.
  419. Each segment is drawn between 2 points, located on a rectangle
  420. with 6 points, as shown in figure \ref{fig:corners}
  421. \begin{figure}
  422. \begin{center}
  423. \caption{Corners of a digit}\label{fig:corners}
  424. \epsfig{file=gtk2ex/corners.png}
  425. \end{center}
  426. \end{figure}
  427. Each segment is drawn between 2 corners: a start corner and an end corner.
  428. For each segment the start and end corner are stored in the
  429. \lstinline|SegmentCorners| array.
  430. \begin{lstlisting}{}
  431. Type
  432. TSegmentCorners = Array [1..2] of Byte;
  433. Const
  434. SegmentCorners : Array [TLEDSegment] of TSegmentCorners =
  435. (
  436. (1,2),
  437. (3,4),
  438. (5,6),
  439. (1,3),
  440. (2,4),
  441. (3,5),
  442. (4,6)
  443. );
  444. \end{lstlisting}
  445. These constants will facilitate the drawing of the digit later on.
  446. For the digit widget, 2 records must again be introduced; one for the class,
  447. and one for the instances of objects:
  448. \begin{lstlisting}{}
  449. Type
  450. TPoint = Record
  451. X,Y : gint;
  452. end;
  453. PGtkDigit = ^TGtkDigit;
  454. TGtkDigit = Record
  455. ParentWidget : TGtkWidget;
  456. borderwidth,
  457. digit : guint;
  458. Corners : Array [1..6] of TPoint;
  459. end;
  460. PGtkDigitClass = ^TGtkDigitClass;
  461. TGtkDigitClass = Record
  462. Parent_Class : TGtkWidgetClass;
  463. end;
  464. \end{lstlisting}
  465. The class record \lstinline|TGtkDigitClass| contains no extra information
  466. in this case, it has the parent class record as its ony field, as required
  467. bythe GTK object model. It could however be used to store some default values to
  468. be applied to new widgets, as was the case for the \lstinline|GTKFileEdit|
  469. widget.
  470. The object record contains three extra fields:
  471. \begin{description}
  472. \item[borderwidth] The distance between the segments and the border of
  473. the widget.
  474. \item[digit] The digit to be displayed.
  475. \item[Corners] this array contains the locations of each of the corners
  476. between which the segments will be drawn.
  477. \end{description}
  478. The \lstinline|GTKDigit| class must be registered with GTK, and this happens
  479. in the same manner as before:
  480. \begin{lstlisting}{}
  481. Function GtkDigit_get_type : Guint;cdecl;
  482. Const
  483. GtkDigitInfo : TGtkTypeInfo =
  484. (type_name : 'GtkDigit';
  485. object_size : SizeOf(TGtkDigit);
  486. class_size : SizeOf(TGtkDigitClass);
  487. class_init_func : TGtkClassInitFunc(@GtkDigitClassInit);
  488. object_init_func : TGtkObjectInitFunc(@GtkDigitInit);
  489. reserved_1 : Nil;
  490. reserved_2 : Nil;
  491. base_class_init_func : Nil
  492. );
  493. begin
  494. if (GtkDigitType=0) then
  495. GtkDigitType:=gtk_type_unique(gtk_widget_get_type,@GtkDigitInfo);
  496. Result:=GtkDigitType;
  497. end;
  498. \end{lstlisting}
  499. In the class initialization code, the real difference between this widget
  500. and the previous one becomes clear:
  501. \begin{lstlisting}{}
  502. Procedure GtkDigitClassInit (CObj : PGtkDigitClass);cdecl;
  503. begin
  504. With PGtkWidgetClass(Cobj)^ do
  505. begin
  506. size_request:=@GTKDigitSizeRequest;
  507. expose_event:=@GTKDigitExpose;
  508. size_allocate:=@GTKDigitSizeAllocate;
  509. end;
  510. end;
  511. \end{lstlisting}
  512. Here GTK is told that, in order to determine the size of the widget,
  513. it should first call \lstinline|GTKDigitSizeRequest|; this will provide
  514. GTK with an initial size for the object. After GTK has placed all widgets
  515. in the window, and has determined the sizes and positions it will allocate
  516. to each widget in the form, it will call \lstinline|GTKDigitSizeAllocate|
  517. to notify the \lstinline|GTKDigit| widget of the size it is being allocated.
  518. Finally, the \lstinline|expose_event| callback is set; this informs GTK that
  519. when a part of the widget should be drawn (because it is visible to the
  520. user), \lstinline|GTKDigitExpose| should be called. There are actually 2
  521. callbacks to draw a widget; one of them is
  522. the \lstinline|draw| function and the other is the (here used)
  523. \lstinline|expose| function. The \lstinline|draw| function of
  524. \lstinline|GTKWidget| just generates an expose event for the entire widget,
  525. and for the current widget this is enough. There are, however, cases where
  526. it may be necessary to differentiate between the two for optmization
  527. purposes.
  528. The object initialization function \lstinline|| simply initializes all fields to their
  529. default values:
  530. \begin{lstlisting}{}
  531. Procedure GtkDigitInit (Obj : PGtkDigit);cdecl;
  532. Var I : longint;
  533. begin
  534. gtk_widget_set_flags(pgtkWidget(obj),GTK_NO_WINDOW);
  535. With Obj^ do
  536. begin
  537. Digit:=0;
  538. BorderWidth:=2;
  539. For I:=1 to 6 do
  540. with Corners[i] do
  541. begin
  542. X:=0;
  543. Y:=0;
  544. end;
  545. end;
  546. end;
  547. \end{lstlisting}
  548. The interesting thing in the initialization function is the call to
  549. \lstinline|gtk_widget_set_flags|; this tells GTK that the
  550. \lstinline|GtkDigit| does not need its own window. Indeed, it will
  551. use its parent window to draw itself when needed.
  552. This also means that no extra resources must be allocated for the widget.
  553. The \lstinline|size_request| callback will in our case simply ask for some
  554. default size for the digit:
  555. \begin{lstlisting}{}
  556. Procedure GTKDigitSizeRequest (Widget : PGtkWidget;
  557. Request : PGtkRequisition);cdecl;
  558. Var BW : guint;
  559. begin
  560. With PGTKDigit(Widget)^ do
  561. BW:=BorderWidth;
  562. With Request^ do
  563. begin
  564. Width:=20+2*BW;
  565. Height:=40+2*BW;
  566. end;
  567. end;
  568. \end{lstlisting}
  569. usually, GTK will allocate a size at least equal to the size requested. It
  570. may however be more than this.
  571. When GTK has decided what the real size of the widget will be, the
  572. \lstinline|GTKDigitSizeAllocate| will be called:
  573. \begin{lstlisting}{}
  574. procedure GTKDigitSizeAllocate(Widget : PGTKWidget;
  575. Allocation : PGTKAllocation);cdecl;
  576. begin
  577. Widget^.Allocation:=Allocation^;
  578. SetDigitCorners(PGtkDigit(Widget),False);
  579. end;
  580. \end{lstlisting}
  581. This procedure first of all stores the allocated size in the widget, and
  582. then it calls \lstinline|SetDigitCorners| to calculate the positions of
  583. the corners of the segments; this is done as follows:
  584. \begin{lstlisting}{}
  585. Procedure SetDigitCorners(Digit : PGtkDigit; IgnoreOffset : Boolean);
  586. Var
  587. BW : guint;
  588. W,H,SX,SY : gint;
  589. i : longint;
  590. Widget : PGTKWidget;
  591. begin
  592. Widget:=PGTKWidget(Digit);
  593. BW:=Digit^.Borderwidth;
  594. If IgnoreOffset then
  595. begin
  596. SX:=0;
  597. SY:=0;
  598. end
  599. else
  600. begin
  601. SX:=Widget^.Allocation.x;
  602. SY:=Widget^.Allocation.y;
  603. end;
  604. W:=Widget^.Allocation.Width-2*BW;
  605. H:=(Widget^.Allocation.Height-2*BW) div 2;
  606. With PGTKDigit(Widget)^ do
  607. For I:=1 to 6 do
  608. begin
  609. Case I of
  610. 1,3,5 : Corners[i].X:=SX+BW;
  611. 2,4,6 : Corners[i].X:=SX+BW+W;
  612. end;
  613. Case I of
  614. 1,2 : Corners[i].Y:=SY+BW;
  615. 3,4 : Corners[i].Y:=SY+BW+H;
  616. 5,6 : Corners[i].Y:=SY+BW+2*H
  617. end;
  618. end;
  619. end;
  620. \end{lstlisting}
  621. Since the \lstinline|GTKDigit| will draw on its parents window, it must
  622. take into account the offset (x,y) of the allocated size. The reason that
  623. this is parametrized with the \lstinline|IgnoreOffset| parameter will become
  624. clear when the descendent widget is introduced.
  625. This function could be adapted to give e.g. a slight tilt to the digits.
  626. Remains to implement the \lstinline|expose_event| callback:
  627. \begin{lstlisting}{}
  628. Function GTKDigitExpose (Widget : PGTKWidget;
  629. ExposeEvent : PGDKEventExpose) : gint;cdecl;
  630. Var
  631. Segment : TLedSegment;
  632. begin
  633. With PGTKDigit(Widget)^ do
  634. For Segment:=lsTop to lsRightBottom do
  635. if DigitSegments[Digit][Segment] then
  636. gdk_draw_line(widget^.window,
  637. PgtkStyle(widget^.thestyle)^.fg_gc[widget^.state],
  638. Corners[SegmentCorners[Segment][1]].X,
  639. Corners[SegmentCorners[Segment][1]].Y,
  640. Corners[SegmentCorners[Segment][2]].X,
  641. Corners[SegmentCorners[Segment][2]].Y
  642. )
  643. else
  644. gdk_draw_line(widget^.window,
  645. PgtkStyle(widget^.thestyle)^.bg_gc[widget^.state],
  646. Corners[SegmentCorners[Segment][1]].X,
  647. Corners[SegmentCorners[Segment][1]].Y,
  648. Corners[SegmentCorners[Segment][2]].X,
  649. Corners[SegmentCorners[Segment][2]].Y
  650. );
  651. end;
  652. \end{lstlisting}
  653. Here the need for the types and constants, introduced in the
  654. beginning of this section becomes obvious; without them, a huge
  655. case statement would be needed to draw all needed segments.
  656. Note that when a segment of our digit is not 'lit', it is drawn in the
  657. background color. When the digit to be displayed changes, the segments
  658. that are no longer lit, must be 'dimmed' again.
  659. Finally we provide 2 methods to get and set the digit to be dislayed:
  660. \begin{lstlisting}{}
  661. Procedure GtkDigit_set_digit (Obj : PGtkDigit; Digit : guint);cdecl;
  662. begin
  663. if Digit in [0..9] then
  664. begin
  665. Obj^.Digit:=Digit;
  666. gtk_widget_draw(PGTKWidget(Obj),Nil);
  667. end;
  668. end;
  669. Function GtkDigit_get_digit (Obj : PGtkDigit) : guint;cdecl;
  670. begin
  671. Result:=Obj^.Digit;
  672. end;
  673. \end{lstlisting}
  674. Obviously, when setting the digit to be displayed, the widget must be
  675. redrawn, or the display would not change till the next expose event.
  676. Calling \lstinline|gtk_widget_draw| ensures that the digit will be displayed
  677. correctly.
  678. Now the widget is ready for use; it can be created and put on a window
  679. in the same manner as the \lstinline|GTKFileEdit| control; the code will
  680. not be shown, but is available separately.
  681. The result is shown in figure \ref{fig:ex2}.
  682. \begin{figure}
  683. \begin{center}
  684. \caption{The GTKDigit widget in action.}\label{fig:ex2}
  685. \epsfig{file=gtk2ex/ex2.png}
  686. \end{center}
  687. \end{figure}
  688. The widget can be improved in many ways. The segments can be tilted, a
  689. bigger width can be used; the can have rounded edges and so on.
  690. The widget as presented here doesn't react on user events; it has no way
  691. of doing that, since it doesn't have an own window; Therefore a descendent
  692. is made which creates its own window, and which will react on mouse clicks;
  693. this widget will be called \lstinline|GTKActiveDigit|.
  694. The lstinline|GTKActiveDigit| widget is a descendent from its inactive
  695. counterpart. Therefore the class and object records will be (almost) empty:
  696. \begin{lstlisting}{}
  697. Type
  698. PGtkActiveDigit = ^TGtkActiveDigit;
  699. TGtkActiveDigit = Record
  700. ParentWidget : TGtkDigit;
  701. Button : guint8;
  702. end;
  703. PGtkActiveDigitClass = ^TGtkActiveDigitClass;
  704. TGtkActiveDigitClass = Record
  705. Parent_Class : TGtkDigitClass;
  706. end;
  707. \end{lstlisting}
  708. The \lstinline|Button| field is used to store which button was used to click
  709. on the digit.
  710. The registration of the new widget is similar to the one for
  711. \lstinline|GTKDigit|, and doesn't need more explanation:
  712. \begin{lstlisting}{}
  713. Const
  714. GtkActiveDigitType : guint = 0;
  715. Function GtkActiveDigit_get_type : Guint;cdecl;
  716. Const
  717. GtkActiveDigitInfo : TGtkTypeInfo =
  718. (type_name : 'GtkActiveDigit';
  719. object_size : SizeOf(TGtkActiveDigit);
  720. class_size : SizeOf(TGtkActiveDigitClass);
  721. class_init_func : TGtkClassInitFunc(@GtkActiveDigitClassInit);
  722. object_init_func : TGtkObjectInitFunc(@GtkActiveDigitInit);
  723. reserved_1 : Nil;
  724. reserved_2 : Nil;
  725. base_class_init_func : Nil
  726. );
  727. begin
  728. if (GtkActiveDigitType=0) then
  729. GtkActiveDigitType:=gtk_type_unique(gtkdigit_get_type,@GtkActiveDigitInfo);
  730. Result:=GtkActiveDigitType;
  731. end;
  732. Function GtkActiveDigit_new : PGtkWidget;cdecl;
  733. begin
  734. Result:=gtk_type_new(GtkActiveDigit_get_type)
  735. end;
  736. \end{lstlisting}
  737. The first real difference is in the class initialization routine:
  738. \begin{lstlisting}{}
  739. Procedure GtkActiveDigitClassInit (CObj : PGtkActiveDigitClass);cdecl;
  740. begin
  741. With PGtkWidgetClass(Cobj)^ do
  742. begin
  743. realize := @GtkActiveDigitRealize;
  744. size_allocate := @GtkActiveDigitSizeAllocate;
  745. button_press_event:=@GtkActiveDigitButtonPress;
  746. button_release_event:=@GtkActiveDigitButtonRelease;
  747. end;
  748. end;
  749. \end{lstlisting}
  750. The \lstinline|realize| and \lstinline|size_allocate| of the parent widget
  751. \lstinline|GTKDigit| are overriden here. Also 2 events callbacks are
  752. assigned in order to react on mouse clicks.
  753. The object initialization function must undo some work that was done
  754. ba the parent's initialization function:
  755. \begin{lstlisting}{}
  756. Procedure GtkActiveDigitInit (Obj : PGtkActiveDigit);cdecl;
  757. begin
  758. gtk_widget_unset_flags(pgtkWidget(obj),GTK_NO_WINDOW);
  759. With Obj^ do
  760. Button:=0;
  761. end;
  762. \end{lstlisting}
  763. This is necessary, because the \lstinline|GTKActiveDigit| will create it's
  764. own window.
  765. For this widget, the \lstinline|realize| callback must do a little more
  766. work. It must create a window on which the digit will be drawn. The window
  767. is created with some default settings, and the event mask for the window
  768. is set such that the window will respond to mouse clicks:
  769. \begin{lstlisting}{}
  770. Procedure GtkActiveDigitRealize(widget : PgtkWidget);cdecl;
  771. Var
  772. attr : TGDKWindowAttr;
  773. Mask : gint;
  774. begin
  775. GTK_WIDGET_SET_FLAGS(widget,GTK_REALIZED);
  776. With Attr do
  777. begin
  778. x := widget^.allocation.x;
  779. y := widget^.allocation.y;
  780. width:=widget^.allocation.width;
  781. height:=widget^.allocation.height;
  782. wclass:=GDK_INPUT_OUTPUT;
  783. window_type:=gdk_window_child;
  784. event_mask:=gtk_widget_get_events(widget) or GDK_EXPOSURE_MASK or
  785. GDK_BUTTON_PRESS_MASK OR GDK_BUTTON_RELEASE_MASK;
  786. visual:=gtk_widget_get_visual(widget);
  787. colormap:=gtk_widget_get_colormap(widget);
  788. end;
  789. Mask:=GDK_WA_X or GDK_WA_Y or GDK_WA_VISUAL or GDK_WA_COLORMAP;
  790. widget^.Window:=gdk_window_new(widget^.parent^.window,@attr,mask);
  791. widget^.thestyle:=gtk_style_attach(widget^.thestyle,widget^.window);
  792. gdk_window_set_user_data(widget^.window,widget);
  793. gtk_style_set_background(widget^.thestyle,widget^.window,GTK_STATE_ACTIVE);
  794. end;
  795. \end{lstlisting}
  796. After the window was created, its userdata is set to the widget. This
  797. ensures that the events which occur in the window are passed on to our
  798. widget by GTK. Finally the background of the window is set to some
  799. other style than the default style.
  800. The size allocation event should in principle do the same as that for the
  801. \lstinline|GTKDigit| widget, with the exeption that the calculation of the
  802. corners for the segments must now not be done relative to the parent window:
  803. \begin{lstlisting}{}
  804. procedure GTKActiveDigitSizeAllocate(Widget : PGTKWidget;
  805. Allocation : PGTKAllocation);cdecl;
  806. begin
  807. Widget^.allocation:=Allocation^;
  808. if GTK_WIDGET_REALIZED(widget) then
  809. gdk_window_move_resize(widget^.window,
  810. Allocation^.x,
  811. Allocation^.y,
  812. Allocation^.width,
  813. Allocation^.height);
  814. SetDigitCorners(PGTKDigit(Widget),True);
  815. end;
  816. \end{lstlisting}
  817. This explains the need for the \lstinline|IgnoreOffset| parameter in the
  818. \lstinline|SetDigitCorners| function.
  819. All that is left is to implement the mouse click events:
  820. \begin{lstlisting}{}
  821. Function GtkActiveDigitButtonPress(Widget: PGtKWidget;
  822. Event : PGdkEventButton) : gint;cdecl;
  823. begin
  824. PGTKActiveDigit(Widget)^.Button:=Event^.Button;
  825. end;
  826. Function GtkActiveDigitButtonRelease(Widget: PGtKWidget;
  827. Event : PGdkEventButton) : gint;cdecl;
  828. Var
  829. Digit : PGtkDigit;
  830. D : guint;
  831. begin
  832. Digit:=PGTKDigit(Widget);
  833. D:=gtkdigit_get_digit(Digit);
  834. If PGTKActiveDigit(Digit)^.Button=Event^.Button then
  835. begin
  836. If Event^.Button=1 then
  837. GTKDigit_set_digit(Digit,D+1)
  838. else if Event^.Button=3 then
  839. GTKDigit_set_digit(Digit,D-1)
  840. else
  841. GTKDigit_set_digit(Digit,0);
  842. end;
  843. PGTKActiveDigit(Digit)^.Button:=0;
  844. end;
  845. \end{lstlisting}
  846. As can be seen, the digit will be incremented when the left mouse button
  847. is clicked. The digit is decremented when the right button is clicked.
  848. On systems with 3 mouse buttons, a click on the middle mouse button will
  849. reset the digit to 0.
  850. After all this, the widget is ready for use, and should look more or less
  851. like the one in figure \ref{fig:ex3}.
  852. \begin{figure}[h]
  853. \begin{center}
  854. \caption{The GTKActiveDigit in action.}\label{fig:ex3}
  855. \epsfig{file=gtk2ex/ex3.png}
  856. \end{center}
  857. \end{figure}
  858. The widgets presented here are not complete; many improvements can be made,
  859. but their main purpose was to demonstrate that implementing some new widgets
  860. is very easy and can be achieved with little effort; what is more, the OOP
  861. structure of GTK is very suitable for the implementation of small
  862. enhancements to existing components, as was shown with the last widget
  863. presented.
  864. \end{document}