ENGLISH VERSION |
|
Links | | | Forum | | | Kommentare | | | News melden |
Chat | | | Umfragen | | | Newsticker | | | Archiv |
[Login] [Registrieren] [Passwort vergessen?] |
| |||
05.Okt.2023 |
Tutorial: Ein Amiga-GUI-Programm in C schreiben (Englisch) Edwin van den Oosterkamp hat sich bereits in zwei Büchern der Programmiering auf dem Amiga gewidmet: "Classic AmigaOS Programming - An introduction" ist eine Einführung in die Programmierung des AmigaOS in C und Assembler. Zielgruppe sind Programmierer ohne Amiga-Erfahrung, oder ehemalige Amiga-Programmierer die nach längerer Unterbrechung wieder für den Amiga entwickeln möchten. "Bare Metal Amiga Programming" geht auf die Programmierung der Hardware unter Umgehung des Betriebssystems ein. Wir haben den Programmierer eingeladen, anhand eines konkreten Beispiels den Einstieg in die C-Programmierung aufzuzeigen und sagen herzlichen Dank für die nachfolgende Anleitung: "There are many things I love about the Amiga and one of these is the OS. AmigaOS provides a lot of the things we now take for granted in an operating system. Not only the obvious things like windows, menus, icons and such but also things like multi-tasking and inter-process messaging. And compared to modern operating systems there are not many layers between AmigaOS and its applications, so it feels like you're having direct access to the OS. Personally I really like using my Amiga for productivity tasks and this includes using it to write Amiga software. This article uses a simple example program to show how an Amiga GUI program in C can be created using the Amiga itself. To save you all the typing I have also released the source code for this program so that you can download it from here. Native developmentWhen the new Kickstart/Workbench 3.2 was released its developers also released the matching Native Development Kit, or NDK for short. This kit can be downloaded for free from the Hyperion website and contains (amongst other things) the include headers needed for development in C. The 3.2 NDK does not just cover all the new things that Kickstart 3.2 brought, but also all includes for the older functionality of previous kickstarts. It is therefore perfectly fine to use the 3.2 NDK and develop software for Kickstart 2.0 and upwards - or even Kickstart 1.x and upwards. You do need to be careful not to call any of the new functions that were not available on the older Kickstart versions.The NDK does not include a compiler nor a text editor. For the text editor you can use any editor you like. I've been using the "TextEdit" program that comes with Workbench 3.2 but plenty more options are available on places like Aminet. There is of course also "edit", the standard text editor that has been part of the Workbench since the 1.x days. There are a number of different C compilers available for the Amiga. From gcc forks down to the old compilers people used in the 90's. My choice for native compilation is VBCC, which is a compiler that runs on the Amiga natively, creates good code and is still actively maintained. It is also designed to run on systems with considerably less resources than a modern PC, unlike for example versions of gcc. Speaking of resources, to install the NDK your Amiga will definitely need a hard disk. It does not matter if it is a real spinning rust drive, a CF card or an emulated one on a memory card. When installed the NDK simply does not fit on a floppy. Of course it is possible to cherry pick just those header files that are required for a certain project, but then you are not making it easy on yourself. Your system also needs something faster than a standard 68000 CPU. The newer versions of VBCC require a 68020 or higher, and while it is possible to use an older version on a 7Mhz 68000, it just takes too long to compile any non-trivial project for it to be really practical. Installing LHAThe NDK download will be in the LHA file format. This is an archive format similar to (but not the same as) the ZIP format used by Windows nowadays. The "lha" command is used to extract the archive, which can be downloaded from Aminet here: http://aminet.net/util/arc/lha.run. If your Amiga already has LHA installed then please feel free to skip this section.The lha.run file is a self-extracting archive that, when run on an Amiga, will produce multiple files. Two are documentation files, one as a "readme" text and one in "guide" format. Then there are three executables, one for the 68k, one for the 68020 (and higher) and one for the 68040 and higher. Select the one that is correct for your system, rename it to "lha" and copy it into the C: folder. Installing the 3.2 NDKThe first step is downloading the NDK from the Hyperion website.To keep things organised I recommend creating a drawer named "Develop" in the root of your hard drive. If you use multiple partitions then it does not matter which one you choose, that is up to you. Then inside that "Develop" drawer create a drawer named "NDK3.2". Then copy the downloaded lha file of the NDK into this "NDK3.2" drawer. Open a Shell or CLI window and navigate into this "NDK3.2" drawer. To extract the lha archive, type the following command into the shell window: > lha x NDK3.2R4.lhaPlease note that the developers of the NDK are planning to keep updating it as and when required. This means that the name of the lha archive may change and that the file you have downloaded may not be named "NDK3.2R4.lha" like mine was. Please update the filename used to unpack the archive with the name your archive has. The above command will unpack all the contents of the lha file. After that has successfully concluded you can safely delete the lha archive from the drawer. Installing VBCCThe VBCC compiler consists of two parts, the compiler part and the target part. This allows VBCC to be used for cross-compilation. For example, with the Amiga compiler and the Atari target it is possible to write Atari software on an Amiga. With the Windows compiler and the Amiga target it is possible to create Amiga executables on a Windows PC.In this case we want to download the Amiga 68k compiler: vbcc_bin_amigaos68k.lha. And the AmigaOS 68k target: vbcc_target_m68k-amigaos.lha. The above target allows for compiling software for Kickstart 2.0 and newer. To develop for the older Kickstart 1.x versions a different target is required, which can be downloaded from: vbcc_target_m68k-kick13.lha. The example used by this article depends on Kickstart 2.0 functionality and therefore the first of the two target archives is required. For more information about VBCC, please check out the website (http://sun.hasenbraten.de/vbcc/) where you can also find compilers and targets for next generation PPC based Amigas and other systems. The lha archives for VBCC contain an installer script that will copy all files to the correct location and set everything up for use. These archives therefore need to be unpacked into a temporary location like the ram: disk or the T: directory. After unpacking you can simply double click the "install" icon and follow the on-screen instructions. First start with the "bin" archive and then follow up with the contents of the "target" archive. One of the things the VBCC installer is going to ask for is the location of the NDK. This location is the "NDK3.2" drawer into which the NDK lha archive was unpacked previously. Hello world, meet our first programThe program below will open a small window titled "Hello World!", which then closes itself automatically after a short time. To open the window a function called OpenWindowTagList() is used, which was introduced with Kickstart 2.0 (Intuition library V36). This program therefore requires Kickstart 2.0 or newer to run.#include <proto/exec.h> #include <proto/intuition.h> #include <proto/dos.h> #include <intuition/intuitionbase.h> #include <intuition/intuition.h> int main() { char Title[] = "Hello World!"; ULONG WinTags[] = { WA_Width, 200, WA_Height, 100, WA_Title, (ULONG)&Title, WA_Activate, 1, TAG_END }; struct Window * pWin = OpenWindowTagList( NULL, (struct TagItem *)&WinTags ); if ( !pWin ) { return -1; } Delay( 500 ); CloseWindow( pWin ); return 0; }To compile it, copy/paste it into a text file named 'test.c' and use the following command in a shell/CLi window: > vc -c99 -lauto test.c -o TestThis will create an executable named "Test", which you can run from the shell. The "-c99" argument enables the compiler's support for the C99 standard. Amongst other things this enables support for comments starting with '//' as well as support for declaring variables at their first use, instead of placing them all at the top of the function. The "-lauto" argument tells the linker to automatically open and close the system libraries used by the program. For example, the OpenWindowTagList() function is part of the Amiga's Intuition library, while the Delay() function is part of the Dos library. Without the "-lauto" argument it is up to the programmer to open and close these libraries as and when required. Letting the linker worry about these things keeps things a bit more readable. Closing on commandInstead of closing automatically, it would be much better if the window had an actual working close gadget. To achieve that we need to enable the window's close gadget and then respond to it when it is clicked by the user. On AmigaOS the windows are managed by the Intuition library and the library communicates with the applications via messages. These messages are received via each window's "Intuition Direct Communications Message Port", or IDCMP for short. The messages are therefore known as IDCMP messages. It is up to the application to indicate which class of message it wants to receive for each window.The updated program is shown below. Two new tags have appeared in the Window's taglist: the WA_CloseGadget tag enables the window's close gadget and the WA_IDCMP tag indicates the classes of messages the program wants to receive - only the IDCMP_CLOSEWINDOW class at this point. #include <proto/exec.h> #include <proto/intuition.h> #include <intuition/intuitionbase.h> #include <intuition/intuition.h> int main() { char Title[] = "Hello World!"; ULONG WinTags[] = { WA_Width, 200, WA_Height, 100, WA_Title, (ULONG)&Title, WA_Activate, 1, WA_IDCMP, IDCMP_CLOSEWINDOW, WA_CloseGadget, 1, TAG_END }; struct Window * pWin = OpenWindowTagList( NULL, (struct TagItem *)&WinTags ); if ( !pWin ) { return -1; } WaitPort( pWin->UserPort ); CloseWindow( pWin ); return 0; }The only other difference is that the Delay() function from the Dos library has been replaced with the WaitPort() function from the Exec library. WaitPort() puts the program to sleep until a message arrives on the port. And in this case that can only be an IDCMP_CLOSEWINDOW message, so as soon as we receive a message on the port we know we can close the window and call it a day. On AmigaOS it is important to ensure that the program closes all Windows, files and so on before it terminates. Unlike modern operating systems there is nothing keeping track of these things for your process. If you forget to close a window upon exit then that Window will stay there. On AmigaOS you are solely responsible to close/free everything that you've opened/allocated. Closing on command, now properly pleaseThe previous program works as intended but only because it is a trivial program. With a normal program there will be a number of different classes of IDCMP messages coming in, each requiring a different response from the program. To do this properly for our program the following part needs to be added instead of the "WaitPort( pWin->UserPort );" line:int Run = 1; while ( Run ) { WaitPort( pWin->UserPort ); struct Message * pMsg; while ( pMsg = GetMsg( pWin->UserPort ) ) { struct IntuiMessage * pIMsg = (struct IntuiMessage *)pMsg; switch ( pIMsg->Class ) { case IDCMP_CLOSEWINDOW : Run = 0; break; } ReplyMsg( pMsg ); } }The program is still put to sleep while waiting for messages on the port. But now when the program wakes up it actually gets the message from the port, checks the class of the message and replies the message. This last point is important since only then will Intuition know that the message has been dealt with and that any resources held can be released. The program receives the messages in a loop since it is possible that there is more than one message waiting when the program wakes up. And if the message is not of the IDCMP_CLOSEWINDOW class (unlikely in our still trivial case) then the program needs to continue running and processing. Let's add some more GUI based functionality to our little program. GadtoolsWith Kickstart 1.x the only way to create menus and gadgets was via the Intuition library. With Kickstart 2.0 a second method was introduced with the Gadtools library. Gadtools made creation of menus and gadgets much simpler and at the same time added a number of new standard gadgets. These new standard gadgets meant not only that programmers no longer needed to create their own, but also that these gadgets now had an uniform look across different programs. The menus and gadgets created with Gadtools still consist of Intuition based elements and can be mixed with traditional Intuition based gadgets and menus.Since Gadtools has been bolted on top of Intuition all messages its elements generate are IDCMP messages. Some of these messages are for internal use by Gadtools only and to filter these out Gadtools provides its own version of the GetMsg() and ReplyMsg() functions that should be used instead. This also means that some IDCMP messages are for Gatools' use only, in which case the GT_GetIMsg() function may return NULL on the first call if there are no other messages available. Using the Gadtools functions the message loop from the previous section now looks as follows: int Run = 1; while ( Run ) { WaitPort( pWin->UserPort ); struct IntuiMessage * pIMsg; while ( pIMsg = GT_GetIMsg( pWin->UserPort ) ) { switch ( pIMsg->Class ) { case IDCMP_CLOSEWINDOW : Run = 0; break; } GT_ReplyIMsg( pIMsg ); } }One additional nicety is that the GT_ functions work on IntuiMessage structs instead of Message structs. This removes the need to cast from one type of pointer to another and makes the code look a bit cleaner. Gadtool menusGadTools menus are created via an array of NewMenu structs. From this array the Gadtools function CreateMenuA() generates a list of Intuition Menu structs. None of the sizes and locations of the menus and their items are calculated at this point. This is done by calling the Gadtools LayoutmenusA() function. This function also requires a pointer to a VisualInfo struct, which contains all information Gadtools requires to calculate screen and font sizes. A pointer to this struct is obtained from the GetVisualInfo() function.The last field of the NewMenu struct is a pointer that can be used for user data. This can for example be a pointer to a function, when the user selects that menu item the program can use the pointer to call a particular function. In this case I have created a number of integer defines that are interpreted as commands. The program can read the user data and show the About window when it sees the CMD_ABOUT value or for example quit the program when it sees CMD_QUIT. struct Menu * CreateMenu( void * pVI ) { struct NewMenu nm[] = { { NM_TITLE, "Project", 0, 0, 0, 0 }, { NM_ITEM, "About...", "A", 0, 0, (APTR)CMD_ABOUT }, { NM_ITEM, NM_BARLABEL, 0, 0, 0, 0 }, { NM_ITEM, "Quit", "Q", 0, 0, (APTR)CMD_QUIT }, { NM_TITLE, "Options", 0, 0, 0, 0 }, { NM_ITEM, "High", 0, CHECKIT|MENUTOGGLE|CHECKED, 0x6, (APTR)CMD_OPTHIGH }, { NM_ITEM, "Mid", 0, CHECKIT|MENUTOGGLE, 0x5, (APTR)CMD_OPTMID }, { NM_ITEM, "Low", 0, CHECKIT|MENUTOGGLE, 0x3, (APTR)CMD_OPTLOW }, { NM_END, 0, 0, 0, 0, 0 } }; struct Menu * pMenu = CreateMenusA( nm, 0 ); if ( !pMenu ) { return NULL; } LayoutMenusA( pMenu, pVI, 0 ); return pMenu; }At this point the menu structure has been setup including the size and location of each of its items. The menu is now ready to be added to a window, for example via the SetMenuStrip() function that is part of the Intuition library. Intuition will send the IDCMP_MENUPICK message each time the user interacts with the menu. In order to receive these messages for our menu we need to add that message class to the WA_IDCMP tag used for the OpenWindowTagList() function. This is done by logic-OR-ing the new message class with the already existing class. In the message loop we also need to add the IDCMP_MENUPICK class to the switch statement that checks the pIMsg->Class field of the received message. The code field of the IDCMP_MENUPICK message has a unique number identifying the menu/item. This number is assigned by Intuition and indicates the item's position in the menu bar (e.g. 5th item of 3rd menu). The NDK provides handy macros to decode the menu number and Intuition provides the ItemAddress() function for obtaining a pointer to the Menu or MenuItem struct of the menu element that the user interacted with. Unfortunately neither the Menu struct nor the MenuItem struct have user data fields. Gadtools worked around this by placing the user data immediately after the struct of the element. It is important to keep in mind that a Menu struct has a different size compared to a MenuItem struct. Before we can read the user data we need to find out if it was a menu or an item that caused the message. In the case of our example program only items have interesting user data, so if the message was not caused by the user interacting with an item then we can skip the reading of the user data. The following function does all the things discussed above; it uses one of the menu number macros to check if the message is from an item. Then it gets the address to the MenuItem struct and moves the pointer to directly after the struct. It interprets the data after the struct as an integer and returns the value of that integer. The returned value also includes a value defined elsewhere in the program to indicate that this command came from a menu selection. int ProcessMenuPick( struct Menu * pMenu, struct IntuiMessage * pIMsg ) { if ( ITEMNUM( pIMsg->Code ) == NOITEM ) { return CMD_NONE; } char * pItem = (char *)ItemAddress( pMenu, pIMsg->Code ); if ( !pItem ) { return CMD_NONE; } pItem += sizeof( struct MenuItem ); int Command = *(int *)pItem; return Command | SRC_MENU; } Gadtools gadgetsThe creation of gadgets works slightly different from the way Gadtools creates menus. Menu creation was done via an array of structs that represented multiple items and menus. Gadgets are created one at a time by calling the CreateGadgetA() function for each gadget. Gadgets are linked into a list by providing the pointer to the previous gadget when calling CreateGadgetA() to create the next gadget. The start of this linked list must first be created by calling CreateContext() and the pointer from CreateContext() is then passed on to CreateGadgetA() for the creation of the first actual gadget.The following function creates a list of gadgets and returns a pointer to the top of the list. This pointer is later required to free the list. The function uses arrays for most of the arguments of CreateGadgetA(). More gadgets can be added by extending these arrays. struct Gadget * CreateGadgets( struct Window * pWin, void * pVI, struct Gadget * pGadgets[] ) { #define NUM_GADGETS 3 // The labels and tags for the cycle gadget static char * cycLabels[] = { "High", "Mid", "Low", 0 }; ULONG cycTags[] = { GTCY_Labels, (ULONG)cycLabels, TAG_END }; // The arrays used for the creation of the gadgets int ggKind[NUM_GADGETS] = { BUTTON_KIND, BUTTON_KIND, CYCLE_KIND }; ULONG * ggTags[NUM_GADGETS] = { NULL, NULL, cycTags }; struct NewGadget ggNew[NUM_GADGETS] = { { 100,78,85,14, "Quit", 0,1,0, pVI, (APTR)CMD_QUIT }, { 100,20,85,14, "About..", 0,2,0, pVI, (APTR)CMD_ABOUT }, { 100,35,85,14, "Options", 0,3,0, pVI, (APTR)CMD_OPTIONS }, }; struct Gadget * pGad; struct Gadget * pContext = CreateContext( &pGad ); if ( !pContext ) { return NULL; } for ( int Index=0; Index < NUM_GADGETS; ++Index ) { pGad = CreateGadgetA( ggKind[ Index ], pGad, &ggNew[ Index ], (struct TagItem *)ggTags[ Index ] ); pGadgets[ Index ] = pGad; } AddGList( pWin, pContext, 0, -1, 0 ); RefreshGList( pContext, pWin, 0, -1 ); return pContext; }After the gadgets have been created the Intuition function AddGList() is used to add the gadgets to the window, followed by Intuition's RefreshGList() function which ensures that all gadgets are setup correctly and show the correct state on screen. One additional thing to note is the pGadgets[] argument of the function above. This array of pointers takes the pointer of each gadget created by Gadtools. These pointers can be used by the program to manipulate the state of the gadgets when required. There wiil be an example of this later on in this article, where the selected item of the cycle gadget will be changed. The window will receive IDCMP_GADGETUP messages when the user interacts with the buttons. Please note that other types of buttons may produce other classes of messages as well. Internally Gadtools may depend on other IDCMP messages as well, but without passing them on. To ensure that the right messages are being received for Gadtools' purposes a macro is provided for each type of Gadtools gadget. In our case we use only the BUTTON_KIND and CYCLE_KIND gadgets. To ensure these work correctly we need to logic-OR the macros BUTTONIDCMP and CYCLEIDCMP with the other classes already present for the window's WA_IDCMP tag. The IDCMP_GADGETUP message has in its "IAddress" field the address of the Gadget structure of the gadget the user interacted with. This is a pointer to the Intuition Gadget struct and unlike the structs used by the menus, this struct does already contain a UserData field. Reading this field will tell us which gadget was being clicked by the user. The only extra step required is for the CYCLE_KIND gadget, where the "Code" field of the message gives the (zero-based) index number of the option the user selected. Since all information we need is already provided by the IntuiMessage of the IDCMP_GADGETUP class, dealing with it is simpler than the dealing with the IDCMP_MENUPICK message, as the following function shows: int ProcessGadgetUp( struct IntuiMessage * pIMsg ) { struct Gadget * pGadget = (struct Gadget *)pIMsg->IAddress; if ( !pGadget ) { return CMD_NONE; } int Command = (int)pGadget->UserData; if ( Command == CMD_OPTIONS ) { Command += pIMsg->Code; } return Command | SRC_GADGET; }Just like the function dealing with the IDCMP_MENUPICK message, this function adds an indicator to show that the command was produced via interaction with a gadget. Updating the user interfaceThere are times when a program needs to update the menu or gadget selections in order to reflect the program's state. In our example program we have a cycle gadget and a menu, each showing the exact same selection. It would only be proper for the program to ensure that both indeed always show the same selection. To do this, the program needs to be able to change the selection of the cycle gadget as well as the selection of the mutual-exclusive menu items.Updating the cycle gadget is straight forward with Gadtools' GT_SetGadgetAttrsA() function. This function takes a pointer to the gadget as well as a taglist with the gadget's new setting. In this case all we need to do is to provide the new selection via the GTCY_Active tag and call GT_SetGadgetAttrsA(). The fact that we need the pointer to the gadget to be able to do this is the reason that our CreateGadgets() function returned all the individual pointers via the the pGadgets[] array. Unfortunately updating the menu is a bit more involved. Before we can make any changes to the menu we need to remove it from the window using the ClearMenuStrip() function. After the changes have been made we can use ResetMenuStrip() to place it back on the window. Intuition menus consist of linked lists. We know that the first selection item is the 1st item on the 2nd menu, so we can use the ItemAddress() function to get the address of the MenuItem struct of the first selection item. The structs of the next two selection items can be found by following the "NextItem" fields of each struct. Updating the selection tick for an item is done by adding or removing the CHECKED flag in the "Flags" field of each item's MenuItem struct. The following function uses the "Command" value to update the cycle gadget and the menu items. The "Command" value also indicates what the source of the command was so that it can be used to prevent updating the element that provided the command. For example, when the user interacts with the menu then the menu does not need to be updated by the program. void UpdateOptions( int Command, struct Window * pWin, struct Gadget * pGadList[] ) { int Source = Command & SRC_MASK; int Option = Commnad & 0x0F; if ( (Source != SRC_GADGET) && pGadList && pGadList[2] ) { ULONG cycTags[] = { GTCY_Active, (ULONG)Option, TAG_END }; GT_SetGadgetAttrsA( pGadList[2], pWin, NULL, (struct TagItem *)&cycTags ); } if ( Source != SRC_MENU ) { struct Menu * pMenu = pWin->MenuStrip; if ( pMenu ) { ClearMenuStrip( pWin ); UWORD MenuNumber = FULLMENUNUM( 1, 0, 0 ); struct MenuItem * pItem = ItemAddress( pMenu, MenuNumber ); for ( int Index=0; Index < 3; ++Index ) { if ( pItem ) { if ( Index == Option ) { pItem->Flags |= CHECKED; } else { pItem->Flags &= ~CHECKED; } pItem = pItem->NextItem; } } ResetMenuStrip( pWin, pMenu ); } } } Keyboard actionIn a lot of cases there is not much to do for a program in order to support the keyboard. The menu takes care of its own shortcuts and any gadgets that take text, e.g. string gadgets, take care of the keyboard themselves. There is one thing though that Intuition does not provide for, mainly since it was not really a "thing" back in the day. And that "thing" is closing a window when the escape key is hit by the user. Of course our window is actually a main window for which close-on-esc is less common, but it still useful to show how simple it is to do this for an AmigaOS application.Keyboard support is provided by means of IDCMP messages, of which there are two key related classes. The IDCMP_RAWKEY message is sent each time a key is pressed and each time a key is released. It contains the raw key code directly from the keyboard, but without translating it according to the installed keyboard layout. The other message is the IDCMP_VANILLAKEY message, which does translate the key codes by using the default keymap. For keys that don't translate to a keymap (like the function keys for example) no IDCMP_VANILLAKEY message will be sent, to receive key codes for those the IDCMP_RAWKEY message is needed. In our case all we need to know is that the user has released the "Esc" key and for that the IDCMP_RAWKEY message is enough. To receive the message we need to add the IDCMP_RAWKEY class to the window's WA_IDCMP tag. Each time a key is pressed and each time a key is released the program will now receive an IDCMP message with the IDCMP_RAWKEY class and the raw key code in the "Code" field of the message. The function below shows a simple way to deal with this message: int ProcessRawKey( struct IntuiMessage * pIMsg ) { if ( pIMsg->Code != 0xC5 ) { return CMD_NONE; } return CMD_QUIT; }The magic number "0xC5" used above is the code sent by the keyboard when the "Esc" key is released. This key is in the same location on all keyboard layouts and therfore the code will be the same for all keyboard layouts. ResourcesThere you have it, a small AmigaOS GUI program that does absolutely nothing. Nothing, apart from showing how things work within the AmigaOS graphical environment. It is up to you now to expand on it. Maybe add some different types of Gadtools gadgets? Or actually add some useful functionality? In any case, to take it further here are some resources that are useful to the general AmigaOS programmer..."
[Meldung: 05. Okt. 2023, 20:49] [Kommentare: 10 - 07. Okt. 2023, 19:09] [Per E-Mail versenden] [Druck-Version] [ASCII-Version] | ||
|
Impressum |
Datenschutzerklärung |
Netiquette |
Werbung |
Kontakt
Copyright © 1998-2024 by amiga-news.de - alle Rechte vorbehalten. |