Главная » Просмотр файлов » John.Wiley.and.Sons.Rapid.Mobile.Enterprise.Development.for.Symbian.OS.An.Introduction.to.OPL.Application.Design.and.Programming.May.2005.eBook-LinG

John.Wiley.and.Sons.Rapid.Mobile.Enterprise.Development.for.Symbian.OS.An.Introduction.to.OPL.Application.Design.and.Programming.May.2005.eBook-LinG (779881), страница 12

Файл №779881 John.Wiley.and.Sons.Rapid.Mobile.Enterprise.Development.for.Symbian.OS.An.Introduction.to.OPL.Application.Design.and.Programming.May.2005.eBook-LinG (Symbian Books) 12 страницаJohn.Wiley.and.Sons.Rapid.Mobile.Enterprise.Development.for.Symbian.OS.An.Introduction.to.OPL.Application.Design.and.Programming.May.2005.eBook-LinG2018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 12)

Dialogs (and Menus) willbe looked at in depth in Chapter 4; suffice to say this code will displaya box explaining the error number and a short description of what theerror is.But what about the GOTO Top:: label? This actually takes us back intoour main loop so the user can carry on using the program, but hopefullyreporting the error back to you, the programmer.So with our error code, our pseudo-OPL looks like this:PROC Main:GLOBAL rem We’ll fill these in as we plan the programLOCAL rem We’ll fill these in as we plan the programONERR Error::Init:InitApp:Top::DOrem Get an eventrem Act on this eventUNTIL rem we need to exit the programExit:Error::PRINT message and carry onGOTO Top::ENDPBack to Breaking out of the LoopSo one way we can come out of the loop is this:UNTIL (ERR<>E)where ERR is the value of the last error, or 0 if there is no error.

So whenwe have an error, ERR and E will not be equal (i.e. ERR<>E will be true).54EVENT COREDoing this ensures that all errors will be passed to the error handler. Ofcourse, when an error happens we will be returned to the program, sowe need another way to force the program to stop.We create a GLOBAL variable called Breakout%. When all variablesare created, they initially hold the value of 0. So when we want to exit, weset the Breakout% flag to something other than 0.

Which gives us this:UNTIL (ERR<>E) OR (Breakout%<>0)IF Breakout%Breakout%=0Exit:ENDIFGOTO Top::We reset the value of Breakout% once we have exited the loop asthere is a chance we could be returned from PROC Exit:. This is gooddefensive programming. Even though you are sure you won’t be backhere, just in case for some unknown, unforeseen reason you are sent backhere, in this case the Breakout% variable will still ‘behave’ itself.Note also that if we come out of the DO...UNTIL loop because of theERR value, we won’t automatically reach the jump to PROC Exit:, ratherwe’ll find the GOTO Top:: label and be returned to the DO...UNTILloop, even if something goes wrong with the error handler.

Again, gooddefensive programming!3.3.3PROC Exit:When we’re ready to exit our program, there are a few things we need todo. These will be handled in PROC Exit:PROC Exit:LOCAL Foo%ONERR JustStop::SaveIniFile%:Foo%=0DOFoo%=Foo%+1IF Id%(Foo%)gCLOSE Id%(Foo%)ENDIFUNTIL Foo%=KMaxWindows%JustStop::ONERR OFFSTOPENDPWe set up a new error handling procedure here. If something goes wrongin the Exit: procedure, rather than report the error and try to go back toOTHER PROCEDURES55the program, we’re going to ask the program to just stop anyway.

ONERRJustStop:: takes care of this.Next we save the INI database file by calling PROC SaveIniFile%:.We discussed this procedure earlier, and although there it was used tosave the default settings, here it will be used to save whatever the settingsare currently.Now we set up a small DO...UNTIL loop that closes all the drawablewindows and graphics that we have loaded. In theory, the OPL Runtimeshould recover the memory used by these elements when we close theprogram, but there is nothing wrong with giving it a helping hand.

Atemporary LOCAL variable (Foo% again) is used to count up from 1 to themaximum number of windows (something that we set as a constant atthe start of the source code) and perform the gCLOSE command on eachelement in turn.Finally, we give the STOP command, which stops the OPL programrunning.3.3.4 Getting Key Presses, Events, and CommandsSo now we have everything in PROC Main:, except how to actuallyreceive any inputs (events) from the device or the user.We need to react to three types of events:• system commands (some of these are defined in Const.oph suchas KGetCmdLetterExit$, KGetCmbLetterBroughtToForeground%, KGetCmdLetterBackup$)• pen taps• a key being pressed.Note that not every Symbian OS phone will have all of these elements(for example, current Series 60 phones do not have a touch screen), butto make our Event Core portable we can address them all anyway.System CommandsWhen the processor wants your OPL program to do something, it willsend a command ‘word’ to the program.

This word will be stored by theruntime until you decide to read it into a string variable (of maximumlength 255 characters) with the following command:Command$=GETCMD$56EVENT COREThe first letter reflects the action that needs to be carried out. This lettervalue is also stored as a constant in Const.oph – as always, using thevalues in Const.oph will make your program easier to read and to port toother versions of OPL.The rest of the string will be a filename. Most of the time this will beto the program file, but if you create an OPL program that uses files (e.g.a text editor) it will refer to the open file. Note that file-based programsare not discussed in this book.LetterSentConstant ValueRequested ActionX?KGetCmdLetterExit$KGetCmdLetterBackup$Close your program immediatelyPhone is being backed up, closeprogramProgram brought to foregroundKGetCmdLetterBroughtToFGround$ONProgram sent to backgroundOpen a specified fileCreate a new blank fileAll good programs should react to system events.

In Event Core we checkthe command word before checking for any events with this command,and take the appropriate action.How Do you Read an Event?First we define a GLOBAL array that will be used to store any event weread. When we want to read an event, we use the GETEVENT commandto read in all the relevant info into the 32-bit array previously defined:GLOBAL Event&(16)...GETEVENT32 Event&()When an event occurs, the details of the event are stored in a queue.The GETEVENT32 command will take the first event in the queue, andthen move to the other events. So if you have two events happening veryclose to each other, the first will be read, and the second will wait untilGETEVENT32 is used again.GETEVENT32 will fill the 16 elements of its array with the followinginformation.

Not all of these are used, so only those relevant to OPL arelisted:OTHER PROCEDURESEvent&()Value12Unicode ValueTimestamp3Window Number4150678IntegerIntegerInteger9Integer57TypeKey pressedWhen the key waspressedWhich window thepointer event is inPointer removed fromscreen (pen up)Pointer tapped ontoscreen (pen down)X Coordinate of pen tapY Coordinate of pen tapX Coordinate of pen taprelative to parentwindowY Coordinate of pen taprelative to parentwindowWe’ll now check the Event& array for our two main types of event.PROC PointerDriver:The pointer can be used in two main areas.

The first is to activate themenu on UIQ devices. The second is to register a tap on the screen.If you tap the menu bar in an OPL program on UIQ, it will pass anevent representing this menu press as if you had pressed a key. This valueis KMenuSilkScreen%, and is picked up in our key event handler. Herewe will discuss pen taps that are in the working area of the screen.There are three types of pen events, and they all report back threenumbers, via the GETEVENT32 command (see above table):• the graphics window the event occurred in (remember the Id%window array? It’s these numbers that are reported)• the X coordinate in the window the event was in• the Y coordinate in the window the event was in.In the case of the Symbian OS phone not having a touch screen (suchas a Series 60 or Communicator), it is not possible for a pointer event tobe passed to the program.

However, the Pointer Driver code can happilystay inside the program and simply never get called.58EVENT COREPROC KeyboardDriver:We split the types of keyboard events into two areas. The first is directkey presses such as pressing cursor keys, the enter key, buttons that selectoptions, etc. You’d use these direct keys in a game, or when scrollingthrough a list.The second type of keyboard event is a hot key – this is commonlyused in devices such as the Communicators, but has less relevance onUIQ devices.After a key is pressed, and it is not one of the ‘direct’ keys (for example,the cursor keys could be direct keys used to choose an item from a list), welook at what modifier keys are used.

If there are any present, this indicatesa hot key has been pressed by the user – these are keyboard shortcutsto various menu items or functions. In the case of Communicators, forexample, hot keys use a combination of Ctrl and Shift keys alongsidenormal keyboard letters.Ctrl-K is a popular hot key. This brings up any settings or preferencesdialog the program has. Note that Event Core does not read the Ctrl keyas a distinct key press, but notes the fact that it has been pressed. Thesame applies to the Shift key. In our code, we have two variables used totrack these:Mod%=Ev&(4) AND 255IF Mod% AND 2 : Shift%=1 : ELSE : Shift%=0: ENDIFIF Mod% AND 4 : Control%=1 : ELSE : Control%=0 : ENDIFrem Check for Direct keys hereIF Shift% : Key&=Key&-32 : ENDIFrem Check for Hot Keys hereIF Key&<=300ActionHotKey:ENDIFrem reset ModifiersControl%=0 : Shift%=0Where do we get these values for Key&? There is a list of character codesfor all the keys in the SDK documentation.

For example, 32 is the codefor the space bar and 13 is the Enter key.We can have as many parts to the IF statement that checks for thespace bar (and we’ll see this in later programs), but once these run out,we check to see if a hot key has been pressed, by jumping to PROCActionHotKey:.Processing Hot KeysA separate procedure for hot keys is used to work out what procedure tojump to when a hot key is pressed. This is because the menu system alsouses the hot key system, but we’ll come back to that in the next chapter.SUMMARY59Now you could do a simple IF Key%=48 (where 48 is the charactercode for the letter "a"), but the ASC function gives the character codefor any requested character.

Therefore we can take the numerical valuefrom Key& and compare it to ASC(Value$) of the hot key to check theresult, and make our code more readable:PROC ActionHotKey:IF Key&=ASC("e")-96 : Exit:ELSEIF Key&=ASC("k")-96 : SetPreferences:ELSEIF Key&=ASC("A")-96 : About:ENDIFENDPOnce we find the correct hot key, we go off to a procedure, do something,and come back. Depending on what you want your program to do, EventCore’s layout and this ‘jumping’ method should see you through mostexercises and tasks for many years to come.Menu SystemChapter 4 looks at the menu system in more depth, and we will discussthe menu commands and how to use them in Chapter 4.3.4 SummaryThis chapter introduced you to the Event Core, a framework that gives yousomething to build your OPL programs into.

Характеристики

Тип файла
PDF-файл
Размер
3,18 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Почему делать на заказ в разы дороже, чем купить готовую учебную работу на СтудИзбе? Наши учебные работы продаются каждый год, тогда как большинство заказов выполняются с нуля. Найдите подходящий учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6384
Авторов
на СтудИзбе
308
Средний доход
с одного платного файла
Обучение Подробнее